text
stringlengths
7
3.69M
function solve(firstNum, secondNum){ let firstFactoriel = calculateFactoriel(firstNum); let secondFactoriel = calculateFactoriel(secondNum); let result = firstFactoriel / secondFactoriel; console.log(result.toFixed(2)); function calculateFactoriel(n){ if(n === 1){ return 1; } return n * calculateFactoriel(n - 1); } } solve(5, 2)
import { CHANGE_MODAL_VISIBLE, BLOCK, BLOCKEDUSERS, UNLOCKUSERS } from './action-types' export const showModalAction = (record) => { return { type: CHANGE_MODAL_VISIBLE, content: record } } export const blockUser = (index) => { return { type: BLOCK, blockUserId: index } } export const blockedUsers = (arr) => { return { type: BLOCKEDUSERS, blockedUsers: arr } } export const unlockUser = (index) => { return { type: UNLOCKUSERS, unlockUserId: index } }
import { useQuery } from "react-query"; import { getMovieDetails } from "../api/movie"; export const useMovieDetails = (imdbId) => { return useQuery(["movie", imdbId], () => getMovieDetails(imdbId), { enabled: !!imdbId, }); };
import React from 'react'; const Screen = (props) => { return( <div className="fl w-100"> <input type="text" placeholder={props.text} value={props.text} className="dib pa3 ma2 bg-light-gray ba2 fl w-100"/> </div> ); } export default Screen;
var form = document.getElementById('contact-form'); form.addEventListener("focusout", isValid); form.addEventListener('focusin', removePlaceholder); function removePlaceholder(el){ if(el.target.type === "textarea" && el.target.value === "Nachricht"){ el.target.value = ""; } } //sets final state class for better design function setFillState(el) { if (el.target.value !== "" && el.target.type !== "textarea") { addClassToLbl(el, 'is-filled'); } } function addClassToLbl(el, className) { if (el.target.nextElementSibling.tagName === "LABEL") { el.target.nextElementSibling.classList.add(className); } } function removeClassFromLbl(el, className) { if (el.target.nextElementSibling.tagName === "LABEL") { el.target.nextElementSibling.classList.remove(className); } } function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function validateNumber(email) { var re = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/; return re.test(String(email).toLowerCase()); } function isValid(el) { var type = el.target.type; var value = el.target.value; switch (type) { case "text": if (value !== "") { setFillState(el); addClassToLbl(el, 'is-valid'); } else { removeClassFromLbl(el, 'is-valid'); } break; case "email": if (value !== "") { setFillState(el); if (validateEmail(value)) { removeClassFromLbl(el, 'is-invalid'); addClassToLbl(el, 'is-valid'); } else { addClassToLbl(el, 'is-invalid'); } } break; case "tel": if (value !== "") { setFillState(el); if (validateNumber(value)) { removeClassFromLbl(el, 'is-invalid'); addClassToLbl(el, 'is-valid'); } else { addClassToLbl(el, 'is-invalid'); } } break; default: break; } }
var dummybase = [ {fortune: 'Today its up to you to create the peacefulness you long for.', user: 'David'}, { fortune: 'A friend asks only for your time not your money.', user: 'Someone' }, { fortune: 'There is a true and sincere friendship between you and your friends.', user: 'Someone' }, { fortune: 'You find beauty in ordinary things, do not lose this ability.', user: 'Someone' }, { fortune: 'Ideas are like children; there are none so wonderful as your own.', user: 'Someone' }, { fortune: 'It takes more than good memory to have good memories.', user: 'Someone' }, { fortune: 'A thrilling time is in your immediate future.', user: 'Someone' }, { fortune: 'Your blessing is no more than being safe and sound for the whole lifetime.', user: 'Someone' }, { fortune: 'Plan for many pleasures ahead.', user: 'Someone' }, { fortune: 'The joyfulness of a man prolongeth his days.', user: 'Someone' }, { fortune: 'Your everlasting patience will be rewarded sooner or later.', user: 'Someone' }, { fortune: 'Make two grins grow where there was only a grouch before.', user: 'Someone' }, { fortune: 'Something you lost will soon turn up.', user: 'Someone' }, { fortune: 'Your heart is pure, and your mind clear, and your soul devout.', user: 'Someone' }, { fortune: 'Excitement and intrigue follow you closely wherever you go!', user: 'Someone' }, { fortune: 'A pleasant surprise is in store for you.', user: 'Someone' }, { fortune: 'May life throw you a pleasant curve.', user: 'Someone' }, { fortune: 'As the purse is emptied the heart is filled.', user: 'Someone' }, { fortune: 'Be mischievous and you will not be lonesome.', user: 'Someone' }, { fortune: 'You have a deep appreciation of the arts and music.', user: 'Someone' }, { fortune: 'Your flair for the creative takes an important place in your life.', user: 'Someone' }, { fortune: 'Your artistic talents win the approval and applause of others.', user: 'Someone' }, { fortune: 'Pray for what you want, but work for the things you need.', user: 'Someone' }, { fortune: 'Your many hidden talents will become obvious to those around you.', user: 'Someone' }, { fortune: 'Dont forget, you are always on our minds.', user: 'Someone' }, { fortune: 'Your greatest fortune is the large number of friends you have.', user: 'Someone' }, { fortune: 'A firm friendship will prove the foundation on your success in life.', user: 'Someone' }, { fortune: 'Look for new outlets for your own creative abilities.', user: 'Someone' }, { fortune: 'Be prepared to accept a wondrous opportunity in the days ahead!', user: 'Someone' }, { fortune: 'Fame, riches and romance are yours for the asking.', user: 'Someone' }, { fortune: 'Good luck is the result of good planning.', user: 'Someone' }, { fortune: 'Good things are being said about you.', user: 'Someone' }, { fortune: 'Smiling often can make you look and feel younger.', user: 'Someone' }, { fortune: 'Someone is speaking well of you.', user: 'Someone' }, { fortune: 'The time is right to make new friends.', user: 'Someone' }, { fortune: 'You will inherit some money or a small piece of land.', user: 'Someone' }, { fortune: 'Your life will be happy and peaceful.', user: 'Someone' }, { fortune: 'A friend is a present you give yourself.', user: 'Someone' }, { fortune: 'A member of your family will soon do something that will make you proud.', user: 'Someone' }, { fortune: 'A quiet evening with friends is the best tonic for a long day.', user: 'Someone' }, { fortune: 'A single kind word will keep one warm for years.', user: 'Someone' }, { fortune: 'Anger begins with folly, and ends with regret.', user: 'Someone' }, { fortune: 'Generosity and perfection are your everlasting goals.', user: 'Someone' }, { fortune: 'Happy news is on its way to you.', user: 'Someone' }, { fortune: 'He who laughs at himself never runs out of things to laugh at.', user: 'Someone' }, { fortune: 'If your desires are not extravagant they will be granted.', user: 'Someone' }, { fortune: 'Let there be magic in your smile and firmness in your handshake.', user: 'Someone' }, { fortune: 'If you want the rainbow, you must to put up with the rain.', user: 'Someone' }, ]; var chineseDictonary = [ { english: 'Hello', chinese: '您好', pronunciation: 'Nín hǎo' }, { english: 'Goodbye', chinese: '再见', pronunciation: 'Zàijiàn' }, { english: 'China', chinese: '中国', pronunciation: 'Zhōngguó' }, { english: 'America', chinese: '美国', pronunciation: 'Měiguó' }, { english: 'Student', chinese: '学生', pronunciation: 'Xuéshēng' }, { english: 'Austin', chinese: '奥斯汀', pronunciation: 'Àosītīng' }, { english: 'Dog', chinese: '狗', pronunciation: 'Gǒu' }, { english: 'Cat', chinese: '猫', pronunciation: 'Māo' }, { english: 'Monkey', chinese: '猴', pronunciation: 'Hóu' }, { english: 'North', chinese: '北', pronunciation: 'Běi' }, { english: 'South', chinese: '南', pronunciation: 'Nán' }, { english: 'Europe', chinese: '欧洲', pronunciation: 'Ōuzhōu' }, { english: 'Magic', chinese: '魔法', pronunciation: 'Mófǎ' }, { english: 'Computer', chinese: '计算机', pronunciation: 'Jìsuànjī' }, { english: 'Ninja', chinese: '忍者', pronunciation: 'Rěnzhě' }, { english: 'Internet', chinese: '因特网', pronunciation: 'Yīntèwǎng' }, { english: 'Dragon', chinese: '龙', pronunciation: 'Lóng' }, { english: 'Pirate', chinese: '海盗', pronunciation: 'Hǎidào' }, ]
$(document).ready(function(){ OrderView.init(); }) var OrderView = { init: function() { var orderJson = JSON.parse($('#orderRawData').val()); var node = new PrettyJSON.view.Node({ el:$('#orderJson'), data: orderJson }) }, history: function (id) { $("#item-"+id).toggle(); //$("#item-"+id).show(); } }
'use strict'; /** * @ngdoc service * @name thelistwebApp.restService * @description * # restService * Factory in the thelistwebApp. */ angular.module('thelistwebApp') .factory('restService', ['$http', function ($http) { var baseUrl = 'http://localhost:8888/'; // var baseUrl = 'https://2-dot-thelisttest.appspot.com/'; // var baseUrl = 'https://duochjagthelist.appspot.com/'; return { get: function (path) { return $http.get(baseUrl + path); }, put: function (path, data) { return $http.put(baseUrl + path, data); }, post: function (path, data) { return $http.post(baseUrl + path, data); }, setHeaders: function (user) { $http.defaults.headers.common['Username'] = user.username; $http.defaults.headers.common['Authorization'] = user.authtoken; }, resetHeaders: function () { $http.defaults.headers.common['Username'] = undefined; $http.defaults.headers.common['Authorization'] = undefined; } }; }]);
const mongoose= require('mongoose'); const Schema = mongoose.Schema; const TaskSchema = new Schema({ title: String, email:String, monto:String, carrera:String, grupo:String, telefono:String, description: String, status:{ type:Boolean, default:false } }) module.exports = mongoose.model('tasks',TaskSchema);
import React from 'react'; import ReactDOM from 'react-dom'; // Styles import "./style/css/main.css" //Views import App from './App' const root = document.querySelector("#__body"); ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, root );
import React from 'react' import ExitIcon from 'material-ui/svg-icons/action/exit-to-app' import UsersIcon from 'material-ui/svg-icons/social/people' import DashboardIcon from 'material-ui/svg-icons/action/dashboard' import SupportIcon from 'material-ui/svg-icons/communication/chat' import IconButton from './IconButton' // Raised buttons export PrimaryButton from './PrimaryButton' export SecondaryButton from './SecondaryButton' // Flat with icons buttons export const IconExitButton = props => <IconButton icon={<ExitIcon />} {...props} /> export const IconUsersButton = props => <IconButton icon={<UsersIcon />} {...props} /> export const IconDashboardButton = props => <IconButton icon={<DashboardIcon />} {...props} /> export const IconSupportButton = props => <IconButton icon={<SupportIcon />} {...props} />
import React, { Component } from 'react'; import './publish.scss'; import ReactQuill from 'react-quill'; // ES6 import 'react-quill/dist/quill.snow.css'; // ES6 import * as util from '../../assets/util' import { Button, Input, message } from 'antd'; export default class List extends Component { constructor(props) { super(props) this.state = { url: 'http://127.0.0.1:7777/publish', title: '', text: '' } // You can also pass a Quill Delta here this.handleChangeDetail = this.handleChangeDetail.bind(this) this.handleChangeTitle = this.handleChangeTitle.bind(this) this.publish = this.publish.bind(this) } handleChangeTitle(event) { this.setState({ title: event.target.value }) } handleChangeDetail(value) { this.setState({ text: value }) } async publish () { console.log(this.state.title) console.log(this.state.text) try { await util.httpPost(this.state.url, { title: this.state.title, text: this.state.text }) // console.log(res) this.setState({title: ''}) this.setState({text: ''}) message.info('发布成功~') } catch (error) { message.info('发布失败~') console.log(error) } } render() { return ( <div className="publish-page"> <div className="title">写文章</div> <Input className="artcle-title" value={this.state.title} onChange={this.handleChangeTitle} placeholder="请输入文章标题"/> <ReactQuill value={this.state.text} onChange={this.handleChangeDetail} /> <Button className="publish-btn" onClick={this.publish} type="primary">发布文章</Button> <Button className="publish-btn" onClick={() => this.props.history.push('/list')} type="primary">回到列表页</Button> </div> ) } }
var app = angular.module('starterApp', [ 'ngRoute', 'ngMessages', 'ngMaterial' ]); app.config([ '$routeProvider', '$mdThemingProvider', function($routeProvider, $mdThemingProvider) { $routeProvider .when('/', { templateUrl: 'partials/home.tmpl.html' }) .when('/layout/:tmpl', { templateUrl: function(params){ return 'partials/layout-' + params.tmpl + '.tmpl.html'; } }) .when('/layout/', { redirectTo: '/layout/introduction' }) .when('/getting-started', { templateUrl: 'partials/getting-started.tmpl.html' }) .when('/license', { templateUrl: 'partials/license.tmpl.html' }); $mdThemingProvider.definePalette('docs-blue', $mdThemingProvider.extendPalette('blue', { '50': '#DCEFFF', '100': '#AAD1F9', '200': '#7BB8F5', '300': '#4C9EF1', '400': '#1C85ED', '500': '#106CC8', '600': '#0159A2', '700': '#025EE9', '800': '#014AB6', '900': '#013583', 'contrastDefaultColor': 'light', 'contrastDarkColors': '50 100 200 A100', 'contrastStrongLightColors': '300 400 A200 A400' })); $mdThemingProvider.definePalette('docs-red', $mdThemingProvider.extendPalette('red', { 'A100': '#DE3641' })); $mdThemingProvider.theme('docs-dark', 'default') .primaryPalette('yellow') .dark(); $mdThemingProvider.theme('default') .primaryPalette('docs-blue') .accentPalette('docs-red'); $routeProvider.otherwise('/'); }]); app.factory('menu', [ '$location', '$rootScope', '$http', '$window', function($location, $rootScope, $http, $window) { var version = {}; var sections = [{ name: 'Getting Started', url: 'getting-started', type: 'link' }]; var demoDocs = []; sections.push({ name: 'Customization', type: 'heading', children: [ { name: 'CSS', type: 'toggle', pages: [{ name: 'Typography', url: 'CSS/typography', type: 'link' }, { name : 'Button', url: 'CSS/button', type: 'link' }, { name : 'Checkbox', url: 'CSS/checkbox', type: 'link' }] }, { name: 'Theming', type: 'toggle', pages: [ { name: 'Introduction and Terms', url: 'Theming/01_introduction', type: 'link' }, { name: 'Declarative Syntax', url: 'Theming/02_declarative_syntax', type: 'link' }, { name: 'Configuring a Theme', url: 'Theming/03_configuring_a_theme', type: 'link' }, { name: 'Multiple Themes', url: 'Theming/04_multiple_themes', type: 'link' }, { name: 'Under the Hood', url: 'Theming/05_under_the_hood', type: 'link' } ] } ] }); var self; $rootScope.$on('$locationChangeSuccess', onLocationChange); return self = { version: version, sections: sections, selectSection: function(section) { self.openedSection = section; }, toggleSelectSection: function(section) { self.openedSection = (self.openedSection === section ? null : section); }, isSectionSelected: function(section) { return self.openedSection === section; }, selectPage: function(section, page) { self.currentSection = section; self.currentPage = page; }, isPageSelected: function(page) { return self.currentPage === page; } }; function onLocationChange() { var path = $location.path(); var introLink = { name: "Introduction", url: "/", type: "link" }; if (path == '/') { self.selectSection(introLink); self.selectPage(introLink, introLink); return; } var matchPage = function(section, page) { if (path.indexOf(page.url) !== -1) { self.selectSection(section); self.selectPage(section, page); } }; sections.forEach(function(section) { if (section.children) { // matches nested section toggles, such as API or Customization section.children.forEach(function(childSection){ if(childSection.pages){ childSection.pages.forEach(function(page){ matchPage(childSection, page); }); } }); } else if (section.pages) { // matches top-level section toggles, such as Demos section.pages.forEach(function(page) { matchPage(section, page); }); } else if (section.type === 'link') { // matches top-level links, such as "Getting Started" matchPage(section, section); } }); } }]) .directive('menuLink', function() { return { scope: { section: '=' }, templateUrl: 'partials/menu-link.tmpl.html', link: function($scope, $element) { var controller = $element.parent().controller(); $scope.isSelected = function() { return controller.isSelected($scope.section); }; $scope.focusSection = function() { // set flag to be used later when // $locationChangeSuccess calls openPage() controller.autoFocusContent = true; }; } }; }); app.directive('mastMenu', [ '$timeout', '$mdUtil', function($timeout, $mdUtil) { return { templateUrl: 'partials/mast-menu.tmpl.html' } }]); app.directive('menuToggle', [ '$timeout', '$mdUtil', function($timeout, $mdUtil) { return { scope: { section: '=' }, templateUrl: 'partials/menu-toggle.tmpl.html', link: function($scope, $element) { var controller = $element.parent().controller(); $scope.isOpen = function() { return controller.isOpen($scope.section); }; $scope.toggle = function() { controller.toggleOpen($scope.section); }; $mdUtil.nextTick(function() { $scope.$watch( function () { return controller.isOpen($scope.section); }, function (open) { var $ul = $element.find('ul'); var targetHeight = open ? getTargetHeight() : 0; $timeout(function () { $ul.css({height: targetHeight + 'px'}); }, 0, false); function getTargetHeight() { var targetHeight; $ul.addClass('no-transition'); $ul.css('height', ''); targetHeight = $ul.prop('clientHeight'); $ul.css('height', 0); $ul.removeClass('no-transition'); return targetHeight; } } ); }); var parentNode = $element[0].parentNode.parentNode.parentNode; if(parentNode.classList.contains('parent-list-item')) { var heading = parentNode.querySelector('h2'); $element[0].firstChild.setAttribute('aria-describedby', heading.id); } } }; }]) .controller('DocsCtrl', [ '$scope', '$mdSidenav', '$timeout', '$mdDialog', 'menu', '$location', '$rootScope', function($scope, $mdSidenav, $timeout, $mdDialog, menu, $location, $rootScope) { var self = this; $scope.menu = menu; $scope.path = path; $scope.goHome = goHome; $scope.openMenu = openMenu; $scope.closeMenu = closeMenu; $scope.isSectionSelected = isSectionSelected; // Grab the current year so we don't have to update the license every year $scope.thisYear = (new Date()).getFullYear(); $rootScope.$on('$locationChangeSuccess', openPage); $scope.focusMainContent = focusMainContent; //-- Define a fake model for the related page selector Object.defineProperty($rootScope, "relatedPage", { get: function () { return null; }, set: angular.noop, enumerable: true, configurable: true }); $rootScope.redirectToUrl = function(url) { $location.path(url); $timeout(function () { $rootScope.relatedPage = null; }, 100); }; // Methods used by menuLink and menuToggle directives this.isOpen = isOpen; this.isSelected = isSelected; this.toggleOpen = toggleOpen; this.autoFocusContent = false; var mainContentArea = document.querySelector("[role='main']"); // ********************* // Internal methods // ********************* function closeMenu() { $timeout(function() { $mdSidenav('left').close(); }); } function openMenu() { $timeout(function() { $mdSidenav('left').open(); }); } function path() { return $location.path(); } function goHome($event) { menu.selectPage(null, null); $location.path( '/' ); } function openPage() { $scope.closeMenu(); if (self.autoFocusContent) { focusMainContent(); self.autoFocusContent = false; } } function focusMainContent($event) { // prevent skip link from redirecting if ($event) { $event.preventDefault(); } $timeout(function(){ mainContentArea.focus(); },90); } function isSelected(page) { return menu.isPageSelected(page); } function isSectionSelected(section) { var selected = false; var openedSection = menu.openedSection; if(openedSection === section){ selected = true; } else if(section.children) { section.children.forEach(function(childSection) { if(childSection === openedSection){ selected = true; } }); } return selected; } function isOpen(section) { return menu.isSectionSelected(section); } function toggleOpen(section) { menu.toggleSelectSection(section); } }]) .filter('nospace', function () { return function (value) { return (!value) ? '' : value.replace(/ /g, ''); }; }) .filter('humanizeDoc', function() { return function(doc) { if (!doc) return; if (doc.type === 'directive') { return doc.name.replace(/([A-Z])/g, function($1) { return '-'+$1.toLowerCase(); }); } return doc.label || doc.name; }; }) .filter('directiveBrackets', function() { return function(str) { if (str.indexOf('-') > -1) { return '<' + str + '>'; } return str; }; }); app.controller('HomeCtrl', [ '$scope', '$rootScope', function($scope, $rootScope) { $rootScope.currentComponent = $rootScope.currentDoc = null; }]);
// create custom component var TimerExample = React.createClass({ getInitialState: function () { // called before render function // object returned is assigned to this.state, for late reuse return { elapsed: 0 }; }, componentDidMount: function () { // componentDidMount is called by reacvt when comp rendered // on the page, we set the interval here this.timer = setInterval(this.tick, 50); }, componentWillUnmount: function () { // this method is called before the comp is removed // from page and destroyed, we clear the interv here clearInterval(this.timer); }, tick: function () { // called every 50ms, updates elapsed counter. calling setState // caused comp rerender this.setState({ elapsed: new Date() - this.props.start }); }, render: function () { var elapsed = Math.round(this.state.elapsed / 100); var seconds = (elapsed / 10).toFixed(1); // react will smartly update only the changed parts return <p>This example was started <b>{seconds}</b> ago</p>; } }); React.renderComponent( <TimerExample start={Date.now()} />, document.body );
// Evolutility-UI-React :: /views/one/Card.js // Single card (usually part of a set of Cards) // https://github.com/evoluteur/evolutility-ui-react // (c) 2017 Olivier Giulieri import React from 'react' import models from '../../../models/all_models' import format from '../../utils/format' import { Link } from 'react-router' export default React.createClass({ viewId: 'card', propTypes: { entity: React.PropTypes.string.isRequired, fields: React.PropTypes.array, data: React.PropTypes.object }, render() { const d = this.props.data || {}, fields = this.props.fields || [], entity = this.props.entity, m = models[entity], link = '/'+entity+'/browse/'; return ( <div className="panel panel-default"> {fields.map(function(f, idx){ const attr = f.id; const fv = format.fieldValue(f, d[attr]) const icon = m.icon ? <img className="evol-many-icon" src={'/pix/'+m.icon}/> : null if(idx===0){ return ( <div key={idx}> <h4><Link key={f.id} to={link+d.id}>{icon}{fv}</Link></h4> </div> ) }else if(f.type=='image'){ return <div key={idx}>{fv}</div> }else{ return ( <div key={idx}> <label>{f.label}: </label> <div>{' '}{fv}</div> </div> ) } })} </div> ) } })
var GameManager = new function() { var RP_URL = null; var tutorialState = false; var isFirstConn = false; var userText = ["임시사용자", "-"]; this.getUserText = function() { return userText; }; this.getFirstConn = function() { return isFirstConn; }; this.init = function(onload) { loadStarmonScripts(function() { var compCnt=0; var complete=function(){ compCnt++; if(compCnt==3){ onload(); } } POPUP.POP_WAITING.setResource(complete); POPUP.POP_MSG_0BTN.setResource(complete); UIMgr.setFPS(12); ResourceMgr.setTimeoutListener(function(){GameManager.openDisconnectPopup("Resource Timeout!!!")}); GameManager.connect(complete); }); }; this.connect = function(onload) { onload(); GF_NET.Connection(function(response) { if (NetManager.isSuccess(response)) { userText[0] = NetManager.getResult(response, 0).userId; userText[1] = "어서오세요~ 반갑습니다!!"; RP_URL = NetManager.getRsPath(); initManager(); // BTV 관련 아이디가 무명등록으로 들어올시 안드로이드 셋탑박스 이름으로 변경 if (userText[0].substr(0, 2) == "무명") { NetManager.Req_ReplaceUserId(); } if (NetManager.getResult(response, 0).connCount == 0) { NetManager.Req_todayInit(function(response) { if (NetManager.isSuccess(response)) { isFirstConn = true; } else { GameManager.openDisconnectPopup("todayInit fail", this); } }); // EventHelper.eventSetting(true); // 해당 날짜 첫 출석인지 아닌지 true : false } else { isFirstConn = false; // EventHelper.eventSetting(false); } onload(); } else { // 로그인 실패 this.openDisconnectPopup("Login Fail!!"); } }); // 서버접속 }; var initManager = function() { TokenManager.update(); // RaidModeManager.update(); }; this.getRP_URL = function() { // return RP_URL + DMC_NAME + "/"; return "http://61.251.167.91/html5/DefenceGame/"; }; this.changeLayer = function(layer, showLoading, nextIFrame) { SCENE.SC_CHANGER.getInstance().setNextScene(layer, showLoading, nextIFrame); UIMgr.changeLayer(SCENE.SC_CHANGER); }; var soundPath; this.playNetSound = function(_path) { if (!(_path in HSoundMgr.soundMap)) { HSoundMgr.add(_path, _path); HSoundMgr.playSound(_path) } else { HSoundMgr.playSound(_path); } }; this.loopNetSound = function(_path) { // if (_path == soundPath) return; // if (soundPath in HSoundMgr.soundMap) // HSoundMgr.stopSound(soundPath); // soundPath = _path; // if (!(soundPath in HSoundMgr.soundMap)) { // HSoundMgr.add(soundPath, soundPath); // HSoundMgr.loopSound(soundPath) // } else { // HSoundMgr.loopSound(soundPath); // } android.loopSound(_path); }; this.stopSound = function() { // HSoundMgr.stopSoundAll(); // soundPath = null; android.stopSound(); }; this.replaceNetIFrame = function (path, onload) { var iframe = new Image(); ResourceMgr.loadImage(iframe, path, function () { if(onload) onload(iframe); }, function () { appMgr.openDisconnectPopup("replaceNetIfrme load fail!"); return null; }); }; /** 통신장애 팝업 */ this.openDisconnectPopup = function(string, owner) { HLog.err(string, null, owner); PopupMgr.openPopup(POPUP.POP_ERROR, null); }; this.getMessage0BtnPopup = function(msg) { Message0BtnPopup.getInstance().setMessage(msg); return Message0BtnPopup; }; this.getMessage1BtnPopup = function(msg) { Message1BtnPopup.getInstance().setMessage(msg); return Message1BtnPopup; }; this.getMessage2BtnPopup = function(msg, str) { if (str == null) { Message2BtnPopup.getInstance().setMessage(msg); } else { Message2BtnPopup.getInstance().setMessage(msg, str); } return Message2BtnPopup; }; this.getTutorialState = function () { return tutorialState; }; this.setTutorialState = function (state) { tutorialState = state; }; this.goGniPortal = function() { HLog.sys("Go To GniPortal Start!!~~"); var openLink = function(redirectURL) { try { var xhr = new XMLHttpRequest(); var ajaxTTimeout = function() { xhr.abort(); // KT 로그인 여부 체크 : 직접 구현 if (!GF_NET.isLogoutStatus()) { this.openDisconnectPopup("Go To GniPortal Error!!~~(1)"); } }; var xmlHttpTimeout = setTimeout(ajaxTTimeout, 20000); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { ApplicationDestroyRequest(false); clearTimeout(xmlHttpTimeout); xmlHttpTimeout = null; window.location.href = redirectURL; HLog.sys("Go To GniPortal Finish!!~~"); } else if ((xhr.readyState == 4 && xhr.status == 0) || xhr.status == 403 || xhr.status == 404) { // 에러팝업 : 직접 구현 GameManager.openDisconnectPopup("Go To GniPortal Error!!~~(2)"); clearTimeout(xmlHttpTimeout); xmlHttpTimeout = null; } }; xhr.open('head', redirectURL); xhr.send(null); } catch (e) { HLog.err(e); } }; openLink("../../gniportal/index.html"); }; this.destroy = function () { // EventHelper.destroyEventHelper(); CommonUIDrawManager.removeResource(); HeroManager.destroy(); ItemManager.destroy(); MessageManager.destroy(); NoticeManager.destroy(); PlayResManager.destroy(); StageManager.destroy(); POPUP.POP_MAILBOX.getInstance().destroy(); }; }; // 공통변수에 할당. var appMgr = GameManager; var Point = function (x, y) { this.x = x; this.y = y; };
var express = require("express"); var router = express.Router(); const sqlite3 = require("sqlite3").verbose(); const json2csv = require("json2csv"); /* GET data listing. */ router.get("/", function(req, res, next) { // console.log("algo"); let sc = req.query.sc; let q = req.query.q; let mun = req.query.mun; let d = req.query.d; let sql; console.log(sc, q, mun, d); if (d) { sql = `SELECT NOM_ORIG, NOM_AMB, NOM_CHIP,NOM_DEST, NOM_FIN, value FROM OUTCOME WHERE NOM_MUN = "${d}"`; } if (mun) { sql = `SELECT t1.NOM_MUN, t1.NOM_CATEGORIA, t1.NOM_DEPAR, t1.[outcome], COALESCE(t2.[income], 0) AS [income] FROM (SELECT NOM_MUN, NOM_DEPAR, NOM_CATEGORIA, SUM(value) AS 'outcome' FROM outcome WHERE NOM_DEPAR = "${mun}" GROUP BY NOM_MUN) t1 LEFT JOIN (SELECT NOM_MUN, SUM(value) AS 'income' FROM income WHERE NOM_DEPAR = "${mun}" GROUP BY NOM_MUN) t2 ON (t1.NOM_MUN = t2.NOM_MUN);`; } if (q) { sql = `select distinct NOM_DEPAR from outcome`; } if (sc) { sql = `select ${sc},count(nom_chip) as conteo from outcome group by ${sc}`; } if (!sc && !q && !mun && !d) { sql = // "select NOM_DEPAR,count(nom_chip) as conteo from outcome group by NOM_DEPAR;"; "SELECT t1.NOM_MUN, t1.NOM_CATEGORIA, t1.NOM_DEPAR, t1.[outcome], COALESCE(t2.[income], 0) AS [income] FROM (SELECT NOM_MUN, NOM_DEPAR, NOM_CATEGORIA, SUM(value) AS 'outcome' FROM outcome GROUP BY NOM_MUN) t1 LEFT JOIN (SELECT NOM_MUN, SUM(value) AS 'income' FROM income GROUP BY NOM_MUN) t2 ON (t1.NOM_MUN = t2.NOM_MUN);"; } let queryResult; let db = new sqlite3.Database("./public/db/main.db", err => { if (err) { return console.error(err.message); } console.log("Connected to the 'data/main.db' SQlite database."); }); db.all(sql, [], (err, rows) => { console.log("sql", sql); if (err) { throw err; } res.set("Content-Type", "text/csv"); res.setHeader("Content-Disposition", 'attachment; filename="huehue.csv"'); res.status(200).send(json2csv.parse(rows)); }); db.close(err => { if (err) { return console.error(err.message); } console.log("Close the database connection."); }); }); module.exports = router;
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed 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. */ (function() { 'use strict'; /** * Class constructor for Data Table Card MDL component. * Implements MDL component design pattern defined at: * https://github.com/jasonmayes/mdl-component-design-pattern * * @constructor * @param {Element} element The element that will be upgraded. */ var CustomInputConfirm = function CustomInputConfirm(element) { this.element_ = element; // Initialize instance. this.init(); }; window['CustomInputConfirm'] = CustomInputConfirm; /** * Store constants in one place so they can be updated easily. * * @enum {string | number} * @private */ CustomInputConfirm.prototype.Constant_ = { // None at the moment. }; /** * Store strings for class names defined by this component that are used in * JavaScript. This allows us to simply change it in one place should we * decide to modify at a later date. * * @enum {string} * @private */ CustomInputConfirm.prototype.CssClasses_ = { IS_UPGRADED: 'is-upgraded', }; /** * Handle on change event of underlyig textfield. */ CustomInputConfirm.prototype.onChange_ = function() { this.element_.classList.remove('is-invalid'); }; /** * Initialize element. */ CustomInputConfirm.prototype.init = function() { if (this.element_) { var cherry = window.cherry; cherry.on(this.element_, 'CustomInputConfirm.keypress', this.onChange_).bind(this).debounce(10); this.element_.classList.add(this.CssClasses_.IS_UPGRADED); } }; /** * Downgrade element. */ CustomInputConfirm.prototype.mdlDowngrade_ = function() { var cherry = window.cherry; cherry.off(this.element_, 'CustomInputConfirm.keypress', this.onChange_); this.element_.classList.remove(this.CssClasses_.IS_UPGRADED); }; // The component registers itself. It can assume componentHandler is available // in the global scope. componentHandler.register({ constructor: CustomInputConfirm, classAsString: 'CustomInputConfirm', cssClass: 'custom-js-input-confirm' }); })();
/* eslint-disable class-methods-use-this */ // @flow import TONAsync from '../TONAsync'; import TONLimitedFetcher from '../TONLimitedFetcher'; class TestFetcher extends TONLimitedFetcher<*, *> { async fetchData(params: *): Promise<*> { await TONAsync.timeout(1); return params; } } test('Data Fetcher', async () => { const fetched = []; const fetcher = new TestFetcher(); fetcher.loadingLimit = 5; const open = (params: any) => { const listener = fetcher.createListener((data) => { fetched.push(data); }); listener.open(params); return listener; }; let listener = open(0); expect(fetcher.getCounters()).toEqual({ loading: 1, waiting: 0, loaded: 0, }); listener.close(); expect(fetcher.getCounters()).toEqual({ loading: 1, waiting: 0, loaded: 0, }); expect(fetched).toEqual([]); await TONAsync.timeout(2); expect(fetcher.getCounters()).toEqual({ loading: 0, waiting: 0, loaded: 1, }); expect(fetched).toEqual([]); listener = open(1); await TONAsync.timeout(2); listener.close(); expect(fetcher.getCounters()).toEqual({ loading: 0, waiting: 0, loaded: 2, }); expect(fetched).toEqual([1]); for (let i = 0; i < 10; i += 1) { open(i); } expect(fetcher.getCounters()).toEqual({ loading: 5, waiting: 3, loaded: 2, }); expect(fetched).toEqual([1, 0, 1]); await TONAsync.timeout(10); expect(fetcher.getCounters()).toEqual({ loading: 0, waiting: 0, loaded: 10, }); const sorted = [...fetched].sort(); expect(sorted).toEqual([0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9]); fetcher.reset(); expect(fetcher.getCounters()).toEqual({ loading: 0, waiting: 0, loaded: 0, }); });
//offline data functionality db.enablePersistence() .catch(err => { if(err.code == 'failed-precondition'){ //Probably multiple tabs open at once console.log('persistence failed'); } else if (err.code == 'unimplemented'){ //Lack of browser support console.log('persistence is not available'); } }); //Real-time listener db.collection('items').onSnapshot((snapshot) => { // console.log(snapshot.docChanges()); snapshot.docChanges().forEach((change) => { // console.log(change, change.doc.data()); if(change.type === 'added'){ //add the document data to the web page addItemDB(change.doc.data(), change.doc.id); } }); })
import {Router} from 'express' import {compose, liftA, get, reduce, filter} from '@cullylarson/f' import jwt from 'express-jwt' import {expressJwtSecret} from 'jwks-rsa' import isUuid from 'is-uuid' import validateMustExist from './validators/validateMustExist' import ForbiddenError from './errors/ForbiddenError' import PageNotFoundError from './errors/PageNotFoundError' // checks that a jwt is provided and is valid. if so, will add the decoded jwt to jwtDecoded // and the list of permissions to jwtPermissions, on the request. // jwtPermissionsKey can be a string or an array. if string, it will just be the key. if array, it's the path into the JWT. export const CheckJwt = (jwksUri, audience, issuer, jwtPermissionsKey) => { const check = jwt({ // Dynamically provide a signing key based on the kid in the header and the signing keys provided by the JWKS endpoint. secret: expressJwtSecret({ cache: true, rateLimit: true, jwksRequestsPerMinute: 5, jwksUri, }), audience, issuer, algorithms: ['RS256'], requestProperty: 'jwtDecoded', // the request object will get the decoded jwt at this key }) const augPermissions = (req, res, next) => { const permissions = compose( get(jwtPermissionsKey, []), get('jwtDecoded', {}), )(req) req.jwtPermissions = Array.isArray(permissions) ? permissions : [] next() } // compose the two middlewarres return Router().use(check, augPermissions) } // at least one permission passed must match. // permissionsOrRequest can be an array of permissions, or the request object. if the // request object, will grab permissions from it. export const allowedAny = (permissionsOrRequest, checkPermissions) => { checkPermissions = liftA(checkPermissions).filter(x => !!x) const permissions = compose( filter(x => !!x), liftA, x => Array.isArray(x) ? x : get('jwtPermissions', [], x), // the request object )(permissionsOrRequest) return compose( reduce((acc, x) => { // already matched if(acc) return acc // ends with a :, so can match a category of permissions if(/:$/.test(x)) { const regex = new RegExp(`^${x}`) return permissions.filter(regex.test.bind(regex)).length > 0 } // must matched a permission exactly else { return permissions.includes(x) } }, false), filter(x => !!x), liftA )(checkPermissions) } export const allowedAll = (permissionsOrRequest, checkPermissions) => { checkPermissions = liftA(checkPermissions).filter(x => !!x) const permissions = compose( filter(x => !!x), liftA, x => Array.isArray(x) ? x : get('jwtPermissions', [], x), // the request object )(permissionsOrRequest) return compose( reduce((acc, x) => { // already found one that doesn't match if(!acc) return acc // ends with a :, so can match a category of permissions if(/:$/.test(x)) { const regex = new RegExp(`^${x}`) return permissions.filter(regex.test.bind(regex)).length > 0 } // must matched a permission exactly else { return permissions.includes(x) } }, true), filter(x => !!x), liftA )(checkPermissions) } // checks that the current account has all of the provided permissions. // relies on jwtPermissions being present on the request (so use CheckJwt first). export const CheckPermission = permissionsToCheck => (req, res, next) => { if(allowedAll(req, permissionsToCheck)) { next() } else { next(new ForbiddenError('not-permitted', {message: 'Not permitted to access this resource.'})) } } // checks that the current account has any of the provided permissions. // relies on jwtPermissions being present on the request (so use CheckJwt first). export const CheckPermissionAny = permissionsToCheck => (req, res, next) => { if(allowedAny(req, permissionsToCheck)) { next() } else { next(new ForbiddenError('not-permitted', {message: 'Not permitted to access this resource.'})) } } export const CheckExists = (pool, tableName, paramNameToColumnName) => (req, res, next) => { validateMustExist(pool, tableName, paramNameToColumnName, undefined, req.params) .then(x => { x.isValid ? next() : next(new PageNotFoundError()) }) .catch(err => { next(err) }) } // makes sure a row in the database exists based on a uuid provided as a request param. if // the id param is not a valid uuid, will not hit the database (passing a non-valid uuid to // mysql's UUID_TO_BIN function will throw an error). // if record not found, will next with a PageNotFoundError. export const CheckExistsUuid = (pool, tableName, idParamName, idColumnName = undefined) => (req, res, next) => { idColumnName = idColumnName || idParamName const idParam = get(['params', idParamName], undefined, req) if(!idParam || !isUuid.v1(idParam)) return next(new PageNotFoundError()) CheckExists(pool, tableName, {[idParamName]: [idColumnName, 'UUID_TO_BIN(?)']})(req, res, next) }
import 'vue-material/dist/vue-material.min.css' import 'vue-material/dist/theme/default.css' import './styles.scss' import Vue_ from 'vue' import { MdApp, MdAvatar, MdButton, MdCard, MdCheckbox, MdContent, MdDatepicker, MdDialog, MdDivider, MdDrawer, MdEmptyState, MdField, MdIcon, MdList, MdMenu, MdProgress, MdRadio, MdRipple, MdSpeedDial, MdSubheader, MdTable, MdTabs, MdToolbar, MdTooltip } from 'vue-material/dist/components' export const Vue = Vue_ const mdComponents = [ MdApp, MdAvatar, MdButton, MdCard, MdCheckbox, MdContent, MdDatepicker, MdDialog, MdDivider, MdDrawer, MdEmptyState, MdField, MdIcon, MdList, MdMenu, MdProgress, MdRadio, MdRipple, MdSpeedDial, MdSubheader, MdTable, MdTabs, MdToolbar, MdTooltip ] mdComponents.forEach(comp => Vue.use(comp)) export default Vue
'use strict'; var cache = require('gulp-cached'); var changed = require('gulp-changed'); var csslint = require('gulp-csslint'); var del = require('del'); var gulp = require('gulp'); var jshint = require('gulp-jshint'); var jsonlint = require('gulp-json-lint'); var less = require('gulp-less'); var livereload = require('gulp-livereload'); var nodemon = require('gulp-nodemon'); var plumber = require('gulp-plumber'); var sourceMaps = require('gulp-sourcemaps'); var traceur = require('gulp-traceur'); var watch = require('gulp-watch'); var contentDir = 'content/common'; var indexHtml = contentDir + '/index.html'; var paths = { css: 'build/**/*.css', html: ['index.html', 'src/**/*.html'], js: ['gulpfile.js', 'src/**/*.js'], jsNext: ['src/**/*.js'], json: ['*.json'], less: 'src/**/*.less' }; gulp.task('clean', function (done) { del(['build'], done); }); gulp.task('csslint', function () { var options = { //'box-model': false, //'box-sizing': false, ids: false, //important: false, //'overqualified-elements': false, //'regex-selectors': false, //'qualified-headings': false, //'unique-headings': false, //'universal-selector': false, //'unqualified-attributes': false }; return gulp.src(paths.css). pipe(cache('csslint')). pipe(csslint(options)). pipe(csslint.reporter()); }); gulp.task('js', ['jshint'], function (done) { //TODO: Don't call this if jshint found any issues. livereload.changed(); done(); }); gulp.task('jshint', function () { // This is using .jshintrc in the gm-earnpower-client directory. return gulp.src(paths.js). pipe(cache('jshint')). pipe(jshint()). pipe(jshint.reporter('default')). pipe(jshint.reporter('fail')); // stop processing if errors }); gulp.task('jsonlint', function () { return gulp.src(paths.json). pipe(cache('jsonlint')). pipe(jsonlint()). pipe(jsonlint.report('verbose')); }); gulp.task('less', function () { return gulp.src(paths.less). pipe(plumber()). pipe(changed('src', {extension: '.css'})). pipe(less()). pipe(gulp.dest('build')); }); gulp.task('lint', ['csslint', 'jshint', 'jsonlint']); // Restarts server when code changes. gulp.task('nodemon', function () { nodemon({ script: 'build/server.js', // TODO: Configure this to only restart server when server.js changes. ignore: [''] }); }); gulp.task('transpile', ['jshint'], function () { return gulp.src(paths.jsNext). pipe(plumber()). pipe(changed('build', {extension: '.js'})). pipe(sourceMaps.init()). pipe(traceur({experimental: true})). pipe(sourceMaps.write('.')). pipe(gulp.dest('build')); }); gulp.task('watch', function () { livereload.listen(); // gulp.watch only processes files that match its glob patterns // when it starts and processes all of them when any file changes. // The watch plugin fixes both of these issues. gulp.watch(paths.css, ['csslint']); gulp.watch(paths.js, ['js']); //gulp.watch(paths.js, ['jshint'], livereload.changed); gulp.watch(paths.jsNext, ['transpile']); gulp.watch(paths.json, ['jsonlint']); gulp.watch(paths.less, ['less']); gulp.watch([paths.css, paths.html], livereload.changed); }); //gulp.task('default', ['less', 'transpile', 'nodemon', 'watch']); gulp.task('default', ['less', 'transpile', 'watch']);
const db = require('../config/connection'); var collection = require('../config/collection') var Objectid = require('mongodb').ObjectID module.exports = { addProduct: (product, callback) => { db.get().collection('product').insertOne(product).then((data) => { callback(data.ops[0]._id) }) }, getallProduct: () => { return new Promise(async (resolve, reject) => { let product = await db.get().collection(collection.PRODUCT_COLLECTION).find().toArray() resolve(product) }) }, deleteProduct: (Proid) => { return new Promise((resolve, reject) => { db.get().collection(collection.PRODUCT_COLLECTION).removeOne({ _id: Objectid(Proid) }).then(() => { resolve() }) }) }, getProductDetails: (prodid) => { return new Promise((resolve, reject) => { db.get().collection(collection.PRODUCT_COLLECTION).findOne({_id:Objectid(prodid)}).then((product)=>{ resolve(product) }) }) }, editProduct:(prodid,productdetails)=>{ return new Promise((resolve,reject)=>{ db.get().collection(collection.PRODUCT_COLLECTION).updateOne({_id:Objectid(prodid)},{ $set:{ name:productdetails.name, category:productdetails.category, price:productdetails.price, description:productdetails.description } }).then(()=>{ resolve() }) }) }, adminLogin: (userData) => { console.log(userData); let loginstatus = false let response = {} return new Promise(async (resolve, reject) => { let admin = await db.get().collection(collection.ADMIN_COLLECTION).findOne({ email: userData.email }) if (admin) { db.get().collection(collection.ADMIN_COLLECTION).findOne({ password: userData.password }).then((status) => { if (status) { console.log('success'); response.admin = admin response.status = true resolve(response) } else { console.log('failed'); resolve({ status: false }) } }) } else { console.log('Failed'); resolve({ status: false }) } }) } }
const onecolor = require('onecolor'); const vec2 = require('gl-matrix').vec2; const vec3 = require('gl-matrix').vec3; const vec4 = require('gl-matrix').vec4; const mat4 = require('gl-matrix').mat4; const b2Vec2 = require('box2dweb').Common.Math.b2Vec2; const b2World = require('box2dweb').Dynamics.b2World; const b2FixtureDef = require('box2dweb').Dynamics.b2FixtureDef; const b2CircleShape = require('box2dweb').Collision.Shapes.b2CircleShape; const b2PolygonShape = require('box2dweb').Collision.Shapes.b2PolygonShape; const b2BodyDef = require('box2dweb').Dynamics.b2BodyDef; const b2Body = require('box2dweb').Dynamics.b2Body; const b2DebugDraw = require('box2dweb').Dynamics.b2DebugDraw; const Timer = require('./Timer'); document.title = 'GLOO'; document.body.style.margin = '0'; document.body.style.padding = '0'; document.body.style.background = '#70787f'; document.body.style.position = 'relative'; const canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0vh'; canvas.style.left = '0vw'; canvas.style.width = '100vw'; canvas.style.height = '100vh'; canvas.style.background = '#fff'; document.body.appendChild(canvas); canvas.width = canvas.offsetWidth; canvas.height = canvas.offsetHeight; const aspectRatio = canvas.height / canvas.width; const div = document.createElement('div'); div.style.position = 'fixed'; div.style.bottom = '10px'; div.style.right = '20px'; div.style.opacity = 0.2; div.style.color = '#fff'; div.style.fontFamily = 'Arial'; div.style.fontSize = '24px'; div.appendChild(document.createTextNode('@line_ctrl')); document.body.appendChild(div); const regl = require('regl')({ canvas: canvas }) // wurld const world = new b2World(new b2Vec2(0, 0), true); const speckList = []; function doodoo() { const radius = 0.1 + Math.random() * 0.08; const fixDef = new b2FixtureDef(); fixDef.density = 2.0; fixDef.friction = 0.0; fixDef.restitution = 0.0; fixDef.shape = new b2CircleShape(radius); const bodyDef = new b2BodyDef(); bodyDef.type = b2Body.b2_dynamicBody; bodyDef.position.x = 1.2 * (Math.random() - 0.5); bodyDef.position.y = 1.2 * (Math.random() - 0.5); const main = world.CreateBody(bodyDef); main.CreateFixture(fixDef); const color = new onecolor.HSL(0.05 + Math.random() * 0.15, 0.6 + Math.random() * 0.3, 0.4 + Math.random() * 0.2); main.particleRadius = radius; main.particleVelocity = vec2.fromValues(0, 0); main.particleSpeed = 0; main.particleColor = color.rgb(); main.speckCountdown = 0; return main; } function baabaa() { const fixDef = new b2FixtureDef() fixDef.density = 200.0 fixDef.friction = 0.0 fixDef.restitution = 0.0 fixDef.shape = new b2PolygonShape() const bodyDef = new b2BodyDef() bodyDef.type = b2Body.b2_staticBody bodyDef.position.x = 0 bodyDef.position.y = 0 const bumperBody = world.CreateBody(bodyDef) const maxRows = 6; for (var r = 1; r < maxRows; r++) { const dist = 1.2 + 0.4 * r * r + r * 0.3; const thickness = 0.2 + r * 0.2// + r * r * 0.1; const offset = Math.random(); const circ = 2 * Math.PI * dist; const size = dist * 0.1 + Math.sqrt(dist) * 0.3 + 0.2; const maxAmount = Math.floor(circ / size); for (var i = 0; i < maxAmount; i++) { const angle = (i / maxAmount) * (Math.PI * 2) + offset + Math.random() * 0.2; const pos = new b2Vec2( dist * Math.cos(angle), dist * Math.sin(angle) ) fixDef.shape.SetAsOrientedBox( 0.5 * size - 0.15 - Math.random() * 0.1, (thickness - Math.random() * 0.1) * 0.5, pos, angle + (Math.random() > 0.0 ? Math.PI * 0.5 : 0) ) bumperBody.CreateFixture(fixDef) } } } baabaa(); const ditherLib = ` // @todo credit from https://github.com/hughsk/glsl-dither float dither4x4(vec2 position) { int x = int(mod(position.x, 4.0)); int y = int(mod(position.y, 4.0)); int index = x + y * 4; if (x < 8) { if (index == 0) return 0.0625; if (index == 1) return 0.5625; if (index == 2) return 0.1875; if (index == 3) return 0.6875; if (index == 4) return 0.8125; if (index == 5) return 0.3125; if (index == 6) return 0.9375; if (index == 7) return 0.4375; if (index == 8) return 0.25; if (index == 9) return 0.75; if (index == 10) return 0.125; if (index == 11) return 0.625; if (index == 12) return 1.0; if (index == 13) return 0.5; if (index == 14) return 0.875; if (index == 15) return 0.375; } } `; // setup draw const debugDraw = new b2DebugDraw(); var cmd, cmd2; if (!regl) { const ctx = canvas.getContext('2d'); ctx.translate(canvas.width / 2, canvas.height / 2); ctx.scale(1, -1); debugDraw.SetSprite(ctx); debugDraw.SetDrawScale(30); debugDraw.SetFillAlpha(0.3); debugDraw.SetLineThickness(1.0); debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit); world.SetDebugDraw(debugDraw); } else { cmd = regl({ vert: ` precision mediump float; uniform float aspectRatio; uniform float time; uniform float pulse; uniform float place; uniform vec2 origin; uniform float radius; uniform float speed; uniform vec2 velocity; uniform mat4 camera; attribute vec2 position; varying float alpha; varying vec2 facePosition; float computeParticleZ() { return place * 0.2 + place * place * 0.03 + 1.0 / (2.0 * place); } void main() { float particleRandom = fract(radius * 10000.0); float instability = clamp((speed - 0.3) * 10.0, 0.0, 1.0); float spawnSizeFactor = clamp(place * 20.0 - 1.9, 0.0, 1.0); float pulseSizeFactor = 1.0 + 0.1 * pulse; float unstableModeSizeFactor = 1.0 + instability * 0.75; float stableGrowthSizeFactor = 1.0 + 0.15 * place * (1.0 - 0.8 * instability); float flickerAmount = clamp( sin(time * 8.0 * (particleRandom + 1.0)) * 10.0 - 9.0, 0.0, 1.0 ); float unstableFlicker = -0.05 + 0.4 * particleRandom + 0.2 * flickerAmount; vec4 center = vec4( origin, computeParticleZ(), 1.0 ); float baseAlpha = 1.0 / (1.0 + radius * place * place * 0.08); alpha = baseAlpha * ( (1.0 - instability) * (1.0 + flickerAmount * 0.2) + instability * unstableFlicker ); facePosition = position; gl_Position = camera * center + 2.75 * vec4(position.x * aspectRatio, position.y, 0, 0) * radius * ( spawnSizeFactor * pulseSizeFactor * unstableModeSizeFactor * stableGrowthSizeFactor ); } `, frag: ` precision mediump float; uniform vec4 color; varying float alpha; varying vec2 facePosition; ${ditherLib} void main() { gl_FragColor = color; // discarding after assigning gl_FragColor, apparently may not discard otherwise due to bug vec2 fp2 = facePosition * facePosition; if (fp2.x + fp2.y > 1.0) { discard; } if (dither4x4(gl_FragCoord.xy) > alpha) { discard; } } `, attributes: { position: regl.buffer([ [ -1, -1 ], [ 1, -1 ], [ 1, 1 ], [ -1, 1 ] ]) }, uniforms: { aspectRatio: regl.prop('aspectRatio'), time: regl.prop('time'), pulse: regl.prop('pulse'), place: regl.prop('place'), origin: regl.prop('origin'), color: regl.prop('color'), radius: regl.prop('radius'), speed: regl.prop('speed'), velocity: regl.prop('velocity'), camera: regl.prop('camera') }, primitive: 'triangle fan', count: 4 }); cmd2 = regl({ vert: ` precision mediump float; uniform float aspectRatio; uniform float time; uniform float pulse; uniform vec4 speck; uniform mat4 camera; attribute vec2 position; varying float alpha; varying float intensity; varying vec2 facePosition; float computeParticleZ(float place) { float age = speck.z; float speckOffset = age * 0.3 + age * age * 0.02; // @todo make a reusable function return place * 0.2 + place * place * 0.03 + 1.0 / (2.0 * place) + speckOffset; } void main() { vec2 origin = speck.xy; vec2 o2 = origin * origin; float vOffset = computeParticleZ(sqrt(o2.x + o2.y)); intensity = sin(vOffset * speck.w * 5.0) * 0.2 + 0.8; vec4 center = vec4( origin, vOffset + 0.2, 1.0 ); facePosition = position; alpha = clamp(speck.z - speck.w * 2.0, 0.0, 0.95); float radius = speck.w * speck.w * 7.5 - 0.02; gl_Position = camera * center + 2.5 * radius * vec4(position.x * aspectRatio, position.y, 0, 0); } `, frag: ` precision mediump float; uniform vec4 color; varying float alpha; varying float intensity; varying vec2 facePosition; ${ditherLib} void main() { gl_FragColor = vec4(color.r * intensity, color.g * intensity, color.b * intensity, 1.0); // discarding after assigning gl_FragColor, apparently may not discard otherwise due to bug vec2 fp2 = facePosition * facePosition; if (fp2.x + fp2.y > 1.0) { discard; } if (dither4x4(gl_FragCoord.xy) > alpha) { discard; } } `, attributes: { position: regl.buffer([ [ -1, -1 ], [ 1, -1 ], [ 1, 1 ], [ -1, 1 ] ]) }, uniforms: { aspectRatio: regl.prop('aspectRatio'), time: regl.prop('time'), pulse: regl.prop('pulse'), origin: regl.prop('origin'), color: regl.prop('color'), speck: regl.prop('speck'), camera: regl.prop('camera') }, primitive: 'triangle fan', count: 4 }); cmd3 = regl({ vert: ` precision mediump float; uniform mat4 camera; attribute vec2 position; varying vec2 facePosition; void main() { facePosition = position; gl_Position = camera * vec4(position.x * 80.0, position.y * 80.0, 0, 1.0); } `, frag: ` precision mediump float; #define M_PI 3.1415926535897932384626433832795 uniform float aspectRatio; varying vec2 facePosition; void main() { vec2 fp2 = facePosition * facePosition; float angle = atan(facePosition.y, facePosition.x) / M_PI; float dist = sqrt(fp2.x + fp2.y) * 50.0; float markers = sqrt(dist) * 2.0 + dist * 0.05; float intensity = (mod(angle * 3.5, 1.0) - 0.5) * (mod(markers, 1.0) - 0.5) < 0.0 ? 1.0 : 0.85; gl_FragColor = vec4(vec3(0.15, 0.25, 0.3) * intensity, 1.0); } `, attributes: { position: regl.buffer([ [ -1, -1 ], [ 1, -1 ], [ 1, 1 ], [ -1, 1 ] ]) }, uniforms: { aspectRatio: regl.prop('aspectRatio'), camera: regl.prop('camera') }, primitive: 'triangle fan', count: 4 }); } const bodyOrigin = vec2.create(); const bodyColor = vec4.create(); const cameraPosition = vec3.create(); const camera = mat4.create(); const STEP = 1 / 60.0; var countdown = 0; const bodyList = []; const delList = []; const imp = new b2Vec2(); const timer = new Timer(STEP, 20, function () { if (countdown <= 0) { countdown += 0.005 + bodyList.length * 0.0005; bodyList.push(doodoo()); bodyList.push(doodoo()); delList.length = 0; bodyList.forEach((b, bi) => { const pos = b.GetPosition(); const l = Math.hypot(pos.x, pos.y); if (l > 20) { delList.push(bi); return; } // apply outward pressure from center imp.x = (1 / (1 + 10 * l)) * 0.5 * pos.x / l; imp.y = (1 / (1 + 10 * l)) * 0.5 * pos.y / l; b.ApplyImpulse(imp, pos); }); // should monotonously increasing, so no issues due to splice delList.forEach(bi => { const b = bodyList[bi]; bodyList.splice(bi, 1); world.DestroyBody(b); }); } else { countdown -= STEP; } world.Step(STEP, 3, 3); // collect stats for rendering and generate specks bodyList.forEach((b, bi) => { const pos = b.GetPosition(); // dampen the speed const vel = b.GetLinearVelocity(); b.particleSpeed = 0.8 * b.particleSpeed + 0.2 * Math.hypot(vel.x, vel.y); vec2.scale(b.particleVelocity, b.particleVelocity, 0.8); b.particleVelocity[0] += vel.x * 0.2; b.particleVelocity[1] += vel.y * 0.2; // generate specks if appropriate if (b.particleSpeed < 0.06 && pos.x * pos.x + pos.y * pos.y > 1) { if (b.speckCountdown === null) { // initial delay until generating a speck b.speckCountdown = Math.random() * 1.5; } else { // countdown b.speckCountdown -= STEP; } if (b.speckCountdown < 0) { // delay either for a consistent amount in a series or for a longer cool-off b.speckCountdown += Math.random() < 0.65 ? b.particleRadius * 4 + Math.random() * 0.1 // slight "breath" to the cadence : 1 + Math.random() * 5; speckList.push(vec4.fromValues(pos.x, pos.y, 0, b.particleRadius)); } } else { // no specks b.speckCountdown = null; } }); // update specks delList.length = 0; speckList.forEach((speck, si) => { speck[2] += STEP; if (speck[2] > 25) { delList.push(si); } }); // should be monotonously increasing, so no issues due to splice delList.forEach(si => { const s = speckList[si]; speckList.splice(si, 1); }); }, function (now) { mat4.perspective(camera, 0.6, canvas.width / canvas.height, 1, 120); // camera shake and zoom const zoomAmount = 1 + 0.35 * Math.sin(now * 0.17) vec3.set(cameraPosition, 0.02 * Math.sin(now * 3.43), 0.02 * Math.cos(now * 2.31), -25 * zoomAmount); mat4.translate(camera, camera, cameraPosition); // pitch mat4.rotateX(camera, camera, -Math.PI / 6 + Math.cos(now * 0.23 - 1.2) * (Math.PI / 6)); // displace the scene downwards a bit vec3.set(cameraPosition, 0, 0, -4.5); mat4.translate(camera, camera, cameraPosition); // slow orbiting mat4.rotateZ(camera, camera, now * 0.05); const pulseSpeed = 1.2 * Math.sin(now * 0.8); const pulse = Math.max(0, Math.sin(5.0 * now + pulseSpeed) * 10.0 - 9.0); // use a slight flicker in saturation const speckColor = new onecolor.HSL(0.5 + Math.sin(now) * 0.075, 0.6 + pulse * 0.1 + Math.random() * 0.08, 0.85); if (!regl) { world.DrawDebugData(); } else { regl.clear({ depth: 1 }); cmd3({ aspectRatio: aspectRatio, camera: camera }); bodyList.forEach(b => { const pos = b.GetPosition(); vec2.set(bodyOrigin, pos.x, pos.y); vec4.set(bodyColor, b.particleColor.red(), b.particleColor.green(), b.particleColor.blue(), 1) cmd({ aspectRatio: aspectRatio, time: now, pulse: pulse, place: vec2.length(bodyOrigin), origin: bodyOrigin, color: bodyColor, radius: b.particleRadius, speed: b.particleSpeed, velocity: b.particleVelocity, camera: camera }); }); vec4.set(bodyColor, speckColor.red(), speckColor.green(), speckColor.blue(), 1) speckList.forEach(s => { cmd2({ aspectRatio: aspectRatio, time: now, pulse: pulse, speck: s, color: bodyColor, camera: camera }); }); } });
import React, { Component } from 'react'; // import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import MyNav from '../Component/nav' import MyCard from '../Component/mycard' import { PageHeader, small, Carousel, Glyphicon, Col, Navbar, Nav, NavItem, NavDropdown, MenuItem, Button } from 'react-bootstrap'; // import './App.css'; import Select from 'react-select'; import 'react-select/dist/react-select.css'; require('../global/global.css') require('./index.css') class PageClassList extends Component { constructor(props) { super(props); this.state = { city: [], age: [], theme: [], show: false, }; } handleChangeCity = (city) => { this.setState({ city }); } handleChangeAge = (age) => { this.setState({ age }); } handleChangeTheme = (theme) => { this.setState({ theme }); } showResult = () => { this.setState({ show: true }) } render() { return ( <div style={{ marginTop: '70px', minHeight: '1000px' }}> <div className='body' > <h1 className='title'>游学一键规划</h1> <div style={{ width: '60%', margin: '0 auto 30px' }}> <div> <h3>游学城市</h3> <Select name="form-field-name" placeholder='请选择城市' value={this.state.city} multi onChange={this.handleChangeCity} options={[ { value: '1', label: '柏林' }, { value: '2', label: '汉堡' }, { value: '3', label: '科隆' }, { value: '4', label: '德累斯顿' }, { value: '5', label: '布莱梅' }, { value: '6', label: '慕尼黑' }, { value: '7', label: '多特蒙德' }, { value: '8', label: '法兰克福' }, { value: '9', label: '杜伊斯堡' }, { value: '10', label: '杜塞尔多夫' }, ]} /> </div> <div> <h3>游学年龄</h3> <Select name="form-field-name" placeholder='请选择年龄' value={this.state.age} multi onChange={this.handleChangeAge} options={[ { value: '1', label: '小学生' }, { value: '2', label: '初中生' }, { value: '3', label: '高中生' }, { value: '4', label: '大学生' }, { value: '5', label: '成人' }, { value: '6', label: '亲子' }, ]} /> </div> <div> <h3>游学主题</h3> <Select name="form-field-name" placeholder='请选择主题' value={this.state.theme} multi onChange={this.handleChangeTheme} options={[ { value: '1', label: 'k12基础教育' }, { value: '2', label: '精英教育' }, { value: '3', label: '优质语言学校' }, { value: '4', label: '主题营地' }, { value: '5', label: '体育教育' }, { value: '6', label: '美食之旅' }, ]} /> </div> <div style={{ textAlign: 'center', marginTop: '30px' }}> <Button bsStyle="primary" bsSize="large" onClick={this.showResult}>一键规划</Button> </div> </div> <div style={{ height: '1100px', display: this.state.show ? '' : 'none' }} > <h2 className='title'>规划结果</h2> <MyCard img={require('../static/class1.jpg')} title='德国精英大学——慕尼黑大学' body=' 路德维希-马克西米利安-慕尼黑大学建校至今已有545年,是坐落于慕尼黑市中心的一所世界顶尖名校,自19世纪以来便是德国和欧洲最具声望大学之一,也是德国精英大学和欧洲研究型大学联盟成员,其物理,化学,生命科学,医学,数学及人文科学等领域均在国际上享有盛名。 ' /> <MyCard img={require('../static/class2.jpg')} title='德国排名第1私校萨勒姆王宫中学Salem官方夏校' body=' 萨勒姆王宫中学(Schule Schloss Salem)始建于1920年,由最后一位德意志帝国总理、一位知名教育家和政治家以及一位内阁大臣共同创建,是德国规模最大、排名第一的顶尖中学。学校坐落于德国南部风景旖旎的博登湖畔,景色优美、环境宜人。学校培养了西班牙索菲亚王后、英国菲利普亲王、宝马总裁、德意志银行总裁等皇家贵族和社会精英,学风严谨, ' /> <MyCard img={require('../static/class3.jpg')} title='德国最古老的大学——海德堡大学' body=' 海德堡大学成立于1386年,是德国最古老的大学,也是德意志神圣罗马帝国继布拉格和维也纳之后开设的第三所大学。十六世纪的下半叶,海德堡大学就成为欧洲科学文化的中心。大学有30787名学生注册在读,其中包括5793名国际学生。。海德堡大学所在的海德堡市也是一座以古堡、内卡河闻名的文化名城. ' /> <MyCard img={require('../static/classInfo1.png')} title='入住海外家庭,大胆开说英语' body=' 入住当地家庭,纯英语环境全面刺激张口说英语的勇气,提升口语交流水平,储备海外独立生活能力。不用担心,寄宿家庭就是一个非常好的锻炼孩子人际交往的环境。友好的寄宿家庭往往有各个年龄段的家庭成员。 ' /> <MyCard img={require('../static/classInfo2.png')} title='体验国外教学环境,历练优秀品格' body=' 放眼全球,亲身体验优质教育,在颠覆认知的全新教学模式中发现学习乐趣及方法,结交国际朋友;和国外小伙伴一起参加多姿多彩本土营,学习国外伙伴处理问题的方式方法 ' /> <MyCard img={require('../static/classInfo3.png')} title='参加国际竞赛,增长国际竞争力' body=' 进名企、见名人,撰写商业方案,挑战国际精英,以国际视角规划人生与未来,澎拜能力自信,提升国际竞争力。在行走的世界课堂上探索、思考、寻找答案,将异国人文精华收入囊中,让成长告别枯燥! ' /> </div> <div style={{ height: '600px' }}> <h2 className='title'>猜你喜欢</h2> <MyCard img={require('../static/class4.jpg')} title='恬静惬意——异国之旅' body=' 打开窗帘开启精彩的德国之旅,从维斯朝圣教堂的古典辉煌,到新天鹅堡 的缤纷生活,梦想将要逐一实现,郁郁苍苍的山林之中,四季展现各种不同风貌,静静记载专属巴伐利亚,童话国王的故事,热情是慕尼黑的个性,啤酒是慕尼黑的象征,玛利亚广场像位真诚好客的东道主,邀请您举起酒杯干杯豪迈干杯,欢迎来到德国开启一场难忘的艺术之旅。 ' /> <MyCard img={require('../static/class5.jpg')} title='舌尖德国——美食之旅' body=' 德国没有统一的“德国菜”,但是有许多地方特色的菜肴,从基尔的西鲱到巴伐利亚的甜芥白香肠再到柏林的熏肉。世界各国的美食家云集德国,如今的德国餐饮业可以说是国际风味大荟萃,世界各国的美味佳肴在此聚集。 ' /> <MyCard img={require('../static/child5.jpg')} title='人文德国——魅力之旅' body=' 从曾经德国唯一的唐人街、上海的友城汉堡到慕尼黑历史极为悠久的集市Viktualienmarkt再到疯狂的购物大街柏林,展示出了德国大城市普遍具有的精神与风貌,同时又体现出了他们独特的魅力。汉堡这座自由汉萨城为10000多名华人提供了一片安全又美丽的家园。 ' /> </div> </div> </div> ); } } export default PageClassList;
import request from '@/utils/request' import { urlSystem } from '@/api/commUrl' const url = urlSystem // const url = 'http://test.womaoapp.com:8080/sys/' // const url = 'https://apiengine.womaoapp.com/security/sys/' export function login(username, password, captcha) { return request({ url: url + 'sys/login', method: 'post', data: { username: username, password: password, captcha: captcha } }) } // 获取用户信息 export function getUserInfo(params) { return request({ url: url + 'user/info', method: 'post', data: params }) } // 获取所有用户信息 export function getAllUserInfo(params) { return request({ url: url + 'user/list', method: 'post', data: params }) } // 登出--退出登录 export function logout(params) { return request({ url: 'http://dev.oss.womaoapp.com/fwas-security-admin/logout', method: 'post', data: params }) } // 获取用户人登录信息 export function getUserData(params) { return request({ url: url + 'user/info', method: 'post', data: {} }) } // 查询角色列表 export function getRoleList(params) { return request({ url: url + 'role/list ', method: 'post', data: {} }) } // 查找当前用户所有部门集合 export function getNowUserToWhereDepart(params) { return request({ url: url + 'dept/select', method: 'post', data: params }) } // 添加用户 export function addUser(params) { return request({ url: url + 'user/save', method: 'post', data: params }) } // 删除用户 export function deleteUser(params) { return request({ url: url + 'user/delete', method: 'post', data: params }) } // 编辑用户 export function editUser(params) { return request({ url: url + 'user/update', method: 'post', data: params }) } // 获取用户的子部门集合 export function getChildrenIdsList(params) { return request({ url: url + 'user/userinfo', method: 'post', data: params }) }
import { ListGroup, Col, Button, Form, Card, Toast } from 'react-bootstrap' import { Link } from 'react-router-dom' import { useState, useEffect } from 'react' import { QuestionCard } from './QuestionCard.js' import API from './API' function SubmitSurvey(props) { const [questions, setQuestions] = useState([]) const [givenAnswers, setGivenAnswers] = useState([]) const [username, setUsername] = useState("") const [required, setRequired] = useState(0) const [count, setCount] = useState(0) const [enable, setEnable] = useState(true) const [message, setMessage] = useState('') const handleErrors = (err) => { setMessage({ msg: err.error, type: 'danger' }) } const handleName = (e) => { setUsername(e) } const handleSubmit = () => { let user = { username: username, sID: props.surveyId } API.addUser(user).then(id => { givenAnswers.forEach((a) => { let answer = { id: id, sID: props.surveyId, qID: a.qID, aID: a.aID, text: a.text } API.addUserAnswer(answer).then((status) => { console.log(status) }).catch(e => handleErrors(e)) }) }).catch(e => handleErrors(e)) } useEffect(() => { if (count !== 0) { console.log(required + "/" + count) if (username.length > 0 && required === count) setEnable(false) else setEnable(true) } }, [username, required, count]) useEffect(() => { API.loadQuestions(props.surveyId).then(dbQuestions => { setQuestions(dbQuestions) setCount(dbQuestions.filter((q) => q.min >= 1).length) }).catch(e => handleErrors(e)) }, [props.surveyId]) return <Col className="d-flex flex-column mx-auto mt-3" style={{ width: "60%" }}> <h1 className="text-center">{props.title}</h1> <h6 className="mandatory" >Mandatory questions are marked with</h6> <Card className="mx-auto" id="username-card"> <Card.Body> <Card.Title className="mandatory">Insert your name</Card.Title> <Form> <Form.Control maxLength="30" onChange={(e) => handleName(e.target.value)} placeholder="Insert your name or a username" /> <Form.Text>{username.length}/30</Form.Text> </Form> </Card.Body> </Card> <Toast show={message !== ''} onClose={() => setMessage('')} delay={3000} autohide> <Toast.Body>{message?.msg}</Toast.Body> </Toast> <ListGroup> {questions.map((q, i) => <QuestionCard setRequired={setRequired} question={q} surveyId={props.surveyId} key={i} givenAnswers={givenAnswers} setGivenAnswers={setGivenAnswers} />)} </ListGroup> <Link className="mx-auto my-3" style={{ textDecoration: 'none' }} to={{ pathname: "/" }}> <Button disabled={enable} id="button" size="lg" onClick={() => handleSubmit()}>Submit</Button> </Link> </Col> } export default SubmitSurvey
import Vue from 'vue' import Router from 'vue-router' import {BasicLayout} from '@/layouts' const originalPush = Router.prototype.push; Router.prototype.push = function push(location, onResolve, onReject) { if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject); return originalPush.call(this, location).catch(err => err) }; Vue.use(Router); export default new Router({ routes: [ { path: '/login', name: 'login', component: () => import('@/views/login') }, { path: '/', name: 'index', component: BasicLayout, meta: {title: '首页'}, redirect: '/dash', children: [ { path: '/dash', name: 'dash', component: () => import('@/views/dash') }, { path: '/role', name: 'role', component: () => import('@/views/role') }, { path: '/user', name: 'user', component: () => import('@/views/user') } ] }, { path: '*', redirect: '/404' } ] })
'use strict'; require('./enroll.public.css'); require('../../../../../../asset/css/buttons.css'); require('../../../../../../asset/js/xxt.ui.image.js'); require('../../../../../../asset/js/xxt.ui.editor.js'); require('./_asset/ui.repos.js'); require('./_asset/ui.tag.js'); require('./_asset/ui.topic.js'); require('./_asset/ui.assoc.js'); require('./_asset/ui.task.js'); window.moduleAngularModules = ['task.ui.enroll', 'editor.ui.xxt', 'repos.ui.enroll', 'tag.ui.enroll', 'topic.ui.enroll', 'assoc.ui.enroll']; var ngApp = require('./main.js'); ngApp.controller('ctrlCowork', ['$scope', '$q', '$timeout', '$location', '$anchorScroll', '$uibModal', 'tmsLocation', 'http2', 'noticebox', 'enlTag', 'enlTopic', 'enlAssoc', 'enlTask', 'picviewer', function ($scope, $q, $timeout, $location, $anchorScroll, $uibModal, LS, http2, noticebox, enlTag, enlTopic, enlAssoc, enlTask, picviewer) { /** * 加载整条记录 */ function fnLoadRecord(aCoworkSchemas) { var oDeferred; oDeferred = $q.defer(); http2.get(LS.j('repos/recordGet', 'site', 'app', 'ek')).then(function (rsp) { var oRecord; oRecord = rsp.data; oRecord._canAgree = fnCanAgreeRecord(oRecord, _oUser); $scope.record = oRecord; /* 如果有图片,且图片是紧凑的,改为中等尺寸的 */ if ($scope.imageSchemas && $scope.imageSchemas.length) { $scope.imageSchemas.forEach(function (oSchema) { var imageUrls = oRecord.data[oSchema.id] if (imageUrls) { oRecord.data[oSchema.id] = imageUrls.replace('.compact.', '.medium.') } }) } /* 设置页面分享信息 */ $scope.setSnsShare(oRecord, null, { target_type: 'cowork', target_id: oRecord.id }); /*页面阅读日志*/ $scope.logAccess({ target_type: 'cowork', target_id: oRecord.id }); /* 加载协作填写数据 */ if (aCoworkSchemas.length) { oRecord.verbose = {}; fnLoadCowork(oRecord, aCoworkSchemas); } // oDeferred.resolve(oRecord); }); return oDeferred.promise; } /** * 加载关联数据 */ function fnLoadAssoc(oRecord, oCachedAssoc) { var oDeferred; oDeferred = $q.defer(); http2.get(LS.j('assoc/byRecord', 'site', 'ek')).then(function (rsp) { if (rsp.data.length) { oRecord.assocs = []; rsp.data.forEach(function (oAssoc) { if (oCachedAssoc[oAssoc.entity_a_type] === undefined) oCachedAssoc[oAssoc.entity_a_type] = {}; switch (oAssoc.entity_a_type) { case 'record': if (oAssoc.entity_a_id == oRecord.id) { if (oAssoc.log && oAssoc.log.assoc_text) { oAssoc.assoc_text = oAssoc.log.assoc_text; } oRecord.assocs.push(oAssoc); } break; case 'data': if (oCachedAssoc.data[oAssoc.entity_a_id] === undefined) oCachedAssoc.data[oAssoc.entity_a_id] = []; oCachedAssoc.data[oAssoc.entity_a_id].push(oAssoc); break; } }); } oDeferred.resolve(); }); return oDeferred.promise; } /** * 加载协作填写数据 */ function fnLoadCowork(oRecord, aCoworkSchemas, bJumpTask) { var url, anchorItemId; if (/item-.+/.test($location.hash())) { anchorItemId = $location.hash().substr(5); } aCoworkSchemas.forEach(function (oSchema) { url = LS.j('data/get', 'site', 'ek') + '&schema=' + oSchema.id + '&cascaded=Y'; http2.get(url, { autoBreak: false, autoNotice: false }).then(function (rsp) { var bRequireAnchorScroll; oRecord.verbose[oSchema.id] = rsp.data.verbose[oSchema.id]; oRecord.verbose[oSchema.id].items.forEach(function (oItem) { if (oItem.userid !== $scope.user.uid) { oItem._others = true; } if (anchorItemId && oItem.id === anchorItemId) { bRequireAnchorScroll = true; } }); if (bRequireAnchorScroll) { $timeout(function () { var elItem; $anchorScroll(); elItem = document.querySelector('#item-' + anchorItemId); elItem.classList.toggle('blink', true); $timeout(function () { elItem.classList.toggle('blink', false); }, 1000); }); } }); }); } function fnAfterRecordLoad(oRecord, oUser) { /*设置页面导航*/ $scope.setPopNav(['repos', 'favor', 'rank', 'kanban', 'event'], 'cowork'); /* 支持图片预览 */ $timeout(function () { var imgs; if (imgs = document.querySelectorAll('.data img')) { picviewer.init(imgs); } }); } /* 是否可以对记录进行表态 */ function fnCanAgreeRecord(oRecord, oUser) { if (oUser.is_leader) { if (oUser.is_leader === 'S') { return true; } if (oUser.is_leader === 'Y') { if (oUser.group_id === oRecord.group_id) { return true; } else if (oUser.is_editor && oUser.is_editor === 'Y') { return true; } } } return false; } function fnAppendRemark(oNewRemark, oUpperRemark) { var oNewRemark; oNewRemark.content = oNewRemark.content.replace(/\\n/g, '<br/>'); if (oUpperRemark) { oNewRemark.reply = '<a href="#remark-' + oUpperRemark.id + '">回复' + oUpperRemark.nickname + '的留言 #' + oUpperRemark.seq_in_record + '</a>'; } $scope.remarks.push(oNewRemark); if (!oUpperRemark) { $scope.record.rec_remark_num++; } $timeout(function () { var elRemark; $location.hash('remark-' + oNewRemark.id); $anchorScroll(); elRemark = document.querySelector('#remark-' + oNewRemark.id); elRemark.classList.toggle('blink', true); $timeout(function () { elRemark.classList.toggle('blink', false); }, 1000); }); } function fnAssignTag(oRecord) { enlTag.assignTag(oRecord).then(function (rsp) { if (rsp.data.user && rsp.data.user.length) { oRecord.userTags = rsp.data.user; } else { delete oRecord.userTags; } }); } if (!LS.s().ek) { noticebox.error('参数不完整'); return; } var _oApp, _oUser, _oAssocs, _shareby; _shareby = location.search.match(/shareby=([^&]*)/) ? location.search.match(/shareby=([^&]*)/)[1] : ''; $scope.options = { forQuestionTask: false, forAnswerTask: false }; $scope.newRemark = {}; $scope.assocs = _oAssocs = {}; $scope.favorStack = { guiding: false, start: function (record, timer) { this.guiding = true; this.record = record; this.timer = timer; }, end: function () { this.guiding = false; delete this.record; delete this.timer; } }; $scope.gotoHome = function () { location.href = "/rest/site/fe/matter/enroll?site=" + _oApp.siteid + "&app=" + _oApp.id + "&page=repos"; }; $scope.copyRecord = function (oRecord) { enlAssoc.copy($scope.app, { id: oRecord.id, type: 'record' }); }; $scope.pasteRecord = function (oRecord) { enlAssoc.paste($scope.user, oRecord, { id: oRecord.id, type: 'record' }).then(function (oNewAssoc) { if (!oRecord.assocs) oRecord.assocs = []; if (oNewAssoc.log) oNewAssoc.assoc_text = oNewAssoc.log.assoc_text; oRecord.assocs.push(oNewAssoc); }); }; $scope.removeAssoc = function (oAssoc) { noticebox.confirm('取消关联,确定?').then(function () { http2.get(LS.j('assoc/unlink', 'site') + '&assoc=' + oAssoc.id).then(function () { $scope.record.assocs.splice($scope.record.assocs.indexOf(oAssoc), 1); }); }); }; $scope.editAssoc = function (oAssoc) { enlAssoc.update($scope.user, oAssoc); }; $scope.favorRecord = function (oRecord) { var url; if (!oRecord.favored) { url = LS.j('favor/add', 'site'); url += '&ek=' + oRecord.enroll_key; http2.get(url).then(function (rsp) { oRecord.favored = true; $scope.favorStack.start(oRecord, $timeout(function () { $scope.favorStack.end(); }, 3000)); }); } else { noticebox.confirm('取消收藏,确定?').then(function () { url = LS.j('favor/remove', 'site'); url += '&ek=' + oRecord.enroll_key; http2.get(url).then(function (rsp) { delete oRecord.favored; }); }); } }; $scope.assignTag = function (oRecord) { if (oRecord) { fnAssignTag(oRecord); } else { $scope.favorStack.timer && $timeout.cancel($scope.favorStack.timer); if (oRecord = $scope.favorStack.record) { fnAssignTag(oRecord); } $scope.favorStack.end(); } }; function fnAssignTopic(oRecord) { http2.get(LS.j('topic/list', 'site', 'app')).then(function (rsp) { var topics; if (rsp.data.total === 0) { location.href = LS.j('', 'site', 'app') + '&page=favor#topic'; } else { topics = rsp.data.topics; enlTopic.assignTopic(oRecord); } }); } $scope.assignTopic = function (oRecord) { if (oRecord) { fnAssignTopic(oRecord); } else { $scope.favorStack.timer && $timeout.cancel($scope.favorStack.timer); if (oRecord = $scope.favorStack.record) { fnAssignTopic(oRecord); } $scope.favorStack.end(); } }; $scope.setAgreed = function (value) { var url, oRecord; oRecord = $scope.record; if (oRecord.agreed !== value) { url = LS.j('record/agree', 'site', 'ek'); url += '&value=' + value; http2.get(url).then(function (rsp) { oRecord.agreed = value; }); } }; $scope.coworkAsRemark = function (oSchema, index) { var oRecData, oItem; oRecData = $scope.record.verbose[oSchema.id]; oItem = oRecData.items[index]; noticebox.confirm('将填写项转为留言,确定?').then(function () { http2.get(LS.j('cowork/asRemark', 'site') + '&item=' + oItem.id).then(function (rsp) { oRecData.items.splice(index, 1); fnAppendRemark(rsp.data); }); }); }; $scope.remarkAsCowork = function (oRemark) { var url, oSchema; url = LS.j('remark/asCowork', 'site'); url += '&remark=' + oRemark.id; if ($scope.coworkSchemas.length === 1) { oSchema = $scope.coworkSchemas[0]; url += '&schema=' + oSchema.id; http2.get(url).then(function (rsp) { var oItem; oItem = rsp.data; $scope.record.verbose[oSchema.id].items.push(oItem); $location.hash('item-' + oItem.id); $timeout(function () { var elItem; $anchorScroll(); elItem = document.querySelector('#item-' + oItem.id); elItem.classList.toggle('blink', true); $timeout(function () { elItem.classList.toggle('blink', false); }, 1000); }); }); } else { alert('需要指定对应的题目!'); } }; $scope.listRemark = function (oRecord) { $scope.transferParam = { 0: 'record', 1: oRecord }; $scope.selectedView.url = '/views/default/site/fe/matter/enroll/template/remark.html'; }; $scope.likeRecord = function () { if ($scope.setOperateLimit('like')) { var oRecord; oRecord = $scope.record; http2.get(LS.j('record/like', 'site', 'ek')).then(function (rsp) { oRecord.like_log = rsp.data.like_log; oRecord.like_num = rsp.data.like_num; }); } }; $scope.dislikeRecord = function () { if ($scope.setOperateLimit('like')) { var oRecord; oRecord = $scope.record; http2.get(LS.j('record/dislike', 'site', 'ek')).then(function (rsp) { oRecord.dislike_log = rsp.data.dislike_log; oRecord.dislike_num = rsp.data.dislike_num; }); } }; $scope.editRecord = function (event) { if ($scope.app.scenarioConfig.can_cowork !== 'Y' && $scope.record.userid !== $scope.user.uid && $scope.user.is_editor !== 'Y') return noticebox.warn('不允许编辑其他用户提交的记录'); var page = $scope.app.pages.find(p => p.type === 'I') if (page) $scope.gotoPage(event, page, $scope.record.enroll_key); }; $scope.shareRecord = function (oRecord) { var url; url = LS.j('', 'site', 'app') + '&ek=' + oRecord.enroll_key + '&page=share'; if (_shareby) url += '&shareby=' + _shareby; location.href = url; }; $scope.doQuestionTask = function (oRecord) { if ($scope.questionTasks.length === 1) { http2.post(LS.j('topic/assign', 'site') + '&record=' + oRecord.id + '&task=' + $scope.questionTasks[0].id, {}).then(function () { noticebox.success('操作成功!'); }); } }; $scope.transmitRecord = function (oRecord) { $uibModal.open({ templateUrl: 'transmitRecord.html', controller: ['$scope', '$uibModalInstance', function ($scope2, $mi) { $scope2.result = {}; $scope2.transmitConfig = _oApp.transmitConfig; $scope2.cancel = function () { $mi.dismiss(); }; $scope2.ok = function () { if ($scope2.result.config) { $mi.close($scope2.result); } }; }], windowClass: 'modal-remark auto-height', backdrop: 'static', }).result.then(function (oResult) { var oConfig; if ((oConfig = oResult.config) && oConfig.id) { http2.get(LS.j('record/transmit', 'site') + '&ek=' + oRecord.enroll_key + '&transmit=' + oConfig.id).then(function (rsp) { var oNewRec; if (oResult.gotoNewRecord) { oNewRec = rsp.data; location.href = LS.j() + '?site=' + oNewRec.site + '&app=' + oNewRec.aid + '&ek=' + oNewRec.enroll_key + '&page=cowork'; } else { noticebox.success('记录转发成功!'); } }); } }); }; $scope.gotoUpper = function (upperId) { var elRemark, offsetTop, parentNode; elRemark = document.querySelector('#remark-' + upperId); offsetTop = elRemark.offsetTop; parentNode = elRemark.parentNode; while (parentNode && parentNode.tagName !== 'BODY') { offsetTop += parentNode.offsetTop; parentNode = parentNode.parentNode; } document.body.scrollTop = offsetTop - 40; elRemark.classList.add('blink'); $timeout(function () { elRemark.classList.remove('blink'); }, 1000); }; /* 关闭任务提示 */ $scope.closeCoworkTask = function (index) { $scope.coworkTasks.splice(index, 1); }; $scope.closeRemarkTask = function (index) { $scope.remarkTasks.splice(index, 1); }; $scope.gotoAssoc = function (oEntity) { var url; switch (oEntity.type) { case 'record': if (oEntity.enroll_key) url = LS.j('', 'site', 'app', 'page') + '&ek=' + oEntity.enroll_key; break; case 'topic': url = LS.j('', 'site', 'app') + '&page=topic' + '&topic=' + oEntity.id; break; case 'article': if (oEntity.entryUrl) url = oEntity.entryUrl; break; } if (url) location.href = url; }; $scope.$on('transfer.param', function (event, data) { $scope.transferParam = data; }); $scope.$on('xxt.app.enroll.ready', function (event, params) { var oSchemasById, aImageSchemas, aCoworkSchemas, aVisibleSchemas, templateUrl; _oApp = params.app; _oUser = params.user; aVisibleSchemas = []; aImageSchemas = []; aCoworkSchemas = []; oSchemasById = {}; _oApp.dynaDataSchemas.forEach(function (oSchema) { if (oSchema.cowork === 'Y') { aCoworkSchemas.push(oSchema); } else if (oSchema.shareable && oSchema.shareable === 'Y') { aVisibleSchemas.push(oSchema); } if (oSchema.type === 'image') { aImageSchemas.push(oSchema) } oSchemasById[oSchema.id] = oSchema; }); $scope.schemasById = oSchemasById; $scope.visibleSchemas = aVisibleSchemas; $scope.imageSchemas = aImageSchemas; $scope.coworkSchemas = aCoworkSchemas; if (aCoworkSchemas.length) { $scope.fileName = 'coworkData'; } else { $scope.fileName = 'remark'; } templateUrl = '/views/default/site/fe/matter/enroll/template/record-' + $scope.fileName + '.html?_=1' $scope.selectedView = { 'url': templateUrl }; fnLoadRecord(aCoworkSchemas).then(function (oRecord) { /* 通过留言完成提问任务 */ new enlTask($scope.app).list('question', 'IP').then(function (tasks) { $scope.questionTasks = tasks; }); new enlTask($scope.app).list('answer', 'IP', null, oRecord.enroll_key).then(function (tasks) { $scope.answerTasks = tasks; }); if (_oApp.scenarioConfig && _oApp.scenarioConfig.can_assoc === 'Y') { fnLoadAssoc(oRecord, _oAssocs).then(function () { fnAfterRecordLoad(oRecord, _oUser); }); } else { fnAfterRecordLoad(oRecord, _oUser); } }); }); }]); /** * 协作题 */ ngApp.controller('ctrlCoworkData', ['$scope', '$timeout', '$anchorScroll', '$uibModal', 'tmsLocation', 'http2', 'noticebox', 'enlAssoc', function ($scope, $timeout, $anchorScroll, $uibModal, LS, http2, noticebox, enlAssoc) { $scope.addItem = function (oSchema) { if ($scope.setOperateLimit('add_cowork')) { $uibModal.open({ templateUrl: 'writeItem.html', controller: ['$scope', '$uibModalInstance', function ($scope2, $mi) { $scope2.data = { content: '' }; $scope2.cancel = function () { $mi.dismiss(); }; $scope2.ok = function () { var content; if (window.tmsEditor && window.tmsEditor.finish) { content = window.tmsEditor.finish(); $scope2.data.content = content; $mi.close({ content: content }); } }; }], windowClass: 'modal-remark auto-height', backdrop: 'static', }).result.then(function (data) { if (!data.content) return; var oRecData, oNewItem, url; oRecData = $scope.record.verbose[oSchema.id]; oNewItem = { value: data.content }; url = LS.j('cowork/add', 'site'); url += '&ek=' + $scope.record.enroll_key + '&schema=' + oSchema.id; if ($scope.options.forAnswerTask) url += '&task=' + $scope.options.forAnswerTask; http2.post(url, oNewItem).then(function (rsp) { var oNewItem; oNewItem = rsp.data.oNewItem; oNewItem.nickname = '我'; if (oRecData) { oRecData.items.push(oNewItem); } else if (rsp.data.oRecData) { oRecData = $scope.record.verbose[oSchema.id] = rsp.data.oRecData; oRecData.items = [oNewItem]; } if (rsp.data.coworkResult.user_total_coin) { noticebox.info('您获得【' + rsp.data.coworkResult.user_total_coin + '】分'); } }); }); } }; $scope.editItem = function (oSchema, index) { var oRecData, oItem; oRecData = $scope.record.verbose[oSchema.id]; oItem = oRecData.items[index]; $uibModal.open({ templateUrl: 'writeItem.html', controller: ['$scope', '$uibModalInstance', function ($scope2, $mi) { $scope2.data = { content: oItem.value }; $scope2.cancel = function () { $mi.dismiss(); }; $scope2.ok = function () { var content; if (window.tmsEditor && window.tmsEditor.finish) { content = window.tmsEditor.finish(); $scope2.data.content = content; $mi.close({ content: content }); } }; }], windowClass: 'modal-remark auto-height', backdrop: 'static', }).result.then(function (data) { if (!data.content) return; var oNewItem; oNewItem = { value: data.content }; http2.post(LS.j('cowork/update', 'site') + '&data=' + oRecData.id + '&item=' + oItem.id, oNewItem).then(function (rsp) { oItem.value = data.content; }); }); }; $scope.removeItem = function (oSchema, index) { var oRecData, oItem; oRecData = $scope.record.verbose[oSchema.id]; oItem = oRecData.items[index]; noticebox.confirm('删除填写项,确定?').then(function () { http2.get(LS.j('cowork/remove', 'site') + '&item=' + oItem.id).then(function (rsp) { oRecData.items.splice(index, 1); }); }); }; $scope.agreeItem = function (oItem, value) { var url; if (oItem.agreed !== value) { url = LS.j('data/agree', 'site', 'ek') + '&data=' + oItem.id + '&schema=' + oItem.schema_id; url += '&value=' + value; http2.get(url).then(function (rsp) { oItem.agreed = value; }); } }; $scope.likeItem = function (oItem) { if ($scope.setOperateLimit('like')) { http2.get(LS.j('data/like', 'site') + '&data=' + oItem.id).then(function (rsp) { oItem.like_log = rsp.data.like_log; oItem.like_num = rsp.data.like_num; }); } }; $scope.dislikeItem = function (oItem) { if ($scope.setOperateLimit('like')) { http2.get(LS.j('data/dislike', 'site') + '&data=' + oItem.id).then(function (rsp) { oItem.dislike_log = rsp.data.dislike_log; oItem.dislike_num = rsp.data.dislike_num; }); } }; $scope.listItemRemark = function (oItem) { $scope.$emit('transfer.param', { 0: 'coworkData', 1: oItem }); $scope.selectedView.url = '/views/default/site/fe/matter/enroll/template/remark.html'; }; $scope.shareItem = function (oItem) { var url, shareby; url = LS.j('', 'site', 'app', 'ek') + '&data=' + oItem.id + '&page=share'; shareby = location.search.match(/shareby=([^&]*)/) ? location.search.match(/shareby=([^&]*)/)[1] : ''; if (shareby) { url += '&shareby=' + shareby; } location.href = url; }; $scope.assocMatter = function (oItem) { enlAssoc.assocMatter($scope.user, $scope.record, { id: oItem.id, type: 'data' }).then(function (oAssoc) { var oCachedAssoc; oCachedAssoc = $scope.assocs; if (oCachedAssoc.data === undefined) oCachedAssoc.data = {}; if (oCachedAssoc.data[oItem.id] === undefined) oCachedAssoc.data[oItem.id] = []; oCachedAssoc.data[oItem.id].push(oAssoc); }); }; $scope.removeItemAssoc = function (oItem, oAssoc) { noticebox.confirm('取消关联,确定?').then(function () { http2.get(LS.j('assoc/unlink', 'site') + '&assoc=' + oAssoc.id).then(function () { $scope.assocs.data[oItem.id].splice($scope.assocs.data[oItem.id].indexOf(oAssoc), 1); }); }); }; $scope.doAnswerTask = function (oItem) { if ($scope.answerTasks && $scope.answerTasks.length) { if ($scope.answerTasks.length === 1) { http2.post(LS.j('topic/assign', 'site') + '&record=' + $scope.record.id + '&data=' + oItem.id + '&task=' + $scope.answerTasks[0].id, {}).then(function () { noticebox.success('操作成功!'); }); } } }; }]); /** * 留言 */ ngApp.controller('ctrlRemark', ['$scope', '$location', '$uibModal', '$anchorScroll', '$timeout', 'http2', 'tmsLocation', 'noticebox', 'picviewer', function ($scope, $location, $uibModal, $anchorScroll, $timeout, http2, LS, noticebox, picviewer) { function addRemark(content, oRemark) { var url; url = LS.j('remark/add', 'site', 'ek', 'data'); if (oRemark) url += '&remark=' + oRemark.id; if ($scope.options.forQuestionTask) url += '&task=' + $scope.options.forQuestionTask; return http2.post(url, { content: content }); } function fnAppendRemark(oNewRemark, oUpperRemark) { var oNewRemark; oNewRemark.content = oNewRemark.content.replace(/\\n/g, '<br/>'); if (oUpperRemark) { oNewRemark.reply = '<a href="#remark-' + oUpperRemark.id + '">回复' + oUpperRemark.nickname + '的留言 #' + oUpperRemark.seq_in_record + '</a>'; } $scope.remarks.push(oNewRemark); if (!oUpperRemark) { $scope.record.rec_remark_num++; } $timeout(function () { var elRemark; $location.hash('remark-' + oNewRemark.id); $anchorScroll(); elRemark = document.querySelector('#remark-' + oNewRemark.id); elRemark.classList.toggle('blink', true); /* 支持图片预览 */ $timeout(function () { var imgs; if (imgs = document.querySelectorAll('#remark-' + oNewRemark.id + ' img')) { picviewer.init(imgs); } }); $timeout(function () { elRemark.classList.toggle('blink', false); }, 1000); }); } function listRemarks(type, data) { var url; url = LS.j('remark/list', 'site', 'ek', 'schema', 'data'); if (type == 'record') { url += '&onlyRecord=true'; } else if (type == 'coworkData') { url += data.id; } http2.get(url).then(function (rsp) { var remarks, oRemark, oUpperRemark, oCoworkRemark, oRemarks; remarks = rsp.data.remarks; if (remarks && remarks.length) { oRemarks = {}; remarks.forEach(function (oRemark) { oRemarks[oRemark.id] = oRemark; }); for (var i = remarks.length - 1; i >= 0; i--) { oRemark = remarks[i]; if (oRemark.content) { oRemark.content = oRemark.content.replace(/\n/g, '<br/>'); } if (oRemark.remark_id !== '0') { if (oUpperRemark = oRemarks[oRemark.remark_id]) { oRemark.reply = '<a href="#remark-' + oRemark.remark_id + '">回复' + oUpperRemark.nickname + '的留言 #' + (oRemark.data_id === '0' ? oUpperRemark.seq_in_record : oUpperRemark.seq_in_data) + '</a>'; } } } } $scope.remarks = remarks; /* 支持图片预览 */ $timeout(function () { var imgs; if (imgs = document.querySelectorAll('#remarks img')) { picviewer.init(imgs); } }); if ($location.hash() === 'remarks') { $timeout(function () { $anchorScroll.yOffset = 30; $anchorScroll(); }); } else if (/remark-.+/.test($location.hash())) { $timeout(function () { var elRemark; if (elRemark = document.querySelector('#' + $location.hash())) { $anchorScroll(); elRemark.classList.toggle('blink', true); $timeout(function () { elRemark.classList.toggle('blink', false); }, 1000); } }); } }); } function writeRemark(oUpperRemark) { if ($scope.setOperateLimit('add_remark')) { $uibModal.open({ templateUrl: 'writeRemark.html', controller: ['$scope', '$uibModalInstance', function ($scope2, $mi) { $scope2.data = { content: '' }; $scope2.cancel = function () { $mi.dismiss(); }; $scope2.ok = function () { var content; if (window.tmsEditor && window.tmsEditor.finish) { content = window.tmsEditor.finish(); $scope2.data.content = content; $mi.close({ content: content }); } }; }], windowClass: 'modal-remark auto-height', backdrop: 'static', }).result.then(function (data) { if (!data.content) return; addRemark(data.content, oUpperRemark).then(function (rsp) { fnAppendRemark(rsp.data, oUpperRemark); if (rsp.data.remarkResult.user_total_coin) { noticebox.info('您获得【' + rsp.data.remarkResult.user_total_coin + '】分'); } }); }); } } function writeItemRemark(oItem) { if ($scope.setOperateLimit('add_remark')) { var itemRemarks; if ($scope.remarks && $scope.remarks.length) { itemRemarks = []; $scope.remarks.forEach(function (oRemark) { if (oRemark.data_id && oRemark.data_id === oItem.id) { itemRemarks.push(oRemark); } }); } $uibModal.open({ templateUrl: 'writeRemark.html', controller: ['$scope', '$uibModalInstance', function ($scope2, $mi) { $scope2.remarks = itemRemarks; $scope2.data = { content: '' }; $scope2.cancel = function () { $mi.dismiss(); }; $scope2.ok = function () { var content; if (window.tmsEditor && window.tmsEditor.finish) { content = window.tmsEditor.finish(); $scope2.data.content = content; $mi.close({ content: content }); } }; }], windowClass: 'modal-remark auto-height', backdrop: 'static', }).result.then(function (data) { if (!data.content) return; http2.post(LS.j('remark/add', 'site', 'ek') + '&data=' + oItem.id, { content: data.content }).then(function (rsp) { var oNewRemark; oNewRemark = rsp.data; oNewRemark.data = oItem; oNewRemark.content = oNewRemark.content.replace(/\\n/g, '<br/>'); $scope.remarks.splice(0, 0, oNewRemark); $timeout(function () { var elRemark, parentNode, offsetTop; elRemark = document.querySelector('#remark-' + oNewRemark.id); parentNode = elRemark.parentNode; while (parentNode && parentNode.tagName !== 'BODY') { offsetTop += parentNode.offsetTop; parentNode = parentNode.parentNode; } document.body.scrollTop = offsetTop - 40; elRemark.classList.add('blink'); if (rsp.data.remarkResult.user_total_coin) { noticebox.info('您获得【' + rsp.data.remarkResult.user_total_coin + '】分'); } $timeout(function () { elRemark.classList.remove('blink'); }, 1000); }); }); }); } } $scope.goback = function () { var templateUrl = '/views/default/site/fe/matter/enroll/template/record-' + $scope.fileName + '.html'; $scope.selectedView.url = templateUrl; }; $scope.editRemark = function (oRemark) { $uibModal.open({ templateUrl: 'writeRemark.html', controller: ['$scope', '$uibModalInstance', function ($scope2, $mi) { $scope2.data = { content: oRemark.content }; $scope2.cancel = function () { $mi.dismiss(); }; $scope2.ok = function () { var content; if (window.tmsEditor && window.tmsEditor.finish) { content = window.tmsEditor.finish(); $scope2.data.content = content; $mi.close({ content: content }); } }; }], windowClass: 'modal-remark auto-height', backdrop: 'static', }).result.then(function (data) { http2.post(LS.j('remark/update', 'site') + '&remark=' + oRemark.id, { content: data.content }).then(function (rsp) { oRemark.content = data.content; }); }); }; $scope.removeRemark = function (oRemark) { noticebox.confirm('撤销留言,确定?').then(function () { http2.post(LS.j('remark/remove', 'site') + '&remark=' + oRemark.id).then(function (rsp) { $scope.remarks.splice($scope.remarks.indexOf(oRemark), 1); }); }); }; $scope.agreeRemark = function (oRemark, value) { var url; if (oRemark.agreed !== value) { url = LS.j('remark/agree', 'site'); url += '&remark=' + oRemark.id; url += '&value=' + value; http2.get(url).then(function (rsp) { oRemark.agreed = rsp.data; }); } }; $scope.likeRemark = function (oRemark) { if ($scope.setOperateLimit('like')) { var url; url = LS.j('remark/like', 'site'); url += '&remark=' + oRemark.id; http2.get(url).then(function (rsp) { oRemark.like_log = rsp.data.like_log; oRemark.like_num = rsp.data.like_num; }); } }; $scope.dislikeRemark = function (oRemark) { if ($scope.setOperateLimit('like')) { var url; url = LS.j('remark/dislike', 'site'); url += '&remark=' + oRemark.id; http2.get(url).then(function (rsp) { oRemark.dislike_log = rsp.data.dislike_log; oRemark.dislike_num = rsp.data.dislike_num; }); } }; $scope.shareRemark = function (oRemark) { var url; url = LS.j('', 'site', 'app', 'ek') + '&remark=' + oRemark.id + '&page=share'; if (shareby) { url += '&shareby=' + shareby; } location.href = url; }; $scope.writeRemark = function (oUpperRemark) { if (oUpperRemark) { writeRemark(oUpperRemark); } else { if (!oType) { writeRemark(); } else { switch (oType) { case 'record': writeRemark(); break; case 'coworkData': writeItemRemark(oData); break; default: break; } } } }; var oType, oData; $scope.$watch('transferParam', function (nv) { if (!nv) { return false; } $scope.transferType = oType = nv[0]; $scope.transferData = oData = nv[1]; switch (oType) { case 'record': listRemarks('record'); break; case 'coworkData': listRemarks('coworkData', oData); break; default: break; } }); if ($scope.fileName == 'remark') { $scope.$watch('record', function (oRecord) { if (oRecord) { listRemarks(); } }, true); } }]);
import { GENERATE_PASSWORD_REQUEST, GENERATE_PASSWORD_SUCCESS, GENERATE_PASSWORD_FAILURE, } from './manage-users-constants'; const initialState = { isLoading: false, }; const generatePassword = (state = initialState, action) => { switch (action.type) { case GENERATE_PASSWORD_REQUEST: return { ...state, isLoading: true, }; case GENERATE_PASSWORD_FAILURE: return { ...state, isLoading: false, }; case GENERATE_PASSWORD_SUCCESS: return { ...state, isLoading: false, }; default: return state; } }; export default generatePassword;
var path = require('path') var postcss = require('postcss') exports.postfactory = function (opts) { return [ //css层级写法 https://github.com/postcss/postcss-nested require('postcss-nested')(), //css浏览器兼容 require('autoprefixer')({ browsers: ['last 2 versions'] }), ]; }
'use strict' require('core-js/stable/object/assign') // TODO: remove dependency require('core-js/stable/set') // TODO: remove dependency require('core-js/stable/map') // TODO: remove dependency require('core-js/stable/typed-array') // TODO: remove dependency const platform = require('./src/platform') const browser = require('./src/platform/browser') const ext = require('../../ext') platform.use(browser) const TracerProxy = require('./src/proxy') const tracer = new TracerProxy() module.exports = tracer module.exports.default = module.exports module.exports.tracer = module.exports window.ddtrace = { tracer, ext }
import Default from '@src/view/Default.vue'; import Foo from '@src/view/Foo.vue'; import Bar from '@src/view/Bar.vue'; export default { mode: 'history', routes: [ {path: '/', component: Default}, {path: '/foo', component: Foo}, {path: '/bar', component: Bar}, ], };
import React, { Component } from 'react'; import Modal from '../Modal/Modal'; import { Link } from "react-router-dom"; import api from "../API/api"; class Login extends Component { state = { email: null, senha: null, alert: null, novaSenha: null, confirmarNovaSenha: null, modal: false, alertModal: null, modalSucess: false, modalEmail: false, carregando: false, } chamarAlerta = (msg) => { this.setState({ alert: msg, }, () => { let alertDiv = document.getElementById("alert-div"); if (alertDiv) alertDiv.scrollIntoView(); }); } // função que atualiza o state do email e senha Submit = (e) => { this.setState({ [e.target.name]: e.target.value }) } //função chamada clicando no botao Login CliqueLogin = async () => { //teste para saber se existe algum campo vazio, se existir exibir um alerta if (this.state.email === "" || this.state.senha === "" || !this.state.email.toString().trim() || !this.state.senha.toString().trim()) return this.chamarAlerta("Preencha todos os campos!"); if (!this.verifyEmail(this.state.email)) return this.chamarAlerta("Formato de email inválido!"); //Criando objeto de usuário a ser logado let user = { email: this.state.email, senha: this.state.senha, } this.setState({carregando: true}); //Executando uma função herdada com os dados passados, res recebe retorno da função; await this.props.login(user).then((res) => { if(res.error) return this.chamarAlerta("Erro inesperado... Tente novamento mais tarde!"); if(res === "Email inválido!" || res === "Senha inválida!") return this.chamarAlerta(res); if( res === 'Confirme seu email!') this.setState({ modalEmail: true }); }).catch(e => { console.log(e); return this.chamarAlerta("Erro inesperado... Tente novamento mais tarde!"); }); this.setState({ carregando: false }); } //função para fechar um alerta fecharAlerta = () => { this.setState({ alert: null, }); } // Função a ser passada para alternar state do modal modalControl = () => { this.setState({ modal: this.state.modal ? false : true }); return this.state.modal } modalControlSucess = () => { this.setState({ modalSucess: this.state.modalSucess ? false : true }); return this.state.modalSucess } modalControlEmail = () => { this.setState({ modalSucess: this.state.modalEmail ? false : true }); return this.state.modalEmail } // Função para verificar validade de email verifyEmail = (emailString) => { const userString = emailString.substring(0, emailString.indexOf("@")); const dom = emailString.substring(emailString.indexOf("@")+ 1, emailString.length); if ((userString.length >=1) && (dom.length >=3) && (userString.search("@")===-1) && (dom.search("@")===-1) && (userString.search(" ")===-1) && (dom.search(" ")===-1) && (dom.search(".")!==-1) &&(dom.indexOf(".") >=1) && (dom.lastIndexOf(".") < dom.length - 1)) { return true; } else return false; } chamarEsqueceSenha = () => { const { email } = this.state; if(!this.state.email || !this.state.email.toString().trim()) return this.chamarAlerta("Preecha o campo de email!"); if(!this.verifyEmail(email)) return this.chamarAlerta("Formato de email inválido!"); else { this.setState({ modal: true }); } } recuperarSenha = async () =>{ const { novaSenha, confirmarNovaSenha } = this.state; if(!novaSenha || !confirmarNovaSenha || !novaSenha.toString().trim() || !confirmarNovaSenha.toString().trim()) return this.chamarAlertaModal("Preencha todos os campos!"); if(novaSenha.length < 6) return this.chamarAlertaModal("Sua senha deve possuir no mínimo 6 caracteres"); if(novaSenha !== confirmarNovaSenha) return this.chamarAlertaModal("A confirmação de senha não coincide!"); const req = { email: this.state.email, newPass: novaSenha }; console.log("chamando api de alteração de senha de senha"); this.setState({ carregando: true }); const res = await api.post('/trocarsenha', req); this.setState({ carregando: false}); if(res.data){ console.log(res.data); if(res.data.status) return this.setState({ modal: false, modalSucess: true }); else if(res.data === "Email não cadastrado!") return this.chamarAlertaModal("Email não cadastrado!"); else this.chamarAlertaModal("Erro inesperado... Tente novament mais tarde!"); } else { return this.chamarAlertaModal("Erro inesperado... Tente mais tarde!"); } console.log(res); } fecharAlertaModal = () => { this.setState({ alertModal: null, }); } chamarAlertaModal = (msg) => { this.setState({ alertModal: msg, }, () => { let alertDiv = document.getElementById("alert-div-modal"); if (alertDiv) alertDiv.scrollIntoView(); }); } sendEmail = async () => { this.setState({ carregando: true }); await api.post('/confirmaremail', { email: this.state.email }).then(res => { if (res.data.status === 200) this.setState({ modalEmail: false, modalSucess: true }); else this.chamarAlertaModal("Erro inesperado... Tente novament mais tarde!"); console.log(res); }).catch(e => { console.log(e); this.chamarAlertaModal("Erro inesperado... Tente novament mais tarde!"); }) this.setState({ carregando: false }); } render() { return ( <div className="login container"> <div className="bread"> <Link to="/home" >Home</Link> <span className="arrow">/</span> <span>Login</span> </div> <div className="criar-conta login"> <header className="page-header"> <h1>Login</h1> </header> <p className="title">Entre na sua conta 7 Tons de Beleza.</p> <form> <label>Email</label><em>*&nbsp;&nbsp;</em> <div> <input className="inputt" type="email" name="email" onChange={this.Submit} value={this.state.email} ></input> </div> <label>Senha</label><em>*&nbsp;&nbsp;</em> <div> <input className="inputt" type="password" name="senha" onChange={this.Submit} value={this.state.senha}></input> </div> {!this.props.admin ? <p onClick={()=> this.chamarEsqueceSenha()}> <Link to="#"> Esqueceu sua senha? </Link></p> : null} <p className="btn-secundaryy"> <Link to="#" onClick={this.CliqueLogin}> { this.state.carregando ? 'Entrando...' : 'Entrar' } </Link> <em className="obrigatorio">(* obrigatório)</em> </p> <div> { this.state.alert? <div id="alert-div" className="alertacadastro">{this.state.alert} <Link className="fecharalerta" name="alerta2" onClick={()=>this.fecharAlerta()} to="#">X</Link> </div> : null } </div> </form> <Modal actived={this.state.modal} controller={this.modalControl}> <h1>Deseja recuperar a senha do email abaixo?</h1> <p> <em> {this.state.email} </em> </p> <p> Te enviaremos um email automático para recuperação de senha! </p> <label>Nova senha</label> <div> <input className="inputt" type="password" name="novaSenha" onChange={this.Submit} value={this.state.novaSenha}></input> </div> <label>Confirmar nova senha</label> <div> <input className="inputt" type="password" name="confirmarNovaSenha" onChange={this.Submit} value={this.state.confirmarNovaSenha}></input> </div> <p className="btn-secundaryy"> <Link to="#" onClick={() => this.recuperarSenha()} > { !this.state.carregando? 'Confirmar' : 'Enviando...' } </Link> </p> { this.state.alertModal ? <div id="alert-div-modal" className="alertacadastro">{this.state.alertModal} <Link className="fecharalerta" name="alerta2" onClick={()=>this.fecharAlertaModal()} to="#">X</Link> </div> : null } </Modal> <Modal actived={this.state.modalSucess} controller={this.modalControlSucess}> <h1> Te enviamos um email de confirmação! </h1> <p> Acesse seu email para finalizar esse processo! </p> </Modal> <Modal actived={this.state.modalEmail} controller={this.modalControlEmail}> <h1> Seu email ainda não foi confirmado! </h1> <p> Para efetuar o login é preciso confirmar seu email <strong>{this.state.email}</strong> através do link na mensagem que te enviamos. </p> <p className="btn-secundaryy"> <Link to="#" onClick={() => this.sendEmail()} > { !this.state.carregando? 'Reenviar mensagem' : 'Enviando...' } </Link> </p> { this.state.alertModal ? <div id="alert-div-modal" className="alertacadastro">{this.state.alertModal} <Link className="fecharalerta" name="alerta2" onClick={()=>this.fecharAlertaModal()} to="#">X</Link> </div> : null } </Modal> </div> </div> ) } } export default Login
Ext.define('AM.controller.CashMutations', { extend: 'Ext.app.Controller', stores: ['CashMutations'], models: ['CashMutation'], views: [ 'master.cashmutation.List', ], refs: [ { ref: 'list', selector: 'cashmutationlist' } ], init: function() { this.control({ 'cashmutationlist': { selectionchange: this.selectionChange, afterrender : this.loadObjectList, }, 'cashmutationlist textfield[name=searchField]': { change: this.liveSearch } , }); }, liveSearch : function(grid, newValue, oldValue, options){ var me = this; me.getCashMutationsStore().getProxy().extraParams = { livesearch: newValue }; me.getCashMutationsStore().load(); }, loadObjectList : function(me){ // console.log("************* IN THE USERS CONTROLLER: afterRENDER"); me.getStore().load(); }, selectionChange: function(selectionModel, selections) { var grid = this.getList(); if (selections.length > 0) { grid.enableRecordButtons(); } else { grid.disableRecordButtons(); } } });
$(document).ready(function() { responsive_resize(); // NAVIGATION $('.menu-toggle').click(function(){ $('.menu-toggle').toggleClass('active'); }); $('.teams-nav-link').hover(function(){ console.log(123); $('.teams-list').toggleClass('team-list-active'); }); // Change width value on user resize, after DOM $(window).resize(function(){ responsive_resize(); }); function responsive_resize() { var current_width = $(window).width(); if (current_width <= 767) { $('.team-page-hero').addClass('justify-content-center'); } else if (current_width >= 768) { $('.team-page-hero').removeClass('justify-content-center'); } } });
import React from 'react'; import Enzyme, { shallow } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import Flight from '.'; Enzyme.configure({ adapter: new Adapter() }); describe('Flight component', () => { test('exists without data', () => { const wrapper = shallow(<Flight />); expect(wrapper.exists()).toBe(true); }); test('exists with empty data', () => { const wrapper = shallow(<Flight data={{}} />); expect(wrapper.exists()).toBe(true); }); test('exists with data', () => { const data = { route: 'Ankara-Singapore', departure: '1558902656', arrival: '1558902656', type: 'Cheap', }; const wrapper = shallow(<Flight data={data} />); expect(wrapper.exists()).toBe(true); }); });
// @TODO fix unterminated expression? {... DefaultScript.parse = function (source, name, onException) { if (typeof onException !== 'function') { throw new TypeError('onException must be provided'); } var syntax = DefaultScript.syntax; var isEscape = false; var isComment = false; var breaks = [-1]; var position = function (start, end) { var i = start; var positionFn = function () { var line = -1; while (i > breaks[line + 1]) { line++; } var column = i - breaks[line]; return 'line ' + ++line + ' column ' + column; }; positionFn.start = start; positionFn.end = typeof end === 'number' ? end : start; positionFn.getSource = function (includeCaret) { var line = -1; while (i > breaks[line + 1]) { line++; } var column = i - breaks[line]; var start = breaks[line] + 1; var sourceLine = source.substr(start, (breaks[line + 1] || start + 1) - start); if (includeCaret) { sourceLine = '\n' + name + ':' + (line + 1) + '\n' + sourceLine + '\n' + new Array(column).join(' ') + '^'; } return sourceLine; }; return positionFn; }; var logic = DefaultScript.block(LOGIC, position(0, source.length - 1)); var head = logic; var stack = []; var previous; var isString; var queue = DefaultScript.token(NAME, position(0)); var queueToHead = function (i) { if (queue[SOURCE].length) { queue[POSITION].end = i - 1; head[SOURCE].push(queue); } queue = DefaultScript.token(NAME, position(i + 1)); }; var breakAt = function (head, i) { var src = head[SOURCE]; if (src.length > 0 && src[src.length - 1][TYPE] !== BREAK) { src.push(DefaultScript.token(BREAK, position(i))); } }; for (var i = 0; i < source.length; i++) { if (source[i] === '\r') { continue; } if (source[i] === '\n') { isComment = false; breaks.push(i); } isString = head[TYPE] && syntax.blocks[head[TYPE]] && syntax.blocks[head[TYPE]].string; if (isComment) { // do nothing } else if (!isString && !isComment && source[i] === syntax.comment) { isComment = true; continue; } else if (!isEscape && source[i] === syntax.escape) { isEscape = true; } else if (isEscape) { isEscape = false; if (isString) { var add = source[i]; if (add === 'n') { add = '\n'; } else if (add === 't') { add = '\t'; } head[SOURCE] += add; } } else if (!isString && source[i] in syntax.open) { queueToHead(i); previous = head; stack.push(previous); var type = syntax.open[source[i]]; // <3 OSS if (syntax.blocks[type].string) { head = DefaultScript.token(type, position(i)); } else { head = DefaultScript.block(type, position(i)); } previous[SOURCE].push(head); } else if (isString && source[i] === syntax.blocks[head[TYPE]].close) { head[POSITION].end = i; head = stack.pop(); } else if (isString) { head[SOURCE] += source[i]; } else if (syntax.close.indexOf(source[i]) !== -1) { if (head && syntax.blocks[head[TYPE]] && source[i] === syntax.blocks[head[TYPE]].close) { queueToHead(i); breakAt(head, i); head[POSITION].end = i; head = stack.pop(); } else { head = null; } if (!head) { onException(new SyntaxError('Unexpected'), { value: source[i], position: position(i) }, name); } } else if (syntax.separators.indexOf(source[i]) !== -1) { queueToHead(i); breakAt(head, i); } else if (syntax.whitespace.indexOf(source[i]) !== -1) { queueToHead(i); } else if (syntax.name.test(source[i])) { queueToHead(i); head[SOURCE].push(DefaultScript.token(OPERATOR, position(i), source[i])); } else { queue[SOURCE] += source[i]; } } return logic; };
'use strict'; angular.module('biofuels.sections.customers.controller', []) .controller('customersCtrl', function ($log, customerService ) { (function (vm) { $log.debug('This is from the customers page'); vm.selected = []; vm.customers = []; function getCustomers () { vm.formError = ''; vm.formResponse = ''; customerService.getCustomers().then(function (data) { vm.formResponse = 'Successfully got customer list!'; vm.customers = data.data; $log.debug(vm.customers.length); }).catch(function (err) { vm.formError = err.error; }); } getCustomers(); })(this); });
import Link from "next/link"; export function Tag({ name, children }) { return ( <> <Link href={`/tags/${name.toLowerCase()}/1`}> <a>#{children}</a> </Link> </> ); }
({ doInit: function (component, event, helper) { try { let regionDetected = window.sessionStorage.getItem("regionStorage"); if (regionDetected) { helper.getCoursePlanList(component, event, helper); } } catch (e) { helper.sendGAExceptionEvent('XCL_CoursePlanSectionList', 'doInit: ' + e.message); } }, regionalisationHandler: function (component, event, helper) { //region change detected let sessionRegion = window.sessionStorage.getItem("regionStorage"); let componentRegion = component.get("v.componentRegion"); //Additional check to prevent multiple server calls //Server calls happen only when region is changed from previous region if (sessionRegion != componentRegion) { component.set("v.componentRegion", sessionRegion); helper.getCoursePlanList(component, event, helper); } } })
import React from "react"; import { NavLink } from "react-router-dom"; const AppCommon = (props) => { return ( <> <section id="header" className=" d-flex "> <div className="container-fluid"> <div className="row "> <div className="col-10 mx-auto "> <div className="row align-items-center"> <div className="col-md-6 pt-5 pt-lg-0 order-lg-1 order-2 mx-auto "> <h1 className=" text-capitalize"> {props.name} <strong className="text-info strongtxt"> Tarun Kushwaha </strong> </h1> <h5>We are the team of talented developers making website</h5> <div> <NavLink to={props.visit} className="btn-get-started text-capitalize btn_start" > {props.btnName} </NavLink> </div> </div> <div className="col-md-6 order-lg-2 order-1 pt-lg-5 mx-auto"> <img src={props.imgSrc} className="img-fluid people_img " alt="Random Image" /> </div> </div> </div> </div> </div> </section> </> ); }; export default AppCommon;
/** @format */ import { StatusBar } from "expo-status-bar"; import { filter } from "lodash"; import React from "react"; import { FlatList } from "react-native"; import { StyleSheet, Text, TextInput, TouchableOpacity, KeyboardAvoidingView, ScrollView, Dimensions, SafeAreaView, View, Alert, Modal, } from "react-native"; import { SearchBar } from "react-native-elements"; import { FAB } from "react-native-paper"; import db from "../config"; export default class Main extends React.Component { constructor() { super(); this.state = { title: "", author: "", story: "", search: "", allStories: [], dataSource: [], isModalVisible: false, }; } publish = (t, a, s) => { if (t == "" || a == "" || s == "") { this.setState({ title: "", author: "", story: "", isModalVisible: false, }); return Alert.alert("Please Write a Story"); } else { db.collection("stories") .add({ title: t, author: a, story: s, }) .then(console.log(t, a, s)); this.setState({ title: "", author: "", story: "", }); return Alert.alert("Story Published"); } }; showModal = () => { return ( <Modal visible={this.state.isModalVisible} transparent={true} animationType={"slide"} > <KeyboardAvoidingView style={styles.modal}> <ScrollView> <Text style={styles.title}>Write A Story</Text> <View style={styles.line}></View> <TextInput placeholder="Story Title" placeholderTextColor="#6fb388" style={styles.input} onChangeText={(text) => { this.setState({ title: text }); }} /> <TextInput placeholder="Author" placeholderTextColor="#6fb388" style={styles.input} onChangeText={(text) => { this.setState({ author: text }); }} /> <TextInput placeholder="Write Your Story" placeholderTextColor="#6fb388" multiline={true} style={[styles.input, { height: 280 }]} onChangeText={(text) => { this.setState({ story: text }); }} /> <TouchableOpacity style={styles.button} onPress={() => { this.publish( this.state.title, this.state.author, this.state.story ), this.setState({ isModalVisible: false }); }} > <Text style={{ color: "#6fb388" }}>Publish</Text> </TouchableOpacity> <TouchableOpacity> <Text style={{ color: "#6fb388", alignSelf: "center", marginTop: -10, marginBottom: 20, textDecorationLine: "underline", }} onPress={() => { this.setState({ isModalVisible: false }); }} > ✖ Cancel ✖ </Text> </TouchableOpacity> </ScrollView> </KeyboardAvoidingView> </Modal> ); }; searchBooks = (search) => { let filteredData = this.state.allStories.filter(function (item) { return item.title.includes(search); }); this.setState({ dataSource: filteredData }); }; componentDidMount = async () => { const query = await db.collection("stories").get(); query.docs.map((doc) => { this.setState({ allStories: [...this.state.allStories, doc.data()], }); }); }; render() { return ( <SafeAreaView style={styles.container}> {this.showModal()} <View style={{ minWidth: Dimensions.get("screen").width }}> <SearchBar placeholder="Search" value={this.state.search} onChangeText={() => { this.searchBooks(this.state.search); }} lightTheme /> <FlatList data={this.state.allStories} renderItem={({ item }) => ( <View style={{ borderWidth: 1, margin: 8, padding: 10, borderRadius: 5, borderColor: "#e2e8ee", width: "96%", backgroundColor: "#bec6cf", }} > <Text style={{ color: "#7e8a94", fontWeight: "600" }}> {"Title: " + item.title} </Text> <Text style={{ color: "#7e8a94", fontWeight: "600" }}> {"Author: " + item.author} </Text> </View> )} keyExtractor={(item, index) => index.toString()} onEndReached={this.fetchMoreStories} onEndReachedThreshold={0.7} /> </View> <FAB style={styles.fab} label={"Write A Story"} icon="plus" onPress={() => { this.setState({ isModalVisible: true }); }} color="#6fb388" /> <StatusBar style="auto" /> </SafeAreaView> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#e2e8ee", alignItems: "center", }, line: { backgroundColor: "#6fb388", height: 2, width: "100%", alignSelf: "center", }, fab: { position: "absolute", margin: 16, marginBottom: 32, right: 0, bottom: 0, backgroundColor: "#c2edce", shadowColor: "#90ba9b", }, modal: { backgroundColor: "#c2edce", marginVertical: 40, width: "90%", alignSelf: "center", borderRadius: 20, shadowColor: "#000", shadowOffset: { width: 8, height: 8, }, shadowOpacity: 0.3, shadowRadius: 10.32, elevation: 20, }, title: { color: "#6fb388", fontSize: 25, margin: 10, marginTop: 15, marginBottom: 15, alignSelf: "center", }, input: { width: "90%", height: 40, fontSize: 20, borderRadius: 20, paddingLeft: 10, margin: 10, marginTop: 15, backgroundColor: "#f6f6f2", color: "#6fb388", alignSelf: "center", shadowColor: "#000", shadowOffset: { width: 8, height: 8, }, shadowOpacity: 0.3, shadowRadius: 10.32, elevation: 4, }, button: { width: "90%", height: 40, fontSize: 20, borderRadius: 20, margin: 10, marginBottom: 30, backgroundColor: "#c2edce", alignContent: "center", justifyContent: "center", alignItems: "center", alignSelf: "center", justifyContent: "center", shadowColor: "#000", shadowOffset: { width: 8, height: 8, }, shadowOpacity: 0.3, shadowRadius: 10.32, elevation: 4, }, });
describe('bubbleSort', function () { it('should be a function', function () { expect(bubbleSort).to.be.a('function'); }); it('should take a single Array as an argument and sort it to ascending order', function () { var testArr = [5, 1, 4, 2, 8]; var testArr2 = [3, 4, 2, 1, 6]; var testArr3 = [2, 5, 5, 6, 1]; var bs1 = new bubbleSort(testArr); var bs2 = new bubbleSort(testArr2); var bs3 = new bubbleSort(testArr3); expect(bs1.arr).to.deep.equal([1, 2, 4, 5, 8]); expect(bs2.arr).to.deep.equal([1, 2, 3, 4, 6]); expect(bs3.arr).to.deep.equal([1, 2, 5, 5, 6]); }); it('should return the amount of moves', function () { var testArr = [5, 1, 4, 2, 8]; var testArr2 = [3, 4, 2, 1, 6]; var testArr3 = [2, 5, 5, 6, 1]; expect(bubbleSort(testArr)).to.equal(4); expect(bubbleSort(testArr2)).to.equal(5); expect(bubbleSort(testArr3)).to.equal(4); }); describe('bubbleSort', function () { // checks if bubbleSort is a method available to all Arrays it('should be a method available to all Arrays', function () { var checkMethodArr = [1, 2, 3]; expect(checkMethodArr).to.respondTo('bubbleSort'); }); it('should return the sorted array', function () { var testArr = [3, 5, 1]; var testArr2 = [3, 2, 6, 1, 1, 9]; var testArr3 = [9, 7, 3, 0, 5]; expect(testArr.bubbleSort()).to.deep.equal([1, 3, 5]); expect(testArr2.bubbleSort()).to.deep.equal([1, 1, 2, 3, 6, 9]); expect(testArr3.bubbleSort()).to.deep.equal([0, 3, 5, 7, 9]); }); }); });
import React from "react"; import { configure, shallow } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; import App from "./App"; import Basket from "./basket/basket"; configure({ adapter: new Adapter() }); describe("<App /> Component tests", () => { let wrapper; beforeEach(() => { wrapper = shallow(<App />); }); it("should render a div with classname App", () => { expect(wrapper.find("div.App").exists()).toBe(true); }); it("should contain Basket component", () => { expect(wrapper.find(Basket)).toHaveLength(1); }); });
var semver = require('semver') var shell = require('shelljs') /** * Execute a shell command. * * @param {string} command */ function exec (command) { return shell.exec(command, { silent: true }) } var repo = { /** * Check whether a repo exists. * * @return {bool} */ exists: function () { return (exec('git status').code === 0) }, /** * Return the highest tag in the repo. * * @return {string} */ getHighestTag: function () { var highestTag = '0.0.0' var tagsCmd = exec('git tag') if (tagsCmd.code !== 0) { return highestTag } var tags = tagsCmd.stdout.split('\n') tags.forEach(function (tag) { tag = semver.valid(tag) if (tag && (!highestTag || semver.gt(tag, highestTag))) { highestTag = tag } }) return highestTag }, /** * Check if the repo is clean. * * @return {bool} */ isClean: function () { return (exec('git diff-index --quiet HEAD --').code === 0) } } /** * The Grunt wrapper. * * @param {object} grunt */ module.exports = function (grunt) { grunt.registerTask('tag', 'Tag.', function () { var pkg = grunt.config('pkg') var tag = pkg.version // Make sure the tag is a valid semver... if (!semver.valid(tag)) { grunt.warn('"' + tag + '" is not a valid semantic version.') } // Make sure a repository exists... if (!repo.exists()) { grunt.warn('Repository not found.') } // Make sure the tag is greater than the current highest tag... var highestTag = repo.getHighestTag() if (highestTag && !semver.gt(tag, highestTag)) { grunt.warn('"' + tag + '" is lower than or equal to the current highest tag "' + highestTag + '".') } // Commit if need be... if (!repo.isClean()) { exec('git add .') if (exec('git commit -a -m " v' + tag + '"').code === 0) { grunt.log.ok('Committed as: v' + tag) } } // Tag... var tagCmd = exec('git tag v' + tag) if (tagCmd.code !== 0) { grunt.warn('Couldn\'t tag: ', tagCmd.stdout) } grunt.log.ok('Tagged as: v' + tag) }) }
import http from "./httpService"; function getTypes() { return http.get("/types"); } export default { getTypes };
import React, { Component } from "react"; import PropTypes from "prop-types"; import RcSlider from "rc-slider"; import Typography from "components/Typography"; import Diamond from "components/Icons/Diamond"; import sliderSound from "assets/slider-change-sound.mp3"; import loseSound from "assets/lose-sound.mp3"; import winSound from "assets/win-sound.mp3"; import Sound from "react-sound"; import styled, { keyframes } from "styled-components"; import "./index.css"; const { Handle } = RcSlider; const diamondwidth = 72; export default class Slider extends Component { static propTypes = { value: PropTypes.number, roll: PropTypes.oneOf(["under", "over"]), onChange: PropTypes.func, result: PropTypes.number, disableControls: PropTypes.bool, onResultAnimation: PropTypes.func.isRequired, isBetDetails: PropTypes.bool }; static defaultProps = { value: 0, roll: "over", onChange: null, result: null, disableControls: false, isBetDetails: false }; constructor(props) { super(props); this.state = { value: props.value, result: null, leftP: 0, bet : {}, oldLeftP: 0, moving: false }; } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.value !== prevState.value) { return { value: nextProps.value }; } if (nextProps.result !== prevState.result) { let leftP = (prevState.container.clientWidth * nextProps.result) / 100; leftP -= diamondwidth * 0.5; let oldLeftP = (prevState.container.clientWidth * prevState.result) / 100; oldLeftP -= diamondwidth * 0.5; if (!nextProps.animating && (nextProps.bet.nonce != prevState.bet.nonce)) { return { result: nextProps.result, bet : nextProps.bet, leftP, oldLeftP }; }else{ return { result: nextProps.result, leftP } } } return { result: null, leftP: 0 }; } handleSlide = props => { const { value, ...restProps } = props; return <Handle value={value} {...restProps} />; }; handleChange = type => value => { const { onChange } = this.props; this.setState({ value, moving: type === "slider", result: null }); if (onChange) onChange(value); }; handleAfterChange = () => { this.setState({ moving: false }); }; handleRef = element => { const { container } = this.state; if (!container) { this.setState({ container: element }); } }; renderResult = () => { const { roll } = this.props; const { result, value, leftP, oldLeftP, moving } = this.state; if (!result || moving) return null; const slide = keyframes` 10% { left: ${oldLeftP}px; z-index: -1; opacity: 1; transform: scale(0.5); } 15% { left: ${leftP}px; z-index: 2; opacity: 1; transform: scale(1); } 97% { left: ${leftP}px; z-index: 2; opacity: 1; transform: scale(1); } 100% { left: ${leftP}px; z-index: -1; opacity: 1; transform: scale(0.5); }`; const Show = styled.div` position: absolute; top: ${-diamondwidth}px; left: 0; z-index: -1; width: ${diamondwidth}px; transform: scale(0.1); animation: ${slide} 2s linear; `; return ( <Show id="animation-div" onAnimationEnd={this.handleAnimation}> {this.renderResultSound()} <Diamond value={value} result={result} roll={roll} /> </Show> ); }; renderBetDetailsResult = () => { const { roll } = this.props; const { result, value, leftP, moving } = this.state; if (!result || moving) return null; const Show = styled.div` position: absolute; top: ${-diamondwidth}px; left: ${leftP}px; z-index: 1; width: ${diamondwidth}px; transform: scale(0.8); `; return ( <Show id="animation-div"> <Diamond value={value} result={result} roll={roll} /> </Show> ); }; handleAnimation = () => { const { onResultAnimation } = this.props; onResultAnimation(); }; renderResultSound = () => { const { roll } = this.props; const { result, value } = this.state; const sound = localStorage.getItem("sound"); if (sound !== "on") { return null; } return ( <Sound volume={100} url={ (result >= value && roll === "over") || (result < value && roll === "under") ? winSound : loseSound } playStatus="PLAYING" autoLoad /> ); }; renderSliderSound = () => { const sound = localStorage.getItem("sound"); const { moving } = this.state; if (sound !== "on") { return null; } return ( <Sound volume={100} url={sliderSound} playStatus={moving ? "PLAYING" : "STOPPED"} autoLoad playbackRate={1} /> ); }; render() { const { roll, disableControls, isBetDetails } = this.props; const { value } = this.state; return ( <div styleName="root"> {this.renderSliderSound()} <div styleName="container"> <div styleName="slider-container" ref={this.handleRef}> {isBetDetails === true ? this.renderBetDetailsResult() : this.renderResult()} <div styleName="marker-0"> <Typography weight="bold" variant="small-body" color="white"> 0 </Typography> <div styleName="triangle" /> </div> <div styleName="marker-25"> <Typography weight="bold" variant="small-body" color="white"> 25 </Typography> <div styleName="triangle" /> </div> <div styleName="marker-50"> <Typography weight="bold" variant="small-body" color="white"> 50 </Typography> <div styleName="triangle" /> </div> <div styleName="marker-75"> <Typography weight="bold" variant="small-body" color="white"> 75 </Typography> <div styleName="triangle" /> </div> <div styleName="marker-100"> <Typography weight="bold" variant="small-body" color="white"> 100 </Typography> <div styleName="triangle" /> </div> <div> <RcSlider className={roll === "under" ? "under" : null} min={2} max={98} value={value} step={1} handle={this.handleSlide} onChange={this.handleChange("slider")} onAfterChange={this.handleAfterChange} disabled={!!disableControls} /> </div> </div> </div> </div> ); } }
import styled from "styled-components"; import Ticker from "react-ticker"; import StyledImageComponent from "../../utility/ImageComponent"; const BannerContainer = styled("div")` width: 100vw; margin-top: 5rem; `; const ImageContainer = styled.div` display: flex; justify-content: center; `; const images = [ { name: "HTML", category: "Frontend", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774194/Public/Stack/HTML_gqml0l.svg", }, { name: "CSS", category: "Frontend", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774194/Public/Stack/CSS_d0peii.svg", }, { name: "Javascript", category: "Frontend", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774194/Public/Stack/Javascript_zmniqy.svg", }, { name: "React", category: "Frontend", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774197/Public/Stack/React_gqppbn.svg", }, { name: "Nextjs", category: "Frontend", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774197/Public/Stack/Nextjs_ivyuye.svg", }, { name: "Nodejs", category: "Backend", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774197/Public/Stack/Nodejs_pklusa.svg", }, { name: "Firebase", category: "Database", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774194/Public/Stack/Firebase_lcs0da.svg", }, { name: "Mongodb", category: "Database", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774196/Public/Stack/Mongodb_hx9qnm.svg", }, { name: "Mysql", category: "Database", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774197/Public/Stack/Mysql_k9qhuf.svg", }, { name: "Figma", category: "Design", url: "https://res.cloudinary.com/djiqhmzqs/image/upload/v1616774194/Public/Stack/Figma_xzsaxj.svg", }, ]; const Banner = () => { return ( <BannerContainer> <Ticker speed={12}> {() => ( <ImageContainer> {images.map((img) => { return ( <StyledImageComponent key={img.name} width={120} height={120} src={`${img.url}`} margin="0 3rem" /> ); })} </ImageContainer> )} </Ticker> </BannerContainer> ); }; export default Banner;
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import Spinner from 'Components/Spinner'; import ShoppingBagHeader from './ShoppingBagHeader'; // Dynamically load ShoppingBagBody component and name it 'ShoppingBagBody' for webpackChunkName. For more info: https://webpack.js.org/guides/code-splitting/#dynamic-imports const ShoppingBagBody = React.lazy(() => import(/* webpackChunkName: 'ShoppingBagBody' */ './ShoppingBagBody')); function ShoppingBag(props) { // Use useState to track variable that is used to open/close shopping bag const [showBag, setShowBag] = useState(false); // Show shopping bag function handleClick() { setShowBag(true); } // Reset state function handleCloseClick() { setShowBag(false); } return ( <React.Fragment> <ShoppingBagHeader hasItems={props.myItems.length} onClick={handleClick} /> { showBag && ( <React.Suspense fallback={<Spinner />}> <ShoppingBagBody {...props} onCloseClick={handleCloseClick} /> </React.Suspense> ) } </React.Fragment> ); } ShoppingBag.propTypes = { myItems: PropTypes.arrayOf(PropTypes.shape({ sku: PropTypes.string.isRequired, name: PropTypes.string.isRequired, price: PropTypes.node.isRequired, qty: PropTypes.node.isRequired, img: PropTypes.string.isRequired, }).isRequired).isRequired, }; export default ShoppingBag;
"use strict"; // Controller function Assets(app, req, res) { // HTTP action this.action = (params) => { // Send file app.sendFile(res, app.getConfig().files.assets_path + params[0]); }; }; module.exports = Assets;
MyApp.service('Config', function() { /* Macro Definition */ this.APIBASE_URL = 'https://api.bounceequestrian.com/'; });
$(document).ready(function() { $('.list-group-items').click(function() { $(this).find('span', function(span) { var num = Number($(this).html()); num--; if (num <= 0) { num = ''; } $(this).html = num; }) }); });
(function () { 'use strict'; APP.NoteModel = Backbone.Model.extend({ // Defaults defaults: { title: '', description: '', author: '', id: _.random(0, 10000) }, validate: function (attributes) { var errors = {}; if (!attributes.title) { errors.title = 'Please give this note a title.'; } if (!attributes.description) { errors.description = 'Please give this note a description.'; } if (!attributes.author) { errors.author = 'Please give this note an author.'; } if (!_.isEmpty(errors)) { return errors; } } }); APP.NoteCollection = Backbone.Collection.extend({ localStorage: new Backbone.LocalStorage('NoteCollection'), model: APP.NoteModel, }); }());
import { GraphQLList, GraphQLObjectType, GraphQLString, } from 'graphql'; import { fetchPersonByURL } from '../api'; const Person = new GraphQLObjectType({ name: 'Person', description: 'Represent Person', fields: () => ({ id: {type: GraphQLString}, firstName: { type: GraphQLString, resolve: person => person.first_name, }, lastName: { type: GraphQLString, resolve: person => person.last_name, }, email: {type: GraphQLString}, username: {type: GraphQLString}, friends: { type: new GraphQLList(Person), resolve: (person, args, loaders) => { return loaders.person.loadMany(person.friends) } } }), }); export default Person;
//var scriptControllerGUI : ControllerGUI ; var scriptControllerGUI : MonoBehaviour; var functionTouchDown : String = null; var functionTouchedDownAndContinue : String = null; var functionTouchUpInside : String = null; var functionTouchUpOutside : String = null; private var imageNormal : Texture; var imageOver : Texture; var isOverImage : boolean = false; private var lastFingerId : int = -1; private var guiTextureCurrent : GUITexture; function Start(){ guiTextureCurrent = this.GetComponent.<GUITexture>(); imageNormal = guiTextureCurrent.texture; } function OnGUI () { TouchControl(); } function Reset() { //nothing is touched lastFingerId = -1; if(imageNormal){ //Change back to normal image if there is already over image! this.GetComponent.<GUITexture>().texture = imageNormal; //normal image isOverImage = false; } } private var touch : Touch; private var touchPositionFinger : Vector2; private var isHitOnGui : boolean; private var hasTouchOnGui: boolean; private var isResetPreviously : boolean = true; //initially, system has already reset. function TouchControl(){ var touchCount : int = Input.touchCount; if ( touchCount > 0 ){ isResetPreviously = false; hasTouchOnGui = false; for(var touchIndex:int = 0; touchIndex < touchCount; touchIndex++){ touch = Input.GetTouch(touchIndex); touchPositionFinger = touch.position; isHitOnGui = guiTextureCurrent.HitTest(touchPositionFinger); if( isHitOnGui && touch.phase == TouchPhase.Began && ( lastFingerId == -1 ) ){ //Started Touch lastFingerId = touch.fingerId; hasTouchOnGui = true; if(functionTouchDown){ scriptControllerGUI.SendMessage(functionTouchDown); } if(imageOver){ //over image this.GetComponent.<GUITexture>().texture = imageOver; //over image isOverImage = true; } } else if ( isHitOnGui && (touch.phase == TouchPhase.Began ||touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) && ( lastFingerId == touch.fingerId ) ){ //Touched Previously and still inside the button hasTouchOnGui = true; if(functionTouchedDownAndContinue){ scriptControllerGUI.SendMessage(functionTouchedDownAndContinue); } } else if ( !isHitOnGui && (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) && ( lastFingerId == touch.fingerId ) ){ //Touched Previously and now touch is outside the button Reset(); isResetPreviously = true; if(functionTouchUpOutside){ scriptControllerGUI.SendMessage(functionTouchUpOutside); } /* If you would like to use button after going outside, uncomment this part and delete other statements in this scope if(isOverImage && imageNormal){ // did not change over image to normal this.guiTexture.texture = imageNormal; //normal image isOverImage = false; } else{ // changed before the over image to normal - do nothing // do nothing } */ } else if ( isHitOnGui && (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) && ( lastFingerId == touch.fingerId ) ){ //Touch Up Inside Reset(); isResetPreviously = true; if(functionTouchUpInside){ scriptControllerGUI.SendMessage(functionTouchUpInside); } } else if ( !isHitOnGui && (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) && ( lastFingerId == touch.fingerId ) ){ //Touch Up Outside Reset(); isResetPreviously = true; if(functionTouchUpOutside){ scriptControllerGUI.SendMessage(functionTouchUpOutside); } } else{ // There is a touch but not on that button or Gui element } } if(!hasTouchOnGui && !isResetPreviously){ // If there isn't touch or there was touch but not with given fingerid then we release the touched button Reset(); isResetPreviously = true; } else{ //There is touch on this button //do nothing } } else if(!isResetPreviously) //There is no touch, so we reset the button config (for performence optimization it is done once for each touch by flag isResetPreviously) { Reset(); isResetPreviously = true; } else{ //do nothing -> Already Reset } }
const CONFIG = { AppFilesPath: './app/**/*.js', BuildDestination: './dist/', BuildOrder: [ // Father object './core/MVCLite.js', // Framework Utilities './utilities/Http.js', // Base Objects './core/MVCLiteObject.js', './core/DynamicNode.js', // Core Entities './core/Template.js', './core/Component.js' ] }; module.exports = CONFIG;
var builder = require('botbuilder'); var customVision = require('./CustomVision'); var musicAlbum = require('./MusicAlbumCard'); var musicTrack = require('./MusicTrackCard'); var musicArtist = require('./MusicArtistCard'); var movieTitleCard = require('./MovieTitleCard'); var movie = require('./FavouriteMovie'); var music = require('./FavouriteMusic'); exports.startDialog = function (bot) { // Replace {YOUR_APP_ID_HERE} and {YOUR_KEY_HERE} with your LUIS app ID and your LUIS key, respectively. var recognizer = new builder.LuisRecognizer('https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/c69d2f3f-fdbd-48aa-bb64-9cd95d509db5?subscription-key=5bde11256c654a1a9ba596c41916094f&verbose=true&timezoneOffset=0&q='); bot.recognizer(recognizer); bot.dialog('ShowOptions', function (session) { var msg = new builder.Message(session); msg.attachmentLayout(builder.AttachmentLayout.carousel) msg.attachments([ new builder.HeroCard(session) .title("Please, choose an option to enjoy our services.") .subtitle("You may either click an option or type an option.") .images([builder.CardImage.create(session, 'http://armdj.com/wp-content/uploads/2015/01/TMMN__HD_ROKU_APP_LOGO.jpg')]) .buttons([ builder.CardAction.imBack(session, "Movie", "Movie"), builder.CardAction.imBack(session, "Music", "Music"), builder.CardAction.imBack(session, "Favourite", "Favourite") ]) ]); session.send(msg).endDialog(); }).triggerAction({ matches: 'ShowOptions' }); bot.dialog('Favourite', function (session) { var msg = new builder.Message(session); msg.attachmentLayout(builder.AttachmentLayout.carousel) msg.attachments([ new builder.HeroCard(session) .title("Please, choose an option to setup your favourite movie or music.") .subtitle("You may either click an option or type an option.") .images([builder.CardImage.create(session, 'http://armdj.com/wp-content/uploads/2015/01/TMMN__HD_ROKU_APP_LOGO.jpg')]) .buttons([ builder.CardAction.imBack(session, "Favourite Music", "Favourite Music") ]) ]); session.send(msg).endDialog(); }).triggerAction({ matches: 'Favourite' }); bot.dialog('FavouriteMusic', function (session) { var msg = new builder.Message(session); msg.attachmentLayout(builder.AttachmentLayout.carousel) msg.attachments([ new builder.HeroCard(session) .title("Please, choose an option to view, add or delete your favourite music.") .subtitle("You may either click an option or type an option.") .images([builder.CardImage.create(session, 'http://armdj.com/wp-content/uploads/2015/01/TMMN__HD_ROKU_APP_LOGO.jpg')]) .buttons([ builder.CardAction.imBack(session, "View My Favourite Music", "View My Favourite Music"), builder.CardAction.imBack(session, "Add My Favourite Music", "Add My Favourite Music"), builder.CardAction.imBack(session, "Delete My Favourite Music", "Delete My Favourite Music") ]) ]); session.send(msg).endDialog(); }).triggerAction({ matches: 'FavouriteMusic' }); bot.dialog('GetFavouriteMusic', [ function (session, args, next) { session.dialogData.args = args || {}; if (!session.conversationData["username"]) { builder.Prompts.text(session, "Enter a username to setup your account."); } else { next(); // Skip if we already have this info. } }, function (session, results, next) { if (results.response) { session.conversationData["username"] = results.response; } session.send("Retrieving your favourite music"); music.displayFavouriteMusic(session, session.conversationData["username"]); // <---- THIS LINE HERE IS WHAT WE NEED } ]).triggerAction({ matches: 'GetFavouriteMusic' }); bot.dialog('AddFavouriteMusic', [ function (session, next) { if (!session.dialogData["username"]) { builder.Prompts.text(session, "Enter a username to setup your account."); } else { next(); // Skip if we already have this info. } }, function(session, results, next) { if (results.response) { session.dialogData["username"] = results.response; } if (!session.dialogData["musicName"]) { builder.Prompts.text(session, "Enter a track name to setup your favourite music."); } else { next(); } }, function(session, results, next) { if (results.response) { session.dialogData["musicName"] = results.response; } if (session.dialogData["musicName"]) { session.send('Thanks for telling me that \'%s\' is your favourite music', session.dialogData["musicName"]); music.sendFavouriteMusic(session, session.dialogData["username"], session.dialogData["musicName"]); } } ]).triggerAction({ matches: 'AddFavouriteMusic' }); bot.dialog('DeleteFavouriteMusic', [ function (session, next) { if (!session.dialogData["username"]) { builder.Prompts.text(session, "Enter a username to setup your account."); } else { next(); // Skip if we already have this info. } }, function(session, results, next) { if (results.response) { session.dialogData["username"] = results.response; } if (!session.dialogData["musicName"]) { builder.Prompts.text(session, "Enter a track name to delete from your favourite music list."); } else { next(); } }, function(session, results, next) { if (results.response) { session.dialogData["musicName"] = results.response; } if (session.dialogData["musicName"]) { session.send('Deleting \'%s\'...', session.dialogData["musicName"]); music.deleteFavouriteMusic(session, session.dialogData["username"], session.dialogData["musicName"]); } } ]).triggerAction({ matches: 'DeleteFavouriteMusic' }); bot.dialog('FindMovie', function (session) { var msg = new builder.Message(session); msg.attachmentLayout(builder.AttachmentLayout.carousel) msg.attachments([ new builder.HeroCard(session) .title("Please, choose an option to search a movie.") .subtitle("You may either click an option or type an option.") .images([builder.CardImage.create(session, 'http://armdj.com/wp-content/uploads/2015/01/TMMN__HD_ROKU_APP_LOGO.jpg')]) .buttons([ builder.CardAction.imBack(session, "Movie Poster", "Movie Poster"), builder.CardAction.imBack(session, "Movie Title", "Movie Title") ]) ]); session.send(msg).endDialog(); }).triggerAction({ matches: 'FindMovie' }); bot.dialog('FindMoviePoster', [ function(session) { var msg = new builder.Message(session); msg.attachmentLayout(builder.AttachmentLayout.carousel) msg.attachments([ new builder.HeroCard(session) .title("Please, type a movie poster's url.") .subtitle("You may click button below to find a url for a movie poster you want to search") .buttons([ builder.CardAction.openUrl(session, "https://images.google.com", "Search poster's url") ]) ]); session.send(msg); builder.Prompts.text(session, "E.G. http://www.impawards.com/2008/posters/dark_knight.jpg") }, function(session, results) { if(results.response.includes('http')) { customVision.retreiveMessage(session); return true; } else { session.replaceDialog('FindMoviePoster'); } } ]).triggerAction({ matches: 'FindMoviePoster' }); bot.dialog('FindMovieTitle', [ function (session) { session.send("Here, you can search a movie by providing a movie title.") builder.Prompts.text(session, "Please provide a movie title.") }, function(session, results) { session.dialogData.movieTitle = results.response; movieTitleCard.displayMovieCards(session); } ]).triggerAction({ matches: 'FindMovieTitle' }); bot.dialog('FindMusic', function (session) { var msg = new builder.Message(session); msg.attachmentLayout(builder.AttachmentLayout.carousel) msg.attachments([ new builder.HeroCard(session) .title("Please, choose an option.") .subtitle("You may either click an option or type an option.") .images([builder.CardImage.create(session, 'http://armdj.com/wp-content/uploads/2015/01/TMMN__HD_ROKU_APP_LOGO.jpg')]) .buttons([ builder.CardAction.imBack(session, "Album", "Album"), builder.CardAction.imBack(session, "Artist", "Artist"), builder.CardAction.imBack(session, "Track", "Track") ]) ]); session.send(msg).endDialog(); }).triggerAction({ matches: 'FindMusic' }); bot.dialog('FindAlbum', [ function (session) { session.send("Here, you can get detailed information about the album.") builder.Prompts.text(session, "Please provide an album name.") }, function(session, results) { session.dialogData.albumName = results.response; builder.Prompts.text(session, "What is the artist name?"); }, function(session, results) { session.dialogData.artistName = results.response; musicAlbum.displayMusicAlbumCards(session); } ]).triggerAction({ matches: 'FindAlbum' }); bot.dialog('FindArtist', [ function (session) { session.send("Here, you can get detailed information about the artist.") builder.Prompts.text(session, "Please provide an artist name.") }, function(session, results) { session.dialogData.artistName = results.response; musicArtist.displayMusicArtistCards(session); } ]).triggerAction({ matches: 'FindArtist' }); bot.dialog('FindTrack', [ function (session) { session.send("Here, you can get detailed information about the track.") builder.Prompts.text(session, "Please provide a track name.") }, function(session, results) { session.dialogData.trackName = results.response; builder.Prompts.text(session, "What is the artist name?"); }, function(session, results) { session.dialogData.artistName = results.response; musicTrack.displayMusicTrackCards(session); } ]).triggerAction({ matches: 'FindTrack' }); bot.dialog('GetFavouriteMovie', [ function (session, args, next) { session.dialogData.args = args || {}; if (!session.conversationData["username"]) { builder.Prompts.text(session, "Enter a username to setup your account."); } else { next(); // Skip if we already have this info. } }, function (session, results, next) { if (results.response) { session.conversationData["username"] = results.response; } session.send("Retrieving your favourite movies"); movie.displayFavouriteMovie(session, session.conversationData["username"]); // <---- THIS LINE HERE IS WHAT WE NEED } ]).triggerAction({ matches: 'GetFavouriteMovie' }); bot.dialog('AddFavouriteMovie', [ function (session, args, next) { session.dialogData.args = args || {}; if (!session.conversationData["username"]) { builder.Prompts.text(session, "Enter a username to setup your account."); } else { next(); // Skip if we already have this info. } }, function (session, results, next) { if (results.response) { session.conversationData["username"] = results.response; } // Pulls out the food entity from the session if it exists var movieEntity = builder.EntityRecognizer.findEntity(session.dialogData.args.intent.entities, 'movie'); // Checks if the food entity was found if (movieEntity) { session.send('Thanks for telling me that \'%s\' is your favourite movie', movieEntity.entity); movie.sendFavouriteMovie(session, session.conversationData["username"], movieEntity.entity); // <-- LINE WE WANT } else { session.send("No movie identified!!!"); } } ]).triggerAction({ matches: 'AddFavouriteMovie' }); }
$(document).ready(function() { var rounds = 1; var ties = 0; var userScore = 0; var computerScore = 0; var computerChoice = "The computer has not decided yet."; var userChoice; $("#game-running p").html("Game is off. Click on red button to turn the game on."); // $(".image").on("click", function(){ // $(".image").off("click"); $("#toggleBtn").on("click", function() { if($(this).attr("data-status") === "on") { $('.image').removeClass("hidden"); // $('.image').addClass("slideUp"); // setTimeout(function() { // $('.image').removeClass('slideUp'); // }, 20000); $("#game-running p").html("GAME IS ON"); $(this) .html("ON")//GREEN the text in the parentheses //after .html refers to the text in the button itself .addClass("btn-success") .removeClass("btn-danger") .attr("data-status", "off"); } else { // $(".image").click(function(){ // $.unbind(); $('.image').addClass("hidden"); $("#game-running p").html("Game is off"); $(this) .html("OFF")//RED .addClass("btn-danger") .removeClass("btn-success") .attr("data-status", "on") .removeClass("bigEntrance"); $('#rounds').html("Round number: " + rounds); $('#ties').html("Ties: " + ties); $('#userScore').html("Your score: " + userScore); $('#computerScore').html("Computer score: " +computerScore); $('#computerChoice').html("Computer choice: " + computerChoice); window.location.reload(); // $(".image").on("click", function(){ // $(".image").off("click"); } }); }); // $(".image").on("click", function(){ // $ (".image").off("click"); // }); // } // }); // }); // $("img").removeClass("hidden"); // $("#game-running p").html("GAME IS ON"); // $(this) // .html("GREEN")//the text in the parentheses // //after .html refers to the text in the button itself // .addClass("btn-success") // .removeClass("btn-danger") // .attr("data-status", "off"); // // $(".btn-warning").off(); // } else { // // $(".image").click(function(){ // // $.unbind(); // $("#game-running p").html("Game is off"); // $(this) // .html("RED") // .addClass("btn-danger") // .removeClass("btn-success") // .attr("data-status", "on") // .removeClass("bigEntrance"); // // $(".image").on("click", function(){ // // $(".image").off("click"); // } // // $('.image').off("click"); // // bindControls(); // // enableAnimation(); // }); // function bindControls() { // $(".btn-warning").on("click", function() { // alert("I AM HERE"); // }); // } // function enableAnimation() { // $(".btn-warning").on("mouseenter", function() { // $(this).toggleClass("slideLeft"); // }).on("mouseleave", function() { // $(this).toggleClass("slideRight"); // }); // } // bindControls(); // enableAnimation(); //});
/// <reference types="Cypress" /> const incometab = ".sidebar-menu > :nth-child(4)" const addincome = "#sibe-box > ul.sidebar-menu.verttop > li.treeview.active > ul > li:nth-child(1) > a" const head = "#inc_head_id" const name = "#name" const invoiceno = "#invoice_no" const date = "#date" const amount = "#amount" const desc = "#description" const file = "#documents" const image = "goku.png" const searchincome = "#sibe-box > ul.sidebar-menu.verttop > li.treeview.active > ul > li:nth-child(2) > a" const searchtype = "#search_type" const search = "#search_text" const searchbutton = "#form1 > div > div:nth-child(1) > div > div.col-sm-12 > div > button" const searchbutton1 = "#form1 > div > div:nth-child(2) > div > div:nth-child(3) > div > button" const savebutton = "#form1 > div.box-footer > button" const savebutton1 = ".box-footer > .btn" const headtab = "#sibe-box > ul.sidebar-menu.verttop > li.treeview.active > ul > li:nth-child(3) > a" const headname = "#incomehead" const idata = require("../../../fixtures/income.json") export class income { incomepage() { cy.get(incometab).click() } addincome() { cy.get(addincome).click() cy.wait(1000) cy.viewport(1200, 600) cy.get(head).select(idata.haed) cy.get(name).type(idata.name) cy.get(invoiceno).type(idata.invoice) cy.get(date).click() cy.get('.datepicker-days > .table > tbody > :nth-child(3) > :nth-child(4)').click() cy.get(amount).type(idata.amount) cy.get(file).attachFile(image) cy.get(desc).type(idata.desc) cy.get(savebutton).click() } searchincome() { cy.get(searchincome).click() if (cy.get(searchtype).select("Last Week")) { cy.get(searchbutton).click() } else (cy.get(search).type(idata.name)) { cy.get(searchbutton1).click() } } incomehead() { cy.get(headtab).click() cy.get(headname).type(idata.head1) cy.get(desc).type(idata.desc) cy.get(savebutton1).click() } deleteincome() { cy.get(addincome).click() cy.viewport(1200, 600) cy.contains('td', idata.name).siblings().find('a').eq(2).click() } }
import React from 'react'; import Particle from 'react-tsparticles' import { optionsParticles } from '../utility'; function HomePage() { //SECURITY CONCERN #1 = ONLY SEND THE INFO NEEDED FOR RELEVANT DISPLAY IE DO NOT SEND EVERYTHING TO DASHBOARD //GENERATE TEST USERS return ( <div className="App"> <div className="tsparticles"> <Particle height="100vh" width="100vw" options={optionsParticles} /> </div> <header className="header"> <img src="/brain.png" alt="logo" /> <h1 className="fade-in">JMSA Tutoring Services</h1> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > </a> </header> <section className="home-blurb"> <h2>About Us</h2> <p> Welcome JMSA students. Having trouble in classes? Need some help? There's no one better to reach out to than someone who's already gone through it all. Use the JMSA tutoring site as a one-stop shop to set up dates, times, organize community service hours, and find tutees and tutors. </p> <h2>FAQ</h2> <p> <div> <p>Q: Can I delete my account?</p> <p>A: Yes, please head to profile, then edit user. You will be able to delete your account there.</p> </div> <div> <p>Q: Help! Something broke!</p> <p>A: This site is in active beta, please email me at sotoemily03@gmail.com so that I can get on fixing it ASAP.</p> </div> <div> <p>Q: What if omeone's behaving inappropriately? </p> <p>A: Please give us their username/email or name and we'll swiftly take care of the issue.</p> </div> <div> <p>Q: What do you do with my data?</p> <p>A: The purpose of all data collected is only to connect you with other students. We will NOT use this data in any other way, unless we need to get in contact with you.</p> </div> <div> <p>Q: I saw something I'm not supposed to see...</p> <p>A: I'll buy you a cookie if you tell me about any security vulnerabilities.</p> </div> <div> <p>Q: Will this work on my phone?</p> <p>A: This *should* work just fine on your phone. If you experience any glitches, again, please get in touch.</p> </div> </p> </section> </div> ); } export default HomePage;
const Discord = require("discord.js"); exports.name = "ban"; exports.guildonly = true; exports.run = async (robot, mess, args)=>{ try{ var embed4 = new Discord.MessageEmbed({title: 'Ошибка!', description: 'Эта команда недоступна в лс!'}).setThumbnail('https://cdn.discordapp.com/emojis/863804794170245121.gif?v=1').setColor("DARK_RED") if(!mess.guild) return mess.reply({ embeds: [embed4] }); args = mess.content.split(` `); args.shift(); args = args.join(` `); var reason = args.split(' ').slice(1).join(" ") if(!reason) reason = "none"; var embed = new Discord.MessageEmbed({title: 'Модерация⚖', description: 'У меня недостаточно прав на выполнение этой команды!'}).setColor("DARK_RED") var embed1 = new Discord.MessageEmbed({title: 'Модерация⚖', description: 'У вас недостаточно прав на выполнение этой команды!'}).setColor("DARK_RED") var embed3 = new Discord.MessageEmbed({title: 'Модерация⚖', description: `У меня недостаточно прав!`}).setColor("RED") if (!mess.channel.permissionsFor(mess.guild.me).has(Discord.Permissions.FLAGS.BAN_MEMBERS) && !mess.channel.permissionsFor(mess.guild.me).has(Discord.Permissions.FLAGS.BAN_MEMBERS)) return mess.channel.send({ embeds: [embed] }); if (!mess.channel.permissionsFor(mess.member).has(Discord.Permissions.FLAGS.BAN_MEMBERS) && !mess.channel.permissionsFor(mess.member).has(Discord.Permissions.FLAGS.BAN_MEMBERS)) return mess.channel.send({ embeds: [embed1] }); const user = mess.mentions.users.first(); // If we have a user mentioned if (user) { // Now we get the member from the user const member = mess.guild.members.cache.get(user.id); // If the member is in the guild if (member) { /** * Ban the member * Make sure you run this on a member, not a user! * There are big differences between a user and a member * Read more about what ban options there are over at * https://discord.js.org/#/docs/main/master/class/GuildMember?scrollTo=ban */ member .ban({ reason: `${reason}`, }) .then(() => { // We let the message author know we were able to ban the person var embed2 =new Discord.MessageEmbed() .setColor('DARK_RED') .setTitle('Модерация⚖') .setDescription(`***<@${user.id}>*** успешно забанен!`) .addFields( { name: '\u200B', value: '\u200B' }, { name: 'Причина:', value: `${reason}` , inline: true }, ) .setTimestamp() .setFooter(mess.author.tag, mess.author.displayAvatarURL()) mess.channel.send({ embeds: [embed2] }); }) .catch(err => { // An error happened // This is generally due to the bot not being able to ban the member, // either due to missing permissions or role hierarchy mess.reply({ embeds: [embed3] }); // Log the error console.error(err); }); } else { var embed5 = new Discord.MessageEmbed({title: 'Модерация⚖', description: `Этот человек не с этого сервера!`}).setColor("RED") // The mentioned user isn't in this guild mess.reply({ embeds: [embed5] }); } } else { // Otherwise, if no user was mentioned var embed6 = new Discord.MessageEmbed({title: 'Модерация⚖', description: `Вы не указали кого забанить!`}).setColor("RED") mess.reply({ embeds: [embed6] }); }} catch(err){mess.reply({ content: `\`\`\`js\n${err.toString("")}\`\`\``, allowedMentions: { repliedUser: true }})} }
var texts = `/* * 大家好,我是王伟超。 * 这是我的简历。 * 来点代码来渲染气氛吧。 * 让我们嗨起来~~~ */ /* 看我变个身 */ html { color:rgb(222,222,222); background:rgb(90, 99, 68); } /* 先加个过渡吧!免得晃瞎眼~~~ */ * { transition:all 1s; } /* 再加个框框,免得跑偏 */ .tag { margin:20px; width:600px; overflow: auto; height:666px; border:2px solid #f082; border-radius:5px; padding:30px; font-size:20px; background: #f082; } /* 好吧,进入正题吧。让这个框框滚一边去 */ .tag { position: fixed; right: 0; } `; var writeCode = function(prefix, texts, fn) { var n = 0; let tag = document.querySelector(".tag"); var id = setInterval(function() { tag.innerHTML = Prism.highlight(prefix + texts.substring(0, n), Prism.languages.css, 'css'); styles.innerHTML = prefix + texts.substring(0, n); tag.scrollTop = tag.scrollHeight; if(n >= texts.length) { clearInterval(id); fn(); } n += 1; }, 10) } var info_css = ` /* 现在需要另外一个框框来显示我的信息了 */ .info { padding:20px; position: fixed; left: 0; margin:20px; width:50%; height:666px; border:3px solid #fff; border-radius:5px; overflow:auto; } /* 加点样式美化一下 */ .info { transform: rotateY(360deg); font-family: 幼圆; } .info p{ padding-left:20px; } .info img { position: fixed; right: 5%; top: 5%; border-radius: 10px; } /* ~~~出来吧!光能使者~~~ */ `; var md = `## 自我介绍 ## 我叫王伟超 92 年 10月 出生 自学前端半年 ![Alt](https://avatar.csdn.net/7/7/B/1_ralf_hx163com.jpg) ## 技能 ## 熟练使用JavaScript、CSS、HTML 熟练使用PHP,有项目经验 ## 项目经验 ## 暂无 ## 联系方式 ## QQ:447154678 电话:1891108 `; writeCode('', texts, function() { createPro(() => { writeCode(texts, info_css, function() { markdow(md, () => {}); }); }); }) function createPro(fn) { var n = 0; let creat_tag = document.createElement('pre'); creat_tag.className = 'info'; document.body.appendChild(creat_tag); fn.call(); } function markdow(markdow, fn) { let info = document.querySelector(".info"); var n = 0; var id = setInterval(function() { info.innerHTML = marked(markdow.substring(0, n)); info.scrollTop = info.scrollHeight; if(n >= markdow.length) { clearInterval(id); fn(); } n += 1; }, 10) }
export const product = { COMMON: 'common', WITH_DESCRIPTION: 'with_description', };
'use strict'; /** * @ngdoc directive * @name seedApp.directive:uploader * @description * # uploader */ angular.module('seedApp') .directive('uploader', ['', function () { return { templateUrl: 'views/uploader.dir.html', scope: { ids: '=', }, restrict: 'E', compile: function(){ return{ pre: function(scope){ // // // scope.uploader = new FileUploader({ // url: 'https://media.leadinglocally.com/api/upload/image/'+scope.id, // // headers: APIService.tokenHeaders().headers // }); }, post: function(scope){ // angular file uploader // console.log( "uploader: ", scope.uploader ); // angular file upload CALLBACKS // // scope.uploader.onWhenAddingFileFailed = function(item #<{(|{File|FileLikeObject}|)}>#, filter, options) { // // console.info('onWhenAddingFileFailed', item, filter, options); // }; // scope.uploader.onAfterAddingFile = function(fileItem) { // // console.info('onAfterAddingFile', fileItem); // }; // scope.uploader.onAfterAddingAll = function(addedFileItems) { // // console.info('onAfterAddingAll', addedFileItems); // }; // scope.uploader.onBeforeUploadItem = function(item) { // // console.info('onBeforeUploadItem', item); // }; // scope.uploader.onProgressItem = function(fileItem, progress) { // // console.info('onProgressItem', fileItem, progress); // }; // scope.uploader.onProgressAll = function(progress) { // // console.info('onProgressAll', progress); // }; // scope.uploader.onSuccessItem = function(fileItem, response, status, headers) { // console.info('onSuccessItem', fileItem, response, status, headers); // //scope.LLToast = (text, position, duration, id, icon, colourClass) // // APIService.LLToast('upload success', 'bottom-left', '1000', 'success-toast', 'done', 'orange'); // window.alert('upload success'); // scope.callback(response); // }; // scope.uploader.onErrorItem = function(fileItem, response, status, headers) { // // console.info('onErrorItem', fileItem, response, status, headers); // }; // scope.uploader.onCancelItem = function(fileItem, response, status, headers) { // // console.info('onCancelItem', fileItem, response, status, headers); // }; // scope.uploader.onCompleteItem = function(fileItem, response, status, headers) { // // console.info('onCompleteItem', fileItem, response, status, headers); // }; // scope.uploader.onCompleteAll = function() { // // console.info('onCompleteAll'); // }; var controller = scope.controller = { isImage: function(item) { var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; } }; } }; }, }; }]);
import config from './config/config'; const history = { action: config.pushName }; export default history;
/** * Station * @flow */ import {handleErrors} from "./utils"; import {REQUEST_STATION, RECEIVE_STATION} from "../constants/ActionTypes"; export function requestStation() { return { type: REQUEST_STATION }; } export function receiveStation(station: Object) { return { type : RECEIVE_STATION, item : station, receivedAt: Date.now() }; } export function fetchStation(stationID: number) { return function (dispatch: Function) { dispatch(requestStation(stationID)); return fetch(`http://localhost:1337/station/${stationID}`, { method: 'GET' }) .then(handleErrors) .then(response => response.json()) .then(station => { dispatch(receiveStation(station)); }) .catch(error => { console.error(error); }); } }
import * as goober from '../index'; describe('goober', () => { it('exports', () => { expect(Object.keys(goober).sort()).toEqual([ 'css', 'extractCss', 'glob', 'keyframes', 'setup', 'styled' ]); }); });
import Highlight from 'vue-highlight-component'; export default { components: {Highlight}, data() { return { rowsPerPage: [50, 100, {text: 'All', value: -1}], headers: [ {text: this.$t('notify.name'), align: 'left', value: 'name'}, {text: this.$t('notify.enabled'), align: 'left', value: 'enabled'}, {text: this.$t('notify.subject'), align: 'left', value: 'subject'}, {text: this.$t('notify.email'), align: 'left', value: 'email'}, {text: this.$t('notify.query'), align: 'left', value: 'query'}, {text: this.$t('notify.last_result'), align: 'left', value: 'last_result'}, {text: this.$t('notify.last_logs'), align: 'left', value: 'last_logs'}, {text: this.$t('notify.actions'), align: 'left', sortable: false}, ], addEditEntryDialog: { open: false, isEditDialog: false }, deleteEntryDialog: { open: false, title: "" }, objectDialog: { data: {}, open: false }, deleteEntry: {}, formValid: false, formEntry: { required: (value) => !!value || this.$t('notify.required'), query: (value) => this.checkValidJson(value) || this.$t('notify.query_not_valid_json') }, selectedEntries: [], editEntry: { id: '', name: '', query: '', subject: '', new_entry: false } } }, computed: { search: { get() { return this.$store.state.notify.search; }, set(value) { this.$store.commit('notify/setSearch', value); } }, pagination: { get() { return this.$store.state.notify.pagination; }, set(value) { this.$store.commit('notify/setPagination', value); } }, entries: { get() { return this.$store.state.notify.entries; }, set(value) { return this.$store.commit('notify/setEntries', value); } } }, methods: { checkValidJson(value) { try { JSON.parse(value); return true; } catch (e) { return false; } }, async openObjectDialog(value) { this.objectDialog.data = value; this.objectDialog.open = true; }, async toggleEnable(enabled) { try { let promises = [], current_entries = []; for (const entry of this.selectedEntries) { let entryCopy = Object.assign({}, entry); entryCopy.enabled = enabled; current_entries.push(entryCopy); promises.push(this.$axios.post('notify/toggleEnable', {name: entry.name, enabled})); } await Promise.all(promises); for (const entry of current_entries) { this.$store.commit('notify/updateEntry', entry); } const text = `${enabled ? this.$t('enabled') : this.$t('disabled') } all selected.`; this.$store.commit('showSnackbar', {type: 'success', text}); } catch (err) { this.$store.dispatch('handleError', err); } }, async openDeleteDialog(entry) { this.deleteEntryDialog.open = true; this.deleteEntryDialog.title = entry.name; Object.assign(this.deleteEntry, entry); }, async deleteEntryConfirm() { try { const deleted = await this.$axios.delete(`notify/${this.deleteEntry.id}`); this.$store.commit('notify/deleteEntry', this.deleteEntry); this.deleteEntryDialog.open = false; this.$store.commit('showSnackbar', {type: 'success', text: this.$t('notify.deleted')}); } catch (err) { this.$store.dispatch('handleError', err); } }, async openAddEditEntryDialog(entry) { this.$refs.addEditEntryForm.reset(); this.$nextTick(() => { if (entry) { Object.assign(this.editEntry, entry); this.editEntry.query = JSON.stringify(this.editEntry.query, null, 4); this.editEntry.new_entry = false; } else { delete this.editEntry.id; this.editEntry.new_entry = true; } delete this.editEntry.created_time; delete this.editEntry.modified_time; this.addEditEntryDialog.isEditDialog = !this.editEntry.new_entry; this.addEditEntryDialog.open = true; }); }, async addEditEntry() { try { this.$refs.addEditEntryForm.validate(); if (!this.formValid) return; this.addEditEntryDialog.open = false; this.editEntry.enabled = !!this.editEntry.enabled; this.editEntry.query = JSON.parse(this.editEntry.query); const input = { name: this.editEntry.name, subject: this.editEntry.subject, email: this.editEntry.email, query: this.editEntry.query }; if (this.editEntry.new_entry === true) { //issue for handling dots in object key names let create_without_query = Object.assign({}, input); delete create_without_query.query; let added = await this.$axios.$post('notify', create_without_query); let patched = await this.$axios.$patch(`notify/${added.id}`, input); this.$store.commit('notify/addEntry', patched); } else { const patched = await this.$axios.$patch(`notify/${this.editEntry.id}`, input); this.$store.commit('notify/updateEntry', patched); } this.$store.commit('showSnackbar', {type: 'success', text: this.$t('notify.saved')}); } catch (err) { this.$store.dispatch('handleError', err); } } }, async asyncData({store, error, app: {$axios, i18n}}) { try { const params = {filter: {}}; let [entries] = await Promise.all([ $axios.$get('notify', {params}) ]); store.commit('notify/setEntries', entries); } catch (err) { if (err.response && err.response.status === 401) { return error({statusCode: 401, message: store.state.unauthorized}); } else { return error({statusCode: err.statusCode, message: err.message}); } } } }
const express = require('express'); const router = express.Router(); const ctrlHome = require('../controllers/home'); const ctrlAdmin = require('../controllers/admin'); const ctrlLogin = require('../controllers/login'); const isAdmin = (req, res, next) => { if (req.session.isAdmin) { return next(); } res.redirect('/'); }; router.get('/', ctrlHome.index); router.post('/', ctrlHome.mail); router.get('/login', ctrlLogin.login); router.post('/login', ctrlLogin.auth); router.get('/admin', isAdmin, ctrlAdmin.admin); router.post('/admin/upload', isAdmin, ctrlAdmin.upload); router.post('/admin/skills', isAdmin, ctrlAdmin.skills); module.exports = router;
import {reactive, readonly} from 'vue' import axios from 'axios' const state = reactive({ tasks: [] }) const methods = { // postTasks(task) { // return apiClient.post('/task',task) // }, // getTasks() { // return apiClient.get('/tasks') // } } export default { state, methods }
var count = 0; function buildHTMLForInput(name, type, id) { return '<tr>' + '<td>'+ id +'</td>' + '<td>' +name +'</td>' + '<td>' + type + '</td>' + '<td>' + '<div class="dropdown">' + '<a href="#" id="drop3" role="button" class="dropdown-toggle pull-right" data-toggle="dropdown">Action<b class="caret"></b></a>' + '<ul id="menu3" class="dropdown-menu" role="menu" aria-labelledby="drop6">' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Modify</a></li>' + '<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Delete</a></li>' + '</ul>' + '</div>'+ '</td>' + '</tr>'; } /** * Adds a new rule from the modal to the rules table */ function addNewInput() { var nameField = $('#add-input-name'); var typeField = $('#add-input-type'); var id = '164BC'+ count; var ruleHTML = buildHTMLForInput(nameField.val(), typeField.val(), id); var inputBody = $('#inputs-body'); inputBody.html(inputBody.html() + ruleHTML); nameField.val(''); count ++; }
const expect = require('expect.js'); const part1 = require('./part1'); const part2 = require('./part2'); describe('Day 03: Part 1', () => { it('Calculates closest intersection from input 1', () => { expect(part1('R75,D30,R83,U83,L12,D49,R71,U7,L72\nU62,R66,U55,R34,D71,R55,D58,R83')).to.equal(159); }); it('Calculates closest intersection from input 2', () => { expect(part1('R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\nU98,R91,D20,R16,D67,R40,U7,R15,U6,R7')).to.equal(135); }); }); describe('Day 03: Part 2', () => { it('Calculates closest intersection by number of steps from input 1', () => { expect(part2('R75,D30,R83,U83,L12,D49,R71,U7,L72\nU62,R66,U55,R34,D71,R55,D58,R83')).to.equal(610); }); it('Calculates closest intersection by number of steps from input 2', () => { expect(part2('R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\nU98,R91,D20,R16,D67,R40,U7,R15,U6,R7')).to.equal(410); }); });
import { createStackNavigator} from 'react-navigation'; import AdvancedPage from './AdvancedPage'; import PortfolioProjectionPage from './PortfolioProjectionPage;' export default createStackNavigator({ Advanced: AdvancedPage, PortfolioProjection: PortfolioProjectionPage, });
const User =require('../models/user'); const {errorHandler}= require('../helpers/dbErrorHandler') exports.sayHi =(req,res) =>{ res.json({ error:0, code:200, message:"The app is running on server side"}) } exports.signup =(req,res) =>{ console.log("req.body",req.body); const user =new User(req.body); user.save((err,user)=>{ if(err){ return res.status(400).json({ err:errorHandler(err) }); } user.salt=undefined; user.hashed_password =undefined; res.json({ user }) }) }
atom.declare("Game.Ship_fighter_1", Game.Ship, { configure: function method() { this.quads = 8; this.solidW = 10; this.solidH = 50; this.baseThrust = 0.03; this.slowdown = 0.005; this.maxThrust = 1; this.rotateSpeed = 0.002; this.HP = 250; this.regenerateHP = 0.01; this.regenerateCooldown = 10000; this.debris = 3; this.debrisRadius = 10; this.type = "fighter"; this.textureMain = Controller.images.get("ship2"); this.textureBroken = Controller.images.get("ship2_broken"); method.previous.call(this); this.configureParts(); this.redraw(); }, configureParts: function() { collider = [ [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0] ]; this.putCollider(collider); var turret1 = new Game.Part_turret_1(Controller.layerShips, { localPosition: new Point(-12, 4), angle: 0, parent: this, quads: [{x: 2, y: 4}] }); this.putPart(turret1); var turret2 = new Game.Part_turret_1(Controller.layerShips, { localPosition: new Point(12, 4), angle: 0, parent: this, quads: [{x: 5, y: 4}] }); this.putPart(turret2); var engine1 = new Game.Part_engine_1(Controller.layerShips, { localPosition: new Point(0, 28), angle: 0, parent: this, quads: [{x: 3, y: 7}, {x: 4, y: 7}] }); this.putPart(engine1); }, onUpdate: function method(time) { method.previous.call(this, time); } });
import React from 'react'; import { shallow} from 'enzyme'; import Reviews from '../client/src/components/Reviews.jsx'; import { reviews, stars } from './testDummyData.js'; describe('Reviews', () => { it('should be defined', () => { expect(Reviews).toBeDefined(); }); it('should render correctly', () => { const tree = shallow( <Reviews name='Reviews test' visibleReviews={reviews} stars={stars[0]}/> ); expect(tree).toMatchSnapshot(); }); });
import React, { useState } from 'react' import { View, TextInput, Image, TouchableOpacity, Alert } from 'react-native' import { connect } from 'react-redux' import { KeyboardAwareView } from 'react-native-keyboard-aware-view' import axios from 'axios' import AsyncStorage from '@react-native-async-storage/async-storage' import Logo from '../../assets/logo.png' import styles from '../../theme/Styles' import { COLORS, SIZES } from '../../theme/Theme' import { RegularText, BoldText } from '../../components/UIComponents/Text' import { validateEmail } from '../../utils/utils' import { saveUserData } from '../../actions/loginActions' const LoginScreen = props => { const { navigation, dispatch } = props const [email, setEmail] = useState('') const [password, setPassword] = useState('') const submitHandler = () => { console.log(email, password) if (!email) { alert("Please enter email") return } if (!validateEmail(email)) { alert("Please enter valid email address") return } if (!password) { alert("Please enter password") return } if (password.length < 6) { alert("Password should be more than 5 characters") return } axios.post('https://dev.haindavasakthi.com/api/auth/login', { email, password }) .then(response => { setEmail('') setPassword('') dispatch(saveUserData(response.data)) storeUserData(response.data) Alert.alert( "Success", response.data.message, [ { text: "Ok" } ] ) }) .catch(error => { console.log(error) alert("Please enter valid email and password") }) } const storeUserData = async (data) => { try { const jsonValue = JSON.stringify(data) await AsyncStorage.setItem('userData', jsonValue) } catch (error) { console.log(error) } } return ( <View style={[styles.flex1, styles.bgWhite, styles.loginWrapper]}> <View style={[styles.flex1, styles.vhCenter]}> <Image source={Logo} style={styles.loginLogo} /> <BoldText style={[styles.bold, styles.loginHeading]}>Login to your Account</BoldText> <TextInput style={styles.input} onChangeText={text => setEmail(text)} value={email} placeholder="Email" placeholderTextColor={COLORS.light} keyboardType="email-address" /> <TextInput style={styles.input} onChangeText={text => setPassword(text)} value={password} placeholder="Password" placeholderTextColor={COLORS.light} secureTextEntry={true} /> <View style={styles.fpWrap}> <TouchableOpacity onPress={() => props.navigation.navigate('ForgotPassword')} style={styles.link} activeOpacity={0.7} > <BoldText style={[styles.linkText, styles.smallText]}>Forgot Password</BoldText> </TouchableOpacity> </View> <TouchableOpacity style={[styles.btn, styles.shadow, styles.btnLogin, styles.btnPrimary]} activeOpacity={0.7} onPress={() => submitHandler()} > <BoldText style={styles.btnPrimaryText}>Sign in</BoldText> </TouchableOpacity> <View style={[styles.row, styles.mtLg]}> <RegularText style={styles.lightText}>Don't have an account? </RegularText> <TouchableOpacity style={styles.link} onPress={() => props.navigation.navigate('Signup')} activeOpacity={0.7} > <BoldText style={styles.linkText}>Sign up</BoldText> </TouchableOpacity> </View> </View> </View> ) } const mapStateToProps = (state) => ({ userData: state.login.userData }) export default connect(mapStateToProps)(LoginScreen) // export default LoginScreen
import {Form, Input, Icon, Select, DatePicker, Row, Col, Checkbox, Button, AutoComplete} from 'antd'; import React, {Component} from 'react'; import moment from 'moment'; import 'moment/locale/zh-cn'; import SearchModal from '../../components/modal/SearchModal.js' import {getCodeType} from '../../requests/http-req.js' moment.locale('zh-cn'); const FormItem = Form.Item; const MonthPicker = DatePicker.MonthPicker; const RangePicker = DatePicker.RangePicker; const Option = Select.Option; class CashBalanceListSearch extends Component { state = {}; handleSearch = (e) => { e.preventDefault(); this.props.form.validateFieldsAndScroll((err, values) => { if (!err) { console.log('Received values of form: ', values); if (this.props.handleSearch) { this.props.handleSearch(values) } } }); } componentWillMount() { } componentDidMount() { //获取币种类型 //获取提现类型的接口 getCodeType().then(((req) => { this.setState({ codeType: req.data.data }, () => { this.props.form.setFieldsValue({ coinCode: this.props.coinCode ? this.props.coinCode : this.state.codeType[0], balanceTime: this.props.balanceTime ? moment(this.props.balanceTime, 'YYYY-MM-DD') : moment(moment().add(-1, 'days').format('YYYY/MM/DD'), 'YYYY-MM-DD'), // balanceTime: moment().add(-1, 'days').format('YYYY/MM/DD'), }) }) })) } render() { const {getFieldDecorator} = this.props.form; return ( <Form style={{ flexDirection: 'row', display: 'flex', minHeight: '60px', height: '60px', width: '100%' , paddingRight: '15px', paddingLeft: '15px', alignItems: 'center' }} className="ant-advanced-search-form" onSubmit={this.handleSearch} > <div style={{ display: 'flex', width: '100%', flex: 1, flexDirection: 'column', justifyContent: 'center' }}> <div style={{width: '100%', display: 'flex', flexDirection: 'row'}}> <FormItem style={{margin: 'auto', flex: 1, paddingRight: '15px'}} label={`币种`}> {getFieldDecorator(`coinCode`, { rules: [{ required: true, message: '选择币种' }] })( <Select placeholder="选择币种" > { this.state.codeType && this.state.codeType.map((item, index) => { return <Option key={index} value={item}>{item}</Option> }) } </Select> )} </FormItem> <FormItem style={{margin: 'auto', flex: 1}} label={`时间`}> {getFieldDecorator('balanceTime', { rules: [{ required: true, message: '选择时间' }], })( <DatePicker format="YYYY-MM-DD" disabledTime={true} />)} </FormItem> <view style={{flex: 2}}></view> </div> </div> <Button htmlType="submit" type="primary" icon="search" style={{ marginLeft: '10px', }}>搜索 </Button> </Form> ); } } const NewCashBalanceListSearch = Form.create()(CashBalanceListSearch); export default NewCashBalanceListSearch;
import multer from 'multer'; const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, __basedir + '/images/') }, filename: (req, file, cb) => { file.name = file.originalname; const date = Date.now(); const newName = date + "_" + file.originalname.replace(/\s/g, '').toLowerCase(); file.url = '/images/' + newName; cb(null, newName) } }); var upload = multer({storage: storage}); module.exports = upload;
var linkman =decodeURI(decodeURI(Request['linkman'])); var linkphone = Request['linkphone']; var addrs = decodeURI(decodeURI(Request['addr'])); $(function () { $('#quxiao').click(function() { $('#dialog1').hide(); }); //页面初始化取得收货地址列表A currentPage = 1; deleteId = ""; if(!empty(MemberInfo)){ getDeliveryAddr(); }else{ getRequest(); initRadioStatus(); linkman =decodeURI(decodeURI(Request['linkman'])); linkphone = Request['linkphone']; addrs = decodeURI(decodeURI(Request['addr'])); console.log(linkman); console.log(linkphone); console.log(addrs); if(linkman==undefined||linkphone==undefined||addrs==undefined){ $(".shdizhilist").append(""); }else{ linshihtml="<dl class='shuxinglist'>"+ "<dt class='dtDz'>"+ //"<input name='demo' type='radio'>"+ "<input class='aui-radio' name='demo' type='radio'>"+ "</dt>"+ "<dd class='name' id='linkman'>"+linkman+ "</dd>"+ "<dd id='linkphone'>"+linkphone+"</dd>"+ "<dd id='addrs'>" +addrs+"</dd>"+ "</dl>"; } $("#addre").html(linshihtml); } //$(".shdizhilist").html(""); }); var linshihtml=""; //取得收货地址 function getDeliveryAddr() { var url = "/Address/MyAddressList/1"; var success=function(data){ if(data.bizData.rows.length>0) { showHtml(data.bizData.rows); initRadioStatus(); } if(data.bizData.rows.length<10){ $("#addr").hide(); } weui.Loading.hide(); }; weui.Loading.show(); ajaxPostFun(url,null,success, null,"取得收货地址"); } // 拼接页面字符串 function showHtml(dataList) { for(var i=0; i<dataList.length; i++) { var countryStr = ""; if(dataList[i].country != "请选择") { countryStr = dataList[i].country; } var html = '<dl class="shuxinglist">' + '<dt class="dtDz">'+ '<input class="aui-radio" name="demo" type="radio" value="' + dataList[i].id + '">'+ '</dt>'+ '<dd class="name" id="'+dataList[i].id+'linkman">'+ dataList[i].linkman+ '</dd>'+ '<dd id="' +dataList[i].id + 'linkphone">'+dataList[i].linkphone+'</dd>'+ '<dd id="' +dataList[i].id + '">' + dataList[i].province + dataList[i].city + countryStr + dataList[i].fullAddress + '</dd>' + '</dl>'; //console.log(html); $(".shdizhilist").append(html); } } //$(".quzhifubtn").click(function(){ // //}); //加载更多 //function loadMore() //{ // currentPage = currentPage + 1; // var url = "/Address/MyAddressList/" + currentPage; // var success=function(data){ // if(data.bizData.rows.length == 0) // { // initRadioStatus(); // layer.msg("没有更多地址"); // weui.Loading.hide(); // } // else // { // showHtml(data.bizData.rows); // weui.Loading.hide(); // initRadioStatus(); // } // }; // weui.Loading.show(); // ajaxPostFun(url,null,success, null,"加载更多收货地址"); //} function save() { var address = ""; if(!empty(MemberInfo)){ $(".aui-radio").each(function(){ if(this.checked) { address="联系人:"+$("#" +this.value+"linkman")[0].innerHTML; address+=",联系电话:"+$("#" +this.value+"linkphone")[0].innerHTML; address+=",地址:"+$("#" +this.value)[0].innerHTML; } }); }else{ $(".aui-radio").each(function(){ if(this.checked) { address = "联系人:"+$("#linkman")[0].innerHTML; address +=",联系电话:"+ $("#linkphone")[0].innerHTML; address+= ",地址:"+$("#addrs")[0].innerHTML; } }); } appStorage.setItem("address", address); window.location.href = "tfFapiao.html"; } function saveView(){ appStorage.setItem("view","tfFapiaoDizhi.html"); window.location.href = "tfxjshouhuoadress.html"; } //如果初始化时有地址,那么该地址前radio是选中状态 function initRadioStatus() { var address = appStorage.getItem("address"); $(".aui-radio").each(function(){ if($("#" +this.value)[0].innerHTML == address) { this.checked = true; } }); } function getRequest() { //var url = decodeURI(location.search); //获取url中"?"符后的字串 var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; }
/** * @class widgets.Util.Tela * Configura componentes genéricos na tela. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ var args = arguments[0] || {}; /** * Faz as configurações iniciais da window. Deve ser invocado no costrutor de todo Controller que possui janela. * @param {Ti.UI.Window} janela Window a se configurar. * @param {Alloy} runningAlloy Alloy vinculado ao Controller. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.initConfigWindow = function(janela, runningAlloy) { try{ janela.addEventListener("close", function(e){ runningAlloy.destroy(); }); if(Ti.Platform.name === 'android') { janela.width = Ti.UI.FILL; janela.height = Ti.UI.FILL; janela.windowSoftInputMode = Titanium.UI.Android.SOFT_INPUT_ADJUST_PAN; janela.exitOnClose = false; } } catch(e){ Alloy.Globals.onError(e.message, "initConfigWindow", "app/widgets/Util/controllers/Tela.js"); } }; /** * Faz as configurações iniciais da popup na tela. Deve ser invocado no costrutor de todo Controller que se comporta como popup. * @param {Ti.UI.View} popupController PopUp a se configurar. * @param {Function} showFunction Rotina executa toda vez que o método show da popup é invocado. * @param {Function} cancelFunction Rotina executa toda vez que o método close da popup é invocado. * @alteracao 21/01/2015 176562 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.initConfigPopUp = function(popupController, showFunction){ var camada = Alloy.createWidget("GUI", "Camada").getView(); var component = popupController.getView(); var animacaoAbrir = Ti.UI.createAnimation({ duration: 200, opacity: 1 }); popupController.show = function(parans){ try{ //Adiciono a nova função do botão voltar no android. Não interfere com o iOS. Alloy.Globals.currentWindow().stackBackFunction.push(popupController.close); Alloy.Globals.currentWindow().add(camada); component.opacity = 0; Alloy.Globals.currentWindow().add(component); component.animate(animacaoAbrir); if(showFunction){ showFunction(parans); } } catch(e){ Alloy.Globals.onError(e.message, "initConfigPopUp", "app/widgets/Util/controllers/Tela.js"); } }; popupController.close = function(parans){ try{ //Desempilho a função do botão voltar para essa popup. Alloy.Globals.currentWindow().stackBackFunction.pop(); Alloy.Globals.currentWindow().remove(camada); Alloy.Globals.currentWindow().remove(component); } catch(e){ Alloy.Globals.onError(e.message, "initConfigPopUp", "app/widgets/Util/controllers/Tela.js"); } }; };
const Todo = require('models/todo'); const User = require('models/user'); module.exports = { app: (req, res) => { res.render('index', { title: 'Todo list', auth: req.isAuthenticated() ? req.user.username : 'anon' }); }, main: (req, res) => { res.render('main', { title: 'Todo' }); }, signIn: (req, res) => { res.render('sign', { title: 'Sign In', register: false }); }, signUp: (req, res) => { res.render('sign', { title: 'Sign Up', register: true }); } };
const request = require('supertest'); const app = require('../app'); const { User, userAdminId, userAdmin, setupDatabase } = require('./fixtures/db'); // Change the timeout from 5000 ms to 3000 ms jest.setTimeout(60000); // Define the authentication path url const url = '/api/v1/auth'; beforeEach(setupDatabase); /* * Test suite for the authentication workflow */ describe('Test the authentication path', () => { test('Should register a new user', async () => { const response = await request(app).post(`${url}/register`).send({ name: 'Andrew', email: 'andrew@example.com', password:'MyPass777!' }).expect(201); // Assertions about the response expect(response.body).toMatchObject({ success: true }); }); test('Should login existing user', async () => { await request(app).post(`${url}/login`).send({ email: userAdmin.email, password: userAdmin.password }).expect(200); }); test('Should get profile for user', async () => { await request(app) .get(`${url}/me`) .set('Authorization', `Bearer ${userAdmin.tokens[0].token}`) .send() .expect(200); }); test('Should not get profile for unauthenticated user', async () => { await request(app) .get(`${url}/me`) .send() .expect(401); }); test('Should logout logged user', async () => { const response = await request(app) .get(`${url}/logout`) .expect(200); expect(response.body).toMatchObject({ success: true, data: {} }); }); }); /* * Test suite for register user fields */ describe('Test register user fields', () => { test('Should not register user with no no name', async () => { await request(app) .post(`${url}/register`) .send({ name: '', email: 'example@gmail.com', password: '123456' }) .expect(400); }); test('Should not register user with invalid email', async () => { await request(app) .post(`${url}/register`) .send({ name: 'example', email: 'example@', password: '123456' }) .expect(400); }); test('Should not register user with password length less than 6 characters', async () => { await request(app) .post(`${url}/register`) .send({ name: 'example', email: 'example@gmail.com', password: '12345' }) .expect(400); }); test('Should not register user with invalid role', async () => { await request(app) .post(`${url}/register`) .send({ name: 'example', email: 'example@gmail.com', password: '123456', role: 'fucking boss' }) .expect(400); }); }); /* * Test suite for the login */ describe('Test login user fields', () => { test('Should not login nonexistent user', async () => { const response = await request(app).post(`${url}/login`).send({ email: 'example@example.com', password: userAdmin.password }).expect(401); expect(response.body.error).toBe('User not found'); }); test('Should not login user with incorrect password', async () => { const response = await request(app).post(`${url}/login`).send({ email: userAdmin.email, password: 'thisisnotmypassword' }).expect(401); expect(response.body.error).toBe('Invalid password'); }); }); /* * Test suite for the update of the user fields */ describe('Test update user fields', () => { test('Should update the current password', async () => { await request(app) .put(`${url}/updatepassword`) .set('Authorization', `Bearer ${userAdmin.tokens[0].token}`) .send({ currentPassword: userAdmin.password, newPassword: 'newpassword' }) .expect(200); const updatedUserPassword = await User.findOne({ email: userAdmin.email }).select('+password'); const isMatch = await updatedUserPassword.matchPassword('newpassword'); expect(isMatch).toBe(true); }); test('Should not update the current password if it does not match', async () => { await request(app) .put(`${url}/updatepassword`) .set('Authorization', `Bearer ${userAdmin.tokens[0].token}`) .send({ currentPassword: 'passwordnotmatching', newPassword: 'newpassword' }) .expect(401); }); test('Should update the current email', async () => { await request(app) .put(`${url}/updatedetails`) .set('Authorization', `Bearer ${userAdmin.tokens[0].token}`) .send({ email: 'mike1@example.com', name: userAdmin.name }) .expect(200); const updatedUser = await User.findOne({ email: 'mike1@example.com'}); expect(updatedUser).not.toBe(null); }); test('Should not update unathorized user', async () => { await request(app) .put(`${url}/updatedetails`) .send({ email: 'mike1@example.com', name: userAdmin.name }) .expect(401); }); }); /* * Test suite for the forgot and reset password */ describe('Test forgot and reset password', () => { test('Should not send forgot password email if user not found', async () => { await request(app) .post(`${url}/forgotpassword`) .send({ email: 'notexistingmail@example.com' }) .expect(404); }); test('Should send forgot password email', async () => { const response = await request(app) .post(`${url}/forgotpassword`) .send({ email: userAdmin.email }) .expect(200); expect(response.body).toMatchObject({ success: true, data: 'Email sent' }); }); test('Should not reset password if unauthenticated or wrong token', async () => { await request(app) .put(`${url}/resetpassword/alinrtiunadf`) .send({ password: userAdmin.password }) .expect(400); }); test('Should not reset password if it is incorrect', async () => { await request(app) .put(`${url}/resetpassword/alinrtiunadf`) .send({ password: 'wrongpassword' }) .expect(400); }); });
import React from "react" const Footer=()=>{ return( <> <footer className="w-100 bg-light text-center"> <p> Made In India | Privacy Policy | About | Insights | Contact Copyright All Rights Reserved © 2020 TechnoIdentity.</p> </footer> </> ) } export default Footer;
define(["ex1/Place"], function (Place) { "use strict"; function Home(title, latitude, longitude, whoLivesHere) { Place.apply(this, arguments); this.whoLivesHere = whoLivesHere; } Home.prototype = Object.create(Place.prototype); Home.prototype.toString = function () { var s = Place.prototype.toString.call(this); return s + ", Who lives here: " + this.whoLivesHere; } return Home; });
import React, { Component } from "react"; import ReactDOMServer from "react-dom/server"; import { Position, Toaster, Button, InputGroup, ButtonGroup } from "@blueprintjs/core"; const { constants, csvToJson, electron, fs, path, process } = window; const { configDir, defaultToast } = constants; let { baseDir } = constants; const { nativeImage } = electron; const { BrowserWindow, dialog } = electron.remote; const exePath = path.join(configDir, "daemon", "CameraDaemon.exe"); const binToStr = array => { var result = ""; for (var i = 0; i < array.length; i++) result += String.fromCharCode(parseInt(array[i])); return result; }; class Photography extends Component { constructor(props) { super(props); this.state = { daemon: null, camera: false, year: false, level: false, school: false, shift: false, group: false, options: {}, students: {}, newStudent: "", currentStudent: "", lastPhoto: "", preview: null, scan: "" }; } componentDidMount = _ => { baseDir = constants.baseDir; this.createDisplayWindow(""); window.addEventListener("keyup", this.handleKeyUp); this.setOptions(); this.setState({ daemon: process.spawn(exePath) }, _ => { this.state.daemon.stdout.on("data", data => { data = binToStr(data); console.log(data); if (data.includes("disconnected")) { this.setState({ camera: false }); this.addToast({ message: "Cámara desconectada", intent: "warning" }); } else if (data.includes("connected")) { this.setState({ camera: true }); this.addToast({ message: "Cámara conectada", intent: "success" }); } else if (data.includes("captured")) { this.setState({ camera: true }); this.addToast({ message: "Fotografía capturada", intent: "success" }); if (this.state.currentStudent) { const photo = data.split("captured:")[1].replace("\n", ""); let preview, tries = 0; // const interval = setInterval(_ => { // if (tries++ > 5) clearInterval(interval); // console.info(photo.slice(0, photo.length - 1)); console.info( "photo copy:", photo .slice(0, photo.length - 1) .replace("Originales con ID", "Originales con nombre") .replace("originales con ID", "originales con nombre") .replace( this.state.currentStudent, this.state.students[this.state.currentStudent].name ) ); // setTimeout( // _ => fs.createReadStream(photo.slice(0, photo.length - 1)).pipe( fs.createWriteStream( photo .slice(0, photo.length - 1) .replace("Originales con ID", "Originales con nombre") // .replace("originales con ID", "originales con nombre") .replace( this.state.currentStudent, this.state.students[this.state.currentStudent].name ) ) ); // 500 // ); fs.readFile(photo.slice(0, photo.length - 1), (err, data) => { if (err) { console.error(err); return; } preview = nativeImage.createFromBuffer(data); preview = preview.toJPEG(100).toString("base64"); this.setState( prev => { prev.students[this.state.currentStudent].photoTaken = true; prev.students[this.state.currentStudent].photo = photo; return { students: prev.students, lastPhoto: photo, preview }; } // _ => clearInterval(interval) ); }); // }, 500); } } else { this.setState({ camera: true }); this.addToast({ message: data, intent: "success" }); } }); this.state.daemon.on("close", _ => { this.setState({ camera: false }); this.addToast({ message: "Camera Daemon closed", intent: "warning" }); }); this.state.daemon.stderr.on("data", err => { err = binToStr(err); console.error(err); this.setState({ camera: false }); this.addToast({ message: "Camera Daemon error!", intent: "danger" }); }); }); }; componentWillUnmount = _ => { this.state.daemon.stdin.pause(); this.state.daemon.kill(); window.removeEventListener("keyup", this.handleKeyUp); }; createDisplayWindow = student => { this.setState( { display: new BrowserWindow({ title: "Zonagrad", frame: true, fullscrern: true, resizeable: false, transparent: false }) }, _ => { this.state.display.setMenu(null); this.renderStudentDisplay(student); this.state.display.on("closed", () => { this.setState({ display: null }); }); } ); }; renderStudentDisplay = student => { if (this.state.display === null) return this.createDisplayWindow(student); const css = ` body { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; height: 100%; margin: 0; color: white; font-family: verdana; text-align: center; background: rgb(48, 64, 77); } h1 { font-size: 80px; } h2 { font-size: 60px; font-weight: 400 !important; } img { width: 80vh; transform: rotate(-90deg); } `; const content = ( <body> <style>{css}</style> <div> <h2>SIGUIENTE:</h2> </div> <div> <h1>{student}</h1> </div> </body> ); this.state.display.loadURL( "data:text/html;charset=utf-8," + ReactDOMServer.renderToString(content) ); }; addToast = options => { Toaster.create({ position: Position.BOTTOM_RIGHT }).show({ ...defaultToast, ...options }); }; handleKeyUp = ({ key }) => { const { students, scan } = this.state; if ((scan + key).includes(".-")) { this.setState({ scan: "" }); } else if (key === "Shift") this.setState({ scan: scan + "." }); else { let sanitized = scan.toUpperCase().replace(".-", ""); for (let i = 0; i < sanitized.length - 1; i++) if (sanitized.charAt(i) == "." && isNaN(sanitized.charAt(i + 1))) sanitized = sanitized.slice(0, i) + sanitized.slice(i + 1); if (key === "Enter") { console.info(students, students[sanitized]); if (students[sanitized]) this.takePhoto(sanitized, students[sanitized].name); } else this.setState({ scan: scan + key }); } }; takePhoto = (id, name) => { this.state.daemon.stdin.write(id + "\n"); this.setState({ currentStudent: id }, _ => this.renderStudentDisplay(name)); this.addToast({ intent: "success", message: "Alumno seleccionado: " + name }); }; selectParam = (field, value) => { this.setState( { [field]: value }, this.setOptions ); }; removeFromState = field => { let removed = {}; switch (field) { case "year": removed.year = false; case "level": removed.level = false; case "school": removed.school = false; case "shift": removed.shift = false; case "group": removed.group = false; removed.currentStudent = ""; default: break; } this.setState(removed, this.setOptions); }; setOptions = _ => { let newState = {}; let dirPath = ""; let search = true; const { lstatSync, readdirSync } = fs; const isDirectory = source => lstatSync(source).isDirectory(); const getDirectories = source => readdirSync(source) .map(name => ({ name: name, path: path.join(source, name) })) .filter(dir => isDirectory(dir.path)); newState.options = {}; if (!this.state.year) dirPath = baseDir; else if (!this.state.level) dirPath = path.join(baseDir, this.state.year.toString()); else if (!this.state.school) dirPath = path.join( baseDir, this.state.year.toString(), this.state.level ); else if (!this.state.shift) dirPath = path.join( baseDir, this.state.year.toString(), this.state.level, this.state.school.toString() ); else if (!this.state.group) dirPath = path.join( baseDir, this.state.year.toString(), this.state.level, this.state.school.toString(), this.state.shift ); else { const { year, level, school, shift, group } = this.state; const listFile = path.join( baseDir, year.toString(), level, school.toString(), shift, group.toString(), "students.csv" ); this.state.daemon.stdin.write(listFile + "\n"); this.readStudentList(); search = false; } if (search && dirPath !== "") { getDirectories(dirPath).forEach( dir => (newState.options[dir.name] = dir.path) ); this.setState(newState); } }; readStudentList = _ => { const { year, level, school, shift, group } = this.state; const listFile = path.join( baseDir, year.toString(), level, school.toString(), shift, group.toString(), "students.csv" ); fs.readFile(listFile, "utf-8", (err, data) => { if (err) { console.error("An error ocurred reading the file :" + err.message); this.addToast({ message: "Error al leer el archivo", intent: "danger" }); return; } const result = csvToJson.toObject(data, { delimiter: ",", quote: '"' }); if (result.length === 0) return; let students = {}; result.forEach( res => (students[res.id] = { name: res.nombre, photo: res.foto, status: res.status }) ); this.setState({ students }); }); }; changenewStudent = ({ target }) => { this.setState({ [target.id]: target.value }); }; addStudent = _ => { const { year, level, school, shift, group } = this.state; const listFile = path.join( baseDir, year.toString(), level, school.toString(), shift, group.toString(), "students.csv" ); fs.readFile(listFile, "utf-8", (err, data) => { if (err) { console.error("An error ocurred reading the file :" + err.message); this.addToast({ message: "Error al agregar alumno", intent: "danger" }); return; } let result = csvToJson.toObject(data, { delimiter: ",", quote: '"' }); let newStudent = result[result.length - 1]; const idArr = newStudent.id.split("-"); const id = `${idArr[0]}-${Number(idArr[1]) + 1}`; const foto = newStudent.foto.replace( `${newStudent.id}_${newStudent.nombre}`, `${id}_${this.state.newStudent}` ); newStudent = { ...newStudent, id, nombre: this.state.newStudent, foto }; result.push(newStudent); this.saveStudentList(result); }); }; deleteStudent = id => { const { year, level, school, shift, group } = this.state; const listFile = path.join( baseDir, year.toString(), level, school.toString(), shift, group.toString(), "students.csv" ); dialog.showMessageBox( { type: "warning", deafaultId: 2, title: "Eliminar alumno", detail: `Seguro que quiere eliminar a ${this.state.students[id].name} de este grupo?`, buttons: ["No", "Sí", "Cancelar"] }, option => { if (option !== 1) { this.addToast({ intent: "warning", message: "Alumno no seleccionado" }); return; } fs.readFile(listFile, "utf-8", (err, data) => { if (err) { console.error("An error ocurred reading the file :" + err.message); this.addToast({ message: "Error al eliminar alumno", intent: "danger" }); return; } let result = csvToJson.toObject(data, { delimiter: ",", quote: '"' }); result = result.filter(student => student.id !== id); this.saveStudentList(result); }); } ); }; saveStudentList = students => { const { year, level, school, shift, group } = this.state; let data = [ "id,nombre,foto,id_escuela,escuela,logoEscuela,nivel,turno,grupo,director,firmaDirector,status" ]; students.forEach(student => { let item = ""; item += `"${student.id}"`; item += `,"${student.nombre}"`; item += `,"${student.foto}"`; item += `,"${student.id_escuela}"`; item += `,"${student.escuela}"`; item += `,"${student.logoEscuela}"`; item += `,"${student.nivel}"`; item += `,"${student.turno}"`; item += `,"${student.grupo}"`; item += `,"${student.director}"`; item += `,"${student.firmaDirector}"`; item += `,"${student.status || ""}"`; data.push(item); }); data = data.join("\n") + "\n"; const relDest = path.join( year.toString(), level, school, shift, group, "students.csv" ); fs.writeFile(path.join(baseDir, relDest), data, err => { if (err) { console.error(err); return; } this.readStudentList(); this.addToast({ message: "Cambios guardados", intent: "success" }); }); }; toggleStatus = (id, status) => { const { year, level, school, shift, group } = this.state; const listFile = path.join( baseDir, year.toString(), level, school.toString(), shift, group.toString(), "students.csv" ); fs.readFile(listFile, "utf-8", (err, data) => { if (err) { console.error("An error ocurred reading the file :" + err.message); this.addToast({ message: "Error al eliminar alumno", intent: "danger" }); return; } let result = csvToJson.toObject(data, { delimiter: ",", quote: '"' }); result = result.map(student => { return student.id === id ? { ...student, status } : student; }); this.saveStudentList(result); }); }; renderBreadcrumbs = _ => ( <ul className="bp3-breadcrumbs"> {this.state.year && ( <li> <a className={ "bp3-breadcrumbs" + (this.state.level ? "" : "bp3-breadcrumb-current") } > <Button onClick={this.removeFromState.bind(this, "year")}> {this.state.year} </Button> </a> </li> )} {this.state.level && ( <li> <a className={ "bp3-breadcrumbs" + (this.state.school ? "" : "bp3-breadcrumb-current") } > <Button onClick={this.removeFromState.bind(this, "level")}> {this.state.level} </Button> </a> </li> )} {this.state.school && ( <li> <a className={ "bp3-breadcrumbs" + (this.state.shift ? "" : "bp3-breadcrumb-current") } > <Button onClick={this.removeFromState.bind(this, "school")}> {this.state.school} </Button> </a> </li> )} {this.state.shift && ( <li> <a className={ "bp3-breadcrumbs" + (this.state.group ? "" : "bp3-breadcrumb-current") } > <Button onClick={this.removeFromState.bind(this, "shift")}> {this.state.shift} </Button> </a> </li> )} {this.state.group && ( <li> <a className="bp3-breadcrumbs bp3-breadcrumb-current"> <Button onClick={this.removeFromState.bind(this, "group")}> {this.state.group} </Button> </a> </li> )} </ul> ); renderSelection = _ => { if (!this.state.year) { return ( <div className="row" style={{ justifyContent: "center" }}> <div className="selection-wrapper"> <ButtonGroup style={{ width: 250 }} vertical={true} large={true}> {Object.keys(this.state.options).map(option => ( <Button key={"option-" + option} className="mar-t-s" onClick={this.selectParam.bind(this, "year", option)} > {option} </Button> ))} </ButtonGroup> </div> </div> ); } else if (!this.state.level) { return ( <div className="row" style={{ justifyContent: "center" }}> <div className="selection-wrapper"> <ButtonGroup style={{ width: 250 }} vertical={true} large={true}> {Object.keys(this.state.options).map(option => ( <Button key={"option-" + option} className="mar-t-s" onClick={this.selectParam.bind(this, "level", option)} > {option} </Button> ))} </ButtonGroup> </div> </div> ); } else if (!this.state.school) { return ( <div className="row" style={{ justifyContent: "center" }}> <div className="selection-wrapper"> <ButtonGroup style={{ width: 250 }} vertical={true} large={true}> {Object.keys(this.state.options).map(option => ( <Button key={"option-" + option} className="mar-t-s" onClick={this.selectParam.bind(this, "school", option)} > {option} </Button> ))} </ButtonGroup> </div> </div> ); } else if (!this.state.shift) { return ( <div className="row" style={{ justifyContent: "center" }}> <div className="selection-wrapper"> <ButtonGroup style={{ width: 250 }} vertical={true} large={true}> {Object.keys(this.state.options).map(option => ( <Button key={"option-" + option} className="mar-t-s" onClick={this.selectParam.bind(this, "shift", option)} > {option} </Button> ))} </ButtonGroup> </div> </div> ); } return ( <div className="row" style={{ justifyContent: "center" }}> <div className="selection-wrapper"> <ButtonGroup style={{ width: 250 }} vertical={true} large={true}> {Object.keys(this.state.options).map(option => ( <Button key={"option-" + option} className="mar-t-s" onClick={this.selectParam.bind(this, "group", option)} > {option} </Button> ))} </ButtonGroup> </div> </div> ); }; render = _ => ( <div id="photography" className="app-route d-f fd-col"> <h2> <Button icon="camera" className="mar-r-s" intent={this.state.camera ? "success" : "danger"} onClick={this.renderTest} ></Button> Photography </h2> <div className="row mar-t-s">{this.renderBreadcrumbs.bind(this)()}</div> {!this.state.group ? ( this.renderSelection.bind(this)() ) : ( <div> <div className="row jc-start pad-t-s"> <Button intent="primary" onClick={this.addStudent.bind(this)}> Agregar alumno </Button> <InputGroup id="newStudent" intent="primary" value={this.state.newStudent} onChange={this.changenewStudent} /> </div> <div className="row jc-center"> <div className="d-f fd-col mar-l-m"> {Object.keys(this.state.students).map((student, index) => { student = { id: student, ...this.state.students[student] }; const { year, level, school, shift, group } = this.state; try { fs.readFileSync( path.join( baseDir, year.toString(), level, school, shift, group, "Originales con ID", `${student.id}.jpg` ) ); student.photoTaken = true; } catch (e) { student.photoTaken = false; } const intent = student.photoTaken ? "success" : this.state.currentStudent === student.id ? "warning" : "primary"; return ( <ButtonGroup key={"student-" + index} className="mar-t-m"> <Button intent="danger" onClick={this.deleteStudent.bind(this, student.id)} > X </Button> {student.status === "ausente" ? ( <Button intent="warning" onClick={this.toggleStatus.bind( this, student.id, "dado de baja" )} > Ausente </Button> ) : student.status === "dado de baja" ? ( <Button intent="danger" onClick={this.toggleStatus.bind(this, student.id, "")} > Dado de baja </Button> ) : ( <Button intent="success" onClick={this.toggleStatus.bind( this, student.id, "ausente" )} > Normal </Button> )} <Button intent={intent} disabled> {student.id} </Button> <Button className="grow-1" intent={intent}> {student.name} </Button> <Button icon="camera" intent={intent} disabled={ student.status !== null && student.status !== "" } onClick={this.takePhoto.bind( this, student.id, student.name )} > Fotografía </Button> </ButtonGroup> ); })} </div> <div className="preview-container"> {this.state.preview && ( <img className="d-f fd-col grow-1 mar-s bg-black photography-preview rotate" src={"data:image/jpeg;base64," + this.state.preview} /> )} </div> </div> </div> )} </div> ); } export default Photography;
// pages/cart/index.js Page({ /** * 页面的初始数据 */ data: { goodsList:Array, // 所有金额 allPrice:'', // 判断全选 allSelect:false, // 选中的商品数 selectGoodsCount:0 }, // 页面加载 onLoad(){ }, onShow(){ let goodsList = wx.getStorageSync('cart') || []; this.statisticsGoods(goodsList) }, // 计算总金额和判断全选 statisticsGoods(goodsList){ // 存储总金额 let money= 0; // 计算选中的商品数 let selectGoods = 0; if(goodsList.length > 0){ // 循环判断金额和是否全选 goodsList.forEach(item=>{ if(item.isSelect){money += item.price * item.goodsCount;} if(item.isSelect){ selectGoods++; } }); } // 满足条件,全选 if(selectGoods == goodsList.length){ this.setData({ allSelect:true }) }else{ this.setData({ allSelect:false }) } // 渲染页面 this.setData({ goodsList, allPrice:money, selectGoodsCount:selectGoods }); wx.setStorageSync('cart', goodsList); }, // 选择商品 radioSelect(e){ // 获取点击商品的索引 let {index} = e.currentTarget.dataset // 拿到页面的商品信息 let goodsArr = this.data.goodsList; goodsArr[index].isSelect = !goodsArr[index].isSelect; // 更新数据 this.statisticsGoods(goodsArr); }, // 加减商品 chageCount(e){ let {key,index} = e.currentTarget.dataset; // 拿到页面的商品信息 let goodsArr = this.data.goodsList; if(key){ // + goodsArr[index].goodsCount++; // 更新数据 this.statisticsGoods(goodsArr); }else{ // - if(goodsArr[index].goodsCount == 1){ wx.showModal({ content:'是否删除商品', confirmColor:'red', success :res=> { if (res.confirm) { goodsArr.splice(index,1); // 更新数据 this.statisticsGoods(goodsArr); } } }) }else{ goodsArr[index].goodsCount--; } // 更新数据 this.statisticsGoods(goodsArr); } }, // 全选触发 allSelectBtn(){ let goodsList = wx.getStorageSync('cart') || []; goodsList.forEach(item=>{ item.isSelect = !this.data.allSelect; }); this.statisticsGoods(goodsList); }, // 结算触发 settlement(){ wx.navigateTo({ url: '/pages/pay/index', }) } })
// global NAMESPACE SWAP_GURU var SWAP_GURU = SWAP_GURU || {}; SWAP_GURU.posts = SWAP_GURU.posts || {}; (function($){ var $dialog; var post_id, trade_post_id; var ITEM_PER_PAGE = 2; var page_offset = ITEM_PER_PAGE; function create_dialog_myposts(){ $dialog = $('<div></div>') .html('This dialog will show every time!') .dialog({ modal: true, autoOpen: false, title: 'Your Current Available Posts', position: 'center', width: 760, height: 530 }); $('.open_dialog').live('click', function() { post_id = $(this).attr('post_id'); $.get( "/posts/my_posts", {}, function (data) { $dialog.empty().append(data); $dialog.dialog('open'); } ); // prevent the default action, e.g., following a link return false; }); } function ajax_get_and_alter_proposal_form(element){ $.get('/proposals/new', function(data){ element.append(data); element.find('input#proposal_post_id').attr('value', post_id); element.find('input#proposal_trade_post_id').attr('value', trade_post_id); }); } function load_more_posts(){ $.get('/feed_timeline', {layout: "false", offset: page_offset}, function(data){ $('#time_line_post').append(data); page_offset += ITEM_PER_PAGE; }); } function create_loading_div(){ loading_div = $("<div id='loading_div' style='display:none'>Loading ..... </div>"); $('#container').append(loading_div); $('#loading_div').ajaxSend(function() { $(this).show(); }).ajaxStop(function() { $(this).hide(); }); } // register live event ----------------- $('.propose').live('click', function(){ trade_post_id = $(this).attr('trade_post_id'); //$('#my_posts').empty(); //.append(post_id).append("---").append(trade_post_id); ajax_get_and_alter_proposal_form($('#my_posts').empty()); }); // initialize variables/elements not depends on DOM. // Initialization depending when DOM ready. $(document).ready(function(){ create_dialog_myposts(); create_loading_div(); $('#load_more').live('click', function(){ $(this).remove(); load_more_posts(); }); }); })(jQuery, SWAP_GURU.posts); // Facebook like function (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));
import {useEffect} from 'react'; import {createPortal} from 'react-dom'; const modalRoot = document.getElementById('modal-container'); const Modal = (props) => { const element = document.createElement('dialog'); const inner = document.createElement('div'); element.style.padding = 0; element.appendChild(inner); function closeWithEscape(event) { if (event.keyCode === 27) { props.hideModal(); } } function closeWithClickOutside(event) { console.log(event.target); if (event.target === element) { props.hideModal(); } } useEffect( () => { modalRoot.appendChild(element); element.showModal(); document.addEventListener('keypress', closeWithEscape); element.addEventListener('click', closeWithClickOutside); document.body.style.overflow = "hidden"; return () => { document.removeEventListener('keypress', closeWithEscape); element.removeEventListener('click', closeWithClickOutside); modalRoot.removeChild(element); document.body.style.overflow = null; } } ); return createPortal(props.children, inner) }; export default Modal;
import React from 'react'; const Landing = () => <p>This is the landing page</p>; export default Landing;
/* * Homework 06 - Dynamic Programming * * * Problem 1: Max Consecutive Sum * * Prompt: Given an array of integers find the sum of consecutive * values in the array that produces the maximum value. * * Input: Unsorted array of positive and negative integers * Output: Integer (max consecutive sum) * * Example: input = [6, -1, 3, 5, -10] * output = 13 (6 + -1 + 3 + 5 = 13) * * */ // Time Complexity: // Auxiliary Space Complexity: function maxConsecutiveSum(arr) { // declare max function findMax() { } // call findMax // return max } // * Example: input = [6, -1, 3, 5, -10] // * output = 13 (6 + -1 + 3 + 5 = 13) function maxConsecutiveSum(arr) { // declare max let max = 0 // loop array for(let i = 0; i < arr.length; i++) { let tempMax = arr[i] // 2nd iterator loop for(let j = i+1; j < arr.length; j++) { tempMax = tempMax + arr[j] // check if if(tempMax > max) { max = tempMax } } } return max } // console.log(maxConsecutiveSum([6, -1, 3, 5, -10])) /* * BitFlip * * Given an array of binary values (0 and 1) and N number of flips that * can convert a 0 to a 1, determine the maximum number of consecutive 1's * that can be made. * * Input: arr {Array} * Input: n {Integer} * Output: Integer * * Example: bitFlip([0,1,1,1,0,1,0,1,0,0], 2) * Result: 7 */ // Time Complexity: // Auxiliary Space Complexity: function bitFlip (arr, n) { // declare ones int let ones = 0 for(let i = 0; i < arr.length; i++) { if(arr[i] === 1) { ones++ } else { continue } for(let j = arr[i] + 1; j < arr.length; j++) { if(arr[j] === 1) { ones++ } else { if(n > 0) { arr[j] = 1 ones++ n-- } } } } return ones } console.log(bitFlip([0,1,1,1,0,1,0,1,0,0], 2))
export default { home: '调度大盘', login: '登录', params: '系统配置', sys_monitor: '系统监控', data_monitor: '数据监控', // cache_monitor: '缓存监控', // equip_monitor: '资源监控', // thread_monitor: '线程监控', task_pool: '线程池配置', repo:'资源库管理', business:'业务配置', busi_db:'业务数据库', busi_db_edit:'业务库编辑', busi_dict:'业务字典', busi_dict_edit:'业务字典编辑', tree_repo:'资源库目录树', db_repo:'数据库资源库', file_repo:'文件库资源库', db_edit_repo:'编辑数据库资源库', file_edit_repo:'编辑文件库资源库', task:'调度管理', task_job:'作业调度', add_job:'新增作业', edit_job:'编辑作业', copy_job:'复制作业', create_job:'创建作业', detail_job:'作业详情', params_job:'作业参数', params_trans:'转换参数', task_trans:'转换调度', add_trans:'新增转换', edit_trans:'编辑转换', copy_trans:'复制转换', create_trans:'创建转换', detail_trans:'转换详情', scheduler:'定时调度', scheduler_manager:'定时管理', job_run:'作业定时', trans_run:'转换定时', scheduler_trans:'转换定时', log_etl:'日志管理', log_page:'调度日志', log_login:'登录日志', log_operate:'操作日志', // cluster_page:'集群调度', // node_page:'服务器节点', // carte_page:'Carte配置', system:'系统管理', // system_user_page:'用户管理', // system_role_page:'角色管理', // system_permission_page:'权限管理', help:'辅助管理', warning:'告警监控', help_db_page:'Druid', help_cron_page:'正则表达式', help_json_page:'JSON格式化' }
// Copyright (c) 2021 Antti Kivi // Licensed under the MIT License import localizedLinkQuery from './localizedLinkQuery'; import navigationQuery from './navigationQuery'; const { site: linkSite, ...pages } = localizedLinkQuery; export default { ...navigationQuery, ...pages, site: { siteMetadata: { ...linkSite.siteMetadata, defaultLocale: 'fi', title: 'Antti Kivi', localePaths: { en_GB: 'en', fi: '', }, }, }, allContentfulEntry: { edges: [ { node: { contentful_id: '6JksITICuGCEYUIVHlWl5U', node_locale: 'fi', internal: { type: 'ContentfulIndexPage', }, }, }, { node: { contentful_id: '6JksITICuGCEYUIVHlWl5U', node_locale: 'en-GB', internal: { type: 'ContentfulIndexPage', }, }, }, { node: { contentful_id: '12OH6cgaTcp4TUDvpqslYc', node_locale: 'fi', internal: { type: 'ContentfulMenu', }, }, }, { node: { contentful_id: '12OH6cgaTcp4TUDvpqslYc', node_locale: 'en-GB', internal: { type: 'ContentfulMenu', }, }, }, { node: { contentful_id: '29kQlzt1s2bR8OirrtTbCo', node_locale: 'fi', internal: { type: 'ContentfulCurriculumVitaePage', }, }, }, { node: { contentful_id: '29kQlzt1s2bR8OirrtTbCo', node_locale: 'en-GB', internal: { type: 'ContentfulCurriculumVitaePage', }, }, }, ], }, };
import React from 'react'; import { Grid, CircularProgress } from '@material-ui/core'; import { useSelector } from 'react-redux'; import Order from './Order/Order'; import useStyles from './styles'; const Orders = ({ setCurrentId }) => { const orders = useSelector((state) => state.orders); const classes = useStyles(); return ( !orders.length ? <CircularProgress /> : ( <Grid className={classes.container} container alignItems="stretch" spacing={3}> {orders.map((order) => ( <Grid key={order._id} item xs={12} sm={6} md={6}> <Order order={order} setCurrentId={setCurrentId} /> </Grid> ))} </Grid> ) ); }; export default Orders;
import ChampionCard from "../ChampionCard/ChampionCard"; import styles from "./ChampionsList.Module.scss"; const ChampionsList = ({ champions }) => { const champList = champions.map((champ) => ( <ChampionCard key={champ.id} champion={champ} /> )); return <ul className={styles.container}>{champList}</ul>; }; export default ChampionsList;
import React, {Fragment} from 'react'; import {useDispatch} from 'react-redux'; import {deleteAsset} from '../../actions/assetActions'; const Asset = ({asset, showDelete}) => { const dispatch = useDispatch(); const assetData = asset.asset; const assetHeaders = ( <Fragment> <thead> <tr> <th className="text-left py-3 px-5 bg-green-300 font-bold uppercase text-sm text-white border-green-800">Asset Name</th> <th className="text-left py-3 px-5 bg-green-300 font-bold uppercase text-sm text-white border-green-800">Value ($)</th> {showDelete === 0 ? <th className="text-left py-3 px-5 bg-green-300 font-bold uppercase text-sm text-white border-green-800">&nbsp;</th> : null} </tr> </thead> </Fragment> ) let contentLoaded = ''; if(assetData.length > 0){ contentLoaded = ( <Fragment> <tbody> {assetData.map(({_id, description_text, asset_number}) => ( <tr key={_id} className="hover:bg-gray-100"> <td className="text-left py-2 px-4 border-b border-gray-500">{description_text}</td> <td className="text-left py-2 px-4 border-b border-gray-500">${parseFloat(asset_number).toFixed(2)}</td> {showDelete === 0 ? <td className="text-left py-2 px-4 border-b border-gray-500"><button className="text-gray-200 font-bold py-1 px-3 rounded text-xs bg-red-500 hover:bg-red-700 outline-none focus:outline-none" onClick={() => dispatch(deleteAsset(_id))}>Delete</button></td> : null} </tr> ))} </tbody> </Fragment> ) } else { contentLoaded = ( <Fragment> <tbody> <tr className="hover:bg-gray-100"> <td colSpan={showDelete === 0 ? 3 : 2} className="text-center py-2 px-4 border-b border-gray-500">NO RECORDS FOUND</td> </tr> </tbody> </Fragment> ) } return ( <Fragment> {assetHeaders} {contentLoaded} </Fragment> ) } export default Asset;
$(function() { $(".change-devoured").on("click", function(event) { console.log($(this)); var id = $(this).attr("id"); var newDevoured = $(this).attr("data-newDevoured"); var newState = { devoured: newDevoured }; //send PUT req $.ajax("/api/burgers/" + id, { type: "PUT", data: newState }).then(function() { console.log("the burger is now" + newDevoured); location.reload(); }); }); $(".create-form").on("submit", function(event) { event.preventDefault(); console.log($("#burgerAdd").val()); var newBurger = { burger_name: $("#burgerAdd").val(), devoured: false }; $.ajax("/api/burgers", { type: "POST", data: newBurger }).then(function() { console.log("created a new burger"); location.reload(); }); }); });
import {Component, ChangeDetectionStrategy} from '/ui/web_modules/@angular/core.js'; import {FormGroup, FormControl} from "/ui/web_modules/@angular/forms.js"; import {UIRouter} from "/ui/web_modules/@uirouter/angular.js"; import {pluck, take, filter, switchMap, switchMapTo, map, shareReplay, takeUntil} from '/ui/web_modules/rxjs/operators.js'; import {combineLatest, Subject, timer} from "/ui/web_modules/rxjs.js"; import {equals, compose, not} from "/ui/web_modules/ramda.js"; import {NgbModal} from "/ui/web_modules/@ng-bootstrap/ng-bootstrap.js"; import {MnLifeCycleHooksToStream} from './mn.core.js'; import {MnCollectionsService} from './mn.collections.service.js'; import {MnPermissionsService} from './mn.permissions.service.js'; import {MnBucketsService} from './mn.buckets.service.js'; import {MnCollectionsAddScopeComponent} from './mn.collections.add.scope.component.js'; import {MnCollectionsAddItemComponent} from './mn.collections.add.item.component.js'; export {MnCollectionsComponent}; class MnCollectionsComponent extends MnLifeCycleHooksToStream { static get annotations() { return [ new Component({ templateUrl: "/ui/app/mn.collections.html", changeDetection: ChangeDetectionStrategy.OnPush }) ]} static get parameters() { return [ MnCollectionsService, MnPermissionsService, MnBucketsService, UIRouter, NgbModal ]} constructor(mnCollectionsService, mnPermissionsService, mnBucketsService, uiRouter, modalService) { super(); var clickAddScope = new Subject(); var clickAddCollection = new Subject(); var bucketSelect = new FormGroup({ name: new FormControl() }); var setBucket = (v) => bucketSelect.patchValue({name: v}); var setBucketUrlParam = (v) => uiRouter.stateService.go('.', {collectionsBucket: v.name}, {notify: false}); var filterBuckets = ([buckets, permissions]) => Object .keys(buckets) .filter(bucketName => permissions[`cluster.bucket[${bucketName}].collections!read`] && buckets[bucketName].bucketType !== "memcached"); var getBuckets = combineLatest(mnBucketsService.stream.getBucketsByName, mnPermissionsService.stream.getBucketsPermissions) .pipe(map(filterBuckets)); var getBucketUrlParam = uiRouter.globals.params$.pipe(pluck("collectionsBucket")) getBucketUrlParam .pipe( filter(equals(undefined)), switchMapTo(getBuckets), pluck(0), take(1)) .subscribe(setBucket); getBucketUrlParam .pipe(filter(compose(not, equals(undefined))), take(1)) .subscribe(setBucket); bucketSelect.valueChanges .pipe(takeUntil(this.mnOnDestroy)) .subscribe(setBucketUrlParam); var manifest = combineLatest(getBucketUrlParam, mnCollectionsService.stream.updateManifest, timer(0, 5000)) .pipe(switchMap(([bucket]) => mnCollectionsService.getManifest(bucket)), shareReplay({refCount: true, bufferSize: 1})); clickAddScope .pipe(takeUntil(this.mnOnDestroy)) .subscribe(() => { var ref = modalService.open(MnCollectionsAddScopeComponent); ref.componentInstance.bucketName = bucketSelect.get("name").value; }); clickAddCollection .pipe(takeUntil(this.mnOnDestroy)) .subscribe(() => { var ref = modalService.open(MnCollectionsAddItemComponent); ref.componentInstance.bucketName = bucketSelect.get("name").value; }); this.buckets = getBuckets; this.bucketSelect = bucketSelect; this.manifest = manifest; this.clickAddScope = clickAddScope; this.clickAddCollection = clickAddCollection; } trackByFn(_, scope) { return scope.name; } }