text
stringlengths
7
3.69M
({ doInit : function(component, event, helper) { helper.getInitialData(component); }, loadNextMonth : function(component, event, helper) { helper.loadNextMonth(component); }, })
var _ = require('underscore'); var fn = require('../fn'); var datas = require('../datas'); var exports = {}; exports.init = function(userID) {} exports.api = { GetUsageRecord: function(req, res, userID) { var $data = datas[userID].$data; res.send(fn.result($data.GetUsageRecord, req.id)); }, SetUsageRecordClear: function(req, res, userID) { var $data = datas[userID].$data; res.send(fn.result()); }, GetUsageSettings: function(req, res, userID) { var $data = datas[userID].$data; res.send(fn.result($data.GetUsageSettings, req.id)); }, SetUsageSettings: function(req, res, userID) { var params = req.params; var $data = datas[userID].$data; $data.GetUsageSettings = params; res.send(fn.result()); }, GetUsageSetFlag: function(req, res, userID) { var $data = datas[userID].$data; res.send(fn.result($data.GetUsageSetFlag, req.id)); }, SetUsageSetFlag: function(req, res, userID) { var $data = datas[userID].$data; res.send(fn.result()); } } module.exports = exports
import React from "react" import Layout from '../components/Layout' import {ExampleButton} from '../components/button' export default () => ( <Layout> <h1 style={{color:"red", textTransform:"uppercase"}}>Hello people!</h1> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release</p> <ExampleButton>click me</ExampleButton> </Layout> )
/* * Usage: /*return next(new Error('{"status": 400, "fields": [{"id": null}]}')); * For sequelize errors just pass sequelize error object like this: * users.create(req.body) .catch(function (error) { return next(error); }); * */ module.exports = function (app) { var handleSequelizeErrors = function(err) { if(err.name === 'SequelizeValidationError' || err.name === 'SequelizeUniqueConstraintError') { err.status = 422; var fields = []; for(var i = 0; i < err.errors.length; i++) { fields.push({ field: err.errors[i].path, message: err.errors[i].message }) } err.fields = fields; } }; return [ function (err, req, res, next) { try { var error = JSON.parse(err.message); } catch(e) { handleSequelizeErrors(err); return(next(err)); } err.status = error.status; err.message = ''; err.fields = []; if(error.message) err.message = error.message; if(error.fields) err.fields = error.fields; err.isError = 1; if(err) return next(err); return next(); } ] }
// jshint esversion: 6 if (typeof module !== 'undefined') { var fs = require('fs'); var path = require('path'); var loader = require(path.resolve(__dirname, './loader.js')); var shell = require(path.resolve(__dirname, './shell.js')); var api_promise = Promise.resolve(require(path.resolve(__dirname, './api.json'))); var layouts_promise = Promise.resolve(require(path.resolve(__dirname, './layouts.json'))); } else { var loader = this; var shell = this; var api_promise = fetch("api.json").then(r => r.json()); var layouts_promise = fetch("layouts.json").then(r => r.json()); } // We now allow the user to pass a custom list of modules if they want to do // their own, more lightweight packaging. function getModulesPromise(modules=shell.my_modules) { const readModule = async m => typeof module !== 'undefined' ? new Uint8Array(await fs.promises.readFile(path.resolve(__dirname, './' + m))) : (await fetch(m)).arrayBuffer(); return Promise.all(modules.map(async name => ({ buf: await readModule(name + ".wasm"), name }) )); } // Comment out for debug loader.setMyPrint((x) => {}); // HELPERS FOR SIZE FIELDS // ----------------------- // Grammar of size fields: // // f ::= // var // var<OP>n // M.f(var) // // var: variable, one of the length variables, may be ghost // n: integer constant // <OP>: +, -, * or / // M.f: function, referred to by its name in the high-level API, e.g. // EverCrypt_Hash.hash_len (and not EverCrypt_Hash_Incremental_hash_len) var parseOp = (arg, op) => { let [ var_, const_ ] = arg.split(op); return [ "Op", var_, op, parseInt(const_) ]; }; var parseApp = (arg) => { let i = arg.indexOf("("); let [ m, f ] = arg.substr(0, i).split("."); let x = arg.substr(i+1, arg.length - 1 - i - 1); return [ "App", m, f, parseSize(x) ]; } var parseSize = (arg) => { if (arg.includes("+")) return parseOp(arg, "+"); if (arg.includes("-")) return parseOp(arg, "-"); if (arg.includes("*")) return parseOp(arg, "*"); if (arg.includes("/")) return parseOp(arg, "/"); if (arg.includes("(")) return parseApp(arg); return [ "Var", arg ]; }; var evalSize = function(parsedSize, args_int32s, api) { let [ kind, ...args ] = parsedSize; switch (kind) { case "Var": { let [ var_ ] = args; return args_int32s[var_]; } case "Op": { let [ var_, op, const_ ] = args; switch (op) { case "+": return args_int32s[var_] + const_; case "-": return args_int32s[var_] - const_; case "*": return args_int32s[var_] * const_; case "/": if (args_int32s[var_] % const_ != 0) throw new Error("Argument whose length is "+arg+" is not a multiple of "+const_); return args_int32s[var_] / const_; default: throw new Error("Illegal operator: "+op); } } case "App": { let [ m, f, x ] = args; if (!(m in api)) throw new Error("For size "+parsedSize+", module "+m+" is unknown"); if (!(f in api[m])) throw new Error("For size "+parsedSize+", function "+m+"."+f+" is unknown"); // console.log("RECURSIVE EVAL SIZE ENTER: ", x); x = evalSize(x, args_int32s, api); // console.log("RECURSIVE EVAL SIZE END: ", x); return api[m][f](x)[0]; } } }; // Given a size formula `var<OP>n` = `total`, invert it, i.e. solve the // equation where `var` is unknown. // // @param {String} arg The formula of the form var<OP>n // @param {Number} total The value of the formula // @return {[String, Number]} The variable name `var` and its value. var invertSize = function(parsedSize, total) { let [ kind, var_, op, const_ ] = parsedSize; if (kind != "Var" && kind != "Op") throw new Error("Illegal size for an input: "+parsedSize); switch (op) { case "+": return [ var_, total - parseInt(const_) ]; case "-": return [ var_, total + parseInt(const_) ]; case "*": let x = parseInt(const_); if (total % x != 0) throw new Error("Argument whose length is "+parsedSize+" is not a multiple of "+x); return [ var_, total / x ]; case "/": return [ var_, total * parseInt(const_) ]; default: return [var_, total]; } }; // VALIDATION // ---------- // The following function validates the contents of `api.json`. It is meant as // a helper when creating new binders, it provides explicit error messages. // It also has the side effect of filling out the parsedSize field on `arg` // objects, so that we don't needlessly re-parse every size field all the time. var validateJSON = function(json) { for (let key_module in json) { for (let key_func in json[key_module]) { let func_obj = json[key_module][key_func]; let obj_name = key_module + "." + key_func; if (!("module" in func_obj)) throw Error("please provide a 'module' field for " + obj_name + " in api.json"); if (!(shell.my_modules.includes(func_obj.module))) throw Error(obj_name + ".module='" + func_obj.module + "' of api.json should be listed in shell.js"); if (!("name" in func_obj)) throw Error("please provide a 'name' field for " + obj_name + " in api.json"); if (!("args" in func_obj)) throw Error("please provide a 'args' field for " + obj_name + " in api.json"); if (!Array.isArray(func_obj.args)) throw Error("the 'args' field for " + obj_name + " should be an array"); let length_args_available = {}; func_obj.args.forEach((arg, i) => { if (!(arg.kind === "input" || (arg.kind === "output"))) throw Error("in " + obj_name + ", argument #" + i + " should have a 'kind' that is 'output' or 'input'"); if (!(arg.type === "bool" || arg.type === "uint32" || arg.type.startsWith("buffer") || arg.type[0].toUpperCase() == arg.type[0])) throw Error("in " + obj_name + ", argument #" + i + " should have a 'kind' that is 'int', 'bool' or 'buffer'"); if (arg.type.startsWith("buffer") && arg.size === undefined) throw Error("in " + obj_name + ", argument #" + i + " is a buffer and should have a 'size' field"); if (arg.kind === "input" && arg.type.startsWith("buffer") && !("interface_index" in arg)) throw Error("in " + obj_name + ", argument #" + i + " is an input and should have a 'interface_index' field"); if ((arg.kind === "output" || (arg.kind === "input" && arg.interface_index !== undefined)) && arg.tests === undefined) throw Error("please provide a 'tests' field for argument #" + i + " of " + obj_name + " in api.json"); if ((arg.kind === "output" || (arg.kind === "input" && arg.interface_index !== undefined)) && !Array.isArray(arg.tests)) throw Error("the 'tests' field for argument #" + i + " of " + obj_name + " should be an array"); if (arg.type === "uint32" && arg.kind === "input" && arg.interface_index !== undefined) length_args_available[arg.name] = true; if (arg.type.startsWith("buffer") && arg.kind === "input" && typeof arg.size === "string") { arg.parsedSize = parseSize(arg.size); let [ kind, var_ ] = arg.parsedSize; if (kind == "Var" || kind == "Op") length_args_available[var_] = true; } }); func_obj.args.forEach(function(arg, i) { if (arg.type.startsWith("buffer") && typeof arg.size === "string" && arg.kind === "output") { arg.parsedSize = parseSize(arg.size); let [ kind, var_ ] = arg.parsedSize; if ((kind == "Var" || kind == "Op") && !(var_ in length_args_available)) { console.log(arg); console.log(length_args_available); throw Error("incorrect 'size' field value (" + arg.size + ") for argument #" + i + " of " + obj_name + " in api.json"); } } }); if (func_obj.return === undefined) { throw Error("please provide a 'return' field for " + obj_name + " in api.json"); } }; }; }; // The module is encapsulated inside a closure to prevent anybody from accessing // the WebAssembly memory. var HaclWasm = (function() { 'use strict'; var isInitialized = false; var Module = {}; // We defined a few WASM-specific "compile-time macros". var my_imports = { EverCrypt_TargetConfig: (mem) => ({ hacl_can_compile_vale: 0, hacl_can_compile_vec128: 0, hacl_can_compile_vec256: 0, has_vec128_not_avx: () => false, has_vec256_not_avx2: () => false, }), }; // The WebAssembly modules have to be initialized before calling any function. // To be called only if isInitialized == false. var loadWasm = async (modules) => { if (!isInitialized) { Module = await loader.link( my_imports, await getModulesPromise(modules) ); isInitialized = true; } }; /* Inside WebAssembly, the functions only take pointers to memory and integers. However, we want to expose the functions of the wasm module with a nice Javascript API that manipulates ArrayBuffers. In order to do that, we have to describe the Javascript prototype of each function that we expose. The functions can take and return multiple objects that can be buffers, integers or booleans. The buffers can either have a fixed length (and in that case we check dynamically whether they have the correct length), or have a variable length (and we have to pass that length as an additional parameter to WebAssembly). In order to match the Javascript API with the actual calls to WebAssembly functions, we have to describe the correspondence between the two in the `api.json` file. The scheme of the JSON file is the following : - `module`, this module name will be shown in the JS API - `function`, this function name will be shown in the JS API - `module`, the name of the WebAssembly file where to find the function - 'name', the name of the WebAssembly export corresponding to the function - 'args', the list of the WebAssembly arguments expected by the function - 'name', the name of the argument which will be shown in the JS Doc - 'kind', either `input` or `output` of the function - 'type', either 'int', 'boolean', 'buffer', 'buffer(uint32)', 'buffer(uint64)', or the name of a struct starting with an uppercase; for the latter case, this is understood to be a pointer (the WASM API does not take structs by value), and we assume the type is described in layouts.json -- in that case, kind is implicitly assumed to be input, and kind == "output" is understood to mean input-output - 'size', see grammar of size fields above - 'interface_index', for all `input` that should appear in JS, position inside the argument list of the JS function - 'tests', a list of values for this arguments, each value corresponding to a different test case - 'return', the return type of the WebAssembly function - 'custom_module_name', if true, it signifies that the prefix of the name of the WebAssembly function does not coincide with the name of the WebAssembly module; the module name will not be used when calling it, instead 'name' will contain the full name of the function */ var array_type = function(type) { switch (type) { case "buffer": return Uint8Array; case "buffer(uint32)": return Uint32Array; case "buffer(uint64)": return BigUint64Array; default: throw new Error("Unknown array type: "+type); } } var cell_size = type => array_type(type).BYTES_PER_ELEMENT; var check_array_type = function(type, candidate, length, name) { if (!(candidate instanceof array_type(type)) || candidate.length !== length) { throw new Error( "name: Please ensure the argument " + name + " has length " + length + " and is a " + array_type(type) ); } }; var copy_array_to_stack = function(type, array, i) { // This returns a suitably-aligned pointer. var pointer = loader.reserve(Module.Karamel.mem, array.length*cell_size(type), cell_size(type)); (new Uint8Array(Module.Karamel.mem.buffer)).set(new Uint8Array(array.buffer), pointer); // console.log("argument "+i, "stack pointer got", loader.p32(pointer)); // console.log(array, array.length); // console.log("source", array.buffer); // loader.dump(Module.Karamel.mem, 2048, 0x13000); return pointer; }; // len is in number of elements var read_memory = function(type, ptr, len) { // TODO: faster path with aligned pointers? var result = new ArrayBuffer(len*cell_size(type)); // console.log("New memory buffer", type, len, len*cell_size(type)); (new Uint8Array(result).set(new Uint8Array(Module.Karamel.mem.buffer) .subarray(ptr, ptr + len*cell_size(type)))); // console.log(result); return new (array_type(type))(result); }; // HELPERS FOR HEAP LAYOUT // ----------------------- // Filled out via a promise. var layouts; var heapReadBlockSize = (ptr) => { var m32 = new Uint32Array(Module.Karamel.mem.buffer) return m32[ptr/4-2]-8; }; // We adopt a uniform layout and length-tag buffers upon copying them onto the // stack. This allows reading back layouts safely after they're modified. var heapWriteBlockSize = (ptr, sz) => { var m32 = new Uint32Array(Module.Karamel.mem.buffer) return m32[ptr/4-2] = sz + 8; }; var heapReadBuffer = (type, ptr) => { // Pointer points to the actual data, header is 8 bytes before, length in // header includes header. Heap base pointers are always aligned on 8 byte // boundaries, but inner pointers (e.g. within a struct) are aligned on // their size. if (!((ptr % cell_size(type)) == 0)) throw new Error("malloc violation (1)"); let block_size = heapReadBlockSize(ptr); if (!(block_size % cell_size(type) == 0)) throw new Error("malloc violation (2)"); let len = block_size / cell_size(type); // console.log("pointer:", loader.p32(ptr), "header:", loader.p32(ptr-8), "len:", loader.p32(len)); return read_memory(type, ptr, len); }; var heapReadInt = (typ, ptr) => { switch (typ) { case "A8": var m8 = new Uint8Array(Module.Karamel.mem.buffer); return m8[ptr]; case "A32": if (!(ptr % 4) == 0) throw new Error("malloc violation (3)"); var m32 = new Uint32Array(Module.Karamel.mem.buffer); return m32[ptr/4]; case "A64": if (!(ptr % 8) == 0) throw new Error("malloc violation (4)"); var m64 = new BigUint64Array(Module.Karamel.mem.buffer); return m64[ptr/8]; default: throw new Error("Not implemented: "+typ); } }; var heapWriteInt = (typ, ptr, v) => { switch (typ) { case "A8": var m8 = new Uint8Array(Module.Karamel.mem.buffer); m8[ptr] = v; break; case "A32": if (!(ptr % 4) == 0) throw new Error("malloc violation (3)"); var m32 = new Uint32Array(Module.Karamel.mem.buffer); m32[ptr/4] = v; break; case "A64": if (!(ptr % 8) == 0) throw new Error("malloc violation (4)"); var m64 = new BigUint64Array(Module.Karamel.mem.buffer); m64[ptr/8] = v; break; default: throw new Error("Not implemented: "+typ); } }; // Fast-path for arrays of flat integers. var heapReadBlockFast = (int_type, ptr) => { switch (int_type) { case "A8": return heapReadBuffer("buffer", ptr); case "A32": return heapReadBuffer("buffer(uint32)", ptr); case "A64": return heapReadBuffer("buffer(uint64)", ptr); default: throw new Error("Not implemented: "+int_type); } }; // Fast-path for arrays of flat integers. var heapWriteBlockFast = (int_type, ptr, arr) => { // console.log(arr); (new Uint8Array(Module.Karamel.mem.buffer)).set(new Uint8Array(arr.buffer), ptr); }; // Eventually will be mutually recursive once Layout is implemented (flat // packed structs). var heapReadType = (runtime_type, ptr) => { // console.log("headReadType", runtime_type, loader.p32(ptr)); let [ type, data ] = runtime_type; switch (type) { case "Int": return heapReadInt(data[0], ptr); case "Pointer": if (data[0] == "Int") return heapReadBlockFast(data[1][0], heapReadInt("A32", ptr)); else if (data[0] == "Layout") return heapReadLayout(data[1], heapReadInt("A32", ptr)); // pass-through default: throw new Error("Not implemented: "+type+","+data); } }; var heapWriteType = (runtime_type, ptr, v) => { // console.log("heapWriteType", runtime_type, loader.p32(ptr), v); let [ type, data ] = runtime_type; switch (type) { case "Int": heapWriteInt(data[0], ptr, v); break; case "Pointer": if (data[0] == "Int") { let sz = v.buffer.byteLength; // NB: could be more precise with alignment, I guess let dst = loader.reserve(Module.Karamel.mem, sz + 8, 8) + 8; heapWriteInt("A32", ptr, dst); heapWriteBlockFast(data[1][0], dst, v); heapWriteBlockSize(dst, sz); break; } else if (data[0] == "Layout") { let dst = stackWriteLayout(data[1], v); heapWriteInt("A32", ptr, dst); break; } // pass-through default: throw new Error("Not implemented: "+type); } }; var lFlatIsTaggedUnion = data => { if (data.fields.length == 2 && data.fields[0][0] == "tag" && data.fields[1][0] == "val") { let [ tag_name, [ tag_ofs, [ tag_type, [ tag_width ]]]] = data.fields[0]; if (!(tag_name == "tag" && tag_ofs == "0" && tag_type == "Int" && tag_width == "A32")) throw new Error("Inconsistent tag"); let [ val_name, [ val_ofs, [ val_type, val_cases]]] = data.fields[1]; if (!(val_name == "val" && val_ofs == "8" && val_type == "Union")) throw new Error("Inconsistent val"); return true; } else { return false; } }; var taggedUnionGetCase = (data, tag) => { let [ val_name, [ val_ofs, [ val_type, val_cases]]] = data.fields[1]; return val_cases[tag]; }; var heapReadLayout = (layout, ptr) => { // console.log("heapReadLayout", layout, loader.p32(ptr)); let [ tag, data ] = layouts[layout]; switch (tag) { case "LFlat": if (lFlatIsTaggedUnion(data)) { let tag = heapReadInt("A32", ptr); return ({ tag, val: heapReadType(taggedUnionGetCase(data, tag), ptr + 8) }); } else { let o = {}; data.fields.forEach(([field, [ ofs, typ ]]) => o[field] = heapReadType(typ, ptr + ofs) ); return o; } default: throw new Error("Not implemented: "+tag); } }; var heapWriteLayout = (layout, ptr, v) => { let [ tag, data ] = layouts[layout]; // console.log(v); switch (tag) { case "LFlat": if (lFlatIsTaggedUnion(data)) { heapWriteInt("A32", ptr, v.tag); heapWriteType(taggedUnionGetCase(data, v.tag), ptr + 8, v.val); } else { data.fields.forEach(([field, [ ofs, typ ]]) => { // console.log("Writing", v[field]); heapWriteType(typ, ptr + ofs, v[field]); }); } break; default: throw new Error("Not implemented: "+tag); } }; var stackWriteLayout = (layout, v) => { // console.log("stackWriteLayout", layout, v); let [ tag, data ] = layouts[layout]; switch (tag) { case "LFlat": let ptr = loader.reserve(Module.Karamel.mem, data.size, 8); heapWriteLayout(layout, ptr, v); return ptr; default: throw new Error("Not implemented: "+tag); } }; // END HELPERS FOR HEAP LAYOUT // The object being filled: // - first level of keys = modules, // - second level of keys = functions within a module var api_obj = {}; // This is the main logic; this function is partially applied to its // first two arguments for each API entry. We assume JITs are working well // enough to make this efficient. var callWithProto = function(proto, args) { var expected_args_number = proto.args.filter(function(arg) { return arg.interface_index !== undefined; }).length; if (args.length != expected_args_number) { throw Error("wrong number of arguments to call the F*-wasm function " + proto.name + ": expected " + expected_args_number + ", got " + args.length); } var memory = new Uint32Array(Module.Karamel.mem.buffer); var sp = memory[0]; // Integer arguments are either // - user-provided, in which case they have an interface_index // - automatically determined, in which case they appear in the `size` field // of another buffer argument. // In a first pass, we need to figure out the value of all integer // arguments to enable lookups by name. var args_int32s = {}; proto.args.forEach(function(arg) { if (arg.type.startsWith("buffer") && typeof arg.size === "string" && arg.interface_index !== undefined && arg.kind === "input") { // API contains e.g.: // { "name": "len" }, // { "name": "buf", "type": "buffer", "size": "len", "interface_index": 3, "kind": "input" } // We need to figure out `len` automatically since it doesn't have an // interface index, meaning it isn't one of the arguments passed to the // high-level API. We know `buf` is the second argument passed to the // function, and thus allows us to fill out `len`. let [ var_, var_value ] = invertSize(arg.parsedSize, args[arg.interface_index].length); // console.log("Determined "+var_+"="+var_value); if (var_ in args_int32s && var_value != args_int32s[var_]) throw new Error("Inconsistency in sizes; previously, "+var_+"="+args_int32s[var_]+"; now "+var_value); args_int32s[var_] = var_value; } else if (arg.interface_index !== undefined) { // API contains e.g.: // { "name": "len", "interface_index": 3 }, // { "name": "buf", "type": "buffer", "size": "len", "kind": "output" } // We know we will need `len` below when trying to allocate an array for // `output` -- insert it into the table. // Note: we are quite lax and don't require that a length be a uint32, // it's sometimes useful to allow it to be anything, like an address. args_int32s[arg.name] = args[arg.interface_index]; } }); // We have determined the value of all user-provided and synthesized // (computed) integer lengths. Now what happens with lengths is: // - when allocating a variable-length output buffer, we compute the // corresponding size via evalSize, passing it the args_int32s in case the // size field of the output buffer refers to a variable // - when computing the value of an integer argument that is not // user-provided (i.e. has no interface_index), we look it up in // args_int32s too // This returns the effective arguments for the function call (all integers, // some of which may be pointers on the stack). It has the side effect of // growing the stack and copying the input buffers onto it. var args = proto.args.map(function(arg, i) { let debug = (type, x) => { // console.log("Argument", i, type, loader.p32(x)); return x; }; if (arg.type.startsWith("buffer")) { var size; if (typeof arg.size === "string") { size = evalSize(arg.parsedSize, args_int32s, api_obj); } else { size = arg.size; } var arg_byte_buffer; if (arg.kind === "input") { var func_arg = args[arg.interface_index]; arg_byte_buffer = new (array_type(arg.type))(func_arg); } else if (arg.kind === "output") { arg_byte_buffer = new (array_type(arg.type))(size); } check_array_type(arg.type, arg_byte_buffer, size, arg.name); // TODO: this copy is un-necessary in the case of output buffers. return debug("array", copy_array_to_stack(arg.type, arg_byte_buffer, i)); } if (arg.type === "bool" || arg.type === "uint32") { if (arg.interface_index === undefined) { // Variable-length argument, determined via first pass above. return debug("int(auto)", args_int32s[arg.name]); } else { // Regular integer argument, passed by the user. return debug("int", args[arg.interface_index]); } } // Layout... TODO: the "kind" field is unused because we do not have the // case where the caller allocates empty space for a layout. if (arg.type[0].toUpperCase() == arg.type[0]) { let func_arg = args[arg.interface_index]; return debug("layout", stackWriteLayout(arg.type, func_arg)); } throw Error("Unimplemented ! ("+proto.name+")"); }); // console.log("Arguments laid out in WASM memory"); // args.forEach((arg, i) => console.log("argument "+i, loader.p32(arg))); // loader.dump(Module.Karamel.mem, 2048, args[0] - (args[0] % 0x20)); // Calling the wasm function ! if (proto.custom_module_name) { var func_name = proto.name; } else { var func_name = proto.module + "_" + proto.name; } if (!(proto.module in Module)) throw new Error(proto.module + " is not in Module"); if (!(func_name in Module[proto.module])) { console.log(Object.keys(Module[proto.module])); throw new Error(func_name + " is not in Module["+proto.module+"]"); } var call_return = Module[proto.module][func_name](...args); // console.log("After function call"); // loader.dump(Module.Karamel.mem, 256, args[0] - (args[0] % 0x20)); //loader.dump(Module.Karamel.mem, 256, call_return - (call_return % 0x20)); // Populating the JS buffers returned with their values read from Wasm memory var return_buffers = args.map(function(pointer, i) { let arg = proto.args[i]; if (arg.type[0].toUpperCase() == arg.type[0] && arg.kind == "output") { // Layout return heapReadLayout(arg.type, pointer); } else if (arg.kind === "output") { // Output buffer, allocated by us above, now need to read its contents // out. var size; if (typeof arg.size === "string") { size = evalSize(arg.parsedSize, args_int32s, api_obj); } else { size = arg.size; } // console.log("About to read", protoRet.type, loader.p32(pointer), size); let r = read_memory(arg.type, pointer, size); // console.log(r); return r; } else { return null; } }).filter(v => v !== null); // Resetting the stack pointer to its old value memory[0] = sp; if ("kind" in proto.return && proto.return.kind === "layout") { // Heap-allocated value let read = proto.return.type.startsWith("buffer") ? heapReadBuffer : heapReadLayout; let r = read(proto.return.type, call_return); memory[Module.Karamel.mem.buffer.byteLength/4-1] = 0; return r; // loader.dump(Module.Karamel.mem, 2048, Module.Karamel.mem.buffer.byteLength - 2048); // console.log(loader.p32(call_return), r, JSON.stringify(layouts[proto.return.type], null, 2)); // let ptr = stackWriteLayout(proto.return.type, r); // console.log(loader.p32(ptr)); // loader.dump(Module.Karamel.mem, 2048, 0x13000); // throw new Error(func_name+": non-buffer return layout not implemented"); } if (proto.return.type === "bool") { return [call_return === 1, return_buffers].flat(); } if (proto.return.type === "uint32") { return [call_return >>> 0, return_buffers].flat(); } if (proto.return.type === "uint64") { // krml convention: uint64s are sent over as two uint32s // console.log(call_return); return [BigInt(call_return[0]>>>0) + (BigInt(call_return[1]>>>0) << 32n), return_buffers].flat(); } if (proto.return.type === "void") { return return_buffers; } throw new Error(func_name+": Unimplemented ! "+proto.return.type); }; var getInitializedHaclModule = async function (modules) { if (!isInitialized) { // Load all WASM modules from network (web) or disk (node). await loadWasm(modules); // Write into the global. layouts = await layouts_promise; // Initial API validation (TODO: disable for release...?) let api_json = await api_promise; validateJSON(api_json); // We follow the structure of api.json to expose an object whose structure // follows the keys of api.json; each entry is a partial application of // `callWithProto` (generic API wrapper) to its specific entry in api.json // held in `api_json[key_module][key_func]`. for (let key_module in api_json) { for (let key_func in api_json[key_module]) { if (api_obj[key_module] == null) { api_obj[key_module] = {}; } api_obj[key_module][key_func] = function(...args) { return callWithProto(api_json[key_module][key_func], args); }; }; }; } return Promise.resolve(api_obj); }; return { getInitializedHaclModule: getInitializedHaclModule, dump: (sz, ofs) => loader.dump(Module.Karamel.mem, sz, ofs) }; })(); if (typeof module !== "undefined") { module.exports = HaclWasm; }
const router = require('express').Router(); const apiRoutes = require('./api'); const homeRoutes = require('./homeRoutes'); const adminRoutes = require('./adminRoutes'); router.use('/', homeRoutes); // user website router.use('/api', apiRoutes); // api router.use('/admin', adminRoutes); //admin site module.exports = router;
/** 对jquery的基础配置 @module @exports undefined **/ define([ 'jquery', 'underscore', 'base/detector' ], function($, _, detector){ // Wrap in a document ready call, because jQuery writes // cssHooks at this time and will blow away your functions // if they exist. $(function($){ var validProp, prop, validFormOf = detector.validFormOf; validProp = { transformOriginX: null, transformOriginY: null, transform: null, userSelect: null }; for(prop in validProp){ if( !validProp.hasOwnProperty(prop) ) continue; validProp[prop] = validFormOf(prop); } $.cssHooks.transformOriginX = { get: function(elem, computed, extra){ if(validProp.transformOriginX){ return elem.style[ validProp.transformOriginX ]; } }, set: function(elem, value){ if(validProp.transformOriginX){ elem.style[ validProp.transformOriginX ] = value; } } }; $.cssHooks.transformOriginY = { get: function(elem, computed, extra){ if(validProp.transformOriginY){ return elem.style[ validProp.transformOriginY ]; } }, set: function(elem, value){ if(validProp.transformOriginY){ elem.style[ validProp.transformOriginY ] = value; } } }; $.cssHooks.backgroundImage = { get: function(elem, computed, extra){ return computed.slice(4, -1); }, set: function(elem, value){ elem.style.backgroundImage = 'url(' + value + ')'; } }; /** 用jquery的 `.css()` 方法设置或获取css属性 `transform` 时: 支持自动添加适当的浏览器厂商前缀; 支持设置多个变换函数,而只会覆盖同名的变换函数,不覆盖不同名的; **/ $.cssHooks.transform = { get: function(elem, computed, extra){ return elem.style[validProp.transform]; }, // TODO: // transform属性中的变换函数的顺序会对变换产生影响, // 不要改变变换函数的顺序 set: function(elem, newVal){ var MATCHER = /^(\w)+\(.+\)$/i, SPLITER = ' '; var prop = validProp.transform, val, i, j, funcName; // 如果新值为matrix矩阵或 `none` ,直接设置 if( newVal.search(/(matrix)|(none)/i) !== -1 ){ elem.style[prop] = newVal; return; } val = elem.style[prop]; if(val){ val = val.trim(); if(val === 'none'){ elem.style[prop] = newVal; return; } // 如果旧值中,存在一个变换函数与新值中的某个变换函数同名, // 则移除旧值中的这个变换函数, // 并将新值中相应的变换函数移出,添加到旧值末尾。 // 添加到末尾,有利于在连续设置同一个变换函数时尽快遍历到该函数,而当新值中没有变换函数时,即可提前结束遍历 newVal = newVal.split(SPLITER); val = val.split(SPLITER); i = val.length; while(i--){ if( !(funcName = val[i].match(MATCHER)[1]) ) continue; j = newVal.length; while(j--){ if(newVal[j].indexOf(funcName) === -1) continue; val.splice(i, 1); val.push(newVal.splice(j, 1)); break; } if(!newVal.length) break; } // 如果新值中还有变换函数,添加到旧值末尾 if(newVal.length){ val.concat(newVal); } // 此时旧值就是新值了 elem.style[prop] = val; } else{ elem.style[prop] = newVal; return; } } }; $.cssHooks['userSelect'] = { get: function(elem, computed, extra){ return elem.style[validProp.userSelect]; }, set: function(elem, newVal){ elem.style[validProp.userSelect] = newVal; } }; }); // 显式的写出来返回undefined,是因为此模块约定为返回undefined, // 避免被修改成返回其他的东西。 // 使用此模块的地方已经将此模块的输出视为undefined return undefined; });
import React from 'react'; import "font-awesome/css/font-awesome.css"; import FA from "react-fontawesome"; import LegendColumn from './legendElements/legendColumn.js' export default class Legend extends React.Component { constructor(props) { super(props); this.state = { visuals: 'chevron-down' }; this.visualHandle = this.visualHandle.bind(this); } visualHandle() { if (this.state.visuals === "chevron-down") { this.setState({ visuals: "chevron-right" }); } else { this.setState({ visuals: "chevron-down" }); } } render() { var main = ( <div className="card legendCard"> <div id="control" className="card-header legendCardHeader card-link mousePointer" data-toggle="collapse" href="#collapseLegend" onClick={this.visualHandle} > <button type="button" className="link-button" > <h4 className="text-center text-muted"> Legende <FA className="faIcon" name={this.state.visuals} /> </h4> </button> </div> <div id="collapseLegend" className="collapse show"> <div className="card-body"> <div className="row justify-content-center"> { this.props.information.notification.map((graph, i) => <LegendColumn name={graph.name} color={graph.wst} style={graph.strokeIndex} key={i}></LegendColumn> ) } </div> <div className="row justify-content-center"> { this.props.information.commands.map((graph, i) => <LegendColumn name={graph.name} color={graph.wst} style={graph.strokeIndex} key={i}></LegendColumn> ) } </div> <div className="row justify-content-center"> { this.props.information.power.map((graph, i) => <LegendColumn name={graph.name} color={graph.wst} style={graph.strokeIndex} key={i}></LegendColumn> ) } </div> </div> </div> </div> ) return main; } }
(() => { function SetupCanvas() { webglApp.ConfigureWebGL(); webglApp.ColorCanvas(0.365, 0.58, 0.984, 1.0); } function Draw() { SetupCanvas(); let cameraTransform = camera.GetCameraTransform(); let projectionTransform = camera.GetProjectionTransform(); scene.Draw(cameraTransform, projectionTransform); window.requestAnimationFrame(Draw); } let scene = new Scene(); scene.AddEntity(new Mario(marioObjectAttributes, texturingVertexShader, texturingFragmentShader, [marioTextureImageSource])); scene.AddEntity(new UndergroundBackground(planeObjectAttributes, shadingVertexShader, shadingFragmentShader)); scene.AddEntity(new Skybox(cubeObjectAttributes, skyboxVertexShader, skyboxFragmentShader, skyboxImageSource)); scene.AddEntityCollection(new Pipes(pipeObjectAttributes, shadingVertexShader, shadingFragmentShader)); scene.AddEntityCollection(new Platforms(platformObjectAttributes, texturingVertexShader, texturingFragmentShader, [platformTextureImageSource])); scene.AddEntityCollection(new Coin(coinObjectAttributes, texturingVertexShader, texturingFragmentShader, [coinTextureImageSource])); scene.AddEntityCollection(new Ground(groundBlockObjectAttributes, bumpMapTextureVertexShader, bumpMapTextureFragmentShader, [groundBlockTextureImageSource, groundBumpMap, groundSpecularMap])); scene.AddEntityCollection(new Underground(groundBlockObjectAttributes, bumpMapTextureVertexShader, bumpMapTextureFragmentShader, [undergroundBlockTextureImageSource, groundBumpMap, groundSpecularMap])); scene.AddEntityCollection(new UndergroundBrick(brickObjectAttributes, bumpMapTextureVertexShader, bumpMapTextureFragmentShader, [undergroundBrickTextureImageSource, brickBumpMap, brickSpecularMap])); scene.AddEntityCollection(new Brick(brickObjectAttributes, bumpMapTextureVertexShader, bumpMapTextureFragmentShader, [brickTextureImageSource, brickBumpMap, brickSpecularMap])); window.requestAnimationFrame(Draw); })();
angular.module('console').filter('shortName', function() { return function(input) { return (input&&input.length>10 )? (input.slice(0,10)+'...') : input; }; }); angular.module('console').filter('noNameFilter', function() { return function(input) { return input ? input: '无'; }; }); angular.module('console').filter('trueORfalse', function() { return function(flag) { switch(flag) { case 'true': return "成功"; case "false": return "失败"; default: return "未知"; } }; }); angular.module('console').filter('phoneFilter', function() { return function(phone) { if(phone != null && phone.length > 0){ return phone.substring(0,3) + "****" + phone.substring(7,4); }else{ return phone; } }; }); angular.module('console').filter('amount',["$filter",function($filter) { return function(number,format) { if(number==0){ return 0; } else{ return $filter('number')(number,format); } }; }]); angular.module('console').filter('partial', function(){ return function(number){ if(isNaN(number)){ return '0%'; }else{ var num = new Number(number * 100); var result = num.toFixed(2); return result + '%'; } }; });
var game = new Phaser.Game(240, 400, Phaser.CANVAS, 'game'); game.States = {}; game.States.boot = function() { this.preload = function() { if(typeof(GAME) !== "undefined") { this.load.baseURL = GAME + "/"; } if(!game.device.desktop){ this.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT; this.scale.forcePortrait = true; this.scale.refresh(); } game.load.image('loading', 'assets/preloader.gif'); }; this.create = function() { game.state.start('preload'); }; }; game.States.preload = function() { this.preload = function() { var preloadSprite = game.add.sprite(10, game.height/2, 'loading'); game.load.setPreloadSprite(preloadSprite); game.load.image('background', 'assets/bg.png'); game.load.image('btnStart', 'assets/btn-start.png'); game.load.image('btnRestart', 'assets/btn-restart.png'); game.load.image('logo', 'assets/logo.png'); game.load.image('btnTryagain', 'assets/btn-tryagain.png'); }; this.create = function() { game.state.start('main'); }; }; game.States.main = function() { this.create = function() { // 背景 game.add.tileSprite(0, 0, game.width, game.height, 'background'); // logo var logo = game.add.image(0, 0, 'logo'); logo.reset((game.width - logo.width) / 2, (game.height - logo.height) / 2 - 50); var startBtn = game.add.button(0, 0, 'btnStart', this.startGame, this); startBtn.reset((game.width - startBtn.width) / 2, (game.height - startBtn.height) / 2 + 100); }; this.startGame = function() { game.state.start('start'); }; }; game.States.start = function() { this.create = function() { // 背景 game.add.tileSprite(0, 0, game.width, game.height, 'background'); this.score = 0; this.best = 0; var titleStyle = { font: "bold 12px Arial", fill: "#4DB3B3", boundsAlignH: "center" }; var scoreStyle = { font: "bold 20px Arial", fill: "#FFFFFF", boundsAlignH: "center" }; //score var scoreSprite = game.add.sprite(10, 10); var scoreGraphics = game.add.graphics(0, 0); scoreGraphics.lineStyle(5, 0xA1C5C5); scoreGraphics.beginFill(0x308C8C); scoreGraphics.drawRoundedRect(0, 0, 70, 50, 10); scoreGraphics.endFill(); scoreSprite.addChild(scoreGraphics); var scoreTitle = game.add.text(0, 5, "SCORE", titleStyle); scoreTitle.setTextBounds(0, 0, 70, 50); scoreSprite.addChild(scoreTitle); this.scoreText = game.add.text(0, 20, this.score, scoreStyle); this.scoreText.setTextBounds(0, 0, 70, 50); scoreSprite.addChild(this.scoreText); //best var bestSprite = game.add.sprite(90, 10); var bestGraphics = game.add.graphics(0, 0); bestGraphics.lineStyle(5, 0xA1C5C5); bestGraphics.beginFill(0x308C8C); bestGraphics.drawRoundedRect(0, 0, 70, 50, 10); bestGraphics.endFill(); bestSprite.addChild(bestGraphics); var bestTitle = game.add.text(0, 5, "BEST", titleStyle); bestTitle.setTextBounds(0, 0, 70, 50); bestSprite.addChild(bestTitle); this.bestText = game.add.text(0, 20, this.best, scoreStyle); this.bestText.setTextBounds(0, 0, 70, 50); bestSprite.addChild(this.bestText); // rerun var restartBtn = game.add.button(180, 15, 'btnRestart', this.rerunGame, this); // mainarea var mainAreaSprite = game.add.sprite(10, 80); var mainAreaBackGraphics = game.add.graphics(0, 0); mainAreaBackGraphics.beginFill(0xADA79A, 0.5); mainAreaBackGraphics.drawRoundedRect(0, 0, 220, 220, 10); mainAreaBackGraphics.endFill(); mainAreaSprite.addChild(mainAreaBackGraphics); // add swipe check this.swipe = new Swipe(this.game, this.swipeCheck); // 定义一组color this.colors = { 2: 0x49B4B4, 4: 0x4DB574, 8: 0x78B450, 16: 0xC4C362, 32: 0xCEA346, 64: 0xDD8758, 128: 0xBF71B3, 256: 0x9F71BF, 512: 0x7183BF, 1024: 0x71BFAF, 2048: 0xFF7C80 }; // 初始化 this.rerunGame(); }; this.update = function() { if(this.canSwipe) { this.swipe.check(); } }; // 重来 this.rerunGame = function() { this.score = 0; this.scoreText.text = this.score; if(this.array) { for(var i=0; i<4; i++) { for(var j=0; j<4; j++) { if(this.array[i][j].sprite) { this.array[i][j].sprite.kill(); } } } } // 4x4 array this.array = []; for(var i=0; i<4; i++) { this.array[i] = []; for(var j=0; j<4; j++) { this.array[i][j] = {}; this.array[i][j].value = 0; this.array[i][j].x = i; this.array[i][j].y = j; } } // 是否响应swipe this.canSwipe = true; // start game this.generateSquare(); }; // 坐标转换 this.transX = function(x) { return 10+8*(x+1)+x*45+45/2; }; this.transY = function(y) { return 80+8*(y+1)+y*45+45/2; }; // 随机产生一个方块 this.generateSquare = function() { var x = Math.floor(Math.random() * 4); var y = Math.floor(Math.random() * 4); while(this.array[x][y].value != 0) { x = Math.floor(Math.random() * 4); y = Math.floor(Math.random() * 4); } var value = 2; if(Math.random() > 0.5) { value = 4; } this.placeSquare(x, y, value); }; // 在x,y位置放置一个值为value的方块 this.placeSquare = function(x, y, value) { var squareStyle = { font: "bold 20px Arial", fill: "#FFFFFF", boundsAlignH: "center", boundsAlignV: "middle" }; var square = game.add.sprite(); square.reset(this.transX(x), this.transY(y)); var squareBackground = game.add.graphics(-45/2, -45/2); squareBackground.beginFill(this.colors[value]); squareBackground.drawRoundedRect(0, 0, 45, 45, 5); squareBackground.endFill(); square.addChild(squareBackground); var squareText = game.add.text(-45/2, -45/2, value, squareStyle); squareText.setTextBounds(0, 0, 45, 45); square.addChild(squareText); this.array[x][y].value = value; this.array[x][y].sprite = square; square.anchor.setTo(0.5, 0.5); square.scale.setTo(0.0, 0.0); var tween = game.add.tween(square.scale).to({x:1.0, y:1.0}, 100, Phaser.Easing.Sinusoidal.InOut, true); tween.onComplete.add(function() { if(this.checkGameover()) { this.gameOver(); } }, this); }; // swipe的公共逻辑抽出 this.swipeCommon = function(i, j, arrNode, posJson, condition, nextArrNode, nextPosJson) { var that = this; var duration = 100; // 遇到了可以合并的 if(!arrNode.newNode && arrNode.value == this.array[i][j].value) { arrNode.value = arrNode.value * 2; arrNode.newNode = true; this.array[i][j].value = 0; this.score = this.score + arrNode.value; this.scoreText.text = this.score; if(this.score > this.best) { this.best = this.score; this.bestText.text = this.best; } // 渐渐透明后被kill掉 var t1 = game.add.tween(arrNode.sprite).to({alpha: 0}, duration, Phaser.Easing.Linear.None, true); t1.onComplete.add(function() { this.sprite.kill(); that.placeSquare(this.x, this.y, this.value); if(!that.canSwipe) { that.canSwipe = true; that.generateSquare(); } }, arrNode); var t2 = game.add.tween(this.array[i][j].sprite).to({alpha: 0}, duration, Phaser.Easing.Linear.None, true); t2.onComplete.add(function() { this.kill(); if(!that.canSwipe) { that.canSwipe = true; that.generateSquare(); } }, this.array[i][j].sprite); game.add.tween(this.array[i][j].sprite).to(posJson, duration, Phaser.Easing.Linear.None, true); arrNode.sprite = this.array[i][j].sprite; this.array[i][j].sprite = undefined; } else if(arrNode.value == 0) { arrNode.value = this.array[i][j].value; this.array[i][j].value = 0; var t = game.add.tween(this.array[i][j].sprite).to(posJson, duration, Phaser.Easing.Linear.None, true); t.onComplete.add(function() { if(!that.canSwipe) { that.canSwipe = true; that.generateSquare(); } }); arrNode.sprite = this.array[i][j].sprite; this.array[i][j].sprite = undefined; } else if(condition) { nextArrNode.value = this.array[i][j].value; this.array[i][j].value = 0; var t = game.add.tween(this.array[i][j].sprite).to(nextPosJson, duration, Phaser.Easing.Linear.None, true); t.onComplete.add(function() { if(!that.canSwipe) { that.canSwipe = true; that.generateSquare(); } }); nextArrNode.sprite = this.array[i][j].sprite; this.array[i][j].sprite = undefined; } }; // swipe的初始逻辑抽出 this.swipeInit = function() { this.canSwipe = false; game.time.events.add(Phaser.Timer.SECOND * 0.5, function() { if(!this.canSwipe) { this.canSwipe = true; } }, this); }; // swipe的结尾逻辑抽出 this.swipeDone = function() { for(var i=0; i<this.array.length; i++) { for(var j=0; j<this.array.length; j++) { this.array[i][j].newNode = undefined; } } }; this.swipeLeft = function() { this.swipeInit(); for(var i=1; i<this.array.length; i++) { for(var j=0; j<this.array.length; j++) { if(this.array[i][j].value != 0) { var index = i-1; while(index > 0 && this.array[index][j].value == 0) { index--; } this.swipeCommon(i, j, this.array[index][j], {x: this.transX(index), y: this.transY(j)}, index + 1 != i, this.array[index+1][j], {x: this.transX(index+1), y: this.transY(j)}); } } } this.swipeDone(); }; this.swipeUp = function() { this.swipeInit(); for(var i=0; i<this.array.length; i++) { for(var j=1; j<this.array.length; j++) { if(this.array[i][j].value != 0) { var index = j-1; while(index > 0 && this.array[i][index].value == 0) { index--; } this.swipeCommon(i, j, this.array[i][index], {x: this.transX(i), y: this.transY(index)}, index + 1 != j, this.array[i][index+1], {x: this.transX(i), y: this.transY(index+1)}); } } } this.swipeDone(); }; this.swipeRight = function() { this.swipeInit(); for(var i=this.array.length-2; i>=0; i--) { for(var j=0; j<this.array.length; j++) { if(this.array[i][j].value != 0) { var index = i+1; while(index < this.array.length-1 && this.array[index][j].value == 0) { index++; } this.swipeCommon(i, j, this.array[index][j], {x: this.transX(index), y: this.transY(j)}, index - 1 != i, this.array[index-1][j], {x: this.transX(index-1), y: this.transY(j)}); } } } this.swipeDone(); }; this.swipeDown = function() { this.swipeInit(); for(var i=0; i<this.array.length; i++) { for(var j=this.array.length-2; j>=0; j--) { if(this.array[i][j].value != 0) { var index = j+1; while(index < this.array.length-1 && this.array[i][index].value == 0) { index++; } this.swipeCommon(i, j, this.array[i][index], {x: this.transX(i), y: this.transY(index)}, index - 1 != j, this.array[i][index-1], {x: this.transX(i), y: this.transY(index-1)}); } } } this.swipeDone(); }; // swipe检测 this.swipeCheck = { up: this.swipeUp.bind(this), down: this.swipeDown.bind(this), left: this.swipeLeft.bind(this), right: this.swipeRight.bind(this) }; // 检测是否游戏结束 this.checkGameover = function() { // 如果16个格子没满,return false for(var i=0; i<this.array.length; i++) { for(var j=0; j<this.array.length; j++) { if(this.array[i][j].value == 0) { return false; } } } // 如果16个格子和周围格子有相同的值的,return false var d = [{dx: -1, dy: 0}, {dx: 1, dy: 0}, {dx: 0, dy: -1}, {dx: 0, dy: 1}]; for(var i=0; i<this.array.length; i++) { for(var j=0; j<this.array.length; j++) { for(var k=0; k<d.length; k++) { if(i+d[k].dx >= 0 && i+d[k].dx < this.array.length && j+d[k].dy >= 0 && j+d[k].dy < this.array.length && this.array[i][j].value == this.array[i+d[k].dx][j+d[k].dy].value) { return false; } } } } return true; }; // 游戏结束 this.gameOver = function() { if(!this.gameOverMask) { this.gameOverMask = game.add.sprite(0, 0); var mask = game.add.graphics(0, 0); mask.beginFill(0x000000, 0.5); mask.drawRect(0, 0, game.width, game.height); mask.endFill(); this.gameOverMask.addChild(mask); var gameOverTextStyle = { font: "bold 35px Arial", fill: "#FFFFFF", boundsAlignH: "center" }; var gameOverText = game.add.text(0, 100, "Game Over", gameOverTextStyle); gameOverText.setTextBounds(0, 0, game.width, game.height); this.gameOverMask.addChild(gameOverText); var gameOverBtn = game.add.button((game.width-206)/2, 200, 'btnTryagain', this.tryAgain, this); this.gameOverMask.addChild(gameOverBtn); } }; // try again this.tryAgain = function() { this.gameOverMask.kill(); this.gameOverMask = undefined; this.rerunGame(); }; }; game.state.add('boot', game.States.boot); game.state.add('preload', game.States.preload); game.state.add('main', game.States.main); game.state.add('start', game.States.start); game.state.start('boot');
import Document, { Html, Head, Main, NextScript } from "next/document"; class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps }; } render() { return ( <Html lang="en"> <Head> <link rel="preconnect" href="https://fonts.gstatic.com/" /> <link href="https://fonts.googleapis.com/css2?family=Barlow&family=Barlow+Condensed:wght@300&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossOrigin="anonymous" /> <link rel="stylesheet" href="./../node_modules/aos/dist/aos.css" /> </Head> <body> <Main /> <div className="offcanvas offcanvas-bottom" tabIndex="-1" id="offcanvasBottom" aria-labelledby="offcanvasBottomLabel" > <div className="offcanvas-header"> <h5 className="offcanvas-title" id="offcanvasBottomLabel"> Offcanvas bottom </h5> <button type="button" className="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close" ></button> </div> <div className="offcanvas-body small">...</div> </div> <NextScript> </NextScript> <script>AOS.init();</script> </body> </Html> ); } } export default MyDocument;
$(function () { var lastId = 0; window.localStorage.setItem('lastId','0'); var style = "left"; var flag = true; var L = 0; var prevUserId = 1; var obj = $('#mesages'); var allData = []; var h = 100; getContents(); //消息列表动画 var move = setInterval(function(){ var top = parseInt(obj.css('top')); top -= 10; obj.css('top',top+'px'); }, 10); setInterval(function(){ var top = parseInt(obj.css('top')); if(h-1080+top<100 && h > 1080){ getContents(); } },3000) function getContents(){ var len = obj.find('li').length; var top = parseInt(obj.css('top')); //console.log(len) if(len > 10){ var m = 0; for(var i=0;i<len-10;i++){ m += parseInt(obj.find('li').eq(i).height()) + 42; } m -= 42; obj.find('li').eq(len-10).prevAll().remove(); h -= m; obj.css('top',top+m+'px'); } var storageId = window.localStorage.getItem('lastId'); if(storageId !== lastId){ $.ajax({ type: 'get', url: 'http://wx.sagacn.com/didi180421/contents', data: {'lastId':lastId}, dataType: 'json', success: function(res){ window.localStorage.setItem('lastId',lastId); var data = res.data; L = data.length; userArr = data; for(var i=0;i<L;i++){ allData.push(data[i]); } var str = ''; var arr = []; if(L > 0){ obj.append(str); lastId = data[L-1].id; }else { var n = allData.length>20 ? 20 : allData.length; var i = 0; while(i<n){ var random = Math.floor(Math.random()*allData.length); if(!isInArray(arr, random)){ arr.push(random); i++; } data.push(allData[random]); } } for(var i=0;i<data.length;i++){ var userId = data[i].userId; if(prevUserId != userId){ flag = !flag; style = flag ? 'left' : 'right'; prevUserId = userId; } var nickName = data[i].info != null ? data[i].info.nickName : ''; var avatarLink = data[i].info != null ? data[i].info.avatarLink : ''; var content = data[i].chatContent ? data[i].chatContent : ''; var imageUrl = data[i].imageUrl; if(imageUrl){ str += '<li class="'+ style +'"> <div class="photo"> <img src="'+ avatarLink +'"> <p>' + nickName +'</p> </div> <div class="content"><img src="'+ imageUrl +'"></div> </li>'; h += 402; } if(content != ''){ str += '<li class="'+ style +'"> <div class="photo"> <img src="'+ avatarLink +'"> <p>' + nickName +'</p> </div> <div class="content"><span>'+ content +'</span></div> </li>'; h += 132; } } console.log(h) obj.append(str).height(h); } }) } } //按空格停止向上滑动,按回车继续向上滑动 document.onkeydown = function(e){ var code = e.keyCode; if (code === 32) { clearInterval(move); }else if (code === 13){ clearInterval(move); move = setInterval(function(){ var top = parseInt(obj.css('top')); top -= 10; obj.css('top',top+'px'); },10); } } function isInArray(arr,value){ for(var i = 0; i < arr.length; i++){ if(value === arr[i]){ return true; } } return false; } });
// service/Container.js // dependency container module.exports = class Container { constructor() { this.animation = { start: () => { const image = this.animation.Image(); new (require('../animation/main'))(image); }, Image: () => new (require('../animation/Image'))() }; this.common = { Navbar: page => new (require('../common/Navbar.js'))(page) }; this.page = { Contact: () => { var util = this.util.Util(); return new (require('../page/contact'))(util); } }; this.util = { Util: () => new (require('../util/Util'))() }; } };
/** * @file : app.js * @description : 程序入口文件 * @author : YanXianPing * @creatTime : 2020/10/29 16:07 */ /**----------------------------------------------- * express *----------------------------------------------*/ const express = require('express'); /**----------------------------------------------- * node modules *----------------------------------------------*/ const path = require('path'); const util = require('util'); /**----------------------------------------------- * 市面上第三方依赖 *----------------------------------------------*/ const compression = require('compression'); /**----------------------------------------------- * 公司规范的npm包 *----------------------------------------------*/ const tplHb = require('@npm-node/tplhb'); const hbHelpers = require('@npm-node/hbhelpers'); // TODO logger记录日志npm包 // TODO sentry哨兵npm包 /**----------------------------------------------- * routers *----------------------------------------------*/ const {IndexRouter} = require('./routers/indexRouter'); /**----------------------------------------------- * appConfig *----------------------------------------------*/ const {appName} = require('./app.config'); /**----------------------------------------------- * 业务代码 *----------------------------------------------*/ const app = express(); // compress all response,即开启gzip(Content-Encoding: gzip) app.use(compression()); // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // (start) : 静态资源服务器 // (end) // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // (start) : 设置模板 tplHb(app, { viewsPath: path.resolve(__dirname, 'views'), helpers: hbHelpers, partialsDirectoryName: 'partials', getTemplateFromCache: true }); // 默认模板引擎 app.set('view engine', 'hb'); // (end) // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // (start) : 路由 app.use(`/${appName}/`, IndexRouter); // (end) // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // (start) : 心跳检测 app.get(/heartbeat$/, (req, res, next) => { res.send(`[${new Date().toLocaleString()}] project (${appName}) heartbeat is alive`); }); // (end) // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // (start) : 最后的中间件兜底,当请求走到这一步肯定是有问题的~~~ // (end) // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< module.exports = app;
import React from 'react' import { Link } from 'react-router-dom' class GameEdit extends React.Component { constructor() { super(); this.state = { Name: "", Date: "" } this.editGame = this.editGame.bind(this) this.updateField = this.updateField.bind(this) } editGame() { const game = Object.assign({}, this.state) fetch(`/api/games/${this.props.match.params.gameid}`, { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(game) }).then(() => this.props.history.goBack()) } updateField(e) { this.setState({ [e.target.name]: e.target.value, }); } getGame() { fetch(`/api/games/${this.props.match.params.gameid}`, { credentials: 'include' }).then((res) => res.json()).then((json) => { this.setState(json[0]) }) } componentDidMount() { this.getGame() } render() { return <div className="game-edit"> <div className="form-input"> <label>Game Title</label> <input name="Name" onChange={this.updateField} type="text" value={this.state.Name} /> </div> <div className="form-input"> <label>Game Date</label> <input name="Date" onChange={this.updateField} type="date" value={this.state.Date} /> </div> <button className="btn btn-primary" onClick={this.editGame}>edit</button> </div> } } export default GameEdit
import { User } from '../models' // 通过 koa-router 创建 api 路由 // 返回的数据均为 json export default function (router) { // 登录 router.post('/api/signin', async (ctx, next) => { // 解析 request body 中的参数 let { email, password } = ctx.request.body ctx.body = await User.login(ctx, email, password) }); // 注册 router.post('/api/signup', async (ctx, next) => { let { username, email, password, repassword } = ctx.request.body if (password !== repassword) { ctx.body = { ok: false, msg: '两次密码不一样'}; } else { let user = new User({ username, email, password, }) ctx.body = await User.add(ctx, user) } }) //获取当前登录用户 router.get('/api/user', async (ctx, next) => { if (ctx.session.user) { console.log(ctx.session.user) ctx.body = { ok: true, msg: '已登录', user: ctx.session.user } } else { ctx.body = { ok: false, msg: '未登录' } } }) // 退出登录 router.get('/api/logout', (ctx, next) => { //删除用户的 session 即可退出登录 delete ctx.session.user ctx.body = { ok: true, msg: '退出成功' } }) }
import axios from 'axios' import { useState, useEffect } from 'react' export default function useFetch(options) { const [response, setResponse] = useState(null) const [error, setError] = useState(null) const [loading, setLoading] = useState(true) useEffect(() => { const fetchData = async () => { try { const res = await axios(options) const json = await res.data setResponse(json) setLoading(false) } catch (error) { const obj = {} setLoading(false) if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx obj.data = error.response.data obj.status = error.response.status obj.headers = error.response.headers obj.message = error.message } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request) obj.message = 'Connection refused, may be API is not running or having some issue on the server end.' } else { // Something happened in setting up the request that triggered an Error obj.message = error.message } setError(obj) } } fetchData() }, []) return [response, error, loading] }
(function($) { var $window = $(window); var $body = $('body'); var $header = $('#header'); var $main = $('#main'); var $banner = $('#banner'); $('body').addClass('is-loading'); $(window).on('load pageshow', function() { $('body').removeClass('is-loading'); }); $banner.scrollex({ bottom: "10%", enter: function() { $header.removeClass('alt'); }, leave: function() { $header.addClass('alt'); } }); $('.go-menu').on('click', function(event) { event.preventDefault(); event.stopPropagation(); $('body').addClass('is-menu-visible'); }); $('#menu .close, body').on('click', function(event) { event.preventDefault(); event.stopPropagation(); $('body').removeClass('is-menu-visible'); }).on('keydown', function(event) { if (event.keyCode == 27) { $('body').removeClass('is-menu-visible'); } }); $('#menu ul a').on('click', function(event){ $('body').removeClass('is-menu-visible'); var _this = $(this); window.setTimeout(function(){ window.location.href = _this.attr('href'); }, 250); }); })(jQuery);
var Store = require('flux/utils').Store, Dispatcher = require('../dispatcher'), TaskerConstants = require('../constants/tasker_constants'); var _taskers = {}; var TaskerStore = new Store(Dispatcher); TaskerStore.all = function () { var keys = Object.keys(_taskers); var taskers = []; for (var i = 0; i < keys.length; i++) { var cat = _taskers[keys[i]]; taskers.push(cat); } return taskers; }; TaskerStore.find = function (id) { return _taskers[id]; }; TaskerStore.__onDispatch = function (payload) { switch (payload.actionType) { case TaskerConstants.RECEIVE_TASKERS: this.setTaskers(payload.taskers); TaskerStore.__emitChange(); break; case TaskerConstants.RECEIVE_TASKER_UPDATE: this.updateTasker(payload.tasker); TaskerStore.__emitChange(); break; } }; TaskerStore.setTaskers = function (taskers) { _taskers = {}; for (var i = 0; i < taskers.length; i++) { var cat = taskers[i]; _taskers[cat.id] = cat; } }; TaskerStore.updateTasker = function (tasker) { if (_taskers[tasker.id] === undefined) { _taskers[tasker.id] = {}; } var keys = Object.keys(tasker); for (var i = 0; i < keys.length; i++) { _taskers[tasker.id][keys[i]] = tasker[keys[i]]; } }; module.exports = TaskerStore;
import React, { Component } from 'react'; class GridTile extends Component { render(){ return( <td className = {this.props.className} onClick = {this.props.handleClick}> </td> ) } } export default GridTile
//頻度が多い関数関連 ((g) => { g.globalfreespace = g.globalfreespace || {}; g.fnc = g.fnc || {}; g.fnc.f = async (f) => { return f(); } const hsla = g.fnc.hsla = (h, l, s, a) => { return "hsl(" + h + "," + l + "%," + s + "%," + a + ")"; } //mapへの平均値の描画 //引数は9個のエリア「num」の含まれるary. [a1,a2,a3,a4,a5,a6,a7,a8,a9] それぞれの平均値を出力.ないときは”noData” //同じ数字は同じ色.var color = "hsl(" + hue + ", 100%, 50%)"; g.fnc.draw2 = async (id, args, tani) => { let avg = ["NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData"]; let _avg = ["NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData"]; let area = document.getElementById("container").children; let ary = []; for(let i = 1; i < args.length;i++){ ary.push(args[i][1]); } //console.log(args) await g.fnc.f(() => { for (let i = 0; i < ary.length; i++) { if (ary[i] && ary[i].length > 0) { avg[i] = 0; for (let j = 0; j < ary[i].length; j++) { avg[i] += parseFloat(ary[i][j]); } let m1 = Math.floor((avg[i] / ary[i].length)); let m2 = Math.floor(100 * (avg[i] / ary[i].length)) * 0.01; let m3 = m2 - m1; let m4 = Math.floor(100 * m3); avg[i] = "" + m1 + "." + m4 + "<div style='display:inline;font-size:0.5em;'>" + tani + "</div>"; _avg[i] = parseFloat("" + m1 + "." + m4) } } }); let CA = await g.fnc.setColor(_avg); await g.fnc.f(() => { for (let i = 0; i < avg.length; i++) { area[i].innerHTML = avg[i]; area[i].style.cssText += "background-color: " + CA[i] + " !important;"; } }); globalfreespace.color = CA; } //draw2 //mapへの合計値の描画 //引数は9個のエリア「num」の含まれるary. [a1,a2,a3,a4,a5,a6,a7,a8,a9] それぞれの合計値を出力.ないときは”noData” g.fnc.draw3 = async (id, args, tani) => { let area = document.getElementById("container").children; let sum = ["NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData", "NoData"]; let ary = []; for(let i = 1; i < args.length;i++){ ary.push(args[i][1]); } await g.fnc.f(() => { for (let i = 0; i < sum.length; i++) { if (ary[i] && ary[i].length > 0) { sum[i] = 0; for (let j = 0; j < ary[i].length; j++) { sum[i] += parseFloat(ary[i][j]); } } } }); let CA = await g.fnc.setColor(sum); await g.fnc.f(() => { for (let i = 0; i < sum.length; i++) { area[i].innerHTML = sum[i] + "<div style='display:inline;font-size:0.5em;'>" + tani + "</div>"; area[i].style.cssText += "background-color: " + CA[i] + " !important;"; } }); globalfreespace.color = CA; } //draw3 g.fnc.setColor = async (data) => { let color = [ hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), hsla(0, 0, 50, 0.5), ]; //60~310の間で等分するそのhslaを配列で返す.初期はNonDataColor //の予定だったがやっぱ180~360で移動させる let delta = 0; //同じデータがあったら減る,等分した色の幅 let _data = []; //_dataは,NoDataではない数字のみで構成されたデータ. let _dataIndex = []; //_dataIndexは,_dataにあるデータの元の場所.これでdataにすぐ戻れる for (let i = 0; i < data.length; i++) { if (data[i] !== "NoData") { _data.push(data[i]); _dataIndex.push(i); } } //ここでソート(バブルww) for (let i = 0; i < _data.length; i++) { for (let j = _data.length - 1; j > i; j--) { if (_data[j] < _data[j - 1]) { let _tmp = _data[j]; _data[j] = _data[j - 1]; _data[j - 1] = _tmp; _tmp = _dataIndex[j]; _dataIndex[j] = _dataIndex[j - 1]; _dataIndex[j - 1] = _tmp; } } } //ここで,同じ値のものの数を取得して,deltaの幅数を調整する let deltaCount = _dataIndex.length; for(let i = 0,tmp = 0; i < _data.length;i++){ if(i === 0){ tmp = _data[i]; }else{ if(tmp === _data[i]){ deltaCount -= 1; }else{ tmp = _data[i]; } } } //色幅は,例えばデータが4つなら,(250/(4-1)|0=83,)60,60+83,60+83*2,60+83*3 delta = (360 - 180)/(deltaCount - 1 + 0.01)|0; for(let i = 0,tmp = 0,j = 0; i < _dataIndex.length; i++){ if(i === 0){ tmp = _data[i]; color[_dataIndex[i]] = hsla(180 + delta * j, 70, 60, 0.5); }else{ if(tmp !== _data[i]){ tmp = _data[i]; j += 1; } color[_dataIndex[i]] = hsla(180 + delta * j, 70, 60, 0.5); } } return color; }//setColor g.fnc.nomal = (numbers) => { let s = 0, ans = Array.from(numbers); for (let i = 0; i < numbers.length; i++) { s += numbers[i]; } if (s !== 0) { let ratio = Math.max(...numbers) / 100; ans = numbers.map(v => Math.round(v / (ratio))); } return ans; } })(this);
require('dotenv').config(); var exports = module.exports = {}; var fs = require("fs"); const fse = require('fs-extra') var path = require('path') const { BlobServiceClient } = require('@azure/storage-blob'); var zipFolder = require('zip-folder') var http = require('http'); var AdmZip = require('adm-zip'); async function makeZip(foldername){ return new Promise(async (resolve)=>{ zipFolder('./blob/'+foldername, './blob/'+foldername+'.zip', async function(err) { if(err) { console.log('oh no!', err); } else { console.log('EXCELLENT'); result = await sendtoBlob(foldername); resolve('success') } }); }) } async function sendtoBlob(fileName){ return new Promise(async (resolve)=>{ fileName = fileName + '.zip'; const blobName = './blob/'+fileName; //path const blobServiceClient = await BlobServiceClient.fromConnectionString(process.env.blobConnectionString); // Get a reference to a container const containerClient = await blobServiceClient.getContainerClient(process.env.blobContainerClient); const blockBlobClient = containerClient.getBlockBlobClient(fileName); fs.readFile(blobName, async function(err, data) { let arrayBuffer = await Uint8Array.from(data); console.log(arrayBuffer.length); const uploadBlobResponse = await blockBlobClient.upload(arrayBuffer, arrayBuffer.length); console.log('request-id',uploadBlobResponse.requestId); resolve('sucesss') }); }) } function copyFile(file,dir,foldername){ return new Promise(async (resolve)=>{ var f = path.basename(file); var source = await fs.createReadStream(file); var dest = await fs.createWriteStream(path.resolve(dir, f)); source.pipe(dest); source.on('end', async function() { console.log('Succesfully copied'); result = await makeZip(foldername) }); source.on('error', function(err) { console.log(err); }); resolve('success') }) } exports.containerInstanceCurr = async function(info,cred,foldername){ console.log(info) await fs.promises.mkdir("./blob/"+foldername, { recursive: true }) stream = await fs.createWriteStream("./blob/"+foldername+"/Container_Instance_Variable.tf") stream.write('provider "azurerm" { \n subscription_id = '+JSON.stringify(info.subscriptionId)+'\n client_id = "'+cred.clientId+'"\n client_secret = "'+cred.clientSecret+'"\n tenant_id = "'+cred.tenantId+'"\n}') stream.write('\nvariable "Resource_Group" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceResourceGroupInfo.ACIresourceGroupName)+'\n}') stream.write('\nvariable "location" {\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceResourceGroupInfo.ACIresourceGroupLocation)+'\n}') stream.write('\nvariable "Conatiner-Instance-Name" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ContainerInstanceName)+'\n}') stream.write('\nvariable "Conatiner-Instance-location" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ContainerInstanceLocation)+'\n}') stream.write('\nvariable "DNS-Name" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ContainerInstanceDNSName)+'\n}') stream.write('\nvariable "OS-type" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ControlInstanceOS)+'\n}') stream.write('\nvariable "Conatiner-Name" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ControlInstanceContainerName)+'\n}') stream.write('\nvariable "Conatiner-Image" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ControlInstanceContainerImage)+'\n}') stream.write('\nvariable "CPU" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ControlInstanceCPUCore)+'\n}') stream.write('\nvariable "Memory" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ControlInstanceMemory)+'\n}') stream.write('\nvariable "Port-number" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ControlInstancePortNumber)+'\n}') stream.write('\nvariable "Protocol" { \n type = "string"\n default = '+JSON.stringify(info.RegistryConfg.ContainerInstanceInfo.ContainerInstanceProtocol)+'\n}') result = await copyFile('./src/DevOps/TerraformResourceFiles/Container_Instance_Main.tf','./blob/'+foldername,foldername) return({ "status":"done" }) }
import Header from './components/commons/Header'; import HomeView from './components/HomeView'; import ProductView from './components/ProductView'; import CartView from './components/CartView'; import SigninView from './components/SigninView'; import RegisterView from './components/RegisterView'; import ProfileView from './components/ProfileView'; import ShippingView from './components/ShippingView'; import PaymentView from './components/PaymentView'; import PlaceOrderView from './components/PlaceOrderView'; import OrderView from './components/OrderView'; import DashboardView from './components/DashboardView'; import ProductListView from './components/ProductListView'; import ProductEditView from './components/ProductEditView'; import OrderListView from './components/OrderListView'; import Error404View from './components/Error404View'; import { parseRequestUrl, showLoading, hideLoading } from './utils'; const routes = { '/': HomeView, '/product/:id': ProductView, '/cart' : CartView, '/cart/:id' : CartView, '/signin': SigninView, '/register': RegisterView, '/profile': ProfileView, '/shipping': ShippingView, '/payment': PaymentView, '/placeorder': PlaceOrderView, '/order/:id': OrderView, '/dashboard': DashboardView, '/productlist': ProductListView, '/product/:id/edit': ProductEditView, '/orderlist': OrderListView, }; const router = async () => { showLoading(); const request = parseRequestUrl(); const parseUrl = (request.resource ? `/${request.resource}` : '/') + (request.id ? '/:id' : '') + (request.verb ? `/${request.verb}` : ''); const view = routes[parseUrl] ? routes[parseUrl] : Error404View; const header = document.getElementById('header-container'); header.innerHTML = await Header.render(); await Header.after_render(); const main = document.getElementById('main-container'); main.innerHTML = await view.render(); if (view.after_render) await view.after_render(); hideLoading(); }; window.addEventListener('load', router); window.addEventListener('hashchange', router);
const sentence = "hello there from lighthouse labs"; let timeDelay = 50 let timeDelayWhenFinished = timeDelay * sentence.length; for (let char = 0; char < sentence.length; char++) { setTimeout(() => { process.stdout.write(sentence[char]); }, timeDelay); timeDelay = timeDelay + 50; }; setTimeout(() => { console.log(''); }, timeDelayWhenFinished);
import styled from 'styled-components'; const green = "#68dd39" const darkBlack = "#16161b" const lightBlack = "#1d1b22" export const Container = styled.header` position: absolute; display: flex; flex-direction: column; justify-content: flex-start; align-content: center; align-items: center; width: 100%; min-height: 100%; background: ${darkBlack}; overflow-y: scroll; ` export const Header = styled.div` display: flex; flex-direction: column; justify-content: center; align-content: center; align-items: center; width: 100%; height: 350px; background: ${green}; color: ${lightBlack}; @media(max-width: 900px) { height: 400px; } ` export const TitleArea = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; align-content: center; width: 40%; @media(max-width: 900px) { width: 95%; } h1{ color: ${lightBlack}; font-size: 36px; margin: 10px; @media(max-width: 900px) { font-size: 27px; } } p{ color: ${lightBlack}; text-align: center; margin: 10px; @media(max-width: 900px) { font-size: 15px; } } ` export const Line = styled.div` display: flex; flex-direction: row; justify-content: center; align-items: center; align-content: center; @media(max-width: 900px) { flex-direction: column; } ` export const Button = styled.button` display: flex; flex-direction: row; justify-content: center; align-items: center; align-content: center; color: ${lightBlack}; background-color: #fff; height: 50px; width: 200px; outline: none; cursor: pointer; border: none; border-radius: 5px; margin: 20px 10px; font-family: 'Montserrat', sans-serif; font-size: 16px; transition: all ease-in-out 0.3s; &&:hover{ -webkit-box-shadow: 2px 2px 19px -2px rgba(0,0,0,0.49); -moz-box-shadow: 2px 2px 19px -2px rgba(0,0,0,0.49); box-shadow: 2px 2px 19px -2px rgba(0,0,0,0.49); } ` export const OutlineButton = styled.button` display: flex; flex-direction: row; justify-content: center; align-items: center; align-content: center; background-color: transparent; border: 2px solid #fff; height: 50px; width: 200px; outline: none; cursor: pointer; border-radius: 5px; margin: 20px 10px; font-family: 'Montserrat', sans-serif; font-size: 16px; color: #fff; transition: all ease-in-out 0.3s; &&:hover{ color: ${lightBlack}; background-color: #fff; -webkit-box-shadow: 2px 2px 19px -2px rgba(0,0,0,0.49); -moz-box-shadow: 2px 2px 19px -2px rgba(0,0,0,0.49); box-shadow: 2px 2px 19px -2px rgba(0,0,0,0.49); } ` export const ContentArea = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; align-content: center; padding-top:30px; text-align: justify; width: 50%; h2{ color: #fff; font-size: 28px; margin-bottom: 30px; } p{ color: #fff; text-align: center; margin: 10px 0px; } ` export const PlaygroundItem = styled.div` display: flex; flex-direction: column; justify-content: flex-start; align-content: center; align-items: center; width: 100%; margin: 0px 10px ; ` export const PlaygroundTitle = styled.p` color: ${green} !important; font-size: 22px; ` export const Input = styled.input` text-align: center; width: 50%; outline: none; height: 40px; width: 300px; font-size: 20px; border-radius: 3px; border: none; ` export const Output = styled.p` text-align: center; height: 40px; width: 300px; font-size: 14px; font-style: italic; ` export const Footer = styled.header` display: flex; flex-direction: column; justify-content: center; align-items: center; align-content: center; width: 100%; height: 80px; background: ${lightBlack}; color: #fff; p{ display: flex; flex-direction: row; justify-content: center; align-items: center; align-content: center; font-size: 13px; cursor: pointer; } `
import React from 'react'; import ReactDOM from 'react-dom'; const { render } = ReactDOM; class HelloWorld extends React.Component { render() { return ( <div>Hello World</div> ); }; } render ( <HelloWorld/>, document.getElementById("react-container") );
const chai = require('chai') const expect = chai.expect const {stub} = require('sinon') const proxyquire = require('proxyquire') require('sinon-as-promised') chai.use(require('sinon-chai')) describe('parameter middleware', () => { let middleware let req, res, next beforeEach(() => { req = { params: {} } res = { end: stub(), send: stub() } next = stub() middleware = proxyquire(process.cwd() + '/lib/middleware/parameter', { }) }) describe('parseParameters', () => { it('can parse parameter "week"', () => { req.params.text = '/time week=2017w12' middleware.parseParameters(req, res, next) expect(req.izone.week).to.eql('2017w12') }) it('can parse parameter "import=träna"', () => { req.params.text = '/time import=träna' middleware.parseParameters(req, res, next) expect(req.izone.import).to.eql('träna') }) it('can parse parameter "import=iteamvs"', () => { req.params.text = '/time import=iteamvs' middleware.parseParameters(req, res, next) expect(req.izone.import).to.eql('iteamvs') }) }) })
// @flow import React from 'react'; import {connect} from 'react-redux'; import {List, ListItem} from 'react-native-elements'; import {ScrollView, View, Text} from '../../../components/core'; import ResponsiveImage from '../../../components/ResponsiveImage'; import conferenceMap from '../../../assets/images/conference-map.png'; import styles from './MapScene-style'; import {THEME_COLOR} from '../../../constants/colors'; import type {Dispatch} from '../../../types'; type Props = { onMapClicked: (imageSource: number) => void, }; export function MapScene(props: Props) { let {onMapClicked} = props; return ( <ScrollView style={styles.root}> <View style={styles.titleContainer}> <Text style={styles.title}>VENUE</Text> </View> <View raised style={styles.mapContainer}> <ResponsiveImage source={conferenceMap} onPress={() => onMapClicked(conferenceMap)} /> </View> <List containerStyle={styles.listContainer}> <ListItem // TODO: use accordion as an optional ListItem because sometimes places like toilet are many, and we need to locate them all title="2 Stages" titleStyle={styles.listItemTitle} subtitle="The Hall & SCTV Studio" leftIcon={{name: 'mic', color: THEME_COLOR}} hideChevron={true} /> <ListItem // TODO: use accordion as an optional ListItem because sometimes places like toilet are many, and we need to locate them all title="2 Topics" titleStyle={styles.listItemTitle} subtitle="Technology & Product Design" leftIcon={{ name: 'comment-o', color: THEME_COLOR, type: 'font-awesome', }} hideChevron={true} /> </List> </ScrollView> ); } function mapDispatchToProps(dispatch: Dispatch) { return { onMapClicked: (imageSource: number) => { dispatch({ type: 'SHOW_PINCHABLE_IMAGE_REQUESTED', imageSource, }); }, }; } export default connect( null, mapDispatchToProps, )(MapScene);
import React from 'react' import { graphql } from 'gatsby' import get from 'lodash/get' import Helmet from 'react-helmet' import Hero from '../components/hero' import Layout from '../components/layout' import ArticlePreview from '../components/article-preview' import MainGallary from '../components/MainGallary' class RootIndex extends React.Component { render() { const siteTitle = get(this, 'props.data.site.siteMetadata.title') const posts = get(this, 'props.data.allContentfulBlogPost.edges') const [author] = get(this, 'props.data.allContentfulPerson.edges') return ( <Layout location={this.props.location}> <div style={{ background: '#fff' }}> <Helmet title={siteTitle} /> <Hero data={author.node} /> <div className="wrapper"> <h2 className="section-headline">@nakumsays</h2> <blockquote className="twitter-tweet"><p lang="en" dir="ltr">Why most organization used agile approach? <a href="https://t.co/1xlvY5DNJI">pic.twitter.com/1xlvY5DNJI</a></p>&mdash; Vishalnakum (@Vishaln76914140) <a href="https://twitter.com/Vishaln76914140/status/1109784878126489600?ref_src=twsrc%5Etfw">March 24, 2019</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charSet="utf-8"></script> <h2 className="section-headline">Recent articles</h2> <ul className="article-list"> {posts.map(({ node }) => { return ( <li key={node.slug}> <ArticlePreview article={node} /> </li> ) })} </ul> <h2 className="section-headline">@Insta</h2> <MainGallary posts={get(this, 'props.data.allInstagramContent')} /> </div> </div> </Layout> ) } } export default RootIndex export const pageQuery = graphql` query HomeQuery { site { siteMetadata { title } } allContentfulBlogPost(sort: { fields: [publishDate], order: DESC }) { edges { node { title slug publishDate(formatString: "MMMM Do, YYYY") tags heroImage { fluid(maxWidth: 350, maxHeight: 196, resizingBehavior: SCALE) { ...GatsbyContentfulFluid_tracedSVG } } description { childMarkdownRemark { html } } } } } allContentfulPerson(filter: { contentful_id: { eq: "15jwOBqpxqSAOy2eOO4S0m" } }) { edges { node { name shortBio { shortBio } title heroImage: image { fluid( maxWidth: 1180 maxHeight: 480 resizingBehavior: PAD background: "rgb:000000" ) { ...GatsbyContentfulFluid_tracedSVG } } } } } allInstagramContent { edges { node { link caption{ text } localImage{ childImageSharp { fluid(maxHeight: 500, maxWidth: 500 quality: 50) { ...GatsbyImageSharpFluid_withWebp_tracedSVG } } } images { standard_resolution { width height url } low_resolution{ url } } } } } } `
const Product = require('../models/product'); var mongoose = require('mongoose'); mongoose.connect('localhost:27017/shopping'); var products = [ new Product({ imagePath: "https://upload.wikimedia.org/wikipedia/ru/5/5e/Gothiccover.png", title: 'Gothic Video Game', description: 'Awesome Game', price: 10 }), new Product({ imagePath: "http://is4.mzstatic.com/image/thumb/Purple122/v4/76/71/92/76719213-306f-bbca-788e-44e6553288a3/source/1200x630bb.jpg", title: 'Minecraft Video Game', description: 'Awesome Game', price: 15 }), new Product({ imagePath: "https://upload.wikimedia.org/wikipedia/ru/0/05/Dark_Souls_Cover_Art.jpeg", title: 'Dark Souls Video Game', description: 'Awesome Game', price: 50 }) ]; var done = 0; for (var i = 0; i < products.length; i++) { products[i].save(function (err, result) { done++; if(done === products.length) { exit(); } }); } function exit() { mongoose.disconnect(); }
const { validationResult } = require("express-validator"); const models = require('../models'); const { returnUserByToken } = require("../middleware"); const { returnProfile,insertHours } = require("../utils/functions") const get = async (req,res) => { try { const profile = await returnProfile(req); const { get_products , page, id} = req.query; let include = ['inventoriesHours'] if(get_products){ include.push( { model: models.Product, as: 'product', include : ['gallery'] }) } let whereInventories = {} if(id) whereInventories = {...whereInventories, id } const inventories = await models.Inventories.paginate({ where : { ...whereInventories, profile_id: profile.id }, include, page : page || 1 }); return res.status(200).send(inventories); } catch (error) { return res.status(500).send(error); } } const create = async (req,res) => { try { const errors = validationResult(req); const user = await returnUserByToken(req); if(!errors.isEmpty()){ return res.status(422).send({ errors: errors.array()}) } const inventory = await models.Inventories.create({ ...req.body, user_id:user.id }); const hours = await insertHours(req.body.time_init,req.body.time_final,inventory.id); return res.status(200).send({...inventory.dataValues,inventoriesHours:hours}); } catch (error) { return res.status(500).send(error); } } const update = async (req,res) => { try { const { id } = req.params; const inventory = await models.Inventories.findOne({where:{ id }}); if(!inventory) return res.status(404).send({ message:"bad id" }); inventory.update({ ...req.body }) inventory.save(); const hours = await insertHours(req.body.time_init,req.body.time_final,inventory.id); return res.status(200).send({...inventory.dataValues,inventoriesHours:hours}); } catch (error) { return res.status(500).send(error); } } async function destroy(req,res){ try { const { id } = req.params; await models.Inventory.destroy({where:{ id }}); return res.status(200).send({ message:"success" }); } catch (error) { return res.status(500).send(error); } } module.exports = { get, create, update, destroy, }
const HOME = "/"; const MOVIELIST = "/movie/movieListByState"; const routes = { home: HOME, movieList: MOVIELIST, }; export default routes;
import React, {Fragment, PureComponent} from 'react'; import { SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, TouchableOpacity, Image, Dimensions, Switch, Platform, } from 'react-native'; import {SvgXml} from 'react-native-svg'; import SVG from '../components/SvgComponent'; import {getStatusBarHeight} from 'react-native-status-bar-height'; import {DARKMINT} from '../Constant'; // 로고 const COMPANYPROFILELOGO = () => { let height = 18; let width = 100; let marginBottom = 40; let screenWidth = Dimensions.get('screen').width; if (screenWidth >= 834) { height = 78; width = 400; marginBottom = 60; } return ( <View style={{ marginBottom: marginBottom, alignItems: 'flex-start', }}> <SvgXml xml={SVG('COMPANYPROFILELOGO')} height={height} width={width} /> </View> ); }; export default class ACCESSTERMS extends PureComponent { constructor(props) { super(props); this.state = { toggle: true, }; } componentDidMount() {} render() { return ( <Fragment> <StatusBar barStyle="dark-content" /> <SafeAreaView /> <ScrollView style={{backgroundColor: 'white', flex: 1}}> <Image source={require('../images/companyprofile.jpg')} resizeMode="cover" style={{ position: 'absolute', top: -(getStatusBarHeight() + 62), left: 0, right: 0, bottom: 0, width: Dimensions.get('screen').width, height: Dimensions.get('screen').height, }} /> <View style={{marginTop: 30, marginLeft: 24, marginRight: 24}}> <View> <Text style={[ styles.bold1, { color: DARKMINT, fontSize: 18, lineHeight: 32, }, ]}> 안녕하세요? 사랑하는 내 아이를 위한 </Text> </View> <View style={{marginBottom: 25}}> <Text style={[styles.bold1, , {color: DARKMINT, fontSize: 18}]}> 유아용품 추천 솔루션 서비스 ‘베블링’입니다. </Text> </View> <View style={{marginBottom: 25}}> <Text style={[styles.bold2, {fontSize: 12, lineHeight: 18}]}> 베블링은 약 3만개의 Data를 수집했으며, 식품, 화장품, 생활용품, 의약외품까지 아이가 쓰는 모든 것에 대한 성분 정보, 영양 정보, 알레르기 정보, 식품첨가물, 첨가물 등의 정보를 알기 쉽게 알려주고, 더 나은 제품으로 추천해주는 서비스입니다. </Text> </View> <View style={{marginBottom: 25}}> <Text style={[styles.bold2, {fontSize: 12, lineHeight: 18}]}> 베블링은 육아에 집안일까지... 엄마의 고민을 대신하며, 10개 종류의 유아 관련 Data를 바탕으로 엄마의 마음을 담았습니다. 또한, 보건복지부, 식약처, 질병관리본부의 공공 데이터를 활용해 3대 주요 성분 (영양성분, 알레르기, 식품첨가물)을 담았고, 화학과 교수, 생의학화장품 학과 교수, 소아과 의사, 약사 등 전문의가 자문위원으로 활동하고 있습니다. </Text> </View> <View> <Text style={[styles.bold2, {fontSize: 12, lineHeight: 18}]}> 베블링은 엄마의 육아가 외롭지 않게 엄마들을 위한 콘텐츠를 운영하고 있습니다. 엄마들의 후기, 고민을 나누는 콘텐츠가 자유로워질 수 있도록 ‘수다 톡’ 서비스를 제공하고 있습니다. 또한, 베블링 평가단을 운영해 원하는 제품을 체험해보고 후기까지 이어져 엄마들이 서로 공감하고, 의견을 나눌 수 있는 대화의 장을 제공하고 있습니다. </Text> </View> <View style={{marginBottom: 25}}> <Text style={[styles.bold2, {fontSize: 12, lineHeight: 18}]}> 베블링은 혼자 하는 육아가 같이하는 육아가 되고, 어려웠던 육아가 좀 더 쉬워질 수 있도록 엄마의 고민을 함께하겠습니다.  </Text> </View> <View style={{marginTop: 20}}>{COMPANYPROFILELOGO()}</View> </View> </ScrollView> </Fragment> ); } } const styles = StyleSheet.create({ bold1: Platform.select({ ios: {fontWeight: 'bold'}, android: {fontFamily: 'Poppins-Bold'}, }), bold2: Platform.select({ ios: {fontWeight: '200'}, android: {fontFamily: '200'}, }), });
import { USER_ADD_NEW_QUESTION, GET_USERS, USER_ANSWER_QUESTION, } from '../types'; export const users = (userState = {}, action) => { switch (action.type) { case GET_USERS: return { ...userState, ...action.payload.users, }; case USER_ANSWER_QUESTION: const { answer, loggedInUser, qid } = action.payload; return { ...userState, [loggedInUser]: { ...userState[loggedInUser], answers: { ...userState[loggedInUser]?.answers, [qid]: answer, }, }, }; case USER_ADD_NEW_QUESTION: const { qid: id, author } = action.payload; console.log('id', id); console.log('author', author); return { ...userState, [author]: { ...userState[author], questions: userState[author]?.questions?.concat(id), }, }; default: return userState; } };
const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin'); const webpack = require('webpack'); const opn = require('opn'); const getConfig = ({ paths }) => { const { workingDir, pagePath, resultOutput } = paths; return { entry: `${__dirname}/buildByWebpack.js`, output: { path: resultOutput.path, filename: 'bundle.js' }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', options: { presets: ['react', 'es2015', 'stage-0'] }, }, { test: /\.(css|pcss)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', { loader: 'postcss-loader', options: { config: { path: `${__dirname}/postcss.config.js`, }, }, }], }), }, { test: /\.(html|hbs)$/, use: [ { loader: 'html-loader', options: { } }, ], }, { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico|otf)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: ['url-loader?name=[name].[hash].[ext]&prefix=true?'], }, ], noParse: [/\.min\.js/], }, plugins: [ new ExtractTextPlugin({ filename: '[name].css', allChunks: true }), new HtmlWebpackPlugin({ template: pagePath, inlineSource: '.(css|js)$', }), new HtmlWebpackInlineSourcePlugin(), ], resolve: { alias: { 'source-htmls': workingDir, }, }, }; }; const build = ({ paths }) => { const config = getConfig({ paths }); return new Promise((resolve, reject) => { return webpack(config, (err, stats) => { if (err || stats.hasErrors()) { return reject({ err: { err, stats } }); } return resolve(); }); }); }; const watch = ({ paths, templateSystem, serverUrl, buildPdf, mode, options }) => { const config = getConfig({ paths }); const compiler = webpack(config); return new Promise((resolve, reject) => { compiler.watch({}, async (err, stats) => { if (err || stats.hasErrors()) { return reject({ err: { err, stats } }); } const { htmlPath, pdfPath } = paths.resultOutput; await buildPdf({ outPaths: { htmlPath, pdfPath }, templateSystem, options, type: 'pdf', serverUrl, mode, watch: true, }); opn(pdfPath); return resolve({ htmlPath, pdfPath }); }); }); }; module.exports = { getConfig, build, watch };
const PATH = require("path"); const { STRING } = require("reshow-constant"); // for test const YoTestLib = require("yeoman-test"); const assert = require("yeoman-assert"); const YoTest = ({ source, params, options = {}, build }) => { const isStringSource = STRING === typeof source; source = isStringSource ? PATH.join(source) : source; const sourceName = isStringSource ? source : source.name; return YoTestLib.create(source) .withPrompts(params) .withOptions(options) .inTmpDir((dir) => { console.log(`Build Dest on: ${dir}`); console.log(`Source : ${sourceName}`); }) .build(build) .run(); }; module.exports = { YoTest, assert, };
var searchData= [ ['_5fwdir',['_WDIR',['../struct__WDIR.html',1,'']]], ['_5fwdirent',['_wdirent',['../struct__wdirent.html',1,'']]] ];
const z = "cls2"; const y = false; const x = {}; let w = "cls3"; let v = true; let a = "cls1"; let b = "cls1 cls2"; let c = "cls1 cls2"; let d = "cls1 cls2"; let e = "cls2"; let f = v ? "cls1" : "cls2"; let g = "cls1 " + ((v ? w : "") + " " + (v ? z : "")); let h = w + " " + x.a; w = "cls4"; v = false;
function NoArguments () { // name and message this.name = this.constructor.name this.message = 'No arguments were passed!' // V8's stack trace Error.captureStackTrace && Error.captureStackTrace(this, this.constructor) } // inheriting Error NoArguments.prototype = Object.create(Error.prototype) NoArguments.prototype.constructor = NoArguments // here, take it module.exports = NoArguments
function lessThan100(num1,num2) { if(num1+num2<100){ return true; } else{return false}; } console.log(lessThan100(22,15)); console.log(lessThan100(83,34));
var toolbar = __get('toolbar'); var updateRadius = function(newsRad){ if (newsRad < minRadius) { newsRad = minRadius; }else if(newsRad > maxRadius){ newsRad = maxRadius; } radius = newsRad; context.lineWidth = radius*2; radSpan.innerHTML = newsRad; }; var minRadius = 0.5, maxRadius = 100, defaultRadius = 5, coef = 5, radSpan = document.getElementById('radVal'), decRad = document.getElementById('decRad'), incRad = document.getElementById('incRad'); // diminuer le rayon decRad.addEventListener('click',function(){ updateRadius(radius-coef); }) // augmenter le rayon incRad.addEventListener('click',function(){ updateRadius(radius+coef); }); updateRadius(defaultRadius); function __get(id){ return document.getElementById(id); } /*===================================================== GESTION DES COULEURS ========================================================*/ var colors = [ "black", "red", "blue", "yellow", "orange", "indigo", "violet", "#fff" ]; // recupération des éléments de la plaette de couleur var palettes = document.getElementsByClassName('color_palet'); // les couleur du tableau son lié a la bar couleurs for (var i = 0; i < colors.length; i++) { var palette = document.createElement("div"); palette.className = "color_palet"; palette.style.backgroundColor = colors[i]; palette.addEventListener('click', setPalette); document.getElementById("colors").appendChild(palette); }; function getColor(color){ //changer la couleur du fille dans la vue context.fillStyle = color; //changer la couleur des lihnes dans la vue context.strokeStyle = color; var active = document.getElementsByClassName('active')[0]; if (active) { active.className = "color_palet"; }; } function setPalette(evt){ var palette = evt.target; //identifier l'éléments clické getColor(palette.style.backgroundColor); //injecter la couleur palette.className += " active"; // injecter la class active dans l'element courant } // la premire couleur est sélectionée par défaut setPalette({target : document.getElementsByClassName('color_palet')[0]}); // function pour gestion des outils var tools = document.querySelectorAll(".spanTools"); for (var i = 0; i < tools.length; i++) { tool = tools[i].addEventListener('click',function(evt){ var selectedTool = this; var currentItem = document.getElementsByClassName('currentTool')[0]; if (currentItem){ currentItem.classList.remove('currentTool'); } selectedTool.classList.add('currentTool'); // recuperer le nom de l'outil grace à son id var selectedTool_name = selectedTool.getAttribute('id'); // si on choisi la gomme on met la couleur blanc if (selectedTool_name === 'eraserTool') { context.fillStyle = '#fff'; //changer la couleur des lignes dans la vue context.strokeStyle = '#fff'; radius = 15; }else if(selectedTool_name === 'pentTool'){ getActiveColor(); } }) }; /*trouver la couleur actuellement utilisée pour dessiner*/ function getActiveColor(){ var currentColor = document.getElementsByClassName('active')[0]; if (currentColor) { var $activeColor = currentColor.getAttribute("style").split(":"); var codeColor = $activeColor[1].toString(); console.log(codeColor.slice(0,-1)); context.fillStyle = codeColor; //changer la couleur des lignes dans la vue context.strokeStyle = codeColor; dessinerPoint; }; } /*================================== sauvegarder une image ===================================*/ function saveImage(link, canvasId, filename) { link.href = document.getElementById(canvasId).toDataURL(); link.download = filename; } var saveBtn = __get('saveBtn');// boouton souvegarder saveBtn.addEventListener('click', saveImage(this, 'canvas', 'imageFromCanvas.png'),false); /* function saveImage(){ var data = canvas.toDataURL(); var left = (window.innerWidth)/2, top = (window.innerHeight)/2; window.open(data,'_blank','location=0, menubar=0'); } */ /*================== nettoyer le canvas ====================*/ var clearBtn = __get("btnClear"); clearBtn.addEventListener('click',function(){ context.clearRect(0, 0, canvas.width, canvas.height); });
$(function () { // the half circle dashboard things built with the Donut functions $('.stats-highlight').each(initStats); $('.plotly-chart').each(initPlotly); }); // TODO: fallback image for non-js, // Description and details for screen readers function initPlotly(d3, Plotly) { var container = $(this); if ($('html').hasClass('ie8') || $('html').hasClass('ie7')) { // TODO: Unsupport graphs fall back to image if (!container.has('img').length) { container.html('<span class="plotly-chart--loading">Chart image not found</span>') } return; } // no supplied image fallback show loading indicator if (!container.has('img').length) { container.html('<span class="plotly-chart--loading">Loading</span>') } var libs = [ 'd3', 'Plotly', // for ie9 support (('Float32Array' in window) ? '' : 'typedarray') ]; requirejs(libs, function (d3, Plotly) { var WIDTH_IN_PERCENT_OF_PARENT = 100, HEIGHT_IN_PERCENT_OF_PARENT = 100; container.empty(); function getHeight() { var tempHeight = container.attr('data-fixed-height') ? container.attr('data-fixed-height') + "px" : HEIGHT_IN_PERCENT_OF_PARENT + "%"; return tempHeight; } var gd3 = d3.select(container.get(0)).style({ width: WIDTH_IN_PERCENT_OF_PARENT + '%', 'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%', height: getHeight(), 'margin-top': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%' }); var gd = gd3.node(); var title = container.attr("data-title"); var xLabel = container.attr('data-x-label'); var yLabel = container.attr('data-y-label'); getConfig(d3, container, function (config) { Plotly.plot(gd, config, { title: title, font: { family: "Source Sans Pro, sans-serif", size: 20, color: '#333' }, xaxis: { title: xLabel, titlefont: { family: "Source Sans Pro, sans-serif", size: 18, color: "#333" } }, yaxis: { title: yLabel, titlefont: { family: "Source Sans Pro, sans-serif", size: 18, color: "#333" } } // not setting the background color atm, keep default // paper_bgcolor: container.css("background-color") }); // This does not work atm, // following this issue for updates // https://github.com/plotly/plotly.js/issues/102 // container.on('mousemove', function (data) { // // // make things bigger // var hovertext = container.find(".hovertext"); // var trans = hovertext.attr('transform') // // hovertext.attr('transform', trans + ' scale(1.3)'); // // // give more padding around text by setting stroke to the // // same color as the fill // var path = hovertext.find('path'); // var color = path.css('fill'); // console.log(color); // path.css({'stroke-width': 7, 'stroke': color}) // }); }) $(window).on('resize', function () { var gd3 = d3.select(container.get(0)).style({ height: getHeight() }); Plotly.Plots.on("resize", gd); }); }); } var defaultBar = [ { "type": "bar", "x": [], "y": [], "marker": { "color": "#046B99", "line": { "width": 0.5 } } } ]; var defaultLine = [ { "x": [], "y": [], "mode": "lines", "name": "Solid", "line": { "color": "#046B99", "dash": "solid", "width": 4 } } ]; var defaultPie = [ { "values": [], "labels": [], "hoverinfo": "label+percent", "type": "pie", "marker": { "colors": [ "#E1F2F7", "#9FDBF1", "#02BFE7", "#35BBAA", "#72CE6F", "#815AB4", "#D34A37", "#F27E31", "#FFCA4A" ] } } ]; function getConfigSkeleton(type) { switch (type) { case "bar": return defaultBar; case "pie": return defaultPie; case "line": return defaultLine; default: return []; } } function getConfig(d3, container, func) { var sourceUrl = container.attr('data-datasource-url'); var configUrl = container.attr('data-config-url'); var chartType = container.attr('data-type'); var color = container.attr('data-color'); if (configUrl) { $.getJSON(configUrl, func); return; } var config = getConfigSkeleton(chartType); var xValues = container.attr('data-x-values'); var yValues = container.attr('data-y-values'); if (xValues) { xValues = xValues.split('|').map(function (d) { if (isNaN(parseFloat(d))) { return d; } return +d }); } else { xValues = []; } if (yValues) { yValues = yValues.split('|'); } else { yValues = []; } switch (chartType) { case "line": case "bar": config[0].x = xValues config[0].y = yValues.map(function (d) { return +d }); break; case "pie": config[0].values = xValues; config[0].labels = yValues; break; default: } if (!color) { color = '#046B99'; } // specifiying the color switch (chartType) { case "line": config[0].line.color = d3.rgb(color).toString(); break; case "bar": config[0].marker.color = d3.rgb(color).toString(); break; case "pie": var colorA = d3.hsl(color); var colorB = d3.hsl((colorA.h - (4 * xValues.length)) % 360, colorA.s, colorA.l) var colorScale = d3.scale.linear().domain(xValues).interpolate(d3.interpolateHsl).range([colorA.toString(), colorB.toString()]); var colors = xValues.map(function (d) { return colorScale(d); }); config[0].marker.colors = colors; break; default: } func(config); } function initStats() { var container = $(this); var libs = ['d3']; if ($('html').hasClass('ie8') || $('html').hasClass('ie7')) { return; // TODO: Unsupport graphs fall back to something else } requirejs(libs, function (d3) { var shouldFlip = container.attr('data-direction') == 'right' ? true : false; var data = parseFloat(container.attr('data-percentfill')); var chart = container.find('.half-gauge-chart'); var color = container.attr('data-colorfill'); var showHalfTick = container.find('.small-goal-text').length != 0; var config = { bindTo: chart.get(0), background: true, maxValue: 100, startAngle: -90, endAngle: 90, thickness: 5, color: color, showHalfTick: showHalfTick, size: { width: chart.get(0).clientWidth, height: chart.get(0).clientWidth }, flipStart: shouldFlip }; var Donut = initHalfDonut(d3); var donutChart = new Donut(config); donutChart.load({ data: 0 }); function sizeText() { var width = chart.get(0).clientWidth; var height = chart.get(0).clientHeight; var detail = container.find('.small-goal-text'); var lineHeight = parseFloat(container.find('.small-goal-text').css('line-height')); container.find('.info').css({ top: -width / 4 }); detail.css({ 'font-size': width / 18 }); var detailHeight = detail.height(); detail.css({ top: (width < 400) ? detailHeight * 2 + 20 : (detailHeight * 1.5) }) container.find('.big-number').css({ 'font-size': width / 6 }); container.find('.percent-detail').css({ 'font-size': width / 10 }); } sizeText(); $(window).on('resize', function () { window.setTimeout(function () { config.size = { width: chart.width(), height: chart.width() }; config.data = data; donutChart = new Donut(config); donutChart.load({ data: data }); sizeText(); }, 10); }); var waypoint = new Waypoint({ element: chart.get(0), // start when it appears at the bottom offset: '100%', handler: function () { donutChart.load({ data: data }) } }); }) } /** * Custom Half Donut plugin * TODO: code clean up, and refactor */ function initHalfDonut(d3) { var defaults = { className: 'donut', size: { width: 200, height: 200 }, margin: { top: 20, right: 20, bottom: 20, left: 20 }, startAngle: 0, endAngle: 360, thickness: null, offset: 0, sort: null, maxValue: null, background: false, flipStart: false, color: 'rgb(49, 130, 189)', accessor: function (d, i) { return d; } }; var Donut = function (config) { // need an extend fn this.config = extend({}, defaults, config); // setup radius this.config.radius = getRadius(this); // setup accessor this.accessor = this.config.accessor; // convenience method to map data to start/end angles this.pie = d3.layout.pie().sort(this.config.sort).startAngle(degToRad(this.config.startAngle)).endAngle(degToRad(this.config.endAngle)) if (this.accessor && typeof this.accessor === 'function') { this.pie.value(this.accessor); } var thickness = getThickness(this); // setup the arc // divide offset by 4 because the middle of the stroke aligns to the edge // so it's 1/2 on the outside, 1/2 inside this.arc = d3.svg.arc().innerRadius(this.config.radius - thickness - (this.config.offset / 4)).outerRadius(this.config.radius + (this.config.offset / 4)); bindSvgToDom(this); }; Donut.prototype.load = function (newOpts) { // store data on object var data = (newOpts && newOpts.data != null) ? newOpts.data : this.data.map(this.accessor); // convert to array if not already data = Array.isArray(data) ? data : [data]; if (this.config.maxValue) { this.data = this.pieMaxValue(data); } else { this.data = this.pie(data); } // drawPaths drawPaths(this); }; Donut.prototype.pieMaxValue = function (data) { var accessor = this.accessor, self = this; // Compute the numeric values for each data element. var values = data.map(function (d, i) { return +accessor.call(self, d, i); }); var sum = d3.sum(values), max = d3.max([this.config.maxValue, sum]), diff = max - sum; // Compute the start angle. var a = +(degToRad(this.config.startAngle)); // Compute the angular scale factor: from value to radians. // include the diff because it will help create angles with a maxValue in mind var k = (degToRad(this.config.endAngle) - a) / (sum + diff); var index = d3.range(data.length); // Compute the arcs! // They are stored in the original data's order. var arcs = []; index.forEach(function (i) { var d; arcs[i] = { data: data[i], value: d = values[i], startAngle: a, endAngle: a += d * k }; }); return arcs; }; function getThickness(donut) { return donut.config.thickness || donut.config.radius; } /* * Setup the svg in the DOM and cache a ref to it */ function bindSvgToDom(donut) { var width = getWidth(donut), height = getHeight(donut); var transString = 'translate(' + width / 2 + ',' + height / 2 + ')' + ((donut.config.flipStart == true) ? ' scale(-1,1)' : ''); var tempSVG = d3.select(donut.config.bindTo).select('svg'); if (tempSVG.empty()) { donut.svg = d3.select(donut.config.bindTo).append('svg').attr('class', donut.config.classNames).attr('width', width).attr('height', height / 2).append('g').attr('transform', transString); } else { donut.svg = d3.select(donut.config.bindTo).select('svg').attr('class', donut.config.classNames).attr('width', width).attr('height', height / 2).select('g').attr('transform', transString); donut.svg.selectAll('*').remove(); } if (donut.config.background) { donut.svg.append('path').attr('class', 'donut-background').transition().duration(0).attrTween('d', function (d, i) { var fullArc = { value: 0, startAngle: degToRad(donut.config.startAngle), endAngle: degToRad(donut.config.endAngle) }; return arcTween.call(this, fullArc, i, donut); }); } if (donut.config.showHalfTick) { donut.svg.append('line').attr('class', 'donut-halfmark').attr('stroke', 'gray').attr('stroke-width', 1).attr({ 'x1': 0, 'x2': 0, 'y1': -height / 2 + 10, 'y2': -height / 2 + 35 }); } } function drawPaths(donut) { var paths = donut.svg.selectAll('path.donut-section').data(donut.data); // enter new data paths.enter().append('path').attr('class', function (d, i) { return 'donut-section value-' + i; }).attr('fill', donut.config.color).attr('stroke', '#fff').attr('stroke-width', donut.config.offset / 2); // transition existing paths donut.svg.selectAll('path.donut-section').transition().duration(2000).attrTween('d', function (d, i) { return arcTween.call(this, d, i, donut); }); // exit old data paths.exit().transition().duration(100).attrTween('d', function (d, i) { return removeArcTween.call(this, d, i, donut); }).remove(); } // Store the currently-displayed angles in this._current. // Then, interpolate from this._current to the new angles. function arcTween(a, i, donut) { var prevSiblingArc, startAngle, newArc, interpolate; if (!this._current) { prevSiblingArc = donut.svg.selectAll('path')[0][i - 1]; // donut.data[i - 1]; // start at the end of the previous one or start of entire donut startAngle = (prevSiblingArc && prevSiblingArc._current) ? prevSiblingArc._current.endAngle : degToRad(donut.config.startAngle); newArc = { startAngle: startAngle, endAngle: startAngle, value: 0 }; } interpolate = d3.interpolate(this._current || newArc, a); // cache a copy of data to each path this._current = interpolate(0); return function (t) { return donut.arc(interpolate(t)); }; } function removeArcTween(a, i, donut) { var emptyArc = { startAngle: degToRad(donut.config.endAngle), endAngle: degToRad(donut.config.endAngle), value: 0 }, i = d3.interpolate(a, emptyArc); return function (t) { return donut.arc(i(t)); }; } function getRadius(donut) { var width = getWidth(donut) - donut.config.margin.left - donut.config.margin.right, height = getHeight(donut) - donut.config.margin.top - donut.config.margin.bottom; return Math.min(width, height) / 2; } function getWidth(donut) { return donut.config.size && donut.config.size.width; } function getHeight(donut) { return donut.config.size && donut.config.size.height; } function degToRad(degree) { return degree * (Math.PI / 180); } function radToDeg(radian) { return radian * (180 / Math.PI); } /* * Simple extend fn like jQuery * * Usage: extend({ name: 'Default' }, { name: 'Matt' }); * Result: { name: 'Matt' } */ function extend() { for (var i = 1; i < arguments.length; i++) { for (var prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { arguments[0][prop] = arguments[i][prop]; } } } return arguments[0]; } return Donut; }
import { WIDGET_SHOW, WIDGET_HIDE } from './constants'; const ID = 'feedbackstreetBoys'; const baseStyles = { border: 0, height: '100vh', width: '100vw', position: 'fixed', top: 0, right: 0, bottom: 0, left: 0, zIndex: 100000000, }; const activeStyles = { ...baseStyles, display: 'block', }; const inactiveStyles = { ...baseStyles, display: 'none', }; function setup() { const iframe = document.createElement('iframe'); iframe.src = chrome.extension.getURL('Widget/index.html'); iframe.setAttribute('id', ID); document.body.appendChild(iframe); return iframe; } function show() { const iframe = document.getElementById(ID) || setup(); Object.assign(iframe.style, activeStyles); } function hide() { const iframe = document.getElementById(ID); Object.assign(iframe.style, inactiveStyles); } const handlers = { [WIDGET_SHOW]: show, [WIDGET_HIDE]: hide, }; chrome.runtime.onMessage.addListener((message) => { const handler = handlers[message.type]; if (handler) { handler(message); } });
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: personnal/orderproducttime/detail // ================================================================================ { var i; var str = ""; weblet.loadClass("MneEditor", "editor/mne_editor.js"); weblet.loadCss('all.css', '/styles/editor'); var ivalues = { schema : 'mne_personnal', query : 'orderproducttime', table : 'orderproducttime', okschema : 'mne_personnal', okfunction : 'orderproducttime_ok', delschema : 'mne_personnal', delfunction : 'orderproducttime_del', producttimeoptschema : 'mne_personnal', producttimeoptquery : 'producttimeopt', ewidth : '570', /* ist etwa a4 */ eheight : '200' }; weblet.initDefaults(ivalues); weblet.loadview(); weblet.eleMkClass(weblet.origframe, "haveeditor" ); var attr = { hinput : false, setdurationInput : { inputtyp : "time" , onblur : function() { this.weblet.showInput(this.weblet.obj.inputs.setdurationsum, this.mne_timevalue * this.weblet.act_values.count, 'interval') } }, setdurationsumInput : { inputtyp : "time" , onblur : function() { if ( this.weblet.act_values.count != 0 ) this.weblet.showInput(this.weblet.obj.inputs.setduration, this.mne_timevalue / this.weblet.act_values.count, 'interval') } }, orderproductidInput : { notclear : true, checktype : 'keyvalue', inputcheckobject : "productname" }, productnameOutput : { notclear : true }, editor : { 'style.width' : this.initpar.ewidth + "px", 'style.height' : this.initpar.eheight + "px" } } weblet.findIO(attr); weblet.showLabel(); weblet.showids = new Array("orderproducttimeid"); weblet.titleString.add = weblet.txtGetText("#mne_lang#Bearbeitungsschritt hinzufügen"); weblet.titleString.mod = weblet.txtGetText("#mne_lang#Bearbeitungsschritt bearbeiten"); weblet.defvalues = { skillid : 'special' }; weblet.obj.editor = null; weblet.obj.editor_win = new MneEditor(weblet.win, weblet.frame.querySelector("#editor"), weblet.frame.querySelector("#editorbuttons")); weblet.obj.editor_win.parameter.mne_ajax = true; weblet.obj.editor_win.parameter.nohtml = true; weblet.obj.editor_win.plugins[weblet.obj.editor_win.plugins.length] = { name: "Xml", line: 1, output : weblet.obj.inputs.longdesc }; weblet.obj.editor_win.plugins[weblet.obj.editor_win.plugins.length] = { name: "Save", line: 1, pos : 0 }; weblet.obj.editor_win.plugins[weblet.obj.editor_win.plugins.length] = { name: "Clipboard", line: 1, pos : 0 }; weblet.obj.editor_win.plugins[weblet.obj.editor_win.plugins.length] = { name: "Itemize", line: 1 }; weblet.obj.editor_win.plugins[weblet.obj.editor_win.plugins.length] = { name: "Table", line: 1 }; weblet.obj.editor_win.show(function(editor){weblet.editor_loadready(editor); }); weblet.editor_loadready = function(editor) { this.obj.editor = editor; if ( typeof this.obj.pendingtext == 'string') { if ( this.obj.pendingtext == '' ) this.obj.editor.setContent(''); else { MneAjax.prototype.load.call(this, "/xmltext/html.html", { xmltext : this.obj.pendingtext, size : weblet.initpar.ewidth } ) this.obj.editor.setContent(this.req.responseText); } this.obj.pendingtext = false; } if ( typeof this.obj.resizetext == 'string') { this.obj.editor.setContent(this.obj.resizetext); this.obj.resizetext = false; } } weblet.reset = function() { if ( this.obj.editor != null ) this.obj.editor.destructor(); this.obj.editor = null; MneAjaxWeblet.prototype.reset.call(this); } weblet.setContent = function(text) { if ( this.obj.editor != null ) { if ( text != '' ) { MneAjax.prototype.load.call(this, "/xmltext/html.html", { xmltext : text, size : weblet.initpar.ewidth } ) this.obj.editor.setContent(this.req.responseText); } else { this.obj.editor.setContent(''); } } else this.obj.pendingtext = text; } weblet.showValue = function(weblet) { var i; if ( typeof this.obj.fire == 'object' && ( weblet == null || weblet.act_values.orderproducttimeid != this.act_values.orderproducttimeid) ) delete this.obj.fire; if ( weblet == null || typeof weblet.act_values.orderproducttimeid == 'undefined' || weblet.act_values.orderproducttimeid == null || weblet.act_values.orderproducttimeid == '' || weblet.act_values.orderid != this.act_values.orderid ) { this.add(); this.setContent(""); if ( weblet != null ) { this.act_values.orderid = weblet.act_values.orderid; if ( typeof weblet.act_values.orderproductid != 'undefined' ) { this.showInput("orderproductid", weblet.act_values.orderproductid); this.showOutput("productname", weblet.act_values.productname, this.typs[this.ids['productname']]); this.showInputDefined (this.obj.inputs.step, weblet.act_values.step, this.typs[this.ids['step']], true); this.showInputDefined (this.obj.inputs.setduration, weblet.act_values.setduration, this.typs[this.ids['setduration']], true); this.showInputDefined (this.obj.inputs.skillid, weblet.act_values.skillid, this.typs[this.ids['skillid']], true); this.showInputDefined (this.obj.inputs.description, weblet.act_values.description, this.typs[this.ids['description']], true); this.showOutputDefined(this.obj.outputs.count, weblet.act_values.count, this.typs[this.ids['count']]); this.act_values.count = weblet.act_values.count; } else { this.showInput("orderproductid", '', null, true); this.showOutput("productname", '', this.typs[this.ids['productname']], true); this.showInput (this.obj.inputs.step, '', this.typs[this.ids['step']], false); this.showInput (this.obj.inputs.setduration, 0, this.typs[this.ids['setduration']], true); this.showInput (this.obj.inputs.skillid, '', this.typs[this.ids['skillid']], true); this.showInput (this.obj.inputs.description, '', this.typs[this.ids['description']], true); this.showOutput(this.obj.outputs.count, 0, this.typs[this.ids['count']]); this.act_values.count = 0; } } return true; } MneAjaxWeblet.prototype.showValue.call(this,weblet); this.setContent(this.obj.inputs.longdesc.value); } weblet.checkmodified = function() { var result = MneAjaxWeblet.prototype.checkmodified.call(this); if ( this.obj.editor != null ) result = result || this.obj.editor.ismodifed; return result; } weblet.ok = function(setdepend) { this.obj.editor.save(); var p = { schema : this.initpar.okschema, name : this.initpar.okfunction, typ0 : "text", typ1 : "text", typ2 : "text", typ3 : "long", typ4 : "long", typ5 : "text", typ6 : "text", typ7 : "long", sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.orderproducttimeid); p = this.addParam(p, "par1", this.obj.inputs.orderproductid); p = this.addParam(p, "par2", this.obj.inputs.skillid); p = this.addParam(p, "par3", this.obj.inputs.setduration); p = this.addParam(p, "par4", this.obj.inputs.step); p = this.addParam(p, "par5", this.obj.inputs.description); p = this.addParam(p, "par6", this.obj.inputs.longdesc); p = this.addParam(p, "par7", this.obj.inputs.ready.checked ? 1 : 0); var result = MneAjaxWeblet.prototype.func.call(this, p, 'orderproducttimeid', setdepend); if ( result == false && this.inputlist != null && this.inputlist.element == 'step' && typeof this.obj.fire != 'undefined' && this.obj.fire.ele == this.inputlist_data['step']['button'] ) MneDocEvents.prototype.fireEvent.call( this, this.inputlist_data['step']['button'], 'click'); return result; } weblet.del = function(setdepend) { if ( typeof this.obj.fire != undefined ) delete this.obj.fire; if ( this.confirm(this.txtSprintf(this.titleString.del, this.act_values[this.titleString.delid])) != true ) return false; var p = { schema : this.initpar.delschema, name : this.initpar.delfunction, typ0 : "text", sqlend : 1 } p = this.addParam(p, "par0", this.obj.inputs.orderproducttimeid); return MneAjaxWeblet.prototype.func.call(this, p, null, setdepend ); } weblet.onbtnok = function(button) { if ( this.inputlist != null && this.inputlist.element == 'step' ) { if ( typeof this.obj.fire != 'undefined' && this.obj.fire.ele == this.inputlist_data['step']['button'] ) { button.weblet.initpar.notclose = true; if ( typeof this.onbtnobj != 'undefined' && this.onbtnobj != null ) this.onbtnobj.initpar.notclose = true; this.add(); } else { button.weblet.initpar.notclose = false; if ( typeof this.onbtnobj != 'undefined' && this.onbtnobj != null ) this.onbtnobj.initpar.notclose = false; } } else if ( typeof this.onbtnobj != 'undefined' && this.onbtnobj != null ) this.onbtnobj.initpar.notclose = false; return MneAjaxWeblet.prototype.onbtnok.call(this,button); } weblet.onbtnclick = function(id, button) { if ( typeof this.inputlist == 'undefined' || this.inputlist == null || id != 'ok' ) { if ( typeof this.obj.fire != undefined ) delete this.obj.fire; return; } if ( this.inputlist.element == 'productname' && this.obj.inputs.productoptid.value != '' ) { var ajax = new MneAjaxData(this.win); var param = { "schema" : weblet.initpar.producttimeoptschema, "query" : weblet.initpar.producttimeoptquery, "cols" : "producttimeid", "productidInput.old" : this.obj.inputs.productoptid.value, "sqlend" : 1 }; ajax.read("/db/utils/query/data.xml", param); if ( ajax.values.length > 0 && typeof this.inputlist_data['step'] == 'object' ) { MneDocEvents.prototype.fireEvent.call( this, this.inputlist_data['step']['button'], 'click'); return; } } else if ( this.inputlist.element == 'step' ) { return; } if ( typeof this.obj.fire != 'undefined' ) delete this.obj.fire; } weblet.wresize = function() { var e = weblet.eleGetById(weblet.frame, "editor"); if ( e != null ) { var h = this.origframe.offsetHeight - this.posGetTop(e, this.origframe) - this.posGetHeight(this.frame.querySelector('#modifyinfo')) - 28; if ( h < this.initpar.eheight ) h = this.initpar.eheight; e.style.height = h + "px"; weblet.obj.editor_win.resize(); } }; { var self = weblet; window.setTimeout(function() { if ( typeof self.popup == 'undefined' && self.popup == null ) self.wresize(); },200); } }
(function ($) { $.extend({ undefined: function () { for (var i = 0; i < arguments.length; i++) if (typeof arguments[i] != 'undefined') return false; return true; }, viewport: function () { var d = document.documentElement, b = document.body, w = window; return jQuery.extend( jQuery.browser.msie ? { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop } : { left: w.pageXOffset, top: w.pageYOffset }, !$.undefined(w.innerWidth) ? { width: w.innerWidth, height: w.innerHeight } : (!$.undefined(d) && !$.undefined(d.clientWidth) && d.clientWidth != 0 ? { width: d.clientWidth, height: d.clientHeight } : { width: b.clientWidth, height: b.clientHeight })); }, getDocHeight: function () { var b = document.body, e = document.documentElement, w = 0, h = 0; if (e) { //w = Math.max(w, e.scrollWidth, e.offsetWidth); h = Math.max(h, e.scrollHeight, e.offsetHeight); } if (b) { // w = Math.max(w, b.scrollWidth, b.offsetWidth); h = Math.max(h, b.scrollHeight, b.offsetHeight); if (window.innerWidth) { // w = Math.max(w, window.innerWidth); h = Math.max(h, window.innerHeight); } } return h; // [w, h]; }, toArguments: function (array) { return $.map(array, function (a) { return $(a).val(); }); }, queryString: function (key) { key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regex = new RegExp("[\\?&]" + key + "=([^&#]*)", 'ig'); var qs = regex.exec(window.location.href); if (qs == null) return null; else return qs[1]; }, bookmark: function (title, url) { if (window.sidebar) { // Mozilla Firefox Bookmark window.sidebar.addPanel(title, url, ""); } else if (window.external) { // IE Favorite window.external.AddFavorite(url, title); } else if (window.opera) { // Opera 7+ return false; // do nothing } else { alert('Unfortunately, this browser does not support the requested action, please bookmark this page manually.'); } return false; }, showDialog: function (url, opts) { var winH = $(window).height(); var winW = $(window).width(); var w = opts && opts.width > 0 ? opts.width : winW * 0.8; var h = opts && opts.height > 0 ? opts.height : winH * 0.8; var winX = (winW - w) * .5; var winY = (winH - h) * .5; window.showModalDialog(url, opts, 'dialogWidth:' + w + ',dialogHeight:' + h + ',center:1,modal:1;dialogTop:' + winY + ';dialogLeft:' + winX); }, toggleCheckbox: function (_state, _forClass) { // default var _class = 'input[type=checkbox].selected'; if (_forClass) _class = _forClass; $(_class).each(function () { $(this).attr("checked", _state); }); }, getItemsSelected: function (_forClass) { var _items = new Array(); var _class = 'input[type=checkbox].selected:checked'; if (_forClass) _class = _forClass; $(_class).each(function () { _items.push($(this).val()); }); return _items; }, scrollTo: function (target, duration) { if ($(target)) $('html,body').animate({ scrollTop: $(target).offset().top }, duration ? duration : 500); }, jump:function (url) { if (url.length > 0) { window.location = url; } }, Html: { encode: function (html) { html = html.replace(/&quot;/g, '&quotx;'); html = html.replace(/"/g, '&quot;'); html = html.replace(/&amp;/g, '&ampx;'); html = html.replace(/&/g, '&amp;'); html = html.replace(/&lt;/g, '&ltx;'); html = html.replace(/</g, '&lt;'); html = html.replace(/&gt;/g, '&gtx;'); html = html.replace(/>/g, '&gt;'); return html; }, democde: function (html) { html = html.replace(/&gt;/g, '>'); html = html.replace(/&gtx;/g, '&gt;'); html = html.replace(/&lt;/g, '<'); html = html.replace(/&ltx;/g, '&lt;'); html = html.replace(/&amp;/g, '&'); html = html.replace(/&ampx;/g, '&amp;'); html = html.replace(/&quot;/g, '"'); html = html.replace(/&quotx;/g, '&quot;'); return html; } }, String: { trim: function () { return this.replace(/^\s+|\s+$/g, ''); }, //if( $.StringEx.isNullOrEmpty('') ) alert('Empty string'); isNullOrEmpty: function (value) { if (value) { if (typeof (value) == 'string') { if (value.length > 0) return false; } if (value != null) return false; } return true; }, replace: function (source, oldVal, newVal) { var result = source; result = result.replace(new RegExp('\\' + oldVal + '\\', 'g'), newVal); return result; }, format: function (format) { var result = format; for (var i = 1; i < arguments.length; i++) { result = result.replace(new RegExp('\\{' + (i - 1) + '\\}', 'g'), arguments[i]); } return result; }, startsWith: function (str, prefix) { return str.indexOf(prefix) === 0; }, endsWith: function (str, suffix) { /*if (!suffix) return false; if (suffix.length > this.length) return false; if (ignoreCase) { if (ignoreCase == true) { return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase()); } } return (this.substr(this.length - suffix.length) === suffix);*/ return str.match(suffix + "$") == suffix; } }, Overlay: { defaults: { bg: '#333333', opacity: 0.3, width: '100%', showDuration: 500, hideDuration: 300 }, options: {}, getId: function () { return $($.String.format("#overlay_{0}", this.Id)); }, create: function (s) { this.options = s = $.extend({}, this.defaults, s || {}); this.Id = new Date().getTime(); var o = $($.String.format('<div id="overlay_{0}"></div>', this.Id)); $('body').append(o); o.css({ position: 'absolute', top: 0, left: 0, background: s.bg, opacity: s.opacity, zIndex: s.zIndex, width: s.width, height: $.getDocHeight()//$(document).outerHeight() }).hide().fadeIn(s.showDuration); //this.created = true; }, show: function (s) { if (this.Id) { this.getId().fadeIn(this.options.showDuration); } else { this.create(s); } }, hide: function () { this.getId().fadeOut(this.options.hideDuration); } }, Loading: { visibled: false, defaults: { theme: '', modal: 1, zIndex: 99999, position: ['center', 'center'], // ['center','top','right','bottom','left'] margin: 10 }, getId: function () { return $($.String.format("#loading_{0}", this.Id)); }, showPosition: function () { if (!this.visibled) return; var s = this.options; var e = this.getId(); var v = $.viewport(); var h = e.outerHeight(); var w = e.outerWidth(); var t = 0, l = 0; switch (s.position[0]) { default: case 'center': l = v.left + ((v.width - w) / 2); t = v.top + ((v.height - h) / 2); break; case 'top-left': t = v.top + s.margin; l = v.left + s.margin; break; case 'top-right': t = v.top + s.margin; l = v.left + v.width - w - s.margin * 2; break; case 'bottom-left': t = v.top + v.height - h - s.margin; l = v.left + s.margin; break; case 'bottom-right': t = v.top + v.height - h - s.margin; l = v.left + v.width - w - s.margin * 2; break; } if (this.animating) { this.animating.stop(); } e.show(); this.animating = e.animate({ top: t, left: l }, { duration: this.options.showDuration, queue: false }); }, setEvents: function () { $(window).bind('resize scroll', $.proxy(function () { this.showPosition(); }, this)); $(window).bind('keydown', $.proxy(function (e) { if (e.keyCode == 27) { this.hide(); e.preventDefault(); } }, this)); }, create: function (s) { this.Id = new Date().getTime(); var e = $($.String.format('<div id="loading_{0}" class="loading {1}"></div>', this.Id, s.theme)); $('body').append(e); e.css({ position: 'absolute', zIndex: s.zIndex }); this.showPosition(); this.setEvents(); //this.created = true; }, show: function (s, o) { this.options = s = $.extend({}, this.defaults, s || {}); if (this.options.modal) { o = $.extend(true, { zIndex: s.zIndex - 1 }, o || {}); $.Overlay.show(o); } this.visibled = true; if (this.Id) { this.showPosition(); } else { this.create(s); } }, hide: function () { if (this.options.modal) { $.Overlay.hide(); } this.getId().hide(); this.visibled = false; } }, Ajax: { defaults: { target: null, loading: true, data: null, resultMode: null, hashPwd: null, onRequest: null, onComplete: null, onError: null, method: 'POST', dataType: 'html' }, submit: function (f, options) { var _f = (typeof f == 'object') ? f : $('#' + f); var _s = $.extend({}, this.defaults, options || {}, $.metadata ? _f.metadata({ type: 'attr', name: 'data-ajax' }) : {}); if (window.tinymce && _f.find('.tinymce')) { window.tinyMCE.triggerSave(); }; /* if ($.validator && $.validator.unobtrusive) $.validator.unobtrusive.parse(_f);*/ //, invalidHandler: function () { _f.find(":input.error:first").focus(); } _f.validate({ meta: 'validate' }); if (_f.valid()) { if (_s.loading && $.Loading) { $.Loading.show(); }; if (_s.hashPwd && $.Hash) { _f.find(":password").each(function () { var _v = $(this).val(); if (_v.length > 0) $(this).val($.Hash.sha256(_v)); }); }; _f.find(":checkbox").each(function () { if (!$(this).attr('value')) $(this).val($(this).is(":checked")); }); if ($.isFunction(_s.onRequest)) { _s.onRequest.apply(); } $.ajax({ type: _s.method, url: _f.attr("action"), data: _f.serialize(), cache: false, statusCode: { 404: function () { alert('page not found'); } }, success: function (data) { if ((_s.dataType == 'html' || _s.dataType == 'text') && _s.target) { switch (_s.resultMode) { case 'append': $(_s.target).append(data); break; case 'prepend': $(_s.target).prepend(data); break; case 'replacewith': $(_s.target).replaceWith(data); break; case 'after': $(data).after($(_s.target)); break; case 'before': $(data).before($(_s.target)); break; default: $(_s.target).html(data); break; } } if (_s.onComplete) { if ($.isFunction(_s.onComplete)) _s.onComplete.apply(data); // _s.onComplete.call(this, data); else eval(_s.onComplete); } if (_s.hashPwd) { _f.find("input:password").val(''); } if (_s.loading && $.Loading) { $.Loading.hide(); } } }) .error(function (xhr, ajaxOptions, thrownError) { if (_s.onError) { if ($.isFunction(_s.onError)) _s.onError.call(this, xhr, ajaxOptions, thrownError); else eval(_s.onError); } else { alert('Error:' + xhr.status + '\n' + thrownError); } if (_s.loading && $.Loading) { $.Loading.hide(); } }); } // end validate }, load: function (u, o) { var _s = $.extend({}, this.defaults, o || {}); if (_s.loading && $.Loading) { $.Loading.show(); }; $.ajax({ type: 'GET', url: u, data:_s.data, success: function (data) { if ((_s.dataType == 'html' || _s.dataType == 'text') && _s.target) { switch (_s.resultMode) { case 'append': $(_s.target).append(data); break; case 'prepend': $(_s.target).prepend(data); break; case 'replacewith': $(_s.target).replaceWith(data); break; case 'after': $(data).after($(_s.target)); break; case 'before': $(data).before($(_s.target)); break; default: $(_s.target).html(data); break; } } if (_s.state && window.history.pushState) { history.pushState(null, _s.title, u); } if (_s.onComplete) { if ($.isFunction(_s.onComplete)) _s.onComplete.call(this, data); else eval(_s.onComplete); } if (_s.loading && $.Loading) { $.Loading.hide(); } /* if (window.history && window.history.pushState) { window.history.pushState(null, null, u); }*/ } }).error(function (xhr, ajaxOptions, thrownError) { if (_s.onError) { if ($.isFunction(_s.onError)) _s.onError.call(this, xhr, ajaxOptions, thrownError); else eval(_s.onError); } else { alert('Error:' + xhr.status + '\n' + thrownError); } }); } //end load } }); })(jQuery);
export const saveNote = () => { const clearAllBtn = document.getElementById('clear'); const saveBtn = document.getElementById('save'); const list = document.getElementById('note-list'); const userNote = document.getElementById('userNote'); const deleteBtn = document.getElementById('delete-single'); let noteItem; let noteId; //Create note and display in UI function entry(input, id) { const errorNote = document.getElementById('error-note'); if(input === '') { errorNote.innerHTML = 'No note to post'; } else { noteItem = document.createElement('li'); noteItem.innerHTML = input; //clear error note errorNote.textContent = ''; //Add noteId as id attribute to each entry noteItem.setAttribute('id', `note-${id}`); //Add note to the list list.appendChild(noteItem); // console.log(noteItem); } //select note to delete noteItem.addEventListener('click', function(e) { $(this).addClass('select-item'); $(this).siblings().removeClass('select-item'); }); //Delete selected note deleteBtn.addEventListener('click', function() { localStorage.removeItem($('.select-item').attr('id')); $('.select-item').remove(); }); }; const getLastIndex = () => { if (localStorage.length !== 0) { let changeToInt let lastIndexToInt; let newArr = []; let noteArr = []; for(let i = 0; i < localStorage.length; i++) { let noteStr = localStorage.key(i); let noteIndex = noteStr.match(/(\d+)/); if(noteIndex !== null ) { noteArr.push(noteIndex); } if(typeof noteArr[i] !== 'undefined'){ changeToInt = parseInt(noteArr[i][1]); newArr.push(changeToInt); // console.log(newArr); } } lastIndexToInt = Math.max(...newArr); // console.log(lastIndexToInt); noteId = lastIndexToInt + 1; } else { noteId = 0; } } //Save note saveBtn.addEventListener('click', (e) => { e.preventDefault(); if(localStorage.key(0)) { if(!localStorage.key(0).match(/(\d+)/)) { localStorage.clear(); } } getLastIndex(); //Add note to localStorage and assign note id localStorage.setItem(`note-${noteId}`, userNote.value); entry(userNote.value, noteId); userNote.value = ''; }); function loadPrevs() { if(localStorage) { getLastIndex(); for(let i = 0; i <= noteId; i++) { const lsKeys = localStorage.getItem(`note-${i}`); if(lsKeys) { entry(lsKeys, i); } } } } loadPrevs(); //Clear All notes clearAllBtn.addEventListener('click', function() { //Reset noteId when all list is cleared localStorage.clear(); while (list.firstChild) { list.removeChild(list.firstChild); } noteId = 0; }); };
define(function(require,exports,moduel){ //s焦点图轮播 function change(obj) { var aLi =obj.getElementsByTagName('ol')[0].getElementsByTagName('li'); var oUl = obj.getElementsByTagName('ul')[0]; var oDiv= obj.getElementsByTagName('div')[0] var aBtn=oDiv.getElementsByTagName('a'); var aLi2 = oUl.getElementsByTagName('li'); var iNow = 0; var iNow2 = 0; var timer = null; var onOff=true; var iLen=aLi2.length; var iWidth=aLi2[0].offsetWidth; oUl.style.width=iLen*iWidth+'px'; obj.onmouseover=function() { clearInterval(timer); oDiv.style.display="block"; } obj.onmouseout=function() { startRun (); oDiv.style.display="none"; } //往前按钮 aBtn[0].onclick=function() { iNow--; if(iNow==-1) { iNow=0; } iNow2--; if(iNow2==-1) { iNow2=0; } toRun(); } //往后按钮 aBtn[1].onclick=function() { iNow++; iNow%=aLi.length; iNow2++; iNow2%=aLi2.length; toRun(); } //鼠标滑过圆点图片滚动 for(var i=0;i<aLi.length;i++){ aLi[i].index = i; aLi[i].onmouseover = function(){ for(var i=0;i<aLi.length;i++){ aLi[i].className = ''; }; this.className = 'active'; require('./move.js').startMove(oUl,{'left' : -iWidth*this.index}); iNow = this.index; iNow2 = this.index; clearInterval(timer); }; aLi[i].onmouseout = function(){ //timer = setInterval(toRun,2000); startRun (); }; } function startRun () { if(timer) { clearInterval(timer); } timer = setInterval(function(){ iNow++; iNow%=aLi.length; iNow2++; iNow2%=aLi2.length; toRun(); },2000); } startRun ();//初始化 function toRun(){ for(var i=0;i<aLi.length;i++){ aLi[i].className = ''; }; aLi[iNow].className = 'active'; require('./move.js').startMove(oUl,{ left : -iWidth * iNow2}); } toRun();//初始化 } exports.change=change; //e焦点图轮播 //s商品列表页面的商品自动切换 function changeList(obj) { var oUl=obj.getElementsByTagName('ul')[0]; var aLi_ul=oUl.getElementsByTagName('li'); var oOl=obj.getElementsByTagName('ol')[0]; var aLi_ol=oOl.getElementsByTagName('li'); var num = 0; var timert = null; for(var i=0;i<aLi_ol.length;i++){ aLi_ol[i].index = i; aLi_ol[i].onmouseover = function(){ for(var i=0;i<aLi_ol.length;i++){ aLi_ol[i].className = ''; require('./move.js').startMove(aLi_ul[i],{opacity:0}); aLi_ul[i].style.zIndex = 1; } this.className = 'active'; aLi_ul[this.index].style.zIndex = 2; require('./move.js').startMove(aLi_ul[this.index],{opacity:100}); num = this.index; }; } obj.onmouseover = function(){ clearInterval(timert); }; obj.onmouseout = function(){ timert = setInterval(toChanges,2400); }; timert = setInterval(toChanges,2400); function toChanges() { num++; num%=aLi_ol.length; for(var i=0;i<aLi_ol.length;i++){ aLi_ol[i].className = ''; require('./move.js').startMove(aLi_ul[i],{opacity:0}); aLi_ul[i].style.zIndex = 1; } aLi_ol[num].className = 'active'; aLi_ul[num].style.zIndex = 2; require('./move.js').startMove(aLi_ul[num],{opacity:100}); } } exports.changeList=changeList; //s导航菜单显示 function show(oLi) { oLi.onmouseover=function() { oLi.className=''; this.className='show'; this.getElementsByTagName('div')[0].style.display="block"; } oLi.onmouseout=function() { this.className='default'; this.getElementsByTagName('div')[0].style.display="none"; } } exports.show=show; //倒计时 function daoJs () { var oTime=document.getElementById('time'); var aInp= oTime.getElementsByTagName('input'); var iNow = new Date(); var iNew = new Date( 'February 27,2017 12:30:00' ); var t = Math.floor((iNew - iNow)/1000); var str=toTwo(Math.floor(t/86400))+toTwo(Math.floor(t%86400/3600)) +toTwo(Math.floor(t%86400%3600/60)) +toTwo(t%60); aInp[0].value = str.substring(0,2); aInp[1].value = str.substring(2,4); aInp[2].value = str.substring(4,6); aInp[3].value = str.substring(6,8); } function toTwo ( n ) {//返回两位数 return n < 10 ? '0' + n : '' + n; } exports.daoJs=daoJs; //返回顶部 function toTop(btn) { var timer2=null; var isTop=true; var clientHeight=document.documentElement.clientHeight; var oTop=document.documentElement.scrollTop||document.body.scrollTop; require('./move.js').bindEvent(window,'scroll',function(){ if(!isTop){ clearInterval(timer2); } isTop=false; }) btn.onclick=function(){ clearInterval(timer2); timer2=setInterval(function(){ //获取滚动条距离顶部距离 var oTop=document.documentElement.scrollTop||document.body.scrollTop; var iSpeed=Math.floor(-oTop/10); document.documentElement.scrollTop=document.body.scrollTop=oTop+iSpeed; isTop=true;//判断是否是点击按钮触发 // console.log(oTop+iSpeed); if(oTop==0){ clearInterval(timer2); } },30); } } exports.toTop=toTop; //两边悬浮导航出现 function showBar(obj) { // var isIE = !!window.ActiveXObject; // var isIE6 = isIE && !window.XMLHttpRequest; var clientHeight=document.documentElement.clientHeight; var clientWidth=document.documentElement.clientWidth; var oTop=document.documentElement.scrollTop||document.body.scrollTop; if(oTop>500&&clientWidth>800){//距离顶部大于500,出现悬浮菜单 require('./move.js').startMove(obj,{opacity:100}); }else { require('./move.js').startMove(obj,{opacity:0}); } } exports.showBar=showBar; //input 获取焦点 function showText(obj,txt) { //onfocus : 当元素获取到焦点的时候触发 obj.onfocus=function() { if(obj.value==txt) { obj.value=''; } } //onblur : 当元素失去焦点的时候触发 obj.onblur=function() { if(obj.value=='') { obj.value=txt; } } } exports.showText=showText; //图片预加载 function showImg(obj) { var showImg=obj.getElementsByTagName('img'); var arrImg=[]; for(var i=0;i<showImg.length;i++) { if(showImg[i].getAttribute('_src')) { arrImg.push(showImg[i]); } } for(var i=0;i<arrImg.length;i++) { arrImg[i].att=true; } function toImg() { var iScroll=document.documentElement.scrollTop||document.body.scrollTop; var iClient=document.documentElement.clientHeight; for(var i=0;i<arrImg.length;i++) { if(require('./move.js').posTop(arrImg[i])<iClient+iScroll&&arrImg[i].att) { arrImg[i].src=arrImg[i].getAttribute('_src'); arrImg[i].style.opacity=0; arrImg[i].style.filter='alpha(opacity:0)'; require('./move.js').startMove(arrImg[i],{opacity:100}); arrImg[i].att=false; } } } toImg(); require('./move.js').bindEvent(window,'scroll',function(){ toImg(); }); } exports.showImg=showImg; //导航定位效果 function detailTop() { var oMain=document.getElementById('main'); var oDh_lf=document.getElementById('dh_lf'); var oUl=oDh_lf.getElementsByTagName('ul')[0]; var aLi=oUl.getElementsByTagName('a'); var acTop=require('./move.js').getByClass(oMain,'act_top'); //var acNav=getByClass(oMain,'act_nav'); var num=0; var oDh_h=oDh_lf.offsetHeight; var isTop=true; var topArr=[]; var sTop=document.documentElement.scrollTop||document.body.scrollTop; for(var i=0;i<aLi.length;i++) { aLi[i].index=i; aLi[i].onclick=function() { //获取滚动条距离顶部距离 isTop=true;//判断是否是点击按钮触发 num=this.index; scrollTop(); } } //定位到对应的楼层初始化 function scrollTop() { for(var i=0;i<aLi.length;i++) { aLi[i].className=''; } aLi[num].className='cur'; document.documentElement.scrollTop=document.body.scrollTop=require('./move.js').posTop(acTop[num])-70; } scrollTop(); //console.log(posTop(acTop[0]));//976 //console.log(posTop(acTop[1])); //1444 } exports.detailTop=detailTop; function scrollClass() { var oMain=document.getElementById('main'); var oDh_lf=document.getElementById('dh_lf'); var oUl=oDh_lf.getElementsByTagName('ul')[0]; var aLi=oUl.getElementsByTagName('a'); var acTop=require('./move.js').getByClass(oMain,'act_top'); var sTop=document.documentElement.scrollTop||document.body.scrollTop; for(var i=0;i<aLi.length;i++) { if(sTop>acTop[i+1].offsetTop+200) { for(var j=0;j<aLi.length;j++) { aLi[j].className=''; } aLi[i].className='cur'; console.log(acTop[i].offsetTop); } } } exports.scrollClass=scrollClass; //改变背景颜色 function changeBg(obj) { var oMain=document.getElementById('main'); var actLf=require('./move.js').getByClass(obj,'act_my_lf'); var arr=['#f99aae','#a69ad8','#bbb','#c0a89c','#92b74d','#f67474','#90a8c2','#f4ab44']; for(var i=0;i<actLf.length;i++) { actLf[i].style.background=arr[i%actLf.length]; } } exports.changeBg=changeBg; //tab切换 function tab(obj1,obj2,sclName1,sclName2) { var aLi=obj1.getElementsByTagName('li'); var actLike=require('./move.js').getByClass(obj2,sclName1); for(var i=0;i<aLi.length;i++) { aLi[i].index=i; aLi[i].onclick=function() { for(var i=0;i<aLi.length;i++) { aLi[i].className='fl'; //actLike[i].className=sclName1+'none clearfix'; require('./move.js').addClass(actLike[i],'none'); } require('./move.js').addClass(aLi[this.index],sclName2); require('./move.js').removeClass(actLike[this.index],'none'); } } } exports.tab=tab; function bigImg(){ var oDic=document.getElementById('bigPic'); var small_dd=document.getElementById('small_dd'); var oMark=require('./move.js').getByClass(oDic,'mark')[0]; var oFloat=require('./move.js').getByClass(oDic,'float_layer')[0]; var oBig=require('./move.js').getByClass(oDic,'big_pic')[0]; var oSmall=require('./move.js').getByClass(oDic,'small_pic')[0]; var oImg=oBig.getElementsByTagName('img')[0]; console.log(oDic); console.log(oImg); oDic.onmouseover=function () { oFloat.style.display='block'; oBig.style.display='block'; }; oDic.onmouseout=function () { oFloat.style.display='none'; oBig.style.display='none'; }; oDic.onmousemove=function (ev) { var oEvent=ev||event; var l=oEvent.clientX-oDic.offsetLeft-oFloat.offsetWidth/2; var t=oEvent.clientY-oDic.offsetTop-oFloat.offsetHeight/2; console.log(oDic.offsetLeft); console.log(oSmall.offsetLeft); console.log(oFloat.offsetWidth/2); console.log(l); if(l<0) { l=0; } else if(l>oDic.offsetWidth-oFloat.offsetWidth) { l=oDic.offsetWidth-oFloat.offsetWidth; } if(t<0) { t=0; } else if(t>oDic.offsetHeight-oFloat.offsetHeight) { t=oDic.offsetHeight-oFloat.offsetHeight; } oFloat.style.left=l+'px'; oFloat.style.top=t+'px'; var percentX=l/(oDic.offsetWidth-oFloat.offsetWidth); var percentY=t/(oDic.offsetHeight-oFloat.offsetHeight); oImg.style.left=-percentX*(oImg.offsetWidth-oBig.offsetWidth)+'px'; oImg.style.top=-percentY*(oImg.offsetHeight-oBig.offsetHeight)+'px'; }; } exports.bigImg=bigImg; function changeImg() { var small_dd=document.getElementById('small_dd'); var aLi=small_dd.getElementsByTagName('a'); var num=0; console.log(aLi); var smallImg=document.getElementById('small_img'); var bigImg=document.getElementById('big_img'); var aImgArr=['images/detail/small1.jpg','images/detail/small2.jpg','images/detail/small3.jpg','images/detail/small4.jpg','images/detail/small5.jpg']; var aImgArr2=['images/detail/big1.jpg','images/detail/big2.jpg','images/detail/big3.jpg','images/detail/big4.jpg','images/detail/big5.jpg']; for(var i=0;i<aLi.length;i++) { aLi[i].index=i; aLi[i].onclick=function() { num=this.index; fnTab(); } } function fnTab(){ smallImg.src = aImgArr[num]; bigImg.src = aImgArr2[num]; for( var i=0; i<aLi.length; i++ ){ aLi[i].className = ''; } aLi[num].className = 'active'; } fnTab(); } exports.changeImg=changeImg; });
$(function () { //閉じる $('#BtnClose').click(function () { parent.$.closeDialog(); }); //***************************************************** //var CheckNum; //var mode; const MaxDispLinePopCommentTemplate = 15; var NowDispMax; var Comment = {}; //───────────────────────────────────── //機能: コメントテンプレート画面Load時イベント //引数: //戻値: //補足: //───────────────────────────────────── $(document).ready(function () { var url = "./Pages/PopCommentTemplate/PopCommentTemplate.aspx/GetJsonCommentData"; var data = JSON.stringify({ }); var result = parent.$.getAjaxData(url, data); //エラーの場合 if (result.match(/エラー:/)) { alert(result); return false; } var cmtData = JSON.parse(result); if (cmtData == null) { $.pageInit(null); } else { $.pageInit(cmtData["template_table"]); //テーブル名 } $.pageDisplay(); }); //───────────────────────────────────── //機能: コメントテンプレート画面 初期化 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInitMain = function () { NowDispMax = MaxDispLinePopCommentTemplate; Comment = {}; for (trCnt = 0; trCnt < NowDispMax; trCnt++) { Comment[trCnt] = ""; } } //───────────────────────────────────── //機能: コメントテンプレート画面 初期データ編集 //引数: //戻値: //補足: //───────────────────────────────────── $.pageInit = function (cmtData) { // 変数初期化 $.pageInitMain(); //最大表示件数 if (cmtData == null) { NowDispMax = 0; } else if (Object.keys(cmtData).length < MaxDispLinePopCommentTemplate) { NowDispMax = Object.keys(cmtData).length; } else { NowDispMax = MaxDispLinePopCommentTemplate; } //検索結果 if (NowDispMax > 0) { for (trCnt = 0; trCnt < NowDispMax; trCnt++) { Comment[trCnt] = cmtData[trCnt]["Comment"]; //trimしない } } } //───────────────────────────────────── //機能: コメントテンプレート画面 初期データ表示 //引数: //戻値: //補足: //───────────────────────────────────── $.pageDisplay = function () { $("#template_table").children().remove(); var table_html = ""; // 一覧を表示 table_html += '<table class="template_table">'; //データありの場合 if (NowDispMax > 0) { //TODO:データをセットする for (trCnt = 1; trCnt <= NowDispMax; trCnt++) { table_html += ' <tr>'; table_html += ' <th style="width: 70px">定型文' + trCnt + '</th>'; table_html += ' <td>'; table_html += ' <textarea name="template' + trCnt + '" id="template' + trCnt + '">' + Comment[trCnt -1] + '</textarea>'; table_html += ' </td>'; table_html += ' <td style="width: 90px">'; table_html += ' <p>'; table_html += ' <input type="button" value="備考へ挿入" onclick="estimateSystemTemplateCommentRef(\' ' + trCnt + ' \');" />'; table_html += ' </p>'; table_html += ' <p class="save_btn">'; table_html += ' <input type="button" value="保 存" onclick="estimateSystemTemplateCommentSave(\' ' + trCnt + ' \');" />'; table_html += ' </p>'; table_html += ' </td>'; table_html += ' </tr>'; } //データなしの場合 } else { table_html += ' <tr>'; table_html += ' <th style="width: 70px">定型文</th>'; table_html += ' <td>'; table_html += ' <textarea name="template1" id="template1"></textarea>'; table_html += ' </td>'; table_html += ' <td style="width: 90px">'; table_html += ' <p>'; table_html += ' <input type="button" value="備考へ挿入" onclick="estimateSystemTemplateCommentRef(\'1\');" />'; table_html += ' </p>'; table_html += ' <p class="save_btn">'; table_html += ' <input type="button" value="保 存" onclick="estimateSystemTemplateCommentSave(\'1\');" />'; table_html += ' </p>'; table_html += ' </td>'; table_html += ' </tr>'; } table_html += '</table>'; $("#template_table").append(table_html); } }); // *********************************************** // イベント // *********************************************** // コメントテンプレートの反映ボタン 20200330 MOVE FROM estimate_system.js function estimateSystemTemplateCommentRef(seq) { //詳細画面のid=Otherに、定型文を最後に追加 //20200401 EDIT //window.opener.document.getElementById("Other").value += document.getElementById("template" + seq).value; var newComment = document.getElementById("template" + seq).value; var parentComment = parent.$("#Other").val(); parent.$("#Other").val(parentComment + newComment); //20200401 EDIT //window.close(); parent.$.closeDialog(); } // コメントテンプレートの保存ボタン 20200330 MOVE FROM estimate_system.js function estimateSystemTemplateCommentSave(seq) { document.getElementById("SaveNo").value = seq; //20200330 EDIT //document.comment_template.submit(); //本番 var SaveComment = document.getElementById("template" + seq).value; var url = "./Pages/PopCommentTemplate/PopCommentTemplate.aspx/SetJsonCommentData"; //TODO:日本語はUrlEncode必要!!!h ttp://surferonwww.info/BlogEngine/post/2011/11/07/Encoding-of-URL-directly-written-in-address-bar-of-browser.aspx var data = JSON.stringify({ SaveNo: seq, Comment: SaveComment }); var result = parent.$.getAjaxData(url, data); //エラーの場合 //Common.js ajaxがreturn ""設定の場合 if (result.match(/エラー:/)) { alert(result); return false; } var message = JSON.parse(result); //if (message == null) { // alert("該当データが見つかりませんでした。"); // return false; //} //if (message.length == 0) { // alert("該当データが見つかりませんでした。"); // return false; //} //if (Object.keys(message).length == 0) { // alert("該当データが見つかりませんでした。"); // return false; //} //結果表示 alert(message["aaa"][0]["message"]); //TODO:仮テーブル名 return false; }
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app') var inputValue = document.getElementsByClassName("auth-enter"); var onFocus = function() { this.parentElement.classList.add("active-input-box"); this.previousElementSibling.classList.add("active-input"); }; var onBlur = function() { var value_login = this.value; if (value_login == 0) { this.parentElement.classList.remove("active-input-box"); this.previousElementSibling.classList.remove("active-input"); } }; for (let i = 0; i < inputValue.length; i++) { inputValue[i].addEventListener("focus", onFocus, false); inputValue[i].addEventListener("blur", onBlur, false); } var inputPassword = document.getElementsByClassName("password-show"); var onMousedown = function() { this.previousElementSibling.setAttribute('type', 'text'); }; var onMouseup = function() { this.previousElementSibling.setAttribute('type', 'password'); }; var onMouseout = function() { this.previousElementSibling.setAttribute('type', 'password'); } for (let i = 0; i < inputPassword.length; i++) { inputPassword[i].addEventListener("mousedown", onMousedown, false); inputPassword[i].addEventListener("mouseup", onMouseup, false); inputPassword[i].addEventListener("mouseout", onMouseout, false); }
var map_socket = io.connect('http://' + document.domain + ':' + location.port + '/map'); map_socket.on('new map', function(data) { $('#map-panel').html('<img src="'+data.value+'">'); }); map_socket.emit('map'); $('#map-button').click(function(event) { map_socket.emit('map'); });
$( document ).ready(function() { console.log( "ready!" ); $('#createButton').click(function () { let public = $('#public').prop("checked") === true; var result = confirm("Are you sure that you want to create this experiment?"); if (result) { $.ajax({ url:"newExperiment?ename=" + $('#experiment_Name').val() + "&pid=" + $('#selectProject').val() + "&description=" + $('#description').val() + "&public="+ public, type: "post", success: function (res) { alert('Your experiment has been created.'); window.location.href = '/projectTab'; } }); } }); });
import React from 'react'; import { Link } from 'react-router'; import Star from '../Star'; export default ({review}) => { return ( <div> <h4>{review.title}</h4> <Star numStars={review.stars} /> <p>By {review.user && review.user.name} on {review.date}</p> <p>{review.body}</p> </div> ) }
/** * @author v.lugovsky * created on 16.12.2015 */ (function() { 'use strict'; angular.module('ROA.pages.dashboard', []) .config(function($stateProvider) { $stateProvider .state('dashboard', { url: '/dashboard', templateUrl: 'app/pages/dashboard/dashboard.html', title: 'Dashboard', sidebarMeta: { icon: 'ion-android-home', order: 0 }, controller: 'DashboardCtrl', data: { requireLogin: true } }); }) .controller('DashboardCtrl', ['$rootScope', '$scope', 'layoutColors', 'layoutPaths', '$filter', 'Map','RestApi', '$state', function($rootScope, $scope, layoutColors, layoutPaths, $filter, Map, RestApi, $state) { $scope.pacientes_totales = 0; $scope.pacientes_riesgo = 0; $scope.pacientes_sin_riesgo = 0; RestApi.getDashboard() .then(function (result) { $scope.pacientes_totales = result.total; $scope.pacientes_riesgo = result.enRiesgo; $scope.pacientes_sin_riesgo = result.sinRiesgo; $scope.alertas = result.alertas; $scope.loadChart(result.riskPerAge); }) .catch(function(error){ }); $scope.scrollbarConfig = { autoHideScrollbar: false, theme: 'dark', scrollInertia: 400, axis: 'y' }; // Variables $scope.citiesList = []; $scope.insights = []; $scope.geocodeCities = function() { Map.GeocodeSet($scope.citiesList); }; $scope.calcularRiesgoTotal = function(){ var continueTo = confirm('Esta acción puede tardar algunos minutos, ¿Está seguro de continuar?'); if(continueTo){ $state.go('calcularRiesgoTotal'); } }; // Load the daily revenue bar chart component $scope.loadChart = function(data) { var new_data = []; data.map(function (currentValue,index,arr) { new_data.push({count: parseInt(currentValue.count), edad: parseInt(currentValue.edad)}); }); console.log(data); console.log(new_data); // Risk per age chart var barChart = AmCharts.makeChart('barChart', { type: 'serial', theme: 'blur', color: layoutColors.defaultText, chartScrollbar: { scrollbarHeight: 10 }, mouseWheelZoomEnabled: true, "export": { "enabled": true }, dataProvider: new_data, valueAxes: [{ axisAlpha: 0, position: 'right', title: 'Cantidad de Pacientes', gridAlpha: 0.5, gridColor: '#00AFBF' }], startDuration: 1, graphs: [{ fillColorsField: 'color', fillAlphas: 1, lineAlpha: 0.2, type: 'column', valueField: 'count' }], chartCursor: { categoryBalloonEnabled: true, cursorAlpha: 1, zoomable: true, cursorColor: '#ff0000', selectionAlpha: 0.5 }, chartCursorSettings: { }, categoryField: 'edad', categoryAxis: { gridPosition: 'start', labelRotation: 45, gridAlpha: 1, gridColor: layoutColors.border }, pathToImages: 'assets/img/' }); }; } ]); })();
// GENERATED CODE -- DO NOT EDIT! 'use strict'; var grpc = require('grpc'); var webfont_pb = require('./webfont_pb.js'); function serialize_webfontsdk_AccessKeyInfo(arg) { if (!(arg instanceof webfont_pb.AccessKeyInfo)) { throw new Error('Expected argument of type webfontsdk.AccessKeyInfo'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_AccessKeyInfo(buffer_arg) { return webfont_pb.AccessKeyInfo.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_FontBuildAccessKeyRequest(arg) { if (!(arg instanceof webfont_pb.FontBuildAccessKeyRequest)) { throw new Error('Expected argument of type webfontsdk.FontBuildAccessKeyRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_FontBuildAccessKeyRequest(buffer_arg) { return webfont_pb.FontBuildAccessKeyRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_FontBuildBufResult(arg) { if (!(arg instanceof webfont_pb.FontBuildBufResult)) { throw new Error('Expected argument of type webfontsdk.FontBuildBufResult'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_FontBuildBufResult(buffer_arg) { return webfont_pb.FontBuildBufResult.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_FontBuildRequest(arg) { if (!(arg instanceof webfont_pb.FontBuildRequest)) { throw new Error('Expected argument of type webfontsdk.FontBuildRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_FontBuildRequest(buffer_arg) { return webfont_pb.FontBuildRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_FontListRequest(arg) { if (!(arg instanceof webfont_pb.FontListRequest)) { throw new Error('Expected argument of type webfontsdk.FontListRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_FontListRequest(buffer_arg) { return webfont_pb.FontListRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_FontListResult(arg) { if (!(arg instanceof webfont_pb.FontListResult)) { throw new Error('Expected argument of type webfontsdk.FontListResult'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_FontListResult(buffer_arg) { return webfont_pb.FontListResult.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_GetAccessKeyInfoRequest(arg) { if (!(arg instanceof webfont_pb.GetAccessKeyInfoRequest)) { throw new Error('Expected argument of type webfontsdk.GetAccessKeyInfoRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_GetAccessKeyInfoRequest(buffer_arg) { return webfont_pb.GetAccessKeyInfoRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_GetFontListReply(arg) { if (!(arg instanceof webfont_pb.GetFontListReply)) { throw new Error('Expected argument of type webfontsdk.GetFontListReply'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_GetFontListReply(buffer_arg) { return webfont_pb.GetFontListReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_GetFontListRequest(arg) { if (!(arg instanceof webfont_pb.GetFontListRequest)) { throw new Error('Expected argument of type webfontsdk.GetFontListRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_GetFontListRequest(buffer_arg) { return webfont_pb.GetFontListRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_GetMultGlyfsUnicodeRequest(arg) { if (!(arg instanceof webfont_pb.GetMultGlyfsUnicodeRequest)) { throw new Error('Expected argument of type webfontsdk.GetMultGlyfsUnicodeRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_GetMultGlyfsUnicodeRequest(buffer_arg) { return webfont_pb.GetMultGlyfsUnicodeRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_GetMultGlyfsUnicodeResult(arg) { if (!(arg instanceof webfont_pb.GetMultGlyfsUnicodeResult)) { throw new Error('Expected argument of type webfontsdk.GetMultGlyfsUnicodeResult'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_GetMultGlyfsUnicodeResult(buffer_arg) { return webfont_pb.GetMultGlyfsUnicodeResult.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_GetProfileWithoutMapRequest(arg) { if (!(arg instanceof webfont_pb.GetProfileWithoutMapRequest)) { throw new Error('Expected argument of type webfontsdk.GetProfileWithoutMapRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_GetProfileWithoutMapRequest(buffer_arg) { return webfont_pb.GetProfileWithoutMapRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_GetProfileWithoutMapResult(arg) { if (!(arg instanceof webfont_pb.GetProfileWithoutMapResult)) { throw new Error('Expected argument of type webfontsdk.GetProfileWithoutMapResult'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_GetProfileWithoutMapResult(buffer_arg) { return webfont_pb.GetProfileWithoutMapResult.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_HelloReply(arg) { if (!(arg instanceof webfont_pb.HelloReply)) { throw new Error('Expected argument of type webfontsdk.HelloReply'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_HelloReply(buffer_arg) { return webfont_pb.HelloReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_HelloRequest(arg) { if (!(arg instanceof webfont_pb.HelloRequest)) { throw new Error('Expected argument of type webfontsdk.HelloRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_HelloRequest(buffer_arg) { return webfont_pb.HelloRequest.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_MultFontBuildBufResult(arg) { if (!(arg instanceof webfont_pb.MultFontBuildBufResult)) { throw new Error('Expected argument of type webfontsdk.MultFontBuildBufResult'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_MultFontBuildBufResult(buffer_arg) { return webfont_pb.MultFontBuildBufResult.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_webfontsdk_MultFontBuildRequest(arg) { if (!(arg instanceof webfont_pb.MultFontBuildRequest)) { throw new Error('Expected argument of type webfontsdk.MultFontBuildRequest'); } return Buffer.from(arg.serializeBinary()); } function deserialize_webfontsdk_MultFontBuildRequest(buffer_arg) { return webfont_pb.MultFontBuildRequest.deserializeBinary(new Uint8Array(buffer_arg)); } // The greeting service definition. var GreeterService = exports.GreeterService = { // Sends a greeting sayHello: { path: '/webfontsdk.Greeter/SayHello', requestStream: false, responseStream: false, requestType: webfont_pb.HelloRequest, responseType: webfont_pb.HelloReply, requestSerialize: serialize_webfontsdk_HelloRequest, requestDeserialize: deserialize_webfontsdk_HelloRequest, responseSerialize: serialize_webfontsdk_HelloReply, responseDeserialize: deserialize_webfontsdk_HelloReply, }, // BuildFont buildFont: { path: '/webfontsdk.Greeter/BuildFont', requestStream: false, responseStream: false, requestType: webfont_pb.FontBuildRequest, responseType: webfont_pb.FontBuildBufResult, requestSerialize: serialize_webfontsdk_FontBuildRequest, requestDeserialize: deserialize_webfontsdk_FontBuildRequest, responseSerialize: serialize_webfontsdk_FontBuildBufResult, responseDeserialize: deserialize_webfontsdk_FontBuildBufResult, }, // BuildFontForAccessKey buildFontForAccessKey: { path: '/webfontsdk.Greeter/BuildFontForAccessKey', requestStream: false, responseStream: false, requestType: webfont_pb.FontBuildAccessKeyRequest, responseType: webfont_pb.FontBuildBufResult, requestSerialize: serialize_webfontsdk_FontBuildAccessKeyRequest, requestDeserialize: deserialize_webfontsdk_FontBuildAccessKeyRequest, responseSerialize: serialize_webfontsdk_FontBuildBufResult, responseDeserialize: deserialize_webfontsdk_FontBuildBufResult, }, // MultBuildFont multBuildFont: { path: '/webfontsdk.Greeter/MultBuildFont', requestStream: false, responseStream: false, requestType: webfont_pb.MultFontBuildRequest, responseType: webfont_pb.MultFontBuildBufResult, requestSerialize: serialize_webfontsdk_MultFontBuildRequest, requestDeserialize: deserialize_webfontsdk_MultFontBuildRequest, responseSerialize: serialize_webfontsdk_MultFontBuildBufResult, responseDeserialize: deserialize_webfontsdk_MultFontBuildBufResult, }, // Get my fontlist fontList: { path: '/webfontsdk.Greeter/FontList', requestStream: false, responseStream: false, requestType: webfont_pb.FontListRequest, responseType: webfont_pb.FontListResult, requestSerialize: serialize_webfontsdk_FontListRequest, requestDeserialize: deserialize_webfontsdk_FontListRequest, responseSerialize: serialize_webfontsdk_FontListResult, responseDeserialize: deserialize_webfontsdk_FontListResult, }, // GetProfile getProfileWithoutMap: { path: '/webfontsdk.Greeter/GetProfileWithoutMap', requestStream: false, responseStream: false, requestType: webfont_pb.GetProfileWithoutMapRequest, responseType: webfont_pb.GetProfileWithoutMapResult, requestSerialize: serialize_webfontsdk_GetProfileWithoutMapRequest, requestDeserialize: deserialize_webfontsdk_GetProfileWithoutMapRequest, responseSerialize: serialize_webfontsdk_GetProfileWithoutMapResult, responseDeserialize: deserialize_webfontsdk_GetProfileWithoutMapResult, }, // GetUnicodeIndexs // rpc GetUnicodeIndexs(GetUnicodeIndexsRequest) returns (GetUnicodeIndexsResult) {} // // GetGlyfs Index // rpc GetGlyfsIndex(GetGlyfsIndexRequest) returns (GetGlyfsIndexResult) {} // // GetGlyfs Unicode // rpc GetGlyfsUnicode(GetGlyfsUnicodeRequest) returns (GetGlyfsUnicodeResult) {} // // GetMultGlyfsUnicode getMultGlyfsUnicode: { path: '/webfontsdk.Greeter/GetMultGlyfsUnicode', requestStream: false, responseStream: false, requestType: webfont_pb.GetMultGlyfsUnicodeRequest, responseType: webfont_pb.GetMultGlyfsUnicodeResult, requestSerialize: serialize_webfontsdk_GetMultGlyfsUnicodeRequest, requestDeserialize: deserialize_webfontsdk_GetMultGlyfsUnicodeRequest, responseSerialize: serialize_webfontsdk_GetMultGlyfsUnicodeResult, responseDeserialize: deserialize_webfontsdk_GetMultGlyfsUnicodeResult, }, // 获得厂商列表和字体列表 getFontList: { path: '/webfontsdk.Greeter/GetFontList', requestStream: false, responseStream: false, requestType: webfont_pb.GetFontListRequest, responseType: webfont_pb.GetFontListReply, requestSerialize: serialize_webfontsdk_GetFontListRequest, requestDeserialize: deserialize_webfontsdk_GetFontListRequest, responseSerialize: serialize_webfontsdk_GetFontListReply, responseDeserialize: deserialize_webfontsdk_GetFontListReply, }, // 获得AccessKey getAccessKeyInfo: { path: '/webfontsdk.Greeter/GetAccessKeyInfo', requestStream: false, responseStream: false, requestType: webfont_pb.GetAccessKeyInfoRequest, responseType: webfont_pb.AccessKeyInfo, requestSerialize: serialize_webfontsdk_GetAccessKeyInfoRequest, requestDeserialize: deserialize_webfontsdk_GetAccessKeyInfoRequest, responseSerialize: serialize_webfontsdk_AccessKeyInfo, responseDeserialize: deserialize_webfontsdk_AccessKeyInfo, }, }; exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
import React from 'react'; import ReactTestUtils from 'react-dom/test-utils'; import { render, screen, fireEvent } from '@testing-library/react'; import { getInstance } from '@test/testUtils'; import Modal from '../Modal'; import SelectPicker from '../../SelectPicker'; describe('Modal', () => { it('Should render the modal content', () => { const instance = getInstance( <Modal open> <p>message</p> </Modal> ); assert.equal(instance.querySelectorAll('p').length, 1); }); it('Should close the modal when the modal dialog is clicked', () => { const onCloseSpy = sinon.spy(); const { getByTestId } = render(<Modal data-testid="wrapper" open onClose={onCloseSpy} />); fireEvent.click(getByTestId('wrapper')); assert.isTrue(onCloseSpy.calledOnce); }); it('Should not close the modal when the "static" dialog is clicked', () => { const onCloseSpy = sinon.spy(); const { getByTestId } = render( <Modal data-testid="wrapper" open onClose={onCloseSpy} backdrop="static" /> ); fireEvent.click(getByTestId('wrapper')); assert.isFalse(onCloseSpy.calledOnce); }); it('Should not close the modal when clicking inside the dialog', () => { const onCloseSpy = sinon.spy(); const { getByRole } = render(<Modal open onClose={onCloseSpy} />); fireEvent.click(getByRole('dialog')); fireEvent.click(getByRole('document')); assert.isFalse(onCloseSpy.calledOnce); }); it('Should be automatic height', () => { const instance = getInstance( <Modal overflow open> <Modal.Body style={{ height: 2000 }} /> </Modal> ); assert.equal(instance.querySelector('.rs-modal-body').style.overflow, 'auto'); }); it('Should call onClose callback', () => { const onCloseSpy = sinon.spy(); const instance = getInstance( <Modal open onClose={onCloseSpy}> <Modal.Header /> </Modal> ); const closeButton = instance.querySelector('.rs-modal-header-close'); ReactTestUtils.Simulate.click(closeButton); assert.isTrue(onCloseSpy.calledOnce); }); it('Should call onExited callback', done => { const doneOp = () => { done(); }; const ref = React.createRef(); class Demo extends React.Component { constructor(props) { super(props); this.state = { open: true }; this.handleClose = this.handleClose.bind(this); } handleClose() { this.setState({ open: false }); } render() { return ( <Modal ref={ref} open={this.state.open} onClose={this.handleClose} onExited={doneOp}> <Modal.Header /> </Modal> ); } } getInstance(<Demo />); const closeButton = ref.current.querySelector('.rs-modal-header-close'); ReactTestUtils.Simulate.click(closeButton); }); it('Should have a custom className', () => { const instance = getInstance(<Modal className="custom" open />); assert.isNotNull(instance.querySelector('.custom')); }); it('Should have a custom style', () => { const fontSize = '12px'; const instance = getInstance(<Modal style={{ fontSize }} open />); assert.equal(instance.style.fontSize, fontSize); }); it('Should have a custom className prefix', () => { const instance = getInstance(<Modal classPrefix="custom-prefix" open />); assert.isNotNull(instance.className.match(/\bcustom-prefix\b/)); }); it('Should call onOpen callback', () => { const onOpenSpy = sinon.spy(); const ref = React.createRef(); const App = React.forwardRef((props, ref) => { const [open, setOpen] = React.useState(false); React.useImperativeHandle(ref, () => ({ openModal: () => { setOpen(true); } })); return ( <Modal {...props} onOpen={onOpenSpy} open={open}> <Modal.Header /> </Modal> ); }); render(<App ref={ref} />); ref.current.openModal(); assert.ok(onOpenSpy.calledOnce); }); it('Should call onClose callback by Esc', () => { const onCloseSpy = sinon.spy(); render( <Modal open onClose={onCloseSpy}> <Modal.Header /> </Modal> ); const event = new KeyboardEvent('keydown', { key: 'Escape' }); document.dispatchEvent(event); assert.isTrue(onCloseSpy.calledOnce); }); it('Should be rendered inside Modal', () => { const ref = React.createRef(); const { getByRole } = render( <Modal open ref={ref}> <Modal.Body> <SelectPicker open data={[{ value: 1, label: 1 }]} /> </Modal.Body> </Modal> ); assert.isNotEmpty(getByRole('listbox')); }); describe('Focused state', () => { let focusableContainer = null; beforeEach(() => { focusableContainer = document.createElement('div'); focusableContainer.tabIndex = 0; document.body.appendChild(focusableContainer); focusableContainer.focus(); }); afterEach(() => { document.body.removeChild(focusableContainer); }); it('Should focus on the Modal when it is opened', () => { const onOpenSpy = sinon.spy(); const App = React.forwardRef((props, ref) => { const [open, setOpen] = React.useState(false); const modalRef = React.useRef(); React.useImperativeHandle(ref, () => ({ get dialog() { return modalRef.current; }, openModal: () => { setOpen(true); } })); return ( <Modal {...props} ref={modalRef} onOpen={onOpenSpy} open={open}> <Modal.Header /> </Modal> ); }); const ref = React.createRef(); render(<App ref={ref} />); assert.equal(document.activeElement, focusableContainer); ref.current.openModal(); assert.isTrue(onOpenSpy.calledOnce); assert.equal(document.activeElement, ref.current.dialog); }); it('Should be forced to focus on Modal', () => { const ref = React.createRef(); render( <Modal ref={ref} open backdrop={false} enforceFocus> test </Modal> ); focusableContainer.focus(); focusableContainer.dispatchEvent(new FocusEvent('focus')); assert.equal(document.activeElement, ref.current); }); it('Should be focused on container outside of Modal', () => { const ref = React.createRef(); render( <Modal ref={ref} open backdrop={false} enforceFocus={false}> test </Modal> ); focusableContainer.focus(); focusableContainer.dispatchEvent(new FocusEvent('focus')); assert.equal(document.activeElement, focusableContainer); }); it('Should only call onOpen once', () => { const onOpenSpy = sinon.spy(); render(<Modal open onOpen={onOpenSpy}></Modal>); assert.equal(onOpenSpy.callCount, 1); }); }); describe('Size variants', () => { const sizes = ['lg', 'md', 'sm', 'xs', 'full']; sizes.forEach(size => { const expectedClassName = `rs-modal-${size}`; it(`Should have .${expectedClassName} class when size=${size}`, () => { render(<Modal open size={size}></Modal>); expect(screen.getByRole('dialog')).to.have.class(expectedClassName); }); }); // Remove this case when full prop is dropped it('[Deprecated] Should have .rs-modal-full class when full=true', () => { sinon.spy(console, 'warn'); render(<Modal open full></Modal>); expect(screen.getByRole('dialog')).to.have.class('rs-modal-full'); expect(console.warn).to.have.been.calledWith( '"full" property of "Modal" has been deprecated.\nUse size="full" instead.' ); }); }); describe('a11y', () => { it('Should render an ARIA dialog with given title as its accessible name', () => { const title = 'Attention'; render( <Modal open> <Modal.Header> <Modal.Title>{title}</Modal.Title> </Modal.Header> <p>Message</p> </Modal> ); expect(screen.getByRole('dialog', { name: title })).to.be.visible; }); it('Should accept custom ID on dialog', () => { const id = 'my-dialog'; render( <Modal open id={id}> <p>Message</p> </Modal> ); expect(screen.getByRole('dialog')).to.have.attr('id', id); }); it('Should accept `aria-labelledby` and `aria-describedby` on dialog', () => { const labelId = 'modal-title'; const labelText = 'My Title'; const descriptionId = 'modal-description'; render( <Modal open aria-labelledby={labelId} aria-describedby={descriptionId}> <Modal.Header> <Modal.Title id={labelId}>{labelText}</Modal.Title> </Modal.Header> <Modal.Body id={descriptionId}>My Description</Modal.Body> </Modal> ); expect(screen.getByRole('dialog', { name: labelText })).to.have.attr( 'aria-describedby', descriptionId ); }); it('Should allow overriding the dialog role', () => { const title = 'Attention'; render( <Modal open role="alertdialog"> <Modal.Header> <Modal.Title>{title}</Modal.Title> </Modal.Header> <p>Message</p> </Modal> ); expect(screen.getByRole('alertdialog', { name: title })).to.be.visible; }); }); });
// ================================================== // ==== JEND v1.11.1 ==== // 基于jQuery v1.3.2,在旧版JEND基础上扩展,包括以下方法集合: // - JS原型方法扩展、 jQuery方法扩展 // - JEND方法库: core/json/base/util/page // ================================================== // -------------------------------- // String/Number/Array/Date.prototype // -------------------------------- (function($) { if (!$) return; // ---------------------------- // String原型方法扩展 $.extend(String.prototype, { 'trim': function() { return this.replace(/(^\s*)|(\s*$)/g,''); }, 'ltrim': function() { return this.replace(/(^\s*)/g,''); }, 'rtrim': function() { return this.replace(/(\s*$)/g,''); }, 'trimAll': function() { return this.replace(/\s/g,''); }, 'left': function(len) { return this.substring(0, len); }, 'right': function(len) { if (this.length <= len) { return this.toString(); } return this.substring(this.length-len, this.length); }, 'reverse': function() { return this.split('').reverse().join(''); }, 'startWith': function(start, noCase) { var index = noCase ? this.toLowerCase().indexOf(start.toLowerCase()) : this.indexOf(start); return !index; }, 'endWith': function(end, noCase) { return noCase ? (new RegExp(end.toLowerCase()+"$").test(this.toLowerCase().trim())) : (new RegExp(end+"$").test(this.trim())); }, 'sliceAfter': function(str) { if (this.indexOf(str)<0) return ''; return this.substring(this.indexOf(str)+str.length, this.length); }, 'sliceBefore': function(str) { if (this.indexOf(str)<0) return ''; return this.substring(0, this.indexOf(str)); }, 'getByteLength': function() { return this.replace(/[^\x00-\xff]/ig, 'xx').length; }, 'subByte': function(len, s) { if (len<0 || this.getByteLength()<=len) { return this.toString(); } var str = this; str = str.substr(0,len).replace(/([^\x00-\xff])/g,"\x241 ").substr(0,len).replace(/[^\x00-\xff]$/,"").replace(/([^\x00-\xff]) /g,"\x241"); return str + (s||''); }, 'textToHtml': function() { return this.replace(/</ig,'&lt;').replace(/>/ig,'&gt;').replace(/\r\n/ig,'<br>').replace(/\n/ig,'<br>'); }, 'htmlToText': function() { return this.replace(/<br>/ig, '\r\n'); }, 'htmlEncode': function() { var text = this; var re = {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}; for (var i in re) { text = text.replace(new RegExp(i,'g'), re[i]); } return text; }, 'htmlDecode': function() { var text = this; var re = {'&lt;':'<','&gt;':'>','&amp;':'&','&quot;':'"'}; for (var i in re) { text = text.replace(new RegExp(i,'g'), re[i]); } return text; }, 'stripHtml': function() { return this.replace(/(<\/?[^>\/]*)\/?>/ig, ''); }, 'stripScript': function() { return this.replace(/<script(.|\n)*\/script>\s*/ig, '').replace(/on[a-z]*?\s*?=".*?"/ig,''); }, 'replaceAll': function(os, ns) { return this.replace(new RegExp(os,"gm"),ns); }, 'escapeReg': function() { return this.replace(new RegExp("([.*+?^=!:\x24{}()|[\\]\/\\\\])", "g"), '\\\x241'); }, 'getQueryValue': function(name) { var reg = new RegExp("(^|&|\\?|#)" + name.escapeReg() + "=([^&]*)(&|\x24)", ""); var match = this.match(reg); return (match) ? match[2] : ''; }, 'getQueryJson': function() { var query = this.substr(this.indexOf('?') + 1), params = query.split('&'), len = params.length, result = {}, key, value, item, param; for (var i=0; i < len; i++) { param = params[i].split('='); key = param[0]; value = param[1]; item = result[key]; if ('undefined' == typeof item) { result[key] = value; } else if (Object.prototype.toString.call(item) == '[object Array]') { item.push(value); } else { result[key] = [item, value]; } } return result; }, 'getPathName': function() { return (this.lastIndexOf('?')==-1)?this.toString():this.substring(0,this.lastIndexOf('?')); }, 'getFilePath': function() { return this.substring(0,this.lastIndexOf('/')+1); }, 'getFileName': function() { return this.substring(this.lastIndexOf('/')+1); }, 'getFileExt': function() { return this.substring(this.lastIndexOf('.')+1); }, 'parseDate': function() { return (new Date()).parse(this.toString()); }, 'parseJSON': function() { try { return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(this.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + this.toString() + ')'); } catch (e) { return false; } }, 'parseAttrJSON': function() { var d = {}, a = this.toString().split(';'); for (var i=0; i<a.length; i++) { if (a[i].trim() == '' || a[i].indexOf(':')<1) continue; var b = a[i].split(':'); if (b[0].trim() != '' && b[1].trim()!='') d[b[0].toCamelCase()] = b[1]; } return d; }, // 将ID串转化为EAN-13 'toEAN13': function(pre) { var len = 12 - pre.length; var str = pre + ((this.length>=len)?this.left(len):this.padLeft(len, '0')); var a=0, b=0, c=0, d=str.reverse(); for (var i=0; i<d.length; i++) { if (i%2) { b += parseInt(d.charAt(i)); } else { a += parseInt(d.charAt(i)); } } if ((a*3 + b)%10) { c = 10 - (a*3 + b)%10; } return str + c; }, 'formatToDSS': function() { var m = this.match(/^http(?:s)?:\/\/([^:\/]*)(:\d+)?([^\?]*)/); var a = ''; if (m[1].match(/^[\d\.]*$/)) { a = '/ip/' + m[1]; } else { var b = m[1].split('.'); for (var i = b.length; i > 0; i--) { a += '/' + b[i - 1]; } } if (m[2]) { a += '/' + m[2]; } return a + m[3]; }, 'formatToDSSID': function() { return this.formatToDSS().replace(/\//g, '_'); }, 'toMapObject': function(sep) { var sep = sep || '/'; var s = this.split(sep); var d = {}; var o = function(a, b, c) { if (c < b.length) { if (!a[b[c]]) { a[b[c]] = {}; } d = a[b[c]]; o(a[b[c]], b, c + 1); } }; o(window, s, 1); return d; }, '_pad': function(width, ch, side) { var str = [side?'':this, side?this:'']; while (str[side].length < (width?width:0) && (str[side] = str[1] + (ch||' ') + str[0])); return str[side]; }, 'padLeft': function(width, ch) { if (this.length>=width) return this.toString(); return this._pad(width, ch, 0); }, 'padRight': function(width, ch) { if (this.length>=width) return this.toString(); return this._pad(width, ch, 1); }, 'toHalfWidth': function() { return this.replace(/[\uFF01-\uFF5E]/g, function(c) { return String.fromCharCode(c.charCodeAt(0) - 65248); }).replace(/\u3000/g, " "); }, 'toCamelCase': function() { if (this.indexOf('-') < 0 && this.indexOf('_') < 0) { return this.toString(); } return this.replace(/[-_][^-_]/g, function (match) { return match.charAt(1).toUpperCase(); }); }, 'format': function() { var result = this; if (arguments.length > 0) { parameters = $.makeArray(arguments); $.each(parameters, function(i, n) { result = result.replace(new RegExp("\\{" + i + "\\}", "g"), n); }); } return result; }, 'substitute': function(data) { if (data && typeof(data)=='object') { return this.replace(/\{([^{}]+)\}/g, function(match, key) { var value = data[key]; return (value !== undefined) ? ''+value :''; }); } else { return this.toString(); } } }); // String原型方法扩展: 数据校验相关 $.extend(String.prototype, { 'isURL': function() { return (new RegExp(/(http[s]?|ftp):\/\/[^\/\.]+?\..+\w$/i).test(this.trim())); }, 'isDate': function() { var result = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); if (result==null) return false; var d = new Date(result[1], result[3]-1, result[4]); return (d.getFullYear()==result[1] && d.getMonth()+1==result[3] && d.getDate()==result[4]); }, 'isTime': function() { var result = this.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/); if (result==null) return false; if (result[1]>24 || result[3]>60 || result[4]>60) return false; return true; }, // 需要测试一下 'isDateTime': function() { var result = this.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/); if (result==null) return false; var d = new Date(result[1], result[3]-1, result[4], result[5], result[6], result[7]); return (d.getFullYear()==result[1] && (d.getMonth()+1)==result[3] && d.getDate()==result[4] && d.getHours()==result[5] && d.getMinutes()==result[6] && d.getSeconds()==result[7]); }, // 整数 'isInteger': function() { return (new RegExp(/^(-|\+)?\d+$/).test(this.trim())); }, // 正整数 'isPositiveInteger': function() { return (new RegExp(/^\d+$/).test(this.trim())) && parseInt(this)>0; }, // 负整数 'isNegativeInteger': function() { return (new RegExp(/^-\d+$/).test(this.trim())); }, 'isNumber': function() { return !isNaN(this); }, 'isEmail': function() { return (new RegExp(/^([_a-zA-Z\d\-\.])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/).test(this.trim())); }, 'isMobile': function() { return (new RegExp(/^(13|14|15|18)\d{9}$/).test(this.trim())); }, 'isPhone': function() { return (new RegExp(/^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/).test(this.trim())); }, 'isAreacode': function() { return (new RegExp(/^0\d{2,3}$/).test(this.trim())); }, 'isPostcode': function() { return (new RegExp(/^\d{6}$/).test(this.trim())); }, 'isLetters': function() { return (new RegExp(/^[A-Za-z]+$/).test(this.trim())); }, 'isDigits': function() { return (new RegExp(/^[1-9][0-9]+$/).test(this.trim())); }, 'isAlphanumeric': function() { return (new RegExp(/^[a-zA-Z0-9]+$/).test(this.trim())); }, 'isValidString': function() { return (new RegExp(/^[a-zA-Z0-9\s.\-_]+$/).test(this.trim())); }, 'isLowerCase': function() { return (new RegExp(/^[a-z]+$/).test(this.trim())); }, 'isUpperCase': function() { return (new RegExp(/^[A-Z]+$/).test(this.trim())); }, 'isChinese': function() { return (new RegExp(/^[\u4e00-\u9fa5]+$/).test(this.trim())); }, 'isIDCard': function() { //这里没有验证有效性,只验证了格式 var r15 = new RegExp(/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/); var r18 = new RegExp(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/); return (r15.test(this.trim()) || r18.test(this.trim())); }, // 卡号校验 模10检查 'isCardNo': function(cardType) { var cards = { "UleCard": { lengths: "16", prefixes: "", checkdigit: true }, "Visa": { lengths: "13,16", prefixes: "4", checkdigit: true }, "MasterCard": { lengths: "16", prefixes: "51,52,53,54,55", checkdigit: true }, "BankCard": { lengths: "16,19", prefixes: "3,4,5,6,9", checkdigit: true } }; if (!cards[cardType]) return false; var cardNo = this.replace(/[\s-]/g, ""); // remove spaces and dashes var cardexp = /^[0-9]{13,19}$/; if (cardNo.length==0 || !cardexp.exec(cardNo)) { return false; } else { cardNo = cardNo.replace(/\D/g, ""); // strip down to digits var modTenValid = true; var prefixValid = false; var lengthValid = false; // 模10检查 if (cards[cardType].checkdigit) { var checksum = 0, mychar = "", j = 1, calc; for (i = cardNo.length - 1; i >= 0; i--) { calc = Number(cardNo.charAt(i)) * j; if (calc > 9) { checksum = checksum + 1; calc = calc - 10; } checksum = checksum + calc; if (j == 1) { j = 2 } else { j = 1 }; } if (checksum % 10 != 0) modTenValid = false; } if (cards[cardType].prefixes=='') { prefixValid = true; } else { // 前缀字符检查 var prefix = cards[cardType].prefixes.split(","); for (i=0; i<prefix.length; i++) { var exp = new RegExp("^" + prefix[i]); if (exp.test(cardNo)) prefixValid = true; } } // 卡号长度检查 var lengths = cards[cardType].lengths.split(","); for (j=0; j<lengths.length; j++) { if (cardNo.length == lengths[j]) lengthValid = true; } if (!modTenValid || !prefixValid || !lengthValid) { return false; } else { return true; } } }, 'isUleCard': function() { return this.isCardNo('UleCard'); }, 'isVisa': function() { return this.isCardNo('Visa'); }, 'isMasterCard': function() { return this.isCardNo('MasterCard'); }, // 判断是否为符合EAN规则的条形码串 'isValidEAN': function() { var code = this.trim(); var a=0, b=0, c=parseInt(code.right(1)), d=code.left(code.length-1).reverse(); for (var i=0; i<d.length; i++) { if (i%2) { b += parseInt(d.charAt(i)); } else { a += parseInt(d.charAt(i)); } } return ((a*3 + b + c)%10)?false:true; }, // 判断是否为符合EAN-8规则的条形码串 'isEAN8': function() { var code = this.trim(); return (new RegExp(/^\d{8}$/).test(code)) && code.isValidEAN(); }, // 判断是否为符合EAN-12规则的条形码串 'isEAN12': function() { var code = this.trim(); return (new RegExp(/^\d{12}$/).test(code)) && code.isValidEAN(); }, // 判断是否为符合EAN-13规则的条形码串 'isEAN13': function() { var code = this.trim(); return (new RegExp(/^\d{13}$/).test(code)) && code.isValidEAN(); }, // 判断是否为符合ISBN-10规则的条形码串 'isISBN10': function() { var code = this.trim(); if (!new RegExp(/^\d{9}([0-9]|X|x)$/).test(code)) return false; var a=0, b=code.right(1), c=code.reverse(); for (var i=1; i<c.length; i++) { a += parseInt(c.charAt(i)) * (i+1); } if (b=='X' || b=='x') b = 10; return ((a+parseInt(b))%11)?false:true; }, 'isISBN': function() { return this.isEAN13(); }, 'isEANCode': function() { return this.isEAN8() || this.isEAN12() || this.isEAN13() || this.isISBN10(); } }); // Number原型方法扩展 $.extend(Number.prototype, { 'comma': function(length) { if (!length || length < 1) length = 3; source = (''+this).split("."); source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{'+length+'})+$)','ig'),"$1,"); return source.join("."); }, 'randomInt': function(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); }, 'padLeft': function(width, ch) { return (''+this).padLeft(width, ch); }, 'padRight': function(width, ch) { return (''+this).padRight(width, ch); } }); // Array原型方法扩展 $.extend(Array.prototype, { 'indexOf': function(item, it) { for (var i=0; i<this.length; i++) { if (item == ((it)?this[i][it]:this[i])) return i; } return -1; }, 'remove': function(item, it) { this.removeAt(this.indexOf(item, it)); }, 'removeAt': function(idx) { if (idx >= 0 && idx < this.length) { for (var i=idx; i<this.length-1; i++) { this[i] = this[i+1]; } this.length --; } }, 'removeEmpty': function() { var arr = []; for (var i=0; i<this.length; i++) { if (this[i].trim()!='') { arr.push(this[i].trim()); } } return arr; }, 'add': function(item) { if (this.indexOf(item)>-1) { return false; } else { this.push(item); return true; } }, 'swap': function(i, j) { if (i<this.length && j<this.length && i!=j) { var item = this[i]; this[i] = this[j]; this[j] = item; } }, // 过滤数组,两种过滤情况 'filter': function(it, item) { var arr = []; for (var i=0; i<this.length; i++) { if (typeof(item)=='undefined') { arr.push(this[i][it]); } else if (this[i][it] == item) { arr.push(this[i]); } } return arr; }, 'sortby': function(it, dt, od) { // it: item name dt: int, char od: asc, desc var compareValues = function(v1, v2, dt, od) { if (dt == 'int') { v1 = parseInt(v1); v2 = parseInt(v2); } else if (dt == 'float') { v1 = parseFloat(v1); v2 = parseFloat(v2); } var ret = 0; if (v1 < v2) ret = 1; if (v1 > v2) ret = -1; if (od == 'desc') { ret = 0 - ret; } return ret; }; var newdata = new Array(); for (var i=0; i<this.length; i++) { newdata[newdata.length] = this[i]; } for (var i=0; i<newdata.length; i++) { var minIdx = i; var minData = (it != '') ? newdata[i][it] : newdata[i]; for (var j=i+1; j<newdata.length; j++) { var tmpData = (it != '') ? newdata[j][it] : newdata[j]; var cmp = compareValues(minData, tmpData, dt, od); if (cmp<0) { minIdx = j; minData = tmpData; } } if (minIdx > i) { var _child = newdata[minIdx]; newdata[minIdx] = newdata[i]; newdata[i] = _child; } } return newdata; } }); // Date原型方法扩展 $.extend(Date.prototype, { 'parse': function(time) { if (typeof(time)=='string') { if (time.indexOf('GMT')>0 || time.indexOf('gmt')>0 || !isNaN(Date.parse(time))) { return this.parseGMT(time); } else if (time.indexOf('UTC')>0 || time.indexOf('utc')>0 || time.indexOf(',')>0) { return this.parseUTC(time); } else { return this.parseCommon(time); } } return new Date(); }, 'parseGMT': function(time) { this.setTime(Date.parse(time)); return this; }, 'parseUTC': function(time) { return (new Date(time)); }, 'parseCommon': function(time) { var d = time.split(/ |T/), d1 = d.length > 1 ? d[1].split(/[^\d]/) : [0, 0, 0], d0 = d[0].split(/[^\d]/); return new Date(d0[0]-0, d0[1]-1, d0[2]-0, d1[0]-0, d1[1]-0, d1[2]-0); }, 'dateAdd': function(type, val) { var _y = this.getFullYear(); var _m = this.getMonth(); var _d = this.getDate(); var _h = this.getHours(); var _n = this.getMinutes(); var _s = this.getSeconds(); switch(type) { case 'y': this.setFullYear(_y + val); break; case 'm': this.setMonth(_m + val); break; case 'd': this.setDate(_d + val); break; case 'h': this.setHours(_h + val); break; case 'n': this.setMinutes(_n + val); break; case 's': this.setSeconds(_s + val); break; } return this; }, 'dateDiff': function(type, date2) { var diff = date2 - this; switch(type) { case 'w': return diff / 1000 / 3600 / 24 / 7; case 'd': return diff / 1000 / 3600 / 24; case 'h': return diff / 1000 / 3600; case 'n': return diff / 1000 / 60; case 's': return diff / 1000; } }, 'format': function(format) { if (isNaN(this)) return ''; var o = { 'm+': this.getMonth()+1, 'd+': this.getDate(), 'h+': this.getHours(), 'n+': this.getMinutes(), 's+': this.getSeconds(), 'S': this.getMilliseconds(), 'W': ["日", "一", "二", "三", "四", "五", "六"][this.getDay()], 'q+': Math.floor((this.getMonth()+3)/3) }; if (format.indexOf('am/pm')>=0) { format = format.replace('am/pm', (o['h+']>=12)?'下午':'上午'); if (o['h+'] >= 12) o['h+'] -= 12; } if(/(y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("("+ k +")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); } } return format; } }); })(jQuery); // -------------------------------- // jQuery extend // -------------------------------- (function($) { if (!$) return; // ---------------------------- // $.browser方法扩展 $.extend($.browser, { 'client': function() { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight, bodyWidth: document.body.clientWidth, bodyHeight: document.body.clientHeight }; }, 'scroll': function() { return { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight, bodyWidth: document.body.scrollWidth, bodyHeight: document.body.scrollHeight, left: Math.max(document.documentElement.scrollLeft, document.body.scrollLeft), top: Math.max(document.documentElement.scrollTop, document.body.scrollTop) }; }, 'screen': function() { return { width: window.screen.width, height: window.screen.height }; }, 'isMinW': function(val) { return Math.min($.browser.client().bodyWidth, $.browser.client().width) <= val; }, 'isMinH': function(val) { return Math.min($.browser.client().bodyHeight, $.browser.client().height) <= val; }, 'isIE6': $.browser.msie && $.browser.version == 6, 'isIPad': (/iPad/i).test(navigator.userAgent), 'language': function() { return (navigator.language || navigator.userLanguage || '').toLowerCase(); } }); // ---------------------------- // 获取DSS接口数据,源自JEND.DSS.get方法 $.getDSS = function(url, params, onSuccess, onError) { if ($.isFunction(params)) { onError = onSuccess; onSuccess = params; params = null; } var o = url.formatToDSS().toMapObject(); if (params) url += (url.match(/\?/)?'&':'?')+ $.param(params); var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.type = 'text/javascript'; script.src = url; script.onload = script.onreadystatechange = function(){ if ( !this.readyState || this.readyState == "loaded" || this.readyState == "complete") { try { if (o.$ && onSuccess) { onSuccess(o.$); } else { if (onError) onError(); } } catch(e) { if (onError) onError(); } script.onload = script.onreadystatechange = null; head.removeChild(script); } }; script.onerror = function() { if (onError) onError(); }; head.appendChild(script); }; // ---------------------------- // 获取tagName $.fn.tagName = function() { if (this.length==0) return ''; if (this.length>1) { var tagNames = []; this.each(function(i, el) { tagNames.push(el.tagName.toLowerCase()); }); return tagNames; } else { return this[0].tagName.toLowerCase(); } }; // 获取select的文本 $.fn.optionText = function(attr) { if (this.length==0) return ''; var sel = this[0]; if (sel.selectedIndex==-1) return ''; return sel.options[sel.selectedIndex].text; }; // 获取element属性的JSON值 $.fn.attrJSON = function(attr) { return (this.attr(attr||'rel')||'').parseAttrJSON(); }; // 绑定jQuery UI事件处理 $.fn.bindJqueryUI = function(action, params) { var elm = this; JEND.load('jqueryui', function() { elm[action](params); }); }; // 绑定JEND.ui事件处理 $.fn.bindJendUI = function(type, params) { if (this.size()==0 || !JEND) return; if (JEND.ui && JEND.ui[type]) { JEND.ui[type](this, params); } else { this.bindJendUIExtend('ui', type, params); } }; // 绑定JEND.ui扩展事件处理 $.fn.bindJendUIExtend = function(file, type, params) { if (this.size()==0 || !JEND) return; var elm = this; JEND.load(file, function() { setTimeout(function() { if (!JEND.ui[type]) return; JEND.ui[type](elm, params); }, 500); }); }; // ---------------------------- })(jQuery); // -------------------------------- // JEND core // 保留旧版方法:Exception/flash/namespace/lang/DOM/DSS/cookie // 新增方法:JEND.debug/load // -------------------------------- (function($) { // ---------------------------- if (!$) return; // ---------------------------- if (!window.JEND) window.JEND = {}; // ---------------------------- // 旧版JEND的保留方法 JEND.Exception = function(pO, pID, pStr) { JEND.Exception[pO+'_'+pID] = pStr; }; JEND.flash = function(pSwf, pBoxID, pW, pH, pVer, pSetup, pFlashvars, pParams, pAttr) { pSetup = pSetup || false; pFlashvars = pFlashvars || false; pParams = pParams || false; pAttr = pAttr || false; JEND.load('swfobject', function() { swfobject.embedSWF(pSwf, pBoxID, pW, pH, pVer, pSetup, pFlashvars, pParams, pAttr); }); }; // JEND.namespace 命名空间 JEND.namespace = function(pStr) { if (typeof(pStr) === 'string') { pStr = '.' + pStr; JEND.lang.mapObject(pStr); } }; // JEND.lang JEND.lang = {}; JEND.lang.mapObject = function(pStr, pSplit) { pSplit = pSplit || '.'; return pStr.toMapObject(pSplit); }; // JEND.DOM JEND.DOM = {}; JEND.DOM.create = function(pTagName, pTagP, pText) { var dom = document.createElement(pTagName); if (typeof(pTagP)=='object') { for (var property in pTagP) { dom[property] = pTagP[property]; } } else { pText = pTagP; } if (pText) { dom.appendChild(document.createTextNode(pText)); } return dom; }; // JEND.DSS JEND.DSS = {}; JEND.DSS.get = function(pSrc, pCallback, pException) { if ($.isFunction(pException)) { $.getDSS(pSrc, null, pCallback, pException); } else if (typeof(pException)=='object') { $.getDSS(pSrc, pException, pCallback); } else { $.getDSS(pSrc, null, pCallback); } }; JEND.DSS.formatToDSS = function(pStr) { return pStr.formatToDSS(); }; JEND.DSS.formatToDSSID = function(pStr) { return pStr.formatToDSSID(); }; // JEND.cookie JEND.cookie = {}; JEND.cookie.load = function(tKey) { var tC = document.cookie.split('; '); var tO = {}; var a = null; for (var i = 0; i < tC.length; i++) { a = tC[i].split('='); tO[a[0]] = a[1]; } return tO; }; JEND.cookie.set = function() { var d = new Date(); var i = arguments.length; var key = i>0 ? arguments[0] : 'undefined'; var value = i>1 ? arguments[1] : ''; var expires = i>2 ? d.setTime(d.getTime() + (arguments[2] * 1000 * 60)) : null; var path = i>3 ? arguments[3] : null; var domain = i>4 ? arguments[4] : null; document.cookie = key + '=' + escape(value) + ((expires === null) ? '' : (';expires=' + d.toGMTString())) + ((path === null) ? '' : (';path=' + path)) + ((domain === null) ? '' : (';domain=' + domain)); return this.get(key); }; JEND.cookie.get = function(tKey) { if (this.load()[tKey]) { try { return decodeURI(this.load()[tKey]); } catch(e) { return unescape(this.load()[tKey]); } } else { return false; } }; JEND.cookie.del = function(tKey) { if (this.get[tKey]) { var d = new Date(); d.setTime(d.getTime()); document.cookie = tKey + '=null; expires=' + d.toGMTString(); } }; JEND.cookie.destroy = function() { var d = new Date(); for (var key in this.load()) { document.cookie = this.load()[key] + ';expires=' + d.setTime(d.getTime()).toGMTString(); } }; // ---------------------------- // JEND.load/JEND.loader 加载管理 JEND.load = function(service, action, params) { if ($.isArray(service)) { var url = service.join(','); var urlsize = service.length; var status = JEND.loader.checkFileLoader(url); if (status == urlsize+1) { if (typeof(action)=='function') action(); } else if (status > 0) { JEND.loader.addExecute(url, action); } else if (status == 0) { JEND.loader.addExecute(url, action); JEND.loader.fileLoader[url] = 1; JEND.debug('开始加载JS', url); for (var i=0; i<urlsize; i++) { JEND.load(service[i], function() { JEND.loader.fileLoader[url] ++; if (JEND.loader.fileLoader[url] == urlsize+1) { JEND.debug('完成加载JS', url); JEND.loader.execute(url); } }); } } } else if (JEND.loader.serviceLibs[service] && JEND.loader.serviceLibs[service].requires) { JEND.load(JEND.loader.serviceLibs[service].requires, function() { JEND.load.run(service, action, params); }); } else { JEND.load.run(service, action, params); } }; JEND.load.add = function(key, data) { if (JEND.loader.serviceLibs[key]) return; JEND.loader.serviceLibs[key] = data; }; JEND.load.setPath = function(path) { JEND.loader.serviceBase = path; }; JEND.load.run = function(service, act, params) { var action = (typeof(act)=='string') ? (function() { try { var o = eval('JEND.'+ service); if (o && o[act]) o[act](params); } catch(e) {} }) : (act||function(){}); if (JEND.loader.checkService(service)) { action(); return; } // status:-1异常, 0未加载, 1开始加载, 2完成加载 var url = JEND.loader.getServiceUrl(service); var status = JEND.loader.checkFileLoader(url); if (status == 2) { action(); } else if (status == 1) { JEND.loader.addExecute(url, action); } else if (status == 0) { if ($('script[src='+url+']').size()>0) { JEND.loader.fileLoader[url] = 2; action(); } else { JEND.loader.addExecute(url, action); JEND.loader.addScript(service); } } else { JEND.debug('加载异常', service); } }; // ---------------------------- JEND.loader = {}; JEND.loader.fileLoader = {}; JEND.loader.executeLoader = {}; JEND.loader.serviceBase = (function() { return $('script:last').attr('src').sliceBefore('/j/') +'/'; })(); JEND.loader.serviceLibs = {}; JEND.loader.checkService = function(service) { if (service.isURL()) return false; try { if (service.indexOf('.')>0) { var o = eval('JEND.'+service); return (typeof(o)!='undefined'); } return false; } catch(e) { return false; } }; JEND.loader.checkFileLoader = function(url) { return (url!='') ? (this.fileLoader[url] || 0) : -1; }; JEND.loader.getServiceUrl = function(service) { var url = ''; if (service.isURL()) { url = service; } else if (this.serviceLibs[service]) { url = (this.serviceLibs[service].js.isURL()) ? this.serviceLibs[service].js : (this.serviceBase + this.serviceLibs[service].js); } return url; }; JEND.loader.execute = function(url) { if (this.executeLoader[url]) { for (var i=0; i<this.executeLoader[url].length; i++) { this.executeLoader[url][i](); } this.executeLoader[url] = null; } }; JEND.loader.addExecute = function(url, action) { if (typeof(action)!='function') return; if (!this.executeLoader[url]) this.executeLoader[url] = []; this.executeLoader[url].push(action); }; JEND.loader.addScript = function(service) { var this_ = this; if (service.isURL()) { var url = service; this.getScript(url, function() { this_.fileLoader[url] = 2; JEND.debug('完成加载JS', url); JEND.loader.execute(url); }); } else if (this.serviceLibs[service]) { if (this.serviceLibs[service].css) { var url = (this.serviceLibs[service].css.isURL()) ? this.serviceLibs[service].css : (this.serviceBase + this.serviceLibs[service].css); if (!this.fileLoader[url]) { $('head').append('<link rel="stylesheet" type="text\/css" href="'+ url +'" \/>'); this.fileLoader[url] = 1; JEND.debug('开始加载CSS', url); } } if (this.serviceLibs[service].js) { var url = (this.serviceLibs[service].js.isURL()) ? this.serviceLibs[service].js : (this.serviceBase + this.serviceLibs[service].js); this.getScript(url, function() { this_.fileLoader[url] = 2; JEND.debug('完成加载JS', url); JEND.loader.execute(url); }); } } }; JEND.loader.getScript = function(url, onSuccess, onError) { // $.ajax({type:"GET", url:url, cache:true, success:onSuccess, error:onError, dataType:'script'}); this.getRemoteScript(url, onSuccess, onError); this.fileLoader[url] = 1; JEND.debug('开始加载JS', url); }; JEND.loader.getRemoteScript = function(url, onSuccess, onError) { var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.type = 'text/javascript'; script.src = url; script.onload = script.onreadystatechange = function(){ if ( !this.readyState || this.readyState == "loaded" || this.readyState == "complete") { if (onSuccess) onSuccess(); script.onload = script.onreadystatechange = null; head.removeChild(script); } }; script.onerror = function() { if (onError) onError(); }; head.appendChild(script); }; // ---------------------------- // JEND.debug 过程调试 JEND.debugMode = false; JEND.debugIndex = 0; JEND.debug = function(a, b) { if (!this.debugMode) return; if (typeof(console) == 'undefined') { JEND.load('firebug', function() { if (console && console.log) console.log(((Date.prototype.format)?(new Date()).format('hh:nn:ss.S'):(++JEND.debugIndex)) +', '+ a, '=', b); }); } else { if (console && console.log) console.log(((Date.prototype.format)?(new Date()).format('hh:nn:ss.S'):(++JEND.debugIndex)) +', '+ a, '=', b); } }; // ---------------------------- // JS相关信息文本(用于多语言支持) // Added 2011-07-14 JEND.lang.text = {}; JEND.lang.get = function(dataset, name) { if (name) { if (this.text[dataset]) { return this.text[dataset][name] || ''; } else { return ''; } } else { return this.text[dataset] || null; } }; JEND.lang.set = function(dataset, name, value) { if (!this.text[dataset]) { this.text[dataset] = {}; } if (value) { this.text[dataset][name] = value; } else { this.text[dataset] = name; } }; JEND.lang.extend = function(dataset, data) { if (!this.text[dataset]) { this.text[dataset] = {}; } $.extend(this.text[dataset], data); }; // ---------------------------- })(jQuery); // -------------------------------- // JEND.json // -------------------------------- (function($) { if (!$ || !window.JEND) return; // ---------------------------- JEND.namespace('JEND.json'); // ---------------------------- JEND.json.parse = function(data) { return (new Function("return " + data))(); }; JEND.json.stringify = function(obj) { var m = {'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"' :'\\"','\\':'\\\\'}, s = { 'array': function(x){var a=['['],b,f,i,l=x.length,v;for(i=0;i<l;i+=1){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=','}a[a.length]=v;b=true}}}a[a.length]=']';return a.join('')}, 'boolean': function(x){return String(x)}, 'null': function(x){return 'null'}, 'number': function(x){return isFinite(x)?String(x):'null'}, 'object': function(x){if(x){if(x instanceof Array){return s.array(x)}var a=['{'],b,f,i,v;for(i in x){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=='string'){if(b){a[a.length]=','}a.push(s.string(i),':',v);b=true}}}a[a.length]='}';return a.join('')}return'null'}, 'string': function(x){if(/["\\\x00-\x1f]/.test(x)){x=x.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c}c=b.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16)})}return'\"'+x+'\"'} }; return s.object(obj); }; // ---------------------------- })(jQuery); // -------------------------------- // JEND.base // -------------------------------- (function($) { if (!$ || !window.JEND) return; // ---------------------------- JEND.namespace('JEND.base'); // ---------------------------- // StringBuilder: 字符串连接 JEND.base.StringBuilder = function() { this._strings = []; }; $.extend(JEND.base.StringBuilder.prototype, { append: function(str) { var aLen = arguments.length; for (var i=0; i<aLen; i++) { this._strings.push(arguments[i]); } }, appendFormat: function(fmt) { var re = /{[0-9]+}/g; var aryMatch = fmt.match(re); var aLen = aryMatch.length; for (var i=0; i < aLen; i++) { fmt = fmt.replace(aryMatch[i], arguments[parseInt(aryMatch[i].replace(/[{}]/g, "")) + 1]); } this._strings.push(fmt); }, toString: function() { return this._strings.join(""); } }); // ---------------------------- // ImageLoader: 图像加载器 JEND.base.ImageLoader = function(options) { this.options = $.extend({src:'', min:0.5, max:30, timer:0.1}, options || {}); this.minTimeout = this.options.min * 1000; this.maxTimeout = this.options.max * 1000; this.intervalTimer = this.options.timer * 1000; this.theTimeout = 0; this.loadStatus = 0; this.loaderId = (new Date()).getTime(); this.onLoad = this.options.onLoad || null; this.onError = this.options.onError || null; var m_this = this; this.init = function() { this.element = new Image(); this.element.onload = function() { m_this.loadStatus = 1; if (m_this.onLoad) m_this.onLoad(); JEND.debug('image onload', m_this.loaderId +': '+ this.width +','+ this.height); }; this.element.onerror = function() { m_this.loadStatus = -1; if (m_this.onError) m_this.onError(); JEND.debug('image onerror', m_this.loaderId); }; this.element.src = this.options.src; this.startMonitor(); JEND.debug('image init', m_this.loaderId); }; this.startMonitor = function() { var m_this = this; setTimeout(function() { m_this.checkMonitor(); }, this.minTimeout); }; this.checkMonitor = function() { if (this.loadStatus != 0) return; this.theTimeout = this.minTimeout; this._monitor = setInterval(function() { m_this.theTimeout += 50; if (m_this.loadStatus != 0) { clearInterval(m_this._monitor); } else if (m_this.element.complete) { clearInterval(m_this._monitor); m_this.loadStatus = 1; if (m_this.onLoad) m_this.onLoad(); JEND.debug('image complete', m_this.loaderId +': '+ m_this.element.width +','+ m_this.element.height); } else if (m_this.theTimeout >= m_this.maxTimeout) { clearInterval(m_this._monitor); m_this.loadStatus = -1; if (m_this.onError) m_this.onError(); JEND.debug('image timeout', m_this.loaderId); } }, m_this.intervalTimer); }; this.init(); }; // ---------------------------- })(jQuery); // -------------------------------- // JEND.util // -------------------------------- (function($) { if (!$ || !window.JEND) return; // ---------------------------- JEND.namespace('JEND.util'); // ---------------------------- // 遮盖层插件 JEND.util.overlayer JEND.util.overlayer = {}; JEND.util.overlayer.id = 'util-overlayer'; JEND.util.overlayer.status = false; // 显示遮盖层 JEND.util.overlayer.showLayer = function(op, bg) { if (this.status) return false; op = (typeof(op)!='undefined')?op:0.5; bg = bg || '#000'; if ($('#'+this.id).length==0) $('body').append('<div id="'+this.id+'" style="width:'+$(document).width()+';height:100%;position:absolute;top:0; left:0;right:0;bottom:0;display:none;z-index:9000"></div>'); $('#'+this.id).css({background:bg,filter:('alpha(opacity='+op*100+')'),opacity:op}); this.setSize(); this.status = true; }; // 关闭遮盖层 JEND.util.overlayer.hideLayer = function() { if (this.status) $('#'+this.id).css('display','none'); this.status = false; }; // 设置遮盖层大小 JEND.util.overlayer.setSize = function() { $('#'+this.id).css({ width:$(document).width()+'px', height:$(document).height()+'px', display:'block'}); }; // 自适应屏幕调整遮盖层大小 JEND.util.overlayer.resize = function() { if (this.status) { $('#'+this.id).css('display','none'); this.setSize(); } }; // ---------------------------- // 分享到其他网站 JEND.util.share = {}; JEND.util.share.sites = { 'kaixin': {url:'http://www.kaixin001.com/repaste/share.php?rtitle={title}&rurl={url}&rcontent={content}'}, 'renren': {url:'http://share.renren.com/share/buttonshare.do?title={title}&link={url}'}, 'douban': {url:'http://www.douban.com/recommend/?title={title}&url={url}',pop:true,width:450,height:340}, 'sina': {url:'http://v.t.sina.com.cn/share/share.php?title={title}&url={url}&source=bookmark',pop:true,width:600,height:480}, 'qzone': {url:'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url={url}'}, 't-qq': {url:'http://v.t.qq.com/share/share.php?url={url}&title={title}'} }; JEND.util.share.openSite = function(site, title, url, content) { if (!this.sites[site]) return; var title = title || document.title; var url = url || document.location.href; var content = content || url; var shareUrl = this.sites[site].url.replace(/{title}/ig, encodeURIComponent(title)).replace(/{url}/ig, encodeURIComponent(url)).replace(/{content}/ig, encodeURIComponent(content)); if (this.sites[site].pop) { var width = this.sites[site].width; var height = this.sites[site].height; var mx = (screen.availWidth - width)/2; var my = (screen.availHeight - height)/2; var feature = 'width='+width+',height='+height+',left='+mx+',top='+my; window.open(shareUrl, site, feature); } else { window.open(shareUrl, site); } }; // ---------------------------- $(window).resize(function() { JEND.util.overlayer.resize(); }); // ---------------------------- })(jQuery); // -------------------------------- // JEND.page // -------------------------------- (function($) { if (!$ || !window.JEND) return; // ---------------------------- JEND.namespace('JEND.page'); // ---------------------------- // 设为首页 JEND.page.setHomepage = function() { var url = document.location.href; if (url.match(/_fromid=[\w]*/)) { url = url.replace(/_fromid=[\w]*/,'_fromid=userfavorite'); } else { url += ((url.indexOf('?')>0)?'&':'?') +'_fromid=userfavorite'; } if (document.all) { document.body.style.behavior = 'url(#default#homepage)'; document.body.setHomePage(url); } else if (window.sidebar) { if (window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); } catch(e) { alert('该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,\n然后将项 signed.applets.codebase_principal_support 值设为true'); } } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBrance); prefs.setCharPref('browser.startup.homepage', url); } }; // 加入收藏 JEND.page.addFavor = function(u,t) { var url = u || document.location.href, title = t || document.title; if (url.match(/_fromid=[\w]*/)) { url = url.replace(/_fromid=[\w]*/,'_fromid=userfavorite'); } else { url += ((url.indexOf('?')>0)?'&':'?') +'_fromid=userfavorite'; } var ctrlStr = ((navigator.userAgent.toLowerCase()).indexOf('mac')!=-1)?'Command/Cmd':'CTRL'; if (document.all) { window.external.AddFavorite(url, title); } else if (window.sidebar) { window.sidebar.addPanel(title, url, ''); } else { alert('您可以尝试通过快捷键'+ ctrlStr +' + D 加入到收藏夹~'); } }; // ---------------------------- // JEND.util.dialog 相关方法的二次封装 JEND.page.alert = function(message, callback) { JEND.load('util.dialog', 'alert', {message:message, callback:callback}); }; JEND.page.showSuccess = function(message, callback) { JEND.load('util.dialog', 'alert', {message:message, type:'success', callback:callback}); }; JEND.page.showError = function(message, callback) { JEND.load('util.dialog', 'alert', {message:message, type:'error', callback:callback}); }; JEND.page.confirm = function(message, onCallback, onCancel) { JEND.load('util.dialog', 'confirm', {message:message, callback:onCallback, cancel:onCancel}); }; JEND.page.showLoading = function(params) { if (typeof(params)=='undefined') params = {}; if (typeof(params)=='string') params = { loadingText: params }; JEND.load('util.dialog', 'showLoading', params); }; JEND.page.hideLoading = function() { JEND.load('util.dialog', 'close', {}); }; JEND.page.closeDialog = function() { JEND.load('util.dialog', 'close'); }; JEND.page.dialog = function(params) { JEND.load('util.dialog', 'open', params); }; JEND.page.dialog.pop = function(params) { JEND.load('util.dialog', 'pop', params); }; JEND.page.dialog.show = function(params) { JEND.load('util.dialog', 'show', params); }; JEND.page.dialog.ajax = function(params) { JEND.load('util.dialog', 'ajax', params); }; JEND.page.dialog.setConfig = function(attr, value) { JEND.load('util.dialog', function() { JEND.util.dialog[attr] = value; }); }; // ---------------------------- JEND.page.setDomain = function() { var k = document.domain.split("."); if (k.length > 2) { if (document.domain.indexOf('.com.cn')>0) { document.domain = k[k.length-3] + '.com.cn'; } else { document.domain = k[k.length-2] +'.'+ k[k.length-1]; } } }; // 页面初始化处理 JEND.page.init = function() { // 解决IE6下默认不缓存背景图片的bug if ($.browser.isIE6) try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} }; // ---------------------------- })(jQuery); // -------------------------------- // JEND.login // -------------------------------- (function($) { if (!$ || !window.JEND) return; // ---------------------------- JEND.namespace('JEND.login'); // ---------------------------- // 快速登录弹窗处理 // JEND.login.pop(param, function() {}); 登录成功后回调 // JEND.login.pop(param, url); 登录成功后调整 // JEND.login.pop(url); // JEND.login.pop(function() {}); JEND.login.pop = function(param, callback) { if (!callback) { callback = param; param = null; } var loginCallback = function() {}; if ($.isFunction(callback)) { loginCallback = callback; } else if (typeof(callback)=='string' && callback!='') { loginCallback = function() { document.location.href = callback; } } if (JEND.cookie.get("mall_cookie") && JEND.cookie.get("mall_cookie") !='') { loginCallback(); } else { JEND.page.setDomain(); var url = 'http://my.'+JEND.server.uleUrl+'/usr/toQuickRegister.do'; if (param) url = url + '?' + $.param(param); JEND.page.dialog.pop({title:'快速登录', url:url, width:750, height:365}); JEND.login.success = function() { JEND.util.dialog.close(); if (JEND.page && JEND.page.header) JEND.page.header.refreshUserInfo(); loginCallback(); }; } return false; }; // 登录成功后回调 JEND.login.success = function() { JEND.util.dialog.close(); }; // ---------------------------- })(jQuery); // -------------------------------- // JEND init // -------------------------------- (function($) { if (!$ || !window.JEND) return; // ---------------------------- JEND.load.add('ui', { js:'j/jend/jend.ui.js' }); JEND.load.add('calendar', { js:'j/jend/ui/calendar.js', css:'c/utility/calendar.css' }); JEND.load.add('util.dialog', { js:'j/jend/util/dialog.js', css:'c/utility/dialog.css' }); JEND.load.add('jqueryui', { js:'j/jend/lib/jqueryui-1.7.3.js' }); JEND.load.add('swfobject', { js:'j/jend/lib/swfobject.js' }); JEND.load.add('address', { js:'j/jend/ui/address.js'}); JEND.load.add('addressold', { js:'j/jend/ui/addressold.js'}); JEND.load.add('firebug', { js:document.location.protocol+'//getfirebug.com/firebug-lite.js' }); // ---------------------------- JEND.server = { url:'ule.tom.com', uleUrl:'ule.com' , name:'' }; // ---------------------------- $(function() { JEND.page.init(); }); // ---------------------------- })(jQuery);
import React from "react"; import { Playlist } from "./Playlist"; import { useSelector } from "react-redux"; import { Spinner } from "../UI/Spinner/Spinner"; import ErrorMessage from "../UI/Error/ErrorMessage"; export function Playlists({ trackToAdd, onAddMessage, style }) { const playlists = useSelector((state) => state.playlists.all); const isLoading = useSelector((state) => state.playlists.isLoading); const error = useSelector((state) => state.playlists.error); const handleSuccess = (message) => { onAddMessage({ text: message, isError: false }); }; const handleError = (message) => { onAddMessage({ text: message, isError: true }); }; return ( <div className="playlists" style={style}> <div className="container"> <Spinner isLoading={isLoading} /> <ErrorMessage hasIcon={true} error={error} /> {playlists && playlists.map((playlist) => ( <Playlist trackToAdd={trackToAdd} key={playlist.id} playlist={playlist} handleAddSuccess={handleSuccess} handleAddError={handleError} /> ))} </div> </div> ); }
class FakeHttpRequestStore { constructor() { this._requests = []; } put(json) { this._requests.push(json); } getLastRequest() { return this._requests.slice(-1)[0]; } } module.exports = FakeHttpRequestStore;
jQuery( document ).ready( function( e ) { jQuery('#loader').fadeOut(); var codigo=''; var negocios=[]; var rutas=[]; var pais_codigo = ''; var pais_nombre = ''; jQuery('#IM_USUARIO1').val(localStorage.EMPID); jQuery('#IM_USUARIO2').val(localStorage.EMPID); jQuery('#IM_USUARIO3').val(localStorage.EMPID); jQuery('.input-date-picker').datepicker({ format: 'yyyy-mm-dd', orientation: "bottom", daysOfWeekDisabled: "7", calendarWeeks: true, autoclose: true, todayHighlight: true }); window.tablaAreas = jQuery("#tb-busqueda").DataTable( { "oLanguage": { "sLengthMenu": "Mostrando _MENU_ filas", "sSearch": "", "sProcessing": "Procesando...", "sLengthMenu": "Mostrar _MENU_ registros", "sZeroRecords": "No se encontraron resultados", "sEmptyTable": "Ningún dato disponible en esta tabla", "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros", "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros", "sInfoFiltered": "(filtrado de un total de _MAX_ registros)", "sInfoPostFix": "", "sSearch": "Buscar:", "sUrl": "", "sInfoThousands": ",", "sLoadingRecords": "Cargando...", "oPaginate": { "sFirst": "Primero", "sLast": "Último", "sNext": "Siguiente", "sPrevious": "Anterior" } } }); jQuery('#btn-busqueda').on('click', busqueda); jQuery('#tb-busqueda').on('click','.btn-PDV-agregar', agregar); jQuery('#btn-agregar-PDV').on('click', agregarPDV); jQuery('#btn-crear-PDV').on('click', nuevoPDV); jQuery('#btn-Deudor-agregar').on('click') jQuery('#tb-busqueda').on('click','.btn-Deudor-agregar', agrego); jQuery('#btn-crear-DEUDOR').on('click', agregarDeudor); jQuery('#ampliado').on('change', cambio_persona); jQuery('#ampliado_').on('change', cambio_persona_); function cambio_persona(){ if( jQuery('#ampliado').val() == '' ){ jQuery('#contenido-juridico').show(); jQuery('.P1').text(' Sociedad'); jQuery('.P2').text('Cédula Jurídica'); jQuery('.P3').text('Tipo doc. jurídico'); } else{ jQuery('#contenido-juridico').hide(); jQuery('.P1').text(' Deudor'); jQuery('.P2').text('Cédula jurídica'); jQuery('.P3').text('Tipo doc. ID'); } } function cambio_persona_(){ console.log( jQuery('#ampliado_').val() ); if( jQuery('#ampliado_').val() == '' ){ jQuery('#contenido-juridico_').show(); jQuery('.P1').text(' Sociedad'); jQuery('.P2').text('Cédula Jurídica'); jQuery('.P3').text('Tipo doc. jurídico'); } else{ jQuery('#contenido-juridico_').hide(); jQuery('.P1').text(' Deudor'); jQuery('.P2').text('Cédula jurídica'); jQuery('.P3').text('Tipo doc. ID'); } } jQuery('#liclicorsn').on('change', function(e){ e.preventDefault(); if( jQuery(this).val()=='S' ){ jQuery('#liclicor').removeAttr('disabled'); }else{ jQuery('#liclicor').attr('disabled','true'); jQuery('#liclicor').val(''); } }) jQuery('#liclicssnn').on('change', function(e){ e.preventDefault(); if( jQuery(this).val()=='S' ){ jQuery('#liclicnum').removeAttr('disabled'); }else{ jQuery('#liclicnum').attr('disabled','true'); jQuery('#liclicnum').val(''); } }) jQuery.ajax({ type: 'GET', url: 'ws/gac/buscar/sociedades?email='+localStorage.USUARIO, dataType: 'json', }) .done(function(data){ if( data.result ){ jQuery('.DD').show(); if( data.records.LAND1 ) pais_codigo = data.records.LAND1; else pais_codigo = data.records.PAIS; if( pais_codigo=='GT' ) pais_nombre='Guatemala'; if( pais_codigo=='CR' ) pais_nombre='Costa Rica'; if( pais_codigo=='SV' ) pais_nombre='El Salvador'; jQuery('#pais_usuario').val(pais_codigo); switch( pais_codigo ) { case 'CR': jQuery('.A').text('Cédula'); jQuery('.B').text('Provincia'); jQuery('.C').text('Tipo de Cédula'); jQuery('.D').text('Cantón'); jQuery('.E').text('Distrito'); jQuery('.F').text('Barrio'); // jQuery('#ZLATITUD').val('10'); // jQuery('#ZLONG').val('83-'); break; case 'GT': jQuery('.A').text('NIT'); jQuery('.B').text('Departamento'); jQuery('.C').text('Tipo de NIT'); jQuery('.DD').hide(); jQuery('.E').text('Municipio'); jQuery('.F').text('Zona'); // jQuery('#ZLATITUD').val('17'); // jQuery('#ZLONG').val('90-'); break; case 'SV': jQuery('.A').text('NIT'); jQuery('.B').text('Departamento'); jQuery('.C').text('Tipo de NIT'); jQuery('.DD').hide(); jQuery('.E').text('Municipio'); jQuery('.F').text('Zona'); break; } } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log('Pais no se detectó'); }); jQuery('#bus').on('change', function(e){ if( jQuery('#bus').val()=='PDV' ){ jQuery('#buscar').attr('placeholder','Nombre o código de PDV'); jQuery('#buscar').removeAttr('type'); jQuery('#buscar').attr('type','text'); }else{ jQuery('#buscar').attr('placeholder','Código del Deudor'); jQuery('#buscar').removeAttr('type'); jQuery('#buscar').attr('type','number'); } }); //Funciones function busqueda( e ){ e.preventDefault(); if( jQuery('#buscar').val() ){ jQuery("#tb-busqueda").dataTable().fnClearTable(); if( jQuery('#bus').val()=='Deudor' ){ codigo = jQuery('#buscar').val(); if( jQuery('#buscar').val()) { jQuery('#loader').show(); jQuery('.dat1').text('Código'); jQuery('.dat2').text('Tipo Id'); jQuery('.dat3').text('Nombre'); jQuery('.dat4').text('Tipo de Deudor'); jQuery('.dat5').text('Dirección'); jQuery('.dat6').text('Correo'); jQuery.ajax({ type: 'POST', url: 'ws/gac/deudores/buscar', data: { 'buscar':jQuery('#buscar').val(), sociedad: localStorage.SOCIEDAD, email: localStorage.USUARIO, empid: localStorage.EMPID}, success: function( result ) { if( result.result ) { jQuery.ajax({ type: 'GET', url: 'ws/gac/codigos/consulta', dataType: 'json', }) .done(function(data){ jQuery.each( result.records.TA_INFO_DEUDOR.item, function( index,item ){ jQuery.each( data.records.tipo_id, function( index,value ){ if(value.id ==item.PAAT1){ var correo =item.AD_SMTPADR; if(!item.AD_SMTPADR) correo='Sin Asignar'; var tp='Persona Jurídica'; if( item.STKZN=='X' ){ tp='Persona Física'; } jQuery('#tb-busqueda').dataTable().fnAddData([ item.KUNNR, value.valor, '<i style="text-transform:capitalize;">'+item.AD_NAME1.toLowerCase()+'</i>', tp, '<i style="text-transform:capitalize;">'+(item.DEUD_REGIO_DESC.toLowerCase()+', '+item.DEUD_LAND1_DESC.toLowerCase())+'</i>', correo, '<a data-placement="top" data-bus="Deudor" data-cedula="'+item.KUNNR+'" href="#modal-agregar" data-toggle="modal" title="Agregar nuevo PDV a Deudor" class="toltip btn-PDV-agregar btn btn-success btn-xs" ><i class="fa fa-file-o"></i> PDV</a>',/*fa-plus*/ ]); } }); }); negocios=[]; negocios = data.records.tipo_negocio; rutas=[]; rutas = data.records.tipo_rutas; jQuery('#loader').fadeOut(); toastr['success'](result.message, 'Éxito'); }).fail(function(err){ toastr['success'](result.message, 'Éxito'); jQuery('#loader').fadeOut(); }); } else { jQuery("#tb-busqueda").dataTable().fnClearTable(); toastr['success'](result.message, 'Exito'); jQuery('#loader').fadeOut(); } }, error: function( result ) { toastr['error']('Ocurrió un problema, intenta más tarde', 'Error'); jQuery('#loader').fadeOut(); } }); } else toastr['error']('Se necesita el codigo o nombre del Deudor', 'Error'); }else{ jQuery('#loader').show(); jQuery('.dat1').text('Código'); jQuery('.dat2').text('Tipo de Negocio'); jQuery('.dat3').text('Nombre'); jQuery('.dat4').text('Patente'); jQuery('.dat5').text('Teléfono'); jQuery('.dat6').text('Dirección'); jQuery.ajax({ type: 'POST', url: 'ws/gac/pdvs/buscar', data: { 'buscar':jQuery('#buscar').val(), sociedad: localStorage.SOCIEDAD, email: localStorage.USUARIO, empid: localStorage.EMPID}, success: function( result ) { if( result.result ){ jQuery.each( result.records.TA_INFO_PDV.item , function( index,value ){ var patente=''; var telefono=''; value.DKTXT?patente=value.DKTXT:patente='Sin Patente'; if( value.TELF1 && value.TELF1!='0' ) telefono=value.TELF1; if( value.TELF2 && value.TELF2!='0' ) if( telefono ) telefono=telefono+', '+value.TELF2 else telefono=value.TELF2 if( value.TELFX && value.TELFX!='0' ) if( telefono ) telefono=telefono+', '+value.TELFX else telefono=value.TELFX jQuery('#tb-busqueda').dataTable().fnAddData([ value.KUNNR, '<span style="text-transform:capitalize;">'+ value.BRSCH_DESC+'</span>', '<i style="text-transform:capitalize;">'+ value.NOMBRE_PDV+'</i>', patente, telefono, '<i style="text-transform:capitalize;">'+(value.REGIO_DESC.toLowerCase()+', '+value.LAND1_DESC.toLowerCase())+'</i>', '<a data-placement="top" data-bus="PDV" data-codigo="'+value.KUNNR+'" href="#modal-agrego" data-toggle="modal" title="Agregar nuevo Deudor a PDV" class="toltip btn-Deudor-agregar btn btn-success btn-xs" ><i class="fa fa-file-o"></i> Deudor</a>',/*fa-plus*/ ]); }); jQuery('#loader').fadeOut(); toastr['success'](result.message, 'Éxito'); }else{ jQuery('#loader').fadeOut(); toastr['success'](result.message, 'Éxito'); } }, error: function( result ) { toastr['error']('Ocurrió un problema, intenta más tarde', 'Error'); jQuery('#loader').fadeOut(); } }); } } else{ toastr['error']('No hay informacion que buscar '+jQuery('#buscar').val(), 'Error'); } // jQuery('#loader').fadeOut(); } function agregar ( e ){ e.preventDefault(); jQuery('.P1').text(' Sociedad'); jQuery('.P2').text('Cédula Jurídica'); jQuery('.P3').text('Tipo doc. jurídico'); jQuery('#negocio').val(''); jQuery('#ampliado').val(''); jQuery('#patente').val(''); jQuery('#licencia').val(''); jQuery('.provincias').remove(''); jQuery('.negocios').remove(''); jQuery('#canton_pdv').val(''); jQuery('#ciudad_pdv_').text(pais_nombre); jQuery('#LAND1').val(pais_codigo); jQuery('#barrio_pdv').val(''); jQuery('#sena_pdv').val(''); jQuery('#tel1_pdv').val(''); jQuery('#tel2_pdv').val(''); jQuery('#tel3_pdv').val(''); jQuery('#tipon_pdv').val(''); jQuery('#rutaa_pdv').val(''); jQuery('#rutana_pdv').val(''); jQuery('#zona_pdv').val(''); jQuery('#frecuencia_pdv').val(''); jQuery('#visita_pdv').val(''); jQuery('#lunes').val(''); jQuery('#rol_lunes').val('0'); jQuery('#martes').val(''); jQuery('#rol_martes').val('0'); jQuery('#miercoles').val(''); jQuery('#rol_miercoles').val('0'); jQuery('#jueves').val(''); jQuery('#rol_jueves').val('0'); jQuery('#viernes').val(''); jQuery('#rol_viernes').val('0'); jQuery('#sabado').val(''); jQuery('#rol_sabado').val('0'); cedula = jQuery(this).data('cedula'); jQuery('#loader').show(); jQuery.ajax({ type: 'POST', url: 'ws/gac/deudores/buscar', data: { 'buscar':cedula, sociedad: localStorage.SOCIEDAD, email: localStorage.USUARIO, empid: localStorage.EMPID}, success: function( result ) { var dataDeudor = result.records.TA_INFO_DEUDOR.item[0]; result.records=result.records.TA_INFO_DEUDOR.item; jQuery('#KUNNR1').val(dataDeudor.KUNNR); jQuery('#KUNNR2').text(dataDeudor.KUNNR); // jQuery('#form-agregar').reset(); // jQuery('#form-nuevo').reset(); // jQuery('#form-agrego').reset(); jQuery('#DEUDOR').val(cedula); jQuery('#STCD1').val(cedula); jQuery('#PAAT1').val(dataDeudor.PAAT1); jQuery('#STKZN').val(dataDeudor.STKZN); jQuery('#AD_NAME1').val(dataDeudor.AD_NAME1); jQuery('#DEUD_REGIO').val(dataDeudor.DEUD_REGIO); jQuery('#DEUD_COUNC').val(dataDeudor.DEUD_COUNC); jQuery('#DEUD_CITYC').val(dataDeudor.DEUD_CITYC); jQuery('#DEUD_LAND1').val(dataDeudor.DEUD_LAND1); jQuery('#DEUD_AD_STRSPP3').val(dataDeudor.DEUD_AD_STRSPP3); jQuery('#DEUD_AD_NAME_CO').val(dataDeudor.DEUD_AD_NAME_CO); jQuery('#CONT_TELEF1').val(dataDeudor.CONT_TELEF1); jQuery('#CONT_TELEF2').val(dataDeudor.CONT_TELEF2); jQuery('#CONT_TELEF3').val(dataDeudor.CONT_TELEF3); jQuery('#AD_SMTPADR').val(dataDeudor.AD_SMTPADR); //------------------------------------------------------------------------------------------fin //datos del pdv //------------------------------------------------------------------------------------------fin // FIN DATOS PARA ENVIAR dataDeudor.STKZN=='X'?tipo='Persona Física':tipo='Persona Jurídica'; jQuery('#tipo').text(tipo); if( dataDeudor.STKZN ){ jQuery('#contenido-juridico-_').hide(); jQuery('.P1').text(' Deudor'); jQuery('.P2').text('Cédula jurídica'); }else{ jQuery('#contenido-juridico-_').show(); jQuery('.P1').text(' Sociedad'); jQuery('.P2').text('Cédula Jurídica'); jQuery('#AD_NAMEFIR').text(dataDeudor.AD_NAMEFIR ); jQuery('#AD_NAMEFIR_1').text(dataDeudor.AD_NAMEFIR ); jQuery('#AD_NAME2_P').text(dataDeudor.AD_NAME2_P ); jQuery('#AD_NAME2_P_1').text(dataDeudor.AD_NAME2_P ); } jQuery('#codigo').text(' '+valornulo(dataDeudor.STCD1)+' '); jQuery('#deudor').text(' '+dataDeudor.AD_NAME1.toLowerCase()); jQuery('#provincia').text(' '+dataDeudor.DEUD_REGIO_DESC.toLowerCase()); jQuery('#canton').text(' '+valornulo(dataDeudor.DEUD_COUNC_DESC.toLowerCase())); jQuery('#distrito').text(' '+valornulo(dataDeudor.DEUD_CITYC_DESC.toLowerCase())); jQuery('#ciudad').text(' '+dataDeudor.DEUD_LAND1_DESC.toLowerCase()); jQuery('#senas').text(' '+valornulo(dataDeudor.DEUD_AD_NAME_CO.toLowerCase())); jQuery('#barrio').text(' '+valornulo(dataDeudor.DEUD_AD_STRSPP3.toLowerCase())); jQuery('#telefono1').text(' '+valornulo(dataDeudor.CONT_TELEF1)); jQuery('#telefono2').text(' '+valornulo(dataDeudor.CONT_TELEF2)); jQuery('#telefono3').text(' '+valornulo(dataDeudor.CONT_TELEF3)); jQuery('#correo').text(' '+valornulo(dataDeudor.AD_SMTPADR.toUpperCase())); jQuery('#loader').fadeOut(); //Agregando valores de Direcciones jQuery('.ruta').remove(); jQuery.each( rutas, function( index,item ) { jQuery('#ruta_pdv').append('<option class="ruta" value="'+item.id+'" style="text-transform:capitalize;">'+item.id+' - '+item.valor.toLowerCase()+'</option>'); }); var pais=jQuery('#pais_usuario').val(); jQuery.ajax( { type: 'GET', url: 'ws/gac/provincia?pais='+pais, dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.BLAND!='000') jQuery('#provincia_pdv').append('<option class="provincias" value="'+item.BLAND+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log( err ); }).always( function(){ console.log('Completo'); }); //Agregando el tipo jQuery.each( negocios, function( index,item ){ jQuery('#BRSCH').append('<option class="negocios" value="'+item.id+'" style="text-transform:capitalize;">'+item.valor.toLowerCase()+'</option>'); }); } }); } function agrego(e){ e.preventDefault(); jQuery('.P1').text('Sociedad'); jQuery('.P2').text('Cédula Jurídica'); jQuery('.P3').text('Tipo doc. jurídico'); jQuery('.limpiar').val(''); jQuery('#loader').show(); jQuery('#DEUD_LAND1_B_CODIGO').val( pais_codigo ); var codigo = jQuery(this).data('codigo'); jQuery('#provincias_B').remove(); jQuery.ajax({ type: 'GET', url: 'ws/gac/pdvs/buscar', dataType: 'json', data: {buscar:codigo, sociedad: localStorage.SOCIEDAD, email: localStorage.USUARIO, empid: localStorage.EMPID}, }) .done(function(data){ jQuery('#form-agregar')[0].reset(); jQuery('#form-nuevo')[0].reset(); jQuery('#form-agrego')[0].reset(); jQuery('#KUNNRPDV1').val(data.records.TA_INFO_PDV.item[0].KUNNR); jQuery('#KUNNRPDV2').text(data.records.TA_INFO_PDV.item[0].KUNNR); jQuery('#NOMBRE_PDV_B').text(valornulo(data.records.TA_INFO_PDV.item[0].NOMBRE_PDV.toLowerCase(),'0')); jQuery('#DKTXT_B').text(data.records.TA_INFO_PDV.item[0].DKTXT?data.records.TA_INFO_PDV.item[0].DKTXT:'Sin Asignar'); jQuery('#BRSCH_B').text(valornulo(data.records.TA_INFO_PDV.item[0].BRSCH_DESC.toLowerCase(),'0')); jQuery('#REGIO_B').text(valornulo(data.records.TA_INFO_PDV.item[0].REGIO_DESC.toLowerCase(),'0')); jQuery('#COUNC_B').text(valornulo(data.records.TA_INFO_PDV.item[0].COUNC_DESC.toLowerCase(),'0')); jQuery('#CITYC_B').text(valornulo(data.records.TA_INFO_PDV.item[0].CITYC_DESC.toLowerCase(),'0')); jQuery('#LAND1_B').text(valornulo(data.records.TA_INFO_PDV.item[0].LAND1_DESC.toLowerCase(),'0')); jQuery('#AD_STRSPP3_B').text(valornulo(data.records.TA_INFO_PDV.item[0].AD_STRSPP3.toLowerCase(),'0')); jQuery('#AD_NAME_CO_B').text(valornulo(data.records.TA_INFO_PDV.item[0].AD_NAME_CO.toLowerCase(),'0')); jQuery('#TELF1_B').text(valornulo(data.records.TA_INFO_PDV.item[0].TELF1,'0')); jQuery('#TELF2_B').text(valornulo(data.records.TA_INFO_PDV.item[0].TELF2,'0')); jQuery('#TELFX_B').text(valornulo(data.records.TA_INFO_PDV.item[0].TELFX,'0')); jQuery('#FREC_VISITA_B').text(valornulo(data.records.TA_INFO_PDV.item[0].FREC_VISITA,'0')); jQuery('#IND_TELEVENTA_B').text(' '+data.records.TA_INFO_PDV.item[0].IND_TELEVENTA=='S'?'Si':'No'); jQuery('#IND_TELEVENTA_G').text(data.records.TA_INFO_PDV.item[0].IND_TELEVENTA); jQuery('#ZLONG_B').text(valornulo(data.records.TA_INFO_PDV.item[0].ZLONG,'0')); jQuery('#ZLONG_').text(valornulo(data.records.TA_INFO_PDV.item[0].ZLONG,'0')); jQuery('#ZLATITUD_B').text(valornulo(data.records.TA_INFO_PDV.item[0].ZLATITUD,'0')); jQuery('#ZLATITUD_').text(valornulo(data.records.TA_INFO_PDV.item[0].ZLATITUD,'0')); jQuery('#FREC_VISITA_G').text(' '+frecuenciavisitas( data.records.TA_INFO_PDV.item[0].FREC_VISITA )); jQuery('#FREC_VISITA_G').text(data.records.TA_INFO_PDV.item[0].FREC_VISITA); jQuery('#BZIRK_G').text(data.records.TA_INFO_PDV.item[0].BZIRK); if( data.records.TA_INFO_PDV.item[0].BZIRK ){ jQuery.ajax({ type: 'GET', url: 'ws/gac/codigos/consulta', dataType: 'json', }) .done(function(data){ jQuery.each( data.records.tipo_rutas, function( index,value ){ if(value.id == data.records.TA_INFO_PDV.item[0].BZIRK ) jQuery('#BZIRK_B').text(' '+value.valor); }); }).fail(function(err){ toastr['error'](err.message, 'Error'); }); }else{ jQuery('#BZIRK_B').text('Sin Asignar'); } jQuery('#NOMBRE_PDV_G').val(data.records.TA_INFO_PDV.item[0].NOMBRE_PDV); jQuery('#DKTXT_G').val(data.records.TA_INFO_PDV.item[0].DKTXT); jQuery('#BRSCH_G').val(data.records.TA_INFO_PDV.item[0].BRSCH); jQuery('#REGIO_G').val(data.records.TA_INFO_PDV.item[0].REGIO); jQuery('#COUNC_G').val(data.records.TA_INFO_PDV.item[0].COUNC); jQuery('#CITYC_G').val(data.records.TA_INFO_PDV.item[0].CITYC); jQuery('#LAND1_G').val(data.records.TA_INFO_PDV.item[0].LAND1); jQuery('#AD_STRSPP3_G').val(data.records.TA_INFO_PDV.item[0].AD_STRSPP3); jQuery('#AD_NAME_CO_G').val(data.records.TA_INFO_PDV.item[0].AD_NAME_CO); jQuery('#TELF1_G').val(data.records.TA_INFO_PDV.item[0].TELF1); jQuery('#TELF2_G').val(data.records.TA_INFO_PDV.item[0].TELF2); jQuery('#TELFX_G').val(data.records.TA_INFO_PDV.item[0].TELFX); jQuery('#FREC_VISITA_G').val(data.records.TA_INFO_PDV.item[0].FREC_VISITA); jQuery('#ZLATITUD').val(data.records.TA_INFO_PDV.item[0].ZLATITUD); jQuery('#ZLONG').val(data.records.TA_INFO_PDV.item[0].ZLONG); if( data.records.TA_INFO_PDV.item[0].ORDEN_LUNES=='1' ){ jQuery('#ORDEN_LUNES_B').attr('checked','checked'); jQuery('#rol_lunes_B').val('1'); }else{ jQuery('#ORDEN_LUNES_B').removeAttr('checked'); jQuery('#rol_lunes_B').val('0'); } if( data.records.TA_INFO_PDV.item[0].ORDEN_MARTES=='1' ){ jQuery('#ORDEN_MARTES_B').attr('checked','checked'); jQuery('#rol_martes_B').val('1'); }else{ jQuery('#ORDEN_MARTES_B').removeAttr('checked'); jQuery('#rol_martes_B').val('0'); } if( data.records.TA_INFO_PDV.item[0].ORDEN_MIERCOLES=='1' ){ jQuery('#ORDEN_MIERCOLES_B').attr('checked','checked'); jQuery('#rol_miercoles_B').val('1'); }else{ jQuery('#ORDEN_MIERCOLES_B').removeAttr('checked'); jQuery('#rol_miercoles_B').val('0'); } if( data.records.TA_INFO_PDV.item[0].ORDEN_JUEVES=='1' ){ jQuery('#ORDEN_JUEVES_B').attr('checked','checked'); jQuery('#rol_jueves_B').val('1'); }else{ jQuery('#ROL_JUEVES_B').removeAttr('checked'); jQuery('#rol_jueves_B').val(''); } if( data.records.TA_INFO_PDV.item[0].ORDEN_VIERNES=='1' ){ jQuery('#ORDEN_VIERNES_B').attr('checked','checked'); jQuery('#rol_viernes_B').val('1'); }else{ jQuery('#ROL_VIERNES_B').removeAttr('checked'); jQuery('#rol_viernes_B').val('0'); } if( data.records.TA_INFO_PDV.item[0].ORDEN_SABADO=='1' ){ jQuery('#ORDEN_SABADO_B').attr('checked','checked'); jQuery('#rol_sabado_B').val('1'); }else{ jQuery('#ORDEN_SABADO_B').removeAttr('checked'); jQuery('#rol_sabado_B').val('0'); } }); jQuery.ajax({ type: 'GET', url: 'ws/gac/codigos/consulta', dataType: 'json', }) .done(function(data){ jQuery('.tipos_id_B').remove(); jQuery.each( data.records.tipo_id, function( index,item ) { jQuery('#PAAT1_B').append('<option class="tipos_id_B" value="'+item.id+'" style="text-transform:capitalize;">'+item.valor.toLowerCase()+'</option>'); }); }).fail(function(err){ console.log(err.messages); }); jQuery('#DEUD_LAND1_B').text(pais_nombre); //Agregando valores de Direcciones var pais=jQuery('#pais_usuario').val(); jQuery.ajax( { type: 'GET', url: 'ws/gac/provincia?pais='+pais, dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.BLAND!='000') jQuery('#DEUD_REGIO_B').append('<option class="provincias_B" value="'+item.BLAND+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); jQuery('#loader').fadeOut(); } else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ console.log( err ); jQuery('#loader').fadeOut(); }).always( function(){ console.log('Completo'); }); } //cambios de lugares jQuery('#provincia_pdv').on('change', function(e){ e.preventDefault(); if( jQuery('#provincia_pdv').val() && jQuery('#pais_usuario').val()=='CR' ){ jQuery('#loader').show(); jQuery('.cantones').remove(''); jQuery('.distritos').remove(''); jQuery('#canton_pdv').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/cantones?pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#provincia_pdv').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='000') jQuery('#canton_pdv').append('<option class="cantones" value="'+item.COUNC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); jQuery('#loader').fadeOut(); } else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ console.log( err ); jQuery('#loader').fadeOut(); }).always( function(){ }); jQuery('#distrito_pdv').attr( 'disabled','true'); } else{ jQuery('#loader').show(); if( jQuery('#provincia_pdv').val() && jQuery('#pais_usuario').val()!='CR' ){ jQuery('.distritos').remove(''); jQuery('#distrito_pdv').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+''+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#provincia_pdv').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#distrito_pdv').append('<option class="distritos" value="'+item.CITYC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); jQuery('#loader').fadeOut(); } else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ console.log( err ); }).always( function(){ }); } else{ jQuery('#distrito_pdv').attr( 'disabled','true'); jQuery('#canton_pdv').attr( 'disabled','true'); jQuery('#loader').fadeOut(); } } }); jQuery('#canton_pdv').on('change', function(e){ e.preventDefault(); console.log( jQuery('#canton_pdv').val()+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#provincia_pdv').val() ); jQuery('#loader').show(); jQuery('.distritos').remove(''); if( jQuery('#canton_pdv').val() ){ jQuery('#distrito_pdv').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+jQuery('#canton_pdv').val()+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#provincia_pdv').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#distrito_pdv').append('<option class="distritos" value="'+item.CITYC+'" style="text-transform:capitalize;"> '+item.BEZEI.toLowerCase()+'</option>'); }); jQuery('#loader').fadeOut(); } else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ console.log( err ); jQuery('#loader').fadeOut(); }).always( function(){ }); }else{ jQuery('#loader').fadeOut(); } }); jQuery('#DEUD_REGIO_B').on('change', function(e){ e.preventDefault(); if( jQuery('#DEUD_REGIO_B').val() && jQuery('#pais_usuario').val()=='CR' ){ jQuery('#loader').show(); jQuery('.cantones_B').remove(''); jQuery('.distritos_B').remove(''); jQuery('#DEUD_COUNC_B').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/cantones?pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#DEUD_REGIO_B').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='000') jQuery('#DEUD_COUNC_B').append('<option class="cantones_B" value="'+item.COUNC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); jQuery('#loader').fadeOut(); } else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ console.log( err ); jQuery('#loader').fadeOut(); }).always( function(){ }); jQuery('#DEUD_CITYC_B').attr( 'disabled','true'); } else{ jQuery('#loader').show(); if( jQuery('#DEUD_REGIO_B').val() && jQuery('#pais_usuario').val()!='CR' ){ jQuery('.distritos_B').remove(''); jQuery('#DEUD_CITYC_B').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+''+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#DEUD_REGIO_B').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#DEUD_CITYC_B').append('<option class="distritos_B" value="'+item.CITYC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); jQuery('#loader').fadeOut(); } else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ console.log( err ); jQuery('#loader').fadeOut(); }).always( function(){ }); } else{ jQuery('#DEUD_CITYC_B').attr( 'disabled','true'); jQuery('#DEUD_COUNC_B').attr( 'disabled','true'); jQuery('#loader').fadeOut(); } } }); jQuery('#DEUD_COUNC_B').on('change', function(e){ e.preventDefault(); jQuery('.distritos_B').remove(''); jQuery('#loader').show(); if( jQuery('#DEUD_COUNC_B').val() ){ jQuery('#DEUD_CITYC_B').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+jQuery('#DEUD_COUNC_B').val()+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#provincia_pdv').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#DEUD_CITYC_B').append('<option class="distritos_B" value="'+item.CITYC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); jQuery('#loader').fadeOut(); } else{ toastr['error'](data.message, 'Error'); } }).fail(function(err){ console.log( err ); jQuery('#loader').fadeOut(); }).always( function(){ }); }else jQuery('#loader').fadeOut(); }); jQuery('#lunes').on('change',function(e){ // jQuery('#lunes').prop('checked')?console.log('Si lunes'):console.log('No lunes'); jQuery('#rol_lunes').val(''); if( jQuery('#lunes').prop('checked') ) jQuery('#rol_lunes').val('1'); else jQuery('#rol_lunes').val('0'); }); jQuery('#martes').on('change',function(e){ // jQuery('#martes').prop('checked')?console.log('Si martes'):console.log('No martes'); jQuery('#rol_martes').val(''); if( jQuery('#martes').prop('checked') ) jQuery('#rol_martes').val('1'); else jQuery('#rol_martes').val('0'); }); jQuery('#miercoles').on('change',function(e){ // jQuery('#miercoles').prop('checked')?console.log('Si miercoles'):console.log('No miercoles'); jQuery('#rol_miercoles').val(''); if( jQuery('#miercoles').prop('checked') ) jQuery('#rol_miercoles').val('1'); else jQuery('#rol_miercoles').val('0'); }); jQuery('#jueves').on('change',function(e){ // jQuery('#jueves').prop('checked')?console.log('Si jueves'):console.log('No jueves'); jQuery('#rol_jueves').val(''); if( jQuery('#jueves').prop('checked') ) jQuery('#rol_jueves').val('1'); else jQuery('#rol_jueves').val('0'); }); jQuery('#viernes').on('change',function(e){ // jQuery('#viernes').prop('checked')?console.log('Si viernes'):console.log('No viernes'); jQuery('#rol_viernes').val(''); if( jQuery('#viernes').prop('checked') ) jQuery('#rol_viernes').val('1'); else jQuery('#rol_viernes').val('0'); }); jQuery('#sabado').on('change',function(e){ // jQuery('#sabado').prop('checked')?console.log('Si sabado'):console.log('No sabado'); jQuery('#rol_sabado').val(''); if( jQuery('#sabado').prop('checked') ) jQuery('#rol_sabado').val('1'); else jQuery('#rol_sabado').val('0'); }); jQuery('#lunes_').on('change',function(e){ jQuery('#rol_lunes_').val(''); if( jQuery('#lunes_').prop('checked') ) jQuery('#rol_lunes_').val('1'); else jQuery('#rol_lunes_').val('0'); }); jQuery('#martes_').on('click',function(e){ jQuery('#rol_martes_').val(''); if( jQuery('#martes_').prop('checked') ) jQuery('#rol_martes_').val('1'); else jQuery('#rol_martes_').val('0'); }); jQuery('#miercoles_').on('click',function(e){ jQuery('#rol_miercoles_').val(''); if( jQuery('#miercoles_').prop('checked') ) jQuery('#rol_miercoles_').val('1'); else jQuery('#rol_miercoles_').val('0'); }); jQuery('#jueves_').on('click',function(e){ jQuery('#rol_jueves_').val(''); if( jQuery('#jueves_').prop('checked') ) jQuery('#rol_jueves_').val('1'); else jQuery('#rol_jueves_').val('0'); }); jQuery('#viernes_').on('click',function(e){ jQuery('#rol_viernes_').val(''); if( jQuery('#viernes_').prop('checked') ) jQuery('#rol_viernes_').val('1'); else jQuery('#rol_viernes_').val('0'); }); jQuery('#sabado_').on('click',function(e){ jQuery('#rol_sabado_').val(''); if( jQuery('#sabado_').prop('checked') ) jQuery('#rol_sabado_').val('1'); else jQuery('#rol_sabado_').val('0'); }); function agregarPDV(e){ e.preventDefault(); if( jQuery('#form-agregar').valid() ) { console.log( jQuery('#form-agregar').serialize() ); jQuery('#loader').show(); jQuery.ajax({ type: 'POST', url: 'ws/gac/pdv', dataType: 'json', data: jQuery('#form-agregar').serialize(), }) .done(function(data) { if(data.result){ toastr['success'](data.message, 'Éxito'); jQuery('#modal-agregar').modal('hide'); jQuery('#loader').fadeOut(); location.reload(); }else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(e){ toastr['error'](e.message, 'Error'); jQuery('#loader').fadeOut(); }).always( function(all){ jQuery('#loader').fadeOut(); }); } else { toastr['warning']('Hace falta información', 'Cuidado'); console.log('falta informacion'); } } function agregarDeudor(e){ e.preventDefault(); jQuery('#loader').show(); if( jQuery('#form-agrego').valid() ) { console.log( jQuery('#form-agrego').serialize() ); jQuery.ajax({ type: 'POST', url: 'ws/gac/pdv', dataType: 'json', data: jQuery('#form-agrego').serialize(), }) .done(function(data) { if(data.result){ toastr['success'](data.message, 'Éxito'); jQuery('#modal-agrego').modal('hide'); jQuery('#loader').fadeOut(); location.reload(); }else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ toastr['error'](err.message, 'Error'); jQuery('#loader').fadeOut(); }).always( function(all){ jQuery('#loader').fadeOut(); }); } else { toastr['error']('Hacen falta Datos en la solicitud', 'Error'); jQuery('#loader').fadeOut(); } } function nuevoPDV(e){ e.preventDefault(); if( jQuery('#form-nuevo').valid() ) { console.log( jQuery('#form-nuevo').serialize() ); jQuery.ajax({ type: 'POST', url: 'ws/gac/pdv', dataType: 'json', data: jQuery('#form-nuevo').serialize(), }) .done(function(data) { if(data.result){ toastr['success'](data.message, 'Éxito'); jQuery('#modal-nuevo').modal('hide'); jQuery('#loader').fadeOut(); location.reload(); }else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(err){ console.log(err); toastr['error'](err.message, 'Error'); }).always( function(all){ jQuery('#loader').fadeOut(); }); } else console.log('falta informacion'); } jQuery('#btn-crear').on('click', function(e){ e.preventDefault(); jQuery('#loader').show(); jQuery('.limpiar').val(''); jQuery(".check").prop('checked', false); jQuery('#DEUD_LAND1_C').val(pais_codigo); jQuery('#LAND1_C').val(pais_codigo); jQuery('#DEUD_COUNC_').attr( 'disabled','true'); jQuery('#DEUD_CITYC_').attr( 'disabled','true'); jQuery('#COUNC_').attr( 'disabled','true'); jQuery('#CITYC_').attr( 'disabled','true'); jQuery('#rut_nuev').remove(); jQuery.ajax({ type: 'GET', url: 'ws/gac/codigos/consulta', dataType: 'json', }) .done(function(data){ jQuery('.negosnvs').remove(); jQuery('.rutannvv').remove(); jQuery.each( data.records.tipo_negocio, function( index,item ){ jQuery('#tipo_neg_n').append('<option class="negosnvs" value="'+item.id+'" style="text-transform:capitalize;">'+item.id+' - '+item.valor.toLowerCase()+'</option>'); }); jQuery.each( data.records.tipo_rutas, function( index,item ){ jQuery('#rutas_nueva').append('<option class="rutannvv" value="'+item.id+'" style="text-transform:capitalize;">'+item.id+' - '+item.valor.toLowerCase()+'</option>'); }); }); jQuery.ajax({ type: 'GET', url: 'ws/gac/codigos/consulta', dataType: 'json', }) .done(function(data){ jQuery('.negoss').remove(); jQuery.each( data.records.tipo_id, function( index,item ){ jQuery('#PAAT1_').append('<option class="negoss" value="'+item.id+'" style="text-transform:capitalize;">'+item.valor.toLowerCase()+'</option>'); }); }); jQuery("#tb-busqueda").dataTable().fnClearTable(); jQuery.ajax({ type: 'GET', url: 'ws/gac/codigos/consulta', dataType: 'json', }) .done(function(data){ jQuery('.negocios').remove(); jQuery.each( data.records.tipo_negocio, function( index,item ){ jQuery('#BRSCH_').append('<option class="negocios" value="'+item.id+'" style="text-transform:capitalize;">'+item.valor.toLowerCase()+'</option>'); }); }); jQuery('#DEUD_LAND1_').text(pais_nombre); jQuery('#LAND1_').text(pais_nombre); jQuery('.provincias').remove(); jQuery('.cantones_').remove(); jQuery('.cantones').remove(); jQuery('.distritos_').remove(); jQuery('.distritos').remove(); jQuery.ajax( { type: 'GET', url: 'ws/gac/provincia?pais='+jQuery('#pais_usuario').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.BLAND!='000') jQuery('#DEUD_REGIO_').append('<option class="provincias" value="'+item.BLAND+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); jQuery('#REGIO_').append('<option class="provincias" value="'+item.BLAND+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log( err.message ); jQuery('#loader').fadeOut(); }).always( function(){ console.log('Completo'); }); jQuery('#loader').fadeOut(); }); jQuery('#REGIO_').on('change', function(e){ e.preventDefault(); if( jQuery('#REGIO_').val() && jQuery('#pais_usuario').val()=='CR' ){ jQuery('#loader').show(); jQuery('.cantones_').remove(); jQuery('.distritos').remove(); jQuery('#COUNC_').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/cantones?pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#REGIO_').val(), dataType: 'json', }) .done(function(data) { // console.log(data); if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='000') jQuery('#COUNC_').append('<option class="cantones_" value="'+item.COUNC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log( err ); }).always( function(){ jQuery('#loader').fadeOut(); }); } else{ jQuery('#loader').show(); if( jQuery('#REGIO_').val() && jQuery('#pais_usuario').val()!='CR' ){ jQuery('.distritos_').remove(''); jQuery('#CITYC_').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+''+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#REGIO_').val(), dataType: 'json', }) .done(function(data) { // console.log(data); if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#CITYC_').append('<option class="distritos_" value="'+item.CITYC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log( err ); }).always( function(){ jQuery('#loader').fadeOut(); }); } else jQuery('#CITYC_').attr( 'disabled','true'); jQuery('#COUNC_').attr( 'disabled','true'); jQuery('#loader').fadeOut(); } }); jQuery('#DEUD_REGIO_').on('change', function(e){ e.preventDefault(); if( jQuery('#DEUD_REGIO_').val() && jQuery('#pais_usuario').val()=='CR' ){ jQuery('#loader').show(); jQuery('#DEUD_COUNC_').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/cantones?pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#DEUD_REGIO_').val(), dataType: 'json', }) .done(function(data) { // console.log(data); jQuery('#DEUD_CITYC_').attr( 'disabled','true'); jQuery('.cantones').remove(''); if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='000') jQuery('#DEUD_COUNC_').append('<option class="cantones" value="'+item.COUNC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); }).fail(function(err){ console.log( err ); jQuery('#loader').fadeOut(); }).always( function(){ jQuery('#loader').fadeOut(); }); } else{ jQuery('#loader').show(); if( jQuery('#DEUD_REGIO_').val() && jQuery('#pais_usuario').val()!='CR' ){ jQuery('#DEUD_CITYC_').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+''+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#DEUD_REGIO_').val(), dataType: 'json', }) .done(function(data) { // console.log(data); jQuery('.distritos').remove(''); if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#DEUD_CITYC_').append('<option class="distritos" value="'+item.CITYC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log( err ); }).always( function(){ jQuery('#loader').fadeOut(); }); } else jQuery('#DEUD_CITYC_').attr( 'disabled','true'); jQuery('#DEUD_COUNC_').attr( 'disabled','true'); jQuery('#loader').fadeOut(); } }); jQuery('#COUNC_').on('change', function(e){ e.preventDefault(); jQuery('#loader').show(); if( jQuery('#COUNC_').val() ){ jQuery('.distritos_').remove(); jQuery('#CITYC_').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+jQuery('#COUNC_').val()+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#REGIO_').val(), dataType: 'json', }) .done(function(data) { if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#CITYC_').append('<option class="distritos_" value="'+item.CITYC+'" style="text-transform:capitalize;">'+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log( err ); }).always( function(){ jQuery('#loader').fadeOut(); }); }else jQuery('#CITYC_').attr( 'disabled','true'); jQuery('#loader').fadeOut(); }); jQuery('#DEUD_COUNC_').on('change', function(e){ e.preventDefault(); jQuery('#loader').show(); if( jQuery('#DEUD_COUNC_').val() ){ jQuery('#DEUD_CITYC_').removeAttr( 'disabled','true'); jQuery.ajax( { type: 'GET', url: 'ws/gac/distritos?canton='+jQuery('#DEUD_COUNC_').val()+'&pais='+jQuery('#pais_usuario').val()+'&provincia='+jQuery('#DEUD_REGIO_').val(), dataType: 'json', }) .done(function(data) { // console.log(data); jQuery('.distritos').remove(); if( data.result ) { jQuery.each( data.records, function( index,item ) { if(item.COUNC!='0000') jQuery('#DEUD_CITYC_').append('<option class="distritos" value="'+item.CITYC+'" style="text-transform:capitalize;"> '+item.BEZEI.toLowerCase()+'</option>'); }); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ console.log( err ); }).always( function(){ jQuery('#loader').fadeOut(); }); }else jQuery('#DEUD_CITYC_').attr( 'disabled','true'); jQuery('#loader').fadeOut(); }); function valornulo( valor, tipo ){ if( tipo=='1' ){ if(valor == '0' || valor == '' || valor == ' ' /*|| valor == 'Undefined'*/) return ''; else return ', '+valor; } else{ if(valor == '0' || valor == '' /*|| valor == 'Undefined'*/) return 'Sin asignar'; else return valor; } } function frecuenciavisitas( valor ){ switch( valor ){ case 'S': return 'Semanal'; break; case 'SP': return 'Semanas Pares'; break; case 'SI': return 'Semanas Impares'; break; case 'M1': return 'Mensual Semana 1'; break; case 'M2': return 'Mensual Semana 2'; break; case 'M3': return 'Mensual Semana 3'; break; case 'M4': return 'Mensual Semana 4'; break; default: return 'Sin asignar'; break; } }; });
import React from 'react' const EditTodoItem = (props) =>{ return ( <form> <div className="form-group"> <label>Description</label> <input type="text" name="description" value={props.description} onChange={ props.handleInputChange}/> </div> <div className="form-group"> <label className="text-white">Deadline</label> <input type="text" name="deadline" value={props.deadline} onChange={ props.handleInputChange} /> </div> <button onClick={props.updateTodoItem }> Update </button> <button onClick={() => props.setEditing(false)} >Cancel</button> </form> ) } export default EditTodoItem;
import React from 'react' import { Link } from 'react-router-dom' import Kanye from '../icon_home.png' import './landing.css' const Landing = () => { return ( <section className='descriptors'> <img className='kanyeimg' src={Kanye} alt='kanye face icon'/> <h2>Satire or Statement? The real Kanye fans will know.</h2> <h3 className='bold'>To Play:</h3> <h4>Read the quote and select if you think it's a real or a fake kanye quote. Save the quote for later to reflect on it's inspiration</h4> <Link className='play-link' to='/home'> <button className='play-btn'>Play</button> </Link> </section> ) } export default Landing
console.log('Vendor dependencies loaded!')
/** * 进度条 * 用例: <Process label="开奖进度:" height={4} nowValue={60} /> */ import React, { Component } from 'react'; import { StyleSheet, View, Text, } from 'react-native'; import CommonStyles from '../common/Styles'; export default class Process extends Component { static defaultProps = { nowValue: 20, // 当前值,单位是,百分比 height: 3, // 高度 label: '', // label文字 labelStyle: {}, // label样式 showText: '', // 自定义显示的文本 } constructor (props) { super(props) this.state = { textWidth: 44, bgViewWidth: 0, showText: props.showText, textHeight: 18, } } // shouldComponentUpdate (a,b) { // console.log('a',a,'b',b) // if (a.showText === b.showText) { // return false // } // return true // } getTextWidth = (e) => { if (e.nativeEvent.layout) { this.setState({ textWidth: e.nativeEvent.layout.width, textHeight: e.nativeEvent.layout.height }) } } getBgViewWidth = (e) => { if (e.nativeEvent.layout) { this.setState({ bgViewWidth: e.nativeEvent.layout.width }) } } getOffset = (nowValue) => { const { bgViewWidth, textWidth } = this.state if (nowValue >= (100 - (textWidth / bgViewWidth) * 100)) { return (100 - (textWidth / bgViewWidth) * 100) } return nowValue } render() { const { height, label, labelStyle, showText, bgViewWidth } = this.props; const { textWidth, textHeight } = this.state // eslint-disable-next-line no-restricted-globals let nowValue = (isNaN(this.props.nowValue) ? 0 : this.props.nowValue); // 排除NaN if (nowValue > 100) { nowValue = 100; } const offsetX = this.getOffset(nowValue) const top = -((textHeight - height) / 2); return ( <View style={styles.containerView}> <Text style={[styles.labelStyle, labelStyle]}>{label}</Text> <View style={[styles.container_bgView,CommonStyles.flex_center, { borderRadius: height, height }]} onLayout={(e) => { this.getBgViewWidth(e) }}> <View style={[styles.container_nowValue, { width: `${nowValue}%`, borderRadius: height, height }, styles.noBorderRadius]}/> <Text numberOfLines={1} style={[styles.container_showValue, { left: `${offsetX}%`, top, }, { ...CommonStyles.shadowStyle }]} onLayout={(e) => { this.getTextWidth(e) }} > {(showText === 'NaN%') ? '0%' : showText || `${nowValue}%`} </Text> </View> </View> ); } } const styles = StyleSheet.create({ labelStyle: { fontSize: 12, color: '#222', paddingRight: 5, }, container_bgView: { backgroundColor: '#DFE2E6', height: '100%', flex: 1, }, container_nowValue: { backgroundColor: CommonStyles.globalHeaderColor, position: 'absolute', left: 0, }, container_showValue: { borderRadius: 2, paddingLeft: 1, paddingRight: 1, maxWidth: 81, backgroundColor: '#fff', position: 'absolute', fontSize: 12, color: '#222', textAlign: 'center', }, noBorderRadius: { borderTopRightRadius: 0, borderBottomRightRadius: 0, }, containerView: { flex: 1, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', }, });
import { GameController } from './controllers/GameController'; import { GameItem } from './models/GameItem'; const rootElement = document.querySelector('#app'); var gameApp = null; if (rootElement) { gameApp = new GameController([ new GameItem(1, '', '1.png'), new GameItem(2, '', '2.png'), new GameItem(3, '', '3.png'), new GameItem(4, '', '4.png'), new GameItem(5, '', '5.png'), new GameItem(6, '', '6.png'), new GameItem(7, '', '7.png'), new GameItem(8, '', '8.png'), new GameItem(9, '', '9.png'), new GameItem(10, '', '10.png') ], rootElement); gameApp.renderGameBoard(); }
import Config from './config.js'; import Modal from './Modal.js'; import Node from './Node.js'; export default class AnchorNode extends Node { constructor(container, instance) { super(container, instance); this.type = 'anchor'; this.defaultData = { file: '', target: 'start' }; } create(id, x, y, data = this.defaultData) { super.create(id, x, y, data); this.node.dataset.data = JSON.stringify(this.data); this.node.appendChild(this._createLabel()); this._addEndpoints(this.node, [], ['TopCenter']); jsp.repaintEverything(); jsp.Report.create(); } _createLabel() { const nodeLabel = document.createElement('span'); nodeLabel.className = 'node_label'; nodeLabel.innerHTML = `${this.data.target}<br>${this.data.file}`; return nodeLabel } save(data) { this.data = data; this.node.querySelector('.node_label').remove(); this.node.appendChild(this._createLabel()); super.save(data); } edit() { super.edit(); const modal = UIkit.modal.dialog(` <button class="uk-modal-close-default" type="button" uk-close></button> <div class="uk-modal-header"> <h2 class="uk-modal-title uk-margin-small-bottom">Anchor node</h2> <h5 class="uk-margin-remove-top">id: ${this.id}</h5> </div> <div id="body" class=" uk-modal-body"> <label class="uk-text-meta" for="file_video">Файл сценария</label> <input class="uk-input" id="anchor_file" type="text" placeholder="файл" value="${this.data.file}"> <label class="uk-text-meta" for="file_video">Узел сценария</label> <input class="uk-input" id="anchor_target" type="text" placeholder="ID узла" value="${this.data.target}"> </div> <div class="uk-modal-footer uk-text-right"> <button class="uk-button uk-button-default uk-modal-close" type="button">Cancel</button> <button class="uk-button uk-button-primary uk-modal-close" id="editor_save" type="button">Save</button> </div>`); UIkit.util.on(modal.$el, 'shown', (e) => { const editModal = e.target; e.target.querySelector("#editor_save").addEventListener('click', (e) => { let data = {}; data.file = editModal.querySelector('#anchor_file').value; data.target = editModal.querySelector('#anchor_target').value; this.save(data); }); }); } }
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "components/ui/swipeActionItem/swipeActionItem" ], { "03fc": function(n, e, t) { t.d(e, "b", function() { return o; }), t.d(e, "c", function() { return c; }), t.d(e, "a", function() {}); var o = function() { var n = this; n.$createElement; n._self._c; }, c = []; }, "5d52": function(n, e, t) { t.r(e); var o = t("c7c4"), c = t.n(o); for (var i in o) [ "default" ].indexOf(i) < 0 && function(n) { t.d(e, n, function() { return o[n]; }); }(i); e.default = c.a; }, "78b7": function(n, e, t) { t.r(e); var o = t("03fc"), c = t("5d52"); for (var i in c) [ "default" ].indexOf(i) < 0 && function(n) { t.d(e, n, function() { return c[n]; }); }(i); t("fdd3"); var a = t("f0c5"), u = t("962f"), f = Object(a.a)(c.default, o.b, o.c, !1, null, "e57cf360", null, !1, o.a, void 0); "function" == typeof u.a && Object(u.a)(f), e.default = f.exports; }, "8b43": function(n, e, t) {}, "962f": function(n, e, t) { e.a = function(n) { n.options.wxsCallMethods || (n.options.wxsCallMethods = []), n.options.wxsCallMethods.push("closeSwipe"), n.options.wxsCallMethods.push("change"); }; }, c7c4: function(n, e, t) { Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var o = { mixins: [ function(n) { return n && n.__esModule ? n : { default: n }; }(t("24c0")).default ], props: { options: { type: Array, default: function() { return []; } }, disabled: { type: Boolean, default: !1 }, show: { type: Boolean, default: !1 }, autoClose: { type: Boolean, default: !0 } }, inject: [ "swipeaction" ] }; e.default = o; }, fdd3: function(n, e, t) { var o = t("8b43"); t.n(o).a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "components/ui/swipeActionItem/swipeActionItem-create-component", { "components/ui/swipeActionItem/swipeActionItem-create-component": function(n, e, t) { t("543d").createComponent(t("78b7")); } }, [ [ "components/ui/swipeActionItem/swipeActionItem-create-component" ] ] ]);
'use strict'; /** * BOSHサービス(HTTP-XMPPブリッジ)のURLとXMPPサーバホスト名、ノード名を * 指定して、デバイスを作成する。ノード名には_dataや_metaを除いた部分を 指定する。 * とる引数の数によって挙動が異なる。 * 引数が2つの場合: * nodeNameとclientを引数にとり、デバイスが生成された時にDeviceを解決しに行く * その他: * 各情報を手動で設定 */ function Device(nodeName, name, type, accessModel, publishModel, transducers) { if (arguments.length === 2) { return this.initWithClient(nodeName, name); } return this.init(nodeName, name, type, accessModel, publishModel, transducers); } /** * @param nodeName XMPP node name of this device. required * @param name name of this device. ignored for remote device * @param type type of this device. ignored for remote device * @param accessModel access model of this device. value must be one of open, authorize, whitelist, presence, and roster. ignored for remote device * @param publishModel publish model of this device. value must be one of open, publishers, or subscribers. ignored for remote device * @param transducers array of transducers of this device. ignored for remote device */ Device.prototype.init = function (nodeName, name, type, accessModel, publishModel, transducers) { /** * profiles of this device included in SoX specification */ this.nodeName = nodeName; this.name = name; this.type = type; this.accessModel = accessModel; this.publishModel = publishModel; /** * runtime information that won't be included in meta data */ this.transducers = transducers ? $.extend(true, {}, transducers) : []; this.soxEventListener = null; this.dataSubid = ''; this.metaSubid = ''; this.dataSubscribed = false; this.metaSubscribed = false; }; /** * @param nodeName XMPP node name of this device. required * @param client connected sox client. */ Device.prototype.initWithClient = function (nodeName, client) { if (!client.isConnected()) { init(nodeName, client); return; } /** * profiles of this device included in SoX specification */ this.nodeName = nodeName; this.client = client; this.name = undefined; this.type = undefined; this.accessModel = undefined; this.publishModel = undefined; /** * runtime information that won't be included in meta data */ this.transducers = []; // array of transducers this.soxEventListener = null; this.dataSubid = ''; this.metaSubid = ''; this.dataSubscribed = false; this.metaSubscribed = false; client.resolveDevice(this); }; /** { "device": { "name": "東京都の今日の天気", "type": "outdoor weather", "nodeName": "東京都の今日の天気", "transducers": [ { "name": "weather_img", "id": "weather_img", "units": "png" }, { "name": "weather", "id": "weather" }, { "name": "max_temp", "id": "max_temp", "units": "celcius" }, { "name": "min_temp", "id": "min_temp", "units": "celcius" }, { "name": "latitude", "id": "latitude" }, { "name": "longitude", "id": "longitude" } ] } } * * @param jsonObject * @returns {___anonymous1506_1515} */ Device.fromJson = function (jsonObject) { var input = jsonObject.device; var device = new Device(); device.name = input.name; device.type = input.type; device.nodeName = input.nodeName ? input.nodeName : input.name; for (var i = 0; i < jsonObject.device.transducers.length; i++) { var transducer = Transducer.fromJson(input.transducers[i]); if (device.getTransducer(transducer.id)) { continue; } device.transducers.push(transducer); } return device; }; /** * <ANYTAG> * <device name='SSLabMote' type='indoor weather'> * <transducer name="temperature" * id="temp" canActuate="false" * units="kelvin" * unitScalar="0" * minValue="270" * maxValue="320" * resolution="0.1"> * </transducer> * <transducer name="humidity" * id="humid" * canActuate="false" * units="percent" * unitScalar="0" * minValue="0" * maxValue="100" * resolution="0.1"> * </transducer> * </device> * </ANYTAG> * @param jQueryObject * @returns device instance */ Device.fromXML = function (jQueryObject) { var deviceElement = $(jQueryObject).find('device'); var device = new Device(); device.name = $(deviceElement).attr('name'); device.type = $(deviceElement).attr('type'); var transducerElements = $(deviceElement).find('transducer'); for (var i = 0; i < transducerElements.length; i++) { var transducer = Transducer.fromXML(transducerElements.eq(i)); if (device.getTransducer(transducer.id)) { continue; } device.transducers.push(transducer); // console.log("Created " + transducer.toString()); } return device; }; Device.prototype.toString = function () { var deviceString = 'Device[nodeName=' + this.nodeName + ', name=' + this.name + ', type=' + this.type + ', accessModel=' + this.accessModel + ', publishModel=' + this.publishModel + ', transducers='; var transducerString = '['; if (this.transducers) { this.transducers.forEach(function (transducer) { transducerString += transducer.toString(); }); } transducerString += ']'; return deviceString + transducerString; }; /** * { "name": "藤沢市役所大気汚染常時監視センサ", * "type": "outdoor weather", * "nodeName": "sample", //optional * "transducers": [ * { "name": "二酸化硫黄(SO2)" * "id": "so2", * "canActuate": false, * "units": "ppm", * "unitScalar": 0, * "minValue": 0, * "maxValue": 10; * "resolution": 0.001, * "value": { * "path":"html:/html/body/table/tbody/tr[3]/td[1]/font[0]", * } * },{ "name": "二酸化窒素(NO2)" * "id": "no2", * "canActuate": false, * "units": "ppm", * "unitScalar": 0, * "minValue": 0, * "maxValue": 10; * "resolution": 0.001, * "value": { * "url": "http://www.k-erc.pref.kanagawa.jp/taiki/fujisawak.asp", * "path":"html:/html/body/table/tbody/tr[3]/td[2]/font[0]", * "update": "15 * * * *" //crontab記法でアップデート時刻を表記 * } * } * ] * } * * @param jsonObject * @returns {___anonymous1506_1515} */ Device.prototype.toJsonString = function () { var jsonString = '{' + (this.name ? '"name":"' + this.name + '",\n' : '') + (this.type ? '"type":"' + this.type + '",\n' : '') + (this.nodeName ? '"nodeName":"' + this.nodeName + '",\n' : '') + '"transducers": [\n'; for (var i = 0; i < this.transducers.length; i++) { var transducerJsonString = this.transducers[i].toJsonString(); jsonString += transducerJsonString; if (i < this.transducers.length - 1) { jsonString += ','; } jsonString += '\n'; } jsonString += ']\n'; // end of transducers jsonString += '}'; // end of device return jsonString; }; /** * Generate a metainfo xml string * * <transducer name='temperature' id='temp' canActuate='false' units='kelvin' unitScalar='0' minValue='270' maxValue='320' resolution='0.1'> * </transducer> * <transducer name='humidity' id='humid' canActuate='false' units='percent' unitScalar='0' minValue='0' maxValue='100' resolution='0.1'> * </transducer> */ Device.prototype.toMetaString = function () { var metaString = ''; for (var i = 0; i < this.transducers.length; i++) { metaString += (this.transducers[i].toMetaString() + '\n'); } return metaString; }; Device.prototype.toDataString = function () { var dataString = ''; for (var i = 0; i < this.transducers.length; i++) { var data = this.transducers[i].getSensorData(); if (data) { dataString += (data.toXMLString() + '\n'); } } return dataString; }; /** * Checks if any transducer has unpublished sensor value */ Device.prototype.isDataDirty = function () { for (var i = 0; i < this.transducers.length; i++) { if (this.transducers[i].isDataDirty) { return true; } } return false; }; Device.prototype.setDataDirty = function (flag) { for (var i = 0; i < this.transducers.length; i++) { this.transducers[i].isDataDirty = flag; } }; /** * Checks if any transducer has unpublished sensor value */ Device.prototype.isMetaDirty = function () { for (var i = 0; i < this.transducers.length; i++) { if (this.transducers[i].isMetaDirty) { return true; } } return false; }; Device.prototype.setMetaDirty = function (flag) { for (var i = 0; i < this.transducers.length; i++) { this.transducers[i].isMetaDirty = flag; } }; /** * Returns the name of this device */ Device.prototype.getName = function () { return this.name; }; /** * Returns the type of this device */ Device.prototype.getType = function () { return this.type; }; Device.prototype.addTransducer = function (transducer) { this.transducers.push(transducer); }; /** * Returns transducer instance with specified id */ Device.prototype.getTransducer = function (id) { for (var i = 0; i < this.transducers.length; i++) { if (this.transducers[i].id == id) { return this.transducers[i]; } } return null; }; /** * Returns transducer instance with specified id */ Device.prototype.hasTransducer = function (id) { for (var i = 0; i < this.transducers.length; i++) { if (this.transducers[i].id == id) { return true; } } return false; }; Device.prototype.getTransducerAt = function (index) { if (index >= this.getTransducerCount()) { return null; } return this.transducers[index]; }; Device.prototype.getTransducerCount = function () { return this.transducers.length; }; /** * Registers a listener object to this device. * * @param soxEventListener * SoxEventListener instance */ Device.prototype.setSoxEventListener = function (soxEventListener) { this.soxEventListener = soxEventListener; };
/** * Get all the scripts and activate the relevant ones */ chrome.storage.sync.get(function (overrides) { // Filter out inactive and irrelevant overrides var relevantOverrides = []; for (var id in overrides) { if (overrides.hasOwnProperty(id) && overrides[id].active) { var query = overrides[id].urlQueries.filter(function (urlQuery) { return new RegExp(urlQuery).test(window.location.href); }); if (query.length > 0) { relevantOverrides.push(overrides[id]); } } } // Activate all relevant overrides relevantOverrides.forEach(function (override) { if (override.htmlContent) { document.body.innerHTML += override.htmlContent; } if (override.cssContent) { document.head.innerHTML += '<style type="text/css">' + override.cssContent + '</style>'; } if (override.libs) { override.libs.forEach(function (lib) { var s = document.createElement("script"); s.type = "text/javascript"; s.src = lib.value; document.head.appendChild(s); }); } if (override.jsContent) { var s = document.createElement("script"); s.type = "text/javascript"; s.text = override.jsContent; document.head.appendChild(s); } }); }); /** * Listen for updates in overrides and reload the page if the updated override is relevant */ chrome.runtime.onMessage.addListener(function (message) { if (message.request == 'overrideUpdated' && message.urlQueries) { // Check if any of the overrides urls pass the regexp test var overrideRelevant = message.urlQueries.filter(function (urlQuery) { return new RegExp(urlQuery).test(window.location.href); }); if (overrideRelevant.length > 0) { window.location.reload(); } } });
(function() { 'use strict'; angular .module('Directives') .directive('orderLineView', orderLineView); orderLineView.$inject = ['$state']; function orderLineView($state) { var directive = { templateUrl: 'view-modules/orders/orders-list/order-line-view/order-line-view.directive.html', restrict: 'EA', // replace: true, scope: { // List of orders to display orders: '=', // Function to call when clicking a product select: '=', tab: '=' }, }; return directive; } })();
import React, { Component } from "react"; import Nav from "../nav"; import Banner from "../banner"; import PostContainer from "../post_component/postContainer"; import { withRouter } from "react-router"; import axios from "axios"; import Cookies from "universal-cookie"; import Tabs from "react-bootstrap/Tabs"; import Tab from "react-bootstrap/Tab"; import { DOMAIN_NAME } from "../../env"; /** * View Profile Component displays profile of searched user * @state * @String email * @String first_name * @String last_name * @String profile_image * @array post * @bool isPostAvailabilityChecked * * @props * @Object location * @methods * @lifecycle * componentDidMount * componentDidUpdate * componentWillUnmount */ class ViewProfile extends Component { constructor(props) { super(props); if (typeof this.props.location.state === "undefined") { this.props.history.goBack(); } else { this.state = { ...this.props.location.state, followingConnectionResult: [], followerConnectionResult: [], isFollowingNetworkChecked: false, isFollowerNetworkChecked: false }; this.name = this.state.first_name + " " + this.state.last_name; const sanctumTokenCookie = new Cookies(); const sanctumToken = sanctumTokenCookie.get("sanctum_token"); axios.defaults.headers.common = { Authorization: "Bearer " + sanctumToken }; const cancelToken = axios.CancelToken; this.source = cancelToken.source(); this.configAxios = { cancelToken: this.source.token }; this.loadPosts = this.loadPosts.bind(this); this.checkIfFollowed = this.checkIfFollowed.bind(this); this.follow = this.follow.bind(this); this.unfollow = this.unfollow.bind(this); this.loadFollowingConnection = this.loadFollowingConnection.bind( this ); this.loadFollowerConnection = this.loadFollowerConnection.bind( this ); } } componentDidMount() { this.checkIfFollowed(); this.loadPosts(); this.loadFollowingConnection(); this.loadFollowerConnection(); } componentDidUpdate() { this.loadPosts(); } componentWillUnmount() { this.source.cancel("View Profile Component Unmounted"); } /** * Load the posts of the viewed user */ loadPosts() { axios .get( `${DOMAIN_NAME}/api/post/${this.state.email}`, this.configAxios ) .then(res => { console.log(res.data); this.setState({ posts: res.data, isPostAvailabilityChecked: true }); }) .catch(error => { if (axios.isCancel(error)) { console.log("View Profile Component Unmounted"); } else { this.setState({ isPostAvailabilityChecked: true }); } }); } /** * Loads all connections that the user follows */ loadFollowingConnection() { axios .get( `${DOMAIN_NAME}/api/network/followings/${this.state.email}`, this.configAxios ) .then(res => { console.log(res.data); this.setState({ followingConnectionResult: res.data, isFollowingNetworkChecked: true }); }) .catch(error => { if (axios.isCancel(error)) { console.log("view profile component unmounted"); } else { this.setState({ isFollowingNetworkChecked: true }); } }); } /** * Loads all connections that the user follows */ loadFollowerConnection() { axios .get( `${DOMAIN_NAME}/api/network/followers/${this.state.email}`, this.configAxios ) .then(res => { console.log(res.data); this.setState({ followerConnectionResult: res.data, isFollowerNetworkChecked: true }); }) .catch(error => { if (axios.isCancel(error)) { console.log("View profile component unmounted"); } else { this.setState({ isFollowerNetworkChecked: true }); } }); } /** * Checks if the logged in user is following the user whose profile is being viewed */ checkIfFollowed() { axios .get(`${DOMAIN_NAME}/api/isFollowing/${this.state.email}`) .then(res => { this.setState({ isFollowing: res.data.isFollowing, isFollowingChecked: true }); console.log("Is following ", res.data); }) .catch(error => { if (axios.isCancel(error)) { console.log("View Profile Component Unmounted"); } console.log("Is following ", error); }); } /** * Handles the creation of a following for the logged in user */ follow() { this.setState({ isFollowingChecked: false }); axios .get( `${DOMAIN_NAME}/api/follow/${this.state.email}`, this.configAxios ) .then(res => { this.setState({ isFollowing: res.data.isFollowing, isFollowingChecked: true }); console.log("Is following ", res.data); }) .catch(error => { if (axios.isCancel(error)) { console.log("View Profile Component Unmounted"); } console.log("Is following ", error); }); } /** * Handles unfollowing the user whose profile is being viewed */ unfollow() { this.setState({ isFollowingChecked: false }); axios .get( `${DOMAIN_NAME}/api/unfollow/${this.state.email}`, this.configAxios ) .then(res => { this.setState({ isFollowing: res.data.isFollowing, isFollowingChecked: true }); console.log("Is following ", res.data); }) .catch(error => { if (axios.isCancel(error)) { console.log("View Profile Component Unmounted"); } // this.setState({ // isPostAvailabilityChecked: true // }); console.log("Is following ", error); }); } render() { const { followBtnClass, followBtnText, followBtnIcon, onClickFunction } = this.state.isFollowingChecked ? this.state.isFollowing ? { followBtnClass: "btn-outline-danger", followBtnText: "Unfollow", followBtnIcon: "fa-times", onClickFunction: this.unfollow } : { followBtnClass: "btn-success", followBtnText: "Follow", followBtnIcon: "fa-plus", onClickFunction: this.follow } : { followBtnClass: "btn-dark", followBtnText: "Loading", followBtnIcon: "fa-spinner fa-pulse", onClickFunction: null }; return ( <React.Fragment> <Nav hasNotification={true} count={9} /> <Banner text={this.name + "'s Profile"} /> <div className="container pt-5"> <div className=" d-flex justify-content-center"> <div className="img-circle-wrapper-profile"> <img src={ `${this.state.profile_image}` } className="img-circle" alt="profile image" /> </div> </div> <div className="text-center"> <h5 className="font-weight-bold mt-1">{this.name}</h5> <button className={ "mx-auto btn my-2 font-weight-bold " + followBtnClass } onClick={onClickFunction} disabled={!this.state.isFollowingChecked} > <span className={"fa " + followBtnIcon}></span> &nbsp;{followBtnText} </button> </div> <Tabs defaultActiveKey="posts" id="view-profile-tabs"> <Tab eventKey="posts" title="Posts" tabClassName="font-weight-bold" > <div className="row"> {this.state.posts.length > 0 ? ( this.state.posts.map(item => ( <PostContainer key={item.post_id} imgUrl={ `${item.post_image}` } poster_first_name={ item.poster_first_name } poster_last_name={ item.poster_last_name } poster_profile_image={ item.poster_profile_image } text={item.post_text} poster_email={item.user_email} likes={item.likes} hearts={item.hearts} comments={item.comments} postId={item.post_id} self_like={item.self_like} self_heart={item.self_heart} self_comment={item.self_comment} /> )) ) : this.state.isPostAvailabilityChecked ? ( <p className="offset-md-4 font-weight-bold text-center text-muted"> <span className="fab fa-searchengin fa-2x"></span>{" "} Seems like {this.name} has no posts yet. </p> ) : ( <div className="font-weight-bold offset-md-6 text-center"> <span className="fa fa-spinner fa-pulse fa-3x"></span> <p className="">Loading</p> </div> )} </div> </Tab> <Tab eventKey="following" title="Following " tabClassName="font-weight-bold" > <div className="row text-center mt-2 link-card"> {this.state.isFollowingNetworkChecked && this.state.followingConnectionResult.length > 0 ? ( this.state.followingConnectionResult.map( connection => ( <a key={connection.conn_follow_id} className="col-md-3 rounded-lg bg-white shadow" onClick={e => { e.preventDefault(); }} > <div className="img-circle-wrapper"> <img src={ `${connection.conn_profile_image}` } className="img-circle" /> </div> <p className="font-weight-bold"> {connection.conn_first_name + " " + connection.conn_last_name} </p> <p> <span className="fas fa-link"></span>{" "} { connection.conn_following_count }{" "} following </p> <p> <span className="fas fa-link"></span>{" "} { connection.conn_follower_count }{" "} follower </p> </a> ) ) ) : this.state.isFollowingNetworkChecked ? ( <p className="offset-md-4 font-weight-bold text-center text-muted"> <span className="fab fa-searchengin fa-2x"></span>{" "} Seems like you have not made connections yet. <br /> Search and start making connections </p> ) : ( <div className="font-weight-bold offset-md-6 text-center"> <span className="fa fa-spinner fa-pulse fa-3x"></span> <p className="">Loading</p> </div> )} </div> <div className="px-4"> </div> </Tab> <Tab eventKey="followers" title="Followers " tabClassName="font-weight-bold" > <div className="row text-center mt-2 link-card"> {this.state.isFollowerNetworkChecked && this.state.followerConnectionResult.length > 0 ? ( this.state.followerConnectionResult.map( connection => ( <a key={connection.conn_follow_id} className="col-md-3 rounded-lg bg-white shadow" onClick={e => { e.preventDefault(); this.viewProfile( connection ); }} > <div className="img-circle-wrapper"> <img src={ `${connection.conn_profile_image}` } className="img-circle" /> </div> <p className="font-weight-bold"> {connection.conn_first_name + " " + connection.conn_last_name} </p> <p> <span className="fas fa-link"></span>{" "} { connection.conn_following_count }{" "} following </p> <p> <span className="fas fa-link"></span>{" "} { connection.conn_follower_count }{" "} follower </p> </a> ) ) ) : this.state.isFollowerNetworkChecked ? ( <p className="offset-md-4 font-weight-bold text-center text-muted"> <span className="fab fa-searchengin fa-2x"></span>{" "} Seems like you have not made connections yet. <br /> Search and start making connections </p> ) : ( <div className="font-weight-bold offset-md-6 text-center"> <span className="fa fa-spinner fa-pulse fa-3x"></span> <p className="">Loading</p> </div> )} </div> </Tab> </Tabs> </div> </React.Fragment> ); } } export default withRouter(ViewProfile);
//definizione modulo overnet in angularjs var app = angular.module("cp", ['colorpicker.module']);
/* global localStorage */ import { Provider } from '@dws/muster-react'; import React from 'react'; import { BrowserRouter } from 'react-router-dom'; import 'todomvc-app-css/index.css'; import App from './components/app'; import Info from './components/info'; import createGraph from './muster'; import saveItemsToLocalStorage from './utils/save-items-to-local-storage'; export default function Main() { const graph = saveItemsToLocalStorage(createGraph()); return ( <Provider muster={graph}> <BrowserRouter> <div> <App /> <Info /> </div> </BrowserRouter> </Provider> ); }
var Note = require('./noteModel.js'); var Notebook = require('../notebook/notebookModel.js'); module.exports = { getNotes: function(req, res, next) { Notebook.findById(req.query._id) .populate('notes') .exec(function(error, doc) { if(error) { res.json(error); } else { res.json(doc); } }); }, saveNote: function(req, res, next) { var note = req.body; console.log(req.body); Note.create(note, function(error, savedNote) { if(error) { res.json(error); } else { Notebook.findById(note.notebook._id, function(error, savedNotebook) { if(error) { res.json(error); } else { savedNotebook.notes.push(savedNote); savedNotebook.save(function(error) { if(error) { res.json(error); } else { res.json(savedNote); } }); } }); } }); } };
import { LOGIN } from '../actions/login'; import { NEW_USER_CREATED } from '../actions/createUser'; import { POOLING_ON, POOLING_OFF, PLAYERS_FETCHED, SET_CURRENT_GAME, RESET_CURRENT_GAME } from '../actions/session'; const initState = { access_token: null, username: null, polling: false, newGameId: null, currentGame: null, players: null }; const session = (state = initState, action) => { switch (action.type) { case PLAYERS_FETCHED: return { ...state, players: action.players }; case NEW_USER_CREATED: return { ...state, players: [ ...state.players, action.user ] }; case POOLING_ON: return { ...state, polling: true }; case POOLING_OFF: return { ...state, polling: false }; case SET_CURRENT_GAME: return { ...state, currentGame: action.gameId }; case RESET_CURRENT_GAME: return { ...state, currentGame: null }; case LOGIN: return { ...state, ...action.user }; default: return state; } }; export default session;
import $ from 'jquery'; import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import './css/styles.css'; // import anime from 'animejs/lib/anime.es.js' import ArtInstitute from './ArtInstitute'; import metMuseum from './metMuseum'; import Harvard from './harvardMuseum'; function clrFields(){ $('#search').val(""); $('#search2').val(""); $('#search3').val(""); } function displayArt(object) { $("#artInFeed").prepend(` <div class="card w-75 mx-auto"> <img class='thumbnail-img card-img-top' src='https://www.artic.edu/iiif/2/${object.data.image_id}/full/843,/0/default.jpg'> <div class="card-body"> <h5 class="card-title">${object.data.title}</h5> <p class="card-text">${object.data.artist_display}, ${object.data.style_title}</p> <p class="card-text"><a href="https://www.artic.edu/artworks/${object.data.id}/">Museum Page</a></p> </div> </div>`); } function displayMet(object) { $("#metFeed").prepend(` <div class="card w-75 mx-auto"> <img class='thumbnail-img card-img-top' src="${object.primaryImage}"> <div class="card-body"> <h5 class="card-title">${object.title}</h5> <p class="card-text">${object.artistDisplayName}, ${object.classification}</p> <p class="card-text"><a href="${object.objectURL}">Museum Page</a></p> </div> </div>`); } function displayHarvard(data) { data.forEach(function (painting) { $("#harvardFeed").prepend(` <div class="card w-75 mx-auto"> <img class='thumbnail-img card-img-top' src="${painting.images[0].baseimageurl}"> <div class="card-body"> <h5 class="card-title">${painting.title}</h5> <p class="card-text">${painting.creditline}</p> <p class="card-text"><a href="${painting.url}">Museum Page</a></p> </div> </div>`); }); } function showHarvard(){ $("#harvardDisplay").removeClass('hidden') $("#artInDisplay").addClass('hidden') $("#metDisplay").addClass('hidden') } function showMet(){ $("#harvardDisplay").addClass('hidden') $("#artInDisplay").addClass('hidden') $("#metDisplay").removeClass('hidden') } function showArtIn(){ $("#harvardDisplay").addClass('hidden') $("#artInDisplay").removeClass('hidden') $("#metDisplay").addClass('hidden') } $(document).ready(function () { $("#searchForm").submit(function (e) { e.preventDefault(); let search = $('#search').val(); clrFields(); ArtInstitute.searchArt(search) .then(function (response) { const data = response.data; data.reverse(); data.forEach(function (piece) { // gathering the art data with artist/history/date etc.. ArtInstitute.searchObject(piece.id) .then(function (object) { displayArt(object); }); }); }); showArtIn(); }); $("#searchForm2").submit(function (e) { e.preventDefault(); const search = $('#search2').val(); const departmentId = $('#departmentId :selected').val(); clrFields(); // get ids for paitings with search metMuseum.searchArt(search, departmentId) .then(function (response) { const data = response.objectIDs; data.reverse(); data.forEach(function (piece) { // gathering the art data with artist/history/date etc.. metMuseum.searchObject(piece) .then(function (object) { displayMet(object); }); }); }); showMet(); }); $("#searchForm3").submit(function (e) { e.preventDefault(); let search = $('#search3').val(); clrFields(); // get ids for paitings with search Harvard.searchArt(search) .then(function (response) { const data = response.records; data.reverse(); displayHarvard(data); }); showHarvard(); }); $("#metMuseum").click(function(){ showMet(); }); $("#harvardMuseum").click(function(){ showHarvard(); }); $("#metMuseum").click(function(){ showArtIn(); }); });
const express = require('express'); const router = express.Router(); const controller = require('./sensors.controller'); router.get('/temp',controller.temp); router.get('/humi',controller.humi); router.get('/lumi',controller.lumi); module.exports = router;
import React, { useState } from 'react'; import Avatar from '@material-ui/core/Avatar'; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import Link from '@material-ui/core/Link'; import Paper from '@material-ui/core/Paper'; import Box from '@material-ui/core/Box'; import Grid from '@material-ui/core/Grid'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import 'antd/dist/antd.css' import { notification } from 'antd' import api from '../services/api' function Copyright() { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link color="inherit" href="https://booknote.com.br/"> BookNote.com.br </Link>{' '} {new Date().getFullYear()} {'.'} </Typography> ); } const useStyles = makeStyles((theme) => ({ root: { height: '100vh', }, image: { backgroundImage: 'url(https://source.unsplash.com/random)', backgroundRepeat: 'no-repeat', backgroundColor: theme.palette.type === 'light' ? theme.palette.grey[50] : theme.palette.grey[900], backgroundSize: 'cover', backgroundPosition: 'center', }, paper: { margin: theme.spacing(8, 4), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, })); export default function Login({ history }) { const [username, setUserName] = useState(''); const [password, setPassword] = useState(''); const handleLogin = async () => { const response = await api.post('/user/login', { username, password }).then((e) => { localStorage.setItem("token_auth", JSON.stringify(e.data)); history.push('/') notification.success({ message: "Seja bem vindo a plataforma :)" }) }).catch(error => { notification.error({ message: "Erro, dados incorretos!" }) }) } const classes = useStyles(); return ( <Grid container component="main" className={classes.root}> <CssBaseline /> <Grid item xs={false} sm={4} md={7} className={classes.image} /> <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> BookNote </Typography> <Typography component="h1" variant="h5"> Uma nova forma de resumos! </Typography> <form className={classes.form} noValidate onSubmit={(e) => { e.preventDefault() handleLogin(); }}> <TextField variant="outlined" margin="normal" required fullWidth id="username" label="Username" autoComplete="username" autoFocus onChange={(e) => { setUserName(e.target.value); }} /> <TextField variant="outlined" margin="normal" required fullWidth label="Senha" type="password" id="password" autoComplete="current-password" onChange={(e) => { setPassword(e.target.value); }} /> <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} > Entrar </Button> <Grid container> <Grid item xs> </Grid> <Grid item> <Link href="#" variant="body2"> {"Cadastrar-se"} </Link> </Grid> </Grid> <Box mt={5}> <Copyright /> </Box> </form> </div> </Grid> </Grid> ); }
import { Box, Flex } from "@chakra-ui/layout"; import Navbar from "./Navbar"; import Footer from "./Footer"; const Layout = ({ children }) => { return ( <Box margin="0 auto" maxWidth="1400" transition="0.5s ease-out"> <Box marginX={[2, 4, 6, 8]}> <Navbar /> {/* <Flex> <Flex display={["none", "block", "block", "block"]} alignItems={"center"} mt="200px" height="50%" > <Flex> <script type="text/javascript" dangerouslySetInnerHTML={{ __html: `atOptions = { 'key' : '4079cfaf752610083839798206411ce8', 'format' : 'iframe', 'height' : 600, 'width' : 160, 'params' : {} }; document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.topdisplayformat.com/4079cfaf752610083839798206411ce8/invoke.js"></scr' + 'ipt>');`, }} /> <script type="text/javascript" dangerouslySetInnerHTML={{ __html: `atOptions = { 'key' : '4079cfaf752610083839798206411ce8', 'format' : 'iframe', 'height' : 600, 'width' : 160, 'params' : {} }; document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.topdisplayformat.com/4079cfaf752610083839798206411ce8/invoke.js"></scr' + 'ipt>');`, }} ></script> </Flex> </Flex> <Box as="main" // marginY={22} old value marginY="4rem" > {children} </Box> <Flex display={["none", "block", "block", "block"]} ml="50px" mt="200px" alignItems={"center"} height="50%" > <Flex> <script type="text/javascript" dangerouslySetInnerHTML={{ __html: `atOptions = { 'key' : '4079cfaf752610083839798206411ce8', 'format' : 'iframe', 'height' : 600, 'width' : 160, 'params' : {} }; document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.topdisplayformat.com/4079cfaf752610083839798206411ce8/invoke.js"></scr' + 'ipt>');`, }} /> <script type="text/javascript" dangerouslySetInnerHTML={{ __html: `atOptions = { 'key' : '4079cfaf752610083839798206411ce8', 'format' : 'iframe', 'height' : 600, 'width' : 160, 'params' : {} }; document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.topdisplayformat.com/4079cfaf752610083839798206411ce8/invoke.js"></scr' + 'ipt>');`, }} ></script> </Flex> </Flex> </Flex> */} <Box as="main" // marginY={22} old value marginY="4rem" > {children} </Box> <Footer /> </Box> </Box> ); }; export default Layout;
//controls the live display and various filter auraCreate.viewController = function($scope){ //controls which view is to be displayed as well as the title $scope.changeView = function(view , org){ //only load data if the organization is changed //waits for the requests to finish before being called back, // then changes the fiew if(org != $scope.curOrg){ $scope.curOrg = org; $scope.loadBeaconsAndObjects(function (){ $scope.switchView(view); }) } else{ $scope.switchView(view); } } //switches the view and title to the user requested display $scope.switchView = function(view){ switch(view){ case "dashboard": $scope.initDashboard(); $scope.changeLiveTitle("Dashboard", false); sessionStorage.curView = view; $scope.curView = view; $("#dashboardLink").addClass("active"); $("#beaconsLink").removeClass("active"); $("#objectsLink").removeClass("active"); $("#settingsLink").removeClass("active"); break; case "beaconsList": $scope.changeLiveTitle("Beacons", true); $scope.filterTitle="beaconsView"; $scope.changeViewType('List'); sessionStorage.curView = view; $scope.curView = view; $("#beaconsLink").addClass("active"); $("#dashboardLink").removeClass("active"); $("#objectsLink").removeClass("active"); $("#settingsLink").removeClass("active"); break; case "objectsList": $scope.changeLiveTitle("Objects", true); $scope.filterTitle = "objectsView"; $scope.changeViewType('List'); $scope.changeBeaconFilter('All'); sessionStorage.curView = view; $scope.curView = view; $("#objectsLink").addClass("active"); $("#dashboardLink").removeClass("active"); $("#beaconsLink").removeClass("active"); $("#settingsLink").removeClass("active"); break; case "orgSettings": $scope.changeLiveTitle("Settings for " + $scope.curOrg.name, false); sessionStorage.curView = view; $scope.curView = view; $("#settingsLink").addClass("active"); $("#dashboardLink").removeClass("active"); $("#beaconsLink").removeClass("active"); $("#objectsLink").removeClass("active"); break; } } //handles the display of all the live display titles $scope.changeLiveTitle = function(primT, bool){ $scope.primTitle = primT; if(bool){ document.getElementById("filterTitle").style.display = "inline"; } else{ document.getElementById("filterTitle").style.display = "none"; } } //changes the view type between list or map $scope.changeViewType = function(type){ $scope.viewType = type; if(type == "Map"){ if($scope.curView == "objectsList"){ $scope.filterObjectsByBeacon($scope.beaconsFilter); } loadGoogleScript(); } } //display a single object to the live display $scope.displayBeacon = function(beacon){ $scope.curBeacon = beacon; sessionStorage.curBeacon = JSON.stringify($scope.curBeacon); $scope.changeLiveTitle("Beacon: " + $scope.curBeacon.beacon_name, false); $scope.curView = "beacon"; sessionStorage.curView = "beacon"; $scope.safeApply(); loadGoogleScript(); } //used to show a specified beacon's objects when selected from the beacons page $scope.displayBeaconObjects = function (){ $scope.changeView("objectsList", $scope.curOrg); $scope.changeBeaconFilter($scope.curBeacon.beacon_name); } //displays a single object to the live display $scope.displayObject = function(obj){ $scope.curObj = obj; sessionStorage.curObj = JSON.stringify($scope.curObj); $scope.changeLiveTitle("Object: " + $scope.curObj.name, true); $scope.curView = "object"; sessionStorage.curView = "object"; $scope.filterTitle = "objectPrivacy"; $scope.safeApply(); loadGoogleScript(); } //----------------------------------------------View Filters--------------------------------------------------------------- //toggles the description content editable on demand feature $scope.toggleObjectDescriptionEdit = function(){ if($scope.showObjDescEdit){ $scope.showObjDescEdit = false; } else{ $scope.showObjDescEdit = true; } } //returns whether or not an asset is to be displayed based on the filters and media type $scope.galleryMediaFilter = function(asset){ return($scope.galleryFilter[asset.content_type]); } //alters the objects list to view by a specific beacon or by all beacons $scope.changeBeaconFilter = function(filter){ $scope.beaconsFilter = filter; if($scope.viewType == "Map"){ $scope.filterObjectsByBeacon(filter); loadGoogleScript(); } } //filters the session storage of objects depending on the beacon filter $scope.filterObjectsByBeacon = function(filter){ var tempArray = []; for(var i = 0; i < $scope.objectsArray.length; i++){ if(filter == "All"){ tempArray.push($scope.objectsArray[i]); } else{ if(filter == $scope.objectsArray[i].beacon_name){ tempArray.push($scope.objectsArray[i]); } } } sessionStorage.objectsArray = JSON.stringify(tempArray); } //shows the tooltip on certain events $scope.showBeaconsFilterTooltip = function(){ $("#beaconsFilterDiv").tooltip({title: $scope.beaconsFilter, placement: "right"}); } //destroys the previous tooltip so that a new title can be assigned $scope.hideBeaconsFilterTooltip = function(){ $("#beaconsFilterDiv").tooltip("destroy"); } //displays the assets of an object with the specified filter $scope.displayFilteredAssets = function(filter, obj){ $scope.curObj = obj; $scope.displayAssetsModal(); $scope.galleryFilter.image = false; $scope.galleryFilter.audio = false; $scope.galleryFilter.video = false; $scope.galleryFilter.threeD = false; switch(filter){ case "image": $scope.galleryFilter.image = true; break; case "audio": $scope.galleryFilter.audio = true; break; case "video": $scope.galleryFilter.video = true; break; case "3d": $scope.galleryFilter.threeD = true; break; default: $scope.galleryFilter.image = true; $scope.galleryFilter.audio = true; $scope.galleryFilter.video = true; $scope.galleryFilter.threeD = true; break; } } }
'use strict'; var Team = Backbone.Model.extend({ defaults: { name: '', age: '', hobby: '' } }); var Teams = Backbone.Collection.extend({}); var teams = new Teams(); var TeamView = Backbone.View.extend({ model: new Team(), tagName: 'tr', initialize: function() { this.template = _.template($('.teams-list-template').html()); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); var TeamsView = Backbone.View.extend({ model: teams, el: $('.teams-list'), initialize: function() { var self = this; this.model.on('add', this.render, this); }, render: function() { var self = this; this.$el.html(''); _.each(this.model.toArray(), function(team) { self.$el.append((new TeamView({ model: team })).render().$el); }); return this; } }); var teamsView = new TeamsView(); $(document).ready(function() { $('.add-team').on('click', function() { var team = new Team({ name: $('.name-input').val(), age: $('.age-input').val(), hobby: $('.hobby-input').val() }); console.log(team.toJSON()); teams.add(team); }) })
import * as React from "react" import ContactForm from "../components/ContactForm" import Layout from "../components/Layout" const Contact = () => { const lang = "en"; return ( <Layout lang={lang}> <ContactForm lang={lang}/> </Layout> ) } export default Contact
export const transition = { duration: 1, ease: [0.43, 0.13, 0.23, 0.96] }; export const containerVariants = { exit: { y: "-30%", opacity: 0, transition }, enter: { y: "0%", opacity: 1, transition } }; export const mediaBoxVariants = { exit: { y: "30%", opacity: 0, transition }, enter: { y: "0%", opacity: 1, transition } }; export const titleVariants = { exit: { x: 50, opacity: 0, transition }, enter: { x: 0, opacity: 1, transition: {delay: 0.1, ...transition } } }; export const imageContainerVariants = { exit: { x: 100, opacity: 0, transition }, enter: { x: 0, opacity: 1, transition: { staggerChildren: 0.2, ...transition } } } export const imageItemVariants = { exit: { opacity: 0 }, enter: { opacity: 1 } }
import axios from 'axios' export function wantedAllFilm (username) { const url = '/account/viewrecord/wanted' return axios.get(url,{ params: { username: username } }).then((res) => { return Promise.resolve(res.data) }).catch((err) => { console.log(err) }) } export function watchedAllFilm (username) { const url = '/account/viewrecord/watched' return axios.get(url,{ params: { username: username } }).then((res) => { return Promise.resolve(res.data) }).catch((err) => { console.log(err) }) } export function myCollection (username) { const url = '/account/collection' return axios.get(url,{ params: { username: username } }).then((res) => { return Promise.resolve(res.data) }).catch((err) => { console.log(err) }) }
import React, { useEffect } from "react"; import { withApollo, Query } from "react-apollo"; import { withRouter } from "react-router-dom"; import { VERIFY_TOKEN } from "api/mutations"; import { USER } from "api/queries"; import * as path from "constants/routes"; export const withAuth = (WrappedComponent) => withRouter( withApollo((props) => { useEffect(() => { verifyUser(); }, []); const verifyUser = async () => { try { await props.client.mutate({ mutation: VERIFY_TOKEN, variables: { token: JSON.parse(localStorage.getItem("token")).token || "", }, fetchPolicy: "no-cache", }); } catch (error) { props.history.push(path.SIGN_IN); window.localStorage.removeItem("token"); } }; return ( <Query query={USER} fetchPolicy="network-only"> {({ loading, error, data }) => { if (loading || !data) return null; if (error) return null; return <WrappedComponent {...props} user={data.me} />; }} </Query> ); }) );
import DefaultLayout from '@layouts/default' import Link from 'next/link' import {getConfig, getAllPosts} from '@api' export default function Blog(props) { return ( <DefaultLayout title={props.title} description={props.description}> <hr/> <div> {props.posts.map(function (post) { return ( <div className='col p-4 d-flex flex-column position-static'> <strong className='d-inline-block mb-2 text-primary'>Hello</strong> <h3 className='mb-0'>{post.title}</h3> <div className='mb-1 text-muted'>13-321-2</div> <Link href={'/posts/' + post.slug}>Continue reading</Link> </div> ) })} </div> </DefaultLayout> ) } export async function getStaticProps() { const config = await getConfig() const allPosts = await getAllPosts() return { props: { posts: allPosts, title: config.title, description: config.description } } }
import likeIcon from "../images/heart.svg"; import likeIconSolid from "../images/heart-solid.svg"; import deleteButton from "../images/trash.svg"; import React from "react"; import { CurrentUserContext } from "../contexts/CurrentUserContext"; import PropTypes from "prop-types"; export default function Card({ source, onClick, onCardLike, onCardDelete }) { Card.propTypes = { source: PropTypes.object, onClick: PropTypes.func, onCardLike: PropTypes.func, onCardDelete: PropTypes.func, }; const { name, link, likes } = source; const currentUser = React.useContext(CurrentUserContext); const isOwn = currentUser._id === source.owner; const isLiked = likes.some((l) => l === currentUser._id); function handleImageClick() { const data = { name, link }; onClick(data); } function handleLikeClick() { onCardLike(source); } function handleDeleteClick() { onCardDelete(source); } return ( <li className="card"> <img src={link} alt={name} className="card__image" onClick={handleImageClick} /> <div className="card__title-container"> <h2 className="card__title">{name}</h2> <button type="button" className="card__like-button" onClick={handleLikeClick}> <img src={isLiked ? likeIconSolid : likeIcon} alt="Нравится" /> <span className="card__like-count">{likes.length}</span> </button> </div> <button type="button" className="card__delete-button" disabled={!isOwn} onClick={handleDeleteClick}> <img src={deleteButton} alt="Удалить место" /> </button> </li> ); }
var Tokensale = artifacts.require('./Tokensale.sol'); var CREDToken = artifacts.require('./CREDToken.sol'); import increaseTime, { duration, increaseTimeTo } from 'zeppelin-solidity/test/helpers/increaseTime'; import latestTime from 'zeppelin-solidity/test/helpers/latestTime'; import exceptThrow from 'zeppelin-solidity/test/helpers/expectThrow'; import { generateAddresses } from './utils'; contract('TokenSale', function (accounts) { let tokensale, token, owner = accounts[0], teamWallet = accounts[1], reserveWallet = accounts[2], advisorsWallet = accounts[3], userWallet = accounts[4], treasury = accounts[5], investmentFundWallet = accounts[6], miscellaneousWallet = accounts[7], preAllocatedTokens = web3.toWei( 10500000+2875000+20000000+5500000, 'ether'), whitelist = [accounts[8], ...generateAddresses(10)], presaleLimits = [5, 1, 10, 20, 1, 256, 1000000, 1, 1, 1, 1]; const deploy = async (hardCap) => { tokensale = await Tokensale.new( latestTime() + duration.days(1), latestTime() + duration.days(3), web3.toBigNumber(web3.toWei(hardCap, 'ether')), investmentFundWallet, miscellaneousWallet, treasury, teamWallet, reserveWallet, advisorsWallet, { from: owner, gas: 6000000 } ); await tokensale.addPresaleWallets( whitelist, presaleLimits.map(l => web3.toWei(l, 'ether')), { from: owner, gas: 6000000 } ); token = CREDToken.at(await tokensale.token()); } beforeEach(async () => { await deploy(5000); }); describe('Before presale', () => { it('should setup token', async () => { assert.deepEqual(await token.cap(), web3.toBigNumber(web3.toWei(50000000, 'ether'))); }); it('should calculate rate', async () => { assert.equal((await tokensale.rate()).toString(), '2225'); }) it('should correctly set token allocations', async () => { let total = await tokensale.MAX_SUPPLY(), sale = await tokensale.SALE_TOKENS_SUPPLY(), investment = await tokensale.INVESTMENT_FUND_TOKENS_SUPPLY(), miscellanous = await tokensale.MISCELLANEOUS_TOKENS_SUPPLY(), team = await tokensale.TEAM_TOKENS_SUPPLY(), reserve = await tokensale.RESERVE_TOKENS_SUPPLY(), advisors = await tokensale.ADVISORS_TOKENS_SUPPLY(); assert.deepEqual(total, web3.toBigNumber(web3.toWei(50000000, 'ether'))); assert.deepEqual(total, sale .plus(investment) .plus(miscellanous) .plus(team) .plus(reserve) .plus(advisors) ); }); it('non-owner should not able to add presale accounts', async () => { await exceptThrow(tokensale.addPresaleWallets([userWallet], [1], { from: userWallet })); }); it('should be possible for owner to change cap', async () => { await tokensale.setHardCap(web3.toWei(1000, 'ether'), {from: owner}); assert.deepEqual(await tokensale.cap(), web3.toBigNumber(web3.toWei(1000, 'ether'))); assert.deepEqual(await tokensale.rate(), web3.toBigNumber(11125)); }); it('non-owner cannot change cap', async () => { await exceptThrow(tokensale.setHardCap(web3.toWei(1000, 'ether'), {from: userWallet})); }); it('should not be possible to take part in presales', async () => { await exceptThrow(tokensale.sendTransaction({from: whitelist[0], value: 1})); }); }); describe('During presale', () => { beforeEach(async () => { await increaseTime(duration.days(1)); }); it('presale should work', async () => { let treasuryBalanceBefore = web3.fromWei(await web3.eth.getBalance(treasury), 'ether').toNumber(); tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('5', 'ether')), from: whitelist[0] }); assert.deepEqual(web3.fromWei(await token.balanceOf(whitelist[0]), 'ether').toString(), '11125'); assert.deepEqual( web3.fromWei(await web3.eth.getBalance(treasury), 'ether').toNumber() - treasuryBalanceBefore, 5); }); it('not possible to change hardcap', async () => { await exceptThrow(tokensale.setHardCap(web3.toWei(1000, 'ether'), {from: owner})); }); it('not possible to buy if not in whitelist', async () => { await exceptThrow(tokensale.sendTransaction({ value: web3.toWei('1', 'ether'), from: userWallet })); }); it('should not presale over cap', async () => { await deploy(5); await increaseTime(duration.days(1)); await exceptThrow(tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('11', 'ether')), from: whitelist[0] })); }); it('should not presale over cap while adding', async () => { await deploy(5); await increaseTime(duration.days(1)); await exceptThrow(tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('11', 'ether')), from: whitelist[0] })); }) it('cannot buy over limit', async () => { await exceptThrow(tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('5.1', 'ether')), from: whitelist[0] })); await tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('4', 'ether')), from: whitelist[0] }); await exceptThrow(tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('1.1', 'ether')), from: whitelist[0] })); }); it('limit behaves correctly when value has many decimal digits', async () => { await tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('2.51', 'ether')), from: whitelist[0] }); await exceptThrow(tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('2.5', 'ether')), from: whitelist[0] })); } ); it('tokens should be frozen', async () => { await tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('4', 'ether')), from: whitelist[0] }); await exceptThrow(token.transfer(accounts[9], 1, {from: whitelist[0]})); }); it('should be finalisable if hard cap reached', async () => { await deploy(5); await increaseTime(duration.days(2)); await tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('5', 'ether')), from: whitelist[0] }); await tokensale.finalise(); }); it('presale tokens transferable week after finalization', async () => { await deploy(5); await increaseTime(duration.days(2)); await tokensale.sendTransaction({ value: web3.toBigNumber(web3.toWei('5', 'ether')), from: whitelist[0] }); await tokensale.finalise(); await increaseTime(duration.weeks(1)); await token.unfreeze(); await token.transfer(accounts[9], 1, {from: whitelist[0]}); assert.deepEqual((await token.balanceOf(accounts[9])).toString(), '1'); }); }); describe('During Sale', () => { beforeEach(async () => { await increaseTime(duration.days(3)); }); it('should be possible to buy', async () => { await tokensale.sendTransaction({value: web3.toWei('1', 'ether'), from: userWallet}); let balance = await token.balanceOf(userWallet); assert.equal(balance.div(await tokensale.rate()).toString(10), web3.toWei('1', 'ether')); }); it('should not be possible to buy over hard cap', async () => { // Need to lower cap because of testrpc limitations await deploy(10); await increaseTime(duration.days(3)); await exceptThrow(tokensale.sendTransaction({ value: web3.toWei('11', 'ether'), from: userWallet })); // Sanity check await tokensale.sendTransaction({ value: web3.toWei('9', 'ether'), from: userWallet }); }); it('tokens should be frozen', async () => { await tokensale.sendTransaction({ value: web3.toWei('1', 'ether'), from: accounts[9] }); await exceptThrow(token.unfreeze()); await exceptThrow(token.transfer(userWallet, 1, { from: userWallet })); }); it('should not be possible to pause if not owner', async () => { await exceptThrow(tokensale.pause({from: userWallet})); }) it('should not be possible to finalise', async () => { await exceptThrow(tokensale.finalise()); }); it('should be finalisable after hard cap reached', async () => { await deploy(3); await increaseTime(duration.days(3)); await tokensale.sendTransaction({ value: web3.toWei('3', 'ether'), from: userWallet }); await tokensale.finalise(); }); describe('Paused', () => { beforeEach(async () => { await tokensale.pause({from: owner}); }); it('should not be possible to buy', async () => { await exceptThrow(tokensale.sendTransaction({value: web3.toWei('1', 'ether'), from: userWallet})); }); it('not owner should not be able to unpause', async () => { await exceptThrow(tokensale.unpause({from: userWallet})); }); it('should buy tokens after unpause', async () => { await tokensale.unpause({from: owner}); await tokensale.sendTransaction({value: web3.toWei('1', 'ether'), from: userWallet}) }); }); describe('After sale', () => { beforeEach(async () => { await increaseTime(duration.days(3)); await tokensale.sendTransaction({ value: web3.toWei('1', 'ether'), from: userWallet }); await increaseTime(duration.days(30)); await tokensale.finalise(); }); it('should be finalised', async () => { assert.equal(await token.mintingFinished(), true); }); it('should not be possible to buy', async () => { await exceptThrow(tokensale.sendTransaction({value: web3.toWei('1', 'ether'), from: userWallet})); await exceptThrow(tokensale.sendTransaction({value: web3.toWei('1', 'ether'), from: whitelist[0]})); }); it('should not be unfreezable', async () => { await exceptThrow(token.unfreeze()); }); describe('Unfrozen tokens', () => { beforeEach(async () => { await increaseTime(duration.weeks(1)); await token.unfreeze(); }) it('tokens should be unfreezable after a week', async () => { await token.transfer(accounts[8], 1, {from: userWallet}); assert.deepEqual((await token.balanceOf(accounts[8])).toString(), '1'); }); it('investment wallet and misc. wallet transferable', async () => { await token.transfer(accounts[8], 1, {from: investmentFundWallet}); await token.transfer(accounts[8], 1, {from: miscellaneousWallet}); assert.deepEqual((await token.balanceOf(accounts[8])).toString(), '2'); }); it('team and reserve not transferable', async () => { await exceptThrow(token.transfer(accounts[8], 1, {from: teamWallet})); await exceptThrow(token.transfer(accounts[8], 1, {from: reserveWallet})); }); it('team and reserve transferable after a year', async () => { await increaseTime(duration.years(1)); await token.transfer(accounts[8], 1, {from: investmentFundWallet}); await token.transfer(accounts[8], 1, {from: miscellaneousWallet}); assert.deepEqual((await token.balanceOf(accounts[8])).toString(), '2'); }); }); }); }); });
'use strict'; const sharedComponent = require('..'); describe('@platform-app/shared-component', () => { it('needs tests'); });
import React from 'react'; import PropTypes from 'prop-types'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCopy } from '@fortawesome/free-solid-svg-icons'; import { toastr } from 'react-redux-toastr'; import copy from 'copy-to-clipboard'; /* eslint-disable css-modules/no-undef-class */ const ListHash = ({ hash }) => ( <div> <span>{`${hash.substring(0, 15)}...`}</span> &nbsp; <button onClick={() => { copy(hash); toastr.info('copied!'); }} style={{ height: 'auto', color: '#f00', background: 'transparent', border: 0, }} > <FontAwesomeIcon icon={faCopy} title="copy" color="#a5bdea" /> </button> </div> ); ListHash.propTypes = { hash: PropTypes.string.isRequired, }; export default ListHash;
//===================================================================================================================================== exercise 7 soal 1 console.log('============================================================================== Soal No. 1'); var rows1=5; // input the number of rows // do loops to display asterisks in the console. for (let i = 0; i < rows1; i++) { console.log('*'); } //===================================================================================================================================== exercise 6 soal 2 console.log('============================================================================== Soal No. 2'); var rows2=5; // input the number of rows // do loops to display asterisks in the console. var str2; for (let i = 0; i < rows2; i++) { str2 = ''; for (let j = 0; j < rows2; j++) { str2 += '*'; } console.log(str2); } //===================================================================================================================================== exercise 6 soal 3 console.log('============================================================================== Soal No. 3'); var rows3=5; // input the number of rows // do loops to display asterisks in the console. var str3; for (let i = 1; i <= rows3; i++) { str3=''; for (let j = 1; j <= i; j++) { str3 += '*'; } console.log(str3); }
const express = require('express'); const app = express() const mongoose = require('mongoose'); const config = require('./config/index'); const routes = require('./config/routes'); require('dotenv').config() //const product = require('./models/product') const HOSTNAME = process.env.HOSTNAME || "localhost"; const PORT = process.env.PORT || 3001; const { MONGO_CONNECTION_URL } = config; mongoose.connect(MONGO_CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true, }) // Adding new mongo url parser .then(() => console.log("Connected to database in cluster")) .catch((err) => console.log(err)); /* #### More data hardcoded into mongoDB collection #### product.create({ "productId": "12445dsd234", "category": "Modile", "productName": "Samsung", "productModel": "GalaxyNote", "price": 700, "availableQuantity": 10 }) */ //app.get('/rest/v1/products', ProductsList) // without explicitly creating routes routes(app); app.listen(PORT, HOSTNAME, () => { console.log(`Product connected to port ${PORT}`); console.log(`GET request @ http://${HOSTNAME}:${PORT}/rest/v1/products`); })
describe('ViewSchemaParser', function() { 'use strict'; describe('normalize:', function() { var ViewSchemaParser; function assertFieldView(fieldViews, index, expectedFieldName, expectedInputType) { expect(fieldViews.length).toBeGreaterThan(index); var fieldView = fieldViews[index]; expect(fieldView.fieldName).toBe(expectedFieldName); expect(fieldView.inputType).toBe(expectedInputType); }; beforeEach(function() { ViewSchemaParser = formsjs.ViewSchemaParser; }); it('should gracefully handle falsy values', function() { var schemas = [undefined, null, false]; schemas.forEach(function(schema) { var normalized = ViewSchemaParser.normalize(schema); expect(normalized.length).toBe(0); }); }); it('should gracefully empty rules', function() { var schemas = [{}, []]; schemas.forEach(function(schema) { var normalized = ViewSchemaParser.normalize(schema); expect(normalized.length).toBe(0); }); }); it('should convert nested objects to an array of field-views', function() { var schema = { name: {inputType: 'text'}, address: { city: {inputType: 'text'}, state: {inputType: 'text'}, zip: {inputType: 'integer'} }, number: {inputType: 'text'} }; var normalized = ViewSchemaParser.normalize(schema); expect(normalized.length).toBe(5); assertFieldView(normalized, 0, 'name', 'text'); assertFieldView(normalized, 1, 'address.city', 'text'); assertFieldView(normalized, 2, 'address.state', 'text'); assertFieldView(normalized, 3, 'address.zip', 'integer'); assertFieldView(normalized, 4, 'number', 'text'); }); it('should pass through field-view arrays without modification', function() { var schema = [ {fieldName: 'name', inputType: 'text'}, {fieldName: 'address.city', inputType: 'text'}, {fieldName: 'address.state', inputType: 'text'}, {fieldName: 'address.zip', inputType: 'integer'}, {fieldName: 'number', inputType: 'text'}, ]; var normalized = ViewSchemaParser.normalize(schema); expect(normalized.length).toBe(5); assertFieldView(normalized, 0, 'name', 'text'); assertFieldView(normalized, 1, 'address.city', 'text'); assertFieldView(normalized, 2, 'address.state', 'text'); assertFieldView(normalized, 3, 'address.zip', 'integer'); assertFieldView(normalized, 4, 'number', 'text'); }); }); });
var http = require('http'); var fs = require('fs'); var file = process.argv[2]; // The `fs` core module also has some streaming APIs for files. You will // need to use the `fs.createReadStream()` method to create a stream // representing the file you are given as a command-line argument. The // method returns a stream object which you can use `src.pipe(dst)` to // pipe the data from the `src` stream to the `dst` stream. In this way // you can connect a filesystem stream with an HTTP response stream. var server = http.createServer(function (req, res){ fs.createReadStream(file).pipe(res); }); server.listen(8000);
import {registerNode} from 'spritejs'; import {Torus as _Torus} from 'ogl'; import TorusAttr from '../attribute/torus'; import Mesh3d from './mesh3d'; export default class Torus extends Mesh3d { static Attr = TorusAttr; /* override */ onPropertyChange(key, newValue, oldValue) { super.onPropertyChange(key, newValue, oldValue); if(key === 'radius' || key === 'tube' || key === 'radialSegments' || key === 'tubularSegments' || key === 'arc') { if(newValue !== oldValue) { this.updateMesh(); } } } /* override */ remesh() { const gl = this.program.gl; const {radius, tube, radialSegments, tubularSegments, arc} = this.attributes; const geometry = new _Torus(gl, { radius, tube, radialSegments, tubularSegments, arc}); this.setGeometry(geometry); } } registerNode(Torus, 'torus');
import React from 'react'; import App from './App'; import { shallow } from 'enzyme'; describe("App", () => { let wrapper; beforeEach(() => { wrapper = shallow( <App/>); }); it("matches the snapshot", () => { expect(wrapper).toMatchSnapshot(); }); it("componentDidUpdate", async () => { wrapper = shallow(<App/>, {disableLifecycleMethods: true}); const update = wrapper.instance().componentDidUpdate();//eslint-disable-line const background = require('../../images/background/background.png');//eslint-disable-line const expectedStyle = {"background-image": "url(background.png)"}; expect(document.body.style._values).toEqual(expectedStyle); }); });
import { useEffect, useState } from "react"; const useDisplayPhoto = (photos) => { const [display, setDisplay] = useState([]); useEffect(() => { setDisplay(photos.map((photo) => URL.createObjectURL(photo))); }, [photos]); return display; }; export default useDisplayPhoto;
var friends = ["Morgan", "Rick", "Jackson", "Noah", "Kaleb"]; var locations = ["Mount Saint Hellen", "Innovation headquarters", "Members Mart", "Sunset Blvd", "Big Blues Pub", "Mystery mountain", "Tuscaloosa", "Costco", "football game", "the black hole sun"]; var weapons = ["a Pistol", "a Cannon", "a paper clip", "a bowling ball", "a knife", "a bat", "a extra most bestest pizza slice", "a car", "a monitor", "a single drop of water", "a hoola hoop", "a serious conersation", "a pool stick", "a cue ball", "a door handle", "a odd look", "a virus", "a lacrosse stick", "a punch", "a nerf gun"]; for (let i = 1; i < 101; i++) { var h3 = document.createElement("h3"); h3.innerText = "Accusation " + i + "."; h3.addEventListener('click', function () { let friend = friends[Math.floor(Math.random() * friends.length)]; let weapon = weapons[Math.floor(Math.random() * weapons.length)]; let location = locations[Math.floor(Math.random() * locations.length)]; alert("Accusation " + i + ": I accuse " + friend + ", with " + weapon + " while at " + location + "!"); }); document.body.appendChild(h3); }
import React, { Component } from 'react' export default class Pagination extends Component { constructor(props) { super(props) this.state={ pageNumber: props.pageNumber, paginate: props.paginate, value: props.value } } render() { return ( <button onClick={this.state.paginate}>{this.state.value}</button> ) } }
module.exports = ` ############################################ ## Contentful Fallback Types ############################################ type ContentfulFluid { base64: String aspectRatio: Float! src: String! srcSet: String! srcWebp: String srcSetWebp: String sizes: String! } type ContentfulFixed { base64: String aspectRatio: Float width: Float! src: String! srcSet: String! srcWebp: String srcSetWebp: String } type ContentfulFile { url: String! } enum ContentfulImageCropFocus { TOP CENTER BOTTOM } type ContentfulAsset implements Node { fluid(maxWidth: Int, maxHeight: Int, cropFocus: ContentfulImageCropFocus): ContentfulFluid fixed(width: Int, height: Int, cropFocus: ContentfulImageCropFocus): ContentfulFixed file: ContentfulFile } `