text
stringlengths
7
3.69M
/** * Created by nisabhar on 7/18/17. */ define(['ojs/ojcore', 'knockout', 'jquery', 'pcs/dynamicProcess/services/DPRolesService', 'pcs/dynamicProcess/services/DPInstanceService','pcs/dynamicProcess/model/DpRole' , 'pcs/dynamicProcess/roles/util/dpRolesUtil', 'pcs/util/pcsUtil', 'ojL10n!pcs/resources/nls/pcsSnippetsResource', 'ojs/ojmenu', 'ojs/ojknockout','promise', 'ojs/ojlistview', 'ojs/ojinputtext', 'ojs/ojarraytabledatasource', 'ojs/ojtoolbar', 'ojs/ojselectcombobox', 'ojs/ojdialog' ], function(oj, ko, $, DPRolesService, InstanceService, DpRole, dpRolesUtil, pcsUtil) { 'use strict'; return function(params, componentInfo) { var self = this, roleService, element = componentInfo.element; var loggerUtil = require('pcs/util/loggerUtil'); //store the params self.properties = params; //Set the resourcebundle self.bundle = require('ojL10n!pcs/resources/nls/pcsSnippetsResource'); // for searching text self.searchText = ko.observable(''); // type of consumer self.consumerType = ko.observable(dpRolesUtil.const.CONSUMER_TYPE.admin_roles); // list of roles self.roleListDS = ko.observable(new oj.ArrayTableDataSource([])); //Improves performance by executing subscribed function after a specified period of time self.roleListDS.extend({rateLimit: {timeout: 250, method: "notifyWhenChangesStop"}}); // list of process definitions self.processDefinitionList= ko.observableArray([]); //Instance roles atributes self.instanceId = ko.observable(); self.processDefinitionId = ko.observable(); self.readOnly = ko.observable(false); // for instance roles which are readOnly //current selected Role Id self.selectedRole = ko.observable(null); /** * the first method call to set up the Component */ self.initContext = function() { roleService = DPRolesService.getInstance(); if(self.properties.hasOwnProperty('consumerType')){ var paramConsumerType = ko.utils.unwrapObservable(self.properties.consumerType); if (paramConsumerType) self.consumerType(paramConsumerType); } if (self.properties.hasOwnProperty('instanceid') ) { var paramInstanceId = ko.utils.unwrapObservable(self.properties.instanceid); if (paramInstanceId) self.instanceId(paramInstanceId); } if (self.properties.hasOwnProperty('processdefinitionid') ) { self.processDefinitionId(ko.utils.unwrapObservable(self.properties.processdefinitionid)); } if (self.properties.hasOwnProperty('readonly') ) { self.readOnly(ko.utils.unwrapObservable(self.properties.readonly)); } //load process def self.fetchProcessDefinitions(); // fetch roles self.fetchDPRoles(); }; /** * method to fetch process definitions */ self.fetchProcessDefinitions = function(){ if(self.consumerType() === dpRolesUtil.const.CONSUMER_TYPE.admin_roles){ var instanceService = InstanceService.getInstance(); //clear old defintition list self.processDefinitionList.removeAll(); instanceService.fetchProcessDefinitions(false,'update').then(function(data) { for (var i = 0; data && i < data.length; i++) { self.processDefinitionList.push({ 'label': data[i].displayName, 'value': data[i].id }); } }).fail(function(error) { var msg = self.bundle.pcs.dp.roles.def_list_error; self.showContentErrorRegion(msg); }); } }; /** * method to fetch role list */ self.fetchDPRoles = function (){ //Start the loading indicator $('#pcs-dp-roles-overlay', element).addClass('pcs-common-load-overlay'); var params = {}; if (self.consumerType() === dpRolesUtil.const.CONSUMER_TYPE.instance_roles) { params = { processInstanceId: self.instanceId(), processDefinitionId: self.processDefinitionId() }; } roleService.getRoles(true, params).then(function(roleItemsList) { self.populateRolesData(roleItemsList); //stop the loading indicator setTimeout(function(){ $('#pcs-dp-roles-overlay', element).removeClass('pcs-common-load-overlay'); },500); }).fail(function(error) { var msg = self.bundle.pcs.dp.roles.list_error; self.showContentErrorRegion(msg); }); }; /** * method to populate Role List */ self.populateRolesData = function(roleItemsList) { var arr = []; for (var i = 0; roleItemsList && i < roleItemsList.length; i++) { if (self.consumerType() === dpRolesUtil.const.CONSUMER_TYPE.admin_roles) { if (roleItemsList[i].getScopeType() === dpRolesUtil.const.SCOPE_TYPE.INSTANCE || roleItemsList[i].getScopeType() === dpRolesUtil.const.SCOPE_TYPE.GLOBAL) { continue; } } //TODO: add appropriate logic here else remove the empty loop if(self.consumerType() === dpRolesUtil.const.CONSUMER_TYPE.instance_roles && roleItemsList[i].getScopeType() === dpRolesUtil.const.SCOPE_TYPE.DEFINITION) { } arr.push(roleItemsList[i]); } self.roleListDS( new oj.ArrayTableDataSource(arr, { idAttribute: 'getRoleId' })); }; /** * method to add a new role, called when add button is clicked */ self.addNewRole = function() { var role = new DpRole(dpRolesUtil.createNewRole(dpRolesUtil.const.SCOPE_TYPE.DEFINITION)); self.selectedRole(role); }; /** * method called when user selects edit role * @param data * @param event */ self.selectEditInMenu = function(data,event){ self.selectedRole(data); }; /** * method called when user selects delete role * @param data * @param event */ self.selectDeleteInMenu = function(data,event){ self.deleteRole(data); }; /** * delete the required role * @param role */ self.deleteRole = function(role) { // var index = -1; // for(var i = 0; self.roleList() && i < self.roleList().length; i++) { // if(self.roleList()[i].getRoleId() === role.getRoleId()){ // index = i; // } // } var successMsg = self.bundle.pcs.dp.roles.delete_role_success.replace('{0}', role.getRoleDisplayName()); // add loading indicator $('#pcs-dp-roles-overlay', element).addClass('pcs-common-load-overlay'); roleService.removeRole(role.getRoleId()).then(function() { self.showContentSuccessRegion(successMsg); //fetch roles again from backend self.fetchDPRoles(); // //if we are deleting a instannce role which has overriden // // the overridden role should show back again // if (self.consumerType()=== dpRolesUtil.const.CONSUMER_TYPE.instance_roles && role.getOverriddenRoleId()){ // roleService.getRole(true, role.getOverriddenRoleId()).then(function(parentRole) { // //remove the item from the list and replace with the new role // self.roleList.splice(index, 1, parentRole); // self.showContentSuccessRegion(successMsg); // // }).fail(function(error) { // //remove the old item from the list // self.roleList.splice(index, 1); // self.showContentSuccessRegion(successMsg); // }); // }else{ // //remove the old item from the list // self.roleList.splice(index, 1); // self.showContentSuccessRegion(successMsg); // } }).fail(function(error) { var msg = self.bundle.pcs.dp.roles.delete_role_error.replace('{0}', role.getRoleDisplayName()); self.showContentErrorRegion(msg); }); }; //method to search as soon as user type function searchRolesList(searchtext) { var promise = $.Deferred(); roleService.searchRolesList(searchtext).then(function(roleItemsObj) { self.populateRolesData(roleItemsObj); promise.resolve(); }); return promise; } //method to search as soon as user type self.searchTextSubscription = self.searchText.subscribe(function(newValue) { searchRolesList(newValue); }); /** * method to clear search Text */ self.onSearchClearClick = function(){ //Updating the observable doesnt clear text for rawValue, hence use OJ to set value $('#pcs-dp-roles-search-input', element).ojInputText({'value': ''}); }; /** * method for error msg containor * @param msg */ self.showContentErrorRegion = function(msg) { self.showContentMsgRegion (msg,false); $('#pcs-dp-roles-overlay', element).removeClass('pcs-common-load-overlay'); }; /** * method for success msg containor * @param msg */ self.showContentSuccessRegion = function (msg){ self.showContentMsgRegion (msg,true); $('#pcs-dp-roles-overlay', element).removeClass('pcs-common-load-overlay'); }; /** * method to show message containor * @param msg * @param success */ self.showContentMsgRegion = function(msg,success) { var successIcon =''; var addClass =''; var removeClass = ''; if (success){ successIcon = 'pcs-dp-roles-content-success-icon'; addClass ='pcs-dp-roles-content-success'; removeClass = 'pcs-dp-roles-content-error'; } else{ successIcon = 'pcs-dp-roles-content-error-icon'; addClass = 'pcs-dp-roles-content-error'; removeClass ='pcs-dp-roles-content-success'; } var html ='<span class=\''+successIcon +'\' style=\'margin:20px\'>'+ msg + '</span>'; $('#pcs-dp-roles-content-msg-container',element).show(0).html(html).addClass(addClass).removeClass(removeClass).delay(5000).hide(0); }; /** * event listener method called when role details is closed * @param event */ self.closeDetails = function(event) { var data = event.detail; //get roles again from cache roleService.getRoles(false).then(function(roleItemsList) { self.populateRolesData(roleItemsList); //make selected Role as null self.selectedRole(null); $('#pcs-dp-roles-list',element).ojListView('refresh'); }); }; /** * event listener method called when a new role save is success * @param event */ self.addRoleCallback = function (event){ var data = event.detail; var role = data.role; //make selected Role as null self.selectedRole(null); var successMsg = self.bundle.pcs.dp.roles.create_role_success.replace('{0}', role.getRoleDisplayName()); self.showContentSuccessRegion(successMsg); //fetch roles again from backend self.fetchDPRoles(); // //get roles again from cache // roleService.getRoles(false).then(function(roleItemsList) { // self.populateRolesData(roleItemsList); // // //remove the overridenId from the list if it exists // if(self.consumerType()=== dpRolesUtil.const.CONSUMER_TYPE.instance_roles && role.getOverriddenRoleId()){ // var currentPosition = -1; // $.each(self.roleList(), function(index,item){ // if(item.getRoleId() === role.getOverriddenRoleId()){ // currentPosition = index; // return false; // } // }); // if (currentPosition != -1){ // //deleted the // self.roleList.splice(currentPosition, 1 ); // } // } // // //make selected Role as null // self.selectedRole(null); // // $('#pcs-dp-roles-list',element).ojListView('refresh'); // // var msg = self.bundle.pcs.dp.roles.create_role_success.replace('{0}', role.getRoleDisplayName()); // self.showContentSuccessRegion(msg); // }); }; /** * event listener method called when a updating a role is success * @param event */ self.editRoleCallback = function (event){ var data = event.detail; var role = data.role; //get roles again from cache roleService.getRoles(false ,null).then(function(roleItemsList) { self.populateRolesData(roleItemsList); //make selected Role as null self.selectedRole(null); $('#pcs-dp-roles-list',element).ojListView('refresh'); var msg = self.bundle.pcs.dp.roles.edit_role_success.replace('{0}', role.getRoleDisplayName()); self.showContentSuccessRegion(msg); }); }; //Handle on click of refresh button self.onRefreshBtnClick = function() { self.fetchDPRoles(); }; self.bindingsApplied = function() { //temp for Knockoutcomponet self.initContext(); //Subscribe to the events pcsUtil.eventHandler.addHandler(element,'dproledetail:close', self.closeDetails); pcsUtil.eventHandler.addHandler(element,'dproledetail:addrole', self.addRoleCallback); pcsUtil.eventHandler.addHandler(element,'dproledetail:editrole', self.editRoleCallback); }; /** * Method to dispose the ocmponent */ self.dispose = function(){ loggerUtil.log('dispose in case roles'); self.searchTextSubscription.dispose(); pcsUtil.eventHandler.removeHandler(element,'dproledetail:close', self.closeDetails); pcsUtil.eventHandler.removeHandler(element,'dproledetail:addrole', self.addRoleCallback); pcsUtil.eventHandler.removeHandler(element,'dproledetail:editrole', self.editRoleCallback); }; self.bindingsApplied(); } } );
const assert = require('assert') const flow = require('./_flow') let schema = '//atom/ipv6' describe(`schema:${schema}`, () => { it('a string', async () => { let data = '2001:db8:1234:0000:0000:0000:0000:0000' let e = flow.verify(schema, data) assert.equal(e, undefined) }) it('a string with uppercase', async () => { let data = '2001:DB8:1234:0000:0000:0000:0000:0000' let e = flow.verify(schema, data) assert.equal(e, undefined) }) it('missing a part', async () => { let data = '2001:db8:1234:0000:0000:0000:0000' let e = flow.verify(schema, data) assert.notEqual(e, undefined) }) it('contains invalid symbols', async () => { let data = '2001:db8:1234:0000:0000:0000:0000:XXXX' let e = flow.verify(schema, data) assert.notEqual(e, undefined) }) })
exports.up = function(knex, Promise) { return knex.schema.createTable('questions', function(tbl) { tbl.increments() tbl .string('question') .notNullable() tbl .string('answer') .notNullable() tbl .integer('quiz_id') .references('id') .inTable('quiz') .notNullable() }) }; exports.down = function(knex, Promise) { return knex.schema.dropTable('questions') };
import { wxRequest } from '../utils/fetch.js' export const GET_CURRENT_CITY = 'GET_CURRENT_CITY' //根据经纬度获取当前地址 export function getAddressByLocation(data) { return wxRequest({ url: "api-data-service/data/find-nearest", method: 'POST', data: data, }) } //获取当前定位城市详情 export function getCurrentCity(json){ return { type:'GET_CURRENT_CITY', json } }
/* eslint-disable @typescript-eslint/camelcase */ module.exports = { siteMetadata: { title: `CSIM`, description: `Revolutionizing scouting since 2018`, author: `@thiskappaisgrey`, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/cardinal-icon.png`, // This path is relative to the root of the site. }, }, { resolve: `gatsby-plugin-typescript`, options: {}, }, `gatsby-plugin-emotion`, { resolve: `gatsby-plugin-typography`, options: { pathToConfigModule: `src/utils/typography`, }, }, { resolve: `gatsby-plugin-layout`, options: { component: require.resolve(`./src/templates/default-layout.tsx`), }, }, { resolve: `gatsby-plugin-webpack-bundle-analyzer`, options: { analyzerPort: 3000, production: true, }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.app/offline `gatsby-plugin-offline`, ], pathPrefix: `/csim`, }
describe("Creating a food inventory item", () => { it("should display a food inventory item", () => { cy.visit("/"); cy.get("[data-test='foodName']").type("ham"); cy.get("[data-test='createButton']").click(); cy.get("[data-test='foodName']").should("have.value", ""); cy.contains("ham"); }); });
import React, {Component, PropTypes} from 'react'; import {connect} from 'react-redux'; import AccountForm from './AccountForm.jsx'; class Account extends Component { static propTypes = { user: PropTypes.object.isRequired } render() { return ( <div> <div style={{ display: 'block', maxWidth: 1200, width: '100%', margin: '30px auto 30px' }}> <AccountForm user={this.props.user} /> </div> </div> ); } } function select(state) { return { user: state.auth.user }; } const bindActions = { }; export default connect(select, bindActions)(Account);
import * as routes from './routes.js' const RECAPTCHA_SITE_KEY = '6Le4hHgUAAAAAKlyl0CIBye2NCXufd2jx0gkZK11' const USER_ROLES = { ADMIN: 2, MOD: 1, USER: 0 } export { routes, RECAPTCHA_SITE_KEY, USER_ROLES }
const CustomError = require("../extensions/custom-error"); module.exports = function countCats(matrix) { let res = 0 matrix.forEach(item => { if(item.includes('^^')){ let a = item.filter(i => i ==='^^') res += a.length } }) return res };
var proxy = require('./index.js'); var options = { address: '127.0.0.1', proxyPort: 19134, servers: [ { serverHost: '127.0.0.1', serverPort: '19135'} ], proxyHost: '0.0.0.0', timeOutTime: 10000 }; var server = proxy.start(options);
const mongoose = require('mongoose'); const helpers = require('../lib/helpers'); const autoIncrement = require('mongoose-auto-increment'); autoIncrement.initialize(mongoose.connection); module.exports = function(db){ let schema = require("../schemas/key"); let modelDef = db.getModelFromSchema(schema); modelDef.schema.plugin(require('./plugins/diffPlugin')); modelDef.schema.plugin(autoIncrement.plugin, { model: 'Key', field: 'kid', startAt: 1, incrementBy: 1 }); modelDef.schema.methods.toHAL = function(){ let json = JSON.stringify(this) //toJSON() return helpers.makeHAL(json); } return mongoose.model(modelDef.name, modelDef.schema) }
var CallidForm; var pageSize = 25; //文字廣告Model Ext.define('gigade.BannerNewsContent', { extend: 'Ext.data.Model', fields: [ { name: "news_id", type: "string" }, { name: "news_site_id", type: "string" }, { name: "news_title", type: "string" }, { name: "news_content", type: "string" }, { name: "news_link_url", type: "string" }, { name: "news_link_mode", type: "string" }, { name: "news_sort", type: "string" }, { name: "news_status", type: "string" }, { name: "news_start", type: "string" }, { name: "news_end", type: "string" }, { name: "news_createdate", type: "string" }, { name: "news_updatedate", type: "string" }, { name: "news_ipfrom", type: "string" } ] }); var BannerNewsContentStore = Ext.create('Ext.data.Store', { autoDestroy: true, autoLoad: true, pageSize: pageSize, model: 'gigade.BannerNewsContent', proxy: { type: 'ajax', url: '/Website/GetBannerNewsList?history=' + document.getElementById("history").value + '&&sid=' + document.getElementById("sid").value, reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); var sm = Ext.create('Ext.selection.CheckboxModel', { listeners: { selectionchange: function (sm, selections) { Ext.getCmp("gdBannerNewsContent").down('#edit').setDisabled(selections.length == 0); } } }); Ext.onReady(function () { Ext.tip.QuickTipManager.init(); var frm = Ext.create('Ext.form.Panel', { id: 'frm', //layout: 'anchor', border: 0, bodyPadding: 10, width: document.documentElement.clientWidth, items: [ { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'displayfield', id: 'site_name', name: 'site_name', value: '<div style="font-size:20px;width:900px;">廣告區塊位置&nbsp;&nbsp;&nbsp;' + document.getElementById('sname').value + '</div>' } ] } ] }); var gdBannerNewsContent = Ext.create('Ext.grid.Panel', { id: 'gdBannerNewsContent', store: BannerNewsContentStore, width: document.documentElement.clientWidth, columnLines: true, flex: 9.3, frame: true, columns: [ { header: "流水號", dataIndex: 'news_id', flex: 1, align: 'center' }, { header: "開啟模式", dataIndex: 'news_link_mode', flex: 1.5, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (value == "1") { return '<p style="color:red;">母視窗連結</p>'; } else if (value == "2") { return '新視窗開啟'; } } }, { header: "狀態", dataIndex: 'news_status', flex: 1, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (value == "0") { return '<p style="color:#666;">新建</p>'; } else if (value == "1") { return '<p style="color:#00F;">顯示</p>'; } else if (value == "2") { return '<p style="color:red;">隱藏</p>'; } else { return '<p style="color:#F00;">下線</p>'; } } }, { header: "排序", dataIndex: 'news_sort', flex: 1, align: 'center' }, { header: "上線時間<br />下線時間", dataIndex: '', flex: 1.5, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { var news_end = Date.parse(record.data.news_end); if (news_end < new Date()) { return record.data.news_start.toString().substr(0, 10) + '<br/><p style="color:#F00;">' + record.data.news_end.toString().substr(0, 10) + '</p>'; } else { return record.data.news_start.toString().substr(0, 10) + '<br/>' + record.data.news_end.toString().substr(0, 10); } } }, { header: "文字標題<br />文字連結", dataIndex: '', flex: 4, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (record.datanews_link_mode == 2) { return record.data.news_title + '<br /><a href="' + record.data.news_link_url + '" target="_blank">' + record.data.news_link_url + '</a>'; } else { return record.data.news_title + '<br /><a href="' + record.data.news_link_url + '">' + record.data.news_link_url + '</a>'; } } } ], tbar: [ { xtype: 'button', text: "新增", id: 'add', hidden: false, iconCls: 'icon-user-add', handler: onAddClick }, { xtype: 'button', text: "編輯", id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick }, { xtype: 'button', text: "回上頁", id: 'back', hidden: false, handler: function () { var tab; var panel = window.parent.parent.Ext.getCmp('ContentPanel'); var imag = panel.down('#imag'); var himag = panel.down('#himag'); //var imag = panel.down('#imag'); //var himag = panel.down('#himag'); if (imag) { tab = imag; } if (himag) { tab = himag;} tab.close(); } } ], bbar: Ext.create('Ext.PagingToolbar', { store: BannerNewsContentStore, pageSize: pageSize, displayInfo: true, displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}', emptyMsg: NOTHING_DISPLAY }), listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } }, selModel: sm }); Ext.create('Ext.container.Viewport', { layout: 'vbox', items: [frm,gdBannerNewsContent], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { gdBannerNewsContent.width = document.documentElement.clientWidth; this.doLayout(); } } }); //ToolAuthority(); BannerNewsContentStore.load({ params: { start: 0, limit: 25, history: document.getElementById("history").value, sid: document.getElementById("sid").value } }); if (document.getElementById('history').value == "1") { document.getElementById('edit-btnInnerEl').innerHTML = '查看'; Ext.getCmp('add').hide(); } }); /***************************新增**********************/ onAddClick = function () { //addWin.show(); editBannerNewsFunction(null, BannerNewsContentStore); } /***************************編輯**********************/ onEditClick = function () { var row = Ext.getCmp("gdBannerNewsContent").getSelectionModel().getSelection(); //alert(row[0]); if (row.length == 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else if (row.length > 1) { Ext.Msg.alert(INFORMATION, ONE_SELECTION); } else if (row.length == 1) { editBannerNewsFunction(row[0], BannerNewsContentStore); } }
handlers.homeHandler = function (ctx) { ctx.isAuth = auth.isAuth(); $.ajax('data.json') .then((contacts) => { ctx.contacts = contacts; ctx.loadPartials({ header: './templates/common/header.hbs', navigation: './templates/common/navigation.hbs', footer: './templates/common/footer.hbs', contactPage: './templates/contacts/contactPage.hbs', contact: './templates/contacts/contact.hbs', contactDetails: './templates/contacts/contactDetails.hbs', contactsList: './templates/contacts/contactsList.hbs', loginForm: './templates/forms/loginForm.hbs' }).then(function () { ctx.partials = this.partials; render(); }); }).catch(console.error); function render () { ctx.partial('./templates/welcome.hbs') .then(attachEvents) } function attachEvents() { $('.contact').click((e) => { let index = $(e.target).closest('.contact').attr('data-id'); ctx.selected = ctx.contacts[index]; render(); }); } };
ig.module( 'game.entities.menu-trigger' ) .requires( 'plusplus.core.entity' ) .defines(function () { EntityMenuTrigger = EntityTrigger.extend({ wait: 0.2, check: function (other) { this.parent(other, 'showMenu'); } }); });
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: crm/person/detail // ================================================================================ { var i; var str = ""; var ivalues = { schema : 'mne_crm', query : 'person_detail', table : 'person', dataschema : 'mne_crm', datatable : 'persondata', addrschema : 'mne_crm', addrtable : 'address', personnalschema : 'mne_personnal', personnaltable : 'personowndata', passwdschema : 'mne_system', passwdtable : 'personsharepasswd', skillschema : 'mne_personnal', skilltable : 'personskill', refidobj : 'weblet', refidname : 'companyid', refnamename : 'company', report : 'mne_person', picturepopup : 'picture', companyweblet : 'crm_company', companyselect : 'all', delschema : 'mne_crm', delfunction : 'person_del', }; var svalues = { }; weblet.initDefaults(ivalues, svalues); weblet.loadview(); var attr = { hinput : false, birthdayInput : { inputtyp : 'date' }, } weblet.findIO(attr); weblet.showLabel(); weblet.showids = new Array("personid"); weblet.titleString.add = weblet.txtGetText('#mne_lang#Person hinzufügen'); weblet.titleString.mod = weblet.txtGetText('#mne_lang#Person bearbeiten'); weblet.titleString.del = weblet.txtGetText('#mne_lang#Person' + ' <$1> ' + '#mne_lang#wirklich löschen'); weblet.titleString.delid = 'fullname'; weblet.defvalues['addressid'] = '################'; weblet.showValue = function(weblet) { if (weblet == null || typeof weblet.act_values.personid == 'undefined' || weblet.act_values.personid == '' || weblet.act_values.personid == '################') { this.add(); return true; } return MneAjaxWeblet.prototype.showValue.call(this, weblet); } weblet.ok = function() { var i; var p = {}; var name = this.act_values.name; var id = this.act_values.id; var action; var result; if (this.okaction == 'add') { action = "/db/utils/table/insert.xml"; } else { action = "/db/utils/table/modify.xml"; } p = this.addParam({}, "schema", this.initpar.schema); p = this.addParam(p, "table", this.initpar.table); p = this.addParam(p, "personidInput.old", this.act_values.personid); p = this.addParam(p, "personidInput", this.act_values.personid); if ( typeof this.obj.inputs.refid != 'undefined' ) p = this.addParam(p, "refid"); p = this.addParam(p, "firstname"); p = this.addParam(p, "lastname"); p = this.addParam(p, "ownerid"); p = this.addParam(p, "sex"); p = this.addParam(p, "sign"); p = this.addParam(p, "sorting"); p = this.addParam(p, "rollback", true); MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/start.xml", {}); MneAjaxWeblet.prototype.write.call(this, action, p); p = this.addParam({}, "schema", this.initpar.dataschema); p = this.addParam(p, "table", this.initpar.datatable); p = this.addParam(p, "persondataidInput.old", this.act_values.personid); p = this.addParam(p, "persondataidInput", this.act_values.personid); p = this.addParam(p, "birthday"); p = this.addParam(p, "email"); p = this.addParam(p, "http"); p = this.addParam(p, "role"); p = this.addParam(p, "telephonoffice"); p = this.addParam(p, "telephonpriv"); p = this.addParam(p, "telephonmobil"); p = this.addParam(p, "language"); p = this.addParam(p, "modifyinsert", 1); p = this.addParam(p, "rollback", true); result = MneAjaxWeblet.prototype.write.call(this, action, p); if (this.act_values.addressid != '') { p = {}; p = this.addParam(p, "schema", this.initpar.addrschema); p = this.addParam(p, "table", this.initpar.addrtable); p = this.addParam(p, "addressidInput.old", this.act_values.addressid); p = this.addParam(p, "addressidInput", this.act_values.addressid); p = this.addParam(p, "refidInput", this.act_values.personid); p = this.addParam(p, "addresstypidInput", "000000000001"); p = this.addParam(p, "postbox"); p = this.addParam(p, "street"); p = this.addParam(p, "cityid"); p = this.addParam(p, "modifyinsert", 1); p = this.addParam(p, "rollback", true); p = this.addParam(p, "sqlend", 1); result = MneAjaxWeblet.prototype.write.call(this, action, p); } else { p = this.addParam({}, "schema", this.initpar.addrschema); p = this.addParam(p, "table", this.initpar.addrtable); p = this.addParam(p, "refidInput.old", this.act_values.personid); p = this.addParam(p, "addresstypidInput.old", "000000000001"); p = this.addParam(p, "rollback", true); p = this.addParam(p, "sqlend", 1); result = MneAjaxWeblet.prototype.write.call(this, "/db/utils/table/delete.xml", p); } if (result == 'ok') { this.showValue(this); this.setDepends("showValue"); return false; } return true; } weblet.del = function() { var i; var p = { schema : this.initpar.delschema, name : this.initpar.delfunction, par0 : this.getParamValue(this.obj.inputs.personid), sqlend : 1 } if ( this.confirm(this.txtSprintf(this.titleString.del, this.txtFormat.call(this, this.act_values[this.titleString.delid], this.typs[this.ids[this.titleString.delid]]) ) ) != true ) return false; return MneAjaxWeblet.prototype.func.call(this, p ); } weblet.cancel = function() { this.showValue(this); return false; } weblet.print = function() { var p = { wval : this.act_values.personid, wop : "=", wcol : 'personid', sort : '', sqlend : 1 }; MneAjaxWeblet.prototype.print.call(this, p); return false; } }
'use strict'; const Models = require('bookshelf-model-loader'); const QuitLogging = Models.Base.extend({ tableName: 'quitLogging', hasTimestamps: ['timestamp'], soft: false }); module.exports = { QuitLogging: Models.Bookshelf.model('quitLogging', QuitLogging) };
/* eslint-env amd */ /* global gaTracker */ var wsdot; require([ "dojo/ready", "dojo/on", "dijit/registry", "utils", "geoportal/setupToolbar", "geoportal/setupLayout", "esri/config", "esri/map", "esri/geometry/jsonUtils", "esri/geometry/Extent", "esri/tasks/GeometryService", "esri/toolbars/navigation", "esri/dijit/HomeButton", "dijit/form/Button", "esri/dijit/Scalebar", "esri/SpatialReference", "BufferUI/BufferUIHelper", "setup", "dijit/form/RadioButton", "dijit/form/Select", "dijit/form/FilteringSelect", "dojo/data/ItemFileReadStore", "dijit/form/NumberSpinner", "dijit/form/DateTextBox", "dojo/parser", "esri/dijit/Attribution", "esri/map", "esri/arcgis/utils", "esri/dijit/Scalebar", "esri/tasks/geometry", "esri/tasks/query", "esri/toolbars/navigation", "esri/toolbars/draw", "esri/tasks/gp", "esri/layers/FeatureLayer", "esri/IdentityManager", "esri/dijit/Popup", "extensions/esriApiExtensions", "extensions/htmlPopupExtensions", "MetadataClient/metadataExtensions", "extensions/graphicsLayer", "controls/layerSorter" ], function( ready, on, registry, utils, setupToolbar, setupLayout, esriConfig, Map, jsonUtils, Extent, GeometryService, Navigation, HomeButton, Button, Scalebar, SpatialReference, BufferUIHelper, setup ) { "use strict"; var extents = null, navToolbar, qsManager; wsdot = { config: {} }; wsdot.map = null; // Sanitize URL of old style parameters (function() { if (!(window.URL && window.URLSearchParams && window.history)) { return; } const url = new URL(location.href); const sp = url.searchParams; ["layers", "center", "zoom"].forEach(function(s) { if (sp.has(s)) { sp.delete(s); } }); history.replaceState(null, window.title, url.toString()); })(); // Setup other geoportals links (function(form) { var select = form.querySelector("select[name=config]"); /** * When a "config" query string parameter has been specified, * set the default selected option to match. */ function syncSelectedWithQSSetting() { const searchParams = new URLSearchParams(location.search); // Test for presence of "config" URL param. if (searchParams.has("config")) { // Get the current "config" param from URL let currentConfig = searchParams.get("config"); // Get the option element with a value matching the // current config param. const configOption = select.querySelector( `option[value='${currentConfig}']` ); if (configOption) { // If the option has a data-url attribute, redirect // to that URL. if (configOption.dataset.url) { window.stop(); open(configOption.dataset.url, "_top"); } // Get the currently selected option. const selectedOption = select.querySelector("option[selected]"); // Remove the "selected" attribute. if (selectedOption) { selectedOption.removeAttribute("selected"); } // Set the "selected" attribute for the option // matching the config specified in the URL // parameter. if (configOption) { configOption.setAttribute("selected", "selected"); } } } } syncSelectedWithQSSetting(); // If config/internal-rmec.json cannot be reached, remove internal options. var request = new XMLHttpRequest(); request.open("head", "config/internal-rmec.json"); request.onloadend = function(e) { var internalGroup; if (e.target.status !== 200) { internalGroup = select.querySelector("optgroup[label='internal']"); select.removeChild(internalGroup); } }; request.send(); select.addEventListener("change", function (e) { let option = form.config.selectedOptions[0]; if (option.dataset.url) { open(option.dataset.url, "_top"); e.preventDefault(); } else { form.submit(); } }); })(document.getElementById("otherGeoportalsForm")); function doPostConfig(config) { wsdot.config = config; var button; // Add a method to the Date object that will return a short date string. if (Date.toShortDateString === undefined) { /** * Returns a string representation of the date in the format Month-Date-Year. * @returns {string} Short date representation of the date. */ Date.prototype.toShortDateString = function() { return ( String(this.getMonth() + 1) + "-" + String(this.getDate()) + "-" + String(this.getFullYear()) ); }; } document.getElementById("mainContainer").style.display = ""; // If a title is specified in the config file, replace the page title. if (wsdot.config.pageTitle) { document.querySelector(".page-title").innerHTML = wsdot.config.pageTitle; document.title = wsdot.config.pageTitle; } function init() { var gaTrackEvent, initBasemap = null; if ( wsdot.config.additionalStylesheets && wsdot.config.additionalStylesheets.length > 0 ) { wsdot.config.additionalStylesheets.forEach(function(path) { var link = document.createElement("link"); link.href = path; link.rel = "stylesheet"; document.head.appendChild(link); }); } // esriConfig.defaults.io.proxyUrl = "proxy.ashx"; // Specify list of CORS enabled servers. (function(servers) { if (wsdot.config.corsEnabledServers) { servers = servers.concat(wsdot.config.corsEnabledServers); } for (var i = 0; i < servers.length; i++) { esriConfig.defaults.io.corsEnabledServers.push(servers[i]); } })(["www.wsdot.wa.gov", "data.wsdot.wa.gov"]); esriConfig.defaults.geometryService = new GeometryService( wsdot.config.geometryServer ); /** * Adds a Google Analytics tracking event for the addition of a layer to the map. * @param {Event} e - layer add event. * @param {Layer} e.layer - layer that was added * @param {Layer} e.error - Error that occurred when trying to add layer. */ gaTrackEvent = function(e) { var label, basemapIdRe = /^layer\d+$/i, layer, error, action; layer = e.layer; error = e.error; label = basemapIdRe.exec(layer.id) ? "Basemap: " + layer.url : layer.id + ": " + layer.url; action = error ? "Add - Fail" : "Add"; gaTracker.send("event", "Layers", action, label); }; /** * Updates the scale level. * @param {number} level - the new scale level. */ function setScaleLabel(level) { // Set the scale. var scale = wsdot.map.getScale(level); var scaleNode = document.getElementById("scaleText"); var nFormat = window.Intl && window.Intl.NumberFormat ? new window.Intl.NumberFormat() : null; var value = nFormat ? nFormat.format(scale) : scale; scaleNode.textContent = scale ? ["1", value].join(":") : ""; } setupLayout.setupLayout(); function setupExtents() { var extentSpatialReference = new SpatialReference({ wkid: 102100 }); // Define zoom extents for menu. extents = { fullExtent: new Extent({ xmin: -14058520.2360666, ymin: 5539437.0343901999, ymax: 6499798.1008670302, xmax: -12822768.6769759, spatialReference: extentSpatialReference }) }; } setupExtents(); // Create the map, using options defined in the query string (if available). ////wsdot.config.mapOptions = QueryStringManager.getMapInitOptions(wsdot.config.mapOptions); if (wsdot.config.mapOptions.extent) { // Convert the extent definition in the options into an Extent object. wsdot.config.mapOptions.extent = new jsonUtils.fromJson( wsdot.config.mapOptions.extent ); } wsdot.map = new Map("map", wsdot.config.mapOptions); // Create the layer list once the map has loaded. wsdot.map.on("load", function () { const layerList = setup.setupLayerList(document.getElementById("layerList"), wsdot.map, wsdot.config.layers); layerList.startup(); setup.createLayerLink(layerList); }); // Add event to page that other scripts can listen for // so they can know when the map has loaded. wsdot.map.on("load", () => { const customEvent = new CustomEvent("mapload", { detail: wsdot.map }); window.dispatchEvent(customEvent); }); setupLayout.setupLegend(); // // Once the map loads, update the extent or zoom to match query string. // (function(ops) { // if (ops.zoom && ops.center) { // wsdot.map.on("load", function() { // wsdot.map.centerAndZoom(ops.center, ops.zoom); // }); // } // })(QueryStringManager.getMapInitOptions()); /** * @typedef {Object} LabelingInfoItem * @property {string} labelExpression - JSON string representation of array of field names. * @property {string} labelPlacement - e.g., "always-horizontal" * @property {TextSymbol} symbol * @property {Boolean} useCodedValues */ // /** Add a LabelLayer if a text layer has that defined. // * @param {Object} result // * @param {Layer} result.layer // * @param {LabelingInfoItem[]} result.layer.labelingInfo // * @param {Map} result.target // * @param {Error} [result.error] // */ // wsdot.map.on("layer-add-result", function(result) { // var layer, labelingInfo, liItem, labelLayer, renderer; // /** // * Moves the label layer's list item below that of the layer it is labelling. // */ // function moveLabelLayerListItem() { // var labelLayerCB, labelLayerLI, layerCB, layerLI; // labelLayerCB = document.querySelector( // "[data-layer-id='" + labelLayer.id + "']" // ); // labelLayerLI = labelLayerCB.parentElement; // layerCB = document.querySelector( // "[data-layer-id='" + layer.id + "']" // ); // layerLI = layerCB.parentElement; // layerLI.parentElement.insertBefore(labelLayerLI, layerLI.nextSibling); // } // /** // * @param {string} labelExpression - E.g., "[WRIA_NR]" // * @returns {string} - E.g., "${WRIA_NR}" // */ // function labelExpressionToTextExpression(labelExpression) { // var re = /\[([^\]]+)/i, // match, // output; // match = labelExpression.match(re); // if (match) { // output = "${" + match[1] + "}"; // } // return output; // } // if (result.layer && result.layer.labelingInfo) { // layer = result.layer; // labelingInfo = layer.labelingInfo; // if (labelingInfo.length) { // if (labelingInfo.length >= 1) { // liItem = labelingInfo[0]; // labelLayer = new LabelLayer({ // id: [layer.id, "(label)"].join(" ") // }); // renderer = new SimpleRenderer(liItem.symbol); // labelLayer.addFeatureLayer( // layer, // renderer, // labelExpressionToTextExpression(liItem.labelExpression), // liItem // ); // wsdot.map.addLayer(labelLayer); // moveLabelLayerListItem(); // } // } // } // }); // Setup the basemap gallery setup.setupBasemapGallery(wsdot.map, wsdot.config); new HomeButton({ map: wsdot.map }, "homeButton").startup(); // Setup Zoom Button wsdot.map.on("load", function() { if (wsdot.airspaceCalculator) { wsdot.airspaceCalculator.map = wsdot.map; wsdot.airspaceCalculator.form.addEventListener( "add-from-map", function() { wsdot.map.disablePopups(); } ); wsdot.airspaceCalculator.form.addEventListener( "draw-complete", function() { wsdot.map.enablePopups(); } ); } setup.setupSearchControls(wsdot.map, config.queryTasks); // Set the scale. setScaleLabel(); // Show the buffer tools form when the buffer link is clicked. (function() { var bufferLink; if (wsdot.bufferUI) { BufferUIHelper.attachBufferUIToMap(wsdot.map, wsdot.bufferUI); bufferLink = wsdot.map.infoWindow.domNode.querySelector("a.buffer"); bufferLink.addEventListener("click", function() { registry.byId("toolsAccordion").selectChild("bufferPane"); registry.byId("tabs").selectChild("toolsTab"); document.querySelector(".buffer-ui [name=distances]").focus(); }); } })(); utils.addGoogleStreetViewLink(wsdot.map.infoWindow); utils.makeDraggable(wsdot.map.infoWindow); utils.addPrintLink(wsdot.map.infoWindow, "blank.html"); // Show the disclaimer if one has been defined. utils.showDisclaimer(wsdot.config.disclaimer, wsdot.config.alwaysShowDisclaimer); setupToolbar(); Scalebar({ map: wsdot.map, attachTo: "bottom-left" }); // Setup Google Analytics tracking of the layers that are added to the map. if (window.gaTracker) { on(wsdot.map, "layer-add-result", gaTrackEvent); } wsdot.map.setupIdentifyPopups({ ignoredLayerRE: wsdot.config.noPopupLayerRe ? new RegExp(wsdot.config.noPopupLayerRe, "i") : /^layer\d+$/i }); setup.setupDrawUI(wsdot.map); // qsManager = new QueryStringManager(wsdot.map); // Attach the map to the print form (if config contains print URL). if (wsdot.printForm) { wsdot.printForm.map = wsdot.map; } setup.setupExportButton(wsdot.map); }); /** * @param {esri.geometry.ScreenPoint} zoomArgs.anchor * @param {esri.geometry.Extent} zoomArgs.extent * @param {number} zoomArgs.level * @param {esri.Map} zoomArgs.target * @param {number} zoomArgs.zoomFactor */ on(wsdot.map, "zoom-end", function(zoomArgs) { setScaleLabel(zoomArgs.level); }); // Setup the navigation toolbar. navToolbar = new Navigation(wsdot.map); navToolbar.on("extent-history-change", function() { registry .byId("previousExtentButton") .attr("disabled", navToolbar.isFirstExtent()); registry .byId("nextExtentButton") .attr("disabled", navToolbar.isLastExtent()); }); button = new Button( { iconClass: "zoomprevIcon", showLabel: false, onClick: function() { navToolbar.zoomToPrevExtent(); } }, "previousExtentButton" ); button = new Button( { iconClass: "zoomnextIcon", showLabel: false, onClick: function() { navToolbar.zoomToNextExtent(); } }, "nextExtentButton" ); } //show map on load ready(init); } (async () => { try { const config = await utils.getConfig(); doPostConfig(config); } catch (error) { console.error(error.message || error); } })(); });
/* eslint-disable jsx-a11y/anchor-is-valid */ import { useEffect } from 'react'; import { projectDesc as data, getCorrectObj } from '../assets/data/data'; import { Link, useParams } from 'react-router-dom'; import { ReactComponent as LeftIcon } from '../assets/images/icons/arrow-left.svg'; import { ReactComponent as RightIcon } from '../assets/images/icons/arrow-right.svg'; function PortfolioDetail({ viewport }) { let { work } = useParams(); let curIdx = getCorrectObj[work]; const { projectName, projectBg, projectSummary, projectSkills, projectType, imgName, } = data[curIdx]; // find next/ prev index let nextIdx = 0; let prevIdx = 0; if (curIdx === 0) { nextIdx = 1; prevIdx = 3; } else if (curIdx === 3) { nextIdx = 0; prevIdx = 2; } else { nextIdx = curIdx + 1; prevIdx = curIdx - 1; } const nextName = data[nextIdx].projectName; const prevName = data[prevIdx].projectName; useEffect(() => { window.scrollTo(0, 0); }); const postfix = viewport === 'desktop' ? `@2x` : ''; const staticImg1 = require(`../assets/images/detail/${viewport}/image-${imgName}-preview-1${postfix}.jpg`) .default; const staticImg2 = require(`../assets/images/detail/${viewport}/image-${imgName}-preview-2${postfix}.jpg`) .default; const heroImg = require(`../assets/images/detail/${viewport}/image-${imgName}-hero${postfix}.jpg`) .default; return ( <> <div className="project-main-container"> <img src={heroImg} alt="hero" className="project-main-container__img" /> <div className="project-main-container__bottom"> <div className="project-detail"> <h1 className="project-detail__name">{projectName}</h1> <p className="project-detail__summary"> {projectSummary} </p> <p className="project-detail__type">{projectType}</p> <p className="project-detail__skills"> {projectSkills} </p> <a href="#" className="project-detail__link-btn"> View Website </a> </div> <div> <div className="project-main-container__background"> <h1>Project Background</h1> <p>{projectBg}</p> </div> <div className="project-main-container__static-preview"> <h1>Static Previews</h1> <img src={staticImg1} alt="preview 1" /> <img src={staticImg2} alt="preview 2" /> </div> </div> </div> </div> <div className="slider-container"> <Link to={`/portfolio/${prevName.toLowerCase()}`} className="slider-container__btn"> <div className="slider-container__info"> <LeftIcon className="slider-container__icon" /> <p>{prevName}</p> <p>Previous Project</p> </div> </Link> <Link to={`/portfolio/${nextName.toLowerCase()}`} className="slider-container__btn"> <div className="slider-container__info"> <RightIcon className="slider-container__icon" /> <p>{nextName}</p> <p>Next Project</p> </div> </Link> </div> </> ); } export default PortfolioDetail;
let quotesData; let currentQuote = ""; let currentAuthor = ""; let colors = ['#16a085', '#27ae60', '#2c3e50', '#f39c12', '#e74c3c', '#9b59b6', '#FB6964', '#342224', "#472E32", "#BDBB99", "#77B1A9", "#73A857"]; function getRandomQuote() { return quotesData.quotes[Math.floor(Math.random() * quotesData.quotes.length)]; } function getRandomColor(){ return colors[Math.floor(Math.random()*colors.length)]; } function openURL(url){ window.open(url, 'Share', 'width=550, height=400, toolbar=0, scrollbars=1 ,location=0 ,statusbar=0,menubar=0, resizable=0'); } function getQuote() { let randomQuote = getRandomQuote(); currentQuote = randomQuote.quote; currentAuthor = randomQuote.author; $("#text").animate({opacity: 0},500,function(){ $(this).animate({opacity: 1},500); $("#text").text(currentQuote); }); $("#author").animate({opacity: 0},500,function(){ $(this).animate({opacity: 1},500); $("#author").text(currentAuthor); }) let color = getRandomColor(); document.documentElement.style.setProperty("--themecolor", color); $("html body").animate({backgroundColor: color},1000 ); $('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + currentQuote + '" ' + currentAuthor)); } function getQuotes() { return $.ajax({ headers: { Accept: "application/json" }, url: 'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json', success: function(jsonQuotes) { if (typeof jsonQuotes === 'string') { quotesData = JSON.parse(jsonQuotes); console.log(quotesData+" "); } } }); } $("document").ready(function(){ getQuotes().then(()=>{ getQuote(); }); $('#new-quote').on('click', getQuote); $('#tweet-quote').on('click', function() { openURL('https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + currentQuote + '" ' + currentAuthor)); }); });
/*$(function(){ $("#header").load("php/header.php"); })*/ /*图片轮播*/ /*异步加载轮播图片*/ $(function(){ $.ajax({ url : 'php/getPic.php', data:'', type:'get', success:function(data){ data = JSON.parse(data); //console.log(data); $($(".swiper-slide")[0]).append(data[2]); $($(".swiper-slide")[1]).append(data[0]); $($(".swiper-slide")[2]).append(data[1]); $($(".swiper-slide")[3]).append(data[2]); $($(".swiper-slide")[4]).append(data[0]); } }) }); var mySwiper = new Swiper ('.swiper-container', { speed: 400, direction: 'horizontal', loop: true, // 分页器 pagination: '.swiper-pagination', paginationClickable :true, paginationBulletRender: function (index, className) { return '<span class="' + className + '"></span>'; }, // 前进后退按钮 nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', autoplay: 2000, autoplayDisableOnInteraction: false, }); /*新闻滚动*/ /*异步加载新闻*/ $(function(){ $.ajax({ type : 'get', url : 'php/getNews.php', data : '', success : function(datas){ datas = JSON.parse(datas); $.each(datas, function(i, data){ alert(1); $("#newsHot-content").append('<li><a href="detail.php?aid='+data.a_id+'">' + data.a_title + '</a><span>' + data.a_time + '</span></li>'); /*$("#newsHot-content").append(` <li> <a href="detail.php?aid=${data.a_id}">${data.a_title}</a> <span>${data.a_time}</span> </li> `);*/ }) startScroll(); } }) }) function startScroll(){ var newsScroll = document.getElementById("newsHot-scroll"); var newsHotContent = document.getElementById("newsHot-content"); var newsHotContent2 = document.getElementById("newsHot-content2"); newsHotContent2.innerHTML = newsHotContent.innerHTML; function scrollUp(){ if(newsScroll.scrollTop >= newsHotContent.offsetHeight){ newsScroll.scrollTop = 0; }else{ newsScroll.scrollTop++; } } var timerScroll = setInterval(scrollUp, 50); $("#newsHot-scroll").mouseenter(function(){ clearInterval(timerScroll); timerScroll = null; }) $("#newsHot-scroll").mouseleave(function(){ timerScroll = setInterval(scrollUp, 25); }) } /***********搜索建议************/ var searchInput = document.getElementById("search"); var searchUl = document.getElementById("search_adv"); searchInput.onkeyup = function(e){ if(this.value == ""){ $(searchUl).empty().hide(); return; } var searchValue = this.value; //当按下数字字母、退格、空格时发送ajax请求 if(e.keyCode > 40 || e.keyCode == 8 || e.keyCode == 32){ sendAjax(searchValue); } //上键 else if(e.keyCode == 38){ if(selectedLI == -1){ setHighLight($("#search_adv li").length - 1); }else{ setHighLight(selectedLI - 1); } } //下键 else if(e.keyCode == 40){ if(selectedLI == -1){ setHighLight(0); }else{ setHighLight(selectedLI + 1); } } //enter键 else if(e.keyCode == 13){ if($('#search_adv').find('li').length == 0 || selectedLI == -1){ return; } $("#search").val($("#search_adv").find('li').eq(selectedLI).text()); $(searchUl).empty().hide(); } } //ajax请求数据 function sendAjax(searchValue){ $.ajax({ url:'php/searchAdv.php', data: {'searchTxt':searchValue}, type: 'post', success:function(data){ data = JSON.parse(data); if(data.length){ $(searchUl).empty(); var frag = document.createDocumentFragment(); $.each(data, function(index, value){ //创建li并绑定事件:鼠标进入高亮 $('<li></li>').text(value).appendTo($(searchUl)) .hover( function(){ $(this).addClass('active').siblings().removeClass('active'); selectedLI = index; }, function(){ $(this).removeClass('active'); selectedLI = -1; } ) .click(function(){ $("#search").val(value); $(searchUl).empty().hide(); }) }) setHighLight(0); $(searchUl).show(); }else{ $(searchUl).empty().hide(); } } }) } //该方法用于设置下拉项的高亮 var selectedLI = null; var setHighLight = function(item){ //更新索引值 selectedLI = item; if(selectedLI < 0){ selectedLI = $("#search_adv li").length - 1; }else if(selectedLI>$("#search_adv li").length - 1){ selectedLI = 0; } //移出其他高亮,当前高亮 $("#search_adv li").removeClass("active").eq(selectedLI).addClass("active"); } //搜索框失去焦点隐藏 searchInput.onblur = function(){ setTimeout(function(){ $(searchUl).empty().hide(); },100) } /***********搜索建议************/ /***********搜索建议************/ $("#school-navbar ul li a[href^='#']").attr("href","article.php");
import { Button, Card, CardActions, CardContent, CardMedia, Typography } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles(theme => ({ card: { marginTop: theme.spacing(2), }, })); function Saver({ title, text, children }) { const classes = useStyles(); return ( <Card className={classes.card}> <CardContent> <Typography variant="h6"> {title} </Typography> <Typography color="textSecondary" variant="body1" component="div"> {text} </Typography> </CardContent> {children} </Card> ); } function SaverAction({ text, href }) { return ( <CardActions> <Button color="primary" href={href} target="_blank">{text}</Button> </CardActions> ); } function SaverImage({ image }) { return <CardMedia image={image} component="img" />; } function SaverVideo({ src }) { return <CardMedia component="iframe" width="100%" height="223" frameBorder="0" allowFullScreen src={src} />; } export { Saver, SaverAction, SaverImage, SaverVideo };
// -------------------------------------------------------------------------------STUDENTS $(function(){ console.log("ready"); // $.ajaxSetup({ // headers: { // 'X-CSRF-TOKEN': '{!! csrf_token() !!}' // } // }); $("button").on("click", function(){ var id = $(this).attr("data"); var div = $(this).parents("div.innerPanel"); $.get("/api/student/delete/"+id, function(res){ div.remove(); }); }); }); //HOVER ZOOM .INNERPANEL // $(document).ready( function() { // $('.innerPanel').hover( // function() { // $(this).animate({ 'zoom': 1.4 }, 50); // }, // function() { // $(this).animate({ 'zoom': 1 }, 50); // }); // }); // ------------------------------------------------------------------------------------HOME // $(function(){ // console.log("ready"); // $.ajaxSetup({ // headers: { // 'X-CSRF-TOKEN': '{!! csrf_token() !!}' // } // }); // $("button").on("click", function(){ // var id = $(this).attr("data"); // var div = $(this).parents("div.popUp"); // $.post("/api/notice/delete/"+id, {id: id}, function(res){ // div.remove(); // }); // }); // }); // HOVER $(document).ready( function() { $('.attending .popUp').hover( function() { $(this).animate({ 'zoom': 1.2 }, 100); }, function() { $(this).animate({ 'zoom': 1 }, 100); }); }); // {{-- FACEBOOK --}} $(document).ready( function() { (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }); // {{-- INTRO VIDEO --}} $(document).ready( function() { setTimeout(function() { $("video").remove(); }, 16000); }); //-------------------------------------------------------------------------COMP // {{-- CAROUSEL --}} $(document).ready( function(){ $('.list').slick({ infinite: true, slidesToShow:1, slidesToScroll: 1 }); }); // HOVER $(document).ready( function() { $('aside').hover( function() { $(this).animate({ 'zoom': 1.2 }, 100); }, function() { $(this).animate({ 'zoom': 1 }, 100); }); }); //-------------------------------------------------------------------------- STUDENTDETAILS $(document).ready( function(){ $('#carousel').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 1 }); }); // $(document).ready( function() { // $('.imageHolder').hover( // function() { // $(this).animate({ 'zoom': 1.2 }, 100); // }, // function() { // $(this).animate({ 'zoom': 1 }, 100); // }); // }); // {{-- DELETE NOTICE --}} // <script> // $(function(){ // console.log("ready"); // $.ajaxSetup({ // headers: { // 'X-CSRF-TOKEN': '{!! csrf_token() !!}' // } // }); // $("button").on("click", function(){ // var id = $(this).attr("data"); // var div = $(this).parents("div.popUp"); // $.post("/api/notice/delete/"+id, {id: id}, function(res){ // div.remove(); // }); // }); // }); // </script> // {{-- HOVER --}} // <script type="text/javascript"> // $(document).ready( function() { // $('.attending .popUp').hover( // function() { // $(this).animate({ 'zoom': 1.2 }, 100); // }, // function() { // $(this).animate({ 'zoom': 1 }, 100); // }); // }); // </script> // {{-- FACEBOOK --}} // <script> // (function(d, s, id) { // var js, fjs = d.getElementsByTagName(s)[0]; // if (d.getElementById(id)) return; // js = d.createElement(s); js.id = id; // js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5"; // fjs.parentNode.insertBefore(js, fjs); // }(document, 'script', 'facebook-jssdk')); // </script> // {{-- INTRO VIDEO --}} // <script type="text/javascript"> // setTimeout(function() { // $("video").remove(); // }, 16000); // </script>
import React from 'react'; class Sidebar extends React.Component { render() { return ( <aside className="sidebar"> <ul className="sidebar--nav"> {this.props.children} </ul> </aside> ); } } export default Sidebar;
var cols; var rows; var w = 20; var frameSlider; var drawing = false; var killing = false; var running = false; var gen = 0; var lcells = 0; var cells = []; var saveArray = []; /* function preload() { soundFormats('mp3', 'ogg'); myMusic = loadSound('assets/backgroundMusic.mp3'); } */ function setup() { //myMusic.setVolume(0,1); //myMusic.play(); createCanvas(window.innerWidth,window.innerHeight); cols = floor(width/w); rows = floor(height/w); for (var i = 0; i < cols; i++) { cells.push([]); for (var j = 0; j < rows; j++) { var cell = new Cell(i, j); cells[i].push(cell); } } frameSlider = createSlider(1, 60, 15, 1); frameSlider.position(10, 40) } function draw() { background(0); fill(0); for (var i = 0; i < cells.length; i++) { for (var j = 0; j < cells[i].length; j++) { cells[i][j].draw(); //cells[i].rand(); if (cells[i][j].alive) { cells[i][j].counter -= 10; } } } //hover if(drawing) { for (var i = 0; i < cells.length; i++) { for (var j = 0; j < cells[i].length; j++) { if (mouseX >= cells[i][j].x && mouseX <= cells[i][j].x + w && mouseY >= cells[i][j].y && mouseY <= cells[i][j].y + w) { cells[i][j].alive = true; cells[i][j].counter = 255; cells[i][j].colour = random(255); } } } } if(killing) { for (var i = 0; i < cells.length; i++) { for (var j = 0; j < cells[i].length; j++) { if (mouseX >= cells[i][j].x && mouseX <= cells[i][j].x + w && mouseY >= cells[i][j].y && mouseY <= cells[i][j].y + w) { cells[i][j].alive = false; cells[i][j].counter = 255; cells[i][j].colour = random(255); } } } } if (running) { run(); frameRate(frameSlider.value()); gen++; } else { frameRate(60); } fill(255); textSize(32); text("Generation:", 10, 35); text(gen, 180, 37); text("Live Cells:", width - 210, 35); lcells = 0; for (var i = 0; i < cells.length; i++) { for (var j = 0; j < cells[i].length; j++) { if (cells[i][j].alive) { lcells += 1; } } } text(lcells, width - 60, 37); } function Cell(i, j) { this.n = 0; this.colour = random(255); this.counter = 255; this.x = i * w - 1; this.y = j * w - 1; this.alive = false; this.balive = false; this.draw = function() { noFill(); stroke(255, 50); if (this.alive) { fill(0,0,255); } else if (this.balive) { fill(0,50,0); } else { fill(0); } rect(this.x, this.y, w, w); } /* this.rand = function() { if (random(10000) <= 1) { this.alive = true; } } */ } function mousePressed() { for (var i = 0; i < cells.length; i++) { for (var j = 0; j < cells[i].length; j++) { if (mouseX >= cells[i][j].x && mouseX <= cells[i][j].x + w && mouseY >= cells[i][j].y && mouseY <= cells[i][j].y + w) { if (cells[i][j].alive) { killing = true; } else { drawing = true; } } } } } function mouseReleased() { drawing = false; killing = false; } function keyPressed() { if (keyCode === CONTROL) { running = !running; } if (!running && keyCode === SHIFT) { run(); gen++; } /* if (!running && keyCode === UP_ARROW) { // Object.create(every cell) and push to saveArray for (var i = 0; i < cols; i++) { var row = []; for (var j = 0; j < rows; j++) { row.push(Object.create(cells[i][j])); } saveArray.push(row); } console.log('save'); } if (!running && keyCode === DOWN_ARROW) { cells = saveArray; console.log('load') } */ } function run() { for (var i = 0; i < cells.length; i++) { for (var j = 0; j < cells[i].length; j++) { cells[i][j].n = 0; //top left if (i - 1 >= 0 && j - 1 >= 0) { if (cells[i-1][j-1].alive) { cells[i][j].n += 1; } } //top right if (i - 1 >= 0 && j + 1 < cells[i].length) { if (cells[i-1][j+1].alive) { cells[i][j].n += 1; } } //bottom left if (i + 1 < cells.length && j - 1 >= 0) { if (cells[i+1][j-1].alive) { cells[i][j].n += 1; } } //bottom right if (i + 1 < cells.length && j + 1 < cells[i].length) { if (cells[i+1][j+1].alive) { cells[i][j].n += 1; } } //top if (i - 1 >= 0) { if (cells[i-1][j].alive) { cells[i][j].n += 1; } } //bottom if (i + 1 < cells.length) { if (cells[i+1][j].alive) { cells[i][j].n += 1; } } //left if (j - 1 >= 0) { if (cells[i][j-1].alive) { cells[i][j].n += 1; } } //right if (j + 1 < cells[i].length) { if (cells[i][j+1].alive) { cells[i][j].n += 1; } } } } for (var i = 0; i < cells.length; i++) { for (var j = 0; j < cells[i].length; j++) { if (cells[i][j].alive) { //game of life if (cells[i][j].n == 2 || cells[i][j].n == 3) { cells[i][j].alive = true; cells[i][j].balive = true; } else { cells[i][j].alive = false; } } else if (cells[i][j].n == 3) { cells[i][j].alive = true; cells[i][j].balive = true; } else { cells[i][j].alive = false; } } } }
// Routing var Router = ReactRouter; var DefaultRoute = Router.DefaultRoute; var Link = Router.Link; var Route = Router.Route; var RouteHandler = Router.RouteHandler; var Navigation = Router.Navigation; // Intl var IntlMixin = ReactIntl.IntlMixin; var FormattedRelative = ReactIntl.FormattedRelative; var App = React.createClass({ render: function() { return ( <RouteHandler/> ); } }); var Header = React.createClass({ // Navigation mixin required to use ReactRouter's `goBack(..)` mixins: [Navigation], render: function() { return ( <div className="bar bar-header bar-stable"> {this.props.hideBackButton ? null : <button onClick={this.goBack} className="button icon-left ion-chevron-left button-clear">Back</button>} <h1 className="title">{this.props.title}</h1> </div> ); } }); var Dashboard = React.createClass({ render: function() { return ( <div> <Header title="Poop Monitor" hideBackButton={true} /> <div className="content has-header"> <EventSelector/> <EventHistory/> </div> </div> ); } }); var EventTypeLink = React.createClass({ render: function() { return ( <Link to={this.props.linkTo} className="button">{this.props.name}</Link> ); } }); var EventSelector = React.createClass({ render: function() { var eventTypes = [ { name: "Diaper", linkTo: "diaperEvent", imageSrc: "#" }, { name: "Food", linkTo: "foodEvent", imageSrc: "#" }, { name: "Sleep", linkTo: "sleepEvent", imageSrc: "#" }, { name: "Wake", linkTo: "wakeEvent", imageSrc: "#" } ]; var eventTypeNodes = eventTypes.map(function(eventType, keyIndex) { return ( <EventTypeLink name={eventType.name} linkTo={eventType.linkTo} imageSrc={eventType.imageSrc} key={keyIndex} /> ); }); return ( <div className="button-bar bar-light padding"> {eventTypeNodes} </div> ); } }); // Renders the list of events, in order of most recent to oldest var EventHistory = React.createClass({ getInitialState: function() { return {events: []}; }, componentWillMount: function() { var eventItems = []; this.dataProvider = new PMDataProvider(); this.dataProvider.getEvents(function(event) { // `unshift` used instead of `push` to place the newest items at the // top, timeline style eventItems.unshift(event); this.setState({ events: eventItems }); }.bind(this)); }, componentWillUnmount: function() { this.dataProvider.close(); }, render: function() { var eventNodes = this.state.events.map(function (event, keyIndex) { var eventComponent; if (event.type === "Diaper") { return (<DiaperEvent event={event} key={keyIndex} />); } else { return (<Event event={event} key={keyIndex} />); } }); return ( <div className="list card"> {eventNodes} </div> ); } }); /* * Event rendering components */ var Event = React.createClass({ render: function() { var event = this.props.event; var imageSrc = "img/" + event.type + ".png"; var eventDate = new Date(event.date); return ( <EventItem imageSrc={imageSrc} type={event.type} date={eventDate} notes={event.notes} /> ); } }); var DiaperEvent = React.createClass({ render: function() { var event = this.props.event; var diaperImageSrc = "img/diaper_" + (event.pee ? "pee" : "") + (event.pee && event.poo ? "_" : "") + (event.poo ? "poo" : "") + ".png"; var eventDate = new Date(event.date); return ( <EventItem imageSrc={diaperImageSrc} type={event.type} date={eventDate} notes={event.notes} /> ); } }); var EventItem = React.createClass({ mixins: [IntlMixin], render: function() { return ( <div className="item item-avatar"> <img src={this.props.imageSrc} alt={this.props.type + " image"} /> <h2>{this.props.type}</h2> <p><FormattedRelative value={this.props.date} /></p> {this.props.notes ? <blockquote>{this.props.notes}</blockquote> : null} </div> ); } }); /* * Event creation components */ var AddDiaperEvent = React.createClass({ // Navigation mixin required to use ReactRouter's `transitionTo(..)` mixins: [Navigation], diaperEventAdded: function() { // Return to root this.transitionTo('/'); }, render: function() { return ( <div> <Header title="Diaper Event"/> <div className="content has-header"> <DiaperEventForm successCallback={this.diaperEventAdded} /> </div> </div> ); } }); var AddFoodEvent = React.createClass({ mixins: [Navigation], eventAdded: function() { this.transitionTo('/'); }, render: function() { return ( <div> <Header title="Food Event"/> <div className="content has-header"> <GenericEventForm eventType="Food" successCallback={this.eventAdded} /> </div> </div> ); } }); var AddSleepEvent = React.createClass({ mixins: [Navigation], eventAdded: function() { this.transitionTo('/'); }, render: function() { return ( <div> <Header title="Sleep Event"/> <div className="content has-header"> <GenericEventForm eventType="Sleep" successCallback={this.eventAdded} /> </div> </div> ); } }); var AddWakeEvent = React.createClass({ mixins: [Navigation], eventAdded: function() { this.transitionTo('/'); }, render: function() { return ( <div> <Header title="Wake Event"/> <div className="content has-header"> <GenericEventForm eventType="Wake" successCallback={this.eventAdded} /> </div> </div> ); } }); // Enable touch events React.initializeTouchEvents(true); // Define the app's routes var routes = ( <Route name="app" path="/" handler={App}> <Route name="diaperEvent" handler={AddDiaperEvent}/> <Route name="foodEvent" handler={AddFoodEvent}/> <Route name="sleepEvent" handler={AddSleepEvent}/> <Route name="wakeEvent" handler={AddWakeEvent}/> <DefaultRoute handler={Dashboard}/> </Route> ); //Router.run(routes, Router.HistoryLocation, function (Handler) { Router.run(routes, function (Handler) { React.render(<Handler/>, document.getElementById("app")); });
module.exports = registrant => ({ from: 'Code Championship <confirmation@codechampionship.com>', // sender address to: registrant.parent_or_guardian_email || 'confirmation@codechampionship.com', // list of receivers subject: '🏆 Your Code Championship Confirmation 🏆', // Subject line html: ` <p>Thank you so much for registering for Code Championship!</p> <p>Your confirmation number is: <b>${registrant.id}</b></p> `, // plain text body });
( function() { 'use strict'; angular.module( 'root', [ 'core', 'components', 'templates', 'ui.router', 'ui.bootstrap', 'angular-loading-bar', 'ngSanitize' ] ) .run( function( $trace ) { $trace.enable( "TRANSITION" ); } ) .config( function( $httpProvider, $locationProvider, cfpLoadingBarProvider ) { // removes '!' after '#' in url -- angular 1.6 defaults to this now, should figure out why $locationProvider.hashPrefix( '' ); cfpLoadingBarProvider.includeSpinner = false; // cors related stuff $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; } ); } )();
function TopplisteSortert (data) { var celler = data.feed.entry; var flateSvar = _.chain(celler) .map(function (celle) { return celle.content.$t; }) .filter(function (celle) { return celle != ""; }) .value(); var svarGruppert = []; while (flateSvar.length) { svarGruppert.push(_.first(flateSvar, 2)); flateSvar = _.drop(flateSvar, 2); } var svar = _.chain(svarGruppert) .map(function (svar) { return { navn: svar[0], score: svar[1] }; }) .groupBy("score") .sortBy("score"); this.pallen = svar .first(3) .value(); this.resten = svar .rest(3) .flatten() .value(); }
const fs = require("fs"); const path = require("path"); const Yaml = require("js-yaml"); const Rspath = require("./rspathutils.js"); const Queue = require("promise-queue"); const RecursiveReaddir = require("recursive-readdir"); const rootconfig = Yaml.safeLoad(fs.readFileSync(__dirname + "/config.yaml", "utf8")); const ROOT = rootconfig.repository.path + "/issues"; async function calc_filelist(){ return await RecursiveReaddir(ROOT).then(files => { return Promise.resolve(files.filter(e => path.extname(e) == ".yaml")); }); } async function run(){ const files = await calc_filelist(); //console.log(files); files.forEach(e => { const obj = Yaml.safeLoad(fs.readFileSync(e, "utf8")); const key = obj.key; if(obj.changelog){ if(obj.changelog.maxResults != obj.changelog.total){ console.log("Truncated result",key,e); } if(obj.changelog.startAt != 0){ console.log("Something wrong",key,e); } }else{ console.log("WARN: no changelog", key); } if(obj.fields.comment){ if(obj.fields.comment.maxResults != obj.fields.comment.total){ console.log("Truncated result",key,e); } if(obj.fields.comment.startAt != 0){ console.log("Something wrong",key,e); } }else{ console.log("WARN: no comment", key); } }); } run();
class _Node { constructor(value = null, next = null, previous = null) { this.value = value; this.next = next; } } class LinkedList { constructor() { this.head = null; } insertFirst(item) { this.head = new _Node(item, this.head); } insertLast(item) { if (this.head === null) { this.insertFirst(item); } else { let tempNode = this.head; while (tempNode.next !== null) { tempNode = tempNode.next; } tempNode.next = new _Node(item, null); } } insertBefore(item, key) { if (this.head === null) { this.insertFirst(item); return; } let currNode = this.head; let previousNode = this.head; while (currNode !== null && currNode.value !== key) { previousNode = currNode; currNode = currNode.next; } previousNode.next = new _Node(item, currNode); } insertAfter(item, key) { if (this.head === null) { this.insertFirst(item); return; } let currNode = this.head; let previousNode = this.head; while (currNode !== null && previousNode.value !== key) { previousNode = currNode; currNode = currNode.next; } previousNode.next = new _Node(item, currNode); } insertAt(item, key) { if (this.head === null) { this.insertFirst(item); return; } let currNode = this.head; let previousNode = this.head; for (let i = 1; i < parseInt(key); i++) { previousNode = currNode; currNode = currNode.next; } previousNode.next = new _Node(item, currNode); } moveHeadTo(m) { console.log(m); let i = 1; let oldHead = this.head; this.head = this.head.next; let temp = this.head; while (i < m && temp.next !== null) { temp = temp.next; i++; } oldHead.next = temp.next; temp.next = oldHead; } find(item) { let currNode = this.head; if (!this.head) { return null; } while (currNode.value !== item) { if (currNode.next === null) { return null; } else { currNode = currNode.next; } } return currNode; } remove(item) { if (!this.head) { return null; } if (this.head.value === item) { this.head = this.head.next; return; } let currNode = this.head; let previousNode = this.head; while (currNode !== null && currNode.value !== item) { previousNode = currNode; currNode = currNode.next; } if (currNode === null) { console.log('Item not found'); return; } previousNode.next = currNode.next; } } module.exports = LinkedList;
import axios from 'axios' const baseUrl = 'https://pokeapi.co/api/v2/' const getPokeByType = type => { const promise = axios( `${baseUrl}type/${encodeURIComponent(type.toLowerCase())}`, { method: 'GET' } ) return promise } export default getPokeByType
var mongoose = require('mongoose'); var passportLocalMongoose = require('passport-local-mongoose'); var user_schema = new mongoose.Schema({ username: String, password: String }); user_schema.plugin(passportLocalMongoose); user = mongoose.model('user', user_schema); module.exports = user; // route middleware to make sure a user is logged in user.isLoggedIn = function(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()){ return next(); } // if they aren't redirect them to the home page res.redirect('/users/login'); }
function init() { var elForm = document.getElementById("form"); var nval = new NValTippy.NValTippy(elForm); var btn = document.getElementById("submitBtn"); btn.addEventListener("click", function(e){ e.preventDefault(); if(nval.isValid()){ alert("Form is valid.") } }); }
import axios from 'axios'; export const getData = () => async dispatch => { // const token = await sessionStorage.getItem('accessToken'); const response = await axios.get('http://econseil.dd:8083/jsonapi/node/diagramme', { // headers: { // // eslint-disable-next-line no-template-curly-in-string // Authorization: `Bearer ${token}`, // } }) dispatch( { type: 'GET_DIAG', payload: response.data } ) }
import React from 'react'; import WrapContent from '../HOC/WrapContent/WrapContent'; import Fade from '@material-ui/core/Fade'; import { Scrollbars } from 'react-custom-scrollbars'; import useMediaQuery from '@material-ui/core/useMediaQuery'; const FilterBlock = ({ visible }) => { const matches = useMediaQuery('(max-width:500px)'); return ( <Fade in={visible} timeout={300}> <div className={'FilterBlock'} style={{display: !visible ? 'none' : 'block'}}> <WrapContent> <Scrollbars autoHeight autoHeightMax={matches ? 320 : 620} renderTrackHorizontal={props => <div {...props} className="track-horizontal"/>} renderTrackVertical={props => <div {...props} className="track-vertical"/>} renderThumbHorizontal={props => <div {...props} className="thumb-horizontal"/>} renderThumbVertical={props => <div {...props} className="thumb-vertical"/>} renderView={props => <div style={{paddingRight: 15, ...props.style}} />} > { Array.from(new Array(3)).map((_, ind) => { return ( <React.Fragment key={ind}> <div className="infoBlock"> <div className="titleBlock"> Государственное автономное учреждение здравоохранен ия Московской области «Центральная городская клиническая больница г. Реутов» </div> <div className="addressPhone"> <p className="address">г.Реутов, ул. Гагарина, д.4</p> <p className="phone">8 (903) 722-61-53</p> </div> </div> <div className="infoBlock"> <div className="titleBlock"> Государственное бюджетное учреждение здравоохранения Московской области «Балашихинская областная больница» </div> <div className="addressPhone"> <p className="address">143900 г.Балашиха, ш.Энтузиастов д.41</p> <p className="phone">8 (916) 431-48-47</p> <p className="phone">8 (915) 451-08-24</p> </div> </div> <div className="infoBlock"> <div className="titleBlock"> Государственное бюджетное учреждение здравоохранения Московской области «Видновская районная клиническая больница» </div> <div className="addressPhone"> <p className="address">142700 Ленинский район, г. Видное, пр-т Ленинского комсомола, д.36А</p> <p className="phone">8 (916) 077-75-74</p> </div> </div> </React.Fragment> ) }) } </Scrollbars> </WrapContent> </div> </Fade> ) } export default FilterBlock;
var path = require('path') , mkdirp = require('mkdirp') , log = require('npmlog') , step = require('step') , sh = require('../sh') , cloner = require('./clone') , converter = require('./convert') ; function prepareConvertedPath() { var that = this; log.verbose('preparing converted path', that); log.verbose('preparing converted path', that.data.convertedPath); mkdirp(that.data.convertedPath, function(err) { if (err) { log.error('Unable to create: ', convertedPath); return; } that(); }); } function convert () { var that = this , opts = { directoryFilter : that.data.directoryFilter , fileFilter : that.data.fileFilter , targetPath : that.data.convertedPath , highlighter : that.data.highlighter } ; log.verbose('converting', opts); converter.convertFolder( that.data.sourcePath , opts , function(err) { if (err) log.error(err); that(); } ); } function zipIt () { var src = this.data.convertedPath , tgt = path.join(this.data.convertedPath, '..', this.data.repoName + '.zip'); log.info('zipping', { src: src, tgt: tgt }); sh.zip(src, tgt, this); } module.exports.convert = function (opts, convertedCb) { function init () { try { this.data = { convertedPath : opts.target , sourcePath : opts.source , repoName : path.basename(opts.source) , directoryFilter : opts.directories.split(',') , fileFilter : opts.files ? opts.files.split(',') : undefined , highlighter : opts.highlighter }; } catch (err) { convertedCb(err); return; } this(); } step( init , prepareConvertedPath , convert , zipIt , convertedCb ); }; module.exports.cloneAndConvert = function (opts, clonedAndConvertedCb) { function init () { try { this.data = { url : opts.url , targetPath : opts.target , directoryFilter : opts.directories.split(',') , fileFilter : opts.files ? opts.files.split(',') : undefined , highlighter : opts.highlighter }; } catch (err) { clonedAndConvertedCb(err); return; } this(); } function prepareTargetPath() { var that = this; log.verbose('Preparing target path'); mkdirp(that.data.targetPath, function(err) { if (err) { log.error('Unable to create: ', targetPath); return; } that(); }); } function clone () { var that = this; log.info('Cloning', { url: that.data.url, target: that.data.targetPath }); cloner.cloneGitRepository(that.data.url, { targetPath: that.data.targetPath }, function(err, res) { if (err) { log.error('Unable to clone: ', that.data.url); log.error(err); return; } log.verbose('cloned', res); that.data.repoName = res.repoName; that.data.sourcePath = res.clonedRepoPath; that.data.convertedPath = res.clonedRepoPath + '_converted'; that(); }); } step( init , prepareTargetPath , clone , prepareConvertedPath , convert , zipIt , clonedAndConvertedCb ); };
import fetch from 'node-fetch'; import { Map, List, fromJS } from 'immutable'; import diff from 'immutablediff'; import logger from 'winston'; function parse(json) { const frameworks = json.frameworks.map((fw) => { return { active: fw.active, name: fw.name, id: fw.id, resources: fw.resources, used_resources: fw.used_resources, webui_url: fw.webui_url, }; }); const slaves = json.slaves.map((slave) => { slave.url = slave.pid.split('@')[1]; return { pid: slave.pid, hostname: slave.hostname, resources: slave.resources, used_resources: slave.used_resources, }; }); const data = { activated_slaves: json.activated_slaves, cluster: json.cluster, flags: json.flags, frameworks, git_tag: json.git_tag, hostname: json.hostname, slaves, version: json.version, }; const newState = fromJS(data); return newState; } async function getState(url) { // const master = process.env.MESOS_MASTER || 'http://localhost:5050'; const response = await fetch(url + '/state.json'); const json = await response.json(); return parse(json); } function glueMasterAndSlaves(master, slaves) { return master.mergeDeep(fromJS({'slaves': slaves})); } async function getSlaves(slaves) { const data = await Promise.all(slaves.map((slave) => { const url = 'http://localhost:5050/' + slave.get('pid').split(':')[1]; return getState(url); })); return data; } export function updateState(context, newState) { context.state = newState; context.clients = context.clients.map(client => { // console.log('diff', diff(client.get('state'), newState).toJS()); return client.set('newMessage', diff(client.get('state'), newState)) .set('state', newState); }); return context.clients; } function notifyListeners(allClients) { allClients.forEach(client => { if (client.get('newMessage').count() > 0) { client.get('socket').emit('MESOS_DIFF', client.get('newMessage')); } }); } export function connect(context, socket) { socket.emit('MESOS_INIT', context.state); context.clients = context.clients.push(fromJS({ state: context.state, socket, })); } export function disconnect(context, id) { context.clients = context.clients.filter(client => client.getIn(['socket', 'id']) !== id); } export function listClients(context) { return context.clients; } export function createContext() { return { pollId: null, clients: new List([]), state: new Map({initial: true}), }; } async function poll(context) { try { const master = await getState('http://localhost:5050'); const slaves = await getSlaves(master.get('slaves')); const state = glueMasterAndSlaves(master, slaves); const clients = updateState(context, state); notifyListeners(clients); } catch (e) { logger.error('Error while fetching state', e); } } export function start(context) { context.pollId = setInterval(() => poll(context), 5000); } export function stop(context) { clearInterval(context.pollId); context.pollId = null; }
import React from 'react' import PropTypes from 'prop-types' import { Flex, Heading } from '@chakra-ui/react' function ForbiddenPage(props) { return ( <Flex flexDirection='column' alignItems='center' justifyContent='center' h='100vh' bg='gray.800' > <Heading as='h1' size='lg' color='gray.100' marginTop={-16}> You don't have access to this page </Heading> </Flex> ) } ForbiddenPage.propTypes = { } export default ForbiddenPage
 function buildDataTable() { var table= $("#grid-object").DataTable({ "searching": false, "processing": true, // for show progress bar "serverSide": true, // for process server side "filter": false, // this is for disable filter (search box) "orderMulti": false, // for disable multiple column at once "lengthChange": false, "ordering": false, "destroy": true, "pageLength": 5, "ajax": { "url": GridUrl, "type": "GET", "datatype": "json", data: function (d) { d.SearchLevel1 = $('#SearchLevel1').val(); d.SearchLevel2 = $('#SearchLevel2').val(); d.SearchLevel3 = $('#SearchLevel3').val(); d.SearchLevel4 = $('#SearchLevel4').val(); d.SearchUserCategory = $("#SearchUserCategory").val(); d.SearchName = $('#SearchName').val(); }, }, "columns": [ { className: 'details-control', orderable: false, data: null, defaultContent: '', width: "30px" }, { "data": "UserCategoryName", width: "350px" }, { "data": "JobName", width: "350px" }, { "data": "DisplayOrder", "autoWidth": true }, { data: "Active", render: function (data, type, row) { if (data) { return '<span class="glyphicon glyphicon-ok"></span>'; } else { return '<span class="glyphicon glyphicon-remove"></span>'; } } }, { data: null, width: "350px", sortable: false, render: function (data, type, row) { var html = '<a href="' + EditUrl + '/' + data.Id + '" class="btn default btn-xs blue-stripe"><i class="fa fa-edit"></i> تعديل</a>'; html += ' <a href="#" class="btn default btn-xs red-stripe" onClick="ConfirmDelete(' + data.Id + ')"><i class="fa fa-trash-o"></i> حذف</a>'; html += '<a href="' + EditPrivelages + '?Id=' + data.Id + '" class="btn default btn-xs purple-stripe"><i class="fa fa-lock"></i> تعديل الصلاحيات</a>'; return html; } }, ], "language": { "emptyTable": emptyTableLoc, "zeroRecords": zeroRecordsLoc, "loadingRecords": loadingRecordsLoc, "processing": loadingRecordsLoc, "infoEmpty": "", "info": "_TOTAL_ " + totalRecord, } }); $('#grid-object tbody').on('click', 'td.details-control', function () { var tr = $(this).closest('tr'); var row = table.row(tr); if (row.child.isShown()) { row.child.hide(); tr.removeClass('shown'); } else { row.child(format(row.data())).show(); buildPrivilegesTree(row.data()); tr.addClass('shown'); } }); } /*This function is override for each search filtering */ function SearchDataTable() { $('#grid-object').DataTable().ajax.reload(); } function format(rowData) { var div = $('<div id="privilegesTree_' + rowData.Id + '" class="tree-demo"><div/>') .addClass('loading') .text(loadingRecordsLoc + '...'); return div; } function buildPrivilegesTree(rowData) { var $treeview = $('#privilegesTree_' + rowData.Id).jstree({ 'plugins': ["wholerow", "checkbox", "types"], 'core': { expand_selected_onload: false, "themes": { "responsive": true, }, "check_callback": false, 'data': { 'url': menuPrivelageUrl + '?Id=' + rowData.Id, 'data': function (node) { return { 'id': node.id }; } } } }).on('refresh.jstree', function () { $treeview.jstree('close_all'); }).on('loaded.jstree', function () { $treeview.jstree('close_all'); }); }
import * as React from "react" import { Link } from "gatsby" import ArticleIcon from "./articleIcon" const PostTag = ({ postTagName }) => { return ( <Link className="taglink" to={`/tags/${postTagName}`}><ArticleIcon tags={postTagName}/> {postTagName}</Link> ) } export default PostTag
const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); var authenticate = require('../authenticate'); const Psys = require('../models/psy'); const psyRouter = express.Router(); psyRouter.use(bodyParser.json()); psyRouter.route('/') .get((req,res,next) => { Psys.find({}) .then((psys) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(psys); }, (err) => next(err)) .catch((err) => next(err)); }) .post(authenticate.verifyUser,(req, res, next) => { Psys.create(req.body) .then((psy) => { console.log('Psy Created ', psy); res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(psy); }, (err) => next(err)) .catch((err) => next(err)); }) .put(authenticate.verifyUser,(req, res, next) => { res.statusCode = 403; res.end('PUT operation not supported on /psys'); }) .delete(authenticate.verifyUser,(req, res, next) => { Psys.remove({}) .then((resp) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(resp); }, (err) => next(err)) .catch((err) => next(err)); }); psyRouter.route('/:psyId') .get((req,res,next) => { Psys.findById(req.params.psyId) .then((psy) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(psy); }, (err) => next(err)) .catch((err) => next(err)); }) .post(authenticate.verifyUser,(req, res, next) => { res.statusCode = 403; res.end('POST operation not supported on /dishes/'+ req.params.psyId); }) .put(authenticate.verifyUser, (req, res, next) => { Psys.findByIdAndUpdate(req.params.psyId, { $set: req.body }, { new: true }) .then((psy) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(psy); }, (err) => next(err)) .catch((err) => next(err)); }) .delete(authenticate.verifyUser, (req, res, next) => { Psys.findByIdAndRemove(req.params.psyId) .then((resp) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(resp); }, (err) => next(err)) .catch((err) => next(err)); }); module.exports = psyRouter;
import jwt from 'jsonwebtoken'; import * as Yup from 'yup'; import authConfig from '../../config/auth'; /** * Controls `Session`. */ class SessionController { /** * Create a new `Session`. * * @param {Object}} request * @param {Object}} response * * @returns {Object} { token: string } */ async store(request, response) { const schema = Yup.object().shape({ usuario: Yup.string().required(), senha: Yup.string().required(), }); try { await schema.validate(request.body); const { usuario, senha } = request.body; if (usuario !== 'admin' || senha !== 'admin') { return response.status(401).json({ error: 'User not found' }); } return response.status(201).json({ token: jwt.sign({ id: 'admin' }, authConfig.SECRET, { expiresIn: authConfig.EXPIRES_IN, }), }); } catch (error) { return response.status(400).json({ error: error.message }); } } } const sessionController = new SessionController(); export { sessionController };
#!/usr/bin/env node const fs = require('fs'); const DockerScaler = require('./src/docker-scaler'); if (!fs.existsSync('./config/config.json')) { throw new Error("config/config.json does not exist."); } const config = require(process.env.CONFIG || './config/config.json'); new DockerScaler(config).init();
import React, { useState } from "react"; import FilterByName from "./FilterByName/FilterByName"; import Footer from "./Footer/Footer"; import "../App.css"; import Raiting from "./Raiting/Raiting"; import { MovieData } from "./MovieData"; import MovieList from "./MovieList/MovieList"; import AddTrailer from "./AddTrailer/AddTrailer"; import { Switch, Route } from "react-router-dom"; const MovieApp = () => { const [movies, setMovies] = useState(MovieData); const [inputSearch, setInputSearch] = useState(""); const [value, setValue] = useState(1); const addMovie = (newMovie) => { setMovies([...movies, newMovie]); }; return ( <div className="App"> <Switch> <Route exact path="/"> <div className="movieApp"> <FilterByName setInputSearch={setInputSearch} /> <Raiting FilterRaiting={true} setValue={setValue} value={value} /> </div> <MovieList movies={movies} inputSearch={inputSearch} value={value} addMovie={addMovie} /> <Footer /> </Route> <Route path="/AddTrailer" component={AddTrailer} /> </Switch> </div> ); }; export default MovieApp;
const PROXY_CONFIG = [ { context: [ "/dept", "/limit", "/limitFile", "/limitMenu", "/limitOpt", "/limitPage", "/login", "/orgManager", "/organ", "/role", "/roleGroup", "/staff", "/role", "/sys", "/res" ], target: "http://192.168.10.178:8082", //拦截 context配置路径,经过此地址 secure: false }, { context: [ "/upload" ], target: "http://192.168.10.178:8092", //拦截 context配置路径,经过此地址 secure: false } ]; module.exports = PROXY_CONFIG;
const musicos = ['Seu Pereira', 'Charlie Brown Jr', 'Seu Jorge']; for (var musico of musicos) { console.log(musico) }
const subscribersRoutes = require("./subscribers"); const userRoutes = require("./user"); const authRoutes = require("./auth"); module.exports = { subscribersRoutes, authRoutes, userRoutes };
// sw.js - Service Worker // You will need 3 e listeners: // - One for installation // - One for activation ( check out MDN's clients.claim() for this step ) // - One for fetch requests const CACHE_NAME = 'allowedCache'; const urlsToCache = 'https://cse110lab6.herokuapp.com/entries'; self.addEventListener('install', function(e) { e.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Cache is opened'); return cache.add("https://cse110lab6.herokuapp.com/entries"); }) ); }); self.addEventListener('activate', function(e) { e.waitUntil(clients.claim()); const cacheAllowlist = ['allowedCache']; e.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (cacheAllowlist.indexOf(cacheName) === -1) return caches.delete(cacheName); }) ); }) ); }); self.addEventListener('fetch', function(e) { e.respondWith( caches.match(e.request) .then(function(response) { // Cache hit - return response if (response) return response; return fetch(e.request).then( function(response) { // Check for a valid response if(!response || response.status !== 200 || response.type !== 'basic') return response; var responseToCache = response.clone(); caches.open(CACHE_NAME) .then(function(cache) { cache.put(e.request, responseToCache); }); return response; } ); }) ); });
const multer = require('multer'); const { v4: uuidv4 } = require('uuid'); uuidv4(); const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './uploads/'); }, filename: function (req, file, cd) { cd(null, uuidv4()+file.originalname); }, }); exports.fileUpload = multer({ storage : storage });
'use strict'; var test = require('tape'); var bts2n = require('./').bts2n; var n2bts = require('./').n2bts; test('balanced ternary string to number', function(t) { t.equal(bts2n('i'), -1); t.equal(bts2n('0'), 0); t.equal(bts2n('1'), 1); t.equal(bts2n('1i'), 2); t.equal(bts2n('i1'), -2); t.equal(bts2n('i01'), -8); t.equal(bts2n('10i'), 8); t.equal(bts2n('11i'), 11); t.equal(bts2n('iiiii'), -121) t.equal(bts2n('11111'), 121) t.end(); }); test('number to balanced ternary string', function(t) { t.equal(n2bts(0), '0'); t.equal(n2bts(1), '1'); t.equal(n2bts(2), '1i'); t.equal(n2bts(-1), 'i'); t.equal(n2bts(-2), 'i1'); t.equal(n2bts(-3), 'i0'); t.equal(n2bts(8), '10i'); t.equal(n2bts(121), '11111'); t.equal(n2bts(-121), 'iiiii'); t.equal(n2bts(6), '1i0'); t.end(); }); test('round trip', function(t) { for (var i = -15; i <= 15; ++i) { t.equal(bts2n(n2bts(i)), i); } t.end(); });
window.onload = function() { // history-img 부분의 js let history_image1 = {his_img:"img/his_img_1.jpg"}; let history_image2 = {his_img:"img/his_img_2.jpg"}; let img_list = [history_image1,history_image2]; for (let i = 0; i < img_list.length; i++) { let his_img = document.createElement("div"); his_img.classList.add("img"); his_img.style = `background-image : url(${img_list[i].his_img});` let history_img = document.getElementsByClassName("history-img")[0]; history_img.appendChild(his_img); } // history-table 부분의 js let history_table1 = {listed_title: "2020.07 - 어쩌구", list_items:["어쩌구 저쩌구 어쩌구 저쩌구","어쩌구 저쩌구 어쩌구 저쩌구","어쩌구 저쩌구 어쩌구 저쩌구"]}; let history_table2 = {listed_title: "2020.10 - 어쩌구", list_items:["어쩌구 저쩌구 어쩌구 저쩌구","어쩌구 저쩌구 어쩌구 저쩌구","어쩌구 저쩌구 어쩌구 저쩌구","어쩌구 저쩌구 어쩌구 저쩌구","어쩌구 저쩌구 어쩌구 저쩌구"]}; let history_table3 = {listed_title: "2020.11 - 어쩌구", list_items:["어쩌구 저쩌구 어쩌구 저쩌구"]}; let history_table4 = {listed_title: "2020.12 - 어쩌구", list_items:["어쩌구 저쩌구 어쩌구 저쩌구"]}; let history_table5 = {listed_title: "2020.12 - 어쩌구", list_items:["어쩌구 저쩌구 어쩌구 저쩌구"]}; let history_table6 = {listed_title: "2020.12 - 어쩌구", list_items:["어쩌구 저쩌구 어쩌구 저쩌구"]}; let table_list = [history_table1,history_table2,history_table3,history_table4,history_table5,history_table6]; for (let i = 0; i < table_list.length; i++) { let listed_box = document.createElement("div"); listed_box.classList.add("listed-box"); let listed_bar = document.createElement("div"); listed_bar.classList.add("listed-bar"); let text_box = document.createElement("div"); text_box.classList.add("text-box"); let listed_title = document.createElement("div"); listed_title.classList.add("listed-title"); let listed_ul = document.createElement("ul"); listed_ul.classList.add("listed-ul"); listed_box.appendChild(listed_bar); listed_box.appendChild(text_box); text_box.appendChild(listed_title); text_box.appendChild(listed_ul); listed_title.textContent = table_list[i].listed_title; let list_items = table_list[i].list_items; for (let j = 0; j < list_items.length; j++) { let listed_li = document.createElement("li"); listed_li.classList.add("listed-li"); listed_ul.appendChild(listed_li); listed_li.textContent = table_list[i].list_items[j]; } for (let k = 0; k < list_items.length; k++) { listed_bar.style.height = `${90 + 17.5 * k}px`; } if (2 < table_list.length) { if (table_list.length % 2 == 0) { evenfunction(); } else { oddfunction(); } } if (i % 2 == 0) { let history_top = document.getElementsByClassName("history-top")[0]; history_top.appendChild(listed_box); } else { let history_bottom = document.getElementsByClassName("history-bottom")[0]; history_bottom.appendChild(listed_box); } // 함수 function evenfunction() { let middle_bar = document.getElementsByClassName("middle-bar")[0]; let history_top = document.getElementsByClassName("history-top")[0]; let history_bottom = document.getElementsByClassName("history-bottom")[0]; let history_table = document.getElementsByClassName("history-table")[0]; history_table.style.width = `${700 + 173 * (table_list.length - 3)}px`; middle_bar.style.width = `${700 + 173 * (table_list.length - 3)}px`; history_top.style.paddingRight = `${243}px`; history_bottom.style.paddingRight = `${70}px`; } function oddfunction() { let middle_bar = document.getElementsByClassName("middle-bar")[0]; let history_top = document.getElementsByClassName("history-top")[0]; let history_bottom = document.getElementsByClassName("history-bottom")[0]; let history_table = document.getElementsByClassName("history-table")[0]; history_table.style.width = `${700 + 173 * (table_list.length - 3)}px`; middle_bar.style.width = `${700 + 173 * (table_list.length - 3)}px`; history_top.style.paddingRight = `${70}px`; history_bottom.style.paddingRight = `${243}px`; } } // 스크롤 // let scroll = document.getElementsByClassName("scroll")[0]; }
const server = require('http').createServer() const io = require('socket.io')(server) io.on('connection', client => { console.log('connected') client.on('event', data => { console.log(data) }) client.on('message', data => { console.log('message:', data) }) client.on('disconnect', () => { /* … */ }) }) server.listen(3000) console.log('server.listen on port 3000')
var express = require('express'); var router = express.Router(); // home page function checkSession(req, res) { if (!req.session.Sign) { res.redirect('/'); return false; } else { res.locals.Account = req.session.Account; res.locals.Name = req.session.Name; res.locals.SuperUser = req.session.SuperUser; } return true; } router.get('/', function (req, res, next) { if (!checkSession(req, res)) { return; } var index = req.query.index ? req.query.index : 0; var mysqlQuery = req.mysqlQuery; var sql = 'SELECT * FROM mqtt_store '; if (req.session.SuperUser != 1) { sql += ("WHERE Account = '" + req.session.Account + "'"); } mysqlQuery(sql, function (err, rows) { if (err) { console.log(err); } var data = rows; mysqlQuery('SELECT Account, name FROM mqtt_user', function (err, rows) { if (err) { console.log(err); } var user = rows; for (var i = 0; i < data.length; i++) { for (var j = 0; j < user.length; j++) { if (data[i].Account == user[j].Account) { data[i].owner = user[j].name; break; } } } // use store.ejs res.render('store', { title: 'Store Information', data: data, user: user, index: index }); }); }); }); // add page router.get('/add', function (req, res, next) { if (!checkSession(req, res)) { return; } var mysqlQuery = req.mysqlQuery; mysqlQuery('SELECT id, name FROM mqtt_user', function (err, rows) { if (err) { console.log(err); } user = rows; // use storeAdd.ejs res.render('storeAdd', { title: 'Add Store', msg: '', user: user }); }); }); // add post router.post('/storeAdd', function (req, res, next) { if (!checkSession(req, res)) { return; } var mysqlQuery = req.mysqlQuery; var sql = { name: req.body.name, Account: req.body.Account, area: req.body.area, address: req.body.address, lat: req.body.lat, lng: req.body.lng, CreateDate: Date.now() }; //console.log(sql); var qur = mysqlQuery('INSERT INTO mqtt_store SET ?', sql, function (err, rows) { if (err) { console.log(err); } res.setHeader('Content-Type', 'application/json'); res.redirect('/store'); }); }); // edit page router.get('/storeEdit', function (req, res, next) { if (!checkSession(req, res)) { return; } var id = req.query.id; var mysqlQuery = req.mysqlQuery; mysqlQuery('SELECT * FROM mqtt_store WHERE id = ?', id, function (err, rows) { if (err) { console.log(err); } var data = rows; mysqlQuery('SELECT Account, name FROM mqtt_user', function (err, rows) { if (err) { console.log(err); } user = rows; res.render('storeEdit', { title: 'Edit store', data: data, user: user }); }); }); }); router.post('/storeEdit', function (req, res, next) { if (!checkSession(req, res)) { return; } var mysqlQuery = req.mysqlQuery; var id = req.body.id; var sql = { Account: req.body.Account, area: req.body.area, address: req.body.address, lat: req.body.lat, lng: req.body.lng, status: req.body.status }; mysqlQuery('UPDATE mqtt_store SET ? WHERE id = ?', [sql, id], function (err, rows) { if (err) { console.log(err); } res.setHeader('Content-Type', 'application/json'); res.redirect('/store'); }); }); router.get('/storeDelete', function (req, res, next) { if (!checkSession(req, res)) { return; } var id = req.query.id; var mysqlQuery = req.mysqlQuery; mysqlQuery('DELETE FROM mqtt_store WHERE id = ?', id, function (err, rows) { if (err) { console.log(err); } res.redirect('/store'); }); }); module.exports = router;
// Export a simple name/value pairs define({ value: 12 });
var tokki = angular.module("directives").directive("referencias", ["confirm", function(confirm){ return { restrict: "A", scope: { referencias: "=", refready: "=" }, templateUrl: "pages/ventas/referencias/referencias.html", controller: ["$scope", "$rootScope", function($scope, $rootScope) { $scope.$watch('referenciasForm.$valid', function(newVal) { $scope.refready = newVal; }); $scope.addref = function(){ console.log($scope.referencias); $scope.referencias.unshift({ dte: "SET", id: null, fecha: null, razonref: "CASO ", codref: null, }) } }] } } ])
import Project from './Project' const projectsData = [ { timeframe: '2018-2020', title: 'Led design at DreamSpring ', description: 'DreamSpring is a 26 year old nonprofit, community lender that propels the dreams of underserved and under-represented entrepreneurs by providing them with capital to start or grow their businesses.', thumbnail: '', projects: [ { id: 4, title: "Customer self service portal", description: 'Designing a customer facing web app which helps them to track their repayment of loans, apply for new loans and refinance existing loan.', url: '/dreamspring/dock' }, { id: 1, title: "The loan origination app", description: 'Designing and iterating on a system that helps clients to apply for business loan and loan officers to process it.', url: '/dreamspring/flare', }, { id: 2, title: "The loan closing app", description: 'Desiging a system for fraud detection, loan application analysis and close eligible loan applications.', url: '/dreamspring/peak', }, { id: 3, title: "The loan servicing app", description: 'Designing a system that will help in the everyday functioning of a lending organisation. The system will keep track of the portfolio quality.', url: '/dreamspring/wave', }, { id: 5, title: "Design system", description: `Building DreamSpring's style guide and defining a shared product design vision`, url: '/dreamspring/coin', }, ], background: '#FAD2D9', id:1 }, { timeframe: '2017-2018', title: 'Designed a Q&A website for programmers', description: 'Hashnode is a friendly and inclusive community for software developers. It was started back in 2014. It let users to ask, answer, write story, share and discover links. Anyone can share articles, questions, discussions, etc. as long as they have the rights to the words they are sharing. ', thumbnail: '', projects: [ { id: 1, title: "Designing for engagement", description: 'blah blah', url: '/hashnode/engagement', }, { id: 2, title: "Designing the feed", description: 'blah blah', url:'/hashnode/feed', }, { id: 3, title: "UI Library", description: 'blah blah', url:'/hashnode/uilibrary', }, ], background: '#FECF7E', id: 2 }, { timeframe: '2015-2017', title: 'Designed an English learning app which had over a million downloads', description: 'Englishdost is an ed-tech startup aimed helping people from smaller towns and cities to learn to speak English fluently. I was part of the product team and was responsible for implementing a interactive and fun filled experience for the users.', thumbnail: '', background: '#E6DBF0', projects: [ { id: 1, title: "Design guidelines", description: `Building EnglishDost's general style guide, illustration style and motion design patterns.`, url: 'ed/uilibrary' }, { id: 2, title: "Payments and subscription ", description: 'Designing the userflows and visual designs for the purchase of subscription plans', url: '/ed/payments', }, { id: 3, title: "The trainer app", description: 'Designing an Android app for English tutors to engage with their students.', url:'/ed/trainer', }, ], id: 3 } ] function AllWork() { return ( <div className="row"> {projectsData.map((item) => ( <div className="col-md-10 offset-md-1" key={item.id} > <Project data={item} /> </div> ))} </div> ) } export default AllWork
/* * @lc app=leetcode.cn id=152 lang=javascript * * [152] 乘积最大子数组 */ // @lc code=start /** * @param {number[]} nums * @return {number} */ var maxProduct = function(nums) { let max = -Infinity, iMax = 1, iMin = 1; for (let i = 0; i < nums.length; i++) { if (nums[i] < 0) { let temp = iMax; iMax = iMin; iMin = temp; } iMax = Math.max(iMax * nums[i], nums[i]); iMin = Math.min(iMin * nums[i], nums[i]); max = Math.max(iMax, max) } return max; }; // @lc code=end
// Condicionais // var timeFilho = 'flamengo' // if (timeFilho == 'palmeiras') { //SE // console.log('ta tranquilo') //BLOCO // console.log('ta favoravel') //BLOCO // } else if (timeFilho == 'corinthians') { // SE NAO SE // console.log('nao é meu filho') // } else if (timeFilho == 'flamengo') { // SE NAO SE // console.log('nao vou tirar da cadeia, nao eh meu filho') // } else { // SE NAO // console.log('paciencia, fazer o que') // console.log('dos males o menor') // } // var saldoConta = 30 // var valorDaPizza = 50 // if (valorDaPizza <= saldoConta) { // saldoConta >= valorDaPizza // console.log('Posso comprar a pizza') // } else { // console.log('Nao pode comprar a pizza, vai aprender a programar para comprar') // console.log('Transacao negada') // } var numeroQualquer = 0.000000000000000000001 if (numeroQualquer > 0) { console.log('numero positivo') } else if (numeroQualquer == 0) { console.log('neutro') } else { console.log('numero negativo') } // SE timeFilho == 'palmeiras' escreve ta tranquilo // SE NAO escreve nao pode // SE (if) e SE NAO (else)
var fs = require('fs'); var path = require('path'); var root = '/Users/zhulei/Documents/demo/'; var info = []; function readJson(dir) { fs.readdir(dir, function (err, files) { if (err) { throw err; } else { files.forEach(function (file) { var filePath = path.join(dir, file); if (/node_module/.test(filePath)) { return; } var stats = fs.statSync(filePath); console.log(1); if (stats.isDirectory()) { readJson(filePath); } else { if (path.extname(filePath) == '.json') { info.push({ name: file, path: filePath }); } } }); var str = ''; info.forEach(function (p) { str += p.name + '\n' + p.path + '\n\n'; }); fs.writeFile('info.txt', str); } }); } readJson(root);
var url = require('url'); var util = require('util'); var database = require('../core/db'); var httpMsg = require('../core/httpMsg'); class Auth { login(request, response, requestBody) { try { if (!requestBody) throw new Error('Input not valid'); var data = JSON.parse(requestBody); if (data) { var sql = util.format("SELECT `id`, `username` FROM `users` WHERE username = '%s' AND password = md5('%s')", data.username, data.password); database.query(sql, (error, results) => { var rsObj = results[0]; if (error) httpMsg.status422(request, response, error); else { if (results.length) { var sql = util.format("UPDATE `users` SET `api_token` = md5('%s') WHERE `id` = %d", rsObj.username + new Date().getTime(), rsObj.id); database.query(sql, (error, results) => { if (error) httpMsg.status422(request, response, error); else { sql = util.format("SELECT `api_token`, `role` FROM `users` WHERE id = %d", rsObj.id); database.query(sql, (error, results) => { if (error) httpMsg.status422(request, response, error); else { var data = { token: results[0].api_token, role: results[0].role } httpMsg.status200(request, response, data); } }) } }) } } }); } else throw new Error('Input not valid'); } catch (error) { httpMsg.status422(request, response, error); } } logout(request, response) { // Get query params on url var urlObj = url.parse(request.url, true); var queryUrl = urlObj.query; try { if (!queryUrl) throw new Error('Input not valid'); var sql = util.format("UPDATE `users` SET `api_token` = %s WHERE `api_token` = '%s'", 'null', queryUrl.token); database.query(sql, (error, results) => { if (error) httpMsg.status401(request, response, error); else { if (results.affectedRows) { var data = { message: 'logout success' }; httpMsg.status200(request, response, data); } else httpMsg.status401(request, response, error); } }); } catch (error) { httpMsg.status401(request, response, error); } } } module.exports.Auth = Auth; module.exports.guard = (request, role, callback) => { // Get query params on url var urlObj = url.parse(request.url, true); var queryUrl = urlObj.query; var sql = util.format("SELECT `role` FROM `users` WHERE `api_token` = '%s'", queryUrl.token); if(role === 'ADMIN') sql += util.format(" AND `role` = '%s'", role); database.query(sql, callback); }
// ---------------------------------------------------------------------------- // PixInsight JavaScript Runtime API - PJSR Version 1.0 // ---------------------------------------------------------------------------- // MixImages Version 0.1.5 - Released 02.07.21 // ---------------------------------------------------------------------------- // // // **************************************************************************** // PixInsight JavaScript Runtime API - PJSR Version 1.0 // **************************************************************************** // MixImages.js - Released 2021 // **************************************************************************** // // This file is part of LinearStarRemoval Script Version 0.1.0 // // Copyright (C) 2021 Alex Woronow. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (http://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // **************************************************************************** /* * BUG REPORTING * Please send information on bugs to Alex@FaintLightPhotography.com. Include * the version number of the script you are reporting as well as relevant * parts of the Process Console output and other outputs/messages. */ #feature-id Utilities > Mix/Restar #feature-info Mix two image in a proprotion that varies by relative image intensities. #include <pjsr/ColorSpace.jsh> #include <pjsr/UndoFlag.jsh> #include <pjsr/StdCursor.jsh> #include <pjsr/Sizer.jsh> #include <pjsr/FrameStyle.jsh> #include <pjsr/TextAlign.jsh> #include <pjsr/NumericControl.jsh> #include <pjsr/FontFamily.jsh> #include <pjsr/SampleType.jsh> #include <pjsr/Color.jsh> #define VERSION "0.1.5" // define a global variable containing script's parameters var MixImages = { KTarget: 1.0, KSource: 1.0, TargetImage: undefined, SourceImage: undefined, Mask: undefined, EquationNo: 0, MixImage: "", Iterate: true, InvertMask: false, RescaleResult: true, save: function () { Parameters.set( "KTarget", MixImages.KTarget ); Parameters.set( "KSource", MixImages.KSource ); Parameters.set( "TargetImage", MixImages.TargetImage.id ); Parameters.set( "SourceImage", MixImages.SourceImage.id ); Parameters.set( "Mask", MixImages.Mask.id ); Parameters.set( "EquationNo", MixImages.EquationNo ); Parameters.set( "InvertMask", MixImages.InvertMask ); Parameters.set( "RescaleResult", MixImages.RescaleResult ); }, // load the script instance parameters load: function() { if (Parameters.has("KTarget")) { MixImages.KTarget = Parameters.getReal("KTarget") } if (Parameters.has("KSource")) { MixImages.KSource = Parameters.getReal("KSource") } if (Parameters.has("TargetImage")) { MixImages.TargetImage = View.viewById(Parameters.getString("TargetImage")) } if (Parameters.has("SourceImage")) { MixImages.SourceImage = View.viewById(Parameters.getString("SourceImage")) } if (Parameters.has("Mask")) { MixImages.Mask = View.viewById(Parameters.getString("Mask")) } if (Parameters.has("EquationNo")) { MixImages.EquationNo = Parameters.getInteger("EquationNo") } if (Parameters.has("InvertMask")) { MixImages.InvertMask = Parameters.getBoolean("InvertMask") } if (Parameters.has("RescaleResult")) { MixImages.RescaleResult = Parameters.getBoolean("RescaleResult") } } }; //------------------------------------------------------------------------------ // Construct the script dialog interface //------------------------------------------------------------------------------ function parametersDialogPrototype() { this.__base__ = Dialog; this.__base__(); this.windowTitle = "ImageMix (v"+VERSION+")"; Console.show(); // create a title area this.title = new TextBox(this); this.title.text = "<b>ImageMix</b><br><br>This script mixes two images" + " according to a user-selected equation." + " Five equations are available. In three of them," + " the mixing is through a mask. The meaning of the" + " weights varies by equation." + " It mixes mask-conceled and Mask-revealed image components." + " with independent mixing coeficients." + " A principal use of this script is to transfer stars" + " into a starless image (or replace the stars in an image." + " <p> --Alex Woronow (v"+VERSION+") -- 3/2021--"; this.title.readOnly = true; this.title.backroundColor = 0x333333ff; this.title.minHeight = 130; this.title.maxHeight = 130; // EquationNo pickers radiobuttons. // this.Eq0rb = new RadioButton(this); this.Eq0rb.text = "#0: Use Simple Equation: ( K*Image_1 + ~K*Image_2 )"; this.Eq0rb.checked = MixImages.EquationNo === 0; this.Eq0rb.enabled = true; this.Eq0rb.onClick = function (checked) { if( this.dialog.Eq0rb.checked ) { MixImages.EquationNo = "0"; Console.writeln (" Selected Equation #",MixImages.EquationNo); this.dialog.update(); } } this.Eq1rb = new RadioButton(this); this.Eq1rb.text = "#1: Use Equation: max( KTarget*Target, Mask*KSource*Source )"; this.Eq1rb.checked = MixImages.EquationNo === 1; this.Eq1rb.enabled = true; this.Eq1rb.onClick = function (checked) { if( this.dialog.Eq1rb.checked ) { MixImages.EquationNo = "1"; Console.writeln (" Selected Equation #",MixImages.EquationNo); this.dialog.update(); } } this.Eq2rb = new RadioButton(this); this.Eq2rb.text = "#2: Use EquationNo: ( ~Mask*KTarget*Target + Mask*KSource*Source )"; this.Eq2rb.checked = MixImages.EquationNo === 2; this.Eq2rb.enabled = true; this.Eq2rb.onClick = function (checked) { if( this.dialog.Eq2rb.checked ) { MixImages.EquationNo = 2; Console.writeln (" Selected Equation #",MixImages.EquationNo); this.dialog.update(); } } this.Eq3rb = new RadioButton(this); this.Eq3rb.text = "#3: Use Equation: max( KTarget*Target, KSource*Source )"; this.Eq3rb.checked = MixImages.EquationNo === 3; this.Eq3rb.enabled = true; this.Eq3rb.onClick = function (checked) { if( this.dialog.Eq3rb.checked ) { MixImages.EquationNo = "3"; Console.writeln (" Selected Equation #",MixImages.EquationNo); this.dialog.update(); } } this.Eq4rb = new RadioButton(this); this.Eq4rb.text = "#4: Use Equation: Mask*(K1*Revealed_Im +~K1*Concealed_Im) + ~Mask*(~K2+*Revealed_Im+K2*Concealed_Im)"; this.Eq4rb.checked = MixImages.EquationNo === 4; this.Eq4rb.enabled = true; this.Eq4rb.onClick = function (checked) { if( this.dialog.Eq4rb.checked ) { MixImages.EquationNo = "4"; Console.writeln (" Selected Equation #",MixImages.EquationNo); this.dialog.update(); } } this.RBSizer = new VerticalSizer; this.RBSizer.scaledMargin = 20; this.RBSizer.spacing = 8; this.RBSizer.add(this.Eq0rb) this.RBSizer.add(this.Eq1rb) this.RBSizer.add(this.Eq2rb) this.RBSizer.add(this.Eq3rb) this.RBSizer.add(this.Eq4rb) // Image Pickers // // add Target View picker this.TIViewList = new ViewList(this); this.TIViewList.scaledMaxWidth = 200; this.TIViewList.getMainViews(); if (MixImages.TargetImage) { this.TIViewList.currentView = MixImages.TargetImage; } MixImages.TargetImage = this.TIViewList.currentView; this.TIViewList.toolTip = "<p>Select the Target image.</p>"; this.TIViewList.onViewSelected = function (View) { MixImages.TargetImage = View; } // add Source picker this.SIViewList = new ViewList(this); this.SIViewList.scaledMaxWidth = 200; this.SIViewList.getMainViews(); if (MixImages.SourceImage) { this.SIViewList.currentView = MixImages.SourceImage; }; MixImages.SourceImage = this.SIViewList.currentView; this.SIViewList.toolTip = "<p>Select a Source image to mix with the target image.</p>"; this.SIViewList.onViewSelected = function (View) { MixImages.SourceImage = View; } // add Mask picker this.MIViewList = new ViewList(this); this.MIViewList.scaledMaxWidth = 200; this.MIViewList.getMainViews(); if (MixImages.Mask) { this.MIViewList.currentView = MixImages.Mask; }; MixImages.Mask = this.MIViewList.currentView; this.MIViewList.toolTip = "<p>Select a Masking Image (Optinal).</p>"; this.MIViewList.onViewSelected = function (View) { MixImages.Mask = View; } // Label for Target picker this.TILabel = new Label(this); this.TILabel.margin = 0; this.TILabel.text = "Target Image:"; this.TILabel.textAlignment = TextAlign_Left|TextAlign_Bottom; // Label for Source picker this.SILabel = new Label(this); this.SILabel.lmargin = 0; this.SILabel.text = "Source Image:"; this.SILabel.textAlignment = TextAlign_Left|TextAlign_Bottom; // Label for Mask picker this.MLabel = new Label(this); this.MLabel.margin = 0; this.MLabel.text = "Mask:"; this.MLabel.textAlignment = TextAlign_Left|TextAlign_Bottom; // blank string this.blank = new Label(this); this.blank.margin = 2; this.blank.text = " "; this.blank.textAlignment = TextAlign_Left|TextAlign_Bottom; // invert the mask? this.InvertMaskcb = new CheckBox(this); this.InvertMaskcb.text = "Invert Mask"; this.InvertMaskcb.checked = MixImages.InvertMask; this.InvertMaskcb.toolTip = "Use the inverted mask." this.InvertMaskcb.enabled = true; this.InvertMaskcb.onClick = function() { MixImages.InvertMask = !MixImages.InvertMask; } this.V1Sizer = new VerticalSizer; this.V1Sizer.spacing = 2; this.V1Sizer.add(this.TILabel); this.V1Sizer.add(this.TIViewList); this.V1Sizer.spacing = 2; this.V1Sizer.add(this.blank); this.V2Sizer = new VerticalSizer; this.V2Sizer.spacing = 2; this.V2Sizer.add(this.SILabel); this.V2Sizer.add(this.SIViewList); this.V2Sizer.spacing = 8; this.V2Sizer.add(this.blank); this.V3Sizer = new VerticalSizer; this.V2Sizer.spacing = 2; this.V3Sizer.add(this.MLabel); this.V3Sizer.add(this.MIViewList); this.V3Sizer.spacing = 2; this.V3Sizer.add(this.InvertMaskcb); // arrange image selectors horizontally this.SelectViewsSizer = new HorizontalSizer; this.SelectViewsSizer.addStretch(); this.SelectViewsSizer.add(this.V1Sizer) this.SelectViewsSizer.addStretch(); this.SelectViewsSizer.add(this.V2Sizer) this.SelectViewsSizer.addStretch(); this.SelectViewsSizer.add(this.V3Sizer) this.SelectViewsSizer.addStretch(); // SourceImage weigth (or star weight) this.SAmountControl = new NumericControl(this); this.SAmountControl.slider.scaledMinWidth = 500; this.SAmountControl.label.text = " Source-Image Weight:"; this.SAmountControl.setRange( 0, 10 ); this.SAmountControl.slider.setRange( 0, 1000 ); this.SAmountControl.setPrecision( 2 ); this.SAmountControl.setValue( MixImages.KSource ); this.SAmountControl.enabled = true; this.SAmountControl.toolTip = "<p>Set the weight for the image mixed with " + "the target image. (E.g., this could be the image with the stars.</p>"; this.SAmountControl.onValueUpdated = function( value ) { MixImages.KSource = value; } // TargetImage weight (or starless weight) this.TAmountControl = new NumericControl(this); this.TAmountControl.slider.scaledMinWidth = 500; this.TAmountControl.label.text = " Target-Image Weight:"; this.TAmountControl.setRange( 0, 10 ); this.TAmountControl.slider.setRange( 0, 1000 ); this.TAmountControl.setPrecision( 2 ); this.TAmountControl.setValue( MixImages.KTarget ); this.TAmountControl.enabled = true; this.TAmountControl.toolTip = "<p>Set weight for the Target image. (E.g., "+ "this image could be a starless image.)</p>"; this.TAmountControl.onValueUpdated = function( value ) { MixImages.KTarget = value; } // Iterate(?) dialog Checkbox this.IterateDialog = new CheckBox(this); this.IterateDialog.scaledMargin = 20; this.IterateDialog.text = " Iterate Dialog "; this.IterateDialog.toolTip = "Check to compute the result then reopen the dialog " + "with the last-used values presented." this.IterateDialog.checked = MixImages.Iterate; this.IterateDialog.enabled = true; this.IterateDialog.onClick = function() { MixImages.Iterate = !MixImages.Iterate; } // rescale results [0,1]? this.RescaleResultcb = new CheckBox(this); this.RescaleResultcb.scaledMargin = 20; this.RescaleResultcb.text = "Resdcale Result"; this.RescaleResultcb.checked = MixImages.RescaleResult; this.RescaleResultcb.toolTip = "Check to cause final image to be rescalled [0,1] " + "with the last-used values presented." this.RescaleResultcb.enabled = true; this.RescaleResultcb.onClick = function() { MixImages.RescaleResult = !MixImages.RescaleResult; } this.CbSizer = new HorizontalSizer; this.CbSizer.spacing =20; this.CbSizer.scaledMargin = 10; this.CbSizer.add(this.RescaleResultcb); this.CbSizer.add(this.IterateDialog); this.CbSizer.addStretch(); // Buttons // // instance button this.newInstanceButton = new ToolButton( this ); this.newInstanceButton.icon = this.scaledResource( ":/process-interface/new-instance.png" ); this.newInstanceButton.setScaledFixedSize( 24, 24 ); this.newInstanceButton.toolTip = "New Instance"; this.newInstanceButton.onMousePress = () => { MixImages.save(); this.newInstance(); }; // doc button this.documentationButton = new ToolButton(this); this.documentationButton.icon = this.scaledResource( ":/process-interface/browse-documentation.png" ); this.documentationButton.toolTip = "<p>See the folder containing this script " + "for the documentation </p>"; // cancel button this.cancelButton = new PushButton(this); this.cancelButton.text = "Exit"; this.cancelButton.backgroundColor = 0x22ff0000; this.cancelButton.textColor = 0xfffffff0; this.cancelButton.onClick = function() { this.dialog.cancel(); }; this.cancelButton.defaultButton = true; this.cancelButton.hasFocus = true; // execution button this.execButton = new PushButton(this); this.execButton.text = "RUN"; this.execButton.toolTip = "Invoke Script on active image."; this.execButton.backgroundColor = 0x2200ff00; this.execButton.width = 40; this.execButton.enabled = true; this.execButton.onClick = () => { this.ok(); }; // create a horizontal sizer to layout the execution-row buttons this.execButtonSizer = new HorizontalSizer; //this.execButtonSizer.scaledMargin = 20; this.execButtonSizer.spacing = 12; this.execButtonSizer.add(this.newInstanceButton); this.execButtonSizer.add(this.documentationButton); this.execButtonSizer.addStretch(); this.execButtonSizer.add(this.cancelButton); this.execButtonSizer.add(this.execButton) // final arrangement of controls this.sizer = new VerticalSizer; this.sizer.scaledMargin = 20; this.sizer.scaledSpacing = 6; this.sizer.add(this.title); this.sizer.addStretch(); this.sizer.add(this.RBSizer); this.sizer.addStretch(); this.sizer.add(this.SelectViewsSizer); this.sizer.add(this.CbSizer) this.sizer.addStretch(); this.sizer.addScaledSpacing(10); this.sizer.add(this.TAmountControl); this.sizer.add(this.SAmountControl); this.sizer.add(this.execButtonSizer); this.adjustToContents(); this.dialog.update(); //------------------------------------------------------------------------------ //------------- Change dialog depending of equation selection ------------------ //------------------------------------------------------------------------------ this.update = function() { this.dialog.Eq0rb.checked = MixImages.EquationNo == 0; this.dialog.Eq1rb.checked = MixImages.EquationNo == 1; this.dialog.Eq2rb.checked = MixImages.EquationNo == 2; this.dialog.Eq3rb.checked = MixImages.EquationNo == 3; this.dialog.Eq4rb.checked = MixImages.EquationNo == 4; this.dialog.MIViewList.enabled = !this.dialog.Eq3rb.checked && !this.dialog.Eq0rb.checked; this.dialog.InvertMaskcb.enabled = !this.dialog.Eq0rb.checked && !this.dialog.Eq3rb.checked; this.dialog.SAmountControl.enabled = !this.dialog.Eq0rb.checked; if( this.dialog.Eq4rb.checked || this.dialog.Eq0rb.checked ) { // either selected this.dialog.TAmountControl.setRange( 0.00, 1.00 ); if( MixImages.KTarget >= 1 ) this.dialog.TAmountControl.setValue( MixImages.KTarget ); if ( this.dialog.Eq0rb.checked ) { //MixImages.KTarget = 0.5; this.dialog.TAmountControl.setValue( MixImages.KTarget ); this.dialog.TIViewList.toolTip = "<p>Select the image that receives the weight below" ; this.dialog.TILabel.text = "Image_1:"; this.dialog.SIViewList.toolTip = "<p>Select the image that receieves the ~weigth" ; this.dialog.SILabel.text = "Image_2:"; this.dialog.TAmountControl.label.text = " Mixing Coefficient:"; this.dialog.TAmountControl.toolTip = "<p>Set weight for the first-specified image.</p>"; } else if( this.dialog.Eq4rb.checked ) { this.dialog.TAmountControl.setRange( 0.00, 1.00 ); this.dialog.SAmountControl.setValue( MixImages.KTarget ); this.dialog.TIViewList.toolTip = "<p>Select the image that dominantly contributes" + " the mask-revealed component to the final image.</p>"; this.dialog.TILabel.text = "Mask-Revealed Image:"; this.dialog.SAmountControl.setRange( 0.00, 1.00 ); this.dialog.SAmountControl.setValue( MixImages.KSource ); this.dialog.SIViewList.toolTip = "<p>Select the image that dominantly contributes" + " the masked-concealed component to the final image.</p>"; this.dialog.SILabel.text = "Mask-Concealed Image:"; this.dialog.TAmountControl.label.text = " K1 Mxing Coef.:"; this.dialog.TAmountControl.toolTip = "<p>Set the weight blending the mask-revealed areas " + "of the Target Image."; this.dialog.SAmountControl.label.text = " K2 Mixing Coef.:"; this.dialog.SAmountControl.toolTip = "<p>Set the mixing coefficient for mask-Concealed areas" ; } } else { // selected 1,2, or 3 this.dialog.TIViewList.toolTip = "<p>Select the TARGET image.</p>"; this.dialog.TILabel.text = "Target Image:"; this.dialog.SIViewList.toolTip = "<p>Select a Source image to mix with the target image.</p>"; this.dialog.SILabel.text = "Source Image:"; this.dialog.TAmountControl.setRange( 0.00, 10.00 ); this.dialog.TAmountControl.setValue( MixImages.KTarget ); this.dialog.TAmountControl.label.text = " Target-Image Weight:"; this.dialog.TAmountControl.toolTip = "<p>Set weight for the Target image. (E.g., "+ "this image could be a starless image.)</p>"; this.dialog.SAmountControl.setRange( 0.00, 10.00 ); this.dialog.SAmountControl.setValue( MixImages.KSource ); this.dialog.SAmountControl.label.text = " Source-Image Weight:"; this.dialog.SAmountControl.toolTip = "<p>Set the mixing coefficient for the mask-concealed areas" ; } }; }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------- Pixel Math that does the Mixing -------------------------------- //------------------------------------------------------------------------------ function Mix (outName) { let TargetImage = MixImages.TargetImage.id; let SourceImage = MixImages.SourceImage.id; let Mask; if( MixImages.Mask.id == "" ) { Mask = 0.50; } else { Mask = MixImages.InvertMaskcb ? "(~"+MixImages.Mask.id+")" : MixImages.Mask.id; } let KT = MixImages.KTarget; let KS = MixImages.KSource; let Eqn = MixImages.EquationNo; let EQ; if( Eqn === 0 ) { EQ = KT+"*"+TargetImage+"+~"+KT+"*"+SourceImage ; } else if( Eqn === 1 ) { EQ = "max("+KT+"*"+TargetImage+","+KS+"*"+Mask+"*"+SourceImage+")" ; } else if( Eqn === 2 ) { EQ = "~"+Mask+"*"+KT+"*"+TargetImage+"+"+Mask+"*"+KS+"*"+SourceImage; } else if( Eqn === 3 ) { EQ = "max("+KS+"*"+SourceImage+","+KT+"*"+TargetImage+")" ; } else { //use Eqn 4 EQ = Mask+"*("+KT+"*"+TargetImage+"+~"+KT+"*"+SourceImage+")+"+ "~"+Mask+"*(~"+KS+"*"+TargetImage+"+"+KS+"*"+SourceImage+");" ; } var P = new PixelMath; P.expression = ""; P.expression = EQ; P.symbols = "TargetImage, SourceImage, Mask, KTarget, w, weight, EQn"; P.expression1 = ""; P.expression2 = ""; P.useSingleExpression = true; P.generateOutput = true; P.singleThreaded = false; P.optimization = true; P.use64BitWorkingImage = true; P.rescale = MixImages.RescaleResult;; P.rescaleLower = 0; P.rescaleUpper = 1; P.truncate = true; P.truncateLower = 0; P.truncateUpper = .94; P.createNewImage = true; P.showNewImage = true; P.newImageId = outName; P.newImageWidth = 0; P.newImageHeight = 0; P.newImageAlpha = false; P.newImageColorSpace = PixelMath.prototype.RGB; //P.newImageColorSpace = PixelMath.prototype.SameAsTarget; P.newImageSampleFormat = PixelMath.prototype.SameAsTarget; P.executeOn(MixImages.TargetImage); // dummy var view = View.viewById(outName); return view; }; //------------------------------------------------------------------------------ //------------- Report input images and settings ------------------------------- //------------------------------------------------------------------------------ function Show_N_Tell () { Console.writeln("\n Target Image: ", MixImages.TargetImage.id); Console.writeln(" Source Image: ", MixImages.SourceImage.id); if( MixImages.EquationNo !== "3" ) { Console.writeln(" Mask: ", MixImages.Mask.id); } Console.writeln(" Target Weighting Coef: ", MixImages.KTarget); Console.writeln(" Source Weighting Coef: ", MixImages.KSource); Console.writeln(" Using Equation: #", MixImages.EquationNo); Console.writeln(" Rescale Results: ", MixImages.RescaleResult); Console.writeln("\n"); return CheckInputs(); }; //------------------------------------------------------------------------------ //------------------- Check for necessary inputs ------------------------------- //------------------------------------------------------------------------------ function CheckInputs() { let HaveT = MixImages.TargetImage.id != ""; let HaveS = MixImages.SourceImage.id != ""; if( MixImages.EquationNo === 3 ) return (HaveT && HaveS); if( MixImages.EquationNo === 0 ) return (HaveT); return ( HaveT && HaveS ); }; //------------------------------------------------------------------------------ parametersDialogPrototype.prototype = new Dialog; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ function main() { Console.abortEnabled = true; Console.hide(); if (Parameters.isGlobalTarget) { MixImages.load(); } if (Parameters.isViewTarget) { MixImages.load(); if( this.Show_N_Tell() ) { MixImages.save(); this.Mix("MixedImage"); } else { Console.criticalln( " Missing image specification "); return; } if( this.Iterate ) main(); // reopen with filled-in dialog return; } // execute via user interface let parametersDialog = new parametersDialogPrototype(); Console.writeln("sending in ", MixImages.EquationNo); parametersDialog.update(MixImages.EquationNo); if( parametersDialog.execute() == 0 ) return; // normal execution via a dialog if( this.Show_N_Tell() ) { MixImages.save(); this.MixedImage = this.Mix("MixedImage"); } else { Console.criticalln( " Missing image specification "); Console.show(); return; } Console.hide(); if( MixImages.Iterate ) { main(); // reopen with filled-in dialog } else { Console.writeln ("DONE"); } } // end 'main' main();
function QuickUnion(N) { this.id = [N]; this.sz = [N]; for (i=0; i<N; i++){ this.id[i] = i; this.sz[i] = i; } } QuickUnion.prototype.root = function(p) { while(this.id[p] != p) p = this.id[p]; return p; }; QuickUnion.prototype.connected = function(id1, id2) { return this.root(id1) == this.root(id2); }; QuickUnion.prototype.union = function(p, q) { var i = this.root(p); var j = this.root(q); if (this.sz[i] < this.sz[j]) { this.id[i] = j; this.sz[j] += this.sz[i]; } else { this.id[j] = i; this.sz[i] += this.sz[j]; } };
"use strict"; import { GetTestClockfaceNumber, IsCorrectAnswerClockface, } from "../../js/test.js"; import { Clockface } from "../../js/Clockface.js"; window.TestConfig = { keyboard: ["rotation", "enter"], testSrcWidth: 11, IsCorrectAnswer: IsCorrectAnswerClockface, GetTest: function () { const test = GetTestClockfaceNumber(); return ( "[ '" + Math.trunc(test / 12) + "час" + (test % 12) * 5 + "мин'" + ", new Clockface({ clocks: 0, minutes: 0 }).elemClockface ]" ); }, GetLogRecordHTML: function (elemTestSrc) { const elemReturn = document.createElement("div"); elemReturn.innerHTML = elemTestSrc.innerText; elemReturn.appendChild(eval(elemTestSrc.getAttribute("src"))[1]); return elemReturn.innerHTML; }, };
import {Button, Modal, ModalBody, ModalFooter, ModalHeader} from "reactstrap"; import {connect} from "react-redux"; import React from "react"; import {cardAllChangeTrashFlag} from "../../redux/actions/card"; function DeleteAllCardsPopUp (props) { return ( <Modal isOpen={props.modal.isOpen} toggle={props.toggle}> <ModalHeader toggle={props.toggle}>Delete all cards</ModalHeader> <ModalBody>Are you sure you want to delete <b>all the cards</b>? Please, confirm your decision.</ModalBody> <ModalFooter> <Button color="danger" onClick={() => {props.cardAllChangeTrashFlag(props.cards, true); props.toggle()}}>Delete</Button> <Button color="secondary" onClick={props.toggle}>Cancel</Button> </ModalFooter> </Modal> ) } const mapStateToProps = (state) => ({ modal: state.modal, cards: state.card }) const mapDispatchToProps = (dispatch) => ({ toggle: () => dispatch({type: "TOGGLE"}), cardAllChangeTrashFlag: (cards, flag) => dispatch(cardAllChangeTrashFlag(cards, flag)), }) export default connect (mapStateToProps, mapDispatchToProps)(DeleteAllCardsPopUp);
define([], function(){ function mul(values){ var prod = 1; for(var i = 0; i < values.length; i++){ prod = prod * values[i]; } return prod; } return mul; })
const ENDPOINT='https://randomuser.me/api/?results=50'; const getApiData=()=> fetch(ENDPOINT).then(response=>response.json()); export {getApiData};
import './global.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Route } from 'react-router'; import { ConnectedRouter as Router } from 'react-router-redux'; import { Client as Styletron } from 'styletron-engine-atomic'; import createStore from './redux/createStore'; import createHistory from 'history/createBrowserHistory'; import registerServiceWorker from './registerServiceWorker'; import App from './components/App'; import LoginForm from './components/LoginForm'; import PullRequestList from './components/PullRequestList'; import Providers from './components/Providers'; // Setup client providers const history = createHistory(); const store = createStore(history); const app = ( <Providers styletronEngine={new Styletron()} reduxStore={store} > <Router history={history}> <App> <Route exact path="/" component={LoginForm} /> <Route path="/pull-requests" component={PullRequestList}/> </App> </Router> </Providers> ); // Render application ReactDOM.render(app, document.getElementById('root')); registerServiceWorker();
const config = { MAX_ATTACHMENT_SIZE: 5000000, STRIPE_KEY: "pk_test_51IHZ40JnMfBcpvMVd9HyOjgDNgpXj9y5aPc1X2qsyLN1csnVRfFplxRI8trhTfQcYPyLgf4MC0WbcXZXSqUvjSL200x7QnRK6p", s3: { REGION: process.env.REACT_APP_API_REGION, BUCKET: process.env.REACT_APP_BUCKET, }, apiGateway: { REGION: process.env.REACT_APP_API_REGION, URL: process.env.REACT_APP_URL, }, cognito: { REGION: process.env.REACT_APP_API_REGION, USER_POOL_ID: process.env.REACT_APP_USER_POOL_ID, APP_CLIENT_ID: process.env.REACT_APP_CLIENT_ID, IDENTITY_POOL_ID: process.env.REACT_APP_ID_POOL_ID, }, }; export default config;
import Vue from 'vue' import Router from 'vue-router' import MeatPicker from '@/components/MeatPicker' import Login from '@/components/Login' import MeatEditor from '@/components/editor/MeatEditor' Vue.use(Router) export default new Router({ // mode: 'history', routes: [ { path: '/', name: 'MeatPicker', component: MeatPicker }, { path: '/login', name: 'Login', component: Login }, { path: '/meat-editor/:meatbook_name', name: 'MeatEditor', component: MeatEditor, props: true } ] })
$(document).ready(function () { $.ajax({ url: "http://cagov.symsoft.local/api/sitecore/LocationSearch/SearchLocations", type: "POST", data: { searchInput: { SearchWord: "", AgencyName: "California", Services: [], SearchCriterion: {} } }, success: function (response) { $.ajax({ url: "http://api-stage.mapthat.co/V3/EmbedFeaturesFromWidget", type: "POST", data: { mapProvider: "google", features: JSON.stringify([{ "type": "geojson", "geometry": response }]), loadMapLib: true, searchControl: true, embedList: true, mapId: 80, facets: "AgencyName" }, error: function (xhr) { } }); }, error: function (xhr) {} }); });
//https://www.hackerrank.com/challenges/bfsshortreach //100% working. for of is not as fast as cached regular for loop. function Queue(){var a=[],b=0;this.getLength=function(){return a.length-b};this.isEmpty=function(){return 0==a.length};this.enqueue=function(b){a.push(b)};this.dequeue=function(){if(0!=a.length){var c=a[b];2*++b>=a.length&&(a=a.slice(b),b=0);return c}};this.peek=function(){return 0<a.length?a[b]:void 0}}; function processData(input) { 'use strict'; const lines = input.split('\n'); // the invisible carriage return: "\r". wtf? let nTests = lines.shift(); let i = 0; // should bring us to the beginning of each test. while(nTests>0){ let ne = lines[i].split(' '); //temp let numNodes = parseInt(ne.shift()); //number of nodes let numEdges = parseInt(ne); //number of edges let startPos = parseInt(lines[i+1+numEdges]); //starting position let distances = {}; //object to keep track what level each item in queue is on. let edges =[]; for(let a = i+1; a<=i+numEdges; a++){ //fill array of edges. edges.push(lines[a].split(' ').map(Number)); } let queue = new Queue(); let level = 1; let subQueue = new Queue(); let len = edges.length; queue.enqueue(startPos); //add start position to queue. while(!queue.isEmpty()){ //use whatever is at start of queue let n = queue.dequeue(); //start at beginning of queue. for(let i = 0; i < len; i++){ //trying cached for loop instead of for of. let edge = edges[i]; let ni = edge.indexOf(n); if(ni == 1 || ni == 0){ let vie0 = distances[edge[0]] === undefined; let vie1 = distances[edge[1]] === undefined; if(ni == 1 && vie0 == true){ //if contains n and isn't already visited. subQueue.enqueue(edge[0]); distances[edge[0]] = level; //track which level we're on. }else if(ni == 0 && vie1 == true){ subQueue.enqueue(edge[1]); distances[edge[1]] = level; //track which level we're on. } } } if(!subQueue.isEmpty() && queue.isEmpty()){ level++; queue = subQueue; subQueue = new Queue(); //had to clear it here, otherwise it got cleared improperly and missed certain numbers. weird. } } let nodesArr = []; let c = 1; while(numNodes>0){ //create queue of nodes. nodesArr.push(c) c++; numNodes--; } nodesArr.splice(nodesArr.indexOf(startPos), 1); //remove start node from nodes let answer = ''; //get the answer ready. for (let n of nodesArr){ //loop through nodes. if(n in distances){ answer += distances[n]*6+' '; }else{ answer += '-1 '; } } console.log(answer); i += numEdges+2; //increment to beginning of next test nTests--; //decrement tests } }
import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import cx from 'classnames'; import Portal from 'react-portal'; import { forbidExtraProps } from 'airbnb-prop-types'; import { addEventListener, removeEventListener } from 'consolidated-events'; import isTouchDevice from 'is-touch-device'; import SingleDatePickerShape from '../shapes/SingleDatePickerShape'; import { SingleDatePickerPhrases } from '../defaultPhrases'; import OutsideClickHandler from './OutsideClickHandler'; import toMomentObject from '../utils/toMomentObject'; import toLocalizedDateString from '../utils/toLocalizedDateString'; import getResponsiveContainerStyles from '../utils/getResponsiveContainerStyles'; import toISODateString from '../utils/toISODateString'; import SingleDatePickerInput from './SingleDatePickerInput'; import DayPickerSingleDateController from './DayPickerSingleDateController'; import CloseButton from '../svg/close.svg'; import isInclusivelyAfterDay from '../utils/isInclusivelyAfterDay'; import { HORIZONTAL_ORIENTATION, VERTICAL_ORIENTATION, ANCHOR_LEFT, ANCHOR_RIGHT, DAY_SIZE, ICON_BEFORE_POSITION, } from '../../constants'; const propTypes = forbidExtraProps(SingleDatePickerShape); const TIMES = [ '12:00 AM', '12:30 AM', '01:00 AM', '01:30 AM', '02:00 AM', '02:30 AM', '03:00 AM', '03:30 AM', '04:00 AM', '04:30 AM', '05:00 AM', '05:30 AM', '06:00 AM', '06:30 AM', '07:00 AM', '07:30 AM', '08:00 AM', '08:30 AM', '09:00 AM', '09:30 AM', '10:00 AM', '10:30 AM', '11:00 AM', '11:30 AM', '12:00 PM', '12:30 PM', '01:00 PM', '01:30 PM', '02:00 PM', '02:30 PM', '03:00 PM', '03:30 PM', '04:00 PM', '04:30 PM', '05:00 PM', '05:30 PM', '06:00 PM', '06:30 PM', '07:00 PM', '07:30 PM', '08:00 PM', '08:30 PM', '09:00 PM', '09:30 PM', '10:00 PM', '10:30 PM', '11:00 PM', '11:30 PM', ]; const defaultProps = { // required props for a functional interactive SingleDatePicker date: null, focused: false, // input related props id: 'date', placeholder: 'Date', disabled: false, required: false, readOnly: false, screenReaderInputMessage: '', showClearDate: false, showDefaultInputIcon: false, inputIconPosition: ICON_BEFORE_POSITION, customInputIcon: null, customCloseIcon: null, // calendar presentation and interaction related props orientation: HORIZONTAL_ORIENTATION, anchorDirection: ANCHOR_LEFT, horizontalMargin: 0, withPortal: false, withFullScreenPortal: false, initialVisibleMonth: null, firstDayOfWeek: null, numberOfMonths: 2, keepOpenOnDateSelect: false, reopenPickerOnClearDate: false, renderCalendarInfo: null, hideKeyboardShortcutsPanel: false, daySize: DAY_SIZE, isRTL: false, // navigation related props navPrev: null, navNext: null, onPrevMonthClick() {}, onNextMonthClick() {}, onClose() {}, // month presentation and interaction related props renderMonth: null, // day presentation and interaction related props renderDay: null, enableOutsideDays: false, isDayBlocked: () => false, isOutsideRange: day => !isInclusivelyAfterDay(day, moment()), isDayHighlighted: () => {}, // internationalization props displayFormat: () => moment.localeData().longDateFormat('L'), monthFormat: 'MMMM YYYY', phrases: SingleDatePickerPhrases, // mobile props isMobile: false, }; export default class SingleDatePicker extends React.Component { constructor(props) { super(props); this.isTouchDevice = false; this.state = { dayPickerContainerStyles: {}, isDayPickerFocused: false, isInputFocused: false, isTimeItemHovered: false, date: moment(), time: null, dateTime: props.dateTime && moment(props.dateTime * 1000), timeItemElementId: null, }; if (props.dateTime) { const time = moment(props.dateTime * 1000); this.state.date = time; this.state.time = time.format('hh:mm A'); } this.onDayPickerFocus = this.onDayPickerFocus.bind(this); this.onDayPickerBlur = this.onDayPickerBlur.bind(this); this.onChange = this.onChange.bind(this); this.onFocus = this.onFocus.bind(this); this.onClearFocus = this.onClearFocus.bind(this); this.clearDate = this.clearDate.bind(this); this.onDateChange = this.onDateChange.bind(this); this.onTimeChange = this.onTimeChange.bind(this); this.onDateTimeSelect = this.onDateTimeSelect.bind(this); this.onTimeItemMouseEnter = this.onTimeItemMouseEnter.bind(this); this.onTimeItemMouseLeave = this.onTimeItemMouseLeave.bind(this); this.responsivizePickerPosition = this.responsivizePickerPosition.bind(this); } /* istanbul ignore next */ componentDidMount() { this.resizeHandle = addEventListener( window, 'resize', this.responsivizePickerPosition, { passive: true }, ); this.responsivizePickerPosition(); if (this.props.focused) { this.setState({ isInputFocused: true, }); } this.isTouchDevice = isTouchDevice(); } componentDidUpdate(prevProps) { if (!prevProps.focused && this.props.focused) { this.responsivizePickerPosition(); } } /* istanbul ignore next */ componentWillUnmount() { removeEventListener(this.resizeHandle); } onChange(dateString) { const { isOutsideRange, keepOpenOnDateSelect, onDateChange, onFocusChange, onClose, } = this.props; const newDate = toMomentObject(dateString, this.getDisplayFormat()); const isValid = newDate && !isOutsideRange(newDate); if (isValid) { onDateChange(newDate); if (!keepOpenOnDateSelect) { onFocusChange({ focused: false }); onClose({ date: newDate }); } } else { onDateChange(null); } } onFocus() { const { disabled, onFocusChange, withPortal, withFullScreenPortal } = this.props; const moveFocusToDayPicker = withPortal || withFullScreenPortal || this.isTouchDevice; if (moveFocusToDayPicker) { this.onDayPickerFocus(); } else { this.onDayPickerBlur(); } if (!disabled) { onFocusChange({ focused: true }); } } onClearFocus() { const { startDate, endDate, focused, onFocusChange, onClose } = this.props; if (!focused) return; this.setState({ isInputFocused: false, isDayPickerFocused: false, }); onFocusChange({ focused: false }); onClose({ startDate, endDate }); } onDayPickerFocus() { this.setState({ isInputFocused: false, isDayPickerFocused: true, }); } onDayPickerBlur() { this.setState({ isInputFocused: true, isDayPickerFocused: false, }); } onDateChange(date) { const dateTime = moment(`${date.format('DD/MM/YYYY')} ${this.state.time}`, 'DD/MM/YYYY hh:mm A'); this.props.onDateTimeChange(dateTime.unix()); this.setState({ dateTime, date }); } onTimeChange(time) { const dateTime = moment(`${this.state.date.format('DD/MM/YYYY')} ${time}`, 'DD/MM/YYYY hh:mm A'); this.props.onDateTimeChange(dateTime.unix()); this.setState({ dateTime, time }); } onTimeItemMouseEnter(e) { this.setState({ isTimeItemHovered: true, timeItemElementId: e.target.getAttribute('id'), }); } onTimeItemMouseLeave() { this.setState({ isTimeItemHovered: false, timeItemElementId: null, }); } onDateTimeSelect() { this.props.onDateTimeChange(this.state.dateTime.unix()); this.props.onFocusChange({ focused: null }); this.props.onClose(); } getDateString(date) { const displayFormat = this.getDisplayFormat(); if (date && displayFormat) { return date && date.format(displayFormat); } return toLocalizedDateString(date); } getDateTimeString() { if (!this.state.dateTime) return ''; const value = this.state.dateTime; let dayName = value.format('dddd'); dayName = dayName.substr(0, 1).toUpperCase() + dayName.substr(1); const date = value.format('D'); const month = value.format('M'); const year = value.format('YYYY'); const hours = value.format('HH:mm'); const displayString = `${dayName}, ${date} tháng ${month}, ${year} vào lúc ${hours}`; return displayString; } getDayPickerContainerClasses() { const { orientation, withPortal, withFullScreenPortal, anchorDirection, isRTL } = this.props; const dayPickerClassName = cx('SingleDatePicker__picker', { 'SingleDatePicker__picker--direction-left': anchorDirection === ANCHOR_LEFT, 'SingleDatePicker__picker--direction-right': anchorDirection === ANCHOR_RIGHT, 'SingleDatePicker__picker--horizontal': orientation === HORIZONTAL_ORIENTATION, 'SingleDatePicker__picker--vertical': orientation === VERTICAL_ORIENTATION, 'SingleDatePicker__picker--portal': withPortal || withFullScreenPortal, 'SingleDatePicker__picker--full-screen-portal': withFullScreenPortal, 'SingleDatePicker__picker--rtl': isRTL, }); return dayPickerClassName; } getDisplayFormat() { const { displayFormat } = this.props; return typeof displayFormat === 'string' ? displayFormat : displayFormat(); } clearDate() { const { onDateChange, reopenPickerOnClearDate, onFocusChange } = this.props; onDateChange(null); if (reopenPickerOnClearDate) { onFocusChange({ focused: true }); } } /* istanbul ignore next */ responsivizePickerPosition() { // It's possible the portal props have been changed in response to window resizes // So let's ensure we reset this back to the base state each time this.setState({ dayPickerContainerStyles: {} }); const { anchorDirection, horizontalMargin, withPortal, withFullScreenPortal, focused, } = this.props; const { dayPickerContainerStyles } = this.state; if (!focused) { return; } const isAnchoredLeft = anchorDirection === ANCHOR_LEFT; if (!withPortal && !withFullScreenPortal) { const containerRect = this.dayPickerContainer.getBoundingClientRect(); const currentOffset = dayPickerContainerStyles[anchorDirection] || 0; const containerEdge = isAnchoredLeft ? containerRect[ANCHOR_RIGHT] : containerRect[ANCHOR_LEFT]; this.setState({ dayPickerContainerStyles: getResponsiveContainerStyles( anchorDirection, currentOffset, containerEdge, horizontalMargin, ), }); } } maybeRenderDayPickerWithPortal() { const { focused, withPortal, withFullScreenPortal } = this.props; if (!focused) { return null; } if (withPortal || withFullScreenPortal) { return ( <Portal isOpened> {this.renderDayPicker()} </Portal> ); } return this.renderDayPicker(); } renderDayPicker() { const { onDateChange, date, dateTime, onFocusChange, focused, enableOutsideDays, numberOfMonths, orientation, monthFormat, navPrev, navNext, onPrevMonthClick, onNextMonthClick, withPortal, withFullScreenPortal, keepOpenOnDateSelect, initialVisibleMonth, renderMonth, renderDay, renderCalendarInfo, hideKeyboardShortcutsPanel, firstDayOfWeek, customCloseIcon, phrases, daySize, isRTL, isOutsideRange, isDayBlocked, isDayHighlighted, isMobile, } = this.props; const { dayPickerContainerStyles, isDayPickerFocused } = this.state; const onOutsideClick = (!withFullScreenPortal && withPortal) ? this.onClearFocus : undefined; const closeIcon = customCloseIcon || (<CloseButton />); if (isMobile) { return ( <div // eslint-disable-line jsx-a11y/no-static-element-interactions ref={(ref) => { this.dayPickerContainer = ref; }} className={this.getDayPickerContainerClasses()} style={{ display: 'flex', flexDirection: 'column', borderRadius: '3px', boxShadow: '0 2px 10px 0 rgba(0, 0, 0, 0.3)', left: 10, }} onClick={onOutsideClick} > <div style={{ display: 'flex', flexDirection: 'column', minHeight: '295px', maxHeight: '100%', borderBottom: 'solid 1px #e9e9e9', }} > <DayPickerSingleDateController isMobile={isMobile} date={this.state.date} onDateChange={this.onDateChange} onFocusChange={onFocusChange} orientation={orientation} enableOutsideDays={enableOutsideDays} numberOfMonths={numberOfMonths} monthFormat={monthFormat} withPortal={withPortal || withFullScreenPortal} focused={focused} keepOpenOnDateSelect={keepOpenOnDateSelect} hideKeyboardShortcutsPanel={hideKeyboardShortcutsPanel} initialVisibleMonth={initialVisibleMonth} navPrev={navPrev} navNext={navNext} onPrevMonthClick={onPrevMonthClick} onNextMonthClick={onNextMonthClick} renderMonth={renderMonth} renderDay={renderDay} renderCalendarInfo={renderCalendarInfo} isFocused={isDayPickerFocused} phrases={phrases} daySize={daySize} isRTL={isRTL} isOutsideRange={isOutsideRange} isDayBlocked={isDayBlocked} isDayHighlighted={isDayHighlighted} firstDayOfWeek={firstDayOfWeek} /> <div style={{ width: '100%', backgroundColor: '#f9f9f9', padding: '0', zIndex: 2 }}> <div style={{ height: '60px', margin: '15px 0', overflowY: 'scroll', overflowX: 'hidden' }}> <ul style={{ margin: '0', height: '100%', padding: '0 15px' }}> { /* eslint-disable */ TIMES.map(time => { const classNames = cx('TimeListItem', { 'TimeListItem--selected': time === this.state.time, 'TimeListItem--hovered': this.state.isTimeItemHovered && time === this.state.timeItemElementId, }); return ( <li key={time} id={time} className={classNames} onMouseEnter={this.onTimeItemMouseEnter} onMouseLeave={this.onTimeItemMouseLeave} onClick={() => this.onTimeChange(time)} > {time} </li> ); }) /* eslint-enable */ } </ul> </div> </div> </div> <div className="SingleDatePickerFooter"> <div> { this.state.date && this.state.time && `${this.state.date.format('DD/MM/YYYY')}, ${this.state.time}` } </div> <div> <button className="CalendarDay__selectButton" onClick={this.onDateTimeSelect} >Chọn </button> </div> </div> </div> ); } return ( <div // eslint-disable-line jsx-a11y/no-static-element-interactions ref={(ref) => { this.dayPickerContainer = ref; }} className={this.getDayPickerContainerClasses()} style={{ display: 'flex', flexDirection: 'column', borderRadius: '3px', boxShadow: '0 2px 10px 0 rgba(0, 0, 0, 0.3)', left: 10, }} onClick={onOutsideClick} > <div style={{ display: 'flex', flexDirection: 'row', minHeight: '295px', maxHeight: '350px', borderBottom: 'solid 1px #e9e9e9', }} > <DayPickerSingleDateController date={this.state.date} onDateChange={this.onDateChange} onFocusChange={onFocusChange} orientation={orientation} enableOutsideDays={enableOutsideDays} numberOfMonths={numberOfMonths} monthFormat={monthFormat} withPortal={withPortal || withFullScreenPortal} focused={focused} keepOpenOnDateSelect={keepOpenOnDateSelect} hideKeyboardShortcutsPanel={hideKeyboardShortcutsPanel} initialVisibleMonth={initialVisibleMonth} navPrev={navPrev} navNext={navNext} onPrevMonthClick={onPrevMonthClick} onNextMonthClick={onNextMonthClick} renderMonth={renderMonth} renderDay={renderDay} renderCalendarInfo={renderCalendarInfo} isFocused={isDayPickerFocused} phrases={phrases} daySize={daySize} isRTL={isRTL} isOutsideRange={isOutsideRange} isDayBlocked={isDayBlocked} isDayHighlighted={isDayHighlighted} firstDayOfWeek={firstDayOfWeek} /> <div style={{ minWidth: '25%', backgroundColor: '#f9f9f9', padding: '15px 0 15px 0', zIndex: 2 }}> <div style={{ height: '90%', margin: '15px 0', overflowY: 'scroll', overflowX: 'hidden' }}> <ul style={{ margin: '0', height: '100%', padding: '0 15px' }}> { /* eslint-disable */ TIMES.map(time => { const classNames = cx('TimeListItem', { 'TimeListItem--selected': time === this.state.time, 'TimeListItem--hovered': this.state.isTimeItemHovered && time === this.state.timeItemElementId, }); return ( <li key={time} id={time} className={classNames} onMouseEnter={this.onTimeItemMouseEnter} onMouseLeave={this.onTimeItemMouseLeave} onClick={() => this.onTimeChange(time)} > {time} </li> ); }) /* eslint-enable */ } </ul> </div> </div> </div> <div className="SingleDatePickerFooter"> <div> { this.state.date && this.state.time && `${this.state.date.format('DD/MM/YYYY')}, ${this.state.time}` } </div> <div> <button className="CalendarDay__selectButton" onClick={this.onDateTimeSelect} >Chọn </button> </div> </div> {withFullScreenPortal && ( <button aria-label={phrases.closeDatePicker} className="SingleDatePicker__close" type="button" onClick={this.onClearFocus} > <div className="SingleDatePicker__close-icon"> {closeIcon} </div> </button> )} </div> ); } render() { const { id, placeholder, disabled, focused, required, readOnly, showClearDate, showDefaultInputIcon, inputIconPosition, customInputIcon, date, phrases, withPortal, withFullScreenPortal, screenReaderInputMessage, isRTL, } = this.props; const { isInputFocused } = this.state; // const displayValue = this.getDateString(date); const displayValue = this.getDateTimeString(); const inputValue = toISODateString(date); const onOutsideClick = (!withPortal && !withFullScreenPortal) ? this.onClearFocus : undefined; return ( <div className="SingleDatePicker"> <OutsideClickHandler onOutsideClick={onOutsideClick}> <SingleDatePickerInput id={id} placeholder={placeholder} focused={focused} isFocused={isInputFocused} disabled={disabled} required={required} readOnly={readOnly} showCaret={!withPortal && !withFullScreenPortal} onClearDate={this.clearDate} showClearDate={showClearDate} showDefaultInputIcon={showDefaultInputIcon} inputIconPosition={inputIconPosition} customInputIcon={customInputIcon} displayValue={displayValue} inputValue={inputValue} onChange={this.onChange} onFocus={this.onFocus} onKeyDownShiftTab={this.onClearFocus} onKeyDownTab={this.onClearFocus} onKeyDownArrowDown={this.onDayPickerFocus} screenReaderMessage={screenReaderInputMessage} phrases={phrases} isRTL={isRTL} /> {this.maybeRenderDayPickerWithPortal()} </OutsideClickHandler> </div> ); } } SingleDatePicker.propTypes = Object.assign(propTypes, { onDateTimeChange: PropTypes.func.isRequired, }); SingleDatePicker.defaultProps = defaultProps;
(function() { 'use strict' angular .module('Orders.view.module') .controller('OrdersCtrl', OrdersCtrl); OrdersCtrl.$inject = ['$log', 'OrderManager', 'OrderDispatcher']; function OrdersCtrl($log, OrderManager, OrderDispatcher) { var vc = this; $log.instantiate("Orders", "Controller"); $log.info("Manager", OrderManager) vc.stateHandler = 'booze.orders'; vc.orders = OrderManager.orders; // temp solution for reducing values for total quantity; vc.orders.forEach(function(order) { order.totalqty = Object.keys(order.qty).reduce(function(sum, key) { return sum + order.qty[key] }, 0); }) $log.info("orders", OrderManager.orders) vc.select = function(order) { vc.stateHandler = 'booze.orders.show'; vc.order = order; }; vc.deselect = function() { vc.order = null; vc.stateHandler = 'booze.orders'; }; vc.toggleSelect = 'command'; vc.tabSelect = 'Pending'; vc.toggleValues = function(view, option) { console.log("toggle values", view) console.log("toggle values", option) vc.toggleSelect = view; view === 'line' && !option ? vc.tabSelect = 'Pending' : vc.tabSelect = option; } } })();
import css from "styled-jsx/css"; export const NavStyles = css` .nav { background: #000; color: #fff; padding: 1em 100px; } .nav a { color: #fff; opacity: 0.8; } .nav a:hover { opacity: 1; } div { align-items: center; display: flex; height: 100%; width: 100%; } ul { padding-left: 0; } ul li { display: inline-block; margin-right: 30px; } a, a:active, a:visited { text-decoration: none; color: black; } `;
import React, {Component} from 'react'; class NewTabParser extends Component { constructor(props) { super(props); this.listener = this.listenToMessages.bind(this); this.messageChannels = null; } listenToMessages(message) { try { if (typeof(message.data.kc3assets) !== "undefined") { localStorage.setItem("kc3assets", message.data.kc3assets); } if (message.data.type==="KC3_SHIPS") this.props.messageHandler(message.data.ships); } catch (e) { return console.error(e); } } componentDidMount() { if(this.messageChannels === null){ this.messageChannels = new MessageChannel(); this.messageChannels.port1.onmessage = this.listener; } window.opener.parent.postMessage("EXPORTER_STATE_READY", "*", [this.messageChannels.port2]); } componentWillUnmount() { window.removeEventListener("message", this.listener); } render() { return (<div>waiting for tab message to come...</div>); } } export default NewTabParser;
// app.module.js (function() { "use strict"; angular.module("CounterApp", []); })();
import React from "react"; import styled from "@emotion/styled"; import { Helmet } from "react-helmet-async"; import { Paper, Typography } from "@mui/material"; import AuthLayout from "../../layouts/Auth"; import SignUpComponent from "../../components/auth/SignUp"; import Logo from "../../vendor/logo.svg"; const Brand = styled(Logo)` fill: ${(props) => props.theme.palette.primary.main}; width: 64px; height: 64px; margin-bottom: 32px; `; const Wrapper = styled(Paper)` padding: ${(props) => props.theme.spacing(6)}; ${(props) => props.theme.breakpoints.up("md")} { padding: ${(props) => props.theme.spacing(10)}; } `; function SignUp() { return ( <React.Fragment> <Brand /> <Wrapper> <Helmet title="Sign Up" /> <Typography component="h1" variant="h4" align="center" gutterBottom> Get started </Typography> <Typography component="h2" variant="body1" align="center"> Start creating the best possible user experience for you customers </Typography> <SignUpComponent /> </Wrapper> </React.Fragment> ); } SignUp.getLayout = function getLayout(page) { return <AuthLayout>{page}</AuthLayout>; }; export default SignUp;
/** * Copyright (c) Benjamin Ansbach - all rights reserved. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const Coding = require('@pascalcoin-sbx/common').Coding; const CompositeType = Coding.CompositeType; /** * The raw coder for a MultiOperation.Receiver. */ class RawAndDigestCoder extends CompositeType { /** * Constructor */ constructor() { super('multiop_receiver_raw'); this.description('The coder for the raw and digest representation of a MultiOperation.Receiver'); this.addSubType( new Coding.Pascal.AccountNumber('account') .description('The account of the operation.') ); this.addSubType( new Coding.Pascal.Currency('amount') .description('The amount sent by the sender.') ); this.addSubType( new Coding.Core.BytesWithLength('payload', 2, 'payload_length', 'The length of the payload') .description('The payload of the operation.') ); } /** * @inheritDoc AbstractType#typeInfo */ /* istanbul ignore next */ get typeInfo() { let info = super.typeInfo; info.name = 'MultiOperation.Receiver (RAW & DIGEST)'; info.hierarchy.push(info.name); return info; } } module.exports = RawAndDigestCoder;
details = document.querySelectorAll("details"); details.forEach((targetDetail) => { targetDetail.addEventListener("click", () => { details.forEach((detail) => { if (detail !== targetDetail) { detail.removeAttribute("open"); } }); }); }); var admo_noblock = function(target) { var html = target.innerHTML; let select = ''; let query = ''; const adm = ['note', 'seealso', 'abstract', 'summary', 'tldr', 'info', 'todo', 'tip', 'hint', 'important', 'success', 'check', 'done', 'question', 'help', 'faq', 'warning', 'caution', 'attention', 'failure', 'fail', 'missing', 'danger', 'error', 'bug', 'example', 'exemple', "abstract", 'quote', 'cite' ]; const p_search = /<p>[?!]{3}ad-([A-Za-zÀ-ÖØ-öø-ÿ]+)/gi; const found_p = html.match(p_search); let select_html = '' if (found_p) { const p_len = found_p.length; for (var i = 0; i < p_len; i++) { select = found_p[i].replace("!!!ad-", ''); select = select.replace("???ad-", ''); select = select.replace('<p>', '') query = "<p class='admo-note'>"; select_html = '.admo-note' const replaced = new RegExp(`<p>[!?]{3}ad-${select}`, 'gi') const replaceit = html.match(replaced) console.log(html) for (var j = 0; j < replaceit.length; j++) { html = html.replace(replaceit[j], query.replace('<br>', '')); console.log(html) } } target.innerHTML = html; } } admo_noblock(document.querySelector('.content'))
//Copyright 2012, John Wilson, Brighton Sussex UK. Licensed under the BSD License. See licence.txt function assert(b,str) { if (!b) { return alert("ASSERT: "+str) } } function Vector4(x,y,z,w) { this._x = x || 0 ; this._y = y || 0 ; this._z = z || 0 ; this._w = w || 0 ; this.className = Vector4.className ; } Vector4.className = 'Vector4' ; Vector4.Create = function(x,y,z,w) { if (x != undefined && y == undefined) { return Vector4._CreateVector(x) ; } else { return Vector4._CreateScalar(x,y,z,w) ; } } Vector4.CreateBroadcast=function(number) { var v = new Vector4() v.SetBroadcast(number) return v ; } Vector4._CreateVector=function(v) { var x = (v && v.X()) || 0 ; var y = (v && v.Y()) || 0 ; var z = (v && v.Z()) || 0 ; var w = (v && v.W()) || 0 ; return new Vector4(x,y,z,w) ; } Vector4._CreateScalar=function(x,y,z,w) { return new Vector4(x,y,z,w) ; } Vector4.Multiply = function(dst,src,scale) { return dst.Multiply(src,scale) ; } Vector4.Dot3 = function(v1,v2) { return v1.Dot3(v2) ; } Vector4.Dot2 = function(v1,v2) { return v1.Dot2(v2) ; } Vector4.Normal2 = function(v) { return v.Normal2() ; } Vector4.Normalise3 = function(v) { v.Normalise3() ; } Vector4.Normalize3 = function(v) { v.Normalise3() ; } Vector4.Normalise2 = function(v) { v.Normalise2() ; } Vector4.Normalize2 = function(v) { v.Normalise2() ; } Vector4.Cross = function(dst,v1,v2) { dst.Cross(v1,v2) ; } Vector4.Length4 = function(v1) { return v1.Length4(v1) ; } Vector4.Length3 = function(v1) { return v1.Length3(v1) ; } Vector4.Length2 = function(v1) { return v1.Length2(v1) ; } Vector4.Add = function(dst,v1,v2) { dst.Add(v1,v2) ; } Vector4.Subtract = function(dst,v1,v2) { dst.Subtract(v1,v2) ; } Vector4.Subtract = function(dst,v1,v2) { dst.Subtract(v1,v2) ; } Vector4.X = function(v) { return v.X() ; } Vector4.Y = function(v) { return v.Y() ; } Vector4.Z = function(v) { return v.Z() ; } Vector4.W = function(v) { return v.W() ; } Vector4.TransformPoint = function(dest,matrix,source) { dest.TransformPoint(matrix,source) ; } Vector4.Calculate2dLineIntersection = function( intersectionPoint, p0, p1, q0, q1, infiniteLine ) { return intersectionPoint.Calculate2dLineIntersection( intersectionPoint, p0, p1, q0, q1, infiniteLine ) ; } Vector4.Test = function() { var tmp = Vector4.Create() Vector4.Add(tmp,Vector4.Create(1,2,3),Vector4.Create(6,7,8)) alert("Result1 = "+tmp) Vector4.Normalise3(tmp) alert("Result2 = "+tmp) alert("Unit Result3 = "+Vector4.Length3(tmp)) Vector4.Subtract(tmp,Vector4.Create(7,9,11),Vector4.Create(6,7,8)) alert("Result4 = "+tmp) } Vector4.prototype = { constructor: Vector4, SetBroadcast: function(val) { this.SetXyzw(val,val,val,val) }, X: function() { return this._x }, Y: function() { return this._y }, Z: function() { return this._z }, W: function() { return this._w }, SetX: function(val) { this._x = val }, SetY: function(val) { this._y = val }, SetZ: function(val) { this._z = val }, SetW: function(val) { this._w = val }, SetXyzw: function(x,y,z,w) { this.SetX(x || 0) this.SetY(y || 0) this.SetZ(z || 0) this.SetW(w || 0) }, Copy: function(source) { this._x = source._x this._y = source._y this._z = source._z this._w = source._w }, Subtract: function(v1,v2) { this._x = v1._x - v2._x this._y = v1._y - v2._y this._z = v1._z - v2._z this._w = v1._w - v2._w }, Add: function(v1,v2) { this._x = v1._x + v2._x this._y = v1._y + v2._y this._z = v1._z + v2._z this._w = v1._w + v2._w }, Divide: function(dst,src1,src2) { assert(false,"Vector4.Divide: NOT YET IMPLEMENTED") }, Cross: function(src1,src2) { this._x = ( src1._y * src2._z ) - ( src1._z * src2._y ) this._y = ( src1._z * src2._x ) - ( src1._x * src2._z ) this._z = ( src1._x * src2._y ) - ( src1._y * src2._x ) }, Multiply: function(src,scale) { // TODO VARIATIONS this._x = src._x * scale this._y = src._y * scale this._z = src._z * scale }, ScaleXXX: function(scale) { this._x = this._x * scale this._y = this._y * scale this._z = this._z * scale }, Length4: function() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w) }, Length3: function() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z) }, Length2: function() { return Math.sqrt(this._x * this._x + this._y * this._y) }, mag: function() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w) }, Normal2: function() { var v = Vector4.Create(this) v._z = 0 v._w = 0 v.Normalise2() return v }, Normal3: function() { var v = Vector4.Create(this) v._w = 0 v.Normalise3() return v }, Normal4: function() { var v = Vector4.Create(this) v.Normalise4() return v }, Normalise2: function() { var len = this.Length2() ; //assert(len != 0,'Normalise2 - Attemp to Normalise with Zero Length Vector:'+this._toString()) this.SetXyzw(this._x / len, this._y / len, this._z,this._w) ; }, Normalize3: function() { this.Normalise3() }, Normalise3: function() { var len = this.Length3() assert(len != 0,'Normalise3 - Attemp to Normalise with Zero Length Vector:'+this._toString()) this.SetXyzw(this._x / len, this._y / len, this._z / len,this._w) }, Normalise4: function() { var len = this.Length4() assert(len != 0,'Normalise4 - Attemp to Normalise with Zero Length Vector:'+this._toString()) this.SetXyzw(this._x / len, this._y / len, this._z / len,this._w / len) ; }, Dot2: function(v2) { return (this._x*v2._x + this._y*v2._y) ; }, Dot3: function(v2) { return (this._x*v2._x + this._y*v2._y + this._z*v2._z) ; }, Dot4: function(v2) { return (this._x*v2._x + this._y*v2._y + this._z*v2._z + this._w*v2._w) ; }, toString: function() { return "Vector4: "+this._x+","+this._y+","+this._z+","+this._w ; }, _toString: function() { return this.toString() }, // TODO - CONVERT Transformation stuff Transform: function(dest,matrix,source) { this._Transform(dest,matrix,source) ; }, TransformVector: function(dest,matrix,source) { this._Transform(dest,matrix,source,0) ; }, TransformPoint: function(matrix,source) { this._Transform(matrix,source,1) ; }, // _Transform: function(dest,matrix,source,defaultW) // { // }, _Transform: function(matrix,source,defaultW) { var dest = this ; // assert(matrix && matrix.className == Matrix44.className,'Vector4.TransformPoint - invalid matrix') if (source && source.className && source.className == Vector4.className) { //assert(dest && source,'Vector4.TransformPoint - invalid source/dest') tmpV.Copy(source) if (defaultW) { tmpV.SetW(defaultW) } matrix._MultiplyVector(tmpV,dest) } else { //assert(dest && source && type(dest) == 'table' && type(source)=='table' and (#dest >= #source),'Vector4.TransformPoint - source/dest Invalid Tables') for (var idx = 0 ; idx < source.length ; source++) { var sourceV = source[idx] ; var destV = dest[idx] ; tmpV.Copy(sourceV) if (defaultW) { tmpV.SetW(defaultW) ; } matrix._MultiplyVector(tmpV,destV) ; } } }, // Gen Equation of 3D Line going through points P0 and P1 // P0 + u(P1 - P0) (u is some constant) // Likewise for second line intersecting points Q0 and Q1 // Q0 + z(Q1 - Q0) z is some constant // @ common intersect P0+u(P1-P0) = Q0 + z(Q1-Q0) // u(P1-P0) - z(Q1-Q0) = Q0 - P0 // In matrix form // Solve (u,v,1,1) = // |px -qx 0 0|^-1 | qpx | // |py -qy 0 0| * | qpy | // |pz -qz 1 -1| | qpz | // |0 0 0 1| | 1 | // px,py,pz = Vector(P1-P0) // qx,qy,qz = Vector(Q1-Q0) // qpx,qpy,qpz = Vector(Q0-P0) // Ok, Ok!.. above eqn I formulated is slightly bollocked - seems to work in 2D only Calculate2dLineIntersection: function( intersectionPoint, p0, p1, q0, q1, infiniteLine ) { // assert(intersectionPoint && intersectionPoint.className == Vector4.className,'Vector4.Calculate2dLineIntersection: Invalid Parameter intersectionPoint') // assert(p0 && p0.className == Vector4.className,'Vector4.Calculate2dLineIntersection: Invalid Parameter p0') // assert(p1 && p1.className == Vector4.className,'Vector4.Calculate2dLineIntersection: Invalid Parameter p1') // assert(q0 && q0.className == Vector4.className,'Vector4.Calculate2dLineIntersection: Invalid Parameter q0') // assert(q1 && q1.className == Vector4.className,'Vector4.Calculate2dLineIntersection: Invalid Parameter q1') var dirP = Vector4.Create(p1) ; dirP.Subtract(dirP,p0) ; var lenP = dirP.Length3() ; var ndirP = Vector4.Create(dirP) ; ndirP.Normalise3() ; var dirQ = Vector4.Create(q1) ; dirQ.Subtract(dirQ,q0) ; var ndirQ = Vector4.Create(dirQ) ; ndirQ.Normalise3() ; dirQ.Multiply(dirQ,-1) ; var lenQ = dirQ.Length3() ; // TODO Quick Check for Parallel lines - Cheaper than Det() var pDp = Vector4.Dot3(ndirQ,ndirP) ; var PQ = Vector4.Create(q0) ; PQ.Subtract(PQ,p0) ; var matrix = Matrix44.Create(dirP,dirQ,Vector4.Create(0,0,1,0),Vector4.Create(0,0,-1,1)) matrix.Transpose() ; var det = matrix._Det() ; if (det == 0) { // No Inverse matrix - no solution - ie. Par lines return {collide:false,u:-1,v:-1,z:-1,w:-1} ; } matrix.Invert(matrix) ; var u = Vector4.Dot3(matrix.GetRow(1),PQ) ; var v = Vector4.Dot3(matrix.GetRow(2),PQ) ; var z = Vector4.Dot3(matrix.GetRow(3),PQ) ; var w = Vector4.Dot3(matrix.GetRow(3),PQ) ; if ((z != 0) || (w != 0)) { return {collide:false,u:u,v:v,z:z,w:w} ; } intersectionPoint.Copy(dirP) ; intersectionPoint.Normalise3() ; intersectionPoint.Multiply(intersectionPoint,u*lenP) ; intersectionPoint.Add(intersectionPoint,p0) ; if (!infiniteLine) { return {collide:(u >=0 && u <=1 && v >= 0 && v <= 1),u:u,v:v,z:z,w:w} ; } else { return {collide:true,u:u,v:v,z:z,w:w} ; } } }
../../../../../shared/src/generic/ErrorMessage/actions.js
const config = require('../../config.json') const filterFeed = require('./filters.js') const generateEmbed = require('./embed.js') const Article = require('./Article.js') const getSubs = require('./subscriptions.js') function isNotEmpty (obj) { for (var x in obj) { return true } } module.exports = function (guildRss, rssName, rawArticle, isTestMessage, returnObject) { const rssList = guildRss.sources // Just in case. If this happens, please report. if (!rssList[rssName]) { console.log(`RSS Error: Unable to translate a null source:\nguildId: ${guildRss ? guildRss.id : undefined}\nrssName: ${rssName}\nrssList:`, rssList); return null } const article = new Article(rawArticle, guildRss, rssName) article.subscriptions = getSubs(rssList, rssName, article) // if (returnObject) return article // Filter message let filterExists = false if (rssList[rssName].filters && typeof rssList[rssName].filters === 'object') { for (var prop in rssList[rssName].filters) { if (prop !== 'roleSubscriptions') filterExists = true // Check if any filter categories exists, excluding roleSubs as they are not filters } } const filterResults = filterExists ? filterFeed(rssList, rssName, article, isTestMessage) : isTestMessage ? {passedFilters: true} : false if (returnObject) { article.filterResults = filterResults return article } if (!isTestMessage && filterExists && !filterResults) return null // Feed article delivery only passes through if the filter found the specified content const finalMessageCombo = {} if (typeof rssList[rssName].embedMessage === 'object' && typeof rssList[rssName].embedMessage.properties === 'object' && isNotEmpty(rssList[rssName].embedMessage.properties)) { // Check if embed is enabled finalMessageCombo.embedMsg = generateEmbed(rssList, rssName, article) let txtMsg = '' if (typeof rssList[rssName].message !== 'string') { if (config.feedSettings.defaultMessage.trim() === '{empty}') txtMsg = '' else txtMsg = article.convertKeywords(config.feedSettings.defaultMessage) } else if (rssList[rssName].message.trim() === '{empty}') txtMsg = '' else txtMsg = article.convertKeywords(rssList[rssName].message) finalMessageCombo.textMsg = txtMsg } else { let txtMsg = '' if (typeof rssList[rssName].message !== 'string' || rssList[rssName].message.trim() === '{empty}') { if (config.feedSettings.defaultMessage.trim() === '{empty}') txtMsg = '' else txtMsg = article.convertKeywords(config.feedSettings.defaultMessage) } else txtMsg = article.convertKeywords(rssList[rssName].message) finalMessageCombo.textMsg = txtMsg } // Generate test details if (isTestMessage) { let testDetails = '' const footer = '\nBelow is the configured message to be sent for this feed:\n\n--' testDetails += `\`\`\`Markdown\n# BEGIN TEST DETAILS #\`\`\`\`\`\`Markdown` if (article.title) { testDetails += `\n\n[Title]: {title}\n${article.title}` } if (article.summary && article.summary !== article.description) { // Do not add summary if summary = description let testSummary if (article.description && article.description.length > 500) testSummary = (article.summary.length > 500) ? `${article.summary.slice(0, 490)} [...]\n\n**(Truncated summary for shorter rsstest)**` : article.summary // If description is long, truncate summary. else testSummary = article.summary testDetails += `\n\n[Summary]: {summary}\n${testSummary}` } if (article.description) { let testDescrip if (article.summary && article.summary.length > 500) testDescrip = (article.description.length > 500) ? `${article.description.slice(0, 490)} [...]\n\n**(Truncated description for shorter rsstest)**` : article.description // If summary is long, truncate description. else testDescrip = article.description testDetails += `\n\n[Description]: {description}\n${testDescrip}` } if (article.date) testDetails += `\n\n[Published Date]: {date}\n${article.date}` if (article.author) testDetails += `\n\n[Author]: {author}\n${article.author}` if (article.link) testDetails += `\n\n[Link]: {link}\n${article.link}` if (article.subscriptions) testDetails += `\n\n[Subscriptions]: {subscriptions}\n${article.subscriptions.split(' ').length - 1} subscriber(s)` if (article.images) testDetails += `\n\n${article.listImages()}` let placeholderImgs = article.listPlaceholderImages() if (placeholderImgs) testDetails += `\n\n${placeholderImgs}` if (article.tags) testDetails += `\n\n[Tags]: {tags}\n${article.tags}` if (filterExists) testDetails += `\n\n[Passed Filters?]: ${filterResults.passedFilters ? 'Yes' : 'No'}${filterResults.passedFilters ? filterResults.listMatches(false) + filterResults.listMatches(true) : filterResults.listMatches(true) + filterResults.listMatches(false)}` testDetails += '```' + footer finalMessageCombo.testDetails = testDetails } return finalMessageCombo }
// 数组转参数 又叫 展开数组 const arr = [1, 2, 3] function foo(...args) { console.log(...args); // 这里也可以拿到参数,由 ... 和 数组组成 } // old foo.apply(foo, arr) foo(...arr) // 可以把一个数组 加上 ... 当成参数传进函数
// @flow import DateTime from 'immutable-datetime'; import type {Schedule} from '../data/schedule/Schedule-type'; type TimeKey = 'upcoming' | 'ongoing' | 'past'; export default function getScheduleBasedOnCurrentTime( scheduleList: Array<Schedule>, date: number, ) { let result: Map<TimeKey, Array<Schedule>> = new Map(); let now = DateTime.fromNumber(date); for (let schedule of scheduleList) { let scheduleDate = DateTime.fromString(schedule.dateString); let endScheduleDate = scheduleDate.addMinutes(schedule.durationInMinutes); let timeKey = ''; if (now.toNumber() < scheduleDate.toNumber()) { timeKey = 'upcoming'; } else if (now.toNumber() < endScheduleDate.toNumber()) { timeKey = 'ongoing'; } else { timeKey = 'past'; } let keySchedule = result.get(timeKey); if (keySchedule) { keySchedule.push(schedule); result.set(timeKey, keySchedule); } else { result.set(timeKey, [schedule]); } } return result; }
/** * Created by Vadym Yatsyuk on 18/10/2016 */ import React from 'react'; import { NavLink } from 'react-router-dom'; import './app.scss'; export class App extends React.Component { render() { return ( <div className="app-component"> <header> <div className="header-container"> <NavLink to="/" exact activeClassName='active'>GraphQL</NavLink> <span className="divider"></span> <NavLink to="/new" exact activeClassName='active'>Add new user</NavLink> </div> </header> <section> { this.props.children } </section> <footer> Vadym Yatsyuk </footer> </div> ); } }
module.exports = class Task { constructor(id, story_points, status) { this.id = id; this.status = status; this.story_points = story_points; this.nstory_points = this.normalizeStoryPoints(story_points) + 'h'; } normalizeStoryPoints(sp) { switch (sp) { case 1: return 1; case 2: return 2; case 3: return 4; case 5: return 8; case 8: return 24; case 13: return 40; } } };
import React from 'react'; class UpdateVideoForm extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.state = { apiResponseMessage: "", title: props.details.title, description: props.details.description } } onChange(e) { this.setState({[e.target.name]: e.target.value}) } handleSubmit(event) { event.preventDefault(); const data = new FormData(event.target); data.set('url', data.get('url')); data.set('title', data.get('title')); data.set('description', data.get('description')); fetch('http://localhost:8080/api/u-video', { method: 'POST', body: data, }).then(response => { return response.json(); }).then(json => { this.setState({apiResponseMessage : json.message}); // then update state to know the api response message this.props.handler(this.state.apiResponseMessage) }).catch((error) => { console.error(error); }); } render () { const details = this.props.details; return ( <form onSubmit={this.handleSubmit} className="form"> <fieldset> <legend>Modification d'une video</legend> <label htmlFor="url">Url: </label> <input name="url" required type="url" value={details.url} readOnly/> <br/> <label htmlFor="title">Titre: </label> <input name="title" required type="text" value={this.state.title} onChange={(value) => this.onChange(value)} /> <br/> <label htmlFor="description">Description: </label> <textarea name="description" required type="text" rows="10" value={this.state.description} onChange={(value) => this.onChange(value)} /> <br/> <button>Modifier cette video</button> </fieldset> </form> ) } } export default UpdateVideoForm;
angular .module('app.service.weatherApi', []) .service('weatherApi', ['$http', weatherApi]); function weatherApi($http) { // We could use some caching here (localStorage, for example) because there // is no point in refetching the data from external API multiple times in // a small time period. // We could also publish an event when an external request is made so that // other components could subscribe and show a loading indicator if desired. // The app id should be configured in app.js or perhaps a dedicated // config file and injected through angular.value, for example. var appId = 'd6a5a71867647fd3062b104541bfb68f'; var listCurrentForCitiesUrl = 'http://api.openweathermap.org/data/2.5/group'; listCurrentForCitiesUrl += '?appid=' + appId; var getForecastForCityLimit = 5; var getForecastForCityUrl = 'http://api.openweathermap.org/data/2.5/forecast'; getForecastForCityUrl += '?appid=' + appId; getForecastForCityUrl += '&cnt=' + getForecastForCityLimit; var iconUrl = 'http://openweathermap.org/img/w/'; // A sample map to map requested city name to open weather data city id. // We wouldn't normally keep such a map at the client side as it would get // huge considering the amount of cities in the world. var cityToIdMap = { Amsterdam: 2759794, Tallinn: 588409, Paris: 2968815, Berlin: 2950159, Helsinki: 658224 }; var service = {}; service.listCurrentForCities = function(cities) { var ids = cities .map(function(city) { return cityToIdMap[city]; }) .join(','); var fullUrl = listCurrentForCitiesUrl + '&id=' + ids; return $http.get(fullUrl).then(function(response) { var models = response.data.list; return models.map(function(model) { return openWeatherModelToAppModel(model); }) }); } service.listForecastForCity = function(city) { var id = cityToIdMap[city]; var fullUrl = getForecastForCityUrl + '&id=' + id; return $http.get(fullUrl).then(function(response) { var models = response.data.list; return models.map(function(model) { return openWeatherModelToAppModel(model); }) }); } function openWeatherModelToAppModel(model) { // Open Weather Map weather model. // Ref: http://openweathermap.org/current // Our app's weather model. // { // name: string; // temperature: number; // kelvin // wind: { // speed: number; // m/sec // direction: number; // degrees from N // }; // iconUrl: string; // date: Date; // } return { name: model.name, temperature: model.main.temp, wind: { speed: model.wind.speed, direction: model.wind.deg }, iconUrl: iconUrl + model.weather[0].icon + '.png', date: new Date(model.dt * 1000) // model.dt is a UNIX timestamp. }; } return service; }
var searchData= [ ['ease',['Ease',['../class_otter_1_1_glide.html#ae8fad59d22180968a7bbd0aab0175e2a',1,'Otter::Glide']]], ['end',['End',['../class_otter_1_1_scene.html#add2ad394bce2fb516b48cb047ae025df',1,'Otter::Scene']]], ['enter',['Enter',['../class_otter_1_1_state.html#abfe4fa10173b958802239606637062d0',1,'Otter::State']]], ['entity',['Entity',['../class_otter_1_1_entity.html#a85c8380d6084204a8942ebd3a27483ef',1,'Otter::Entity']]], ['enumtointarray',['EnumToIntArray',['../class_otter_1_1_util.html#a53aa68453af8a11ea17c921da38f797b',1,'Otter::Util']]], ['enumvalues_3c_20t_20_3e',['EnumValues&lt; T &gt;',['../class_otter_1_1_util.html#a42f9dc792cf44629234af7dd713a1373',1,'Otter::Util']]], ['enumvaluetostring',['EnumValueToString',['../class_otter_1_1_util.html#afdda2a5f3d0f218c943b957a6215bd7e',1,'Otter::Util']]], ['exists',['Exists',['../class_otter_1_1_atlas.html#a6ff346e0abe83f59c4517156edb555e0',1,'Otter.Atlas.Exists()'],['../class_otter_1_1_textures.html#a9b1700a49ef5e843c74409dcbe2b9da6',1,'Otter.Textures.Exists()']]], ['exit',['Exit',['../class_otter_1_1_state.html#a737a87f38bd185a4657209a6f87ccca7',1,'Otter::State']]] ];
const mongoose = require("mongoose"); const productSchema = new mongoose.Schema({ title: {type: String, required: true}, description: {type: String, required: true}, creator: {type: String, required: true}, price: {type: Number, required: true}, tags: [String], selectedFile: String , likeCount: { type: Number, default: 0 }, createdAt: { type: Date, default: new Date() } }); module.exports = mongoose.model("Product", productSchema);
define(['jqueryUI','dataTables'], function(){ wgn.console('customers module loaded','f'); wgn.optout = wgn.optout || {}; wgn.customers = wgn.customers || {}; wgn.customers.selectedRow = false; wgn.customers.parameters = wgn.customers.parameters || {}; wgn.customers.editMode = ""; wgn.customers.editSubject = ""; wgn.customers.editPredicate = ""; wgn.customers.caModal = wgn.customers.caModal || {}; wgn.programs = wgn.programs || {}; wgn.programs.selectedRow = false; wgn.programs.parameters = wgn.programs.parameters || {}; wgn.programs.editMode = ""; wgn.programs.editSubject = ""; wgn.programs.editPredicate = ""; wgn.programs.pModal = wgn.programs.pModal || {}; //Initialize callbacks wgn.customers.customerListFn = wgn.customers.customerListFn || {}; wgn.customers.customerListFn.callback = wgn.customers.customerListFn.callback || {}; wgn.customers.deleteRowFn = wgn.customers.deleteRowFn || {}; wgn.customers.deleteRowFn.callback = wgn.customers.deleteRowFn.callback || {}; wgn.programs.programListFn = wgn.programs.programListFn || {}; wgn.programs.programListFn.callback = wgn.programs.programListFn.callback || {}; wgn.programs.deleteRowFn = wgn.programs.deleteRowFn || {}; wgn.programs.deleteRowFn.callback = wgn.programs.deleteRowFn.callback || {}; wgn.dtCustomerRowsHandler = function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ $(nRow).click(function(){ wgn.tableSelector = '#' + $(this)[0].parentNode.parentNode.id; $('#program_table').dataTable().fnClearTable(); if ($(this).hasClass('selected')){ $(this).removeClass('selected'); $('#editAccountModal, #deleteAccountRow').addClass('disabled'); $('div.programActions').removeClass('active'); wgn.customers.selectedRow = false; $('#enrollment_table').addClass('noRows'); } else{ $(wgn.tableSelector + ' tr').removeClass('selected'); $(this).addClass('selected'); $('#editAccountModal, #deleteAccountRow').removeClass('disabled'); $('div.programActions').addClass('active'); wgn.customers.selectedRow = true; wgn.customers.selectedData = aData; programList(wgn.customers.selectedData.id); $('#enroll_table_title').text(messages_arr.customeradmin.enrollment_title.replace("{0}",wgn.customers.selectedData.name)); $('#enrollment_table').removeClass('noRows'); } }); }; wgn.dtProgramRowsHandler = function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ $(nRow).click(function(event){ wgn.tableSelector = '#' + $(this)[0].parentNode.parentNode.id; if (event.target.type == "checkbox"){ wgn.programs.selectedData = aData; var updateId = wgn.programs.selectedData.id; delete wgn.programs.selectedData.id; wgn.programs.selectedData.contractActive = $(this).find('input')[0].checked; $.ajax({ url: wgn.routes.controllers.Enrollment.updateCustomerProgram(updateId).url, contentType: 'application/json', dataType: 'json', data: JSON.stringify(wgn.programs.selectedData), type: wgn.routes.controllers.Enrollment.updateCustomerProgram().method, cache: false }) .done(function(data){ programList(wgn.customers.selectedData.id); }); } else{ if ($(this).hasClass('selected')){ $(this).removeClass('selected'); $('#editProgramModal').addClass('disabled'); $('#deleteProgramAssociation').addClass('disabled'); wgn.programs.selectedRow = false; } else{ $(wgn.tableSelector + ' tr').removeClass('selected'); $(this).addClass('selected'); $('#editProgramModal').removeClass('disabled'); $('#deleteProgramAssociation').removeClass('disabled'); wgn.programs.selectedRow = true; wgn.programs.selectedData = aData; } } }); }; function customerList(){ $.ajax({ url: wgn.routes.controllers.Customer.listCustomers().url, contentType: 'application/json', dataType: 'json', type: wgn.routes.controllers.Customer.listCustomers().method, cache: false }) .done(function(data){ wgn.customers.list = data; $('#customer_table').dataTable().fnClearTable(); $('#customer_table').dataTable().fnAddData(wgn.customers.list.vertexAccounts); $('#program_table').dataTable().fnClearTable(); wgn.console("customer list loaded","f"); }) .complete(function(){ if (typeof(wgn.customers.customerListFn.callback) == "function"){ wgn.customers.customerListFn.callback(); wgn.console("callback from customerListFn() executed: " + wgn.customers.customerListFn.callback.name + "()","f"); wgn.customers.customerListFn.callback = {}; } }); } function programList(customerId){ $.ajax({ url: wgn.routes.controllers.Enrollment.listForCustomer(customerId).url, contentType: 'application/json', dataType: 'json', type: wgn.routes.controllers.Enrollment.listForCustomer().method, cache: false }) .done(function(data){ wgn.programs.list = data; $('#program_table').dataTable().fnClearTable(); $('#program_table').dataTable().fnAddData(wgn.programs.list); wgn.console("program list loaded","f"); }) .fail(function(data){ var errorMessage = ""; var lineBreak = ""; wgn.programs.errors = $.parseJSON(data.responseText); for (i in wgn.programs.errors.globalErrors){ errorMessage = errorMessage + lineBreak + wgn.programs.errors.globalErrors[i]; lineBreak = "<br/>"; } $('.alert-failure span').html(errorMessage); $('.alert-failure').removeClass('fade'); }) .complete(function(){ if (typeof(wgn.programs.programListFn.callback) == "function"){ wgn.programs.programListFn.callback(); wgn.console("callback from programListFn() executed: " + wgn.programs.programListFn.callback.name + "()","f"); wgn.programs.programListFn.callback = {}; } $.ajax({ url: wgn.routes.controllers.DrProgram.listDrProgram().url, contentType: 'application/json', dataType: 'json', type: wgn.routes.controllers.DrProgram.listDrProgram().method, cache: false }) .done(function(data){ wgn.programs.programList = data; for (i in wgn.programs.programList.drPrograms){ $('#program_table tr td').each(function(){ if ($(this).text() == wgn.programs.programList.drPrograms[i].marketContext){ $(this).text(wgn.programs.programList.drPrograms[i].programName); } }) } }); }); } function timestamp(timeslot,day){ $('#' + day + '_schedule .' + day + '_optin').removeClass('invalid'); // validate and adjust the time and duration from the dom view var posLeft = $(timeslot).position().left - 0; if (posLeft == 0){ posLeft = $(timeslot).css("left").replace("px","") - 0; } if (posLeft == -1){ posLeft = 0; $(timeslot).css({"left":"0px"}); } var timeduration = $(timeslot).width() - 0; var posRight = posLeft + timeduration; if (posRight > 480){ posLeft = 475 - timeduration; posLeftPx = posLeft + "px"; $(timeslot).css({"left":posLeftPx}); posRight = posLeft + timeduration; } validateSchedule(day); var timestart = posLeft / 480 * 24; var timestartH = Math.floor(timestart); var timestartM = Math.floor((timestart - timestartH) * 60); var timestartM = Math.floor(timestartM / 15) * 15; var timedurationDur = timestartH * 60 + timestartM; if (timestartH < 10){ timestartH = "0" + timestartH; } if (timestartM < 10){timestartM = "0" + timestartM}; var timestartF = "T" + timestartH + ":" + timestartM; var timestop = (posLeft - 0 + timeduration) / 480 * 24; var timestopH = Math.floor(timestop); var timestopM = Math.floor((timestop - timestopH) * 60); var timestopM = Math.floor(timestopM / 15) * 15; timedurationDur = (timestopH * 60 + timestopM) - timedurationDur; if (timestopH < 10){ timestopH = "0" + timestopH; } if (timestopM < 10){timestopM = "0" + timestopM}; var timestopF = "T" + timestopH + ":" + timestopM; var timedurationH = Math.floor(timedurationDur / 60); var timedurationM = timedurationDur - (timedurationH * 60); var timedurationF = "PT" + timedurationH + "H" + timedurationM + "M"; timetip = timestartF.replace("T","") + " - " + timestopF.replace("T",""); $(timeslot).attr("title",timetip); $(timeslot).tooltip({content: timetip}); $(timeslot).attr("data-start_time",timestartF); $(timeslot).attr("data-stop_time",timestopF); $(timeslot).attr("data-duration",timedurationF); $(timeslot).removeClass('ignoreDom'); } function validateSchedule(day){ var isValidSchedule = true; $('#' + day + '_schedule .' + day + '_optin').each(function(){ $(this).addClass('ignoreDom'); var selfLeft = $(this).css("left").replace("px","") - 0; var selfDuration = $(this).width() - 0; var selfRight = selfLeft + selfDuration; $('#' + day + '_schedule .' + day + '_optin').each(function(){ if ($(this).hasClass('ignoreDom')){ // self-reference } else{ // found a sibling var siblingLeft = $(this).css("left").replace("px","") - 0; var siblingDuration = $(this).width() - 0; var siblingRight = siblingLeft + siblingDuration; switch (true){ case (selfLeft > siblingLeft && selfLeft < siblingRight): $(this).addClass('invalid'); isValidSchedule = false; break; case (selfRight > siblingLeft && selfRight < siblingRight): $(this).addClass('invalid'); isValidSchedule = false; break; case (selfLeft < siblingLeft && selfRight > siblingRight): $(this).addClass('invalid'); isValidSchedule = false; break; default: break; } } }) $(this).removeClass('ignoreDom'); }); if (isValidSchedule){ $('#' + day + '_schedule').removeClass('invalid'); } else{ $('#' + day + '_schedule').addClass('invalid'); } } function weekday(timeslot){ timeslot .tooltip({position:{my: "center bottom-7"}, track:true, tooltipClass: "schedule_tooltip"}) .draggable({containment: $(".weekday_container"), revert: "invalid", stop: function(event,ui){ //wgn.console('Weekday dragndrop stopped ==>','f'); wgn.debug.scheduleWidget = ui; if ($(this).hasClass("appended")){ if (ui.position.top < -30){ $(this).remove(); $('#weekday_schedule .weekday_optin').removeClass('invalid'); validateSchedule('weekday'); } else{ $(this).css("top","0px"); timestamp(this,'weekday'); } } else{ var tempLeft = ($(this).css("left").replace("px","") - 0); if (tempLeft < 0){ var styleLeft = ($(this).css("left").replace("px","") - 0 + 486 + "px"); $(this).appendTo("#weekday_schedule"); $(this).addClass("appended"); $(this).css("left", styleLeft); $(this).css("top","0px"); $(this).css({"position":"absolute"}); $(this).resizable( {stop: function(event, ui){ $(this).css({"top":"0px"}); timestamp(this,'weekday'); }}, {minHeight: 28}, {maxHeight: 28} ); var optOutTemp = wgn.optout.weekday.clone(); optOutTemp.appendTo(".weekday_parent"); timestamp(this,'weekday'); // set time data-attributes weekday(optOutTemp); } } } }); } function weekend(timeslot){ timeslot .tooltip({position:{my: "center bottom-7"}, track:true, tooltipClass: "schedule_tooltip"}) .draggable({containment: $(".weekend_container"), revert: "invalid", stop: function(event,ui){ //wgn.console('Weekend dragndrop stopped ==>','f'); if ($(this).hasClass("appended")){ if (ui.position.top < -30){ $(this).remove(); $('#weekend_schedule .weekend_optin').removeClass('invalid'); validateSchedule('weekend'); } else{ $(this).css("top","0px"); timestamp(this,'weekend'); } } else{ var tempLeft = ($(this).css("left").replace("px","") - 0); if (tempLeft < 0){ var styleLeft = ($(this).css("left").replace("px","") - 0 + 486 + "px"); $(this).appendTo("#weekend_schedule"); $(this).addClass("appended"); $(this).css("left", styleLeft); $(this).css("top", "0px"); $(this).css({"position":"absolute"}); $(this).resizable( {stop: function(event, ui){ $(this).css({"top":"0px"}); timestamp(this,'weekend'); }}, {minHeight: 28}, {maxHeight: 28} ); var optOutTemp = wgn.optout.weekend.clone(); optOutTemp.appendTo(".weekend_parent"); timestamp(this,'weekend'); // set time data-attributes weekend(optOutTemp); } } } }); } function getCas(){ $.ajax({ // get current _cas url: wgn.routes.controllers.Customer.getCustomer(wgn.customers.selectedData["id"]).url, type: wgn.routes.controllers.Customer.getCustomer().method, cache: false }) .done(function(data){ wgn.customers.parameters._cas = data["_cas"]; }) } // dataTable rendering $(document).ready(function(){ // Default header class modification // Use $.fn.dataTableExt.oStdClasses when bjQueryUI is false $.extend($.fn.dataTableExt.oJUIClasses, { "sSortAsc": "header headerSortDown", "sSortDesc": "header headerSortUp", "sSortable": "header" }); var dateLang = (wgn.browserLang == "en") ? "" : wgn.browserLang; // default english value is empty string "" $.datepicker.setDefaults($.datepicker.regional[dateLang]); $.datepicker.setDefaults({ dateFormat: 'yy-mm-dd' }); // Programs list initialization $('#program_table').dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers", "sDom": '<""l>t<"F"fp>', "oLanguage": { "sUrl": wgn.assetsRoot + "/assets/javascripts/lang/jquery.dataTables." + wgn.browserLang + ".json" }, "aoColumns": [ {"mData": "program"}, {"mData": "contractStart"}, {"mData": "contractEnd"}, {"mData": "contractActive"} ], "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ $('td:eq(0)',nRow).addClass('alignLeft'); var activeTemp = aData['contractActive']; if (!!activeTemp){ var activeCb = "<input type='checkbox' checked>"; } else{ var activeCb = "<input type='checkbox'>"; } $('td:eq(3)',nRow).addClass('alignCenter'); $('td:eq(3)',nRow).html(activeCb); wgn.dtProgramRowsHandler(nRow, aData, iDisplayIndex, iDisplayIndexFull); }, "fnDrawCallback": function(oSettings){ //wgn.console('program table has been redrawn'); } }); // Customer table initialization $('#customer_table').dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers", "sDom": '<""l>t<"F"fp>', "oLanguage": { "sUrl": wgn.assetsRoot + "/assets/javascripts/lang/jquery.dataTables." + wgn.browserLang + ".json" }, "aoColumns": [ {"mData": "name"}, {"mData": "location"}, {"mData": "telephoneNumber"}, {"mData": "scalarBaseline"}, {"mData": "loadshedCapacity"} ], "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ $('td:eq(0)',nRow).addClass('alignLeft'); $('td:eq(1)',nRow).addClass('alignLeft'); wgn.dtCustomerRowsHandler(nRow, aData, iDisplayIndex, iDisplayIndexFull); }, "fnDrawCallback": function(oSettings){ //wgn.console('customer table has been redrawn'); }, "fnInitComplete": function(oSettings, json){ customerList(); } }); wgn.optout.weekday = $(".weekday_optin").clone(); weekday($(".weekday_optin")); wgn.optout.weekend = $(".weekend_optin").clone(); weekend($(".weekend_optin")); $(".scheduler").droppable(); $('button.alertClose.close').on('click', function(){ $(this).parent().addClass("fade"); }); $('#caModal').on('hidden.bs.modal', function(){ $('.schedule_icon').tooltip('close'); }); $('#caModal').css('max-height',wgn.modalAvailHeight); $('#caModal .modal-body').css('max-height',wgn.modalContentAvailHeight); $('#pModal').css('max-height',wgn.modalAvailHeight); $('#pModal .modal-body').css('max-height',wgn.modalContentAvailHeight); $('#contract_start').datepicker(); $('#contract_end').datepicker(); }); // show account add modal $('#addAccountModal').on('click',function(){ $('#customer_table tr').removeClass('selected'); $('#editAccountModal, #deleteAccountRow').addClass('disabled'); wgn.customers.selectedRow = false; $('#enrollment_table').addClass('noRows'); wgn.customers.caModal.header_text = wgn.messages_arr.customeradmin.add_title; $('#caModal .modal-title').text(wgn.customers.caModal.header_text); $("#caModal input, #caModal div").removeClass('invalid'); $('#caModal [data-key="name"]').val(''); $('#caModal [data-key="phoneticName"]').val(''); $('#caModal [data-key="location"]').val(''); $('#caModal [data-key="phoneticLocation"]').val(''); $('#caModal [data-key="telephoneNumber"]').val(''); $('#caModal [data-key="scalarBaseline"]').val(''); $('#caModal [data-key="loadshedCapacity"]').val(''); $('#caModal #weekday_schedule').empty(); $('#caModal #weekend_schedule').empty(); delete wgn.customers.parameters._cas; wgn.customers.editMode = "add"; wgn.customers.editPredicate = messages_arr.customeradmin.edit_message.add; wgn.customers.submitUrl = wgn.routes.controllers.Customer.addCustomer().url; wgn.customers.submitType = wgn.routes.controllers.Customer.addCustomer().method; $('#caModal').modal('show'); }); // show edit account modal $('#editAccountModal').on('click',function(){ if (wgn.customers.selectedRow){ wgn.customers.caModal.header_text = wgn.messages_arr.customeradmin.edit_title; $('#caModal .modal-title').text(wgn.customers.caModal.header_text); $("#caModal input, #caModal div").removeClass('invalid'); $('#caModal [data-key="name"]').val(wgn.customers.selectedData["name"]); $('#caModal [data-key="phoneticName"]').val(wgn.customers.selectedData["phoneticName"]); $('#caModal [data-key="location"]').val(wgn.customers.selectedData["location"]); $('#caModal [data-key="phoneticLocation"]').val(wgn.customers.selectedData["phoneticLocation"]); $('#caModal [data-key="telephoneNumber"]').val(wgn.customers.selectedData["telephoneNumber"]); $('#caModal [data-key="scalarBaseline"]').val(wgn.customers.selectedData["scalarBaseline"]); $('#caModal [data-key="loadshedCapacity"]').val(wgn.customers.selectedData["loadshedCapacity"]); $('#caModal #weekday_schedule').empty(); $('#caModal #weekend_schedule').empty(); for (x in wgn.customers.selectedData["weekdaySchedules"]){ if (wgn.customers.selectedData["weekdaySchedules"][x]["opt"] == "optOut"){ var startTime = wgn.customers.selectedData["weekdaySchedules"][x]["startTime"]; startTime = startTime.replace("T",""); var startTimeArr = startTime.split(":"); var styleLeft = Math.floor(((startTimeArr[0] - 0) * 60 + (startTimeArr[1] - 0)) / (24 * 60) * 480) + "px"; var optDuration = wgn.customers.selectedData["weekdaySchedules"][x]["duration"]; optDuration = optDuration.replace("PT",""); var optDurationArr = optDuration.split("H"); var styleWidth = Math.floor(((optDurationArr[0] - 0) * 60 + (optDurationArr[1].replace("M","") - 0)) / (24 * 60) * 480) + "px"; var tempOptout = wgn.optout.weekday.clone(); tempOptout.css({"position":"absolute", "left":styleLeft, "width":styleWidth}); tempOptout.appendTo("#caModal #weekday_schedule"); tempOptout.addClass("appended"); $(tempOptout).resizable( {stop: function(event, ui){ $(this).css({"top":"0px"}); timestamp(this,'weekday'); }}, {minHeight: 28}, {maxHeight: 28} ); timestamp(tempOptout,'weekday'); weekday(tempOptout); } } for (x in wgn.customers.selectedData["weekendSchedules"]){ if (wgn.customers.selectedData["weekendSchedules"][x]["opt"] == "optOut"){ var startTime = wgn.customers.selectedData["weekendSchedules"][x]["startTime"]; startTime = startTime.replace("T",""); var startTimeArr = startTime.split(":"); var styleLeft = Math.floor(((startTimeArr[0] - 0) * 60 + (startTimeArr[1] - 0)) / (24 * 60) * 480) + "px"; var optDuration = wgn.customers.selectedData["weekendSchedules"][x]["duration"]; optDuration = optDuration.replace("PT",""); var optDurationArr = optDuration.split("H"); var styleWidth = Math.floor(((optDurationArr[0] - 0) * 60 + (optDurationArr[1].replace("M","") - 0)) / (24 * 60) * 480) + "px"; var tempOptout = wgn.optout.weekend.clone(); tempOptout.css({"position":"absolute", "left":styleLeft, "width":styleWidth}); tempOptout.appendTo("#caModal #weekend_schedule"); tempOptout.addClass("appended"); $(tempOptout).resizable( {stop: function(event, ui){ var styleLeft = ($(this).css("left").replace("px","") - 25 + "px"); $(this).css({"top":"0px"}); timestamp(this,'weekend'); }}, {minHeight: 28}, {maxHeight: 28} ); timestamp(tempOptout,'weekend'); weekend(tempOptout); } } getCas(); wgn.customers.editMode = "edit"; wgn.customers.editPredicate = messages_arr.customeradmin.edit_message.edit; wgn.customers.submitUrl = wgn.routes.controllers.Customer.updateCustomer(wgn.customers.selectedData["id"]).url; wgn.customers.submitType = wgn.routes.controllers.Customer.updateCustomer().method; $('#caModal').modal('show'); } }); // delete a customer row $('#deleteAccountRow').on('click',function(){ if (wgn.customers.selectedRow){ wgn.customers.editMode = "delete"; wgn.customers.editSubject = wgn.customers.selectedData["name"]; wgn.customers.editPredicate = messages_arr.customeradmin.edit_message.delete; wgn.customers.errorPredicate = messages_arr.customeradmin.delete_error; wgn.customers.submitUrl = wgn.routes.controllers.Customer.deleteCustomer(wgn.customers.selectedData["id"]).url; wgn.customers.submitType = wgn.routes.controllers.Customer.deleteCustomer().method; $.ajax({ url: wgn.customers.submitUrl, type: wgn.customers.submitType, cache: false, beforeSend: function(){ wgn.console('customer delete requested','f'); } }) .done(function(){ wgn.console('customer delete successful','f'); var successMessage = wgn.customers.editSubject + " " + wgn.customers.editPredicate; $('.alert-success span.successMessage').text(successMessage); $('.alert-success').removeClass('fade'); $('tr').removeClass('selected'); $('#editAccountModal, #deleteAccountRow').addClass('disabled'); wgn.customers.selectedRow = false; $('#enrollment_table').addClass('noRows'); customerList(); }) .fail(function(){ var errorMessage = wgn.customers.errorPredicate + " " + wgn.customers.editSubject; $('.alert-failure span b').text(errorMessage); $('.alert-failure').removeClass('fade'); }) .complete(function(data){ if (typeof(wgn.customers.deleteRowFn.callback) == "function"){ wgn.customers.deleteRowFn.callback(); wgn.console("callback from deleteRow() executed: " + wgn.customers.deleteRowFn.callback.name + "()","f"); wgn.customers.deleteRowFn.callback = {}; } }); return; } }) // customer form post add and edit $('#customerModalSubmit').on('click',function(){ $('#caModal .modal-title').text(wgn.customers.caModal.header_text); $("#caModal input, #caModal div:not(.schedule_icon, #weekday_schedule, #weekend_schedule)").removeClass('invalid'); var invalidFields = 0; var modalErrorMsg = ""; var lineBreak = ""; wgn.console('customer form submit request','f'); wgn.customers.parameters.name = $('#caModal [data-key="name"]').val(); if (wgn.customers.parameters.name == ""){ $('#caModal .name_marker').addClass("invalid"); invalidFields++; } wgn.customers.parameters.location = $('#caModal [data-key="location"]').val(); if (wgn.customers.parameters.location == ""){ $('#caModal .location_marker').addClass("invalid"); invalidFields++; } if ($('#caModal #weekday_schedule').hasClass('invalid')){ invalidFields++; } if ($('#caModal #weekend_schedule').hasClass('invalid')){ invalidFields++; } switch (true){ case (invalidFields == 1): modalErrorMsg = modalErrorMsg + lineBreak + wgn.messages_arr.customeradmin.field_error; break; case (invalidFields > 1): modalErrorMsg = modalErrorMsg + lineBreak + wgn.messages_arr.customeradmin.field_errors; break; default: break; } if (modalErrorMsg != ""){ $('#caModal .modal-title').html(modalErrorMsg); return; } wgn.customers.parameters.phoneticName = $('#caModal [data-key="phoneticName"]').val(); wgn.customers.parameters.phoneticLocation = $('#caModal [data-key="phoneticLocation"]').val(); wgn.customers.parameters.telephoneNumber = $('#caModal [data-key="telephoneNumber"]').val(); wgn.customers.parameters.scalarBaseline = $('#caModal [data-key="scalarBaseline"]').val(); wgn.customers.parameters.loadshedCapacity = $('#caModal [data-key="loadshedCapacity"]').val(); wgn.customers.parameters.weekdaySchedules = []; $("#weekday_schedule .weekday_optin").each(function(){ var weekday = {}; weekday.optout = {}; weekday.optout.startTime = $(this).attr('data-start_time'); weekday.optout.duration = $(this).attr('data-duration'); weekday.optout.opt = "optOut"; wgn.customers.parameters.weekdaySchedules.push(weekday.optout); }) wgn.customers.parameters.weekendSchedules = []; $("#weekend_schedule .weekend_optin").each(function(){ var weekend = {}; weekend.optout = {}; weekend.optout.startTime = $(this).attr('data-start_time'); weekend.optout.duration = $(this).attr('data-duration'); weekend.optout.opt = "optOut"; wgn.customers.parameters.weekendSchedules.push(weekend.optout); }) $.ajax({ url: wgn.customers.submitUrl, contentType: "application/json", dataType: 'json', data: JSON.stringify(wgn.customers.parameters), type: wgn.customers.submitType, cache: false }) .done(function(data){ $('#caModal').modal('hide'); customerList(); wgn.customers.editSubject = wgn.customers.parameters.name; var successMessage = wgn.customers.editSubject + " " + wgn.customers.editPredicate; $('.alert-success span.successMessage').text(successMessage); $('.alert-success').removeClass('fade'); $('#editAccountModal, #deleteAccountRow').addClass('disabled'); wgn.customers.selectedRow = false; $('#enrollment_table').addClass('noRows'); }) .fail(function(data){ wgn.customers.errors = $.parseJSON(data.responseText); for (i in wgn.customers.errors.fieldErrors){ //field error object iteration switch(true){ case (i == "weekday_schedules"): $("#weekday_schedule").addClass("invalid"); invalidFields++; break; case (i == "weekend_schedules"): $("#weekend_schedule").addClass("invalid"); invalidFields++; break; case ($('.' + i + '_marker').length == 1): $('.' + i + '_marker').addClass("invalid"); invalidFields++; break; case ($('#' + i).length == 1): $('#' + i).addClass("invalid"); invalidFields++; break; default: // no field to mark break; } } for (j in wgn.customers.errors.globalErrors){ //global error array iteration modalErrorMsg = modalErrorMsg + lineBreak + wgn.customers.errors.globalErrors[j]; lineBreak = "<br/>"; } switch(true){ case (invalidFields == 1): modalErrorMsg = modalErrorMsg + lineBreak + wgn.messages_arr.customeradmin.field_error; lineBreak = "<br/>"; break; case (invalidFields > 1): modalErrorMsg = modalErrorMsg + lineBreak + wgn.messages_arr.customeradmin.field_errors; lineBreak = "<br/>"; break; default: break; } if (modalErrorMsg != ""){ $('#caModal .modal-title').html(modalErrorMsg); } }); }); $('#addProgramModal').on('click',function(){ wgn.programs.pModal.header_text = messages_arr.customeradmin.newContract_title.replace("{0}",wgn.customers.selectedData["name"]); $('#pModal .modal-title').text(wgn.programs.pModal.header_text); $("#pModal input, #pModal div").removeClass('invalid'); $('#pModal [data-key="customerId"]').val(wgn.customers.selectedData.id); $('#pModal [data-key="contractStart"]').val(''); $('#pModal [data-key="contractEnd"]').val(''); wgn.programs.editMode = "add"; wgn.programs.editPredicate = messages_arr.customeradmin.alert_new_contract_success.replace("{0}",wgn.customers.selectedData["name"]); wgn.programs.submitUrl = wgn.routes.controllers.Enrollment.addCustomerProgram().url; wgn.programs.submitType = wgn.routes.controllers.Enrollment.addCustomerProgram().method; $('#pModal').modal('show'); $.ajax({ url: wgn.routes.controllers.DrProgram.listDrProgram().url, contentType: 'application/json', dataType: 'json', type: wgn.routes.controllers.DrProgram.listDrProgram().method, cache: false }) .done(function(data){ wgn.debug.programList = data; $('#pModal [data-key="availablePrograms"]').empty(); for (i in wgn.debug.programList.drPrograms){ var tempOption = $("<option></option>"); $(tempOption).val(wgn.debug.programList.drPrograms[i].marketContext); $(tempOption).html(wgn.debug.programList.drPrograms[i].programName); $('#pModal [data-key="availablePrograms"]').append(tempOption); } }); }); $('#editProgramModal').on('click',function(){ var pModalMessage = messages_arr.customeradmin.editContract_title.replace("{0}",wgn.customers.selectedData["name"]); $('#pModal .modal-title').text(pModalMessage); $('#pModal [data-key="contractStart"]').val(wgn.programs.selectedData["contractStart"]); $('#pModal [data-key="contractEnd"]').val(wgn.programs.selectedData["contractEnd"]); $('#pModal [data-key="customerId"]').val(wgn.customers.selectedData.id); $('#pModal').modal('show'); $.ajax({ url: wgn.routes.controllers.DrProgram.listDrProgram().url, contentType: 'application/json', dataType: 'json', type: wgn.routes.controllers.DrProgram.listDrProgram().method, cache: false }) .done(function(data){ wgn.debug.programList = data; $('#availablePrograms').empty(); for (i in wgn.debug.programList.drPrograms){ var tempOption = $("<option></option>"); $(tempOption).val(wgn.debug.programList.drPrograms[i].marketContext); $(tempOption).html(wgn.debug.programList.drPrograms[i].programName); $('#availablePrograms').append(tempOption); } }) .complete(function(){ $("#availablePrograms option[value=" + wgn.programs.selectedData["program"] + "]").prop('selected', true); }); wgn.programs.parameters._cas = wgn.programs.selectedData["_cas"]; wgn.programs.submitUrl = wgn.routes.controllers.Enrollment.updateCustomerProgram(wgn.programs.selectedData.id).url; wgn.programs.submitType = wgn.routes.controllers.Enrollment.updateCustomerProgram().method; wgn.programs.editMode = "edit"; wgn.programs.editPredicate = messages_arr.customeradmin.edit_message.edit; }); // delete a customer contract $('#deleteProgramAssociation').on('click', function(){ if (wgn.programs.selectedRow){ wgn.programs.editMode = "delete"; wgn.programs.deleteError = messages_arr.customeradmin.delete_error; wgn.programs.submitUrl = wgn.routes.controllers.Enrollment.deleteCustomerProgram(wgn.programs.selectedData["id"]).url; wgn.programs.submitType = wgn.routes.controllers.Enrollment.deleteCustomerProgram().method; $.ajax({ url: wgn.programs.submitUrl, type: wgn.programs.submitType, cache: false, beforeSend: function(){ wgn.console('enrollment contract delete requested', 'f'); } }) .done(function(data){ wgn.console('customer delete successful','f'); programList(wgn.customers.selectedData.id); wgn.debug.programList = data; $('#deleteProgramAssociation').addClass('disabled'); wgn.programs.selectedRow = false; $('#availablePrograms').empty(); for (i in wgn.debug.programList.drPrograms){ var tempOption = $("<option></option>"); $(tempOption).val(wgn.debug.programList.drPrograms[i].id); $(tempOption).html(wgn.debug.programList.drPrograms[i].programName); $('#availablePrograms').append(tempOption); } }) .fail(function(){ var errorMessage = messages_arr.customeradmin.enroll.delete_error; $('.alert-failure span b').text(errorMessage); $('.alert-failure').removeClass('fade'); }) .complete(function(data){ if (typeof(wgn.programs.deleteRowFn.callback) == "function"){ wgn.programs.deleteRowFn.callback(); wgn.console("callback from deleteRow() executed: " + wgn.programs.deleteRowFn.callback.name + "()","f"); wgn.programs.deleteRowFn.callback = {}; } }); return; } }); // program form post add and edit $('#programModalSubmit').on('click',function(){ $('#pModal .modal-title').text(wgn.programs.pModal.header_text); $("#pModal input, #pModal div").removeClass('invalid'); var invalidFields = 0; var modalErrorMsg = ""; var lineBreak = ""; wgn.console('program form submit request','f'); wgn.programs.parameters.account = $('#pModal [data-key="customerId"]').val(); wgn.programs.parameters.program = $('#pModal #availablePrograms')[0].value; wgn.programs.parameters.contractStart = $('#pModal [data-key="contractStart"]').val(); wgn.programs.parameters.contractEnd = $('#pModal [data-key="contractEnd"]').val(); wgn.programs.parameters.contractActive = true; if (!$('#contract_start')[0].validity.valid){ $('#contract_start').addClass("invalid"); } else if (!$('#contract_end')[0].validity.valid){ $('#contract_end').addClass("invalid"); } else{ $.ajax({ url: wgn.programs.submitUrl, contentType: "application/json", dataType: 'json', data: JSON.stringify(wgn.programs.parameters), type: wgn.programs.submitType, cache: false }) .done(function(data){ $('#pModal').modal('hide'); programList(wgn.customers.selectedData.id); var successMessage = wgn.programs.editPredicate.replace("{1}",$('#availablePrograms')[0].selectedOptions[0].text); $('.alert-success span.successMessage').text(successMessage); $('.alert-success').removeClass('fade'); $('#editProgramModal').addClass('disabled'); wgn.programs.selectedRow = false; }) .fail(function(data){ wgn.programs.errors = $.parseJSON(data.responseText); for (i in wgn.programs.errors.fieldErrors){ //field error object iteration switch(true){ case ($('.' + i + '_marker').length == 1): $('.' + i + '_marker').addClass("invalid"); invalidFields++; break; case ($('#' + i).length == 1): $('#' + i).addClass("invalid"); invalidFields++; break; default: // no field to mark break; } } for (j in wgn.programs.errors.globalErrors){ modalErrorMsg = modalErrorMsg + lineBreak + wgn.programs.errors.globalErrors[j]; lineBreak = "<br/>"; } switch(true){ case (invalidFields == 1): modalErrorMsg = modalErrorMsg + lineBreak + wgn.messages_arr.customeradmin.field_error; lineBreak = "<br/>" break; case (invalidFields > 1): modalErrormsg = modalErrormsg + lineBreak + wgn.messages_arr.customeradmin.field_errors; lineBreak = "<br/>"; break; default: break; } if (modalErrorMsg != ""){ $('#pModal .modal-title').html(modalErrorMsg); } }); return; } }); });
import React from "react"; import Button from "../Button"; import ProfileImg from "../ProfileImg"; import ImageJobPoints from "../../assets/images/JobPoints.svg"; import "./styles.css"; function Emprego(props) { const { urlEmpresaImg, tituloEmprego, jobPoints, tipo, cargaHoraria, funcao, local } = props; return ( <div id="container-emprego"> <div id="imagem-empresa-emprego"> <ProfileImg url={urlEmpresaImg} size="2" link="#" id="imagem-empresa-emprego-img" /> </div> <div id="titulo-emprego">{tituloEmprego}</div> <div id="job-points"> <img src={ImageJobPoints} alt="JobPoints" /> <label>{jobPoints}</label> </div> <ul id="infos-emprego"> <li>Tipo: {tipo}</li> <li>Carga Horária: {cargaHoraria}</li> <li>Função: {funcao}</li> <li>Local: {local}</li> </ul> <div id="button-detalhes"> <Button color="green" label="Mais detalhes" link="#" buttonCallback="" /> </div> </div> ); } export default Emprego;
// ==UserScript== // @name OGARio by szymy v4 || Deobfuscated // @namespace ogario.v4.b // @version 4.0.0.35 // @description Unoffical Polish MOD // @author szymy, ReF // @match *://agar.io/* // @run-at document-start // @grant GM_xmlhttpRequest // @connect cdn.ogario.ovh // ==/UserScript== if (location.host === "agar.io" && location.pathname === "/") { location.href = "https://agar.io/ogario" + location.hash; return; } function inject(page) { page = page.replace('<head>', '<head><script src="https://bundle.run/buffer@5.2.1"></script><script src="http://localhost:8082/vendor"></script>'); page = page.replace('https://cdn.ogario.ovh/v4/beta/ogario.v4.js', 'http://localhost:8082/js'); return page; } window.stop(); document.documentElement.innerHTML = ""; GM_xmlhttpRequest({ method : "GET", url : "https://cdn.ogario.ovh/v4/beta/", onload : function(e) { var doc = inject(e.responseText); document.open(); document.write(doc); document.close(); } });
const AWS = require('aws-sdk') // S3 instance for production DEFAULT module.exports.s3 = new AWS.S3() // S3 instance for production development module.exports.devS3 = new AWS.S3({s3ForcePathStyle: true, endpoint: new AWS.Endpoint('http://localhost:8000')})
foo == bar foo === bar foo = 2 + 2 bar = 3 + 2 foo = 3 * 2 bar = 3 ** 2 foo = 3 % 2
import React from 'react'; import Preloader from 'components/Preloader/Preloader'; import Photo from 'components/Photo.jsx'; function Photos() { return ( <div> <Preloader/> <Photo/> </div> ); } export default Photos
class Parser { constructor(lexer) { this.lexer = lexer; } parse() { return this.expr() } /* * Parser * * expr -> NUMBER ADD_OPERATOR NUMBER **/ expr() { let left_value = this.lexer.consume("NUMBER"); let operator = this.lexer.consume("ADD_OPERATOR"); let right_value = this.lexer.consume("NUMBER"); return { type: "BINARY_OPERATION", value: operator.value, left: { ...left_value, left: null, right: null }, right: { ...right_value, left: null, right: null } } } } module.exports = Parser
/** * Represent an error that is supposed to be exposed to the service consumer. Should not be instantiated directly, extend it and throw the more specific subclasses * @class PublicError * * @extends {Error} */ class PublicError extends Error { constructor(status, type, message) { super(message); this.type = type; this.statusCode = status; } } module.exports = PublicError;
import React, {View, Text, TouchableOpacity} from 'react-native'; import Routes from '../Routes'; import DataFetcher from '../shit/DataFetcher'; const Menu = React.createClass({ render: function() { return ( <View style={styles.container}> <TouchableOpacity onPress={() => {}}> <Text style={styles.item}> View Orders </Text> </TouchableOpacity> <TouchableOpacity onPress={() => { DataFetcher.isOpen = false; this.props.navigator.resetTo(Routes[4]); }}> <Text style={styles.item}> Sign Out </Text> </TouchableOpacity> </View> ); } }); const styles = { container: { backgroundColor: '#3B2164', flexDirection: 'column', justifyContent: 'flex-start', flex: 1, paddingTop: 40, width: 280, height: 1000 }, item: { textAlign: 'left', color: '#FFFFFF', fontSize: 28, fontWeight: '100', marginTop: 10, paddingTop: 10, paddingBottom: 20, paddingLeft: 20, height: 50, backgroundColor: '#25143F', }, }; export default Menu;
'use strict'; var _ = require('lodash'); var ExactaBetCalc = require('./exacta-bet-calc'); var PlaceBetCalc = require('./place-bet-calc'); var WinBetCalc = require('./win-bet-calc'); var Promise = require('bluebird'); /** * This method calculates dividends for each type of bets and returns an object denoting * the dividend values. * * If successful, it returns an object with key as bet type and value as dividend * * @param {Race} race - An object of concluded race * @param {function} cb - A callback function */ function calculateDividend(race, cb) { if(typeof race === 'function') { cb = race; race = null; } if(!race || !race.concluded) { return cb(new Error('Concluded race is mandatory for calculating dividends')); } var betTypes = _.keys(race.commissions); var dividends = {}; Promise.each(betTypes, (betType) => { return Promise.promisify(race.betsOfType, {context: race})(betType) .then((bets) => { switch(betType) { case 'W': return Promise.promisify(WinBetCalc.calculateDividend)(race.result, bets, race.commissions[betType]); case 'P': return Promise.promisify(PlaceBetCalc.calculateDividend)(race.result, bets, race.commissions[betType]); case 'E': return Promise.promisify(ExactaBetCalc.calculateDividend)(race.result, bets, race.commissions[betType]); } }).then((dividend) => { dividends[betType] = dividend; }); }).then(() => { cb(null, dividends); }).catch((e) => { cb(e); }); } module.exports.calculateDividend = calculateDividend;