text
stringlengths
7
3.69M
/*** * Copyrights * Project: MDL * Author: Thilina Herath * Module: photo controller */ 'use strict'; var controllerName = 'mdl.mobileweb.controller.photo' angular.module('newApp').controller(controllerName,[ '$rootScope', '$scope', function($rootScope, $scope) { $rootScope.loginactive = false; var vm = this; $scope.picture = false; } ]);
angular.module("MainApp").controller('ChargeCategory', ['$scope','$http','$location','$state', function ($scope, $http, $location,$state) { // SAVE PAYMENT $scope.saveChargeCategory = function (formData) { $http.post('/chargeCategory', formData) .success(function (data, status, headers, config) { $state.reload(); }); }; // UPDATE REFERRAL $scope.updateChargeCategory = function (formData) { $http.put('/chargeCategory', formData) .success(function (data, status, headers, config) { $state.reload(); }); }; //INITIALIZE DATAS $scope.mScope = {} ; $scope.mScope.features = $scope.features; $http.get('/chargeCategory') .success(function (data, status, headers, config) { $scope.chargeCategory = data; }); }])
/***** 项目配置管理参数项JS操作 lastDate 2013-07-24 by zhengYunFei ******************************************/ /** *提交保存 */ function forSave(){ if(validData()){ $("#theForm").submit(); } } /*** *验证表单数据 */ function validData(){ var confKey = $("#confKey").val(); if(confKey.replace(/(^\s*)|(\s*$)/,"").length==0){ $.ligerDialog.warn("配置项不能为空!"); return false; } var confValue = $("#confValue").val(); if(confValue.replace(/(^\s*)|(\s*$)/,"").length==0){ $.ligerDialog.warn("配置项值不能为空!"); return false; } var confDes = $("#confDes").val(); if(confDes.replace(/(^\s*)|(\s*$)/,"").length==0){ $.ligerDialog.warn("描述不能为空!"); return false; } var remark = $("#remark").val(); var length=remark.replace(/[^\x00-\xff]/g, "**").length;// if(length>256){ $.ligerDialog.warn("备注长度不能大于128个英文字符或者多于64个中文字符!"); return false; } return true; }
import Stack from './stack.js.js'; let stack = new Stack(); stack.push(1); stack.push(2); stack.push(3); stack.push(4);
module.exports = { db: { host: "localhost", user: "root", password: "", database: "followup2do" }, secret: ":KDP(&QP@:EUIBQ SSAIB SA:DKSJDB:UIW" };
const mongoose = require('mongoose') const AddressSchema = new mongoose.Schema({ streetName:String, streetNumber:String, postCode:String, city :String }); const Adress = mongoose.model('Adress',AddressSchema); module.exports = Adress;
const Data = [ { type: 'renderTitle', content: '网络攻击' }, { type: 'renderSubTitle', content: '一、xss攻击' }, { type: 'renderHtml', content: ` <text>XSS(Cross-Site Scripting,跨站脚本攻击)是一种代码注入攻击。攻击者在目标网站上注入恶意代码,当被攻击者登陆网站时就会执行这些恶意代码,这些脚本可以读取 cookie,session tokens,或者其它敏感的网站信息,对用户进行钓鱼欺诈,甚至发起蠕虫攻击等</text> <text> <ul> <li>1. 存储型(持久性)</li> <p>恶意脚本永久存储在目标服务器上。当浏览器请求数据时,脚本从服务器传回并执行,影响范围比反射型和DOM型XSS更大。存储型XSS攻击的原因仍然是没有做好数据过滤:前端提交数据至服务端时,没有做好过滤;服务端在接受到数据时,在存储之前,没有做过滤;前端从服务端请求到数据,没有过滤输出</p> <codeBlock> <text>攻击步骤</text> <code>1.攻击者将恶意代码提交到目标网站的数据库中。</code> <code>2.用户打开目标网站时,网站服务端将恶意代码从数据库取出,拼接在 HTML 中返回给浏览器。</code> <code>3.用户浏览器接收到响应后解析执行,混在其中的恶意代码也被执行。</code> <code>4.恶意代码窃取用户数据并发送到攻击者的网站,或者冒充用户的行为,调用目标网站接口执行攻击者指定的操作。</code> </codeBlock> <codeBlock> <text>防御措施</text> <code>1.前端数据传递给服务器之前,先转义/过滤(防范不了抓包修改数据的情况)</code> <code>2.服务器接收到数据,在存储到数据库之前,进行转义/过滤</code> <code>3.前端接收到服务器传递过来的数据,在展示到页面前,先进行转义/过滤</code> </codeBlock> </ul> </text> <text> <ul> <li>2.反射型(非持久型)</li> <codeBlock> <text>攻击步骤</text> <code>1.攻击者构造出特殊的 URL,其中包含恶 意代码。</code> <code>2.用户打开带有恶意代码的 URL 时,网站服务端将恶意代码从 URL 中取出,拼接在 HTML 中返回给浏览器。</code> <code>3.用户浏览器接收到响应后解析执行,混在其中的恶意代码也被执行。</code> <code>4.恶意代码窃取用户数据并发送到攻击者的网站,或者冒充用户的行为,调用目标网站接口执行攻击者指定的操作</code> </codeBlock> <codeBlock> <text>防御措施</text> <code>1.后端可以设置 httpOnly</code> <code>2.对url的查询参数进行转义后再输出到页面</code> </codeBlock> </ul> </text> <text> <ul> <li>3.DOM型</li> <codeBlock> <text>攻击步骤</text> <code>1.攻击者构造出特殊数据,其中包含恶意代码。</code> <code>2.用户浏览器执行了恶意代码。</code> <code>3.恶意代码窃取用户数据并发送到攻击者的网站,或者冒充用户的行为,调用目标网站接口执行攻击者指定的操作。</code> </codeBlock> <codeBlock> <text>防御措施</text> <code>1.防范 DOM 型 XSS 攻击的核心就是对输入内容进行转义(DOM 中的内联事件监听器和链接跳转都能把字符串作为代码运行,需要对其内容进行检查)</code> </codeBlock> </ul> </text> <text>其他措施:</text> <text>1.服务端使用 HTTP的 Content-Security-Policy 头部来指定策略,或者在前端设置 meta 标签 <text>2.输入内容长度和内容限制</text> <text>3.HTTP-only Cookie: 禁止 JavaScript 读取某些敏感 Cookie,攻击者完成 XSS 注入后也无法窃取此 Cookie。</text> ` }, { type: 'renderSubTitle', content: '二、csrf攻击' }, { type: 'renderHtml', content: ` <codeBlock> <text>攻击流程</text> <code>1.受害者登录A站点,并保留了登录凭证(Cookie)。</code> <code>2.攻击者诱导受害者访问了站点B。</code> <code>3.站点B向站点A发送了一个请求,浏览器会默认携带站点A的Cookie信息。</code> <code>4.站点A接收到请求后,对请求进行验证,并确认是受害者的凭证,误以为是无辜的受害者发送的请求。</code> <code>5.站点A以受害者的名义执行了站点B的请求。</code> <code>6.攻击完成,攻击者在受害者不知情的情况下,冒充受害者完成了攻击。</code> </codeBlock> <codeBlock> <text>防御措施</text> <code>1. 添加验证码(体验不好)验证码能够防御CSRF攻击,但是我们不可能每一次交互都需要验证码,否则用户的体验会非常差,但是我们可以在转账,交易等操作时,增加验证码,确保我们的账户安全。</code> <code>2. 判断请求的来源:检测Referer(并不安全,Referer可以被更改) Referer 可以作为一种辅助手段,来判断请求的来源是否是安全的,但是鉴于 Referer 本身是可以被修改的,因为不能仅依赖于Referer</code> <code>3. 使用Token(主流) CSRF攻击之所以能够成功,是因为服务器误把攻击者发送的请求当成了用户自己的请求。那么我们可以要求所有的用户请求都携带一个CSRF攻击者无法获取到的Token。服务器通过校验请求是否携带正确的Token,来把正常的请求和攻击的请求区分开。跟验证码类似,只是用户无感知。</code> <code>- 服务端给用户生成一个token,加密后传递给用户</code> <code>- 用户在提交请求时,需要携带这个token</code> <code>- 服务端验证token是否正确</code> <code>4. Samesite Cookie属性</code> 为了从源头上解决这个问题,Google起草了一份草案来改进HTTP协议,为Set-Cookie响应头新增Samesite属性,它用来标明这个 Cookie是个“同站 Cookie”,同站Cookie只能作为第一方Cookie,不能作为第三方Cookie,Samesite 有两个属性值,分别是 Strict 和 Lax。 </codeBlock> ` }, { type: 'renderSubTitle', content: '三、点击劫持' }, { type: 'renderHtml', content: ` <text>一个Web页面中隐藏了一个透明的iframe,用外层假页面诱导用户点击,实际上是在隐藏的frame上触发了点击事件进行一些用户不知情的操作</text> <codeBlock> <text>攻击流程</text> <code>1.攻击者构建了一个网页</code> <code>2.将被攻击的页面放置在当前页面的 iframe 中</code> <code>3.使用样式将 iframe 叠加到内容的上方</code> <code>4.将iframe设置为100%透明</code> <code>5.你被诱导点击了网页内容,你以为你点击的是***,而实际上,你成功被攻击了</code> </codeBlock> <codeBlock> <text>防御</text> <code>1.frame busting <pre><code> if ( top.location != window.location ){ top.location = window.location } </code> </pre> <code> 需要注意的是: HTML5中iframe的 sandbox 属性、IE中iframe的security 属性等,都可以限制iframe页面中的JavaScript脚本执行,从而可以使得 frame busting 失效。 </code> <code>2. X-Frame-Options</code> <code>X-FRAME-OPTIONS是微软提出的一个http头,专门用来防御利用iframe嵌套的点击劫持攻击。并且在IE8、Firefox3.6、Chrome4以上的版本均能很好的支持。</code> <code>可以设置为以下值:</code> <code>DENY: 拒绝任何域加载</code> <code>SAMEORIGIN: 允许同源域下加载</code> <code>ALLOW-FROM: 可以定义允许frame加载的页面地址</code> </code> </codeBlock> ` } ] export default Data
// pages/team/team.js const app = getApp(); const base = app.globalData.base; const U = require('../../utils/util.js'); Page({ data: { invite_level: 'son', list: [], listLen: 0 }, onLoad: function (options) { wx.setNavigationBarTitle({ title: '我的团队' }); var token = wx.getStorageSync('token'); if (token) { this.token = token; } var userInfo = wx.getStorageSync('userInfo'); this.invite_code = 'zhuantuitui'; if (userInfo) { if (userInfo.invite_code) { this.invite_code = userInfo.invite_code; } else { this.invite_code = 'zhuantuitui'; } } this.getTeam(); }, getTeam() { var that = this, data = {}; data.invite_level = this.data.invite_level; if (this.token) { data.token = this.token; } wx.request({ url: base + '/User/inviteList', data: data, success(res) { var list = res.data.data; list.map((v, i) => { list[i].add_time_trans = U.ftime(v.add_time); }); that.setData({ list: list, listLen: list.length }) if (that.onPullDown) { that.onPullDown = false; wx.stopPullDownRefresh() } }, fail(err) { console.log(err) } }) }, showSon() { this.setData({ invite_level: 'son' }) this.getTeam(); }, showOther() { this.setData({ invite_level: 'other' }); this.getTeam(); }, onShareAppMessage: function (res) { return { title: '还在傻傻拼团?点击看看,更优惠。自购更省钱,推广还能赚钱!', path: 'pages/index/index?invite_code=' + this.invite_code, imageUrl: 'https://pic.taodianke.com/static/MiniProgram/share.png', success: function (res) { // 转发成功 }, fail: function (res) { // 转发失败 } } }, onPullDownRefresh() { this.onPullDown = true; this.getTeam(); } })
var o = function() { function r() { this._subTitle = "你想要的这里都有", this._desc = "赠送好友游戏道具,当有好友领取时,你与好友共同得到奖励\n资源补给每日0点刷新", this._clickHomeCallback = null, this._pageType = 0; } return Object.defineProperty(r.prototype, "subTitle", { get: function() { return this._subTitle; }, enumerable: !0, configurable: !0 }), Object.defineProperty(r.prototype, "desc", { get: function() { return this._desc; }, enumerable: !0, configurable: !0 }), Object.defineProperty(r.prototype, "clickHomeCallback", { get: function() { return this._clickHomeCallback; }, enumerable: !0, configurable: !0 }), Object.defineProperty(r.prototype, "pageType", { get: function() { return this._pageType; }, enumerable: !0, configurable: !0 }), r.prototype.init = function(a, e, t, o) { void 0 === e && (e = null), void 0 === t && (t = ""), void 0 === o && (o = ""), this._pageType = a, this._subTitle = t || this._subTitle, this._desc = o || this._desc, this._clickHomeCallback = e; }, r.get = function(a, e, t, o) { void 0 === e && (e = null), void 0 === t && (t = ""), void 0 === o && (o = ""); var i = new r(); return i._pageType = a, i._subTitle = t || i._subTitle, i._desc = o || i._desc, i._clickHomeCallback = e, i; }, r; }(); exports.default = o;
var sum1=0; var sum2=0; function ForSum(){ for(var i=1; i<=1000; i++){ sum1=sum1+i; } return sum1; } function whileSum(){ var i=1; while(i<=1000){ sum2=sum2+i; i++; } return sum2; } console.log("Sum upto 1000 numbers using For Loop: "+ForSum()); console.log("Sum upto 1000 numbers using While Loop: "+whileSum());
import styled from "styled-components"; export const H1 = styled.h1` font-weight: normal; font-size: 12px; line-height: 1.3em; margin: 0; `; export const H2 = styled.h2` font-weight: normal; font-size: 12px; line-height: 1.3em; margin: 0; `;
import React from 'react'; import Display from './display'; import Key from './key'; import '../index.css'; // calculate expression based on the operator that is provided const calcExpression = { '+': function(firstValue, secondValue ) { return firstValue+secondValue }, '-': function(firstValue, secondValue ) { return firstValue-secondValue }, '*': function(firstValue, secondValue ) { return firstValue*secondValue }, "/": function(firstValue, secondValue ) { return firstValue/secondValue }, "=": function(firstValue, secondValue ) { return secondValue} }; //Calculator takes care of calculating logic export default class Calculator extends React.Component { constructor(props) { super(props); //Initial state of the calculator this.state = { operator: '', displayValue: '0', firstValue: null, needOperator: true, } } //Set the current operator that is being used setOperation(operator) { const firstValue = this.state.firstValue; const value = parseFloat(this.state.displayValue); //Sets first value if it hasn't been set yet, otherwise calculators previous expression before moving onto next if (firstValue === null) { this.setState({ firstValue: value, }); } else if (this.state.operator) { const result = calcExpression[this.state.operator](firstValue,value); this.setState({ firstValue: result, displayValue: String(result), }); } this.setState({ operator: operator, needOperator: true, }); } //Calculate expression when clicking equals setEquals() { //Grab variables needed to make calculation const operator = this.state.operator; const firstValue = this.state.firstValue; const value = parseFloat(this.state.displayValue); //go to key of operator and use const result = calcExpression[operator](firstValue,value); //Update calculator display this.setState({ firstValue: result, displayValue: String(result), needOperator: true, operator: '=' }); } //Basic functionality of inputting a number into the display addInput(number) { const needOperator = this.state.needOperator; //Determine if number input is for a new number or to write on an existing number if (needOperator) { this.setState({ displayValue: String(number), needOperator: false }); } else { const combine = String(this.state.displayValue) + String(number); this.setState({ displayValue: combine, }); } } //Clearing the calculator to initial state clearAll() { this.setState({ operator: '', displayValue: '0', firstValue: null, needOperator: true, }) } //Divide the current display by 100 setPercent() { const value = parseFloat(this.state.displayValue); const percentValue = value/100; this.setState({ displayValue: percentValue.toString(), }) } //Toggle between positive and negative changeSign() { this.setState({ displayValue: this.state.displayValue * -1 }) } //Alerts user that scientific mode is only for display scientificInput() { alert("Scientific mode is display only!"); } //Add decimal point to the current value decimalInput() { const displayValue = this.state.displayValue; if (displayValue.indexOf('.') > -1) { return null; } else { this.setState({ displayValue: displayValue + '.', }) } } scientificCalculator(colour, displayValue) { return( <div> <div> <Display output={displayValue}/> </div> <div className={"scientificCalculator"}> <div><Key className={"function-"+colour} colour={colour} value={'('} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={')'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'mc'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'m+'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'m-'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'mr'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'C'} onClick={ () => this.clearAll()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'+/-'} onClick={ () => this.changeSign()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'%'} onClick={ () => this.setPercent()}/></div> <div><Key className="operator" value={'÷'} colour={colour} onClick={() => this.setOperation('/')}/></div> <div><Key className={"function-"+colour} colour={colour} value={'2nd'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'x^2'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'x^3'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'x^y'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'e^x'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'10^x'} onClick={() => this.scientificInput()}/></div> <div><Key value={'7'} colour={colour} onClick={() => this.addInput(7)} /></div> <div><Key value={'8'} colour={colour} onClick={() => this.addInput(8)} /></div> <div><Key value={'9'} colour={colour} onClick={() => this.addInput(9)} /></div> <div><Key className="operator" value={'x'} colour={colour} onClick={() => this.setOperation('*')}/></div> <div><Key className={"function-"+colour} colour={colour} value={'1/x'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'sqrt'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'cbrt'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'root'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'ln'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'log10'} onClick={() => this.scientificInput()}/></div> <div><Key value={'4'} colour={colour} onClick={() => this.addInput(4)} /></div> <div><Key value={'5'} colour={colour} onClick={() => this.addInput(5)} /></div> <div><Key value={'6'} colour={colour} onClick={() => this.addInput(6)} /></div> <div><Key className="operator" value={'-'} colour={colour} onClick={() => this.setOperation('-')}/></div> <div><Key className={"function-"+colour} colour={colour} value={'x!'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'sin'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'cos'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'tan'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'e'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'EE'} onClick={() => this.scientificInput()}/></div> <div><Key value={'1'} colour={colour} onClick={() => this.addInput(1)} /></div> <div><Key value={'2'} colour={colour} onClick={() => this.addInput(2)} /></div> <div><Key value={'3'} colour={colour} onClick={() => this.addInput(3)} /></div> <div><Key className="operator" value={'+'} colour={colour} onClick={() => this.setOperation('+')}/></div> <div><Key className={"function-"+colour} colour={colour} value={'Rad'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'sinh'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'cosh'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'tanh'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'pi'} onClick={() => this.scientificInput()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'Rand'} onClick={() => this.scientificInput()}/></div> <div className={"zeroKeyScientific"}><Key className="key-0" value={'0'} colour={colour} onClick={() => this.addInput(0)}/></div> <div><Key value={'.'} colour={colour} onClick={() => this.decimalInput()}/></div> <div><Key className="operator" value={'='} colour={colour} onClick={() => this.setOperation('=')}/></div> </div> </div> ); } basicCalculator(colour, displayValue) { return( <div> <div> <Display output={displayValue}/> </div> <div className={"basicCalculator"}> <div><Key className={"function-"+colour} colour={colour} value={'C'} onClick={ () => this.clearAll()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'+/-'} onClick={ () => this.changeSign()}/></div> <div><Key className={"function-"+colour} colour={colour} value={'%'} onClick={ () => this.setPercent()}/></div> <div><Key className="operator" value={'÷'} colour={colour} onClick={() => this.setOperation('/')}/></div> <div><Key value={'7'} colour={colour} onClick={() => this.addInput(7)} /></div> <div><Key value={'8'} colour={colour} onClick={() => this.addInput(8)} /></div> <div><Key value={'9'} colour={colour} onClick={() => this.addInput(9)} /></div> <div><Key className="operator" value={'x'} colour={colour} onClick={() => this.setOperation('*')}/></div> <div><Key value={'4'} colour={colour} onClick={() => this.addInput(4)} /></div> <div><Key value={'5'} colour={colour} onClick={() => this.addInput(5)} /></div> <div><Key value={'6'} colour={colour} onClick={() => this.addInput(6)} /></div> <div><Key className="operator" value={'-'} colour={colour} onClick={() => this.setOperation('-')}/></div> <div><Key value={'1'} colour={colour} onClick={() => this.addInput(1)} /></div> <div><Key value={'2'} colour={colour} onClick={() => this.addInput(2)} /></div> <div><Key value={'3'} colour={colour} onClick={() => this.addInput(3)} /></div> <div><Key className="operator" value={'+'} colour={colour} onClick={() => this.setOperation('+')}/></div> <div className={"zeroKey"}><Key className="key-0" value={'0'} colour={colour} onClick={() => this.addInput(0)}/></div> <div><Key value={'.'} colour={colour} onClick={() => this.decimalInput()}/></div> <div><Key className="operator" value={'='} colour={colour} onClick={() => this.setOperation('=')}/></div> </div> </div> ); } render() { if (this.props.show === false) { return null; } const colour = this.props.colour; const displayValue= this.state.displayValue; const scientific = this.props.scientific; if (!scientific) { return (this.basicCalculator(colour, displayValue)) } else { return (this.scientificCalculator(colour, displayValue)) } } }
var requirejs = require('requirejs'); var ModuleController = require('../controllers/module'); var AvailabilityController = requirejs('common/modules/availability'); var AvailabilityView = require('../views/modules/availability'); module.exports = ModuleController.extend(AvailabilityController).extend({ visualisationClass: AvailabilityView });
let student_name = ['Oto', 'Robi', 'Luka', 'vaxo', 'lasha', 'nodo' ]; student_name.sort(); console.log(student_name);
/** * 实现一个全局事件监听的脚本 * - 用于 H5 与 外界壳的通信,主要用于外界壳主动通知H5 * - 外界壳可以是 QT / SU 等等 * - 订阅/发布者 模式 */ const DEFAULT_CONFIG = { needRegister: true, }; class Comm { constructor (config) { this.config = { ...DEFAULT_CONFIG, ...config, }; this.listeners = {}; } // 注册通信事件 register (evtName) { // 已经注册过了 if (this.listeners[evtName]) return false; this.listeners[evtName] = []; return true; } // 注销通信事件 unregister (evtName) { if (!this.listeners[evtName]) return false; this.listeners[evtName] = undefined; return true; } // 订阅 subscribe (evtName, cb) { if (typeof cb === 'function') { if (!this.listeners[evtName]) { if (this.config.needRegister) throw new Error(`通信事件:"${evtName}"暂未注册!请注册后再使用!`); else this.listeners[evtName] = []; } this.listeners[evtName].push(cb); return true; } return false; } // 触发 trigger (evtName) { if (!evtName || !this.listeners[evtName]) { return false; } let args = [...arguments].slice(1); this.listeners[evtName].map((cb)=>{ cb(...args); }); } // 取消订阅 unsubscribe (evtName, cb) { if (!evtName || !this.listeners[evtName] || !cb || (typeof cb !== 'function')) { return false; } let len = this.listeners[evtName].length; for (let i=0; i<len; i++) { if (this.listeners[evtName][i] === cb) { this.listeners[evtName].splice(i, 1); return true; } } } } export default Comm;
class AddressEditor extends React.Component { state = { address: {} } findAddressByUserId = (user_id) => findAddressById(user_id) .then(address => this.setState({address})) componentDidMount = () => { const user_id = window.location.search.split("=")[1] this.findAddressByUserId(user_id) } saveStreet = () => changeAddressStreet(this.state.address) saveApartment = () => changeAddressApartment(this.state.address) saveCity = () => changeAddressCity(this.state.address) saveZip = () => changeAddressZip(this.state.address) saveAddressPrimary = () => changeAddressPrimaryP(this.state.address) render() { return( <div className="container"> <h1>Address Editor: <br/> {this.state.address.address}</h1> ID: <input className="form-control" readOnly={true} value={this.state.address.id}/> <br/> Street: <input onChange={(event) => this.setState({ address: { ...this.state.address, street: event.target.value}})} className="form-control" value={this.state.address.street}/> <button onClick={this.saveStreet}> Save Street </button> <br/> <br/> Apartment: <input onChange={(event) => this.setState({ address: { ...this.state.address, apartment: event.target.value}})} className="form-control" value={this.state.address.apartment}/> <button onClick={this.saveApartment}> Save Apartment </button> <br/> <br/> City: <input onChange={(event) => this.setState({ address: { ...this.state.address, city: event.target.value}})} className="form-control" value={this.state.address.city}/> <button onClick={this.saveCity}> Save City </button> <br/> <br/> Zip: <input onChange={(event) => this.setState({ address: { ...this.state.address, zip: event.target.value}})} className="form-control" value={this.state.address.zip}/> <button onClick={this.saveZip}> Save Zip Code </button> <br/> <br/> Primary (1 for "yes", 0 for "no"): <input onChange={(event) => this.setState({ address: { ...this.state.address, primary_p: event.target.value}})} className="form-control" value={this.state.address.primary_p}/> <button onClick={this.saveAddressPrimary}> Save Primary </button> <br/> <br/> <a href="/home-manager.html"> Home </a> <br/> <br/> </div> ) } } ReactDOM.render( <AddressEditor/>, document.getElementById("root"))
// 不放空的start无法启动的!!!!
export default ngModule => { ngModule.config(addSelectType); function addSelectType(formlyConfigProvider, formlyBootstrapApiCheck) { const c = formlyBootstrapApiCheck; formlyConfigProvider.setType({ name: 'select', template: require('./select.html'), wrapper: ['bootstrapLabel', 'bootstrapHasError'], defaultOptions(options) { if (options.templateOptions.ngOptions) { return { ngModelAttrs: { [options.templateOptions.ngOptions]: { value: 'ng-options' } } }; } }, apiCheck: { templateOptions: c.shape({ options: c.arrayOf(c.object), labelProp: c.string.optional, valueProp: c.string.optional, groupProp: c.string.optional }) }, apiCheckInstance: c }); } };
import React,{useState,useEffect} from 'react' const StopWatch = () => { const [time, setTime] = useState({hours:0,minutes:0,seconds:0}) const [isActive, setIsActive] = useState(false); const [isTimer,setIsTimer] = useState(true); const reset = () => { setTime({hours:0,minutes:0,seconds:0}) setIsActive(false); setIsTimer(true); } const stopwatch = () =>{ if(isTimer){ if(time.hours === 1) console.log('stop stop-watch') else if(time.minutes===60 && time.seconds===60) setTime({hours:time.hours+1,minutes:0,seconds:0}) else if(time.seconds===60) setTime({hours:time.hours,minutes:time.minutes+1,seconds:0}) else setTime({hours:time.hours,minutes:time.minutes,seconds:time.seconds+1}) } } useEffect(() => { let timerId if(isActive) timerId = setInterval(()=>stopwatch(),1000) return () => { clearInterval(timerId) }; }) return ( <div className="text-white rounded-full h-96 w-96 flex flex-col ml-10 justify-center items-center bg-gray-800"> <p className="text-3xl font-bold">{`${time.hours.toString().padStart(2, 0)} : ${time.minutes.toString().padStart(2, 0)} : ${time.seconds.toString().padStart(2, 0)}`}</p> { isActive ? <div> <button className="mt-10 rounded bg-purple-500 text-lg p-2 w-20 tracking-widest hover:bg-purple-700 focus:outline-none" onClick={reset}> RESET </button> <button className="mt-10 rounded bg-purple-500 text-lg p-2 w-26 tracking-widest hover:bg-purple-700 focus:outline-none ml-3" onClick={()=>setIsTimer(!isTimer)}> {isTimer ? "PAUSE" : "RESUME"} </button> </div> : <div> <button className="mt-10 rounded bg-purple-500 text-lg p-2 w-20 tracking-widest hover:bg-purple-700 focus:outline-none" onClick={()=>setIsActive(true)}> START </button> </div> } </div> ) } export default StopWatch
module.exports = { CurrPlayIndex: 0, Jump: false, End: false };
var express = require('express'); var router = express.Router(); var marked = require('marked'); var debug = require('debug')('notekeep:posts'); var Post = require('../db/post.js'); marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, sanitize: true, smartLists: true, }); /* GET users listing. */ router.get('/', function(req, res, next) { Post.find().findByUser(req.userID) .populate('user').lean() .then(function(posts) { var title; if (posts.length > 0) { title = posts[0].user.username + '\'s posts'; for (let i = 0; i < posts.length; i++) { posts[i].content = marked(posts[i].content); } } else { title = 'Unknown user\'s posts'; } res.render('posts', {title: title, posts: posts}); }); }); router.get('/new', function(req, res, next) { var title = 'Add new note'; var form = { entries: [ {name: 'content', type: 'textarea', text: 'Content'} ] }; res.render('form', {title: title, form: form}); }); router.post('/new', function(req, res, next) { var body = req.body; Post.create({ user: req.userID, createdDate: new Date(), content: body.content }) .then(function(newPost) { debug('New post created for ' + req.userID); res.redirect('.'); }) .catch(function(err) { debug('Error creating new post for ' + req.userID); req.log.error('Error creating new post', err); }); }); module.exports = router;
module.exports = function (req) { if (!req) throw new Error('Request object required to find client IP address'); var forwardedFor = req.headers['x-forwarded-for']; if (forwardedFor !== undefined) return forwardedFor.split(',')[0]; var cf = req.headers['cf-connecting-ip']; if (cf !== undefined) return cf; return req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; }
process.stdout.write('Hello, clouds!');
$(document).ready(function () { $.ajax({ type: "GET", url: "http://localhost:8081/medications/allmedications", dataType: "json", beforeSend: function(xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function (data) { console.log("SUCCESS : ", data); for (i = 0; i < data.length; i++) { var name = data[i]['name']; $("#idDropDown").append("<option value='" + name + "'>" + name + "</option>"); } }, error: function (data) { console.log("ERROR : ", data); } }); }); $(document).on("submit", "form", function (event) { event.preventDefault(); var namee = $("#name").val(); var code = $("#code").val(); var type = $("#type_med").val(); var shape = $("#shape").val(); var ingredients = $("#ingredients").val(); var producer = $("#producer").val(); var contraindication = $("#contraindication").val(); var recommended_daily_intake = $("#intake").val(); var alternative = $("#idDropDown :selected").val(); var newUserJSON = formToJSON(namee,code,type,shape,ingredients,producer,contraindication,recommended_daily_intake,alternative); $.ajax({ type: "POST", // HTTP metoda je POST url: "http://localhost:8081/systemadmins/registerMedication", // URL na koji se šalju podaci dataType: "json", // tip povratne vrednosti contentType: "application/json", // tip podataka koje šaljemo data: newUserJSON, beforeSend: function (xhr) { if (localStorage.token) { xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token); } }, success: function () { alert("success"); window.location.href = "adminSystemHomePage.html"; }, error: function (error) { alert(error); } }); }); function formToJSON(namee,code,type,shape,ingredients,producer,contraindication,recommended_daily_intake,alternative) { return JSON.stringify( { "name": namee, "code": code, "type_med": type, "shape_med": shape, "ingredients": ingredients, "producer": producer, "contraindication": contraindication, "recommended_daily_intake": recommended_daily_intake, "alternative":alternative } ); }
import { createStore } from "redux"; import { expect } from "chai"; import restaurantsReducer, { addRestaurant, } from "../features/restaurant/restaurantsSlice"; describe("restaurantsReducer", () => { it("updates the store on successful dispatch", () => { let store = createStore(restaurantsReducer); store.dispatch( addRestaurant({ name: "Blooming Hill", location: "Blooming Grove, NY" }) ); expect(store.getState().restaurants.length).to.equal(1); expect(store.getState().restaurants[0].name).to.equal("Blooming Hill"); expect(store.getState().restaurants[0].location).to.equal( "Blooming Grove, NY" ); }); });
// 这里指定每个页面组件的动态引入方式 // await import 是ES6标准引入方式,vue-router官方是 以下写法: // const Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo') 是等价的 // 通过 /* webpackChunkName: "githuber" */ 这样的方式指定 都打到同一个包中 // 开发人员只需要修改 vue文件的位置、给出组件名称就可以了 //import PageUserList from './page/userlist/page.vue' //const PageUserList = async resolve => resolve(await import(/* webpackChunkName: "githuber" */'./page/userlist/page.vue')); //const UserDetail = async resolve => resolve(await import(/* webpackChunkName: "githuber" */'./page/hello/page.vue')); // const taxAdd = () => import(/* webpackChunkName: "tax" */ './tax/taxAdd.vue'); //新增和编辑 // const list = () => import(/* webpackChunkName: "tax" */'./list/index.vue'); //列表 // const detail = () => import(/* webpackChunkName: "tax" */'./details/index.vue'); //详情 const edit = () => import(/* webpackChunkName: "mail" */'./edit-mail/edit-mail.vue'); //详情 const setting = () => import(/* webpackChunkName: "mail" */'./setting-mail/index.vue'); //设置 const inboxList = () => import(/* webpackChunkName: "mail" */'./inbox-mail/inboxList.vue'); //收件箱 const outboxList = () => import(/* webpackChunkName: "mail" */'./outbox-mail/outboxList.vue'); //发件箱 const draftList = () => import(/* webpackChunkName: "mail" */'./drafts-mail/draftList.vue'); //草稿箱 const dustbinList = () => import(/* webpackChunkName: "mail" */'./dustbin-mail/dustbinList.vue'); //垃圾箱 const deletedList = () => import(/* webpackChunkName: "mail" */'./deleted-mail/deleteList.vue'); //已删除 const detailMail = () => import(/* webpackChunkName: "mail" */'./detail-mail/detailMail.vue'); //邮件详情 export { inboxList, outboxList, draftList, dustbinList, deletedList, edit, setting, detailMail, };
import React from 'react'; import Layout from '../components/layout'; import { graphql } from 'gatsby'; export default ({ data }) => { const { goodreadsShelf: { reviews } } = data; const BookContainer = ({ link, title, imageUrl }) => { return( <div style={{display: 'flex', flexWrap: 'wrap'}}> <div style={{width: '20%'}}> <a href={link} target="_blank" rel="noopener noreferrer"> <img src={imageUrl} alt={title}/> </a> </div> <div style={{width: '80%'}}> <a href={link} target="_blank" rel="noopener noreferrer"> <h3>{title}</h3> </a> </div> </div> ); } const BookList = () => reviews.map(({ book }) => <li key={book.bookID} style={{borderBottom: '4px dotted black'}}> <BookContainer link={book.link} title={book.title} imageUrl={book.imageUrl} /> </li> ); return ( <Layout> <h4> Book Shelf </h4> <ul style={{listStyle: 'none'}}> <BookList /> </ul> </Layout> ); } export const query = graphql` query goodRead { goodreadsShelf { id reviews { reviewID book { bookID link title imageUrl } } } } `;
const { Schema } = require('mongoose'); const connection = require('../connections/mongoose/instance'); const ContactReference = { type: Schema.Types.ObjectId, required: true, validate: { async validator(v) { const doc = await connection.model('contact').findOne({ _id: v }, { _id: 1 }); if (doc) return true; return false; }, message: 'No contact found for ID {VALUE}', }, }; const getIds = (doc, fieldName) => { const value = doc.get(fieldName); return Array.isArray(value) ? value : []; }; module.exports = function notifyPlugin(schema) { schema.add({ notify: { internal: [ContactReference], external: [ContactReference], }, }); schema.method('addContactId', function addContactId(type, contactId) { const fieldName = `notify.${type}`; const ids = getIds(this, fieldName); const current = ids.map(id => `${id}`); current.push(`${contactId}`); this.set(fieldName, [...new Set(current)]); }); schema.method('removeContactId', function removeContactId(type, contactId) { const fieldName = `notify.${type}`; const ids = getIds(this, fieldName); const filtered = ids.filter(id => `${id}` !== `${contactId}`); this.set(fieldName, filtered); }); schema.method('addInternalContactId', function addInternalContactId(contactId) { this.addContactId('internal', contactId); }); schema.method('addExternalContactId', function addExternalContactId(contactId) { this.addContactId('external', contactId); }); schema.method('removeInternalContactId', function removeInternalContactId(contactId) { this.removeContactId('internal', contactId); }); schema.method('removeExternalContactId', function removeExternalContactId(contactId) { this.removeContactId('external', contactId); }); schema.method('removeContactIdAll', function removeContactIdAll(contactId) { this.removeContactId('internal', contactId); this.removeContactId('external', contactId); }); };
import React, {useState, useContext} from 'react' import {useHistory} from 'react-router-dom' import {Checkout, Spinner} from '../components' import {CartContext} from '../context/cart' import {loadStripe} from '@stripe/stripe-js' import {Elements} from '@stripe/react-stripe-js' import {firestore} from '../firebase/firebase.utils' import * as ROUTES from '../constants/routes' export function CheckoutContainer(){ const [isLoading, setIsLoading] = useState(false) const history = useHistory() const { selectedCar, dateFrom, setDateFrom, dateTo, setDateTo, driversName, setDriversName, phone, setPhone, location, setLocation, insurance, setInsurance } = useContext(CartContext) const getNumberOfDays = (firstDate, secondDate) => { const oneDay = 24 * 60 * 60 * 1000 return Math.round(Math.abs((new Date(firstDate) - new Date(secondDate)) / oneDay)) } const stripePromise = loadStripe('pk_test_51GwkiKCDAP5OrfdHiqDdThPtn0VMfSsKYDktZrGwkBlEniMMZzAAPZ4VMNgRRuXRcuFrBfSgRwZJyT5KvENJoIkF004KLxi9L3') const days = getNumberOfDays(dateFrom, dateTo) const total = ((insurance * days) + (days * selectedCar.price)) const handleSubmit = (e) => { e.preventDefault() setIsLoading(true) setTimeout(() => { firestore.collection('orders').add({ driversName, phone, dateFrom, dateTo, location, insurance, total }) setDriversName('') setDateFrom(new Date()) setDateTo(new Date()) setPhone() setLocation('') setInsurance(5) setIsLoading(false) history.push(ROUTES.HOME) }, 2000) } return ( <Checkout> <Checkout.Title> Summary: </Checkout.Title> <Checkout.Item> <Checkout.ItemName> {selectedCar.name} </Checkout.ItemName> <Checkout.ItemQuantity> {days} days </Checkout.ItemQuantity> <Checkout.ItemPrice> Total: {days * selectedCar.price} $ </Checkout.ItemPrice> </Checkout.Item> <Checkout.Item> <Checkout.ItemName> {insurance === 5 ? 'Regular insurance' : 'Premium insurance'} </Checkout.ItemName> <Checkout.ItemQuantity> {days} days </Checkout.ItemQuantity> <Checkout.ItemPrice> Total: {insurance * days} $ </Checkout.ItemPrice> </Checkout.Item> <Elements stripe={stripePromise}> <Checkout.Form onSubmit={handleSubmit}> <Checkout.Input value={driversName} placeholder="Full name" onChange={e => setDriversName(e.target.value)} required={true} /> <Checkout.Input value={location} placeholder="Address" onChange={e => setLocation(e.target.value)} required={true} /> <Checkout.Input value={phone} placeholder="Phone number" type="number" onChange={e => setPhone(e.target.value)} required={true} /> <Checkout.FormCardInput /> <Checkout.FormBtn> Pay {total} $</Checkout.FormBtn> </Checkout.Form> <Spinner loading = {isLoading}/> </Elements> </Checkout> ) }
const BaseRest = require('./_rest.js'); module.exports = class extends BaseRest { async getAction() { const appsModel = this.model('apps') const app = await appsModel.get(this.appId) return this.success(app) } };
const Joi = require("joi"); const nurseObj = require("../modules/nurse"); const getNurses = async () => { const nurses = await nurseObj.Nurse.find({}).select("-password"); return nurses; }; const addNurse = nurse => { const newNurse = new nurseObj.Nurse(nurse); newNurse.save(); return newNurse; }; const getNurseById = async id => { const nurse = await nurseObj.Nurse.findOne({ _id: id }); return nurse; }; const getNurseByUserName = async userName => { const nurse = await nurseObj.Nurse.findOne({ userName }); return nurse; }; const updateNurseById = async (id, reqBody) => { const nurse = await nurseObj.Nurse.findOneAndUpdate( { _id: id }, { $set: reqBody }, { new: true } ); return nurse; }; const deleteNurseById = async id => { const nurse = await nurseObj.Nurse.findOneAndRemove({ _id: id }); return nurse; }; // ======================Nurse validation==================== const validateNurse = nurse => { const schema = { name: Joi.string().min(3), userName: Joi.string().min(3), password: Joi.string(), email: Joi.string().email(), phone: Joi.string().length(10), userType: Joi.string().min(3) }; return Joi.validate(nurse, schema); }; module.exports = { getNurses, addNurse, getNurseById, getNurseByUserName, updateNurseById, deleteNurseById, validateNurse };
import { GET_QUESTIONS_SUCCESS, GET_QUESTIONS_FAIL, SET_QUESTION_COUNT, GET_QUESTIONS_REQUEST, RESET_QUESTIONS, } from "./questions.types"; const initialState = { questions: { page: [], currentPage: 1, pageCount: 1, pageLimit: 3, questionCount: 0, }, loading: true, }; const reducer = (state = initialState, action) => { switch (action.type) { case RESET_QUESTIONS: return initialState; case SET_QUESTION_COUNT: return { ...state, questions: { ...state.questions, questionCount: action.payload, pageCount: Math.ceil(action.payload / state.questions.pageLimit), }, }; case GET_QUESTIONS_REQUEST: { return { ...state, loading: true }; } case GET_QUESTIONS_SUCCESS: return { ...state, questions: { ...state.questions, page: action.payload.questions, currentPage: action.payload.page, }, loading: false, }; case GET_QUESTIONS_FAIL: return { ...state, questions: [], loading: false, question: null }; default: return state; } }; export default reducer;
const paypal = require('paypal-rest-sdk'); const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); paypal.configure({ 'mode': 'sandbox', //sandbox or live 'client_id': 'AQCh7WjQscPDgBpEN88zRCiFYtr44a6jqZQl6Bh4FbUBn6rV1Uzslr4kcqJwMud5nFnAaXE7PbPciAr8', 'client_secret': 'EDWl0KuuCpTg8hYX-QOz6pmWxpkvF4m1Pqu-Lk-FG870ORVr77ZkA67U_ivunFUNypu2fAZYEHNDU8rC' }); var create_payment_json = { "intent": "sale", "payer": { "payment_method": "paypal" }, "redirect_urls": { "return_url": "http://mysite.com/return", "cancel_url": "http://mysite.com/cancel" }, "transactions": [{ "item_list": { "items": [{ "name": "apple", "price": "1.00", "currency": "USD", "quantity": 1 }] }, "amount": { "currency": "USD", "total": "1.00" }, "description": "This is the payment description.", "payment_options": { "allowed_payment_method": "INSTANT_FUNDING_SOURCE" } }] }; var execute_payment_json = { "payer_id": "Appended to redirect url", // "transactions": [{ // "amount": { // "currency": "USD", // "total": "1.00" // } // }] }; var sale_refund_json = { "amount": { "currency": "USD", "total": "1.00" } }; var sale_full_refund_json = {}; let createdPayment; let approvedPayment; Promise.resolve().then(() => { return new Promise((resolve, reject) => { paypal.payment.create(create_payment_json, function (error, payment) { if (error) { console.error(payment); throw error; } else { console.log("Create Payment Response"); console.log(JSON.stringify(payment, null, 4)); createdPayment = payment; resolve(payment); } }); }) }).then(() => { return new Promise((resolve, reject) => { rl.question('payer ID? ', (answer) => { resolve(answer); }); }); }).then((payerID) => { return new Promise((resolve, reject) => { execute_payment_json.payer_id = payerID; paypal.payment.execute(createdPayment.id, execute_payment_json, function (error, payment) { if (error) { console.log(error.response); throw error; } else { console.log("Get Payment Response"); console.log(JSON.stringify(payment, null, 4)); approvedPayment = payment; resolve(); } }); }); }).then(() => { return new Promise((resolve, reject) => { rl.question('refund? ', (answer) => { resolve(answer); }); }); }).then(() => { return new Promise((resolve, reject) => { paypal.sale.refund(approvedPayment.transactions[0].related_resources[0].sale.id, sale_full_refund_json, function (error, refund) { if (error) { throw error; } else { console.log("Refund Sale Response"); console.log(JSON.stringify(refund, null, 4)); } }); }); });
(function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) return installedModules[moduleId].exports; var module = installedModules[moduleId] = {exports: {}, id: moduleId, loaded: false}; modules[moduleId].__c("call", module.__g("exports"), module, module.__g("exports"), __webpack_require__); module.__s("loaded", true); return module.exports; } __webpack_require__.__s("m", modules); __webpack_require__.__s("c", installedModules); __webpack_require__.__s("p", ""); return __webpack_require__(0); })({0: function(module, exports, __webpack_require__) { "use strict"; importApi("ui"); importClass("android.view.View.OnClickListener"); importClass("android.widget.Toast"); var helloXml = __webpack_require__(9); var page = {onLoad: function onLoad() { var imageView = hybridView.__c("findViewWithTag", "imageView"); imageView.__c("setOnClickListener", new OnClickListener(function() { ui.__c("alert", '\u539f\u751fAPI\u8c03\u7528\u5bf9\u8bdd\u6846\u5c01\u88c5'); })); }}; hybridView.__s("onLoad", function() { page.__c("onLoad"); }); hybridView.__c("loadXml", helloXml); }, 9: function(module, exports) { module.__s("exports", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<View\n width=\"750\"\n height=\"100%\"\n screenUnit=\"750\">\n <ImageView\n width=\"750\"\n height=\"300\"\n imageUrl=\"https://img.alicdn.com/tfs/TB1Pth5mcLJ8KJjy0FnXXcFDpXa-520-280.jpg\"\n scaleType=\"fitXY\"\n tag=\"imageView\"/>\n <TextView\n y=\"300\"\n width=\"750\"\n textAlign=\"center\"\n height=\"100\"\n text=\"Hello World \u624b\u673a\u6dd8\u5b9d\"\n tag=\"helloTextField\"/>\n</View>\n"); }});
//@todo move to canvas options var cell_size = 40; var cell_border = 2; var TuringMachineCanvas = function(canvas_id) { this.machine = null; this.canvas = document.getElementById(canvas_id); this.canvas.style.width = '100%'; this.canvas.width = this.canvas.offsetWidth; this.canvas.height = 200; this.ctx = this.canvas.getContext('2d'); this.font_size = 32; }; TuringMachineCanvas.prototype.setMachine = function(machine) { this.machine = machine; this.draw(); }; TuringMachineCanvas.prototype.draw = function() { this.canvas.width = this.canvas.width; var width = this.canvas.width; var height = this.canvas.height; if(this.machine) { var length = this.machine.strip.cells.length; if(length > 10) { cell_size = 40 - (length - 10) * 0.5; if(cell_size < 10) cell_size = 10; this.font_size = 32 - (length - 10) * 0.5; if(this.font_size < 12) this.font_size = 12; } else { cell_size = 40; cell_border = 2; this.font_size = 32; } var strip_width = length * cell_size; var start_x = (width - strip_width) / 2; var middle_y = (height - cell_size) / 2; var x = start_x; var fade_cells_count = 4; var fade_cells_min = 0.05; var fade_cells_max= 0.5; var face_cells_step = (fade_cells_max - fade_cells_min) / fade_cells_count; for(var i = 0; i < fade_cells_count; i++) { this.drawEmptyCell(x - cell_size * (fade_cells_count - i), middle_y, cell_size, fade_cells_min + face_cells_step * i); } for(var i = 0; i < length; i++) { this.drawStripCell(x, middle_y, this.machine.strip.cells[i]); x += cell_size; } for(var i = 0; i < fade_cells_count; i++) { this.drawEmptyCell(x + cell_size * i, middle_y, cell_size, fade_cells_max - face_cells_step * i); } x = start_x + this.machine.strip.caret_position * cell_size; var y = middle_y - cell_size; this.drawMachine(x, y); } else { var ctx = this.ctx; var text = 'No machine'; ctx.fillStyle = '#000000'; var font_size = this.font_size + 4; ctx.font = font_size + "px Courier"; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; var text_size = ctx.measureText(text); ctx.fillText(text, (width - text_size.width) / 2 , (height - font_size) / 2 ); } }; TuringMachineCanvas.prototype.drawEmptyCell = function(x, y, size, opacity) { var ctx = this.ctx; ctx.fillStyle = "rgba(230, 230, 230, " + opacity + ")"; ctx.fillRect(x, y, size, size); ctx.beginPath(); ctx.lineWidth = cell_border; ctx.strokeStyle = "rgba(0, 0, 0, " + opacity + ")"; ctx.rect(x, y, size, size); ctx.stroke(); }; TuringMachineCanvas.prototype.drawStripCell = function(x, y, value) { this.drawEmptyCell(x, y, cell_size, 1); var ctx = this.ctx; ctx.fillStyle = '#000000'; ctx.font = this.font_size + "px Courier"; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; var text_size = ctx.measureText(value); ctx.fillText(value, x + (cell_size - text_size.width) / 2 , y + (cell_size - this.font_size) / 2 ); } TuringMachineCanvas.prototype.drawMachine = function(x, y) { var ctx = this.ctx; ctx.fillStyle = '#ccccff'; if(this.machine.stop) { ctx.fillStyle = '#ffcccc'; } ctx.fillRect(x, y, cell_size, cell_size); ctx.beginPath(); ctx.lineWidth = cell_border; ctx.strokeStyle = "black"; ctx.rect(x, y, cell_size, cell_size); ctx.stroke(); ctx.fillStyle = '#000000'; var font_size = this.font_size - 10; ctx.font = font_size + "px Courier bold"; ctx.textAlign = 'left'; ctx.textBaseline = 'top'; var text = this.machine.state; var text_size = ctx.measureText(text); ctx.fillText(text, x + (cell_size - text_size.width) / 2 , y + (cell_size - font_size) / 2 ); }
({ cachetabinfo: function(component) { this.getTabInfo(component); }, // Call this function from your controller for // opening Primary Tab (Company) and subsequently Multiple subTabs (Accounts, Cases etc). //Eg: helper.openSobjectPrimSubTab(component, primaryRecordId, secondaryRecordId). openSobjectPrimSubTabs: function(component, primaryRecordId, secondaryRecordIds) { this.openSobjectPrimaryTab(component, primaryRecordId, null, this.openSobjectSubTabPromise, secondaryRecordIds); }, // Call this function from your controller for // opening Primary Tab (Company) and subsequently a related subTab (Account). //Eg: helper.openSobjectPrimSubTab(component, primaryRecordId, secondaryRecordId). openSobjectPrimSubTab: function(component, primaryRecordId, secondaryRecordId) { this.openSobjectPrimaryTab(component, primaryRecordId, secondaryRecordId, this.openSobjectSubTabIdApi); }, // Call this function from your controller for // 1. Opening Primary Tab only helper.openSobjectPrimaryTab(component, primaryRecordId) openSobjectPrimaryTab: function(component, primaryRecordId, secondaryRecordId, subTabCallback, secondaryRecordIds) { var workspaceApi = component.find("workspace"); var urlString = '#/sObject/' + primaryRecordId + '/view'; workspaceApi.openTab({ url: urlString, focus: true }).then(function(response) { if (typeof(subTabCallback) !== "undefined" && typeof(secondaryRecordId) !== "undefined" && secondaryRecordId !== null) { subTabCallback(component, secondaryRecordId, response); }; if (typeof(subTabCallback) !== "undefined" && typeof(secondaryRecordIds) !== "undefined" && secondaryRecordIds !== null) { var secondaryrecordId1 = secondaryRecordIds[0]; var secondaryrecordId2 = secondaryRecordIds[1]; var createsubTabPromise1 = subTabCallback(component, secondaryrecordId1, response); createsubTabPromise1.then($A.getCallback(function(result) { var createsubTabPromise2 = subTabCallback(component, secondaryrecordId2, response); return createsubTabPromise2; })).then($A.getCallback(function(result) { console.log('createsubTabPromise2 resolved ' + JSON.stringify(result)); })).catch($A.getCallback(function(error) { console.log('An error occurred in subtab promise: ' + JSON.stringify(error)); })); }; }); }, // Call this function from your controller for opening a record in subtab // eg:helper. openSobjectSubTab(component, recordId); openSobjectSubTab: function(component, recordId) { this.getTabInfo(component, this.openSobjectSubTabApi, recordId); }, // Call this in your controller to set tab label.Label is set only on the focussed tab. //eg:helper.setTablabel(component) setTabLabel: function(component) { // If tabinfo is not populated on component if (component.get("v.tabinfo") === undefined || component.get("v.tabinfo") === null) { //populate tabinfo on component and set the label this.getTabInfo(component, this.setTabLabelApi); } else { // set the tab label this.setTabLabelApi(component); } }, // Call this in your controller to set tab Icon.Tab Icon is set only on the focussed tab. // helper.setTabIcon(component) setTabIcon: function(component) { // If tabinfo is not populated on component debugger; if (component.get("v.tabinfo") === undefined || component.get("v.tabinfo") === null) { debugger; this.getTabInfo(component, this.setTabIconApi); } else { debugger; this.setTabIconApi(component); } }, // Do not call this function from your controller. Used internally by the helper. setTabLabelApi: function(component) { debugger; var workspaceApi = component.find("workspace"); console.log('@@@@ Inside setTabLabelApi'); debugger; console.log('component.get"v.tabinfo".tabId' +component.get("v.tabinfo").tabId); console.log('component.get"v.tablabel' +component.get("v.tablabel")); if (component.get("v.tabinfo") !== undefined && component.get("v.tabinfo") !== null) { workspaceApi.setTabLabel({ tabId: component.get("v.tabinfo").tabId, label: component.get("v.tablabel") }).then(function(response) { if (response !== null) { console.log('JSON.stringify(response)' + JSON.stringify(response)); } else { console.log('Error in setTabLabelApi' + JSON.stringify(response)); } }); } }, // Do not call this function from your controller. Used internally by the helper. setTabIconApi: function(component) { var workspaceApi = component.find("workspace"); debugger; console.log('@@@@ Inside setTabIconApi'); console.log('component.get"v.tabinfo".tabId' +component.get("v.tabinfo").tabId); console.log('component.get"v.tablabel' +component.get("v.tabicon")); debugger; if (component.get("v.tabinfo") !== undefined && component.get("v.tabinfo") !== null) { workspaceApi.setTabIcon({ tabId: component.get("v.tabinfo").tabId, icon: component.get("v.tabicon"), iconAlt: "Loading.." }).then(function(response) { if (response !== null) { console.log('JSON.stringify(response)' + JSON.stringify(response)); } else { console.log('Error in setTabIconApi' + JSON.stringify(response)); } }); } }, // Do not call this function from your controller. Used internally by the helper. openSobjectSubTabApi: function(component, recordId) { var workspaceApi = component.find("workspace"); var urlString = '#/sObject/' + recordId + '/view'; debugger; workspaceApi.openSubtab({ parentTabId: component.get("v.tabinfo").tabId, url: urlString, focus: true }).then(function(response) { if (response !== null) { console.log('JSON.stringify(response)' + JSON.stringify(response)); } else { console.log('Error in openSobjectSubTabApi' + JSON.stringify(response)); } }); }, // Do not call this function from your controller. Used internally by the helper. openSobjectSubTabIdApi: function(component, recordId, primarytabId) { var workspaceApi = component.find("workspace"); var urlString = '#/sObject/' + recordId + '/view'; workspaceApi.openSubtab({ parentTabId: primarytabId, url: urlString, focus: true }).then(function(response) { if (response !== null) { console.log('JSON.stringify(response)' + JSON.stringify(response)); } else { console.log('Error in openSobjectSubTabIdApi' + JSON.stringify(response)); } }); }, // Do not call this function from your controller. Used internally by the helper. openSobjectSubTabPromise: function(component, recordId, primarytabId) { return new Promise(function(resolve, reject) { var workspaceApi = component.find("workspace"); var urlString = '#/sObject/' + recordId + '/view'; workspaceApi.openSubtab({ parentTabId: primarytabId, url: urlString, focus: true }).then(function(response) { if (response !== null) { console.log('JSON.stringify(response)' + JSON.stringify(response)); resolve(response); } else { console.log('Error in openSubtabcallback' + JSON.stringify(response)); reject(Error("Error message: " + JSON.stringify(response))); } }); }); }, // Do not call this method from your controller. Used internally by the helper. getTabInfo: function(component, callback, recordId) { var workspaceApi = component.find("workspace"); workspaceApi.getFocusedTabInfo().then(function(response) { debugger; if (response !== null) { if (typeof(recordId) !== "undefined") { debugger; callback(component, recordId); } else if (typeof(response.title) !== "undefined" && response.title === "Loading..." && typeof(response.customTitle) === "undefined") { if (component.get("v.tabinfo") === undefined || component.get("v.tabinfo") === null) { debugger; component.set("v.tabinfo", response); } if (typeof(callback) != "undefined") { debugger; component.set("v.tabinfo", response); callback(component); } } } else { console.log('Error in getFocusedTabInfocallback'); } }); } })
import React, {Component} from 'react'; import styles from '@/web-client/components/LoginForm/LoginForm.css'; import {Button, ButtonThemes} from '@/web-client/components/Button'; export default class LoginForm extends Component { constructor (props) { super(props); this.formElements = {}; } render () { return ( <form onSubmit={this.onSubmitForm.bind(this)}> <select className={styles.select} ref={this.referenceElement.bind(this)} name="username" onChange={this.onChangeUsernameSelect.bind(this)} > <option value="">- Select User -</option> <option value="store-owner" password="password">Store Owner</option> </select> <input type="hidden" name="password" ref={this.referenceElement.bind(this)} /> <Button theme={ButtonThemes.ENCOURAGING} className={styles.submitButton} type="submit">Login</Button> </form> ); } onChangeUsernameSelect (event) { const selectElement = event.currentTarget;//.querySelector('opt'); const value = selectElement.value; const optionElement = selectElement.querySelector(`option[value="${value}"]`); this.formElements.password.value = optionElement.getAttribute('password'); } onSubmitForm (event) { event.preventDefault(); const {onSubmit} = this.props; const values = {}; for (let key of Object.keys(this.formElements)) { const element = this.formElements[key]; let value = element.value; if (element.getAttribute('type') === 'number') { value = Number.parseInt(value); } values[key] = value; } onSubmit(values); } referenceElement (element) { if (!element) return; const name = element.getAttribute('name'); this.formElements[name] = element; const {defaultValues = {}} = this.props; if (defaultValues[name]) { element.value = defaultValues[name]; } } }
import React from 'react'; import './Header.css'; const Header = () => { return ( <header className="container header_container"> <a href="/"><img src="/images/logo.png" alt="Gatry" /></a> <h1><a href="/">Gatry</a></h1> </header> ); } export default Header;
function doFirst() { barSize = 100; myMovie = document.getElementById(myMovie); playButton = document.getElementById(playButton); bar = document.getElementById(defaultBar); progressBar = document.getElementById(progressBar); playButton.addEventListener('click', playOrPause, false); bar.addEventListener('click', clickedBar, false); } function playOrPause() { if (!myMovie.paused && !myMovie.ended) { myMovie.pause(); playButton.innerHTML = 'Play' window.clearInterval(updateBar); } else { myMovie.play(); playButton.innerHTML = 'Pause' updateBar = setInterval(update, 500); } } function update() { if(!myMovie.ended) { var size = parseInt(myMovie.currentTime * barSize / myMovie.drration); progressBar.style.with=size+'px'; }else{ progressBar.style.with='0px'; playButton.innerHTML='Play'; window.clearInterval(updateBar); } } function clickedBar(e){ if(!myMovie.paused && !myMovie.ended){ var mouseX=e.pageX-bar.offsetLeft; var newtime=mouseX*myMovie.duration/barSize; myMovie.currentTime=newtime; progressBar.style.width=mouseX+'px'; } } window.addEventListener('load', doFirst,false);
class KaInclude extends KtRenderable { constructor() { super(); this._attrs = { "src": null, "auto": null, "raw": null, "debug": false } } static get observedAttributes() { return ["src", "debug", "auto", "raw"]; } /** * <script> tags that were loaded via ajax won't be executed * when added to dom. * * Therefore we have to rewrite them. This method does this * automatically both for normal and for template (content) nodes. * * @param node * @private */ _importScritpRecursive(node) { let chels = node instanceof HTMLTemplateElement ? node.content.childNodes : node.childNodes; for (let s of chels) { if (s.tagName !== "SCRIPT") { this._importScritpRecursive(s); continue; } let n = document.createElement("script"); n.innerHTML = s.innerHTML; s.replaceWith(n); } } _loadDataRemote() { let xhttp = new XMLHttpRequest(); xhttp.open("GET", this._attrs.src); xhttp.onreadystatechange = () => { if (xhttp.readyState === 4) { if (xhttp.status >= 400) { console.warn("Can't load '" + this.params.src + "': " + xhttp.responseText); return; } this.innerHTML = xhttp.responseText; if (this._attrs.raw !== null) { let p = new KtTemplateParser(); p.parseRecursive(this.content); } // Nodes loaded from remote won't get executed. So import them. this._importScritpRecursive(this.content); this._appendElementsToParent(); for (let el of this._els) { this._log("trigger DOMContentLoaded event on", el); el.dispatchEvent(new Event("DOMContentLoaded")); } return; } }; xhttp.send(); } disconnectedCallback() { for (let el of this._els) this.parentElement.removeChild(el); } connectedCallback() { let auto = this.getAttribute("auto"); if (auto !== null) { if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", () => { this._loadDataRemote(); }); } else { this._loadDataRemote(); } } } render(context) { if (this._els === null) this._appendElementsToParent(); } } customElements.define("ka-include", KaInclude, {extends: "template"});
import React, { Component } from 'react'; import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native'; import { Icon, CheckBox, Button } from 'react-native-elements'; import { Actions } from 'react-native-router-flux'; import { addFriend, acceptFriend, declineFriend } from '../../services/apiActions'; // export class FriendDetail extends Component { constructor(props) { super(props); this.state = { checked: false }; this.addFriendToDatabase = this.addFriendToDatabase.bind(this); this.denyFriendRequest = this.denyFriendRequest.bind(this); this.acceptFriendRequest = this.acceptFriendRequest.bind(this); this.addToGroup = this.addToGroup.bind(this); } addFriendToDatabase(friend) { addFriend(friend) .then((resp) => console.log('ADDED FRIEND', resp)) .catch((err) => console.error('NO ADD FRIEND', err)); } goToProfile(friend) { Actions.profile({person: friend}); } acceptFriendRequest(friend) { console.log("ACCEPT FRIEND", friend) acceptFriend(friend) .then((yay) => console.log("ACCEPTED", yay)) .catch(err => console.log('nOOOOO ', err)) } denyFriendRequest(friend) { console.log("DENIED", friend) declineFriend(friend) .then((yay) => console.log("DECLINE", yay)) .catch(err => console.log('nOOOOO ', err)) } renderCheckBox(friend) { return ( <CheckBox checked={this.state.checked} onPress={ _ => { friend.invited = !this.state.checked this.setState({ checked: !this.state.checked }) }} /> ); } addToGroup(friend) { return ( <CheckBox checked={this.state.checked} onPress={ _ => { friend.invited = !this.state.checked this.setState({ checked: !this.state.checked }) console.log("ON CHECK", friend) }} /> ); } render() { const friend = this.props.friend; return ( <View style={styles.friendItem}> <Image source={{ uri: friend.photo_url || null }} style={styles.photo} /> <View style={styles.textContainer}> <TouchableOpacity onPress={() => this.goToProfile(friend)}> <Text style={styles.text}> {`${friend.first_name} ${friend.last_name}`} </Text> </TouchableOpacity> { friend.search && <View style={styles.addFriend}> <Button buttonStyle={styles.acceptJoinGroupRequestButton} title="Add" icon={{name: 'add', color: '#4296CC'}} backgroundColor='#FFF' color='#4296CC' borderRadius={1} /> </View> } { friend.pending && <View style={styles.acceptFriend}> <Icon name='x' color='red' onPress={() => this.denyFriendRequest(friend)} /> <Icon name='add' color="#4296CC" onPress={() => this.acceptFriendRequest(friend)} /> </View> } { this.props.isGroup && this.renderCheckBox(friend) } { friend.isGroup && this.addToGroup(friend) } </View> </View> ); } } const styles = StyleSheet.create({ friendItem: { height: 45, flexDirection: 'row', marginLeft: 10, marginTop: 7, marginBottom: 5, }, photo: { height: 40, width: 40, borderRadius: 20, }, textContainer: { marginLeft: 5, marginTop: 10, flexDirection: 'row', alignSelf: 'flex-start' }, text: { marginLeft: 8, fontSize: 16, color: '#4296CC', fontWeight: '500' }, checkboxContainer: { flex: 1, alignSelf: 'stretch' }, acceptFriend: { alignItems: 'flex-end', flexDirection: 'row', }, acceptJoinGroupRequestButton: { borderWidth: 1, borderColor: '#4296CC', alignSelf: 'flex-end' }, acceptJoinPlus: { color: '#4296CC', backgroundColor: '#4296CC' }, });
$('#button').click(function(){ $downloadImages($('#input').val()); } ); $downloadImages = function(input){ //Procura a API do artista input.replace(' ', '+'); var link = 'https://api.spotify.com/v1/search?query='+ input +'&type=artist'; //Recebe o ID do artista $.get(link).done(function(data){ var id = data.artists.items[0].id; var link = 'https://api.spotify.com/v1/artists/'+ id +'/albums?limit=50'; //Limpa H1 e mostra as imagens da banda atual $.get(link).done(function(data){ var images = data.items; $('h1').empty(); images.forEach(function(elem){ $('h1').append($('<img>').attr('src', elem.images[1].url).attr('alt', input)); }); }); }); };
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; const WIN_AT = 5; class Square extends React.Component { render() { return ( <button className="square" onClick={() => this.props.onClick()} > {this.props.value} </button> ); } } class Board extends React.Component { getBoardSize() { return Math.sqrt(this.props.squares.length); } renderSquare(i) { return ( <Square value={this.props.squares[i]} key={i} onClick={() => this.props.onClick(i)} /> ); } renderRow(i) { let boardSize = this.getBoardSize() let squares = Array(boardSize) for (let j = 0; j < boardSize; j++) { squares[j] = this.renderSquare(boardSize * i + j) } return ( <div className="board-row" key={i}> {squares} </div> ) } render() { let boardSize = this.getBoardSize() let rows = [] for (let i = 0; i < boardSize; i++) { let row = this.renderRow(i) rows.push(row) } return ( <div> {/* <div className="status">{status}</div> */} {rows} </div> ); } } class Game extends React.Component { constructor(props) { super(props); this.state = { boardSize: 10, history: [{ squares: Array(10 ** 2).fill(null) }], stepNumber: 0, xIsNext: true, }; } handleClick(i) { const history = this.state.history.slice(0, this.state.stepNumber + 1); const current = history[history.length - 1]; const squares = current.squares.slice() if (calculateWinner(squares) || squares[i]) { return } squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState({ history: history.concat([{ squares: squares, }]), stepNumber: history.length, xIsNext: !this.state.xIsNext, }); } jumpTo(step) { this.setState({ stepNumber: step, xIsNext: (step % 2) === 0, }) } handleValueChange(event) { let {value, min, max} = event.target value = Math.max(Number(min), Math.min(Number(max), Number(value))) value = Math.trunc(value) console.log(`current value ${value}`) this.setState({ history: [{ squares: Array(value ** 2).fill(null) }], stepNumber: 0, xIsNext: true, boardSize:value?value:"", }) } render() { const history = this.state.history; const current = history[this.state.stepNumber]; const winner = calculateWinner(current.squares); const moves = history.map((_, move) => { const desc = move ? `Go to move #${move}` : `Go to game start`; return ( <li key={move}> <button onClick={() => this.jumpTo(move)}> {desc} </button> </li> ); }); let status; if (winner) { status = 'Winner: ' + winner; } else { status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O'); } console.log(`current + ${current.squares}`) return ( <div className="game"> <div className="game-board"> <Board squares={current.squares} onClick={(i) => this.handleClick(i)} /> </div> <div className="game-info"> <label> Board Size: </label> <input value={this.state.boardSize} onChange={(event) => this.handleValueChange(event)} type="number" min="0" max="20" /> <div>{status}</div> <ol>{moves}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') ); function updateLongest(longestVal, longest, currentCount, cVal) { longestVal = longest < currentCount ? cVal : longestVal; longest = longest < currentCount ? currentCount : longest; return { longestVal, longest }; } function countConsecutiveIdenticalValues(aArray) { let currentCount = 0; let longest = 0; let longestVal = null; for (let i = 0; i < aArray.length; i++) { let cVal = aArray[i]; if (cVal != null) { if (cVal === aArray[i - 1]) { currentCount++; ({ longestVal, longest } = updateLongest(longestVal, longest, currentCount, cVal)); } else { ({ longestVal, longest } = updateLongest(longestVal, longest, currentCount, cVal)); currentCount = 1; } } else { ({ longestVal, longest } = updateLongest(longestVal, longest, currentCount, cVal)); currentCount = 1; } } return { longest, longestVal }; } function checkRow(squares) { let size = Math.sqrt(squares.length) for (let ridx = 0; ridx < size; ridx++) { let rowSquares = squares.slice(ridx * size, (ridx + 1) * size) let { longest, longestVal } = countConsecutiveIdenticalValues(rowSquares) if (longest === WIN_AT) { return longestVal } } } function checkColumn(squares) { let size = Math.sqrt(squares.length) for (let cidx = 0; cidx < size; cidx++) { let colSquares = Array(size).fill(null) for (let ridx = 0; ridx < size; ridx++) { colSquares[ridx] = squares[cidx + ridx * size] } let { longest, longestVal } = countConsecutiveIdenticalValues(colSquares) if (longest == 5) { return longestVal } } } function generateTLRBiagonals(size) { let diags = [] for (let s = 0; s < 2 * size - 1; s++) { let diag = [] for (let cidx = 0; cidx < size; cidx++) { for (let ridx = size - 1; ridx >= 0; ridx--) { if (cidx + ridx === s) { diag.push([cidx, ridx]) } } } diags.push(diag) } return diags } function generateBLTRDiagonals(size) { let diags = [] for (let d = -(size - 1); d < size; d++) { let diag = [] for (let cidx = 0; cidx < size; cidx++) { for (let ridx = 0; ridx < size; ridx++) { if (cidx - ridx === d) { diag.push([cidx, ridx]) } } } diags.push(diag) } return diags } function checkDiagonal(squares) { let size = Math.sqrt(squares.length); let idxDiags = generateBLTRDiagonals(size); idxDiags.push(...generateTLRBiagonals(size)) for (let i = 0; i < idxDiags.length; i++) { let diag = idxDiags[i].map((idx) => { let [cidx, ridx] = idx; return squares[cidx + ridx * size] }); let { longest, longestVal } = countConsecutiveIdenticalValues(diag) if (longest === 5) { return longestVal } } } function calculateWinner(squares) { console.time("checkWinner") let longestVal = checkRow(squares) if (longestVal == null) { longestVal = checkColumn(squares) if (longestVal == null) { longestVal = checkDiagonal(squares) } } console.timeEnd("checkWinner") return longestVal; }
/* tabSingleSelect.js js script for handling a ajax tab single select control bchapman may 2010 mods bchapman 12/3/11 Include search function (782) bchapman 25/06/11 allow setting of external control to selected tabid */ var registeredControls = [{}]; //empty json array var ifty_tss_delay = (function() { var timer = 0; return function(callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); var ifty_tss = function () { return { //registerControl : run on page load and remembers control containerId and ajaxHandler Path, //as well as hooking the events registerControl: function (strAjaxHandler, strContainerId, blnAutoPostback, strTabIdFieldId) { var control = { ajaxHandler: strAjaxHandler, containerId: strContainerId, autoPostback: blnAutoPostback, tabIdFieldId: strTabIdFieldId }; registeredControls.push(control); ifty_tss.hookControlEvents(control); }, //reHookAllEvents : run through all registered control and re-hook the events reHookAllEvents: function () { //loop through the registered controls for (var i = 0; i < registeredControls.length; i++) { ifty_tss.hookControlEvents(registeredControls[i]); } }, //hookControlEvents : setups jQuery event handlers for the various controls in the page list. hookControlEvents: function (control) { //listbox select and change / keypress var lstTabsId = control.containerId + '_lstTabs'; var changeHandler = function () { ifty_tss.setSelTabId(this, control.containerId, control.tabIdFieldId); if (control.autoPostback == "True") { var dollarCtlId = ifty_tss.idWithDollars(control.containerId, 'lstTabs'); //call asp.net postback control function __doPostBack(dollarCtlId, ''); } } jQuery('#' + lstTabsId).change(changeHandler).keypress(changeHandler); //first link jQuery('#' + control.containerId + '_hlFirst').click(function () { ifty_tss.showPage(control.ajaxHandler, control.containerId, "first"); return false; }); //prev link jQuery('#' + control.containerId + '_hlPrev').click(function () { ifty_tss.showPage(control.ajaxHandler, control.containerId, "prev"); return false; }); //next link jQuery('#' + control.containerId + '_hlNext').click(function () { ifty_tss.showPage(control.ajaxHandler, control.containerId, "next"); return false; }); //last link jQuery('#' + control.containerId + '_hlLast').click(function () { ifty_tss.showPage(control.ajaxHandler, control.containerId, "last"); return false; }); //782 : new search function //search link jQuery('#' + control.containerId + '_hlSearch').click(function () { ifty_tss.showPage(control.ajaxHandler, control.containerId, "search"); return false; }); //press enter on search box jQuery('#' + control.containerId + '_txtSearchString').bind('keydown', function (e) { var code = e.keyCode || e.which; if (code == 13) //enter { e.preventDefault(); ifty_tss.showPage(control.ajaxHandler, control.containerId, "search"); return false; } else { //all other keystrokes ifty_tss_delay(function () { ifty_tss.showPage(control.ajaxHandler, control.containerId, "search"); }, 700); } }); }, //showPage : main function for displaying the list of tabs showPage: function (ajaxHandler, containerId, pagerVal, listbox) { //prepare the modal overlay var tabsContainerId = containerId + '_tabsContainer'; var src = jQuery('.tss_loadingImg').attr('src'); //make the overlay, well, overlay jQuery('#' + tabsContainerId).block({ message: '<img src="' + src + '" alt=".....">', css: { cursor: 'wait', border: '2px solid #efefef', backgroundColor: 'white' }, overlayCSS: { backgroundColor: 'white', opacity: 0.6 } }); //find the options configured for this tabs list instance var options = ifty_tss.getPagingOptions(containerId); var listbox = jQuery('#' + containerId + '_lstTabs')[0]; //get the json data for the paging var data; jQuery.getJSON(ajaxHandler, { page: +options.curPage.toString(), pager: pagerVal, pageSize: options.pageSize, showAdmin: options.showAdmin, showHost: options.showHost, showDeleted: options.showDeleted, showExpired: options.showExpired, pages: options.numPages, portalid: options.portalid, search: options.search } , function (data) { //iterate the collection and add the items ifty_tss.buildList(data, listbox, options.selTabId); //set the current to the result options.curPage = data.page; options.numPages = data.numPages; //save the options data back ifty_tss.saveOptions(options, containerId); //set the label (page x of y) var lblPages = jQuery('#' + containerId + '_lblPages'); lblPages.html(data.page.toString() + '/' + data.numPages.toString()); }); //remove the modal overlay jQuery('#' + tabsContainerId).unblock(); }, //list control functions addItemToList: function (listbox, text, value, isSelected) { //adds an item to a listbox var item = document.createElement("option"); item.text = text; item.value = value; if (isSelected) item.selected = 'selected'; listbox.options.add(item); }, clearList: function (listbox) { //removes all items from a listbox listbox.options.length = 0; }, buildList: function (data, listbox, selTabId) { //clear the listbox ifty_tss.clearList(listbox); for (var i = 0; i < data.tabs.length; i++) { var tab = data.tabs[i]; var isSelected = (selTabId == tab.tabid); ifty_tss.addItemToList(listbox, tab.tabname, tab.tabid, isSelected); } }, setSelTabId: function (lstTabs, containerId, tabIdFieldId) { //set the selected tab var options = ifty_tss.getPagingOptions(containerId); var selIndex = lstTabs.options.selectedIndex; var hiddenTabIdFieldFound = false; if (tabIdFieldId != '') { //look for field var hiddenFieldjQ = jQuery('#' + tabIdFieldId); if (hiddenFieldjQ.length) { hiddenTabIdFieldFound = true; } } if (selIndex > -1) { var selTabId = lstTabs.options[selIndex].value options.selTabId = selTabId; ifty_tss.saveOptions(options, containerId); if (hiddenTabIdFieldFound) { //exists, so set value to selTabId var pageName = lstTabs.options[selIndex].text; pageName = pageName.replace(/\.\.\./g, ''); //replace leading ... characters hiddenFieldjQ.val(selTabId + ':' + pageName).change(); } } else { //no selection if (hiddenTabIdFieldFound) { //exists, so set value to selTabId hiddenFieldjQ.val(-1 + ':'); } } }, //getPagingOptions : retrives the current options from the hidden field in the control getPagingOptions: function (containerId) { var options = jQuery('#' + containerId + '_hdnOptions').val(); var optionsArr = options.split(':', 10); var optionData = { 'selTabId': optionsArr[0], 'pageSize': optionsArr[1], 'showAdmin': optionsArr[2], 'showHost': optionsArr[3], 'showDeleted': optionsArr[4], 'showExpired': optionsArr[5], 'numPages': optionsArr[6], 'curPage': optionsArr[7], 'portalid': optionsArr[8], 'search': optionsArr[9] }; //overwrite the search data with the value from the search box, if it exists var searchVal = jQuery('#' + containerId + '_txtSearchString').val(); if (optionData.search != searchVal) optionData.search = searchVal; return optionData; }, //saveOptions : saves the current options back into the hidden field in the control saveOptions: function (optionData, containerId) { //writes the options back to the hidden field var data = optionData.selTabId.toString() + ':' + optionData.pageSize.toString() + ':' + optionData.showAdmin.toString() + ':' + optionData.showHost.toString() + ':' + optionData.showDeleted.toString() + ':' + optionData.showExpired + ':' + optionData.numPages + ':' + optionData.curPage.toString() + ':' + optionData.portalid.toString() + ':' + optionData.search; var options = jQuery('#' + containerId + '_hdnOptions'); options.val(data); //save back to hidden field }, idWithDollars: function (containerid, id) { var id = containerid + '_' + id; var did = id.replace(/_/gi, '$'); return did; } }; } ();
import React, { useEffect, useState } from "react"; import { Link, useHistory, useParams } from "react-router-dom"; import Grid from "@material-ui/core/Grid"; import Button from "@material-ui/core/Button"; import Typography from "@material-ui/core/Typography"; import CreateRoomPage from "./CreateRoomPage"; function Room({ clearRoomCode }) { const [votesToSkip, setVotesToSkip] = useState(2); const [guestCanPause, setGuestCanPause] = useState(false); const [isHost, setIsHost] = useState(false); const [showSettings, setShowSettings] = useState(false); const [spotifyAuthenticated, setSpotifyAuthenticated] = useState(false) const history = useHistory(); const { roomCode } = useParams(); useEffect(() => { fetch(`/api/get-room?code=${roomCode}`) .then((res) => { if (!res.ok) { console.log("room code not ok"); clearRoomCode(); history.push("/"); } console.log("room code ok"); return res.json(); }) .then((data) => { console.log("data: ", data); setVotesToSkip(data.votes_to_skip); setGuestCanPause(data.guest_can_pause); setIsHost(data.is_host); if(data.is_host) { console.log("calling authenticate") authenticateSpotify() } }); }, []); const leaveRoom = () => { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, }; fetch("/api/leave-room", requestOptions).then((_res) => { clearRoomCode(); history.push("/"); }); }; const updateShowSettings = (val) => { setShowSettings(val); }; const authenticateSpotify = () => { fetch('/spotify/is-authenticated') .then((res) => res.json()) .then((data) => { setSpotifyAuthenticated(data.status) //in case not authenticated, we authenticate if(!data.status) { fetch('/spotify/get-auth-url') .then((res) => res.json()) .then((data) => { window.location.replace(data.url) }) } }) } if (showSettings) { return ( <Grid container spacing={1}> <Grid item align="center" xs={12}> <CreateRoomPage update={true} votes_to_skip={votesToSkip} guest_can_pause={guestCanPause} setGuestCanPause={setGuestCanPause} setVotesToSkip={setVotesToSkip} roomCode={roomCode} updateCallback={() => {}} /> </Grid> <Grid item align="center" xs={12}> <Button variant="contained" color="secondary" onClick={() => updateShowSettings(false)} > Close </Button> </Grid> <Grid item align="center" xs={12}></Grid> </Grid> ); } else { return ( <Grid container spacing={1}> <Grid item xs={12} align="center"> <Typography variant="h4" component="h4"> Code: {roomCode} </Typography> </Grid> <Grid item xs={12} align="center"> <Typography variant="h6" component="h6"> Votes: {votesToSkip} </Typography> </Grid> <Grid item xs={12} align="center"> <Typography variant="h6" component="h6"> Guest can pause: {guestCanPause.toString()} </Typography> </Grid> <Grid item xs={12} align="center"> <Typography variant="h6" component="h6"> Host: {isHost.toString()} </Typography> </Grid> <Grid container justify="space-around" style={{ height: 50 }}> {isHost && ( <Button variant="contained" color="secondary" onClick={() => updateShowSettings(true)} > Settings </Button> )} <Button variant="contained" color="secondary" onClick={() => leaveRoom()} > Leave room </Button> </Grid> </Grid> ); } } export default Room;
import React, { useState } from 'react' import { withRouter } from 'react-router-dom' import { parse as sherlock } from 'sherlockjs' import { DateTime } from 'luxon' import { formatTimezoneName } from '~/helpers/getUserTimezone' import { timestampToParameter } from '~/helpers/timeParameter' import LayoutGradient from '~/components/LayoutGradient' import TextInput from '~/components/TextInput' import Button from '~/components/Button' const PageCreateEvent = props => { const [eventTime, setEventTime] = useState('') const [eventName, setEventName] = useState('') const [eventTimeError, setEventTimeError] = useState('') const timezone = formatTimezoneName(props.timezone) const handleSubmit = event => { event.preventDefault() const { startDate } = sherlock(eventTime) const eventTimestamp = DateTime.fromJSDate(startDate, { zone: props.timezone }).toMillis() if (startDate) { // react-router only exposes an imperative API. // eslint-disable-next-line fp/no-mutating-methods props.history.push({ pathname: `/share/${timestampToParameter(eventTimestamp)}/${eventName}` }) } else { setEventTimeError('Please double check the format') } } return ( <LayoutGradient backgroundTime={Date.now()}> <form onSubmit={handleSubmit}> <h2>When is the event?</h2> <p> In your local time zone ({timezone} ). </p> <TextInput required name="eventTime" value={eventTime} onChange={({ target: { value } }) => { setEventTime(value) setEventTimeError('') }} placeholder="e.g. Wednesday at 7pm" error={eventTimeError} marginBottom="30px" /> <h2>{"What's the name of the event?"}</h2> <TextInput name="eventName" value={eventName} onChange={({ target: { value } }) => setEventName(value)} placeholder="e.g. Juliette's Webinar" marginBottom="40px" /> <br /> <Button as="button" type="submit"> Create Event </Button> </form> </LayoutGradient> ) } export default withRouter(PageCreateEvent)
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ /** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ 'use strict'; define(['ojs/ojcore', 'knockout', 'jquery', 'dataService', 'appController', 'ojs/ojknockout', 'ojs/ojlistview'], function(oj, ko, $, data, app) { function driverDetailsViewModel() { var self = this; self.driverData = ko.observable(); app.refreshDriver = function (response) { var driverData = JSON.parse(response); driverData.statusSelection = ko.observableArray([driverData.status]); driverData.prioritySelection = ko.observableArray([driverData.priority]); self.driverData(driverData); }; self.handleActivated = function(params) { var parentRouter = params.valueAccessor().params['ojRouter']['parentRouter']; self.router = parentRouter.createChildRouter('driver').configure(function(stateId) { if(stateId) { var state = new oj.RouterState(stateId, { enter: function () { data.getDriver(stateId).then(function(response) { var driverData = JSON.parse(response); driverData.statusSelection = ko.observableArray([driverData.status]); driverData.prioritySelection = ko.observableArray([driverData.priority]); self.driverData(driverData); }); } }); return state; } }); return oj.Router.sync(); }; self.dispose = function(info) { self.router.dispose(); }; self.locationId = ko.computed(function() { if (self.driverData()) { return self.driverData().locationId; } }); // update incident when status or priority changes self.updateDriver = function(id, driver) { data.updateDriver(id, driver).then(function(response){ // update success }).fail(function(response) { oj.Logger.error('Failed to update incident.', response); }); }; // priority selection change self.priorityChange = function(event, data) { updatePriorityStatus('priority', data); }; // status selection change self.statusChange = function(event, data) { updatePriorityStatus('status', data); }; function updatePriorityStatus(option, data) { if(data.option === "value") { if(data.value) { var driver = {}; driver[option] = data.value; self.updateDriver(self.router.stateId(), driver); } } } // adjust content padding top self.handleAttached = function(info) { app.appUtilities.adjustContentPadding(); }; self.handleBindingsApplied = function(info) { if (app.pendingAnimationType === 'navParent' || app.pendingAnimationType === 'navChild') { app.preDrill(); } }; self.handleTransitionCompleted = function(info) { if (app.pendingAnimationType === 'navParent' || app.pendingAnimationType === 'navChild') { app.postDrill(); } }; // trigger click when selection changes self.optionChange = function (event, ui) { if(ui.option === 'selection') { $(ui.items[0]).trigger('click'); } }; var categoryDic = {'appliance': 'Notificação entregue fora do prazo', 'electrical': 'Aferição do Radar / Balança', 'heatingcooling': 'Outros', 'plumbing': 'Outros', 'general': 'Falta de sinalização'}; self.categoryLabel = function(categoryID) { return categoryDic[categoryID]; }; var statusDic = {'accepted': 'Deferido', 'open': 'Em Análise', 'closed': 'Indeferido'}; self.statusLabel = function(statusID) { return statusDic[statusID]; }; var leftClickAction = function() { //if(self.editMode()) { // self.revertCustomerData(); // self.editMode(false); //} else { app.pendingAnimationType = 'navParent'; window.history.back(); //} }; var rightClickAction = function() { //if(self.editMode()) { // self.updateCustomerData(); // self.editMode(false); //} else { // self.editMode(true); //} }; var rightBtnLabel = ko.computed(function() { //if(self.editMode()) { // return 'Save'; //} else { // return 'Edit'; //} }); var leftBtnLabel = ko.computed(function() { //if(self.editMode()) { // return 'Cancel'; //} else { return 'Back'; //} }); // customer details page header self.driverDetailsHeaderSettings = { name:'basicHeader', params: { title: 'Indicação de Condutor Infrator', startBtn: { id: 'backBtn', click: leftClickAction, display: 'icons', label: leftBtnLabel, icons: {start:'oj-hybrid-applayout-header-icon-back oj-fwk-icon'}, visible: true }, endBtn: { id: 'nextBtn', click: rightClickAction, display: 'all', label: rightBtnLabel, icons: {}, visible: true, disabled: false } } }; } return driverDetailsViewModel; });
/*************************************** * Tip Calculator Write a function tipAmount that is given the bill amount and the level of service (one of good, fair and poor) and returns the dollar amount for the tip. Based on: good -> 20% fair -> 15% bad -> 10% > tipAmount(100, 'good') 20 > tipAmount(40, 'fair') 6 */ function tipAmount(bill,service){ if (service === 'good') { return 'The tip is $' + bill * .20 // returns 20% of the bill } else if (service === 'fair') { return 'The tip is $' + bill * .15 // returns 15% of the bill } else if (service === 'bad') { return 'The tip is $' + bill * .10 // returns 10% of the bill } else { return bill * 0; // assuming there's no tip } } console.log(tipAmount(10,'good')); /*************************************** * Write a function totalAmount that takes the same arguments as tipAmount except it returns the total as the tip amount plus the bill amount. This function may make use of tipAmount as a sub-task. > totalAmount(100, 'good') 120 > totalAmount(40, 'fair') 46 */ function totalAmount(bill,service) { return bill + tipAmount(bill, service); /* if (service === 'good') { tipAmount = bill * .20; // declares tipAmount; 20% of the bill total = bill + tipAmount; // declares total; addition of the bill and tipAmount return 'The total bill is $' + total; } else if (service === 'fair') { tipAmount = bill * .15; total = bill + tipAmount; return 'The total bill is $' + total; } else if (service === 'bad') { tipAmount = bill * .10; total = bill + tipAmount; return 'The total bill is $' + total; } else { tipAmount = bill * 0; total = bill + tipAmount; return 'The total bill is $' + total; } */ } /*************************************** * Tip Calculator 3 Write a function splitAmount that takes the bill amount and the level of service, and the number of people to split the bill between. It will return the final amount for each person. > splitAmount(100, 'good', 5) 24 > splitAmount(40, 'fair', 2) 23 */ function splitAmount(bill,service,people) { return totalAmount(bill, service) / people /* if (service === 'good') { tipAmount = bill * .20; total = bill + tipAmount; perPerson = total / people; return 'The total per person is $' + perPerson; } else if (service === 'fair') { tipAmount = bill * .15; total = bill + tipAmount; perPerson = total / people; return 'The total per person is $' + perPerson; } else if(service === 'bad') { tipAmount = bill * .10; total = bill + tipAmount; perPerson = total / people; return 'The total per person is $' + perPerson; } else { tipAmount = bill * .20; total = bill + tipAmount; perPerson = total / people; return 'The total per person is $' + perPerson; } */ } console.log(splitAmount(100,'good',5));
import React, { forwardRef, useImperativeHandle, useState, useEffect, } from 'react'; import {View, StyleSheet, ToastAndroid, Button, StatusBar} from 'react-native'; // const Toast = ({visible, message}) => { if (visible) { ToastAndroid.show(message, ToastAndroid.SHORT); return null; } return null; }; // const ToastMsg = forwardRef((props, ref) => { useImperativeHandle(ref, () => ({ handleToastButtonPress() { setvisibleToast(true); }, })); // const [visibleToast, setvisibleToast] = useState(false); // useEffect(() => setvisibleToast(false), [visibleToast]); // return ( <> <Toast visible={visibleToast} message={props.msg} /> </> ); }); // styling const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: StatusBar.currentHeight, backgroundColor: '#888888', padding: 8, }, }); export default ToastMsg;
import { Container } from "@material-ui/core"; import { NextSeo } from "next-seo"; import FutureOfPrint from "../Component/HomePage/FutureOfPrint"; import HomeHero from "../Component/HomePage/Hero"; import MilkyWay from "../Component/HomePage/MilkyWay"; import OurPartner from "../Component/HomePage/OurPartner"; import ProductMap from "../Component/HomePage/ProductMap"; import Testimonials from "../Component/HomePage/Testimonials"; const Index = () => { return ( <> <NextSeo title="Print MIS | Print Workflow | Print Estimating Software | printIQ" description="printIQ is a cloud-based management workflow system. You get a seamless, end-to-end estimating, ordering, and production workflow system." openGraph={{ url: "https://www.printiq.com/", title: "printIQ Far more than just an MIS", description: "printIQ is a cloud-based management workflow system. You get a seamless, end-to-end estimating, ordering, and production workflow system.", images: [ { url: "https://iq-website.vercel.app/images/homepage/printIQ-Universe2020-map.jpg", width: 800, height: 600, alt: "printIQ product Map", }, ], locale: "en_US", }} twitter={{ handle: "https://www.printiq.com/", site: "@printIQGlobal", cardType: "summary_large_image", }} /> <HomeHero /> <ProductMap /> <MilkyWay /> <FutureOfPrint /> <OurPartner /> <Testimonials /> </> ); }; export default Index;
'use strict' import compression from 'compression' import config from 'config' import express from 'express' import expressWs from '@joepie91/express-ws' // todo by default we want use express-ws import morgan from 'morgan' import nodeDebug from 'debug' import swig from 'swig' import path from 'path' import Promise from 'bluebird' import middlewares from './middlewares' import routes from './routes' const debug = nodeDebug('tweetwall:app') const {host, port} = config.get('tweetwall.app') const app = Promise.promisifyAll(express()) expressWs(app) app.engine('html', swig.renderFile) app.set('view engine', 'html') app.set('views', path.resolve(__dirname, '../../views')) app.use(compression()) app.use(morgan('dev')) app.use(express.static(path.resolve(__dirname, '../../public'))) app.use('/', middlewares(), routes()) app.listenAsync(port, host) .then(() => debug(`Server started, check '${host}:${port}'`)) .catch((err) => debug('An error occurred during server startup: %s %j', err, err))
import * as THREE from "three"; export function convertToSphericalUV(geometry) { // This function is based on the code found at (the original source doesn't work well) // http://stackoverflow.com/questions/20774648/three-js-generate-uv-coordinate // // She following page explains how UV map should be calculated // https://solutiondesign.com/blog/-/blogs/webgl-and-three-js-texture-mappi-1/ // // The following documentation shows what a apherical UV map should look like // https://threejs.org/examples/#misc_uv_tests // converting all vertices into polar coordinates var polarVertices = geometry.vertices.map(cartesian2polar); geometry.faceVertexUvs[0] = []; // This clears out any UV mapping that may have already existed on the object // walking through all the faces defined by the object // ... we need to define a UV map for each of them geometry.faces.forEach(function (face) { var uvs = []; // Each face is a triangle defined by three points or vertices (point a, b and c). // Instead of storing the three points (vertices) by itself, // a face uses points from the [vertices] array. // The 'a', 'b' and 'c' properties of the [face] object in fact represent // index at which each of the three points is stored in the [vertices] array var ids = ["a", "b", "c"]; for (var i = 0; i < ids.length; i++) { // using the point to access the vertice var vertexIndex = face[ids[i]]; var vertex = polarVertices[vertexIndex]; // If the vertice is located at the top or the bottom // of the sphere, the x coordinates will always be 0 // This isn't good, since it will make all the faces // which meet at this point use the same starting point // for their texture ... // this is a bit difficult to explainm, so try to comment out // the following block and take look at the top of the // spehere to see how it is mapped. Also have a look // at the following image: https://dev.ngit.hr/vr/textures/sphere-uv.png if (vertex.theta === 0 && (vertex.phi === 0 || vertex.phi === Math.PI)) { // at the sphere bottom and at the top different // points are alligned differently - have a look at the // following image https://dev.ngit.hr/vr/textures/sphere-uv.png var alignedVertice = vertex.phi === 0 ? face.b : face.a; vertex = { phi: vertex.phi, theta: polarVertices[alignedVertice].theta, }; } // Fixing vertices, which close the gap in the circle // These are the last vertices in a row, and are at identical position as // vertices which are at the first position in the row. // This causes the [theta] angle to be miscalculated if ( vertex.theta === Math.PI && cartesian2polar(face.normal).theta < Math.PI * 2 ) { vertex.theta = -Math.PI; } var canvasPoint = polar2canvas(vertex); uvs.push(new THREE.Vector2(1 - canvasPoint.x, 1 - canvasPoint.y)); } geometry.faceVertexUvs[0].push(uvs); }); geometry.uvsNeedUpdate = true; } function cartesian2polar(position) { var r = Math.sqrt( position.x * position.x + position.z * position.z + position.y * position.y ); return { r: r, phi: Math.acos(position.y / r), theta: Math.atan2(position.z, position.x), }; } function polar2cartesian(polar) { return { x: polar.distance * Math.cos(polar.radians), z: polar.distance * Math.sin(polar.radians), }; } function polar2canvas(polarPoint) { return { y: polarPoint.phi / Math.PI, x: (polarPoint.theta + Math.PI) / (2 * Math.PI), }; }
import './App.css'; import Home from './components/home.jsx'; import Port from './components/portfolio' import Err from './components/error' import About from './components/about' import { BrowserRouter as Router , Route , Switch } from 'react-router-dom' function App() { return ( <div className="App"> <Router> <Switch> <Route path="/" exact component={Home}/> <Route path="/port" component={Port}/> <Route component={Err}/> </Switch> </Router> </div> ); } export default App;
const express = require('express'); const parser = require('body-parser'); const cors = require('cors'); const mongoose = require('./db/book.js'); const Book = mongoose.model('Book'); const app = express(); app.set('port', process.env.PORT || 3001); app.use(parser.json()); app.use(cors()); app.get('/api/books', (req, res) => { Book.find() .then(books => { res.json(books); }) .catch(err => { console.log(err); }); }); app.post('/api/books', (req, res) => { Book.create(req.body) .then(books => { res.json(books); }) .catch(err => { console.log(err); }); }); app.get('/api/books/:id', (req, res) => { Book.findById(req.params.id) .then(book => { res.json(book); }) .catch(err => { console.log(err); }); }); app.put('/api/books/:id', (req, res) => { Book.findOneAndUpdate({ _id: req.params.id }, req.body, { new: true }) .then(book => { res.json(book); }) .catch(err => { console.log(err); }); }); app.delete('/api/books/:id', (req, res) => { Book.findOneAndRemove({ _id: req.params.id }) .then(book => { res.json(book); }) .catch(err => { console.log(err); }) }) app.listen(app.get('port'), () => { console.log('Server listening on port ' + app.get('port')); })
var containsDuplicate = function(nums) { //array of integers //if a number is there more than once, return true //if no numbers have any duplicates return nums.sort((a, b)=> a-b); for(let i=0; i<nums.length; i++){ if(nums[i]===nums[i+1]){ return true; } } return false; }; // Runtime: 84 ms, faster than 81.93% of JavaScript online submissions for Contains Duplicate. // Memory Usage: 42.7 MB, less than 81.55% of JavaScript online submissions for Contains Duplicate. //tried again 8/24 // /** // * @param {number[]} nums // * @return {boolean} // */ // var containsDuplicate = function(nums) { // let obj = {}; // for(let curr of nums){ // if(!obj[curr]){ // obj[curr] = 0; // obj[curr]++; // } // else if(obj[curr]){ // obj[curr]++; // if(obj[curr]>=2){ // return true; // } // } // } // return false; // } //faster than 68.25% // let set = new Set(nums); // console.log([...set]) // return [...set].length === nums.length? false : true //hoping it's wrong rn //faster than 23.64% of js subs // let obj = {}; // for(let curr of nums){ // if(!obj[curr]){ // obj[curr] = 0; // obj[curr]++ // } // else if (obj[curr]){ // obj[curr]++ // } // } // console.log(obj) // return Object.values(obj).some(a => a>1); // solution below is faster than 68.41% of JS // let arr = nums.sort((a, b) => a - b); // for(let i=0; i<arr.length; i++){ // if(arr[i]===arr[i+1]) return true; // } // return false; //};
import React from 'react' import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; import { usePoints } from '../context/pointContext'; const TotalPoints = ({showModal}) => { const {totalPoints} = usePoints() return ( <View style={styles.mainArea}> <Text style={styles.title}>Nkwa Points</Text> <Text style={styles.large}>{totalPoints}</Text> <Text style={styles.medium}>POINTS</Text> <TouchableOpacity style={styles.btn} onPress={showModal}> <Text style={styles.btnText}>Redeem Points</Text> </TouchableOpacity> </View> ) } const styles = StyleSheet.create({ mainArea: { backgroundColor: '#fcfcfc', padding: 20, width: 300, marginBottom: 30, borderRadius: 15, alignItems: 'center', justifyContent: 'center', }, title: { color: '#2fb28f', textAlign: 'center' }, large: { fontWeight: '700', fontSize: 80 }, medium: { fontWeight: '700', fontSize: 30 }, btn: { backgroundColor: '#2fb28f', width: 220, padding: 15, borderRadius: 10, marginVertical: 20 }, btnText: { color: 'white', fontSize: 18, fontWeight: 'bold', textAlign: 'center' } }); export default TotalPoints
function getOpenTabsCount(callback) { var queryInfo = { currentWindow: true }; chrome.tabs.query(queryInfo, function (tabs) { callback(tabs.length.toString()); }); } function renderStatus(statusText) { document.getElementById('status').textContent = statusText; } document.addEventListener('DOMContentLoaded', function () { getOpenTabsCount(function (tabs) { var template = 'Number of tabs: {{tabs}} '; var output = Mustache.render(template, {tabs: tabs}); renderStatus(output); }); });
'use strict'; var searchData; //stores current search keyword response data. /* main function that calls the API Parse data to cards and also sets data to frontend using DOM. */ function callApi(page) { console.log('callApi'); $.ajax({ type: "GET", url: "https://www.omdbapi.com/?s=" + document.getElementById("searchKeyward").value + "&apikey=3173bd84" + "&page=" + page, success: function (result) { document.getElementById("gridRow1").innerHTML = ""; document.getElementById("gridRow2").innerHTML = ""; document.getElementById("gridRow3").innerHTML = ""; // 1st ROW for (let i = 0; i < 4; i++) { if (!isNaN(result.Search[i].Poster)) { result.Search[i].Poster = 'https://lightning.od-cdn.com/static/img/no-cover_en_US.a8920a302274ea37cfaecb7cf318890e.jpg'; } document.getElementById("gridRow1").innerHTML += "<div class='card card" + i + "' style='background: url(" + result.Search[i].Poster + "');' onclick='showinfo(" + i + ")' >" + "<div class='border'>" + "<h2>" + result.Search[i].Title + "</h2>" + "<h2>" + result.Search[i].Year + "</h2>" + "<h2>" + result.Search[i].Type + "</h2>" + "</div>" + "</div>"; } // 2nd ROW for (let i = 4; i < 8; i++) { if (!isNaN(result.Search[i].Poster)) { result.Search[i].Poster = 'https://lightning.od-cdn.com/static/img/no-cover_en_US.a8920a302274ea37cfaecb7cf318890e.jpg'; } document.getElementById("gridRow2").innerHTML += "<div class='card card" + i + "' style='background: url(" + result.Search[i].Poster + "');' onclick='showinfo(" + i + ")' >" + "<div class='border'>" + "<h2>" + result.Search[i].Title + "</h2>" + "<h2>" + result.Search[i].Year + "</h2>" + "<h2>" + result.Search[i].Type + "</h2>" + "</div>" + "</div>"; } // 3rd ROW for (let i = 8; i < 10; i++) { if (!isNaN(result.Search[i].Poster)) { result.Search[i].Poster = 'https://lightning.od-cdn.com/static/img/no-cover_en_US.a8920a302274ea37cfaecb7cf318890e.jpg'; } document.getElementById("gridRow3").innerHTML += "<div class='card card" + i + "' style='background: url(" + result.Search[i].Poster + "');' onclick='showinfo(" + i + ")' >" + "<div class='border'>" + "<h2>" + result.Search[i].Title + "</h2>" + "<h2>" + result.Search[i].Year + "</h2>" + "<h2>" + result.Search[i].Type + "</h2>" + "</div>" + "</div>" } // Puts Extra cards on for desktop view to fix UI issue document.getElementById("gridRow3").innerHTML += "<div class='card desktop-only' style='background:transparent'>" + "</div>" + "<div class='card desktop-only' style='background:transparent'>" + "</div>"; searchData = result.Search; getDetails(0); }, error: function (result) { alert('error : Unable To Search'); } }); }
// https://medium.com/hackernoon/why-capacity-planning-needs-queueing-theory-without-the-hard-math-342a851e215c // https://en.wikipedia.org/wiki/M/M/c_queue var servers = 1 var arrivalRate = 0.45 var serviceRate = 0.5 function modelQueue(servers, arrivalRate, serviceRate) { var utilisation = arrivalRate/(servers*serviceRate) if(utilisation >= 1) { console.log("Unbounded queue!") return {serverUtilisation: utilisation} } var C = cFormula(servers, arrivalRate, serviceRate) var averageCustomers = utilisation/(1 - utilisation)*C + servers*utilisation var responseTime = C/(servers*serviceRate - arrivalRate) + 1/serviceRate return { serverUtilisation: utilisation, probabilityOfQueuing: C, averageCustomersInSystem: averageCustomers, responseTime: responseTime } } function cFormula(c, l, m) { var p = l / (c*m) //utilisation var sum = 0 for (k = 0; k <= c-1; k++) { sum += Math.pow(c*p, k)/factorial(k) } var multiplier = factorial(c)/Math.pow(c*p, c) var denominator = 1 + (1-p)*multiplier*sum return 1/denominator } function factorial(num) { var rval=1; for (var i = 2; i <= num; i++) rval = rval * i; return rval; } // https://towardsdatascience.com/the-poisson-process-everything-you-need-to-know-322aa0ab9e9a // M/M/c queues have arrivals based on the Poisson distribution // which means inter-arrival times (time between arrivals) follow an exponential distribution function generateInterArrival(rate) { var u = Math.random(); // uniform[0,1) return - Math.log(1.0-u)/rate } function scheduleNextArrival(rate, action, max) { var arrivalTime = generateInterArrival(rate) setTimeout(() => { action(arrivalTime) if(max > 1) { scheduleNextArrival(rate, action, max - 1) } }, arrivalTime*1000) } function workerPool(workers, rate, data, notify) { var pool = function() {} pool.data = data pool.rate = rate pool.workers = [] for (var i = 0; i < workers; i++) { pool.workers.push({id: i, state: "idle"}) } pool.notify = function() { var idleWorkers = pool.workers.filter(x => x.state == "idle") if(idleWorkers.length > 0) { pool.doWork(idleWorkers[0]) } return pool } pool.doWork = function(worker) { var tasks = pool.data.filter(x => x.state == "queued") if (tasks.length == 0) { // no work left to do worker.state = "idle" return; } worker.state = "busy" var task = tasks[0] task.state = "in-progress" notify() scheduleNextArrival(pool.rate, () => { task.state = "done" notify() pool.doWork(worker) }, 1) return pool } return pool } function queueModel() { var model = function() {} model.data = [] model.bind = function(base, scale = 10) { model.base = d3.select(base) model.graph = model.base.append("svg") .attr("width", "200px") .attr("height", "200px") //.attr("viewBox", `0 -20 ${width} 33`); //model.annotation = model.base.append("p") model.max = scale*scale model.scale = scale model.update() return model } model.update = function() { model.graph.selectAll("circle") .data(model.data, d => d.id) .join("circle") .attr("class", d => d.state) .attr("cx", (d,i) => (i % 10)*10+5 + "%") .attr("cy", (d,i) => Math.floor(i / 10)*10+5 + "%") .attr("r", "4.5%") //.text(d => `${d.id}`) if(model.data.length == model.max && model.data.every(x => x.state == "done")) { model.start(model.rate, model.max) } return model } model.workers = function(workers, rate) { model.workerPool = workerPool(workers, rate, model.data, () => model.update()) return model } model.start = function(rate) { model.data.length = 0 model.rate = rate //model.annotation.text(`New tasks arrive ${rate} times per day on average. There are ${model.workerPool.workers.length} workers able to complete ${model.workerPool.rate} tasks per day on average.`) scheduleNextArrival(rate, () => { model.data.push({id: model.data.length, state: "queued"}) model.update() model.workerPool.notify() }, model.max) return model } return model } var charts = {} console.log(modelQueue(servers,arrivalRate,serviceRate))
import babel from 'rollup-plugin-babel'; //This is the standalone rollup config file to bundle and build dist files. //With rollup installed globally in your environment, you can simple run rollup -c. export default { entry: 'src/c.js', dest: 'dist/catarse.js', sourceMap: true, format: 'iife', moduleName: 'c', plugins: [babel()], globals: { chartjs: 'Chart', mithril: 'm', 'mithril-postgrest': 'Postgrest', moment: 'moment', 'i18n-js': 'I18n', replaceDiacritics: 'replaceDiacritics', select: 'select', underscore: '_', liquidjs: 'Liquid' } };
/** * Entrenador.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models */ module.exports = { attributes: { pokemons:{ collection:"Pokemon", via:"idEntrenador" } } };
export { default as AirQloudsTable } from "./AirQloudsTable"; export { default as AirQloudToolbar } from "./AirQloudToolbar"; export { default as AirQloudRegistry } from "./AirQloudRegistry"; export { default as AirQloudView } from "./AirQloudView";
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ var NotificationError = require('./NotificationError'); var modulemapper = require('cordova/modulemapper'); // keep hold of notification for future use var mozNotifications = {}; var mozNotification = modulemapper.getOriginalSymbol(window, 'window.Notification'); var closeEvent = new Event('close'); var clickEvent = new Event('click'); var showEvent = new Event('show'); var errorEvent = new Event('error'); function makeNotification(successCB, errorCB, options) { var title = options.title; var nId = options.notificationId; var pluginObject = options.pluginObject; delete options.title; delete options.notificationId; delete options.pluginObject; var notification = new mozNotification(title, options); mozNotifications[nId] = notification; // handle events notification.onclose = function() { pluginObject.dispatchEvent(closeEvent); } notification.onclick = function() { pluginObject.dispatchEvent(clickEvent); } notification.onshow = function() { pluginObject.dispatchEvent(showEvent); } notification.onerror = function() { pluginObject.dispatchEvent(errorEvent); } successCB(); } // errors currently reporting String for debug only function create(successCB, errorCB, options) { console.log('FxOS DEBUG: create', options); if (mozNotification.permission === 'denied') { errorCB(new NotificationError(NotificationError.PERMISSION_DENIED, 'FxOS Notification: Permission denied')); return; } if (mozNotification.permission === 'granted') { makeNotification(successCB, errorCB, options); return; } mozNotification.requestPermission(function (permission) { if (permission === 'granted') { makeNotification(successCB, errorCB, options); } else { errorCB(new NotificationError(NotificationError.USER_DENIED, 'FxOS Notification: User denied')); } }); } function remove(successCB, errorCB, params) { successCB = (successCB) ? successCB : function() {}; errorCB = (errorCB) ? errorCB : function() {}; var nId = params.notificationId; mozNotifications[nId].close(); successCB(); } module.exports = { create: create, remove: remove }; require("cordova/exec/proxy").add("Notification", module.exports);
import { makeStyles, Tooltip } from '@material-ui/core'; import React from 'react'; const useStyles = makeStyles(() => ({ transaction: { display: 'grid', height: '40px', width: '100%', flexDirection: 'row', color: '#6c757e', borderBottom: '2px solid #e7eaf3', gridTemplateColumns: '16% 16% 16% 16% 16% 16%', justifyContent: 'space-between' }, item: { width: '100%', display: 'flex', justifyContent: 'center', alignItems: 'center' }, text: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } })); const weiToEth = 1000000000000000000; export default ({ transaction: { timeStamp, from, to, value, confirmations, hash }, reference }) => { const classes = useStyles(); timeStamp = new Date(parseInt(timeStamp)).toString(); value = value / weiToEth; const Property = ({ prop }) => { return <div className={classes.item} > <Tooltip title={prop}> <div className={classes.text}> {prop} </div> </Tooltip> </div> } return ( <div className={classes.transaction} ref={reference}> <Property prop={timeStamp} /> <Property prop={from} /> <Property prop={to} /> <Property prop={value} /> <Property prop={confirmations} /> <Property prop={hash} /> </div>); };
import { html ,LitElement} from '@polymer/lit-element'; import bulmaStyles from '../../style/bulma-styles' // import './components/exporter-renew' class PageIndexDefault extends LitElement { render() { return html` ${bulmaStyles(this)} page-index-default `; } _pageActive(params) { console.log(params) console.log('page-index-default'); } } customElements.define('page-index-default', PageIndexDefault);
var searchData= [ ['var_5fassembly_5fstack_126',['var_assembly_stack',['../structvar__assembly__stack.html',1,'']]], ['variable_127',['Variable',['../structVariable.html',1,'']]], ['variables_128',['Variables',['../structVariables.html',1,'']]], ['variablescomparelist_129',['variablesCompareList',['../structvariablesCompareList.html',1,'']]] ];
export const phones = { "A": [{ "id": 1, "name": "安徽" }], "B": [{ "id": 2, "name": "北京" }], "C": [{ "id": 3, "name": "重庆" }], "F": [{ "id": 4, "name": "福建" }], "G": [{ "id": 5, "name": "甘肃" },{ "id": 6, "name": "广东" },{ "id": 7, "name": "广西" },{ "id": 8, "name": "贵州" }], "H": [{ "id": 10, "name": "海南" },{ "id": 11, "name": "河北" },{ "id": 12, "name": "河南" },{ "id": 13, "name": "黑龙江" },{ "id": 14, "name": "湖北" },{ "id": 15, "name": "湖南" }], "J": [{ "id": 16, "name": "吉林" },{ "id": 17, "name": "江西" },{ "id": 18, "name": "江苏" }], "L": [{ "id": 19, "name": "辽宁" }], "N": [{ "id": 20, "name": "内蒙古" },{ "id": 21, "name": "宁夏回族" },], "Q": [{ "id": 22, "name": "青海" }], "S": [{ "id": 23, "name": "山东" },{ "id": 24, "name": "山西" },{ "id": 25, "name": "山西" },{ "id": 26, "name": "上海" },{ "id": 27, "name": "四川" }], "T": [{ "id": 28, "name": "天津" }], "X": [{ "id": 29, "name": "西藏" },{ "id": 30, "name": "新疆维吾尔" }], "Y": [{ "id": 31, "name": "云南" }], "Z": [{ "id": 32, "name": "浙江" }] }; //七牛图片域名 export const QiNiuImgDomainName = 'http://xjm.cachito.top/'; //腾讯SDK获取位置 export const QQSDK = 'S57BZ-S4J66-YBRS5-M3SB6-PL6PZ-JEF2M'; //获取七牛的 export const bucketName = 'xiejiang'; //测试头像 export const portrait = 'https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoEZR8fMGUADxBT0rfnpB5OYJqYsWA4ec8DNl2pH7ibVdjoyuHCzbENZpk7ERW1GiaibNtvyQmwRKltg/132'; //客服提示 export const CustomerServiceTips = '鞋匠云集荟聚鞋业资源,欢迎您开通领域权限,畅享更多鞋业资讯,若有需要了解点击下方【联系客服】' //视频播放的所有后缀几个 export const VideoType = ['.wmv','.asf','.asx','.rm','.rmvb','.mp4','.mov','.m4v','.avi','.dat','.mkv','.flv','.vob']; export default { phones, QiNiuImgDomainName, QQSDK, bucketName, portrait, CustomerServiceTips, VideoType }
({ toggleExpand : function(cmp) { var itemSection = cmp.find("itemSection"); $A.util.toggleClass(itemSection, "slds-is-open"); var isExpanded = cmp.get("v.isExpanded"); cmp.set("v.isExpanded", !isExpanded); }, fireItemClicked: function(cmp) { var clickedItem = $A.get("e.c:ClickedAccordionItem"); clickedItem.setParams({ itemName: cmp.get("v.iterationIndex") }); clickedItem.fire(); }, verifyToggleState: function(cmp, event) { var iterationIndex = cmp.get("v.iterationIndex"); var isExpanded = cmp.get("v.isExpanded"); var clickedItem = event.getParam("itemName"); if(iterationIndex !== clickedItem && isExpanded) { this.toggleExpand(cmp); } } })
'use strict' var EnvisaLink = require('./envisalink.js') module.exports = function (RED) { function EnvisaLinkControllerNode (config) { this.node = RED.nodes.createNode(this, config) var _this = this this.host = config.host this.port = config.port this.password = this.credentials.password config.password = this.password config.zones = config.zones config.atomicEvents = false config.partitions = config.partitions this.connected = false this.connecting = false this.el = new EnvisaLink(config) this.users = {} this.register = function (elNode) { _this.users[elNode.id] = elNode if (Object.keys(_this.users).length === 1) { if (!_this.connected && !_this.connecting) { _this.connecting = true _this.el.connect() } } else if (_this.connected) { elNode.status({ fill: 'green', shape: 'dot', text: 'Connected' }) } else if (!_this.connecting) { _this.connecting = true _this.el.connect() } } this.deregister = function (elNode, done) { delete _this.users[elNode.id] if (_this.closing) { return done() } if (Object.keys(_this.users).length === 0) { _this.done = done _this.el.disconnect() } else { done() } } this.el.on('connected', function () { _this.connected = true _this.connecting = false for (var id in _this.users) { if (_this.users.hasOwnProperty(id)) { _this.users[id].status({ fill: 'green', shape: 'dot', text: 'Connected' }) } } }) this.el.on('error', function (ex) { _this.connected = false _this.connecting = false for (var id in _this.users) { if (_this.users.hasOwnProperty(id)) { _this.users[id].status({ fill: 'red', shape: 'ring', text: 'Disconnected' }) } } }) this.el.on('log-trace', function (text) { _this.trace(RED._(text)) }) this.el.on('log-debug', function (text) { _this.log(RED._(text)) }) this.el.on('log-warn', function (text) { _this.warn(RED._(text)) }) this.el.on('log-error', function (text) { _this.error(RED._(text)) }) // CET: Feb 9/2020 this one stays as is. this.el.on('zoneupdate', function (update) { for (var id in _this.users) { if (_this.users.hasOwnProperty(id)) { _this.users[id].emit('el-zoneupdate', update) } } }) this.el.on('partitionupdate', function (update) { for (var id in _this.users) { if (_this.users.hasOwnProperty(id)) { _this.users[id].emit('el-partitionupdate', update) } } }) this.el.on('cidupdate', function (update) { for (var id in _this.users) { if (_this.users.hasOwnProperty(id)) { _this.users[id].emit('el-cidupdate', update) } } }) this.el.on('keypadupdate', function (update) { for (var id in _this.users) { if (_this.users.hasOwnProperty(id)) { _this.users[id].emit('el-keypadupdate', update); } } }); this.sendCommand = function (command) { this.el.sendCommand(command) }.bind(this) this.el.on('disconnect', function () { if (_this.done !== undefined) { _this.done() _this.done = null } _this.connected = false _this.connecting = false // CET added a normal log message FEB 8/2020 _this.log("Received disconnect.. host:"+_this.host+" port:"+_this.port); _this.log(RED._('Disconnected from ' + _this.host + ':' + _this.port)) for (var id in _this.users) { if (_this.users.hasOwnProperty(id)) { _this.users[id].status({ fill: 'red', shape: 'ring', text: 'Disconnected' }) } } }) this.on('close', function (done) { _this.log(RED._('Closing Envisalink', {})) _this.closing = true _this.connected = false _this.connecting = false _this.done = done var wasDisconnected = _this.el.disconnect() if (wasDisconnected) { _this.done = null done() } }) } RED.nodes.registerType('envisalink-controller', EnvisaLinkControllerNode, { credentials: { password: { type: 'password' } } }) }
CordSharp.call = function (method, arg, arg2) { };
$(function(){ $('#Buscador').submit(function(e){ e.preventDefault(); }) $('#search').keyup(function(){ var busqueda = $('#search').val(); $.ajax({ type: 'POST', url: 'Registrosphp/result.php', data: {'search': busqueda} }) .done(function(resultado){ if(resultado !="") $('#result').html(resultado); }) .fail(function(){ alert('Hubo algun error'); }) }) })
const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault() }); const db = admin.firestore(); async function highlight(id) { const documentSnapshot = await db.collection('cats').doc(id).get(); return documentSnapshot.ref.update({ highlight: new Date(Date.now()).toUTCString() }); } module.exports = highlight;
function loop() { } module.exports = { loop }
import React, { Component } from 'react'; import { combineReducers, createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import Displaycep from '../components/displaycep'; import Consultar from '../components/consultar'; import cepReducer from '../reducers/cep'; import '../css/app.css'; import 'bootstrap/dist/css/bootstrap.min.css'; const reducers = combineReducers({ cepReducer }); const store = createStore( reducers, applyMiddleware(thunk) ); class App extends Component { render() { return ( <Provider store={store}> <div> <Displaycep/> <Consultar/> </div> </Provider> ) } } export default App;
cc.Class({ extends: cc.Component, properties: { }, onLoad () { this.node.runAction(cc.repeatForever(cc.rotateBy(5,360))); }, // 碰撞后 onCollisionEnter: function (other, self) { this.node.stopAllActions(); this.node.parent.getComponent('tower1').isShoot = false; this.node.x = 0; this.node.y = 0; } });
const Mock = require("mockjs"); const Random = Mock.Random; const getResource = () => { let resources = [ { title: "新房" }, { title: "二手房" }, { title: "租房" }, { title: "卖房" }, { title: "转介绍" }, { title: "计算器" }, { title: "地图找房" }, { title: "买卖流程" }, { title: "房屋估价" }, { title: "搬家保洁" }, ]; let resources1 = resources.map((v) => { return { ...v, image: Random.dataImage("30x30", "图标") }; }); return resources1; }; Mock.mock("http://mockjs.com/getResource", "get", getResource()); const getfloorSwiper = () => { let resources = []; for (let i = 0; i < 10; i++) { resources.push({ "id|+1": 0, "type|1": ["hot", "soon"], name: Random.cword(4, 8), image: Random.dataImage("150x100", "楼盘图"), address: Random.city(true), area: "74-129㎡", price: "388万元/套起", time: Random.date(), }); } return resources; }; Mock.mock("http://mockjs.com/getfloorSwiper", "get", getfloorSwiper()); const getfloorDetail = () => { let resources = { name: "华樾国际", address: Random.city(true), area: "74-129㎡", price: "388万元/套起", time: Random.date(), houseType: "3/4室", image: [], }; for (let i = 0; i < 3; i++) { resources.image.push(Random.dataImage("375x200", "楼盘图")); } return resources; }; Mock.mock("http://mockjs.com/getfloorDetail", "get", getfloorDetail()); const getHouseType = () => { let resources = []; for (let i = 0; i < 2; i++) { resources.push({ houseType: "4室2厅2卫", image: Random.dataImage("150x150", "户型图"), area: "129㎡", price: "售价待定", state: "在售", }); } return resources; }; Mock.mock("http://mockjs.com/getHouseType", "get", getHouseType()); const getFloorDynamic = () => { let resources = []; for (let i = 0; i < 2; i++) { resources.push({ time: Random.date(), state: "楼盘资讯", article: Random.cparagraph(3), }); } return resources; }; Mock.mock("http://mockjs.com/getFloorDynamic", "get", getFloorDynamic()); const getHouseDetails = () => { let resources = { name: "A户型", address: Random.city(true), area: "100㎡", price: "约260万/套", houseType: "住宅", direction: "南,北", image: Random.dataImage("375x400", "户型图"), }; return resources; }; Mock.mock("http://mockjs.com/getHouseDetails", "get", getHouseDetails()); const getRealShot = () => { let resources = []; for (let i = 0; i < 3; i++) { resources.push({ image: Random.dataImage("100x70", "实拍图"), title: Random.cparagraph(1), icon: Random.dataImage("20x20", "头像"), name: Random.cname(), }); } return resources; }; Mock.mock("http://mockjs.com/getRealShot", "get", getRealShot()); const getCollection = () => { let resources = []; for (let i = 0; i < 5; i++) { resources.push({ "id|+1": 0, "type|1": ["floor", "house"], name: Random.cword(4, 8), image: Random.dataImage("150x100"), price: "388万元/套起", }); } return resources; }; Mock.mock("http://mockjs.com/getCollection", "get", getCollection()); const getPriceComparison = () => { let resources = []; for (let i = 0; i < 2; i++) { resources.push({ image: Random.dataImage("100x100", "户型图"), "houseType|1": ["A户型", "C户型"], type: "住宅", "price|1": ["约260万/套", "约660万/套"], "area|1": ["100㎡", "150㎡"], direction: "南,北", address: "北京。。。", }); } return resources; }; Mock.mock("http://mockjs.com/getPriceComparison", "get", getPriceComparison()); const getAgentList = () => { let resources = []; for (let i = 0; i < 10; i++) { resources.push({ image: Random.dataImage("80x80", "头像"), name: Random.cname(), "service|1000-5000": 1, "look|100-500": 1, }); } return resources; }; Mock.mock("http://mockjs.com/getAgentList", "get", getAgentList());
import React, { Component } from 'react' import { connect } from "react-redux"; import { TextFieldForm, SelectForm } from "../../../utils/FormComponent"; import Dashboard from "../../layouts/Dashboard"; import { addMovie } from "../../../redux/actions/MovieActions"; import {fetchGenre} from "../../../redux/actions/GenreActions"; import { withRouter } from 'react-router-dom'; class MovieCreate extends Component { componentDidMount() { this.props.fetchGenre(); } state = { title: '', genreId: '', numberInStock: '', dailyRentalRate: '', } HandleSubmit = (e) => { e.preventDefault(); const newItem = { title: this.state.title, genreId: this.state.genreId, numberInStock: this.state.numberInStock, dailyRentalRate: this.state.dailyRentalRate, } console.log(newItem); this.props.addMovie(newItem, this.props.history); } onChange = (e) => { e.preventDefault(); this.setState({ [e.target.name]: e.target.value }) } render() { const {genres} = this.props.genre const selectOptions = genres.map(option => ( <option key={option._id} value={option._id}> {option.name} </option> )); return ( <div> <Dashboard /> <div> <div className="page-container"> {/* MAIN CONTENT*/} <div className="main-content"> <div className="section__content section__content--p30"> <div className="container-fluid"> <div className="row"> <div className="col-lg-6"> <div className="card"> <div className="card-header">Movie</div> <div className="card-body"> <div className="card-title"> <h3 className="text-center title-2">Movie Create</h3> </div> <hr /> <form onSubmit={this.HandleSubmit}> <TextFieldForm label="title " className="control-label mb-1" name="title" value={this.state.title} onChange={this.onChange} /> <SelectForm placeholder="Genre" name="genreId" value={this.state.genreId} onChange={this.onChange} options={selectOptions} /> <TextFieldForm label="numberInStock" className="control-label mb-1" name="numberInStock" value={this.state.numberInStock} onChange={this.onChange} /> <TextFieldForm label="dailyRentalRate" className="control-label mb-1" name="dailyRentalRate" value={this.state.dailyRentalRate} onChange={this.onChange} /> <div> <button id="payment-button" type="submit" className="btn btn-lg btn-info btn-block"> Create Movie </button> </div> </form> </div> </div> </div> </div> </div> </div> </div> {/* END MAIN CONTENT*/} {/* END PAGE CONTAINER*/} </div> </div> </div> ) } } const mapStateToProps = state => ({ movie: state.movie, genre: state.genre }); export default connect(mapStateToProps, { addMovie, fetchGenre})(withRouter(MovieCreate));
var db = require('./db'); /** * 고객 추가 * @param item_no * @param customer_no * @param callback */ exports.insert = function(sock_id, name, callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'INSERT INTO user (type, name, sock_id) ' + 'VALUES (?, ?, ?)'; conn.query(sql, [2, name, sock_id], function(err, result) { if (err) callback(err); else { callback(null, result.insertId); } conn.release(); }); } }); }; exports.selectIdConsult = function(consult_no, callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'SELECT U.no, U.sock_id FROM user U JOIN consult C ' + 'ON U.no = C.customer_no WHERE C.no = ?'; conn.query(sql, [consult_no], function(err, rows) { if (err) callback(err); else { callback(null, rows[0].no, rows[0].sock_id); } conn.release(); }); } }); }; /** * 다음 상담원 no (순환) * @param curUserNo 현재 상담원 no * @param groups 검색 그룹 * @param callback */ exports.selectRotate = function(curUserNo, groups, restUsers, callback) { db.pool.getConnection(function(err, conn) { if (err) { callback(err); } else { var whereGroup = parseWhereGroup(groups); var whereRest = ''; if (restUsers.length != 0) { whereRest = ' AND no NOT IN ('; restUsers.forEach(function (no) { whereRest += no + ','; }); whereRest = whereRest.slice(0, -1) + ')'; } var sql = 'SELECT IFNULL((SELECT MIN(no) FROM user WHERE no > ? AND consult_enable = 1 ' + whereGroup + whereRest + '), ' + '(SELECT MIN(no) FROM user WHERE no > 0 AND consult_enable = 1 ' + whereGroup + whereRest + ')) no '; // 'SELECT U.no FROM user U ' + // 'LEFT JOIN (SELECT * FROM consult WHERE status in (1, 2)) C ON U.no=C.consultant_no ' + // 'WHERE U.no = IFNULL((SELECT MIN(no) FROM user WHERE no > ?), (SELECT MIN(no) FROM user WHERE no > 0)) '; conn.query(sql, [curUserNo], function (err, rows) { if (err) { callback(err); } else { callback(null, rows[0]); } conn.release(); }); } }); }; /** * 다음 상담원 no (랜덤) * @param groups 검색 그룹 * @param callback */ exports.selectRandom = function(groups, restUsers, callback) { db.pool.getConnection(function(err, conn) { if (err) { callback(err); } else { var whereGroup = parseWhereGroup(groups); var whereRest = ''; if (restUsers.length != 0) { whereRest = ' AND no NOT IN ('; restUsers.forEach(function (no) { whereRest += no + ','; }); whereRest = whereRest.slice(0, -1) + ')'; } var sql = 'SELECT no FROM user WHERE 1=1 AND consult_enable = 1 ' + whereGroup + whereRest + ' ' + ' order by rand() limit 1'; // 'SELECT U.no FROM user U ' + // 'LEFT JOIN (SELECT * FROM consult WHERE status in (1, 2)) C ON U.no=C.consultant_no ' + // 'WHERE U.no = IFNULL((SELECT MIN(no) FROM user WHERE no > ?), (SELECT MIN(no) FROM user WHERE no > 0)) '; conn.query(sql, [], function (err, rows) { if (err) { callback(err); } else { callback(null, rows[0]); } conn.release(); }); } }); }; /** * 다음 상담원 no (균등) * @param groups 검색 그룹 * @param callback */ exports.selectEqual = function(groups, restUsers, callback) { db.pool.getConnection(function(err, conn) { if (err) { callback(err); } else { var whereGroup = parseWhereGroup(groups); var whereRest = ''; if (restUsers.length != 0) { whereRest = ' AND U.no NOT IN ('; restUsers.forEach(function (no) { whereRest += no + ','; }); whereRest = whereRest.slice(0, -1) + ')'; } var sql = 'SELECT no, count FROM ( ' + 'SELECT U.no, COUNT(C.consultant_no) count FROM user U ' + 'LEFT JOIN (SELECT * FROM consult WHERE status in (1, 2)) C ON U.no = C.consultant_no ' + 'WHERE 1=1 AND U.consult_enable = 1 ' + whereGroup + whereRest + ' ' + 'GROUP BY U.no ' + 'ORDER BY count, no ' + // 'LIMIT 1 ' + ') A'; conn.query(sql, [], function (err, rows) { if (err) { callback(err); } else { callback(null, rows[0]); console.log('[test] dist equal', rows); } conn.release(); }); } }); }; function parseWhereGroup(groups) { var str = ''; if (groups != null && groups.length != 0) { str = 'AND group_no IN ('; for (var i = 0; i < groups.length; i++) { str += groups[i] + ','; } str = str.substring(0, str.length - 1) + ') '; } return str; } /** * 이름 검색 * @param callback */ exports.selectNameByNo = function(no, callback) { db.pool.getConnection(function(err, conn) { if (err) { callback(err); } else { var sql = 'SELECT name FROM user WHERE no = ?'; conn.query(sql, [no], function (err, rows) { if (err) { callback(err); } else { if (rows.length == 0) { callback(new Error('not exist row')); } else { callback(null, rows[0].name); } } conn.release(); }); } }); }; /** * 휴식중인 유저 확인 * @param callback */ exports.selectRestUser = function(callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'select user_no no from user_rest where start_time < now() and end_time > now() and end_time is not null'; conn.query(sql, [], function(err, rows) { if (err) callback(err); else { callback(null, rows); } conn.release(); }); } }); }; /** * 가장 조금 상담중인 상담원의 no 가져옴 * @param callback */ exports.selectLeastConsult = function(callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'SELECT U.no, count(C.consultant_no) count FROM user U ' + 'LEFT JOIN (SELECT * FROM consult WHERE status in (1, 2)) C ON U.no=C.consultant_no ' + 'GROUP BY U.no ' + 'ORDER BY count'; conn.query(sql, [], function(err, rows) { if (err) callback(err); else { callback(null, rows[0].no); } conn.release(); }); } }); }; /** * 상담량 초과 이메일 보낸 날짜 가져옴 * @param callback */ exports.selectExcessEmailDate = function(no, callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'SELECT name, email, excess_email_date FROM user WHERE no = ?'; conn.query(sql, [no], function(err, rows) { if (err) callback(err); else { if (rows.length == 0) { callback(new Error('not exist rows')); } else { callback(null, rows[0]); } } conn.release(); }); } }); }; /** * 상담량 초과 이메일 보낸 날짜 업데이트 * @param callback */ exports.updateExcessEmailDate = function(no, callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'UPDATE user SET excess_email_date = now() WHERE no = ?'; conn.query(sql, [no], function(err, result) { if (err) callback(err); else { callback(null, result.affectedRows); } conn.release(); }); } }); };
import { REASON_PREFIX, getLIFFURL, createAskArticleSubmissionReply, ellipsis, } from './utils'; import ga from '../ga'; export default async function askingArticleSource(params) { let { data, state, event, issuedAt, userId, replies, isSkipUser } = params; const source = data.articleSources[event.input - 1]; if (!source) { replies = [ { type: 'text', text: `請輸入 1~${data.articleSources.length} 的數字,選擇訊息來源。`, }, ]; state = 'ASKING_ARTICLE_SOURCE'; return { data, state, event, issuedAt, userId, replies, isSkipUser }; } const visitor = ga(userId, state, data.selectedArticleText); // Track the source of the new message. visitor.event({ ec: 'Article', ea: 'ProvidingSource', el: source }); if (source === '自己輸入的') { replies = [ { type: 'template', altText: '好的,建議您把訊息轉傳給 MyGoPen 或蘭姆酒吐司,兩個都是很專業的謠言破解網站,而且有 💁 專人為您解答喔!', template: { type: 'confirm', text: '好的,建議您把訊息轉傳給 MyGoPen 或蘭姆酒吐司,兩個都是很專業的謠言破解網站,而且有 💁 專人為您解答喔!', actions: [ { type: 'uri', label: 'MyGoPen', uri: `line://ti/p/%40mygopen`, }, { type: 'uri', label: '蘭姆酒吐司', uri: `line://ti/p/1q14ZZ8yjb`, }, ], }, }, ]; state = '__INIT__'; } else if ( data.foundArticleIds && data.foundArticleIds.length > 0 && data.selectedArticleId ) { // articles that are already reported const altText = '【跟編輯說您的疑惑】\n' + '好的,謝謝您。若您覺得這是一則謠言,請指出您有疑惑之處,說服編輯這是一份應該被闢謠的訊息。\n' + '\n' + '請按左下角「⌨️」鈕,把「為何您會覺得這是一則謠言」的理由傳給我們,幫助闢謠編輯釐清您的疑惑;\n' + '若想跳過,請輸入「n」。'; replies = [ { type: 'flex', altText, contents: { type: 'bubble', header: { type: 'box', layout: 'horizontal', contents: [ { type: 'text', text: '跟編輯說您的疑惑', weight: 'bold', color: '#009900', size: 'sm', }, ], }, body: { type: 'box', layout: 'vertical', spacing: 'md', contents: [ { type: 'text', text: '好的,謝謝您。若您希望闢謠的好心人可以關注這一篇,請按「我也想知道」告訴大家你的想法。', wrap: true, }, ], }, footer: { type: 'box', layout: 'vertical', contents: [ { type: 'button', style: 'primary', action: { type: 'uri', label: '🙋 我也想知道', uri: getLIFFURL( 'ASKING_REPLY_REQUEST_REASON', data.searchedText, REASON_PREFIX, issuedAt ), }, }, ], }, }, }, ]; state = 'ASKING_REPLY_REQUEST_REASON'; } else if (data.messageType === 'text') { // brand new articles replies = [ { type: 'text', text: '好的,謝謝您。', }, ].concat( createAskArticleSubmissionReply( 'ASKING_ARTICLE_SUBMISSION_REASON', ellipsis(data.searchedText, 12), REASON_PREFIX, issuedAt ) ); state = 'ASKING_ARTICLE_SUBMISSION_REASON'; } else { replies = [ { type: 'template', altText: '好的,建議您把訊息轉傳給 MyGoPen 或蘭姆酒吐司,兩個都是很專業的謠言破解網站,而且有 💁 專人為您解答喔!', template: { type: 'confirm', text: '好的,建議您把訊息轉傳給 MyGoPen 或蘭姆酒吐司,兩個都是很專業的謠言破解網站,而且有 💁 專人為您解答喔!', actions: [ { type: 'uri', label: 'MyGoPen', uri: `line://ti/p/%40mygopen`, }, { type: 'uri', label: '蘭姆酒吐司', uri: `line://ti/p/1q14ZZ8yjb`, }, ], }, }, ]; state = '__INIT__'; } visitor.send(); return { data, state, event, issuedAt, userId, replies, isSkipUser }; }
var FormCacheGroupController = function(cacheGroup, $scope, cacheGroupService) { $scope.cacheGroup = cacheGroup; $scope.hasError = function(input) { return !input.$focused && input.$dirty && input.$invalid; }; $scope.hasPropertyError = function(input, property) { return !input.$focused && input.$dirty && input.$error[property]; }; }; FormCacheGroupController.$inject = ['cacheGroup', '$scope', 'cacheGroupService']; module.exports = FormCacheGroupController;
import React from 'react'; import './newnote.css'; const NewNote = (props) => { return ( <div className="mainContent"> <form onSubmit={props.submitNote}> <h1> Create New Note: </h1> <div className="createNoteStyles"> <input type="text" name="note" onChange={props.handleInput} placeholder="New Note" value={props.noteValue} className="formBox1"/> <br /> <input type="text" name="details" onChange={props.handleInput} placeholder="Note Details" value={props.detailsValue} className="formBox2"/> <button type="submit" className="saveNote">Save</button> </div> </form> </div> ) } export default NewNote;
const request = require('supertest'); const server = require('./server.js'); describe('the server', () => { describe('GET /', () => { it('should run the testing env', () => { }); it('it should return status 200', () => { return request(server) .get('/') .then(res =>{ expect(res.status).toBe(200); }) }); it('it should return the correct object', () => { return request(server) .get('/') .then(res =>{ expect(res.type).toBe('application/json'); // tobe will not work // expect(res.body).toBe({message: 'hi'}); expect(res.body).toEqual({message: 'hi'}); }) }); }); }); // Sam Allen 6:39 PM // We worked on an AH problem just now and utilized the terminal command // knex migrate:latest --env testing // this will update the test.db3 file. (if you only run knex migrate:latest, the test db will not be populated)
import React from 'react'; import logo from './logo.svg'; import './App.css'; import {Navigation, Header, Layout, Drawer, Content, Footer, FooterSection, FooterLinkList} from 'react-mdl'; import Main from './components/routes'; import { Link } from 'react-router-dom'; function App() { const GitHub = 'https://github.com/nathanzilgo'; const LinkedIn = 'https://www.linkedin.com/in/nathan-fernandes98/'; const back_url = 'url(https://miro.medium.com/max/3840/1*_gg1Te-7SJfk9E2D-mORfw.png) center / cover'; const img_url = 'https://p7.hiclipart.com/preview/522/51/735/tony-tony-chopper-monkey-d-luffy-one-piece-treasure-cruise-chibi-chopper.jpg'; return ( <div style={{height: '100vh', position: 'relative'}}> <Layout style={{background: back_url}}> <Header transparent title="A simple ReactJS Landing Page" style={{color: 'whitblanchedalmonde', textShadow: '3px 3px 2px black '}}> <Navigation> <Link style={{textShadow: '3px 3px 3px black '}} to="/">Home</Link> <Link style={{textShadow: '3px 3px 3px black '}} to="/references">References</Link> <Link style={{textShadow: '3px 3px 3px black '}} to="/projects">Projects</Link> <Link style={{textShadow: '3px 3px 3px black '}} to="/about">About</Link> <Link style={{textShadow: '3px 3px 3px black '}} to="/contact">Contact</Link> </Navigation> </Header> <Drawer title="Mobile navigation"> <Navigation> <a href={"/"}>Home</a> <a href={"/projects"}>Projects</a> <a href={"/references"}>References</a> <a href={"/about"}>About</a> <a href={"/contact"}>Contact</a> <a href={GitHub}>GitHub</a> <a href={LinkedIn}>LinkedIn</a> </Navigation> </Drawer> <Content> <div className="page-content"></div> <Main/> </Content> <Footer size="mini" style={{ minWidth: '100%', margin: 'auto', height: '2vh', opacity: '0.8'}}> <img src={img_url} style={{width:' 5vh', height:'5vh'}}></img> <FooterSection type="left" logo='Footer'> <FooterLinkList> <Link to="/">Home</Link> <Link to="/projects">Open Projects</Link> <Link to="/about">About</Link> <Link to="/contact">Contact</Link> </FooterLinkList> </FooterSection> </Footer> </Layout> </div> ); } export default App;
import { expectSaga } from "redux-saga-test-plan"; import watchAutocompletes from "../../redux/sagas/autocompletes"; describe("Autocompletes saga", () => { it("should have the expected watchers", (done) => { expectSaga(watchAutocompletes) .run({ silenceTimeout: true }) .then((saga) => { expect(saga).toMatchSnapshot(); done(); }); }); });
// moment.js injection service. angular.module('tdf').factory('moment', [function() { return window.moment; }]);
import React, { useEffect } from 'react'; import { StyleSheet, Text, View, Button, TextInput, Alert, SafeAreaView } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { useState } from 'react'; import { useNavigation } from '@react-navigation/native'; import Home from './Home'; import {useDispatch, useSelector} from "react-redux"; import { TouchableOpacity } from 'react-native-gesture-handler'; export default function Start() { // const [username, setUsername] = useState(""); // const [refresh, setRefresh] = useState(""); // const [userstate, setUserstate] = useState(GLOBAL.userstate); const dispatch = useDispatch(); const navigation = useNavigation() const usernameState = useSelector((state) => state.usernameState); const userisPressing = useSelector((state) => state.userisPressing); const setuserpresstru = () => { console.log(usernameState); dispatch({type: "USER_PRESSED_TRUE"}); } // forceRemount = () => { // dispatch({type:"CHANGE_USER_STATE_TRUE"}) // } // const storeData = async () => { // if(username==""){ // Alert.alert("Input is Null") // }else{ // try{ // await AsyncStorage.setItem('UserName', username) // console.log("Successfully stored") // Alert.alert("Successfully stored") // // navigation.push('Main') // forceRemount(); // // console.log("kok: " + GLOBAL.userstate) // }catch(e){ // console.log(e) // } // } // } // const getData = async () => { // try { // const value = await AsyncStorage.getItem('UserName') // if( value !== null) { // setusertrue(); // }else{ // setUserstate(false) // } // } catch(e) { // } // } const hajimeruOnpress = () => { if(usernameState !== false){ // navigation.navigate("Authscreen"); setuserpresstru(); // console.log(userisPressing); }else{ // navigation.navigate("Start"); // console.log("here1"); } } // useEffect(() => { // // console.log(usernameState) // getData() // },[]); return( <SafeAreaView style={styles.container}> <Text style={{ fontSize:46, marginTop:30, margin:10 }} >就活面接 読み上げアプリ</Text> {/* <Button style={{ }} color="lightgrey" title = "始める" /> */} <TouchableOpacity style={styles.button} onPress={hajimeruOnpress}> <Text style={{ fontSize: 30 }}> 始める </Text> </TouchableOpacity> <TouchableOpacity style={styles.tukaikata}> <Text style={{ color: 'blue', fontSize: 20 }}> 使い方 </Text> </TouchableOpacity> </SafeAreaView> // <View style={styles.container}> // <Te // {/* <Text> // このアプリをダウンロードしてくれてありがとうございます // </Text> // <Text> // まず初めにユーザーネームを入れてください // </Text> // <TextInput // style={{ // marginTop: 30 // }} // backgroundColor='white' // onChangeText={text => setUsername(text)} // placeholder=" Type your username " // /> // <Button // style={{ // marginTop: 30 // }} // title="Save" onPress={storeData}/> */} // {/* <Button title="Home.js" onPress={()=>navigation.navigate('Home')} /> */} // </View> ); } const styles = StyleSheet.create({ container: { flex: 1, fontSize: 40, // marginTop: 20, backgroundColor: 'tomato', // alignItems: 'center', // justifyContent: 'center', }, button: { // fontSize:, alignItems: 'center', justifyContent: 'center', padding: 10, // width:100, // height: 100, fontSize: 60, margin: 60, backgroundColor: 'lightgrey' }, tukaikata: { paddingRight: 40, alignItems: 'flex-end', color:'lightblue', } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.A = void 0; var db_1 = require("./modules/db"); db_1.getData(); console.log(db_1.dbUrl); var A; (function (A) { var Dog = /** @class */ (function () { function Dog(name) { this.name = name; } Dog.prototype.eat = function () { console.log(this.name + " is eating"); }; return Dog; }()); A.Dog = Dog; })(A = exports.A || (exports.A = {})); var d = new A.Dog('ww');
import Ember from 'ember'; export default Ember.Component.extend({ tagName: "ul", durations: [], initialize: function() { $('input.datetimepicker').daterangepicker({ timePicker: true, timePickerIncrement: 30, locale: { format: 'YYYY-MM-DD HH:mm' } }); }.on('didRender'), actions: { addDuration() { // Add a new row and initialize the datetime picker let durations = this.get('durations'); this.get('durations').pushObject({ 'id':durations.length+1, 'startdate':'2016-08-04T10:00:00.000Z', 'enddate':'2016-08-04T10:30:00.000Z' }); }, removeDuration(obj) { // Remove a row this.get('durations').removeObject(obj); } } });
const esClient = require('../elastic'); const moment = require('moment'); const logger = require('../logger'); const logcsv = require('../logger/csvIndex'); const { userCache, ipCache } = require('../cache'); const { md5 } = require('../util'); const userRepo = require('../repository/user'); const { getGeo } = require('../geo'); const reg = /user\s*?:\s*(.*?)\s*,/; const regId = /(\w+-){2,}/; const getOffUser = async (str) => { try { if (/(\w+-){4}/.test(str)) return str; let arr = reg.exec(str); if (arr && arr.length > 1) { let userKey = arr[0]; let uk = arr[1]; if (userCache[uk]) { userKey = userKey.replace(uk, userCache[uk]); return str.replace(arr[0], userKey); } else { uk = uk.replace(/^[\s']*|[\s']*$/g, ''); switch (uk) { case '-': case 'UNKNOWN': case 'unknown': case 'localhost': case 'null': case 'NULL': case 'nil': { userCache[uk] = md5(uk); userKey = userKey.replace(uk, userCache[uk]); return str.replace(arr[0], userKey); } case '': { return str; } default: { let [user] = await userRepo.getUser(uk); if (user && user.id) { userCache[uk] = user.id; userKey = userKey.replace(uk, userCache[uk]); return str.replace(arr[0], userKey); } else { console.log(`u404:${uk}`); return str; } } } } } else { return str; } } catch (err) { console.log('getOffUser', err); return str; } }; const anlysisFeilds = async (str) => { let isErrorLog = /\[error\]/.test(str); if (isErrorLog) { // 如果是错误日志,但是并非lua脚本定义的错误,就跳过 if (!/ngx_error\(\)/.test(str)) { return false; } } let user, ip, action, actionTime, what, result; user = /user:\s*([\w-]+),/.exec(str); user && ([, user] = user); if (!user || user === '-') return false; ip = /client:\s*([\d.]+)/.exec(str); ip && ([, ip] = ip); if (!/^[\d.]+$/.test(ip)) { console.log('>>>', ip, str); return false; } if (!ipCache[ip]) { try { const geoInfo = await getGeo(ip); if (geoInfo) { ipCache[ip] = geoInfo; } else { ipCache[ip] = {}; } } catch (err) { console.error('geoInfo error'); console.error(err); } } let loc = ipCache[ip].location; let lnglat = ipCache[ip].lnglat; action = /action:\s*(\w+)\s*,/.exec(str); action && ([, action] = action); result = /result:\s*(\w+)\s*,/.exec(str); result && ([, result] = result); if (isErrorLog) { actionTime = /^([\d/:\s]+)\s*\[error\]/.exec(str); actionTime && ([, actionTime] = actionTime); actionTime = moment(new Date(actionTime)).format('YYYYMMDDHHmmss'); what = /request:\s*"\w+\s(.*?)\s+.*?"/.exec(str); what && ([, what] = what); if (str.indexOf('UA HMAC ERROR') >= 0) { result = 3; } else if (str.indexOf('POLICY ERROR') >= 0) { result = 2; } else { result = 1; } } else { actionTime = /\[timestamp:\s*([\w\/:]+)\s*[+\d]*\]/.exec(str); // 24/Dec/2019:16:50:43 ---> 24/Dec/2019 16:50:43 actionTime && ([, actionTime] = actionTime); actionTime = actionTime.replace(/:/, ' '); actionTime = moment(new Date(actionTime)).format('YYYYMMDDHHmmss'); what = /, \w{3,} (.*)\s.*?,result:/.exec(str); what && ([, what] = what); result = result === 'success' ? 1 : result; } return [user, actionTime, ip, loc, lnglat, what, action, result]; }; module.exports = { getOffUser: getOffUser, async getIndices () { try { let elkData = await esClient.cat.indices({ index: 'sdp*', format: 'json' }); let { body } = elkData; return body; } catch (err) { console.error('获取索引失败'); return undefined; } }, /** * 分页查询,最多返回前 10000 条记录, from + size > 10000, 将报错 * @param {string} indexName * @param {int} from * @param {int} size */ async getDocs (indexName, from, size) { try { let elkData = await esClient.search({ index: indexName, format: 'json', from: from, size: size, sort: '@timestamp', }); if (elkData) { let { body: { hits } } = elkData; return hits; } } catch (err) { console.error('获取索引失败'); console.error(err); return undefined; } }, async getDocsByScroll (indexName, size) { try { let scrollData = await esClient.search({ index: indexName, format: 'json', scroll: '1m', // 设置每个 scroll 查询的时长,超时就断开 size: size, sort: '@timestamp', body: { query: { bool: { must: [{ term: { 'fields.source': 'nginx' } }], must_not: [{ match: { message: 'log/getLocation log/getLocation push/register [notice] [alert] [emerg] "upstream time out" NGXSHARED.lua generic_host' } }] } } } }); if (scrollData) { let { body: { _scroll_id: scrollId, hits: { total: indexDocCnt, hits: rows } } } = scrollData; console.log('+++', indexName, indexDocCnt); for (let row of rows) { let str = await getOffUser(row._source.message); let csvRow = await anlysisFeilds(str); logger.info(JSON.stringify(str)); if (csvRow) { logcsv.info(csvRow.join(',')); } }; let idx = 0; while (scrollId) { let scrollData2 = await esClient.scroll({ scroll_id: scrollId, scroll: '1m' }); let { body: { _scroll_id: tempScrollId, hits: { hits: scrollHits } } } = scrollData2; for (let row of scrollHits) { let str = await getOffUser(row._source.message); logger.info(JSON.stringify(str)); let csvRow = await anlysisFeilds(str); if (csvRow) { logcsv.info(csvRow.join(',')); } }; if (scrollHits.length === 0) { console.log(JSON.stringify(scrollData2)); break; } console.log(`-- tempScrollId -- ${idx++} -- ${scrollHits.length} --`); scrollId = tempScrollId; } esClient.clearScroll({ scroll_id: scrollId }) .then((res) => { console.info('==========', res); }) .catch(err => { console.error(err); console.log('\naaaaaaa\n'); }); } } catch (err) { console.error('获取索引失败11'); console.error(err); return undefined; } }, async scroll (scrollId) { try { let scrollData = await esClient.scroll({ scroll_id: scrollId, scroll: '1m' }); } catch (err) { console.error('获取索引失败'); console.error(err); return undefined; } }, async clearScroll (scrollId) { try { let clsScroll = await esClient.clearScroll({ scroll_id: scrollId }); return clsScroll; } catch (err) { console.error('获取索引失败'); console.error(err); return undefined; } } };
var ProductDetail = {}; ProductDetail.init = function () { ProductDetail.productImageCarousel(); ProductDetail.onClickRatingStar(); ProductDetail.productVariationHandler(); ProductDetail.productVariationSwatchHandler(); }; // Carousel for Product Detail Main Images ProductDetail.productImageCarousel = function () { var imgset = 1; var productimages = $(".product-img-inner > img"); for (var j = 0; j < productimages.length; j += imgset) { productimages.slice(j, j + imgset).wrapAll("<div class='item'></div>"); } var productthumbs = $(".product-img-thumbs img"); for (var i = 0; i < productthumbs.length; i += imgset) { var productthumb = productthumbs.slice(i, i + imgset); // add a product-thumb-set frame only if not added yet if (!productthumb.parent().hasClass('product-thumb-set')) { var carousel = productthumb.closest('.row.product-details').find('.carousel.slide'); productthumb.wrapAll("<div class='product-thumb-set' data-target='#" + carousel.attr('id') + "'></div>"); // handle when the carousel is about to slide from one item to another to set the active image thumb carousel.on('slide.bs.carousel', function (event) { var from = $(event.target).find('.carousel-inner > .item.active').index(); var to = $(event.relatedTarget).index(); var carouselID = carousel.attr('id'); $(".product-thumb-set[data-target='#" + carouselID + "'][data-slide-to='" + from + "']").removeClass('active'); $(".product-thumb-set[data-target='#" + carouselID + "'][data-slide-to='" + to + "']").addClass('active'); }); } } // add data-slide-to attribute $.each($('.row.product-details'), function () { $.each($(this).find('.product-thumb-set'), function (index, value) { $(this).attr('data-slide-to', index); }); }); // make first thumb active if none is currently active $.each($('.product-img-thumbs'), function (index, value) { if ($(this).find('.product-thumb-set.active').length == 0) { $(this).find('.product-thumb-set:first-child').addClass('active'); } }); // handle clicking on thumbs $('.product-thumb-set').on('click', function () { $(this).parent().find('.product-thumb-set').removeClass('active'); $(this).addClass('active'); }); // make first set active $.each($('.carousel-inner.product-img-inner'), function () { if ($(this).find('.item.active').length == 0) { $(this).find('.item:first-child').addClass('active'); } }); }; /** * Update star field value and remove error message if display regarding star field */ ProductDetail.onClickRatingStar = function () { $(document).on('click', '.rating-input a', function () { // Set star value in hidden field $('input[name=' + $(this).data('field-name') + ']').val($(this).data('value')); // Set active class $('.rating-input').attr('class', 'rating-input ' + $(this).data('parent-class')); var formGroup = $(this).closest('.form-group'); // Remove error class from container $(formGroup).removeClass('has-error'); $(formGroup).find('.rating-star-required').remove(); // Submit button enabled if (!($(this).closest('form').find('.has-error').length > 0)) { $(this).closest('form').find('button[type=submit]').prop('disabled', false); } }); }; /** * Get the content of a changed product variation */ ProductDetail.productVariationSwatchHandler = function () { $(document).on("click", ".imageVariationListItem a", function () { var $container = $(this).closest('[data-dynamic-block]'); var currentClicked = $(this); var currentAttributeType = $(this).attr('data-variation-attribute'); var allAttributes = ProductDetail.extractAttributes($(this).closest('form'), currentClicked); var currentProductSKU = $container.attr('data-dynamic-block-product-sku'); //Search priority var productSearchAttributes = {}; productSearchAttributes['prioritySearchAttribute'] = currentAttributeType; productSearchAttributes['searchAttributes'] = allAttributes; ProductDetail.searchVariation(currentProductSKU, productSearchAttributes, $container); }); }; ProductDetail.productVariationHandler = function () { $(document).on("change", '.variation-attribute', function () { var $container = $(this).closest('[data-dynamic-block]'); var currentChanged = $(this); var currentAttributeType = $(this).attr('data-variation-attribute'); var allAttributes = ProductDetail.extractAttributes($(this).closest('form'), currentChanged); var currentProductSKU = $container.attr('data-dynamic-block-product-sku'); //Search priority var productSearchAttributes = {}; productSearchAttributes['prioritySearchAttribute'] = currentAttributeType; productSearchAttributes['searchAttributes'] = allAttributes; ProductDetail.searchVariation(currentProductSKU, productSearchAttributes, $container); }); }; //input com.intershop.sellside.rest.common.capi.resourceobject.ProductSearchAttributesRO as json and master product sku as string ProductDetail.searchVariation = function(masterProductSKU, productSearchAttributes, container) { productSearchAttributes['masterProductSKU'] = masterProductSKU; $.ajax({ dataType: 'json', type: 'post', contentType: 'application/json', data: JSON.stringify(productSearchAttributes), processData: false, url: RESTConfiguration.getBaseRESTUrl()+'products/'+masterProductSKU+'/variations/search', success: function (productVariation) { ProductDetail.getProductVariationContent(productVariation['sku'], container.attr("data-dynamic-block-call-parameters"), container); }, error: function (jqXHR, exception) { var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXHR.responseText; } console.error(msg); }, }); }; ProductDetail.extractAttributes = function(variationAttributesForm, current) { var variationAttributes = $(variationAttributesForm).find('.variation-attribute'); var variationAttributeValues = {}; $.each(variationAttributes, function (i, variationAttribute) { if ($(variationAttribute).is('ul')) { if(($(variationAttribute).attr('data-attribute-uuid') && current.closest('.variation-attribute').attr('data-attribute-uuid')) && $(variationAttribute).attr('data-attribute-uuid') == current.closest('.variation-attribute').attr('data-attribute-uuid')){ variationAttributeValues[current.attr('data-variation-attribute')] = current.attr('data-variation-product-attribute'); }else{ variationAttributeValues[$($(this).find('li > a[class="selected"]')).attr('data-variation-attribute')] = $($(this).find('li > a[class="selected"]')).attr('data-variation-product-attribute'); } } if ($(variationAttribute).is('select')) { variationAttributeValues[$(variationAttribute).attr('data-variation-attribute')] = $(variationAttribute).val(); } }); return variationAttributeValues; }; ProductDetail.getProductVariationContent = function (sku, callParameters, container) { // send an Ajax request for a given sku to get the different product content and the new content in the given container if (sku !== undefined) { $.ajax({ type: 'get', datatype: 'text/html', url: RetailShop.URLs.getProductComponents, data: '&SKU=' + sku + '&' + callParameters, success: function (data) { // replace the containers HTML with the content of the selected product variation container.replaceWith(data); // initialize the product image carousel if available within the container if (container.find('#prodimgcarousel').length > 0) { ProductDetail.productImageCarousel(); } // rebind bootstrapValidator at the relevant forms within the container Validation.bind($('form.bv-form')); }, error: function (jqXHR, exception) { var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXHR.responseText; } console.error(msg); } }); } }; //initialize all product detail functions $(document).ready(function () { ProductDetail.init(); });
"use strict"; // state chrome.storage.local.set({ tabs: {} }); // functions function valid(tabId) { chrome.storage.local.get("tabs", function ({ tabs }) { chrome.tabs.executeScript(tabId, { code: "document.body.classList.add('UI_Build_Assistant')" }); chrome.storage.local.set({ tabs: { ...tabs, [tabId]: true } }); }); } function invalid(tabId) { chrome.storage.local.get("tabs", function ({ tabs }) { chrome.tabs.executeScript(tabId, { code: "document.body.classList.remove('UI_Build_Assistant')" }); chrome.storage.local.set({ tabs: { ...tabs, [tabId]: false } }); }); } function initialize(tabId) { chrome.tabs.insertCSS(tabId, { file: "style.css" }); chrome.storage.local.get("tabs", function ({ tabs }) { if (tabs[tabId]) { valid(tabId); } }); } // events chrome.browserAction.onClicked.addListener(function ({ id: tabId }) { chrome.storage.local.get("tabs", function ({ tabs }) { tabs[tabId] ? invalid(tabId) : valid(tabId); }); }); chrome.tabs.onUpdated.addListener(function (tabId, { status }) { if (status !== "loading") { return; } initialize(tabId); });
import Component from '@ember/component'; import { htmlSafe } from '@ember/template'; import { computed } from '@ember/object'; import { run } from '@ember/runloop'; import $ from 'jquery'; import Ember from 'ember'; import layout from '../templates/components/paper-data-table-dialog-inner'; const { Handlebars: { Utils: { escapeExpression } } } = Ember; export default Component.extend({ layout, tagName: 'md-edit-dialog', attributeBindings: ['style'], width: null, transitionClass: 'ng', classNames: ['md-whiteframe-1dp'], style: computed('left','top','width',function() { let left = escapeExpression(this.get('left')); let top = escapeExpression(this.get('top')); let width = escapeExpression(this.get('width')); return htmlSafe(`left: ${left}px;top: ${top}px; min-width: ${width}px;`); }), positionDialog() { let element = this.get('element') || { clientWidth: 0, clientHeight: 0}; let size = { width: element.clientWidth, height: element.clientHeight }; let cellBounds = $(`#${this.get('parent')}`)[0].getBoundingClientRect(); let tableBounds = this._mdTableContainer.getBoundingClientRect(); if (size.width > tableBounds.right - cellBounds.left) { this.set('left',tableBounds.right - size.width); } else { this.set('left',cellBounds.left); } if (size.height > tableBounds.bottom - cellBounds.top) { this.set('top',tableBounds.bottom - size.height); } else { this.set('top',cellBounds.top + 1); } this.set('width',(this.get('row') ? tableBounds.width : cellBounds.width)); }, didInsertElement() { this._super(...arguments); this._mdTableContainer = this.$().closest('md-table-container')[0]; $(window).on('resize', this.positionDialog.bind(this)); run.scheduleOnce('afterRender', this, function() { this.positionDialog(); this.$('input').first().focus(); }); }, willDestroyElement() { this._super(...arguments); $(window).off('resize', this.positionDialog.bind(this)); } });
import React from 'react'; import { Card } from '../commons/Card'; import AnswerCard from './AnswerCard'; export default function GuessOrWait({ question, guess, guessed }) { const questionAskedButNotAnswered = question && !guessed; return questionAskedButNotAnswered ? ( <AnswerCard question={question} guess={guess} /> ) : ( <Card> please wait for{' '} {guessed ? 'other players to guess' : 'dealer to ask Question...'} </Card> ); }
const assert = require('assert'); const HDWalletProvider = require('truffle-hdwallet-provider'); const Web3 = require('web3'); const {interface,bytecode} = require('../compile'); const provider = new HDWalletProvider( 'recycle diamond reward swift insect fault suit measure friend bundle dinosaur observe', 'ropsten.infura.io/v3/2ec2a1f3b4714294907cd7bd4ae1d3ef' ); const web3 = new Web3(provider); // const deploy = async()=>{ // const accounts = await web3.eth.getAccounts(); // aconsole.log('Attemp to deploy contract', accounts[0]); // const Web4 = require('web3aaa'); // }; // deploy(); beforeEach(async()=>{ const accounts = await web3.eth.getAccounts(); aconsole.log('Attemp to deploy contract', accounts[0]); }) describe('deploy test',()=>{ it('Attemp to deploy contract', ()=>{ //var me = new person(); assert.equal('eat', 'eat'); }) })
import { NavigationContainer } from "@react-navigation/native"; import { useFonts } from "expo-font"; import React from "react"; import { UserStore } from "./src/contexts/UserContext"; import MyStackNavigator from "./src/navigation/MyStackNavigator"; import Toast from "react-native-toast-message"; export default function App() { const [fontLoaded] = useFonts({ MonCricket: require("./assets/fonts/MonCricket.ttf"), }); if (!fontLoaded) { return null; } return ( <> <NavigationContainer> <UserStore> <MyStackNavigator /> </UserStore> </NavigationContainer> <Toast ref={(ref) => Toast.setRef(ref)} /> </> ); }
// template for testing components describe('sampleComponent', function() { // Load the module that contains the `phoneList` component before each test beforeEach(module('musicApp')); // Test the controller describe('sampleController', function() { it('should set internal greeting var to hi on init', inject(function($componentController) { var ctrl = $componentController('sampleComponent'); //at this point, template and controller are already linked // and executed. since the controller and view are linked, // the controller function shouldnt really return a value and we // shouldnt expect one, just roll with tre scope variable testing expect(ctrl.greeting).toEqual('hi'); })); }); });
import React from 'react'; import './Sections.css' import secBackgroung from "./resources/SectionsBackground.png" import sec1Img from "./resources/sec1.png" import sec2Img from "./resources/sec2.png" import sec12Img from "./resources/sec12.png" import sec14Img from "./resources/sec14.png" import sec15Img from "./resources/sec15.png" const imgStyle = { display: 'block', zIndex:-1, position: 'absolute', width:'100%' }; const ulStyle = { zIndex:2, position: 'absolute' }; const sec1Style = { marginTop: '15vh', marginLeft: '9vh' }; const sec2Style = { marginTop: '15vh', marginLeft: '9vh' }; const sec12Style = { marginTop: '15vh', marginLeft: '13vh' }; const sec14Style = { marginTop: '15vh', marginLeft: '18vh' }; const sec15Style = { marginTop: '15vh', marginLeft: '19vh' }; class Sections extends React.Component { render() { return ( <div> <img src={secBackgroung} style={imgStyle} /> <div> <img class="hvr-grow" src={sec1Img} style={sec1Style}/> <img class="hvr-grow" src={sec2Img} style={sec2Style}/> <img class="hvr-grow" src={sec12Img} style={sec12Style}/> <img class="hvr-grow" src={sec14Img} style={sec14Style}/> <img class="hvr-grow" src={sec15Img} style={sec15Style}/> </div> </div> ); } } // <ul style={ulStyle}> // <li>Mador 1</li> // <li>Mador 2</li> // <li>Mador 12</li> // <li>Mador 14</li> // <li>Mador 15</li> // </ul> export default Sections;
import * as types from "../types/index" const initstate = { auth: false } export const reducer = (state = initstate, action) => { if (action.type == types.LoginToken) { return { ...state, auth: true } } if (action.type == types.currentUser) { const data = action.payload return { ...state, auth: true, email: data.email, name: data.name } } if (action.type == types.LOGOUT) { return { ...state, auth: false } } return { ...state } }
/*jshint esversion: 6 */ /* In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p piece 2p piece 5p piece 10p piece 20p piece 50p piece £1 (100p) £2 (200p) It is possible to make £2 in the following way: 1 * £1 + 1 * 50p + 2 * 20p + 1 * 5p + 1 * 2p + 3 * 1p How many different ways can £2 be made using any number of coins? example usage of `makeChange`: // aka, there's only one way to make 1p. that's with a single 1p piece makeChange(1) === 1 // aka, there's only two ways to make 2p. that's with two, 1p pieces or with a single 2p piece makeChange(2) === 2 */ var makeChange = function(total) { if (!total) { return 1; } let coinsUsed = {}; let pieces = [1, 2, 5, 10, 20, 50, 100, 200]; let combos = (currentInputValue, coins) => { if (currentInputValue === 0) { coins = JSON.stringify(coins.sort()); if (!coinsUsed[coins]) { coinsUsed[coins] = true; return; } else { return; } } else if (currentInputValue < 0) { return; } for (var i = pieces.length - 1; i > -1; i--) { combos(currentInputValue - pieces[i], coins.concat([pieces(i)])); } }; combos(total, []); return Object.keys(coinsUsed).length; }; module.exports = makeChange;
import {Form, Progress, Icon, Upload, Input, Button, Radio, Select, message, InputNumber} from 'antd'; import React, {Component} from 'react'; import {upLoad} from '../../requests/http-req.js'; const RadioGroup = Radio.Group; const FormItem = Form.Item; const Option = Select.Option; class InviteEdit extends Component { state = { description: null, linkUrl: null, logo: null, title: null, percent: 0, }; handleSubmit = () => { const {description, linkUrl, logo, title} = this.state if (linkUrl == null || logo == null || logo == null || title == null) { message.warning('信息不完整') return } let tem = {description: description, linkUrl: linkUrl, logo: logo, title: title} if (this.itemData) { //更新 tem.id = this.itemData.id tem.createTime = this.itemData.createTime this.props.upData(tem) } else { this.props.onSave(tem) } } componentDidMount() { // } componentWillMount() { this.itemData = this.props.itemData || null if (this.itemData) { this.state.description = this.itemData.description, this.state.linkUrl = this.itemData.linkUrl, this.state.logo = this.itemData.logo, this.state.title = this.itemData.title } } uploadImg = (file) => { // file.onProgress({percent: 0.8}) let fordata = new FormData() fordata.append('type', 'logo'); fordata.append('file ', file.file); upLoad(fordata, (e) => { let count = ( (e.loaded / e.total) * 100).toFixed(2) if (count == 100) { percent:0 } else { this.setState({ percent: count }) } }).then(res => {//absolutePath relativePath file.onSuccess() this.setState({ logo: res.data.data.relativePath, percent: 0 }) }).catch(e => { if (e) { file.onError() this.setState({ percent: 0 }) message.warning('失败,检查网络') } }) } handleChange = (info) => { const isLt1M = info.file.size / 1024 / 1024 < 2; if (!isLt1M) { return } let arr = info.file.name.split('.') let imgs = ['jpg', 'jpeg', 'png', 'png', 'jpg'] if (imgs.indexOf(arr[1]) == -1) { return } let fileList = [] fileList.push(info.fileList[info.fileList.length - 1]) this.setState({fileList}); } render() { const {getFieldDecorator} = this.props.form; const formItemLayout = { labelCol: { sm: {span: 8},//24 }, }; const props = { accept: 'image/*', customRequest: (e) => { this.uploadImg(e) }, beforeUpload: (file) => { const isLt1M = file.size / 1024 / 1024 < 2; if (!isLt1M) { message.warning('币种图片不能超过2M') return false } let arr = file.name.split('.') let imgs = ['jpg', 'jpeg', 'png', 'png', 'jpg'] if (imgs.indexOf(arr[1]) == -1) { message.warning('只能选择图片') return false } else { return true; } }, onChange: this.handleChange, listType: 'picture', onRemove: (file) => { this.setState(({fileList}) => { const index = fileList.indexOf(file); const newFileList = fileList.slice(); newFileList.splice(index, 1); return { fileList: newFileList, percent: 0 }; }); } }; return ( <Form> <FormItem {...formItemLayout} label="Logo" > <Upload {...props} fileList={this.state.fileList} style={{width: 300}}> <Button> <Icon title="upload"/> {this.state.logo ? '更改' : '上传'} </Button> {this.state.percent > 0 && this.state.percent < 100 ? <Progress showInfo={false} width={250} status="active" percent={this.state.percent}/> : null} </Upload> </FormItem> <FormItem {...formItemLayout} label="描述" > <Input value={this.state.description} onChange={(e) => { this.setState({description: e.target.value}) }} style={{width: 300}}/> </FormItem> <FormItem {...formItemLayout}//linkUrl label="链接地址" > <Input value={this.state.linkUrl} onChange={(e) => { this.setState({linkUrl: e.target.value}) }} style={{width: 300}}/> </FormItem> <FormItem {...formItemLayout} label="标题" > <Input value={this.state.title} onChange={(e) => { this.setState({title: e.target.value}) }} style={{width: 300}}/> </FormItem> <Button style={{width: '100%'}} onClick={this.handleSubmit}>{this.itemData ? '修改' : '保存'}</Button> </Form> ); } } const NewInviteEdit = Form.create()(InviteEdit); export default NewInviteEdit;