text
stringlengths 7
3.69M
|
|---|
/**
* Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland.
*
* See the file license.txt for copying permission.
*/
/*global embedded_svg_edit */
require([
'Underscore',
'jquery',
'ext/PluginAdapterContext'
], function (_, $, Context) {
'use strict';
var frame,
svgCanvas;
/**
* Runs func every delay milliseconds until func returns true.
*/
function until(func, delay) {
if (!func()) {
_.delay(until, delay, func, delay);
}
}
/**
* Embedded method draw shouldn't have the stand alone file menu because the host app will
* provide that functionality.
* If data is provided, load method draw with that svg so that it can be edited.
*/
function configureForEmbed(data) {
var frameContents = frame.contents(),
fileMenu = frameContents.find('#main_button'),
menuDone = false,
canvasDone = true,
canvas;
if (fileMenu.length > 0) {
fileMenu.hide();
menuDone = true;
}
if (data) {
canvasDone = false;
canvas = frameContents.find('#svgcanvas');
if (canvas) {
svgCanvas.setSvgString(data);
canvasDone = true;
}
}
if (menuDone && canvasDone) {
frame.removeClass('qk_invisible');
Context.publish('opened');
}
return menuDone && canvasDone;
}
function hide(topic, data) {
frame.detach();
frame.addClass('qk_invisible');
Context.publish(topic, data);
}
/**
* If this isn't done then one some browsers (e.g. desktop Chrome) the previous drawing
* shows up in SVG Editor when a new instance os opened, which isn't what's wanted.
*/
function ensureCleanState() {
if (window.localStorage && window.localStorage.getItem('svgedit-default')) {
window.localStorage.removeItem('svgedit-default');
}
}
/**
* Callback.
*/
function save() {
svgCanvas.getSvgString()(function (data, error) {
if (error) {
console.log('save error: ' + error);
} else {
hide('saved', data);
}
});
}
/**
* Callback.
*/
function exit() {
hide('exited');
}
/**
* Callback.
* Loads the method draw DOM nodes into the document and configures it to run embedded.
*/
function open(data) {
frame.appendTo('body');
ensureCleanState();
until(_.partial(configureForEmbed, data), 100);
}
function fetchMarkup() {
var url = Context.adapterUrl('svg-edit/SvgEditEmbed.html');
$.get(url).done(function (data) {
frame = $(data);
svgCanvas = new embedded_svg_edit(frame[0]);
Context.publish('loaded', {
open: open,
save: save,
exit: exit,
dom: frame[0].parentNode
});
console.log('Downloaded svg edit markup');
}).fail(function (jqxhr, textStatus, error) {
console.log('Failed to load svg edit markup from: ' + url + '. ' + jqxhr.status + '. ' + error);
});
}
function fetchCss() {
var url = Context.adapterUrl('svg-edit/SvgEditEmbed.css');
$.get(url).done(function (data) {
$('<style>').html(data).appendTo('head');
fetchMarkup();
console.log('Downloaded svg edit css');
}).fail(function (jqxhr, textStatus, error) {
console.log('Failed to load svg edit css from: ' + url + '. ' + jqxhr.status + '. ' + error);
});
}
function fetchScript() {
var url = Context.pluginUrl('svg-edit-2.6/embedapi.js');
$.getScript(url).done(function () {
fetchCss();
}).fail(function (jqxhr, textStatus, error) {
console.log('Failed to load embedapi from: ' + url + '. ' + jqxhr.status + '. ' + error);
});
}
fetchScript();
});
|
$('#submit-staff-button').click(function(){
var nombre_n = $('#nombre').val();
var apellido_paterno_n = $('#apellido_paterno').val();
var apellido_materno_n = $('#apellido_materno').val();
var correo_n = $('#correo').val();
var telefono_n = $('#telefono').val();
var contrasena_n = $('#contraseña').val();
var contrasena2_n = $('#contraseña2').val();
var id_rol_n = $('#id_rol').val();
// Validar que ningun campo esta vacio
var dict = {
1 : check_is_not_empty(nombre_n, '#nombre'),
2 : check_is_not_empty(apellido_paterno_n, '#apellido_paterno'),
3 : check_is_not_empty(apellido_materno_n, '#apellido_materno'),
4 : check_is_not_empty(correo_n, '#correo'),
5 : check_is_not_empty(telefono_n, '#telefono'),
6 : check_is_not_empty(contrasena_n, '#contraseña'),
7 : check_is_not_empty(contrasena2_n, '#contraseña2'),
8 : check_is_not_empty(contrasena2_n, '#contraseña2'),
9 : check_is_not_empty(id_rol_n, '#id_rol')
}
var flag = true;
for(var key in dict) {
var value = dict[key];
if(value == false){
flag = false
break;
}
}
$("#correo").on("keyup",val_mail);
// Enviar un mensaje de retroalimentacion de html si un campo no cumple con los requisitos
contrasena_flag = $('#contraseña')[0].reportValidity();
contrasena_flag2 = $('#contraseña2')[0].reportValidity();
correo_flag = $('#correo')[0].reportValidity();
last_flag = flag && correo_verificar && contrasena_flag && contrasena_flag2 && correo_flag;
if(last_flag == true){
document.getElementById("submit-staff-form").submit();
}
});
|
import React from 'react';
import './style.scss';
import {NavLink} from 'react-router-dom';
function Menu(props) {
return (
<ul id="menu">
<li><NavLink exact to = "/">photos</NavLink></li>
<li><NavLink to = "/favourite">favourite</NavLink></li>
</ul>
)
}
export default Menu;
|
export {format}
function format (old, args) {
let formatted = old
for (var i = 0; i < args.length; i++) {
var regexp = new RegExp('\\%\\%' + i + '\\%\\%', 'gi')
formatted = formatted.replace(regexp, args[i])
}
return formatted
}
|
"use strict";
var proveedorModel = {};
/**
* Agrega un nuevo proveedor o actualiza uno en la base de datos
* @var db - Instancia de la base de datos postgrest
* @var proveedor - Datos del proveedor nuevo a agregar
* @var callback - Función de retorno
*/
proveedorModel.addOrUpdateProveedor = function(db, proveedor, telefonos, callback){
if(db){
db.proveedor.save(proveedor, function(err,res){
if(telefonos != undefined || telefonos != null){
for(var i = 0; i < telefonos.length ;i++){
db.contacto.insert({
id_proveedor : res.id_proveedor,
telefono : telefonos[i]
}, function(erro,resp){
console.log(erro);
console.log(resp);
});
}
}
console.log(res);
callback(res);
});
}
};
/**
* Obtiene un proveedor mediante su id
* @var db - Instancia de la base de datos postgrest
* @var id - Id del proveedor a buscar
* @var callback - Función de retorno
*/
proveedorModel.getProveedor = function(db, id, callback){
if(db){
db.proveedor.findOne(id, function(err,proveedor){
callback(proveedor);
});
}
};
/**
* Obtiene todos los proveedores de la base de datos
* @var db - Instancia de la base de datos postgrest
* @var callback - Función de retorno
*/
proveedorModel.getProveedores = function(db, callback){
if(db){
var sql = "SELECT id_proveedor, nombre, email, saldo_adeudo FROM proveedor";
db.run(sql , function(err,proveedores){
var arrayResponse = [];
arrayResponse.push({
index : 0,
id_proveedor : "",
nombre : "Seleccione un proveedor",
email : "",
saldo_adeudo : 0
});
for(var i = 0 ; i < proveedores.length ; i++){
arrayResponse.push({
index : i + 1 ,
id_proveedor : proveedores[i].id_proveedor,
nombre : proveedores[i].nombre,
email : proveedores[i].email,
saldo_adeudo : proveedores[i].saldo_adeudo
});
}
callback(arrayResponse);
});
}
};
module.exports = proveedorModel;
|
//pageRouter.js
define([
"Log"
,"module"
,"pageDefault"
,"products/pageProducts"
], function(
Log
,module
,pageDefault
,pageProducts
){
// private pub vars
var log = new Log().allow(true).setModule(module).log;
var require2 = require;
//
var moduleObj = {
loadPageSpecificHandler: loadPageSpecificHandler
}
return moduleObj;
//
function loadPageSpecificHandler(onready){
log("init").allow(true).log;
var sURL = document.location.toString();
if (sURL.indexOf("/products")!=-1){
log("choosing Products")
onready(pageProducts)
}
else if(sURL.indexOf("solutions") != -1){
log("choosing Solutions")
onready(pageDefault)
}
else{
log.allow(true).log("can't determine page")
onready(pageDefault)
}
}
})
|
"use strict";
let mongoose = require('mongoose');
let Review = require('../api/models/reviewListModel');
let Category = require('../api/models/categoryModel');
let dimsum = require('dimsum');
mongoose.Promise = global.Promise;
module.exports = (config) => {
let dbURI = config.dev.db;
mongoose.connect(dbURI, {
useMongoClient: true,
}).then(() => {
console.log(`Connected to ${dbURI}`);
}).catch((e) => {
throw e;
});
mongoose.connection.on('connected', (req, res) => {
let categories = require('./categories.json');
let reviews = require('./reviews.json');
// Category.remove((err) => {
// console.log('categories removed');
// Category.collection.insertMany(categories, (err) => {
// console.log('categories added');
// });
// });
Review.remove((err) => {
console.log('reviews removed');
Review.collection.insertMany(reviews, (err) => {
if(err) throw err;
console.log('reviews added');
});
});
});
};
|
const reviews = [
{
id: 1,
reviewTime: `2019-04-24`,
ratingStars: 4.1,
user: {
name: `Max`,
avatar: `img/avatar-max.jpg`
},
reviewText: `A quiet cozy and picturesque that hides behind a a river by the unique lightness of Amsterdam. The building is green and from 18th century.`,
offerId: 1
},
{
id: 2,
reviewTime: `2018-05-24`,
ratingStars: 2.1,
user: {
name: `Max`,
avatar: `img/avatar-max.jpg`
},
reviewText: `A quiet cozy and picturesque that hides behind a a river by the unique lightness of Amsterdam. The building is green and from 18th century.`,
offerId: 1
},
{
id: 3,
reviewTime: `2020-11-12`,
ratingStars: 3.5,
user: {
name: `Max`,
avatar: `img/avatar-max.jpg`
},
reviewText: `A quiet cozy and picturesque that hides behind a a river by the unique lightness of Amsterdam. The building is green and from 18th century.`,
offerId: 1
}
];
export default reviews;
|
var NAVTREEINDEX1 =
{
"auth_8h.html#abd5fa696308aee8cc8d7ce03dffe5593":[2,0,16,1,6],
"auth_8h.html#ac0d4ef7854b342279fb3175045fea0bd":[2,0,16,1,5],
"auth_8h.html#af3464c1149cb7d89dc32fc1c5d3921dc":[2,0,16,1,1],
"auth_8h_source.html":[2,0,16,1],
"auth__anon_8c.html":[2,0,16,2],
"auth__anon_8c.html#abb796c4b74f3553ce7b9722b48c3eafd":[2,0,16,2,0],
"auth__anon_8c_source.html":[2,0,16,2],
"auth__cram_8c.html":[2,0,16,3],
"auth__cram_8c.html#a54b2d394d72e8119c3d217fa64d5598e":[2,0,16,3,3],
"auth__cram_8c.html#a60ca0159a96dd495269bd32f27b784a3":[2,0,16,3,0],
"auth__cram_8c.html#a7491dc64781290870974d803a0dc6b75":[2,0,16,3,2],
"auth__cram_8c.html#ae1ccf1a4af3f69b0f73113109de28a90":[2,0,16,3,1],
"auth__cram_8c_source.html":[2,0,16,3],
"auth__gss_8c.html":[2,0,16,4],
"auth__gss_8c.html#a203bd1c72cb86256613c10cb0c8e1c82":[2,0,16,4,4],
"auth__gss_8c.html#a5bc0cc6171ded3b990764a7926573ead":[2,0,16,4,0],
"auth__gss_8c.html#a690d69a2cbc379fe0eb5392017d54b82":[2,0,16,4,3],
"auth__gss_8c.html#a9870d8bbf044578ccb26ada1e76315f8":[2,0,16,4,2],
"auth__gss_8c.html#ae24a325301dd6fd9599c06f659120b18":[2,0,16,4,1],
"auth__gss_8c_source.html":[2,0,16,4],
"auth__login_8c.html":[2,0,16,5],
"auth__login_8c.html#a2fe43890cdcb3e8cf4c4dbbc8b3e2fda":[2,0,16,5,0],
"auth__login_8c_source.html":[2,0,16,5],
"auth__oauth_8c.html":[2,0,16,6],
"auth__oauth_8c.html#abd5fa696308aee8cc8d7ce03dffe5593":[2,0,16,6,0],
"auth__oauth_8c_source.html":[2,0,16,6],
"auth__plain_8c.html":[2,0,16,7],
"auth__plain_8c.html#ab8347cf766db9a036c3ff83e98f967de":[2,0,16,7,0],
"auth__plain_8c_source.html":[2,0,16,7],
"auth__sasl_8c.html":[2,0,16,8],
"auth__sasl_8c.html#ac0d4ef7854b342279fb3175045fea0bd":[2,0,16,8,0],
"auth__sasl_8c_source.html":[2,0,16,8],
"autocrypt_2config_8c.html":[2,0,2,1],
"autocrypt_2config_8c.html#a1ff2e3a6d4ac57f4f1ddad1e70362217":[2,0,2,1,5],
"autocrypt_2config_8c.html#a2ead7bcfa32f8fc40027a9d094e24ee3":[2,0,2,1,4],
"autocrypt_2config_8c.html#a586714ecbbf893b366082cf8997b015b":[2,0,2,1,3],
"autocrypt_2config_8c.html#a5bf45f267972a6a25b972607dabfaa75":[2,0,2,1,2],
"autocrypt_2config_8c.html#a8a8e0e956c7e9b8da132ec899bdbd8ac":[2,0,2,1,0],
"autocrypt_2config_8c.html#a933b5108398b46e2aadfe51b4ce466a7":[2,0,2,1,6],
"autocrypt_2config_8c.html#acee37b1f22382a6ba6c4a35e016549d9":[2,0,2,1,7],
"autocrypt_2config_8c.html#ae14143f593d5c98d88eeb12bf207ac3b":[2,0,2,1,1],
"autocrypt_2config_8c_source.html":[2,0,2,1],
"autocrypt_2db_8c.html":[2,0,2,2],
"autocrypt_2db_8c.html#a06abfa5c13cc1c6ce053d63c5c692508":[2,0,2,2,4],
"autocrypt_2db_8c.html#a0f742adea596c0b718cc44b5f533ab01":[2,0,2,2,31],
"autocrypt_2db_8c.html#a1475a5c5e3f022694e685651289fb21a":[2,0,2,2,12],
"autocrypt_2db_8c.html#a14ea324044dc79deee0e30ff8fa9e3db":[2,0,2,2,29],
"autocrypt_2db_8c.html#a16f22cdf30f8df65993a0d16e13f2724":[2,0,2,2,17],
"autocrypt_2db_8c.html#a278e65c7972b3237d176caeca0ca4a02":[2,0,2,2,2],
"autocrypt_2db_8c.html#a2ac699259f5467de8e9280229ffe9c56":[2,0,2,2,34],
"autocrypt_2db_8c.html#a3232f54bb8c81c043037aaf8454b5f4c":[2,0,2,2,24],
"autocrypt_2db_8c.html#a46f8db1fe0e0066603a705689dec64c6":[2,0,2,2,9],
"autocrypt_2db_8c.html#a4f30f8989b257f89a46c3af7d09d1e19":[2,0,2,2,16],
"autocrypt_2db_8c.html#a506a23fdc617b5d2f4a810f4138abce3":[2,0,2,2,6],
"autocrypt_2db_8c.html#a51e0aee05d3a3896b5fa0a6d52e195b8":[2,0,2,2,18],
"autocrypt_2db_8c.html#a63c568751c51464a8f0c1e7bb1164292":[2,0,2,2,10],
"autocrypt_2db_8c.html#a68854efa33d1b0d6f63c2d34767b2f9e":[2,0,2,2,8],
"autocrypt_2db_8c.html#a784b83d4ac3b7a315b720fa93ebf9fbf":[2,0,2,2,26],
"autocrypt_2db_8c.html#a7a1ba8370247983cbe31e79557e3e1e9":[2,0,2,2,3],
"autocrypt_2db_8c.html#a84ce468a01d60186082e483812a9883c":[2,0,2,2,32],
"autocrypt_2db_8c.html#a8625763fac1577d11f1a9d7074fcc80e":[2,0,2,2,7],
"autocrypt_2db_8c.html#a89d02546893521f4105eaacfbf3b81f3":[2,0,2,2,22],
"autocrypt_2db_8c.html#a8c87468bf157e512f2835b01823118c1":[2,0,2,2,20],
"autocrypt_2db_8c.html#a9c401461f82bbd761feed64166fb7802":[2,0,2,2,33],
"autocrypt_2db_8c.html#aa1a5925a985592bad3eba18f803386e5":[2,0,2,2,11],
"autocrypt_2db_8c.html#aa280e1078cc60f4e8bd179d6eb0c313c":[2,0,2,2,13],
"autocrypt_2db_8c.html#aaa4ccb4012ae52f10375616cf2770114":[2,0,2,2,27],
"autocrypt_2db_8c.html#abd0f103cd6d4b96587348badc7492240":[2,0,2,2,15],
"autocrypt_2db_8c.html#ac63a3a4e2bb74ffd02cf222e0c0b00eb":[2,0,2,2,14],
"autocrypt_2db_8c.html#ac64386ceb7551f4d92eb76cf750051ba":[2,0,2,2,23],
"autocrypt_2db_8c.html#ac69f3bce090a325d5e948460707899bc":[2,0,2,2,5],
"autocrypt_2db_8c.html#acf7b106265614277728d6aa0ece0dfd9":[2,0,2,2,0],
"autocrypt_2db_8c.html#ad59785b79d676d49d46db0f095faadda":[2,0,2,2,25],
"autocrypt_2db_8c.html#ad641524d30b3714343d161c84049f788":[2,0,2,2,1],
"autocrypt_2db_8c.html#ae5cd16bf38efe076c80192f4a91414c7":[2,0,2,2,19],
"autocrypt_2db_8c.html#ae5f8db547e9c953b8e1d151bdad402d0":[2,0,2,2,28],
"autocrypt_2db_8c.html#aff0072c821e680a2c0e0ccc21ac2b9a1":[2,0,2,2,30],
"autocrypt_2db_8c.html#aff9a9d353dd568fa3989b0555769d172":[2,0,2,2,21],
"autocrypt_2db_8c_source.html":[2,0,2,2],
"autocrypt_2lib_8h.html":[2,0,2,5],
"autocrypt_2lib_8h.html#a0477a928cf8c6b79a25b42e63f4647b8":[2,0,2,5,9],
"autocrypt_2lib_8h.html#a1ff2e3a6d4ac57f4f1ddad1e70362217":[2,0,2,5,15],
"autocrypt_2lib_8h.html#a2ead7bcfa32f8fc40027a9d094e24ee3":[2,0,2,5,20],
"autocrypt_2lib_8h.html#a30461121efab5b3f112767d63191c507":[2,0,2,5,7],
"autocrypt_2lib_8h.html#a586714ecbbf893b366082cf8997b015b":[2,0,2,5,19],
"autocrypt_2lib_8h.html#a5bf45f267972a6a25b972607dabfaa75":[2,0,2,5,18],
"autocrypt_2lib_8h.html#a6ccee2b006fad28ea865139d135e5d59":[2,0,2,5,6],
"autocrypt_2lib_8h.html#a7babe74e49d7b8a73e9f72093d622e66":[2,0,2,5,14],
"autocrypt_2lib_8h.html#a933b5108398b46e2aadfe51b4ce466a7":[2,0,2,5,16],
"autocrypt_2lib_8h.html#aa4a3f8e9aa1ff62c878f2622f1c55ba5":[2,0,2,5,12],
"autocrypt_2lib_8h.html#ab0cad601c656450a46c98e47197b8376":[2,0,2,5,5],
"autocrypt_2lib_8h.html#ac2a58142d9962d1108cf66d8386a70bd":[2,0,2,5,8],
"autocrypt_2lib_8h.html#adba267f8e040ccf88d4c556c6c9e7868":[2,0,2,5,13],
"autocrypt_2lib_8h.html#ae14143f593d5c98d88eeb12bf207ac3b":[2,0,2,5,17],
"autocrypt_2lib_8h.html#ae4aac04801499d414565c58f9f5ac6f6":[2,0,2,5,11],
"autocrypt_2lib_8h.html#aed237ffa27e23d83cb0acc07586ffbda":[2,0,2,5,4],
"autocrypt_2lib_8h.html#aed237ffa27e23d83cb0acc07586ffbdaa09281271bb1138418f339d9b0cf36690":[2,0,2,5,4,2],
"autocrypt_2lib_8h.html#aed237ffa27e23d83cb0acc07586ffbdaa5243c176ca12aa8812707f39781ebec3":[2,0,2,5,4,1],
"autocrypt_2lib_8h.html#aed237ffa27e23d83cb0acc07586ffbdaa63933954fc4878d029d0971193d04338":[2,0,2,5,4,0],
"autocrypt_2lib_8h.html#aed237ffa27e23d83cb0acc07586ffbdaab14b9a70442ff260fb2da093d0ab0c4f":[2,0,2,5,4,3],
"autocrypt_2lib_8h.html#aed237ffa27e23d83cb0acc07586ffbdaaf1e9fd8d8b038a7cf37ee5fd1e4ee741":[2,0,2,5,4,4],
"autocrypt_2lib_8h.html#af4b307317d8b6fba7c6321e93fc21194":[2,0,2,5,10],
"autocrypt_2lib_8h_source.html":[2,0,2,5],
"autocrypt_2private_8h.html":[2,0,2,6],
"autocrypt_2private_8h.html#a06abfa5c13cc1c6ce053d63c5c692508":[2,0,2,6,15],
"autocrypt_2private_8h.html#a1475a5c5e3f022694e685651289fb21a":[2,0,2,6,2],
"autocrypt_2private_8h.html#a1688864ad42e9772f4c1de8e297b097b":[2,0,2,6,29],
"autocrypt_2private_8h.html#a16f22cdf30f8df65993a0d16e13f2724":[2,0,2,6,21],
"autocrypt_2private_8h.html#a183f2f1eff311c4f49f5552966804fdf":[2,0,2,6,26],
"autocrypt_2private_8h.html#a278e65c7972b3237d176caeca0ca4a02":[2,0,2,6,9],
"autocrypt_2private_8h.html#a2894737dbf5865d40fa9807c20d9a51f":[2,0,2,6,30],
"autocrypt_2private_8h.html#a2ac699259f5467de8e9280229ffe9c56":[2,0,2,6,32],
"autocrypt_2private_8h.html#a3232f54bb8c81c043037aaf8454b5f4c":[2,0,2,6,11],
"autocrypt_2private_8h.html#a46f8db1fe0e0066603a705689dec64c6":[2,0,2,6,4],
"autocrypt_2private_8h.html#a4f30f8989b257f89a46c3af7d09d1e19":[2,0,2,6,17],
"autocrypt_2private_8h.html#a51e0aee05d3a3896b5fa0a6d52e195b8":[2,0,2,6,23],
"autocrypt_2private_8h.html#a63c568751c51464a8f0c1e7bb1164292":[2,0,2,6,6],
"autocrypt_2private_8h.html#a68854efa33d1b0d6f63c2d34767b2f9e":[2,0,2,6,3],
"autocrypt_2private_8h.html#a6bf8cc8f42e2dce5232ea607b5706b32":[2,0,2,6,25],
"autocrypt_2private_8h.html#a73749110f164d660af828e2373bc4211":[2,0,2,6,24],
"autocrypt_2private_8h.html#a7a1ba8370247983cbe31e79557e3e1e9":[2,0,2,6,14],
"autocrypt_2private_8h.html#a8625763fac1577d11f1a9d7074fcc80e":[2,0,2,6,7],
"autocrypt_2private_8h.html#a89d02546893521f4105eaacfbf3b81f3":[2,0,2,6,12],
"autocrypt_2private_8h.html#a8c87468bf157e512f2835b01823118c1":[2,0,2,6,18],
"autocrypt_2private_8h.html#a9fb3090d17cb409f612144f817cbcab6":[2,0,2,6,28],
"autocrypt_2private_8h.html#aa1a5925a985592bad3eba18f803386e5":[2,0,2,6,8],
"autocrypt_2private_8h.html#aa280e1078cc60f4e8bd179d6eb0c313c":[2,0,2,6,5],
"autocrypt_2private_8h.html#aa6a1d41202dd88cfe7d34655352e437e":[2,0,2,6,0],
"autocrypt_2private_8h.html#ab8c8b3b72e54e9c0dbead13c629a6885":[2,0,2,6,27],
"autocrypt_2private_8h.html#abd0f103cd6d4b96587348badc7492240":[2,0,2,6,16],
"autocrypt_2private_8h.html#ac63a3a4e2bb74ffd02cf222e0c0b00eb":[2,0,2,6,22],
"autocrypt_2private_8h.html#ac64386ceb7551f4d92eb76cf750051ba":[2,0,2,6,10],
"autocrypt_2private_8h.html#ad641524d30b3714343d161c84049f788":[2,0,2,6,13],
"autocrypt_2private_8h.html#ae5cd16bf38efe076c80192f4a91414c7":[2,0,2,6,20],
"autocrypt_2private_8h.html#ae662fb061f19856ae08ea6d9007d2aa2":[2,0,2,6,1],
"autocrypt_2private_8h.html#afe4f6c496561dd2b14a6d576d369889a":[2,0,2,6,31],
"autocrypt_2private_8h.html#aff9a9d353dd568fa3989b0555769d172":[2,0,2,6,19],
"autocrypt_2private_8h_source.html":[2,0,2,6],
"autocrypt_8c.html":[2,0,2,0],
"autocrypt_8c.html#a0477a928cf8c6b79a25b42e63f4647b8":[2,0,2,0,4],
"autocrypt_8c.html#a30461121efab5b3f112767d63191c507":[2,0,2,0,11],
"autocrypt_8c.html#a33b9a5f3a296e1bcaaeebda77f86ab44":[2,0,2,0,0],
"autocrypt_8c.html#a5a11d5de380fab330d5f37e7ef018da1":[2,0,2,0,8],
"autocrypt_8c.html#a6ccee2b006fad28ea865139d135e5d59":[2,0,2,0,2],
"autocrypt_8c.html#a7babe74e49d7b8a73e9f72093d622e66":[2,0,2,0,10],
"autocrypt_8c.html#aa4a3f8e9aa1ff62c878f2622f1c55ba5":[2,0,2,0,6],
"autocrypt_8c.html#aa6a1d41202dd88cfe7d34655352e437e":[2,0,2,0,3],
"autocrypt_8c.html#ac2a58142d9962d1108cf66d8386a70bd":[2,0,2,0,1],
"autocrypt_8c.html#adba267f8e040ccf88d4c556c6c9e7868":[2,0,2,0,9],
"autocrypt_8c.html#ae4aac04801499d414565c58f9f5ac6f6":[2,0,2,0,7],
"autocrypt_8c.html#ae662fb061f19856ae08ea6d9007d2aa2":[2,0,2,0,12],
"autocrypt_8c.html#af4b307317d8b6fba7c6321e93fc21194":[2,0,2,0,5],
"autocrypt_8c_source.html":[2,0,2,0],
"autocrypt_account.html":[3,2,1],
"autocrypt_autocrypt.html":[3,2,0],
"autocrypt_config.html":[3,2,2],
"autocrypt_db.html":[3,2,3],
"autocrypt_gpgme.html":[3,2,4],
"autocrypt_schema.html":[3,2,5],
"backtrace_8c.html":[2,0,10,0],
"backtrace_8c.html#ad4e568bce6fff0e62266165aec83d7e6":[2,0,10,0,0],
"backtrace_8c_source.html":[2,0,10,0],
"base64_8c.html":[2,0,19,1],
"base64_8c.html#a19ef6d7010ebd0b203c0e6da4119ba0f":[2,0,19,1,1],
"base64_8c.html#a3465fa1b0c7205634eb87bb505264c60":[2,0,19,1,3],
"base64_8c.html#a46d7ee223a298c936fe501e37b06ac58":[2,0,19,1,2],
"base64_8c.html#a6e40ee29658fd6bae8023a2617157514":[2,0,19,1,6],
"base64_8c.html#a768e7c625e7318c12cfe37bc713d365c":[2,0,19,1,4],
"base64_8c.html#abff3beb459075c9e0859e64d791273b8":[2,0,19,1,5],
"base64_8c.html#afd3fc9004925132db4faf607ebbf9db7":[2,0,19,1,0],
"base64_8c_source.html":[2,0,19,1],
"base64_8h.html":[2,0,19,2],
"base64_8h.html#a19ef6d7010ebd0b203c0e6da4119ba0f":[2,0,19,2,2],
"base64_8h.html#a3465fa1b0c7205634eb87bb505264c60":[2,0,19,2,4],
"base64_8h.html#a46d7ee223a298c936fe501e37b06ac58":[2,0,19,2,1],
"base64_8h.html#a768e7c625e7318c12cfe37bc713d365c":[2,0,19,2,3],
"base64_8h.html#a7d7ae4dd0a9d6cbb528295fb24b91a9d":[2,0,19,2,0],
"base64_8h.html#a88f05c9dd91ab9442cdf30aab295ab3e":[2,0,19,2,5],
"base64_8h_source.html":[2,0,19,2],
"bcache_2lib_8h.html":[2,0,3,1],
"bcache_2lib_8h.html#a0bf86733ff0fefb7879f1d75bb44415a":[2,0,3,1,9],
"bcache_2lib_8h.html#a0fd8cd0e88c27788e6268674c71c7879":[2,0,3,1,4],
"bcache_2lib_8h.html#a1cbba854dbad4ca2ef97dfad376a2fa6":[2,0,3,1,0],
"bcache_2lib_8h.html#a3eba1237cb1746acad5efa0a123a892c":[2,0,3,1,7],
"bcache_2lib_8h.html#a5125c4a660fa9267a94153695c44a4f0":[2,0,3,1,2],
"bcache_2lib_8h.html#a61b6432fa4ef33ea232dad524cf907bb":[2,0,3,1,6],
"bcache_2lib_8h.html#a747ba79497d0a085ea36885146f187f4":[2,0,3,1,10],
"bcache_2lib_8h.html#a81a73e04de0e74abec304abb57f9a21a":[2,0,3,1,3],
"bcache_2lib_8h.html#acf998afceb34defdd8d6be4b652ce729":[2,0,3,1,8],
"bcache_2lib_8h.html#aecd453abbb62e97d92f9b39a469c8324":[2,0,3,1,5],
"bcache_2lib_8h.html#af3a22202fb2135dfb1081cb6e6c5fecb":[2,0,3,1,1],
"bcache_2lib_8h_source.html":[2,0,3,1],
"bcache_8c.html":[2,0,3,0],
"bcache_8c.html#a0bf86733ff0fefb7879f1d75bb44415a":[2,0,3,0,11],
"bcache_8c.html#a0fd8cd0e88c27788e6268674c71c7879":[2,0,3,0,9],
"bcache_8c.html#a3eba1237cb1746acad5efa0a123a892c":[2,0,3,0,3],
"bcache_8c.html#a5125c4a660fa9267a94153695c44a4f0":[2,0,3,0,7],
"bcache_8c.html#a5a6da9a92e635c11bf3af21611c6ea5f":[2,0,3,0,1],
"bcache_8c.html#a61b6432fa4ef33ea232dad524cf907bb":[2,0,3,0,10],
"bcache_8c.html#a747ba79497d0a085ea36885146f187f4":[2,0,3,0,12],
"bcache_8c.html#a81a73e04de0e74abec304abb57f9a21a":[2,0,3,0,8],
"bcache_8c.html#acf998afceb34defdd8d6be4b652ce729":[2,0,3,0,6],
"bcache_8c.html#aecd453abbb62e97d92f9b39a469c8324":[2,0,3,0,5],
"bcache_8c.html#af3a22202fb2135dfb1081cb6e6c5fecb":[2,0,3,0,4],
"bcache_8c.html#affefecb14cd62cc08faf0a6ba19b52c0":[2,0,3,0,2],
"bcache_8c_source.html":[2,0,3,0],
"bcache_bcache.html":[3,3,0],
"bdb_8c.html":[2,0,27,0],
"bdb_8c.html#a49a50871ac2d15c6080307ae3220fd05":[2,0,27,0,8],
"bdb_8c.html#a53866de1125543ec46485a4ae61608f0":[2,0,27,0,6],
"bdb_8c.html#a643f916c7bfeb8835411cd8c64563c28":[2,0,27,0,4],
"bdb_8c.html#a7ac56157c217f853bf0d2115eecbfdf5":[2,0,27,0,7],
"bdb_8c.html#a7fb93ba832f9c3b36ae4a00dd2856907":[2,0,27,0,5],
"bdb_8c.html#a8ba0de880d78ebd26fb9c0e2f793d75d":[2,0,27,0,2],
"bdb_8c.html#abff292683b5826af2265983e746780b9":[2,0,27,0,3],
"bdb_8c.html#ac0d858225d9c67a81344e4fdb79ef132":[2,0,27,0,1],
"bdb_8c.html#afc8e37744791b444b9c849dd3279f754":[2,0,27,0,9],
"bdb_8c_source.html":[2,0,27,0],
"bool_8c.html":[2,0,7,2],
"bool_8c.html#a3f0f8081b626af5ea57f2210b6f13927":[2,0,7,2,0],
"bool_8c.html#a45d93120abd858441df2f2d983aa536b":[2,0,7,2,8],
"bool_8c.html#a5ef0a3002d75e9d9a91cda84336c13f5":[2,0,7,2,6],
"bool_8c.html#a8c62e12d9f8415ec172ca96cdf8d83f1":[2,0,7,2,2],
"bool_8c.html#ab5dff16050811e0eb5537725169fb0f4":[2,0,7,2,5],
"bool_8c.html#abc1cdeed545a0b068036842cd2e5a986":[2,0,7,2,7],
"bool_8c.html#ad3c45cb204d1372625fa72c9f00fa2db":[2,0,7,2,4],
"bool_8c.html#adcc1fd1ca971eacff907f8e5f08e6a15":[2,0,7,2,1],
"bool_8c.html#add3e84a22709e9a0711b174a2d8201e8":[2,0,7,2,3],
"bool_8c_source.html":[2,0,7,2],
"bool_8h.html":[2,0,7,3],
"bool_8h.html#a5ef0a3002d75e9d9a91cda84336c13f5":[2,0,7,3,1],
"bool_8h.html#ab5dff16050811e0eb5537725169fb0f4":[2,0,7,3,0],
"bool_8h.html#abc1cdeed545a0b068036842cd2e5a986":[2,0,7,3,2],
"bool_8h_source.html":[2,0,7,3],
"browser_8c.html":[2,0,30],
"browser_8c.html#a06ced7d8ff0eb01b5f17b23f73f76bfb":[2,0,30,20],
"browser_8c.html#a14cf9d1783b7b5e2139bb0dbeea2f57d":[2,0,30,12],
"browser_8c.html#a1ec49102db5b09962963bf5ab5ae16d6":[2,0,30,5],
"browser_8c.html#a2fdd342366031697eaaececec586db00":[2,0,30,19],
"browser_8c.html#a3a2a586cddbc6bf0aae67ea4b85eae81":[2,0,30,0],
"browser_8c.html#a40a157ecde1135a2ddde0a85c0e07150":[2,0,30,15],
"browser_8c.html#a40e724c3dc9462d889ad39181d1aabce":[2,0,30,9],
"browser_8c.html#a42c31e21eb059726b468814248ddf7cd":[2,0,30,10],
"browser_8c.html#a44aefdb8e3bc126b5fab29a8501499e2":[2,0,30,18],
"browser_8c.html#a4c2145b2c5c5bce768e8c77d335a45cc":[2,0,30,30],
"browser_8c.html#a521fce142a7a9c2761988fcfebeceac0":[2,0,30,13],
"browser_8c.html#a66083512f4b2523d4012b7f501eb1842":[2,0,30,2],
"browser_8c.html#a7b9330cfc3900716b46bcb97f0a65f04":[2,0,30,31],
"browser_8c.html#a817b5b600b59e87c2fc7d559077b26ed":[2,0,30,11],
"browser_8c.html#a885690503717d9d6d9f8e7927d6d4abb":[2,0,30,16]
};
|
// import moment from 'moment';
import require from 'requirejs'
// Day 3 exercise
// ///// 1. Exercises: Data types Part
// 1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it
const firstName = "Vladimir";
const lastName = "Striber";
const age = 36;
const country = "Serbia";
const city = "Novi Sad";
const isMarried = true;
const year = new Date();
const now = year.getFullYear();
console.log(`My name is ${firstName} ${lastName}, I am ${age} years old, I live in ${city}, ${country} and if you ask me if I am married the answer is ${isMarried}. I would like to wish you everything best in ${now}.`);
// 2. Check if type of '10' is equal to 10
const number10 = 10;
const string10 = "10";
console.log(typeof number10 === typeof string10);
console.log(number10 === string10);
// 3. Check if parseInt('9.8') is equal to 10
console.log(parseInt("9.8" === 10));
// 4. Boolean value is either true or false.
// a) Write three JavaScript statement which provide truthy value.
// b) Write three JavaScript statement which provide falsy value.
let number1 = 1;
let string1 = "1";
console.log(number1 === string1, "number1 == string1");
console.log(null === 0, "null === 0");
// 5. Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log()
// I. 4 > 3 true
// II. 4 >= 3 true
// III. 4 < 3 false
// IV. 4 <= 3 false
// V. 4 == 4 true
// VI. 4 === 4 true
// VII. 4 != 4 false
// VIII. 4 !== 4 false
// IX. 4 != '4' false
// X. 4 == '4' true
// XI. 4 === '4' false
// XII. Find the length of python and jargon and make a falsy comparison statement.
console.log("4 > 3", 4 > 3);
console.log("4 >= 3", 4 >= 3);
console.log("4 < 3", 4 < 3);
console.log("4 <= 3", 4 <= 3);
console.log("4 == 4", 4 == 4);
console.log("4 === 4", 4 === 4);
console.log("4 != 4", 4 != 4);
console.log("4 !== 4", 4 !== 4);
console.log("4 != '4'", 4 != '4');
console.log("4 == '4'", 4 == '4');
console.log("4 === '4'", 4 === '4');
const python = "python";
const jargon = "jargon";
console.log("python === jargon", python.length !== jargon.length );
// 6. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log()
// I. 4 > 3 && 10 < 12 true
// II. 4 > 3 && 10 > 12 false
// III. 4 > 3 || 10 < 12 true
// IV. 4 > 3 || 10 > 12 true
// V. !(4 > 3) false
// VI. !(4 < 3) true
// VII. !(false) true
// VIII. !(4 > 3 && 10 < 12) false
// IX. !(4 > 3 && 10 > 12) true
// X. !(4 === '4') true
// XI. There is no 'on' in both dragon and python false
console.log(" I. 4 > 3 && 10 < 12", 4 > 3 && 10 < 12);
console.log("II. 4 > 3 && 10 > 12", 4 > 3 && 10 > 12);
console.log("III. 4 > 3 || 10 < 12", 4 > 3 || 10 < 12);
console.log("IV. 4 > 3 || 10 > 12", 4 > 3 || 10 > 12);
console.log("V. !(4 > 3)", !(4 > 3));
console.log("VI. !(4 < 3)", !(4 < 3));
console.log("VII. !(false)", !(false));
console.log("VIII. !(4 > 3 && 10 < 12)", !(4 > 3 && 10 < 12));
console.log("IX. !(4 > 3 && 10 > 12)", !(4 > 3 && 10 > 12));
console.log("X. !(4 === '4')", !(4 === '4'));
// 7. Use the Date object to do the following activities:
// I. What is the year today?
// II. What is the month today as a number?
// III. What is the date today?
// IV. What is the day today as a number?
// V. What is the hours now?
// VI. What is the minutes now?
// VII. Find out the numbers of seconds elapsed from January 1, 1970 to now.
const myDate = new Date();
console.log("I. What is the year today?", myDate.getFullYear());
console.log("II. What is the month today as a number?", myDate.getMonth());
console.log(" III. What is the date today?", myDate);
console.log("IV. What is the day today as a number?", myDate.getDate());
console.log("V. What is the hours now?", myDate.getHours());
console.log("// VII. Find out the numbers of seconds elapsed from January 1, 1970 to now.\n", myDate.getTime());
// 2. The JavaScript typeof operator uses to check different data types. Check the data type of each variables from question number 1.
console.log(`firstName (${firstName}) - `, typeof firstName);
console.log(`lastName (${lastName}) - `, typeof lastName);
console.log(`age (${age}) - `, typeof age);
console.log(`country (${country}) - `, typeof country);
console.log(`city (${city}) - `, typeof city);
console.log(`isMarried (${isMarried}) - `, typeof isMarried);
console.log(`year (${year}) - `, typeof year);
console.log(`now (${now}) - `, typeof now);
// ///// 2. Exercises: Arithmetic Operators Part
// 1. Write a script that prompt the user to enter base and height of the triangle and calculate an area of a triangle (area = 0.5 x b x h).
// let base = prompt("Enter base", "Number goes here");
// let height = prompt("Enter height", "Number goes here");
// console.log(`area of the triangle - `, base * height / 2);
// 2. Write a script that prompt the user to enter side a, side b, and side c of the triangle and and calculate the perimeter of triangle (perimeter = a + b + c)
// let side_a = prompt("Enter side a", "Enter side a");
// let side_b = prompt("Enter side b", "Enter side b");
// let side_c = prompt("Enter side c", "Enter side c");
// console.log(`perimeter of the triangle - `, Number(side_a) + Number(side_b) + Number(side_c));
// when we work with addition we need to use Number() or +{{variable}} because we would get the string (eg. 2345 instead of 2 + 3 + 4 + 5 = 14)
// if we work with multiply then we don't have to use these methods
// the same as above (but strange though)
// console.log(`perimeter of the triangle - `, +side_a + +side_b + +side_c);
// 3. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width))
// let side_a = prompt("Enter side a", "Side a");
// let side_b = prompt("Enter side b", "Side b");
// console.log("The area of a triangle is: ", side_a * side_b);
// 4. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14.
// const radius = prompt("Enter radius", "radius");
// console.log(radius**2*3.14, "area");
// console.log(radius*2*3.14, "circumference");
// 5. Calculate the slope, x-intercept and y-intercept of y = 2x -2
let x = Math.floor(Math.random() * 11);
let y = 2*x - 2;
console.log(`x - ${x}, y - ${y}`);
// 6. Slope is (m = y2-y1/x2-x1). Find the slope between point (2, 2) and point(6,10)
const x1 = 2;
const y1 = 2;
const x2 = 6;
const y2 = 10;
const m = y2 - y1 / x2 - x1;
console.log(m);
// 7. Compare the slope of above two questions.
// 8. Calculate the value of y (w = z^2 + 6x + 9). Try to use different x values and figure out at what z value w is 0.
let z;
let w;
z = -3;
w = z**2 + 6*z + 9;
console.log(`w is ${w}`);
// 9. Writ a script that prompt a user to enters hours and rate per hour. Calculate pay of the person?
// Enter hours: 40
// Enter rate per hour: 28
// Your weekly earning is 1120
// let hours = prompt("Enter hours", "Hours here");
// let rate = prompt("Enter rate per hour", "Rate here");
// console.log(`Pay of the persone - `, hours * rate);
// 10. If the length of your name is greater than 7 say, your name is long else say your name is short.
const myName = "Vladimir";
if (myName.length > 7) {
console.log(`My name is long`);
} else {
console.log(`My name is short`);
}
// 11. Compare your first name length and your family name length and you should get this output.
const myFirstName = `Vladimir`;
const myLastName = `Striber`;
if (myFirstName.length > myLastName.length) {
console.log(`My first name, ${myFirstName}, is longer than my last name, ${myLastName}!`);
} else {
console.log(`My last name, ${myLastName}, is longer than my first name, ${myFirstName}!`);
}
// 12. Declare two variables myAge and yourAge and assign them initial values and myAge and yourAge.
let myAge = 250;
let yourAge = 25;
let diff = myAge - yourAge;
console.log(`I am ${diff} years older than you!`);
// 13. Using prompt get the year the user was born and if the user is 18 or above allow the user to drive if not tell the user to wait a certain amount of years.
// const birthYear = prompt("Enter your birth year", "Year");
// const today = new Date().getUTCFullYear();
// const driversAge = today - birthYear;
// if (driversAge > 18) {
// console.log("You are " + driversAge + ". " + "You are old enough to drive.");
// } else {
// console.log(`You are ${driversAge}. You are not old enough to drive!`);
// }
// 14. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
// const numOfYears = prompt("Enter number of years", "Number of years");
// console.log(numOfYears * 31536000);
// 15. Create a human readable time format using the Date time object
// i. YYY-MM-DD HH:mm
// ii. DD-MM-YYYY HH:mm
// iii. DD/MM/YYY HH:mm
var moment = require('moment');
// moment().format();
console.log(moment());
// var currentDateTime = new moment();
//
// console.log(currentDateTime);
// window.onload = function() {
// let new_date = new Date();
// let display_date = moment(new_date).format("YYY-MM-DD HH:mm");
// console.log(display_date);
// };
|
const { courseProgress } = require('./courseProgress');
exports.allCourseProgressMutations = `
${ courseProgress }
`;
|
const initialState = {
limitFirst: false,
limitFirstLoading: false,
limitFirstError: false
};
function LimitFirstReducer(state = initialState, action) {
switch (action.type) {
case 'limitFirst/get-start':
return {
...state,
loading: true
}
case 'limitFirst/get-success':
return {
...state,
limitFirst: action.payload.limitFirst,
loading: false,
error: ''
}
case 'limitFirst/get-failed':
return {
...state,
loading: false,
error: action.payload.error
}
default:
return state
}
}
export default LimitFirstReducer;
|
var objCarrer = new Object();
objCarrer.ID = 0;
objCarrer.TIPUS = '';
objCarrer.CARRER = '';
function carrer() {
alert('carr');
return objCarrer;
}
function carrer(aDatos) {
if (undefined === aDatos) return objCarrer;
if (void 0 === aDatos) return objCarrer;
if(aDatos == null) return objCarrer;
try {
this.ID = aDatos['id'];
this.TIPUS = aDatos['tipus'] + '';
this.CARRER = aDatos['carrer'] + '';
return this;
} catch (e) { mensaje('creant objecte : carrer ERROR : ' + e.message,"error"); return null; }
}
|
document.addEventListener("DOMContentLoaded", function() {
var sendToExtensionButton = document.getElementById("sendToExtension");
sendToExtensionButton.addEventListener('click', function(e) {
chrome.runtime.sendMessage({
content : "popup.js chrome.runtime.sendMessage"
}, function(response) {
console.log(response);
});
});
var sendToContentButton = document.getElementById("sendToContent");
sendToContentButton.addEventListener('click', function() {
chrome.tabs.query({
active : true,
currentWindow : true
}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
content : "popup.js chrome.tabs.sendMessage"
}, function(response) {
console.log(response);
});
});
});
});
|
import React from "react";
import { connect } from "react-redux";
import QueryString from "query-string";
import ListView from "../ListView";
import MapView from "../MapView";
import "./styles.scss";
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
export class LunchPage extends React.PureComponent {
render() {
const { list, location } = this.props;
const search = QueryString.parse(location.search);
const selected = search.restaurant ? list.items.filter(item => item.name.toLowerCase() === search.restaurant.toLowerCase()) : (isMobile ? []: list.items);
return (
<div className={`lunch-page ${selected.length ? "selected" : ""}`}>
<ListView />
<MapView item={selected[0]} />
</div>
);
}
}
const mapStateToProps = state => ({
list: state.list
});
export default connect(mapStateToProps)(LunchPage);
|
'use strict';
const eventData = require('../../data/events/dates');
var moment = require("moment");
const getAllDateDoctors = async (req, res, next) => {
try {
var fechaactual0 = moment().format("YYYYMM");
//var fechaactual1 = moment().add(1, 'month').format("YYYYMM");
const data ={
idEspecialidad:req.params.idEspecialidad,
periodo:fechaactual0,
sede:req.params.sede
}
/*const data2 ={
idEspecialidad:req.params.idEspecialidad,
periodo:fechaactual1,
sede:req.params.sede
}
let fechas = [];
for(var i=0;i < 2;i++){
if(i===0){
const eventlist = await eventData.getAllDateDoctors(data);
fechas.push(eventlist);
}
if (i===1){
const eventlist = await eventData.getAllDateDoctors(data2);
fechas.push(eventlist);
}
} */
const eventlist = await eventData.getAllDateDoctors(data);
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getOneDateDoctors = async (req, res, next) => {
try {
var fechaactual0 = moment().format("YYYYMM");
// var fechaactual1 = moment().add(1, 'month').format("YYYYMM");
const data ={
idMedico:req.params.idMedico,
idEspecialidad:req.params.idEspecialidad,
periodo:fechaactual0,
sede:req.params.sede,
}
/*const data2 ={
idMedico:req.params.idMedico,
idEspecialidad:req.params.idEspecialidad,
periodo:fechaactual1,
sede:req.params.sede,
}
let fechas = [];
for(var i=0;i < 2;i++){
if(i===0){
const eventlist = await eventData.getOneDateDoctors(data);
fechas.push(eventlist);
}
if (i===1){
const eventlist = await eventData.getOneDateDoctors(data2);
fechas.push(eventlist);
}
} */
const eventlist = await eventData.getOneDateDoctors(data);
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
module.exports = {
getAllDateDoctors,
getOneDateDoctors
}
|
/**
* The Renderer class converts between screen and scene space.
*/
function Renderer(canvas, scene) {
this.canvas = canvas;
this.scene = scene;
this.init_views();
};
/**
* Setup variables for screen<->camera<->scene conversions.
*/
Renderer.prototype.init_views = function() {
var camera = this.scene.camera;
var world_width = this.canvas.width;
var world_height = this.canvas.height;
var world_up = new Vector(0, -1, 0);
// compute view limits
this.eye_vector = camera.direction.sub(camera.position);
this.viewpoint_right = this.eye_vector.cross(world_up).normalize();
this.viewpoint_up = this.viewpoint_right.cross(this.eye_vector).normalize();
// camera <-> screen space conversion
this.half_width = Math.tan(Math.PI * (camera.field_of_view / 2) / 180);
this.half_height = (world_height / world_width) * this.half_width;
this.pixel_width = (this.half_width * 2) / (world_width - 1);
this.pixel_height = (this.half_height * 2) / (world_height - 1);
};
/**
* Render the pixel at (x, y) by recursive ray tracing.
*/
Renderer.prototype.render_pixel = function(x, y) {
// compute direction of pixel from eye position
var X = this.viewpoint_right.mult((x * this.pixel_width) - this.half_width);
var Y = this.viewpoint_up.mult((y * this.pixel_height) - this.half_height);
// trace primary ray
var ray = new Ray(this.scene.camera.position,
this.eye_vector.add(X).add(Y).normalize());
var color = trace(this.scene, ray, 0);
return color;
};
|
'use strict';
describe('Controller: RecordDetailsCtrl', function () {
// load the controller's module
beforeEach(module('batchUtilApp'));
var RecorddetailsCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
RecorddetailsCtrl = $controller('RecordDetailsCtrl', {
$scope: scope
});
}));
});
|
import SSO from '../lib/SSO';
import GoodDataHelper from '../lib/GoodDataHelper';
const _ = require('lodash');
const fs = require('fs');
const moment = require('moment');
export default class Users {
constructor(db, storage, validation, services) {
this.db = db;
this.storage = storage;
this.validation = validation;
this.services = services;
}
list(event) {
this.validation.validate(event, {
pagination: true,
});
return this.storage.verifyToken()
.then(auth => this.db.listUsers(auth.owner.id, _.get(event, 'queryStringParameters.nextPageToken', null)))
.then(res => ({
headers: { Link: _.get(res, 'nextPageToken', null) ? `${this.services.getEnv('API_URL')}/projects?nextPageToken=${res.nextPageToken}; rel="next"` : null },
body: res.data,
statusCode: 200,
}));
}
async create(event) {
const params = this.validation.validate(event, {
body: {
login: this.validation.stringRequired('login'),
password: this.validation.stringRequiredMinLength('password', 7),
firstName: this.validation.stringRequired('firstName'),
lastName: this.validation.stringRequired('lastName'),
email: this.validation.email('email'),
uid: this.validation.forbidden('uid'),
},
});
const gdHelper = new GoodDataHelper(this.db, this.services);
const auth = await this.storage.verifyToken();
const uid = await gdHelper.createUser(params.body, auth);
return { uid };
}
async delete(event) {
const params = this.validation.validate(event, {
path: {
login: this.validation.string('login'),
},
});
const gdHelper = new GoodDataHelper(this.db, this.services);
const auth = await this.storage.verifyToken();
return gdHelper.deleteUser(params.pathParameters.login, auth);
}
sso(event) {
const params = this.validation.validate(event, {
path: {
login: this.validation.string('login'),
},
});
const encryptKey = fs.readFileSync('./gooddata-pub.key').toString('ascii');
const signKey = Buffer.from(this.services.getEnv('GD_SSO_SIGN_KEY'), 'base64').toString('ascii');
const sso = new SSO(
this.services.getEnv('GD_SSO_PROVIDER'),
encryptKey,
signKey,
this.services.getEnv('GD_SSO_SIGN_KEY_PASS')
);
return this.storage.verifyToken()
.then(auth => this.db.getUser(params.pathParameters.login, auth.owner.id))
.then(() => sso.getClaims(params.pathParameters.login, moment().add(1, 'day').unix()));
}
}
|
import React, { Component } from 'react';
import Countdown from 'react-countdown-now';
const Completionist = () => <span>Started already</span>;
const renderer = ({ days, hours, minutes, completed }) => {
if (completed) {
// Render a completed state
return <Completionist />;
} else {
// Render a countdown
var months = Math.floor(days/30);
days = days % 30;
return <span>{months} months {days} days {hours} hours and {minutes} minutes</span>;
}
};
export default class Home extends Component {
render(){
return(
<Countdown date={new Date('2020-04-01T10:00:00')}
renderer={renderer} />
)
}
}
|
import React, { Component } from 'react';
import axios from 'axios';
import PendingPartners from './PendingPartners';
import {Link} from 'react-router-dom';
import {BrowserRouter as Router,Route} from 'react-router-dom';
class PendingPartnersForm extends Component {
state={
_id:'',
email: '',
password: '',
name: '',
registered:''
}
constructor(props){
super(props)
this.state={
pendingpartners:[],
error:false,
loading:true
// updatedadmin:null
}
}
componentDidMount() {
const tokenB= localStorage.getItem('jwtToken');
axios
.get('http://localhost:5000/api/admins/p/pendingpartners',{
Authorization: tokenB
})
.then(res=> this.setState({pendingpartners:res.data.data,loading:false}))
.catch(error=> this.ERROR.bind(error))
}
approvepartner =(id)=>{
const tokenB= localStorage.getItem('jwtToken');
console.log(id)
axios.put(`http://localhost:5000/api/admins/arpartner/${id}`,{registered:"yes"
},{
Authorization: tokenB
}
).then(res => {this.setState({pendingpartners:[...this.state.PendingPartnersForm,res.data]})})
.catch(e=> "error")
alert('Partner was registered succesfully')
window.location = '/admin/pendingpartners';
}
rejectpartner =(id)=>{
const tokenB= localStorage.getItem('jwtToken');
console.log(id)
axios.put(`http://localhost:5000/api/admins/arpartner/${id}`,{registered:"rejected"
},{
Authorization: tokenB
}
).then(res => {this.setState({pendingpartners:[...this.state.PendingPartnersForm,res.data]})})
.catch(e=> "error")
alert('Partner was rejected to register and removed succesfully')
window.location = '/admin/pendingpartners';
window.location = '/admin/pendingpartners';
}
render() {
return this.state.error?<h1>process could not be complete</h1>:this.state.loading?
<h1>loading please be patient</h1>
:(
<div className="Pending Jobs">
<h1>Pending Partners</h1>
<Link to="/admin">Admin Page</Link>
<PendingPartners pendingpartners = {this.state.pendingpartners} approvepartner={this.approvepartner} rejectpartner={this.rejectpartner}/>
<br />
</div>
);
}
ERROR=(error)=>{
console.log(error)
this.setState({error:true})
}
}
export default PendingPartnersForm;
|
import React from "react";
import { ToastContainer } from "react-toastify";
import { HashRouter as Router, Switch, Route } from "react-router-dom";
import Report from "./containers/Reports";
import ChangePassword from "./containers/ChangePassword";
import Login from "./containers/Login";
import PrivateRoute from "./components/PrivateRoute";
import Dashboard from "./containers/Dashboard";
import Loader from "./components/Loader";
const AsyncDashboard = React.lazy(() => import("./containers/Dashboard"));
const Routing = props => (
<Router>
<Switch>
<Route exact path="/" render={props => <Report {...props} />} />
<Route path="/login" component={Login} />
<Route
exact
path="/change-password"
render={props => <ChangePassword {...props} />}
/>
<PrivateRoute path="/dashboard" component={Dashboard} />
<PrivateRoute
path="/"
component={
process.env.NODE_ENV === "development" ? (
Dashboard
) : (
<Suspense fallback={<Loader />}>
<AsyncDashboard />
</Suspense>
)
}
/>
</Switch>
<ToastContainer />
</Router>
);
export default Routing;
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router-dom';
import { connect } from 'react-redux';
import Place from 'components/Place/Place';
import PlaceLink from 'components/PlaceLink/PlaceLink';
import Search from 'containers/Search';
import Details from 'containers/Details';
export class HomePage extends PureComponent {
static propTypes = {
place: PropTypes.object,
match: PropTypes.object,
};
render() {
const { place } = this.props;
const PlaceComponent = place.id ?
<PlaceLink place={place} /> :
<Place place={place} />;
return (
<div className="homePageWrapper">
<Route path="/" exact component={ () => PlaceComponent } />
<Route path="/" exact component={ Search } />
<Route path="/details/:placeid" exact component={Details} />
</div>
);
}
}
const mapStateToProps = state => ({
place: state.place,
});
export default connect(
mapStateToProps,
)(HomePage);
|
module.exports.authenticate = (opts) => {
const props = Object.assign({}, {
fallbackUrl : '',
successUrl : '',
sendError : true
}, opts);
return (req, res, next) => {
if (req.isAuthenticated()) {
if (props.successUrl) {
res.redirect(props.successUrl);
} else {
next();
}
} else {
if (props.fallbackUrl) {
res.redirect(props.fallbackUrl);
} else {
if (props.sendError) {
res.status(403).send('Access Denied');
} else {
next();
}
}
}
}
};
|
var mobileSearchButton = document.querySelector('.header-search__mobile-search');
var searchInput = document.querySelector('.header-search__input');
var searchForm = document.querySelector('.header-search');
mobileSearchButton.addEventListener('click', function (e) {
e.preventDefault();
searchInput.classList.add('header-search__input--mobile-open');
searchInput.focus();
searchInput.addEventListener('blur', function (e) {
searchInput.classList.remove('header-search__input--mobile-open');
});
});
var mobileMenuToggle = document.getElementById('mobileMenuToggle');
var productsMenu = document.querySelector('.products-menu');
var mobileMenuClose = document.querySelector('.products-menu__heading-button');
mobileMenuToggle.addEventListener('click', function (e) {
e.preventDefault();
productsMenu.classList.add('products-menu--mobile-open');
});
mobileMenuClose.addEventListener('click', function (e) {
e.preventDefault();
productsMenu.classList.remove('products-menu--mobile-open');
});
var parentLinks = document.querySelectorAll('.products-menu__link--parent');
[].forEach.call(parentLinks, function (link) {
var productsSubmenu = link.nextSibling;;
var mobileCategoryClose = productsSubmenu.querySelector('.products-menu__heading-button--sub');
link.addEventListener('click', function (e) {
e.preventDefault();
productsSubmenu.classList.add('products-menu__submenu-wrapper--mobile-open');
});
mobileCategoryClose.addEventListener('click', function (e) {
e.preventDefault();
productsSubmenu.classList.remove('products-menu__submenu-wrapper--mobile-open');
});
});
|
import React, { Fragment } from 'react';
import './HeaderNav.scss';
import { IconContext } from 'react-icons';
import { Link } from 'react-router-dom';
import { FaBars } from 'react-icons/fa';
const HeaderNav = ({ onClickHandle }) => {
return (
<Fragment>
<div className="HeaderNav">
<div className="NavList">
<Link to="/editor">editor</Link>
<Link to="/template">template</Link>
<Link to="/community">community</Link>
{!localStorage.getItem('webber_user') && (
<Link to="/login">login</Link>
)}
</div>
<IconContext.Provider value={{ size: '27', className: 'NavMore' }}>
<FaBars onClick={onClickHandle.bind(this)} />
</IconContext.Provider>
</div>
</Fragment>
);
};
export default HeaderNav;
|
import React,{ useState } from 'react';
import {
Button,
Modal,
ModalHeader,
ModalBody,
Form,
FormGroup,
Container,
Label,
Input
} from 'react-bootstrap';
import axios from 'axios';
const AddReview = (props) => {
const [AddedReviewID,setAddedReviewID] = useState();
const [show, setShow] = useState(false);
//const[AddedPost,setAddedPost] = useState({});
//const[CurrentReviews,setCurrentReviews] = useState(props.reviews);
const[Username,setUsername] = useState('');
const[Comment,setComment] = useState('');
const[Score,setScore] = useState(0);
//const[DateCreated,setDateCreated] = useState(new Date());
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
const onChangeUsername = (e) => {
setUsername(e.target.value)
}
const onChangeComment = (e) => {
setComment(e.target.value)
}
const onChangeScore = (e) => {
setScore(e.target.value)
}
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const SubmitPost = async (e) => {
e.preventDefault();
const Review = {
username: Username,
post_id: props.id ,
comment: Comment,
score: Score,
date: date,
}
/*console.log(Review);
console.log(props.reviews);
const CurrentReviews = [...props.reviews,Review];
console.log(CurrentReviews);*/
axios.post('http://localhost:5000/reviews/add',Review)
.then(response => {
console.log(response.data._id);
//setAddedReviewID(response.data._id);
//console.log(AddedReviewID);
axios.patch('http://localhost:5000/posts/update/' + props.id , { "reviews": [...props.reviews,{Original_Id: response.data._id ,username: Username, post_id: props.id ,comment: Comment, score: Score, date: date,
}
] });
window.location.reload();
})
.catch(error => console.log(error));
/*axios.patch('http://localhost:5000/posts/update/' + props.id , { "reviews": [...props.reviews,{
Original_Id: AddedReviewID,
username: Username,
post_id: props.id ,
comment: Comment,
score: Score,
date: date,
}] });*/
//axios.get('http://localhost:5000/reviews/')
//
//
}
return (
<div>
<button onClick={()=>(console.log(props.reviews))}>
click
</button>
<Button className="EDIT btn btn-outline-info btn-sm" variant="primary" onClick={handleShow}>
Add Review
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Container>
<Form classname="container" onSubmit={SubmitPost}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Username</Form.Label>
<Form.Control type="text" placeholder="Enter title" value={Username} onChange={onChangeUsername} />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>comment</Form.Label>
<Form.Control type="text" placeholder="Enter title" value={Comment} onChange={onChangeComment} />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>score</Form.Label>
<Form.Control type="number" placeholder="Enter title" value={Score} onChange={onChangeScore} />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</Container>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</div>
)
}
export default AddReview
|
import React from 'react';
import PostPage from '../features/post/PostPage';
export const paginate = {
data: 'posts',
size: 1,
};
export const postLink = function (post) {
return `/${post.slug}/index.html`;
};
export const permalink = function (data) {
const post = data.pagination.items[0];
return postLink(post);
};
export default function PostItem({ pagination, route }) {
const post = pagination.items[0];
return (
<PostPage
route={route}
post={post}
prev={pagination.prevItem}
next={pagination.nextItem}
/>
);
}
|
import React from 'react';
import {
ActivityIndicator,
AsyncStorage,
Button,
Dimensions,
FlatList,
Keyboard, Linking,
StyleSheet,
Text,
TouchableWithoutFeedback,
View,
} from 'react-native';
import * as _ from 'lodash';
import Metrics from '../Themes/Metrics';
import Colors from '../Themes/Colors';
import {Feather} from '@expo/vector-icons';
import Modal from 'react-native-modal';
import MovingBlock from '../components/movingBlock';
import axios from 'axios';
import {FormInput} from 'react-native-elements';
import Loading from '../components/loading';
import MovingCompanyCard from '../components/moving-company-card';
const {width} = Dimensions.get('window');
/*
Displays information about Jedi
*/
export default class MovingCompanies extends React.Component {
static navigationOptions = ({navigation}) => {
const {navigate} = navigation;
return {
headerTitle: 'Moving Companies',
title: 'Moving Companies',
headerLeft: (
<Feather
style={styles.icon}
name="menu"
size={Metrics.icons.medium}
color={'lightblue'}
onPress={() => navigate('DrawerToggle')}
/>
),
}
};
constructor(props) {
super(props);
this.state = {
isDataLoaded: false,
offset: 0,
limit: 10,
data: [],
zipCode: null,
};
}
async componentDidMount() {
const zipCode = +(await AsyncStorage.getItem('movingCompanies/zipCode'));
if (!_.isFinite(zipCode)) {
return this.setState({
isDataLoaded: true,
});
}
this.setState({
zipCode,
}, () => this._resetData());
}
_renderListItem(item) {
const {navigate} = this.props.navigation;
return (
<MovingCompanyCard
jedi={item}
onCardPressed={() => navigate('MovingCompanyScreen', {jedi: item})}
onButtonPressed={() => Linking.openURL(item['url'])}
/>
);
}
static _extractKey(item, index) {
return index.toString();
}
render() {
const {zipCode} = this.state;
let isRequiredFieldsFilled = _.isFinite(zipCode);
const {
isDataLoaded,
data,
} = this.state;
if (!isDataLoaded) {
return (<Loading/>);
}
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
<View style={styles.container}>
<View style={styles.purchaseBox}>
<View style={{
flexDirection: 'row',
justifyContent: 'center',
}}>
<FormInput
value={this.zipCodeTextInputValue || _.isFinite(zipCode) ? zipCode.toString() : ''}
placeholder="Zip code"
containerStyle={{flex: 1}}
onChangeText={(zipCode) => this._onZipCodeChanged(zipCode)}
/>
<Button
title="Save"
color="powderblue"
onPress={() => this._onSaveZipCodeButtonPressed()}
/>
</View>
<View style={{alignItems: 'center', justifyContent: 'center'}}>
<Modal
isVisible={this.state.isModalVisible}
onBackdropPress={() => this.setState({isModalVisible: false})}
backdropColor={'black'}>
<View style={styles.modalView}>
<Text style={styles.modalText}>
Pick a Category!
</Text>
<Button
backgroundColor='#03A9F4'
buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 5, marginTop: 5}}
title='MISCELLANEOUS'
onPress={() => this.onPressMiscellaneous()}/>
<Button
backgroundColor='#03A9F4'
buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 5, marginTop: 5}}
title='ELECTRONICS'
onPress={() => this.onPressElectronics()}/>
<Button
backgroundColor='#03A9F4'
buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 5, marginTop: 5}}
title='CLOTHES'
onPress={() => this.onPressClothes()}/>
<Button
backgroundColor='#03A9F4'
buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 5, marginTop: 5}}
title='SMALL ITEMS'
onPress={() => this.onPressSmallItems()}/>
</View>
</Modal>
</View>
</View>
<View style={styles.itemList}>
{isRequiredFieldsFilled
? (
<FlatList
data={data}
renderItem={({item}) => this._renderListItem(item)}
keyExtractor={MovingCompanies._extractKey}
contentContainerStyle={{alignItems: 'center'}}
ListEmptyComponent={<Text>The list is empty.</Text>}
ItemSeparatorComponent={() => (<View style={{height: 10}}/>)}
ListFooterComponent={<ActivityIndicator/>}
onEndReached={() => this._appendData()}
/>
)
: (
<View style={{alignItems: 'center'}}>
<Text>Please fill required fields.</Text>
</View>
)
}
</View>
</View>
</TouchableWithoutFeedback>
);
}
_onZipCodeChanged(zipCodeTextInputValue) {
this.setState({zipCodeTextInputValue});
}
async _onSaveZipCodeButtonPressed() {
const {zipCodeTextInputValue} = this.state;
const zipCode = _.toInteger(zipCodeTextInputValue);
if (!_.isFinite(zipCode)) return;
await AsyncStorage.setItem('movingCompanies/zipCode', zipCode.toString());
this.setState({
offset: 0,
zipCode,
}, () => this._resetData());
}
static async _getData(zipCode, offset = 0, limit = 10) {
const config = {
headers: {'Authorization': 'Bearer' + ' seLNca0HOVX5jAVvi_Fz6YjBCHh7qklq2-bgXmK92gRX_37KbTBewIUjHTav4Sv1UUZtv8feAarIaqQGJqd8sdEAX_iVxucHiDRVHTXBhJ_IFLSug7ExYCwsM5HVWnYx'},
params: {
term: 'moving',
location: zipCode,
categories: 'moving,storage',
offset,
limit,
},
};
const response = await axios.get('https://api.yelp.com/v3/businesses/search', config);
return response['data'];
}
async _resetData() {
this.setState({
isDataLoaded: false,
});
const {zipCode} = this.state;
const rawData = await MovingCompanies._getData(zipCode);
this.setState({
zipCode,
isDataLoaded: true,
offset: 0,
limit: 10,
data: rawData['businesses'],
});
}
async _appendData() {
const {zipCode, data} = this.state;
const {offset, limit} = this.state;
const rawData = await MovingCompanies._getData(zipCode, offset, limit);
this.setState({
zipCode,
offset: offset + limit,
data: [...data, ...rawData['businesses']],
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
// paddingTop: 40,
backgroundColor: Colors.snow,
alignItems: 'center',
// justifyContent: 'center',
},
header: {
height: 60,
width: width,
backgroundColor: '#ff8080',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 10,
},
title: {
color: 'white',
fontSize: 24,
},
purchaseBox: {
alignItems: 'center',
justifyContent: 'center',
marginTop: 20,
// height: 200,
width: Metrics.width * .9,
marginBottom: 16,
},
textStyles: {
justifyContent: 'center',
alignItems: 'center',
marginTop: 10,
marginBottom: 10,
fontWeight: 'bold',
fontSize: 12,
},
itemList: {
// height: Metrics.screenHeight * .6,
// width: Metrics.screenWidth,
// paddingTop: 10,
},
modalView: {
// width: Metrics.screenWidth,
height: Metrics.screenHeight * .6,
borderStyle: 'solid',
borderWidth: .5,
alignItems: 'center',
justifyContent: 'space-around',
backgroundColor: 'white',
borderBottomLeftRadius: 15,
borderBottomRightRadius: 15,
borderTopLeftRadius: 15,
borderTopRightRadius: 15,
},
modalText: {
fontSize: 24,
fontWeight: 'bold',
},
icon: {
marginLeft: 15,
},
});
|
import React from "react";
import styled from "styled-components";
import timeOrDateAgo from "../../../../utils/timeOrDateAgo";
const Container = styled.div`
display: flex;
`;
const Justify = styled.div`
${({ recieved }) => recieved && { flex: "1", minWidth: "20%" }};
`;
const MessageContainer = styled.div`
padding: 10px;
${({ recieved }) => !recieved && { maxWidth: "calc(80% - 40px)" }};
${({ recieved }) => recieved && { textAlign: "right" }};
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;
/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
`;
const AvatarContainer = styled.div`
margin: ${({ recieved }) => (recieved ? "10px 10px 0 0" : "10px 0 0 10px")};
`;
const Body = styled.div`
text-align: left;
display: inline-block;
padding: 5px;
border-radius: 10px;
background-color: ${({ recieved, theme }) =>
recieved ? theme.backgroundBlueMenu : theme.backgroundGreyMenu};
`;
const TimeStamp = styled.div`
display: flex;
font-style: italic;
padding: 0 20px;
color: ${({ theme }) => theme.primaryGrey};
`;
const Message = ({ message, recieved }) => {
//const formatedMessage = message.body.replace(/\n/g, "<br />");
const formatedMessage = message.body.split("\n");
return (
<Container>
<Justify recieved={recieved} />
{!recieved && <AvatarContainer recieved={recieved}></AvatarContainer>}
<MessageContainer recieved={recieved}>
<Body recieved={recieved}>
{formatedMessage.map((message) => {
return (
<>
{message}
<br />
</>
);
})}
</Body>
<TimeStamp>
{recieved && <div style={{ flex: 1 }} />}
{recieved ? "Recieved " : "Sent "}
{timeOrDateAgo(message.timeSent)}
</TimeStamp>
</MessageContainer>
{recieved && (
<AvatarContainer recieved={recieved}>
{/* <Avatar
size={28}
profileImage={from.profileImage}
userId={from._id}
username={from.username}
/> */}
</AvatarContainer>
)}
</Container>
);
};
export default Message;
|
function Server(messageChannel, voiceChannel) {
this.messageChannel = messageChannel;
this.voiceChannel = voiceChannel;
this.connection = null;
this.dispatcher = null;
this.playing = false;
this.timerId = null;
}
module.exports = {
Server: Server
}
|
import React from 'react';
import PropTypes from 'prop-types';
const ErrorContainer = ({ children, errorText, hasSubmitted, errorId }) => (
<div className={errorText && hasSubmitted ? 'error' : null}>
{children}
<div className="error-wrapper">
{errorText && hasSubmitted && <span id={errorId}>{errorText}</span>}
</div>
</div>
);
ErrorContainer.propTypes = {
children: PropTypes.node.isRequired,
errorText: PropTypes.string,
hasSubmitted: PropTypes.bool.isRequired,
errorId: PropTypes.string.isRequired
};
export default ErrorContainer;
|
/**
* Trackpad controller to move
*
* Schema :
*
* Name | Type | Description | Default
* ================================================================================================
* targetMove | string | Element to move | cameraRig
* speedMoveTrackpad | number | Speed | 10
* menuSelect | number | the number of option in menu to activate | -1
*
*/
AFRAME.registerComponent('trackpad-move', {
schema: {
targetMove: {type: 'string', default: 'cameraRig'},
speedMoveTrackpad: {type: 'number', default: 10},
menuSelect: {type: 'number', default: -1}
},
init: function () {
var el = this.el;
this.el.targetMove = document.getElementById(this.data.targetMove);
if (this.el.targetMove == null) {
console.error("ERROR [trackpad-move] : target is null");
return;
}
el.movecontrols = {movX: 0, movY: 0, movZ: 0};
el.movecontrols.enabled = false;
el.addEventListener('axismove', function (event) {
var axis1 = event.detail.axis[0];
var axis2 = event.detail.axis[1];
var rot = el.getAttribute("rotation");
el.movecontrols.movX = -Math.sin(rot.y / 180 * Math.PI) * axis2 / 10 * Math.cos(rot.x / 180 * Math.PI)
+ Math.cos(rot.y / 180 * Math.PI) * axis1 / 10 * Math.cos(rot.z / 180 * Math.PI);
el.movecontrols.movY = Math.sin(rot.x / 180 * Math.PI) * axis2 / 10
+ Math.sin(rot.z / 180 * Math.PI) * axis1 / 10;
el.movecontrols.movZ = -Math.cos(rot.y / 180 * Math.PI) * axis2 / 10 * Math.cos(rot.x / 180 * Math.PI)
- Math.sin(rot.y / 180 * Math.PI) * axis1 / 10 * Math.cos(rot.z / 180 * Math.PI);
});
},
tick: function (time, timeDelta) {
var menuSelect = this.data.menuSelect;
if (menuSelect == -1 || this.el.menu == undefined || this.el.menu.select == menuSelect) {
var target = this.el.targetMove;
var pos = target.getAttribute("position");
var speed = this.data.speedMoveTrackpad / 300;
target.setAttribute("position", {
x: pos.x + this.el.movecontrols.movX * timeDelta * speed,
y: pos.y + this.el.movecontrols.movY * timeDelta * speed,
z: pos.z + this.el.movecontrols.movZ * timeDelta * speed
});
}
}
});
|
import * as React from 'react';
import { useHistory } from 'react-router-dom'
import './styles/index.scss'
export const HomeIndex = (props) => {
let history = useHistory();
const onClickAddThing = () => {
history.push('/add')
}
return (
<div className='pg-home'>
<div className='bottom-btn'>
<div></div>
<div></div>
</div>
</div>
);
};
|
const {get} = require('lodash')
function compileMessage(precompiled, message) {
return precompiled.replace(/{{([a-zA-Z-_\.]+)}}/g, (match, index, original) => {
return get(message, index, index)
})
}
function chatResponder({response, message, client}) {
return client.sendText(message.from, compileMessage(response.body, message))
}
module.exports = {
'chat': chatResponder
}
|
document.addEventListener("DOMContentLoaded", function () {
//Showin and hiding form
var newTask = document.getElementById("task-new");
var taskForm = document.querySelector(".task-features")
newTask.addEventListener("click", function(event){
taskForm.classList.toggle("task-features-display");
});
//Priority - showing the stars
var priority = document.getElementById("priority");
var stars = document.querySelectorAll(".fa-star");
var starCount;
priority.addEventListener("change", function(){
var starNumber = priority.value;
if (starNumber < starCount){
stars[starCount-1].classList.remove("checked");
} else {
for (var i = 0; i < starNumber; i++) {
stars[i].classList.add("checked");
}
}
starCount = priority.value;
});
//Adding new element to the list
//Elements
var addTask = document.getElementById("task-add");
var taskList = document.getElementById("task-list");
var task = document.getElementById("task");
var date = document.getElementById("date");
var priority = document.getElementById("priority");
var description = document.getElementById("description");
//Checking if something is in ls
function checkLocalStorage() {
var tasks;
if(localStorage.getItem('tasks') === null){
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem('tasks'));
}
return tasks;
}
//Validation condition
function validation(value) {
if (value.length > 2 && value.length < 100) {
return true;
} else {
return false;
}
}
addTask.addEventListener("click", function(event){
//Validation
if (validation(task.value) === false) {
alert("Your task name has incorrect length. Please try again :)");
e.stopImmediatePropagation();
}
//New elements
var newLi = document.createElement("li");
var newTask = document.createElement("h3");
var newDate = document.createElement("span");
var newPriority = document.createElement("div");
var newDescription = document.createElement("p");
var newBtnDelete = document.createElement("a");
var newBtnComplete = document.createElement("a");
//Creating stars
for (var i = 0; i < priority.value; i++){
var newStar = document.createElement("span");
newStar.classList.add("fa");
newStar.classList.add("fa-star");
newStar.classList.add("checked");
newPriority.appendChild(newStar);
}
//Elements inside
newTask.innerText = task.value;
newDate.innerText = date.value;
newDescription.innerText = description.value;
newBtnDelete.innerHTML = '<i class="far fa-times-circle"></i>';
newBtnComplete.innerHTML = '<i class="far fa-check-circle"></i>';
//Elements classes
newDate.classList.add("till");
newBtnDelete.classList.add("task-delete");
newBtnComplete.classList.add("task-complete");
newLi.classList.add("collection-item");
newTask.classList.add("title");
newPriority.classList.add("priority");
newDescription.classList.add("remark");
//Adding elements to li
newLi.appendChild(newDate);
newLi.appendChild(newBtnDelete);
newLi.appendChild(newBtnComplete);
newLi.appendChild(newTask);
newLi.appendChild(newPriority);
newLi.appendChild(newDescription);
taskList.appendChild(newLi);
//Geting inpute valuse for local storage
var storageInfo = {title: task.value, date: date.value, priority: priority.value, description: description.value, isCompleted: false};
storeTaskInLocalStorage(storageInfo);
//Event for delete button
newBtnDelete.addEventListener("click", removeTask);
//Event for completed button
newBtnComplete.addEventListener("click", function () {
newLi.classList.toggle("completed");
changeCompletedInLocalStorage(this.parentElement);
});
//Hiding form after click
taskForm.classList.toggle("task-features-display");
//Cleaning the form
task.value = "";
date.value = "";
priority.value = "";
description.value = "";
});
//Puting data in ls
function storeTaskInLocalStorage(task) {
var tasks = checkLocalStorage();
tasks.push(task);
localStorage.setItem('tasks', JSON.stringify(tasks));
}
//Geting data form ls
function getTasks() {
var tasks = checkLocalStorage();
//Looping through ls keys
tasks.forEach(function(key){
//New elements
var newLi = document.createElement("li");
var newTask = document.createElement("h3");
var newDate = document.createElement("span");
var newPriority = document.createElement("div");
var newDescription = document.createElement("p");
var newBtnDelete = document.createElement("a");
var newBtnComplete = document.createElement("a");
//Creating the stars
for (var i = 0; i < key.priority; i++){
var newStar = document.createElement("span");
newStar.classList.add("fa");
newStar.classList.add("fa-star");
newStar.classList.add("checked");
newPriority.appendChild(newStar);
}
//Elements inside
newTask.innerText = key.title;
newDate.innerText = key.date;
newDescription.innerText = key.description;
newBtnDelete.innerHTML = '<i class="far fa-times-circle"></i>';
newBtnComplete.innerHTML = '<i class="far fa-check-circle"></i>';
//Elements classes
newLi.classList.add("collection-item");
if(key.isCompleted === true){
newLi.classList.add("completed");
}
newTask.classList.add("title");
newDate.classList.add("till");
newPriority.classList.add("priority");
newDescription.classList.add("remark");
newBtnDelete.classList.add("task-delete");
newBtnComplete.classList.add("task-complete");
//Adding elements to li
newLi.appendChild(newDate);
newLi.appendChild(newBtnDelete);
newLi.appendChild(newBtnComplete);
newLi.appendChild(newTask);
newLi.appendChild(newPriority);
newLi.appendChild(newDescription);
taskList.appendChild(newLi);
//Event for delete button
newBtnDelete.addEventListener("click", removeTask);
//Event for completed button
newBtnComplete.addEventListener("click", function () {
newLi.classList.toggle("completed");
changeCompletedInLocalStorage(newLi);
});
});
}
//Activating function to get data form ls
getTasks();
//Deleting tasks one by one
function removeTask(e) {
if(e.target.parentElement.classList.contains('task-delete')) {
e.target.parentElement.parentElement.remove();
// removing from ls
removeTaskFromLocalStorage(e.target.parentElement.parentElement);
}
}
//Function deleting tasks one by one from ls
function removeTaskFromLocalStorage(removedTask) {
var tasks = checkLocalStorage();
tasks.forEach(function(task, index){
if( task.title === removedTask.children[3].innerHTML && task.description === removedTask.children[5].innerHTML) {
tasks.splice(index, 1);
}
});
localStorage.setItem('tasks', JSON.stringify(tasks));
}
// Function checking if task is completed
function changeCompletedInLocalStorage(completedTask){
var tasks = checkLocalStorage();
tasks.forEach(function(task){
if(task.title === completedTask.children[3].innerHTML && task.description === completedTask.children[5].innerHTML){
if(task.isCompleted){
task.isCompleted = false;
}else{
task.isCompleted = true;
}
}
})
localStorage.setItem('tasks', JSON.stringify(tasks));
}
//Filtering tasks by title
filter.addEventListener("keyup", filterTasks);
function filterTasks(e) {
const text = e.target.value.toLowerCase();
document.querySelectorAll('.collection-item').forEach(function(task){
const item = task.querySelector(".title").textContent;
if(item.toLowerCase().indexOf(text) != -1){
task.style.display = 'block';
} else {
task.style.display = 'none';
}
});
}
//function cleaning everything from ls
function clearTasksFromLocalStorage() {
localStorage.removeItem('tasks');
}
//Deleting Everything!
var deleteTasks = document.getElementById("clear")
deleteTasks.addEventListener("click", function(event){
var allTasks = document.querySelectorAll(".collection-item");
clearTasksFromLocalStorage()
for (var i = 0; i < allTasks.length; i++) {
allTasks[i].parentElement.removeChild(allTasks[i]);
}
});
});
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
import pageEditorControlsTemplate from './pageEditorControls.html';
import angular from 'angular';
const pageToSummary = (input) => {
const result = {};
result.xid = input.xid;
result.name = input.name;
result.editPermission = input.editPermission;
result.readPermission = input.readPermission;
return result;
};
class PageEditorControlsController {
static get $$ngIsClass() { return true; }
static get $inject() { return ['$scope', 'maUiPages', 'MA_UI_PAGES_XID', 'maUiMenuEditor', '$state',
'localStorageService', '$mdDialog', '$mdToast', 'maTranslate', 'maUiMenu', '$window', 'maUser', '$q',
'$templateRequest', 'maDialogHelper', 'maRevisionHistoryDialog', 'maJsonStore', 'maUtil']; }
constructor($scope, maUiPages, MA_UI_PAGES_XID, maUiMenuEditor, $state,
localStorageService, $mdDialog, $mdToast, Translate, Menu, $window, User, $q,
$templateRequest, maDialogHelper, maRevisionHistoryDialog, maJsonStore, maUtil) {
this.$scope = $scope;
this.maUiPages = maUiPages;
this.MA_UI_PAGES_XID = MA_UI_PAGES_XID;
this.MenuEditor = maUiMenuEditor;
this.$state = $state;
this.localStorageService = localStorageService;
this.$mdDialog = $mdDialog;
this.$mdToast = $mdToast;
this.Translate = Translate;
this.Menu = Menu;
this.$window = $window;
this.User = User; // used in template
this.$q = $q;
this.$templateRequest = $templateRequest;
this.$window = $window;
this.maDialogHelper = maDialogHelper;
this.maRevisionHistoryDialog = maRevisionHistoryDialog;
this.maJsonStore = maJsonStore;
this.maUtil = maUtil;
}
$onInit() {
const Translate = this.Translate;
const $window = this.$window;
this.maJsonStore.notificationManager.subscribe({
scope: this.$scope,
xids: [this.MA_UI_PAGES_XID],
handler: (event, item) => {
this.pageSummaryStore.jsonData = item.jsonData;
this.filterPages();
}
});
this.$scope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams) => {
if (event.defaultPrevented) return;
if (this.pageEditorForm.$dirty || this.selectedPage.$dirty) {
if (!$window.confirm(Translate.trSync('ui.app.discardUnsavedChanges'))) {
event.preventDefault();
}
}
});
const oldUnload = $window.onbeforeunload;
$window.onbeforeunload = (event) => {
if (this.inputsDirty() || this.selectedPage.$dirty) {
const text = Translate.trSync('ui.app.discardUnsavedChanges');
event.returnValue = text;
return text;
}
};
const keyDownHandler = this.keyDownHandler.bind(this);
angular.element($window).on('keydown', keyDownHandler);
this.$scope.$on('$destroy', function() {
$window.onbeforeunload = oldUnload;
angular.element($window).off('keydown', keyDownHandler);
});
this.maUiPages.getPages().then(pageSummaryStore => {
this.pageSummaryStore = pageSummaryStore;
this.filterPages();
}, error => {
this.pageSummaryStore = null;
this.maDialogHelper.toastOptions({
textTr: ['ui.app.errorGettingPages', 'error.mangoStatusText'],
hideDelay: 10000,
classes: 'md-warn'
});
});
// Attempt load lastSelectedPage from local storage
const lastSelectedPage = this.localStorageService.get('lastSelectedPage');
if (this.$state.params.pageXid) {
this.loadPage(this.$state.params.pageXid);
} else if (this.$state.params.templateUrl) {
this.$templateRequest(this.$state.params.templateUrl).then(markup => {
this.createNewPage(markup);
});
} else if (this.$state.params.markup) {
this.createNewPage(this.$state.params.markup);
} else if (lastSelectedPage && lastSelectedPage.pageXid) {
this.loadPage(lastSelectedPage.pageXid);
} else {
this.createNewPage();
}
}
filterPages() {
const user = this.User.current;
this.pageList = this.pageSummaryStore.jsonData.pages.filter(p => {
return user.hasPermission(p.editPermission);
}).sort((a, b) => {
const aName = a.name.toLowerCase();
const bName = b.name.toLowerCase();
if (aName < bName) return -1;
if (aName > bName) return 1;
return 0;
});
}
searchPages(filter) {
const pages = this.pageList || [];
if (!filter) {
return pages;
}
const escaped = this.maUtil.escapeRegExp(filter);
return pages.filter(p => (new RegExp(escaped, 'gi')).test(p.name));
}
createNewPage(markup) {
const page = this.maUiPages.newPageContent();
if (!markup && this.newPageContents) {
markup = this.newPageContents();
}
page.jsonData.markup = markup || '';
this.menuItem = null;
return this.setSelectedPage(page);
}
inputsDirty() {
return this.pageEditorForm && this.pageEditorForm.$dirty;
}
pageChanged() {
this.confirmLoadPage(this.selectedPageSummary ? this.selectedPageSummary.xid : null);
}
newPageClicked(event) {
if (this.confirmLoadPage()) {
this.showDialog();
}
}
confirmLoadPage(xid) {
if (this.inputsDirty() || this.selectedPage.$dirty) {
if (!this.$window.confirm(this.Translate.trSync('ui.app.discardUnsavedChanges'))) {
this.selectedPageSummary = this.prevSelectedPageSummary;
return;
}
}
if (xid) {
this.loadPage(xid);
} else {
this.createNewPage();
}
return true;
}
loadPage(xid) {
const menuItemPromise = this.MenuEditor.getMenuItemForPageXid(xid).then(menuItem => {
return (this.menuItem = menuItem);
}, angular.noop);
const pagePromise = this.maUiPages.loadPage(xid).then(page => {
this.localStorageService.set('lastSelectedPage', {
pageXid: page.xid
});
return page;
});
return this.$q.all([menuItemPromise, pagePromise]).then(([menuItem, page]) => {
return this.setSelectedPage(page);
}, () => {
return this.createNewPage();
});
}
setSelectedPage(page, triggerChange) {
if (triggerChange == null) triggerChange = true;
this.selectedPage = page;
this.prevSelectedPageSummary = this.selectedPageSummary = page.isNew() ? null : pageToSummary(page);
this.updateViewLink();
// form might not have initialized
if (this.pageEditorForm) {
this.pageEditorForm.$setPristine();
this.pageEditorForm.$setUntouched();
}
if (triggerChange && this.onPageChanged) {
this.onPageChanged({$page: page});
}
return page;
}
updateViewLink() {
const xid = this.selectedPage.isNew() ? null : this.selectedPage.xid;
if (this.menuItem) {
this.viewPageLink = this.$state.href(this.menuItem.name);
} else {
this.viewPageLink = this.$state.href('ui.viewPage', {pageXid: xid});
}
this.$state.params.pageXid = xid;
this.$state.go('.', this.$state.params, { location: 'replace', notify: false });
}
editMenuItem(event) {
const defaults = {
menuText: this.selectedPage.name,
permission: this.selectedPage.readPermission
};
return this.MenuEditor.editMenuItemForPageXid(event, this.selectedPage.xid, defaults).then(menuItem => {
this.menuItem = menuItem;
this.updateViewLink();
});
}
confirmDeletePage(event) {
const Translate = this.Translate;
const confirm = this.$mdDialog.confirm()
.title(Translate.trSync('ui.app.areYouSure'))
.textContent(Translate.trSync('ui.app.confirmDeletePage'))
.ariaLabel(Translate.trSync('ui.app.areYouSure'))
.targetEvent(event)
.ok(Translate.trSync('common.ok'))
.cancel(Translate.trSync('common.cancel'));
return this.$mdDialog.show(confirm).then(() => {
this.deletePage(this);
});
}
deletePage() {
const pageXid = this.selectedPage.xid;
// consume errors, page might not exist in store for build in demo pages etc
const pageDeletedPromise = this.selectedPage.$delete().then(null, angular.noop);
let menuItemDeletedPromise;
if (this.menuItem) {
menuItemDeletedPromise = this.Menu.removeMenuItem(this.menuItem.name).then(null, angular.noop);
} else {
menuItemDeletedPromise = this.$q.when();
}
this.$q.all([pageDeletedPromise, menuItemDeletedPromise]).then(() => {
const pageSummaries = this.pageSummaryStore.jsonData.pages;
const pageIndex = pageSummaries.findIndex(ps => ps.xid === pageXid);
if (pageIndex >= 0) {
pageSummaries.splice(pageIndex, 1);
}
this.createNewPage();
return this.pageSummaryStore.$save().then(result => {
this.filterPages();
});
});
}
savePage(dialog) {
this.pageEditorForm.$setSubmitted();
if (this.pageEditorForm.$valid) {
return this.selectedPage.$save().then(page => {
this.localStorageService.set('lastSelectedPage', {
pageXid: page.xid
});
this.prevSelectedPageSummary = this.selectedPageSummary = pageToSummary(page);
this.updateViewLink();
this.pageEditorForm.$setPristine();
this.pageEditorForm.$setUntouched();
const pageSummaries = this.pageSummaryStore.jsonData.pages;
const existing = pageSummaries.find(ps => ps.xid === page.xid);
if (existing) {
angular.copy(this.selectedPageSummary, existing);
} else {
pageSummaries.push(this.selectedPageSummary);
}
return this.pageSummaryStore.$save();
}).then(result => {
this.filterPages();
const toast = this.$mdToast.simple()
.textContent(this.Translate.trSync('ui.app.pageSaved', [this.selectedPage.name]))
.action(this.Translate.trSync('common.ok'))
.actionKey('o')
.highlightAction(true)
.position('bottom center')
.hideDelay(5000);
this.$mdToast.show(toast);
if (dialog) {
dialog.hide();
}
}, error => {
const errorToast = this.$mdToast.simple()
.textContent(this.Translate.trSync('ui.app.errorSavingPage', [this.selectedPage.name, error.mangoStatusText]))
.action(this.Translate.trSync('common.ok'))
.actionKey('o')
.highlightAction(true)
.position('bottom center')
.toastClass('md-warn')
.hideDelay(10000);
this.$mdToast.show(errorToast);
});
} else {
this.showDialog();
}
}
showDialog() {
if (!this.showInputs) {
this.showInputs = {};
}
}
keyDownHandler(event) {
// ctrl-s
if ((event.ctrlKey || event.metaKey) && event.which === 83) {
event.preventDefault();
this.$scope.$applyAsync(() => {
this.savePage();
});
}
}
showRevisionDialog(event) {
this.maRevisionHistoryDialog.show(event, {
typeName: 'JSON_DATA',
objectId: this.selectedPage.id,
filterValues: val => val.context && !!val.context.jsonData
}).then(revision => {
this.selectedPage.jsonData = angular.fromJson(revision.context.jsonData);
this.selectedPage.$dirty = true;
if (this.onPageChanged) {
this.onPageChanged({$page: this.selectedPage});
}
}, angular.noop);
}
}
pageEditorControlsFactory.$inject = [];
function pageEditorControlsFactory() {
return {
restrict: 'E',
scope: {},
template: pageEditorControlsTemplate,
controller: PageEditorControlsController,
controllerAs: '$ctrl',
bindToController: {
onPageChanged: '&?',
newPageContents: '&?'
},
transclude: {
extraControls: '?extraControls'
}
};
}
export default pageEditorControlsFactory;
|
function header() {
var top = `<nav class="navbar navbar-light bg-light">
<a class="navbar-brand" href="backStage.html">
<img src="../images/logo2.png" width="130" alt="logo">後台
</a>
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
XXX您好
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">登出</a>
</div>
</nav>
<div class="container content">
<div class="row justify-content-center">
<div class="col-3">
<div class="list-group">
<a href="backStage.php" class="list-group-item list-group-item-action">
管理員帳號管理
</a>
<a href="backMember.php" class="list-group-item list-group-item-action">會員管理</a>
<a href="backItem.php" class="list-group-item list-group-item-action">商品管理</a>
<a href="backReport.php" class="list-group-item list-group-item-action">檢舉管理</a>
<a href="backAct.php" class="list-group-item list-group-item-action" tabindex="-1" aria-disabled="true">活動管理</a>
</div>
</div>
<div class="col-9">`;
document.write(top);
}
function buttom() {
var down = `</div></div></div>`;
document.write(down);
}
var title = document.getElementsByTagName(title).innerHTML;
if(title == 'manager'){
alert()
; $('.list-group .index').addClass('achive');
}
|
const textPanel = document.querySelector(".text");
const text = 'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Mollitia repellat deserunt consectetur dicta iste ut assumenda maxime illum aperiam debitis deleniti asperiores modi id, totam doloremque explicabo recusandae sit aliquam.'
const cursor = document.querySelector(".cursor");
let letterIndex = 0;
const letterTime = 400;
const cursorTime = 300;
const typing = () => {
textPanel.textContent += text[letterIndex];
letterIndex++
if (letterIndex === text.length) {
clearInterval(textInterval)
}
}
const textInterval = setInterval(typing, letterTime)
const cursorAnimation = () => {
cursor.classList.toggle("active")
}
setInterval(cursorAnimation, cursorTime)
|
function ProjectCategoryCtrl($scope, $http, $localStorage, $modal, $stateParams, SweetAlert, userPhotoService, Constants) {
$scope.projectId = $stateParams.id;
$scope.SelectedCategory = null;
$scope.budgetLoading = false;
$scope.Categories = [];
$scope.loadCategories = function () {
$scope.loading = true;
$http.get(Constants.WebApi.Project.GetCategories, { params: { projectId: $scope.projectId } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.length = 0;
$scope.Categories = response.data;
for (var i = 0; i < $scope.Categories.length; i++) {
if ($scope.Categories[i].IsIncome==true) {
$scope.length += 1;
}
};
$scope.loading = false;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.loading = false;
SweetAlert.swal({
title: "Error!",
text: "Load Category Failed!",
type: "warning"
});
});
}
$scope.onload = function () {
$scope.loadCategories();
}
$scope.addNewCategoryExpense = function()
{
var newCategory = {
ProjectId: $scope.projectId,
CategoryTitle: '',
CategoryDescription: null,
HighlightColor: null,
IsIncome: false,
IsClosed:false,
IsDelete: false,
Stage:1 // add new
}
$scope.Categories.push(newCategory);
}
$scope.addNewCategoryIncome = function () {
var newCategory = {
ProjectId: $scope.projectId,
CategoryTitle: '',
CategoryDescription: null,
HighlightColor: null,
IsClosed: false,
IsIncome: true,
IsDelete: false,
Stage: 1 // add new
}
$scope.Categories.push(newCategory);
$scope.length += 1;
}
$scope.selectCategory = function (CategoryDto) {
$scope.SelectedCategory = CategoryDto;
if(CategoryDto.Stage != 1)
{
CategoryDto.Stage = 2; // modified
}
}
$scope.saveCategory = function()
{
$scope.loading = true;
$http.post(Constants.WebApi.Project.SaveCategory, $scope.SelectedCategory).then(function (response) {
$scope.SelectedCategory.Id = response.data.Id;
$scope.loading = false;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.loading = false;
toastr.options.closeButton = true;
toastr.error('Network Error', 'Save category failed!')
});
}
$scope.partialSave = function()
{
$scope.saveCategory();
}
$scope.remove = function () {
}
$scope.closeCategory = function (category, isClosed) {
category.IsClosed = isClosed;
$http.post(Constants.WebApi.Project.CloseCategory, category).then(function (response) {
category.IsClosed = isClosed;
}, function (response) {
category.IsClosed = !isClosed;
toastr.options.closeButton = true;
toastr.error('Network Error', 'Save category failed!')
});
}
$scope.confirmDelete = function (category) {
SweetAlert.swal({ title: "Delete this category?", text: "You will not be able to recover this!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", closeOnConfirm: true },
function (isConfirm) {
if (isConfirm) {
$scope.deleteCategory(category);
}
});
}
$scope.deleteCategory = function (category) {
$http.post(Constants.WebApi.Project.DeleteCategory, category).then(function (response) {
var index = $scope.Categories.indexOf(category);
$scope.Categories.splice(index, 1);
$scope.SelectedCategory = null;
}, function (response) {
SweetAlert.swal({
title: "Error!",
text: "Delete category error!",
type: "warning"
});
});
}
$scope.setHighlightColor = function (category, color) {
if (category != null) {
category.HighlightColor = color;
$scope.partialSave();
}
}
$scope.createBudget = function(categoryId)
{
var modalInstance = $modal.open({
templateUrl: 'views/modals/CategoryBudget.html',
controller: CategoryBudgetCtrl,
resolve: {
categoryId: function () {
return categoryId;
}
}
});
modalInstance.result.then(function () {
//on ok button press
//$scope.loadRecentProjects();
}, function () {
//on cancel button press
});
}
$scope.Budgets = [];
$scope.loadBudgets = function (categoryId) {
$scope.budgetLoading = true;
$http.get(Constants.WebApi.Project.GetCategoryBudgets, { params: { categoryId: categoryId } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.Budgets = response.data;
$scope.budgetLoading = false;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.budgetLoading = false;
toastr.error('Network Error', 'Could not load budgets!')
});
}
$scope.confirmRemoveBudget = function(budgetId)
{
SweetAlert.swal({ title: "Delete this budget?", text: "You will not be able to recover this!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", closeOnConfirm: true },
function () {
var categoryId = $scope.SelectedCategory.Id;
$scope.removeBudget(budgetId, categoryId);
});
}
$scope.removeBudget = function(budgetId, categoryId)
{
var budgetDto = {
Id: budgetId,
CategoryId: categoryId
};
$http.post(Constants.WebApi.Project.DeleteBudget, budgetDto).then(function (response) {
$scope.Budgets = response.data;
}, function (response) {
SweetAlert.swal({
title: "Error!",
text: "Remove budget error!",
type: "warning"
});
});
}
$scope.$watch('SelectedCategory', function (newVal, oldVal) {
if ($scope.SelectedCategory != null && $scope.SelectedCategory.Id != null) {
var categoryId = $scope.SelectedCategory.Id;
$scope.loadBudgets(categoryId);
$scope.loadAuditLogs(categoryId);
$scope.loadUserComments(categoryId);
}
else {
$scope.Budgets = [];
}
}, false);
$scope.AuditLogs = [];
$scope.CommentText = '';
$scope.UserComments = [];
$scope.loadAuditLogs = function (categoryId) {
if (!(angular.isUndefined(categoryId) || categoryId === null)) {
$http.get(Constants.WebApi.AuditLog.GetProjectCategoryAuditLogs, { params: { CategoryId: categoryId } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.AuditLogs = response.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
toastr.options.closeButton = true;
toastr.error('Network Error', 'Could not load audit logs!')
});
}
}
$scope.loadUserComments = function (categoryId) {
if (!(angular.isUndefined(categoryId) || categoryId === null)) {
$http.get(Constants.WebApi.UserComment.GetProjectCategoryUserComments, { params: { CategoryId: categoryId } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.UserComments = response.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
toastr.options.closeButton = true;
toastr.error('Network Error', 'Could not user comments!')
});
}
}
$scope.addComment = function () {
var categoryId = $scope.SelectedCategory.Id;
if (categoryId != null) {
var comment = {
ObjectId: categoryId,
CommentText: $scope.CommentText
}
$http.post(Constants.WebApi.UserComment.CreateProjectCategoryUserComment, comment).then(function (response) {
// this callback will be called asynchronously
// when the response is available
var savedComment = response.data;
savedComment.User = {
Id: savedComment.UserId,
Photo: null
};
$scope.UserComments.push(savedComment);
$scope.CommentText = '';
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: "Add comment failed!",
type: "warning"
});
});
$scope.loadUserComments();
}
}
$scope.$watch('UserComments', function (newVal, oldVal) {
if (newVal != null) {
for (var i = 0; i < newVal.length; i++) {
var user = newVal[i].User;
if (user != null && user.Id != null && (user.Photo == null || user.Photo.length < 8)) {
var photoResult = userPhotoService.getUserPhoto(user);
photoResult.then(function (data) {
}, function (error) { });
}
}
}
}, true);
};
|
import Tiempo from "./tiempo.js";
import Nombre from "./nombre.js";
import Doctor from "./doctor.js";
import Fecha from "./fecha.js";
import Paciente from "./paciente.js";
import Cita from "./cita.js";
export default class Hospital{
/**
*
* @param {string} nombre Nombre del hospital
* @param {string} direccion Direccion del hospital
*/
constructor(nombre,direccion){
this.nombre=nombre;
this.direccion=direccion;
this.doctores=new Array();
this.citas= new Array();
}
registrarDoctores(doctor){
this.doctores.push(doctor);
}
registrarCitas(cita){
this.citas.push(cita);
}
listarCitas(){
this.citas.forEach((cita,i)=>{
console.log(`${i} ${cita.getPerfil()}`);
});
}
listarDoctores(){
this.doctores.forEach((doctores,a)=>{
console.log(`${a} ${doctores.getPerfil()}`);
});
}
}
|
var express = require('express');
var Devices = require('../app/models/devices');
var router = express.Router();
// push one notofication
router.post('/', function(req, res){
if(req.body.deviceToken.length == 73){
var deviceToken = req.body.deviceToken;
Devices.find({'token':deviceToken},function(err,deviceArray){
if (err) res.send(err);
if (deviceArray.length == 0) {
var newDevice = new Devices({
token: deviceToken
});
newDevice.save(function(err){
if(err) throw err;
res.json({
'message' : 'New device registered!'
});
});
}else{
res.json({
'message' : 'This device is already registered!'
});
}
});
}else{
res.json({
'message' : 'Invalid token!'
});
}
});
module.exports = router;
|
import React from 'react';
export default function NumberInput(props) {
const styles = {
borderRadius: '5px',
border: `2px solid ${ props.color }`,
background: 'white',
color: `${ props.color }`,
fontSize: '2rem',
lineHeight: 1,
textAlign: 'center',
width: '100%'
}
return (
<input
type='number'
placeholder='Enter up to 19 digits'
onChange={ (e) => props.onChange(e.target.value) }
value={ props.value }
style={ styles } />
)
}
|
"use strict";
function navFunc() {
document.querySelector(".navBtn").classList.toggle("is-active");
document.querySelector("html").classList.toggle("open");
}
|
// @flow
import React from 'react'
import { storiesOf } from '@kadira/storybook'
import Label from './'
storiesOf('Label', module)
.add('default', () => (
<Label>Default Label</Label>
))
.add('small', () => (
<Label className="is-small">Small Label</Label>
))
.add('large', () => (
<Label className="is-large">Large Label</Label>
))
|
/**
* Created by 周文静 on 2017/5/14.
*/
/**
* 页面最初先加载页面html结构,
* 再加载页面link引入的样式,这时候页面所有的结构与样式都有了,后续只要有了bootstrap就ok了。
* 页面先加载require.js,
* 然后再加载main.js,
* 如果是首页那么根据页面pathname加载了index.js,
* 然后index.js存在很多依赖,这些依赖项同时异步加载,他们的执行顺序是不确定的,
* 那么现在有一个aside模块,它依赖与jquery与jquery_cookie,所以需要在aside模块编写时进行配置
* */
define(['bootstrap', 'jquery', 'aside', 'header','util','nprogress','jquery_form'], function(ud, $, ud, ud,util,nprogress,ud) {
// 检测登陆状态
util.checkLoginStatus();
// 配置网站进度条
nprogress.start();
//window.onlod是页面所有的HTML,JS,CS加载完成后才执行
//所有的HTML页面加载完成后在执行
$(function(){
nprogress.done();
})
//配置ajax全局请求的loading效果
util.loading()
// 表单转ajax提交(增加讲师列表),成功后跳转到讲师列表页
$('.teacher-add form').ajaxForm(function() {
location.href = '/html/teacher/list.html';
});
});
|
import React from 'react';
import { NavLink, Link } from 'react-router-dom';
import { Button, Toolbar } from '@material-ui/core';
const Navigation = () => {
return (
<Toolbar>
<Button color="inherit">
<NavLink to="/">Home</NavLink>
</Button>
<Button component={({ ...props }) => <Link to="/path" {...props} />}>
Path
</Button>
<Button color="inherit" component={Link} to="/home">
Home
</Button>
<Button color="inherit" component={Link} to="/login">
Login
</Button>
<Button color="inherit" component={Link} to="/profile">
Profile
</Button>
<Button
label="Details"
containerElement={<Link to="/coder-details" />}
linkButton={true}
/>
<Button>
<Link to="/login">Login</Link>
</Button>
<Link to="/">
<Button color="inherit">Home</Button>
</Link>
<Button color="inherit">Button</Button>
<NavLink to="/login">Login</NavLink>
<NavLink to="/" />
</Toolbar>
);
};
export default Navigation;
|
// @ts-check
import { setStore, getStore, getActions, getEnv } from './globals';
import { createStore, asyncAction, mutator, orchestrator } from '@poa/satcheljs';
import { getRouter } from '@poa/router';
/**
* Used to initialize SatchelJS store, and save at as global
* @private
* @param {*} state
*/
export function createInitialStore(state) {
setStore(createStore('poaStore', state)());
return getStore();
}
/**
* Creates new action in systems
* @public
* @param {*} actionType
* @param {*} target
*/
export function createAction(actionType, target) {
return asyncAction(actionType, target);
}
/**
* Add mutation to action
* @public
* @param {*} actionCreator
* @param {*} target
*/
export function addMutator(actionCreator, target) {
return mutator(actionCreator, actionMessage => {
target(actionMessage, { store: getStore() });
});
}
/**
* Add side effects to action
* @public
* @param {*} actionCreator
* @param {*} target
*/
export function addSideEffects(actionCreator, target) {
return orchestrator(actionCreator, actionMessage => {
return target(actionMessage, {
actions: getActions(),
env: getEnv(),
store: getStore(),
router: getRouter()
});
});
}
|
// change checked
export const changeFunc = name => ({
type: 'CHANGE_CHECKED',
name
})
// change words
export const onWordsChange = val => ({
type: 'CHANGE_WORDS',
val
})
|
const test = require('japa')
const post = require('../stubs/post.json')
const Helpers = require('../../src/Helpers')
const PostClass = require('../stubs/Post')
test.group('Helpers', (group) => {
test('it should format correctly the resource name', (assert) => {
assert.equal(Helpers.formatResourceName(post), 'Post')
assert.equal(Helpers.formatResourceName(PostClass), 'Post')
assert.equal(Helpers.formatResourceName(new PostClass()), 'Post')
})
})
|
/* eslint-disable no-undef */
window.jQuery = window.$ = require("jquery");
require("popper.js");
require("bootstrap");
require("@fortawesome/fontawesome-free");
window.moment = require("moment");
require("tempusdominus-bootstrap-4");
require("../css/styles.less");
$(document).ready(function() {
"use strict";
$("i.pass__toggle--visibility").on("click", function() {
let field;
if ($(this).hasClass("fa-eye")) {
field = $(this).siblings("input[type=password]");
$(this).removeClass("fa-eye");
$(this).addClass("fa-eye-slash");
field.attr("type", "text");
$(this).attr("title", "Hide password");
} else if ($(this).hasClass("fa-eye-slash")) {
field = $(this).siblings("input[type=text]");
$(this).removeClass("fa-eye-slash");
$(this).addClass("fa-eye");
field.attr("type", "password");
$(this).attr("title", "Show password");
}
});
// inizialize datetimepicker constructor to use fontawesome 5 icons by default
try {
$.fn.datetimepicker.Constructor.Default = $.extend({},
$.fn.datetimepicker.Constructor.Default, {
icons: {
time: "fas fa-clock",
date: "fas fa-calendar",
up: "fas fa-arrow-up",
down: "fas fa-arrow-down",
previous: "fas fa-chevron-left",
next: "fas fa-chevron-right",
today: "fas fa-calendar-check-o",
clear: "far fa-trash",
close: "fas fa-times"
}
}
);
} catch (error) {
throw ("tempusdominus-bootstrap-4 datetimepicker is required", error);
}
});
/*!
* Start Bootstrap - SB Admin v6.0.1 (https://startbootstrap.com/templates/sb-admin)
* Copyright 2013-2020 Start Bootstrap
* Licensed under MIT (https://github.com/StartBootstrap/startbootstrap-sb-admin/blob/master/LICENSE)
*/
(function($) {
"use strict";
// Add active state to sidbar nav links
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$("#layoutSidenav_nav .sb-sidenav a.nav-link").each(function() {
if (this.href === path) {
$(this).addClass("active");
}
});
// Toggle the side navigation
$("#sidebarToggle").on("click", function(e) {
e.preventDefault();
$("body").toggleClass("sb-sidenav-toggled");
});
})(window.jQuery);
|
import React, {useState} from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
// Increment call
const handleIncrement = () => {
setCount(count + 1);
}
// Decrement call
const handleDecrement = () => {
setCount(count - 1);
}
console.log(count);
return (
<>
<div className = "counter-container">
<button className = "increment" onClick={() => handleIncrement()}> + </button>
<p>{count}</p>
<button className = "decrement" onClick={() => handleDecrement()}> - </button>
</div>
</>
)
}
|
import {createStore, applyMiddleware} from 'redux'
import {composeWithDevTools} from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'
import reducers from 'reducers'
export const initStore = () => {
return createStore(
reducers,
composeWithDevTools(applyMiddleware(thunkMiddleware))
)
}
|
/*global $:true, casper:true, document:true */
'use strict';
casper.test.comment('Pre-test setup');
casper.start('http://localhost:3001/', function () {
casper.test.info('Clearing out localStorage');
// Clear localStorage from any previous test runs.
this.evaluate(function() {
window.localStorage.clear();
});
this.test.assertEval(function() {
return window.localStorage.length === 0;
}, 'localStorage should be empty');
}).run(function () {
this.test.done();
});
|
import "./App.css";
import Navigation from "./components/Navigation/Navigation";
import NewsPageContainer from "./components/News/NewsPage/NewsPageContainer";
import TargetNewsContainer from "./components/News/NewsPage/TargetNewsContainer";
import CommentsContainer from "./components/News/NewsPage/CommentsContainer";
import { Route } from 'react-router-dom';
function App() {
return (
<div className="App">
<Navigation />
<Route exact path='/'
render={ () => <NewsPageContainer /> } />
<Route path='/:id'
render={ (props) =>
<>
<TargetNewsContainer props={props} />
<CommentsContainer props={props}/>
</>
}/>
</div>
);
}
export default App;
|
import React from 'react';
export default class Modal extends React.Component {
render() {
const msg = typeof this.props.winner === 'number'
? `The winner is Player ${this.props.winner + 1}!`
: 'Whoops, the game is a draw!';
return (
<div className="modal-wrapper">
<div className="modal-wrapper__content">
<article className="modal">
<div className="modal__inner">
<header>
<h1>Game Over!</h1>
</header>
<div>
<p>{ msg }</p>
</div>
<footer>
<button onClick={ this.props.onClick }>Play Again</button>
</footer>
</div>
</article>
</div>
</div>
);
}
}
|
//common variable values
var lineLength = 80;
//reusable functions
function getMonthName(monthIndex)
{
var monthNames = new Array();
monthNames[0] = "January";
monthNames[1] = "February";
monthNames[2] = "March";
monthNames[3] = "April";
monthNames[4] = "May";
monthNames[5] = "June";
monthNames[6] = "July";
monthNames[7] = "August";
monthNames[8] = "September";
monthNames[9] = "October";
monthNames[10] = "November";
monthNames[11] = "December";
return monthNames[monthIndex];
}
function genOption(optNum)
{
var htmlOptionTag =
"<option value='" + optNum + "'>Choice " + optNum + "</option>";
return htmlOptionTag;
}
function drawLine(length)
{
for (i=0; i<length; i++)
{
document.write("-");
}
document.write("<br />");
}
|
import {Kato} from "../..";
import {Misc} from "./api/misc";
export async function startServer() {
let kato = new Kato({outputRuntimeError: false});
kato.load(Misc);
await kato.listen(0);
kato.server.prefix = "";
return kato.server;
}
|
/* eslint-disable class-methods-use-this,no-param-reassign */
// @flow
import type {
TONCacheConfigurator,
TONStringEncryptor,
} from './TONCache';
import TONLog from './TONLog';
export type TONLimitedFetcherListener<Params> = {
open: (params: Params) => void,
close: () => void,
};
export type TONLimitedFetcherListenerOptions = {
onError?: (error: any) => void,
};
export type TONLimitedFetcherFetchOptions<Data> = {
postInterim: (data: Data) => void,
};
type Listener<Params, Data> = {
key: string,
params: ?Params,
onData: (data: Data) => void,
onError?: (error: any) => void,
};
type Queue<Params, Data> = {
key: string,
params: Params,
listeners: Listener<Params, Data>[],
}
const log = new TONLog('TONLimitedFetcher');
export default class TONLimitedFetcher<Params, Data> implements TONCacheConfigurator {
static log = log;
loadingLimit: number;
constructor() {
this.loadedData = new Map();
this.loadingQueues = new Map();
this.waitingQueues = [];
this.loadingLimit = 10;
}
// TONCacheConfigurator
// eslint-disable-next-line no-unused-vars
setEncryptor(encryptor: ?TONStringEncryptor): void {
this.reset();
}
// eslint-disable-next-line no-unused-vars
setScope(scope: ?string): void {
this.reset();
}
// Virtuals
keyOfParams(params: Params): string {
const paramsType = typeof params;
if (paramsType === 'string' || paramsType === 'number') {
return (params: any);
}
return JSON.stringify((params: any));
}
// eslint-disable-next-line no-unused-vars
async fetchData(params: Params, options: TONLimitedFetcherFetchOptions<Data>): Promise<any> {
return params;
}
// Public
reset() {
this.loadedData.clear();
this.loadingQueues.clear();
this.waitingQueues = [];
}
getCounters(): { loaded: number, loading: number, waiting: number } {
return {
loaded: this.loadedData.size,
loading: this.loadingQueues.size,
waiting: this.waitingQueues.length,
};
}
createListener(onData: (data: Data) => void, options?: TONLimitedFetcherListenerOptions): TONLimitedFetcherListener<Params> {
const listener = {
key: '',
params: (null: any),
onData,
onError: options?.onError,
};
return {
open: (params: Params) => {
this.openListener(listener, params);
},
close: () => {
this.closeListener(listener);
},
};
}
// Internals
loadedData: Map<string, Data>;
loadingQueues: Map<string, Queue<Params, Data>>;
waitingQueues: Queue<Params, Data>[];
openListener(listener: Listener<Params, Data>, params: Params) {
this.closeListener(listener);
listener.params = params;
listener.key = this.keyOfParams(params);
// If data is already loaded just provide it and return closed listener
const loadedData = this.loadedData.get(listener.key);
if (loadedData !== undefined) {
listener.onData(loadedData);
return;
}
let queue = this.loadingQueues.get(listener.key);
if (!queue) {
// If requested data does not loading place request to waiting queue
const waitingQueueIndex = this.waitingQueues.findIndex(x => x.key === listener.key);
if (waitingQueueIndex >= 0) {
// Temporary remove from waiting (then push back as most wanted)
[queue] = this.waitingQueues.splice(waitingQueueIndex, 1);
} else {
queue = {
key: listener.key,
params,
listeners: [],
};
}
// Push to back of waiting queue (most wanted)
this.waitingQueues.push(queue);
}
queue.listeners.push(listener);
this.checkWaiting();
}
closeListener(listener: Listener<Params, Data>) {
const loadingQueue = this.loadingQueues.get(listener.key);
if (loadingQueue) {
// If request in loading queue remove it from queue
const requestIndex = loadingQueue.listeners.indexOf(listener);
if (requestIndex >= 0) {
loadingQueue.listeners.splice(requestIndex, 1);
}
} else {
const waitingQueueIndex = this.waitingQueues.findIndex(x => x.key === listener.key);
if (waitingQueueIndex >= 0) {
// If request in waiting queue, remove it from queue
const waitingQueue = this.waitingQueues[waitingQueueIndex];
const requestIndex = waitingQueue.listeners.indexOf(listener);
if (requestIndex >= 0) {
if (waitingQueue.listeners.length > 1) {
waitingQueue.listeners.splice(requestIndex, 1);
} else {
// If waiting queue have emptied, remove queue itself
this.waitingQueues.splice(waitingQueueIndex, 1);
}
}
}
}
listener.key = '';
listener.params = null;
}
checkWaiting() {
while (this.waitingQueues.length > 0 && this.loadingQueues.size < this.loadingLimit) {
const queue = this.waitingQueues.pop();
this.loadingQueues.set(queue.key, queue);
this.fetchDataForQueue(queue);
}
}
fetchDataForQueue(queue: Queue<Params, Data>) {
(async () => {
try {
const finalData = await this.fetchData(
queue.params,
{
postInterim: (interimData: Data) => {
this.loadedData.set(queue.key, interimData);
TONLimitedFetcher.notifyListeners(queue, interimData, undefined);
},
},
);
this.loadingQueues.delete(queue.key);
this.loadedData.set(queue.key, finalData);
TONLimitedFetcher.notifyListeners(queue, finalData);
} catch (error) {
log.error(`fetchDataForQueue [${queue.key}'] fetch failed: `, error);
this.loadingQueues.delete(queue.key);
TONLimitedFetcher.notifyListeners(queue, undefined, error);
}
this.checkWaiting();
})();
}
static notifyListeners(queue: Queue<Params, Data>, data?: Data, error?: Error) {
try {
if (data !== undefined) {
queue.listeners.forEach(x => x.onData((data: any)));
}
if (error) {
queue.listeners.forEach((x) => {
if (x.onError) {
x.onError(error);
}
});
}
} catch (postError) {
log.error(`fetchDataForQueue [${queue.key}'] listeners failed: `, postError);
}
}
}
|
import React, { useEffect, useState, useContext, useReducer } from 'react';
import { View, Text, StyleSheet, ScrollView, TextInput, TouchableOpacity } from 'react-native';
import RNPickerSelect from 'react-native-picker-select';
import KeyContext from '../../KeyContext';
import { LightStyles, DarkStyles, Colors } from '../../constants/globalStyle';
import { BASE_URL } from '../../constants/API.js';
const fetch = require('node-fetch');
import LogEntry from './WaferUtils/LogEntry';
import GrowthDetails from '../Growths/GrowthDetails';
import Record from '../Maintenance/Find/Record';
import ViewPublication from '../Publications/View/ViewPublication';
const deletionGuide = {
Growth: {
name: "Growth",
fetchResponseKey: "results",
component: GrowthDetails,
},
MaintenanceRecord: {
name: "Maintenance Record",
fetchResponseKey: "records",
component: Record,
},
Publication: {
name: "Publication",
fetchResponseKey: "publications",
component: ViewPublication,
},
WaferLogEntry: {
name: "Wafer Log Entry",
fetchResponseKey: "entries",
component: LogEntry,
}
};
const DEFAULT_TARGET = {
type: "Growth",
id: null,
table: "SIGaAs",
machine: "Bravo",
}
export default function DeleteManager(props) {
const { dark, key } = useContext(KeyContext);
const [styles, updateStyles] = useReducer(() => StyleSheet.create({...(dark ? DarkStyles : LightStyles), ...LocalStyles}), {});
useEffect(updateStyles, [dark]);
const givenID = props.route.params && props.route.params.toDelete ? props.route.params.toDelete.id : null;
useEffect(() => {
setTarget(props.route.params && props.route.params.toDelete ? ({...DEFAULT_TARGET, ...props.route.params.toDelete}) : DEFAULT_TARGET);
}, [givenID]);
// Initialize deletion target based on whether we were navigated here by a delete button from elsewhere.
const [deletionTarget, setTarget] = useState(DEFAULT_TARGET);
// const [deletionTarget, setTarget] = useState(props.route.params && props.route.params.toDelete ? ({...DEFAULT_TARGET, ...props.route.params.toDelete}) : DEFAULT_TARGET);
const [previewData, setPreviewData] = useState(null);
const [waferTypes, setWaferTypes] = useState([]);
const [machines, setMachines] = useState([]);
function ExecuteDeletion(skip) {
let url = BASE_URL;
switch(deletionTarget.type) {
case "Growth":
if(skip) return url + `/machine/${deletionTarget.machine}/growths?id=${deletionTarget.id}`;
url += `/machine/${deletionTarget.machine}/${deletionTarget.id}`;
break;
case "MaintenanceRecord":
if(skip) return url + `/maintenance?RecordID=${deletionTarget.id}`;
url += `/maintenance/${deletionTarget.id}`;
break;
case "Publication":
if(skip) return url + `/publications?id=${deletionTarget.id}`;
url += `/publications/${deletionTarget.id}`;
break;
case "WaferLogEntry":
if(skip) return url + `/wafers/${deletionTarget.table}?id=${deletionTarget.id}`;
url += `/wafers/${deletionTarget.table}/id/${deletionTarget.id}`;
}
const f = async () => {
let { statusCode } = await fetch(url, {
method: "DELETE",
headers: {
"x-api-key": key,
"Content-Type": "application/json"
}
}).then(r => r.json());
if(statusCode == 200) {
window.alert("Successfully deleted item");
setTarget({...deletionTarget, id: null});
} else window.alert("A problem occurred during deletion");
}
f();
}
useEffect(() => {
const get = async () => {
const a = async () => {
let { substrates } = await fetch(`${BASE_URL}/settings/substrates`).then(r => r.json());
setWaferTypes(substrates.map(({ substrate }) => ({label: substrate, value: substrate})));
}
const b = async () => {
let { machines } = await fetch(`${BASE_URL}/settings/machines`).then(r => r.json());
setMachines(machines.map(machine => ({label: machine, value: machine})));
}
a();
b();
}
get();
}, []);
useEffect(() => {
setTarget({...deletionTarget, id: null});
}, [deletionTarget.type, deletionTarget.table, deletionTarget.machine]);
useEffect(() => {
if(deletionTarget.id) {
setPreviewData(null);
const url = ExecuteDeletion(true);
const f = async () => {
let response = await fetch(url, {
method: "GET",
headers: { "x-api-key": key }
}).then(r => r.json());
if(response.statusCode != 200) {
setPreviewData(null);
return;
};
const data = response[deletionGuide[deletionTarget.type].fetchResponseKey][0];
setPreviewData(data || null);
}
f();
}
}, [deletionTarget.id]);
function preview() {
const Comp = deletionGuide[deletionTarget.type].component;
let route = {params: {}};
switch(deletionTarget.type) {
case "Growth":
route.params.growth = previewData;
route.params.sampleID = previewData.id;
return (<Comp route={route} />);
case "MaintenanceRecord":
route.params.record = previewData;
return (<Comp route={route} navigation={{setOptions: () => true}}/>);
case "Publication":
route.params.publication = previewData;
return (<Comp route={route}/>);
case "WaferLogEntry":
return (<Comp data={previewData}/>);
}
}
return (
<View style={[styles.container, styles.componentBackground]}>
<ScrollView>
<View style={[styles.componentBackground,styles.section]}>
<Text style = {styles.lblColorized}>Delete an item from the database</Text>
<Text style = {styles.lblColorized}>Select the type of item you are attempting to remove, then enter its unique ID.</Text>
</View>
<View style={[styles.componentBackground,styles.section]}>
<View style={styles.formRow}>
<Text style={styles.lblFormLabel}>Item Type</Text>
<View style={styles.widthLimiter}>
<RNPickerSelect
onValueChange={type => setTarget({...deletionTarget, type})}
placeholder={{}}
value={deletionTarget.type}
items={Object.keys(deletionGuide).map(type => ({label: deletionGuide[type].name, value: type}))}
/>
</View>
</View>
</View>
{deletionTarget.type === "WaferLogEntry" ? (
<View style={[styles.componentBackground, styles.section]}>
<View style={styles.formRow}>
<Text style={styles.lblFormLabel}>Table Selection</Text>
<View style={styles.widthLimiter}>
<RNPickerSelect
onValueChange={table => setTarget({...deletionTarget, table})}
placeholder={{}}
items={waferTypes}
/>
</View>
</View>
</View>
) : deletionTarget.type === "Growth" ? (
<View style={[styles.componentBackground, styles.section]}>
<View style={styles.formRow}>
<Text style={styles.lblFormLabel}>Target Machine</Text>
<View style={styles.widthLimiter}>
<RNPickerSelect
onValueChange={machine => setTarget({...deletionTarget, machine})}
placeholder={{}}
items={machines}
/>
</View>
</View>
</View>
) : (<View />)}
<View style={[styles.componentBackground, styles.section]}>
<View style={styles.formRow}>
<Text style={styles.lblFormLabel}>Target ID</Text>
<View style={styles.widthLimiter}>
<TextInput
style={[styles.txt, styles.idInput]}
onChangeText={id => setTarget({...deletionTarget, id})}
value={deletionTarget.id ? `${deletionTarget.id}` : ""}
keyboardType="numeric"/>
</View>
</View>
</View>
<View style={styles.section}>
<TouchableOpacity
style={styles.btnDelete}
onPress={() => ExecuteDeletion()}
>
<Text style={{fontSize: 16, fontWeight: "bold"}}>Delete Item</Text>
</TouchableOpacity>
</View>
<View style={styles.preview}>
<View style={{alignItems: "center"}}>
<Text style={[styles.lblColorized, styles.titleText]}>Target Preview</Text>
</View>
{previewData && deletionTarget.id ? preview() : (
<View style={{alignItems: "center"}}>
<Text style = {styles.lblColorized}>Enter a valid deletion target to see a preview here.</Text>
</View>
)}
</View>
</ScrollView>
</View>
);
}
const LocalStyles = {
btnDelete: {
borderRadius: 5,
width: "100%",
maxWidth: 250,
margin: 5,
padding: 15,
backgroundColor: "#F33",
alignItems: "center",
},
widthLimiter: {
flex: 1,
maxWidth: 250,
},
idInput: {
margin: 5,
borderColor: "#CCC",
borderWidth: 2,
maxWidth: 250,
},
formLabel: {
marginRight: 10,
fontSize: 16,
},
formRow: {
flexDirection: "row",
paddingVertical: 5,
alignItems: "center",
},
titleText: {
fontSize: 20,
},
preview: {
margin: 5,
padding: 5,
borderColor: "#000",
borderTopWidth: 2,
},
section: {
margin: 5,
},
container: {
flex: 1,
backgroundColor: "#FFF",
}
}
|
import React from "react";
import VehicleCard from "./VehicleCard";
import { Grid, Row } from "react-bootstrap";
import SearchContainer from "../containers/SearchContainer";
import PaginationContainer from "../containers/PaginationContainer";
const getResourceID = url => {
let urlParts = url.split("/");
let id = urlParts[urlParts.length - 2];
return id;
};
const Vehicles = ({ vehicles, isFetching, page }) => {
const vehicleCards = vehicles.map((vehicle, index) =>
<VehicleCard
vehicle={vehicle}
key={index}
id={getResourceID(vehicle.url)}
/>
);
return (
<Grid>
<h1>Vehicles</h1>
<SearchContainer type="vehicles" />
<Row>
{isFetching ? <span className="img-loader" /> : vehicleCards}
</Row>
<PaginationContainer type="vehicles" page={page} />
</Grid>
);
};
export default Vehicles;
|
var Queue = function() {
var someInstance = {};
// Use an object with numeric keys to store values
var storage = {};
var highIndex = 0;
var lowIndex = 0;
// Implement the methods below
someInstance.enqueue = function(value) {
storage[highIndex] = value;
highIndex++;
return value;
};
someInstance.dequeue = function() {
if (someInstance.size()) {
var result = storage[lowIndex];
delete storage[lowIndex];
lowIndex++;
return result;
}
};
someInstance.size = function() {
return highIndex - lowIndex;
};
return someInstance;
};
// Performance Profile:
// 100k instansiations
// 120 ms
|
var JsonData = getModel()
var PriceStandardList;
var th_PriceStandard;
var th_ProjectCategory;
var DocumentReady = $.Deferred();
var stage = "C"
var QuoteList = [];
var _ClickSend = false
var JsonDataAsync = $.Deferred()
function ExportReport() {
window.location.href = "/PR/Report/" + $("#DocNum").text()
}
//權限判斷
function fun_stage() {
P_CustomFlowKey = $('#P_CustomFlowKey').val();
P_CurrentStep = $("#P_CurrentStep").val();
if (
(P_CustomFlowKey == "PR_P1_001" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P1_002" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P1_003" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "1")
) {
return "C"
}
if (
(P_CustomFlowKey == "PR_P1_001" && P_CurrentStep == "2")
|| (P_CustomFlowKey == "PR_P1_002" && P_CurrentStep == "2")
|| (P_CustomFlowKey == "PR_P1_002" && P_CurrentStep == "4")
|| (P_CustomFlowKey == "PR_P1_002" && P_CurrentStep == "5")
|| (P_CustomFlowKey == "PR_P1_003" && P_CurrentStep == "2")
|| (P_CustomFlowKey == "PR_P1_003" && P_CurrentStep == "4")
|| (P_CustomFlowKey == "PR_P1_003" && P_CurrentStep == "5")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "2")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "4")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "5")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "7")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "8")
) {
return "M"
}
if (
(P_CustomFlowKey == "PR_P2_001" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P2_002" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P2_003" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P2_004" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P2_005" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P2_006" && P_CurrentStep == "1")
|| (P_CustomFlowKey == "PR_P2_007" && P_CurrentStep == "1")
) {
return "B"
}
}
//關卡流程判斷
function fun_CustomFlowKey() {
P_CustomFlowKey = $('#P_CustomFlowKey').val();
P_CurrentStep = $("#P_CurrentStep").val();
YN = true//是否為總行人員
YN_0532 = false//是否為資訊處人員
$(_unitData).each(function (index, obj) {
if (obj.unit_level == 6) YN = false //6 為非總行人員
if (obj.unit_level == 4 && obj.unit_id == "0532") YN_0532 = true
})
if (P_CurrentStep == "1") {
switch (stage) {
case "C"://起單階段
let IsInformationProducts = JsonData.IsInformationProducts;
//資訊處只簽一遍,簽過就當非資訊產品處理
if (JsonData.isSigntoInformation == 1) {
IsInformationProducts = 0;
}
//申請人為資訊處人員不必加會資訊處、資訊處簽核過後不用在簽資訊處 *資訊處為總行人員
if ((IsInformationProducts == 0 || (IsInformationProducts == 1 && YN_0532)) && YN) {
$("#P_CustomFlowKey").val("PR_P1_001")
updateCustomFlowKey("PR_P1_001");
_stageInfo.CustomFlowKey = "PR_P1_001";
return false;
}
if ((IsInformationProducts == 1 && !YN_0532) && YN) {
$("#P_CustomFlowKey").val("PR_P1_002")
updateCustomFlowKey("PR_P1_002");
_stageInfo.CustomFlowKey = "PR_P1_002";
return false;
}
if (IsInformationProducts == 0 && !YN) {
$("#P_CustomFlowKey").val("PR_P1_003")
updateCustomFlowKey("PR_P1_003");
_stageInfo.CustomFlowKey = "PR_P1_003";
return false;
}
if (IsInformationProducts == 1 && !YN) {
$("#P_CustomFlowKey").val("PR_P1_004")
updateCustomFlowKey("PR_P1_004");
_stageInfo.CustomFlowKey = "PR_P1_004";
return false;
}
break;
case "B"://採購經辦階段
if (JsonData.QuoteAmount > 0) {
switch (JsonData.PurchasePriceStardandId) {
case "11":
$("#P_CustomFlowKey").val("PR_P2_001")
updateCustomFlowKey("PR_P2_001");
_stageInfo.CustomFlowKey = "PR_P2_001";
break;
case "12":
$("#P_CustomFlowKey").val("PR_P2_002")
updateCustomFlowKey("PR_P2_002");
_stageInfo.CustomFlowKey = "PR_P2_002";
break;
case "13":
$("#P_CustomFlowKey").val("PR_P2_003")
updateCustomFlowKey("PR_P2_003");
_stageInfo.CustomFlowKey = "PR_P2_003";
break;
case "14":
$("#P_CustomFlowKey").val("PR_P2_004")
updateCustomFlowKey("PR_P2_004");
_stageInfo.CustomFlowKey = "PR_P2_004";
break;
case "15":
$("#P_CustomFlowKey").val("PR_P2_005")
updateCustomFlowKey("PR_P2_005");
_stageInfo.CustomFlowKey = "PR_P2_005";
break;
case "16":
case "21":
case "31":
case "41":
$("#P_CustomFlowKey").val("PR_P2_006")
updateCustomFlowKey("PR_P2_006");
_stageInfo.CustomFlowKey = "PR_P2_006";
break;
case "17":
case "18"://董事會屬於線外作業
case "22":
case "23"://董事會屬於線外作業
case "32":
case "33"://董事會屬於線外作業
case "42"://董事會屬於線外作業
$("#P_CustomFlowKey").val("PR_P2_007")
updateCustomFlowKey("PR_P2_007");
_stageInfo.CustomFlowKey = "PR_P2_007";
break;
}
}
break;
}
}
}
//下一關人員調整
function GetPageCustomizedList(stepSequence) {
//改後端判斷
/* obj = $(_unitData).map(function () {
if (this.unit_level == 4) {
return { unit_id: this.unit_id, unit_name: this.unit_name };
}
})
console.log({ SignedID: obj[0].unit_id, SignedName: obj[0].unit_name })
return { SignedID: [obj[0].unit_id + "-JA08000609"], SignedName: [obj[0].unit_name + "總務股長"] }*/
P_CustomFlowKey = $('#P_CustomFlowKey').val();
P_CurrentStep = $("#P_CurrentStep").val();
rtn = GetFirstPurchaseEmpNum()
if (rtn.rtn) {
return { SignedID: [rtn.SignedID], SignedName: [rtn.SignedName] }
}
else {
if (parseInt(RoleMemberCount) > 0) {
return { SignedID: [SignedID], SignedName: [SignedName] }
}
else {
alert("查無人員")
}
}
}
function OverrideOrgPickerSetting(step) {
/// <summary>提供cbp-SendSetting.js針對「傳送其他主管同仁」按鈕做最後OrgPicker更改機會</summary>
/// <param name="step" type="number">目前關卡數</param>
// 第一關傳其他只能傳送採購經辦群組, 第二關傳其他只能傳送採購覆核群組:
P_CustomFlowKey = $('#P_CustomFlowKey').val();
if (P_CustomFlowKey.indexOf("PR_P1") > -1) {
switch (step) {
case 2:
case 5:
case 8:
return {
allowRole: ["MGR"],//主管階
LowestUnitLevel: 6
};
break;
}
}
if (P_CustomFlowKey.indexOf("PR_P2") > -1) {
switch (step) {
case 1:
return {
allowRole: ["JA18000078"]//採購經辦
};
break;
case 2:
return {
allowRole: ["JA18000226"]//採購覆核
};
break;
}
}
}
//取得第一個明細的採購經辦
function GetFirstPurchaseEmpNum() {
let SignedID = "";
let SignedName = "";
rtn = { rtn: false, SignedID: "", SignedName: "" }
//第一階段最後一關需抓第一個明細的採購經辦當下一關關主
if ((P_CustomFlowKey == "PR_P1_001" && P_CurrentStep == 2) ||
(P_CustomFlowKey == "PR_P1_002" && P_CurrentStep == 5) ||
(P_CustomFlowKey == "PR_P1_003" && P_CurrentStep == 5) ||
(P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == 8)) {
$("#YCDetailTable tbody").not("[alt=deleted]").find("[name=PurchaseEmpNum]").each(function (i, o) {
if (!isNullOrEmpty($(o).val())) {
SignedID = $(o).val();
SignedName = $(o).find("option:selected").text()
return false
}
})
if (isNullOrEmpty(SignedID)) {
$("#PROneTimeDetailTable tbody").not("[alt=deleted]").find("[name=PurchaseEmpNum]").each(function (i, o) {
if (!isNullOrEmpty($(o).val())) {
SignedID = $(o).val();
SignedName = $(o).find("option:selected").text()
return false
}
})
}
if ($('#sentdropbox').length > 0) {
$('#sentdropbox').empty()
$('#sentdropbox').append('<option value="' + SignedID + '" selected>' + SignedName + '(' + SignedID + ')</option>').selectpicker('refresh');
}
rtn.rtn = true
rtn.SignedID = SignedID
rtn.SignedName = SignedName
}
else {
rtn.rtn = false;
}
return rtn
}
//暫存
function draft() {
let draftAjax = $.Deferred()
blockPageForJBPMSend()
fun_JsonDataUpdate();
return $.ajax({
url: '/PR/Edit',
dataType: 'json',
type: 'POST',
data: JsonData,
//async: false,
success: function (data, textStatus, jqXHR) {
// window.location.href = '/PR/Edit/' + data;
_formInfo.formGuid = data.FormGuid
_formInfo.formNum = data.FormNum
_formInfo.flag = data.Flag
if (!data.Flag && data.Err != undefined) {
let ErrorMessage = "";
$.each(data.Err, function (i, Err) {
ErrorMessage += Err.ErrorMessage + "<br>"
})
$.unblockUI();
$("#AlertMessage").html(ErrorMessage);
window.location.href = "#modal-added-info-2"
draftAjax.reject;
}
else {
draftAjax.resolve();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$.unblockUI();
alert("暫存失敗 " + textStatus)
}
});
return draftAjax.promise()
}
//驗證
function Verify() {
$("[errmsg]").remove()
let draftAjax = $.Deferred()
setTimeout(function () {
fun_JsonDataUpdate();
let alertMsg = "";
let rtn = true
let isHaveQuote = true
if (JsonData.HaveQuoteForm == 1 && $("#fileSection").find("tr.fileDetail").length == 0) {
isHaveQuote = false;
fun_AddErrMesg($("tbody.fileList").closest("table"), null, "請上傳報價單")
}
if (fun_basicVerify($("#InformationSection")) && isHaveQuote) {
hasDetail = false
yErrArray = [];//協議的錯誤
pErrArray = [];//一次性的錯誤
BpcNumList = [];//協議金額陣列
if (JsonData.PurReqDetailList && JsonData.PurReqDetailList.length > 0) {
$.each(JsonData.PurReqDetailList, function (index, obj) {
if (obj.IsDelete != "true") {
YCD = false
if (obj.YCDetailID && obj.YCDetailID != 0) {
YCD = true
}
hasDetail = true
if (!obj.PurReqDeliveryList || obj.PurReqDeliveryList.length == 0) {
if (YCD) {
yErrArray.push("協議採購項次 " + obj.Index + " 未輸入送貨單位明細")
}
else {
pErrArray.push("一次性採購項次 " + obj.Index + " 未輸入送貨單位明細")
}
return true
}
else {
rtn = fun_DeliveryVerify(obj.PurReqDeliveryList, (obj.UomCode == "AMT"))
obj.Quantity = rtn.Quantity;
if (!rtn.result) {
if (YCD) {
yErrArray.push("協議採購項次 " + obj.Index + " " + rtn.ErrMsg)
}
else {
pErrArray.push("一次性採購項次 " + obj.Index + " " + rtn.ErrMsg)
}
}
else {
if (YCD) {//檢核是否超過核發金額
bpcObj = $.grep(BpcNumList, function (bobj) {
return bobj.BpcNum == obj.BpcNum
})
if (bpcObj.length == 0) {
tmp = { BpcNum: obj.BpcNum, QuoteAmount: (obj.QuoteAmount - obj.usedTwdQuoteAmount) }
BpcNumList.push(tmp)
bpcObj.push(tmp)
}
bpcObj[0].QuoteAmount -= (obj.UnitTwdPrice * obj.Quantity)
if (bpcObj[0].QuoteAmount < 0) {
yErrArray.push("協議採購項次 " + obj.Index + " 已超出剩餘可核發金額")
}
}
}
}
}
})
}
if (!hasDetail) {
alertMsg = "請至少輸入一筆採購資料";
}
$.each(yErrArray, function (index, yerr) {
alertMsg += yerr + "<br>";
})
if (alertMsg != "") { alertMsg += "<br>"; }
$.each(pErrArray, function (index, perr) {
alertMsg += perr + "<br>";
})
//20190318 新增 是否有報價單=”是” 且 是否為本行供應商=”否”時,卡控表單無法傳送
if (JsonData.HaveQuoteForm == 1 && JsonData.IsNewSupplier == 0) {
if (alertMsg != "") { alertMsg += "<br>"; }
alertMsg += "非本行供應商不得提供報價單,請先至供應商資料平台新增供應商";
}
if (alertMsg != "") {
rtn = false
$("#AlertMessage").html(alertMsg);
window.location.href = "#modal-added-info-2"
}
else {
if (stage == "B") {//採購經辦階段檢核
rtn = fun_QuoteVerify()
if (rtn && _clickButtonType != 8) {
if (isNaN(parseInt($("#QuoteAmount").val())) || parseInt($("#QuoteAmount").val()) <= 0) {
rtn = false;
$("#AlertMessage").html("請採購程序尚未填寫");
window.location.href = "#modal-added-info-2"
$('html, body').animate({
scrollTop: ($("#PriceStandardSection").offset().top) - 50
}, 500);
}
}
}
}
}
else {
rtn = false
if ($('[Errmsg=Y]').length > 0) {
$('html, body').animate({
scrollTop: ($('[Errmsg=Y]').first().closest("div .row").offset().top) - 50
}, 500);
}
}
if (rtn) {
$.ajax({
url: '/PR/ApiAmountMaxValueCheck',
dataType: 'json',
type: 'POST',
data: JsonData,
async: false,
success: function (data) {
if (data) {
let ErrorMessage = "";
$.each(data, function (i, Err) {
ErrorMessage += Err.ErrorMessage + "<br>"
})
$("#AlertMessage").html(ErrorMessage);
window.location.href = "#modal-added-info-2"
draftAjax.reject();
}
else {
draftAjax.resolve();
}
},
error: function (jqXHR, textStatus, errorThrown) {
draftAjax.reject();
alert("金額檢核發生異常 " + textStatus)
}
})
}
else {
draftAjax.reject()
}
}, 0)
return draftAjax.promise();
}
//基本驗證
function fun_basicVerify(target) {
rtn = true;
$(target).find("[Errmsg=Y]").remove();
$(target).find("[necessary]").each(function () {
if ($(this).parents("[alt=deleted]").length == 0) {
if ($(this).val() == null || String($(this).val()).trim().length < 1) {
fun_AddErrMesg($(this), null, "此為必填欄位")
rtn = false;
}
}
})
$(target).find("input[Amount]").each(function () {
if (!fun_onblurAction(this)) {
rtn = false;
}
})
return rtn
}
//送貨層驗證
function fun_DeliveryVerify(DeliveryList, isAMT) {
rtn = { result: true, Quantity: 0, ErrMsg: "" }
hasDelivery = false;
hasDeliveryErr = false;
Quantity = 0
$.each(DeliveryList, function (devindex, devObj) {
if (!devObj.IsDelete) {
hasDelivery = true
if (devObj.ChargeDept == "" || devObj.RcvDept == "" || devObj.Quantity <= 0) {
hasDeliveryErr = true;
}
else {
Quantity += devObj.Quantity;
if (!isAMT) {
if (devObj.Quantity != parseInt(devObj.Quantity)) {
hasDeliveryErr = true;
return false
}
}
else {
if (Quantity > 1) {
hasDeliveryErr = true;
return false
}
}
}
}
})
Err = "";
if (!hasDelivery) { Err = "未輸入送貨單位明細" }
if (hasDeliveryErr) { Err = "送貨單位明細有誤" }
if (isAMT && Quantity != 1) { Err = "單位為金額時數量需等於1" }
rtn.result = (Err == "");
rtn.Quantity = Quantity;
rtn.ErrMsg = Err;
return rtn
}
//報價驗證
function fun_QuoteVerify() {
rtn = true
if (_clickButtonType == 8) {//傳送其他主管,只需完成部份報價
$.each($("#QuoteInfoTable").find("tbody"), function (index, tbody) {
if ($(tbody).find("input[name=Confirmed]").length > 0 && !$(tbody).find("input[name=Confirmed]").prop("checked")) {
/* $('html, body').animate({
scrollTop: ($("#QuoteInfoTable").closest("div .row").offset().top) - 50
}, 500);*/
$("#AlertMessage").html("尚有報價商品未確認報價");
rtn = false
window.location.href = "#modal-added-info-2"
return false
}
})
}
else {//傳送下一關,需完成全部報價
$.each($("#PROneTimeDetailTable").find("tbody").not("[alt=deleted]"), function (index, tbody) {
if ($(tbody).find("input[name=Confirmed]").val() != "true") {
/* $('html, body').animate({
scrollTop: ($("#PROneTimeDetailTable").closest("div .row").offset().top) - 50
}, 500);*/
$("#AlertMessage").html("尚有一次性採購商品未確認報價");
rtn = false
window.location.href = "#modal-added-info-2"
return false
}
})
}
return rtn
}
//傳送
function Save() {
_formInfo.flag = false
fun_CustomFlowKey();
//送其他不會跑驗證,只好再組一次
fun_JsonDataUpdate();
//判斷的資訊處主管簽核流程
{
P_CustomFlowKey = $('#P_CustomFlowKey').val();
P_CurrentStep = $("#P_CurrentStep").val();
if ((P_CustomFlowKey == "PR_P1_002" && P_CurrentStep == "5")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "5")) {
if (_clickButtonType == 1 || _clickButtonType == 9) {//1 傳送 9 加會
JsonData.isSigntoInformation = 1;
}
}
}
let deferred = $.Deferred();
$.ajax({
url: '/PR/Save?clickButtonType=' + _clickButtonType,
dataType: 'json',
type: 'POST',
data: JsonData,
// async: false,
success: function (data) {
_formInfo.formGuid = data.FormGuid
_formInfo.formNum = data.FormNum
_formInfo.flag = data.Flag
$("#FormTypeName").val("一般請購單")
$("#ApplyItem").val("請購主旨-" + JsonData.Subject)
if (!data.Flag) {
let ErrorMessage = "";
if (data.Err != undefined) {
$.each(data.Err, function (i, Err) {
ErrorMessage += Err.ErrorMessage + "<br>"
})
}
else {
let ErrorMessage = "存檔發生錯誤";
}
$("#AlertMessage").html(ErrorMessage);
window.location.href = "#modal-added-info-2"
deferred.reject();
}
else {
$.when(CreditBudgetSave(data.FormGuid)).always(function (data) {
if (data.Status) {
deferred.resolve();
} else {
_formInfo.flag = false
$("#AlertMessage").html("信用卡處預算回寫失敗");
window.location.href = "#modal-added-info-2"
deferred.reject();
}
}
)
// deferred.resolve();
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("新增失敗 " + textStatus)
}
}).always(function () {
$("[Amount]").each(function () {
$(this).val(fun_accountingformatNumberdelzero($(this).val()))
$(this).text(fun_accountingformatNumberdelzero($(this).text()))
})
});
return deferred.promise();
}
$(function () {
stage = fun_stage()
// ----------------
$("#__CustomFlowKey").val($('#P_CustomFlowKey').val())
$("#__CurrentStep").val($("#P_CurrentStep").val())
// ----------------
//判斷的資訊處主管簽核流程
{
P_CustomFlowKey = $('#P_CustomFlowKey').val();
P_CurrentStep = $("#P_CurrentStep").val();
/* if ((P_CustomFlowKey == "PR_P1_002" && P_CurrentStep == "5")
|| (P_CustomFlowKey == "PR_P1_004" && P_CurrentStep == "5")) {
sendButtonAction()
}*/
}
DocumentReady.resolve();
fun_AjaxDataLoading()
$("#divEcryption").data("DateTimePicker").minDate(new Date().getFullYear() + "/" + (new Date().getMonth() + 1) + "/" + new Date().getDate());
//控件Acton綁定
{
$("input[Amount]").on("focus", function () {
fun_onfocusAction(this);
})
$("input[Amount]").on("blur", function () {
fun_onblurAction(this);
})
$("[name=IsEncryptionYN]").on("click", fun_IsEncryptionAction)
$("[name=HaveQuoteFormYN]").on("click", fun_HaveQuoteFormAction)
$("[name=IsNewSupplierYN]").on("click", fun_IsNewSupplierAction)
$("[name=isInstallmentYN]").on("click", fun_isInstallmentAction)
$("[name=HaveQuoteFormYN]").on("change", fun_PriceStandard)
$("[name=BudgetAmount]").on("blur", fun_PriceStandard)
$("[name=IsConsult]").on("change", fun_PriceStandard)
$("select[name=ProjectCategoryID]").on("change", fun_ProjectCategoryChange)
$("select[name=ProjectID]").on("change", fun_ProjectChange)
$("#AddNewYCDetail").on("click", function () {
fun_YCDetailCreate()
})
$("#PROneTimeDetailCreate").on("click", function () {
fun_PROneTimeDetailCreate()
})
$("#chkHaveContract").on("click", function () {
if ($(this).prop("checked")) {
QueryTempForCounterSignUnits([{ unit_name: "法律事務處", unit_id: "0028" }])
}
})
$("#chkIsOutSourcing").on("click", function () {
if ($(this).prop("checked")) {
QueryTempForCounterSignUnits([{ unit_name: "個人金融事業處", unit_id: "0055" }])
}
})
}
//塞資料進表單
if (JsonData) {
setTimeout(function () {
$.each(JsonData, function (key, value) {
DomObj = $("#InformationSection_Master").find("[name=" + key + "]")
if ($(DomObj).length > 0) {
switch ($(DomObj)[0].tagName) {
case "SELECT":
//選單連動也很機車 拉到後面處理
break;
case "TEXTAREA":
$(DomObj).val(value)
break;
case "INPUT":
switch ($(DomObj).attr("type")) {
case "checkbox":
if (value == 1) { $(DomObj).prop("checked", true) }
else { $(DomObj).prop("checked", false) }
break;
case "hidden":
if ($("#InformationSection_Master").find("[name=" + key + "YN]").length > 0) {
$(DomObj).val(value)
if (value == 1) { $("#InformationSection_Master").find("[name=" + key + "YN]").eq(0).prop("checked", true) }
else { $("#InformationSection_Master").find("[name=" + key + "YN]").eq(1).prop("checked", true) }
}
else {
$(DomObj).val(value)
}
break;
default:
$(DomObj).val(value)
break;
}
break;
}
}
//日期格式比較機車
if (key == "DecryptionDate") {
$("#InformationSection_Master").find("[name=DecryptionDate]").val(fun_DataToString(value))
}
})
if (JsonData.PurReqDetailList) {
$.each(JsonData.PurReqDetailList, function (index, obj) {
if (obj.YCDetailID != 0) {//協議
target = fun_YCDetailCreate()
$(target).find("[name=PRDetailID]").val(obj.PRDetailID)
//用YCDetailID回查品項
if (obj.YCDetailID > 0) {
$.ajax({
type: 'POST',
url: '/PR/GetYearlyContractDetailInfo/' + obj.YCDetailID,
async: false,
success: function (data) {
if (data) {
data.PurchaseEmpName = obj.PurchaseEmpName
data.PurchaseEmpNum = obj.PurchaseEmpNum
popPOitem_inputData(data, target)
}
}
});
target.find("td[name=Quantity]").text(fun_accountingformatNumberdelzero(obj.Quantity))
target.find("input[name=DeliveryPrompt]").val(obj.DeliveryPrompt)
$(target).data("DeliveryList", obj.PurReqDeliveryList)
$(target).find("span[name=totalTwdAmount]").eq(0).text(fun_accountingformatNumberdelzero(accounting.toFixed(obj.Price * obj.Quantity, 4)))
}
}
else {//一次性
fun_PROneTimeDetailCreate(obj)
}
})
}
fun_IsEncryptionAction()
fun_ProjectSet(JsonData.ProjectCategoryID, JsonData.ProjectID, JsonData.ProjectItemID)
//是否為新供應商預設是/否皆不勾選
if (JsonData.IsNewSupplier == null) {
$("[name=IsNewSupplierYN]").prop("checked", false)
}
else {
fun_IsNewSupplierAction()
}
//是否為新供應商預設是/否皆不勾選
if (JsonData.IsNewSupplier == null) {
$("[name=IsNewSupplierYN]").prop("checked", false)
}
else {
fun_IsNewSupplierAction()
}
//是否為分期付款預設是/否皆不勾選
if (JsonData.isInstallment == null) {
$("[name=isInstallmentYN]").prop("checked", false)
}
else {
fun_isInstallmentAction()
}
//是否有報價單預設是/否皆不勾選
if (JsonData.HaveQuoteForm == null) {
$("[name=HaveQuoteFormYN]").prop("checked", false)
}
else {
fun_HaveQuoteFormAction()
}
JsonDataAsync.resolve()
}, 0)
}
else {
JsonDataAsync.resolve()
}
$.when(JsonDataAsync.promise()).always(function () {
fun_PriceStandard()
$("input").on("focus", function () {
$(this).nextAll("[Errmsg=Y]").remove();
})
$("textarea").on("focus", function () {
$(this).nextAll("[Errmsg=Y]").remove();
})
$("select").on("change", function () {
$(this).nextAll("[Errmsg=Y]").remove();
})
stageControl(stage)
GetFirstPurchaseEmpNum()
})
})
//權限控制
{
function stageControl(stage) {
//C --起單人 *除報價單、請採購程序判定區外都可控 報價單需清空
//M --主管、經辦 *除報價單、請採購程序判定區與請購資訊區部分欄位外都可控 報價單需清空
//B --採購 *請購資訊區部分欄位外都可控
//R --唯讀
switch (stage) {
case "C":
fun_ControlDisable($("#QuoteInfoSection"), null)
fun_ControlDisable($("#PriceStandardSection"), null)
fun_ControlDisable($("#PROneTimeDetailCloneTemplate").find("[PRDConform]"), null)
fun_ControlDisable($("#PROneTimeDetailCloneTemplate").find("[ReQO]"), null)
break;
case "M":
fun_ControlDisable($("[name=Subject]"), JsonData.Subject)
fun_ControlDisable($("[name=Description]"), JsonData.Description)
fun_ControlDisable($("[name=IsEncryptionYN]"), null)
$("#spanCalendar").hide()
// fun_ControlDisable($("[name=isInstallmentYN]"), null)
fun_ControlDisable($("[name=DecryptionDate]"), fun_DataToString(JsonData.DecryptionDate))
fun_ControlDisable($("#PROneTimeDetailCloneTemplate").find("[ReQO]"), null)
fun_ControlDisable($("[name=IsInformationProducts]"), null)
fun_ControlDisable($("[name=HaveContract]"), null)
fun_ControlDisable($("[name=IsOutSourcing]"), null)
fun_ControlDisable($("#QuoteInfoSection"), null)
fun_ControlDisable($("#PriceStandardSection"), null)
fun_ControlDisable($("#PROneTimeDetailCloneTemplate").find("[PRDConform]"), null)
fun_ControlDisable($("#PROneTimeDetailCloneTemplate").find("[ReQO]"), null)
break;
case "B":
fun_ControlDisable($("[name=Subject]"), JsonData.Subject)
fun_ControlDisable($("[name=Description]"), JsonData.Description)
fun_ControlDisable($("[name=IsEncryptionYN]"), null)
$("#spanCalendar").hide()
// fun_ControlDisable($("[name=isInstallmentYN]"), null)
fun_ControlDisable($("[name=DecryptionDate]"), fun_DataToString(JsonData.DecryptionDate))
fun_ControlDisable($("[name=IsInformationProducts]"), null)
fun_ControlDisable($("[name=HaveContract]"), null)
fun_ControlDisable($("[name=IsOutSourcing]"), null)
// fun_ControlDisable($("[name=HaveQuoteFormYN]"), null)
// fun_ControlDisable($("[name=BudgetAmount]"), fun_accountingformatNumberdelzero(JsonData.BudgetAmount))
break;
case "R":
break;
}
}
function fun_ControlDisable(target, context) {
parentObj = $(target).parent();
intable = ($(target).parents("table").length > 0);
if ($(target).length == 0) {
return false
}
switch ($(target)[0].tagName) {
case "SELECT":
$(target).remove();
if (intable) {
$(parentObj).append(context)
}
else {
$(parentObj).append("<div class=\"disable-text\">" + context + "</div>")
}
break;
case "TEXTAREA":
$(target).remove();
if (intable) {
$(parentObj).append(context.replace(/\n/g, "<br/>"))
}
else {
$(parentObj).append("<div class=\"disable-text\">" + context.replace(/\n/g, "<br/>") + "</div>")
}
break;
case "INPUT":
switch ($(target).attr("type")) {
case "checkbox":
case "radio":
$(target).toggleClass("input-disable", true).prop("readonly", true).prop("disabled", true)
break;
default:
$(target).remove();
if (intable) {
$(parentObj).append(context)
}
else {
$(parentObj).append("<div class=\"disable-text\">" + context + "</div>")
}
break;
}
break;
case "TABLE":
$(target).remove()
break;
case "DIV":
$(target).remove()
break;
default:
$(target).toggleClass("input-disable", true).prop("readonly", true).prop("disabled", true)
break;
}
}
}
//控項的Action
{
//是否為密件
function fun_IsEncryptionAction() {
if ($("[name=IsEncryptionYN]").eq(0).prop("checked")) {
$("[name=IsEncryption]").val(1)
$("#textDecryptDate").toggleClass("input-disable", false).prop("readonly", false)
$("#spanCalendar").toggleClass("input-disable", false)
$("#EcryptionNote").show()
}
else {
$("[name=IsEncryption]").val(0)
$("#textDecryptDate").val("").toggleClass("input-disable", true).prop("readonly", true)
$("#spanCalendar").toggleClass("input-disable", true)
$("#EcryptionNote").hide()
}
}
// 是否有報價單
function fun_HaveQuoteFormAction() {
$("input[name=HaveQuoteForm]").nextAll("[Errmsg=Y]").remove();
if ($("[name=HaveQuoteFormYN]").eq(0).prop("checked")) {
$("[name=HaveQuoteForm]").val(1)
$("[name=BudgetAmount]").attr("necessary", "").attr("Amount", "")
$("#start_BudgetAmount").show()
$("#QuoteFormText").show()
}
else {
$("[name=HaveQuoteForm]").val(0)
$("[name=BudgetAmount]").removeAttr("necessary").attr("Amount", "Zero")
$("#start_BudgetAmount").hide()
$("#QuoteFormText").hide()
}
// $("[name=BudgetAmount]").trigger('focus');
// $("[name=BudgetAmount]").trigger('blur');
}
//新供應商判定 *改為是否為本行供應商
function fun_IsNewSupplierAction() {
$("input[name=IsNewSupplier]").nextAll("[Errmsg=Y]").remove();
if ($("[name=IsNewSupplierYN]").eq(0).prop("checked")) {
$("[name=IsNewSupplier]").val(1)
$("#mesIsNewSupplierY").show()
$("#mesIsNewSupplierN").hide()
}
else {
$("[name=IsNewSupplier]").val(0)
$("#mesIsNewSupplierN").show()
$("#mesIsNewSupplierY").hide()
}
}
//是否分期
function fun_isInstallmentAction() {
$("input[name=isInstallment]").nextAll("[Errmsg=Y]").remove();
if ($("[name=isInstallmentYN]").eq(0).prop("checked")) {
$("[name=isInstallment]").val(1)
}
else {
$("[name=isInstallment]").val(0)
}
}
function fun_ProjectCategoryChange() {
$("select[name=ProjectID]").empty();
$("select[name=ProjectID]").attr("selectedIndex", 0)
$("select[name=ProjectID]").selectpicker('setStyle', 'input-disable', 'add');
$("select[name=ProjectID]").prop('disabled', true);
$("select[name=ProjectID]").removeAttr("necessary")
$("select[name=ProjectID]").nextAll("[Errmsg=Y]").remove();
$("select[name=ProjectItemID]").empty();
$("select[name=ProjectItemID]").attr("selectedIndex", 0)
$("select[name=ProjectItemID]").selectpicker('setStyle', 'input-disable', 'add');
$("select[name=ProjectItemID]").prop('disabled', true);
$("select[name=ProjectItemID]").removeAttr("necessary")
$("select[name=ProjectItemID]").nextAll("[Errmsg=Y]").remove();
if ($("select[name=ProjectCategoryID]").val()) {
$("select[name=ProjectID]").attr("necessary", "")
$("select[name=ProjectItemID]").attr("necessary", "")
$("select[name=ProjectID]").selectpicker('setStyle', 'input-disable', 'remove');
$("select[name=ProjectID]").prop('disabled', false);
$.ajax({
url: "/Project/GetProjectDropMenu/",
type: "POST",
cache: false,
dataType: 'json',
async: false,
data: { projectCategoryCode: $("select[name=ProjectCategoryID]").val() },
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
$("select[name=ProjectID]").append($("<option></option>").attr("value", index).text(obj))
})
}
}
})
}
$("select[name=ProjectID]").selectpicker('refresh');
$("select[name=ProjectItemID]").selectpicker('refresh');
}
function fun_ProjectChange() {
$("select[name=ProjectItemID]").empty();
$("select[name=ProjectItemID]").attr("selectedIndex", 0)
$("select[name=ProjectItemID]").selectpicker('setStyle', 'input-disable', 'add');
$("select[name=ProjectItemID]").prop('disabled', true);
if ($("select[name=ProjectID]").val()) {
$("select[name=ProjectItemID]").selectpicker('setStyle', 'input-disable', 'remove');
$("select[name=ProjectItemID]").prop('disabled', false);
$.ajax({
url: "/Project/GetProjectItemDropMenu/",
type: "POST",
cache: false,
dataType: 'json',
async: false,
data: { ProjectID: $("select[name=ProjectID]").val() },
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
$("select[name=ProjectItemID]").append($("<option></option>").attr("value", index).text(obj))
})
}
}
})
$("select[name=ProjectItemID]").selectpicker('refresh');
}
}
}
//協議採購區Action
{
//產生表樣
function fun_YCDetailCreate() {
$("#nodata_YCDetail").hide();
$("#AddNewYCDetail").hide();
if ($("#YCDetailTable").length == 0) {
obj = $("#YCDetailTableTemplate").clone()
obj.attr("id", "YCDetailTable")
$(obj).find("a[toggleArrow]").on("click", function () {
fun_toggleAllCloumn($(this))
})
$(obj).find("a[addRow]").on("click", function () {
fun_YCDetailAddNewRow($(this).closest("table"))
})
$(obj).find("tbody").remove();
$("#div_YCDetail").append(obj)
}
else {
obj = $("#YCDetailTable");
}
$(obj).show()
return fun_YCDetailAddNewRow(obj)
}
//新增協議採購明細
function fun_YCDetailAddNewRow(target) {
tbody = $("#YCDetailTableTemplate").find("tbody").eq(0).clone();
$(tbody).find("a[toggleArrow]").on("click", function () {
fun_toggleCloumn($(this))
})
$(tbody).find("a[alt=linkpopPOitemList]").on("click", function () {
$("#inp_POitemListSearchBox").val("")
$("#popPOitemList").find("a[alt=btnSearch]").click()//預設展示全品項
$("#popPOitemList").data("target", $(this).closest("tbody"))//指定品名查詢的跳窗要回寫的物件
})
$(tbody).find("a[alt=showDetail]").addClass("input-disable")
$(tbody).find("a[alt=addDelivery]").on("click", function () {
if ($(this).closest("tbody").data("obj")) {
$(this).closest("tbody").find("input[name=UomCode]").val($(this).closest("tbody").data("obj").UomCode)
$("#popPROneTimeDetail").data("target", $(this).closest("tbody"))//指定新增明細跳窗要回寫的物件
$("#popPROneTimeDetail").trigger("reset", $(this).closest("tbody").find("input[name=ReadOnly]").val())//觸發重新繪製的動作
}
else {
alert("請先選擇採購品項")
return false
}
})
$(tbody).find("[removeBtn]").on("click", function () {
table = $(this).closest("table")
PRDetailID = parseInt($(this).closest("tbody").find("[name=PRDetailID]").val())
if (PRDetailID > 0) {
$(this).closest("tbody").attr("alt", "deleted")
$(this).closest("tbody").find("td[alt=Index]").attr("alt", "deleted")
$(this).closest("tbody").find("[name=IsDelete]").val(true)
$(this).closest("tbody").hide()
}
else {
$(this).closest("tbody").remove()
}
if ($(table).find("tbody").not("[alt=deleted]").length > 0) {
fun_resetCellIndex(table, "Index", 1)
}
else {
$("#nodata_YCDetail").show();
$("#AddNewYCDetail").show();
$(table).hide();
}
GetFirstPurchaseEmpNum()
})
$(tbody).on("mouseenter", function () {
$(this).find("[removeBtn]").show();
})
$(tbody).on("mouseleave", function () {
$(this).find("[removeBtn]").hide();
})
$(tbody).find("select[name=PurchaseEmpNum]").on("change", function () {
GetFirstPurchaseEmpNum()
})
$(tbody).find('.selectpicker').data('selectpicker', null);
$(tbody).find('.bootstrap-select').find("button:first").remove();
$(tbody).find(".selectpicker").selectpicker("render")
$(tbody).find('.selectpicker').selectpicker('setStyle', 'input-disable', 'add')
target.append(tbody)
fun_resetCellIndex(target, "Index", 1)
return tbody
}
}
//一次性採購區Action
{
var VendortargetRow = null
//產生表樣
function fun_PROneTimeDetailCreate(defalutInfo) {
$.when(th_POCategorySet, th_UomList, th_GreenCategory, th_PurchaseEmpListSet).always(function () {
$("#nodata_PROneTimeDetail").hide();
$("#PROneTimeDetailCreate").hide();
$("#CategoryExcelDL").show();
if ($("#PROneTimeDetailTable").length == 0) {
obj = $("#PROneTimeDetailTableTemplate").clone()
obj.attr("id", "PROneTimeDetailTable")
$(obj).find("a[toggleArrow]").on("click", function () {
fun_toggleAllCloumn($(this))
})
$(obj).find("a[addRow]").on("click", function () {
fun_PROneTimeAddNewRow($(this).closest("table"))
})
$(obj).find("tbody").remove();
$("#div_PROneTimeDetail").append(obj)
}
else {
obj = $("#PROneTimeDetailTable");
}
$(obj).show()
target = fun_PROneTimeAddNewRow(obj)
//有DB資料
if (defalutInfo && target) {
$(target).find("[name]").each(function () {
name = $(this).attr("name");
if (!defalutInfo[name]) return
value = defalutInfo[name]
if ($(this).is("[amount]")) {
value = fun_accountingformatNumberdelzero(value)
}
switch ($(this)[0].tagName) {
case "SELECT":
$(this).val(value).selectpicker('refresh');
break;
case "INPUT":
case "TEXTAREA":
$(this).val(value);
break;
default:
$(this).text(value).removeClass("undone-text");
break;
}
})
if (defalutInfo.InvoiceEmpName) {
$(target).find("[name=InvoiceEmptext]").text(defalutInfo.InvoiceEmpName + "(" + defalutInfo.InvoiceEmpNum + ")")
}
if (stage == "B") {
let hasQuote = false
$.ajax({
url: "/PR/QuoteDetailListGet/",
type: "POST",
cache: false,
dataType: 'json',
data: { PRDetailID: defalutInfo.PRDetailID },
async: false,
success: function (data) {
if (data.length > 0) {
hasQuote = true
}
}
})
//有報價單
if (hasQuote) {
$(tbody).find("input").prop("disabled", true).addClass("input-disable")
$(tbody).find("select").prop("disabled", true).selectpicker('setStyle', 'input-disable', 'add');
$(tbody).find("[removeBtn]").hide();
$(tbody).find("[PRDConform]").hide();
$(tbody).find("a[alt=Addperson]").hide();
$(tbody).off("mouseenter")
$(tbody).off("mouseleave")
$(tbody).on("mouseenter", function () {
$(this).find("[ReQO]").show();
})
$(tbody).on("mouseleave", function () {
$(this).find("[ReQO]").hide();
})
$(tbody).find("input[name=ReadOnly]").val(1)
//生成報價單
fun_QuoteRowAddNew(defalutInfo)
$(tbody).find("span[name=totalTwdAmount]").text(fun_accountingformatNumberdelzero(accounting.toFixed(defalutInfo.Price * defalutInfo.Quantity, 4)))
}
}
$(target).data("DeliveryList", defalutInfo.PurReqDeliveryList)
return target
}
}).fail(function () {
alert("FIIS資料異常")
})
}
//新增一次性採購明細
function fun_PROneTimeAddNewRow(target) {
tbody = $("#PROneTimeDetailTableTemplate").find("tbody").eq(0).clone();
$(tbody).removeAttr("id");
$(tbody).find("a[toggleArrow]").on("click", function () {
fun_toggleCloumn($(this))
})
$(tbody).find("a[alt=showDetail]").addClass("input-disable")
if ($("[name=isInstallment]").val() == 1) {
$(tbody).find("select[name=UomCode]").val("AMT").selectpicker("refresh")
}
$(tbody).find("a[alt=addDelivery]").on("click", function () {
$("#popPROneTimeDetail").data("target", $(this).closest("tbody"))//指定新增明細跳窗要回寫的物件
ReadOnly = $(this).closest("tbody").find("input[name=ReadOnly]").val()
$("#popPROneTimeDetail").trigger("reset", ReadOnly)//觸發重新繪製的動作
})
$(tbody).find("select[name=CategoryId]").on("change", function () {
defaultBuyerEmployeeNumber = $("#PROneTimeDetailCloneTemplate").find("option[value=" + $(this).val() + "]").data("defaultBuyerEmployeeNumber")
if (defaultBuyerEmployeeNumber) {
$(this).closest("tbody").find("select[name=PurchaseEmpNum]").nextAll("[Errmsg=Y]").remove();
if ($(this).closest("tbody").find("select[name=PurchaseEmpNum]").find("option[value='" + defaultBuyerEmployeeNumber + "']").length > 0) {
$(this).closest("tbody").find("select[name=PurchaseEmpNum]").val(defaultBuyerEmployeeNumber).selectpicker("refresh")
$(this).closest("tbody").find("select[name=PurchaseEmpNum]").change()
}
else {
alert("該採購分類無對應採購經辦人員,請聯繫管理處採購科,謝謝。")
}
}
})
$(tbody).find("select[name=PurchaseEmpNum]").on("change", function () {
/*if ($(this).closest("tbody").find("span[name=InvoiceEmptext]").text() == "") {
$(this).closest("tbody").find("span[name=InvoiceEmptext]").text($(this).find("option:selected").text() + "(" + $(this).val() + ")")
$(this).closest("tbody").find("input[name=InvoiceEmpNum]").val($(this).val())
$(this).closest("tbody").find("input[name=InvoiceEmpName]").val($(this).find("option:selected").text())
}*/
$(this).closest("tbody").find("span[name=InvoiceEmptext]").text($(this).find("option:selected").text() + "(" + $(this).val() + ")")
$(this).closest("tbody").find("input[name=InvoiceEmpNum]").val($(this).val())
$(this).closest("tbody").find("input[name=InvoiceEmpName]").val($(this).find("option:selected").text())
GetFirstPurchaseEmpNum()
})
$(tbody).find("a[alt=Addperson]").on("click", function () {
VendortargetRow = $(this).closest("tbody")
//限縮發票人員在總經理室 限縮該單位的MBR、OMG、MGR
orgpickUser({
RootUnitSeq: "0011", outputfunction: "QueryTempForVendor", allowRole: ["MBR", "OMG", "MGR"]
})
})
//重新報價
$(tbody).find("[ReQO]").on("click", function () {
tbody = $(this).closest("tbody")
let PRDetailID = parseInt($(tbody).find("input[name=PRDetailID]").val())
$.ajax({
url: "/PR/QuoteDetailListGet/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { PRDetailID: PRDetailID },
async: false,
success: function (data) {
if (data && data.length > 0) {
EmpNum = data[0].QuoteEmpNum
/* if (!confirm("重新報價會導致經辦 " + data[0].QuoteEmpName + "(" + EmpNum + ")所建立之所有報價單及相關資料被一併刪除。是否確認重新報價")) {
return false;
}*/
if (!confirm("請購調整會導致與該明細相關之所有報價單及資料被一併刪除。是否確認")) {
return false;
}
else {
$.ajax({
// url: "/PR/DelQuoteByCreateBy/", //存取Json的網址
url: "/PR/DelQuoteByPRDetail/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { PRDID: PRDetailID, FillinEmpNum: $("#LoginEno").val() },
async: false,
success: function (data) {
if (data.length > 0) {
$("#PROneTimeDetailTable").find("tbody").each(function () {
if (data.includes(parseInt($(this).find("input[name=PRDetailID]").val()))) {
$(this).find("input[name=CurrencyCode]").val("")
$(this).find("input[name=CurrencyName]").val("")
$(this).find("input[name=ExchangeRate]").val(0)
$(this).find("input[name=ForeignPrice]").val(0)
$(this).find("input[name=Price]").val(0)
$(this).find("input[name=Confirmed]").val(false)
$(this).find("input[name=QuoteEmpNum]").val("")
$(this).find("td[name=CurrencyName]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).find("td[name=ExchangeRate]").text("系統自動帶入").addClass("undone-text")
$(this).find("td[name=ForeignPrice]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).find("td[name=Price]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).find("span[name=totalTwdAmount]").html("<b class=\"undone-text\">系統自動帶入</b>")
}
})
$("#QuoteInfoTable").find("tbody").each(function () {
if (data.includes($(this).find("input[name=PRDetailID]").val()) && $(this).find("input[name=Confirmed]").prop("checked")) {
$(tbody).find("input[name=Confirmed]").prop("disabled", false).removeClass("input-disable").trigger("click")
}
})
}
},
error: function () {
alert("刪除報價發生錯誤")
return false;
}
})
}
}
$("#QuoteInfoTable").find("input[name=PRDetailID][value=" + PRDetailID + "]").closest("tbody").remove()
if ($("#QuoteInfoTable").find("tbody").length == 1) {
$("#QuoteInfoSection").hide()
}
else {
fun_resetCellIndex($("#QuoteInfoTable"), "Index", 1)
}
$(tbody).find("input[name=ReadOnly]").val(0)
$(tbody).find("input").prop("disabled", false).removeClass("input-disable")
$(tbody).find("select").prop("disabled", false).selectpicker('setStyle', 'input-disable', 'remove');
$(tbody).find("[removeBtn]").hide();
$(tbody).find("[PRDConform]").hide();
$(tbody).find("[ReQO]").hide();
$(tbody).find("a[alt=Addperson]").show();
(tbody).find("input:hidden").each(function () {
name = $(this).attr("name")
if (name == "CurrencyCode" ||
name == "CurrencyName" ||
name == "ExchangeRate" ||
name == "ForeignPrice" ||
name == "Price" ||
name == "Confirmed" ||
name == "QuoteEmpNum" ||
name == "QuoteEmpName" ||
name == "StakeHolder"
) {
$(this).val("")
return true
}
if (name == "ReadOnly") {
$(this).val(0)
return true
}
})
$(tbody).off("mouseenter")
$(tbody).off("mouseleave")
$(tbody).on("mouseenter", function () {
$(this).find("[removeBtn]").show();
$(this).find("[PRDConform]").show();
})
$(tbody).on("mouseleave", function () {
$(this).find("[removeBtn]").hide();
$(this).find("[PRDConform]").hide();
})
},
error: function () {
alert("查詢報價單失敗")
}
})
})
//移除請購項目
$(tbody).find("[removeBtn]").on("click", function () {
table = $(this).closest("table")
PRDetailID = parseInt($(this).closest("tbody").find("input[name=PRDetailID]").val())
if (PRDetailID > 0) {
$(this).closest("tbody").attr("alt", "deleted")
$(this).closest("tbody").find("td[alt=Index]").attr("alt", "deleted")
$(this).closest("tbody").find("[name=IsDelete]").val(true)
$(this).closest("tbody").hide()
}
else {
$(this).closest("tbody").remove()
}
if ($(table).find("tbody").not("[alt=deleted]").length > 0) {
fun_resetCellIndex(table, "Index", 1)
}
else {
$("#nodata_PROneTimeDetail").show();
$("#PROneTimeDetailCreate").show();
$("#CategoryExcelDL").hide();
$(table).hide();
}
GetFirstPurchaseEmpNum()
})
//確認請購項目
$(tbody).find("[PRDConform]").on("click", function () {
tbody = $(this).closest("tbody")
let rtn = fun_basicVerify(tbody)
if (!rtn) {
alert("請檢核輸入資料完整性")
return
}
if (!$(tbody).data("DeliveryList") || $(tbody).data("DeliveryList").length == 0) {
alert("請輸入送貨單位明細")
return
}
else {
rtn = fun_DeliveryVerify($(tbody).data("DeliveryList"), ($(tbody).find("select[name=UomCode]").val() == "AMT"))
if (!rtn.result) {
alert("送貨層資料有誤")
return
}
}
Detail = fun_PROneTimeDetailtoJson(tbody)
$.extend(Detail, { PRID: JsonData.FormID, CreateBy: $("#FillInEmpNum").val() })
result = false
//先存檔確認報價單可以取得正確的資料
$.ajax({
url: "/PR/ModifyPRD/", //存取Json的網址
type: "POST",
cache: false,
data: { PRD: Detail },
dataType: 'json',
async: false,
success: function (data) {
if (data && data.Detail) {
$.each(data.Detail, function (k, v) {
$(tbody).find("input[name=PRDetailID]").val(k)
$(tbody).data("DeliveryList", v)
})
result = true
}
else {
if (data.Err) {
alert(data.Err)
}
else {
alert("採購明細更新失敗")
}
}
},
error: function (err) {
alert("採購明細更新失敗")
}
})
if (!result) return false
json = fun_PROneTimeDetailtoJson(tbody)
fun_QuoteRowAddNew(json)
$(tbody).find("input").prop("disabled", true).addClass("input-disable")
$(tbody).find("select").prop("disabled", true).selectpicker('setStyle', 'input-disable', 'add');
$(tbody).find("[removeBtn]").hide();
$(tbody).find("[PRDConform]").hide();
$(tbody).find("a[alt=Addperson]").hide();
$(tbody).off("mouseenter")
$(tbody).off("mouseleave")
$(tbody).on("mouseenter", function () {
$(this).find("[ReQO]").show();
})
$(tbody).on("mouseleave", function () {
$(this).find("[ReQO]").hide();
})
$(tbody).find("input[name=ReadOnly]").val(1)
GetFirstPurchaseEmpNum()
})
$(tbody).on("mouseenter", function () {
$(this).find("[removeBtn]").show();
$(this).find("[PRDConform]").show();
})
$(tbody).on("mouseleave", function () {
$(this).find("[removeBtn]").hide();
$(this).find("[PRDConform]").hide();
})
$(tbody).find('.selectpicker').data('selectpicker', null);
$(tbody).find('.bootstrap-select').find("button:first").remove();
$(tbody).find(".selectpicker").selectpicker("render")
$(tbody).find("input").on("focus", function () {
$(this).nextAll("[Errmsg=Y]").remove();
})
$(tbody).find("select").on("change", function () {
$(this).nextAll("[Errmsg=Y]").remove();
})
target.append(tbody)
fun_resetCellIndex(target, "Index", 1)
return tbody
}
//人員選擇器ACTION
function QueryTempForVendor(datas) {
var context = "";
if (datas.length > 0) {
if (VendortargetRow) {
}
var context = datas[0].user_name.replace(/\d+/, "").replace(/\s+/, "") + "(" + datas[0].user_id + ")";
$(VendortargetRow).find("[name=InvoiceEmpNum]").val(datas[0].user_id)
$(VendortargetRow).find("[name=InvoiceEmpName]").val(datas[0].user_name)
$(VendortargetRow).find("[name=InvoiceEmptext]").text(datas[0].user_name + "(" + datas[0].user_id + ")")
}
}
}
//報價區Action
{
$(function () {
$("#linkCreatQOInfo").on("click", function () {
PRDList = $.map($("#QuoteInfoTable").find("tbody"), function (QoTbody) {
if ($(QoTbody).find("[name=QoItem]").prop("checked")) {
PRDObj = {
PRDetailID: $(QoTbody).find("[name=PRDetailID]").val(),
CategoryName: $(QoTbody).find("[tag=CategoryName]").text(),
ItemDescription: $(QoTbody).find("[tag=ItemDescription]").text(),
Quantity: $(QoTbody).find("[tag=Quantity]").text(),
UomName: $(QoTbody).find("[tag=UomName]").text()
}
return PRDObj
}
})
if (PRDList.length == 0) {
alert("請選擇報價品項")
}
else {
openVendor(true, null)
$("#AddVendor").data("PRDList", PRDList)
$("#AddVendor").find("a#VendorConfirm").one("click", function () {
VID = $('#VendorList input[name="VendorSelect"]:checked').val()
if (VID) {
$("#popQuote").data("PRDList", $("#AddVendor").data("PRDList")).data("VID", VID)
setTimeout(function () {
$("#popQuote").trigger("reset")
}, 0)
}
})
}
})
})
function fun_QuoteRowAddNew(PODetail) {
if ($("#QuoteInfoTable")) {
let tbody = $("#QuoteTemplate").find("tbody").eq(0).clone();
$(tbody).find("[tag]").each(function () {
tag = $(this).attr("tag")
$(this).text("")
if (PODetail[tag]) {
value = PODetail[tag]
if ($(this).is("[Amount]")) {
value = fun_accountingformatNumberdelzero(value)
}
if ($(this)[0].tagName == "INPUT") {
$(this).val(value)
}
else {
$(this).text(value)
}
}
})
$(tbody).find("[name=Confirmed]").on("click", function () {
tbody = $(this).closest("tbody")
PRDetailID = $(tbody).find("input[name=PRDetailID]").val()
if ($(this).prop("checked")) {
ForeignPrice = 0
Price = 0
ExchangeRate = 0
CurrencyCode = ""
CurrencyName = ""
QDetailID = 0
StakeHolder = 0
$.ajax({
url: "/PR/QuoteDetailListGet/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
data: { PRDetailID: PRDetailID },
async: false,
success: function (data) {
$.each(data, function (index, obj) {
if (obj.IsEnabled && obj.Price > Price) {
QDetailID = obj.QDetailID
ForeignPrice = obj.ForeignPrice
Price = obj.Price
ExchangeRate = obj.ExchangeRate
CurrencyCode = obj.CurrencyCode
CurrencyName = obj.CurrencyName
StakeHolder = obj.StakeHolder
}
})
},
error: function () {
alert("查詢報價單失敗")
}
})
if (Price > 0) {
$(tbody).find("[name=QoItem]").prop("checked", false).prop("disabled", true).addClass("input-disable")
$(tbody).find("[name=CurrencyName]").text(CurrencyName)
$(tbody).find("[name=ExchangeRate]").text(fun_accountingformatNumberdelzero(ExchangeRate))
$(tbody).find("[name=Price]").text(fun_accountingformatNumberdelzero(Price, 4))
$(tbody).find("span[name=QuoteEmpName]").text($("#FillInName").val())
$(tbody).find("span[name=QuoteEmpNum]").text($("#FillInEmpNum").val())
$(tbody).find("input[name=QuoteEmpNum]").val($("#FillInEmpNum").val())
$(tbody).find("input[name=StakeHolder]").val(StakeHolder)
$("#PROneTimeDetailTable").find("input[name=PRDetailID]").each(function () {
if ($(this).val() == PRDetailID) {
let DeliveryList = $(this).closest("tbody").data("DeliveryList")
let totalTwdAmount = 0;
$(DeliveryList).each(function (i, o) {
o.UnitPrice = Price
o.Amount = accounting.unformat(accounting.toFixed(Price * o.Quantity, 4))
totalTwdAmount = parseFloat(accounting.toFixed(totalTwdAmount + o.Amount, 4))
})
$(this).closest("tbody").find("td[name=CurrencyName]").text(CurrencyName)
$(this).closest("tbody").find("td[name=ExchangeRate]").text(fun_accountingformatNumberdelzero(ExchangeRate))
$(this).closest("tbody").find("td[name=ForeignPrice]").text(fun_accountingformatNumberdelzero(ForeignPrice))
$(this).closest("tbody").find("td[name=Price]").text(fun_accountingformatNumberdelzero(Price))
$(this).closest("tbody").find("span[name=totalTwdAmount]").text(fun_accountingformatNumberdelzero(totalTwdAmount))
$(this).closest("tbody").find("input[name=CurrencyCode]").val(CurrencyCode)
$(this).closest("tbody").find("input[name=CurrencyName]").val(CurrencyName)
$(this).closest("tbody").find("input[name=ExchangeRate]").val(ExchangeRate)
$(this).closest("tbody").find("input[name=ForeignPrice]").val(ForeignPrice)
$(this).closest("tbody").find("input[name=Price]").val(Price)
$(this).closest("tbody").find("input[name=Confirmed]").val(true)
$(this).closest("tbody").find("input[name=QuoteEmpName]").val($("#FillInName").val())
$(this).closest("tbody").find("input[name=QuoteEmpNum]").val($("#FillInEmpNum").val())
$(this).closest("tbody").find("input[name=StakeHolder]").val(StakeHolder)
return false
}
})
}
else {
alert("查無有效報價資料")
$(this).prop("checked", false)
}
}
else {
$(tbody).find("[name=QoItem]").prop("checked", false).prop("disabled", false).removeClass("input-disable")
$(tbody).find("[name=CurrencyName]").html("<b class=\"undone-text\">系統帶入</b>")
$(tbody).find("[name=ExchangeRate]").html("<b class=\"undone-text\">系統帶入</b>")
$(tbody).find("[name=Price]").html("<b class=\"undone-text\">系統帶入</b>")
$(tbody).find("[name=QuoteEmpName]").empty()
$(tbody).find("[name=QuoteEmpNum]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(tbody).find("input[name=QuoteEmpNum]").val("")
$("#PROneTimeDetailTable").find("input[name=PRDetailID]").each(function () {
if ($(this).val() == PRDetailID) {
$(this).closest("tbody").find("td[name=CurrencyName]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).closest("tbody").find("td[name=ExchangeRate]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).closest("tbody").find("td[name=ForeignPrice]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).closest("tbody").find("td[name=Price]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).closest("tbody").find("span[name=totalTwdAmount]").html("<b class=\"undone-text\">系統自動帶入</b>")
$(this).closest("tbody").find("input[name=CurrencyCode]").val("")
$(this).closest("tbody").find("input[name=CurrencyName]").val("")
$(this).closest("tbody").find("input[name=ExchangeRate]").val("")
$(this).closest("tbody").find("input[name=ForeignPrice]").val("")
$(this).closest("tbody").find("input[name=Price]").val("")
$(this).closest("tbody").find("input[name=Confirmed]").val(false)
$(this).closest("tbody").find("input[name=QuoteEmpName]").val("")
$(this).closest("tbody").find("input[name=QuoteEmpNum]").val("")
$(this).closest("tbody").find("input[name=StakeHolder]").val(0)
return false
}
})
}
})
$(tbody).find("[name=QuoDetail]").on("click", function () {
PRDetailID = $(this).closest("tbody").find("input[name=PRDetailID]").val()
Confirmed = $(this).closest("tbody").find("input[name=Confirmed]").prop("checked")
$("#QuotationInforemodal").trigger("reset", { PRDetailID: PRDetailID, Confirmed: Confirmed })
})
if (PODetail.Confirmed) {
//$(tbody).find("[name=Confirmed]").prop("checked", true).prop("disabled", true).addClass("input-disable")
$(tbody).find("[name=Confirmed]").prop("checked", true)
$(tbody).find("[name=CurrencyName]").text(PODetail.CurrencyName)
$(tbody).find("[name=ExchangeRate]").text(fun_accountingformatNumberdelzero(PODetail.ExchangeRate))
$(tbody).find("[name=Price]").text(fun_accountingformatNumberdelzero(PODetail.Price))
$(tbody).find("span[name=QuoteEmpName]").text(PODetail.QuoteEmpName)
$(tbody).find("span[name=QuoteEmpNum]").text(PODetail.QuoteEmpNum)
$(tbody).find("input[name=StakeHolder]").val(PODetail.StakeHolder)
$(tbody).find("[name=QoItem]").prop("checked", false).prop("disabled", true).addClass("input-disable")
}
$("#QuoteInfoTable").append(tbody)
fun_resetCellIndex($("#QuoteInfoTable"), "Index", 1)
$("#QuoteInfoSection").show()
}
}
function fun_QuoteRowDeltet(target) {
$(target).remove();
fun_resetCellIndex($("#QuoteInfoTable"), "Index", 1)
}
}
//請採購程序判定區Action
{
$(function () {
if (fun_stage() == "B" && JsonData.PurchasePriceStardandId != 0 && JsonData.PurchaseSigningLevelId != 0 &&
JsonData.PurReqDetailList != null && JsonData.PurReqDetailList.length > 0) {
$.when(JsonDataAsync.promise(), th_POCategorySet, th_UomList, th_GreenCategory, th_PurchaseEmpListSet).done(function () {
let AllConfirmed = true;
//會計經辦階段時如果載入時已經全部報價完成則自動展開請採購程序判定區
if ($.map(JsonData.PurReqDetailList, function (o) {
//抓出一次性未確認資料
if (!o.Confirmed && o.YCDetailID == 0) { return o.Confirmed }
}).length == 0) {
setTimeout(function () {
fun_PriceStandardShow(JsonData.QuoteAmount)
$("input[name=PurchasePriceStardandDescription]").val(JsonData.PurchasePriceStardandDescription)
$("select[name=PurchasePriceStardandId]").val(JsonData.PurchasePriceStardandId).selectpicker('refresh');
$("select[name=PurchaseSigningLevelId]").val(JsonData.PurchaseSigningLevelId).selectpicker('refresh');
$("#PurchaseSigningLevelId").change()
}, 100)
}
})
}
$("#CreatePriceStandard").on("click", function () {
totalAmount = fun_GetTotalAmount()
if (totalAmount <= 0) {
alert("請完成所有明細報價與確認")
return false;
}
else {
$("input[name=PurchasePriceStardandDescription]").removeAttr("necessary", "")
$("#satrMark_PurchasePriceStardandDescription").hide()
fun_PriceStandardShow(totalAmount)
}
})
$("#CancelPriceStandard").on("click", function () {
$("select[name=PurchaseSigningLevelId]").removeAttr("necessary", "")
$("select[name=PurchasePriceStardandId]").removeAttr("necessary", "")
$("input[name=PurchasePriceStardandDescription]").val("").removeAttr("necessary", "")
$("#ContractTotalAmount").text(0)
$("#QuoteAmount").val(0)
$("#chkIsConsult").removeClass("input-disable").removeAttr("readonly").prop("disabled", false)
$("#AddNewYCDetail").show();
$("#YCDetailTable").find("a[addRow]").show();
$("#YCDetailTable").find("a[alt=linkpopPOitemList]").show();
//$("#YCDetailTable").find("input[name=ReadOnly]").val(0);
$("#YCDetailTable").find("input[name=DeliveryPrompt]").addClass("input-disable").prop("disabled", true)
$("#YCDetailTable").find("tbody").on("mouseenter", function () {
$(this).find("[removeBtn]").show();
})
$("#YCDetailTable").find("tbody").on("mouseleave", function () {
$(this).find("[removeBtn]").hide();
})
$("#PROneTimeDetailCreate").show();
$("#PROneTimeDetailTable").find("a[addRow]").show();
//$("#PROneTimeDetailTable").find("input[name=ReadOnly]").val(0);
$("#PROneTimeDetailTable").find("tbody").on("mouseenter", function () {
$(this).find("[ReQO]").show();
})
$("#PROneTimeDetailTable").find("tbody").on("mouseleave", function () {
$(this).find("[ReQO]").hide();
})
$("#QuoteInfoTable").find("input:checkbox[name=Confirmed]").removeClass("input-disable").prop("disabled", false)
$("#linkCreatQOInfo").show()
$(this).hide()
$("#PriceStandardArea").hide()
$("#CreatePriceStandard").show()
})
$(document).on("change", "#PurchaseSigningLevelId", function () {
$("input[name=PurchasePriceStardandDescription]").next("[Errmsg=Y]").remove()
if ($("#PurchaseSigningLevelId option:selected").is("[default]")) {//預設選項
$("input[name=PurchasePriceStardandDescription]").removeAttr("necessary", "")
$("#satrMark_PurchasePriceStardandDescription").hide()
}
else {
$("input[name=PurchasePriceStardandDescription]").attr("necessary", "")
$("#satrMark_PurchasePriceStardandDescription").show()
}
})
$("[name=IsConsult]").on("change", function () {
$("select[name=PurchasePriceStardandId]").empty()
ContractTotalAmount = parseInt(accounting.unformat($("#ContractTotalAmount").text()))
$.each(PriceStandardList, function (index, option) {
if (($("[name=IsConsult]").prop("checked") && option.PriceKind == 2) || (!$("[name=IsConsult]").prop("checked") && option.PriceKind == 1)) {
Obj = $("<option></option>").val(option.ItemNo).text(option.ItemName).data("MaxAmount", option.MaxAmount).data("MinAmount", option.MinAmount)
if (option.MaxAmount > ContractTotalAmount) {
$("select[name=PurchasePriceStardandId]").append(Obj)
}
}
})
$("select[name=PurchasePriceStardandId] option").eq(0).attr("selected", "")
$("select[name=PurchasePriceStardandId]").selectpicker('refresh');
})
})
function fun_PriceStandardShow(totalAmount) {
$.when(th_PriceStandard).done(function () {
$("select[name=PurchaseSigningLevelId]").empty()
$("select[name=PurchasePriceStardandId]").empty()
$("#ContractTotalAmount").text(fun_accountingformatNumberdelzero(totalAmount))
$("#QuoteAmount").val(totalAmount)
if (PriceStandardList) {
PriceStandard = $.grep(PriceStandardList, function (obj) {
return (obj.MaxAmount >= totalAmount || obj.PriceKind == 0)
})
IsConsult = $(":checkbox[name=IsConsult]").prop("checked")
StakeHolder = false;
if ($("#QuoteInfoTable").find("input[name=StakeHolder][value=1]").length > 0) {
$("#haveStakeHolder").show()
StakeHolder = true
}
else {
$("#haveStakeHolder").hide()
}
SigningLevelId = "";
PriceKind = 1
if (!IsConsult && !StakeHolder) {
PriceKind = 1//沒顧問類沒利害關係
}
else if (IsConsult && !StakeHolder) {
PriceKind = 2//有顧問類沒利害關係
}
else if (IsConsult && StakeHolder) {
PriceKind = 3//有顧問類有利害關係
}
else {
PriceKind = 4//沒顧問類有利害關係
}
$.each(PriceStandard, function (index, option) {
if (option.PriceKind == 0) {
$("select[name=PurchaseSigningLevelId]").append($("<option></option>").val(option.ItemNo).text(option.ItemName).data("MaxAmount", option.MaxAmount).data("MinAmount", option.MinAmount))
if (totalAmount >= option.MinAmount && totalAmount <= option.MaxAmount) SigningLevelId = option.ItemNo
}
if ((option.PriceKind == PriceKind)) {
$("select[name=PurchasePriceStardandId]").append($("<option></option>").val(option.ItemNo).text(option.ItemName).data("MaxAmount", option.MaxAmount).data("MinAmount", option.MinAmount))
}
})
$("select[name=PurchaseSigningLevelId] option[value=" + SigningLevelId + "]").attr("selected", "selected").attr("default", "")
$("select[name=PurchasePriceStardandId] option").eq(0).attr("selected", "selected")
$("select[name=PurchaseSigningLevelId]").selectpicker('refresh');
$("select[name=PurchasePriceStardandId]").selectpicker('refresh');
}
$("select[name=PurchaseSigningLevelId]").attr("necessary", "")
$("select[name=PurchasePriceStardandId]").attr("necessary", "")
$("#chkIsConsult").addClass("input-disable").attr("readonly", "").prop("disabled", true)
$("#AddNewYCDetail").hide();
$("#YCDetailTable").find("a[addRow]").hide();
$("#YCDetailTable").find("a[alt=linkpopPOitemList]").hide();
$("#YCDetailTable").find("input[name=ReadOnly]").val(1);
$("#YCDetailTable").find("input[name=DeliveryPrompt]").addClass("input-disable").prop("disabled", true)
$("#YCDetailTable").find("tbody").off("mouseenter")
$("#YCDetailTable").find("tbody").off("mouseleave")
$("#PROneTimeDetailCreate").hide();
$("#PROneTimeDetailTable").find("a[addRow]").hide();
$("#PROneTimeDetailTable").find("input[name=ReadOnly]").val(1);
$("#PROneTimeDetailTable").find("input").addClass("input-disable").prop("disabled", true)
$("#PROneTimeDetailTable").find("select").selectpicker('setStyle', 'input-disable', 'add').prop("disabled", true);
$("#PROneTimeDetailTable").find("a[alt=Addperson]").hide();
$("#PROneTimeDetailTable").find("tbody").off("mouseenter")
$("#PROneTimeDetailTable").find("tbody").off("mouseleave")
$("#QuoteInfoTable").find("input:checkbox").addClass("input-disable").prop("disabled", true)
$("#linkCreatQOInfo").hide()
$("#CreatePriceStandard").hide()
$("#PriceStandardArea").show()
$("#CancelPriceStandard").show()
})
}
function fun_GetTotalAmount() {
totalAmount = 0;
if (fun_basicVerify($("#YCDetailTable").find("tbody")) &&
fun_basicVerify($("#PROneTimeDetailTable").find("tbody"))) {
$.each($("#YCDetailTable").find("tbody").not("[alt=deleted]"), function (index, tbody) {
Quantity = parseInt(accounting.unformat($(tbody).find("td[name=Quantity]").text()))
UnitTwdPrice = accounting.unformat($(tbody).find("span[tag=UnitTwdPrice]").text())
if (Quantity > 0 && UnitTwdPrice > 0) {
totalAmount += Quantity * UnitTwdPrice
}
else {
totalAmount = -1
return false;
}
})
if (totalAmount < 0) return false;
$.each($("#PROneTimeDetailTable").find("tbody").not("[alt=deleted]"), function (index, tbody) {
Quantity = parseInt(accounting.unformat($(tbody).find("td[name=Quantity]").text()))
UnitTwdPrice = accounting.unformat($(tbody).find("td[name=Price]").text())
if (Quantity > 0 && UnitTwdPrice > 0) {
totalAmount += Quantity * UnitTwdPrice
}
else {
totalAmount = -1
return false;
}
})
}
else {
totalAmount = -1
}
totalAmount = Math.round(totalAmount)
if (totalAmount <= 0) { totalAmount = -1; }
return totalAmount
}
}
//初始頁面 ajax載入資料
function fun_AjaxDataLoading() {
//抓取簽核層級對照表資料
th_PriceStandard = $.ajax({
url: "/PR/PriceStandardListGet/", //存取Json的網址
type: "POST",
cache: false,
dataType: 'json',
async: true,
success: function (data) {
PriceStandardList = data
}
})
//抓取專案類別資料
th_ProjectCategory = $.ajax({
url: "/Project/GetProjectCategoryDropMenu/",
cache: false,
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$("select[name=ProjectCategoryID]").append($("<option></option>").attr("value", "").text("請選擇"))
$.each(data, function (index, obj) {
$("select[name=ProjectCategoryID]").append($("<option></option>").attr("value", index).text(obj))
})
$("select[name=ProjectCategoryID]").selectpicker('refresh');
}
}
})
//抓取採購分類
th_POCategorySet = $.ajax({
url: "/PR/POCategorySet/",
type: "POST",
cache: false,
data: { PRnum: $("#DocNum").text() },
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
$("#PROneTimeDetailCloneTemplate").find("select[name=CategoryId]").append($("<option></option>").data("defaultBuyerEmployeeNumber", obj.defaultBuyerEmployeeNumber).attr("value", obj.categoryId).text(obj.category))
})
$("select[name=CategoryId]").selectpicker('refresh');
}
}
})
//抓取商品單位分類
th_UomList = $.ajax({
url: "/PR/GetUomList/",
type: "POST",
cache: false,
data: { PRnum: $("#DocNum").text() },
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$.each(data, function (key, value) {
$("#PROneTimeDetailCloneTemplate").find("select[name=UomCode]").append($("<option></option>").attr("value", key).text(value))
})
$("select[name=UomCode]").selectpicker('refresh');
}
}
})
//抓取綠色採購分類
th_GreenCategory = $.ajax({
url: "/PR/GetGreenCategory/",
type: "POST",
cache: false,
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$.each(data, function (index, obj) {
$("#PROneTimeDetailCloneTemplate").find("select[name=GreenCategory]").append($("<option></option>").attr("value", obj.greenProcureCategory).text(obj.description))
})
$("select[name=GreenCategory]").selectpicker('refresh');
}
}
})
//抓取採購經辦名單
th_PurchaseEmpListSet = $.ajax({
url: "/PR/PurchaseEmpListSet/",
type: "POST",
cache: false,
dataType: 'json',
async: true,
success: function (data) {
if (data) {
$.each(data, function (key, value) {
// $("#PROneTimeDetailCloneTemplate").find("select[name=PurchaseEmpNum]").append($("<option></option>").attr("data-subtext", key).attr("value", key).text(value))
$("select[name=PurchaseEmpNum]").append($("<option></option>").attr("data-subtext", key).attr("value", key).text(value))
})
$("select[name=PurchaseEmpNum]").selectpicker('refresh');
}
}
})
}
//設定專案
function fun_ProjectSet(ProjectCategoryID, ProjectID, ProjectItemID) {
$.when(th_ProjectCategory).done(function () {
$("select[name=ProjectCategoryID]").val(ProjectCategoryID).selectpicker('refresh');
fun_ProjectCategoryChange()
$("select[name=ProjectID]").val(ProjectID).selectpicker('refresh');
fun_ProjectChange()
$("select[name=ProjectItemID]").val(ProjectItemID).selectpicker('refresh');
})
}
//判斷預設簽核層級
function fun_PriceStandard() {
$("#divParity span").toggleClass("undone-text", true).text("系統自動帶入");
$("#divSignLv span").toggleClass("undone-text", true).text("系統自動帶入");
$("input[name=PriceStandardId]").val(-1)
$("input[name=SigningLevelId]").val(-1)
$.when(th_PriceStandard, DocumentReady).done(function () {
if (PriceStandardList) {
BudgetAmount = accounting.unformat($("input[name=BudgetAmount]").val())
if (BudgetAmount == 0) {
return false
}
IsConsult = $(":checkbox[name=IsConsult]").prop("checked")
Info = $.grep(PriceStandardList, function (obj) {
return (obj.MaxAmount >= BudgetAmount && obj.MinAmount <= BudgetAmount)
})
if (Info) {
$.each(Info, function () {
if (this.PriceKind == 0) {
$("#divParity span").toggleClass("undone-text", false).text(this.ItemName);
$("input[name=PriceStandardId]").val(this.ItemNo)
}
if ((IsConsult && this.PriceKind == 2) || (!IsConsult && this.PriceKind == 1)) {
$("#divSignLv span").toggleClass("undone-text", false).text(this.ItemName);
$("input[name=SigningLevelId]").val(this.ItemNo)
}
})
}
}
})
}
//將表單資料更新回JsonData
function fun_JsonDataUpdate() {
if (JsonData) {
JsonData.FillInEmpNum = $("#LoginEno").val()
$("input[Amount]").each(function () {
$(this).val(accounting.unformat($(this).val()))
})
$.each(JsonData, function (key, value) {
DomObj = $("#InformationSection_Master , #PriceStandardSection").find("[name=" + key + "]")
if ($(DomObj).length > 0) {
switch ($(DomObj)[0].tagName) {
case "SELECT":
case "TEXTAREA":
JsonData[key] = $(DomObj).val();
break;
case "INPUT":
switch ($(DomObj).attr("type")) {
case "checkbox":
if ($(DomObj).prop("checked")) {
JsonData[key] = 1
}
else {
JsonData[key] = 0;
}
break;
default:
JsonData[key] = $(DomObj).val();
break;
}
break;
case "DIV":
JsonData[key] = $(DomObj).text();
break;
}
}
})
PurReqDetailList = [];
$("#YCDetailTable tbody").each(function () {
Detail = { Index: "000", PRDetailID: 0, Quantity: 0, DeliveryPrompt: "", IsDelete: false, ForeignPrice: 0, Price: 0, PurReqDeliveryList: [] }
if ($(this).data("DeliveryList")) Detail.PurReqDeliveryList = $(this).data("DeliveryList");
Detail.PRDetailID = $(this).find("[name=PRDetailID]").val()
Detail.DeliveryPrompt = $(this).find("[name=DeliveryPrompt]").val()
Detail.Quantity = accounting.unformat($(this).find("[name=Quantity]").text())
Detail.Index = $(this).find("[alt=Index]").text()
Detail.IsDelete = $(this).find("[name=IsDelete]").val()
if ($(this).data("obj")) {
Detail.ForeignPrice = $(this).data("obj").UnitPrice
Detail.Price = $(this).data("obj").UnitTwdPrice
$.extend(Detail, $(this).data("obj"));
}
Detail.PurchaseEmpNum = $(this).find("select[name=PurchaseEmpNum]").val()
if (!isNullOrEmpty(Detail.PurchaseEmpNum)) {
//避免存到請選擇
Detail.PurchaseEmpName = $(this).find("select[name=PurchaseEmpNum]").find("option:selected").text()
}
if (!Detail.YCDetailID || Detail.YCDetailID <= 0) {
Detail.YCDetailID = -1 //避免未選品項就暫存時無法分辨是ㄧ次或協議
}
PurReqDetailList.push(Detail)
})
$("#PROneTimeDetailTable tbody").each(function () {
Detail = fun_PROneTimeDetailtoJson(this)
PurReqDetailList.push(Detail)
})
JsonData.PurReqDetailList = PurReqDetailList
JsonData.FillInEmpNum = $("#LoginEno").val();
JsonData.FillInName = $("#LoginName").val();
//只有起單會寫入
JsonData.ApplicantEmpNum = $("#ApplicantEmpNum").val();
JsonData.ApplicantName = $("#ApplicantName").val();
JsonData.ApplicantDepId = $("#ApplicantDepId").val();
JsonData.ApplicantDepName = $("#ApplicantDepName").val();
}
}
function fun_PROneTimeDetailtoJson(tbody) {
Detail = {
Index: $(tbody).find("[alt=Index]").text(),
PRDetailID: $(tbody).find("[name=PRDetailID]").val(),
CategoryId: $(tbody).find("[name=CategoryId]").val(),
CategoryName: $(tbody).find("[name=CategoryId]").find("option:selected").text(),
ItemDescription: $(tbody).find("[name=ItemDescription]").val(),
Quantity: accounting.unformat($(tbody).find("[name=Quantity]").text()),
UomCode: $(tbody).find("[name=UomCode]").val(),
UomName: $(tbody).find("[name=UomCode]").find("option:selected").text(),
PurchaseEmpNum: $(tbody).find("[name=PurchaseEmpNum]").val(),
PurchaseEmpName: $(tbody).find("[name=PurchaseEmpNum]").find("option:selected").text(),
InvoiceEmpNum: $(tbody).find("[name=InvoiceEmpNum]").val(),
InvoiceEmpName: $(tbody).find("[name=InvoiceEmpName]").val(),
GreenCategory: $(tbody).find("[name=GreenCategory]").val(),
DeliveryPrompt: $(tbody).find("[name=DeliveryPrompt]").val(),
IsDelete: $(tbody).find("[name=IsDelete]").val(),
CurrencyCode: $(tbody).find("input[name=CurrencyCode]").val(),
CurrencyName: $(tbody).find("input[name=CurrencyName]").val(),
ExchangeRate: $(tbody).find("input[name=ExchangeRate]").val(),
ForeignPrice: accounting.unformat($(tbody).find("input[name=ForeignPrice]").val()),
Price: accounting.unformat($(tbody).find("input[name=Price]").val()),
QuoteEmpNum: $(tbody).find("input[name=QuoteEmpNum]").val(),
QuoteEmpName: $(tbody).find("input[name=QuoteEmpName]").val(),
Confirmed: $(tbody).find("input[name=Confirmed]").val(),
StakeHolder: $(tbody).find("input[name=StakeHolder]").val(),
PurReqDeliveryList: []
}
if (isNullOrEmpty(Detail.UomCode)) { Detail.UomName = "" }
if (isNullOrEmpty(Detail.PurchaseEmpNum)) { Detail.PurchaseEmpName = "" }
if (isNullOrEmpty(Detail.CategoryId)) { Detail.CategoryName = "" }
if ($(tbody).data("DeliveryList")) Detail.PurReqDeliveryList = $(tbody).data("DeliveryList");
return Detail
}
//全部展開收合Action
function fun_toggleAllCloumn(target) {
if ($(target).children("div").hasClass("list-open-icon")) {
$(target).closest("thead").nextAll("tbody").not("[alt=no-data]").children("tr").not("[Rowtitle]").each(function () {
$(this).show(200);
})
$(target).closest("table").find("div[Arrow]").addClass("glyphicon-chevron-up").attr("title", "全部展開")
$(target).closest("table").find("div[Arrow]").removeClass("glyphicon-chevron-down")
$(target).children("div").addClass("list-close-icon")
$(target).children("div").removeClass("list-open-icon")
}
else {
$(target).closest("thead").nextAll("tbody").not("[alt=no-data]").children("tr").not("[Rowtitle]").each(function () {
$(this).hide(200);
})
$(target).closest("table").find("div[Arrow]").removeClass("glyphicon-chevron-up")
$(target).closest("table").find("div[Arrow]").addClass("glyphicon-chevron-down").attr("title", "全部收合")
$(target).children("div").removeClass("list-close-icon")
$(target).children("div").addClass("list-open-icon")
}
}
//單一列展開收合Action
function fun_toggleCloumn(target) {
$(target).closest("tbody").find("tr").not("[Rowtitle]").each(function () {
$(this).toggle(200);
})
$(target).children("div").toggleClass("glyphicon-chevron-down")
$(target).children("div").toggleClass("glyphicon-chevron-up")
}
//公用副程式
{
//日期格式轉中文 yyyy-MM-dd
function fun_DataToString(value) {
strDate = ""
if (value) {
DateObj = new Date(value)
if (!isNaN(DateObj.getDate())) {
strDate = DateObj.getFullYear() + "-" + funAddheadZero(2, (DateObj.getMonth() + 1)) + "-" + funAddheadZero(2, DateObj.getDate())
}
}
return strDate
}
//字串補0
function funAddheadZero(len, val) {
val = String(val);
while (val.length < len) {
val = "0" + val;
}
return val;
}
//金額欄位獲得焦點動作
function fun_onfocusAction(target) {
$(target).val(accounting.unformat($(target).val()));
if ($(target).val() == "0") $(target).val("");
$(target).nextAll("[Errmsg=Y]").remove();
SelectionRange(target, $(target).val().length, $(target).val().length)
}
//金額欄位失去焦點動作
function fun_onblurAction(target) {
Accuracy = parseInt($(target).attr("Accuracy"))
MaxValue = $(target).attr("MaxValue")
Amount = accounting.unformat($(target).val())
if (isNaN(Accuracy)) {
Accuracy = 0;
}
else {
if (Accuracy > 4) Accuracy = 4;//小數點最大四位
}
if (isNaN(MaxValue)) {
MaxValue = -1;
}
if (Amount == 0 && $(target).attr("Amount") != "Zero") {
fun_AddErrMesg(target, "ErrAmount", "請輸入大於0的數字")
return false;
}
if (regNum(Amount, (Accuracy > 0))) {
if (String(Amount).indexOf(".") > 0) {
if ((String(Amount).length - (String(Amount).indexOf(".") + 1)) > Accuracy) {
// fun_AddErrMesg(target, "ErrAmount", "小數點長度錯誤,最多" + Accuracy + "碼")
// return false;
Amount = parseFloat(String(Amount).substring(0, String(Amount).indexOf(".") + Accuracy + 1))//自動截斷
}
}
if (MaxValue > 0 && Amount > MaxValue) {
fun_AddErrMesg(target, "ErrAmount", "數字不可大於 " + MaxValue)
return false;
}
//資料庫只開8碼
/*if (Amount > 10000000) {
fun_AddErrMesg(target, "ErrAmount", "超出數字上限")
return false;
}*/
if (target.id == "textBudgetAmount" && Amount == 0) {
$(target).val("")//針對BudgetAmount 的特殊處理
}
else {
$(target).val(fun_accountingformatNumberdelzero(Amount))
}
return true;
}
else {
if (regNum(Amount, true)) {
Amount = parseInt(Amount)
$(target).val(fun_accountingformatNumberdelzero(Amount))
return true;
}
else {
fun_AddErrMesg(target, "ErrAmount", "數字輸入錯誤")
return false;
}
}
}
//控制光標位置 *目標,起始點,結束點
function SelectionRange(target, start, end) {
if (target.createTextRange) {//IE
var range = target.createTextRange();
range.collapse(true);//將指標移動至開頭或結尾 true(開頭)
range.moveEnd('character', end); //單位有character(字符)、word(單詞)、sentence(段落)
range.moveStart('character', start);
range.select();//選取
}
else if (target.setSelectionRange) {//Chrome IE 10以上
//IE 10支援setSelectionRange 但是不支援setcRange...
//target.setcRange(start, end);
}
}
//新增錯誤訊息
function fun_AddErrMesg(target, NewElementID, ErrMesg) {
if ($(target).nextAll("[alt=" + NewElementID + "]").length > 0) {
$(target).nextAll("[alt=" + NewElementID + "]").html("<span class=\"icon-error icon-error-size\"></span>" + ErrMesg);
}
else {
$(target).after('<div Errmsg="Y" style="text-align:left" alt="' + NewElementID + '" class="error-text"><span class="icon-error icon-error-size"></span>' + ErrMesg + '</div>')
}
}
//去除 accounting.format 的尾數0
function fun_accountingformatNumberdelzero(val) {
val = accounting.formatNumber(val, 4)
reg = /\.[0-9]*0$/
while (reg.test(val)) {
val = val.replace(/0$/, '');
}
val = val.replace(/\.$/, '');
return val;
}
//數字驗證 *正值
function regNum(target, hasfloat) {
if (hasfloat) {
reg = /^(([0-9]\.[0-9]*)|([1-9][0-9]*\.[0-9]*)|([0-9]\d*))$/
}
else {
reg = /^([0-9]\d*)$/
}
if (String(target).search(reg) == 0) {
return true;
}
else {
return false;
}
}
//重新排號
function fun_resetCellIndex(targetTable, alttag, len) {
i = 1;
$(targetTable).find("[alt='" + alttag + "']").each(function () {
index = String(i)
while (index.length < len) {
index = "0" + index;
}
$(this).text(index);
i++;
})
}
}
|
// For toggle button;
function toggleClass()
{
const body = document.querySelector('body');
body.classList.toggle('light');
body.style.transition = `0.3s linear`;
}
// for time;
const deg = 6;
// 360 / (12 * 5);
const hr = document.querySelector('#hr');
const mn = document.querySelector('#mn');
const sc = document.querySelector('#sc');
setInterval(() => {
let day = new Date();
let hh = day.getHours() * 30;
let mm = day.getMinutes() * deg;
let ss = day.getSeconds() * deg;
let msec = day.getMilliseconds();
// VERY IMPORTANT STEP:
hr.style.transform = `rotateZ(${(hh) + (mm / 12)}deg)`;
mn.style.transform = `rotateZ(${mm}deg)`;
sc.style.transform = `rotateZ(${ss}deg)`;
// gives the smooth transitioning effect, but there's a bug here!
// sc.style.transition = `1s`;
})
|
var example
example = (987654321);
console.log(example);
|
import React from 'react';
import {View, Text, ActivityIndicator} from 'react-native';
export default Loading = () => {
return (
<View style={loadingStyle}>
<ActivityIndicator size="large" color="#0000ff" />
<Text style={fontStyle}>Data is downloading, Please wait...</Text>
</View>
);
};
const loadingStyle = {
alignItems: 'center',
flex: 1,
marginTop: 50,
};
const fontStyle = {
fontSize: 10,
};
|
import app from '../server/server';
import authController from '../router/authRouter';
import usuarioRouter from '../router/usuarioRouter';
import proyectoRouter from '../router/proyectoRouter';
import tareaRouter from '../router/tareaRouter';
app.use('/api/auth', authController);
app.use('/api/usuario', usuarioRouter);
app.use('/api/proyecto', proyectoRouter);
app.use('/api/tarea', tareaRouter);
|
import React from 'react'
import PropTypes from 'prop-types'
import { gridded } from '../../../traits'
import { control } from '../../../macros'
import {
inputTypes,
Input,
SelectNative,
Textarea,
Label,
Message,
} from '../../atoms'
import { handleProps } from '../../utils'
import Select from '../select'
import ToggleGroup from '../toggle-group'
import * as Styled from './styles'
export const controlTypes = [
'select-native',
'select',
'multiselect-native',
'multiselect',
'textarea',
'checkbox',
'radio',
...inputTypes,
]
const FormControl = ({
type,
name,
id,
label,
placeholder,
required,
hasError,
errorMessage,
horizontal,
options,
...others
}) => {
const errorClass = hasError && 'error'
let WrapperTag = Styled.FormControl
let wrapperProps = {}
const inputProps = {}
if (horizontal) {
WrapperTag = Styled.FormControlHorizontal
wrapperProps = { columns: 2 }
}
let Tag
switch (type) {
case 'hidden':
inputProps.type = type
return (
<Input
type={type}
name={name}
id={id}
placeholder={placeholder}
required={required}
{...handleProps(inputProps, errorClass)}
/>
)
case 'select-native':
Tag = SelectNative
inputProps.options = options
break
case 'multiselect-native':
Tag = SelectNative
wrapperProps.multiLine = true
inputProps.multiple = true
inputProps.options = options
break
case 'select':
Tag = Select
inputProps.options = options
break
case 'multiselect':
Tag = Select
wrapperProps.multiLine = true
inputProps.multiple = true
inputProps.options = options
break
case 'textarea':
Tag = Textarea
wrapperProps.multiLine = true
break
case 'checkbox':
case 'radio':
Tag = ToggleGroup
inputProps.options = options
if (horizontal) {
wrapperProps.multiLine = true
}
break
default:
Tag = Input
inputProps.type = type
}
return (
<WrapperTag {...wrapperProps} {...handleProps(others, 'form-control')}>
{label && (
<Label htmlFor={id} required={required} className={errorClass}>
{label}
</Label>
)}
<Tag
type={type}
name={name}
id={id}
placeholder={placeholder}
required={required}
{...handleProps(inputProps, errorClass)}
/>
{errorMessage && (
<Message htmlFor={id} variant="danger">
{errorMessage}
</Message>
)}
</WrapperTag>
)
}
FormControl.propTypes = {
...gridded.propTypes(),
...control.propTypes(),
horizontal: PropTypes.bool,
}
FormControl.defaultProps = {
...gridded.defaultProps(true),
...control.defaultProps(),
horizontal: false,
fluid: true,
gap: 'xSmall',
}
export default FormControl
|
const promise = new Promise((resolve,reject) => {
setTimeout(()=>{
console.log("got the user");
reject(new Error ("User got fked up!!"));
},2000);
});
promise.then(user => {
console.log(user);
})
.catch(err=>console.log(err)); // if we use err.message in the console.log we will get the message,will be logged in the form of object
|
import Head from 'next/head'
import Image from 'next/image'
export default function Home() {
return (
<div>
<p className={'bg-green-500 text-white'}>
Hello Next!
</p>
</div>
)
}
|
import {useEffect, useState} from "react";
import styled from "styled-components";
import ComponentRender from "~/components/pageComponents/ComponentRender";
const Preview = function () {
const [pageData, setPageData] = useState(null);
const init = function () {
if (window.parent != null) {
window.parent.document.getElementById("previewWindow").setAttribute("data-ready", "true");
}
};
useEffect(() => {
init();
}, []);
const update = () => {
var value = JSON.parse(document.getElementById("importDataSendedByParent").value);
setPageData(value);
};
return (
<>
<StyledTextarea id="importDataSendedByParent" onChange={update}></StyledTextarea>
{pageData && <ComponentRender component={pageData.component} />}
</>
);
};
const StyledTextarea = styled.textarea`
position: fixed;
left: -9999px;
top: 0px;
`;
export default Preview;
|
import React, { PropTypes, Component } from 'react';
import Header from './header';
import Footer from './footer';
import Hero from './hero';
import Locator from './locator';
import { findDOMNode } from 'react-dom';
import { browserHistory } from 'react-router';
class BrandsListFood extends Component {
componentWillMount() {
// get brands to display for > this.props.params.category <
}
toggleActive(product) {
this.refs[product].className += ' active'
}
toBudget() {
browserHistory.push(`/budget/${this.props.params.category}`);
}
showCheck(check) {
this.refs[check].className = this.refs[check].className.includes('hide') ?
'check' :
'check hide'
}
render() {
return(
<div className='brands-container'>
<Header />
<Hero category={this.props.params.category}/>
<Locator stage={2}/>
<p className='brand-subtitle'>{`Next let's pick some of your preferred stores.`}</p>
<div className='brandlist'>
<div className='brand'>
<img src='/assets/images/aldi-gift-card.png'></img>
</div>
<div className='brand'>
<img src='/assets/images/kroger-gift-card.png'></img>
</div>
<div className='brand'>
<img src='/assets/images/meijer-gift-card.png'></img>
</div>
<div className='brand'>
<img src='/assets/images/publix-gift-card.png'></img>
</div>
<div className='brand'>
<img src='/assets/images/safeway-gift-card.png'></img>
</div>
<div className='brand'>
<img src='/assets/images/starbucks-gift-card.png'></img>
</div>
<div className='brand' onClick={this.showCheck.bind(this, 'traderCheck')}>
<div className='check hide' ref='traderCheck'></div>
<img src='/assets/images/trader-joes-gift-card.png'></img>
</div>
<div className='brand' onClick={this.showCheck.bind(this, 'wholeCheck')}>
<div className='check hide' ref='wholeCheck'></div>
<img src='/assets/images/whole-foods-gift-card.png'></img>
</div>
</div>
<div className='buttons'>
<div className='button'>
< Back
</div>
<div className='button-next' onClick={this.toBudget.bind(this)}>
NEXT >
</div>
</div>
<Footer />
</div>
)
}
}
export default BrandsListFood;
|
var s=process.argv.length;
var sum=0;
for(var i=2;i<s;i++){
var str=process.argv[i];
var num=Number(str);
sum=sum+num;
}
console.log(sum);
|
import React from 'react';
import { useScrollTrigger, makeStyles, Fab, Slide } from '@material-ui/core';
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';
const useStyles = makeStyles({
fab: {
position: 'fixed',
bottom: 32,
right: 32,
zIndex: 100000,
}
});
function ScrollToTopFab() {
const scrollTrigger = useScrollTrigger({
disableHysteresis: true,
threshold: 500,
});
const classes = useStyles();
return (
<Slide direction="up" in={scrollTrigger}>
<Fab className={classes.fab} onClick={() => window.scroll({ top: 0 })}>
<KeyboardArrowUpIcon />
</Fab>
</Slide>
)
}
export default ScrollToTopFab;
|
export const FETCH_AUTOCOMPLETES_REQUEST = "FETCH_AUTOCOMPLETES_REQUEST";
export const FETCH_AUTOCOMPLETES_SUCCESS = "FETCH_AUTOCOMPLETES_SUCCESS";
export const FETCH_AUTOCOMPLETES_FAILED = "FETCH_AUTOCOMPLETES_FAILED";
export const getAutocompletes = (payload) => ({
type: FETCH_AUTOCOMPLETES_REQUEST,
payload,
});
|
/* Input: Date from the computer
* Processing: Checks date and reads if it's weekend or holidays
* Output: Outputs massege if the days of the week are weekends or holidays
*/
function alarm() {
// Input: Accepting date form user computer
let now = new Date();
let month = now.getMonth();
let dayOfMonth = now.getDate();
let dayOfWeek = now.getDay();
// Output: Setting alarm messege to output massege during weekdays that are not holidays
let AlarmMassege = "Get up!";
// Processing: Checking if date is weekdays are weekends or holidays
if (
dayOfWeek == 0 ||
dayOfWeek == 6 ||
(month == 0 && dayOfMonth == 1) ||
(month == 6 && dayOfMonth == 4) ||
(month == 11 && dayOfMonth == 25)
) {
AlarmMassege = "Sleep in";
}
// Output: Displaying alarm massege
document.getElementById("output").innerHTML = AlarmMassege;
}
|
OC.L10N.register(
"files_external",
{
"Step 1 failed. Exception: %s" : "Чекор 1 Неуспешен: %s",
"Step 2 failed. Exception: %s" : "Чекор 2 Неуспешен: %s",
"External storage" : "Надворешна меморија",
"Google Drive App Configuration" : "Google Drive Конфигурација",
"Error verifying OAuth2 Code for " : "Грешка при верификација на OAuth2 кодот за",
"Personal" : "Лично",
"System" : "Систем",
"Grant access" : "Дозволи пристап",
"(group)" : "(group)",
"Compatibility with Mac NFD encoding (slow)" : "Компатибилност со Mac NFD кодирање (бавно)",
"Saved" : "Снимено",
"Username" : "Корисничко име",
"Password" : "Лозинка",
"Credentials saved" : "Акредетивите зачувани",
"Credentials saving failed" : "Акредетивите не се зачувани",
"Credentials required" : "Акредетивите се задолжителни",
"Save" : "Сними",
"Insufficient data: %s" : "Недоволно податоци: %s",
"%s" : "%s",
"API key" : "API key",
"WebDAV" : "WebDAV",
"URL" : "Адреса",
"Google Drive" : "Google Drive",
"Local" : "Локален",
"Location" : "Локација",
"ownCloud" : "ownCloud",
"Host" : "Домаќин",
"Share" : "Сподели",
"Domain" : "Домен",
"<b>Note:</b> " : "<b>Забелешка:</b> ",
"<b>Note:</b> The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Забелешка:</b> cURL поддршка во PHP не е овозможена или не е инсталирана. Монтирање на %s не е возможно. Контактирајте го администраторот.",
"<b>Note:</b> \"%s\" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it." : "<b>Забелешка:</b> \"%s\" не е инсталиран. Монтирањето на %s не е возможно. Контактирајте го администраторот.",
"No external storage configured" : "Нема надворешно складирање",
"You can add external storages in the storage settings" : "Можете да додадете надворешни складирања во подесувањата за Складиште",
"Name" : "Име",
"Storage type" : "Тип на чување",
"Scope" : "опсег",
"Enable encryption" : "Овозможи енкрипција",
"Enable previews" : "Овозможи прегледи",
"Enable sharing" : "Овозможи споделување",
"Check for changes" : "Проверувај измени",
"Never" : "Никогаш",
"Once every direct access" : "Еднаш при директен пристап",
"External Storage" : "Надворешно складиште",
"Enable external storage" : "Овозможи надворешно складирање",
"External storage has been disabled by the administrator" : "Надворешно складирање не е дозволено од администраторот",
"Folder name" : "Име на папка",
"Authentication" : "Автентикација",
"Configuration" : "Конфигурација",
"Available for" : "Достапно за",
"Add storage" : "Додади складиште",
"Advanced settings" : "Напредни подесувања",
"Delete" : "Избриши",
"Allow users to mount external storage" : "Дозволи на корисниците да монтираат надворешно складирање",
"Allow users to mount the following external storage" : "Дозволи на корисниците да ги монтираат следниве надворешни складови",
"Allow sharing on user-mounted external storages" : "Дозволи споделувања на корисничките монтирани надворешни складови"
},
"nplurals=2; plural=(n % 10 == 1 && n % 100 != 11) ? 0 : 1;");
|
const yargs = require('yargs');
var faker = require('faker');
const {
GoogleAuth
} = require('google-auth-library');
var functionURL = 'https://asia-east2-wipro-gcp-parsnet-poc.cloudfunctions.net/insert-to-yugabyte-asia';
var cities_and_sensors = [];
var sensor_data = [];
var response_recieved = 0;
var errorred_requests = 0;
const auth = new GoogleAuth();
var client;
//Define and Accept arguments;
const argv = yargs
.option('cities', {
alias: 'c',
description: 'Number of cities to generate data',
type: 'integer',
})
.option('sensor_index', {
alias: 's',
description: 'Start index for sensor ids',
type: 'integer',
})
.option('rate', {
alias: 'r',
description: 'Number of records per second ',
type: 'integer',
})
.option('duration', {
alias: 'd',
description: 'How long to generate records for in mins ',
type: 'integer',
})
.demandOption(['cities', 'sensor_index', 'rate'])
.help()
.alias('help', 'h')
.argv;
//Function to generate cities and sensorids
//This is our reference data
function generateCitiesAndSensors(num_of_cities, start_sensor_id) {
console.time('GENERATE_REF_CITIES_AND_SENSORS_DURATION')
var i = 0;
for (i = 0; i < num_of_cities; i++)
cities_and_sensors[i] = {
'city': faker.address.city(),
'sensor': start_sensor_id + i
};
console.timeEnd('GENERATE_REF_CITIES_AND_SENSORS_DURATION')
return new Promise((resolve, reject) => {
resolve();
});
}
//Interval in millisecond to generate at required rps.
const rate_interval = (1000 * argv.cities) / argv.rate;
//duration in millisecond
const duration = argv.duration * 1000;
//Function to generate seiemic data
function generateSiesmicData() {
var time_now = Date.now();
var data = cities_and_sensors.map(city => {
var message = {
'city': city.city,
'sensor': city.sensor,
'time_created': time_now,
'value': Math.random() * 7.0 + 1.0
};
return message;
});
client.request({
url: functionURL,
params: {
message: JSON.stringify(data)
}
})
.then((res) => {
resp = res.data;
response_recieved += resp.success;
errorred_requests += resp.failed;
})
.catch((err) => {
//console.log(err);
})
sensor_data = data.concat(sensor_data);
}
//Generate reference city and sensor data
var genDataInterval;
generateCitiesAndSensors(argv.cities, argv.sensor_index)
.then(() => {
auth.getIdTokenClient(functionURL).then((cl) => {
client = cl;
genDataInterval = setInterval(generateSiesmicData, rate_interval);
setInterval(() => {
clearInterval(genDataInterval);
}, duration);
return new Promise((resolve, reject) => {
resolve();
});
})
})
.then(() => {
setInterval(checkStatus, 10000)
});
function checkStatus() {
if (sensor_data.length != 0 && sensor_data.length == response_recieved + errorred_requests) {
console.log(`Total records generated: ${sensor_data.length} Successful delivered: ${response_recieved} Errored records: ${errorred_requests}`)
process.exit();
} else {
console.log(`Total records generated: ${sensor_data.length} Successful delivered: ${response_recieved} Errored records: ${errorred_requests}`)
}
}
console.log("Starting data generation");
|
import React, { useState, useEffect } from 'react';
import Select from 'react-select';
import { trackPromise } from 'react-promise-tracker';
import $ from 'jquery';
import Dashboard from '../components/dashboard'
import jQuery from 'jquery';
import moment from 'moment';
import DateRangePicker from 'react-bootstrap-daterangepicker';
import axios from 'axios';
import {
Badge,
Button,
Card,
Navbar,
Nav,
Table,
Container,
Row,
Col,
Form,
OverlayTrigger,
Tooltip,
} from "react-bootstrap";
const customStyles = {
option: (provided, state) => ({
...provided,
borderBottom: '2px dotted green',
color: state.isSelected ? 'yellow' : 'black',
backgroundColor: state.isSelected ? 'green' : 'white'
}),
control: (provided) => ({
...provided,
marginTop: "5%",
})
};
const options1 = [
{ value: 'National', label: 'National' },
{ value: 'Region', label: 'Region' },
{ value: 'Dealer', label: 'Dealer' }
]
function Dropdown() {
const [showForm, setShowForm] = useState('National');
const [resp, setGitData] = useState({ data: null, repos: null });
const [selectValue, setSelectValue] = useState('');
const [state, setState] = useState({
start: moment().subtract(100, 'days'),
end: moment().subtract(70, 'days'),
});
const [response, setResponse] = useState({ resonse_data: null});
let comp , comp1;
const handleAddrTypeChange = (e) =>
{
if(e.value == "Region")
{
var region_east = localStorage.getItem("region_east")
setSelectValue(region_east);
}
else if(e.value == "Dealer")
{
var dealer = localStorage.getItem("dealer");
setSelectValue(dealer);
}
else if(e.value == "National")
{
setSelectValue(' ');
}
setShowForm(e.value)
}
const handleAddrTypeChange1 = (e) =>
{
setSelectValue((e.value));
}
const handleAddrTypeChange2 = (e) =>
{
setSelectValue((e.value));
}
const fetchData = async () => {
const respGlobal = await axios.get(
`https://kmi-salessatisfaction.apprikart.com/secured_api/dashboard_api/get_dealer_list/?username=login1&permission=[%22KIA%22]&start_date=01/01/2021&end_date=30/01/2021&report_type=DCSI`
);
const respRepos = await axios.get(
'https://kmi-salessatisfaction.apprikart.com/secured_api/dashboard_api/get_region_list/',{ params: { username: 'login' , permission : '["KIA"]' , start_date : '01/01/2021' , end_date : '30/01/2021' , report_type :'DCSI' } },
);
setGitData({ data: respGlobal.data, repos: respRepos.data })
localStorage.setItem("region_east",resp.repos[0].value);
localStorage.setItem("dealer",resp.data[0].value);
};
const fetchData1 = async () => {
const dashApi = await axios.get(
'https://kmi-salessatisfaction.apprikart.com/secured_api/dashboard_api/get_dashboard_data/',{ params : {username: 'login' , hierarchy : showForm , dealer_code : selectValue , region_name : selectValue , permission : '["KIA"]', start_date : state.start.format('DD/MM/YYYY') , end_date : state.end.format('DD/MM/YYYY'), report_type : 'DCSI' } },
);
setResponse({ resonse_data: dashApi.data})
};
useEffect(() => {
trackPromise(
fetchData()
);
trackPromise(
fetchData1()
);
}, [showForm,state,selectValue]);
if (showForm == 'Region') {
comp = <Select className="col-md-2 col-offset-4" styles = { customStyles } options = {resp.repos} defaultValue={resp.repos[0]}
onChange={e => handleAddrTypeChange1(e)}
/>
}
else if(showForm == 'Dealer')
{
comp1 = <Select className="col-md-2 col-offset-4"
styles = { customStyles }
options = {resp.data}
defaultValue={resp.data[0]}
onChange={e => handleAddrTypeChange2(e)}
/>
}
const handleEvent = (e) =>
{
console.log(e.ranges);
}
console.log(state.start.format('DD/MM/YYYY') + "-"+ state.end.format('DD/MM/YYYY'))
const { start, end } = state;
const handleCallback = (start, end) => {
setState({ start, end });
};
const label =
start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY');
return (
<>
<Container fluid >
<Row style={{margin:'1px'}}>
<DateRangePicker initialSettings={{
startDate: start.toDate(),
endDate: end.toDate()
}}
onCallback={handleCallback}
styles = { customStyles }
>
<input id = "someRandomID" className="col-sm-2 col-offset-4" style={{ height: '40px', margin: '10px'}}/>
</DateRangePicker>
<Select className="col-sm-2 col-offset-4"
styles = { customStyles }
defaultValue={{ value: 'National', label: 'National' }}
options = {options1}
onChange={e => handleAddrTypeChange(e)}
/>
{comp}
{comp1}
</Row>
</Container >
{
response.resonse_data && <Dashboard todos={selectValue} todos1={response.resonse_data} />
}
</>
);
}
export default Dropdown;
|
define([
"jquery",
"base/declare",
"base/_WidgetBase"
], function ($, declare, _WidgetBase) {
var colorIgnore = ["rgb(39, 38, 54)", "rgba(0, 0, 0, 0)", "#fff", "rgb(255, 255, 255)"];
var elemIgnore = ["span", "font"];
var listenerSelector = "color-listener";
var onlyStyleSelector = "only-styles";
function _convertColor(tinycolor) {
if (!tinycolor) {
return "transparent";
}
var value = tinycolor.toHexString();
if (tinycolor._a == 0) {
value = "transparent";
} else if (tinycolor._a < 1) {
value = tinycolor.toRgbString();
}
return value;
}
function getMatchedCSSRules(el) {
el = el || this.element;
if (!el) {
return {};
}
var dom = el.ownerDocument;
if (!dom) {
return {};
}
//if (dom.defaultView.getMatchedCSSRules !== undefined) {
// return dom.defaultView.getMatchedCSSRules(el, null);
//} else {
var styles = dom.styleSheets,
result = {};
for (var s = 0; s < styles.length; s++) {
var styleSheet = styles[s],
cssRules = styleSheet.cssRules;
for (var c = 0; c < cssRules.length; c++) {
var cssRule = cssRules[c];
if ($(cssRule.selectorText, dom).is(el)) {
result[Object.keys(result).length] = cssRule;
}
}
}
result["length"] = Object.keys(result).length;
return result;
//}
}
function getOwnStyle(el, styles) {
var doc = el.ownerDocument,
style = el.style,
s = getMatchedCSSRules(el);
var result = {};
_.each(styles, function (st) {
_.each(s, function (CssRule) {
if (CssRule.style[st] && colorIgnore.indexOf(CssRule.style[st]) === -1) {
result[st] = CssRule.style[st];
result["has"] = true;
}
});
if (style[st] && colorIgnore.indexOf(style[st]) === -1) {
result[st] = style[st];
result["has"] = true;
}
});
return result || {};
}
return declare(_WidgetBase, {
baseClass: "mail-toolbar-color-picker",
templateString: "<div style=\"position:absolute;z-index: 3; width: 54px;\"><input data-kb-attach-point='_colorNode'></div>",
colorShowing: false,
node: null,
root: null,
isShow: false,
_colorNode: null,
_styles: null,
init: function () {
this.inherited(arguments);
this._initSpectrum();
},
_initSpectrum: function () {
var self = this;
$(this._colorNode).spectrum({
color: "#f9c502",
showInput: true,
containerClassName: "full-spectrum",
showInitial: true,
showPalette: true,
showButtons: false,
togglePaletteOnly: true,
showSelectionPalette: true,
showAlpha: true,
maxPaletteSize: 6,
maxSelectionSize: 6,
showPaletteOnly: true,
togglePaletteMoreText: "+",
togglePaletteLessText: "-",
preferredFormat: "hex",
localStorageKey: false,
palette: [
["rgb(204, 0, 51)", "rgb(247, 148, 30)", "rgb(0, 102, 102)", "rgb(0, 0, 204)", "rgb(0, 159, 227)", "rgb(249, 197, 2)"]
],
move: function (tinycolor) {
self.setNodeColor(_convertColor(tinycolor));
},
change: function (tinycolor) {
self.setNodeColor(_convertColor(tinycolor));
// self.emit("spectrumHide", self, tinycolor);
},
hide: function (tinycolor) {
self.colorShowing = false;
self.emit("spectrumHide", self, tinycolor);
},
cancelClick: function () {
self.reset();
},
okClick: function () {
}
}).on('show.spectrum', function () {
self.colorShowing = true;
self.emit("colorShow");
});
},
_initColor: function () {
var self = this;
_.each(this._styles, function (value, name) {
if (name !== "has") {
self.color = value;
}
});
this.setSpectrumColor(this.color);
},
_show: function (fix) {
var $node = $(this.node),
offset = this.node.getBoundingClientRect();
$(this.domNode).css({
left: offset.left + fix.left,
top: offset.top + fix.top + $node.outerHeight()
}).show();
$(this._colorNode).spectrum("hide");
//offset.left + fix.left, offset.top + fix.top + $el.height()
},
show: function (o) {
var def = {
node: this.node,
root: this.root
},
conf = _.extend(def, o);
this.clear();
this._setNode(conf.node, conf.root);
if (this._styles) {
this._initColor();
this._show(conf.fix);
}
this.isShow = true;
return this;
},
hide: function () {
$(this.domNode).hide();
$(this._colorNode).spectrum("hide");
this.isShow = false;
return this;
},
startup: function () {
this.hide();
return this;
},
setNodeColor: function (color) {
var self = this;
_.each(this._styles, function (value, name) {
$(self.node).css(name, color);
});
this.setListenerColor(color);
},
setListenerColor: function (color) {
var $listeners = $(this.node).find("> [data-" + listenerSelector + "]");
$listeners.each(function () {
var $this = $(this), styles = $this.data(listenerSelector).split(",");
_.each(styles, function (name) {
$this.css(name, color);
})
});
},
setSpectrumColor: function (color) {
return $(this._colorNode).spectrum("set", color);
},
_setNode: function (node, root) {
var self = this, p = node, tmp = {},
styles, eg, onlyStyles;
var s = ["background-color",
"border-bottom-color",
"border-top-color",
"border-left-color",
"border-right-color"
];
while (p && p != root.parentNode) {
eg = {};
if (elemIgnore.indexOf(p.tagName.toLocaleLowerCase()) === -1) {
eg = getOwnStyle(p, s);
if (eg.has) {
this._styles = eg;
this.node = p;
this.root = root;
if ($(p).data(onlyStyleSelector)) {
onlyStyles = $(p).data(onlyStyleSelector).split(",");
_.each(onlyStyles, function (name) {
tmp[name] = self._styles[name];
});
self._styles = tmp;
}
break;
}
}
p = p.parentNode;
}
},
_value: function (value) {
var self = this;
if (value) {
self.color = value;
$(this._colorNode).spectrum("set", value);
} else {
return $(this._colorNode).spectrum("get", value);
}
},
reset: function () {
return this.setSpectrumColor(this.color);
},
clear: function () {
this._styles = null;
this.node = null;
this.root = null;
this.isShow = false;
},
destroy: function () {
$(this._colorNode).spectrum("destroy");
this.inherited(arguments);
delete this._colorNode;
delete this._styles;
delete this.node;
delete this.root;
}
});
});
|
import React from 'react';
import styles from './characterDetails.css';
import R from 'ramda';
import Animate from './animate';
import { connect } from 'react-redux';
import { closeModal } from '../redux/actions';
import Classes from '../../data/classes';
import StatsTable from './statsTable';
const CharacterDetails = ({character, dispatch}) => {
const classes = R.prepend(character.classSet, Classes[character.class].promote);
return (
<Animate className={styles.overlay}
from={{opacity: 0}} to={{opacity: 1}}>
<div className={styles.container}>
<Animate className={styles.characterDetails}
from={{opacity: 0, scale: 0.5}} to={{opacity: 1, scale: 1}}>
<div className={styles.header}>
<img src={character.icon} />
<div className={styles.headerInfo}>
<h3>{character.name}</h3>
<div className={styles.characterClass}>{character.class}</div>
</div>
<span></span>
<div className={styles.close}
onClick={() => dispatch(closeModal())}>⨯</div>
</div>
<div className={styles.body}>
{ character.parent &&
<div>{character.sex === 'Male' ? 'son' : 'daughter'} of {character.parent}</div> }
{ character.marriable && !!character.marriable.length &&
<div>S+:
<select>
<option key="-" value="">-</option>
{ R.map(c => <option key={c} value={c}>{c}</option>,
character.marriable) }
</select>
</div>
}
{ character.support && !!character.support.length &&
<div>A+:
<select>
<option key="-" value="">-</option>
{ R.map(c => <option key={c} value={c}>{c}</option>,
character.support) }
</select>
</div>
}
<ul><strong>Classes:</strong>
{ R.map(cl => <li key={cl}> {cl} </li>, classes) }
</ul>
{ /* <ul><strong>Branches of Fate:</strong>
{ R.map(path => <li key={path}> {path} </li>, character.paths) }
</ul> */ }
<strong>Base stats:</strong>
<StatsTable {...character.baseStats} />
<strong>Modifiers:</strong>
<StatsTable {...character.modifiers} />
</div>
</Animate>
</div>
</Animate>
);
}
export default connect()(CharacterDetails);
|
// 能发送异步ajax请求的函数模块
// 封装ajax库
// 函数的返回值是promise对象
// 1 优化1: 统一处理请求异常?
// 在外层包一个自己创建的Promise对象
// 在请求出错时不调用reject
// 2 优化2: 异步得到不是response 而是response.data
// 在请求成功时:resolve(response.data)
import axios from 'axios';
import {message} from 'antd';
export default function ajax(url,data={},type='GET'){
return new Promise((resolve,reject)=>{
let promise
//执行异步ajax请求
if(type==='GET')
//发送get请求
{
promise = axios.get(url,{ //配置对象
params: data //指定请求参数
})
} else
//发送post请求
{
promise = axios.post(url,data)
}
//如果成功了
promise.then(response =>{
resolve(response.data)
}).catch(error=>{
message.error(error.message)
})
})
}
|
const request = require('request')
const getForecast = (lat, lon, calllback) => {
const url = 'https://api.darksky.net/forecast/614e001a636f32af47e1bff7ad088504/' + lat + ',' + lon + '?units=si'
request({ url, json: true }, (error, { body }) => {
if (error) {
calllback('Unable to connect to wheater service!')
} else if (body.error) {
calllback('Unable to find location!')
} else {
calllback(undefined, `${body.daily.data[0].summary} It's currently ${body.currently.temperature} degrees out. There is a ${body.currently.precipProbability} % chance to rain. The high today is ${body.daily.data[0].temperatureHigh}°C with a low of ${body.daily.data[0].temperatureLow}°C`)
}
})
}
module.exports = {
getForecast
}
|
/**
* @type {import('@stryker-mutator/api/core').StrykerOptions}
*/
module.exports = {
mutator: 'javascript',
packageManager: 'npm',
reporters: ['html', 'clear-text', 'progress', 'dashboard'],
testRunner: 'jest',
transpilers: [],
coverageAnalysis: 'off',
dashboard: {
project: 'github.com/samycici/auth-app'
},
mutate: [
'server/**/*.js'
],
jest: {
projectType: 'custom',
configFile: 'jest.config.js',
enableFindRelatedTests: false
},
timeoutMS: 15000,
tempDirName: '.stryker-tmp'
}
|
// @flow
import type { EdgeMetaToken } from 'edge-core-js'
import * as React from 'react'
import { Image, Switch, View } from 'react-native'
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'
import { SYNCED_ACCOUNT_DEFAULTS } from '../../modules/Core/Account/settings.js'
import * as UTILS from '../../util/utils.js'
import { type Theme, cacheStyles, useTheme } from '../services/ThemeContext.js'
import { WalletListRow } from './WalletListRow'
export type Props = {
toggleToken: string => void,
metaToken: EdgeMetaToken & {
item: any
},
enabledList: string[],
goToEditTokenScene: string => void,
symbolImage: string
}
function ManageTokensRow(props: Props) {
const theme = useTheme()
const styles = getStyles(theme)
const { currencyCode, currencyName } = props.metaToken.item
const { enabledList, toggleToken, goToEditTokenScene, symbolImage } = props
const Icon = () => (
<View style={styles.iconContainer}>
<Image style={styles.iconSize} source={{ uri: symbolImage }} />
</View>
)
const EditIcon = () => (isEditable ? <FontAwesomeIcon name="edit" size={theme.rem(0.95)} color={theme.iconTappable} /> : null)
const enabled = enabledList.indexOf(currencyCode) >= 0
// disable editing if token is native to the app
const isEditable = !Object.keys(SYNCED_ACCOUNT_DEFAULTS).includes(currencyCode)
const onPress = () => {
isEditable ? goToEditTokenScene(currencyCode) : UTILS.noOp()
}
return (
<WalletListRow onPress={onPress} gradient icon={<Icon />} editIcon={<EditIcon />} currencyCode={currencyCode} walletName={currencyName}>
<View style={styles.touchableCheckboxInterior}>
<Switch
onChange={() => toggleToken(currencyCode)}
value={enabled}
ios_backgroundColor={theme.toggleButtonOff}
trackColor={{
false: theme.toggleButtonOff,
true: theme.toggleButton
}}
/>
</View>
</WalletListRow>
)
}
const getStyles = cacheStyles((theme: Theme) => ({
iconContainer: {
alignItems: 'center',
justifyContent: 'center'
},
iconSize: {
width: theme.rem(2),
height: theme.rem(2)
},
touchableCheckboxInterior: {
justifyContent: 'center',
alignItems: 'center'
},
checkBox: {
alignSelf: 'center'
}
}))
export default ManageTokensRow
|
import styled from "styled-components";
export const Notification = styled.div`
font-size: 0.4rem;
font-weight: bold;
height: .8rem;
width: .8rem;
background-image: linear-gradient(
to right,
${(props) => props.theme.secondaryColor},
${(props) => props.theme.primaryColor}
);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
border-radius: 50%;
box-shadow: 0 10px 6px -6px;
`;
|
export * from './constants';
export userSettings from './userSettings';
|
import HttpStatus from 'http-status-codes';
import Notification from '../models/notification.model';
import formidable from 'formidable';
import fs from 'fs';
import date from 'date-and-time';
import randomstring from 'randomstring';
/**
* Upload Image
*
* @param {object} req
* @param {object} res
* @param {string} oldpaht
* @param {string} newpath
* @returns {*}
*/
function UploadImage(req, res, oldpath, newpath) {
fs.rename(oldpath, newpath, function(err) {
if (err)
throw err;
Notification.forge({
Image : newpath
}, {hasTimestamps: true}).save()
.then(notification => res.json({
error : true,
message : "Image Uploading Succed!",
id : notification.id
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
});
}
/**
* Change Image
*
* @param {object} req
* @param {object} res
* @param {string} oldpath
* @param {string} newpath
* @param {integer} id
* @returns {*}
*/
function ChangeImage(req, res, oldpath, newpath, id) {
Notification.forge({id: id})
.fetch({require: true})
.then(function(notification) {
if (notification.get('Image') != "")
fs.unlinkSync(notification.get('Image'));
fs.rename(oldpath, newpath, function(err) {
if (err)
throw err;
Notification.forge({id: id})
.fetch()
.then(notification => notification.save({
Image : newpath
})
.then(() => res.json({
error : false,
message : "Image Uploading Succed!",
id : id
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: true,
data: {message: err.message}
})
)
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
});
});
}
/**
* Store new notification
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function SaveNotification(req, res) {
let Release_Time = new Date();
date.format(Release_Time, 'YYYY-MM-DD HH:mm:ss');
Notification.forge({id: req.body.id})
.fetch({require: true})
.then(notification => notification.save({
Title : req.body.title || notification.get('Title'),
Notice : req.body.notice || notification.get('Notice'),
Release_Time : Release_Time
})
.then(() => res.json({
error : false,
message : "Save Notification Succed!"
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: true,
data: {message: err.message}
})
)
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
}
/**
* Upload Notification Image
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function UploadNotificationImage(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if (files.image == null) {
res.send({
error : true,
message : "Select File Correctly!"
});
} else {
console.log(files.image);
var oldpath = files.image.path;
var fileName = randomstring.generate(7);
var newpath = 'C:/Users/royal/notification/' + fileName + ".jpg";
if (req.params.id == 0) {
UploadImage(req, res, oldpath, newpath);
} else {
ChangeImage(req, res, oldpath, newpath, req.params.id);
}
}
});
}
/**
* Download notification Image
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function DownloadNotificationImage(req, res) {
Notification.forge({id : req.params.id})
.fetch()
.then(function(notification) {
var path = notification.toJSON().Image.toString();
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers.range) { // meaning client (browser) has moved the forward/back slider
// which has sent this request back to this server logic ... cool
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'image/jpeg' });
file.pipe(res);
} else {
res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'image/jpeg' });
fs.createReadStream(path).pipe(res);
}
});
}
/**
* Find notification by id
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function GetNotificationById(req, res) {
Notification.forge({id: req.params.id})
.fetch()
.then(notification => {
if (!notification) {
res.status(HttpStatus.NOT_FOUND).json({
error: true, Notification: {}
});
}
else {
res.json({
error: false,
notification: notification.toJSON()
});
}
})
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
}
/**
* Change Notification Status
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function ChangeStatus(req, res) {
Notification.forge({id: req.params.id})
.fetch({require: true})
.then(notification => notification.save({
Status : !notification.get('Status')
})
.then(() => res.json({
error : false,
message : "Change Status Succed"
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: true,
data: {message: err.message}
})
)
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
}
/**
* Get All Notifications
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function GetNotifications(req, res) {
Notification.forge()
.fetchAll()
.then(notification => res.json({
error: false,
notifications: notification.toJSON()
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
}
/**
* Delete notification by id
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function DeleteNotification(req, res) {
Notification.forge({id: req.params.id})
.fetch({require: true})
.then(notification => notification.destroy()
.then(() => res.json({
error: false,
message: 'Delete Notification Succed.'
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: true,
message: err.message
})
)
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
Notification.forge({id: req.params.id})
.fetch({require: true})
.then(notification => fs.unlinkSync(notification.get('Image')));
}
|
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { ProgressBar } from '@react-native-community/progress-bar-android';
function Stat() {
return (
<View style={styles.container}>
<View style={styles.containerStat}>
<Text style={styles.nameStat}>HP</Text>
<Text style={styles.valueStat}>45</Text>
<ProgressBar
style={styles.pbStat}
styleAttr="Horizontal"
indeterminate={false}
progress={0.45}
color='#c86c79'
/>
</View>
<View style={styles.containerStat}>
<Text style={styles.nameStat}>Attack</Text>
<Text style={styles.valueStat}>60</Text>
<ProgressBar
style={styles.pbStat}
styleAttr="Horizontal"
indeterminate={false}
progress={0.6}
/>
</View>
<View style={styles.containerStat}>
<Text style={styles.nameStat}>Defense</Text>
<Text style={styles.valueStat}>48</Text>
<ProgressBar
style={styles.pbStat}
styleAttr="Horizontal"
indeterminate={false}
progress={0.48}
color='#c86c79'
/>
</View>
<View style={styles.containerStat}>
<Text style={styles.nameStat}>Sp. Atk</Text>
<Text style={styles.valueStat}>65</Text>
<ProgressBar
style={styles.pbStat}
styleAttr="Horizontal"
indeterminate={false}
progress={0.65}
/>
</View>
<View style={styles.containerStat}>
<Text style={styles.nameStat}>Sp. Def</Text>
<Text style={styles.valueStat}>65</Text>
<ProgressBar
style={styles.pbStat}
styleAttr="Horizontal"
indeterminate={false}
progress={0.65}
/>
</View>
<View style={styles.containerStat}>
<Text style={styles.nameStat}>Speed</Text>
<Text style={styles.valueStat}>45</Text>
<ProgressBar
style={styles.pbStat}
styleAttr="Horizontal"
indeterminate={false}
progress={0.45}
color='#c86c79'
/>
</View><View style={styles.containerStat}>
<Text style={styles.nameStat}>Total</Text>
<Text style={styles.valueStat}>317</Text>
<ProgressBar
style={styles.pbStat}
styleAttr="Horizontal"
indeterminate={false}
progress={0.7}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 24,
backgroundColor:'#ffffff'
},
containerStat: {
flexDirection: "row",
justifyContent: 'center',
alignItems: 'center',
paddingVertical: 5,
flex: 1,
maxHeight: 35,
},
nameStat: {
flex: 2,
color: '#b3afb4',
fontFamily: 'Nunito-Regular'
},
valueStat: {
flex: 1,
},
pbStat: {
flex: 3,
}
})
export default Stat;
|
import React from 'react';
import Request from 'superagent';
import Button from './Button.jsx';
import SongList from './SongList.jsx';
import CronSetter from './CronSetter.jsx';
import Actions from '../actions/Actions.jsx';
import SongStore from '../stores/SongStore.jsx';
let AUDIO_TYPES = {
song : 'song',
random : 'random',
sound : 'sound'
};
let PLAYING = false;
function getState() {
return {
data : [],
showCronSetter: false,
selectedAudioType : null
};
}
class SongManager extends React.Component {
constructor() {
super();
this.state = getState();
this.showSection = this.showSection.bind(this);
this.selectSong = this.selectSong.bind(this);
this.playSong = this.playSong.bind(this);
this.stopSong = this.stopSong.bind(this);
this.createCron = this.createCron.bind(this);
this.renderSongList = this.renderSongList.bind(this);
this.onChange = this.onChange.bind(this);
}
componentDidMount(){
SongStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
this.setState(getState());
SongStore.removeChangeListener(this.onChange);
}
onChange(songsArray) {
this.setState({
data: songsArray,
showCronSetter : this.state.selectedAudioType === 'random' ? true : false
});
}
selectSong(i = 0) {
let selectedSong = [this.state.data[i]];
this.setState({
data: selectedSong,
showCronSetter : true
});
}
playSong(i = 0) {
Actions[this.state.selectedAudioType].stop();
let selectedSong = this.state.data[i].name;
Actions[this.state.selectedAudioType].play(selectedSong);
}
stopSong() {
if (this.state.selectedAudioType && this.state.selectedAudioType !== 'random') {
Actions[this.state.selectedAudioType].stop();
}
}
showSection(type) {
this.setState({
selectedAudioType : AUDIO_TYPES[type],
showCronSetter : this.state.selectedAudioType === 'random' ? true : false
});
console.log('this.state', this.state);
Actions[AUDIO_TYPES[type]].get();
}
// need to differentiate between song and sound
createCron(cron){
cron.song = this.state.selectedAudioType === 'random' ? this.state.selectedAudioType : this.state.data[0].name;
cron.audioType = this.state.selectedAudioType;
Actions.cron.create(cron);
Actions.ui.set('cron');
}
renderCronSetter(){
return (
<CronSetter onCreateCronHandler={this.createCron} />
);
}
renderSongList(){
return (
<SongList data={this.state.data} onSelect={this.selectSong} onPlay={this.playSong} onStop={this.stopSong}/>
);
}
render() {
let showSongListClass = this.state.selectedAudioType === 'song' ? 'active' : '';
let showSoundListClass = this.state.selectedAudioType === 'sound' ? 'active' : '';
let showRandomClass = this.state.selectedAudioType === 'random' ? 'active' : '';
let cronSetter = this.state.showCronSetter === true ? this.renderCronSetter() : null;
return (
<section>
<h2>Play...</h2>
<Button className={showSongListClass} onClick={this.showSection.bind(this, 'song')}>
A song
</Button>
<strong className="divider">or</strong>
<Button className={showRandomClass} onClick={this.showSection.bind(this, 'random')}>
A random song
</Button>
<strong className="divider">or</strong>
<Button className={showSoundListClass} onClick={this.showSection.bind(this, 'sound')}>
A Sound
</Button>
{this.renderSongList()}
{cronSetter}
</section>
);
}
}
export default SongManager;
|
import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMusic } from '@fortawesome/free-solid-svg-icons';
export const Song = ({
currentSong,
setShowLibrary,
showLibrary,
isPlaying,
}) => {
//handle click
const handleShowLibrary = () => {
setShowLibrary((previuosState) => !previuosState);
};
return (
<div className="song-container">
<div className="show-library">
<button onClick={handleShowLibrary}>
<FontAwesomeIcon
icon={faMusic}
size="1x"
style={{ marginRight: '5' }}
/>
{showLibrary ? 'Hide library' : 'Show library'}
</button>
</div>
<img
className={isPlaying ? 'rotate' : ''}
src={currentSong.cover}
alt="song cover"
/>
<h2>{currentSong.name}</h2>
<h3>{currentSong.artist}</h3>
</div>
);
};
|
// Nest manages the eggs
const fs = require('fs');
const egg = require('../tamagochi/egg.js');
const savefile = "tamagochi/nest.json"
const { tick_time } = require("../config.json")
var nest = {};
// Initialize nest file
try {
if (fs.existsSync(savefile)) {
n = JSON.parse(fs.readFileSync(savefile));
for (owner in n) {
_egg = egg.egg.fromJSON(n[owner]);
nest[owner] = _egg;
}
} else {
save();
}
} catch(err) {
console.error(err)
}
// Initialize Egg update
const _eggupdate = setInterval(
egg_update,
tick_time * 1000
)
module.exports = {
clear,
create,
egg_update,
get,
update,
}
// Update all eggs
function egg_update() {
let _before = Date.now()
for (owner in nest) {
nest[owner].update();
}
save();
let _after = Date.now()
console.log(`Eggs updated in ${_after - _before} milliseconds.`);
}
// Get the egg of an user
function get(user) {
return nest[user];
}
// Remove the egg of an user
function clear(user) {
delete nest[user];
save();
}
// Create a new egg for an user
function create(user) {
let newegg = new egg.egg(user);
update(user.id, newegg);
}
// save a modified egg for an user
function update(user, egg) {
nest[user] = egg;
save();
}
// save the eggs
function save() {
fs.writeFileSync(savefile, JSON.stringify(nest), function(err) {
if (err) {
console.log(err);
}
});
}
|
linechartoptions = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.0)',
zeroLineColor: "transparent",
},
ticks: {
suggestedMin: 60,
suggestedMax: 125,
padding: 20,
fontColor: "#9a9a9a"
}
}],
xAxes: [{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#9a9a9a"
}
}]
}
};
gradientBarChartConfiguration = {
maintainAspectRatio: false,
legend: {
display: false
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [{
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.1)',
zeroLineColor: "transparent",
},
ticks: {
suggestedMin: 60,
suggestedMax: 120,
padding: 20,
fontColor: "#9e9e9e"
}
}],
xAxes: [{
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#9e9e9e"
}
}]
}
};
var int data = "{{data}}";
var overall = "{{overall}}";
//first line chart polarity_line
let ctx = document.getElementById('polarity_date');
var gradientStroke = ctx.createLinearGradient(0, 230, 0, 50);
gradientStroke.addColorStop(1, 'rgba(29,140,248,0.2)');
gradientStroke.addColorStop(0.4, 'rgba(29,140,248,0.0)');
gradientStroke.addColorStop(0, 'rgba(29,140,248,0)'); //blue colors
let massPopChart = new Chart(ctx,{
type:'line',
data:{
labels:data[0],
datasets:[{
label:"",
data:parseInt(data[1]),
fill: true,
backgroundColor:gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#1f8ef1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#00d6b4',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
}]
},
options:linechartoptions
});
var myChart = new Chart(ctx, {
type: 'bar',
responsive: true,
legend: {
display: false
},
data: {
labels: ['Positive', 'Negative', 'Neutral'],
datasets: [{
label: "",
fill: true,
backgroundColor: gradientStroke,
hoverBackgroundColor: gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
data: [53, 20, 10, 80, 100, 45],
}]
},
options: gradientBarChartConfiguration
});
/*function loaddata(canid, lable1, lable2, lable3, lable4, lable5, lable6){
this.canid = canid;
this.lable1 = lable1;
this.lable2 = lable2;
this.lable3 = lable3;
this.lable4 = lable4;
this.lable5 = lable5;
this.lable6 = lable6;
var x = 100;//parseInt("{{positive}}");
var y = 600;//parseInt("{{negative}}");
var z = 700;//parseInt("{{neutral}}");
var sad = 600;//parseInt("{{sad}}");
var ang = 800;//parseInt("{{ang}}");
var joy = 900;//parseInt("{{joy}}");
var total = x+y+z+sad+ang+joy;
var type = 'line';
var all = [x,y,z,sad,ang,joy];
var bg1 = ['#003333','#E62727','#10375C'];
var bg2 = ['#2A0033','#CC3300','#F3C623'];
Chart.defaults.global.responsive=true;
//Chart.defaults.global.defaultFontSize='2px';
let massPopChart = new Chart(ctx,{
type:type,
data:{
labels:labels,
datasets:[{
barPercentage:0.5,
categoryPercentage: 0.7,
label:"",
data:data,
fill: true,
backgroundColor:gradientStroke,
borderColor: '#1f8ef1',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#1f8ef1',
pointBorderColor: 'rgba(255,255,255,0)',
pointHoverBackgroundColor: '#00d6b4',
pointBorderWidth: 20,
pointHoverRadius: 4,
pointHoverBorderWidth: 15,
pointRadius: 4,
}]
},
options:linechartoptions
});}*/
|
import axios from 'axios';
const api = axios.create({
baseURL: 'http://youriphere:3333' //put your ip here before the ':'
});
export default api;
|
const express = require('express');
var cors = require('cors');
const app = express()
const port = 5000;
app.use(express.json());
app.use(cors());
var todosData = [
{
id: 0,
description: "Brush teeth",
isDone : false
},
{
id: 1,
description: "Get out of bed",
isDone : false
},
{
id: 2,
description: "Eat breakfast",
isDone : false
}
];
app.get('/todos', (req, res) => {
res.json(todosData);
})
app.post('/todo', (req, res) => {
console.log(req.body)
const getHigherId = Math.max(0, ...todosData.map(todo => todo.id)) +1;
todosData = [
...todosData,
{
id: getHigherId,
description: req.body.description,
isDone: false,
},
];
res.json(todosData);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
|
module.exports = {
eventAppointmentRegister: `declare @ni_Error int
select @ni_Error = 0
exec SP_CMS_CITAS_REGISTRA @IdHorario, @idPaciente, @fechaCita, @usuario, @ni_Error output
select @ni_Error as error`,
eventBookedAppointments: `SELECT a.IdCita as idcita,
a.FechaCita as fechacita,
(SELECT RTRIM(x.Nombre)
FROM GE_Sucursal x
WHERE x.Sucursal = a.Sucursal) AS sucursal,
(SELECT RTRIM(x.sucursal)
FROM ge_sucursal x
WHERE x.sucursal = a.sucursal) AS idsucursal,
(SELECT ltrim(rtrim(x.NombreCompleto))
FROM PersonaMast x
WHERE x.Persona = b.Medico) AS nombreMedico,
(SELECT ltrim(rtrim(x.Sexo))
FROM PersonaMast x
WHERE x.Persona = b.Medico) AS sexo,
(SELECT x.CMP
FROM EmpleadoMast x
WHERE x.Empleado = b.Medico) AS cmp,
(SELECT ltrim(rtrim(x.Nombre))
FROM SS_GE_Especialidad x
WHERE x.IdEspecialidad = b.IdEspecialidad) AS nombreEspecialidad,
(SELECT x.Codigo
FROM SS_GE_Consultorio x
WHERE x.IdConsultorio = b.IdConsultorio) AS nroConsultorio,
(SELECT x.CodigoEstado
FROM GE_EstadoDocumento x
WHERE x.IdDocumento = 45
AND x.IdEstado = a.EstadoDocumento) AS estado
FROM SS_CC_Cita a,
SS_CC_Horario b
WHERE b.IdHorario = a.IdHorario
AND a.FechaCita >= @fechaActual --Parámetro a enviar fecha actual
AND a.IdPaciente = @IdPaciente --Parámetro a enviar código de persona
AND a.EstadoDocumento = 2
ORDER BY a.IdPaciente DESC`,
eventDeleteQuotes: `exec SP_CMS_CITAS_ANULA @idCita, @usuario`,
eventDoctorCita: `SELECT a.idcita,
a.fechacita,
(SELECT RTRIM(x.nombre)
FROM ge_sucursal x
WHERE x.sucursal = a.sucursal) AS sucursal,
(SELECT RTRIM(x.sucursal)
FROM ge_sucursal x
WHERE x.sucursal = a.sucursal) AS idsucursal,
(SELECT Ltrim(Rtrim(x.nombrecompleto))
FROM personamast x
WHERE x.persona = b.medico) AS nombreMedico,
(SELECT ltrim(rtrim(x.Sexo))
FROM PersonaMast x
WHERE x.Persona = b.Medico) AS sexo,
(SELECT x.cmp
FROM empleadomast x
WHERE x.empleado = b.medico) AS cmp,
(SELECT Ltrim(Rtrim(x.nombre))
FROM ss_ge_especialidad x
WHERE x.idespecialidad = b.idespecialidad) AS nombreEspecialidad,
(SELECT x.codigo
FROM ss_ge_consultorio x
WHERE x.idconsultorio = b.idconsultorio) AS nroConsultorio,
a.estadodocumento,
(SELECT x.codigoestado
FROM ge_estadodocumento x
WHERE x.iddocumento = 45
AND x.idestado = a.estadodocumento) AS estado
FROM ss_cc_cita a,
ss_cc_horario b
WHERE b.idhorario = a.idhorario
AND a.idcita IN (SELECT TOP 1 idcita
FROM ss_cc_cita
WHERE idpaciente = @idPaciente
ORDER BY 1 DESC)
ORDER BY a.fechacita DESC`,
eventListQuotes: `SELECT a.IdCita,
a.FechaCita,
(SELECT RTRIM(x.Nombre)
FROM GE_Sucursal x
WHERE x.Sucursal = a.Sucursal) AS sucursal,
(SELECT ltrim(rtrim(x.NombreCompleto))
FROM PersonaMast x
WHERE x.Persona = b.Medico) AS nombreMedico,
(SELECT ltrim(rtrim(x.Sexo))
FROM PersonaMast x
WHERE x.Persona = b.Medico) AS sexo,
(SELECT x.CMP
FROM EmpleadoMast x
WHERE x.Empleado = b.Medico) AS cmp,
(SELECT ltrim(rtrim(x.Nombre))
FROM SS_GE_Especialidad x
WHERE x.IdEspecialidad = b.IdEspecialidad) AS nombreEspecialidad,
(SELECT x.Codigo
FROM SS_GE_Consultorio x
WHERE x.IdConsultorio = b.IdConsultorio) AS nroConsultorio,
a.EstadoDocumento,
(SELECT x.CodigoEstado
FROM GE_EstadoDocumento x
WHERE x.IdDocumento = 45
AND x.IdEstado = a.EstadoDocumento) AS estado
FROM SS_CC_Cita a,
SS_CC_Horario b
WHERE b.IdHorario = a.IdHorario
AND a.IdPaciente = @idPaciente --Parámetro a enviar código de persona
ORDER BY a.FechaCita DESC`,
};
|
// GLOBAIS
var TELA_LARGURA = 700;
var TELA_ALTURA = 400;
var TAXA_ATUALIZACAO = 1;
// Constantes para o desenrolar do jogo
var COLIDIU = false; //indica se o jogador pegou a Elemento
var FIM_DE_JOGO = false; //indica fim de jogo
// Controla a dificuldade do jogo
var DIFICULDADE = 1; //é a taxa de dificuldade, funciona de forma inversamente proporcional, quanto menor mais dificil fica
var FACILIDADE = 0; //é a taxa de facilidade do jogo, funciona de forma inversa tambem
// Gloabl animation holder
var player = new Array();
// Função para reiniciar o jogo
function reiniciar(){
window.location.reload();
};
//JOGADOR
function Jogador( nodo ){
this.nodo = nodo; //Instancia atual
this.vidas = 3; //Numero de aceitação de Elementos podres
this.pontos = 0;
//Usada para decrementar a vidas
this.dano = function(){
this.vidas--;
if (this.vidas == 0){
FIM_DE_JOGO = true;
return true;
}
return false;
};
//Pontua os pontos de cada Elemento coletada
this.pontua = function( pontos ){
this.pontos += pontos;
}
//Recomeça o jogo
this.recomecar = function(){
this.vidas = 3;
$(this.nodo).fadeTo(0, 0.5);
return false;
};
return true;
}
//Elemento
function Elemento( nodo ){
this.speedx = 0; //velocidade eixo x
this.speedy = -5; //velocidade eixo y
this.nodo = $(nodo); //Instancia atual
this.pontos = 10; //quantidades de pontos fornecidos ao ser coletada (padrão 10)
this.tipo = 'bom';
//Atualização
this.updateX = function(){
this.nodo.x(this.speedx, true);
};
this.updateY= function(){
var newpos = parseInt(this.node.css("top"))+this.speedy;
this.nodo.y(this.speedy, true);
};
}
//Elementos Bons
function ElementoBom( nodo ){
this.nodo = $(nodo); //Instancia atual
}
ElementoBom.prototype = new Elemento(); //Herança do elemento
ElementoBom.prototype.tipo = 'bom'; //Reescrevendo o tipo
//Elementos ruins
function ElementoRuim( nodo ){
this.nodo = $(nodo); //Instancia atual
}
ElementoRuim.prototype = new Elemento();// Herança de Elemento
ElementoRuim.prototype.tipo = 'ruim';//Reescrevendo o tipo
ElementoRuim.prototype.pontos = -30;
//MOTOR DO GAME
$(function(){
//DECLARAÇÕES
// O fundo do game
var fundo = new $.gQ.Animation({imageURL: "sprites/background.jpg"});
//player
player["spin_idle"] = new $.gQ.Animation({imageURL: "sprites/spin_waiting.png", numberOfFrame: 2, delta: 47, rate: 1, type: $.gQ.ANIMATION_VERTICAL});
player["spin_turn_right"] = new $.gQ.Animation({imageURL: "sprites/spin_turn_right.png", numberOfFrame: 2, delta: 47, rate: 1, type: $.gQ.ANIMATION_VERTICAL});
player["spin_turn_left"] = new $.gQ.Animation({imageURL: "sprites/spin_turn_left.png", numberOfFrame: 2, delta: 47, rate: 1, type: $.gQ.ANIMATION_VERTICAL});
player["ball_turn_right"] = new $.gQ.Animation({imageURL: "sprites/ball_turn_right.png", numberOfFrame: 3, delta: 26, rate: 60, type: $.gQ.ANIMATION_VERTICAL});
player["ball_turn_left"] = new $.gQ.Animation({imageURL: "sprites/ball_turn_left.png", numberOfFrame: 3, delta: 26, rate: 60, type: $.gQ.ANIMATION_VERTICAL});
//Elemento bom
var elementobom = new $.gQ.Animation({imageURL: "sprites/ElementoBom.png"});
//Elemento ruim
var elementoruim = new $.gQ.Animation({imageURL: "sprites/ElementoRuim.png"});
// Inicialização do espaço amostral do jogo:
$("#espaco").playground({ width: TELA_LARGURA, height: TELA_ALTURA, keyTracker: true});
// Inicialização das camadas
$.playground().addGroup("fundo", {width: TELA_LARGURA, height: TELA_ALTURA})
.addSprite("fundo", {animation: fundo, width: TELA_LARGURA, height: TELA_ALTURA})
.end()
.addGroup("jogador", {posx: TELA_LARGURA/2, posy: TELA_ALTURA-100, width: TELA_LARGURA, height: TELA_ALTURA})
.addSprite("player", {animation: player["spin_idle"], posx: 0, posy: 0, width: 33, height: 47})
.end()
.addGroup("elementos", {width: TELA_LARGURA, height: TELA_ALTURA})
.end()
.addGroup("alerta",{width: TELA_LARGURA, height: TELA_ALTURA});
//Quando o botão de novo jogo for clicado
$("#novojogo").click(function(){
$.playground().startGame(function(){
$('#menuinicial').children().remove();
$("#menuinicial").fadeTo(500,0,function(){$(this).remove();});
});
})
//Instancia o novo jogador
$("#jogador")[0].jogador = new Jogador($("#jogador"));
//Contador de pontos
$("#alerta").append("<div id='contadorvidas'style='color: #000; width: 100px; position: absolute; font-family: verdana, sans-serif;'></div><div id='contadorpontos'style='color: #000; width: 100px; position: absolute; right: 0px; font-family: verdana, sans-serif;'></div>");
//Método que controla o loop principal
$.playground().registerCallback(function(){
if(!FIM_DE_JOGO){
$("#contadorvidas").html("Vidas: "+$("#jogador")[0].jogador.vidas);
$("#contadorpontos").html("Pontos: "+$("#jogador")[0].jogador.pontos);
//Movimentação do jogador
if(jQuery.gameQuery.keyTracker[65]){ //FOI PARA ESQUERDA! apertou letra (a)
var proxpos = $("#jogador").x()-5;
if(proxpos > 0){
$("#jogador").x(proxpos);
}
}
if(jQuery.gameQuery.keyTracker[68]){ //FOI PARA DIREITA! apertou letra (d)
var proxpos = $("#jogador").x()+5;
if(proxpos < TELA_LARGURA - 100){
$("#jogador").x(proxpos);
}
}
}
//Atualiza a movimentação das Elementos
$(".elemento").each(function(l, j){
var objeto = j; //pega a instancia da Elemento em questão
var posy = $(this).y();
if(posy > 300){ //Remove as Elementos que ultrapassarem do final da tela
$(this).remove();
return;
}
$(this).y(+5+parseInt(10*FACILIDADE), true);//realiza a movimentação no eixo y
//Teste de colisão
var colidiu = $(this).collision("#player,."+$.gQ.groupCssClass);
if(colidiu.length > 0){
//O player pegou uma Elemento
tipo = objeto.elemento.tipo;
//verifica se foi Elemento ruim
if( tipo == 'ruim' ){
if( $("#jogador")[0].jogador.dano() ){ //causa o dano no jogador
$("#contadorvidas").html("Vidas: "+$("#jogador")[0].jogador.vidas); //atualiza o contador de vidas
//apresenta tela de fim de jogo
$("#espaco").append('<div style="position: absolute; top: 50px; width: 700px; color: #fff; font-family: verdana, sans-serif;"><center><h1>Fim de Jogo</h1><br><a style="cursor: pointer;" id="btnreiniciar">Recomeçar</a></center></div>');
$("#btnreiniciar").click( reiniciar );
//remove os elementos anteriores
$("#jogador,#Elementos").fadeTo(1000,0);
$("#fundo").fadeTo(5000,0);
}
}
$("#jogador")[0].jogador.pontua( j.elemento.pontos );
$(this).remove();
}
});
}, TAXA_ATUALIZACAO);
//Chamada de teclado em background
$(document).keyup(function(e){
if(!FIM_DE_JOGO){
switch(e.keyCode){
case 65: //this is left! (a)
$("#player").setAnimation(player["spin_idle"]);
break;
case 68: //this is right (d)
$("#player").setAnimation(player["spin_idle"]);
break;
}
}
});
//this is where the keybinding occurs
$(document).keydown(function(e){
if(!FIM_DE_JOGO){
switch(e.keyCode){
case 65: //this is left! (a)
$("#player").setAnimation(player["spin_turn_left"]);
break;
case 68: //this is right (d)
$("#player").setAnimation(player["spin_turn_right"]);
break;
}
}
});
//Criação das Elementos
$.playground().registerCallback(function(){
if(!FIM_DE_JOGO){ //se não for fim de jogo
if(Math.random().toFixed(2) > FACILIDADE.toFixed(2)){// criação de Elementos bons
var name = "elemento_"+Math.ceil(Math.random()*1000);
//inicia a criação sempre no topo do espaço, apenas mudando a posição horizontal
$("#elementos").addSprite(name, {animation: elementobom, posx: Math.random()*TELA_LARGURA, posy: -50,width: 44, height: 37});
$("#"+name).addClass("elemento");
$("#"+name)[0].elemento = new ElementoBom($("#"+name));
} else if (Math.random().toFixed(2) > DIFICULDADE.toFixed(2)){// criação de Elementos ruins
var name = "elemento_"+Math.ceil(Math.random()*1000);
//inicia a criação sempre no topo do espaço, apenas mudando a posição horizontal
$("#elementos").addSprite(name, {animation: elementoruim, posx: Math.random()*TELA_LARGURA, posy: -50,width: 64, height: 59});
$("#"+name).addClass("elemento");
$("#"+name)[0].elemento = new ElementoRuim($("#"+name));
}
}
}, 500);
//A cada 10segundos aumenta a dificuldade
$.playground().registerCallback(function(){
if( DIFICULDADE > 0.1 && FACILIDADE < 0.9 ){
DIFICULDADE = DIFICULDADE - 0.1;
FACILIDADE = FACILIDADE + 0.1;
}
}, 10000);
});
|
import React from 'react';
const NoMatch = () => {
return ( <h2>sorry this link doesn't exists </h2> );
}
export default NoMatch;
|
import React from 'react';
import './About.scss';
class About extends React.Component {
render() {
return (
<section id='about-section'>
<h1 className='section-title'>About</h1>
<hr />
<br />
<p style={{ textAlign: 'center', paddingTop: '5%' }}>Greetings,
<br />
<br />
My name is Luka and I am a Front End Web Developer.
<br />
I have been a self-taught web dev for almost year now ever since I discovered how the web is built. I am always on the lookout for a challenging and interesting opportunity to showcase and level up my skills and knowledge. If you've enjoyed my portfolio, reach out. Let's work.</p>
</section>
);
}
}
export default About;
|
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import styles from '../styles/globalStyle';
function valorTotal(quant, preco) {
return quant*preco;
}
export default function({ descricao, quantidade, preco }) {
return (
<View style={styles.postItContainer}>
<Text style={styles.title}>Produto</Text>
<Text>{descricao}</Text>
<Text>{quantidade}</Text>
<Text>{preco}</Text>
<Text>Preço total: R$ {valorTotal(quantidade, preco)}</Text>
</View>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.