text stringlengths 7 3.69M |
|---|
import React, { Component } from 'react'
import s from './Avatar.css'
class Avatar extends Component{
render(){
return(
<div className={s.avatar} >
<img src={this.props.src} alt={this.props.user} />
</div>
)
}
}
export default Avatar |
๏ปฟangular.module('ngApp.uploadShipment').controller('WithServiceFinalMessageController', function ($scope, $uibModal, BatchProcessedShipments, BatchUnprocessedShipments, BatchProcess, config, SessionRecord) {
function init() {
$scope.UnsuccessFullShipments = [];
$scope.ImagePath = config.BUILD_URL;
$scope.Total = BatchProcess;
$scope.Processed = BatchProcessedShipments;
$scope.Unprocessed = BatchUnprocessedShipments;
$scope.SessionName = SessionRecord.SessionName;
}
init();
}); |
export const getModules = ({
app: {
config: { modules },
},
}) => modules;
export const getPages = ({
app: {
config: { pages },
},
}) => pages;
|
'use strict';
// api globals
var appToken = 'RLf82kXaTSeOLmaES2qZ5Bkc8';
var metioriteLandingUrl = 'https://data.nasa.gov/resource/gh4g-9sfh.json';
var seattleCrime = 'https://data.seattle.gov/resource/3xqu-vnum.json';
// app globals
var metoriteData = [];
function Metiorite(name, mass, fall, year){
this.name = name;
this.mass = mass;
this.fall = fall;
this.year = year;
metoriteData.push(this);
}
Metiorite.prototype.createLiEl = function(){
var li = document.createElement('li');
var section = document.createElement('section');
li.appendChild(section);
var h1 = document.createElement('h1');
h1.textContent = this.name;
section.appendChild(h1);
var p = document.createElement('p');
p.textContent = 'Mass: ' + this.mass + ', Year: ' + new Date(this.year).getFullYear();
section.appendChild(p);
return li;
};
function handleRequestFail(data, textSatus){
dubugger;
}
function getDataFromUrl(url, data, handler){
url += '?$$app_token=' + appToken;
$.getJSON(url, data, handler).fail(function(xhr){
alert( 'Sorry, there was a problem!' );
console.log('Error Status Code: ' + xhr.status);
console.log('Error Status Text: ' + xhr.statusText);
console.dir(xhr);
});
//$.ajax({
//url: url,
//type: 'GET',
//data: data,
//dataType: 'json',
//success: handler,
//}).fail(function(xhr) {
//alert( 'Sorry, there was a problem!' );
//console.log('Error Status Code: ' + xhr.status);
//console.log('Error Status Text: ' + xhr.statusText);
//console.dir(xhr);
//})
}
function render250Metiorites(offset){
var metioriteImageListUL = document.getElementsByClassName('metiorite-image-list')[0];
if (offset < metoriteData.length){
for (var i = offset; i < metoriteData.length && i < (offset + 250); i++){
var meatiorLi = metoriteData[i].createLiEl();
metioriteImageListUL.appendChild(meatiorLi);
}
}
}
function handleAjaxRequest(data){
if (Array.isArray(data)){
for(var i = 0; i < data.length; i++){
var item = data[i]
new Metiorite(item.name, item.mass, item.fall, item.year);
}
render250Metiorites(0);
}
}
var options = {
'$limit': 5,
'$offset': 100,
};
getDataFromUrl(metioriteLandingUrl, options, handleAjaxRequest);
//function handleSetateRequest(data){
//console.dir(data);
//debugger;
//}
//getDataFromUrl(seattleCrime, options, handleSetateRequest);
|
const inputUsername = document.querySelector('[data-id=username]')
inputUsername.addEventListener('input', (event) => {
const target = event.currentTarget
const lowerCaseWords = [ 'de', 'da', 'do', 'dos' ]
const valueArray = target.value.split(' ')
target.value = valueArray.map((word) => {
return lowerCaseWords.includes(word.toLowerCase())
? word.toLowerCase()
: `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`
}).join(' ')
})
const groupSelect = document.querySelector('[data-id=group-select]')
const groupColors = document.querySelector('[data-id=group-colors]')
const label = document.createElement('label')
const select = document.createElement('select')
const colors = [
{
name: 'Azoxo',
hex: '#5865F2'
},
{
name: 'Verde',
hex: '#57F287'
},
{
name: 'Amarelo',
hex: '#FEE75C'
},
{
name: 'Fรบcsia',
hex: '#EB459E'
},
{
name: 'Vermelho',
hex: '#ED4245'
}
]
colors.forEach(value => {
const option = document.createElement('option')
option.value = value.hex
option.innerText = value.name
select.appendChild(option)
})
label.innerText = 'Selecione uma cor'
select.setAttribute('multiple', '')
select.addEventListener('change', (event) => {
groupColors.innerHTML = ''
const target = event.target
const options = target.selectedOptions
Array.from(options).forEach((option) => {
const span = document.createElement('span')
span.style.backgroundColor = option.value
groupColors.appendChild(span)
})
})
groupSelect.appendChild(label)
groupSelect.appendChild(select)
|
var mentor = "Dylan Westover";
console.log("My mentor's name is "+mentor)
|
import React, { Component } from 'react';
import './modal.css';
class Modal extends Component {
constructor (props) {
super(props)
this.state = {
visible: true
}
}
render () {
const { visible } = this.state;
const { title, children } = this.props
return visible && <div className="modal-wrapper">
<div className="modal">
<div className="modal-title">{title}</div>
<div className="modal-content">{children}</div>
<div className="modal-operator">
<button className="modal-operator-close" onClick={this.closeModal}>ๅๆถ</button>
<button className="modal-operator-confirm" onClick={this.confirm}>็กฎ่ฎค</button>
</div>
</div>
<div className="mask"
onClick={this.maskClick}></div>
</div>
}
maskClick = () => {
console.log('ๆ็นๅปไบ่ๅฑ');
this.setState({
visible: false
})
}
closeModal = ()=>{
const { onClose } = this.props;
onClose && onClose();
this.setState({
visible: false
})
}
confirm = () => {
const { confirm } = this.props;
confirm && confirm();
this.setState({
visible: false
})
}
componentWillReceiveProps(props){
this.setState({
visible: props.visible
})
}
}
export default Modal;
|
const { SlashCommandBuilder } = require('@discordjs/builders');
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
data: new SlashCommandBuilder()
.setName('gif')
.setDescription('Get a gif!')
.addStringOption(option =>
option.setName('searchterm')
.setRequired(true)
.setDescription('Your search term!')),
async execute(selection) {
const response = await axios.get(`https://g.tenor.com/v1/random?q=${selection.options._hoistedOptions[0].value}&key=${process.env.TENOR_API_TOKEN}&limit=10`);
const randomGif = await response.data.results[Math.floor(Math.random() * response.data.results.length)].url;
await selection.reply(randomGif);
}
};
|
// import { useHistory } from "react-router-dom";
// function HovedsideButton() {
// let history = useHistory();
// function handleClick() {
// history.push("/loginside");
// }
// return (
// <button type="button" onClick={handleClick}>
// Tilbake
// </button>
// );
// }
// export default HovedsideButton;
|
import Position from './position';
import { ANIMATION_DURATION_MS, CLASS_NO_ANIMATION, ID_OVERLAY, OVERLAY_HTML } from '../common/constants';
import { createNodeFromString } from '../common/utils';
/**
* Responsible for overlay creation and manipulation i.e.
* cutting out the visible part, animating between the sections etc
*/
export default class Overlay {
/**
* @param {Object} options
* @param {Window} window
* @param {Document} document
*/
constructor(options, window, document) {
this.options = options;
this.positionToHighlight = new Position({}); // position at which layover is to be patched at
this.highlightedElement = null; // currently highlighted dom element (instance of Element)
this.lastHighlightedElement = null; // element that was highlighted before current one
this.hideTimer = null;
this.window = window;
this.document = document;
}
/**
* Prepares the overlay
*/
makeNode() {
let pageOverlay = this.document.getElementById(ID_OVERLAY);
if (!pageOverlay) {
pageOverlay = createNodeFromString(OVERLAY_HTML);
document.body.appendChild(pageOverlay);
}
this.node = pageOverlay;
this.node.style.opacity = '0';
if (!this.options.animate) {
this.node.classList.add(CLASS_NO_ANIMATION);
} else {
this.node.classList.remove(CLASS_NO_ANIMATION);
}
}
/**
* Highlights the dom element on the screen
* @param {Element} element
*/
highlight(element) {
if (!element || !element.node) {
console.warn('Invalid element to highlight. Must be an instance of `Element`');
return;
}
// If highlighted element is not changed from last time
if (element.isSame(this.highlightedElement)) {
return;
}
// There might be hide timer from last time
// which might be getting triggered
this.window.clearTimeout(this.hideTimer);
// Trigger the hook for highlight started
element.onHighlightStarted();
// Old element has been deselected
if (this.highlightedElement && !this.highlightedElement.isSame(this.lastHighlightedElement)) {
this.highlightedElement.onDeselected();
}
// get the position of element around which we need to draw
const position = element.getCalculatedPosition();
if (!position.canHighlight()) {
return;
}
this.lastHighlightedElement = this.highlightedElement;
this.highlightedElement = element;
this.positionToHighlight = position;
this.show();
// Element has been highlighted
this.highlightedElement.onHighlighted();
}
show() {
if (this.node && this.node.parentElement) {
return;
}
this.makeNode();
window.setTimeout(() => {
this.node.style.opacity = `${this.options.opacity}`;
this.node.style.position = 'fixed';
this.node.style.left = '0';
this.node.style.top = '0';
this.node.style.bottom = '0';
this.node.style.right = '0';
});
}
hideOverlay() {
this.node.style.opacity = '0';
this.hideTimer = window.setTimeout(() => {
this.node.style.position = 'absolute';
this.node.style.left = '';
this.node.style.top = '';
this.node.style.bottom = '';
this.node.style.right = '';
this.node.parentElement.removeChild(this.node);
}, ANIMATION_DURATION_MS);
}
/**
* Returns the currently selected element
* @returns {null|*}
*/
getHighlightedElement() {
return this.highlightedElement;
}
/**
* Gets the element that was highlighted before current element
* @returns {null|*}
*/
getLastHighlightedElement() {
return this.lastHighlightedElement;
}
/**
* Removes the overlay and cancel any listeners
*/
clear() {
this.positionToHighlight = new Position();
if (this.highlightedElement) {
this.highlightedElement.onDeselected(true);
}
this.highlightedElement = null;
this.lastHighlightedElement = null;
this.hideOverlay();
}
/**
* Refreshes the overlay i.e. sets the size according to current window size
* And moves the highlight around if necessary
*/
refresh() {
// If no highlighted element, cancel the refresh
if (!this.highlightedElement) {
return;
}
// Reposition the stage and show popover
this.highlightedElement.showPopover();
this.highlightedElement.showStage();
}
}
|
import isPlainObject from "./isPlainObject"
import owns from "./owns"
import createDOMBackend from "./createDOMBackend"
import applyTransforms from "./applyTransforms"
import assertValidIdentifier from "./assertValidIdentifier"
import createRenderer from "./createRenderer"
let globalId = 0
export default function sansSel({ name="", backend=null, _renderer=null, _styles=null, _transforms=null }={}) {
if (process.env.NODE_ENV !== "production") {
if (typeof name !== "string") {
throw new Error("The 'name' option should be a string")
}
if (backend !== null && typeof backend !== "function") {
throw new Error("The 'backend' option should be a function")
}
}
const renderer = _renderer || createRenderer(backend || createDOMBackend())
const transformsCache = Object.create(null)
const namespaces = Object.create(null)
const transforms = Object.create(_transforms)
const styles = Object.create(_styles)
function sansSelInstance() {
return renderer(getRules(arguments))
}
sansSelInstance.namespace = namespace
sansSelInstance.addTransform = addTransform
sansSelInstance.addTransforms = multiSetter(addTransform)
sansSelInstance.addRule = addRule
sansSelInstance.addRules = multiSetter(addRule)
function multiSetter(fn) {
return (set) => {
if (process.env.NODE_ENV !== "production") {
if (!set || typeof set !== "object") {
throw new Error("The 'set' argument should be an object")
}
}
for (const name in set) fn(name, set[name])
return sansSelInstance
}
}
function getRulesRec(names, result) {
let i, l
for (i = 0, l = names.length; i < l; i++) {
const name = names[i]
if (name) {
const type = typeof name
if (type === "object" && name) {
if (name._rules) {
getRulesRec(name._rules, result)
}
else if (name.length) {
getRulesRec(name, result)
}
else {
result.push(name)
}
}
else if (type === "string") {
if (!(name in styles)) {
throw new Error(`Unknown style "${name}"`)
}
result.push(styles[name])
}
else {
throw new Error(`Style "${name}" has wrong type`)
}
}
}
return result
}
function getRules() {
return getRulesRec(arguments, [])
}
function namespace(namespaceName) {
if (process.env.NODE_ENV !== "production") {
assertValidIdentifier(namespaceName)
if (typeof namespaceName !== "string") {
throw new Error("The 'name' argument should be a string")
}
}
if (!(namespaceName in namespaces)) {
namespaces[namespaceName] = sansSel({
name: name ? `${name}_${namespaceName}` : namespaceName,
_renderer: renderer,
_transforms: transforms,
_styles: styles,
})
}
return namespaces[namespaceName]
}
function addTransform(name, definition) {
if (process.env.NODE_ENV !== "production") {
if (typeof name !== "string") {
throw new Error("The 'name' argument should be a string")
}
if (!definition || (typeof definition !== "object" && typeof definition !== "function")) {
throw new Error("The 'definition' argument should be an object or a function")
}
if (owns(transforms, name)) {
throw new Error(`The transform ${name} already exists`)
}
}
transforms[name] = definition
return sansSelInstance
}
function addRule(ruleName, declarations) {
if (process.env.NODE_ENV !== "production") {
if (typeof ruleName !== "string") {
throw new Error("The 'name' argument should be a string")
}
assertValidIdentifier(ruleName)
if (!isPlainObject(declarations)) {
throw new Error("The 'declaration' argument should be a plain object")
}
if (owns(styles, ruleName)) {
throw new Error(`A "${ruleName}" style already exists`)
}
}
const directParents =
declarations.inherit ?
Array.isArray(declarations.inherit) ?
declarations.inherit :
[declarations.inherit] :
[]
styles[ruleName] = {
id: globalId,
class: `${name}__${ruleName}`,
parents: getRules(directParents),
declarations: applyTransforms(transforms, declarations, transformsCache),
}
globalId += 1
return sansSelInstance
}
return sansSelInstance
}
|
var TreeNode = require('./tree_node').TreeNode;
// Given a sorted (increasing order) array,
// write an algorithm to create a binary tree with minimal height
function createMinimalBST(array) {
if (array.length === 0) {
return null;
}
var midpoint = array.length >> 1,
middle = array[midpoint],
left = array.slice(0, midpoint),
right = array.slice(midpoint + 1),
node = new TreeNode(middle);
node.left = createMinimalBST(left);
node.right = createMinimalBST(right);
return node;
}
exports.createMinimalBST = createMinimalBST;
|
const { Transform, pipeline } = require("stream");
const fs = require("fs-extra");
const path = require("path");
const vfs = require("vinyl-fs");
const cheerio = require("cheerio");
const html = fs.readFileSync("./jsdoc/classes.list.html", "utf8");
// const style = `<style>
// .pae-container {
// display: inline-block;
// cursor: pointer;
// position: fixed;
// top: 0;
// right: 0;
// }
// </style>`;
const style = fs.readFileSync("./resources/navigation.html", "utf8");
console.log(style);
const $ = cheerio.load(html);
$("body").append(style);
console.log($.html());
|
import g from 'src/App/helpers/plain/provedGet'
import ig from 'src/App/helpers/immutable/provedGet'
import PropTypes from 'src/App/helpers/propTypes'
import ImmutablePropTypes from 'src/App/helpers/propTypes/immutable'
import {assertPropTypes} from 'src/App/helpers/propTypes/check'
const
dataModelProps = process.env.NODE_ENV === 'production' ? null : Object.freeze({
isLoaded: PropTypes.bool,
}),
propsModel = process.env.NODE_ENV === 'production' ? null : PropTypes.shape({
currentSection: PropTypes.nullable(PropTypes.string),
data: PropTypes.oneOfType([
ImmutablePropTypes.recordOf(dataModelProps),
ImmutablePropTypes.shape(dataModelProps),
])
}),
optionalPropsModel = process.env.NODE_ENV === 'production' ? null :
PropTypes.nullable(propsModel)
export default (prevProps, nextProps) => {
if (process.env.NODE_ENV !== 'production') {
assertPropTypes(optionalPropsModel, prevProps, 'areWeSwitchedOnPage', 'prevProps')
assertPropTypes(propsModel, nextProps, 'areWeSwitchedOnPage', 'nextProps')
}
if (
// if we went to new section
(
prevProps !== null &&
g(prevProps, 'currentSection') !== g(nextProps, 'currentSection')
) ||
// if we still on the same section but new data is just loaded
(prevProps === null && ig(g(nextProps, 'data'), 'isLoaded')) ||
(
prevProps !== null &&
!ig(g(prevProps, 'data'), 'isLoaded') &&
ig(g(nextProps, 'data'), 'isLoaded')
)
)
return true
else
return false
}
|
๏ปฟvar booksDb = require("./books-db");
var path = require("path");
var connect = require("connect");
var url = require("url");
var multipartyHandle = require("./../multiparty-handle");
var xml2js = require("xml2js");
var xmlBuilder = new xml2js.Builder({ rootName: "books" });
var parseXml = xml2js.parseString;
var CsvStringifier = require("csv-stringify");
var parseCsv = require("csv-parse");
var fs = require("fs");
var formHtml = fs.readFileSync("./serialization/index.html");
var mimes = {
"json": "application/json",
"xml": "application/xml",
"csv": "application/csv"
};
function createHeader(dataType) {
return {
"Content-Type": mimes[dataType],
"Content-Disposition": "attachment;filename=books." + dataType
};
}
function handleGetRequest(dataType, req, res) {
var query = url.parse(path.basename(decodeURI(req.url)), true).query;
res.writeHead(200, createHeader(dataType));
var books = booksDb.read(query);
switch (dataType) {
case "xml":
res.end(xmlBuilder.buildObject({ book: books }));
break;
case "csv":
var csvStrigifier = CsvStringifier(books, { header: true });
csvStrigifier.pipe(res);
break;
case "json":
default:
res.end(JSON.stringify(books));
break;
}
}
function handleParseResult(res, error, result) {
if (error) {
console.dir(error);
res.writeHead(400);
res.end();
return;
}
var books = result.books && result.books.book || result;
booksDb.create(books);
res.writeHead(200);
res.end();
}
function handlePostRequest(dataType, req, res) {
var handle = new multipartyHandle();
handle.form.on("error", function(error) {
handleParseResult(res, error);
})
.on("close", function() {
var text = handle.files && handle.files[0].getText();
if (!text) {
handleParseResult(res, { message: "Upload error" });
return;
}
switch (dataType) {
case "xml":
parseXml(text, { explicitArray: false }, handleParseResult.bind(null, res));
break;
case "csv":
parseCsv(text, { columns: true }, handleParseResult.bind(null, res));
break;
case "json":
try {
var books = JSON.parse(text);
handleParseResult(res, null, books);
} catch (e) {
handleParseResult(res, e);
}
break;
default:
handleParseResult(res, { message: "Data type " + dataType + " is not supported" });
break;
}
})
.parse(req);
};
function handleRequest(dataType, req, res) {
if (req.method === "GET") handleGetRequest(dataType, req, res);
else if (req.method === "POST") handlePostRequest(dataType, req, res);
}
var app = connect();
var server = app.use("/xml", handleRequest.bind(null, "xml"))
.use("/json", handleRequest.bind(null, "json"))
.use("/csv", handleRequest.bind(null, "csv"))
.use("/", function(req, res) {
res.writeHead(200, { "Content-Type": "text/html" });
res.end(formHtml);
})
.listen(1010, function() {
console.log("Server started on port " + server.address().port);
}); |
import Vue from 'vue'
import Vuex from 'vuex'
import { productsList, productDelete, productAdd, productUpdate } from '../api/products'
import { userLogin, userValidate, userRegister } from '../api/users'
import { contractsList, contractAdd, contractDelete, contractEdit } from '../api/contracts'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
id: localStorage.getItem('id') || '',
token: localStorage.getItem('token') || '',
items: []
},
mutations: {
setToken: (state, token) => {
state.token = token
},
setId: (state, id) => {
state.id = id
},
setItems: (state, items) => {
state.items = items
}
},
actions: {
// Products
getProducts: () => {
return productsList()
},
deleteProduct: (context, data) => {
return productDelete(data.value)
},
addProduct: (context, data) => {
return productAdd(data)
},
editProduct: (context, data) => {
return productUpdate(data)
},
// Contracts
getContracts: (context, data) => {
return contractsList(data.axios)
},
addContract: (context, data) => {
return contractAdd(data.data, data.axios)
},
deleteContract: (context, data) => {
return contractDelete(data.data, data.axios)
},
editContract: (context, data) => {
return contractEdit(data.data, data.axios, data.id)
},
// Validation
login: (context, data) => {
return userLogin(data)
},
validate: (context, data) => {
return userValidate(data)
},
register: (context, data) => {
return userRegister(data)
}
},
getters: {
getToken: state => state.token,
getId: state => state.id,
getItems: state => state.items
}
})
|
var MongoClient = require('mongodb');
var settings = require('../settings');
var request = require('request');
var url = settings.MongoConnectionsString;
var MongoDB = {
OpenConnection: function(req, res, next, onOpen) {
MongoClient.connect(url, function(err, db) {
if(err) res.send('Error connecting to db');
onOpen(db);
});
}
};
module.exports = MongoDB; |
angular.module('sxroApp')
.controller('StackDisassemblyCtrl', ['$scope','StackDisassemblyFactory','StacksFactory','ToastService',
function ( $scope, StackDisassemblyFactory, StacksFactory, ToastService) {
$scope.stackdisassemblydata = {};
/**
*
* @param fetch all the stacks
* @return array
*/
StacksFactory.query(function(data) {
$scope.stacks = data.data;
$scope.AjaxInProgress = false;
}, function(error) {
ToastService.error('Connection interrupted!');
});
}]);
|
let debug = true;
let singlePage = true;
|
export { default } from '@upfluence/ember-upf-utils/resources/country-codes';
|
// @flow
import * as React from "react";
import omit from "lodash/omit";
import { NavigationGroupOrElement } from "./NavigationGroupOrElement.js";
import type { NavigationElementPropsType } from "./NavigationElement.js";
import type { NavigationGroupPropsType } from "./NavigationGroup.js";
type Item = NavigationGroupPropsType | NavigationElementPropsType;
type Props =
{
items: Array<Item>,
showListForm: ( {} ) => void
};
type State =
{
activeEntity: string | null
}
export class Navigation extends React.PureComponent <Props, State>
{
constructor( props: Props )
{
super( props );
this.state =
{
activeEntity: null
};
}
onClickHandler = ( elementProps: NavigationElementPropsType ) =>
{
this.setState( { activeEntity: elementProps.entity } );
this.props.showListForm( omit( elementProps, [ "activeEntity", "onClick" ] ) );
}
render()
{
return (
<nav>
{ this.props.items.map( ( element ) => <NavigationGroupOrElement key={ element.title } activeEntity={ this.state.activeEntity } onClick={ this.onClickHandler } { ...element } /> ) }
</nav>
);
}
} |
๏ปฟangular.module('ngApp.apiUser').controller('ApiController', function (AppSpinner, $scope, SessionService, toaster, ProfileandSettingService, $translate) {
var setModalOptions = function () {
$translate(['Frayte-Error', 'FrayteWarning', 'No_API_Available']).then(function (translations) {
$scope.TitleFrayteWarning = translations.FrayteWarning;
$scope.TitleFrayteError = translations.FrayteError;
$scope.No_API_Available = translations.No_API_Available;
});
};
var getInitial = function () {
ProfileandSettingService.ApiDetail($scope.customerId).then(function (response) {
if (response.data !== null) {
$scope.CustomerApi = response.data;
}
else {
toaster.pop({
type: 'warning',
title: $scope.TitleFrayteWarning,
body: $scope.TextSuccessfullyChangedPassword,
showCloseButton: true
});
}
}, function () {
toaster.pop({
type: 'warning',
title: $scope.TitleFrayteError,
body: $scope.No_API_Available,
showCloseButton: true
});
});
};
function init() {
var userInfo = SessionService.getUser();
$scope.RoleId = userInfo.RoleId;
if ($scope.RoleId === 3) {
$scope.customerId = userInfo.EmployeeId;
getInitial();
}
setModalOptions();
}
init();
}); |
#!/usr/bin/env node
process.title = 'linx'
require('commander')
.version(require('../package').version)
.usage('<command> [options]')
.command('generate', 'generate file from a template')
.parse(process.argv)
require('./linx-generate') |
/**
* Copyright (c) 2013 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
define(['jquery', '../util/ui_util', './table', './timeline', './attr_chart', './map', './wordcloud', './buildCase', './nodeSummary', './clusterManager', '../util/rest', './linkCriteria', './refine', './graph', './searchpanel', './simplesearchpanel', './pagingpanel', './selection', '../util/colors'],
function($, ui_util, table, timeline, attr_chart, map, wordcloud, buildCase, nodeSummary, cluster, rest, linkCriteria, refine, graph, searchpanel, simplesearchpanel, pagingpanel, selection, colors) {
var SIMPLE_SEARCH_WIDTH = 317,
SIMPLE_SEARCH_HEIGHT = 27,
WIDGET_TITLE_HEIGHT = 20,
TRANSITION_TIME = 700,
BORDER_STYLE = '1px solid '+ colors.BORDER_DARK,
getClusterDetails = function(baseUrl, datasetName, clustersetName, clusterId, callback) {
rest.get(baseUrl + 'rest/clusterDetails/' + datasetName + '/' + clustersetName + "/" + clusterId, 'Get cluster details', function(response) {
var entityDetails, j, i = 0,
transformedResponse = {
memberDetails : []
};
for (i; i < response.memberDetails.length; i++) {
entityDetails = {};
for (j = 0; j < response.memberDetails[i].map.entry.length; j++) {
entityDetails[response.memberDetails[i].map.entry[j].key] = response.memberDetails[i].map.entry[j].value;
}
transformedResponse.memberDetails.push(entityDetails);
}
callback(transformedResponse);
});
},
detailsCallback = function(response, callback) {
var entityDetails, j, i = 0,
transformedResponse = { memberDetails : [] };
for (i; i < response.memberDetails.length; i++) {
entityDetails = {};
for (j = 0; j < response.memberDetails[i].map.entry.length; j++) {
entityDetails[response.memberDetails[i].map.entry[j].key] = response.memberDetails[i].map.entry[j].value;
}
transformedResponse.memberDetails.push(entityDetails);
}
callback(transformedResponse);
},
searchTipDetailsCallback = function(graph, widget, callback) {
var entityDetails, j, i, current, nodeId, key,
nodeDetails={},
response = graph.response,
maxNode = {memberDetails: {length: -1}},
transformedResponse, nodeMap = {};
for (var h=0; h<graph.nodes.length;h++) {
nodeMap[graph.nodes[h].id] = {
label: graph.nodes[h].name,
ring: graph.nodes[h].ring
}
}
graph.nodeMap=nodeMap;
for (var k = 0; k<response.memberDetails.entry.length;k++) {
transformedResponse = { memberDetails : [] };
key = response.memberDetails.entry[k].key;
current = [].concat(response.memberDetails.entry[k].value.memberDetails);
for (i = 0; i < current.length; i++) {
entityDetails = {};
for (j = 0; j < current[i].map.entry.length; j++) {
entityDetails[current[i].map.entry[j].key] = current[i].map.entry[j].value;
}
transformedResponse.memberDetails.push(entityDetails);
}
if (transformedResponse.memberDetails.length>maxNode.memberDetails.length && nodeMap[key].ring==0) {
maxNode = transformedResponse;
nodeId = key;
}
nodeDetails[key] = transformedResponse;
nodeDetails[key].label = nodeMap[key].label;
}
widget.nodeDetails = nodeDetails;
if(callback) {
callback(nodeId);
}
},
getPreclusterDetails = function(baseUrl, preclusterType, clusterId, callback) {
rest.get(baseUrl + 'rest/preclusterDetails/' + preclusterType + "/" + clusterId, 'Get precluster details', function(response) {
detailsCallback(response, callback);
});
},
getPreclusterSearchDetails = function(baseUrl, graph, widget, callback) {
var attributeIds = [];
for (var i=0;i<graph.nodes.length;i++) {
attributeIds.push(graph.nodes[i].id);
}
graph.attributeIds = attributeIds;
rest.post(baseUrl + "rest/preclusterDetails/fetchAds/",
'{ids:'+ JSON.stringify(graph.attributeIds) + '}',
"Cluster Search Details",
function (response) {
graph.response=response;
searchTipDetailsCallback(graph, widget, callback);
},
false,
function () {
alert('error fetching ads');
});
},
getAttributeSearchDetails = function(baseUrl, graph, widget, callback) {
var attributeIds = [];
for (var i=0;i<graph.nodes.length;i++) {
attributeIds.push(graph.nodes[i].id);
}
graph.attributeIds = attributeIds;
rest.post(baseUrl + "rest/attributeDetails/fetchAds/",
'{ids:'+ JSON.stringify(graph.attributeIds) + '}',
"Attribute Search Details",
function (response) {
graph.response=response;
searchTipDetailsCallback(graph, widget, callback);
},
false,
function () {
alert('error fetching ads');
});
},
getAttributeDetails = function(baseUrl, attribute, value, callback) {
rest.get(baseUrl + 'rest/attributeDetails/' + attribute + "/" + value, 'Get attribute details', function(response) {
detailsCallback(response, callback);
});
},
getAttributeIdDetails = function(baseUrl, attributeid, callback) {
rest.get(baseUrl + 'rest/attributeDetails/id/' + attributeid, 'Get attribute id details', function(response) {
detailsCallback(response, callback);
});
},
createWidget = function(container, baseUrl) {
var linkWidgetObj = {
searchPanel: null,
graphCanvasContainer: null,
simpleSearchContainer: null,
simpleSearch: null,
movementPanel: {},
mapPanel: {},
wordCloudPanel: {},
attributesPanel: {},
buildCasePanel: {},
nodeSummaryPanel: {},
timeline : null,
wordCloud:null,
attrChart: null,
buildCase: null,
nodeSummary:null,
searchToggleButton:null,
isAdvancedSearchMode:false,
sidePanelWidth:null,
detailsHeight:null,
visitedNodes:[],
nodeDetails:{},
selection:selection.createSelectionManager(),
init: function() {
this.amplifyInit();
this.createGraphCanvas();
this.createSimpleSearchCanvas();
this.pagingPanel = pagingpanel.createWidget(this);
this.initSidePanels();
//start with the Case Builder and Summary panels expanded
/*this.buildCasePanel.collapseDiv.click();
setTimeout(function() {
that.nodeSummaryPanel.collapseDiv.click();
}, 50);*/
},
amplifyInit: function() {
var setPanel = function (panel, amp) {
panel.height = amp.height;
panel.uncollapse = amp.uncollapse;
panel.collapsed = amp.collapsed;
},
movementPanelAmp = amplify.store('movementPanel'),
mapPanelAmp = amplify.store('mapPanel'),
wordCloudPanelAmp = amplify.store('wordCloudPanel'),
attributesPanelAmp = amplify.store('attributesPanel'),
buildCasePanelAmp = amplify.store('buildCasePanel'),
nodeSummaryPanelAmp = amplify.store('nodeSummaryPanel'),
sidePanelWidthAmp = amplify.store('sidePanelWidth'),
detailsHeightAmp = amplify.store('detailsHeight');
movementPanelAmp?setPanel(this.movementPanel,movementPanelAmp):this.movementPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:120,collapsed:true};
mapPanelAmp?setPanel(this.mapPanel,mapPanelAmp):this.mapPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:233,collapsed:true};
wordCloudPanelAmp?setPanel(this.wordCloudPanel,wordCloudPanelAmp):this.wordCloudPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:200,collapsed:true};
attributesPanelAmp?setPanel(this.attributesPanel,attributesPanelAmp):this.attributesPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:300,collapsed:true};
buildCasePanelAmp?setPanel(this.buildCasePanel,buildCasePanelAmp):this.buildCasePanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:316,collapsed:true};
nodeSummaryPanelAmp?setPanel(this.nodeSummaryPanel,nodeSummaryPanelAmp):this.nodeSummaryPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:200,collapsed:true};
this.sidePanelWidth = sidePanelWidthAmp?sidePanelWidthAmp:300;
this.detailsHeight = detailsHeightAmp?detailsHeightAmp:300;
},
initSidePanels: function () {
var that = this,
jqContainer = $(container),
startX = 0, startY = 0,
sidePanels = [
{
panel:this.nodeSummaryPanel,
label:'Summary'
},
{
panel:this.buildCasePanel,
label:'Case Builder'
},
{
panel:this.movementPanel,
label:'Movement'
},
{
panel:this.mapPanel,
label:'Map'
},
{
panel:this.wordCloudPanel,
label:'Word Cloud'
},
{
panel:this.attributesPanel,
label:'Attributes'
}
],
getUpper = function (upperPanelsCount, attr) {
var upper = 0,
i = 0;
for(i;i<upperPanelsCount;i++) {
upper += parseFloat(sidePanels[i].panel.header.css(attr));
}
return upper;
},
makeCollapsible = function(sidePanel) {
sidePanel.collapseDiv = $('<div/>')
.addClass('ui-icon')
.addClass(sidePanel.collapsed?'ui-icon-triangle-1-e':'ui-icon-triangle-1-s')
.css({
position:'relative',
float:'left',
cursor:'pointer',
width:'16px',
height:'16px'
});
sidePanel.label.css({
height:WIDGET_TITLE_HEIGHT+'px',
cursor:'pointer',
position:'relative',
width: 'calc(100% - 17px)',
float:'left',
'padding-top':'1.5px',
'font-weight':'bold',
'white-space': 'nowrap',
color: colors.SIDEPANEL_LABEL,
overflow:'hidden'
});
sidePanel.header.append(sidePanel.collapseDiv);
sidePanel.header.append(sidePanel.label);
sidePanel.header.on('click', function(event) {
var i,
numUncollapsed = 0;
if (sidePanel.collapsed) {
var heightToSteal = 0,
heightTaken = 0,
curHeightTaken;
sidePanel.collapsed = false;
sidePanel.collapseDiv.removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
for (i=0; i<sidePanels.length; i++) {
if (sidePanels[i].panel==sidePanel) continue;
if (!sidePanels[i].panel.collapsed) {
numUncollapsed++;
heightToSteal += sidePanels[i].panel.height;
}
}
if (numUncollapsed>0) {
for (i=0; i<sidePanels.length; i++) {
if (sidePanels[i].panel==sidePanel) continue;
if (!sidePanels[i].panel.collapsed) {
curHeightTaken = sidePanels[i].panel.height/(numUncollapsed+1);
sidePanels[i].panel.height -= curHeightTaken;
heightTaken += curHeightTaken;
}
}
sidePanel.height += heightTaken;
} else {
sidePanel.height = sidePanel.uncollapse;
}
} else {
sidePanel.collapsed = true;
sidePanel.collapseDiv.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
for (i=0; i<sidePanels.length; i++) {
if (sidePanels[i].panel==sidePanel) continue;
if (!sidePanels[i].panel.collapsed) numUncollapsed++;
}
if (numUncollapsed>0) {
for (i=0; i<sidePanels.length; i++) {
if (sidePanels[i].panel==sidePanel) continue;
if (!sidePanels[i].panel.collapsed) sidePanels[i].panel.height += sidePanel.height/numUncollapsed;
}
}
sidePanel.uncollapse = sidePanel.height;
sidePanel.height = WIDGET_TITLE_HEIGHT;
}
that.panelResize();
});
},
createPanel = function(sidePanel) {
sidePanel.panel.header = $('<div/>')
.css({
width:that.sidePanelWidth+'px',
top:sidePanel.top+'px',
position:'absolute'
}).addClass('moduleHeader');
sidePanel.panel.label = $('<div/>')
.css({
position:'absolute',
left:'2px',
top:'1px'
}).text(sidePanel.label);
sidePanel.panel.canvas = $('<div/>')
.css({
position:'absolute',
top:WIDGET_TITLE_HEIGHT+'px',
right:'0px',
'padding-top':'1.5px',
width:that.sidePanelWidth+'px',
height:(sidePanel.height-WIDGET_TITLE_HEIGHT)+'px',
overflow:'hidden',
'border-left': BORDER_STYLE,
cursor: 'default'
});
jqContainer.append(sidePanel.panel.header).append(sidePanel.panel.canvas);
},
makeDraggable = function(upperPanel, sidePanel) {
sidePanel.header.draggable({
axis:'y',
helper: 'clone',
start: function(event, ui) {
if (upperPanel.collapsed||sidePanel.collapsed) return false;
startY = event.clientY;
},
stop: function(event, ui) {
var endY = event.clientY,
delta = endY-startY;
if (sidePanel.height-delta<WIDGET_TITLE_HEIGHT) delta = sidePanel.height-WIDGET_TITLE_HEIGHT;
if (upperPanel.height+delta<WIDGET_TITLE_HEIGHT) delta = WIDGET_TITLE_HEIGHT-upperPanel.height;
sidePanel.height -= delta;
upperPanel.height += delta;
that.panelResize();
}
});
};
//add the side panels
for (var i=0; i<sidePanels.length; i++) {
var panel = sidePanels[i];
panel.top = getUpper(panel,'top');
panel.height = getUpper(panel,'height');
createPanel(panel);
makeCollapsible(sidePanels[i].panel);
if (i>0) {
makeDraggable(sidePanels[i-1].panel,panel.panel);
}
}
//add other elements
this.detailsCanvas = $('<div/>')
.css({
'background':'url(\'img/table.png\')',
'background-position':'center',
'background-repeat':'no-repeat',
'background-size':'100% 100%',
position:'absolute',
height:this.detailsHeight+'px',
right:this.sidePanelWidth+'px',
left:'0px',
bottom:'0px',
overflow:'auto',
'border-top':BORDER_STYLE,
'border-right':BORDER_STYLE,
cursor: 'default'
});
jqContainer.append(this.detailsCanvas);
this.searchToggleButton = $('<div/>')
.button({
text:false,
disabled:true,
icons:{
primary:'ui-icon-triangle-1-e'
},
label:'Advanced controls (disabled)'
})
.css({
position:'absolute',
top:WIDGET_TITLE_HEIGHT+4+'px',
left:'2px',
margin:'0px',
width:'20px',
height:'20px',
display: 'none' //TODO remove
})
.click(function() {
if (that.isAdvancedSearchMode) {
that.onSimpleSearch();
} else {
that.onAdvancedSearch();
}
});
jqContainer.append(this.searchToggleButton);
//resize for side panel
this.resizeBar = $('<div/>')
.css({
position:'absolute',
bottom:'0px',
top:'0px',
width:'3px',
right:this.sidePanelWidth+'px',
background:colors.APPWIDGET_RESIZE_BAR,
cursor:'ew-resize'
})
.draggable({
axis:'x',
cursor: 'ew-resize',
helper: 'clone',
start: function(event, ui) {
startX = event.clientX;
},
stop: function(event, ui) {
var endX = event.clientX,
w = that.sidePanelWidth-(endX-startX);
if (w<10) w = 10;
that.sidePanelWidth = w;
amplify.store('sidePanelWidth', w);
that.panelResize();
}
});
jqContainer.append(this.resizeBar);
//resize for details table
this.detailResizeBar = $('<div/>')
.css({
position:'absolute',
bottom:this.detailsHeight+'px',
height:'3px',
left:'0px',
right:this.sidePanelWidth+'px',
background:colors.APPWIDGET_RESIZE_BAR,
cursor:'ns-resize'
})
.draggable({
axis:'y',
cursor: 'ns-resize',
helper: 'clone',
start: function(event, ui) {
startY = event.clientY;
},
stop: function(event, ui) {
var endY = event.clientY,
h = that.detailsHeight-(endY-startY);
if (h<WIDGET_TITLE_HEIGHT) h = WIDGET_TITLE_HEIGHT;
that.detailsHeight = h;
amplify.store('detailsHeight', h);
that.panelResize();
}
});
jqContainer.append(this.detailResizeBar);
},
onSimpleSearch: function() {
var that = this;
this.graphHeader.animate({left:'0px'}, TRANSITION_TIME/2);
this.graphCanvasContainer.animate({left:'0px'}, TRANSITION_TIME/2, function() {
that.graphCanvasContainer.resize();
});
this.searchToggleButton.animate({left:'2px'}, TRANSITION_TIME/2, function() {
that.searchToggleButton.button({
icons:{
primary:'ui-icon-triangle-1-e'
},
label:'Show advanced controls'
});
});
this.graphPropertiesCanvas.animate({width:'0px'}, TRANSITION_TIME/2, function() {
that.simpleSearchContainer.animate({top:WIDGET_TITLE_HEIGHT+'px', opacity:1}, TRANSITION_TIME/2);
});
this.isAdvancedSearchMode = false;
},
doSimpleSearch: function(searchStr,clusterType) {
var that = this;
this.softClear();
this.graphWidget.displayLoader();
this.pagingPanel.hidePagingControls();
this.graphWidget.simpleGraph(baseUrl, searchStr, clusterType, function(graph) {
that.pagingPanel.setFullGraph(graph, null, null, clusterType);
that.nodeSummaryPanel.canvas.empty();
that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,graph);
var clusterid = that.nodeSummary.centerNode.id;
that.displayDetailsSpinners();
that.graphWidget.markSelectedCluster(clusterid);
getPreclusterDetails(baseUrl, clusterType, clusterid, function(response) {
that.showClusterDetails(response, that.nodeSummary.centerNode.label);
that.nodeDetails[clusterid] = response;
});
}, function() {
alert('Error fetching graph');
that.softClear();
});
},
fetchClusterId: function(clusterid,clusterType) {
var that = this;
this.softClear();
this.graphWidget.displayLoader();
this.pagingPanel.hidePagingControls();
this.graphWidget.fetchClusterId(baseUrl, clusterid, clusterType, function(graph) {
var title = graph.nodes[0].label;
that.pagingPanel.setFullGraph(graph, null, null, clusterType);
that.nodeSummaryPanel.canvas.empty();
that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,graph);
var clusterid = that.nodeSummary.centerNode.id;
that.displayDetailsSpinners();
getPreclusterDetails(baseUrl, clusterType, clusterid, function(response) {
that.showClusterDetails(response, title);
that.nodeDetails[clusterid] = response;
});
that.graphWidget.markSelectedCluster(clusterid);
}, function() {
alert('Error fetching graph');
that.softClear();
});
},
redirect: function(attribute, value, callback) {
var that = this,
$dSpinner = $('#details-spinner');
this.table.mainDiv.css('display','none');
$dSpinner.css('display','');
rest.get(baseUrl + 'rest/attributeDetails/getattrid/'+attribute+'/'+value,
"get Attribute ID",
function (response) {
if(response) {
var caseid;
if (that.buildCase.currentCase && that.buildCase.currentCase.case_id) {
caseid = that.buildCase.currentCase.case_id;
}
window.open(baseUrl + 'graph.html?attributeid=' + response + (caseid ? '&case_id=' + caseid : ''), '_self');
} else {
that.table.mainDiv.css('display','inline');
$dSpinner.css('display','none');
alert('cluster for ' + attribute + ': ' + value + ' could not be found.');
callback(false);
}
},
function () {
alert('error fetching cluster for ' + attribute + ': ' + value);
callback(false);
});
},
fetchAttribute: function(attribute, value) {
var that = this;
this.softClear();
this.graphWidget.displayLoader();
this.pagingPanel.hidePagingControls();
this.graphWidget.fetchAttribute(baseUrl, attribute, value, function(graph) {
that.graphWidget.ATTRIBUTE_MODE = true;
that.graphWidget.createControlsCanvas();
that.pagingPanel.setFullGraph(graph, null, null, "attribute");
that.graphWidget.selectNode(graph.nodes[0].id);
that.displayDetailsSpinners();
getAttributeDetails(baseUrl, attribute, value, function(response) {
that.showClusterDetails(response, graph.nodes[0].label);
});
}, function() {
alert('Error fetching graph');
that.softClear();
});
},
fetchAttributeId: function(attributeid) {
var that = this;
this.softClear();
this.graphWidget.displayLoader();
this.pagingPanel.hidePagingControls();
this.graphWidget.fetchAttributeId(baseUrl, attributeid, function(graph) {
if (graph) {
var title = graph.nodes[0].label;
that.pagingPanel.setFullGraph(graph, null, null, "attribute");
that.nodeSummaryPanel.canvas.empty();
that.nodeSummary = new nodeSummary.createWidget(that, baseUrl, graph);
that.displayDetailsSpinners();
that.visitedNodes.push(attributeid);
getAttributeIdDetails(baseUrl, attributeid, function (response) {
that.showClusterDetails(response, title);
that.nodeDetails[attributeid] = response;
});
that.graphWidget.markSelectedCluster(attributeid);
that.graphWidget.markVisitedNodes(that.visitedNodes);
} else {
alert('Error fetching graph');
that.softClear();
}
}, function() {
alert('Error fetching graph');
that.softClear();
});
},
fetchImageGraph: function(imageid) {
var that = this;
this.softClear();
this.graphWidget.displayLoader();
this.pagingPanel.hidePagingControls();
this.graphWidget.fetchImageId(baseUrl, imageid, function(graph) {
var title = graph.nodes[0].label;
that.pagingPanel.setFullGraph(graph, null, null, 'org');
that.nodeSummaryPanel.canvas.empty();
that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,graph);
that.displayDetailsSpinners();
var clusterid = that.nodeSummary.centerNode.id;
getPreclusterDetails(baseUrl, 'org', clusterid, function(response) {
that.showClusterDetails(response, title);
that.nodeDetails[clusterid] = response;
that.table.filterImage(imageid);
});
that.graphWidget.markSelectedCluster(clusterid);
}, function() {
alert('Error fetching graph');
that.softClear();
});
},
onAdvancedSearch: function() {
var that = this;
this.simpleSearchContainer.animate({top:'-50px', opacity:0}, TRANSITION_TIME/2, function() {
that.graphHeader.animate({left:'300px'}, TRANSITION_TIME/2);
that.graphCanvasContainer.animate({left:'300px'}, TRANSITION_TIME/2, function() {
that.graphCanvasContainer.resize();
});
that.graphPropertiesCanvas.animate({width:'300px'}, TRANSITION_TIME/2);
that.searchToggleButton.animate({left:(300+2)+'px'}, TRANSITION_TIME/2,function(){
that.searchToggleButton.button({
icons:{
primary:'ui-icon-triangle-1-w'
},
label:'Show simple controls'
});
});
});
this.isAdvancedSearchMode = true;
},
createGraphCanvas: function() {
var that = this,
jqContainer = $(container),
$logout = $('<div/>')
.text('Logout')
.button()
.addClass('logoutButton')
.css({
position:'absolute',
top:'1px',
right:'-3.5px',
height:'14px',
padding: '.1em .5em'
})
.on('click',function(event) {
window.location.href = 'OpenAdsLogout.jsp';
});
this.graphHeader = $('<div/>')
.css({
height:WIDGET_TITLE_HEIGHT+'px',
top:'0px',
left:'0px',
right:this.sidePanelWidth,
position:'absolute',
'border-left': BORDER_STYLE,
'border-right': BORDER_STYLE
}).addClass('moduleHeader');
this.graphLabel = $('<div/>')
.css({
position:'absolute',
left:'2px',
top:'1px'
});
this.graphHeader.append(this.graphLabel).append($logout);
jqContainer.append(this.graphHeader);
this.graphCanvasContainer = $('<div/>')
.css({
'background':'url(\'img/graph.png\')',
'background-position':'center',
'background-repeat':'no-repeat',
position:'absolute',
top:WIDGET_TITLE_HEIGHT+'px',
left:'0px',
right:this.sidePanelWidth+'px',
bottom:this.detailsHeight+'px',
'border-left': BORDER_STYLE,
'border-right': BORDER_STYLE,
overflow:'hidden'
});
jqContainer.append(this.graphCanvasContainer);
this.graphWidget = graph.createWidget(this, baseUrl, function(event, datasetName, clustersetName, preclusterType) {
var clusterId = event.data.id;
if (event.eventType === 'dblclick') {
if (datasetName && clustersetName) {
that.displayDetailsSpinners();
getClusterDetails(baseUrl, datasetName, clustersetName, clusterId, function (response) {
that.showClusterDetails(response, clustersetName);
});
} else if (preclusterType) {
if (preclusterType == 'attribute') {
that.fetchAttributeId(clusterId);
} else {
that.fetchClusterId(clusterId, preclusterType);
}
} else if (event.data.fields) {
var html = '';
for (var field in event.data.fields) {
html += '<BR/><B>' + field + ':</B>' + ui_util.escapeHtml(event.data.fields[field]);
}
that.detailsCanvas.html(html);
}
} else if (event.eventType === 'click') {
that.updatePanels(clusterId);
}
});
this.graphLabel.text('Ads grouped by ' + (this.graphWidget.ATTRIBUTE_MODE?'Attribute':'Entity'))
},
updatePanels: function(nodeId) {
var that = this,
update = function () {
that.nodeSummaryPanel.canvas.empty();
that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,that.graphWidget.linkData, nodeId);
if(!that.nodeDetails[nodeId].label) {
that.nodeDetails[nodeId].label = that.graphWidget.linkData.nodeMap[nodeId].label;
}
that.showClusterDetails(that.nodeDetails[nodeId]);
};
this.displayDetailsSpinners();
setTimeout(function() {
if(!that.nodeDetails[nodeId]) {
if(that.graphWidget.ATTRIBUTE_MODE) {
getAttributeIdDetails(baseUrl, nodeId, function(response) {
that.nodeDetails[nodeId] = response;
update();
});
} else {
getPreclusterDetails(baseUrl, 'org', nodeId, function(response) {
that.nodeDetails[nodeId] = response;
update();
});
}
} else {
update();
}
}, 10);
},
createSimpleSearchCanvas: function() {
this.simpleSearchContainer = $('<div/>')
.css({
position:'absolute',
top:WIDGET_TITLE_HEIGHT+'px',
left:'26px',
width:SIMPLE_SEARCH_WIDTH + 'px',
height:SIMPLE_SEARCH_HEIGHT + 'px',
border:'1px solid ' + colors.BORDER_DARK,
overflow:'hidden',
opacity:1,
display: 'none' //TODO remove
});
$(container).append(this.simpleSearchContainer);
this.simpleSearch = simplesearchpanel.createWidget(this.simpleSearchContainer, this, baseUrl);
},
createGraphPropertiesCanvas: function() {
var jqContainer = $(container);
this.graphPropertiesHeader = $('<div/>')
.css({
height:WIDGET_TITLE_HEIGHT+'px',
width:'300px',
top:'0px',
left:'0px',
position:'absolute'
}).addClass('moduleHeader');
this.graphPropertiesLabel = $('<div/>')
.css({
position:'absolute',
left:'2px',
top:'1px'
}).text('Advanced Search');
this.graphPropertiesHeader.append(this.graphPropertiesLabel);
jqContainer.append(this.graphPropertiesHeader);
this.graphPropertiesCanvas = $('<div/>')
.css({
top:WIDGET_TITLE_HEIGHT+'px',
width:'0px',
bottom:this.detailsHeight+'px',
left:'0px',
position:'absolute',
'overflow-y':'auto'
});
jqContainer.append(this.graphPropertiesCanvas);
this.searchPanel = searchpanel.createWidget(this.graphPropertiesCanvas, this, baseUrl);
},
displayLoader: function() {
this.graphWidget.displayLoader();
},
showClusterDetails: function(response, title) {
var headerList = [],
objectData = [],
that = this,
i = 0, fields;
if (!title && response.label) {
title = response.label;
}
for (i; i<response.memberDetails.length; i++) {
fields = response.memberDetails[i];
if (i==0) {
for (var field in fields) {
if (fields.hasOwnProperty(field)) {
headerList.push(field);
}
}
}
fields.locationLabel = fields.location;
objectData.push(fields);
}
//add node link click function
this.graphWidget.selectLinksFn = function(event) {
var i, j, detailsList, found1, found2,
val1 = event.data.source.label,
val2 = event.data.target.label,
attributes = ['phone', 'email', 'websites'],
result = [];
for(i=0;i<objectData.length;i++) {
found1 = found2 = false;
for(j=0;j<attributes.length;j++) {
detailsList = objectData[i][attributes[j]];
if (!found1 && detailsList && detailsList.indexOf(val1) > -1) {
found1 = true;
}
if (!found2 && detailsList && detailsList.indexOf(val2) > -1) {
found2 = true;
}
if (found1 && found2) {
result.push(objectData[i].id);
break;
}
}
}
that.selection.set('graph', result);
};
this.movementPanel.canvas.css('background-image', '');
this.wordCloudPanel.canvas.css('background-image', '');
this.mapPanel.canvas.css('background-image', '');
this.attributesPanel.canvas.css('background-image', '');
this.detailsCanvas.css('background-image', '');
this.detailsCanvas.empty();
if (this.table) {
this.table.destroyTable();
}
this.table = table.createWidget(baseUrl, this.detailsCanvas, headerList, objectData, title, this.selection);
this.table.searchFn = function(attribute, value, callback) {
if (attribute=='images') {
that.fetchImageGraph(value);
} else {
that.redirect(attribute, value, callback);
}
};
if (!this.buildCase) {
var caseId = decodeURIComponent(ui_util.getParameter('case_id'));
this.buildCase = new buildCase.createWidget(this.buildCasePanel.canvas, baseUrl);
if(caseId && caseId!=undefined && caseId!=null && caseId!='null') {
this.buildCase.loadCaseContentsURL(caseId);
}
}
this.buildCase.resize(this.sidePanelWidth, this.buildCasePanel.canvas.height());
this.movementPanel.canvas.empty();
if (this.timeline) {
this.timeline.destroy();
}
this.timeline = new timeline.createWidget(this.movementPanel.canvas.get(0), objectData, this.selection);
this.timeline.resize(this.sidePanelWidth, this.movementPanel.height);
this.mapPanel.canvas.empty();
this.mapObj = new map.createWidget(baseUrl, this.mapPanel.canvas.get(0), objectData, this.selection);
this.mapObj.resize(this.sidePanelWidth, this.mapPanel.height);
this.wordCloudPanel.canvas.empty();
if (this.wordCloud) {
this.wordCloud.destroy();
}
this.wordCloud = new wordcloud.createWidget(baseUrl, this.wordCloudPanel.canvas, objectData, this.selection);
this.wordCloud.resize(this.sidePanelWidth, this.wordCloudPanel.canvas.height());
this.attributesPanel.canvas.empty();
if (this.attrChart) {
this.attrChart.destroy();
}
this.attrChart = new attr_chart.createWidget(this.attributesPanel.canvas, objectData);
this.attrChart.resize(this.sidePanelWidth, this.attributesPanel.canvas.height());
this.selection.listen('table', function(selectedIds) { that.table.selectionChanged(selectedIds);});
this.selection.listen('timeline', function(selectedIds) { that.timeline.selectionChanged(selectedIds);});
this.selection.listen('map', function(selectedIds) { that.mapObj.selectionChange(selectedIds) });
},
panelResize: function() {
var totalHeight = this.nodeSummaryPanel.height + this.buildCasePanel.height + this.movementPanel.height + this.mapPanel.height + this.wordCloudPanel.height + this.attributesPanel.height,
overflow,
delta;
if (totalHeight>this.height && this.nodeSummaryPanel.height>WIDGET_TITLE_HEIGHT) {
overflow = totalHeight-this.height;
delta = Math.min(overflow,this.nodeSummaryPanel.height-WIDGET_TITLE_HEIGHT);
this.nodeSummaryPanel.height -= delta;
totalHeight -= delta;
}
if (totalHeight>this.height && this.buildCasePanel.height>WIDGET_TITLE_HEIGHT) {
overflow = totalHeight-this.height;
delta = Math.min(overflow,this.buildCasePanel.height-WIDGET_TITLE_HEIGHT);
this.buildCasePanel.height -= delta;
totalHeight -= delta;
}
if (totalHeight>this.height && this.wordCloudPanel.height>WIDGET_TITLE_HEIGHT) {
overflow = totalHeight-this.height;
delta = Math.min(overflow,this.wordCloudPanel.height-WIDGET_TITLE_HEIGHT);
this.wordCloudPanel.height -= delta;
totalHeight -= delta;
}
if (totalHeight>this.height && this.attributesPanel.height>WIDGET_TITLE_HEIGHT) {
overflow = totalHeight-this.height;
delta = Math.min(overflow,this.attributesPanel.height-WIDGET_TITLE_HEIGHT);
this.attributesPanel.height -= delta;
totalHeight -= delta;
}
if (totalHeight>this.height && this.mapPanel.height>WIDGET_TITLE_HEIGHT) {
overflow = totalHeight-this.height;
delta = Math.min(overflow,this.mapPanel.height-WIDGET_TITLE_HEIGHT);
this.mapPanel.height -= delta;
totalHeight -= delta;
}
if (totalHeight>this.height && this.movementPanel.height>WIDGET_TITLE_HEIGHT) {
overflow = totalHeight-this.height;
delta = Math.min(overflow,this.movementPanel.height-WIDGET_TITLE_HEIGHT);
this.movementPanel.height -= delta;
totalHeight -= delta;
}
if (totalHeight<this.height && !this.nodeSummaryPanel.collapsed) {
this.nodeSummaryPanel.height += this.height-totalHeight;
totalHeight = this.height;
}
if (totalHeight<this.height && !this.buildCasePanel.collapsed) {
this.buildCasePanel.height += this.height-totalHeight;
totalHeight = this.height;
}
if (totalHeight<this.height && !this.attributesPanel.collapsed) {
this.attributesPanel.height += this.height-totalHeight;
totalHeight = this.height;
}
if (totalHeight<this.height && !this.wordCloudPanel.collapsed) {
this.wordCloudPanel.height += this.height-totalHeight;
totalHeight = this.height;
}
if (totalHeight<this.height && !this.mapPanel.collapsed) {
this.mapPanel.height += this.height-totalHeight;
totalHeight = this.height;
}
if (totalHeight<this.height && !this.movementPanel.collapsed) {
this.movementPanel.height += this.height-totalHeight;
totalHeight = this.height;
}
this.nodeSummaryPanel.header.css({width:this.sidePanelWidth + 'px'});
this.nodeSummaryPanel.canvas.css({width:this.sidePanelWidth + 'px', height:(this.nodeSummaryPanel.height-WIDGET_TITLE_HEIGHT) + 'px'});
this.buildCasePanel.header.css({width:this.sidePanelWidth + 'px', top:this.nodeSummaryPanel.height + 'px'});
this.buildCasePanel.canvas.css({width:this.sidePanelWidth + 'px', top:this.nodeSummaryPanel.height+WIDGET_TITLE_HEIGHT + 'px',height:(this.buildCasePanel.height-WIDGET_TITLE_HEIGHT) + 'px'});
this.movementPanel.header.css({width:this.sidePanelWidth + 'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height + 'px'});
this.movementPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+WIDGET_TITLE_HEIGHT + 'px', height:(this.movementPanel.height-WIDGET_TITLE_HEIGHT) + 'px'});
this.mapPanel.header.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+'px'});
this.mapPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+WIDGET_TITLE_HEIGHT + 'px', height:(this.mapPanel.height-WIDGET_TITLE_HEIGHT)+'px'});
this.wordCloudPanel.header.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height+'px'});
this.wordCloudPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height + WIDGET_TITLE_HEIGHT + 'px', height:(this.wordCloudPanel.height-WIDGET_TITLE_HEIGHT)+'px'});
this.detailsCanvas.css({right:this.sidePanelWidth+'px',height:this.detailsHeight+'px'});
this.attributesPanel.header.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height+this.wordCloudPanel.height+'px'});
this.attributesPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height+this.wordCloudPanel.height+WIDGET_TITLE_HEIGHT+'px', height:(this.attributesPanel.height-WIDGET_TITLE_HEIGHT)+'px'});
this.resizeBar.css({right:this.sidePanelWidth+'px'});
this.detailResizeBar.css({bottom:this.detailsHeight+'px',right:this.sidePanelWidth+'px'});
if(this.table) this.table.updateSelectedOverlay();
if (this.timeline) this.timeline.resize(this.sidePanelWidth, this.movementPanel.canvas.height());
if (this.mapObj) this.mapObj.resize(this.sidePanelWidth, this.mapPanel.canvas.height());
if (this.wordCloud) this.wordCloud.resize(this.sidePanelWidth, this.wordCloudPanel.canvas.height());
if (this.attrChart) this.attrChart.resize(this.sidePanelWidth, this.attributesPanel.canvas.height());
this.graphHeader.css({right:this.sidePanelWidth});
this.graphCanvasContainer.css({right:this.sidePanelWidth+'px',bottom:this.detailsHeight+'px'});
if (this.graphWidget) this.graphWidget.resize(this.width-this.sidePanelWidth, this.graphCanvasContainer.height());
if (this.graphPropertiesCanvas) this.graphPropertiesCanvas.css({bottom:this.detailsHeight+'px'});
this.amplifyUpdate();
},
amplifyUpdate: function() {
var amplifyStore = function (panel, amp) {
var amplifyStore = {
height: panel.height,
uncollapse: panel.uncollapse,
collapsed: panel.collapsed
};
amplify.store(amp, amplifyStore);
};
amplifyStore(this.nodeSummaryPanel, 'nodeSummaryPanel');
amplifyStore(this.buildCasePanel, 'buildCasePanel');
amplifyStore(this.movementPanel, 'movementPanel');
amplifyStore(this.mapPanel, 'mapPanel');
amplifyStore(this.wordCloudPanel,'wordCloudPanel');
amplifyStore(this.attributesPanel,'attributesPanel');
},
resize: function(w,h) {
this.width = w;
this.height = h;
this.panelResize();
if (this.graphWidget) {
this.graphWidget.resize(w,h);
}
},
displayDetailsSpinners: function() {
this.movementPanel.canvas.empty();
this.wordCloudPanel.canvas.empty();
this.mapPanel.canvas.empty();
this.attributesPanel.canvas.empty();
this.detailsCanvas.empty();
this.movementPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'});
this.wordCloudPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'});
this.mapPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'});
this.attributesPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'});
this.detailsCanvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'});
},
softClear : function() {
this.graphWidget.empty();
this.movementPanel.canvas.empty();
this.mapPanel.canvas.empty();
this.attributesPanel.canvas.empty();
this.detailsCanvas.empty();
this.graphCanvasContainer.css('background-image', '');
this.movementPanel.canvas.css('background-image', '');
this.wordCloudPanel.canvas.css('background-image', '');
this.mapPanel.canvas.css('background-image', '');
this.attributesPanel.canvas.css('background-image', '');
this.detailsCanvas.css('background-image', '');
//this.movementPanel.canvas.append(this.movementPanel.description);
this.selection.clear();
}
};
linkWidgetObj.init();
return linkWidgetObj;
};
return {
createWidget:createWidget
}
});
|
<script>
let power = 4,
state = {
w: 520,
maxWidth:520,
h: 260,
origin: [270, 130],
background: [0,61,93],
renderer: 'svg',
ppm: 300,
items: [
// real lens and fake one
{
type: 'thinlens',
id: 'L#1',
power: 3,
aperture: 0.5,
axis: [1,0],
position: [0,0.001],
ui: { xlock: true, ylock: true},
style: {
strokeWeight: 3
}
},
// a ray
{
type: 'divergent light',
position: [-0.6,0.3],
id: 'rule3',
off: false,
target: [0,0],
spread: 0,
raycount: 1,
ui: {xlock:[-Infinity, -1/power]},
style: {
stroke: [220,220,0],
strokeWeight: 2,
arrows: ['50%','']
}
},
// object & image
{
type: 'js',
init(state) {
let p = findObject(state, 'rule3').position
findObject(state,'object').start = [p[0],0]
findObject(state,'object').end = [...p]
let img = 1/(1/p[0]+power)
findObject(state,'image').start = [img,0]
findObject(state,'image').end = [img, p[1]*img/p[0]]
findObject(state, 'end').position = [img,-5,img,5]
}
},
{
type: 'barrier',
id: 'end',
position: [1,-5, 1, 5],
style: {
visible:false
}
},
{
type: 'dimension',
id: 'object',
start: [],
end: [],
label: ' ',
style: {
stroke: [255, 255, 255],
strokeWeight: 5,
arrowLength: 10,
arrowWidth: 5,
z_order:-1
}
},
{
type: 'dimension',
id: 'image',
start: [],
end: [],
label: ' ',
style: {
stroke: [200, 200, 255],
strokeWeight: 5,
arrowLength: 10,
arrowWidth: 5,
z_order:-1,
visible: true
}
},
// optic axis
{
type: 'dimension',
start: [-2,0],
end: [2,0],
label: ' ',
style: {
stroke: [255, 255, 255],
strokeDash: [5,5]
}
},
]
};
makeP5App(state)(window)
</script> |
const restify = require('restify-plugins');
var client = restify.createJsonClient({
url : 'http://localhost:3000'
});
client.post('/foo', {bar : 'bar'}, function (err, req, res, obj) {
if(err){
console.log(err.message);
}
}); |
// Learn more about this file at:
// https://victorzhou.com/blog/build-an-io-game-part-1/#5-client-rendering
import { debounce } from 'throttle-debounce';
import { getAsset } from './assets';
import { getCurrentState } from './state';
import { getCurrentInput } from './input';
const Constants = require('../shared/constants');
const { PLAYER_RADIUS, PLAYER_MAX_HP, BULLET_RADIUS, MAP_SIZE } = Constants;
const BULLET_TRAIL = {}
// Get the canvas graphics context
const canvas = document.getElementById('game-canvas');
const context = canvas.getContext('2d');
setCanvasDimensions();
function setCanvasDimensions() {
// On small screens (e.g. phones), we want to "zoom out" so players can still see at least
// 800 in-game units of width.
const scaleRatio = Math.max(1, 800 / window.innerWidth);
canvas.width = scaleRatio * window.innerWidth;
canvas.height = scaleRatio * window.innerHeight;
}
window.addEventListener('resize', debounce(40, setCanvasDimensions));
function render() {
const { me, others, bullets } = getCurrentState();
if (!me) {
return;
}
// Draw background
renderBackground(me.x, me.y);
// Draw boundaries
context.strokeStyle = '#535353';
context.shadowColor = '#3A3A3A';
context.shadowBlur = 15;
context.lineWidth = 4;
context.strokeRect(canvas.width / 2 - me.x, canvas.height / 2 - me.y, MAP_SIZE, MAP_SIZE);
// Draw all bullets
bullets.forEach(renderBullet.bind(null, me));
const bulletIds = bullets.map(b => b.id);
const keysToDelete = []
for (let key in Object.keys(BULLET_TRAIL)) {
if (!bulletIds.includes(key)) {
keysToDelete.push(key);
}
}
for (let key of keysToDelete) {
delete BULLET_TRAIL[key];
}
// Draw all players
renderPlayer(me, me);
others.forEach(otherPlayer => renderOtherPlayer(me, otherPlayer));
}
function renderBackground(x, y) {
// const imagebg = new Image();
// imagebg.src = backgroundImage;
// const bgimagepattern = context.createPattern(imagebg, 'repeat');
const backgroundX = MAP_SIZE / 2 - x + canvas.width / 2;
const backgroundY = MAP_SIZE / 2 - y + canvas.height / 2;
const backgroundGradient = context.createRadialGradient(
backgroundX,
backgroundY,
MAP_SIZE / 10,
backgroundX,
backgroundY,
MAP_SIZE / 2,
);
backgroundGradient.addColorStop(0, '#333');
backgroundGradient.addColorStop(1, '#000');
context.fillStyle = backgroundGradient;
context.fillRect(0, 0, canvas.width, canvas.height);
}
const CURRENT_PLAYER = {}
// Renders a ship at the given coordinates
function renderPlayer(me, player) {
const { id, x, y, direction } = player;
const canvasX = canvas.width / 2 + x - me.x;
const canvasY = canvas.height / 2 + y - me.y;
const striperID = hasNaNAtEnd(id) ? id.slice(0, id.length - 3) : id;
if (!CURRENT_PLAYER[striperID]) {
CURRENT_PLAYER[striperID] = [{x: x, y:y, mex: me.x, mey: me.y}]
}else {
if (CURRENT_PLAYER[striperID].length > 20) {
CURRENT_PLAYER[striperID].shift();
}
CURRENT_PLAYER[striperID].push({x:x, y:y, mex: me.x, mey: me.y})
}
const numPrevPlayerTrail = CURRENT_PLAYER[striperID].length;
const opacityIncrease = 1 / numPrevPlayerTrail;
let count = 0;
for (let obj of CURRENT_PLAYER[striperID]) {
if (count > 8) {
count += 1;
continue;
}
const {x, y, mex, mey} = obj;
context.beginPath();
context.arc(canvas.width / 2 + x - me.x,canvas.height / 2 + y - me.y , 10, 0, 2 * Math.PI, true);
const opacity = opacityIncrease * count;
const styleString = "rgba(137, 196, 244, " + opacity.toString() + ")"
context.fillStyle = styleString;
context.fill();
count += 1;
}
// Draw ship
context.save();
context.translate(canvasX, canvasY);
context.rotate(direction);
context.drawImage(
getAsset('ship3.svg'),
-PLAYER_RADIUS,
-PLAYER_RADIUS,
PLAYER_RADIUS * 2,
PLAYER_RADIUS * 2,
);
context.restore();
// Draw health bar
context.fillStyle = 'white';
context.fillRect(
canvasX - PLAYER_RADIUS,
canvasY + PLAYER_RADIUS + 8,
PLAYER_RADIUS * 2,
2,
);
context.fillStyle = 'red';
context.fillRect(
canvasX - PLAYER_RADIUS + PLAYER_RADIUS * 2 * player.hp / PLAYER_MAX_HP,
canvasY + PLAYER_RADIUS + 8,
PLAYER_RADIUS * 2 * (1 - player.hp / PLAYER_MAX_HP),
2,
);
// Draw input field
context.font = '18px DM Sans';
context.fillStyle = 'white';
context.textAlign = 'center';
const input = getCurrentInput() === '' ? 'Type an answer + enter' : getCurrentInput();
context.fillText(input, canvasX, canvasY + 56);
}
function hasNaNAtEnd(string) {
const last3Char = string.slice(string.length - 3);
return last3Char === 'NaN';
}
const OTHER_PLAYERS = {}
// Renders a ship at the given coordinates
function renderOtherPlayer(me, player) {
const { x, y, direction, id } = player;
let user = null;
const striperID = hasNaNAtEnd(id) ? id.slice(0, id.length - 3) : id;
const otherPlayer = window.players[striperID];
if (otherPlayer || user) {
user = otherPlayer;
}
const canvasX = canvas.width / 2 + x - me.x;
const canvasY = canvas.height / 2 + y - me.y;
if (!OTHER_PLAYERS[striperID]) {
OTHER_PLAYERS[striperID] = [{x: x, y:y, mex: me.x, mey: me.y}]
}else {
if (OTHER_PLAYERS[striperID].length > 12) {
OTHER_PLAYERS[striperID].shift();
}
OTHER_PLAYERS[striperID].push({x:x, y:y, mex: me.x, mey: me.y})
}
const numPrevPlayerTrail = OTHER_PLAYERS[striperID].length;
const opacityIncrease = 1 / numPrevPlayerTrail;
let count = 0;
for (let obj of OTHER_PLAYERS[striperID]) {
const {x, y, mex, mey} = obj;
context.beginPath();
context.arc(canvas.width / 2 + x - me.x,canvas.height / 2 + y - me.y , 10, 0, 2 * Math.PI, true);
const opacity = opacityIncrease * count;
const styleString = "rgba(255, 69, 0, " + opacity.toString() + ")"
context.fillStyle = styleString;
context.fill();
count += 1;
}
// Draw ship
context.save();
context.translate(canvasX, canvasY);
context.rotate(direction);
context.drawImage(
getAsset('ship2.svg'),
-PLAYER_RADIUS,
-PLAYER_RADIUS,
PLAYER_RADIUS * 2,
PLAYER_RADIUS * 2,
);
context.restore();
// Draw health bar
context.fillStyle = 'white';
context.fillRect(
canvasX - PLAYER_RADIUS,
canvasY + PLAYER_RADIUS + 8,
PLAYER_RADIUS * 2,
2,
);
context.fillStyle = 'red';
context.fillRect(
canvasX - PLAYER_RADIUS + PLAYER_RADIUS * 2 * player.hp / PLAYER_MAX_HP,
canvasY + PLAYER_RADIUS + 8,
PLAYER_RADIUS * 2 * (1 - player.hp / PLAYER_MAX_HP),
2,
);
// setup font
context.font = '26px DM Sans';
context.fillStyle = 'white';
context.textAlign = 'center';
// draw math question
context.fillText(user.mathQuestion.mathString, canvasX, canvasY - 40);
context.font = '14px DM Sans';
// draw draw username
context.fillText(user.username, canvasX, canvasY + 48);
}
function renderBullet(me, bullet) {
const { id, x, y } = bullet;
const striperID = hasNaNAtEnd(id) ? id.slice(0, id.length - 3) : id;
if (!BULLET_TRAIL[striperID]) {
BULLET_TRAIL[striperID] = [{x: x, y:y, mex: me.x, mey: me.y}]
}else {
if (BULLET_TRAIL[striperID].length > 3) {
BULLET_TRAIL[striperID].shift();
}
BULLET_TRAIL[striperID].push({x:x, y:y, mex: me.x, mey: me.y})
}
const numPrevBullets = BULLET_TRAIL[striperID].length;
const opacityIncrease = 1 / numPrevBullets;
let count = 0;
for (let obj of BULLET_TRAIL[striperID]) {
const {x, y, mex, mey} = obj;
context.beginPath();
context.arc(canvas.width / 2 + x - me.x - BULLET_RADIUS,canvas.height / 2 + y - me.y - BULLET_RADIUS, 10, 0, 2 * Math.PI, true);
const opacity = opacityIncrease * count;
const styleString = "rgba(98, 54, 255, " + opacity.toString() + ")"
context.fillStyle = styleString;
context.fill();
count += 1;
}
context.drawImage(
getAsset('bullet.svg'),
canvas.width / 2 + x - me.x - BULLET_RADIUS,
canvas.height / 2 + y - me.y - BULLET_RADIUS,
BULLET_RADIUS * 2,
BULLET_RADIUS * 2,
);
}
function renderMainMenu() {
const t = Date.now() / 7500;
const x = MAP_SIZE / 2 + 800 * Math.cos(t);
const y = MAP_SIZE / 2 + 800 * Math.sin(t);
renderBackground(x, y);
}
let renderInterval = setInterval(renderMainMenu, 1000 / 60);
// Replaces main menu rendering with game rendering.
export function startRendering() {
clearInterval(renderInterval);
renderInterval = setInterval(render, 1000 / 60);
}
// Replaces game rendering with main menu rendering.
export function stopRendering() {
clearInterval(renderInterval);
renderInterval = setInterval(renderMainMenu, 1000 / 60);
}
|
import React, {Component, PropTypes} from 'react';
import ListItem from 'material-ui/lib/lists/list-item';
class Channel extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
selected: PropTypes.bool.isRequired,
onClick: PropTypes.func.isRequired
}
render() {
const style = {};
if (this.props.selected) {
style.backgroundColor = '#f0f0f0';
}
return (
<ListItem primaryText={this.props.name} style={style} onClick={this.props.onClick} />
);
}
}
export default Channel;
|
import React, { useState, useEffect } from "react";
import { Typography } from "@material-ui/core";
import { IconButton } from "@material-ui/core";
import Input from "../../common/Input/Input";
import ExpansionPanel from "@material-ui/core/ExpansionPanel";
import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary";
import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails";
import Fab from "@material-ui/core/Fab";
import AddIcon from "@material-ui/icons/Add";
import DeleteIcon from "@material-ui/icons/Delete";
import CloudUploadIcon from '@material-ui/icons/CloudUpload';
import Button from '@material-ui/core/Button';
import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';
import DialogTitle from '@material-ui/core/DialogTitle';
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import moment from 'moment';
import CloseIcon from '@material-ui/icons/Close';
import FormUtils from "../../utils/formUtils";
import utils from "../../utils/utils";
import useStyles from "./BookingFormStyle";
import "./BookingForm.scss";
import ratemasterService from "../../services/ratemasterService";
import Loader from "../../common/Loader/Loader";
import taxService from "../../services/taxService";
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import GuestNameDialog from './GuestNameDialog'
const BookingForm = props => {
const classes = useStyles();
let [expanded] = React.useState("panel1");
const {
onFormSubmit,
onInputChange: inputfun,
onDatePickerChange: datefun,
onSelectChange: selectfun,
onSelectChange1: selectfun1,
onAddRoom,
onDeleteRoom,
availableRooms,
data,
errors,
options,
options1,
onFileSelect,
onBack,
shouldDisable,
openDatePickerCheckIn,
openDatePickerCheckOut,
handleDatePicker,
enableFileUpload,
onSetPrice,
handleFlatRateChange,
updatedata,
onCheckIn,
setData,
isDirtyroomSelected,
isEdit,
onHandleAdditionalGuest,
additionalGuests
} = props;
console.log("errorsshouldDisable", errors, shouldDisable)
const [loading, setLoading] = React.useState(false);
const [openPriceModal, setOpenPriceModal] = React.useState(false)
const [dayWiseRates, setDayWiseRates] = React.useState([])
const [formattedRates, setFormattedRates] = React.useState({})
const [planTypes, setPlanTypes] = React.useState([
{ planType: "AP" },
{ planType: "CP" },
{ planType: "EP" },
{ planType: "MAP" },
]);
const proofTypes = [
{ label: "Passport", value: "Passport" }
]
const [taxSlabs, setTaxSlabs] = React.useState([]);
// const roomOptions = availableRooms.map(room => {
// return { label: room.roomNumber, value: room.roomNumber };
// });
// data.rooms.map(roomId =>
// availableRooms.filter(room => {
// if (room._id === roomId) selectedRooms.push(room);
// return room;
// })
// );
React.useEffect(() => {
fetchTaxes()
}, [])
React.useEffect(() => {
if (data["checkIn"] > data["checkOut"]) {
return
}
fetchRates()
}, [data["checkIn"], data["checkOut"]])
React.useEffect(() => {
formatRates()
}, [dayWiseRates, data.planType, data.flatRoomRate, data.roomCharges])
React.useEffect(() => {
calculateBookingPrice(formattedRates, data.rooms)
}, [data.rooms])
const fetchTaxes = async () => {
setLoading(true)
const taxSlabs = await taxService.getTaxSlabs("GST");
setTaxSlabs(taxSlabs);
setLoading(false);
};
const fetchRates = async () => {
if (!data["checkIn"] || !data["checkOut"])
return
setLoading(true);
const dayRates = await ratemasterService.getDayWiseRate(data["checkIn"], data["checkOut"]);
if (dayRates) {
setDayWiseRates(dayRates)
}
console.log("----------------dayRates", dayRates)
setLoading(false);
}
const formatRates = () => {
const rates = {}
dayWiseRates.forEach(el => {
if (el.planType === data.planType && !rates[el.roomType]) {
rates[el.roomType] = []
rates[el.roomType].push(el)
} else if (el.planType === data.planType && rates[el.roomType]) {
rates[el.roomType].push(el)
}
})
// .sort((a,b) => moment(a.date).isBefore(b.date))
Object.keys(rates).forEach(el => {
// debugger
let arr = rates[el]
rates[el] = arr.sort((a, b) => {
if (a.date > b.date) {
return 1;
}
return -1;
})
})
// console.log
setFormattedRates(rates)
calculateBookingPrice(rates, data.rooms)
}
const calculateBookingPrice = (rates, rooms) => {
console.log("--------shouldDisable", shouldDisable, data.roomCharges)
// debugger
if (shouldDisable)
return
let price = data.flatRoomRate ? data.roomCharges : 0
console.log("rates, rooms", rates, rooms)
const roomWiseRatesForBooking = []
let dates = data.flatRoomRate && daysBetweenDates(data.checkIn, data.checkOut)
let nights = dates.length > 0 ? dates.length : 1
let divi = data.flatRoomRate && Number(nights) * Number(rooms.length)
// console.log("data.roomCharges/divi",data.roomCharges/divi,data.roomCharges,divi)
let singleRooomSingleNightRateT = data.flatRoomRate && data.roomCharges / divi;
console.log("singleRooomSingleNightRateT", dates, singleRooomSingleNightRateT)
rooms.forEach(room => {
const bookingRate = {
roomNumber: room.roomNumber,
}
const bookingRates = []
if (!data.flatRoomRate) {
rates[room.roomType] && rates[room.roomType].forEach(dayrate => {
// debugger
price += parseInt(dayrate.rate)
const slab = taxSlabs.filter(el => dayrate.rate > el.greaterThan && dayrate.rate <= (el.lessThanAndEqual || 9999999999))
let taxPercent;
let tax;
if (slab.length > 0) {
taxPercent = slab[0].taxPercent
tax = dayrate.rate * (slab[0].taxPercent / 100)
}
bookingRates.push({
date: dayrate.date,
rate: dayrate.rate,
extra: dayrate.extraRate,
taxPercent,
tax: Number(tax).toFixed(2)
})
})
} else {
let singleRooomSingleNightRate;
const slab = taxSlabs.filter(el => Number(singleRooomSingleNightRateT) > Number(el.greaterThan) && Number(singleRooomSingleNightRateT) <= (Number(el.lessThanAndEqual) || 9999999999))
let taxPercent;
let tax;
if (slab.length > 0) {
console.log("slab Price", slab)
taxPercent = slab[0].taxPercent
singleRooomSingleNightRate = (Number(singleRooomSingleNightRateT) / ((100 + Number(taxPercent)) / 100)).toFixed(2)
// console.log("singleRooomSingleNightRate Price",singleRooomSingleNightRate)
// const slab2 = taxSlabs.filter(el => singleRooomSingleNightRate>el.greaterThan && singleRooomSingleNightRate<= (el.lessThanAndEqual || 9999999999))
// if(Number(slab2[0].taxPercent) !== Number(taxPercent)){
// console.log("slab2 Price",slab2)
// taxPercent = slab2[0].taxPercent
// singleRooomSingleNightRate = (Number(singleRooomSingleNightRateT)/((100+Number(taxPercent))/100)).toFixed(2)
// console.log("singleRooomSingleNightRate2 Price",singleRooomSingleNightRate)
// }
tax = (singleRooomSingleNightRate * (taxPercent / 100)).toFixed(2)
}
dates.forEach(el => {
bookingRates.push({
date: el.toISOString(),
rate: Number(singleRooomSingleNightRate).toFixed(2),
extra: 0,
taxPercent,
tax: Number(tax).toFixed(2)
})
})
}
bookingRate.rates = bookingRates
roomWiseRatesForBooking.push(bookingRate)
})
console.log("Final Price", price, roomWiseRatesForBooking)
onSetPrice(price, roomWiseRatesForBooking)
};
const daysBetweenDates = (startDate, endDate) => {
let dates = [];
const currDate = moment(startDate).startOf("day");
//console.log(currDate)
const lastDate = moment(endDate).startOf("day");
//console.log("lastDate",currDate,lastDate)
while (currDate.add(1, "days").diff(lastDate) < 0) {
dates.push(currDate.clone().toDate());
}
dates.unshift(moment(startDate).toDate());
// dates.push(moment(endDate).toDate());
console.log(dates)
return dates;
}
const handleChange = panel => (event, isExpanded) => {
// setExpanded(isExpanded ? panel : false);
};
const getInputArgObj = (id, label, type, shouldDisable) => {
return {
id,
label,
type,
value: data[id],
onChange: inputfun,
error: errors[id],
disabled: shouldDisable,
};
};
const getDateArgObj = (id, label, type, minDate, shouldDisable, open) => {
return {
id,
label,
type,
value: data[id],
onChange: datefun,
error: errors[id],
minDate,
disabled: shouldDisable,
// open: open
};
};
const getRoomOptions = roomType => {
// if (availableRooms.length === 0) return [];
const roomsByType = availableRooms.filter(
room => room.roomType === roomType
);
return roomsByType.map(room => {
return { label: room.roomNumber, value: room.roomNumber, room };
});
};
const getPlanOptions = () => {
return planTypes.map(plan => {
return { label: plan.planType, value: plan.planType };
});
};
const getRoomTypeOptions = (roomtypes) => {
return roomtypes.map(room => {
return { label: room.roomType, value: room.roomType, key: room.roomType };
});
};
const checkRoomError = index => {
if (errors.rooms && errors.rooms.length > 0) {
const err = errors.rooms.find(error => error.index === index);
return err ? err.message : null;
}
return null;
};
console.log("*******formattedRates", formattedRates)
//Type
useEffect(() => {
if (data.bookedBy === "Agent") {
setIsAgent(true);
setIsMember(false);
console.log("Hello Agent")
}
else if (data.bookedBy === 'Head Office') {
setisHeadOffice(true)
setIsAgent(false)
setIsMember(false);
console.log("Hello member")
}
else if (data.bookedBy === "Member") {
setIsMember(true)
setIsAgent(false)
setisHeadOffice(false)
console.log("Hello member")
}
else {
setIsAgent(false)
setIsMember(false)
setisHeadOffice(false)
}
}, [data.bookedBy])
//Adding BookedOptions
const [bookedBy, setBookedBy] = useState("")
const [agent, setAgent] = useState("")
const [nationality, setNationality] = useState("")
const [memberShipNumber, setMembershipNumber] = useState()
const [isAgent, setIsAgent] = useState(false);
const [isMember, setIsMember] = useState(false);
const [isHeadOffice, setisHeadOffice] = useState(false);
const bookedByOptions = [
{ label: "Walk In", value: "Walk In" },
{ label: "Agent", value: "Agent" },
{ label: "Member", value: "Member" },
{ label: "Head Office", value: "Head Office" },
]
const agentOption = [
{ label: "Make my Trip", value: "Make my Trip" },
{ label: "Gobibo", value: "Gobibo" },
{ label: "Sitram Travel Agent", value: "Sitram Travel Agent" },
{ label: "Local Agent", value: "Local Agent" },
]
//Adding Nationality
const nationalityOptions = [
{ label: "Indian", value: "Indian" }
, { label: "British", value: "British" }
, { label: "American", value: "American" }
, { label: "Australian", value: "Australian" }
, { label: "Japan", value: "Japan" }
, { label: "Saudi Arab", value: "Saudi Arab" }
, { label: "UAE", value: "UAE" }
, { label: "Africa", value: "Africa" },
, { label: "French", value: "French" }
]
console.log(memberShipNumber)
//BookedByType
const selectBookedByOption = (event) => {
// setBookedBy(event.target.value);
updatedata({
bookedBy: event.target.value
})
}
const selectAgentOption = (event) => {
setAgent(event.target.value);
updatedata({
agent: event.target.value
})
}
const selectNationalityOption = (event) => {
setNationality(event.target.value);
updatedata({
nationality: event.target.value
})
}
// console.log("TESTTING",isEdit)
//Guest Name Add
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const onHandleGuest = (guests) => {
setOpen(false);
onHandleAdditionalGuest(guests)
};
return (
<React.Fragment>
<GuestNameDialog open={open} onClose={handleClose} shouldDisable={shouldDisable} onHandleGuest={onHandleGuest} additionalGuests={additionalGuests}/>
<form onSubmit={event => onFormSubmit(event)} style={{ marginBottom: "2rem" }}>
{loading && <Loader color="#0088bc" />}
<div className="form-group">
{FormUtils.renderInput(
getInputArgObj("firstName", "First Name", "text", shouldDisable)
)}
{FormUtils.renderInput(
getInputArgObj("lastName", "Last Name", "text", shouldDisable)
)}
<IconButton>
<Fab
size="small"
color="primary"
aria-label="add"
onClick={handleClickOpen}
disabled={shouldDisable}
>
<AddIcon />
</Fab>
</IconButton>
{FormUtils.renderInput(
getInputArgObj(
"contactNumber",
"Contact Number",
"number",
shouldDisable
)
)}
</div>
<div className="form-group">
{FormUtils.renderAddressInput(
getInputArgObj("address", "Address", "text", shouldDisable)
)}
{FormUtils.renderNationality({
id: "nationality",
label: "Nationality",
name: "nationality",
value: data.nationality,
onChange: event => selectNationalityOption(event),
nationalityOptions,
disabled: shouldDisable
})}
</div>
<div className="form-group">
<div
className={classes.datePicker}
onClick={() => handleDatePicker("checkIn")}
>
{FormUtils.renderDatepicker(
getDateArgObj(
"checkIn",
"Check In",
"text",
utils.getDate(),
shouldDisable,
// openDatePickerCheckIn
)
)}
</div>
<div
className={classes.datePicker}
onClick={() => handleDatePicker("checkOut")}
>
{FormUtils.renderDatepicker(
getDateArgObj(
"checkOut",
"Check Out",
"text",
utils.getDate(),
shouldDisable,
// openDatePickerCheckOut
)
)}
</div>
{FormUtils.renderInput(
getInputArgObj("nights", "Nights Stay", "number", true)
)}
{FormUtils.renderInput(
getInputArgObj("adults", "Adults", "number", shouldDisable)
)}
{FormUtils.renderInput(
getInputArgObj("children", "Children", "number", shouldDisable)
)}
</div>
<div className="form-group" style={{ position: "relative" }}>
{FormUtils.renderSelect({
id: "planType",
label: "Plan Type",
name: "planType",
value: data.planType,
onChange: event => selectfun1(event),
options: getPlanOptions(),
disabled: shouldDisable
})}
<FormControlLabel
control={
<Checkbox
checked={data.flatRoomRate}
onChange={handleFlatRateChange}
name="flatRoomRate"
color="primary"
disabled={shouldDisable}
/>
}
label="Flat Rate"
style={{ minWidth: "max-content", marginLeft: "0.3rem" }}
/>
{FormUtils.renderInput(
getInputArgObj("roomCharges", "Total Room Charge", "number", shouldDisable || !data.flatRoomRate)
)}
<IconButton color="primary" aria-label="Price breakup" style={{ position: "absolute", left: "65%", top: "20px" }} onClick={() => setOpenPriceModal(true)}>
<InfoOutlinedIcon />
</IconButton>
{FormUtils.renderInput(
getInputArgObj("advance", "Advance", "number", shouldDisable)
)}
</div>
<div className="form-group">
{FormUtils.renderBookedBy({
id: "bookedBy",
name: "bookedBy",
label: "Booked By",
value: data.bookedBy,
onChange: event => selectfun1(event),
bookedByOptions,
disabled: shouldDisable,
error: errors["bookedBy"]
})}
{isAgent && FormUtils.renderAgent({
id: "agent",
name: "agent",
label: "Select Agent",
value: data.agent,
onChange: event => selectfun1(event),
agentOption,
disabled: shouldDisable,
error: errors["agent"]
})}
{isAgent && FormUtils.renderInput(
getInputArgObj("referencenumber", "Reference number", "string", shouldDisable)
)}
{isHeadOffice && FormUtils.renderInput(
getInputArgObj("referencenumber", "Reference number", "string", shouldDisable)
)}
{
isMember && FormUtils.renderInput({
id: "memberNumber",
label: "Membership Number",
type: "string",
value: data.memberNumber,
onChange: (e) => selectfun1(e),
error: errors["memberNumber"],
disabled: shouldDisable,
}
)
}
</div>
<div className="form-group">
{data.nationality === "Indian" && FormUtils.renderproof1({
id: "proofs",
name: "proofs",
label: "Proof Type",
value: data.proofs,
onChange: event => selectfun1(event),
options1,
disabled: shouldDisable,
error: errors["proofs"]
})}
{data.nationality !== "Indian" && FormUtils.renderproof2({
id: "proofs",
name: "proofs",
label: "Proof Type",
value: data.proofs,
onChange: event => selectfun1(event),
proofTypes,
disabled: shouldDisable,
error: errors["proofs"]
})}
{FormUtils.renderInput(
getInputArgObj("Idproof", "ID Proof Number", "text", shouldDisable)
)}
</div>
<div className="form-group">
<div>
{/* <label htmlFor="proofImage">
Upload Proof Image
</label> */}
<input
accept="image/*"
className={classes.input}
id="proofImage"
type="file"
onChange={onFileSelect}
disabled={shouldDisable && !enableFileUpload}
style={{ display: "none" }}
/>
<label htmlFor="proofImage">
<Button variant="contained" color="primary" component="span" startIcon={<CloudUploadIcon />} disabled={shouldDisable && !enableFileUpload}>
Id Proof
</Button>
</label>
{/* <label htmlFor="proofImage">
<Button
variant="contained"
color="default"
className={classes.uploadButton}
startIcon={<CloudUploadIcon />}
>style={{display:"none"}}
Upload Proof Image
</Button>
</label> */}
</div>
<div>
<img src={data["idProofImage"]} width="300px" />
</div>
</div>
<div className={classes.panel}>
<ExpansionPanel
expanded={expanded === "panel1"}
onChange={handleChange("panel1")}
>
<ExpansionPanelSummary
aria-controls="panel1a-content"
id="panel1a-header"
className={classes.panelHeader}
>
<div className={classes.expansionPanelSummary} >
<Typography className={classes.panelLabel} >Room</Typography>
<Fab
size="small"
color="primary"
aria-label="add"
onClick={onAddRoom}
disabled={shouldDisable}
>
<AddIcon />
</Fab>
</div>
</ExpansionPanelSummary>
<ExpansionPanelDetails className={classes.expansionPanelDetails}>
{data.rooms.map((room, index) => {
const error = checkRoomError(index);
return (
<div key={`room-${index}`} className="form-group">
{FormUtils.renderSelect({
id: "roomType",
label: "Room Type",
value: room.roomType,
renderValue: (value) => (<label>{value}</label>),
onChange: event => selectfun(event, index),
options: getRoomTypeOptions(options),
error,
disabled: shouldDisable
})}
{/* <FormControl style={{width:"80%"}}>
<InputLabel id="demo-simple-select-label">Age</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
// value= {"Delux"}
renderValue={(value)=>(<label>{value}</label>)}
value= {room.roomType}
>
{options && options.map(el=><MenuItem value={el.roomType} key={el.roomType}>{el.roomType}</MenuItem>)}
</Select>
</FormControl> */}
{FormUtils.renderSelect({
id: "roomNumber",
label: "Room Number",
value: room.roomNumber,
onChange: event => selectfun(event, index),
options: getRoomOptions(room.roomType),
error: error ? " " : null,
disabled: shouldDisable
})}
<div>
<IconButton
color="secondary"
className={classes.deleteButton}
onClick={() => onDeleteRoom(index)}
disabled={index === 0 ? true : shouldDisable}
>
<DeleteIcon />
</IconButton>
</div>
</div>
);
})}
</ExpansionPanelDetails>
</ExpansionPanel>
</div>
<div className={classes.button}>
{FormUtils.renderButton({
type: "button",
size: "large",
label: "Back",
color: "secondary",
className: classes.buttonSec,
disabled: false,
onClick: onBack
})}
{FormUtils.renderButton({
type: "submit",
size: "large",
label: data._id ? "Save" : "Book",
color: "primary",
className: null,
disabled: Object.keys(errors).length || shouldDisable ? true : false
})}
{data.status && !isDirtyroomSelected && !data.status.checkedIn && !isEdit && moment().startOf('date').toDate() >= moment(data.checkIn).startOf('date').toDate() && FormUtils.renderButton({
type: "button",
size: "large",
label: "CheckIn",
color: "primary",
className: null,
disabled: Object.keys(errors).length ? true : false,
style: { marginLeft: "1rem" },
onClick: onCheckIn
})}
{/* && moment(data.checkOut).toDate() >= moment(data.checkIn).startOf('date').toDate() */}
</div>
<Dialog onClose={() => setOpenPriceModal(false)} aria-labelledby="simple-dialog-title" open={openPriceModal} maxWidth="md" fullWidth={true}>
{/* <div style={{textAlign:"right", padding:"0.5rem"}}>
<CloseIcon onClick={()=>setOpenPriceModal(false)} style={{cursor:"pointer"}}/>
</div> */}
<DialogTitle id="simple-dialog-title" style={{ textAlign: "center" }}>
Date Wise Price Breakup
<CloseIcon onClick={() => setOpenPriceModal(false)} style={{ cursor: "pointer", float: "right" }} />
</DialogTitle>
<DialogContent style={{ maxHeight: "500px", overflowY: "auto" }}>
<span style={{ float: "right" }}>Nights Stay - {" " + data.nights}</span>
{Object.keys(formattedRates).map(element => {
return (
<React.Fragment>
<p>{element}-{data.planType}</p>
<div style={{ overflowX: "auto" }}>
<table className={classes.pricebreaktable}>
<tr className={classes.pricebreaktableTr}>
{formattedRates[element].map(rate => {
return (
<th className={classes.pricebreaktableTh}>{moment(rate.date).format('D.MMM.YYYY')}</th>
)
})}
</tr>
<tr>
{formattedRates[element].map(rate => {
return (
<td className={classes.pricebreaktableTd}>Rate: {rate.rate}</td>
)
})}
</tr>
<tr>
{formattedRates[element].map(rate => {
return (
<td className={classes.pricebreaktableTd}>Extra Rate: {rate.extraRate}</td>
)
})}
</tr>
</table>
</div>
</React.Fragment>
)
})}
{/* <div>
{
dayWiseRates.map(rate => {
if(rate.planType === data.planType){
return(
<div>
<div>{moment(rate.date).format('Do MMMM YYYY')}</div>
<div>{rate.roomType}</div>
<div>{rate.rate}</div>
<div>{rate.extraRate}</div>
</div>
)
}
})
}
</div> */}
</DialogContent>
</Dialog>
</form>
</React.Fragment>
);
};
export default BookingForm;
|
import React from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import { createHashHistory } from 'history';
import CourseReactGA from 'react-ga';
import Loadable from 'react-loadable';
import Loading from 'App/components/Loading';
import { MainContainer } from 'App';
const history = createHashHistory();
/**
* Dynamic imports
*
* @since 2.2.0
*/
const CourseContainer = Loadable({
loader: () => import(
/* webpackChunkName: 'CourseContainer' */
'Course/containers/CourseContainer'
),
loading: Loading
});
const LessonContainer = Loadable({
loader: () => import(
/* webpackChunkName: 'LessonContainer' */
'Lesson/containers/LessonContainer'
),
loading: Loading
});
const InstructorContainer = Loadable({
loader: () => import(
/* webpackChunkName: 'InstructorContainer' */
'Instructor/containers/InstructorContainer'
),
loading: Loading
});
const QuizContainer = Loadable({
loader: () => import(
/* webpackChunkName: 'QuizContainer' */
'Quiz/containers/QuizContainer'
),
loading: Loading
});
/**
* Initialize Google analytics. Check for the global object on page
* If it does not exist, initialize it
*
* @todo Figure out use case for fetching a UA code when not already embedded in page
*
* @since 2.1.0
*/
function checkForTrackingCode() {
if (!typeof ga === 'function') {
CourseReactGA.initialize('[GOOGLE UA CODE]');
}
}
checkForTrackingCode();
/**
* Log the page view to analytics. Only send information
* to analytics if on a non-index route.
*
* @since 2.1.0
*/
function logPageView(location) {
if (history.location) {
const { pathname } = history.location;
if (pathname !== '/') {
CourseReactGA.set({ page: pathname });
CourseReactGA.pageview(pathname);
}
}
}
history.listen(logPageView);
/**
* The App
*
* @since 1.0.0
*/
const Routes = () => (
<MainContainer>
<Router>
<Switch>
<Route exact path='/' component={ CourseContainer } />
<Route path='/lesson/:lessonSlug' component={ LessonContainer } />
<Route path='/instructors/:slug' component={ InstructorContainer } />
<Route exact path='/quiz' component={ QuizContainer } />
</Switch>
</Router>
</MainContainer>
);
export default Routes;
|
var _ = require('lodash');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var doiuse = require('doiuse');
var cssnext = require('postcss-cssnext');
var mergeLonghand = require('postcss-merge-longhand');
var mergeRules = require('postcss-merge-rules');
module.exports = function () {
var setup = this.opts.setup;
var browserSync = this.opts.browserSync;
var asserts = setup.asserts;
var src = asserts.src.styles;
var dest = asserts.root + asserts.res.styles;
var optionsSass = setup.plugins.gulpSass;
var optionsDoiuse = setup.plugins.doiuse;
var optionsPostcss = [
cssnext,
mergeLonghand,
mergeRules,
setup.isVerbose ? doiuse(optionsDoiuse) : undefined
];
optionsPostcss = _(optionsPostcss).reject(_.isUndefined).value();
return gulp.src(src, {cwd: asserts.base.src})
.pipe($.if(setup.isLocal, $.plumber()))
.pipe($.if(setup.isVerbose, $.sourcemaps.init()))
.pipe($.sass(optionsSass))
.pipe($.postcss(optionsPostcss))
.pipe($.if(setup.isVerbose, $.sourcemaps.write('.')))
.pipe(gulp.dest(dest, {cwd: asserts.dist}))
.pipe(browserSync.stream());
};
|
/*
* Module code goes here. Use 'module.exports' to export things:
* module.exports.thing = 'a thing';
*
* You can import it from another modules like this:
* var mod = require('manager.paths');
* mod.thing == 'a thing'; // true
*/
var logger = require("screeps.logger");
logger = new logger("manager.paths");
var obj = function() {
}
obj.prototype.init = function() {
logger.log("init")
this.mem = {};
// RawMemory.setActiveSegments([0,2,3]);
// this.mem = {};
// if (RawMemory.segments[0]) {
// var allPaths = RawMemory.segments[0];
// if (RawMemory.segments[2]) {
// allPaths += RawMemory.segments[2];
// }
// if (RawMemory.segments[3]) {
// allPaths += RawMemory.segments[3];
// }
// logger.log(allPaths);
// if (allPaths) {
// this.mem = JSON.parse(allPaths)
// } else {
// }
// }
// Memory.paths = false;
// if (!Memory.paths) {
// Memory.paths = {};
// }
}
var lastParseTick = 0;
obj.prototype.tickInit = function() {
var startCpu = Game.cpu.getUsed();
//this.mem = Memory.paths;
// RawMemory.setActiveSegments([0,2,3,99]);
// var dataLength = 0;
// if (RawMemory.segments[0] && (lastParseTick+1 != Game.time)) {
// var allPaths = RawMemory.segments[0];
// if (RawMemory.segments[2]) {
// allPaths += RawMemory.segments[2];
// }
// if (RawMemory.segments[3]) {
// allPaths += RawMemory.segments[3];
// }
// dataLength = allPaths.length;
// if (allPaths && allPaths.length < 210000) {
// this.mem = JSON.parse(allPaths)
// if (dataLength > 190000) {
// for(var d in this.mem) {
// var dest = this.mem[d];
// logger.log("-----------]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--", dest, _.keys(dest).length);
// if (_.keys(dest).length < 2) {
// delete this.mem[d];
// }
// }
// }
// } else {
// }
//lastParseTick = Game.time;
//}
var cpu = Game.cpu.getUsed();
//global.utils.stats.runningAvgStat("paths", "parseCpu", cpu-startCpu, 0.9);
//global.utils.stats.setStat("paths", "dataSize", dataLength);
logger.log("paths parsed", startCpu, cpu, cpu-startCpu, "********************", this.mem.length)
}
obj.prototype.tick = function() {
}
obj.prototype.tickEnd = function() {
logger.log('tickEnd---------------------')
var displayFlags = global.utils.flagsByColor(Game.flags, COLOR_WHITE, COLOR_GREY);
for(var f in displayFlags) {
var flag = displayFlags[f];
var destName = flag.pos.roomName+"-"+flag.pos.x+"-"+flag.pos.y;
if (this.mem[destName]) {
var flow = this.mem[destName];
logger.log('-----------------drawing path', flag.pos)
global.utils.drawFlowField(flag.pos, flow);
}
}
//drawFlowField
// var allPaths = JSON.stringify(this.mem);
// var sections = allPaths.match(/.{1,100000}/g);
// if (sections.length > 3) {
// return;
// }
// if (sections.length > 0)
// RawMemory.segments[0] = sections[0];
// if (sections.length > 1) {
// RawMemory.segments[2] = sections[1];
// } else {
// RawMemory.segments[2] = ""
// }
// if (sections.length > 2) {
// RawMemory.segments[3] = sections[2];
// } else {
// RawMemory.segments[3] = ""
// }
}
obj.prototype.getFlowDir = function(dest, currentPos) {
//this.mem = {};
//return false;
var destName = dest.roomName+"-"+dest.x+"-"+dest.y
//logger.log(destName)
var flow = this.mem[destName];
if (flow) {
if (flow[currentPos.roomName] && flow[currentPos.roomName][currentPos.x] && flow[currentPos.roomName][currentPos.x][currentPos.y]) {
var myflow = flow[currentPos.roomName][currentPos.x][currentPos.y];
//global.utils.drawFlowField(dest, flow);
return myflow;
}
}
return false;
}
obj.prototype.savePath = function(dest, pathInfo) {
//return;
// if (pathInfo.ops < 10) {
// return;
// }
//logger.log('saving path', dest.roomName, dest.x, dest.y, JSON.stringify(pathInfo))
var destName = dest.roomName+"-"+dest.x+"-"+dest.y
if (!this.mem[destName]) {
this.mem[destName] = {};
}
var flow = this.mem[destName];
var lastPos = false;
for(var p in pathInfo.path) {
var pos = pathInfo.path[p];
if (lastPos) {
var dir = lastPos.getDirectionTo(pos);
flow = this.setFlowValue(flow, lastPos, dir);
//logger.log(flow[pos.roomName][pos.x][pos.y]);
}
lastPos = pos;
}
this.mem[destName] = flow;
}
obj.prototype.setFlowValue = function(flow, pos, direction) {
if (!flow[pos.roomName]) {
flow[pos.roomName] = {};
}
if (!flow[pos.roomName][pos.x]) {
flow[pos.roomName][pos.x] = {};
}
//logger.log(pos.roomName, pos.x, pos.y, direction);
// only update flow if it has no value for this square
if (!flow[pos.roomName][pos.x][pos.y]) {
flow[pos.roomName][pos.x][pos.y] = direction;
}
return flow;
}
/*
Creep.prototype.oldMoveTo = Creep.prototype.moveTo;
Creep.prototype.moveTo = function(target, opts) {
if (opts == undefined) {
opts = {};
}
opts.reusePath=100;
opts.ignoreCreeps=true;
if (target == null) {
console.log(this.name, "is dumb and going no where")
return;
}
if (this.memory.stuck == undefined) {
this.memory.stuck = 0;
}
if (this.memory.stuckLastTick == undefined) {
this.memory.stuckLastTick = 0;
}
//this.memory.stuckLastTick=0
if (this.memory.lastPos) {
//if we're in the same position we were in, we may be stuck
if (this.memory.lastPos.x == this.pos.x && this.memory.lastPos.y == this.pos.y) {
this.memory.stuck++;
if (this.memory.stuck > 1) {
this.memory.stuckLastTick = (this.memory.stuckLastTick == 0 ? 2 : this.memory.stuckLastTick++);
}
} else {
if (this.memory.stuck > 0) {
this.memory.stuck--;
}
if (this.memory.stuckLastTick > 0) {
this.memory.stuckLastTick--;
}
}
}
this.memory.lastPos = this.pos;
// if (this.memory.stuckLastTick) {
// this.say("s"+this.memory.stuckLastTick);
// opts.ignoreCreeps = false;
// var res = this.oldMoveTo(target, opts);
// return res;
// } else {
// var res = this.oldMoveTo(target, opts);
// return res;
// }
var targetPos;
if (target instanceof RoomPosition) {
targetPos = target;
} else {
targetPos = target.pos;
}
if (Creep.prototype.mem[targetPos.gridName()] == undefined) {
Creep.prototype.mem[targetPos.gridName()] = {
count: 0,
paths: {}
};
}
Creep.prototype.mem[targetPos.gridName()].count++;
var alreadyOnPath = this.pathsContain(Creep.prototype.mem[targetPos.gridName()].paths, this.pos);
if (this.memory.stuckLastTick) {
this.say("s"+this.memory.stuckLastTick);
opts.ignoreCreeps = false;
var res = this.oldMoveTo(target, opts);
return res;
} else {
if (!Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()]) {
Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()] = {
count:0
};
}
if (alreadyOnPath) {
Creep.prototype.mem[targetPos.gridName()].paths[alreadyOnPath].count++;
var path = Creep.prototype.mem[targetPos.gridName()].paths[alreadyOnPath].path;
//logger.log(this.name, 'moving by path2', this.pos, alreadyOnPath)
this.say("on a path!");
if (Creep.prototype.mem[targetPos.gridName()].paths[alreadyOnPath].count > 4) {
this.buildRoad();
}
return this.moveByPath(path);
} else {
Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()].count++;
path = this.pos.findPathTo(targetPos, opts);
Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()].path = path;
//logger.log(this.name, 'moving by path', this.pos, target, targetPos)
this.say("routing!");
return this.moveByPath(path);
}
}
}
*/
module.exports = obj; |
window.onload = function() {
var button = document.querySelector('button');
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var width = canvas.width;
var height = canvas.height;
var capturing = false;
video.width = width;
video.height = height;
// We need the 2D context to individually manipulate pixel data
var ctx = canvas.getContext('2d');
// Start with a black background
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, width, height);
// Since we're continuously accessing and overwriting the pixels
// object, we'll request it once and reuse it across calls to draw()
// for best performance (we don't need to create ImageData objects
// on every frame)
var pixels = ctx.getImageData(0, 0, width, height);
var data = pixels.data;
var numPixels = data.length;
var stream = canvas.captureStream(30);
var recorder = new MediaRecorder(stream);
recorder.addEventListener('dataavailable', finishCapturing);
button.onclick = function() {
startCapturing();
};
function startCapturing() {
capturing = true;
draw();
recorder.start();
setTimeout(function() {
recorder.stop();
}, 2000);
}
function finishCapturing(e) {
capturing = false;
var videoData = [ e.data ];
var blob = new Blob(videoData, { 'type': 'video/webm' });
var videoURL = URL.createObjectURL(blob);
video.src = videoURL;
video.play();
}
function draw() {
// We don't want to render again if we're not capturing
if(capturing) {
requestAnimationFrame(draw);
}
drawWhiteNoise();
}
function drawWhiteNoise() {
var offset = 0;
for(var i = 0; i < numPixels; i++) {
var grey = Math.round(Math.random() * 255);
// The data array has pixel values in RGBA order
// (Red, Green, Blue and Alpha for transparency)
// We will make R, G and B have the same value ('grey'),
// then skip the Alpha value by increasing the offset,
// as we're happy with the opaque value we set when painting
// the background black at the beginning
data[offset++] = grey;
data[offset++] = grey;
data[offset++] = grey;
offset++; // skip the alpha component
}
// And tell the context to draw the updated pixels in the canvas
ctx.putImageData(pixels, 0, 0);
}
};
|
angular.module('PersonalWebsiteAngularApp').controller('navigationCtrl', function($scope, $location) {
return $scope.isActive = function(currentUrl) {
return currentUrl === $location.$$path;
};
});
|
// console.log(global);
//2.ๅจๅฆไธไธชๆไปถ้ๅผๅ
ฅไธไธไธชๅจglobalไธๆทปๅ ไผ ้ๅผ็ๆไปถ๏ผไฝฟๅพไธคไธชๆไปถไน้ดไบง็ๅ
ณ่
require('./m3.js');
//3.ๅจๅฆไธไธชๆไปถไฝฟ็จไธไธไธชๆไปถไผ ้็ๅผ
console.log(global.str) |
var points = []
var bounds ={
min: {x: undefined, y: undefined},
max: {x: undefined, y: undefined}
}
/*----------------------------------------------------------------------------*/
function addPoint(x, y, radius) {
radius = Number(radius || 10)
var pointElement = document.createElement('div')
pointElement.setAttribute('style', [
'position: absolute',
'left: ' + (x - radius / 2) + 'px',
'top: ' + (y - radius / 2) + 'px',
'width: ' + radius + 'px',
'height: ' + radius + 'px',
'background: rgba(0, 0, 0, 0.75)',
'border-radius: 50%'
].join(';')
)
document.body.appendChild(pointElement)
if (points.length > 1) {
for (var index = 0; index < points.length; index += 1) {
if (points[index].x < bounds.min.x || typeof bounds.min.x === 'undefined') {
bounds.min.x = points[index].x;
}
if (points[index].y < bounds.min.y || typeof bounds.min.y === 'undefined') {
bounds.min.y = points[index].y;
}
if (points[index].x > bounds.max.x || typeof bounds.max.x === 'undefined') {
bounds.max.x = points[index].x;
}
if (points[index].y > bounds.max.y || typeof bounds.max.y === 'undefined') {
bounds.max.y = points[index].y;
}
}
var width = bounds.max.x - bounds.min.x;
var height = bounds.max.y - bounds.min.y;
setBounds(bounds.min.x, bounds.min.y, width, height);
}
}
/*----------------------------------------------------------------------------*/
function setBounds(x, y, width, height) {
var boundsElement = document.getElementById('bounds')
if (!boundsElement) {
boundsElement = document.createElement('div')
boundsElement.setAttribute('id', 'bounds')
document.body.appendChild(boundsElement)
}
boundsElement.setAttribute('style', [
'position: absolute',
'z-index: 1',
'border: solid 1px rgba(196, 0, 0, 0.75)',
'left: ' + Number(x) + 'px',
'top:' + Number(y) + 'px',
'width: ' + (Number(width) - 2) + 'px',
'height: ' + (Number(height) - 2) + 'px'
].join(';')
)
}
/*----------------------------------------------------------------------------*/
document.addEventListener('mousedown', mouseDown);
var isMouseDown = false;
function mouseDown(event) {
isMouseDown = true;
points.push({ x: event.clientX, y: event.clientY});
addPoint(event.clientX, event.clientY);
}
document.addEventListener('mouseup', mouseUp);
function mouseUp(event) {
isMouseDown = false;
}
document.addEventListener('mousemove', mouseMove);
function mouseMove(event) {
if (isMouseDown) {
var lastPoint = points[points.length - 1];
var currentPoint = { x: event.clientX, y: event.clientY };
if (Math.abs(currentPoint.x - lastPoint.x) > 10 || Math.abs(currentPoint.y - lastPoint.y) > 10) {
points.push(currentPoint);
addPoint(currentPoint.x, currentPoint.y);
}
}
}
|
import React, { Component } from "react";
class PageContent extends Component {
render() {
return (
<div>
<p>Can you spot the item that doesn't belong?</p>
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
<li>Sit</li>
<li>Bumblebees</li>
<li>Aenean</li>
<li>Consectetur</li>
</ul>
</div>
);
}
}
export default PageContent; |
import YinFft from './yinfft.js'
const notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
function pitchToN (pitch) {
const n = 12 * (Math.log2(pitch) - Math.log2(440))
return Math.round(n)
}
function nToPitch (n) {
return 440 * 2 ** (n / 12)
}
function nToLabel (n) {
return notes[(n + 5 * notes.length) % notes.length]
}
function getClosestNote (pitch) {
const n = pitchToN(pitch)
// const minN = pitchToN(82.41) E low guitar
const minN = pitchToN(64) // C piano
const maxN = pitchToN(335)
if (n < minN || n > maxN) {
return null
}
return nToLabel(n)
}
class TunerACE extends HTMLElement {
constructor () {
super()
const root = this.attachShadow({ mode: 'open' })
const template = document.createElement('template')
template.innerHTML = `
<div>
<div class="pitch-main"></div>
<div>
<input type="range" disabled/>
</div>
<div>
<span class="lower"></span>
<span class="upper"></span>
</div>
<div style="clear:both;"></div>
</div>
<style>
input{ width: 100%; margin:0;}
input[type=range]::-webkit-slider-runnable-track, input[type=range]::-moz-range-track{
width: 99%; /* border make it overflow */
height: 8.4px;
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;
border-radius: 1.3px;
border: 0.2px solid #010101;
background: red;
background: -moz-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%);
background: -webkit-gradient(left, right, color-stop(0%, red), color-stop(25%, yellow), color-stop(51%, green), color-stop(75%, yellow), color-stop(100%, red));
background: -webkit-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%);
background: -o-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%);
background: -ms-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%);
background: linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%);
}
div.pitch-main {
font-size: 3em;
text-align:center;
}
.lower { float: left; }
.upper { float: right; }
</style>`
root.appendChild(template.content.cloneNode(true))
this.note = root.querySelector('.pitch-main')
this.lower = root.querySelector('.lower')
this.upper = root.querySelector('.upper')
this.input = root.querySelector('input')
}
static get observedAttributes () {
return ['pitch']
}
attributeChangedCallback (name, old, now) {
if (name === 'pitch') {
const pitch = parseFloat(now)
console.log('newpitch', pitch, getClosestNote(pitch))
if (isNaN(pitch) || !getClosestNote(pitch)) {
this.lower.innerHTML = '--'
this.upper.innerHTML = '--'
this.lower.setAttribute('title', '--')
this.upper.setAttribute('title', '--')
return
}
const n = pitchToN(pitch)
const minN = n - 1
const maxN = n + 1
this.note.innerHTML = nToLabel(n) + '(' + pitch.toFixed(2) + 'hz)'
this.lower.setAttribute('title', nToPitch(minN).toFixed(2) + ' hz')
this.upper.setAttribute('title', nToPitch(maxN).toFixed(2) + ' hz')
this.lower.innerHTML = nToLabel(minN)
this.upper.innerHTML = nToLabel(maxN)
this.input.min = nToPitch(minN)
this.input.max = nToPitch(maxN)
this.input.value = pitch
}
}
};
customElements.define('my-tuner', TunerACE)
class PitchDrawer {
constructor (node) {
this.chunks = []
this.pitchDrawNode = node
this.tuner = document.createElement('my-tuner')
this.tuner.setAttribute('pitch', 100)
node.appendChild(this.tuner)
this.started = false
}
draw (v) {
const yin = new YinFft()
const pitch = yin(v)
console.log('pitch', pitch)
this.tuner.setAttribute('pitch', pitch)
}
start (arr) {
this.chunks = [arr]
this.started = true
}
feed (arr) {
if (!this.started) return
this.chunks.push(arr)
const l = this.chunks[0].length
if (this.chunks.length * l === 32768) {
const newbuf = new Uint8Array(32768)
this.chunks.forEach((c, i) => {
newbuf.set(c, l * i)
})
this.draw(newbuf)
this.started = false
}
}
}
export default PitchDrawer
|
/* BEGIN BUBBLE SHIT */
var max_income = 123000;
var min_income = 18000;
var max_pop = 1000000;
var min_pop = 169;
var min_vote = 0;
var max_vote = 1;
var min_unemp = 0;
var max_unemp = .26;
var min_max = {
"income": {'min': min_income, 'max': max_income},
"pop" : {'min': min_pop, 'max': max_pop},
"vote" : {'min': min_vote, 'max': max_vote},
"unemp" : {'min': min_unemp, 'max': max_unemp}
}
var dem_title = {
"income": "Median Income",
"vote" : "% GOP Vote 2016",
"unemp" : "Unemployment Rate"
}
var dem_label = {
"income": "Income: $",
"vote" : "% GOP Vote: ",
"unemp" : "Unemployment"
}
var dem_pos = {
"income": income_pos,
"vote" : pos_vote,
"unemp" : unemp_pos
}
var quantize = d3.scaleQuantize()
.domain([0, 4])
.range(d3.range(5).map(function(i) {
if (i == 0)
return "#9adbb5";
else if (i == 1)
return "rgb(205, 235, 178)";
else if (i == 2)
return "#F6F5AE";
else if (i == 3)
return "rgb(253, 223, 158)";
else
return "rgb(211, 85, 65)";
}))
var move_dict = d3.map();
og_data.forEach( function(d){ move_dict.set( d.fips, d.move_index) });
var county_dict = d3.map();
var sab_dict = d3.map();
og_data.forEach( function(d){
county_dict.set( d.fips, d.county);
sab_dict.set(d.fips, d.sab);
});
var pop_dict = d3.map()
dem_data.forEach( function(d){
pop_dict.set( d.fips, d.pop_2019);
});
var unemp_dict = d3.map()
unemp_data.forEach( function(d) {
unemp_dict.set(d.id, d.rate);
});
function get_rad_range(width) {
if (width >= 900) {
return [3,8]
}
else if (width >= 600) {
return [2,5]
}
return [1.5,3]
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
percentFormat = d3.format(',.2%');
function get_x_value(dem, data) {
if (dem == "income") {
return numberWithCommas(data.income);
}
else if (dem == "unemp") {
return percentFormat(data.unemp);
}
return (dem == "vote") ? percentFormat(data.vote) : data.cases;
}
function get_node_x(dem, node) {
if (dem == "income") {
return node.median_income
}
else if (dem == "unemp")
return node.unemp
return (dem == "vote") ? node.per_gop : node.cpc
}
function get_d_x(dem, node) {
if (dem == "income") {
return node.income
}
else if (dem == "unemp") {
return node.unemp
}
return (dem == "vote") ? node.vote : node.cpc
}
function get_move(d) {
var val = document.getElementById("myRange").value;
return move_dict.get(d.fips)[val-1]
}
function make_x_axis(dem) {
var margin = {top: 300, right: 250, bottom: 50, left: 50};
var width = $("#maps").width()
var height = $("#maps").height()
pos = $("#maps").position().top;
var bubbles = d3.select(".bubble_svg")
var x = d3.scaleLinear()
.domain( [min_max[dem].min, min_max[dem].max] )
.range( [margin.left, width - margin.right] );
var xAxis = d3.axisBottom(x);
var xAxisTitle = bubbles.append("text")
.attr("class", "axisTitle")
.text(dem_title[dem]);
xAxisTitle
.attr("x", width - xAxisTitle.node().getBBox().width - width/4.5)
.attr("y", ( height/2) - xAxisTitle.node().getBBox().height - height/5)
bubbles.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height/2) + ")")
.call(xAxis);
}
function update_demographic(dem, val) {
console.log("update");
console.log(dem);
var margin = {top: 300, right: 250, bottom: 50, left: 50};
var t = d3.transition()
.duration(750);
var width = $("#maps").width()
var height = $("#maps").height()
var bubbles = d3.select(".bubble_svg")
bubbles.select(".axisTitle").remove()
bubbles.select("g.x.axis").remove()
bubbles.select(".d3-tip").remove()
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-5, 0])
.html(function(d) {
return "County: " + toTitleCase(d.county)
+ " (" + d.sab + ")<br>Move Index: " + get_move(d)
+ "<br>Population: " + numberWithCommas(d.pop)
+ "<br>" + dem_label[dem] + ": " + get_x_value(dem, d);
})
bubbles.call(tip);
var x = d3.scaleLinear()
.domain([min_max[dem].min, min_max[dem].max] )
.range([margin.left, width - margin.right]);
var y_dict = d3.map();
y_pos = dem_pos[dem];
y_pos.forEach( function(d){ y_dict.set(d.fips, 250 - d.y )});
var circle = bubbles.selectAll("circle")
.attr("x", function(d) { return x(get_d_x(dem, d))})
.attr("y", function(d) { return y_dict.get(d.fips)})
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.transition(t)
.attr("cx", function(d) { return x(get_d_x(dem, d))})
.attr("cy", function(d) { return y_dict.get(d.fips)})
.attr("transform", "translate(0," + height/2 + ")")
make_x_axis(dem)
}
// to be used with swapmap to replace map with bubbles
function make_bubbles_rep(us, val, dem) {
console.log(dem);
console.log("swap map");
var margin = {top: 300, right: 250, bottom: 50, left: 50};
d3.select(".bubble_svg").remove();
var width = $("#maps").width()
var height = $("#maps").height()
pos = $("#maps").position().top;
rad_range = get_rad_range(width)
var x = d3.scaleLinear()
.domain( [min_max[dem].min, min_max[dem].max] )
.range( [margin.left, width - margin.right]);
var radquantize = d3.scaleQuantize()
.domain([min_max['pop'].min, min_max['pop'].max])
.range(rad_range)
d3.json("./bubble/dem-data.json", function(error, data) {
if (error) throw error;
var bubbles = d3.select("#maps").append("svg")
.attr("width", width)
.attr("height", height)
.attr("class", "bubble_svg")
.attr("shape-rendering", "geometric-precision");
$("#maps").css("visibility", "visible");
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-5, 0])
.html(function(d) {
return "County: " + toTitleCase(d.county)
+ " (" + d.sab + ")<br>Move Index: " + get_move(d)
+ "<br>Population: " + numberWithCommas(d.pop)
+ "<br>" + dem_label[dem] + ": " + get_x_value(dem, d);
})
bubbles.call(tip);
var y_dict = d3.map();
y_pos = dem_pos[dem]
y_pos.forEach( function(d){ y_dict.set(d.fips, 250 - d.y )});
//add education metric
var nodes = data.map(function(node, index) {
return {
index: index,
fips: node.fips,
pop: node.pop_2019,
income: node.median_income,
county: node.county,
sab: node.sab,
vote: node.per_gop,
unemp: unemp_dict.get(node.fips),
x: x(get_node_x(dem, node)),
fx: x(get_node_x(dem, node)),
r: radquantize(node.pop_2019),
y: y_dict.get(node.fips)
};
});
// var simulation = d3.forceSimulation(nodes)
// .force("x", d3.forceX(function(d) { return d.x; }).strength(1))
// .force("collide", d3.forceCollide().radius(function(d){ return d.r}))
// .force("manyBody", d3.forceManyBody().strength(-1))
// .tick();
var circle = bubbles.selectAll("circle")
.data(nodes)
.enter().append("circle")
.style("fill", function(d) { return quantize(move_dict.get(d.fips)[val-1]); })
.attr("cx", function(d) { return x(get_d_x(dem, d))} )
.attr("cy", function(d) { return y_dict.get(d.fips)} )
.attr("r", function(d) { return d.r} )
.style("opacity", function(d) {
return ((d.y + height/2) <= d.r || (d.y + height/2) >= (height - d.r)) ? 0 : 0.75})
.attr("transform", "translate(0," + height/2 + ")")
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.on('click', function(d) { handleClick(d.fips) })
make_x_axis(dem)
if (selected_fips != null)
highlight_single(selected_fips);
});
}
|
const express = require('express');
const dotenv = require('dotenv');
const path = require('path');
const helpers = require('./helpers/pug-helpers');
const mainRoutes = require('./routes/main');
const projectRoutes = require('./routes/project');
dotenv.config({ path: '.env' });
const app = express();
// Set up template engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Add helpers to local variables for access in pug templates
app.use((req, res, next) => {
res.locals.h = helpers;
next();
});
// Add main static files
app.use(express.static(path.join(__dirname, 'public/site')));
app.use('/project', express.static(path.join(__dirname, 'public/site')));
// Add main routes
app.use('/', mainRoutes);
// Add static files for projects
app.use(express.static(path.join(__dirname, 'public/projects')));
app.use(express.static(path.join(__dirname, 'public/projects/myreads')));
app.use(express.static(path.join(__dirname, 'public/projects/senate-map')));
app.use(express.static(path.join(__dirname, 'public/projects/message-board')));
app.use(express.static(path.join(__dirname, 'public/projects/todos')));
app.use(express.static(path.join(__dirname, 'public/documents')));
// Add project routes
app.use('/', projectRoutes);
// Handle 404s
app.use((req, res) => {
res.status(404).send('404: Page Not Found');
});
app.set('port', process.env.PORT || 3000);
const server = app.listen(app.get('port'), () => {
console.log(`Listening on port ${app.get('port')}โฆ`);
});
|
import React from "react";
import './NavControl.scss';
import {faUserCircle} from "@fortawesome/free-solid-svg-icons";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import AnimationMixin from "../../plugin/animation";
class NavControl extends React.Component {
componentDidMount() {
window.addEventListener("scroll", this.scrollEvent, true)
}
componentWillUnmount() {
window.removeEventListener("scroll", this.scrollEvent)
}
scrollEvent() {
const navControl = document.getElementById("nav-control");
AnimationMixin.fixTop(navControl);
}
render() {
return(
<div className="NavControl" id="nav-control">
<FontAwesomeIcon icon={faUserCircle} className="nav-icon"/>
<FontAwesomeIcon icon={faUserCircle} className="nav-icon"/>
</div>
)
}
}
export default NavControl;
|
const mysql = require("mysql");
const inquirer = require("inquirer");
const cTable = require("console.table");
// set up connection to server
// =========================================================
var connection = mysql.createConnection({
host: "localhost",
// Your port; if not 3306
PORT: 3306,
// Your username
user: "root",
// Your password
password: "20164Runner",
database: "employeeTracker_DB"
});
connection.connect(function (err) {
if (err) throw err;
console.log("connected as id " + connection.threadId + "\n");
start();
});
// Function to run inquirer
// =========================================================
function questions(options) {
return inquirer.prompt(options);
}
// main function to run program
// =========================================================
const start = function () {
questions({
name: "action",
type: "rawlist",
message: "What would you like to do?",
choices: [
"View all employees",
"View all employees by manager",
"View all departments",
"View all roles",
"Search Employees",
"Add employees",
"Add departments",
"Add roles",
"Update an employee's data"
]
})
.then(function (answer) {
switch (answer.action) {
case "View all employees":
allEmployees();
break;
case "View all employees by manager":
employeesByManager();
break;
case "View all departments":
allDepartments();
break;
case "View all roles":
allRoles();
break;
case "Search Employees":
employeeSearch();
break;
case "Add employees":
addEmployee();
break;
case "Add roles":
addRole();
break;
case "Add departments":
addDepartment();
break;
case "Update an employee's data":
update();
break;
}
})
}
// query specific functions used above in main program
// =========================================================
const allEmployees = function () {
var query = "SELECT employee.id, employee.first_name, employee.last_name, roles.title, department.department_name AS department, roles.salary "
query += "FROM employee "
query += "LEFT JOIN roles ON (employee.role_id = roles.id) "
query += "LEFT JOIN department ON (roles.department_id = department.id);"
connection.query(query, function (error, results, fields) {
console.log("");
console.table(results);
})
start()
}
const allDepartments = function () {
var query = "SELECT * "
query += "FROM department "
connection.query(query, function (error, results, fields) {
console.log("");
console.table(results);
})
start();
}
const allRoles = function () {
var query = "SELECT * "
query += "FROM roles "
query += "INNER JOIN department ON (roles.department_id = department.id)"
connection.query(query, function (error, results, fields) {
console.log("");
console.table(results);
})
start();
}
const employeeSearch = function () {
questions({
name: "id",
type: "input",
message: "Please enter the id of the employee you would like to view."
})
.then(function (answer) {
var query = "SELECT employee.id, employee.first_name, employee.last_name, roles.title, department.department_name AS department, roles.salary "
query += "FROM employee "
query += "LEFT JOIN roles ON (employee.role_id = roles.id) "
query += "LEFT JOIN department ON (roles.department_id = department.id) "
query += "WHERE employee.id = ?"
connection.query(query, [answer.id], function (error, results, fields) {
console.log("");
console.table(results);
})
start()
})
}
// Add Functions =====
const addEmployee = function () {
questions([{
name: "fName",
type: "input",
message: "Please enter the first name of the employee you would like to add"
},
{
name: "lName",
type: "input",
message: "Please enter the last name of the employee you would like to add"
},
{
name: "role",
type: "input",
message: "Please enter the role ID of the employee you would like to add"
},
{
name: "manager",
type: "input",
message: "Please enter the manager ID of the employee you would like to add"
}]
)
.then(function (answer) {
var query = "INSERT INTO employee (first_name, last_name, role_id, manager_id) "
query += "VALUES (?, ?, ?, ?)"
connection.query(query, [answer.fName, answer.lName, answer.role, answer.manager], function (error, results, fields) {
console.table(results);
if (error) throw error;
})
console.log("successfully added")
start()
})
}
const addDepartment = function () {
questions([{
name: "name",
type: "input",
message: "Please enter the name of the department you would like to add"
}]
)
.then(function (answer) {
var query = "INSERT INTO department (department_name) "
query += "VALUES (?)"
connection.query(query, [answer.name], function (error, results, fields) {
console.table(results);
if (error) throw error;
})
console.log("successfully added")
start()
})
}
const addRole = function () {
questions([{
name: "title",
type: "input",
message: "Please enter the title of the role you would like to add"
},
{
name: "salary",
type: "input",
message: "Please enter the salary of the role you would like to add"
},
{
name: "department_id",
type: "input",
message: "Please enter the department ID of the role you would like to add"
}]
)
.then(function (answer) {
var query = "INSERT INTO roles (title, salary, department_id) "
query += "VALUES (?, ?, ?)"
connection.query(query, [answer.title, answer.salary, answer.department_id], function (error, results, fields) {
console.table(results);
if (error) throw error;
})
console.log("successfully added")
start()
})
}
// ===================
// update function ====
const update = function () {
questions([{
name: "id",
type: "input",
message: "Please enter the ID of the employee you would like to update"
},
{
name: "employeeAttribute",
type: "rawlist",
message: "Please choose the data of the employee you would like to update",
choices: [
"first_name",
"last_name",
"role_id",
"manager_id"
]
},
{
name: "employeeValue",
type: "input",
message: "Please enter the updated value of the employee you would like to update"
}
])
.then(function (answer) {
console.log(answer);
switch (answer.employeeAttribute) {
case "first_name":
var query = "UPDATE employee SET first_name = ? WHERE id = ?"
connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) {
console.table(results);
if (error) {
return console.log(error);
}
})
console.log("successfully updated");
start();
break;
case "last_name":
var query = "UPDATE employee SET last_name = ? WHERE id = ?"
connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) {
console.table(results);
if (error) {
return console.log(error);
}
})
console.log("successfully updated");
start();
break;
case "role_id":
var query = "UPDATE employee SET role_id = ? WHERE id = ?"
connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) {
console.table(results);
if (error) {
return console.log(error);
}
})
console.log("successfully updated");
start();
break;
case "manager_id":
var query = "UPDATE employee SET manager_id = ? WHERE id = ?"
connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) {
console.table(results);
if (error) {
return console.log(error);
}
})
console.log("successfully updated");
start();
break;
}
})} |
"use strict";
import { NavbarTop } from "./navbarTop.js";
import { NavbarBottom } from "./navbarBottom.js";
import { OutlayCategory } from "./outlayCategory.js";
import { OutlayEntry } from "./outlayEntry.js";
import {
db,
outlayObjectStoreName,
outlayCategoryObjectStoreName,
settingObjectStoreName,
outlayCategorySelectedKeyName,
outlayEntriesDateMinCalcKeyName,
} from "./db.js";
import { Setting } from "./setting.js";
import { Category } from "./category.js";
import { setContentHeight } from "./pattern.js";
let categorySelectedId;
let categorySelected;
let categorySelectedParent;
let categorySelectedParentInit;
export class OutlayCategoryMove {
static async displayData() {
NavbarTop.show({
menu: {
buttonHTML: "☰",
content: [
{
innerHTML: "ะะตัะตะผะตััะธัั ะบะฐัะตะณะพัะธั",
href: "#func=OutlayCategoryMove",
},
{
innerHTML: "ะงะตะบะธ",
href: "Javascript:OutlayEntries_displayData()",
},
{
innerHTML: "ะัะพะณะธ ะฒ ัะฐะทัะตะทะต ะบะฐัะตะณะพัะธะน",
href: "Javascript:OutlaySummary_displayData()",
},
{
innerHTML: "ะฃัะธะปะธัั",
href: "#func=OutlayUtils",
},
],
},
titleHTML: "ะะตัะตะผะตัะตะฝะธะต ะบะฐัะตะณะพัะธะธ",
buttons: [
{
onclick: OutlayCategoryMove.save,
title: "ะกะพั
ัะฐะฝะธัั",
innerHTML: "✔",
id: "buttonSave",
},
],
});
NavbarBottom.show([
{ text: "ะงะตะบะธ", href: 'Javascript:displayData("OutlayEntries")' },
{ text: "ะะฐัะตะณะพัะธะธ", href: 'Javascript:displayData("OutlayCategory")' },
{ text: "ะัะพะณะธ", href: 'Javascript:displayData("OutlaySummary")' },
]);
const divContent = document.getElementsByClassName("content")[0];
{
while (divContent.firstChild) {
divContent.removeChild(divContent.firstChild);
}
}
divContent.appendChild(
await OutlayCategory.displayTree(
null,
db.transaction(outlayCategoryObjectStoreName),
true
)
);
categorySelectedId = await Setting.get(outlayCategorySelectedKeyName);
categorySelected = document.getElementById(categorySelectedId)
.parentElement;
categorySelected.className = "categoryToMove";
categorySelectedParentInit = categorySelected.parentElement.parentElement;
categorySelectedParent = categorySelectedParentInit;
categorySelectedParent.className = "categoryToMoveParent";
// https://vc.ru/dev/89555-javascript-massivy-peresechenie-raznost-i-obedinenie-v-es6
for (let li of Array.prototype.slice
.call(divContent.getElementsByTagName("LI"), 0)
.filter(
(x) =>
!Array.prototype.slice
.call(categorySelected.getElementsByTagName("LI"), 0)
.includes(x)
)) {
li.querySelector("li > span:nth-child(2)").onclick =
OutlayCategoryMove.categoryParentSelect;
}
OutlayCategoryMove.navbarTopRefresh();
setContentHeight();
}
static categoryParentSelect() {
categorySelectedParent.className = null;
categorySelectedParent = this.parentElement.parentElement;
categorySelectedParent.className = "categoryToMoveParent";
const categorySelectedText = categorySelected
.querySelector(".categoryToMove > li > span:nth-child(2)")
.innerHTML.trim();
{
let categoryMoved = false;
for (let ul of categorySelectedParent.querySelectorAll(
".categoryToMoveParent > li > ul"
)) {
if (
categorySelectedText <
ul.querySelector("li > span:nth-child(2)").innerHTML.trim()
) {
categorySelectedParent
.querySelector(".categoryToMoveParent > li")
.insertBefore(categorySelected, ul);
categoryMoved = true;
break;
}
}
if (!categoryMoved) {
categorySelectedParent
.querySelector(".categoryToMoveParent > li")
.appendChild(categorySelected);
}
}
OutlayCategoryMove.navbarTopRefresh();
}
static navbarTopRefresh() {
const navBarTopTitle = document
.getElementsByClassName("navBarTopTitle")
.item(0);
navBarTopTitle.innerHTML =
' "' +
categorySelected
.querySelector(".categoryToMove > li > span:nth-child(2)")
.innerHTML.trim() +
'" ะธะท "' +
categorySelectedParentInit
.querySelector("li > span:nth-child(2)")
.innerHTML.trim() +
'"';
if (categorySelectedParentInit === categorySelectedParent) {
navBarTopTitle.innerHTML = "ะะตัะตะผะตัะตะฝะธะต " + navBarTopTitle.innerHTML;
document.getElementById("buttonSave").className = "buttonDisabled";
} else {
navBarTopTitle.innerHTML =
"ะะตัะตะผะตััะธัั " +
navBarTopTitle.innerHTML +
' ะฒ "' +
categorySelectedParent
.querySelector("li > span:nth-child(2)")
.innerHTML.trim() +
'"';
}
}
static async save() {
if ("buttonDisabled" === document.getElementById("buttonSave").className) {
return;
}
if (
!window.confirm(
'ะั ะดะตะนััะฒะธัะตะปัะฝะพ ั
ะพัะธัะต ะฟะตัะตะผะตััะธัั "' +
categorySelected
.querySelector(".categoryToMove > li > span:nth-child(2)")
.innerHTML.trim() +
'" ะธะท "' +
categorySelectedParentInit
.querySelector("li > span:nth-child(2)")
.innerHTML.trim() +
'" ะฒ "' +
categorySelectedParent
.querySelector("li > span:nth-child(2)")
.innerHTML.trim() +
'"?'
)
)
return;
try {
const transaction = db.transaction(
[
outlayCategoryObjectStoreName,
outlayObjectStoreName,
settingObjectStoreName,
],
"readwrite"
);
await Setting.set(
outlayEntriesDateMinCalcKeyName,
(await OutlayEntry.getEntryYoungest(transaction)).date,
transaction
);
const category = await Category.get(categorySelectedId, transaction);
category.parentId = Number(categorySelectedParent.firstChild.id);
await Category.set(category, transaction);
transaction.onerror = function (event) {
alert("ะะจะะะะ: " + event.target.error);
};
transaction.oncomplete = function () {
history.back();
};
} catch (error) {
alert(error);
}
}
}
|
var home = {},
football = {
goalkeeper : "Van der Sar",
midfielder : "De Jong",
attacker : "Depay"
};
function isEmpty(object) {
for(var key in object) {
return false;
}
return true;
}
console.log(isEmpty(home));
console.log(isEmpty(football)); |
'use strict';
angular.module('FEF-Angular-UI.MqService', [])
.factory('MqService', function() {
if (typeof Modernizr === 'undefined') {
throw 'Modernizr is not defined';
}
return {
mq: Modernizr.mq
}
}); |
(function () {
'use strict';
angular
.module('app.socket',[])
.factory('socket',['User',function (User) {
var socket = io();
socket.log = function (texto) {
socket.emit('users:logs',{
log:texto,
date:new Date(),
user:User.current
})
};
return socket;
}]);
})();
|
// /*
// *
// * WordPres็ๅพฎไฟกๅฐ็จๅบ
// * author: jianbo
// * organization: ๅฎๆ่ฝฉ www.watch-life.net
// * github: https://github.com/iamxjb/winxin-app-watch-life.net
// * ๆๆฏๆฏๆๅพฎไฟกๅท๏ผiamxjb
// * ๅผๆบๅ่ฎฎ๏ผMIT
// *
// * *Copyright (c) 2017 https://www.watch-life.net All rights reserved.
// */
// var Api = require('../../utils/api.js');
// var util = require('../../utils/util.js');
// var WxParse = require('../../wxParse/wxParse.js');
// var wxApi = require('../../utils/wxApi.js')
// var wxRequest = require('../../utils/wxRequest.js')
var wxCharts = require('../../utils/wxcharts.js')
import config from '../../utils/config.js'
// var pageCount = config.getPageCount;
let lineChart = null
Page({
/**
* ้กต้ข็ๅๅงๆฐๆฎ
*/
data: {
tabInd:0,
animation:true,
data0:"60%",
data1:300,
data2:200,
data3:300,
},
tabInds(event){
let ind = event.currentTarget.dataset.index
if (this.data.tabInd ===ind) {
return false;
} else {
if (ind==0){
this.setData({
tabInd: ind,
data1: 100,
data2: 200,
data3: 300,
});
} else if (ind == 1){
this.setData({
tabInd: ind,
data1: 200,
data2: 200,
data3: 200,
});
}else{
this.setData({
tabInd: ind,
data1: 300,
data2: 200,
data3: 100,
});
}
this.data.animation = false
this.chartss()
}
},
chartss() {
lineChart = new wxCharts({
animation: this.data.animation, //ๆฏๅฆๆๅจ็ป
canvasId: 'ringCanvas',
type: 'ring',
extra: {
ringWidth: 30,
pie: {
offsetAngle: -90
}
},
title: {
name: this.data.data0,
color: '#FF5B1F',
fontSize: 14
},
// subtitle: {
// name: '่ฟๅบฆ',
// color: '#191F23',
// fontSize: 12
// },
series: [{
name: '็ฎๆ ',
data: this.data.data1,
color: '#C552DB',
stroke: true
}, {
name: '้้',
data: this.data.data2,
color: '#E66878',
stroke: true
}, {
name: '่ฟๅบฆ',
data: this.data.data3,
color: '#F2AB62',
stroke: true
}],
disablePieStroke: true,
width: 150,
height: 150,
dataLabel: false,
legend: false,
padding: 10,
});
},
/**
* ็ๅฝๅจๆๅฝๆฐ--็ๅฌ้กต้ขๅ ่ฝฝ
*/
onLoad: function (options) {
this.chartss()
},
/**
* ็ๅฝๅจๆๅฝๆฐ--็ๅฌ้กต้ขๅๆฌกๆธฒๆๅฎๆ
*/
onReady: function () {
},
/**
* ็ๅฝๅจๆๅฝๆฐ--็ๅฌ้กต้ขๆพ็คบ
*/
onShow: function () {
},
/**
* ็ๅฝๅจๆๅฝๆฐ--็ๅฌ้กต้ข้่
*/
onHide: function () {
},
/**
* ็ๅฝๅจๆๅฝๆฐ--็ๅฌ้กต้ขๅธ่ฝฝ
*/
onUnload: function () {
},
/**
* ้กต้ข็ธๅ
ณไบไปถๅค็ๅฝๆฐ--็ๅฌ็จๆทไธๆๅจไฝ
*/
onPullDownRefresh: function () {
},
/**
* ้กต้ขไธๆ่งฆๅบไบไปถ็ๅค็ๅฝๆฐ
*/
onReachBottom: function () {
},
/**
* ็จๆท็นๅปๅณไธ่งๅไบซ
*/
onShareAppMessage: function () {
}
})
// Page({
// data: {
// postsList: [],
// postsShowSwiperList:[],
// isLastPage:false,
// page: 1,
// search: '',
// categories: 0,
// showerror:"none",
// showCategoryName:"",
// categoryName:"",
// showallDisplay:"block",
// displayHeader:"none",
// displaySwiper: "none",
// floatDisplay: "none",
// displayfirstSwiper:"none",
// topNav: []
// },
// formSubmit: function (e) {
// var url = '../list/list'
// var key ='';
// if (e.currentTarget.id =="search-input")
// {
// key = e.detail.value;
// }
// else{
// key = e.detail.value.input;
// }
// if (key != '') {
// url = url + '?search=' +key;
// wx.navigateTo({
// url: url
// })
// }
// else
// {
// wx.showModal({
// title: 'ๆ็คบ',
// content: '่ฏท่พๅ
ฅๅ
ๅฎน',
// showCancel: false,
// });
// }
// },
// onShareAppMessage: function () {
// return {
// title: 'โ' + config.getWebsiteName+'โ็ฝ็ซๅพฎไฟกๅฐ็จๅบ,ๅบไบWordPress็ๅฐ็จๅบๆๅปบ.ๆๆฏๆฏๆ๏ผwww.watch-life.net',
// path: 'pages/index/index',
// success: function (res) {
// // ่ฝฌๅๆๅ
// },
// fail: function (res) {
// // ่ฝฌๅๅคฑ่ดฅ
// }
// }
// },
// onPullDownRefresh: function () {
// var self = this;
// self.setData({
// showerror: "none",
// showallDisplay:"block",
// displaySwiper:"none",
// floatDisplay:"none",
// isLastPage:false,
// page:1,
// postsShowSwiperList:[]
// });
// this.fetchTopFivePosts();
// this.fetchPostsData(self.data);
// },
// onReachBottom: function () {
// var self = this;
// if (!self.data.isLastPage) {
// self.setData({
// page: self.data.page + 1
// });
// console.log('ๅฝๅ้กต' + self.data.page);
// this.fetchPostsData(self.data);
// }
// else {
// console.log('ๆๅไธ้กต');
// }
// },
// onLoad: function (options) {
// var self = this;
// self.fetchTopFivePosts();
// self.fetchPostsData(self.data);
// self.setData({
// topNav: config.getIndexNav
// });
// },
// onShow: function (options){
// wx.setStorageSync('openLinkCount', 0);
// },
// fetchTopFivePosts: function () {
// var self = this;
// //่ทๅๆปๅจๅพ็็ๆ็ซ
// var getPostsRequest = wxRequest.getRequest(Api.getSwiperPosts());
// getPostsRequest.then(response => {
// if (response.data.status =='200' && response.data.posts.length > 0) {
// self.setData({
// // postsShowSwiperList: response.data.posts,
// postsShowSwiperList: self.data.postsShowSwiperList.concat(response.data.posts.map(function (item) {
// if (item.post_medium_image == null || item.post_medium_image == '') {
// item.post_medium_image = "../../images/logo700.png";
// }
// return item;
// })),
// displaySwiper: "block"
// });
// }
// else {
// self.setData({
// displaySwiper: "none"
// });
// }
// }).catch(function (response){
// console.log(response);
// self.setData({
// showerror: "block",
// floatDisplay: "none"
// });
// })
// .finally(function () {
// });
// },
// //่ทๅๆ็ซ ๅ่กจๆฐๆฎ
// fetchPostsData: function (data) {
// var self = this;
// if (!data) data = {};
// if (!data.page) data.page = 1;
// if (!data.categories) data.categories = 0;
// if (!data.search) data.search = '';
// if (data.page === 1) {
// self.setData({
// postsList: []
// });
// };
// wx.showLoading({
// title: 'ๆญฃๅจๅ ่ฝฝ',
// mask:true
// });
// var getPostsRequest = wxRequest.getRequest(Api.getPosts(data));
// getPostsRequest
// .then(response => {
// if (response.statusCode === 200) {
// if (response.data.length) {
// if(response.data.length < pageCount)
// {
// self.setData({
// isLastPage: true
// });
// }
// self.setData({
// floatDisplay: "block",
// postsList: self.data.postsList.concat(response.data.map(function (item) {
// var strdate = item.date
// if (item.category_name != null) {
// item.categoryImage = "../../images/category.png";
// }
// else {
// item.categoryImage = "";
// }
// if (item.post_medium_image == null || item.post_medium_image == '') {
// item.post_medium_image = "../../images/logo700.png";
// }
// item.date = util.cutstr(strdate, 10, 1);
// return item;
// })),
// });
// setTimeout(function () {
// wx.hideLoading();
// }, 900);
// }
// else {
// if (response.data.code == "rest_post_invalid_page_number") {
// self.setData({
// isLastPage: true
// });
// wx.showToast({
// title: 'ๆฒกๆๆดๅคๅ
ๅฎน',
// mask: false,
// duration: 1500
// });
// }
// else {
// wx.showToast({
// title: response.data.message,
// duration: 1500
// })
// }
// }
// }
// })
// .catch(function (response)
// {
// if (data.page == 1) {
// self.setData({
// showerror: "block",
// floatDisplay: "none"
// });
// }
// else {
// wx.showModal({
// title: 'ๅ ่ฝฝๅคฑ่ดฅ',
// content: 'ๅ ่ฝฝๆฐๆฎๅคฑ่ดฅ,่ฏท้่ฏ.',
// showCancel: false,
// });
// self.setData({
// page: data.page - 1
// });
// }
// })
// .finally(function (response) {
// wx.hideLoading();
// wx.stopPullDownRefresh();
// });
// },
// //ๅ ่ฝฝๅ้กต
// loadMore: function (e) {
// var self = this;
// if (!self.data.isLastPage)
// {
// self.setData({
// page: self.data.page + 1
// });
// //console.log('ๅฝๅ้กต' + self.data.page);
// this.fetchPostsData(self.data);
// }
// else
// {
// wx.showToast({
// title: 'ๆฒกๆๆดๅคๅ
ๅฎน',
// mask: false,
// duration: 1000
// });
// }
// },
// // ่ทณ่ฝฌ่ณๆฅ็ๆ็ซ ่ฏฆๆ
// redictDetail: function (e) {
// // console.log('ๆฅ็ๆ็ซ ');
// var id = e.currentTarget.id,
// url = '../detail/detail?id=' + id;
// wx.navigateTo({
// url: url
// })
// },
// //้ฆ้กตๅพๆ ่ทณ่ฝฌ
// onNavRedirect:function(e){
// var redicttype = e.currentTarget.dataset.redicttype;
// var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
// var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;
// var extraData = e.currentTarget.dataset.extraData == null ? '' : e.currentTarget.dataset.extraData;
// if (redicttype == 'apppage') {//่ทณ่ฝฌๅฐๅฐ็จๅบๅ
้จ้กต้ข
// wx.navigateTo({
// url: url
// })
// }
// else if (redicttype == 'webpage')//่ทณ่ฝฌๅฐweb-viewๅ
ๅต็้กต้ข
// {
// url = '../webpage/webpage?url=' + url;
// wx.navigateTo({
// url: url
// })
// }
// else if (redicttype == 'miniapp')//่ทณ่ฝฌๅฐๅ
ถไปapp
// {
// wx.navigateToMiniProgram({
// appId: appid,
// envVersion: 'release',
// path: url,
// extraData: extraData,
// success(res) {
// // ๆๅผๆๅ
// },
// fail: function (res) {
// console.log(res);
// }
// })
// }
// },
// // ่ทณ่ฝฌ่ณๆฅ็ๅฐ็จๅบๅ่กจ้กต้ขๆๆ็ซ ่ฏฆๆ
้กต
// redictAppDetail: function (e) {
// // console.log('ๆฅ็ๆ็ซ ');
// var id = e.currentTarget.id;
// var redicttype = e.currentTarget.dataset.redicttype;
// var url = e.currentTarget.dataset.url == null ? '':e.currentTarget.dataset.url;
// var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;
// if (redicttype == 'detailpage')//่ทณ่ฝฌๅฐๅ
ๅฎน้กต
// {
// url = '../detail/detail?id=' + id;
// wx.navigateTo({
// url: url
// })
// }
// if (redicttype == 'apppage') {//่ทณ่ฝฌๅฐๅฐ็จๅบๅ
้จ้กต้ข
// wx.navigateTo({
// url: url
// })
// }
// else if (redicttype == 'webpage')//่ทณ่ฝฌๅฐweb-viewๅ
ๅต็้กต้ข
// {
// url = '../webpage/webpage?url=' + url;
// wx.navigateTo({
// url: url
// })
// }
// else if (redicttype == 'miniapp')//่ทณ่ฝฌๅฐๅ
ถไปapp
// {
// wx.navigateToMiniProgram({
// appId: appid,
// envVersion: 'release',
// path: url,
// success(res) {
// // ๆๅผๆๅ
// },
// fail: function (res) {
// console.log(res);
// }
// })
// }
// },
// //่ฟๅ้ฆ้กต
// redictHome: function (e) {
// //console.log('ๆฅ็ๆ็ฑปๅซไธ็ๆ็ซ ');
// var id = e.currentTarget.dataset.id,
// url = '/pages/index/index';
// wx.switchTab({
// url: url
// });
// }
// })
|
/*globals $*/
/**
* Check A Box v0.1.4
* http://immobilienscout24.github.io/CheckABox/
*
*/
$.fn.checkABox=function(m,d){var q={checkedClass:"ui-icon-on",uncheckedClass:"",iconClass:"ui-icon icon-ok",iconHtml:"<span></span>"},p=$(this),g="relatedIcon";
function e(s){return s.prop(g);}function h(s){return s.is(":checked");}function f(t,s){t.prop("checked",s);t.trigger("change");}function n(u,t){var s=e(u);
s.toggleClass(q.checkedClass,t);s.toggleClass(q.uncheckedClass,!t);}function k(){p.each(function(t,s){s=$(s);n(s,h(s));});}function r(s,t){f(s,t);n(s,t);
}function b(s){r(s,!h(s));}function i(s){return(h(s)?q.checkedClass:q.uncheckedClass);}function j(s){if($(s.currentTarget).is("label")){s.stopPropagation();
}}function c(s){return(s.is("input[type='radio']")&&h(s));}function a(s){return function(t){j(t);t.preventDefault();if(!c(s)){b(s);k();}};}function o(s){s.each(function(u,t){var w,v,x=$(t);
if(!x.prop("checkABoxEnabled")){x.prop("checkABoxEnabled",true);w=$(q.iconHtml);w.addClass(i(x)+" "+q.iconClass);x.prop(g,w);v=x.parent();v.on("mousedown",a(x));
v.on("touchstart",a(x));w.insertBefore(x);}});}function l(s){d=d||{};$.extend(q,d);if(typeof s==="boolean"){r(p,s);}else{if(s==="toggle"){b(p);}else{if(s==="bind"){o(p);
}else{if(s==="refresh"){k();}}}}}l(m);return p;}; |
import React, {Component} from 'react';
import {
Text,
View,
TouchableOpacity,
Image,
Dimensions,
FlatList,
StyleSheet
} from 'react-native';
import { connect } from 'react-redux';
import Header from'../../Header';
let backIcon = require('../../../../media/appIcon/backList.png');
const url = 'http://192.168.1.32:8080/ShoppingApp/images/product/';
const { width, height } = Dimensions.get('window');
class ListProduct extends Component<Props> {
//hร m mแป menu
openMenu(){
this.props.navigation.toggleDrawer();
}
//hร m mแป trang tรฌn kiแบฟm
openSearch(){
this.props.navigation.navigate('SearchScreen');
}
render() {
const { navigate } = this.props.navigation;
const { topProducts } = this.props;
const product = this.props.navigation.getParam('product', null);
const { name } = product;
const {
container,
wrapper, header, titleStyle,
productContainer, productInfo, productImage,
lastRowInfo, dotStyle,
txtName, txtPrice, txtMaterial, txtColor, txtDetail
} = styles;
return (
<View style={ container }>
<Header onOpen={this.openMenu.bind(this)} onSearch={this.openSearch.bind(this)}/>
<View style={ wrapper }>
<View style={ header }>
<TouchableOpacity onPress={() => {this.props.navigation.goBack()}}>
<Image source={ backIcon } style={{ width: 30, height: 30 }}/>
</TouchableOpacity>
<Text style={ titleStyle }>{ name }</Text>
<View style={{ width: 30 }}/>
</View>
<FlatList
data={topProducts}
renderItem = { ({item}) =>{
return (
<View style={ productContainer }>
<Image source={{uri: `${url}${item.images[0]}`}} style={ productImage }/>
<View style={ productInfo }>
<Text style={ txtName }>{item.name}</Text>
<Text style={ txtPrice }>{item.price}$</Text>
<Text style={ txtMaterial }>Material: {item.material}</Text>
<View style={ lastRowInfo }>
<Text style={ txtColor }>Color: {item.color}</Text>
<View
style={{
backgroundColor: item.color.toLowerCase(),
width: 14,
height: 14,
borderRadius: 7
}}
/>
<TouchableOpacity
onPress={() => {navigate('DetailScreen', {product: item})}}
>
<Text style={ txtDetail }>Show Detail</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}}
/>
</View>
</View>
);
}
}
function mapStateToProps(state){
return {
topProducts: state.topProducts
};
}
export default connect(mapStateToProps)(ListProduct);
const styles = StyleSheet.create({
container: {
flex: 1,
},
wrapper: {
margin: 10,
padding: 10,
backgroundColor: '#fff',
flex: 1
},
header: {
height: height/20,
backgroundColor: '#fff',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 10
},
titleStyle: {
color: '#B10D65',
fontFamily: 'avenir',
fontSize: 20
},
productContainer: {
paddingTop: 10,
paddingHorizontal: 10,
marginBottom: 20,
flexDirection: 'row',
borderTopWidth: 1,
borderTopColor: '#F0F0F0'
},
productInfo: {
flex: 1,
justifyContent: 'space-between',
paddingHorizontal: 20
},
productImage: {
width: 80,
height: (80 * 452) / 361
},
lastRowInfo: {
flexDirection: 'row',
justifyContent: 'space-between'
},
txtName: {
fontFamily: 'avenir',
color: '#BCBCBC',
fontSize: 18,
fontWeight: '400'
},
txtPrice: {
fontFamily: 'avenir',
color: '#B10D65',
},
txtColor: {
fontFamily: 'avenir'
},
txtDetail: {
fontFamily: 'avenir',
color: '#B10D65',
}
}); |
$(document).ready(function() {
var id_region = $('#txtId_region').val();
cargar_fb();
function cargar_fb() {
funcion = 'cargarFb';
$.post('../../Controlador/region_controler.php', { funcion, id_region }, (response) => {
const obj = JSON.parse(response);
let template = `<div id="fb-root"></div>
<br><br>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/es_LA/sdk.js#xfbml=1&version=v10.0" nonce="5vkyCoVX"></script>
<div class="fb-page" data-href="${obj.facebook}" data-tabs="timeline" data-width="" data-height="" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true">
<blockquote cite="${obj.facebook}" class="fb-xfbml-parse-ignore"><a href="${obj.facebook}"></a></blockquote>
</div>`;
$('#divFb').html(template);
});
}
}); |
var RenewalFeeEscrow = artifacts.require('./RenewalFeeEscrow.sol')
let SUBNETDAO_FOR_RECEIVING_PAYMENTS = ''
module.exports = function (deployer, network, accounts) {
if (network === 'development') {
SUBNETDAO_FOR_RECEIVING_PAYMENTS = accounts[9]
}
console.log("Constructor arguments: ", SUBNETDAO_FOR_RECEIVING_PAYMENTS)
deployer.deploy(RenewalFeeEscrow, SUBNETDAO_FOR_RECEIVING_PAYMENTS)
}
|
import React from "react";
import Modal from "@material-ui/core/Modal";
import Backdrop from "@material-ui/core/Backdrop";
import Fade from "@material-ui/core/Fade";
import { useStyles } from "./style";
export default function ModalUntility(props) {
const classes = useStyles();
const { item, open, setOpen } = props;
const handleClose = () => {
setOpen(false);
};
return (
<div>
<Modal
className={classes.modal}
open={open}
onClose={handleClose}
closeAfterTransition
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}
>
<Fade in={open}>
<div className={classes.paper}>
<iframe
width="100%"
height="100%"
src={item}
loading="true"
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
aria-controls
></iframe>
</div>
</Fade>
</Modal>
</div>
);
}
|
import styled from 'styled-components';
const H1 = styled.h1`
color: #04476d;
font-size: calc(1.65vw + 1.65vh + 1.65vmin);
font-weight: 800;
line-height: 1.5;
margin: 0;
padding: 0 0 0 0;
text-align: center;
`;
export default H1; |
/**
* Backbone object for all file actions functionality.
*/
var Files = Backbone.Model.extend({
defaults: {
},
initialize: function () {
},
/**
* Rename a file.
*
* @param {string} promptQuestionString Translated version of "Which file to rename?".
* @param {string} namespace The namespace.
* @param {string} parentPath Parent path of the folder to rename.
* @param {string} oldName Old name of the file to be renamed.
* @param {object} element The object that calls this function, usually of type HTMLAnchorElement)
*/
renameFile: function (promptQuestionString, namespace, parentPath, oldName, element)
{
var newName = window.prompt(promptQuestionString, oldName);
if (!newName.length) {
return;
}
$.ajax({
url: bolt.paths.async + 'renamefile',
type: 'POST',
data: {
namespace: namespace,
parent: parentPath,
oldname: oldName,
newname: newName
},
success: function (result) {
document.location.reload();
},
error: function () {
console.log('Something went wrong renaming this file!');
}
});
},
/**
* Delete a file from the server.
*
* @param {string} namespace
* @param {string} filename
* @param {object} element
*/
deleteFile: function (namespace, filename, element) {
if (!confirm('Are you sure you want to delete ' + filename + '?')) {
return;
}
$.ajax({
url: bolt.paths.async + 'deletefile',
type: 'POST',
data: {
namespace: namespace,
filename: filename
},
success: function (result) {
console.log('Deleted file ' + filename + ' from the server');
// If we are on the files table, remove image row from the table, as visual feedback
if (element !== null) {
$(element).closest('tr').slideUp();
}
// TODO delete from Stack if applicable
},
error: function () {
console.log('Failed to delete the file from the server');
}
});
},
duplicateFile: function (namespace, filename) {
$.ajax({
url: bolt.paths.async + 'duplicatefile',
type: 'POST',
data: {
namespace: namespace,
filename: filename
},
success: function (result) {
document.location.reload();
},
error: function () {
console.log('Something went wrong duplicating this file!');
}
});
}
});
|
/*
https://www.codewars.com/kata/valid-parentheses/train/csharp
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Constraints
0 <= input.length <= 100
*/
// Split into array
// Move through array, if ( +1, if ) -1
// If it ever drops below zero, fail. If it ends at 0, pass
function validParentheses(parens){
const arr = parens.split('');
let count = 0;
arr.forEach((par, i) => {
if (par === ')') {
count++;
} else if (par === '(') {
count--;
} else {
return false;
}
if (count < 0) {
return false;
}
});
return count === 0;
} |
import React, { useState } from 'react';
import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
import './Account.css'
import IconButton from "@material-ui/core/IconButton";
import Tooltip from "@material-ui/core/Tooltip";
import AddIcon from "@material-ui/icons/Add";
import { Link } from 'react-router-dom';
const Example = (props) => {
const [dropdownOpen, setOpen] = useState(false);
const toggle = () => setOpen(!dropdownOpen);
return (
<ButtonDropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle style={{backgroundColor:'white', border: 'none'}} caret>
<Tooltip title={"Tambah Data Karyawan"}>
<IconButton>
<AddIcon />
</IconButton>
</Tooltip>
</DropdownToggle>
<DropdownMenu>
<Link to="/add-account"><DropdownItem>Add Acount</DropdownItem></Link>
</DropdownMenu>
</ButtonDropdown>
);
}
export default Example;
|
import React from 'react'
import ReactDOM from 'react-dom'
class UserInfo extends React.Component {
constructor(props) {
super(props)
this.state = { message: '', region: {} }
this.changeProvice = this.changeProvice.bind(this)
this.changeCity = this.changeCity.bind(this)
this.submit = this.submit.bind(this)
}
componentDidMount() {
// console.log(location.search)
let uuid = urlParameter('uuid')
if (!!!uuid) {
this.setState({ message: '้พๆฅๆฅๆบๅผๅธธใ' })
}
let elProvince = document.getElementById('province')
axios({
method: 'GET',
url: './assets/data/list.json',
responseType: 'json'
}).then(response => {
this.setState({ region: response.data })
for (let key in response.data) {
if (key.substr(2, 4) === '0000') {
elProvince.options.add(new Option(response.data[key], key))
}
}
})
}
changeProvice() {
let elProvince = document.getElementById('province')
let elCity = document.getElementById('city')
let elDistrict = document.getElementById('district')
elCity.innerHTML = ''
elCity.options.add(new Option('ๆช้ๆฉ', ''))
elDistrict.innerHTML = ''
elDistrict.options.add(new Option('ๆช้ๆฉ', ''))
for (let key in this.state.region) {
if (key.substr(0, 2) === elProvince.value.substr(0, 2) && key.substr(2, 4) !== '0000') {
if (elProvince.options[elProvince.options.selectedIndex].text.indexOf('ๅธ') !== -1) {
elCity.options.add(new Option(this.state.region[key], key))
} else {
if (key.substr(4, 2) === '00') {
elCity.options.add(new Option(this.state.region[key], key))
}
}
}
}
}
changeCity() {
let elProvince = document.getElementById('province')
let elCity = document.getElementById('city')
let elDistrict = document.getElementById('district')
elDistrict.innerHTML = ''
elDistrict.options.add(new Option('ๆช้ๆฉ', ''))
if (elProvince.options[elProvince.options.selectedIndex].text.indexOf('ๅธ') !== -1) {
return false
}
for (let key in this.state.region) {
if (key.substr(0, 4) === elCity.value.substr(0, 4) && key.substr(4, 2) !== '00') {
elDistrict.options.add(new Option(this.state.region[key], key))
}
}
}
submit() {
this.setState({ message: '' })
let elName = document.getElementById('name')
let elMobile = document.getElementById('mobile')
let elProvince = document.getElementById('province')
let elCity = document.getElementById('city')
let elAddress = document.getElementById('address')
let elPostage = document.getElementById('postage')
if (!!!elName.value || !!!elMobile.value || !!!elProvince.value || !!!elCity.value || !!!elAddress.value || !!!elPostage.checked) {
this.setState({ message: '่ฏทๅฎๆดๅกซๅ็จๆทไฟกๆฏใ' })
return false
}
axios({
method: 'POST',
url: './api/customer/',
data: {
user_uuid: urlParameter('uuid'),
name: elName.value,
mobile: elMobile.value,
province: elProvince.value,
city: elCity.value,
district: document.getElementById('district').value,
address: elAddress.value,
postage: elPostage.checked
},
responseType: 'json'
}).then(response => {
console.log(response.data)
})
}
render() {
return (
<div className="row">
<div className="col-12">
<h2>ๅกซๅ็จๆทไฟกๆฏ</h2>
<hr/>
<div className="form-group">
<label className="text-primary">ๅงๅ</label>
<input type="text" id="name" className="form-control"/>
<label className="text-secondary">่ฏทๅกซๅๆถ่ดงไบบๅ
จๅ๏ผ่ตๆไธ่ฏฆ๏ผไธไบๅ่ดง๏ผ</label>
</div>
<div className="form-group">
<label className="text-primary">ๆๆบๅท</label>
<input type="text" id="mobile" className="form-control"/>
<label className="text-secondary">่ฏทๅกซๅๆญฃ็กฎๆๆบๅท็ ๏ผๅท็ ไธ่ฏฆ๏ผไธไบๅ่ดง๏ผ</label>
</div>
<div className="form-group">
<label className="text-primary">ๆถ่ดงๅฐๅ</label>
<select id="province" className="form-control" onChange={this.changeProvice}>
<option value="">ๆช้ๆฉ</option>
</select>
<br/>
<select id="city" className="form-control" onChange={this.changeCity}>
<option value="">ๆช้ๆฉ</option>
</select>
<br/>
<select id="district" className="form-control">
<option value="">ๆช้ๆฉ</option>
</select>
<span className="text-secondary">ๆฐ็ใ่ฅฟ่ใๆธฏๆพณๅฐ็ญๅฐๅบไธๅไธๆญคๆฌกๆดปๅจ</span>
</div>
<div className="form-group">
<label className="text-primary">่ฏฆ็ป่ก้ๅฐๅ</label>
<input type="text" id="address" className="form-control"/>
<span className="text-danger">่ฏทๅกซๅๅฟ/ไนก/่ก้/่ทฏ/ๅท๏ผ่ตๆไธ่ฏฆ๏ผไธไบๅ่ดง๏ผ</span>
</div>
<div className="form-check">
<input type="radio" value="postage" id="postage" className="form-check-input"/>
<label className="text-primary" htmlFor="postage">ๆฅๅ้ฎ่ดน่ช็(่ฟ่ดน+ไฟไปท่ดนๅจ19่ณ39ๅ
ไน้ด๏ผๆถๅฐ่ดงๆฏไป็ปๅฟซ้ๅฐๅฅๅณๅฏ๏ผๅ่ฟๅฐๅบๆ้ซไธ่ถ
่ฟ39ๅ
๏ผไธๆฅๅ็ไธไบๅ่ดง๏ผ๏ผ</label>
</div>
<hr/>
<div className="col-12">
<span className="text-danger">ๆธฉ้ฆจๆ็คบ๏ผ</span>
<span className="text-primary">
ๆฌๆฌกๆดปๅจ้้2000ๅฅ๏ผๆขๅฎๆชๆญข๏ผไป
ๅ
่ดนๆไพ็คผๅ๏ผ้ฎ่ดน่ช็ใ
</span>
<br/>
<br/>
</div>
{this.state.message && <div className="col-12 alert alert-danger">
{this.state.message}
</div>
}
<div className="col-12">
<button type="button" id="submit" className="btn btn-outline-dark btn-block" onClick={this.submit}>
ๅกซๅๅฎๆฏ๏ผ็กฎ่ฎคๆไบคใ
</button>
</div>
</div>
</div>
)
}
}
ReactDOM.render(
<UserInfo/>,
document.getElementById('app')
) |
import { mount, shallowMount } from '@vue/test-utils'
import Pageables from '@/store/Pageables.js'
describe('Pageables.vue', () => {
describe('Getters', () => {
it ('returns all the pages', () => {
const state = {
all: []
}
expect(Pageables.getters['all'](state)).toEqual([]);
})
it ('returns all the pages by id', () => {
const state = {
all: [
{id: 1, title: 'Foo'},
{id: 2, title: 'Bar'},
{id: 3, title: 'Baz'},
{id: 2, title: 'BarBaz'},
{id: 4, title: 'Foobar'},
]
}
expect(Pageables.getters['allById'](state)(2)).toEqual([
{id: 2, title: 'Bar'},
{id:2, title: 'BarBaz'}
]);
})
it ('returns the first page by id', () => {
const state = {
all: [
{id: 1, title: 'Foo'},
{id: 2, title: 'Bar'},
{id: 3, title: 'Baz'},
{id: 2, title: 'BarBaz'},
{id: 4, title: 'Foobar'},
]
}
expect(Pageables.getters['byId'](state)(2)).toEqual({id: 2, title: 'Bar'});
})
it ('returns elements by a page slug', () => {
const state = {
dictionary: {
'page-1': [{id: 1, title: 'Foo'}],
'page-2': [{id: 2, title: 'Bar'}],
'page-3': [{id: 3, title: 'Baz'}],
}
}
expect(Pageables.getters['byPageSlug'](state)('page-2')).toEqual([{id: 2, title: 'Bar'}]);
expect(Pageables.getters['byPageSlug'](state)('page-4')).toEqual([]);
})
it ('returns an empty array if page slug does not exist', () => {
const state = {
dictionary: {
}
}
expect(Pageables.getters['byPageSlug'](state)('page-4')).toEqual([]);
})
it ('returns elements count by a page slug', () => {
const state = {
dictionary: {
'page-1': [{id: 1, title: 'Foo'}],
'page-2': [{id: 2, title: 'Bar'}],
'page-3': [{id: 3, title: 'Baz'}],
}
}
expect(Pageables.getters['countByPageSlug'](state)('page-2')).toEqual(1);
expect(Pageables.getters['countByPageSlug'](state)('page-4')).toEqual(0);
})
it ('asserts that a page has an element by id', () => {
const state = {
dictionary: {
'page-1': [{id: 1, title: 'Foo'}],
'page-2': [{id: 2, title: 'Bar'}],
'page-3': [{id: 3, title: 'Baz'}],
}
}
expect(Pageables.getters['pageHas'](state)({
page: {slug: 'page-1'},
record: {id: 1}
})).toEqual(true);
expect(Pageables.getters['pageHas'](state)({
page: {slug: 'page-1'},
record: {id: 2}
})).toEqual(false);
})
it ('asserts that a page has an element by id and pivot property', () => {
const state = {
dictionary: {
'page-1': [
{id: 1, title: 'Foo', pivot: {preferences: {color: 'red'}}},
{id: 1, title: 'Bar', pivot: {preferences: {color: 'blue'}}},
],
}
}
expect(Pageables.getters['pageHasWithPivot'](state)({
page: {slug: 'page-1'},
record: {id: 1, pivot: {preferences: {color: 'red'}}},
pivotProperty: 'color',
})).toEqual(true);
expect(Pageables.getters['pageHasWithPivot'](state)({
page: {slug: 'page-1'},
record: {id: 1, pivot: {preferences: {color: 'green'}}},
pivotProperty: 'color',
})).toEqual(false);
})
it ('returns an array of ids for pageables associated with a page', () => {
const state = {
dictionary: {
'page-1': [
{id: 1, title: 'Foo'},
{id: 3, title: 'Bar'},
],
'page-2': [
{id: 2, title: 'Baz'}
]
}
}
expect(Pageables.getters['idsForPage'](state)({slug: 'page-1'})).toEqual([1, 3]);
})
it ('returns an array of ids and pivot data for pageables associated with a page', () => {
const state = {
dictionary: {
'page-1': [
{id: 1, title: 'Foo', pivot: {preferences: {color: 'red'}}},
{id: 3, title: 'Bar', pivot: {preferences: {color: 'blue'}}},
],
'page-2': [
{id: 2, title: 'Foo', pivot: {preferences: {color: 'green'}}},
],
}
}
expect(Pageables.getters['idsAndPivotForPage'](state)({
page: {slug: 'page-1'},
pivotProperty: 'color',
})).toEqual([
{id: 1, color: 'red'},
{id: 3, color: 'blue'}
]);
})
})
describe('Mutators', () => {
let payload;
beforeEach (() => {
payload = {
'_library': [{id: 1, title: 'Red'}, {id: 2, title: 'Green'}, {id: 3, title: 'Blue'}],
'page-1': [{id: 1, title: 'Red'}],
'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}],
'page-3': [],
}
})
it ('initializes the store', () => {
const state = {
all: [],
dictionary: {},
}
expect(state.all).toEqual([]);
expect(state.dictionary).toEqual({});
Pageables.mutations['initialize'](state, payload)
expect(state.all).toBe(payload['_library']);
expect(state.dictionary).toBe(payload);
})
it ('initializes the store without a library property', () => {
const state = {
all: [],
dictionary: {},
}
let dictionary = {
'page-1': [{id: 1, title: 'Red'}],
'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}],
'page-3': [],
}
expect(state.all).toEqual([]);
expect(state.dictionary).toEqual({});
Pageables.mutations['initialize'](state, dictionary)
expect(state.all).toBe(dictionary);
expect(state.dictionary).toBe(dictionary);
})
it ('removes a pageable by id', () => {
const state = {
all: [{id: 1}, {id: 2}, {id: 3}, {id: 2}]
}
expect(state.all.length).toBe(4);
Pageables.mutations['removeById'](state, 2);
expect(state.all.length).toBe(2);
})
it ('overrides a pageable by id', () => {
const state = {
all: [
{id: 1, title: 'Red'},
{id: 2, title: 'Green'},
{id: 3, title: 'Blue'},
{id: 2, title: 'Brown'}
]
}
expect(state.all.length).toBe(4);
expect(state.all[1]).toEqual({id: 2, title: 'Green'});
expect(state.all[3]).toEqual({id: 2, title: 'Brown'});
Pageables.mutations['overrideById'](state, {
id: 2,
record: {id: 2, title: 'Orange'}
});
expect(state.all.length).toBe(4);
expect(state.all[1]).toEqual({id: 2, title: 'Orange'});
expect(state.all[3]).toEqual({id: 2, title: 'Orange'});
})
it ('adds a pageable to the library', () => {
const state = {
all: [
{id: 1, title: 'Red'},
{id: 2, title: 'Green'},
{id: 3, title: 'Blue'},
]
}
expect(state.all.length).toBe(3);
Pageables.mutations['add'](state, {id: 4, title: 'Orange'});
expect(state.all.length).toBe(4);
})
it ('adds a pageable to a page by slug', () => {
const state = {
dictionary: {
'page-1': [{id: 1, title: 'Red'}],
'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}],
'page-3': [],
}
}
expect(state.dictionary['page-1'].length).toBe(1);
Pageables.mutations['addToPage'](state, {
page: {id: 1, slug: 'page-1'},
record: {id: 4, title: 'Orange'}
});
expect(state.dictionary['page-1'].length).toBe(2);
})
it ('removes a pageable from a page by slug', () => {
const state = {
dictionary: {
'page-1': [{id: 1, title: 'Red'}],
'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}],
'page-3': [],
}
}
expect(state.dictionary['page-2'].length).toBe(2);
Pageables.mutations['removeFromPage'](state, {
page: {slug: 'page-2'},
record: {id: 3}
});
expect(state.dictionary['page-2'].length).toBe(1);
})
it ('removes a pageable from a page by index', () => {
const state = {
dictionary: {
'page-1': [{id: 1, title: 'Red'}],
'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}],
'page-3': [],
}
}
expect(state.dictionary['page-2'].length).toBe(2);
Pageables.mutations['removeFromPageByIndex'](state, {
page: {slug: 'page-2'},
index: 0
});
expect(state.dictionary['page-2'].length).toBe(1);
expect(state.dictionary['page-2'][0]).toEqual({id: 3, title: 'Blue'});
})
it ('removes a pageable from a page by id and by pivot', () => {
const state = {
dictionary: {
'page-1': [
{id: 1, title: 'Foo', pivot: {preferences: {color: 'red'}}}
],
'page-2': [
{id: 2, title: 'Bar', pivot: {preferences: {color: 'lime'}}},
{id: 2, title: 'Bar', pivot: {preferences: {color: 'green'}}},
{id: 3, title: 'Baz', pivot: {preferences: {color: 'blue'}}}
],
'page-3': [],
}
}
expect(state.dictionary['page-2'].length).toBe(3);
Pageables.mutations['removeFromPageByIdAndPivot'](state, {
page: {slug: 'page-2'},
record: {id: 2, pivot: {preferences: {color: 'green'}}},
pivotProperty: 'color'
});
expect(state.dictionary['page-2'].length).toBe(2);
expect(state.dictionary['page-2'][0].title).toEqual('Bar');
expect(state.dictionary['page-2'][0].pivot.preferences.color).toEqual('lime');
expect(state.dictionary['page-2'][1].title).toEqual('Baz');
expect(state.dictionary['page-2'][1].pivot.preferences.color).toEqual('blue');
})
describe('Modify pages pageables if the page has none', () => {
let state;
beforeEach (() => {
state = {
dictionary: {}
}
})
it ('adds a pageable to a page by slug', () => {
expect(Object.keys(state.dictionary).length).toBe(0);
Pageables.mutations['addToPage'](state, {
page: {id: 1, slug: 'page-4'},
record: {id: 4, title: 'Orange'}
});
expect(Object.keys(state.dictionary).length).toBe(1);
expect(state.dictionary['page-4'].length).toBe(1);
})
it ('removes a pageable from a page by slug', () => {
expect(Object.keys(state.dictionary).length).toBe(0);
Pageables.mutations['removeFromPage'](state, {
page: {slug: 'page-2'},
record: {id: 3}
});
expect(Object.keys(state.dictionary).length).toBe(1);
})
it ('removes a pageable from a page by index', () => {
expect(Object.keys(state.dictionary).length).toBe(0);
Pageables.mutations['removeFromPageByIndex'](state, {
page: {slug: 'page-2'},
index: 0
});
expect(Object.keys(state.dictionary).length).toBe(1);
})
it ('removes a pageable from a page by id and by pivot', () => {
expect(Object.keys(state.dictionary).length).toBe(0);
Pageables.mutations['removeFromPageByIdAndPivot'](state, {
page: {slug: 'page-4'},
record: {id: 2, pivot: {preferences: {color: 'green'}}},
pivotProperty: 'color'
});
expect(Object.keys(state.dictionary).length).toBe(1);
})
})
})
}) |
/**
* ํ๋ฉด ์ด๊ธฐํ - ํ๋ฉด ๋ก๋์ ์๋ ํธ์ถ ๋จ
*/
function _Initialize() {
// ๋จ์ํ๋ฉด์์ ์ฌ์ฉ๋ ์ผ๋ฐ ์ ์ญ ๋ณ์ ์ ์
$NC.setGlobalVar({
// ์ฒดํฌํ ์ ์ฑ
๊ฐ
policyVal: {
LI420: "" // ์ฌ๊ณ ๊ด๋ฆฌ ๊ธฐ์ค
},
printOptions: [{
PRINT_INDEX: 0,
PRINT_COMMENT: "์
๊ณ ๋ผ๋ฒจ ์ถ๋ ฅ"
}],
// ์ค๋ฅธ์ชฝ ํ๋จ ๊ทธ๋ฆฌ๋ NEW๋ฒํผ ํด๋ฆญ์๋ง๋ค 1์ฉ ์ฆ๊ฐ
SEQ_NO: 0
});
// ๊ทธ๋ฆฌ๋ ์ด๊ธฐํ
grdMasterInitialize();
grdDetailInitialize();
grdSubInitialize();
grdSub1Initialize();
// ์กฐํ์กฐ๊ฑด - ๋ฌผ๋ฅ์ผํฐ ์ธํ
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CSUSERCENTER",
P_QUERY_PARAMS: $NC.getParams({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_CENTER_CD: "%"
})
}, {
selector: "#cboQCenter_Cd",
codeField: "CENTER_CD",
nameField: "CENTER_NM",
onComplete: function() {
$NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD);
// ์ ์ฑ
์ฝ๋ ์ทจ๋
setPolicyValInfo();
}
});
// ์กฐํ์กฐ๊ฑด - ์
๊ณ ๊ตฌ๋ถ ์ธํ
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CMCODE",
P_QUERY_PARAMS: $NC.getParams({
P_CODE_GRP: "INOUT_CD",
P_CODE_CD: "%",
P_SUB_CD1: "E1",
P_SUB_CD2: "E2"
})
}, {
selector: "#cboQInout_Cd",
codeField: "CODE_CD",
nameField: "CODE_NM",
fullNameField: "CODE_CD_F",
addAll: true
});
// ์ถ๊ฐ ์กฐํ์กฐ๊ฑด ์ฌ์ฉ
$NC.setInitAdditionalCondition();
// ๋ธ๋๋ ์ด๊ธฐ๊ฐ ์ค์
$NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD);
$NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM);
$("#btnQBu_Cd").click(showUserBuPopup);
$("#btnQBrand_Cd").click(showBuBrandPopup);
$("#btnQVendor_Cd").click(showVendorPopup);
// ๋ธ๋๋์ ์ํ์ฌ ์ฝ๋ ๊ฐ ์ค์
$NC.setValue("#edtQCust_Cd", $NC.G_USERINFO.CUST_CD);
// ๋ถํ ๊ตฌ๋ถ ์ด๊ธฐ๊ฐ ์ค์ (์ฒดํฌ)
$NC.setValue("#rgbQSplit_Div1", "1");
// ์ถ๊ณ ์ผ์์ ๋ฌ๋ ฅ์ด๋ฏธ์ง ์ค์
$NC.setInitDatePicker("#dtpQInbound_Date");
// ์๋๋ถํ ํด๋ฆญ ์ด๋ฒคํธ
$("#btnAutoSplit").click(autoSplit);
// ์ ์ฅ๊ถํ์ด ์๋ ๊ฒฝ์ฐ๋ง ์๋๋ถํ ๊ฐ๋ฅ
var permission = $NC.getProgramPermission();
$NC.setEnable("#btnAutoSplit", permission.canSave);
}
function _OnLoaded() {
// $NC.setInitSplitter("#divRightView", "h", 200);
}
/**
* ํ๋ฉด ๋ฆฌ์ฌ์ด์ฆ Offset ์ธํ
*/
function _SetResizeOffset() {
$NC.G_OFFSET.leftViewWidth = 800;
$NC.G_OFFSET.RightViewHeight = 100;
$NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight;
//$NC.G_OFFSET.rightBottomHeightOffset = $("#divSplitInfo").outerHeight();
// $NC.G_OFFSET.rightBottom1HeightOffset = $("#divSplitInfo").outerHeight();
}
/**
* Window Resize Event - Window Size ์กฐ์ ์ ํธ์ถ ๋จ
*/
function _OnResize(parent) {
var clientWidth = parent.width() - $NC.G_OFFSET.leftViewWidth - $NC.G_LAYOUT.nonClientWidth;
var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight;
var testHeight = Math.ceil(clientHeight / 3);
$NC.resizeContainer("#divLeftView", $NC.G_OFFSET.leftViewWidth, clientHeight);
$NC.resizeContainer("#divRightView", clientWidth, testHeight * 3 );
// Grid ์ฌ์ด์ฆ ์กฐ์
$NC.resizeGrid("#grdMaster", $NC.G_OFFSET.leftViewWidth, clientHeight - $NC.G_LAYOUT.header);
// Grid ์ฌ์ด์ฆ ์กฐ์
$NC.resizeGrid("#grdDetail", clientWidth, testHeight - $NC.G_LAYOUT.header );
var test1 = $NC.G_LAYOUT.header - 10 + 'px';
// Grid ์ฌ์ด์ฆ ์กฐ์
$NC.resizeGrid("#grdSub1", clientWidth, testHeight - $NC.G_LAYOUT.header
);
// Grid ์ฌ์ด์ฆ ์กฐ์
$NC.resizeGrid("#grdSub", clientWidth, testHeight - $NC.G_LAYOUT.header
);
}
/**
* Input, Select Change Event ์ฒ๋ฆฌ
*
* @param e
* ์ด๋ฒคํธ ํธ๋ค๋ฌ
* @param view
* ๋์ Object
*/
function _OnConditionChange(e, view, val) {
// ์กฐํ ์กฐ๊ฑด์ Object Change
var id = view.prop("id").substr(4).toUpperCase();
switch (id) {
case "CENTER_CD":
setPolicyValInfo();
break;
//์ฌ์
๋ถ Key ์
๋ ฅ
case "BU_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
P_QUERY_PARAMS = {
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: val
};
O_RESULT_DATA = $NP.getUserBuInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onUserBuPopup(O_RESULT_DATA[0]);
} else {
$NP.showUserBuPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onUserBuPopup, onUserBuPopup);
}
return;
// ๋ธ๋๋ Key ์
๋ ฅ
case "BRAND_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
var BU_CD = $NC.getValue("#edtQBu_Cd");
P_QUERY_PARAMS = {
P_BU_CD: BU_CD,
P_BRAND_CD: val
};
O_RESULT_DATA = $NP.getBuBrandInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onBuBrandPopup(O_RESULT_DATA[0]);
} else {
$NP.showBuBrandPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onBuBrandPopup, onBuBrandPopup);
}
return;
case "VENDOR_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
var CUST_CD = $NC.getValue("#edtQCust_Cd");
P_QUERY_PARAMS = {
P_CUST_CD: CUST_CD,
P_VENDOR_CD: val,
P_VIEW_DIV: "2"
};
O_RESULT_DATA = $NP.getVendorInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onVendorPopup(O_RESULT_DATA[0]);
} else {
$NP.showVendorPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onVendorPopup, onVendorPopup);
}
return;
case "INBOUND_DATE":
$NC.setValueDatePicker(view, val, "๊ฒ์ ์
๊ณ ์ผ์๋ฅผ ์ ํํ ์
๋ ฅํ์ญ์์ค.");
break;
}
// ํ๋ฉดํด๋ฆฌ์ด
onChangingCondition();
}
/**
* Input Change Event - Input, Select Change ์ ํธ์ถ ๋จ
*/
function _OnInputChange(e, view, val) {
}
/**
* Inquiry Button Event - ๋ฉ์ธ ์๋จ ์กฐํ ๋ฒํผ ํด๋ฆญ์ ํธ์ถ ๋จ
*/
function _Inquiry() {
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(CENTER_CD)) {
alert("๋ฌผ๋ฅ์ผํฐ๋ฅผ ์ ํํ์ญ์์ค.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var BU_CD = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(BU_CD)) {
alert("์ฌ์
๋ถ์ฝ๋๋ฅผ ์
๋ ฅํ์ญ์์ค.");
$NC.setFocus("#edtQBrand_Cd");
return;
}
var INOUND_DATE = $NC.getValue("#dtpQInbound_Date");
if ($NC.isNull(INOUND_DATE)) {
alert("์
๊ณ ์ผ์๋ฅผ ์
๋ ฅํ์ญ์์ค.");
$NC.setFocus("#dtpQInbound_Date");
return;
}
var BRAND_CD = $NC.getValue("#edtQBrand_Cd", true);
var VENDOR_CD = $NC.getValue("#edtQVendor_Cd", true);
var ITEM_CD = $NC.getValue("#edtQItem_Cd", true);
var ITEM_NM = $NC.getValue("#edtQItem_Nm", true);
var INOUT_CD = $NC.getValue("#cboQInout_Cd");
// ์กฐํ์ ์ ์ญ ๋ณ์ ๊ฐ ์ด๊ธฐํ
$NC.setInitGridVar(G_GRDMASTER);
$NC.setInitGridVar(G_GRDDETAIL);
$NC.setInitGridVar(G_GRDSUB);
G_GRDMASTER.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_INBOUND_DATE: INOUND_DATE,
P_INOUT_CD: INOUT_CD,
P_VENDOR_CD: VENDOR_CD,
P_BRAND_CD: BRAND_CD,
P_ITEM_CD: ITEM_CD,
P_ITEM_NM: ITEM_NM
});
// ๋ฐ์ดํฐ ์กฐํ
$NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster);
}
/**
* New Button Event - ๋ฉ์ธ ์๋จ ์ ๊ท ๋ฒํผ ํด๋ฆญ์ ํธ์ถ ๋จ
*/
function _New() {
}
/**
* Save Button Event - ๋ฉ์ธ ์๋จ ์ ์ฅ ๋ฒํผ ํด๋ฆญ์ ํธ์ถ ๋จ
*/
function _Save() {
if (G_GRDMASTER.data.getLength() === 0 || G_GRDDETAIL.data.getLength() === 0 || G_GRDSUB.data.getLength() === 0) {
alert("์ ์ฅํ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.");
return;
}
// ํ์ฌ ์์ ๋ชจ๋๋ฉด
if (G_GRDSUB.view.getEditorLock().isActive()) {
G_GRDSUB.view.getEditorLock().commitCurrentEdit();
}
var totConfirmQty = 0;
var rowDetailData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow);
var saveDS = [ ];
var rowCount = G_GRDSUB.data.getLength();
for ( var row = 0; row < rowCount; row++) {
var rowData = G_GRDSUB.data.getItem(row);
totConfirmQty += Number(rowData.CONFIRM_QTY);
if (rowData.CRUD !== "R") {
if (!grdSubOnBeforePost(row)) {
return;
}
var saveData = {
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_INBOUND_DATE: rowData.INBOUND_DATE,
P_INBOUND_NO: rowData.INBOUND_NO,
P_LINE_NO: rowData.LINE_NO,
P_INBOUND_SEQ: rowData.INBOUND_SEQ,
P_LOCATION_CD: rowData.LOCATION_CD,
P_ENTRY_QTY: rowData.CONFIRM_QTY,
P_CONFIRM_QTY: rowData.CONFIRM_QTY,
P_CRUD: rowData.CRUD
};
saveDS.push(saveData);
}
}
if (totConfirmQty != Number(rowDetailData.ENTRY_QTY)) {
alert("๋ฑ๋ก์๋(" + rowDetailData.ENTRY_QTY + ")๊ณผ \nํ์ ์๋์ ํฉ(" + totConfirmQty + ")์ด ์ผ์นํ์ง ์์ต๋๋ค.");
return;
}
if (saveDS.length > 0) {
$NC.serviceCall("/LI05010E/save.do", {
P_DS_MASTER: $NC.toJson(saveDS),
P_USER_ID: $NC.G_USERINFO.USER_ID
}, onSave, onSaveError);
}
}
/**
* Delete Button Event - ๋ฉ์ธ ์๋จ ์ญ์ ๋ฒํผ ํด๋ฆญ์ ํธ์ถ ๋จ
*/
function _Delete() {
}
/**
* Cancel Button Event - ๋ฉ์ธ ์๋จ ์ทจ์ ๋ฒํผ ํด๋ฆญ์ ํธ์ถ ๋จ
*/
function _Cancel() {
var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTER, {
selectKey: "INBOUND_NO"
});
var lastKeyValD = $NC.getGridLastKeyVal(G_GRDDETAIL, {
selectKey: "LINE_NO"
});
var lastKeyValS = $NC.getGridLastKeyVal(G_GRDSUB, {
selectKey: "INBOUND_SEQ"
});
_Inquiry();
G_GRDMASTER.lastKeyVal = lastKeyVal;
G_GRDDETAIL.lastKeyVal = lastKeyValD;
G_GRDSUB.lastKeyVal = lastKeyValS;
}
/**
* Print Button Event - ๋ฉ์ธ ์๋จ ์ถ๋ ฅ ๋ฒํผ ํด๋ฆญ์ ํธ์ถ ๋จ
*
* @param printIndex
* ์ ํํ ์ถ๋ ฅ๋ฌผ Index
*/
function _Print(printIndex, printName) {
if (G_GRDDETAIL.data.getLength() == 0 || G_GRDDETAIL.lastRow == null) {
alert("์ถ๋ ฅํ ๋ฐ์ดํฐ๋ฅผ ์ ํํ์ญ์์ค.");
return;
}
var rowData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow);
// ์
๊ณ ๋ผ๋ฒจ
if (printIndex == 0) {
// ์ถ๋ ฅ ํธ์ถ
$NC.G_MAIN.showPrintPreview({
reportDoc: "common/LABEL_PALLET",
queryId: "WR.RS_LABEL_PALLET02",
queryParams: {
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_INBOUND_DATE: rowData.INBOUND_DATE,
P_INBOUND_NO: rowData.INBOUND_NO,
P_LINE_NO: rowData.LINE_NO,
P_PROCESS_GRP: "LI"
}
});
}
}
function grdMasterOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "INBOUND_NO",
field: "INBOUND_NO",
name: "์
๊ณ ๋ฒํธ",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "VENDOR_NM",
field: "VENDOR_NM",
name: "๊ณต๊ธ์ฒ",
minWidth: 150
});
$NC.setGridColumn(columns, {
id: "INOUT_NM",
field: "INOUT_NM",
name: "์
๊ณ ๊ตฌ๋ถ",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "ORDER_DATE",
field: "ORDER_DATE",
name: "์์ ์ผ์",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "ORDER_NO",
field: "ORDER_NO",
name: "์์ ๋ฒํธ",
minWidth: 70,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BU_DATE",
field: "BU_DATE",
name: "์ ํ์ผ์",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BUD_NO",
field: "BU_NO",
name: "์ ํ๋ฒํธ",
minWidth: 100
});
$NC.setGridColumn(columns, {
id: "REMARK1",
field: "REMARK1",
name: "๋น๊ณ ",
minWidth: 130
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* ์ผ์ชฝ๊ทธ๋ฆฌ๋ ์ด๊ธฐํ
*/
function grdMasterInitialize() {
var options = {
frozenColumn: 1
};
// Grid Object, DataView ์์ฑ ๋ฐ ์ด๊ธฐํ
$NC.setInitGridObject("#grdMaster", {
columns: grdMasterOnGetColumns(),
queryId: "LI05010E.RS_MASTER",
sortCol: "INBOUND_NO",
gridOptions: options
});
G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll);
}
function grdDetailOnGetColumns(policyLI420) {
if ($NC.isNull(policyLI420)) {
policyLI420 = "1";
}
var columns = [ ];
$NC.setGridColumn(columns, {
id: "LINE_NO",
field: "LINE_NO",
name: "์๋ฒ",
minWidth: 50,
cssClass: "align-right"
});
$NC.setGridColumn(columns, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "์ํ์ฝ๋",
minWidth: 90
});
$NC.setGridColumn(columns, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "์ํ๋ช
",
minWidth: 150
});
$NC.setGridColumn(columns, {
id: "ITEM_SPEC",
field: "ITEM_SPEC",
name: "๊ท๊ฒฉ",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "BRAND_NM",
field: "BRAND_NM",
name: "๋ธ๋๋๋ช
",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "ITEM_STATE_F",
field: "ITEM_STATE_F",
name: "์ํ",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "ITEM_LOT",
field: "ITEM_LOT",
name: "LOT๋ฒํธ",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "QTY_IN_BOX",
field: "QTY_IN_BOX",
name: "์
์",
minWidth: 70,
cssClass: "align-right"
});
$NC.setGridColumn(columns, {
id: "ORDER_QTY",
field: "ORDER_QTY",
name: "์์ ์๋",
minWidth: 70,
cssClass: "align-right"
});
$NC.setGridColumn(columns, {
id: "ENTRY_QTY",
field: "ENTRY_QTY",
name: "๋ฑ๋ก์๋",
minWidth: 70,
cssClass: "align-right"
});
$NC.setGridColumn(columns, {
id: "ENTRY_BOX",
field: "ENTRY_BOX",
name: "๋ฑ๋กBOX",
minWidth: 70,
cssClass: "align-right"
});
$NC.setGridColumn(columns, {
id: "ENTRY_EA",
field: "ENTRY_EA",
name: "๋ฑ๋กEA",
minWidth: 70,
cssClass: "align-right"
});
$NC.setGridColumn(columns, {
id: "ENTRY_WEIGHT",
field: "ENTRY_WEIGHT",
name: "๋ฑ๋ก์ค๋",
minWidth: 70,
cssClass: "align-right"
});
if (policyLI420 == "2") {
$NC.setGridColumn(columns, {
id: "VALID_DATE",
field: "VALID_DATE",
name: "์ ํต๊ธฐํ",
minWidth: 100,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BATCH_NO",
field: "BATCH_NO",
name: "์ ์กฐ๋ฐฐ์น๋ฒํธ",
minWidth: 100
});
}
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* ์ค๋ฅธ์ชฝ ์๋จ ๊ทธ๋ฆฌ๋ ์ด๊ธฐํ
*/
function grdDetailInitialize() {
var options = {
frozenColumn: 2
};
// Grid Object, DataView ์์ฑ ๋ฐ ์ด๊ธฐํ
$NC.setInitGridObject("#grdDetail", {
columns: grdDetailOnGetColumns(),
queryId: "LI05010E.RS_DETAIL",
sortCol: "LINE_NO",
gridOptions: options
});
G_GRDDETAIL.view.onSelectedRowsChanged.subscribe(grdDetailOnAfterScroll);
G_GRDDETAIL.height = 300;
$("#grdDetail").height(G_GRDDETAIL.height);
}
function grdSubOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "์ํ์ฝ๋",
minWidth: 120
});
$NC.setGridColumn(columns, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "์ํ๋ช
",
minWidth: 180
});
$NC.setGridColumn(columns, {
id: "CONFIRM_QTY",
field: "CONFIRM_QTY",
name: "ํ์ ์๋",
minWidth: 70,
cssClass: "align-right",
editor: Slick.Editors.Number,
editorOptions: {
isKeyField: true
}
});
$NC.setGridColumn(columns, {
id: "INBOUND_SEQ",
field: "INBOUND_SEQ",
name: "์
๊ณ SEQ",
minWidth: 150,
cssClass: "align-center"
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ ๊ทธ๋ฆฌ๋ ์ด๊ธฐํ
*/
function grdSubInitialize() {
var options = {
editable: true,
autoEdit: true,
frozenColumn: 1
};
// Grid Object, DataView ์์ฑ ๋ฐ ์ด๊ธฐํ
$NC.setInitGridObject("#grdSub", {
columns: grdSubOnGetColumns(),
queryId: "LI05010E.RS_SUB1",
sortCol: "LOCATION_ID",
gridOptions: options
});
G_GRDSUB.view.onSelectedRowsChanged.subscribe(grdSubOnAfterScroll);
G_GRDSUB.view.onBeforeEditCell.subscribe(grdSubOnBeforeEditCell);
G_GRDSUB.view.onCellChange.subscribe(grdSubOnCellChange);
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ๊ทธ๋ฆฌ๋์ ์
๋ ฅ์ฒดํฌ ์ฒ๋ฆฌ
*/
function grdSubOnBeforePost(row) {
var rowData = G_GRDSUB.data.getItem(row);
if ($NC.isNull(rowData)) {
return true;
}
/*
// ์ญ์ ๋ฐ์ดํฐ๋ฉด Return
if (rowData.CRUD == "D") {
return true;
}
// ์ ๊ท์ผ ๋ ํค ๊ฐ์ด ์์ผ๋ฉด ์ ๊ท ์ทจ์
if (rowData.CRUD == "N") {
}
*/
if (rowData.CRUD != "R") {
if ($NC.isNull(rowData.CONFIRM_QTY) || Number(rowData.CONFIRM_QTY) == 0) {
alert("ํ์ ์๋์ ์ ํํ ์
๋ ฅํ์ญ์์ค.");
$NC.setGridSelectRow(G_GRDSUB, {
selectRow: row,
activeCell: G_GRDSUB.view.getColumnIndex("CONFIRM_QTY"),
editMode: true
});
return false;
}
}
return true;
}
/**
* ์ค์ชฝ ๋ฅธํ๋จ๊ทธ๋ฆฌ๋ ํธ์ง๋ถ๊ฐ๋ฅ
*
* @param e
* @param args
* @returns {Boolean}
*/
function grdSubOnBeforeEditCell(e, args) {
return true;
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ๊ทธ๋ฆฌ๋์ ์
๊ฐ ๋ณ๊ฒฝ์ ์ฒ๋ฆฌ
*
* @param e
* @param args
*/
function grdSubOnCellChange(e, args) {
var rowData = args.item;
if ($NC.isNull(rowData.CONFIRM_QTY)) rowData.CONFIRM_QTY = "0";
if (Number(rowData.CONFIRM_QTY) < 0) {
alert("ํ์ ์๋์๋ 0๋ณด๋ค ์์๊ฐ์ ์
๋ ฅํ ์ ์์ต๋๋ค.");
rowData.CONFIRM_QTY = 0;
$NC.setGridSelectRow(G_GRDSUB, {
selectRow: G_GRDSUB.lastRow,
activeCell: G_GRDSUB.view.getColumnIndex("CONFIRM_QTY"),
editMode: true
});
return;
}
if ($NC.isNull(rowData.CRUD) || rowData.CRUD === "R") {
rowData.CRUD = "U";
}
G_GRDSUB.data.updateItem(rowData.id, rowData);
// ๋ง์ง๋ง ์ ํ Row ์์ ์ํ๋ก ๋ณ๊ฒฝ
G_GRDSUB.lastRowModified = true;
G_GRDSUB.view.getCanvasNode().focus();
}
/*---------------test-----------------*/
function grdSub1OnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "์ํ์ฝ๋",
minWidth: 120
});
$NC.setGridColumn(columns, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "์ํ๋ช
",
minWidth: 180
});
$NC.setGridColumn(columns, {
id: "CONFIRM_QTY",
field: "CONFIRM_QTY",
name: "ํ์ ์๋",
minWidth: 70,
cssClass: "align-right",
editor: Slick.Editors.Number,
editorOptions: {
isKeyField: true
}
});
$NC.setGridColumn(columns, {
id: "INBOUND_SEQ",
field: "INBOUND_SEQ",
name: "์
๊ณ SEQ",
minWidth: 150,
cssClass: "align-center"
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ ๊ทธ๋ฆฌ๋ ์ด๊ธฐํ
*/
function grdSub1Initialize() {
var options = {
editable: true,
autoEdit: true,
frozenColumn: 1
};
// Grid Object, DataView ์์ฑ ๋ฐ ์ด๊ธฐํ
$NC.setInitGridObject("#grdSub1", {
columns: grdSub1OnGetColumns(),
queryId: "LI05010E.RS_SUB1",
sortCol: "LOCATION_ID",
gridOptions: options
});
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ๊ทธ๋ฆฌ๋์ ์
๋ ฅ์ฒดํฌ ์ฒ๋ฆฌ
*/
function grdSub1OnBeforePost(row) {
var rowData = G_GRDSUB1.data.getItem(row);
if ($NC.isNull(rowData)) {
return true;
}
/*
// ์ญ์ ๋ฐ์ดํฐ๋ฉด Return
if (rowData.CRUD == "D") {
return true;
}
// ์ ๊ท์ผ ๋ ํค ๊ฐ์ด ์์ผ๋ฉด ์ ๊ท ์ทจ์
if (rowData.CRUD == "N") {
}
*/
if (rowData.CRUD != "R") {
if ($NC.isNull(rowData.CONFIRM_QTY) || Number(rowData.CONFIRM_QTY) == 0) {
alert("ํ์ ์๋์ ์ ํํ ์
๋ ฅํ์ญ์์ค.");
$NC.setGridSelectRow(G_GRDSUB1, {
selectRow: row,
activeCell: G_GRDSUB1.view.getColumnIndex("CONFIRM_QTY"),
editMode: true
});
return false;
}
}
return true;
}
/**
* ์ค์ชฝ ๋ฅธํ๋จ๊ทธ๋ฆฌ๋ ํธ์ง๋ถ๊ฐ๋ฅ
*
* @param e
* @param args
* @returns {Boolean}
*/
function grdSub1OnBeforeEditCell(e, args) {
return true;
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ๊ทธ๋ฆฌ๋์ ์
๊ฐ ๋ณ๊ฒฝ์ ์ฒ๋ฆฌ
*
* @param e
* @param args
*/
function grdSub1OnCellChange(e, args) {
var rowData = args.item;
if ($NC.isNull(rowData.CONFIRM_QTY)) rowData.CONFIRM_QTY = "0";
if (Number(rowData.CONFIRM_QTY) < 0) {
alert("ํ์ ์๋์๋ 0๋ณด๋ค ์์๊ฐ์ ์
๋ ฅํ ์ ์์ต๋๋ค.");
rowData.CONFIRM_QTY = 0;
$NC.setGridSelectRow(G_GRDSUB, {
selectRow: G_GRDSUB1.lastRow,
activeCell: G_GRDSUB1.view.getColumnIndex("CONFIRM_QTY"),
editMode: true
});
return;
}
if ($NC.isNull(rowData.CRUD) || rowData.CRUD === "R") {
rowData.CRUD = "U";
}
G_GRDSUB1.data.updateItem(rowData.id, rowData);
// ๋ง์ง๋ง ์ ํ Row ์์ ์ํ๋ก ๋ณ๊ฒฝ
G_GRDSUB1.lastRowModified = true;
G_GRDSUB1.view.getCanvasNode().focus();
}
/**
* ๊ฒ์์กฐ๊ฑด์ ์ฌ์
๋ถ ๊ฒ์ ํ์
ํด๋ฆญ
*/
function showUserBuPopup() {
$NP.showUserBuPopup({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: "%"
}, onUserBuPopup, function() {
$NC.setFocus("#edtQBu_Cd", true);
});
}
/**
* ์ฌ์
๋ถ ๊ฒ์ ๊ฒฐ๊ณผ
*
* @param seletedRowData
*/
function onUserBuPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQBu_Cd", resultInfo.BU_CD);
$NC.setValue("#edtQBu_Nm", resultInfo.BU_NM);
} else {
$NC.setValue("#edtQBu_Cd");
$NC.setValue("#edtQBu_Nm");
$NC.setFocus("#edtQBu_Cd", true);
}
$NC.setValue("#edtQBrand_Cd");
$NC.setValue("#edtQBrand_Nm");
onChangingCondition();
setPolicyValInfo();
}
/**
* ๊ฒ์์กฐ๊ฑด์ ๋ธ๋๋ ๊ฒ์ ํ์
ํด๋ฆญ
*/
function showBuBrandPopup() {
var BU_CD = $NC.getValue("#edtQBu_Cd");
$NP.showBuBrandPopup({
P_BU_CD: BU_CD,
P_BRAND_CD: "%"
}, onBuBrandPopup, function() {
$NC.setFocus("#edtQBrand_Cd", true);
});
}
/**
* ๋ธ๋๋ ๊ฒ์ ๊ฒฐ๊ณผ
*
* @param seletedRowData
*/
function onBuBrandPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQBrand_Cd", resultInfo.BRAND_CD);
$NC.setValue("#edtQBrand_Nm", resultInfo.BRAND_NM);
} else {
$NC.setValue("#edtQBrand_Cd");
$NC.setValue("#edtQBrand_Nm");
$NC.setFocus("#edtQBrand_Cd", true);
}
onChangingCondition();
}
/**
* ๊ฒ์์กฐ๊ฑด์ ๋ฐฐ์ก์ฒ ๊ฒ์ ์ด๋ฏธ์ง ํด๋ฆญ
*/
function showVendorPopup() {
var CUST_CD = $NC.getValue("#edtQCust_Cd");
$NP.showVendorPopup({
queryParams: {
P_CUST_CD: CUST_CD,
P_VENDOR_CD: "%",
P_VIEW_DIV: "1"
}
}, onVendorPopup, function() {
$NC.setFocus("#edtQVendor_Cd", true);
});
}
function onVendorPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQVendor_Cd", resultInfo.VENDOR_CD);
$NC.setValue("#edtQVendor_Nm", resultInfo.VENDOR_NM);
} else {
$NC.setValue("#edtQVendor_Cd");
$NC.setValue("#edtQVendor_Nm");
$NC.setFocus("#edtQVendor_Cd", true);
}
onChangingCondition();
}
/**
* ์ผ์ชฝ๊ทธ๋ฆฌ๋ ํ ํด๋ฆญ์ ์ฒ๋ฆฌ
*
* @param e
* @param args
*/
function grdMasterOnAfterScroll(e, args) {
var row = args.rows[0];
var rowData = G_GRDMASTER.data.getItem(row);
if (G_GRDMASTER.lastRow != null) {
if (row == G_GRDMASTER.lastRow) {
e.stopImmediatePropagation();
return;
}
}
// ์กฐํ์ ์ ์ญ ๋ณ์ ๊ฐ ์ด๊ธฐํ
$NC.setInitGridVar(G_GRDDETAIL);
onGetDetail({
data: null
});
G_GRDDETAIL.queryParams = $NC.getParams({
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_INBOUND_DATE: rowData.INBOUND_DATE,
P_INBOUND_NO: rowData.INBOUND_NO
});
// ๋ฐ์ดํฐ ์กฐํ
$NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDDETAIL), onGetDetail);
// ์๋จ ํ์ฌ๋ก์ฐ/์ด๊ฑด์ ์
๋ฐ์ดํธ
$NC.setGridDisplayRows("#grdMaster", row + 1);
}
/**
* ์ค๋ฅธ์ชฝ ์๋จ ๊ทธ๋ฆฌ๋ ํ ํด๋ฆญ์ ์ฒ๋ฆฌ
*
* @param e
* @param args
*/
function grdDetailOnAfterScroll(e, args) {
var row = args.rows[0];
if (G_GRDDETAIL.lastRow != null) {
if (row == G_GRDDETAIL.lastRow) {
e.stopImmediatePropagation();
return;
}
}
// ์กฐํ์ ์ ์ญ ๋ณ์ ๊ฐ ์ด๊ธฐํ
$NC.setInitGridVar(G_GRDSUB);
onGetSub({
data: null
});
var rowData = G_GRDDETAIL.data.getItem(row);
G_GRDSUB.queryParams = $NC.getParams({
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_INBOUND_DATE: rowData.INBOUND_DATE,
P_INBOUND_NO: rowData.INBOUND_NO,
P_LINE_NO: rowData.LINE_NO
});
// ๋ฐ์ดํฐ ์กฐํ
$NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDSUB), onGetSub);
// ์๋จ ํ์ฌ๋ก์ฐ/์ด๊ฑด์ ์
๋ฐ์ดํธ
$NC.setGridDisplayRows("#grdDetail", row + 1);
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ๊ทธ๋ฆฌ๋ ํ ํด๋ฆญ์ ํ๋จ๊ทธ๋ฆฌ๋ ๊ฐ ์ทจ๋ํด์ ํ์ ์ฒ๋ฆฌ
*
* @param e
* @param args
*/
function grdSubOnAfterScroll(e, args) {
var row = args.rows[0];
if (G_GRDSUB.lastRow != null) {
if (row == G_GRDSUB.lastRow) {
e.stopImmediatePropagation();
return;
}
}
// ์๋จ ํ์ฌ๋ก์ฐ/์ด๊ฑด์ ์
๋ฐ์ดํธ
$NC.setGridDisplayRows("#grdSub", row + 1);
}
/**
* ์กฐํ๋ฒํผ ํด๋ฆญํ ์ผ์ชฝ ๊ทธ๋ฆฌ๋์ ๋ฐ์ดํฐ ํ์์ฒ๋ฆฌ
*/
function onGetMaster(ajaxData) {
$NC.setInitGridData(G_GRDMASTER, ajaxData);
if (G_GRDMASTER.data.getLength() > 0) {
if ($NC.isNull(G_GRDMASTER.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDMASTER, 0);
} else {
$NC.setGridSelectRow(G_GRDMASTER, {
selectKey: "INBOUND_NO",
selectVal: G_GRDMASTER.lastKeyVal
});
}
} else {
$NC.setGridDisplayRows("#grdMaster", 0, 0);
// ์ค๋ถ๋ฅ ์ ์ญ ๋ณ์ ๊ฐ ์ด๊ธฐํ
$NC.setInitGridVar(G_GRDDETAIL);
onGetDetail({
data: null
});
}
// ๋ฒํผ ํ์ฑํ ์ฒ๋ฆฌ
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "1";
$NC.G_VAR.buttons._cancel = "1";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "1";
$NC.setInitTopButtons($NC.G_VAR.buttons, $NC.G_VAR.printOptions);
}
/**
* ์ค๋ฅธ์ชฝ ์๋จ ๊ทธ๋ฆฌ๋์ ๋ฐ์ดํฐ ํ์์ฒ๋ฆฌ
*/
function onGetDetail(ajaxData) {
$NC.setInitGridData(G_GRDDETAIL, ajaxData);
if (G_GRDDETAIL.data.getLength() > 0) {
if ($NC.isNull(G_GRDDETAIL.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDDETAIL, 0);
} else {
$NC.setGridSelectRow(G_GRDDETAIL, {
selectKey: "LINE_NO",
selectVal: G_GRDDETAIL.lastKeyVal
});
}
} else {
$NC.setGridDisplayRows("#grdDetail", 0, 0);
// ์๋ถ๋ฅ ์ ์ญ ๋ณ์ ๊ฐ ์ด๊ธฐํ
$NC.setInitGridVar(G_GRDSUB);
onGetSub({
data: null
});
}
G_GRDDETAIL.view.getCanvasNode().focus();
}
/**
* ์ค๋ฅธ์ชฝ ํ๋จ ๊ทธ๋ฆฌ๋์ ๋ฐ์ดํฐ ํ์์ฒ๋ฆฌ
*/
function onGetSub(ajaxData) {
$NC.setInitGridData(G_GRDSUB, ajaxData);
if (G_GRDSUB.data.getLength() > 0) {
if ($NC.isNull(G_GRDSUB.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDSUB, 0);
} else {
$NC.setGridSelectRow(G_GRDSUB, {
selectKey: "INBOUND_SEQ",
selectVal: G_GRDSUB.lastKeyVal
});
}
} else {
$NC.setGridDisplayRows("#grdSub", 0, 0);
}
$NC.G_VAR.SEQ_NO = 0;
}
/**
* ์ ์ฅ ์ฒ๋ฆฌ ์ฑ๊ณต ํ์ ๊ฒฝ์ฐ ์ฒ๋ฆฌ
*/
function onSave(ajaxData) {
var resultData = $NC.toArray(ajaxData);
if (!$NC.isNull(resultData)) {
if (resultData.RESULT_DATA !== "OK") {
alert(resultData.RESULT_DATA);
return;
}
}
var rowData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow);
var lastKeyVal = $NC.getGridLastKeyVal(G_GRDSUB, {
selectKey: "INBOUND_SEQ"
});
// ์กฐํ์ ์ ์ญ ๋ณ์ ๊ฐ ์ด๊ธฐํ
$NC.setInitGridVar(G_GRDSUB);
G_GRDSUB.queryParams = $NC.getParams({
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_INBOUND_DATE: rowData.INBOUND_DATE,
P_INBOUND_NO: rowData.INBOUND_NO,
P_LINE_NO: rowData.LINE_NO
});
// ๋ฐ์ดํฐ ์กฐํ
$NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDSUB), onGetSub);
G_GRDSUB.lastKeyVal = lastKeyVal;
}
/**
* ์ ์ฅ ์ฒ๋ฆฌ ์คํจ ํ์ ๊ฒฝ์ฐ ์ฒ๋ฆฌ
*/
function onSaveError(ajaxData) {
$NC.onError(ajaxData);
}
/**
* ๊ฒ์ํญ๋ชฉ ๊ฐ ๋ณ๊ฒฝ์ ํ๋ฉด ํด๋ฆฌ์ด
*/
function onChangingCondition() {
$NC.clearGridData(G_GRDMASTER);
$NC.clearGridData(G_GRDDETAIL);
$NC.clearGridData(G_GRDSUB);
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "1";
$NC.setInitTopButtons($NC.G_VAR.buttons, $NC.G_VAR.printOptions);
}
/**
* ์๋๋ถํ ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ ์ฒ๋ฆฌ
*/
function autoSplit() {
if (G_GRDMASTER.data.getLength() === 0 || G_GRDDETAIL.data.getLength() === 0 || G_GRDSUB.data.getLength() === 0) {
alert("์๋๋ถํ ๋์ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค.");
return;
}
var SPLIT_VAL = $NC.getValue("#edtQSplit_Val");
if ($NC.isNull(SPLIT_VAL) || Number(SPLIT_VAL) == 0) {
alert("์๋๋ฅผ ์ ํํ ์
๋ ฅํ์ญ์์ค.");
$NC.setFocus("#edtQSplit_Val");
return;
}
var result = confirm("์๋๋ถํ ํ์๊ฒ ์ต๋๊น?");
if (!result) return;
var rowData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow);
var SPLIT_FLAG = $(':radio[name="rgbQSplit_Div"]:checked').val();
$NC.serviceCall("/LI05010E/setSplitPallet.do", {
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: rowData.CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_INBOUND_DATE: rowData.INBOUND_DATE,
P_INBOUND_NO: rowData.INBOUND_NO,
P_LINE_NO: rowData.LINE_NO,
P_SPLIT_FLAG: SPLIT_FLAG,
P_SPLIT_VAL: SPLIT_VAL,
P_USER_ID: $NC.G_USERINFO.USER_ID
})
}, onSave, onSaveError);
}
/**
* ์ ์ฑ
์ ๋ณด ์ทจ๋
*/
function setPolicyValInfo() {
$NC.G_VAR.policyVal.LI420 = "";
// ๊ฐ ์ค๋ฅ ์ฒดํฌ๋ ์ํจ
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
for ( var POLICY_CD in $NC.G_VAR.policyVal) {
// ๋ฐ์ดํฐ ์กฐํ
$NC.serviceCall("/LI05010E/callSP.do", {
P_QUERY_ID: "WF.GET_POLICY_VAL",
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_POLICY_CD: POLICY_CD
})
}, onGetPolicyVal);
}
}
/**
* ์ ์ฑ
์ ๋ณด ์ทจ๋ํ ์ฒ๋ฆฌ
*
* @param ajaxData
*/
function onGetPolicyVal(ajaxData) {
var resultData = $NC.toArray(ajaxData);
if (!$NC.isNull(resultData)) {
if (resultData.O_MSG === "OK") {
$NC.G_VAR.policyVal[resultData.P_POLICY_CD] = resultData.O_POLICY_VAL;
if (resultData.P_POLICY_CD != "LI420") {
return;
}
// ์ฌ๊ณ ๊ด๋ฆฌ๊ธฐ์ค์ ๋ฐ๋ผ ์ ํจ์ผ์/๋ฐฐ์น๋ฒํธ๋ณ ํ์/๋นํ์
var policyVal = resultData.O_POLICY_VAL;
G_GRDDETAIL.view.setColumns(grdDetailOnGetColumns(policyVal));
}
}
} |
var type_name=['ๆ่ฃ
้ๅ
','ๆๆบๆฐ็ ','็พๅฆ้ฅฐๅ','็พ่ดง้ฃๅ','่ฟๅจๆทๅค','ๅ
ถไป'];
var school_address=['็ๅฑฑๆ กๅบ','่่ๆ กๅบ','ๆๆฐดๆ กๅบ','ๅฃไบๆ กๅบ','่ฑ่ๆ กๅบ'];
//็ปๅพ
function drawImg(){
getProCount();
getUserCount();
getForderCount();
getForderCountZ();
}
//ๅ็ฑปๅๅ็ฑปๅซ็ป่ฎก
function getProCount(){
//alert(1);
var count=[];
var arr=getProType(7);
var type_val=[];
var url=baseurl+'product/getProCount';
//alert(url);
$.get(url,function(data){
//console.log(data.length);
for(var i=0;i<data.length;i++){
type_val.push(data[i]['ptype']);
count.push(parseInt(data[i]['id_count']));
}
if(arr.length!=type_val.length){
for(var j=0;j<arr.length;j++){
if(!contains(type_val,arr[j])){
count.splice(j,0,0);
}
}
}
//alert(count);
var option = {
title : {
text: 'ๅ็ง็ฑปๅๅๅๆๅ ๆฏไพ',
x:'center'
},
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
left: 'left',
data: type_name
},
series : [
{
name: 'ๆฐๆฎๅฑ็คบ',
type: 'pie',
radius : '55%',
center: ['50%', '60%'],
data:[
{value:count[0], name:type_name[0]},
{value:count[1], name:type_name[1]},
{value:count[2], name:type_name[2]},
{value:count[3], name:type_name[3]},
{value:count[4], name:type_name[4]},
{value:count[5], name:type_name[5]}
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
//$("#productCount").empty();
// ไธบechartsๅฏน่ฑกๅ ่ฝฝๆฐๆฎ
var myChart = echarts.init(document.getElementById('productCount'));
myChart.setOption(option);
var app={};
app.currentIndex=-1;
setInterval(function () {
var dataLen = option.series[0].data.length;
// ๅๆถไนๅ้ซไบฎ็ๅพๅฝข
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0,
dataIndex: app.currentIndex
});
app.currentIndex = (app.currentIndex + 1) % dataLen;
// ้ซไบฎๅฝๅๅพๅฝข
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: app.currentIndex
});
// ๆพ็คบ tooltip
myChart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: app.currentIndex
});
}, 2000);
});
}
//ๅๆ กๅบ็จๆทๆฐ้็ป่ฎก
function getUserCount(){
var url=baseurl+'user/getUserCount';
var address=[];
var arr=getProType(6);
// alert(arr);
var count=[];
$.get(url,function(data){
for(var i=0;i<data.length;i++){
//alert(data[i]['address']);
address.push(data[i]['address']);
count.push(data[i]['id_count']);
}
if(arr.length!=address.length){
for(var j=0;j<arr.length;j++){
if(!contains(address,arr[j])){
count.splice(j,0,0);
}
}
}
// alert(school_address);
// alert(count);
var option = {
color: ['#3398DB'],
title : {
text: 'ๅๆ กๅบ็จๆทๆฐ้็ป่ฎก',
x:'center'
},
tooltip : {
trigger: 'axis',
axisPointer : { // ๅๆ ่ฝดๆ็คบๅจ๏ผๅๆ ่ฝด่งฆๅๆๆ
type : 'shadow' // ้ป่ฎคไธบ็ด็บฟ๏ผๅฏ้ไธบ๏ผ'line' | 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis : [
{
type : 'category',
data : school_address,
axisTick: {
alignWithLabel: true
}
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'็จๆทๆฐ้',
type:'bar',
barWidth: '60%',
data:count
}
]
};
var myChart = echarts.init(document.getElementById('userCount'));
myChart.setOption(option);
});
}
//ๅๆ กๅบ่ฎขๅๆฐ้็ป่ฎก
function getForderCount(){
var url=baseurl+'forder/getForderCount';
var saddress=[];
var arr=getProType(6);
var count=[];
$.get(url,function(data){
for(var i=0;i<data.length;i++){
saddress.push(data[i]['saddress']);
count.push(data[i]['id_count']);
}
if(saddress.length!=arr.length){
for(var j=0;j<arr.length;j++){
if(!contains(saddress,arr[j])){
count.splice(j,0,0);
}
}
}
var option = {
title : {
text: 'ๅๆ กๅบ่ฎขๅๆฐ้ๆฏไพ',
x:'center'
},
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b}: {c} ({d}%)"
},
legend: {
orient: 'vertical',
x: 'left',
data:school_address
},
series: [
{
name:'็ป่ฎกๅๆ',
type:'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: 'center'
},
emphasis: {
show: true,
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
}
},
labelLine: {
normal: {
show: false
}
},
data:[
{value:count[0], name:school_address[0]},
{value:count[1], name:school_address[1]},
{value:count[2], name:school_address[2]},
{value:count[3], name:school_address[3]},
{value:count[4], name:school_address[4]}
]
}
]
};
var myChart = echarts.init(document.getElementById('forderCountBySchoolAddress'));
myChart.setOption(option);
});
}
/*
* ๅๆ กๅบ่ฎขๅๆฐ้ๆ็บฟๅพ
*/
function getForderCountZ(){
var url=baseurl+'forder/getForderCountZ';
var dateArr=[];
var count=[];
$.get(url,function(data){
for(var i=0;i<data.length;i++){
dateArr.push(data[i]['f_time']);
count.push(data[i]['id_count']);
}
var option = {
title: {
text: '่ฎขๅๆฐ้้ๆฅ็ป่ฎก'
},
tooltip: {
trigger: 'axis'
},
legend: {
data:'่ฎขๅๆฐ้'
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: dateArr
},
yAxis: {
type: 'value'
},
series: [
{
name:'่ฎขๅๆฐ้',
type:'line',
data:count
}
]
};
var myChart = echarts.init(document.getElementById('forderCountByZheXian'));
myChart.setOption(option);
});
}
//่ทๅๅๅ็ฑปๅๆฐ็ป
function getProType(val){
var arr=[];
for(var i=1;i<val;i++){
arr.push(i);
}
return arr;
}
//ๆฅ่ฏขๆไธๅ
็ด ๅจๆฐ็ปไธญๆฏๅฆๅญๅจ
function contains(arr, val) {
for ( var i = 0; i < arr.length; i++) {
if (arr[i] == val)
return true;
}
return false;
} |
/**
* Our Schema for Users
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Define the User Schema
var userSchema = new Schema({
firstname: { type: String, required: true },
lastname: { type: String, required: true },
ccs: { type: String, required: true, unique: true }
});
// The primary user model
var User = mongoose.model('User', userSchema);
module.exports = User;
|
import React, { useState } from 'react'
import axios from 'axios'
const AddEmployee = () => {
const [Hire, setHire] = useState({
firstName: '',
lastName: '',
email: '',
jobTitle: '',
city: '',
state: '',
zip: ''
})
const submitNewEmployee = async e => {
e.preventDefault()
console.log(Hire)
const resp = await axios.post(
`https://sdg-staff-directory-app.herokuapp.com/api/realcompany/Employees`,
Hire
)
console.log('employee form', resp.data)
}
const updateForm = e => {
setHire({
...Hire,
[e.target.id]: e.target.value
})
}
return (
<>
<section className="contact-header">
<h5 className="form-header">New Employee Form</h5>
</section>
<section className="form">
<form
action=""
className="col s12"
onSubmit={e => submitNewEmployee(e)}
>
{/* onSubmit={newEmployee} */}
<div className="row">
<div className="input-field col s6">
<i className="material-icons prefix">account_circle</i>
<input
id="firstName"
type="text"
className="validate"
// value={Hire.firstName}
onChange={updateForm}
/>
<label htmlFor="first_name">First Name</label>
</div>
<div className="row">
<div className="input-field col s6">
<input
id="lastName"
type="text"
className="validate"
// value={Hire.lastName}
onChange={updateForm}
/>
<label htmlFor="last_name">Last Name</label>
</div>
<div className="row email">
<div className="input-field col s6">
<i className="material-icons prefix">email</i>
<input
id="email"
type="text"
className="validate"
// value={Hire.email}
onChange={updateForm}
/>
<label htmlFor="email">Email</label>
<span
className="helper-text"
data-error="wrong"
data-success="right"
></span>
</div>
<div className="row">
<div className="input-field col s6">
<input
id="jobTitle"
type="text"
className="validate"
// value={Hire.job_Title}
onChange={updateForm}
/>
<label htmlFor="jobTitle">Job Title</label>
</div>
</div>
<div className="row city">
<div className="input-field col s2">
<i className="material-icons prefix">add_location</i>
<input
id="city"
type="text"
className="validate"
// value={Hire.city}
onChange={updateForm}
/>
<label htmlFor="city">City</label>
</div>
<div className="row">
<div className="input-field col s1">
<input
id="state"
type="text"
className="validate"
// value={Hire.state}
onChange={updateForm}
/>
<label htmlFor="state">State</label>
</div>
<div className="row">
<div className="input-field col s1">
<input
id="zip"
type="text"
className="validate"
// value={Hire.zip}
onChange={updateForm}
/>
<label htmlFor="zip">Zip</label>
</div>
</div>
<button
className="btn waves-effect waves-light"
type="submit"
name="action"
>
<i className="material-icons right">send</i>
Done
</button>
</div>
</div>
</div>
</div>
</div>
</form>
</section>
</>
)
}
export default AddEmployee
|
const mongoose =require("mongoose");
const mongoosePaginate = require('mongoose-paginate-v2');
Customer = new mongoose.Schema({
customer_name : {
type:String,
require:true
},
customer_code:{
type:String,
require:true
},
customer_email:{
type:String,
require:true
},
customer_contact:{
type:String,
require:true
},
customer_gst:{
type:String,
require:true
},
customer_pan:{
type:String,
require:true
},
customer_state:{
type:Number,
require:true
},
customer_city:{
type:Number,
require:true
},
customer_country:{
type:Number,
require:true
},
customer_status:{
type:Number,
default:1
},
added_date:{
type :Date,
default: Date.now
}
})
Customer.plugin(mongoosePaginate);
module.exports = mongoose.model('customer',Customer); |
$(function () {
// perloader js
$(window).on('load', function () {
$('.preloader').delay(2500).fadeOut(800);
})
// back to top js
let btn = $('#button');
$(window).scroll(function () {
if ($(window).scrollTop() > 200) {
btn.addClass('show');
} else {
btn.removeClass('show');
}
});
btn.on('click', function (e) {
e.preventDefault();
$('html, body').animate({ scrollTop: 0 }, 1000);
});
// sticky menu js
$(window).scroll(function () {
let scrolling = $(this).scrollTop();
if (scrolling > 0) {
$('.nav').addClass('fixed');
}
else {
$('.nav').removeClass('fixed');
}
})
//animation scroll js
let html_body = $('html, body');
$('nav a').on('click', function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
html_body.animate({
scrollTop: target.offset().top - 80
}, 1000);
return false;
}
}
});
}) |
import request from '@/utils/request'
const roles = {
// ่ทๅ้ป่ฎค้
็ฝฎ่ทฏ็ฑไฟกๆฏ
getDefaultRoutes(data) {
return request({ url: '/vueDefaultRouteGet', method: 'post', data })
},
// ่ทๅๆ้็ปๅ่กจ
getRoutesGroup(data){
return request({ url: '/group/get', method: 'post', data })
},
// ่ทๅๆ้็ปไฟกๆฏ
getRoutesData(data){
return request({ url: '/vueRoleGet', method: 'post', data })
},
// ็งป้คๆ้็ปไฟกๆฏ
delRoutesData(data){
return request({ url: '/vueRoleDel', method: 'post', data })
},
// ไฟฎๆนๆ้็ปไฟกๆฏ
editRoutesData(data){
return request({ url: '/vueRoleUpdate', method: 'post', data })
},
// ๆบๆไฟกๆฏ
orgTreeGet(data){
return request({ url: '/orgTreeGet', method: 'post', data })
},
// ่ง่ฒ
getRoleList(data) {
return request({ url: '/roleGetByPage', method: 'post', data })
},
}
export default roles |
// pages/report/2020/steps/consultant.js
Page({data: {}}) |
// learn 55.ะะฐะนะณััะปะฐะณั ััะฝะบัะธะนะณ ะฐัะธะณะปะฐะฝ ัะดะฐะผัะธะป ั
ัััะณะถาฏาฏะปัั
.
/*ะะฐัะตั --> ะะผััะฐะฝ --> ั
าฏะฝ */
/*ะะฐะนะณััะปะฐะณั ััะฝะบััะฝ ะฝััะธะนะณ ัะพะผะพะพั ะฑะธัะธะถ javascript delevoper-ััะด ะฐะผะฐะฐั ัะพั
ะธััะพะฝ ะทะฐััะธะผ ะฑะฐะนะดะฐะณ. ะญะฝะณะธะนะฝ
ััะฝะบัััะด ะถะธะถะธะณััั ะฑะธัะธะณะดัะณ. ะะฐะนะณััะปะฐะณั ััะฝะบััะณ ะทะฐะฐะฒะฐะป new ะณัะถ ะฑะธัะธะณะดัะฝั. */
// ะะฐะนะณััะปะฐะณั ััะฝะบั:
// function Materi(une) {
// this.une = une;
// this.haragdah = function () {
// console.log(this.une + "าฏะฝัััะน ะผะฐัะตัะธ ะฑะฐะนะฝะฐ. ");
// };
// }
// var m1 = new Materi(1000000);
// m1.haragdah();
/*
ัะฝั ััะฝะบั ะฝั haragdah ะณัั
ััะฝะบััะฝ copy ะดะพัะพั ะฑาฏั
ะผะฐัะตัะธ, ั
าฏะฝ, ะฐะผััะฐะฝ ั
ััะปะปะฐะฐะด broser-ัะฝ ัะฐะฝะฐั
ะพะนะด
ะฑะฐะนััััะปะดะฐะณ ะฑะพะปะพั
ะพะพั ัะดะฐะฐะฝ ะฐะถะธะปะปะฐะฝะฐ.าฎาฏะฝััั ัััะณะธะนะปัั
ะธะนะฝ ััะปะด ั
ะฐัะฐะณะดะฐั
object-ะธะนะณ ะผะฐัะตัะธะนะฝ prototype ะดะพัะพั
ั
ะธะนะณััะด ำฉะฝะณำฉ. ะาฏั
ััะฝะบั prototype ะพะฑัะตะบัะฐะน ะฑะฐะนะดะฐะณ.*/
// ะัะพะณััะฐะผะผะธััััะด ะตั ะฝั ะณะฐะดะฝะฐะฐั ำฉะณั ะฑะฐะนะณะฐะฐ าฏะฝั ะดะพัะพั ั
ะฐะดะณะฐะปะฐะณะดะฐะถ ะฑะฐะนะณะฐะฐ าฏะฝะธะนะฝ ะฝััะธะนะณ ะธะถะธะปั
ัะฝ ำฉะณัะธั
ัำฉะฝ ะฑะฐะนะดะฐะณ.
// function Materi(une) {
// this.une = une;
// }
// Materi.prototype.haragdah = function () {
// console.log(this.une + "าฏะฝัััะน ะผะฐัะตัะธ ะฑะฐะนะฝะฐ. ");
// }
// var m1 = new Materi(1000000);
// m1.haragdah();
// 1. ะฅะธะนั
ะฐะปั
ะฐะผ
// ะะพะพัั
ะถะธััั ะฑะพะป: ะะผััะฐะฝะณะฐะฐั ะพัะถ ะธัััะฝ une-ะธะนะณ call-ะฐั ะดะฐะถััะปะฐะฐะด ะดะฐัะฐะฐ ะฝั ะฐะผััะฐะฝั ะฑะฐะนะณััะปะปะฐะณัะฐะฐั ะพัะถ ะธัััะฝ
// ungu call ััะฝะบัะฐะฐั Materi ะดะฐะถััะปัะธั
ะฝะฐ.
// ะะฐัะตัะธ ััะฝะบั าฏาฏัะณัะถ ำฉะณัำฉะฝ
function Materi(une, ungu) {
this.ungu = ungu;
this.une = une;
}
// ะะฐัะตัะธ ะณะฐะดะฝะฐ haragdah ััะฝะบั าฏาฏัะณัะถ ำฉะณัำฉะฝ ะฅััะฒัั ะดะพัะพั ะฝั haragdah ััะฝะบั าฏาฏัะณัะถ ำฉะณะฒำฉะป ัะดะฐะฐะฝ ะฑะพะปะฝะพ.
Materi.prototype.haragdah = function () {
console.log(this.une + " าฏะฝัััะน ะผะฐัะตัะธ ะฑะฐะนะฝะฐ. ");
};
//Amitan ััะฝะบั าฏาฏัะณัะถ ำฉะณัำฉะฝ
function Amitan(nas, une, ungu) {
Materi.call(this, une, ungu);
this.nas = nas;
}
// ะะฐัะตัะธ-ะด Amitan ะพะฑัะตั ัะดะฐะผัััะปะถ ำฉะณั ะฑะฐะนะฝะฐ.
Amitan.prototype = Object.create(Materi.prototype);
Amitan.prototype.hoolloh = function () {
console.log(
this.nas +
" ะฝะฐััะฐะน " +
this.une +
" าฏะฝัััะน " +
this.ungu +
" ำฉะฝะณำฉััะน าฏะฝัั ั
ะพะพะปะพะปะปะพะพ "
);
};
//ะฅาฏะฝ ััะฝะบั าฏาฏัะณัะถ ำฉะณัำฉะฝ
function ะฅาฏะฝ(ะฝัั, ะฝะฐั, าฏะฝั, ำฉะฝะณำฉ) {
Amitan.call(this, ะฝะฐั, าฏะฝั, ำฉะฝะณำฉ);
this.ะฝัั = ะฝัั;
}
// Amitan-ะด ะฅาฏะฝ ะพะฑัะตั ัะดะฐะผัััะปะถ ำฉะณั ะฑะฐะนะฝะฐ.
ะฅาฏะฝ.prototype = Object.create(Amitan.prototype);
ะฅาฏะฝ.prototype.setgeh = function (bodol) {
console.log(
this.ะฝัั +
" ะฝััััะน " +
this.nas +
" ะฝะฐััะฐะน " +
this.une +
" าฏะฝัััะน " +
this.ungu +
" ำฉะฝะณำฉััะน ั
าฏะฝ " +
bodol +
" ะณัะถ ะฑะพะดะปะพะพ "
);
};
// unee -ะฝะด ััะณะฐ ำฉะณำฉำฉะด ั
ัะฒะปัะถ ะฑะฐะนะฝะฐ.
var unee = new Amitan(20, 40000, "alag");
unee.haragdah();
unee.hoolloh();
// p1 -ะฝะด ััะณะฐ ำฉะณำฉำฉะด ั
ัะฒะปัะถ ะฑะฐะนะฝะฐ.
var p1 = new ะฅาฏะฝ(" ะะพะปะดะพะพ ", 18, 150, " ัะฐั ");
p1.haragdah();
p1.hoolloh();
p1.setgeh("Javascript ะปะฐะนัะฐะน ัะผะฐะฐะฐ");
// 2. ะฅะธะนั
ะฐะปั
ะฐะผ Materi Amitan 2 ะฑะฐะนะณััะปะฐะณั ััะฝะบััะณ ะณะฐั ะฐัะณะฐะฐั ะทะฐะปะณะฐะถ ะฑะฐะนะฝะฐ ะณัััะฝ าฏะณ.
// Object.create -ะฝั ัะธะฝััั ะพะฑัะตะบั าฏาฏัะณัะถ ำฉะณะดำฉะณ. ะัั
ะดัั ัะผะฐั ะฝัะณัะฝ ะพะฑัะตะบัะพะพั ะทะฐะณะฒะฐั ะฑะพะปะณะพะถ ะฐัะณัะผะตะฝัะฐะฐั ะฝั ะดะฐะถััะปัะฐะฝ ะพะฑัะตะบัะพะพั
// ะทะฐะณะฒะฐั ะฑะพะปะณะพะถ าฏาฏัะณัะดัะณ. ะัััั
ะถะธััั ะฝั ะดััั ะทะฐะณัะฐั ะฝั Materi ะฑะฐะนะฝะฐ.
// ะะนะผ ะฑะฐะนะดะปะฐะฐั ะฑะฐะนะณััะปะฐะณั ััะฝะบั ะฐัะธะณะปะฐะถ ัะดะฐะผัะธ ั
ะธะนั
ะฝัั. ะัั
ะดัั ัะฝั ะฑะพะป
|
//RAFCE shortcut to paste this
const Header = () => {
return (
<div className = 'container pb-5'>
<h1 className = 'row-12 text-light text-center'>Image changer</h1>
</div>
)
}
export default Header
|
describe('standard.h.willMount', () => {
test.todo('Executa o evento willMount da instancia vinculada')
test.todo('Executa o metodo associado ao evento willMount')
})
|
// Functional component or stateless component without hooks
import React from 'react'
// function Greet() {
// return <h1>Hello CVGA</h1>
// }
// export const Greet = () => <h1>Hello CVGA</h1> // using arrow functions
// above is named export
//below deault export if we change the name in app js it won't effect output
// const Greet = () => <h1>Hello CVGA </h1> //using arrow functions
const Greet = (props) =>{
console.log(props);
return <h1>Hello CVGA, {props.name} a.k.a {props.codeName}</h1>
}
export default Greet
|
import axios from 'axios'
// URL and endpoint constants
const API_URL = 'https://geocode.xyz/'
function getGeoLocation (options) {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject, options)
})
}
// VUE Store
const state = {
data: {},
ready: false
}
const getters = {
location: state => {
return state
}
}
const mutations = {
SET_LOCATION (state, location) {
state.data = location
state.ready = true
},
CLEAR_LOCATION (state) {
state.data = {}
state.ready = false
}
}
const actions = {
getLocation: ({commit}) => {
let options = { enableHighAccuracy: true }
getGeoLocation(options)
.then((position) => {
axios({
method: 'get',
url: API_URL + position.coords.latitude + ',' + position.coords.longitude + '?geoit=json'
})
.then(function (response) {
commit('SET_LOCATION', response.data)
})
.catch(function (error) {
console.log(error)
})
})
.catch((err) => {
console.error(err.message)
})
}
}
export default {
state, mutations, getters, actions
}
|
import React from 'react';
import PlayerList from '../../../controller/components/lobby/PlayerList';
import TopBar from './../shared/TopBar';
import BottomBar from './../shared/BottomBar';
import styles from './lobby.less';
const Lobby = (props) => {
const className = styles['lobby'] + (props.className ? ' ' + props.className : '');
let bottomLine1;
if(props.players.length < props.numPlayersRequired) {
const delta = props.numPlayersRequired - props.players.length;
bottomLine1 = <p>Waiting on at least {delta} more player{delta != 1 ? 's' : ''} to join.</p>;
} else {
const playersReadyCount = props.players.filter(p => !p.ready).length;
bottomLine1 = <p>Waiting on {playersReadyCount} player{playersReadyCount != 1 ? 's' : ''} to get ready.</p>
}
let bottomLine2;
if(props.serverIP){
bottomLine2 = <p>Point your mobile browser at: {props.serverIP}/controller</p>
}
const localPlayerZx = (
<button onClick={props.zxButtonClicked}>z-x keys</button>
)
const localPlayerArrow = (
<button onClick={props.arrowsButtonClicked}>arrow keys</button>
)
return (
<div className= {className }>
<TopBar height="5">Lobby { localPlayerArrow } { localPlayerZx } </TopBar>
<PlayerList { ... props }/>
<BottomBar height="15">{ bottomLine1 } { bottomLine2 }</BottomBar>
</div>
);
}
export default Lobby; |
import React, { useState, useEffect } from 'react';
const FetchUseEffect = () => {
const [state, setState] = useState({
email: '',
picture: ''
});
useEffect(() => {
fetch('https://randomuser.me/api/')
.then(rs => rs.json())
.then(data => {
const [user] = data.results;
setState({
email: user.email,
picture: user.picture.medium
});
});
}, []);
const { email, picture } = state;
return (
<div>
<img src={picture} alt="" />
<div>{email}</div>
</div>
);
};
export default FetchUseEffect;
|
window.onload = function(){
var marco = document.getElementById("marco");
marco.addEventListener("click", function(){
var url = "http://" + window.location.host + "/STOMPSpringMarcopolo/marcopolo";
// ๅๅปบSockJS่ฟๆฅ
var sock = new SockJS(url);
// ๅๅปบSTOMPๅฎขๆท็ซฏ
var stomp = Stomp.over(sock);
var payload = JSON.stringify({"message": "Marco!"});
// ่ฟๆฅSTOMP็ซฏ็น
// ไฝฟ็จๅ
ๅญๆถๆฏไปฃ็็ๆถๅ๏ผๅไธคไธชๅผๅฏไปฅ้ไพฟๅ
stomp.connect("guest", "guest", function(){
// ๅ้ๆถๆฏ
stomp.send("/app/marco", {}, payload);
});
});
};
|
๏ปฟ// ็ปๅฝ็ฎก็
export default {
type: 'แแแแ
แแแแแแแแแ แถแ',
addType: 'แแแแแพแแแแแแแ',
checkSelectorHolder: 'แแผแแแแแพแแแพแแแแแถแแแถแแแแแแแแ',
displaySelectorHolder: 'แแผแแแแแพแแแพแแแแแถแแแถแแกแพแแแแแพ',
checkStatus: 'แแแแถแแแถแแแแแถแแแแแฝแแแทแแทแแแ',
checkStatusA: 'แแแ
แถแแแถแแแแแฝแแแทแแทแแแ',
checkStatusB: 'แแถแแแทแแทแแแแแฝแ
',
checkStatusC: 'แแทแแขแแปแแแแถแ',
putaway: 'แกแพแ แ
แปแแแแแพ',
putawayA: 'แแแแทแแแแแปแแแถแแแแ',
putawayB: 'แแ
แแแแปแแแแแถแแ',
putawayC: 'แกแพแแแแแพ',
putawayD: 'แแแแแถแแแแแแแแแถแแแแถแแกแพแแแแแพ',
putawayE: 'แ
แปแแแธแแแแพ (แแแแแถแแปแแแ
แแแแปแแแแแปแ)',
putawayF: 'แแแแถแแธแแแแแแแแ',
putawayG: 'แแแแถแแแถแแแแ',
putawayTip: 'แ
แปแ
แแพแแแแธแแแแแแแแแแแแแถแแแแผแแแแแถแแแถแแแแแถแแกแพแแแบแ
แปแแแแแพ',
price: 'แแแแแ',
inventory: 'แแแแปแ',
saled: 'แแถแแแแ',
piEdit: 'แแแแปแ แแทแ แแแแแ',
typeEdit: 'แแถแแแแแแแแแแแแแแแแแทแ',
parentType: 'แแแแแแแแแแ
แแแแแแผแ',
name: 'แแแแแ',
intro: 'แแถแแแแแถแ',
goodsType: 'แแแแแแแแแแทแ',
goodsType1: 'แแแแทแแแแแแแถ',
goodsType2: 'แแถแแแทแแแถแแแแปแ',
goodsType3: 'แแแแทแแแทแแแแป',
cobuy: 'แแถแแแทแแแถแแแแปแ',
cobuyPrice: 'แแแแแแแแแถแแแทแแแถแแแแปแ',
cobuyuser: 'แ
แแแฝแแแแปแแแแแแแถแแแทแแแถแแแแปแ',
cobuysec: 'แแแแแแแถแแถแแแแแแทแแแแแถแ',
conbuytip1: 'แขแแแแแถแแ
แถแแแแแแพแแแถแแแทแแแถแแแแปแ แแผแแแแแแแ
แแแฝแแแแปแแแแแแแถแแแทแแแถแแแแปแแขแแแแถแแแแแนแแแแแผแ (แแทแแแทแ
แแถแ 2แขแแแ)',
conbuytip2: 'แแผแแแแแแแแแแแแแแปแแแแถแแแแแถแแแแแแถแแทแแแถแแแแปแ (แแแแแทแแแพแแถแแแทแแแถแแแแปแแแทแแแแแแแแแแแปแแแแแแแแแแแแ แแถแแแแแแถแแทแแแนแแแแแผแแแปแแ
แแแแแแแแแแแแแแแแแแท)',
hour: 'แแแแ',
note: 'แแแแแถแแ',
edit: 'แแถแแแแแแแแแแแทแ',
next: 'แแแ แถแแแแแแถแแ',
pre: 'แแแ แถแแแปแ',
placeholder: 'แแผแแแแแพแแแพแแแแแทแ',
selectorTitle: 'แแถแแแแแพแแแพแแแแแทแ',
step1: 'แแแ แถแแแธ แก',
step1Tip: 'แแแแแแแแแแแแแแแทแ แแทแ แแปแแแแแแแ',
step2: 'แแแ แถแแแธ แข',
step2Tip: 'แแแแพแแแพแแแแแแแ แแทแ แแถแแถแแแแแ แถแแแแแทแ',
step3: 'แแแ แถแแแธ แฃ',
step3Tip: 'แแแแแแแถแแแแแถแแแแขแทแแขแแแธแแแแทแ',
step4: 'แแแ แถแแแธ แค',
step4Tip: 'แแถแแแแแแแแแแแถแแแแธแแแทแแ, แแแแปแ แ แพแ แแนแ แแแแแ',
sysType: 'แแแแแแแแแแทแ',
sysTypeProp: 'แแแแแแแแปแแแแแแแ',
goodsPic: 'แแผแแแถแแแแแทแ',
picdes: 'แแถแแแแแถแแแธแแผแแแถแ',
sp: 'แแถแแแถแแแแถแแ แแทแ แแปแแแแแแแ',
spec: 'แแแแแแแถแแแแถแแ',
spec1: '+แแถแแแถแแแแถแแ',
prop: 'แแแแแแแปแแแแแแแ',
prop1: 'แแปแแแแแแแ',
shareTip: 'แขแแแแแทแแแถแแแทแแแแทแ
แแแ
แถแแแ แแผแแแทแแแแแแแถแแฝแแขแแแแแแแแแแแแแแแแแทแแแพแขแแแแแแแผแแแถแแ
แแแ
แถแ',
commissionPercent: 'แขแแแแถแแแแแแพแแแถแ ๏ผโฐ๏ผ',
commissionMoney: 'แแแแแแแพแแแถแ ๏ผ$๏ผ',
shareSet: 'แแแแแแแแแทแแ
แแแ
แถแ',
shareGoods: 'แ
แแแ
แถแแแแแทแ',
shareAll: 'แแแแทแแแถแแแขแแแแแแผแแแถแแแถแแแแพแแแแพ',
goodsSelect: 'แแถแแแแแพแแแพแแแแแทแ',
systip1: 'แแผแแแแแพแแแพแแแแแแแแแแแทแ',
dpTypeTip1: 'แแผแแแแแแแแแแแแแ แถแแแถแแปแแแทแ',
dpTypeTip2: 'แแผแแแแแพแแแพแแแแแแแแแแแทแแแแแปแแ แถแแขแแแแแแผแแแแแทแแแแแ
แแแแแ',
nameTip: 'แแผแแแแแแแแแแแแแแแทแ',
imgTip: 'แแผแแขแถแแแกแผแแแผแแแผแแแถแแแแแถแแแแแทแ',
ipTip: 'แแผแแแแแแแแถแแแแแแถแแแแแแทแ แแทแ แแแแแแแแแทแแแแถแแ แแ
แแถแแแแฝแ',
postageRuleTip: 'แแผแแแแแพแแแพแแ
แแแถแแแแแแถแแแนแแแแแแผแ',
addressIdTip: 'แแผแแแแแพแแแพแแแธแแแแแแแแนแแแแแแผแแแแแทแ',
needExp: 'แแทแแแแปแแแแแแแผแแแถแ',
exp: 'แแทแแแแป',
whole: 'แแถแแแขแแ',
goodsInfo1: 'แแแแแแถแแแผแแแแแถแ',
goodsInfo2: 'แแแแแถแแขแแแธแแแถแแแแ',
goodsInfo3: 'แแทแแแแแถแแผแแแถแ',
goodsInfo4: 'แแแแแถแแแถแแแนแแแแแแผแ',
goodsInfo5: 'แแแแถแแแแแแแแแแแแแแฝแ
',
riderPost: 'แแถแแแแนแแแแแแผแแแแแปแแแแแปแแแแแฝแ',
riderPostSupport: 'แแถแแแแ',
posageRule: 'แ
แแแถแแแแแแถแแแนแแแแแแผแ',
postAddr: 'แแธแแแแแแแแแแถแแแนแแแแแแผแ',
saveGoods: 'แแแแแถแแปแแแแแแแถแแแแแทแ',
saveTip1: 'แแแแแแถแแแแแทแแแแแผแแแถแแแแแแถแแปแแแแแแแแแแแ แแพแขแแแแ
แแแแแแแแแแแแแแถแแ?',
saveTip2: 'แแแแแแถแแแแแทแแแแแผแแแถแแแแแแถแแปแแแแแแแแแแ!',
saveTip3: 'แแพแขแแแแ
แแแแแแแแแแแแแแ?',
xgLabel: 'แแถแแแทแแแแแทแแแถแแแแแแ',
xgLabel1: 'แแทแแแแแถแแแแแแแแแ',
xgLabel2: 'แแทแแแถแแแแแแ',
delTip: 'แแพแขแแแแแแแถแแแแถแแปแแแแแทแแแ
แแ
แปแแแแแแแฌ?',
restore: 'แแแแถแแแแแทแ',
commodityPreview: 'แแทแแทแแแแแพแแแแแทแ',
goodsLang: 'แแแแแแแถแแถแแแแแแแแถแแแแแทแ',
goodsLangSet: 'แแแแแแแแถแแถ',
goodsLangSetTip: 'แ
แปแ
แแพแแแแธแแแแแ',
goodsLangSetTip1: 'แแผแแแแแแแแแแแแแแแแถแแแถแแแแแถแแแพแแแปแแแทแ',
baseSetTip: 'แแผแแแแแแแแแแแแแทแแแแแแแแผแแแแแถแแแถแแแแแแแแปแแแทแ',
addressSetTip: 'แแแแแแขแถแแแแแแแถแ',
postageSet: 'แแแแแแ
แแแถแแแแแแถแแแนแแแแแแผแ',
dpTypeSet: 'แแแแแแแแแแแแ แถแ',
weight: 'แแแแแแ',
imgae: 'แแผแแแถแแแแแทแ',
shangJia: 'แแถแแแแพแแแแพ',
refuse: 'แแแทแแแ',
approvalSuccess: 'แขแแปแแแแถแแแแแแแแแแ',
notListed: 'แแทแแแถแแแถแแแแพแแแแพ',
hasBeenAddedTo: 'แแถแแแถแแแแ
แแพแแแแพ',
removed: 'แแถแแแแ
แแแแธแแแแพ',
backGoodsList: 'แแแแกแแแแ
แแแแแธแแแแทแแแทแ',
successTip: 'แแแแนแแแแแแแ',
lookGoodsInfo: 'แแพแแแแแแแถแแแแแขแทแแแแแทแ',
noSaveGoodsTip: 'แขแแแแแถแแแทแแแแแแแแแแทแแแทแแแถแแแแถแแแแแแถแแปแ แแแแถแแแแถแแพแแแแผแแแแแถแแแทแแแแแแ',
lijihuifusuju: 'แแแแถแแแทแแแแแแแแแแถแแ',
cancelhuifusuju: 'แแแแแแแแถแแแแแถแแแทแแแแแแ',
distributionLowProfits: 'แแถแแบแแถแแแแทแแแแแแถแแแแแแทแแ
แแแผแแแทแ
แแบ',
yes: 'แแแแผแแ แพแ',
not: 'แขแแแแ',
lowMarginGoods: 'แแแแทแแแถแแแแแแทแแ
แแแผแแแทแ
',
noLowMarginGoods: 'แแทแแแแแแแแทแแแแแแถแแแแแแทแแ
แแแผแแแทแ
',
introGoods: 'แแแแแแแแทแแแ',
introDetail: 'แแถแแแทแแแแแถแแถแขแแแแ',
goodslist: 'แแแแแธโแแแแทแ',
wkcgm: 'แแทแแแแแแแแถแแแถแแ แแปแ'
}
|
/* eslint-disable max-len */
/* eslint-disable no-irregular-whitespace */
/* eslint-disable react/no-string-refs */
/**
* ้ๆไบ็ปด็
*/
import React, { Component, PureComponent } from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
TouchableOpacity,
ImageBackground,
} from 'react-native';
import CameraRoll from '@react-native-community/cameraroll';
import { connect } from 'rn-dva';
import QRCode from 'react-native-qrcode-svg';
import ViewShot from 'react-native-view-shot';
import CommonStyles from '../../common/Styles';
import Header from '../../components/Header';
import ImageView from '../../components/ImageView';
import DashLine from '../../components/DashLine';
import ModalDemo from '../../components/Model';
import * as scanConfig from '../../config/scanConfig';
import config from '../../config/config';
import {RequestWritePermission} from '../../config/permission.js';
const { width, height } = Dimensions.get('window');
function getwidth(val) {
return (width * val) / 375;
}
class ReceiptStaticQrCodeScreen extends PureComponent {
constructor(props) {
super(props);
this.state = {
};
}
takeToImage=() => {
this.refs.location.capture().then(async (uri) => {
console.log(uri);
let granted = await RequestWritePermission();
if(!granted) return;
CameraRoll.saveToCameraRoll(uri)
.then((result) => {
Toast.show('ๅทฒไฟๅญๅฐๆๆบ็ธๅ');
console.log(`ไฟๅญๆๅ๏ผๅฐๅๅฆไธ๏ผ\n${result}`);
})
.catch((error) => {
if(error=='Error: ็จๆทๆ็ป่ฎฟ้ฎ'){
CustomAlert.onShow(
"alert",
"่ฅ่ฆ็ปง็ปญไฟๅญๅพ็๏ผ่ฏทๅฐๆๆบ่ฎพ็ฝฎไธญๅฟๆๅผ็ธๅๆ้",
"ๆจๅทฒๆ็ป็ธๅ่ฎฟ้ฎๆ้"
);
}else{
alert(`ไฟๅญๅคฑ่ดฅ๏ผ\n${error}`);ย ย
}
});
}).catch(
error => alert(error),
);
}
renderTakeImage=(qrUri) => {
const { navigation, userShop } = this.props;
const params = navigation.state.params || {};
const shopIcon = params.logo || userShop.logo || '';
console.log(qrUri);
return (
<ImageBackground
resizeMode="stretch"
style={styles.contentSty}
source={require('../../images/qrcode/background.png')}
>
<View style={styles.storeImg}>
<ImageView
source={shopIcon ? { uri: shopIcon } : require('../../images/qrcode/store.png')}
resizeMode="cover"
sourceWidth={83}
sourceHeight={83}
/>
</View>
<Text style={styles.storeName}>{params.title || userShop.name}</Text>
<View style={styles.codeimg}>
<QRCode
value={qrUri}
size={222}
/>
</View>
</ImageBackground>
);
}
render() {
const { navigation, user, userShop } = this.props;
const params = navigation.state.params || {};
let qrParams = {};
const shopIcon = params.logo || userShop.logo || '';
params.title
? qrParams = {// ๅบ้บ่ฏฆๆ
storeId: params.storeId || userShop.id,
userId: user.id,
lat: params.lat,
lng: params.lng,
securityCode: user.securityCode,
}
: qrParams = {// ้ๆไบ็ปด็
userId: user.id,
merchantId: user.merchantId,
storeId: userShop.id,
};
const takeImageUri =`${config.baseUrl_share_h5}codeShop?shopId=${params.storeId || userShop.id}&merchantId=${user.merchantId}&logo=${shopIcon}&name=${encodeURIComponent(`${params.title}`)}&securityCode=${user.securityCode}&condensationCode=1`;
// const otherUri=scanConfig.qrCodeValue(params.title ?'store_detail':'store_receipt', qrParams)
const otherUri = params.title ? takeImageUri : scanConfig.qrCodeValue('store_receipt', qrParams);
return (
<View style={styles.container}>
<Header
title={params.title ? 'ๅบ้บไบ็ปด็ ' : '้ๆไบ็ปด็ '}
navigation={navigation}
goBack
rightView={
params.title
&& (
<TouchableOpacity
style={styles.headerItem}
onPress={this.takeToImage}
>
<Text style={{ fontSize: 17, color: '#fff' }}>ไฟๅญ</Text>
</TouchableOpacity>
)
}
/>
{
this.renderTakeImage(otherUri)
}
<ViewShot ref="location" style={{ position: 'absolute', top: -height }} options={{ format: 'png', quality: 1 }}>
{this.renderTakeImage(takeImageUri)}
</ViewShot>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
alignItems: 'center',
backgroundColor: '#4688ED',
},
headerItem: {
width: 50,
},
contentSty: {
width: 314,
height: 415,
marginTop: 57,
alignItems: 'center',
},
storeImg: {
// ...CommonStyles.shadowStyle,
justifyContent: 'center',
alignItems: 'center',
width: 83,
height: 83,
marginTop: -83 / 2 + 21,
borderWidth: 1,
borderColor: '#F1F1F1',
borderRadius: 83 / 2,
backgroundColor: '#fff',
overflow: 'hidden',
},
storeName: {
fontSize: 16,
color: '#000',
fontWeight: '500',
marginTop: 10,
letterSpacing: 0.1,
},
codeimg: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
marginTop: getwidth(15),
},
});
export default connect(
state => ({
user: state.user.user || {},
userShop: state.user.userShop || {},
}),
)(ReceiptStaticQrCodeScreen);
|
global.ROUTER.web.Request = {};
|
/**
* ไฝ่
๏ผluanjie
ๆถ้ด๏ผ2021-7
ๆ่ฟฐ๏ผ็ปๅฝ้กต้ข
*/
(function() {
"use strict";
initLiserners();
console.log(sha1.hex('123'));
/**
* ็ๅฌ้กต้ขๆๆ็นๅปไบไปถ
*/
function initLiserners() {
$(".sendbox").on("click", function() {
var username=$('#username').val();
var password=$('#password').val();
console.log(sha1.hex(password))
var registdata={
username:username,
password:sha1.hex(password)
}
console.log(registdata)
// regist(registdata);
login(registdata);
})
}
//ๆณจๅๆฅๅฃ็่ฐ็จ
function regist(data) {
var url = 'http://127.0.0.1:3300/rest/regist';
//console.log('่ฏทๆฑๅฐๅ' + url);
$.ajax(url, {
data:data,
type:'post',
dataType: "json",
timeout: "15000", //่ถ
ๆถๆถ้ด่ฎพ็ฝฎไธบ3็ง๏ผ
headers:{
authcode:'123456'
},
success: function(response) {
console.log(JSON.stringify(response));
},
error: function(error) {
console.log("่ฏฆๆ
error");
console.log(JSON.stringify(error));
}
});
}
//็ปๅฝๆฅๅฃ็่ฐ็จ
function login(data) {
var url = 'http://127.0.0.1:3300/rest/login';
//console.log('่ฏทๆฑๅฐๅ' + url);
$.ajax(url, {
data:data,
type:'post',
dataType: "json",
timeout: "15000", //่ถ
ๆถๆถ้ด่ฎพ็ฝฎไธบ3็ง๏ผ
headers:{
authcode:'123456'
},
success: function(response) {
console.log(JSON.stringify(response));
},
error: function(error) {
console.log("่ฏฆๆ
error");
console.log(JSON.stringify(error));
}
});
}
})();
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CityOptionItem from './CityOptionItem';
class ProvinceSelect extends Component {
constructor(){
super();
this.state={};
this.handleChange=this.handleChange.bind(this);
}
handleChange(event){
if(this.props.dataChange){
this.props.dataChange(this.refs.area_option.value);
}
}
render(){
let element;
if(this.props.areaList){
element = this.props.areaList.map((area,index)=>{
return (<CityOptionItem key={index} area={area} />);
});
}
return (
<select onChange={this.handleChange} ref="area_option" className="area_select">
{element}
</select>
);
}
}
ProvinceSelect.propTypes={
areaList:PropTypes.array,
dataChange:PropTypes.func
}
export default ProvinceSelect;
|
function Cities (props) {
if(props.City==null){
return null;
}
else{
return <option value={props.City}>{props.City}</option>
}}
export default Cities |
import React from "react";
import Button from "./ButtonLibrary/Button";
function CustomButtonLibrary() {
return (
<div>
<Button type="primary">Click Me</Button>
<Button type="disabled">Click Me</Button>
</div>
);
}
export default CustomButtonLibrary;
|
/********************
ใๅใๅใใ
********************/
$(document).ready(function() {
// $('#sendBtn').click(function() {
// $('#vals').submit();
// });
});
$(function() {
$('#vals').submit(function(){
var result = ajaxSendMail();
result.done(function(response) {
console.debug(response);
showSent(response);
// jAlert('ใๅใๅใใๅ
ๅฎนใ้ไฟกใใใพใใ' ,'ใๅใๅใใ' ,
// function(r) {
// location.href = 'index.html';
// }
// );
});
result.fail(function(result, textStatus, errorThrown) {
console.log("error for ajaxSendMail for inquiry:" + result.status + ' ' + textStatus);
});
result.always(function() {
});
return false;
});
});
/**********
ใกใผใซ้ไฟก
**********/
function ajaxSendMail() {
var retAddr = $('#retAddr').val();
var sentence = $('#sentence').val();
var destAddr = $('#destAddr').val();
var branchNo = $('#branchID').val();
//console.debug(dataStr);
var jqXHR;
jqXHR = $.ajax({
type : "post" ,
url : "../cgi/ajax/sendInqMail.php" ,
data : {
retAddr : retAddr ,
sentence : sentence ,
destAddr : destAddr ,
branchNo : branchNo
} ,
cache : false
});
return jqXHR;
}
/**********
ๅ
ๅฎน้ไฟก
**********/
function send() {
window.history.back(-1);
}
/**********
ๆปใ
**********/
function ret() {
window.history.back(-1);
}
function showSent(retVal) {
var height = $("#vals").height();
var retAddr = $('#retAddr').val();
var str;
str = 'ใๅใๅใใใฎ้ไฟกใๅฎไบใใพใใใ<br>' +
'ๆฐๆฅไธญใซ' + retAddr + 'ใซๅ็ญใใพใใฎใงใใฐใใใๅพ
ใกใใ ใใใ<br>';
// '้ทๆ้ๅ็ญใใชใใจใใฏใใใซใ้ฃ็ตกใใ ใใใ';
$("#vals").html(str);
height-=10;
$("#vals").css('height' ,height + 'px');
}
|
function F(a, b, c, d, e) {
return a + b * c / d + e;
}
var a = "one";
var b = 1;
var c = a + b;
var arr = [b, 2 + b, 3];
c = 2 + " equals "+ c + '?';
if (b === 1 - 1 - 1) {
a = "-1";
}
else {
a = "-2";
}
for (/*!int */ var i = 0; i < arr.length; ++i) {
arr[i] = arr[i] * 2;
}
var j = 1, n = 10;
while (j < n) {
b += j;
j += 2;
} |
function uniteUnique(arr) {
var args = Array.prototype.slice.call(arguments);
var flattened = args.reduce(function(a, b) {
return a.concat(b);
});
var unique = flattened.filter(function(item, index, inputArray) {
return inputArray.indexOf(item) === index;
});
return unique;
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
|
//1.2.1
// var message = 'hi';
//
// {
// var message = 'bye';
// }
//
// console.log(message);
// let message = 'hi';
//
// {
// let message = 'bye';
// }
//
// console.log(message);
//1.2.2
// var fs = [];
//
// for (var i = 0; i < 10; i++) {
// fs.push(function() {
// console.log(i);
// })
// }
//
// fs.forEach(function(f) {
// f();
// })
// var fs = [];
//
// for (let i = 0; i < 10; i++) {
// fs.push(function() {
// console.log(i);
// })
// }
//
// fs.forEach(function(f) {
// f();
// });
//1.2.3
// function varFunc() {
// var previous = 0;
// var current = 1;
// var i;
// var temp;
//
// for (i = 0; i < n; i += 1) {
// temp = previous;
// previous = current;
// current = temp + current;
// }
// }
function letFunc(n) {
let previous = 0;
let current = 1;
for (let i = 0; i < n; i += 1) {
let temp = previous;
previous = current;
current = temp + current;
console.log(current);
}
}
console.log(letFunc(10));
|
const mongoose = require("mongoose");
const { Schema } = mongoose;
const ContactSchema = new Schema({
name: {
type: String,
required: [true, "Please provide a name."],
},
email: {
type: String,
required: [true, "Please provide a email."],
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
"Please provide a valid email",
],
},
subject: {
type: String,
required: [true, "Please provide a subject."],
},
content: {
type: String,
required: [true, "Please provide a content."],
},
createdAt: {
type: Date,
default: Date.now(),
},
});
module.exports = mongoose.model("Contact",ContactSchema); |
/**
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
var count = 0;
for (var i= 0; i<=31; i++) {
if((n & (1 << i)) !== 0) count++;
}
return count;
};
console.log(hammingWeight(4)); //1
console.log(hammingWeight(11)); //3
console.log(hammingWeight(128)); //1 |
/*
* ๆฌ้
็ฝฎๆไปถๅฃฐๆไบๆดไธชๅบ็จ็ๆฐๆฎๅบ่ฟๆฅ้จๅใ
*/
var ioc = {
/*
* ๆฐๆฎๅบ่ฟๆฅๆฑ
*/
dataSource : {
type : "com.mchange.v2.c3p0.ComboPooledDataSource",
fields : {
driverClass : "com.mysql.jdbc.Driver",
jdbcUrl : "jdbc:mysql://172.16.106.24:3399/hansight",
user : "hansight",
password : "hansight"
}
},
/*
* ่ฟไธช้
็ฝฎๅพๅฅฝ็่งฃ๏ผ args ่กจ็คบ่ฟไธชๅฏน่ฑกๆ้ ๅฝๆฐ็ๅๆฐใๆพ็ถ๏ผไธ้ข็ๆณจๅ
ฅๆนๅผๅฐ่ฐ็จ new NutDao(dataSource)
*/
dao : {
type : "org.nutz.dao.impl.NutDao",
args : [ {
refer : "dataSource"
} ]
}
}; |
import React, { Component } from 'react'
import { View, Text, StyleSheet, TouchableOpacity, Dimensions } from 'react-native'
import { chooseColor } from './helperFunctions'
import ReactNativeComponentTree from 'react-native';
import GameOver from './GameOver'
var lineButtonWidth;
var fontSize;
export default class Gameboard extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.getLineButtonDimensions()
}
getLineButtonDimensions() {
var {height, width} = Dimensions.get('window');
lineButtonWidth = (width - 70) / Math.sqrt(this.props.numberOfTrains)
fontSize = height * .05
}
render() {
if (this.props.lives > 0) {
return(
<View style={styles.gameboardWrapper}>
<View style={styles.dataWrapper}>
<View style={styles.metaDataWrapper}>
<Text style={styles.metaData}>lives: {this.props.lives}</Text>
<Text style={styles.metaData}>score: {this.props.counter}</Text>
</View>
<View style={styles.currentStationWrapper}>
<Text style={StyleSheet.flatten([styles.currentStation, {fontSize: fontSize}])}>
{this.props.currentStation} ({this.props.currentLine})
</Text>
</View>
</View>
<View style={styles.lineButtonWrapper}>
{this.props.linesInPlay.map(line => {
return(
<TouchableOpacity
id={line}
key={line}
onPress={() => this.props.checkMatch(line)}
style={StyleSheet.flatten([
styles.lineButton,
chooseColor(line, lineButtonWidth),
{width: lineButtonWidth,
height: lineButtonWidth,
borderRadius: lineButtonWidth/2,
margin: (this.props.numberOfTrains > 9 ? 5 : 10)
}
])}
>
<Text style={StyleSheet.flatten([styles.lineButtonText, chooseColor(line, lineButtonWidth)])}>{line}</Text>
</TouchableOpacity>
)
})}
</View>
</View>
)
} else if (this.props.lives === 0) {
return(
<GameOver
counter={this.props.counter}
wrongGuesses={this.props.wrongGuesses}
rightAnswersOne={this.props.rightAnswersOne}
rightAnswersTwo={this.props.rightAnswersTwo}
rightAnswersThree={this.props.rightAnswersThree}
playAgain={this.props.playAgain}
lineButtonWidth={lineButtonWidth}
/>
)
}
}
}
const styles = StyleSheet.create({
gameboardWrapper: {
display: "flex",
flex: 1,
width: "100%",
height: "auto",
alignItems: "center",
backgroundColor: "#161A1C",
},
dataWrapper: {
display: "flex",
alignItems: "center",
height: "32%",
width: "100%",
},
metaDataWrapper: {
display: "flex",
position: "relative",
flexDirection: "row",
justifyContent: "space-between",
width: "100%",
borderTopColor: "white",
borderTopWidth: 1,
borderBottomColor: "white",
borderBottomWidth: 1,
},
metaData: {
fontSize: 16,
paddingLeft: 20,
paddingRight: 20,
paddingTop: 10,
paddingBottom: 10,
color: "white",
},
currentStationWrapper: {
width: "80%",
flex: 2,
display: "flex",
justifyContent: "center",
alignItems: "center",
alignContent: "center",
},
currentStation: {
width: "100%",
textAlign: "center",
color: "#FFF",
fontWeight: "800",
textDecorationLine: "underline",
},
lineButtonWrapper: {
display: "flex",
flex: 2,
position: "relative",
flexDirection: "row",
justifyContent: "center",
alignContent: "center",
flexWrap: "wrap",
width: "100%",
borderTopColor: "white",
borderTopWidth: 1,
},
lineButton: {
display: "flex",
alignItems: "center",
justifyContent: "center",
overflow: 'hidden',
backgroundColor: "blue",
},
lineButtonText: {
fontSize: 35,
fontWeight: "600",
},
});
|
/**
* ๅปบ็ญ็ฑปๅ็ๅ็ซฏๆงๅถJS
* ไฝ่
๏ผๅๆทๅ
ฐ
*
*/
$(function(){
var typeNo=null;
var name=null;
//่ฎพ็ฝฎ็ณป็ป้กต้ขๆ ้ข
$("span#mainpagetille").html("ๅปบ็ญ็ฑปๅ็ฎก็");
//ๆพ็คบๅปบ็ญ็ฑปๅๅ่กจ
$("table#BuildingTypeGrid").jqGrid({
url: host+'buildType/list/all/page',
datatype: "json",
colModel: [
{ label: '็ฑปๅ็ผๅท', name: 'no', width: 50},
{ label: '็ฑปๅๅ็งฐ', name: 'name', width: 50}
],
caption:"ๅปบ็ญ็ฑปๅๅ่กจ",
viewrecords: true,
autowidth: true,
height:300,
rowNum: 10,
rowList:[5,6,7,8,9,10],
jsonReader : {
root: "list",
page: "page",
total: "pageCount",
records: "count",
repeatitems: true,
id: "no"
},
pager: "#BuildingTypeGridPager",//jqGridๅ้กตๆ ทๅผ
multiselect:false,
onSelectRow:function(ptno){
typeNo=ptno;
}
});
function reloadBuildingTypeList()
{
$("table#BuildingTypeGrid").jqGrid().trigger("reloadGrid");
}
//===========================ๅขๅ ๅปบ็ญ็ฑปๅๅค็=================================
//็นๅปๅปบ็ญ็ฑปๅๅขๅ ้พๆฅๅค็๏ผๅตๅ
ฅadd.html
$("a#BuildingTypeAddLink").off().on("click",function(){
$("div#BuildingTypeDialogArea").load("buildingType/add.html",function(){
//้ช่ฏๆไบคๆฐๆฎ
$("form#BuildingTypeDialogArea").validate({
rules: {
no: {
required: true
},
name: {
required: true
}
},
message:{
no: {
required: "็ฑปๅ็ผๅทไธบ็ฉบ"
},
name: {
required: "็ฑปๅๅ็งฐ็ฉบ"
}
}
});
//ๅขๅ ๅปบ็ญ็ฑปๅ็ๅผน็ช
$("div#BuildingTypeDialogArea").dialog({
title:"ๅขๅ ๅปบ็ญ็ฑปๅ",
width:400
});
//ๆฆๆชๅขๅ ๆไบค่กจๅ
$("form#BuildingTypeAddForm").ajaxForm(function(result){
if(result.status=="OK"){
reloadBuildingTypeList(); //ๆดๆฐๅปบ็ญ็ฑปๅๅ่กจ
}
//alert(result.message);
//BootstrapDialog.alert(result.message);
BootstrapDialog.show({
title: 'ๅปบ็ญ็ฑปๅๆไฝไฟกๆฏ',
message:result.message,
buttons: [{
label: '็กฎๅฎ',
action: function(dialog) {
dialog.close();
}
}]
});
$("div#BuildingTypeDialogArea").dialog( "close" );
$("div#BuildingTypeDialogArea").dialog( "destroy" );
$("div#BuildingTypeDialogArea").html("");
});
//็นๅปๅๆถๆ้ฎๅค็
$("input[value='ๅๆถ']").on("click",function(){
$("div#BuildingTypeDialogArea").dialog( "close" );
$("div#BuildingTypeDialogArea").dialog( "destroy" );
$("div#BuildingTypeDialogArea").html("");
});
});
});
//===========================ไฟฎๆนๅปบ็ญ็ฑปๅๅค็=================================
$("a#BuildingTypeModifyLink").off().on("click",function(){
if(typeNo==null){
BootstrapDialog.show({
title: 'ๅปบ็ญ็ฑปๅๆไฝไฟกๆฏ',
message:"่ฏท้ๆฉ่ฆไฟฎๆน็ๅปบ็ญ็ฑปๅ",
buttons: [{
label: '็กฎๅฎ',
action: function(dialog) {
dialog.close();
}
}]
});
}
else {
$("div#BuildingTypeDialogArea").load("buildingType/modify.html",function(){
//ๅๅพ้ๆฉ็ๅปบ็ญ็ฑปๅ
$.getJSON(host+"buildType/get",{no:typeNo},function(data){
//alert(typeNo);
if(data){
$("input[name='no']").val(typeNo);
$("input[name='name']").val(data.name);
}
});
$("div#BuildingTypeDialogArea" ).dialog({
title:"ๅปบ็ญ็ฑปๅไฟฎๆน",
width:600
});
//ๆฆๆช่กจๅๆไบค
$("form#BuildingTypeModifyForm").ajaxForm(function(result){
if(result.status=="OK"){
reloadBuildingTypeList(); //ๆดๆฐๅปบ็ญ็ฑปๅๅ่กจ
}
//alert(result.message);
//BootstrapDialog.alert(result.message);
BootstrapDialog.show({
title: 'ๅปบ็ญ็ฑปๅๆไฝไฟกๆฏ',
message:result.message,
buttons: [{
label: '็กฎๅฎ',
action: function(dialog) {
dialog.close();
}
}]
});
$("div#BuildingTypeDialogArea").dialog( "close" );
$("div#BuildingTypeDialogArea").dialog( "destroy" );
$("div#BuildingTypeDialogArea").html("");
});
//็นๅปๅๆถๆ้ฎๅค็
$("input[value='ๅๆถ']").on("click",function(){
$( "div#BuildingTypeDialogArea").dialog( "close" );
$( "div#BuildingTypeDialogArea").dialog( "destroy" );
$("div#BuildingTypeDialogArea").html("");
});
});
}
});
//===========================ๅ ้คๅปบ็ญ็ฑปๅๅค็=================================
$("a#BuildingTypeDeleteLink").off().on("click",function(){
if(typeNo==null){
BootstrapDialog.show({
title: 'ๅปบ็ญ็ฑปๅๆไฝไฟกๆฏ',
message:"่ฏท้ๆฉ่ฆๅ ้ค็ๅปบ็ญ็ฑปๅ",
buttons: [{
label: '็กฎๅฎ',
action: function(dialog) {
dialog.close();
}
}]
});
}
else {
BootstrapDialog.confirm('็กฎ่ฎคๅ ้คๆญคๅปบ็ญ็ฑปๅไน?', function(result){
if(result) {
$.post(host+"buildType/delete",{no:typeNo},function(result){
if(result.status=="OK"){
reloadBuildingTypeList(); //ๆดๆฐๅปบ็ญ็ฑปๅๅ่กจ
}
BootstrapDialog.show({
title: 'ๅปบ็ญ็ฑปๅๆไฝไฟกๆฏ',
message:result.message,
buttons: [{
label: '็กฎๅฎ',
action: function(dialog) {
dialog.close();
}
}]
});
});
}
});
}
});
//===========================ๆฅ็ๅปบ็ญ็ฑปๅๅค็=================================
$("a#BuildingTypeViewLink").off().on("click",function(){
if(typeNo==null){
BootstrapDialog.show({
title: 'ๅปบ็ญ็ฑปๅๆไฝไฟกๆฏ',
message:"่ฏท้ๆฉ่ฆๆฅ็็ๅปบ็ญ็ฑปๅ",
buttons: [{
label: '็กฎๅฎ',
action: function(dialog) {
dialog.close();
}
}]
});
}
else{
$("div#BuildingTypeDialogArea").load("buildingType/view.html",function(){
//ๅๅพ้ๆฉ็ๅปบ็ญ็ฑปๅ
$.getJSON(host+"buildType/get",{no:typeNo},function(data){
if(data){
$("span#no").html(typeNo);
$("span#name").html(data.name);
}
});
//ๅผนๅบDialog
$("div#BuildingTypeDialogArea" ).dialog({
title:"ๅปบ็ญ็ฑปๅ่ฏฆ็ป",
width:600
});
//็นๅปๅๆถๆ้ฎๅค็
$("input[value='ๅ
ณ้ญ']").on("click",function(){
$( "div#BuildingTypeDialogArea").dialog( "close" );
$( "div#BuildingTypeDialogArea").dialog( "destroy" );
$("div#BuildingTypeDialogArea").html("");
});
});
}
});
}); |
'use strict';
$(window).on('load resize', function() {
let width = $(document).width();
if ( width < 767.9 && !$('.top-directions__slider').hasClass('slick-initialized') ) {
let topDirectionsSlider = $('.top-directions__slider').slick({
infinite: true,
fade: true,
autoplay: false,
speed: 300,
autoplaySpeed: 5000,
pauseOnDotsHover: true,
pauseOnHover: true,
slidesToShow: 1,
rows: 1,
swipeToSlide: true,
swipe: true,
adaptiveHeight: false,
dots: true,
arrows: false,
appendDots: $('.top-directions__dots-container'),
mobileFirst: true,
responsive: [
{
breakpoint: 767.9,
settings: 'unslick'
}
]
});
topDirectionsSlider.on('afterChange', function(event, slick, currentSlide, nextSlide) {
let prevSlide1,
prevSlide2;
if(currentSlide === slick.$slides.length - 1 ) {
prevSlide1 = $(slick.$slides[0]).data('bg');
} else {
prevSlide1 = $(slick.$slides[currentSlide + 1]).data('bg');
}
if( currentSlide === slick.$slides.length - 2 ) {
prevSlide2 = $(slick.$slides[0]).data('bg');
} else if(currentSlide > slick.$slides.length - 2) {
prevSlide2 = $(slick.$slides[1]).data('bg');
} else {
prevSlide2 = $(slick.$slides[currentSlide + 2]).data('bg');
}
$('.top-directions__prev-slide_1').css({'background':'url(' + prevSlide1 + ') center no-repeat', 'background-size':'cover'});
$('.top-directions__prev-slide_2').css({'background':'url(' + prevSlide2 + ') center no-repeat', 'background-size':'cover'});
});
$('.top-directions__prev-slide_1').css({'background':'url(' + $('.top-directions__item:nth-child(2)').data('bg') + ') center no-repeat', 'background-size':'cover'});
$('.top-directions__prev-slide_2').css({'background':'url(' + $('.top-directions__item:nth-child(3)').data('bg') + ') center no-repeat', 'background-size':'cover'});
}
});
|
module.exports ={
"secret_key":"she_come_dey_fuck_u,i_wanttoshifturwombforu"
} |
import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/user';
import carrier from './modules/carrier';
import mock from './modules/mock';
//ไพง่พนๆ ๅๆข
import toggleSideBar from './modules/toggleSideBar';
//ๆต่ง้กต้ขๅก็
import tabView from './modules/tabView';
import getters from './getters';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
user,
carrier,
mock,
toggleSideBar,
tabView,
},
getters
});
export default store
|
// @flow
import React from 'react';
import {View, Text} from '../../components/core';
import {ResponsiveImage} from '../../components';
import {baseTextStyle} from '../../constants/text';
import {themeColors} from '../../constants/colors';
import CODEPOLITAN from '../../assets/images/communityPartners/codepolitan.png';
import ID_RUBY from '../../assets/images/communityPartners/id-ruby.png';
import SARCCOM from '../../assets/images/communityPartners/sarccom.png';
import BNCC from '../../assets/images/communityPartners/bncc.png';
export default function CommunityPartners() {
return (
<View>
<Text
style={{
fontWeight: baseTextStyle.FONT_BOLD,
textAlign: 'center',
fontSize: 20,
paddingVertical: 10,
color: themeColors.THEME_COLOR,
}}
>
Community Partners
</Text>
<View
style={{flexDirection: 'row', paddingTop: 10, alignItems: 'center'}}
>
<View style={{flex: 1}}>
<ResponsiveImage source={SARCCOM} style={{marginBottom: 30}} />
<ResponsiveImage source={CODEPOLITAN} />
</View>
<View style={{flex: 1, paddingHorizontal: 10}}>
<ResponsiveImage source={ID_RUBY} style={{marginBottom: 30}} />
<ResponsiveImage source={BNCC} />
</View>
</View>
</View>
);
}
|
var http = require('http');
var qs = require('querystring');
var fs = require('fs');
var server = http.createServer(function(req, res) {
if (req.method === 'POST') {
var body='';
req.on('data', function(chunk) {
console.log(chunk);
body+=chunk;
});
req.on('end', function() {
var data = qs.parse(body);
res.writeHead(200, {'Content-Type': 'text/html'});
var file = fs.createReadStream('index.html');
file.pipe(res);
//res.end(JSON.stringify(data));
});
}
if (req.method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/html'});
var file = fs.createReadStream('index.html');
file.pipe(res);
}
}).listen(8888);
console.log('Listening on port 8888');
|
import React from "react";
import './Objective.scss';
class Objective extends React.Component {
render() {
return (
<div className="Objective">
<h2 className="title">Hello, I'm Pham Ngoc Lam</h2>
<p>
It is a long established fact that a reader will be distracted by the readable content of a page
when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal
distribution of letters, as opposed to using 'Content here, content here', making it look like
readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their
default model text, and a search for 'lorem ipsum' will uncover many web sites still in their
infancy.
</p>
</div>
);
}
}
export default Objective;
|
import React from 'react'
import { StyleSheet, Text, View, Image} from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome';
import { colors } from '../../utils/colors';
import { Rupiah } from '../../helper/Rupiah';
import {logo} from '../../assets';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { SafeAreaView } from 'react-native-safe-area-context';
const NotifAlert = ({navigation, route}) => {
const dateRegister = () => {
var todayTime = new Date();
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
var year = todayTime.getFullYear();
var hour = todayTime.getHours();
var minute = todayTime.getMinutes();
return year + "-" + month + "-" + day + " " + hour +":"+ minute;
}
return (
<SafeAreaView style={styles.container}>
<View style={{flexDirection : 'row', justifyContent : 'center'}}>
<View style={{flex : 2}}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<Icon name = 'times' size = {20} />
</TouchableOpacity>
</View>
<View style={{flex : 2, alignItems :'center', justifyContent : 'center'}}>
<Text style={styles.title}>USADHA BAKTHI</Text>
</View>
<View style={{flex : 2}}>
</View>
</View>
<View style={{alignItems : 'center'}}>
<Image source={logo} style={{marginTop : 60, height : 100, width : 100, borderRadius :100}}/>
<Text style={{fontSize : 20, marginTop : 70, textAlign : 'center', color : 'green'}}>{route.params.notif}</Text>
<Text style={{marginTop : 30, fontSize : 15, color : '#000'}}>{dateRegister()}</Text>
<TouchableOpacity style={styles.btn} onPress={() => navigation.navigate('Dashboard')}>
<Text style={{color : '#ffffff', fontSize: 15, fontWeight : 'bold'}}>Kembali</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
)
}
export default NotifAlert
const styles = StyleSheet.create({
container : {
flex : 1,
backgroundColor : '#ffffff',
padding : 20,
alignItems : 'center',
},
title : {
textAlign : 'center',
fontSize : 20,
fontWeight : 'bold'
},
btn : {
borderWidth : 1,
padding : 10,
width : 340,
borderRadius : 10,
alignItems : 'center',
justifyContent : 'center',
marginTop : 40,
borderColor : colors.btn,
backgroundColor : colors.btn
}
})
|
"use strict";
const
_ = require('lodash'),
semver = require('semver'),
params = require('./parameters'),
// private data
_configuration = {
dbType: null, // shoud be overriden in driver implementation
dbVer: null, // shoud be overriden in driver implementation
maxRows: 10000, // max rows for fetch results
getConnMaxProbes: 30, // times
getConnWaitMinTime: 1000, // miliseconds
getConnWaitMaxTime: 4000,
poolFetchTimeout: 60, // timeout in seconds for waiting to getDbConnection() succesful callback
gatherStats: false
};
// private data
let _driver = null;
let _dbPool = null;
class AbstractDriver {
/**
* Base Constructor
*
* @param driver
* @param cfg
* @constructor
*/
constructor(driver, cfg) {
this.setCfg(cfg);
this.setDriver(driver);
// disable setters (no longer needed)
this.setCfg = null;
this.setDriver = null;
}
performStandardSetupChecks(requiredVer) {
// check driver version match
if(!semver.satisfies(this.getCfg().driverVersion, requiredVer)) {
throw new Error('Driver version (' + this.getCfg().driverVersion + ') is not supported! Required version is ' + requiredVer);
}
// todo-me: replace it with injected object handler not global
// check and eventually setup MyError global handler
if(typeof global.MyError !== 'function') {
global.MyError = Error;
}
// check connection param object existence
if(typeof this.getCfg().connection !== 'object') {
throw new Error('No connection parameters is provided in config data!');
}
}
// getters/setters methods
setCfg(cfg) { _.extend(_configuration, cfg); }
setDriver(driver) { _driver = driver; }
setDbPool(dbPool) { _dbPool = dbPool; }
getCfg() { return _configuration; }
getDriver() { return _driver; }
getDbPool() { return _dbPool; }
getFnParams(args, fnName) { return params[fnName](args); }
// Templates methods
setupPool () { throw new Error('setupPool() must be implemented!'); }
getDbConnection () { throw new Error('getDbConnection() must be implemented!'); }
executeTransaction () { throw new Error('executeTransaction() must be implemented!'); }
selectOneRowSql () { throw new Error('selectOneRowSql() must be implemented!'); }
selectOneRow () { throw new Error('selectOneRow() must be implemented!'); }
selectOneValueSql () { throw new Error('selectOneValueSql() must be implemented!'); }
selectOneValue () { throw new Error('selectOneValue() must be implemented!'); }
selectAllRowsSql () { throw new Error('selectAllRowsSql() must be implemented!'); }
selectAllRows () { throw new Error('selectAllRows() must be implemented!'); }
getSqlForSelectAllRowsSql () { throw new Error('getSqlForSelectAllRowsSql() must be implemented!'); }
getSqlForSelectAllRows () { throw new Error('getSqlForSelectAllRows() must be implemented!'); }
runProcedure () { throw new Error('runProcedure() must be implemented!'); }
insertReturningId () { throw new Error('insertReturningId() must be implemented!'); }
insertReturningIdSql () { throw new Error('insertReturningIdSql() must be implemented!'); }
querySql () { throw new Error('querySql() must be implemented!'); }
update () { throw new Error('update() must be implemented!'); }
insert () { throw new Error('insert() must be implemented!'); }
del () { throw new Error('del() must be implemented!'); }
}
module.exports = AbstractDriver;
|
import CONSTANT from "../../constants.js";
export default ({ target, store, actionCreators }) => {
const { addToFavorites, deleteFromFavorites } = actionCreators;
const addItemToFavorites =
target.dataset.favorite === CONSTANT.ADD_TO_FAVORITES;
addItemToFavorites
? store.dispatch(addToFavorites(target.id))
: store.dispatch(deleteFromFavorites(target.id));
document.getElementById("searchInput").value = "";
};
|
// 'use strict';
const gulp = require('gulp');
const plumber = require('gulp-plumber');
const imagemin = require('gulp-imagemin');
const terser = require('gulp-terser');
const babel = require('gulp-babel');
const webpack = require('webpack-stream');
const sass = require('gulp-sass');
const rename = require('gulp-rename');
const concat = require('gulp-concat');
const autoprefixer = require('gulp-autoprefixer');
const cleancss = require('gulp-clean-css');
const purgecss = require('gulp-purgecss');
sass.compiler = require('node-sass');
// images
gulp.task('images', function() {
return gulp
.src('src/images/**/*')
.pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
.pipe(gulp.dest('dist/images/'));
});
// assets
gulp.task('assets', function() {
return gulp.src('src/assets/**/*').pipe(gulp.dest('dist/assets/'));
});
// scripts
gulp.task('scripts', function() {
return gulp
.src(['!src/scripts/bundle.js', 'src/scripts/**/*.js'])
.pipe(
plumber({
errorHandler: function(error) {
console.log(error.message);
this.emit('end');
}
})
)
.pipe(
babel({
presets: ['@babel/env']
})
)
.pipe(webpack())
.pipe(concat('bundle.js'))
.pipe(terser())
.pipe(gulp.dest('dist/scripts'));
});
// styles
gulp.task('styles', function() {
return gulp
.src('src/styles/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(rename('style.css'))
.pipe(
autoprefixer({
browsers: ['last 10 versions'],
cascade: false
})
)
.pipe(
purgecss({
content: ['src/**/*.html']
})
)
.pipe(cleancss({ level: '2', minify: 'true' }))
.pipe(gulp.dest('src/styles'))
.pipe(gulp.dest('dist/styles'));
});
// html
gulp.task('html', function() {
return gulp.src('src/**/*.html').pipe(gulp.dest('dist'));
});
// default
gulp.task('default', gulp.series('images', 'assets', 'scripts', 'styles', 'html'));
// watch
gulp.task('watch', function() {
gulp.watch('src/images/**/*', gulp.series('images'));
gulp.watch('src/assets/**/*', gulp.series('assets'));
gulp.watch('src/scripts/**/*.js', gulp.series('scripts'));
gulp.watch('src/styles/**/*.scss', gulp.series('styles'));
gulp.watch('src/**/*.html', gulp.series('html'));
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.