text
stringlengths
7
3.69M
import { createMachine, assign, send, spawn } from 'xstate'; import { mapMachine } from './map.machine'; import { logMachine } from './log.machine'; const context = { logMachine: undefined, mapMachine: undefined, userPosition: { lat: null, lng: null, }, } // Tell map.machine and log.machine each time the location changes? export const appMachine = createMachine({ id: 'app', // initial: 'pending', context, entry: ['spawnActors'], on: { LOG: { actions: ['forwardLogEvent'] }, POSITION_CHANGE: { actions: ['updateUserPosition', 'updateMap'] }, }, states: {}, }, { actions: { updateMap: send( (ctx) => ({ type: 'UPDATE_USER_POSITION', userPosition: ctx.userPosition, }), { to: 'mapMachine' } ), updateUserPosition: assign({ userPosition: (ctx, e) => ({ lat: e.coords.latitude, lng: e.coords.longitude, }) }), forwardLogEvent: send( (ctx, e) => ({ ...e, item: { ...e.item, userPosition: ctx.userPosition, } }), { to: 'logMachine' } ), forwardLogMachineEvent: send( (ctx, e) => e, { to: 'logMachine' } ), forwardMapMachineEvent: send( (ctx, e) => e, { to: 'mapMachine' } ), spawnActors: assign({ logMachine: () => spawn(logMachine, 'logMachine'), mapMachine: () => spawn(mapMachine, 'mapMachine'), }), updateUserPosition: assign({ userPosition: (ctx, e) => { return { lat: e.coords.latitude, lng: e.coords.longitude, } } }), }, });
function ListNode(val) { this.val = val; this.next = null; } var addTwoNumbers = function(l1, l2) { let head, node, isCarry; while (l1 || l2) { let sum, next; if (l1 && l2) { sum = l1.val + l2.val; } else if (l1) { sum = l1.val; } else { sum = l2.val; } if (isCarry) { sum += 1; } isCarry = sum >= 10; next = new ListNode(isCarry ? sum - 10 : sum); if (!head) { head = next; node = head; } else { node.next = next; } node = next; l1 = l1 && l1.next; l2 = l2 && l2.next; } if (isCarry) { node.next = new ListNode(1); } return head; }; module.exports = { ListNode, addTwoNumbers };
'use strict'; var ifbCommonServices = angular.module("ifbCommonServices", []); var ifbControllers = angular.module("ifbControllers", []); // Declare app level module which depends on views, and components angular.module('companyFace', ['ui.router', 'angularModalService', 'cgBusy', 'ifbCommonServices', 'ifbControllers', 'ngResource', 'ngDialog']) .constant('_', window._) .constant('baseURL', 'http://localhost:3000') .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('app', { url: '/', views: { 'header': { templateUrl: 'views/header.html' }, 'content': { templateUrl: 'modules/persons/personList.html', controller: 'PersonListController as ctl' }, 'footer': { templateUrl: 'views/footer.html' } } }) .state('app.search', { url: 'search', views: { 'content@': { templateUrl: 'modules/search/search.html', controller: 'SearchController as ctl' } } }); $urlRouterProvider.otherwise('/'); });
import React, {Component} from 'react'; import { StyleSheet, Text, View, ToolbarAndroid, Image, ScrollView, TextInput , TouchableOpacity } from 'react-native'; class Login extends Component { render(){ return ( <View style={styles.container}> <ToolbarAndroid style={styles.toolbar} titleColor= "#ffffff" title="Stutech" /> <ScrollView contentContainerStyle={styles.scrollContainer}> <Image style={{width: 200, height: 180}} source={require('../images/app_logo.png')} /> <Text>{"\n"}</Text> <TextInput style={{width: 300, borderBottomColor:'#14c2e0', borderWidth: 2, borderTopColor:'#fff', borderLeftColor:'#fff', borderRightColor:'#fff'}} placeholder="Enter Email" /> <Text>{"\n"}</Text> <TextInput style={{width: 300, borderBottomColor:'#14c2e0', borderWidth: 2, borderTopColor:'#fff', borderLeftColor:'#fff', borderRightColor:'#fff'}} placeholder="Enter Password" /> <Text>{"\n"}</Text> <TouchableOpacity style={styles.button} onPress={() => this.props.navigation.navigate('StudentNewsFeed')} > <Text> Submit </Text> </TouchableOpacity> <Text>{"\n"}</Text> <Text>Don't have an account yet ?<Text style={{color:'#14c2e0'}} onPress={() => this.props.navigation.navigate('Signup1')} > Click Here</Text> </Text> <Text>{"\n"}</Text> <Text>{"\n"}</Text> </ScrollView> </View> ); } } export default Login; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', marginTop: 24, justifyContent: 'flex-start', }, button: { alignItems: 'center', backgroundColor: '#14c2e0', width: 200, padding: 10 }, toolbar: { backgroundColor: '#14c2e0', height: 56, alignSelf: 'stretch', }, scrollContainer: { alignItems: 'center', backgroundColor: '#fff', width: '100%', marginTop: 24, }, });
import React, { useState, useEffect } from 'react'; import './App.css'; import './grid.css'; function App() { return ( <div> <DrumMachine /> </div> ); } const DrumMachine = () => { const keyArray1 = [ { "Q": "Piano Chord 1", "src": "https://s3.amazonaws.com/freecodecamp/drums/Chord_1.mp3" }, { "W": "Piano Chord 2", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Chord_2.mp3' }, { "E": "Piano Chord 3", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3' }, { "A": "HiHat", "src": "https://raw.githubusercontent.com/wazebase/drum-machine/master/01%20HHclosed08.wav" }, { "S": "Snare", "src": "https://raw.githubusercontent.com/wazebase/drum-machine/master/2Pac%20Snare3.wav" }, { "D": "Bass", "src": "https://raw.githubusercontent.com/wazebase/drum-machine/master/808LONG'.WAV" }, { "Z": "Shaker", "src": "https://raw.githubusercontent.com/wazebase/drum-machine/master/50%20Cent%20Shaker%201.wav" }, { "X": "Kick", "src": "https://raw.githubusercontent.com/wazebase/drum-machine/master/50%20dre%20kick.wav" }, { "C": "Flick", "src": "https://raw.githubusercontent.com/wazebase/drum-machine/master/50%20flick.wav" }]; const keyArray2 = [{ "Q": "Heater-1", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3' }, { "W": "Heater-2", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3' }, { "E": "Heater-3", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3' }, { "A": "Heater-4", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3' } , { "S": "Clap", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3' }, { "D": 'Open-HH', "src": 'https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3' }, { "Z": "Kick-n'-Hat", "src": 'https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3' }, { "X": 'Kick', "src": 'https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3' }, { "C": 'Closed-HH', "src": 'https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3' }]; const [padName, setPadName] = useState("Drum kit 1"); const [keys, setKeys] = useState(keyArray1); const [keysChange, setKeysChange] = useState(false); const [volume, setVolume] = useState(50); useEffect(() => { if (keysChange) { setPadName("Drum kit 2"); setKeys(keyArray2); } if (!keysChange) { setPadName("Drum kit 1"); setKeys(keyArray1); } }, [keysChange]) document.addEventListener('keydown', function (key) { let padKey = key.key.toUpperCase(); if (["Q", "W", "E", "A", "S", "D", "Z", "X", "C"].includes(padKey)) { handlePlay(padKey); } }) const handlePlay = (padKey) => { handleColor(padKey); let newPadName; keys.map(obj => { if (Object.keys(obj)[0] === padKey) { newPadName = obj[padKey]; } }) setPadName(newPadName); let music = document.getElementById(padKey); if (music.currentTime > 0) { music.pause(); music.currentTime = 0; } music.volume = volume / 100; music.play(); } const handleColor = (padKey) => { let pad = document.getElementById("div-" + padKey); pad.style.backgroundColor = "rgba(0, 171, 238,0.7)"; pad.style.marginTop = "3px"; setTimeout(() => { pad.style.backgroundColor = "rgb(44, 32, 97)";; pad.style.boxShadow = '3px 3px 5px black'; pad.style.marginTop = "0px"; }, 200); } const handleVolumeChange = (currentVolume) => { setPadName("Volume:" + currentVolume); setVolume(currentVolume); } return ( <div id="drum-machine"> <div id="display">{padName}</div> <div class="slidecontainer"> <input type="range" min="1" max="100" value={volume} class="slider" id="volume_slider" onChange={() => handleVolumeChange(document.getElementById("volume_slider").value)} /> </div> <button id="bank" onClick={() => setKeysChange(!keysChange)}>Change bank</button> <div id="pads"> <DrumPad padKey={"Q"} src={keys[0]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"W"} src={keys[1]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"E"} src={keys[2]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"A"} src={keys[3]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"S"} src={keys[4]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"D"} src={keys[5]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"Z"} src={keys[6]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"X"} src={keys[7]["src"]} handlePlay={handlePlay} /> <DrumPad padKey={"C"} src={keys[8]["src"]} handlePlay={handlePlay} /> </div> </div> ); } const DrumPad = (props) => { return ( <div className="drum-pad" id={"div-" + props.padKey} onClick={() => props.handlePlay(props.padKey)}> <audio id={props.padKey} className="clip" src={props.src} /> {props.padKey} </div> ); } export default App;
import React from 'react'; const Navigation = () => ( <div className="navigation"> <input type="checkbox" className="navigation__checkbox" id="navi-toggle" /> <label for="navi-toggle" className="navigation__button"> <span className="navigation__icon">&nbsp;</span> </label> <div className="navigation__background" /> <nav className="navigation__nav"> <ul className="navigation__list"> <li className="navigation__item"> <a href="#profile-section" className="navigation__link">Profile</a> </li> <li className="navigation__item"> <a href="#academic-section" className="navigation__link"> Qualifications </a> </li> <li className="navigation__item"> <a href="#courses-section" className="navigation__link">Courses</a> </li> <li className="navigation__item"> <a href="#publication-section" className="navigation__link"> Publications </a> </li> <li className="navigation__item"> <a href="#contact-section" className="navigation__link">Contact Me</a> </li> </ul> </nav> </div> ); export default Navigation;
#pragma strict function StartMenu(){ Application.LoadLevel("Keys"); }
///TODO: Review /** * @param {number[]} nums * @param {number} k * @return {boolean} */ var checkSubarraySum = function(nums, k) { for(let i = 0; i<nums.length; i++) { var sum = nums[i]; for(let j = i+1; j < nums.length; j++) { sum += nums[j]; if(sum === k) return true; if(k !== 0 && sum % k === 0) return true; } } return false; };
var Stack = function() { this.top = null } Stack.createNode = function(data) { data = (typeof data === 'undefined') ? null : data return { data: data, next: null } } Stack.prototype.push = function(data) { var node = Stack.createNode(data) node.next = this.top this.top = node } Stack.prototype.pop = function() { var node = this.top if (node !== null) { this.top = this.top.next } return node } Stack.prototype.length = function() { var length = 0 , current = this.top while (current) { length++ current = current.next } return length } Stack.prototype.isEmpty = function() { return this.top === null } Stack.prototype.peek = function() { return this.top } Stack.prototype.toArray = function() { var result = [] , current = this.top while (current) { result.push(current.data) current = current.next } return result } Queue = function() { this.head = null this.tail = null } Queue.prototype.enqueue = function(data) { var node = Stack.createNode(data) if (this.head === null) { this.head = this.tail = node } else { this.tail = this.tail.next = node } } Queue.prototype.dequeue = function() { var node = this.head if (node) { this.head = this.head.next } return node } module.exports = { Stack: Stack, Queue: Queue }
const managesModel = require("./manages.model"); module.exports = { create:(data)=>{ return managesModel.create(data); }, getManageByMobile:(mob)=>{ return managesModel.find(); }, getManageByWebsite:(web,mob,key)=>{ return managesModel.find({mWebsite:web,mMobile:mob,mKey:key}); }, checkHost:(host,flag)=>{ return managesModel.findOne({mWebsite:host,mFlag:flag}); }, getManageLogin:(web,email)=>{ return managesModel.findOne({mWebsite:web,mEmail:email}); }, checkManage:(web,key,flag)=>{ return managesModel.findOne({mWebsite:web,mKey:key,mFlag:flag}); } }
import React, { useContext } from "react"; import { Modal, ModalHeader, ModalBody, ModalFooter, Button, Input, Form, Label, } from "reactstrap"; import { StateContext } from "./contexts/StateContext"; function HeaderModal() { const { wordsPerLight, setWordsPerLight, modal, setModal } = useContext( StateContext ); const dismiss = () => setModal(false); const updateWordsPerLight = (e) => setWordsPerLight(parseInt(e.target.value)); const startWritingChallenge = (e) => { e.preventDefault(); // remove the modal from the view dismiss(); // focus the cursor inside the word editor document.querySelector("div[contentEditable]").focus(); }; return ( <div className="header-modal"> <Modal className="mymuse-modal" isOpen={modal} modalTransition={{ timeout: 300 }} backdropTransition={{ timeout: 300 }} > <ModalHeader> <h6>Welcome, Writer! </h6> </ModalHeader> <ModalBody> There are 10 lights that you need to power on by the pure, unstoppable magic of your written words! <Form id="start-challenge" onSubmit={startWritingChallenge}> <Label>How many words will it take to power one light?</Label> <Input type="number" value={wordsPerLight} onChange={updateWordsPerLight} /> </Form> If you're struggling to get any writing done, it is recommended to choose a low number like 50 or 25, and once you have powered on all ten lights just start a new session. <br /> <br /> NOTE: as of now, this app has no backend, which means your words are not saved anywhere. You MUST copy your words at the end of each session and save them somewhere else. </ModalBody> <ModalFooter> <Button className="mymuse-modal-button" type="submit" form="start-challenge" color="success" > start </Button> <Button className="mymuse-modal-button" onClick={dismiss}> dismiss </Button> </ModalFooter> </Modal> </div> ); } export default HeaderModal;
var app = angular.module('predix_redis_login',[]); app.service('loginFormSubmit',function($http){ this.loginHandler = function(serv_instance_name,password) { return $http({ method : 'POST', url : '/login', data: {'serv_instance_name':serv_instance_name,'password':password} }).then(function Success(response) { console.log(JSON.stringify(response)); return 'success'; },function Error(response) { return 'error'; }); } }); app.controller('login', function($scope,$http,loginFormSubmit) { $scope.user = {}; $scope.loginAlert = {'display':'none'}; $scope.spinner_state = true; $scope.overlay_style = {'display':'none'}; $scope.formValidation = function(){ if($scope.user['serv_instance_name'] === undefined) { $scope.serv_instance_name_validation = 'validation-error'; } else { $scope.serv_instance_name_validation = ''; } if($scope.user['password'] === undefined) { $scope.password_validation = 'validation-error'; } else { $scope.password_validation = ''; } }; $scope.formSubmit = function(){ if($scope.loginForm.$valid) { $scope.overlay_style = {'display':''}; $scope.spinner_state = false; var response = loginFormSubmit.loginHandler($scope.user['serv_instance_name'],$scope.user['password']); response.then(function(data) { $scope.overlay_style = {'display':'none'}; switch(data) { case 'success' :console.log('logged in'); window.location.href = '/dashboard'; break; case 'error': $scope.loginAlert = {'display':''}; $scope.serv_instance_name_validation = 'validation-error'; $scope.password_validation = 'validation-error'; break; } }); } else { $scope.formValidation(); } } });
/* * @lc app=leetcode.cn id=680 lang=javascript * * [680] 验证回文串 II */ // @lc code=start /** * @param {string} s * @return {boolean} */ var validPalindrome = function (s) { let left = 0, right = s.length - 1; const isPalindrome = (s, l, r) => { while (l < r) { if (s[l++] !== s[r--]) { return false; } } return true; }; while (left < right) { if (s[left] !== s[right]) { return ( isPalindrome(s, left + 1, right) || isPalindrome(s, left, right - 1) ); } left++; right--; } return true; }; // @lc code=end
'use strict'; var _ = require('lodash'); var knex = require('../../connection.js'); var mocks = require('./fixtures/changesets.js'); var XML = require('../../services/xml.js'); var log = require('../../services/log.js'); var Node = require('./helpers/create-node.js'); var Way = require('./helpers/create-way.js'); var Relation = require('./helpers/create-relation.js'); var Change = require('./helpers/create-changeset.js'); var Area = require('./helpers/create-area'); var serverTest = require('./helpers/server-test'); var testChangeset = new serverTest.testChangeset(); // Changeset Id. Shortcut for easy access. var cid = null; function makeNodes(changesetId, ii) { var nodes = []; for (var i = 0; i < ii; ++i) { nodes.push(new Node({ id: -(i+1), changeset: changesetId })); } return nodes; } describe('Area helper functions', function () { it.skip('Test helper creates properly formed areas', function () { var nodes = makeNodes(1, 10); var area = new Area().nodes(nodes); var nd = area.entity.nd; // Length of node references is one more than total existant nodes nd.should.have.lengthOf(11); // Last node should be first node nd[0].ref.should.equal(nd[nd.length-1].ref); // Should have key/value of area: true area.entity.tag[0].k.should.equal('area'); area.entity.tag[0].v.should.equal(true); }); }); describe('changeset upload endpoint', function() { after(function (done) { testChangeset.remove() .then(function () { return done(); }) .catch(done); }); before('Create changeset', function (done) { testChangeset.create() .then(function (changesetId) { cid = changesetId; return done(); }) .catch(done); }); var cs = new Change(); beforeEach(function() { cs.wipe(); }); it('Creates 1 node', function(done) { cs.create('node', new Node({changeset: cid})); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); it('Creates 500 nodes', function(done) { var nodes = makeNodes(cid, 500); cs.create('node', nodes); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); it('Creates 1 node and 1 node tag', function(done) { cs.create('node', new Node({changeset: cid}).tags({k: 'howdy', v: 'test'})); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); it('Creates 1 way with 500 nodes and 50 tags', function(done) { var nodes = makeNodes(cid, 500); var way = new Way({changeset: cid}).nodes(nodes); for (var i = 0; i < 50; ++i) { way.tags({ k: 'happy' + i, v: 'testing' + i }); } cs.create('node', nodes).create('way', way); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); it('Creates 5 ways with 500 nodes', function(done) { var nodes = makeNodes(cid, 500); var ways = [ new Way({ id: -1, changeset: cid }).nodes(nodes.slice(0,100)), new Way({ id: -2, changeset: cid }).nodes(nodes.slice(101,200)), new Way({ id: -3, changeset: cid }).nodes(nodes.slice(201,300)), new Way({ id: -4, changeset: cid }).nodes(nodes.slice(301,400)), new Way({ id: -5, changeset: cid }).nodes(nodes.slice(401,499)) ]; cs.create('node', nodes).create('way', ways); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); it('Creates 5 nodes, 1 way, and 1 relation', function(done) { var nodes = makeNodes(cid, 5); var way = new Way({changeset: cid}).nodes(nodes); var relation = new Relation({changeset: cid}).members('node', nodes).members('way', way); cs.create('node', nodes).create('way', way).create('relation', relation); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); it('Modifies 1 node', function(done) { knex('current_nodes').where('changeset_id', cid).then(function(nodes) { nodes[0].changeset = cid; cs.modify('node', new Node(nodes[0])); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Modifies up to 50 nodes', function(done) { knex('current_nodes').where('changeset_id', cid).then(function(nodes) { var newNodes = []; var modified = 0; nodes = nodes.slice(0,50); nodes.forEach(function(node) { if (node) { node.changeset = cid; modified += 1; newNodes.push(new Node(node)); } }); log.info('Modifying ' + modified + ' nodes'); cs.modify('node', newNodes); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Creates 500 nodes, Modifies a way with 500 nodes', function(done) { knex('current_ways').where('changeset_id', cid).then(function(ways) { var nodes = makeNodes(cid, 500); ways[0].changeset = cid; var way = new Way(ways[0]).nodes(nodes); cs.create('node', nodes).modify('way', way); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Creates 500 nodes, modifies up to 10 ways', function(done) { knex('current_ways').where('changeset_id', cid).then(function(ways) { ways = ways.slice(0,10); var nodes = makeNodes(cid, 500); var newWays = []; var modified = 0; ways.forEach(function(way) { if (way) { modified += 1; way.changeset = cid; newWays.push(new Way(way).nodes(nodes)); } }); log.info('Modifying ' + modified + ' ways'); cs.create('node', nodes).modify('way', newWays); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Modifies a relation', function(done) { knex('current_relations').where('changeset_id', cid).then(function(relations) { var nodes = makeNodes(cid, 150); var relation = new Relation({ id: relations[0].id, changeset: cid}).members('node', nodes); cs.create('node', nodes).modify('relation', relation); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Deletes 1 node', function(done) { knex('current_nodes').where('changeset_id', cid).then(function(nodes) { cs.delete('node', new Node(nodes[0])); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Deletes 1 way', function(done) { knex('current_ways').where('changeset_id', cid).then(function(ways) { cs.delete('node', new Way(ways[0])); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Deletes up to 500 nodes', function(done) { knex('current_nodes').where('changeset_id', cid).then(function(nodes) { nodes = nodes.slice(0, 500); cs.delete('node', nodes); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Deletes 1 relation', function(done) { knex('current_relations').where('changeset_id', cid).then(function(relations) { relations = relations[0]; cs.delete('relation', relations); testChangeset.upload(cs.get()) .then(function(res) { return done(); }) .catch(done); }); }); it('Increments the number of changes', function(done) { knex('changesets').where('id', cid).then(function(changeset) { var nodes = makeNodes(cid, 15); var way = new Way({changeset: cid}).nodes(nodes); var relation = new Relation({changeset: cid}).members('node', nodes); cs.create('node', nodes); cs.create('way', way); cs.create('relation', relation); testChangeset.upload(cs.get()) .then(function(res) { var oldChanges = changeset[0].num_changes; var newChanges = res.result.changeset.num_changes; (newChanges).should.be.equal(oldChanges + 15 + 1 + 1); done(); }) .catch(done); }); }); it('Returns the modified IDs of newly-created elements', function(done) { var nodes = makeNodes(cid, 3); var way = new Way({changeset: cid}).nodes(nodes); var relation = new Relation({changeset: cid}).members('node', nodes); cs.create('node', nodes); cs.create('way', way); cs.create('relation', relation); testChangeset.upload(cs.get()) .then(function(res) { var created = res.result.created; created.node.should.have.property('-3'); created.way.should.have.property('-1'); created.relation.should.have.property('-1'); done(); }) .catch(done); }); });
import InvoiceTmp from './base'; export default InvoiceTmp;
const user = require('../models/user'); const loginRoute = require('./loginRoute'); const signinRoute= require('./signupRoute'); const chatRoute= require('./chatRoute'); const middleware = require("../middlewares/middlewres"); const multer = require('multer') const upload = multer({ dest: './public/uploads/' }) const room = require('../models/room'); const passport = require('passport'); const { isValidObjectId } = require('mongoose'); const session = require('express-session'); function route (app){ //test app.get('/test',(req, res)=>{ app.use(session({ secret: 'cats', resave: false, saveUninitialized: true, })) res.send("hahah"); }) app.post('/upload', upload.single('avatar'), (req, res, next)=>{ const avatar = req.body.avatar = req.file.path.split('/').slice(1).join('/'); console.log(req.file.path); console.log(avatar); const _id = req.body._id; console.log(avatar, _id); user.findById(_id).then(result=>{ result.avatar = avatar; result.save(); }).then(()=>{ res.redirect('/'); }) // const test3= new test({ // name: "beta", // avatar: req.body.avatar // }); // test3.save().then((result)=>{ // test.findOne({name: 'test3'}).then((result)=>{ // res.send(`<img = src=${result.avata}>`); // }) // }); }); app.get( '/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }) ); app.get( '/auth/google/callback', passport.authenticate('google', { session: false, failureRedirect: '/signup' }), function(req, res) { if(req.user != null){ const _id = req.user.id; const name = req.user.name.familyName +" "+req.user.name.givenName; const email = req.user.email; user.findOne({email: email}).then(result=>{ if(result == null){ user.create({ name: name, email: email, keys: generateKeywords(name.toLowerCase()), password: 'temppass' }).then(()=>{ user.findOne({email: email}).then(result=>{ if(result){ const cookie = result._id+"/"+result.password; res.cookie('user_id', cookie, { expires: new Date(Date.now() + 72*60*60*1000) /*,httpOnly: true */ }); res.redirect('/'); return; } }); }); }else{ user.findOne({email: email}).then(result=>{ if(result){ const cookie = result._id+"/"+result.password; res.cookie('user_id', cookie, { expires: new Date(Date.now() + 60*60*1000) /*,httpOnly: true */ }); res.redirect('/'); return; }else{ res.redirect('/signup'); } }) } }) } }) // app.get( '/auth/google/callback', // passport.authenticate( 'google', { // successRedirect: '/signup', // failureRedirect: '/login' // })); app.use('/signup', signinRoute); app.use('/login',loginRoute); app.use('/',middleware.auth, chatRoute); } module.exports = route; const generateKeywords = (displayName) => { // liet ke tat cac hoan vi. vd: name = ["David", "Van", "Teo"] // => ["David", "Van", "Teo"], ["David", "Teo", "Van"], ["Teo", "David", "Van"],... const name = displayName.split(' ').filter((word) => word); const length = name.length; let flagArray = []; let result = []; let stringArray = []; /** * khoi tao mang flag false * dung de danh dau xem gia tri * tai vi tri nay da duoc su dung * hay chua **/ for (let i = 0; i < length; i++) { flagArray[i] = false; } const createKeywords = (name) => { const arrName = []; let curName = ''; name.split('').forEach((letter) => { curName += letter; arrName.push(curName); }); return arrName; }; function findPermutation(k) { for (let i = 0; i < length; i++) { if (!flagArray[i]) { flagArray[i] = true; result[k] = name[i]; if (k === length - 1) { stringArray.push(result.join(' ')); } findPermutation(k + 1); flagArray[i] = false; } } } findPermutation(0); const keywords = stringArray.reduce((acc, cur) => { const words = createKeywords(cur); return [...acc, ...words]; }, []); return keywords; };
document.addEventListener('DOMContentLoaded', () => { document.getElementById('submit').addEventListener('click', (e) => { e.preventDefault(); const username = document.getElementById('username').value; const password = document.getElementById('password').value; $.post(`${window.location.pathname}/update`, { username, password }, (res) => { if (res.success) { window.location.reload(); } else { showError(res); } }) }) }) const showError = (err) => { console.log(err); };
const { BigNumber } = require("bignumber.js"); const config = require(`./${ process.env.BOT_ENV || "prod" }-network-config.json`); /** * Returns the minimum expected value by an initiator after deducting reward for swap responder * * @param swapValue the actual swap value initiated by the user * @param rewardInBIPS reward taken by the swap responder in basis points */ module.exports.calcSwapReturn = (swapValue, rewardInBIPS) => { return new BigNumber(swapValue) .multipliedBy( new BigNumber(1).minus(new BigNumber(rewardInBIPS).div(10000)) ) .toFixed(0, 3); }; /** * constants for calculations * feePad : contains the fee padding of each asset for each pair tx fee [Y*txFee] * minTradeVolume : contains minimum volume of swaps expected of each asset for each pair, helps calculate estimated eth balance req. (no. of swaps = maxVolume/minVolume)*feePerTx*feePad */ module.exports.constants = { tokenTypes: { FA2: "fa2", FA12: "FA12", }, feePad: { "usdc/usdtz": { usdc: new BigNumber(config.pairs["usdc/usdtz"]["usdc"].feePad), usdtz: new BigNumber(config.pairs["usdc/usdtz"]["usdtz"].feePad), }, "eth/ethtz": { eth: new BigNumber(config.pairs["eth/ethtz"]["eth"].feePad), ethtz: new BigNumber(config.pairs["eth/ethtz"]["ethtz"].feePad), }, "wbtc/tzbtc": { wbtc: new BigNumber(config.pairs["wbtc/tzbtc"]["wbtc"].feePad), tzbtc: new BigNumber(config.pairs["wbtc/tzbtc"]["tzbtc"].feePad), }, "wbtc/btctz": { wbtc: new BigNumber(config.pairs["wbtc/btctz"]["wbtc"].feePad), btctz: new BigNumber(config.pairs["wbtc/btctz"]["btctz"].feePad), }, }, minTradeVolume: { "usdc/usdtz": { usdc: new BigNumber( config.pairs["usdc/usdtz"]["usdc"].minTradeVolume ).multipliedBy(10 ** 6), usdtz: new BigNumber( config.pairs["usdc/usdtz"]["usdtz"].minTradeVolume ).multipliedBy(10 ** 6), }, "eth/ethtz": { eth: new BigNumber( config.pairs["eth/ethtz"]["eth"].minTradeVolume ).multipliedBy(10 ** 18), ethtz: new BigNumber( config.pairs["eth/ethtz"]["ethtz"].minTradeVolume ).multipliedBy(10 ** 18), }, "wbtc/tzbtc": { wbtc: new BigNumber( config.pairs["wbtc/tzbtc"]["wbtc"].minTradeVolume ).multipliedBy(10 ** 8), tzbtc: new BigNumber( config.pairs["wbtc/tzbtc"]["tzbtc"].minTradeVolume ).multipliedBy(10 ** 8), }, "wbtc/btctz": { wbtc: new BigNumber( config.pairs["wbtc/btctz"]["wbtc"].minTradeVolume ).multipliedBy(10 ** 8), btctz: new BigNumber( config.pairs["wbtc/btctz"]["btctz"].minTradeVolume ).multipliedBy(10 ** 8), }, }, }; module.exports.STATE = { START: 0, DONE: 0, INITIATED: 1, RESPONSE_FOUND: 2, REFUNDED: 3, ERROR: 4, }; /** * Takes a whole no. with the original decimal count and required precision (rounded up) * @param number BigNumber compatible value * @param decimals original decimal count * @param precision required decimal places */ module.exports.convertBigIntToFloat = (number, decimals, precision) => { return new BigNumber(number) .div(new BigNumber(10).pow(decimals)) .toFixed(precision); }; /** * Returns the individual pairs from a given pair string eg. "a/b" -> ["a","b"] * * @param pairString a valid pair string eg. "a/b" * @returns individual items/assets from the pair */ module.exports.getAssets = (pairString) => { return pairString.split("/"); }; /** * Returns the counter item from a given pair string eg. ("a/b","b") -> "a" * * @param pairString a valid pair string eg. "a/b" * @param asset one of the items in the pair * @returns the other item in the pair */ module.exports.getCounterPair = (pairString, asset) => { const items = pairString.split("/"); if (items[0] !== asset) return items[0]; if (items[1] !== asset) return items[1]; throw new Error("counter pair not found"); };
const assert = require("assert"); function g() { let x = 1; return x; throw 'dead code'; } function f() { let c = 1; let a = g(); let b = 2; return a + b; } let x = f(); assert.equal(x, 3);
import nock from 'nock'; import chai, { expect } from 'chai'; import spies from 'chai-spies' chai.use(spies); import APIGateway from '../src/APIGateway'; nock.disableNetConnect(); describe('APIGateway', () => { var apiGateway = new APIGateway; describe('#requestTo', () => { context('when response is success', () => { before(() => { nock('http://remark-api.alterego-labs.com') .post('/api/v1/login', { user: { login: 'ahsdnsah' } }) .reply(200, { data: { user: { login: 'ahsdnsah' } } }); }); it('processes only success case', (done) => { apiGateway .requestTo('POST', 'login', {user: { login: 'ahsdnsah' }}) .then((response_json) => { expect(response_json).to.have.property('data'); done(); }).catch((error) => { done(error); }); }); }); context('when response is failure', () => { before(() => { nock('http://remark-api.alterego-labs.com') .post('/api/v1/login', { user: { login: 'ahsdnsah' } }) .reply(404, { data: { errors: ['User not found'] } }); }); it('processes only catch case', (done) => { apiGateway .requestTo('POST', 'login', {user: { login: 'ahsdnsah' }}) .then((response_json) => { done(new Error('Response must be processed as failure!')); }).catch((error) => { var response_json = error.response; expect(response_json.data.errors.length).to.equal(1) done(); }); }); }); }); describe('#postRequestTo', () => { it('calls requestTo with proper parameters', () => { var spy = chai.spy.on(apiGateway, 'requestTo'); apiGateway.postRequestTo('login', { login: 'aha' }); expect(spy).to.have.been.called.with('POST', 'login', {login: 'aha'}); }); }); });
/** * Created by eriy on 27.02.15. */ var TABLES = require( '../constants/tables' ); module.exports = function ( PostGre, ParentModel ) { return ParentModel.extend( { tableName: TABLES.USERS }); };
'use strict'; angular.module('myApp', ['photoLibrary']) .config(['$routeProvider', '$locationProvider', function($routeProvider, $location) { $location.html5Mode(true).hashPrefix('!'); $routeProvider. when('/home', { templateUrl: 'partials/home.html', controller: 'HomeController' }) .otherwise({redirectTo: '/home'}); }])
export const titlebarHeight = (state, height) => { state.titlebarHeight = height } export const toc = (state, toc) => { state.toc.splice(0, state.toc.length, ...toc) }
var pageSize = 25; /*******************群組管理主頁面****************************/ //群組管理Model Ext.define('gigade.PromoAmountGiftModel', { extend: 'Ext.data.Model', fields: [ { name: "id", type: "int" }, { name: "event_ids", type: "string" }, { name: "product_id", type: "int" }, { name: "category_id", type: "int" }, { name: "class_id", type: "int" }, { name: "brand_id", type: "int" }, { name: "brand_name", type: "string" }, { name: "name", type: "string" }, { name: "event_desc", type: "string" }, { name: "url_by", type: "int" }, { name: "count_by", type: "int" }, { name: "banner_image", type: "string" }, { name: "category_link_url", type: "string" }, { name: "group_name", type: "string" }, { name: "condition_id", type: "int" }, { name: "condition_name", type: "string" }, { name: "num_limit", type: "int" }, { name: "repeat", type: "bool" }, { name: "freight", type: "string" }, { name: "amount", type: "int" }, { name: "quantity", type: "int" }, { name: "deduct_welfare", type: "int" }, { name: "eventtype", type: "string" }, { name: "event_type", type: "string" }, { name: "gift_type", type: "int" }, { name: "gift_id", type: "int" }, { name: "payment", type: "string" }, { name: "payment_code", type: "string" }, { name: "devicename", type: "string" }, { name: "startdate", type: "datetime" }, { name: "enddate", type: "datetime" }, { name: "use_start", type: "datetime" }, { name: "use_end", type: "datetime" }, { name: "newactive", type: "int" }, { name: "site", type: "string" }, { name: "vendor_coverage", type: "string" }, { name: "gift_product_number", type: "string" }, { name: "freight_price", type: "string" },//運費 { name: "delivery_category", type: "string" }, { name: 'gift_mundane', type: "int" }, { name: 'bonus_state', type: 'int' }, { name: 'dollar', type: 'int' }, { name: 'dividend', type: 'int' },//紅利類型1.點2:點+金3:比率固定4:非固定 { name: 'point', type: 'int' }, { name: 'muser', type: 'int' }, { name: 'user_username', type: 'string' } ] }); var PromoAmountGiftStore = Ext.create('Ext.data.Store', { pageSize: pageSize, model: 'gigade.PromoAmountGiftModel', proxy: { type: 'ajax', url: '/PromotionsAmountGift/GetTryEatDiscountList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); //前面選擇框 選擇之後顯示編輯刪除 var sm = Ext.create('Ext.selection.CheckboxModel', { listeners: { selectionchange: function (sm, selections) { Ext.getCmp("gdGift").down('#edit').setDisabled(selections.length == 0); Ext.getCmp("gdGift").down('#remove').setDisabled(selections.length == 0); } } }); //定義ddl的數據 var DDLStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": TEXPIRED, "value": "1" }, { "txt": NOTPASTDUE, "value": "0" } ] }); //加載前先獲取ddl的值 PromoAmountGiftStore.on('beforeload', function () { Ext.apply(PromoAmountGiftStore.proxy.extraParams, { ddlSel: Ext.getCmp('ddlSel').getValue(), timestart: Ext.getCmp('timestart').getValue(), timeend: Ext.getCmp('timeend').getValue(), serchcontent: Ext.getCmp('serchcontent').getValue() }); }); function Query(x) { PromoAmountGiftStore.removeAll(); Ext.getCmp("gdGift").store.loadPage(1, { params: { ddlSel: Ext.getCmp('ddlSel').getValue(), timestart: Ext.getCmp('timestart').getValue(), timeend: Ext.getCmp('timeend').getValue(), serchcontent: Ext.getCmp('serchcontent').getValue() } }); } //頁面載入 Ext.onReady(function () { var frm = Ext.create('Ext.form.Panel', { id: 'frm', layout: 'anchor', height: 90, border: 0, bodyPadding: 10, width: document.documentElement.clientWidth, items: [ { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'combobox', editable: false, margin: '0 5 3 0', fieldLabel: OPTION, labelWidth: 60, id: 'ddlSel', store: DDLStore, displayField: 'txt', valueField: 'value', value: '0', listeners: { "select": function (combo, record) { Query(); } } }, { xtype: 'datetimefield', margin: '0 5 3 0', allowBlank: true, id: 'timestart', name: 'serchcontent', fieldLabel: PROMOSSTARTTIME, labelWidth: 100, editable: false, format: 'Y-m-d H:i:s', time: { hour: 00, min: 00, sec: 00 },//開始時間00:00:00 listeners: { select: function () { var start = Ext.getCmp("timestart"); var end = Ext.getCmp("timeend"); if (end.getValue() == null) { end.setValue(setNextMonth(start.getValue(), 1)); } else if (start.getValue() > end.getValue()) { Ext.Msg.alert(INFORMATION, "開始時間不能大於結束時間"); end.setValue(setNextMonth(start.getValue(), 1)); } //else if (end.getValue() > setNextMonth(start.getValue(), 1)) { // // Ext.Msg.alert(INFORMATION, DATE_LIMIT); // end.setValue(setNextMonth(start.getValue(), 1)); //} }, specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } } } }, { xtype: 'displayfield', value: '~', labelWidth: 20, margin: '0 10 3 7' }, { xtype: 'datetimefield', allowBlank: true, id: 'timeend', name: 'serchcontent', editable: false, time: { hour: 23, min: 59, sec: 59 },//標記結束時間23:59:59 format: 'Y-m-d H:i:s', listeners: { select: function (a, b, c) { var start = Ext.getCmp("timestart"); var end = Ext.getCmp("timeend"); var s_date = new Date(start.getValue()); var now_date = new Date(end.getValue()); if (start.getValue() != "" && start.getValue() != null) { if (end.getValue() < start.getValue()) { Ext.Msg.alert(INFORMATION, "結束時間不能小於開始時間"); start.setValue(setNextMonth(end.getValue(), -1)); }// else if (end.getValue() > setNextMonth(start.getValue(), 1)) { // //Ext.Msg.alert(INFORMATION, DATE_LIMIT); // start.setValue(setNextMonth(end.getValue(), -1)); //} } else { start.setValue(setNextMonth(end.getValue(), -1)); } }, specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } } } } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'textfield', allowBlank: true, id: 'serchcontent', name: 'serchcontent', fieldLabel: PROMOSITIONNAMECODE, labelWidth: 120, listeners: { specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(1); } } } }, { xtype: 'button', text: SEARCH, iconCls: 'ui-icon ui-icon-search-2', id: 'btnQuery', margin: '0 10 3 30', handler: Query }, { xtype: 'button', text: '重置', id: 'btn_reset', iconCls: 'ui-icon ui-icon-reset', listeners: { click: function () { frm.getForm().reset(); } } } ] } ] }); var gdGift = Ext.create('Ext.grid.Panel', { id: 'gdGift', store: PromoAmountGiftStore, columnLines: true, frame: true, viewConfig: { enableTextSelection: true, stripeRows: false, getRowClass: function (record, rowIndex, rowParams, store) { return "x-selectable"; } }, columns: [ { header: HDID, dataIndex: 'event_ids', width: 70, align: 'center', align: 'center' }, { header: ACTIVENAME, dataIndex: 'name', width: 70, align: 'center' }, { header: "活動類型", dataIndex: 'event_type', width: 70, align: 'center', renderer: function (value) { if (value == "G3") { return Ext.String.format('試吃'); } else if (value == "G4") { return Ext.String.format('紅利折抵'); } else if (value == "G0") { return Ext.String.format('一般'); } } }, { header: "紅利折抵", dataIndex: 'dividend', width: 80, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (record.data.bonus_state == 1) {//1:試吃 2:紅利折抵 return ""; } else { switch (value) { case 1: return "點"; break; case 2: return "點+金"; break; case 3: return "金"; break; case 4: return "比率固定"; break; case 5: return "非固定"; break; } } } }, { header: "運費", dataIndex: 'freight_price', width: 40, align: 'center', align: 'center' }, { header: "購物車", dataIndex: 'delivery_category', width: 80, align: 'center' }, { header: ACTIVEDESC, dataIndex: 'event_desc', width: 100, align: 'center' }, { header: ISBANNERURL, dataIndex: 'url_by', width: 60, align: 'center', renderer: Banner }, { header: BANNERIMG, dataIndex: 'banner_image', width: 90, align: 'center', xtype: 'templatecolumn', tpl: '<a target="_blank" href="{category_link_url}" ><img width=50 name="tplImg" onmousemove="javascript:imgFadeBig(this.src,250);" onmouseout = "javascript:$(\'#imgTip\').hide()" height=50 src="{banner_image}" /></a>' }, { header: GROUPNAME, dataIndex: 'group_name', width: 80, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (record.data.condition_id != 0) { return VIPCONDITION; } else { if (value == "") { return BUFEN; } else { return value; } } } }, { header: TIMELIMIT, dataIndex: 'count_by', width: 100, align: 'center', renderer: Count_byLimit }, { header: ISREPEAT, dataIndex: 'repeat', width: 100, align: 'center', renderer: ChongfuYorN }, { header: YSCLASS, dataIndex: 'freight', width: 80, align: 'center', renderer: BufenShow }, { header: PAYTYPE, dataIndex: 'payment', width: 100, align: 'center', renderer: BufenShow }, { header: PAYTYPE, dataIndex: 'payment_code', hidden: true, width: 80, align: 'center', renderer: BufenShow }, { header: DEVICE, dataIndex: 'devicename', width: 50, align: 'center', renderer: BufenShow }, { header: "限量件數", dataIndex: 'gift_mundane', width: 70, align: 'center' }, { header: START, dataIndex: 'startdate', width: 120, align: 'center' }, { header: END, dataIndex: 'enddate', width: 120, align: 'center' }, { header: 'muser', dataIndex: 'muser', hidden: true }, { header: QuanXianMuser, dataIndex: 'user_username', width: 60, align: 'center' }, { header: ISACTIVE, dataIndex: 'newactive', align: 'center', width: 60, id: 'controlactive', hidden: true, renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) { if (value == 1) { return "<a href='javascript:void(0);' onclick='UpdateActive(" + record.data.id + "," + record.data.muser + ")'><img hidValue='0' id='img" + record.data.id + "' src='../../../Content/img/icons/accept.gif'/></a>"; } else { return "<a href='javascript:void(0);' onclick='UpdateActive(" + record.data.id + "," + record.data.muser + ")'><img hidValue='1' id='img" + record.data.id + "' src='../../../Content/img/icons/drop-no.gif'/></a>"; } } } ], tbar: [ { xtype: 'button', text: ADD, id: 'add', hidden: false, iconCls: 'icon-user-add', handler: onAddClick }, { xtype: 'button', text: EDIT, id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick }, { xtype: 'button', text: REMOVE, id: 'remove', hidden: true, iconCls: 'icon-user-remove', disabled: true, handler: onRemoveClick }, '->' ], bbar: Ext.create('Ext.PagingToolbar', { store: PromoAmountGiftStore, pageSize: pageSize, displayInfo: true, displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}', emptyMsg: NOTHING_DISPLAY }), listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } }, selModel: sm }); Ext.create('Ext.container.Viewport', { layout: 'vbox', items: [frm, gdGift], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { gdGift.width = document.documentElement.clientWidth; gdGift.height = document.documentElement.clientHeight - 90; this.doLayout(); } } }); ToolAuthority(); // PromoAmountGiftStore.load({ params: { start: 0, limit: 25 } }); }); function Count_byLimit(val) { switch (val) { case 3: return BYMEMBER; break; case 2: return BYORDER; break; case 1: return NOTHING; break; } } function Banner(val) { switch (val) { case 0: return NO; break; case 1: return YES; break; } } function ChongfuYorN(val) { switch (val) { case true: return YES; break; case false: return NO; break; } } function BufenShow(val) { switch (val) { case "": return BUFEN; break; default: return val; break; } } function imgFadeBig(img, width, height) { var e = this.event; if (img.split('/').length != 5) { $("#imgTip").attr("src", img) .css({ "top": (e.clientY < height ? e.clientY : e.clientY - height) + "px", "left": (e.clientX) + "px", "width": width + "px", "height": height + "px" }).show(); } } //添加 onAddClick = function () { editFunction(null, PromoAmountGiftStore); } //修改 onEditClick = function () { var row = Ext.getCmp("gdGift").getSelectionModel().getSelection(); if (row.length == 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else if (row.length > 1) { Ext.Msg.alert(INFORMATION, ONE_SELECTION); } else if (row.length == 1) { editFunction(row[0], PromoAmountGiftStore); } } //刪除 onRemoveClick = function () { var row = Ext.getCmp("gdGift").getSelectionModel().getSelection(); if (row.length < 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else { Ext.Msg.confirm(CONFIRM, Ext.String.format(DELETE_INFO, row.length), function (btn) { if (btn == 'yes') { var rowIDs = ''; for (var i = 0; i < row.length; i++) { rowIDs += row[i].data.id + '|'; } Ext.Ajax.request({ url: '/PromotionsAmountGift/DeletePromoAmountGift', method: 'post', params: { rowID: rowIDs }, success: function (form, action) { var result = Ext.decode(form.responseText); Ext.Msg.alert(INFORMATION, SUCCESS); PromoAmountGiftStore.load(1); if (result.success) { PromoAmountGiftStore.load(1); } }, failure: function () { Ext.Msg.alert(INFORMATION, FAILURE); } }); } }); } } //更改活動狀態(設置活動可用與不可用) function UpdateActive(id, muser) { var activeValue = $("#img" + id).attr("hidValue"); $.ajax({ url: "/PromotionsAmountGift/UpdateActive", data: { "id": id, "muser": muser, "active": activeValue }, type: "POST", dataType: "json", success: function (msg) { if (msg.success == "stop") { Ext.Msg.alert("提示信息", QuanXianInfo); } else if (msg.success == "true") { PromoAmountGiftStore.removeAll(); PromoAmountGiftStore.load(); this.doLayout(); if (activeValue == 1) { $("#img" + id).attr("hidValue", 0); $("#img" + id).attr("src", "../../../Content/img/icons/accept.gif"); } else { $("#img" + id).attr("hidValue", 1); $("#img" + id).attr("src", "../../../Content/img/icons/drop-no.gif"); } } else { Ext.Msg.alert("提示信息", "更改失敗"); } }, error: function (msg) { Ext.Msg.alert(INFORMATION, EDITERROR); } }); } setNextMonth = function (source, n) { var s = new Date(source); s.setMonth(s.getMonth() + n); if (n < 0) { s.setHours(0, 0, 0); } else if (n > 0) { s.setHours(23, 59, 59); } return s; }
import * as constants from '../constants'; export const fetchAllNewSeller = () => ({ type: constants.API, payload: { method: 'GET', url: '/admin/new-seller/get-new-seller', success: (response) => (getAllNewSeller(response)) } }); export const fetchNewSellerById = (id, onSuccess, onError) => ({ type: constants.API, payload:{ method: 'GET', url: `/admin/new-seller/get-new-seller-detail/${id}`, success: (response) => (getNewSellerById(response)), postProccessSuccess: onSuccess, postProccessError: onError } }) export const acceptNewSeller = (id, onSuccess, onError) => ({ type: constants.API, payload: { method: 'POST', url: `/admin/new-seller/accept-new-seller/${id}`, id, success: (response) => (acceptAdminNewSeller(response)), postProccessSuccess: onSuccess, postProccessError: onError } }); export const rejectNewSeller = (id, onSuccess, onError) => ({ type: constants.API, payload: { method: 'POST', url: `/admin/new-seller/reject-new-seller/${id}`, id, success: (response) => (rejectAdminNewSeller(response)), postProccessSuccess: onSuccess, postProccessError: onError } }); const getAllNewSeller = (data) => ({ type: constants.ADMIN_GET_NEW_SELLER, payload: data.lists }); const getNewSellerById = (data) => ({ type: constants.ADMIN_GET_NEW_SELLER_DETAIL, payload: data.details }); const acceptAdminNewSeller = (data) => ({ type: constants.ADMIN_ACCEPT_NEW_SELLER, payload: data }); const rejectAdminNewSeller = (data) => ({ type: constants.ADMIN_REJECT_NEW_SELLER, payload: data });
const jwt = require("jsonwebtoken"); const bcrypt = require("bcryptjs"); const qrcode = require("qrcode"); const db = require("../_helpers/db"); const Role = require("../_helpers/role"); const ErrorHelper = require("../_helpers/error-helper"); const mfa = require("../_helpers/mfa"); const { User } = db; const refreshTokens = []; // const blacklistedRefreshTokens = []; async function login({ username, password }) { const user = await User.findOne({ username }); if (user && bcrypt.compareSync(password, user.hash)) { if (user.mfaEnabled) { const refreshToken = jwt.sign( { sub: user.id, role: user.role, }, process.env.REFRESHTOKENSECRET, ); return { refreshToken }; } const accessToken = jwt.sign( { sub: user.id, role: user.role }, process.env.ACCESSTOKENSECRET, { expiresIn: "25m" }, ); const refreshToken = jwt.sign( { sub: user.id, role: user.role, }, process.env.REFRESHTOKENSECRET, ); refreshTokens.push(refreshToken); const { hash, mfaSecret, ...userWithoutSecrets } = user.toObject(); return { ...userWithoutSecrets, accessToken, refreshToken, }; } throw new ErrorHelper( "Unauthorized", 401, "Username or Password is incorrect.", ); } async function verifyMfaToken(refreshToken, totp) { if (refreshTokens.includes(refreshToken)) { throw new ErrorHelper("Not Needed", 200, "Already Logged in."); } const tokenData = jwt.verify( refreshToken, process.env.REFRESHTOKENSECRET, (err, data) => { if (err) { throw new ErrorHelper( "Unauthorized", 401, "The refresh token is invalid.", ); } return { data, }; }, ); const user = await User.findById(tokenData.data.sub); const authenticated = mfa.verifyTOTP( totp, user.mfaSecret, process.env.MFAWINDOW, ); if (authenticated) { refreshTokens.push(refreshToken); const accessToken = jwt.sign( { sub: user.id, role: user.role }, process.env.ACCESSTOKENSECRET, { expiresIn: "25m" }, ); const { hash, mfaSecret, ...userWithoutSecrets } = user.toObject(); return { ...userWithoutSecrets, accessToken, refreshToken }; } throw new ErrorHelper( "Unauthorized", 401, "TOTP Token is incorrect.", ); } async function generateMfa(id) { const user = await User.findById(id); const userSecret = mfa.generateSecret(process.env.MFASECRETLENGTH); user.mfaSecret = userSecret; const otpauthurl = `otpauth://totp/LoginBackend:${user.username}?secret=${userSecret}`; const dataurl = await qrcode.toDataURL(otpauthurl); await user.save(); return { userSecret, dataurl }; } async function enableMfa(id, totp) { const user = await User.findById(id); const authenticated = mfa.verifyTOTP( totp, user.mfaSecret, process.env.MFAWINDOW, ); if (authenticated) { user.mfaEnabled = true; return user.save(); } user.mfaSecret = ""; throw new ErrorHelper( "Unauthorized", 401, "TOTP Token is incorrect. Mfa Activation process exited.", ); } async function disableMfa(id) { const user = await User.findById(id); user.mfaSecret = ""; user.mfaEnabled = false; return user.save(); } async function logout(refreshToken) { const index = refreshTokens.findIndex( (element) => element === refreshToken, ); if (index === -1) { throw new ErrorHelper( "Unauthorized", 401, "The refresh token is invalid.", ); } refreshTokens.splice(index, 1); } async function tokenRefresh(refreshToken) { if (!refreshTokens.includes(refreshToken)) { throw new ErrorHelper( "Unauthorized", 401, "The refresh token is invalid.", ); } const tokens = jwt.verify( refreshToken, process.env.REFRESHTOKENSECRET, (err, user) => { if (err) { throw new ErrorHelper( "Unauthorized", 401, "The refresh token is invalid.", ); } const accessToken = jwt.sign( { sub: user.sub, role: user.role }, process.env.ACCESSTOKENSECRET, { expiresIn: "25m" }, ); return { accessToken, refreshToken, }; }, ); return tokens; } async function getAll() { return User.find().select("-hash"); } async function getById(id) { const user = await User.findById(id).select("-hash"); if (user) { return user; } throw new ErrorHelper( "Not Found", 404, "Wrong ID or User deleted.", ); } async function create(userParam) { // look if username is free if (await User.findOne({ username: userParam.username })) { throw new ErrorHelper( "Not Unique", 500, `Username ${userParam.username} is already taken`, ); } const user = new User(userParam); // hash password if (!("role" in userParam)) { user.role = JSON.stringify(Role.User); } if (userParam.password) { user.hash = bcrypt.hashSync(userParam.password, 10); } return user.save(); } async function update(id, userParam) { const user = await User.findById(id); // validate if (user.username !== userParam.username) { if (await User.findOne({ username: userParam.username })) { throw new ErrorHelper( "Not Unique", 500, `Username ${userParam.username} is already taken`, ); } } // hash password user.hash = bcrypt.hashSync(userParam.password, 10); // copy userParam properties to user Object.assign(user, userParam); return user.save(); } async function deleter(id) { const user = await User.findByIdAndDelete(id); if (user === null) { throw new ErrorHelper( "Not Found", 404, "Wrong ID or User deleted.", ); } } module.exports = { login, verifyMfaToken, generateMfa, enableMfa, disableMfa, logout, tokenRefresh, getAll, getById, create, update, delete: deleter, };
import { CREATE_POST_REQUEST, CREATE_POST_SUCCESS, CREATE_POST_FAILURE, } from "./postActionTypes"; // create post export const createPostRequest = () => { return { type: CREATE_POST_REQUEST, }; }; export const createPostSuccess = (data) => { return { type: CREATE_POST_SUCCESS, payload: data, }; }; export const createPostFailure = (error) => { return { type: CREATE_POST_FAILURE, error: error, }; };
import React, {useState, useEffect} from 'react'; import axios from 'axios' const Home = () => { const [daftarBuku, setdaftarBuku] = useState(null) useEffect( () => { if (daftarBuku === null){ axios.get(`http://backendexample.sanbercloud.com/api/books`) .then(res => { setdaftarBuku(res.data.map(el=>{ return {id: el.id, title: el.title, description: el.description, review: el.review, release_year: el.release_year, totalPage: el.totalPage, price: el.price }} )) }) } }, [daftarBuku]) return ( <div> <section id="utama"> <h1>Daftar Buku Pilihan</h1> { daftarBuku !== null && daftarBuku.map((item, index)=>{ return( <article> <h1 style={{textAlign:"left"}}>{item.title}</h1> <div> <img src={item.image_url} style={{float:"left"}}></img> </div> <div> <h5>{item.release_year}</h5> <h5>{item.price}</h5> <h5>{item.totalPage}</h5> </div> <h5>Deskripsi: {item.description}</h5> <h5>Ulasan: {item.review}</h5> <hr></hr> </article> ) }) } <div id="article-list"> <article> <br /> <a href><h3>Lorem Post 1</h3></a> <p> Lorem Ipsum Dolor Sit Amet, mea te verear signiferumque, per illum labores ne. Blandit omnesque scripserit pri ex, et pri dicant eirmod deserunt. Aeque perpetua ea nec. Sit erant patrioque delicatissimi ut. Et sea quem sint, nam in minim voluptatibus. Etiam placerat eam in. </p> <hr /> </article> </div> </section> </div> ); } export default Home;
import React, { Component } from 'react' import { connect } from 'react-redux' import { dangKyNguoiDungAction } from '../../Redux/Actions/QuanLyNguoiDungAction'; import { NavLink } from 'react-router-dom' class SignUpPage extends Component { constructor(props) { super(props); this.state = { value: { taiKhoan: "", matKhau: "", email: "", soDt: "", maNhom: "GP14", maLoaiNguoiDung: "khachHang", hoTen: "", }, errors: { taiKhoan: "", matKhau: "", email: "", soDt: "", hoTen: "", matkhau: "", }, valid: true, matkhau: '', } } handleChange = (event) => { let name = event.target.name; let value = event.target.value; this.setState({ value: { ...this.state.value, [name]: value } }) } handleClear = () => { this.setState({ value: { taiKhoan: "", matKhau: "", email: "", soDt: "", maNhom: "GP14", maLoaiNguoiDung: "khachHang", hoTen: "", } }) document.getElementById('matkhau').value = ''; } handleError = (event) => { //dành riêng cho mật khẩu, let { name, value } = event.target; let Errors = value === '' ? 'mật khẩu không được bỏ trống !' : ''; this.setState({ errors: { ...this.state.errors, [name]: Errors } }) } handleErrors = (event) => { //xử lý lổi phần user let { name, value } = event.target; let nameInput = ''; switch (name) { case "taiKhoan": nameInput = "Tài khoản" break; case "matKhau": nameInput = "Xác nhận mật khẩu" break; case "soDt": nameInput = "Số điện thoại" break; case "email": nameInput = "Email" break; case "hoTen": nameInput = "Họ tên" break; default: break; } //xử lý trống let Errors = value === '' ? nameInput + ' không được bỏ trống!' : ''; //xử lý định dạng email if (name === 'email' && Errors === '') { let regex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; if (!regex.test(value)) { Errors = 'Email này không đúng định dạng!' } } //xử lý định dạng số điện thoại if (name === 'soDt' && Errors === '') { let regex = /^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$/; if (!regex.test(value)) { Errors = 'Số điện thoại không đúng định dạng!' } } this.state.valid = Errors !== '' ? true : false; this.setState({ errors: { ...this.state.errors, [name]: Errors } }) } handleErrorBackend = (error) => { //XỬ LÝ PHẦN ERROR BACKEND console.log(error); } submitForm = (event) => { event.preventDefault(); } render() { return ( <div className="SignUpPage container-fluid"> <div className="SignUpPage_left"> </div> <div className="SignUpPage_right"> <div className="form-content"> <h3 className="form-content_title">ĐĂNG KÝ</h3> <form onSubmit={this.submitForm}> <div className="form-group"> <label htmlFor="exampleInputEmail1">Tài Khoản</label> <input type="text" onKeyUp={this.handleErrors} onBlur={this.handleErrors} className="form-control" id="taiKhoan" onChange={this.handleChange} value={this.state.value.taiKhoan} name='taiKhoan' placeholder="Nhập vào tài khoản" /> <div className='alert'>{this.state.errors.taiKhoan}</div> </div> <div className="form-group"> <label htmlFor="exampleInputEmail1">Mật khẩu</label> <input type="password" onKeyUp={this.handleError} onBlur={this.handleError} className="form-control" id="matkhau" placeholder="Nhập vào mật khẩu" /> <div className="alert">{this.state.errors.matkhau}</div> </div> <div className="form-group"> <label htmlFor="exampleInputEmail1">Nhập lại mật khẩu</label> <input type="password" onKeyUp={this.handleErrors} onBlur={this.handleErrors} className="form-control" id="matKhau" onChange={this.handleChange} value={this.state.value.matKhau} name='matKhau' placeholder="Nhập lại vào mật khẩu" /> <div className="alert">{this.state.errors.matKhau}</div> </div> <div className="form-group"> <label htmlFor="exampleInputEmail1">Họ tên</label> <input type="text" onKeyUp={this.handleErrors} onBlur={this.handleErrors} className="form-control" id="hoTen" onChange={this.handleChange} value={this.state.value.hoTen} name='hoTen' placeholder="Nhập vào họ tên" /> <div className="alert">{this.state.errors.hoTen}</div> </div> <div className="form-group"> <label htmlFor="exampleInputEmail1">Email</label> <input type="email" onKeyUp={this.handleErrors} onBlur={this.handleErrors} className="form-control" id="email" onChange={this.handleChange} value={this.state.value.email} name='email' placeholder="Nhập vào email" /> <div className="alert">{this.state.errors.email}</div> </div> <div className="form-group"> <label htmlFor="exampleInputPassword1">Số điện thoại</label> <input type='text' onKeyUp={this.handleErrors} onBlur={this.handleErrors} className="form-control" id="soDt" onChange={this.handleChange} value={this.state.value.soDt} name='soDt' placeholder="Nhập vào số điện thoại" /> <div className="alert">{this.state.errors.soDt}</div> </div> <button onClick={() => { this.props.dangKyNguoiDung(this.state.value, this.handleClear) }} className="button_sign_up"> <p className='button_sign_up_css'>Đăng ký</p> </button> <button className="button_login"> <NavLink to="/dangnhap"><p className="button_sign_in_css">Đăng Nhập</p></NavLink> </button> </form> </div> </div> </div> ) } } const mapStateToProp = state => { return { } } const mapDispatchToProps = (dispatch) => { return { dangKyNguoiDung: (user, handleClear) => { dispatch(dangKyNguoiDungAction(user, handleClear)); } } } export default connect(mapStateToProp, mapDispatchToProps)(SignUpPage);
import React, { Component } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; class Like extends Component { state = { isActive: false } componentDidMount() { const userLike = this.props.userLike; this.setState({isActive: (userLike ? true: false)}); } componentWillReceiveProps(nextProps) { // Load new data when the dataSource property changes. // console.log('like receive props', nextProps) if (nextProps.userLike != this.props.userLike) { this.setState({isActive: (nextProps.userLike ? true: false)}); } } render() { const {isDisabled, onLike, totalLike} = this.props; return ( <React.Fragment> <button className={classnames('btn btn-transparent', {linkActive: this.state.isActive})} disabled={isDisabled} onClick={()=> onLike()}> <i className="fas fa-thumbs-up" /> {(totalLike > 0 || totalLike === 0) && ( <span>{totalLike}</span> )} </button> </React.Fragment> ) } } Like.propTypes = { isDisabled: PropTypes.bool.isRequired, onLike: PropTypes.func.isRequired, totalLike: PropTypes.number, userLike: PropTypes.number }; export default Like;
/** * * @author Anass Ferrak aka " TheLordA " <ferrak.anass@gmail.com> * GitHub repo: https://github.com/TheLordA/Instagram-Clone * */ import React from "react"; import AuthentificationState from "./contexts/auth/Auth.state"; import Routing from "./routes/Routing"; import "./App.css"; const App = () => { return ( <AuthentificationState> <Routing /> </AuthentificationState> ); }; export default App;
Ext.define('Accounts.view.main.MainModel', { extend: 'Ext.app.ViewModel', alias: 'viewmodel.main', requires: [ 'Accounts.model.Customer', 'Accounts.model.Item', 'Accounts.model.SalePurchase', 'Accounts.model.Payment' ], data: { name: 'Accounts' }, stores: { customerStore: { model: 'Accounts.model.Customer', autoLoad : { start : 0, limit : 5 } }, itemStore: { model: 'Accounts.model.Item', autoLoad : { start : 0, limit : 5 } }, salePurchaseStore: { model: 'Accounts.model.SalePurchase', autoLoad: { start : 0, limit : 5 } }, paymentStore: { model: 'Accounts.model.Payment', autoLoad : { start : 0, limit : 5 } } } });
module.exports = { generateBitmap: function(bits) { var bitmap = new Array(bits); for (i=0; i<bitmap.length; i++) { bitmap[i] = new Array(bits); } for (i=0; i<bitmap.length; i++) { for (j=0; j<bitmap[i].length; j++) { if (Math.random() > 0.5) { bitmap[i][j] = 0; } else { bitmap[i][j] = 1; } } } console.log("Height of Bits: " + bits); console.log("Area of Bitmap: " + bits*bits); /* for (i=0; i<bitmap.length; i++) { console.log(bitmap[i].join(" | ")) } */ return bitmap; }, migrateBitmap: function(oldmap, callback) { for (i=0; i<oldmap.length; i++) { for (j=0; j<oldmap[i].length; j++) { var randomNumber = Math.random(); console.log(randomNumber); if (randomNumber < 1/16) { if (oldmap[i][j] == 0) { oldmap[i][j] = 1; } else { oldmap[i][j] = 0; } } } } callback(oldmap); }, getGenerateMap: function(callback) { callback(module.exports.generateBitmap(16)); }, generateNewSave: function(callback) { map = JSON.stringify(module.exports.generateBitmap(16)); vote = 50; people = 0; callback(map, vote, people); }, makeBaseGenerations: function(database) { database.getNumberOfSpacemen(function(data){ if (data < 3) { module.exports.generateNewSave( function(map, vote, people) { database.addSpaceman(map, vote, people, function(data) { console.log(data); module.exports.makeBaseGenerations(database); }); } ); } else { // Don't Generate More Data } }); } }
'use strict'; /** * @ngdoc function * @name ossuClientApp.controller:MainmodalcontrollerCtrl * @description * # MainmodalcontrollerCtrl * Controller of the ossuClientApp */ angular.module('ossuClientApp') .controller('MainmodalcontrollerCtrl', function ($scope, $uibModalInstance) { $scope.ok = function () { $uibModalInstance.close(); }; });
const morgan = require('morgan') module.exports = (options) => { return morgan('combined'); }
'use strict'; angular.module('FEF-Angular-UI.Filter', []) .factory('Filter', ['$filter', 'Utils', function($filter, Utils) { return { filter: function(subject, filter) { var filters = [], categories = []; // format the filter object in to an array of 'categories' for each filter 'category' for (var category in filter) { var filterObj = { category: category, indexes: Utils.getTrueIndexes(filter[category]) }; categories.push(filterObj); } // the filter function, needs categories to be defined var filterFn = function(i) { var i = i; return function(item) { return Utils.containsIndex(item[categories[i].category], categories[i].indexes); } }; // loop the categories and push filter function for those with indexes for (var x = 0; x < categories.length; x++) { if (categories[x].indexes.length > 0) { filters.push(filterFn(x)); } } var filterItem = function(item) { if (filters.length === 0) return false; var rtn = true; for(var i = 0; i < filters.length; i++) { if (filters[i](item) !== true) { rtn = false; } } return rtn; }; return $filter('filter')(subject, filterItem); } } }]);
import React from 'react'; import PropTypes from 'prop-types'; import { validate } from 'isemail'; import FormField from './FormField'; const EmailField = props => { // prevent passing type and validator props from this component to the rendered form field component const { type, validator, ...restProps } = props; // validateEmail function using the validate() method of the isemail package const validateEmail = value => { var emails = ["Inna66@gmail.com", "Sanni@gmail.com", "Doglove@gmail.com", "Kello@gmail.com", "Rimpula@gmail.com"] if (!validate(value)) throw new Error('Säkhköposti on virheellinen. Tarkista puuttuuko @ tai . -merkki'); for(let x = 0; x < emails.length; x++) { if(value === emails[x]) throw new Error('Sähköposti on jo käytössä') } }; // pass the validateEmail to the validator prop return <FormField type="text" validator={validateEmail} {...restProps} /> }; EmailField.propTypes = { label: PropTypes.string.isRequired, fieldId: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, required: PropTypes.bool, children: PropTypes.node, onStateChanged: PropTypes.func }; export default EmailField;
export const setCurrentUserPolls = (polls) => { return { type: "SET_CURRENT_USER_POLLS", payload: polls, }; }; export const addCurrentUserPoll = (poll) => { return { type: "ADD_CURRENT_USER_POLL", payload: poll, }; }; export const setVotedOption = (votedOption) => { return { type: "SET_VOTED_OPTION", payload: votedOption, }; };
import React from 'react'; import classNames from "classnames"; import styles from "../styles/BrowseRecipes.module.scss"; import RecipeCard from "../../client/components/recipes/RecipeCard"; import {sampleRecipes} from "../../client/components/tour/sampleData"; export default function Index() { const browseRecipesContainerClassName = classNames({ [styles.browseRecipesContainer]: true, }); return ( <div> <div className={browseRecipesContainerClassName}> {sampleRecipes.map(recipe => { return <RecipeCard deleteRecipe={() => {}} key={recipe.id} recipe={recipe}/> })} </div> </div> ) }
import PropTypes from "prop-types"; import { PureComponent } from "react"; import Card from "react-bootstrap/Card"; export default class PanelWithTitle extends PureComponent { static propTypes = { title: PropTypes.string.isRequired, panelBody: PropTypes.bool.isRequired, children: PropTypes.node.isRequired }; static defaultProps = { panelBody: false }; render() { const { title, panelBody, children, ...otherProps } = this.props; let currentChildren = children; if (panelBody) { currentChildren = <Card.Body>{currentChildren}</Card.Body>; } return ( <Card {...otherProps}> <Card.Header> <Card.Title as="h6" className="mb-0"> {title} </Card.Title> </Card.Header> {currentChildren} </Card> ); } }
"use strict" // async function statement async function foo() { return await x } // async function expression var bar = async function() { await x } // async gen function statement async function* foo() { yield await x } // async gen function expression var bar = async function* () { await (yield x) } // async arrow functions with body var arrow1 = async () => { await 42 } // async arrow functions with expression var arrow2 = async () => await 42; // async function with minimal whitespace var arrow3=async()=>await(42); // double async functions with minimal whitespace var arrow3=async()=>await(async()=>await 42); // async arrow IIFE (async () => { await 42 })(); // crockford style IIFE (async function () { await 42 }()); // async obj member function var obj = { async baz() { await this.x }, async* bazGen() { yield await this.x } } // async class method class Dog { async woof() { await this.x } async* woofGen() { await (yield this.x); } } // static async class method class Cat { static async miau() { await this.x } static async* woofGen() { yield await this.x; } } // normal function referencing this function normalThis() { return this; } // async function referencing this async function asyncThis() { return this; } // async arrow function referencing this var fn = async () => this; var fn2 = /**/ async /**/ ( /**/ ) /**/ => /**/ /**/ this /**/ ; // async arrow function referencing this within async function async function within1() { async function within2() { return await (async () => await this) } } // async arrow function referencing this within normal function function within1() { function within2() { return async () => this } } // normal arrow function referencing this within async function function within1() { async function within2() { return () => this } } // normal arrow function referencing this deep within async function async function within1() { function within2() { return () => this } } // async arrow inside normal arrow inside async function async function within1() { () => async () => this } // normal function referencing arguments function normalThis() { return arguments; } // async function referencing arguments async function asyncThis() { return arguments; } // async arrow function referencing arguments async function within1() { () => async () => arguments } class SuperDuper extends BaseClass { constructor(arg) { super(arg) } async barAsync() { const arg = super.arg() super.arg = super.arg() super.arg = super[super.arg = super.arg()] super /*a*/ . /*b*/ arg /*c*/ = /*d*/ super /*e*/ . /*f*/ arg /*g*/ super /*a*/ [ /*b*/ arg /*c*/ ] /*d*/ = /*e*/ super /*f*/ [ /*g*/ arg /*h*/ ] /*i*/ const arg = super['arg'] super['arg'] = arg delete super.arg return super[arg](arg) delete super.arg return super.barAsync(arg) } async bazAsync() { super['arg'] = super['arg'] } } // await and yield parse differences async function requireParens() { await x || y; y && await x; await x + 1; await x << 5; await x | 0; 0 | await x; await x == 3; 4 !== await x; await x instanceof Foo; await x in await y; typeof await x; void await x; delete await x; !await x; ~await x; -await x; +await x; await x ? y : z; } // await and yield parse similarities async function noRequiredParens() { await x; (await x, await x); await x++; return await x; throw await x; if (await x) return; while (await x) await x; do { await x } while (await x); for (y in await x) await y; for (y of await x) await y; x ? await y : await z; await await x; } // await on its own line async function ownLine() { await someThing; } // await gen on its own line async function* ownLineGen() { await someThing; } // for await async function* mapStream(stream, mapper) { for await (let item of stream) { yield await mapper(item); } } async function reduceStream(stream, reducer, initial) { var value = initial; for await (let item of stream) { value = reducer(value, item); } return value; } // doesn't break for holey destructuring (#22) const [,holey] = [1,2,3] // support arrow functions returning parentheic expressions (#49) const arrowOfParentheic = async () => (12345) const arrowOfNestedDoubleParentheic = (async () => ((12345))) const arrowOfSequence = async () => (12345, 67890) const arrowOfObj1 = async () => ({}) const arrowOfObj2 = async () => ({ key: await x })
import React from 'react'; import {createStackNavigator} from '@react-navigation/stack'; import {NavigationContainer} from '@react-navigation/native'; import {DefaultTheme, DarkTheme} from '@react-navigation/native'; //! Navigator import Permissions from 'features/permissions/Permissions'; import WeatherView from 'features/weather/WeatherView'; const RootStack = createStackNavigator(); const RootNavigator = () => { const navigationTheme = DefaultTheme; return ( <NavigationContainer theme={navigationTheme}> <RootStack.Navigator headerMode="none"> <RootStack.Screen name="Permissions" component={Permissions} /> <RootStack.Screen name="Home" component={WeatherView} /> </RootStack.Navigator> </NavigationContainer> ); }; export default RootNavigator;
/* * jQuery Mobile Framework : "textinput" plugin for text inputs, textareas * Copyright (c) jQuery Project * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license */ (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.widget, { options: { theme: null, initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type])" }, _create: function() { var input = this.element, o = this.options, theme = o.theme, themeclass, focusedEl, clearbtn; if ( !theme ) { theme = $.mobile.getInheritedTheme( this.element, "c" ); } themeclass = " ui-body-" + theme; $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" ); input.addClass("ui-input-text ui-body-"+ theme ); focusedEl = input; // XXX: Temporary workaround for issue 785 (Apple bug 8910589). // Turn off autocorrect and autocomplete on non-iOS 5 devices // since the popup they use can't be dismissed by the user. Note // that we test for the presence of the feature by looking for // the autocorrect property on the input element. We currently // have no test for iOS 5 or newer so we're temporarily using // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. input[0].setAttribute( "autocorrect", "off" ); input[0].setAttribute( "autocomplete", "off" ); } //"search" input widget if ( input.is( "[type='search'],:jqmData(type='search')" ) ) { focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + "'></div>" ).parent(); clearbtn = $( "<a href='#' class='ui-input-clear' title='clear text'>clear text</a>" ) .tap(function( event ) { input.val( "" ).focus(); input.trigger( "change" ); clearbtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }) .appendTo( focusedEl ) .buttonMarkup({ icon: "delete", iconpos: "notext", corners: true, shadow: true }); function toggleClear() { if ( !input.val() ) { clearbtn.addClass( "ui-input-clear-hidden" ); } else { clearbtn.removeClass( "ui-input-clear-hidden" ); } } toggleClear(); input.keyup( toggleClear ) .focus( toggleClear ); } else { input.addClass( "ui-corner-all ui-shadow-inset" + themeclass ); } input.focus(function() { focusedEl.addClass( "ui-focus" ); }) .blur(function(){ focusedEl.removeClass( "ui-focus" ); }); // Autogrow // Modified from previous implementation. Now supports cutting/pasting, and holding down keys. function checkTextarea() { var el = currEl; var minHeight = el.attr( "data-height" ); if (minHeight == undefined) { minHeight = el.innerHeight() el.attr( "data-height", minHeight); } $( "html" ).append( '<xmp id="testbed" style="position: fixed; border: 1px solid #f00; opacity: 0; top: ' + window.innerHeight + 'px">' + (el.val()) + "</xmp>" ); $( "#testbed" ).html( el.val().replace( /([\n\r])/g, "$1=" )); $( "#testbed" ).css({ wordWrap: "break-word", backgroundColor: "#faa", paddingTop: el.css( "padding-top" ), paddingRight: el.css( "padding-right" ), paddingBottom: el.css( "padding-bottom" ), paddingLeft: el.css( "padding-left" ), fontFamily: el.css( "font-family" ), fontSize: el.css( "font-size" ), lineHeight: el.css("line-height"), width: el.css( "width" ), display: "block" }) $( "textarea" ).css( "overflow", "hidden" ); var newHeight = $( "#testbed" ).innerHeight(); if ( newHeight < minHeight ) { newHeight = minHeight; } $( "textarea" ).css({ height: newHeight }) } var numKeysPressed = 0; var timerChecker; var currEl; if ( input.is( "textarea" ) ) { input.blur(function() { keysPressed = 0; clearInterval(timerChecker); checkTextarea(); }) input.keydown(function(e) { numKeysPressed += 1; if (numKeysPressed == 1) { timerChecker = setInterval(function() { checkTextarea(); }, 20); currEl = $(this); } setTimeout(function() { checkTextarea(); }, 0) }) input.keyup(function(e) { numKeysPressed -= 1; if (numKeysPressed < 0) numKeysPressed = 0; if (numKeysPressed == 0) { clearInterval(timerChecker); } checkTextarea(); }) } }, disable: function(){ ( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).addClass( "ui-disabled" ); }, enable: function(){ ( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ? this.element.parent() : this.element ).removeClass( "ui-disabled" ); } }); //auto self-init widgets $( document ).bind( "pagecreate create", function( e ){ $.mobile.textinput.prototype.enhanceWithin( e.target ); }); })( jQuery );
'use strict'; let logger = require('tracer').colorConsole(); let express = require('express'); let router = express.Router(); router.get('/', (req, res) => { res.render('categorys', {layout:'layout', title: 'Danh mục tin - Trạng Nguyên', categorys}) }); module.exports = router;
/* global require, describe, it */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Module to be tested: dot = require( './../lib' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'compute-dot', function tests() { it( 'should export a function', function test() { expect( dot ).to.be.a( 'function' ); }); it( 'should throw an error if the first argument is not an array', function test() { var values = [ 5, '5', null, undefined, true, NaN, {}, function(){} ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( TypeError ); } function badValue( value ) { return function() { dot( value, [] ); }; } }); it( 'should throw an error if the second argument is not an array', function test() { var values = [ 5, '5', null, undefined, NaN, true, {}, function(){} ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[i] ) ).to.throw( TypeError ); } function badValue( value ) { return function() { dot( [], value ); }; } }); it( 'should throw an error if provided an accessor argument which is not a function', function test() { var values = [ '5', 5, true, undefined, null, NaN, [], {} ]; for ( var i = 0; i < values.length; i++ ) { expect( badValue( values[ i ] ) ).to.throw( TypeError ); } function badValue( value ) { return function() { dot( [ 1, 2, 3 ], [ 1, 2, 3 ], value ); }; } }); it( 'should throw an error if the input arrays are not the same length', function test() { expect( foo ).to.throw( Error ); function foo() { dot( [1,2,3], [1,2] ); } }); it( 'should return null if provided empty arrays', function test() { assert.isNull( dot( [], [] ) ); }); it( 'should compute the dot product', function test() { var x = [ 1, 2, 3 ], y = [ 4, 5, 6 ], expected = 32, actual; actual = dot( x, y ); assert.strictEqual( actual, expected ); }); it( 'should compute the dot product using an accessor function', function test() { var dat1, dat2, expected, actual; dat1 = [ {'x':2}, {'x':4}, {'x':5} ]; dat2 = [ [1,3], [2,1], [3,5] ]; actual = dot( dat1, dat2, getValue ); expected = 35; assert.strictEqual( actual, expected ); function getValue( d, i, j ) { if ( j === 0 ) { return d.x; } return d[ 1 ]; } }); });
var continueButton = document.getElementById('continue'); var intro = document.getElementById('intro'); var hiddenDiv = document.getElementById('hiddenDiv1'); document.getElementById('continue').addEventListener('click', function() { document.getElementById('hiddenDiv1').style.display = 'block'; document.getElementById('continue').style.display = 'none'; document.getElementById('intro').style.display = 'none'; }); document.getElementById('razzle').addEventListener('click', function() { document.getElementById('hiddenDiv1').style.display = 'none'; document.getElementById('hiddenDiv2Raz').style.display = 'block'; })
const APIKEY = 4 b87c57531f0db1d73507427b3dbb26f;
angular.module('WhatToWear', []) .factory('Weather', function($http) { var getWeather = function(zipcode) { return $http({ method: 'GET', url:'http://api.openweathermap.org/data/2.5/weather?zip=' + zipcode + ',us&units=imperial&APPID=5c680e5d8c8f29befb9f1c239dfae90b' }).success(function (data) { return data; }) }; var getJacket = function() { return $http({ method: 'GET', url: '/api/inventory' }).success(function (data) { return data; }) } return { getJacket: getJacket, getWeather: getWeather }; }) .controller('weatherController', function($scope, Weather) { $scope.data = {}; $scope.zip = ''; $scope.getInfo = function() { Weather.getWeather($scope.zip).then(function(data) { console.log(data); $scope.data.city = data.data.name; console.log($scope.data.chanceOfPrecip); $scope.data.precip = data.data.weather[0].description; $scope.data.temp = data.data.main.temp; $scope.zip = ''; $scope.data.clothing = ''; if($scope.data.temp < 60 || $scope.data.precip === 'moderate rain') { $scope.data.clothing = 'Looks like you need your ' + $scope.jacket; } else if ($scope.data.precip === 'clear skies') { $scope.data.clothing = 'Looks like no rain - you can leave your jacket at home!' } else if ($scope.data.precip === 'heavy intensity rain') { $scope.data.clothing = 'Bring out the big guns and throw on your heavy rain jacket!' } else if ($scope.data.precip === 'broken clouds') { $scope.data.clothing = 'Looks like you need your ' + $scope.jacket; } }); }; $scope.getJacket = function() { Weather.getJacket().then(function(data) { $scope.jacket = data.data.light; $scope.zip = ''; }) } }) .factory('Inventory', function($http) { var addOne = function (jacket) { return $http({ method: 'POST', url: '/api/inventory', data: {jacket: jacket} }).success(function(data) { console.log('SUCCESS'); }); }; return { addOne: addOne } }) .controller('inventoryController', function($scope, Inventory) { $scope.jacket = ''; $scope.addInventory = function() { console.log($scope.jacket); Inventory.addOne($scope.jacket) .then(function() { console.log('made request'); $scope.jacket = ''; }) } })
const { Review } = require('../../models/review') module.exports = (req, res) => { const review = new Review({ name: req.body.name, restaurantId: req.body.restaurantId, stars: req.body.stars, comment: req.body.comment }) review.save().then((result) => { res.send(result) }, (error) => { res.status(400).send(error) // 400 for bad request }) }
var express = require('express'); var router = express.Router(); var usersController = require('../controllers/users'); /* GET users listing. */ router.get('/', function(req, res, next) { res.send('respond with a resource'); }); router.post('/login', async (req, res) => { let email = req.body.email; let password = req.body.password; if(!email || !password){ req.flash('errors', 'Falta usuario o contraseña'); res.redirect('/users/login') } else { let user = await usersController.checkLogin(email,password); if(user){ req.session.email = user.email; req.session.name = user.name; req.session.userId = user.id; req.session.logginDate = new Date(); res.redirect('/films'); }else{ req.flash('errors', 'Usuario o contraseña inválido'); res.redirect('/users/login'); } } }); router.get('/login', (req, res) => { let error = req.flash('errors'); if(req.session.name){ res.redirect('/films'); }else{ res.render('user/login', { error }); } }) router.get('/register', (req, res) => { let error = req.flash('error'); res.render('user/register',{ error }); }); router.post('/register', async (req, res) => { let { email, name, password} = req.body; let isRegistered = await usersController.register(email, password, name); if(isRegistered){ res.redirect('/users/login') }else{ req.flash('error', 'No se pudo registrar'); res.redirect('/users/register'); } }) module.exports = router;
#!/usr/bin/env node const puppeteer = require('puppeteer'); const Koa = require('koa'); const cors = require('@koa/cors'); const info = (...m) => console.log(...m); const env = (k, d) => process.env.PRODUCTION ? process.env[k] || (console.error(`ERROR: missing env key '${k}'`), process.exit(1)) : d; const reporter = (browser, pat) => async ctx => { if (ctx.path === '/good-morning') { return ctx.body = 'oh hey hi!'; } ctx.assert(ctx.path.startsWith('/report'), 404, `bad path: '${ctx.path}'`); ctx.assert(ctx.query.id, 400, `bad query: ${JSON.stringify(ctx.query)}`); ctx.assert(ctx.query.token, 400, `bad query: missing token ${JSON.stringify(ctx.query)}`); const { id, token } = ctx.query; const page = await browser.newPage(); await page.setViewport({ width: 800, height: 600, deviceScaleFactor: 2.5, }); const response = await page.goto(`${pat}/project/${id}/report?token=${token}`, { timeout: 25000, // try to avoid getting killed by heroku waitUntil: 'networkidle2', }); ctx.assert(response.ok(), response.status(), `report request error: ${response.statusText()}`); const buff = await page.pdf({ format: 'letter', margin: { top: '0.8in', left: '0.6in', right: '0.6in', bottom: '0.3in', }, }); ctx.type = 'application/pdf'; ctx.body = buff; info(`successfully fetched and rendered report ${id}`); }; async function bootstrap() { const port = parseInt(env('PORT', '3000')); const pat = env('PAT_HOST', 'http://localhost:8000'); info(`starting in ${process.env.PRODUCTION ? 'PRODUCTION' : 'DEBUG'} mode.`); if (isNaN(port)) { throw new Error(`$PORT is not a valid number: ${port}`); } info('starting browser...'); const browser = await puppeteer.launch({ args: ['--no-sandbox'] }); ['SIGINT', 'SIGTERM'].forEach(sig => process.once(sig, async () => { info('shutting down browser...'); await browser.close(); info('bye!'); process.exit(0); })); info('started.'); info(`launching koa app on port ${port}`); new Koa() .use(cors({ origin: pat })) .use(reporter(browser, pat)) .listen(parseInt(port)); info(`flying with ${pat}`); } if (!module.parent) bootstrap();
../../../../../../shared/src/App/MainHeader/Niche/index.js
const collections = document.querySelectorAll('ul'), elems = document.querySelectorAll('li'), blocks = document.querySelectorAll('.book'), adv = document.querySelector('.adv'), alink =document.querySelectorAll('a'), bg = document.getElementsByTagName('body'); console.log(collections); console.log(elems); console.log(blocks); console.log(adv); console.log(alink); console.log(bg); // Удалить рекламу со страницы adv.remove(); // Восстановить порядок книг. blocks[0].before(blocks[1]); blocks[5].after(blocks[2]); blocks[2].before(blocks[3]); blocks[4].after(blocks[3]); // Восстановить порядок глав во второй и пятой книге (внимательно инспектируйте индексы элементов, поможет dev tools) // book2 elems[10].before(elems[2]); elems[8].after(elems[7]); elems[4].before(elems[6]); elems[4].before(elems[8]); // book5 elems[48].before(elems[55]); elems[54].before(elems[51]); elems[50].after(elems[48]); // в шестой книге добавить главу “Глава 8: За пределами ES6” и поставить её в правильное место const elemClone = elems[25].cloneNode(true); elemClone.textContent = 'Глава 8: За пределами ES6'; elems[26].before(elemClone); // Исправить заголовок в книге 3( Получится - "Книга 3. this и Прототипы Объектов") alink[4].textContent = 'Книга 3. this и Прототипы Объектов'; // Заменить картинку заднего фона на другую из папки image // bg[0].body.style.backgroundImage = 'image/you-dont-know-js.jpg'; function changeBg(){ bg[0].style.backgroundImage = "url('image/you-dont-know-js.jpg')"; } changeBg();
import React from "react"; export const ParentComponent = React.createClass({ getDefaultProps: function() { console.log("ParentComponent - getDefaultProps"); }, getInitialState: function() { console.log("ParentComponent - getInitialState"); return { text: "" }; }, componentWillMount: function() { console.log("ParentComponent - componentWillMount"); }, shouldComponentUpdate: function(nextProps, nextState) { console.log("parent - shouldComponentUpdate"); return true; }, componentWillUpdate: function(nextProps, nextState) { console.log(" parent - componentWillUpdate"); }, render: function() { console.log("ParentComponent - render"); return ( <div className="container"> <input value={this.state.text} onChange={this.onInputChange} /> <ChildComponent text={this.state.text} /> </div> ); }, componentDidUpdate: function(nextProps, nextState) { console.log(" parent - component Did Update"); }, componentDidMount: function() { console.log("ParentComponent - componentDidMount"); }, componentWillUnmount: function() { console.log("ParentComponent - componentWillUnmount"); }, onInputChange: function(e) { this.setState({ text: e.target.value }); } }); export const ChildComponent = React.createClass({ getDefaultProps: function() { console.log(" -- -- --- ChildComponent - getDefaultProps"); }, getInitialState: function() { console.log("-- -- --- ChildComponent - getInitialState"); return { dummy: "" }; }, componentWillMount: function() { console.log("-- -- --- ChildComponent - componentWillMount"); }, componentDidMount: function() { console.log("-- -- --- ChildComponent - componentDidMount"); }, componentWillUnmount: function() { console.log("-- -- --- ChildComponent - componentWillUnmount"); }, componentWillReceiveProps: function(nextProps) { console.log("-- -- --- ChildComponent - componentWillReceiveProps"); console.log(nextProps); this.setState({dummy : "changed in receive props"}); }, shouldComponentUpdate: function(nextProps, nextState) { console.log("-- -- --- ChildComponent - shouldComponentUpdate"); return true; }, componentWillUpdate: function(nextProps, nextState) { console.log("-- -- --- ChildComponent - componentWillUpdate"); console.log("-- -- --- nextProps:"); console.log(nextProps); console.log("-- -- --- nextState:"); console.log(nextState); }, render: function() { console.log("-- -- --- ChildComponent - render"); return ( <div>Props: {this.props.text}</div> ); }, componentDidUpdate: function(previousProps, previousState) { console.log("-- -- --- ChildComponent - componentDidUpdate"); console.log("-- -- --- previousProps:"); console.log(previousProps); console.log("-- -- --- previousState:"); console.log(previousState); } });
var express = require('express'); var router = express.Router(); var appRoot = require('app-root-path'); var commentsModule = require(appRoot + "/javascripts/comments") /* GET home page. */ router.post('/', function(req, res, next) { console.log("in comme"); commentsModule.createComment(req.session.username, req.body.postId, req.body.commentContent); res.redirect("/"); }); router.get('/', function(req, res, next) { postModule.retrievePosts("simonwallin1@gmail.com", function(gottenPosts) { res.render('includes/post', {logged_in: req.session.username, admin: req.session.admin, posts: gottenPosts.reverse() }); }); }); module.exports = router;
const store = { getByKey(key) { try { const data = localStorage.getItem(key); if (data === null) { return null; } return JSON.parse(data); } catch (e) { return Error(e); } }, setItem(key, data) { try { const serializedData = JSON.stringify(data); localStorage.setItem(key, serializedData); } catch (e) { return Error(e); } }, deleteByKey(key) { try { localStorage.removeItem(key); return true; } catch (e) { return Error(e); } }, deleteAll() { try { localStorage.clear(); } catch (e) { return Error(e); } }, getAll() { try { const data = {}; const keys = Object.keys(localStorage); let i = keys.length; while (i--) { data[keys[i]] = JSON.parse(localStorage.getItem(keys[i])); } if (keys === null) { return null; } return data; } catch (e) { return Error(e); } } }; export default store;
document.write( '<div class="sign-box">' + ' <div class="sign-form-header">' + ' <span class="active">登录</span>' + ' <!-- <span class="">注册</span> -->' + ' <i id="close-btn" class="close-btn">×</i>' + ' </div>' + ' <div class="sign-form-body">' + ' <form action="#" class="login-form">' + ' <input type="text" name="email" class="login-form-ipt" placeholder="请输入登陆邮箱">' + ' <input type="password" name="password" autocomplete="off" placeholder="请输入密码" class="login-form-ipt">' + ' <div class="form-fn-wrap">' + ' <label for="auto-signin">' + ' <input type="checkbox" id="auto-signin" checked="checked">' + ' <span class="tip-txt">自动登录</span>' + ' </label>' + ' <a href="#" class="forget-pwd" target="_blank" hidefocus="true">忘记密码?</a>' + ' </div>' + ' <input type="submit" value="确认登录" class="submit-btn">' + ' </form>' + ' </div>' + '</div>' + '<i class="cover index-cover"></i>' );
import fs from "fs"; import config from "../../../app/server/config/database.json"; const dbImpl = config.db; /********************************************************************************** * It is up to you to make sure you implement all functions in your repositories. * * A sample comment is included in bookshelf/UserRepository. * * No interfaces in Javascript :( * **********************************************************************************/ const repositories = {}; // add bindings here repositories.UserRepository = new (require("./" + dbImpl + "/UserRepository"))(); repositories.BlogRepository = new (require("./" + dbImpl + "/BlogRepository"))(); repositories.PostRepository = new (require("./" + dbImpl + "/PostRepository"))(); repositories.CommentRepository = new (require("./" + dbImpl + "/CommentRepository"))(); export default repositories;
import Router from 'koa-router'; import { getOpportunity, addOpportunity, getOpportunityById } from '../service/opportunity'; async function getList(ctx) { const result = await getOpportunity(); ctx.body = { status: '1', data: result } } async function submit(ctx) { const id = ctx.params.id; console.log(ctx.request.body); if (id === '-1') { //add customer const result = await addOpportunity(ctx.request.body); ctx.body = { status: '1', data: result } } else { // update customer ctx.body = { status: '1', } } } async function getById(ctx) { const id = ctx.params.id; const result = await getOpportunityById(id); ctx.body = { status: '1', data: result } } // export default { // getList, // submit, // getById // } const router = new Router({ prefix: '/opportunity' }); router.post('/', getList); router.put('/:id', submit); router.get('/:id', getById); export default router;
// 更新的模态框 import React, { Component } from 'react'; import { View, Text, StyleSheet, Modal, TouchableOpacity, Image, Dimensions, Animated, Easing, Platform, Linking, DeviceEventEmitter, Alert, } from 'react-native'; import { connect } from 'rn-dva'; import Progress from './UpdateProgress'; import CommonStyles from '../common/Styles'; import { downloadAndInstall, openPermissionSettings } from '../config/nativeApi'; import Button from './Button'; const { width, height } = Dimensions.get('window'); class UpdateComModal extends Component { state = { immediateUpdate: false, planeAin: new Animated.Value(32), downloadError: false, } componentDidMount() { DeviceEventEmitter.addListener('downloadProgress', this._handleDownloadProgress); DeviceEventEmitter.addListener('downloadError', this._handleDownloadError); } componentWillUnmount() { DeviceEventEmitter.removeListener('downloadProgress', this._handleDownloadProgress); DeviceEventEmitter.addListener('downloadError', this._handleDownloadError); } _immediateUpdate = async () => { const { isMandatory } = this.props; this.setState({ immediateUpdate: true }); if (Platform.OS === 'ios') { Linking.openURL('itms-apps://itunes.apple.com/app/id1448670815'); // 非强制更新才能关闭弹框 if (!isMandatory) this.handleCloseModal(); } if (Platform.OS === 'android') { const url = this.props.updateInfo.url; if (url) { const isSuccess = await downloadAndInstall(url); if (!isSuccess) { Alert.alert('提示', '请为应用开启存储权限,以便下载最新的更新包,更新后可继续使用应用。', [ { text: '确定', onPress: () => { openPermissionSettings(); }, }, ]); this.setState({ immediateUpdate: false }); } } } } _handleDownloadProgress = (progress) => { const { modalVisible, isMandatory } = this.props; const { immediateUpdate } = this.state; console.log('下载进度=>', progress); if (modalVisible && immediateUpdate) { if (this.progress != progress) this.startPlaneAni(progress / 100); this.progress = progress; if (progress === 100) { // 非强制更新,才可以关闭弹框 if (!isMandatory) { this._setState({ modalVisible: false, }); } this.setState({ immediateUpdate: false, }); } } } _handleDownloadError = () => { this.setState({ downloadError: true, }); } startPlaneAni = (progress) => { const val = progress * 270 >= 32 ? progress * 270 >= 248 ? 270 : progress * 270 : 32; Animated.timing(this.state.planeAin, { toValue: val, duration: 100, easing: Easing.linear, }).start(); this.progressBar.progress = progress; } _setState = (state) => { const { isMandatory, modalVisible, updateInfo = {} } = this.props; this.props.saveUpgradeInfo({ isMandatory, modalVisible, updateInfo, ...state, }); } handleCloseModal = () => { const { isMandatory, readLaunchAppNotification } = this.props; const modalVisible = false; this._setState({ modalVisible }); if (!modalVisible && !isMandatory) { readLaunchAppNotification(); } } handleRedownload = () => { this.setState({ downloadError: false, }); this._immediateUpdate(); } renderModal() { const { planeAin, immediateUpdate, downloadError } = this.state; const { isMandatory, modalVisible, updateInfo = {} } = this.props; return ( <Modal animationType="none" transparent visible={modalVisible} onRequestClose={() => { }} > <TouchableOpacity style={styles.modal} activeOpacity={1} onPress={() => { isMandatory ? null : this.handleCloseModal(); }}> <View style={styles.modalContainer}> { isMandatory ? null : ( <View style={{ paddingBottom: 27, ...CommonStyles.flex_end }}> <TouchableOpacity onPress={() => this.handleCloseModal()} activeOpacity={1}> <Image source={require('../images/home/closeUpdate.png')} /> </TouchableOpacity> </View> ) } {/* 检查是否在进行下载更新包 */} { !immediateUpdate ? ( <TouchableOpacity activeOpacity={1} style={{ backgroundColor: '#fff', position: 'relative', borderRadius: 10 }}> <Image fadeDuration={0} style={{ width: 295, position: 'relative', top: -27 }} source={require('../images/home/updateBgimg.png')} /> <View style={{ borderBottomLeftRadius: 15, borderBottomRightRadius: 15, position: 'relative', top: -20, }} > <View style={{ paddingHorizontal: 25 }}> <View style={[CommonStyles.flex_start, { backgroundColor: 'rgba(0,0,0,0)' }]}> <Text style={{ marginBottom: 10, fontSize: 15, color: '#666' }}>更新内容</Text> </View> <Text style={{ lineHeight: 20, fontSize: 12, color: '#a1a1a1' }} numberOfLines={5}>{updateInfo.updateMessage}</Text> </View> {/* 判断是否是强制更新,显示不同按钮,现在修改为如果强制,不显示关闭按钮,否则显示 */} <View style={{ marginVertical: 30, ...CommonStyles.flex_center }}> <TouchableOpacity onPress={() => { this._immediateUpdate(); }} activeOpacity={1} > <Image fadeDuration={0} source={require('../images/home/update_btn.png')} /> </TouchableOpacity> </View> </View> </TouchableOpacity> ) : ( <TouchableOpacity activeOpacity={1} style={{ backgroundColor: '#fff', borderRadius: 10 }}> <Image style={{ width: 295, position: 'relative', top: -27 }} fadeDuration={0} source={require('../images/home/updateBgimg.png')} /> <View style={{ backgroundColor: '#fff', borderBottomLeftRadius: 15, borderBottomRightRadius: 15, alignItems: 'center', }} > <Progress ref={dom => this.progressBar = dom} progressColor="#89C0FF" style={{ marginTop: 20, height: 10, width: 270, backgroundColor: '#eee', borderRadius: 10, }} /> <View style={{ position: 'absolute', top: 20, ...CommonStyles.flex_start, width: 270, }} > <Animated.View style={{ width: planeAin, ...CommonStyles.flex_end, }} > <Image style={{ width: 32, height: 20, position: 'relative', top: -5, }} source={require('../images/home/update_plane.png')} /> </Animated.View> </View> { downloadError ? ( <View style={{ alignItems: 'center', marginVertical: 10 }}> <Text style={{ fontSize: 14, color: '#999' }}>下载失败,请确定您的网络情况良好</Text> <Button type="link" title="重新下载" titleStyle={{ fontSize: 14, color: '#ee6161' }} onPress={() => this.handleRedownload()} /> </View> ) : ( <View style={{ alignItems: 'center', marginVertical: 20 }}> <Text style={{ fontSize: 14, color: '#999' }}>版本正在努力更新中,请等待</Text> </View> ) } </View> </TouchableOpacity> ) } </View> </TouchableOpacity> </Modal> ); } render() { return ( <View style={styles.container}> {this.renderModal()} </View> ); } } const styles = StyleSheet.create({ container: { height: 0, }, modal: { height, width, alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.5)', }, closeBtn: { width: 18, height: 18, borderRadius: 40, zIndex: 1, }, closeWrap: { ...CommonStyles.flex_center, position: 'absolute', top: 45, right: 10, width: 24, height: 24, borderRadius: 40, zIndex: 1, backgroundColor: '#fff', }, modalContainer: { }, }); export default connect((state) => { const upgradeInfo = state.upgrade.upgradeInfo || {}; return { isMandatory: upgradeInfo.isMandatory || false, modalVisible: (upgradeInfo.modalVisible || false) && !state.system.isFirst, updateInfo: upgradeInfo.updateInfo || {}, }; }, { saveUpgradeInfo: upgradeInfo => ({ type: 'upgrade/save', payload: { upgradeInfo: { ...upgradeInfo }, }, }), readLaunchAppNotification: () => ({ type: 'application/readLaunchAppNotification', }), })(UpdateComModal);
var express = require("express"); var app = express(); var path = __dirname + "/dist/recipe-book/"; app.use(express.static(path)); var server = app.listen(process.env.PORT || 8080, function () { var port = server.address().port; console.log("App now running on port", port); }); app.get('*', function(req, res) { res.sendFile(path + "index.html") })
import React from "react"; import { dispatcher as RouteDispatcher, RouteTo } from "./RouteDispatcher"; export default class Link extends React.Component { constructor() { super(); this.id = this.id = "k" + Math.floor(Math.random() * 999999) + "-" + Math.floor(Math.random() * 999999); } componentDidMount() { let self = document.getElementsByClassName(this.id)[0]; self.addEventListener("click", (e) => { RouteTo(this.props.to, this.props.in || ""); }); } render() { return React.createElement("div", { "className" : this.id + " " + (this.props.className ? this.props.className : "") }, this.props.children); } }
function createLegend(legendDomain, colorScale) { // 1. create a group to hold the legend const legend = svg.append("g") .attr("id", "legend") .attr("transform", "translate(" + (canvWidth - margin.right + 10) + "," + margin.top + ")") // 2. create the legend boxes and the text label // use .data(legendDomain) on an empty DOM selection const legend_entry = legend.selectAll("rect") .data(legendDomain) .enter(); legend_entry.append("rect") .attr("x", 10) .attr("y", (d,i) => 30 * i + 10) .attr("width", 20) .attr("height", 20) .attr("fill", d => colorScale(d)) .attr("stroke", "black") .attr("stroke-width", "1"); legend_entry.append("text") .attr("x", 40) .attr("y", (d,i) => 30 * i + 25) .text(d => d); // 3. create the main border of the legend legend.append("rect") .attr("x", 1) .attr("y", 1) .attr("width", margin.right - 15) .attr("height", legendDomain.length * 30 + 10) .attr("fill", "none") .attr("stroke", "black") .attr("stroke-width", "1"); }
angular.module("estacionamento").controller("estacionamentoCtrl", function ($scope, $http){ var listarEstacionamento = function (patioId){ $http.get("http://localhost:8080/estacionamento/" + patioId).then((data, status)=>{ $scope.vagas = data.data; console.log($scope.vagas.length); }); }; var addEstacionamento = function (registro){ $http.post("http://localhost:8080/estacionamento", registro).then((data, status)=>{ console.log(data); listarEstacionamento(registro.patioId); if(!data.data.saida){ $scope.ticket = { "msg" : "Bem vindo.", "entrada" : data.data.entrada, "saida" : null, "tempoPermanencia" : 0, "valor" : 0.00 } }else{ $scope.ticket = { "msg" : "Boa viagem.", "entrada" : data.data.entrada, "saida" : data.data.saida, "tempoPermanencia" : data.data.tempoPermanencia, "valorPago" : data.data.valorPago } } var dialog = document.getElementById('ticketDialog'); dialog.showModal(); }); }; $scope.patios = [ {id: 1, descricao: "Patio A", quantidadeVagas:"30", taxaHora:"1.30"}, {id: 2, descricao: "Patio B", quantidadeVagas:"60", taxaHora:"1.50"}, {id: 3, descricao: "Patio C", quantidadeVagas:"50", taxaHora:"1.00"} ]; $scope.selecionar = function (patio){ console.log(patio) $scope.patioSelecionado = patio; listarEstacionamento($scope.patioSelecionado.id); }; $scope.getArray = function (num) { values = []; for(var x = 1 ; x < num ; x++){ values.push(x); } return values; } $scope.add = function (placa){ console.log(placa); var novoRegistro = { "placa": placa, "patioId": $scope.patioSelecionado.id } addEstacionamento(novoRegistro); delete $scope.placa; $scope.close('registro'); } $scope.logIn = function (){ var dialog = document.getElementById('registro'); dialog.showModal(); } $scope.close = function (idDialog){ var dialog = document.getElementById(idDialog); delete $scope.placa; dialog.close(); } });
import {Navigation} from "react-native-navigation"; console.disableYellowBox = true; // メイン画面 import MainScreen from "./screens/MainScreen"; // コンポーネント // メッセージボックス import MessageDialogBox from "./component/MessageDialogBox"; // メッセージポップアップ console.debug("IOS START!!!!!!!!!!!!!"); Navigation.registerComponent('Main', () => MainScreen); Navigation.registerComponent('MessageDialogBox', () => MessageDialogBox); // 画面作成 const createTabs = () => { // タブ内容を定義する let screenTabs = []; screenTabs.push( { title: "Main", // 画面のタイトル screen: "Main", // 画面名(register名)(必須項目) icon: require("./image/main.png"), // タブボタンの表示アイコン(必須項目) } ); return screenTabs; }; // 画面を開く Navigation.startTabBasedApp({ tabs: createTabs(), animationType: "fade", backButtonHidden: true, // バックボタンを隠す appStyle: { //縦固定 orientation: 'portrait' }, portraitOnlyMode: true, });
/** * @param {number[]} nums * @param {number} target * @return {number} */ var search = function(nums, target) { let left = 0; let right = nums.length - 1; let result = search2(nums, target, left, right); return result; }; function search2(nums, target, left, right) { if (left > right) { return -1; } let mid = Math.floor((right + left) / 2); let val = nums[mid]; if (val == target) { return mid; } if (target < val) { // search left return search2(nums, target, left, mid - 1); } else { // search right return search2(nums, target, mid + 1, right); } } let nums = [-1, 0, 3, 5, 9, 12]; let target = 9; let result = search(nums, target); console.log(result);
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $(function(){ setInterval(function() { updataRoleStatus(); }, 1000*60); //修改服务器 function loadVariable(formId,modeId) { var userName = $("#userName").text(); var userid = $("#userid").text(); var server = $("#server").text(); $("#"+formId+" [name=name]").val(userName); $("#"+formId+" [name=userid]").val(userid); $("#"+formId+" [name=server]").val(server); $("#"+modeId+"").modal({backdrop:"static"}).modal('show'); } /** * 货币简校验 ** */ function userInfoProcess(status) { var property =null; var formId = null; var propertyName = null; switch(status) { case 1: property = 'gold'; formId = "editAccountGoldForm"; propertyName ='金币'; break; case 2: property = 'sugar'; formId = "editsugarForm"; propertyName ='棒棒糖'; break; case 3: property = 'pill'; formId = "editpillForm"; propertyName ='药丸'; break; case 4: property = 'vip'; formId = "editvipForm"; propertyName ='vip等级'; break; default: property = null; formId = null; break; } if( property == null && formId == null ) { alert('设置为空的属性,请检查所更改的属性系统是否更新!'); } //var amount = Number($("#amount").text()); var oldAmount = Number($("#"+property+"").text()); var userName = $("#userName").text(); var userid = $("#userid").text(); var Type = $("#"+formId+" input[name='"+property+"Type']:checked").val(); if( Type =='' || Type==0 || Type==false || Type==null ) { alert(propertyName+'空的选项类型,请填写选项类型!'); return false; } var amount = Number($("#"+formId+" input[name=amount]").val()); if( amount=='' && amount<0 ) { alert('请输入'+propertyName+',且不能小于<0'); return false; } var param = $("#"+formId+"").serializeArray(); var statusInfo = Type==3001?"提升":"下降"; if(Type==3003) { if( amount>oldAmount ){ alert(propertNyame+'超出上限!'); return false; } } var prompt = userid+statusInfo+propertyName+"为"+amount+"么?"; if (confirm("你确定要给 "+userName+"角色ID为"+prompt)) { $.ajax({ type:'POST', url:'/account/editmoney', data:param, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } } }); } } $("#coseGuide").click(function() { var PlayerId = $("#userid").text(); var ServerId = $("#server").text(); var userName = $("#userName").text(); var ifonline = $("#LevelPropsForm input[name=ifonline]").val(); ifonline = parseInt(ifonline); if(ifonline==1) { alert('在线玩家信息禁止更改,请退出重试'); return false; } if(PlayerId=='' || PlayerId==null || PlayerId=='undefined'){ alert('玩家数据为空!不可更改'); return false; } if (confirm("你确定要关闭,"+userName+"正在进行中的引导么?")) { $.ajax({ type:'POST', url:'/account/roleCoseGuide', data:"ServerId="+ServerId+"&PlayerId="+PlayerId, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ location.reload(); } } }); } }); // 等级变更 $("#LevelPropbtn").click(function() { var PlayerId = $("#userid").text(); var ServerId = $("#server").text(); var Roleaccount = $("#Roleaccount").text(); var ifonline = $("#LevelPropsForm input[name=ifonline]").val(); ifonline = parseInt(ifonline); if(ifonline==1) { alert('在线玩家信息禁止更改,请退出重试'); return false; } if(PlayerId=='' || PlayerId==null || PlayerId=='undefined'){ alert('玩家数据为空!不可更改'); return false; } $.ajax({ type:'POST', url:'/account/roleOnlineStatusVerif', data:"ServerId="+ServerId+"&PlayerId="+PlayerId, dataType:'json', success:function(result){ if(result.errcode == 0){ $("#LevelPropsForm [name=ServerId]").val(ServerId); $("#LevelPropsForm [name=PlayerId]").val(PlayerId); $("#LevelPropsForm [name=RoleAccount]").val(Roleaccount); $("#levelPropmodal").modal({backdrop:"static"}).modal('show'); }else{ alert(result.msg); } } }); }); // levelPropsBtn $("#levelPropsBtn").click(function(){ var userName = $("#userName").text(); var PlayerId = $("#userid").text(); var ServerId = $("#server").text(); var Roleaccount = $("#Roleaccount").text(); var level = $("#LevelPropsForm input[name=uplevel]").val(); if (confirm("你确定要给 "+userName+"角色ID为"+PlayerId+"变更等级么?")) { var param = $("#LevelPropsForm").serializeArray(); $.ajax({ type:'POST', url:'/account/editRoleInfo', data:param, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } } }); } }); /** * 体力变更 ***/ $("#BodyStrength").click(function() { var PlayerId = $("#userid").text(); var ServerId = $("#server").text(); var Roleaccount = $("#Roleaccount").text(); $("#BodyStrengthForm [name=ServerId]").val(ServerId); $("#BodyStrengthForm [name=PlayerId]").val(PlayerId); $("#BodyStrengthForm [name=RoleAccount]").val(Roleaccount); $("#BodyStrengthmodal").modal({backdrop:"static"}).modal('show'); }); $("#BodyStrengthBtn").click(function(){ var userName = $("#userName").text(); var PlayerId = $("#userid").text(); var ServerId = $("#server").text(); var Roleaccount = $("#Roleaccount").text(); var strength = $("#BodyStrengthForm input[name=strength]").val(); if(strength<0 || strength=='' || strength==false || strength==null){ alert('请选择体力!'); return false; } if (confirm("你确定要给 "+userName+"角色ID为"+PlayerId+"变更体力么?")) { var param = $("#BodyStrengthForm").serializeArray(); $.ajax({ type:'POST', url:'/account/editBodyStrength', data:param, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } } }); } }); // 金币变更提交 $("#goldAccountBtn").click(function(){ userInfoProcess(1); }); // 棒棒糖变更提交 $("#sugarBtn").click(function(){ userInfoProcess(2); }); // 药丸变更提交 $("#pillBtn").click(function(){ userInfoProcess(3); }); // vip变更提交 $("#vipBtn").click(function(){ userInfoProcess(4); }); // 道具更改 $("#addPropbtn ").click(function() { var userid = $("#userid").text(); var server = $("#server").text(); $("#PropsForm [name=userid]").val(userid); $("#PropsForm [name=server]").val(server); $("#addPropmodal").modal({backdrop:"static"}).modal('show'); }); // 道具变更提交 $("#PropsBtn").click(function(){ var userName = $("#userName").text(); var userid = $("#userid").text(); var propsid = $("#PropsForm input[name=propsid]").val(); var propsType = $("#PropsForm input[name='propsType']:checked").val(); var propsNum = Number($("#PropsForm input[name=propsNum]").val()); if(propsid<0 || propsid=='' || propsid==false || propsid==null){ alert('请选择道具Id!'); return false; } if(propsType =='' || propsType==0 || propsType==false || propsType==null ){ alert('请选择道具修改类型!'); return false; } if( propsNum== '' && propsNum <=0 ) { alert('请选择道具数量!'); return false; } var statusInfo = propsType==2001?"增加":"扣除"; if (confirm("你确定要给 "+userName+"角色ID为"+userid+statusInfo+"道具么?")) { var param = $("#PropsForm").serializeArray(); $.ajax({ type:'POST', url:'/account/editProps', data:param, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } } }); } }); // 公告model $("#addnoticebtn").click(function() { var userid = $("#userid").text(); var server = $("#server").text(); $("#noticeForm [name=userid]").val(userid); $("#noticeForm [name=server]").val(server); $("#addnoticemodal").modal({backdrop:"static"}).modal('show'); }); // 公告发布 $("#noticeBtn").click(function(){ var userName = $("#userName").text(); var userid = $("#userid").text(); var message = $("#noticeForm textarea[name=message]").val(); var loopTimes = $("#noticeForm input[name='loopTimes']").val(); if(message=='' || message==false || message==null){ alert('请输入公告内容!'); return false; } if(loopTimes =='' || loopTimes==0 || loopTimes==false || loopTimes==null ){ alert('请输入循环次数!'); return false; } if (confirm("你确定要给 "+userName+"角色ID为"+userid+"发布公告么?")) { var param = $("#noticeForm").serializeArray(); $.ajax({ type:'POST', url:'/account/sendUserNotice', data:param, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } } }); } }); $("#kickedOut").click(function(){ var userName = $("#userName").text(); var userid = $("#userid").text(); var server = $("#server").text(); if (confirm("你确定要把 "+userName+"角色ID为"+userid+"踢出下线么?")) { var jsondata = '{"server":'+server+',"userid":'+userid+'}'; $.ajax({ type:'POST', url:'/account/kickedOut', data:jsondata, dataType:'json', success:function(result){ alert(result.msg); if(result.errcode == 0){ window.location.href = window.location.href; } } }); } }); //<<<<<<<<<<<<<<<<<<<<<<<<<<< }); function updataRoleStatus(){ var PlayerId = $("#userid").text(); var ServerId = $("#server").text(); var userName = $("#userName").text(); var userHtml = null; if(PlayerId!='' && ServerId!=''){ $.ajax({ type:'POST', url:'/account/roleOnlineStatusVerif', data:"ServerId="+ServerId+"&PlayerId="+PlayerId, dataType:'json', success:function(result){ if(result.ifonline==0) { $("#userName").text(""); $("#LevelPropsForm input[name=ifonline]").val(0); // 离线 echo"<td class='success' id='userName'>".$playerName."&nbsp;".$onlineName; userHtml = result.playerName+"&nbsp;" + "<font style='color: #99a09b;'>(离线)</font>"; $("#userName").append(userHtml); } if(result.ifonline==1){ $("#userName").text(""); $("#LevelPropsForm input[name=ifonline]").val(1); userHtml = result.playerName+"&nbsp;" + " <font style='color: #48a260;'>(在线)</font>"; $("#userName").append(userHtml); // 在线 } } }); } }
"use strict"; /* global grist, window, document, fetch */ let resolve, reject; grist.rpc.registerImpl('github', { getImportSource: () => new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject; }) }); grist.ready(); window.onload = function() { document.getElementById('import').addEventListener('click', () => { const name = document.getElementById('name').value; fetch(`https://api.github.com/users/${name}/repos`).then( resp => resp.text() ).then( resp => resolve({ item: { kind: "fileList", files: [{content: resp, name: "repos.json"}] }, description: `Github repositories of ${name}` })); }); document.getElementById('cancel').addEventListener('click', () => resolve()); };
// let name = "Emi" // let favoriteNum = 27 // let isAlive = true; // let address = { // street: "123 main street", // city: "austin", // state: "Texas", // zip: "78741" // } // let favFruits = ['Banana', 'Strawberry', 'Apple']; // let x = 12; // let y = 45; // let z = x + y; // console.log(z); // let w = "45"; // let sum2 = x+ w; // console.log(sum2); // //this doesn't work because you can add a string to a number// // let f1 = 'Bananas'; // let f2 = "Orange"; // let salad = f1+f2; // console.log(salad); //concatination// // print out a sentence, that introduces me// // let sentence = `Hi my name is ${name} I love to eat ${salad} smoothies.` // console.log(sentence); /** write a function, that will generate a happy b-day message // this function should take in 3 variables // name // age*/ let age = 26 let birthdayMessage = (name, age) => { let message = `Hello ${name}, Oh my goodness, you turned ${age} today! Here's a promo code you can use in celebration of your birthday:)` return message; } let birthday1 = birthdayMessage ("Emi", 26); console.log(birthday1) let birthday2 = birthdayMessage ("Mr Smith", 102); console.log(birthday2) /**This funtion takes in the height and base of a triangle and returns the area * @param height of the triangle * @param base of the triangle * @return area of the triangle */ let triangleArea = function(height,base){ // some code let area = (height * base) / 2; return area; } let answer1 = triangleArea (12,15); console.log(answer1);
// Given an array of integers, find the one that appears an odd number of times. // There will always be only one integer that appears an odd number of times. // Examples // [7] should return 7, because it occurs 1 time (which is odd). // [0] should return 0, because it occurs 1 time (which is odd). // [1,1,2] should return 2, because it occurs 1 time (which is odd). // [0,1,0,1,0] should return 0, because it occurs 3 times (which is odd). // [1,2,2,3,3,3,4,3,3,3,2,2,1] should return 4, because it appears 1 time (which is odd). A = [1, 2, 2, 3, 3, 3, 4, 3, 3, 3, 2, 2, 1]; // function findOdd(A) { //happy coding! // return 0; // } /// need to look at each element and compare it to the others and filter out how many times it occurs // need to take that number and % 2 = 1 which will give all odd occurances //return number that is % 2 = 1 // const findOdd = A => { // let sortedArr = A.sort((a,b) => a-b); // for (let i = 0; sortedArr[i] === sortedArr[i+1]; i++){ // } // return sortedArr // // if (sortedArr[0] === sortedArr[1]) { // // } // } //figured out I needed nested for loops and I was almost there! // https://sebhastian.com/nested-loops-javascript/ //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort console.log(findOdd(A)); const findOdd = (A) => { let count = 0; let arr = A.sort((a, b) => a - b); for (let i = 0; i < arr.length; i++) { //console.log(i); for (let j = 0; j < arr.length; j++) { //console.log(j); if (arr[i] == arr[j]) { count++; } } if (count % 2 !== 0) { return arr[i]; } } };
import React, { useState } from 'react' import { history } from '../redux' // import Header from './header' // import Head from './head' const Dummy = () => { const [userName, setValue] = useState('') const onChange = (e) => { setValue(e.target.value) } return ( <div> <form className="flex items-center justify-center h-screen"> <div className="flex items-center px-80 py-10"> <div className="md:w-1/3"> <label className=" text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4" htmlFor="inline-full-name"> Repository: </label> </div> <div className="md:w-2/3"> <div> <input className="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500" id='input-field' type="text" value={userName} onChange={onChange} /> </div> </div> </div> <div> <div> {/* <div className="md:w-1/3" /> */} {/* </div> */} {/* <div className="md:w-2/3"> */} <button type='button' id='search-button' onClick={() => history.push(`/${userName}`)} className="shadow bg-purple-500 hover:bg-purple-400 focus:shadow-outline focus:outline-none text-white font-bold py-2 px-4 rounded" >Баттонидзе </button> {/* </div> */} </div> </div> </form> </div> ) } Dummy.propTypes = {} export default Dummy
/* * C.System.TileSchemaManager //TODO description */ 'use strict'; C.System.TileSchemaManager = function () { this.schemas = {}; var self = this; C.Utils.Event.once('initialized', function () { self.init(); }); }; C.System.TileSchemaManager.prototype.init = function () { for (var schema in C.Layer.Tile.Schema) { console.log('register', schema); this.register(C.Layer.Tile.Schema[schema], schema); } C.Helpers.viewport.on('move', this.update.bind(this)); }; C.System.TileSchemaManager.prototype.register = function (schema, name) { if (!schema || !name) { return; } if (name in this.schemas) { return; } var self = this; var sch = { schema: schema, registered: 0 }; this.schemas[name] = sch; schema.on('register', function () { ++self.schemas[name].registered; if (self.schemas[name].registered == 1) { schema.computeTiles(C.Helpers.viewport); } }); schema.on('unregister', function () { --self.schemas[name].registered; if (self.schemas[name].registered < 0) { self.schemas[name].registered = 0; } }); schema.computeTiles(C.Helpers.viewport); }; C.System.TileSchemaManager.prototype.update = function (viewport) { for (var schema in this.schemas) { var sch = this.schemas[schema]; if (sch.registered <= 0) continue; sch.schema.computeTiles(viewport); } }; C.System.TileSchemaManager = new C.System.TileSchemaManager();
/** * Created by clicklabs on 6/12/17. */ 'use strict'; const responseFormatter = require('Utils/responseformatter.js'); const organizationTypeSchema = require('schema/mongo/organizationtype'); const log = require('Utils/logger.js'); var config=require('../config'); const logger = log.getLogger(); module.exports.setOrganizationTypes = function (payload, callback) { organizationTypeSchema.OrganizationType.insertMany(payload.docs, function (err, OrganizationTypes) { console.log('OrganizationTypes :: ', OrganizationTypes); if (err) { logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { callback(null, OrganizationTypes) } }); }; module.exports.getOrganizationTypes = function (callback) { organizationTypeSchema.OrganizationType.find({}, {}, {lean: true}, function (err, data) { if (err) { callback(err) } else { if (!data) { responseFormatter.formatServiceResponse([], callback, "Organization type not found", "error", 400) } else { console.log("--------***Data", data) callback(null, data) } } }) }
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; export const fetchposts = createAsyncThunk( 'fetchposts', async (data, thunkAPI) => { const response = await fetch('https://jsonplaceholder.typicode.com/posts/') return await response.json() } ) export const todoSlicer = createSlice({ name: 'todolist', // for single // initialState: [ // { // id: 1, // text : 'Hey', // } // ], // for multiple initialState: { todos: [{text:'buy milk', id:1}], posts: [] }, reducers: { addTodo(state, action) { // const { id, text } = action.payload // return [...state,{ id : Math.random(0,9), // text : action.payload, // completed: false}] state.todos.push({ id : Math.random(0,9), text : action.payload, completed: false }) }, delAll(state){ state.todos.length = 0 }, delTodo(state, action){ state.todos = state.todos.filter((item) => item.id !== action.payload ) // return state.todos }, editTodo(state, action){ let updatedTodo = state.todos.find((item) =>{ console.log("KK") console.log(item.id) console.log(parseFloat(action.payload.id)) if (item.id == parseFloat(action.payload.id) ) { item.text = action.payload.text console.log("IN") } } ) return updatedTodo } }, extraReducers: { // Add reducers for additional action types here, and handle loading state as needed [fetchposts.fulfilled]: (state, action) => { // console.log(action.payload) action = action.payload.slice(0,10) console.log(action) // Add user to the state array state.posts = action // return state.post } } }) export const {addTodo, delAll, delTodo, editTodo} = todoSlicer.actions; export default todoSlicer.reducer // We can return directly it will set in state but if we have multiple properties set data by yourself
//---------------------------------------------------------------------------------------------- // MENU MOBILE //----------------------------------------------------------------------------------------------- $.fn.menuMobile = function(options){ console.log('MENU'); var settings = $.extend({ 'minWidth' : 767 }, options); return this.each(function(){ var target = $(this); var navIcon = $('<div>', {class: 'mobile-nav-icon', style: 'display:none'}); target.parent().prepend(navIcon); // click do nav icon - abre o menu //------------------------------------ navIcon.click(function(){ if(target.is(':visible')){ target.slideUp(); $(this).removeClass('opened'); } else { target.slideDown(); $(this).addClass('opened'); } }); // função de resize //-------------------------- function onWindowResize(){ var W = $(window).width(); if(W < settings.minWidth){ if(!navIcon.is(':visible')){ navIcon.show(); target.removeClass('navigation-menu').addClass('mobile-nav'); if(navIcon.hasClass('opened')){ target.show(); } else { target.hide(); } // click do dropdown - abre o submenu target.find('.dropdown a').click(function(e){ e.preventDefault(); $(this).parent().find('ul:first').slideToggle(); }); } } else { navIcon.hide(); target.removeClass('mobile-nav').addClass('navigation-menu').show(); target.find('ul').css({'display':''}); target.find('.dropdown a').off('click'); } } onWindowResize(); $(window).resize(onWindowResize); }); } //----------------------------------------------------------------------------------------------------------------------------------------------- // LISTA COM SUBLIST - SHOW HIDE //----------------------------------------------------------------------------------------------------------------------------------------------- $.fn.showHideList = function(options){ var settings = $.extend({ 'hideParent' : true, 'icoList' : true }, options); return this.each(function(){ var target = $(this); target.find('li').each(function(){ var item = $(this); // se o item possuir sub-lista if(item.find('ul').length > 0){ item.addClass('dropdown'); // adiciona a classe dropdown if(settings.icoList){ item.append('<i class="ico ico-list-arrow"></i>'); // adiciona o ico-list ao item } // adiciona a função ao evento click item.find('a:first').click(function(e){ e.preventDefault(); // se o item estiver aberto if(item.find('ul').is(':visible')){ item.removeClass('active').find('ul').slideUp(); // apenas fecha as sublistas deste item e remove a classe active } else { if(settings.hideParent){ target.find('.active').removeClass('active').find('ul').slideUp(); // fecha as sublistas abertas } item.find('ul:first').slideDown(); // mostra a sublista do próximo nivel deste item item.addClass('active'); // adiciona a classe active ao item } }); } }); }); } //----------------------------------------------------------------------------------------------------------------------------------------------- // POP UPS //----------------------------------------------------------------------------------------------------------------------------------------------- // pop up show $.fn.popUpShow = function(){ return this.each(function(){ var lastIndex = parseInt($('body div:last').css('z-index')); lastIndex = lastIndex > 0 ? lastIndex : 1; $(this).css({'margin-top': -($(this).height()/2+10)+'px', 'z-index': (lastIndex+2)}).fadeIn('fast'); $(this).parent().append('<div class="uiPopUpOverlay" style="z-index:'+(lastIndex+1)+'"></div>'); }); }; // pop up hide $.fn.popUpHide = function(){ return this.each(function(){ $(this).fadeOut('fast'); $(this).parent().find(".uiPopUpOverlay:last").remove(); }); } //----------------------------------------------------------------------------------------------------------------------------------------------- // ALERTS RESULT (com timer) //----------------------------------------------------------------------------------------------------------------------------------------------- var timeResultStatus = 0; $.fn.resultStatus = function(options){ // atualizar: fazer uma função close caso não seja setada a variavel timer var settings = $.extend({ 'value' : '', 'timer' : 3000 }, options); return this.each(function(){ clearTimeout(timeResultStatus); var Obj = $(this); Obj.html(''); Obj.append(settings.value).css({'display':'none'}).fadeIn(); timeResultStatus = setTimeout(function(){ Obj.children().animate({height:'0px', paddingTop: '0px', paddingBottom: '0px', opacity: '0'}, 500, function(){$(this).remove()}); }, settings.timer); }); } //----------------------------------------------------------------------------------------------------------------------------------------------- /* ALERTS BOOTSTRAP */ //----------------------------------------------------------------------------------------------------------------------------------------------- /* Warning messages */ $.fn.showBootstrapAlert = function(options){ var settings = $.extend({ 'message' : '&nbsp;', 'type' : 'alert-info' // alert-success | alert-info | alert-warning | alert-danger }, options); return this.each(function(){ var alertItem = ''; alertItem = '<div class="alert '+ settings.type +' alert-dismissable" >'; alertItem += '<button class="close" aria-hidden="true" data-dismiss="alert" type="button">×</button>'; alertItem += settings.message; alertItem += '</div>'; $(this).html(alertItem); }); }; //----------------------------------------------------------------------------------------------------------------------------------------------- /* AJAX FORM SUBMIT */ //----------------------------------------------------------------------------------------------------------------------------------------------- // requer plugin ajax.form $.fn.ajaxFormSubmit = function(options){ return this.each(function(){ var settings = $.extend({ type : $(this).attr('method'), url : $(this).attr('action'), divResult : $(this).find('.result'), successMsg : 'As Informações foram atualizadas com sucesso.', success : function(data){ if(data == true){ settings.divResult.resultStatus({'value': '<p>'+ settings.successMsg +'</p>'}); $(document).trigger('AjaxFormTrue'); } else { settings.divResult.resultStatus({'value': '<p>'+ data +'</p>'}); $(document).trigger('AjaxFormFalse'); } }, error : function(data){ settings.divResult.html('Erro de resposta!'); $(document).trigger('AjaxFormError'); } }, options); $(this).submit(function(e){ e.preventDefault(); $(this).ajaxSubmit({ type : settings.type, url : settings.url, success : settings.success, error : settings.error }); }); }); } //------------------------------------------------------------------------------------------------------------------------------------------ // AJAX FORM LOAD //------------------------------------------------------------------------------------------------------------------------------------------ $.fn.ajaxFormLoad = function(options){ return this.each(function(){ var settings = $.extend({ 'type' : $(this).attr('method'), 'url' : $(this).attr('action'), 'act' : ($(this).attr('id') ? $(this).attr('id') : $(this).attr('name'))+ ' Load', 'vars' : '' }, options); var thisForm = $(this); $.ajax({ type: settings.type, url: settings.url, data: { 'act': settings.act, 'vars': settings.vars }, dataType: 'json', success: function(data){ $.each(data, function(index, value){ var item = thisForm.find('#'+index).length ? _thisForm.find('#'+index) : _thisForm.find('name["'+ index +'"]'); item.val(value); }); } }); }); } //----------------------------------------------------------------------------------------------------------------------------------------------- // HACK IMG FLOAT - tira o espaço oposto da imagem de conteúdo //----------------------------------------------------------------------------------------------------------------------------------------------- $.fn.hackImgFloat = function(){ $(this).find('img').each(function(){ $j(this).css('max-width', '100%'); var thisFloat = $(this).css("float"); if(thisFloat == 'right'){ $(this).css('margin-right','0'); } if(thisFloat == 'left'){ $(this).css('margin-left','0'); } }); }; //----------------------------------------------------------------------------------------------------------------------------------------------- // HIDE FORM LABEL //----------------------------------------------------------------------------------------------------------------------------------------------- $.fn.hideFormLabel = function(){ $(this).find('input[type="text"], input[type="password"], textarea, select').each(function(){ var item = $(this); var itemid = item.attr('id') ? item.attr('id') : item.attr('name'); var label = item.parent().find('label[for="'+ itemid +'"]'); label = label.attr('for') ? label : item.parent().find('label'); // se não encontrou o label for, tenta encontrar um label sem identificador var mTop = item.css('padding-top'); var mLeft = item.css('padding-left'); label.css({ 'position' : 'absolute', 'width' : 'auto', 'padding' : 0, 'margin' : 0, 'top' : mTop, 'left' : mLeft, 'z-index' : 2 }); item.focus(labelHide).focusout(labelToogle).change(labelToogle); function labelToogle(){ if((this).val() == ''){ label.show(); } else { labelHide(); } } function labelHide(){ label.hide(); } // já é padrão no label-for label.click(function(){ item.focus(); }); item.focusout(); }); }; //----------------------------------------------------------------------------------------------------------------------------------------------- // NL2BR //----------------------------------------------------------------------------------------------------------------------------------------------- function js_nl2br(str, is_xhtml) { var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br ' + '/>' : '<br>'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); } //------------------------------------------------------------------------------------------------ // PAGE SCROLLING // Rola o conteúdo da página ao clicar //------------------------------------------------------------------------------------------------ $.fn.pageScrolling = function(options){ var settings = $.extend({ 'easing' : '', 'animationTime' : 1500 }, options); return this.each(function(){ $(this).find('a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, settings.animationTime, settings.easing); $(this).parent().parent().find('.active').removeClass('active'); $(this).parent().addClass('active'); $('#menuprincipal.mobile-nav').fadeOut('fast'); event.preventDefault(); }); }); }
var variables__11_8js = [ [ "js", "variables__11_8js.html#a36e8bb713520a15833bafb5d93f8949c", null ], [ "searchData", "variables__11_8js.html#ad01a7523f103d6242ef9b0451861231e", null ] ];
spacesApp.controller( 'navigation.controller', [ function(){ } ] );
angular.module('myModule', []) .directive('myTag1', function () { return { restrict: 'ECAM', template: '<div>myTag1 Template {{ user.id }} {{ user.name }}<span ng-transclude=""></span></div>', transclude: true, replace: true, // false。为 true 时模板内容必须包含在标签内 // compile 改变当前结构 // link 绑定事件 // 以 ng-repeat 为例,如:<div ng-repeat="user in users" my-tag1 my-tag2 my-tag3></div> // 首先 ng-repeat 会复制元素,然后逐一对复制出来的每个元素依次应用 指令: // 所有指令应用前,都会先执行每个指令的 compile 函数 // 在应用指令时,根据优先级依次执行 preLink // 在所有指令应用完之后,从后往前倒序执行 postLink // 接着对 ng-repeat 复制的下一个元素重复上述应用过程 // compile: 直接返回的函数是 postLink,也可以返回一个包含 preLink 和 postLink 的对象 // 想在 DOM 渲染前对它进行变形,并且不需要 scope 参数 // 想在所有相同 directive 里共享某些方法,这时应该定义在 compile 里,性能会比较好 compile: function (tElement, tAttrs, transclude) { console.log('1-001', 'my-tag1 compile 编译阶段'); // tElement 的类型是 angular 内置的 jQuery 对象,表示模板对象 // 此处打印的是修改后的 template DOM console.log('1-002', 'compile - tElement', tElement); // 改变 template DOM 结构 tElement.append(angular.element('<span> --- my-tag1 compile 阶段改变的DOM内容</span>')); console.log('1-003', 'compile - tAttrs', tAttrs); console.log('1-004', 'compile - transclude', transclude); // // 直接返回的函数是 postLink // return function postLink(scope, iElement, iAttrs, controller) { // console.log('1-005', 'link (compile, function) - postLink 所有子元素指令都已连接'); // // // 绑定事件 // iElement.on('click', function () { // console.log('1-005', 'click (compile, function) - postLink'); // }); // }; return { // 在编译阶段之后、指令连接到子元素之前运行 pre: function preLink(scope, iElement, iAttrs, controller) { console.log('1-006', 'link (compile, object) - preLink 连接下一个子元素之前'); }, // 在所有子元素指令都连接之后运行 post: function postLink(scope, iElement, iAttrs, controller) { // 绑定事件 iElement.on('click', function () { console.log('1-007', 'click (compile, object) - postLink'); // 触发脏检查 scope.$apply(function () { scope.user.click_count += 1; }); }); console.log('1-007', 'link (compile, object) - postLink 所有子元素指令都已连接'); }, }; }, // // link: 对特定的元素注册事件,需要用到 scope 参数来实现 DOM 元素的一些行为 // // compile 和 link 同时出现时,忽略 link // // // // 如果是函数,则表示 postLink,也可以是一个包含 preLink 和 postLink 的对象 // link: function postLink(scope, iElement, iAttrs, controller) { // console.log('1-008', 'link (link, function) - postLink 所有子元素指令都已连接'); // // // 绑定事件 // iElement.on('click', function () { // console.log('1-008', 'click (link, function) - postLink'); // }); // }, // // link: { // pre: function preLink(scope, iElement, iAttrs, controller) { // console.log('1-009', 'link (link, object) - preLink 连接下一个子元素之前'); // }, // post: function postLink(scope, iElement, iAttrs, controller) { // console.log('1-010', 'link (link, object) - postLink 所有子元素指令都已连接'); // // // 绑定事件 // iElement.on('click', function () { // console.log('1-009', 'click (link, object) - postLink'); // }); // }, // }, }; }) .directive('myTag2', function () { return { restrict: 'ECAM', // template: '<div>myTag2 Template <div ng-transclude=""></div></div>', // transclude: true, replace: true, // false。为 true 时模板内容必须包含在标签内 // compile: 直接返回的函数是 postLink,也可以返回一个包含 preLink 和 postLink 的对象 // 想在 DOM 渲染前对它进行变形,并且不需要 scope 参数 // 想在所有相同 directive 里共享某些方法,这时应该定义在 compile 里,性能会比较好 compile: function (tElement, tAttrs, transclude) { console.log('2-001', 'my-tag2 compile 编译阶段'); console.log('2-002', 'compile - tElement', tElement); tElement.append(angular.element('<span> --- my-tag2 compile 阶段改变的DOM内容</span>')); console.log('2-003', 'compile - tAttrs', tAttrs); console.log('2-004', 'compile - transclude', transclude); // // 直接返回的函数是 postLink // return postLink function (scope, iElement, iAttrs, controller) { // console.log('2-005', 'link (compile, function) - postLink 所有子元素指令都已连接'); // }; return { // 在编译阶段之后、指令连接到子元素之前运行 pre: function preLink(scope, iElement, iAttrs, controller) { console.log('2-006', 'link (compile, object) - preLink 连接下一个子元素之前'); }, // 在所有子元素指令都连接之后运行 post: function postLink(scope, iElement, iAttrs, controller) { console.log('2-007', 'link (compile, object) - postLink 所有子元素指令都已连接'); }, }; }, // link: 对特定的元素注册事件,需要用到 scope 参数来实现 DOM 元素的一些行为 // compile 和 link 同时出现时,忽略 link // 如果是函数,则表示 postLink,也可以是一个包含 preLink 和 postLink 的对象 // link: function postLink(scope, iElement, iAttrs, controller) { // console.log('2-008', 'link (link, function) - postLink 所有子元素指令都已连接'); // }, // link: { // pre: function preLink(scope, iElement, iAttrs, controller) { // console.log('2-009', 'link (link, object) - preLink 连接下一个子元素之前'); // }, // post: function postLink(scope, iElement, iAttrs, controller) { // console.log('2-010', 'link (link, object) - postLink 所有子元素指令都已连接'); // }, // }, }; }) .directive('myTag3', function () { return { restrict: 'ECAM', // template: '<div>myTag3 Template <div ng-transclude=""></div></div>', // transclude: true, replace: true, // false。为 true 时模板内容必须包含在标签内 // compile: 直接返回的函数是 postLink,也可以返回一个包含 preLink 和 postLink 的对象 // 想在 DOM 渲染前对它进行变形,并且不需要 scope 参数 // 想在所有相同 directive 里共享某些方法,这时应该定义在 compile 里,性能会比较好 compile: function (tElement, tAttrs, transclude) { console.log('3-001', 'my-tag3 compile 编译阶段'); tElement.append(angular.element('<span> --- my-tag3 compile 阶段改变的DOM内容</span>')); console.log('3-002', 'compile - tElement', tElement); console.log('3-003', 'compile - tAttrs', tAttrs); console.log('3-004', 'compile - transclude', transclude); // // 直接返回的函数是 postLink // return postLink function (scope, iElement, iAttrs, controller) { // console.log('3-005', 'link (compile, function) - postLink 所有子元素指令都已连接'); // }; return { // 在编译阶段之后、指令连接到子元素之前运行 pre: function preLink(scope, iElement, iAttrs, controller) { console.log('3-006', 'link (compile, object) - preLink 连接下一个子元素之前'); }, // 在所有子元素指令都连接之后运行 post: function postLink(scope, iElement, iAttrs, controller) { console.log('3-007', 'link (compile, object) - postLink 所有子元素指令都已连接'); }, }; }, // link: 对特定的元素注册事件,需要用到 scope 参数来实现 DOM 元素的一些行为 // compile 和 link 同时出现时,忽略 link // 如果是函数,则表示 postLink,也可以是一个包含 preLink 和 postLink 的对象 // link: function postLink(scope, iElement, iAttrs, controller) { // console.log('3-008', 'link (link, function) - postLink 所有子元素指令都已连接'); // }, // link: { // pre: function preLink(scope, iElement, iAttrs, controller) { // console.log('3-009', 'link (link, object) - preLink 连接下一个子元素之前'); // }, // post: function postLink(scope, iElement, iAttrs, controller) { // console.log('3-010', 'link (link, object) - postLink 所有子元素指令都已连接'); // }, // }, }; }) .directive('myTag4', function () { return function postLink(scope, iElement, iAttrs, controller) { console.log('4-001', 'link (link, function) - postLink 所有子元素指令都已连接'); // 绑定事件 iElement.on('click', function () { console.log('4-002', 'click (compile, object) - postLink'); // 触发脏检查 scope.$apply(function () { scope.user.click_count += 1; }); }); }; }) .controller('firstController', ['$scope', function ($scope) { $scope.users = [ { id: 1, name: '张三', click_count: 0, }, { id: 2, name: '李四', click_count: 0, }, ] ; }]);
import { combineReducers } from 'redux'; import articles from './articles'; import signup from './signup'; import login from './login'; import resetpassword from './resetpassword'; import rating from './rating'; import articlelist from './articlesList'; import profileReducer from './profile'; import like from './like'; import comments from './comments'; import commentList from './commentsList'; import tag from './tag'; import search from './search'; /* * We combine all reducers into a single object before updated data is dispatched (sent) to store * Your entire applications state (store) is just whatever gets returned from all your reducers * */ const allReducers = combineReducers({ articles, articlelist, signup, login, resetpassword, rating, profileReducer, like, comments, commentList, tag, search, }); export default allReducers;
import React from 'react'; import { Title, TextBlock, InvasivePotential, Resources, Resource, Summary, SexualReproduction, AsexualReproduction, EcologicalNiche, PopulationDensity, EnvironmentImpact, ManagementMethod, ManagementApplication, OriginalArea, SecondaryArea, Introduction, Breeding, CaseImage, } from '../components'; import image from '../../../assets/caseDetails/vodni-mor-kanadsky.jpg'; const VodniMorKanadsky = (props) => ( <div> <Title name="Vodní mor kanadský" nameSynonyms="" latinName="Elodea canadensis" latinNameSynonyms={ <> Anacharis canadensis <em>(Michx.) Planch.</em>/Hydora canadensis <em>(Michx.) Besser</em>/Philotria canadensis{' '} <em>(Michx.) Britton.</em>/Serpicula canadensis{' '} <em>(Michx.) Eaton</em>/Udora canadensis{' '} <em>(Michx.) Nutt.</em> </> } /> <Summary> <OriginalArea text="Severní Amerika (USA a Kanada), jinde druhotně" /> <SecondaryArea text="Evropa/Irsko (od roku 1836), ČR (od roku 1879). V současnosti prakticky na celé severní polokouli a v Australii. " /> <Introduction text="Rozšiřován v rámci botanických zahrad, akvaristy a při přesunu rybí násady. Není vyloučeno šíření propagulí vodními ptáky. Druh rozšířen od nížin do podhorských oblastí." /> <Breeding text="V kultuře (uzavřené nádrže) jako akvaristicky využitelný druh." /> </Summary> <CaseImage source={image} copyright="Foto: Chrisitan Fisher" /> <TextBlock> <p> Poměrně vytrvalá ponořená vodní rostlina z čeledí voďankovitých (<i>Hydrocharitaceae</i>). Lodyhy bohatě olistěny drobnými listy v přeslenech po třech. Samičí květy vyrůstají na dlouhých, nitkovitých stopkách. Mají růžové kališní lístky a 3 bělavé korunní lístky. V ČR se vyskytuje pouze populace se samičími květy, proto u nás ke generativnímu rozmnožování nedochází. Samčí jedinci udávaní z Irska – jedná se zřejmě o záměnu s{' '} <i>Elodea nuttallii</i>. </p> <h5>Ekologie a způsob šíření</h5> <p> Hydrofyt, anemofil, hydrochor, K-stratég. Roste ve stojatých i tekoucích vodách od mělkých tůní až po hlubší mrtvá ramena a rybníky. V současné době je výskyt vázán především na poříční tůně, náhony a stoky.V rybnících vzácně, pouze v litorálu, nikoliv v monotypických populacích. Druh náročný na vyšší obsah vápníku ve vodáchméně toleruje kyselé vody. I přesto ho lze považovat za druh se širokou ekologickou amlitudou, včetně tolerance k zastínění. Může se objevovat ve všech typech společenstev vodních rostlin, v případě intentzivního rozvoje potlačuje růst a vývoj drobnolistých typů makrofyt. </p> <p> Množí se výhradně vegetativně. Propagulemi jsou úlomky lodyh a zimní pupeny (propagule). Vzhledem k přirozenému úbytku v rybničních nádržích (lze přisuzovat zejména vysokým rybím obsádkám, neověřeným vlivem je hydrobiologicky potvrzená změna obsahu dusíku a fosforu v rybnících) není nutné žádné razantní opatření.Dříve (60. – 80. léta 20. stol). bylo účinnou formou likvidace zimování a letnění rybníků. </p> </TextBlock> <InvasivePotential> <SexualReproduction score={0} /> <AsexualReproduction score={3} /> <EcologicalNiche score={3} /> <PopulationDensity score={2} /> <EnvironmentImpact score={1} /> <ManagementMethod text="mechanická likvidace, využití specifické rybí obsádky" /> <ManagementApplication text="cíleně se neprovádí" /> </InvasivePotential> <Resources> <Resource> Černý, R. (1994). Vegetace makrofyt tůní a slepých ramen nivy řeky Lužnice a její bioindikační význam. Kandidátská dizertační práce. Pedagogická fakulta JU v Českých Budějovicích. České Budějovice. </Resource> <Resource> Hejný, S. a kol. (2000). Rostliny vod a pobřeží. East West Publisching Company Praha. </Resource> <Resource> Jehlík, V. (ed.) (1998). Cizí expanzní plevele české a Slovenské republiky. Academia Praha. </Resource> <Resource> Stalmachová, B. a kol. (2019). Strategie řešení invazních druhů rostlin v obcích česko-polského pohraničí. IMAGE STUDIO s.r.o., Slezská Ostrava. </Resource> <Resource> Thouvenot, L., Thiébaut, G. (2018). Regeneration and colonization abilities of the invasive species{' '} <i>Elodea canadensis</i> and <i>Elodea nuttallii</i> under a salt gradient: implications for freshwater invasibility. Hydrobiologia, 817(1), 193-203. </Resource> </Resources> </div> ); export default VodniMorKanadsky;
function prixTtc(prixHorsTaxes,nombreArticle,tva){ let ttc = nombreArticle * prixHorsTaxes * (1 + tva); console.log("Votre Prix TTC est de " + ttc + " €"); } prixTtc(15,1,0.20); prixTtc(30,1,0.20); prixTtc(25,1,0.20); prixTtc(14,1,0.20); prixTtc(12,1,0.20); prixTtc(45,1,0.20);
var uid_usuario = ''; var liquidacion_id = 0; var array_index = 0; var liquidaciones = new Array(); var ceco_validacion=true; var orden_validacion=true; var validacion_rechazo=0; var array = new Array(); var gastos_origen = new Array(); jQuery( document ).ready( function( $ ) { $('#loader').show(); window.tabla_registros = jQuery('#tabla-registros').DataTable({ "order": [[ 8, "desc" ]], "columnDefs": [ { "targets": [ 8 ], "visible": false, "searchable": false } ], "oLanguage": { "sLengthMenu": "Mostrando _MENU_ filas", "sSearch": "", "sProcessing": "Procesando...", "sLengthMenu": "Mostrar _MENU_ registros", "sZeroRecords": "No se encontraron resultados", "sEmptyTable": "Ningún dato disponible en esta tabla", "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros", "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros", "sInfoFiltered": "(filtrado de un total de _MAX_ registros)", "sInfoPostFix": "", "sSearch": "Buscar:", "sUrl": "", "sInfoThousands": ",", "sLoadingRecords": "Cargando...", "oPaginate": { "sFirst": "Primero", "sLast": "Último", "sNext": "Siguiente", "sPrevious": "Anterior" } } }); $('.input-date-picker').datepicker({ format: 'dd-mm-yyyy', orientation: "bottom", daysOfWeekDisabled: "7", calendarWeeks: true, autoclose: true, todayHighlight: true }); // Initial functions uid_usuario = localStorage.USUARIO.toUpperCase(); cargarDatosUsuario(uid_usuario); loadData(); delegates(uid_usuario); // Events $('#usuarios').on('change', changeUser); $('#tabla-registros').on('click', 'a.btn-liq-detail', liquidationDetail); $('#btn-aprobar').on('click', aprobLiquidation); $('#btn-rechazar').on('click', rejectLiquidation); $('#btn-send-reject').on('click', sendRejectLiquidation); $('#btn-send-aprob').on('click', sendAprobLiquidation); // Functions function cargarDatosUsuario(usuario) { console.log(usuario); jQuery.ajax({ url: 'ws/sap/data/showmember', type: 'GET', dataType: 'json', async: false, data: {user:usuario} }) .done(function (response) { if (response.result) { // jQuery('#tarjeta_user').val(response.records.MONIBYTE); console.log(response.records); localStorage.setItem('TRAVEL_DATOS_USUARIO', JSON.stringify(response.records)); cargarDatosJefe(usuario); } else { console.log(response.message); } }) } function cargarDatosJefe(usuario) { jQuery.ajax({ url: 'ws/concursos/perfil', type: 'GET', dataType: 'json', data: { user:usuario } }) .done(function (response) { if (response.result) { localStorage.setItem('TRAVEL_DATOS_JEFE', JSON.stringify(response.records.jefe)); } else { console.log(response.message); } }) } function loadData() { $('#loader').show(); window.tabla_registros.clear().draw(); $.ajax({ url: 'ws/travel/liquidacion/historial/aprobaciones', type: 'GET', dataType: 'json', data : {usuario_email:uid_usuario}, }) .done(function(response) { if (response.result) { //console.log(response.records); if (response.records.length > 0) { liquidaciones = response.records; $.each(response.records, function (index, value) { row1 = '<center>'+value.correlativo+'</center>'; row2 = value.nombre_creo; row3 = value.tarjeta !== '' ? '<span class="label label-primary"> Monibyte </span>' : '<span class="label label-success"> No monibyte </span>'; row4 = value.justificacion; row5 = formato_fecha(value.fecha_finalizacion); row6 = formato_fecha(value.fecha_liquidacion); row7 = '<span class="label label-default"> Pendiente </span>'; row8 = '<a data-placement="top" title="Ver" class="toltip btn btn-info btn-xs btn-liq-detail" href="#modal-ver" data-usuario="'+value.usuario_creo+'" data-toggle="modal" data-id="'+value.id+'" data-index="'+index+'"><i class="fa fa-eye"></i> Ver</a>'; row9 = value.updated_at; window.tabla_registros.row.add([row1,row2,row3,row4,row5,row6,row7,row8,row9]).draw(false); }); //console.log(response.records); } else { toastr['success'](response.message, 'Éxito'); } } else { toastr['error'](response.message, 'Error'); } }) .always(function(error){ $('#loader').hide(); }) } function delegates( email ) { $.ajax({ type: 'GET', url: 'ws/travel/liquidaciones/permisos?email='+email, dataType: 'json', }) .done(function(data){ if (data.result) { var bandera = 0; $('.usuarios').remove(); $('#usuarios').append('<option class="usuarios" selected="selected" value="'+localStorage.USUARIO+'">'+localStorage.NOMBRE_USUARIO+'</option>'); $.each(data.records, function(index, valor) { if (valor.aprobacion == 'true') { bandera = 1; $('#usuarios').append('<option class="usuarios" value="'+valor.email_jefe+'">'+valor.nombre_jefe+'</option>'); } }); //console.log(data.records); } else{ toastr['error'](data.message, 'Error'); } }).always( function(){ }); } function changeUser () { uid_usuario = $(this).val(); loadData(uid_usuario); //cargarDatosUsuario(uid_usuario); } function changeOrden () { var id=$(this).data('id'); if ($('.orden'+id).val()) { $('#btn-buscar-ceco'+id).attr('disabled', 'disabled'); $('#btn-buscar-ceco'+id).css('pointer-events', 'none'); $('.ceco'+id).prop('disabled', true); } else { $('#btn-buscar-ceco'+id).removeAttr('disabled', 'disabled'); $('.ceco'+id).prop('disabled', false); $('#btn-buscar-ceco'+id).css('pointer-events', ''); } orden_validacion=false; } function changeCeco () { var id=$(this).data('id'); if ($('.ceco'+id).val()) { $('#btn-buscar-orden'+id).attr('disabled', 'disabled'); $('#btn-buscar-orden'+id).css('pointer-events', 'none'); $('.orden'+id).prop('disabled', true); } else { $('#btn-buscar-orden'+id).removeAttr('disabled', 'disabled'); $('.orden'+id).prop('disabled', false); $('#btn-buscar-orden'+id).css('pointer-events', ''); } ceco_validacion=false; } function searchCeco () { var datos_usuario = JSON.parse(localStorage.TRAVEL_DATOS_USUARIO); $.ajax({ url: 'ws/ordenceco/sociedad', type: 'GET', dataType: 'json', data: {ceco: $('#ceco').val(), orden: $('#orden').val(), sociedad:datos_usuario.SOCIEDAD}, }) .done(function (response) { if (response.result) { toastr['success'](response.message, 'Éxito'); ceco_validacion=true; } else { toastr['error'](response.message, 'Error'); ceco_validacion=false; } }); } function searchOrden () { var datos_usuario = JSON.parse(localStorage.TRAVEL_DATOS_USUARIO); $.ajax({ url: 'ws/ordenceco/sociedad', type: 'GET', dataType: 'json', data: {ceco: $('#ceco').val(), orden: $('#orden').val(), sociedad:datos_usuario.SOCIEDAD}, }) .done(function (response) { if (response.result) { toastr['success'](response.message, 'Éxito'); orden_validacion=true; } else { toastr['error'](response.message, 'Error'); orden_validacion=false; } }); } function liquidationDetail () { $('#loader').fadeOut(); $('#gastos-list').html(''); liquidacion_id = $(this).data('id'); array_index = $(this).data('index'); var datos_usuario = JSON.parse(localStorage.TRAVEL_DATOS_USUARIO); $.ajax({ type: 'GET', url: 'ws/travel/liquidacion/detalles', dataType: 'json', data: {id_liquidacion:liquidacion_id, tarjeta:datos_usuario.MONIBYTE } }) .done(function (response) { //console.log(response.records); if (response.result) { gastos_origen = response.records.gastos; //funcion para editar el gasto function editExpense(e){ console.log("entro"); var validacion_editar = $('.validacion').attr('class'); // if ( validacion_editar == 'validacion btn btn-success' ) { // toastr['error']('Ya se esta editando un gasto por favor guarde los cambios', 'Error'); // } // else { var validacion; var id=$(this).data('id'); validacion= $(this).prop('class'); if ( validacion == 'validacion btn btn-success' ) { $(this).removeClass('btn-success'); $(this).addClass('btn-primary'); $(this).val('Editar Gasto'); $('.ceco'+id).attr('disabled','true'); $('.monto'+id).attr('disabled','true'); $('.orden'+id).attr('disabled','true'); $('.impuesto'+id).attr('disabled','true'); $('.isr'+id).attr('disabled','true'); $('.retencion'+id).attr('disabled','true'); $('.no_retencion'+id).attr('disabled','true'); data = { id_gasto: id, ceco: $('.ceco'+id).val(), orden: $('.orden'+id).val(), monton: $('.monto'+id).val(), impuesto: $('.impuesto'+id).val(), isr: $('.isr'+id).val(), no_retencion: $('.no_retencion').val(), retencion_monto: $('.retencion'+id).val() }; $.ajax({ type: 'POST', url: 'ws/travel/gastos/modificar', dataType: 'json', data: data }) .done(function (response) { if (response.result) { toastr['success'](response.message, 'Éxito'); //console.log(response.records); $('#monton').text(response.records.total); } else { toastr['error'](response.message, 'Error'); } }) .always(function () { $('#loader').fadeOut(); }); // } } else { // $('#no_factura').removeProp('disabled'); // $('#fecha_factura').removeProp('disabled'); // $('#cedula').removeProp('disabled'); // $('#codigo_tributario').removeProp('disabled'); // $('.ceco'+id).removeAttr('disabled'); $('.monto'+id).removeAttr('disabled'); // $('.orden'+id).removeAttr('disabled'); if (response.records.pais=='GT') { $('.isr'+id).removeAttr('disabled'); $('.retencion'+id).removeAttr('disabled'); $('.impuesto'+id).removeAttr('disabled'); } else { if (response.records.sociedad == 'FBEB' || response.records.sociedad == 'FRCN') { $('.impuesto'+id).attr('disabled','true'); } else { $('.impuesto'+id).removeAttr('disabled'); } } $(this).removeClass('btn-primary'); $(this).addClass('btn-success'); $(this).val('Guardar Gasto'); } if ($('.ceco'+id).val() == "") { $('.ceco'+id).attr('disabled','true'); } else { $('.orden'+id).attr('disabled','true'); } // } } moneda = ''; documento = ''; if (response.records.moneda == 0) moneda = '$. '; else if (response.records.moneda == 1) moneda = '₡. '; else moneda = 'Q. '; documento = response.records.pais === 'GT' ? 'NIT' : 'Cédula'; $('#moneda').text(moneda); $('#fecha_finalizacion').text((response.records.fecha_finalizacion)); $('#fecha_liquidacion').text((response.records.fecha_liquidacion)); $('#tipos').text(response.records.tipo); $('#monton').text(response.records.monto); $('#justificacion').text(response.records.justificacion); $('#comentario_rechazado').text(response.records.comentario_rechazado); if (response.records.gastos.length == 0) { toastr['error']('No existen gastos asociados', 'Error'); } else { $.each(response.records.gastos, function (index, value) { // console.log(value) var html = '<div class="panel panel-info detail-expense">'+ '<div class="panel-heading" style="font-size: 1.6em;">'+ '<input id="'+value.id+'" type="checkbox" data-id="'+value.id+'" class="check-expense"/>'+ '<label for="'+value.id+'" class="checkbox">Gasto #'+value.correlativo+' '+ '<input type="button" id="btn-editar-gasto" class="validacion btn btn-primary" data-id="'+value.id+'" style="float:right;" value="Editar Gastos"> </label>'+ '</div>'+ '<div class="panel-body">'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> CECO #</span>'+ '<input type="number" data-id="'+value.id+'" id="ceco" class="ceco form-control ceco'+value.id+'" aria-describedby="basic-addon1" value="'+value.ceco+'" disabled />'+ '<span id="btn-buscar-ceco" class="input-group-addon btn-danger"> <i id="buscarcecoico" class="fa fa-search"></i> </span>'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Monto '+moneda+'</span>'+ '<input type="number" class="form-control monto'+value.id+'" aria-describedby="basic-addon1" value="'+value.monton+'" disabled />'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info">'+documento+'</span>'+ '<input type="text" id="cedula" class="form-control" aria-describedby="basic-addon1" value="'+value.documento+'" disabled />'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Código tributario</span>'+ '<input id="codigo_tributario" type="text" class="form-control" aria-describedby="basic-addon1" value="'+value.codigo_tributario+'" disabled />'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Órden</span>'+ '<input type="number" id="orden" data-id="'+value.id+'" class="orden form-control orden'+value.id+'" aria-describedby="basic-addon1" value="'+value.orden+'" disabled />'+ '<span id="btn-buscar-orden" class="input-group-addon btn-danger"> <i id="buscarcecoico" class="fa fa-search"></i> </span>'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Cuenta gasto</span>'+ '<input class="form-control" aria-describedby="basic-addon1" value="'+value.rubro.nombre+'" disabled />'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info">Número de factura</span>'+ '<input id="no_factura" class="form-control" aria-describedby="basic-addon1" value="'+value.factura+'" disabled />'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Fecha</span>'+ '<input class="form-control input-date-picker id="fecha_factura" type="text" aria-describedby="basic-addon1" value="'+value.fecha+'" disabled/>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12"></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Impuesto '+moneda+'</span>'+ '<input class="form-control impuesto'+value.id+'" type="number" aria-describedby="basic-addon1" value="'+value.impuesto+'" disabled/>'+ '</div>'+ '</div>'+ '<div class="col-lg-6 GT">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> ISR '+moneda+'</span>'+ '<input class="form-control isr'+value.id+'" type="number" aria-describedby="basic-addon1" value="'+value.isr+'" disabled/>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12 GT"></div>'+ '<div class="col-lg-6 GT">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Número de retención</span>'+ '<input class="form-control no_retencion'+value.id+'" type="number" aria-describedby="basic-addon1" value="'+value.retencion_numero+'" disabled/>'+ '</div>'+ '</div>'+ '<div class="col-lg-6 GT">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Retención '+moneda+'</span>'+ '<input class="form-control retencion'+value.id+'" type="number" aria-describedby="basic-addon1" value="'+value.retencion_monto+'" disabled/>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="form-group col-md-12" >'+ '<a class="thumbnail" href="'+value.foto+'" target="_blank"><img src="'+value.foto+'" alt="Little Egret" width="60%" height="60%" border="0"></a>'+ '</div>'+ '<div class="form-group col-md-12 save-update" style="display: none;" data-id="'+value.id+'">'+ '<button type="button" class="btn btn-primary btn-block btn-save-update" data-id="'+value.id+'"> Guardar cambios</button>'+ '</div>'+ '</div>'+ '</div>'; $('#gastos-list').append(html); }); $('.validacion').on('click',editExpense); // $('.ceco').on('keyup', changeCeco); // $('.orden').on('keyup', changeOrden); // $('#btn-buscar-ceco').on('click', searchCeco) // $('#btn-buscar-orden').on('click', searchOrden) response.records.pais === 'CR' ? $('.GT').hide() : $('.GT').show(); } } else { toastr['error'](response.message, 'Error'); } }) .always(function () { $('#loader').fadeOut(); }); } function aprobLiquidation (e) { e.preventDefault(); array = new Array(); contador = 0; no_aprobados=0; $.each($('#gastos-list > div.detail-expense').find('input.check-expense'), function (index, value) { ++contador; if ($(this).is(':checked')) { ++no_aprobados; item = new Object(); item.id = $(this).data('id'); array.push(item); } }); // if (no_aprobados<contador) { // console.log("ingrese un comentario para los que no fueron aprobados") // } else { // console.log("todos han sido aprobados"); // } item_liquidacion = liquidaciones[array_index]; // console.log(item_liquidacion); data = { id_liquidacion: liquidacion_id, tipo: 1, comentario_rechazo: '', json: JSON.stringify(array), empid: item_liquidacion.empid, pais: item_liquidacion.pais, acreedor: item_liquidacion.acreedor, sociedad: item_liquidacion.sociedad, uid_aprobador: uid_usuario, }; if (array.length > 0) { if (array.length < contador) { $('#modal-ver').modal('hide'); $('#modal-aprobar').modal('show'); $('#coments').val(''); } else if (contador >= array.length) { var bolean = false; for (var i = 0; i < gastos_origen.length; i++) { //console.log(gastos_origen); // console.log(gastos_origen[i].monto); if(gastos_origen[i].monton<gastos_origen[i].monto){ //console.log("entro"); bolean = true; break; } } if(bolean){ $('#modal-ver').modal('hide'); $('#modal-aprobar').modal('show'); $('#coments').val(''); } else{ $('#loader').show(); $.ajax({ type: 'POST', url: 'ws/travel/liquidacion/pendientes', dataType: 'json', data: data }) .done(function (response) { if (response.result) { $('#modal-ver').modal('hide'); toastr['success'](response.message, 'Éxito') setTimeout( function(){ amigable(); }, 500); } else { toastr['error'](response.message, 'Error') } }) .always(function () { $('#loader').fadeOut(); }); } } } else { $('#loader').fadeOut(); toastr['warning']('No ha seleccionado ningún gasto para aprobación', 'Espere'); } } function sendAprobLiquidation (e) { e.preventDefault(); item_liquidacion = liquidaciones[array_index]; data = { id_liquidacion: liquidacion_id, tipo: 1, comentario_rechazado: $('#coments').val(), json: JSON.stringify(array), empid: item_liquidacion.empid, pais: item_liquidacion.pais, acreedor: item_liquidacion.acreedor, sociedad: item_liquidacion.sociedad }; $('#loader').show(); $.ajax({ type: 'POST', url: 'ws/travel/liquidacion/pendientes', dataType: 'json', data: data }) .done(function (response) { if (response.result) { $('#modal-ver').modal('hide'); toastr['success'](response.message, 'Éxito') setTimeout( function(){ amigable(); }, 500); } else { toastr['error'](response.message, 'Error') } }) .always(function () { $('#loader').fadeOut(); }); } function rejectLiquidation (e) { e.preventDefault(); $('#modal-ver').modal('hide'); $('#modal-rechazar').modal('show'); $('#coment').val('') console.log('hola'); } function sendRejectLiquidation () { if ($('#coment').val()=='') { toastr['error']('Ingrese un comentario de rechazo para la liquidación', 'Error') } else { $('#loader').show(); array = new Array(); item_liquidacion = liquidaciones[array_index]; data = { id_liquidacion: liquidacion_id, tipo: 2, comentario_rechazado: $('#coment').val(), json: JSON.stringify(array), empid: item_liquidacion.empid, pais: item_liquidacion.pais, acreedor: item_liquidacion.acreedor, sociedad: item_liquidacion.sociedad }; $.ajax({ type: 'POST', url: 'ws/travel/liquidacion/pendientes', dataType: 'json', data: data }) .done(function (response) { if (response.result) { $('#modal-ver').modal('hide'); $('#modal-rechazar').modal('hide'); toastr['success'](response.message, 'Éxito'); setTimeout( function(){ amigable(); }, 500); } else { toastr['error'](response.message, 'Error') } }) .always(function () { $('#loader').fadeOut(); }); } } function formato_fecha(fecha) { var A = new Date(Date.parse(fecha)).getFullYear(); var M = new Date(Date.parse(fecha)).getMonth()+1; var D = new Date(Date.parse(fecha)).getDate()+1; if (M < 10) M = '0' + M; if (D < 10) D = '0' + D; var fecha = D+'-'+M+'-'+A; return fecha; } function formato_fecha2(fecha) { var A = new Date(Date.parse(fecha)).getFullYear(); var M = new Date(Date.parse(fecha)).getMonth()+1; var D = new Date(Date.parse(fecha)).getDate()+1; if (M < 10) M = '0' + M; if (D < 10) D = '0' + D; var fecha = A+'-'+M+'-'+D; return fecha; } function separador_miles_decimales(id) { var valor=id.toString(); var valor=valor.replace(/,/gi, " "); Cantidad=generador.call(valor.split(' ').join(''),' ','.'); } function generador(comma, period) { comma = comma || ','; period = period || '.'; var split = this.toString().split('.'); var numeric = split[0]; var decimal = split.length > 1 ? period + split[1] : ''; var reg = /(\d+)(\d{3})/; while (reg.test(numeric)) { numeric = numeric.replace(reg, '$1' + comma + '$2'); } /*body = a.toFixed(2); */ var total=0; if(decimal.length>1) { if(decimal.length>3){ decimal_pruebas=parseFloat(decimal); decimal_pruebas = decimal_pruebas.toFixed(2); decimal_pruebas >=1?decimal_pruebas = 0.99 :decimal_pruebas=decimal_pruebas; decimal_pruebas = decimal_pruebas.toString(); decimal= decimal_pruebas.replace(/0./gi, "."); //console.log(decimal_pruebas); } numeric=numeric.replace(/ /gi, ","); total=numeric+decimal; }else{ numeric=numeric.replace(/ /gi, ","); total=numeric+decimal; } return total; } jQuery('#gastos').on('click', '.guardar', function(){//----------------------------------------------------->guarda la información de los gastos jQuery('#loader').show(); var id = jQuery(this).data('id'); jQuery('#monton_'+id).val(); jQuery('#orden_'+id).val(); // console.log( { ceco: jQuery('#ceco_'+id).val(), sociedad: jQuery('#sociedad_usuario_creo').val(), orden: jQuery('#orden_'+id).val() } ); jQuery.ajax({ url:'ws/ordenceco/sociedad', type:'POST', dataType: 'json', data : { ceco: jQuery('#ceco_'+id).val(), sociedad: jQuery('#sociedad_usuario_creo').val(), orden: jQuery('#orden_'+id).val() }, }).done(function( data ){ if(data.result){ jQuery.ajax({ url:'ws/travel/gastos/modificar', type:'POST', dataType: 'json', data : {id_gasto: id, ceco: jQuery('#ceco_'+id).val(), monton: jQuery('#monton_'+id).val(), orden: jQuery('#orden_'+id).val() }, }).done(function( data ){ if(data.result){ jQuery('#cecob_'+id).val(jQuery('#ceco_'+id).val()); jQuery('#ordenb_'+id).val(jQuery('#orden_'+id).val()); jQuery('#montonb_'+id).val(jQuery('#monton_'+id).val()); jQuery('#guardar_'+id).hide(); toastr['success']('Se guardaron los cambios en el gasto #TG-'+id, 'Éxito'); jQuery('#loader').fadeOut(); }else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(error){ //console.log(error); toastr['error'](error.message, 'Error'); jQuery('#loader').fadeOut(); }); }else{ toastr['error'](data.records.ZMENSAJE, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(error){ //console.log(error); toastr['error']('Ocurrio un error en la conexión', 'Error'); jQuery('#loader').fadeOut(); }); }) jQuery('#gastos').on('click', '.checkbox', function(){//---------------------------------------------------->agrega o quita los id de los gastos en el json var id = jQuery(this).data('id'); var index = jQuery(this).data('index'); var nombre_clase=jQuery(this).attr('class'); if (nombre_clase=='checkbox checked') { jQuery(this).removeClass('checked'); json.pop(); } else { jQuery(this).addClass('checked'); json.push({'id': id}); } }); jQuery('#gastos').on('keyup', '.cambiar', function(){//----------------------------------------------------->esconder o aparecer el boton de guardar var id = jQuery(this).data('id'); var tipo = jQuery(this).data('tipo'); if(( jQuery('#ceco_'+id).val() != jQuery('#cecob_'+id).val() ) || ( jQuery('#monton_'+id).val() != jQuery('#montonb_'+id).val() ) || ( jQuery('#orden_'+id).val() != jQuery('#ordenb_'+id).val() )) jQuery('#guardar_'+id).show(); else jQuery('#guardar_'+id).hide(); }); jQuery('#btn-aprobars').on('click', function(e){//---------------------------------------------------------->rechazar liquidación e.preventDefault(); // console.log(); if( jQuery('.guardar').is(":visible") ){ toastr['error']('Aun hay cambios que no se han guardado', 'Error'); }else{ var inn = 0; var cnta = json.length; contador = jQuery('.gas-todos > .panel-heading > .checked').length; if (contador == 0 ){ toastr['warning']('No hay líneas seleccionadas para aprobar', 'Cuidado'); }else{ var inn=0; jQuery.each(json, function (index, item) { if(item) inn=inn+1; if( (cnta-1) == index ){ if(inn == todos_gastos){ jQuery('#loader').show(); jQuery('#tipo').val('1'); if( json ) var jsons = JSON.stringify(json); else var jsons = JSON.stringify([]); // console.log('id_liquidacion'+jQuery('#id_liquidacion').val()+' tipo'+jQuery('#tipo').val()+' comentario_rechazado'+jQuery('#coments').val()+'json'+jsons+' pais'+jQuery('#pais_codigo').val+' sociedad'+jQuery('#sociedad_usuario_creo').val()+' empid'+jQuery('#empid').val+' codigo'+jQuery('#codigo').val()+' acreedor'+jQuery('#acreedor_us_cr').val()); jQuery.ajax({ url:'ws/travel/liquidacion/pendientes', type:'POST', dataType: 'json', data : {id_liquidacion: jQuery('#id_liquidacion').val(), tipo: jQuery('#tipo').val(), comentario_rechazado: jQuery('#coments').val(), json: jsons,pais: jQuery('#pais_codigo').val(),sociedad: jQuery('#sociedad_usuario_creo').val()/*jQuery('#sociedad').val()*/,empid: jQuery('#empid').val(),codigo: jQuery('#codigo').val(), acreedor:jQuery('#acreedor_us_cr').val()} }).done(function( data ){ if(data.result){ BD_Cargar(); toastr['success'](data.message, 'Éxito'); jQuery('#loader').fadeOut(); jQuery('#modal-ver').modal('hide'); }else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(error){ //console.log(error); toastr['error'](error.message, 'Error'); jQuery('#loader').fadeOut(); }); // data : {id_liquidacion: jQuery('#id_liquidacion').val(), tipo: jQuery('#tipo').val(), comentario_rechazado: '', json: jsons, pais: jQuery('#pais_codigo').val(),sociedad: jQuery('#sociedad_usuario_creo').val(),empid: jQuery('#empid').val(),codigo: jQuery('#codigo').val(), acreedor:jQuery('#acreedor_us_cr').val()} }else{ jQuery('#loader').fadeOut(); //console.log('no se seleccionaron todos'); jQuery('#tipo').val('2'); jQuery('#modal-aprobar').modal('show'); jQuery('#modal-ver').modal('hide'); } } }); } } }); jQuery('#btn-aprobar-').on('click', function(e){//----------------------------------------------------------->aprobar liquidacion e.preventDefault(); // console.log('id_liquidacion'+jQuery('#id_liquidacion').val()+' tipo'+jQuery('#tipo').val()+' comentario_rechazado'+jQuery('#coments').val()+'json'+jsons+' pais'+jQuery('#pais_codigo').val+' sociedad'+jQuery('#sociedad_usuario_creo').val()+' empid'+jQuery('#empid').val+' codigo'+jQuery('#codigo').val()+' acreedor'+jQuery('#acreedor_us_cr').val()); if( jQuery('#coments').val() ){ jQuery('#loader').show(); if( jQuery('.guardars').is(":visible") ){ toastr['error']('Aun hay cambios que no se han guardado', 'Error'); }else{ jQuery('#tipo').val('1'); if( json ) var jsons = JSON.stringify(json); else var jsons = [{}]; jQuery.ajax({ url:'ws/travel/liquidacion/pendientes', type:'POST', dataType: 'json', data : {id_liquidacion: jQuery('#id_liquidacion').val(), tipo: jQuery('#tipo').val(), comentario_rechazado: jQuery('#coments').val(), json: jsons,pais: jQuery('#pais_codigo').val,sociedad: jQuery('#sociedad_usuario_creo').val()/*jQuery('#sociedad').val()*/,empid: jQuery('#empid').val(),codigo: jQuery('#codigo').val(), acreedor:jQuery('#acreedor_us_cr').val()} }).done(function( data ){ if(data.result){ BD_Cargar(); toastr['success'](data.message, 'Éxito'); jQuery('#loader').fadeOut(); jQuery('#modal-aprobar').modal('hide'); }else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(error){ //console.log(error); toastr['error'](error.message, 'Error'); jQuery('#loader').fadeOut(); }); } }else{ toastr['error']('Sin comentarios', 'Error'); } }); jQuery('#btn-rechazar-').on('click', function(e){//---------------------------------------------------------->rechazar liquidación e.preventDefault(); if( jQuery('.guardars').is(":visible") ){ toastr['error']('Aun hay cambios que no se han guardado', 'Error'); }else{ // if( json.length>0 ){ jQuery('#tipo').val('2'); jQuery('#modal-rechazar').modal('show'); jQuery('#modal-ver').modal('hide'); // }else{ // toastr['warning']('No ha seleccionado los gastos para eliminar', 'Cuidado'); // } } }); jQuery('#btn-rechazar-enviar').on('click', function(e){//--------------------------------------------------->enviar el rechazo e.preventDefault(); var jsons = JSON.stringify([]); jQuery('#loader').show(); if( jQuery('#coment').val() ){ // console.log( jQuery('#empid').val() ); jQuery.ajax({ url:'ws/travel/liquidacion/pendientes', type:'POST', dataType: 'json', data : {id_liquidacion: jQuery('#id_liquidacion').val(), tipo: jQuery('#tipo').val(), comentario_rechazado: jQuery('#coment').val(), json: jsons,pais: jQuery('#pais_codigo').val(),sociedad: jQuery('#sociedad_usuario_creo').val(),empid: jQuery('#empid').val(),codigo: jQuery('#codigo').val(), hola:jQuery('#codigo').val('holass'), acreedor:jQuery('#acreedor_us_cr').val()} }).done(function( data ){ if(data.result){ BD_Cargar(); toastr['success'](data.message, 'Éxito'); jQuery('#loader').fadeOut(); jQuery('#modal-rechazar').modal('hide'); }else{ toastr['error'](data.message, 'Error'); jQuery('#loader').fadeOut(); } }).fail(function(error){ //console.log(error); toastr['error'](error.message, 'Error'); jQuery('#loader').fadeOut(); }); }else{ toastr['warning']('Hace falta el comentario de rechazo', 'Cuidado'); } }); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////------------------------------------------------->BOTONES jQuery('#tabla-registros').on('click','a.btn-liq-detai',function(e){ e.preventDefault(); json = []; jQuery('#coment').val(''); jQuery('#coments').val(''); jQuery('#loader').show(); var id = jQuery(this).data('id'); jQuery('.limpiar').val(''); jQuery('.limpiar').text(''); todos_gastos=0; var soc_usu_ccreo = jQuery(this).data('usuario'); // console.log(soc_usu_ccreo); jQuery.ajax({ type: 'POST', url: 'ws/vsociedadusuario', dataType: 'json', data: {user: soc_usu_ccreo}, }) .done(function(data){ if( data.result ) { jQuery('#pais_codigo').val(data.records.PAIS); pais=data.records.PAIS; //console.log(pais); jQuery('#sociedad_usuario_creo').val(data.records.SOCIEDAD); jQuery('#acreedor_us_cr').val(data.records.ACREEDOR); jQuery('#empid').val(data.records.EMPID); if( jQuery('#pais_codigo').val()=='GT' ){ jQuery('#pais_nombre').val('Guatemala'); } if( jQuery('#pais_codigo').val()=='CR' ){ jQuery('#pais_nombre').val('Costa Rica'); } segunda(); } else toastr['error'](data.message, 'Error'); }).fail(function(err){ //console.log('Pais no se detectó'); }); function segunda(){ jQuery.ajax({ url:'ws/travel/liquidacion/detalles', type:'POST', dataType: 'json', data : {id_liquidacion: id}, }).done(function( data ){ //console.log(data.records); var consulta=data.records; //Liquidaciones jQuery('#id_liquidacion').val(id); jQuery('#myModalLabel').text('Liquidación de gastos #'+consulta.correlativo); switch(consulta.moneda){ case '0': jQuery('#moneda').text('$.'); break; case '1': jQuery('#moneda').text('₡.'); break; case '2': jQuery('#moneda').text('Q.'); break; } if(consulta.estado == 5) jQuery('#rechazado').hide(); else jQuery('#rechazado').show(); // jQuery('#sociedad').val()= consulta.usuario_creo; jQuery('#fecha_finalizacion').text(formato_fecha(consulta.fecha_finalizacion)); jQuery('#fecha_liquidacion').text(formato_fecha(consulta.fecha_liquidacion)); jQuery('#tipos').text(consulta.tipo); jQuery('#monton').text(consulta.monto); jQuery('#justificacion').text(consulta.justificacion); jQuery('#comentario_rechazado').text(consulta.comentario_rechazado); jQuery('#coment').val(''); // Gastos jQuery('.gas-todos').remove(); switch( pais ){ case 'CR': doc = 'Número de Cédula'; var ver = 'none'; break; case 'GT': doc = 'NIT'; var ver = 'block'; break; } if(consulta.gastos.length>0){ var conteo = consulta.gastos.length-1; jQuery.each(consulta.gastos, function (index, valor) { var cecos=''; if( !valor.ceco ) cecos=' disabled="true" ' if( valor.estado == 2 ) var est='<span style="font-size: 0.5em;" class="label label-danger">Reenviada</span>'; else if( valor.estado == 1 ) var est='<span style="font-size: 0.5em;" class="label label-success">Aprobada</span>'; else var est=''; jQuery.ajax({ type: 'GET', url: 'ws/travel/cuentas/detalles', dataType: 'json', }) .done(function(data){ var encuentro=0; var contar=data.records.length-1; jQuery.each(data.records, function (index_GASTO, valor_gasto){ if(valor_gasto.id == valor.cnta_gasto){ valor.cnta_gasto=valor_gasto.cuenta.nombre; encuentro=1; } if(contar == index_GASTO && encuentro==0) valor.cnta_gasto='Sin Asignar'; if(contar == index_GASTO){ todos_gastos=todos_gastos+1; if(valor.ceco){ cecoatr='<input minlength="10" maxlength="10" type="text" name="ceco_" id="ceco_'+valor.id+'" '+cecos+' class="form-control cambiar limpiar" data-id="'+valor.id+'" data-tipo="ceco" placeholder="Sin Asignar" aria-describedby="basic-addon1" value="'+valor.ceco+'"/>'; ordenatr='<span type="text" class="form-control limpiar" id="orden_'+valor.id+'" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.orden+'</span>'; }else{ cecoatr='<span type="text" class="form-control limpiar" id="ceco_'+valor.id+'" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.ceco+'</span>'; ordenatr='<input minlength="12" maxlength="12" type="text" name="ceco_" id="orden_'+valor.id+'" class="form-control cambiar limpiar" data-id="'+valor.id+'" data-tipo="orden" placeholder="Sin Asignar" aria-describedby="basic-addon1" value="'+valor.orden+'"/>'; } if (pais=='CR') { doc="Numero de cedula" } else if(pais=='GT') { doc= "Nit" } //console.log(pais); jQuery('#gastos-list').append(''+ '<div class="panel panel-info gas-todos">'+ '<div class="panel-heading" style="font-size: 1.6em;">'+ '<input id="'+index+'" type="checkbox" />'+ '<label for="'+index+'" class="checkbox" data-index="'+index+'" data-id="'+valor.id+'">Gasto #'+valor.correlativo+' '+ '</label>'+ '</div>'+ '<div class="panel-body">'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> CECO #</span>'+cecoatr+ // '<input type="text" name="ceco_" id="ceco_'+valor.id+'" '+cecos+' class="form-control cambiar limpiar" data-id="'+valor.id+'" data-tipo="ceco" placeholder="Sin Asignar" aria-describedby="basic-addon1" value="'+valor.ceco+'"/>'+ '<input style="display: none;" type="hide" name="ceco_" id="cecob_'+valor.id+'" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" value="'+valor.ceco+'"/>'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Monto '+jQuery('#moneda').text()+'</span>'+ '<input type="text" name="monton_" id="monton_'+valor.id+'" class="form-control cambiar limpiar" data-id="'+valor.id+'" data-tipo="monton" placeholder="Cantidad" aria-describedby="basic-addon1" value="'+valor.monton+'"/>'+ '<input style="display: none;" type="hide" name="monton_" id="montonb_'+valor.id+'" class="form-control" placeholder="Cantidad" aria-describedby="basic-addon1" value="'+valor.monton+'"/>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info">'+doc+'</span>'+ '<span type="text" class="form-control limpiar" placeholder="Cantidad" aria-describedby="basic-addon1" >'+valor.documento+'</span>'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Cód. Tributario</span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1">'+valor.codigo_tributario+'</span>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Órden</span>'+ ordenatr+ '<input style="display: none;" type="hide" name="ceco_" id="ordenb_'+valor.id+'" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" value="'+valor.orden+'"/>'+ // '<input type="text" name="ceco_" id="orden_'+valor.id+'" '+ordenatr+' class="form-control cambiar limpiar" data-id="'+valor.orden+'" data-tipo="ceco" placeholder="Sin Asignar" aria-describedby="basic-addon1" value="'+valor.ceco+'"/>'+ // '<span type="text" class="form-control limpiar" id="orden_'+valor.id+'" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.orden+'</span>'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Cnta. gasto</span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.cnta_gasto+'</span>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Factura #</span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.factura+'</span>'+ '</div>'+ '</div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Fecha</span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+formato_fecha(valor.fecha)+'</span>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="col-lg-6">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Impuesto</span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.impuesto+'</span>'+ '</div>'+ '</div>'+ '<div class="col-lg-6" style="display: '+ver+';">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> ISR </span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.isr+'</span>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" style="display: '+ver+';"></div>'+ '<div class="col-lg-6" style="display: '+ver+';">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Retención #</span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.retencion_numero+'</span>'+ '</div>'+ '</div>'+ '<div class="col-lg-6" style="display: '+ver+';">'+ '<div class="input-group">'+ '<span class="input-group-addon btn-info"> Retención '+jQuery('#moneda').text()+'</span>'+ '<span type="text" class="form-control limpiar" placeholder="Sin Asignar" aria-describedby="basic-addon1" >'+valor.retencion_monto+'</span>'+ '</div>'+ '</div>'+ '<div class="form-group col-md-12" ></div>'+ '<div class="form-group col-md-12" >'+ '<a class="thumbnail" href="'+valor.foto+'" target="_blank"><img src="'+valor.foto+'" alt="Little Egret" width="60%" height="60%" border="0"></a>'+ '</div>'+ '<div class="form-group col-md-12 guardars" style="display: none;" id="guardar_'+valor.id+'">'+ '<button type="button" class="btn btn-primary btn-block guardar" data-id="'+valor.id+'"> Guardar cambios </button>'+ '</div>'+ '</div>'+ '</div>'+ ''); if(conteo == index) jQuery('#loader').hide(); } }); }).fail(function(err){ // console.log('Pais no se detectó'); }); }); } else{ jQuery('#gastos').append(''+ '<div style="font-size: 1.2em;"" class="alert alert-info gas-todos" role="alert"><center>No hay Gastos para esta liquidacion</center></div>'+ ''); jQuery('#loader').hide(); } }) .fail(function(error){console.log('error: ');console.log(error);}) } }); });
import React, { useEffect, useState } from 'react'; import styles from './_login.module.scss'; import banner from './../../static/images/Сгруппировать 647.jpg'; import Button from 'components/UI/Button'; import { useDispatch, useSelector } from 'react-redux'; import { useHistory } from 'react-router-dom'; import { clearState, login, userSelector } from 'store/slices/userSlice'; import { Spin } from 'antd'; import { Link } from 'react-router-dom'; import * as yup from 'yup'; import { yupResolver } from '@hookform/resolvers/yup'; import { openNotification } from 'utils/notifications'; import { useForm } from 'react-hook-form'; import clsx from 'clsx'; import PreloadSpinner from '../../components/UI/PreloadSpinner'; const schema = yup.object({ email: yup.string().required('Это обязательное поле').email('Введите email в корректном формате'), password: yup.string().required('Это обязательное поле'), }); const LoginPage = () => { const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: yupResolver(schema) }); const [DOMLoading, setDOMLoading] = useState(true); const { isSuccess, isError, isLoading, errorMessage, user } = useSelector(userSelector); const dispatch = useDispatch(); const history = useHistory(); const onSubmit = (data) => { dispatch(login(data)); }; useEffect(() => { if (user) { history.push('/'); } return () => { dispatch(clearState()); }; }, [user]); useEffect(() => { const handleDOMLoaded = () => { console.log('worked'); setDOMLoading(false); }; console.log('use effect'); window.addEventListener('load', handleDOMLoaded); return () => { window.removeEventListener('load', handleDOMLoaded); setDOMLoading(false); }; }, []); useEffect(() => { if (isError) { openNotification('error', errorMessage, 10); console.log(errorMessage); console.log('from login page'); dispatch(clearState()); } if (isSuccess) { dispatch(clearState()); openNotification('success', 'Вы успешно вошли в систему'); history.push('/'); } }, [isSuccess, isError]); return ( <div className={styles.login}> {/* {DOMLoading && <PreloadSpinner />} */} <div className={styles.login_left_banner}></div> <div className={styles.login_right_column}> <form className={styles.login_form} onSubmit={handleSubmit(onSubmit)}> <h1 className={styles.login_title}>Войдите в GetByVerto</h1> <div className={styles.login_subtitle}> <span>или создайте </span> <Link to="/register"> <span>учетную запись</span> </Link> </div> {/* {isError ? ( <p className={styles.input_error}>{errorMessage}</p> ) : null} */} <div className={styles.input_wrapper}> <div className={styles.input_item}> <div className={styles.login_email_label}>Адрес электронной почты</div> <input className={clsx({ [styles.input]: true, [styles.input_error]: errors.email, })} type="text" {...register('email')} /> <p className={styles.login_validate}>{errors.email?.message}</p> </div> <div className={styles.input_item}> <div className={styles.login_password_label}> <span>Пароль</span> <span>Забыли пароль?</span> </div> <input className={clsx({ [styles.input]: true, [styles.input_error]: errors.password, })} type="password" {...register('password')} /> <p className={styles.login_validate}>{errors.password?.message}</p> </div> </div> <Button className={styles.login_btn}> {isLoading ? ( <div className="spinner"> <Spin /> </div> ) : ( 'Войдите в систему' )} </Button> </form> </div> </div> ); }; export default LoginPage;
// Global variables var gl; var program; var loopID, isPaused; var then, deltaTime; var KEY_LEFT = 37; var KEY_RIGHT = 39; var KEY_UP = 38; var KEY_DOWN = 40; var KEY_A = 65; var KEY_D = 68; var KEY_F = 70; var KEY_G = 71; var KEY_H = 72; var KEY_P = 80; var KEY_Q = 81; var KEY_S = 83; var KEY_X = 88; var KEY_Z = 90; // Entry document.addEventListener( 'DOMContentLoaded', main, false ); function main () { setup(); isPaused = false; then = 0; loopID = requestAnimationFrame( render ); } // Setup function setup () { // Initialize the GL context const canvas = document.querySelector( '#glCanvas' ); gl = canvas.getContext( 'webgl2' ); // Only continue if WebGL is available and working if ( gl === null ) { alert( 'Unable to initialize WebGL. Your browser or machine may not support it.' ); return; } program = new MainGameLoop(); } // Loop function render ( now ) { // Get time now *= 0.001; // convert to seconds deltaTime = now - then; then = now; // TODO: split to Update(deltaTime) and Draw() // ... // Render program.render(); // Loop loopID = requestAnimationFrame( render ); } // Exit function stop () { cancelAnimationFrame( loopID ); // stop loop program.cleanUp(); console.log( 'Adios!' ); } // Pause function pause () { cancelAnimationFrame( loopID ); // stop loop isPaused = true; console.log( 'Paused' ); } function resume () { isPaused = false; console.log( 'Resumed' ); loopID = requestAnimationFrame( render ); // start loop } document.addEventListener( 'keydown', function ( evt ) { if ( evt.keyCode == KEY_Q ) { stop(); } else if ( evt.keyCode == KEY_P ) { if ( isPaused ) { resume(); } else { pause(); } } } );
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsTextRotationAngledown = { name: 'text_rotation_angledown', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19.4 4.91l-1.06-1.06L7.2 8.27l1.48 1.48 2.19-.92 3.54 3.54-.92 2.19 1.48 1.48L19.4 4.91zm-6.81 3.1l4.87-2.23-2.23 4.87-2.64-2.64zM14.27 21v-4.24l-1.41 1.41-8.84-8.84-1.42 1.42 8.84 8.84L10.03 21h4.24z"/></svg>` };
import React, { Component } from 'react'; import { Link } from "react-router-dom"; import { Formik, Form, Field } from 'formik'; import {userService} from '../services/user.service'; import * as Yup from 'yup'; //Form validation const SignupSchema = Yup.object().shape({ password: Yup.string() .required('Required'), email: Yup.string() .email('Invalid email') .required('Required'), }); class Login extends Component { constructor(props) { super(props); //TODO: if user already logged, redirect him to create cv this.state = { isLoginFailed: false, //for showing error msg }; } //if user already logged, redirect him to cvs componentDidMount(){ if(userService.isUserLogged()) this.toCvs(); } render(){ let errorMsg; if (this.state.isLoginFailed) errorMsg = <div className="text-danger">Login failed, try again!</div> return( <div> <div className="title">Connection</div> <div className="container spacer col-md-4 offset-md-4 col-sm-12 login-form"> {errorMsg} <Formik initialValues={{ password: '', email: '', }} validationSchema={SignupSchema} onSubmit={values => { const { email, password } = values; this.handleLogin(email, password); }} > {({ errors, touched }) => ( <Form> <Field name="email" className="form-control border rounded" placeholder="email"/> {errors.email && touched.email ? ( <div className="text-danger">{errors.email}</div> ) : null} <Field name="password" type="password" className="form-control border rounded" placeholder="password"/> {errors.password && touched.password ? <div className="text-danger">{errors.password}</div> : null} <br/> <div> <button type="submit" className="btn btn-dark">Sign in</button> <p>New? <Link to="/register">Register</Link></p> </div> </Form> )} </Formik> </div> </div> ) } handleLogin (email, password){ userService.login(email, password) .then(response => { console.log(response); return response; }) .then(json => { if (json.data.success) { const { id, name, email, api_token } = json.data.data; let userData = { id, name, email, api_token, timestamp: new Date().toString() }; // save user data in browser local storage localStorage.setItem('user', JSON.stringify(userData)); //REDIRECT to user's cvs this.toCvs(); } //show error msg else this.setState({isLoginFailed:true}); }) .catch(error => { //show error msg this.setState({isLoginFailed:true}); }); } toCvs(){ window.location.href = "/cvs"; } } export default Login;
import React, { Component } from 'react'; import ResetButton from '../helpers/reset'; import distanceCalculator from '../helpers/distanceCalculator'; import { ToastContainer, toast } from 'react-toastify'; import "react-toastify/dist/ReactToastify.css"; export default class TripTracker extends Component { constructor(props) { super(props); this.geolocator = () => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { console.log('Current accuracy:' + position.coords.accuracy + 'm') this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude }); }) } else { console.log("Geolocation is not supported by this browser/Please turn on location services."); } } const customToastId = '1'; this.playEnterSound = () => this.audioEnter.play(); this.toastAlert = () => { toast("You are approaching your stop!", { onOpen: setInterval(this.playEnterSound, 1000), toastId: customToastId }) } } state = { latitude: {}, longitude: {} }; render() { let routeName = (this.props.route).substring(0, (this.props.route).length - 1) let stopName = (this.props.location.Name) let stopLat = this.props.location.Latitude; let stopLong = this.props.location.Longitude; let userLat = this.state.latitude; let userLong = this.state.longitude; let distanceAway = distanceCalculator(stopLat, stopLong, userLat, userLong) console.log(distanceAway) const stopLocation = this.props.location if ((Object.keys(stopLocation).length === 0)) { this.geolocator(); return null } else if (isNaN(this.state.latitude) || isNaN(this.state.longitude)) { this.geolocator(); return <div>Loading... Please confirm your internet connection</div> } else if (distanceAway > 500) { this.geolocator(); return ( <> <div className='layer trackingRoute'> <div className='trackingRoute__title'>You are en route!</div> <div className='trackingRoute__info'>Tracking route: {routeName} </div> <div className='trackingRoute__info'>Tracking stop: {stopName}</div> <div className='trackingRoute__info'>You are currently {Math.trunc(distanceAway)}m from your destination </div> <form className='trackingRoute__form'> <button type='button' onClick={ResetButton} className='trackingRoute__endTracking'>Cancel Tracking</button> </form> </div> </> ) } else if (distanceAway < 500) { this.toastAlert(); return ( <> <div className='layer trackingRoute arrival'> <div className='trackingRoute__title'>Alert!</div> <div className='trackingRoute__info--approaching'>You are approaching: {stopName}</div> <form className='trackingRoute__form'> <button type='button' onClick={ResetButton} className='trackingRoute__endTracking'>End trip!</button> </form> </div> <audio ref={r => (this.audioEnter = r)}> <source src="https://notificationsounds.com/soundfiles/a86c450b76fb8c371afead6410d55534/file-sounds-1108-slow-spring-board.mp3" type="audio/mpeg" /> </audio> <ToastContainer position="bottom-center" autoClose={false} hideProgressBar={true} /> </> ) } } }
const config = require('../../src/config'); const pactum = require('../../src/index'); const { addInteractionHandler, addWaitHandler } = pactum.handler; const { expect } = require('chai'); describe('Non CRUD Requests - Numbered Waits', () => { before(() => { addInteractionHandler('get bg', () => { return { background: true, request: { method: 'GET', path: '/api/bg' }, response: { status: 200 } } }); config.response.wait.duration = 10; config.response.wait.polling = 1; }); it('should exercise bg interaction without wait', async () => { await pactum.spec() .useInteraction('get bg') .get('http://localhost:9393/api/bg') .expectStatus(200); }); it('should exercise bg interaction with default wait', async () => { await pactum.spec() .useInteraction('get bg') .get('http://localhost:9393/api/bg') .expectStatus(200) .wait(); }); it('should fail with response exceptions when bg interactions are present', async () => { let err; try { await pactum.spec() .useLogLevel('ERROR') .useInteraction('get bg') .get('http://localhost:9393/api/bg/fake') .expectStatus(200); } catch (error) { err = error } expect(err.message).equals('HTTP status 404 !== 200'); }); it('should fail when bg interactions are not exercised without any waits', async () => { let err; try { await pactum.spec() .useLogLevel('ERROR') .useInteraction('get bg') .get('http://localhost:9393/api/bg/fake') .expectStatus(404); } catch (error) { err = error } expect(err.message).equals('Interaction not exercised: GET - /api/bg'); }); it('should fail when bg interactions are not exercised with default waits', async () => { let err; try { await pactum.spec() .useLogLevel('ERROR') .useInteraction('get bg') .get('http://localhost:9393/api/bg/fake') .expectStatus(404) .wait(); } catch (error) { err = error } expect(err.message).equals('Interaction not exercised: GET - /api/bg'); }); it('should fail when bg interactions are not exercised with custom wait with duration', async () => { let err; try { await pactum.spec() .useLogLevel('ERROR') .useInteraction('get bg') .get('http://localhost:9393/api/bg/fake') .expectStatus(404) .wait(20); } catch (error) { err = error } expect(err.message).equals('Interaction not exercised: GET - /api/bg'); }); it('should fail when bg interactions are not exercised with custom wait with duration and polling', async () => { let err; try { await pactum.spec() .useLogLevel('ERROR') .useInteraction('get bg') .get('http://localhost:9393/api/bg/fake') .expectStatus(404) .wait(20, 7); } catch (error) { err = error } expect(err.message).equals('Interaction not exercised: GET - /api/bg'); }); }); describe('Non CRUD Requests - Wait Handlers', () => { before(() => { addInteractionHandler('get bg', () => { return { background: true, request: { method: 'GET', path: '/api/bg' }, response: { status: 200 } } }); addWaitHandler('send request to /api/bg', async (ctx) => { await pactum.spec() .get('http://localhost:9393/api/bg') .expectStatus(ctx.data || 200); }); config.response.wait.duration = 10; config.response.wait.polling = 1; }); it('should exercise bg interaction with wait handler', async () => { await pactum.spec() .useInteraction('get bg') .get('http://localhost:9393/api/bg/1') .expectStatus(404) .wait('send request to /api/bg'); }); it('should wait without background interactions', async () => { await pactum.spec() .get('http://localhost:9393/api/bg/1') .expectStatus(404) .wait('send request to /api/bg', 404); }); it('should fail when wait handler fails', async () => { let err; try { await pactum.spec() .get('http://localhost:9393/api/bg/1') .expectStatus(404) .wait('send request to /api/bg', 500); } catch (error) { err = error; } expect(err.message).equals('HTTP status 404 !== 500'); }); });
import PositionTool from "./positionTool"; import * as Registry from "../../core/registry"; import Feature from "../../core/feature"; import CustomComponent from "../../core/customComponent"; import Params from "../../core/params"; import Component from "../../core/component"; export default class CustomComponentPositionTool extends PositionTool { constructor(customcomponent, setString) { super(customcomponent.type, setString); this.__customComponent = customcomponent; } createNewFeature(point) { let featureIDs = []; // console.log("Custom Component:", this.__customComponent); let newFeature = Feature.makeCustomComponentFeature(this.__customComponent, this.setString, { position: PositionTool.getTarget(point) }); this.currentFeatureID = newFeature.getID(); Registry.currentLayer.addFeature(newFeature); featureIDs.push(newFeature.getID()); let params_to_copy = newFeature.getParams(); //TODO: Change the component generation this.createNewCustomComponent(params_to_copy, featureIDs); Registry.viewManager.saveDeviceState(); } showTarget() { let target = PositionTool.getTarget(this.lastPoint); Registry.viewManager.updateTarget(this.typeString, this.setString, target); } createNewCustomComponent(paramdata, featureIDs) { let definition = CustomComponent.defaultParameterDefinitions(); //Clean Param Data let cleanparamdata = {}; for (let key in paramdata) { cleanparamdata[key] = paramdata[key].getValue(); } // console.log(cleanparamdata); let params = new Params(cleanparamdata, definition.unique, definition.heritable); let componentid = Feature.generateID(); console.log(this.__customComponent.entity, this.__customComponent.type); let name = Registry.currentDevice.generateNewName(this.__customComponent.entity); let newComponent = new Component(this.__customComponent.entity, params, name, this.__customComponent.entity, componentid); let feature; for (let i in featureIDs) { newComponent.addFeatureID(featureIDs[i]); //Update the component reference feature = Registry.currentDevice.getFeatureByID(featureIDs[i]); feature.referenceID = componentid; } Registry.currentDevice.addComponent(newComponent); return newComponent; } }
var dirfilter = require ("./dirfilter.js"); var file_path = process.argv[2]; var extension = process.argv[3]; var callback = function(err, data) { i = 0; if (err) throw err; while (i < data.length) { console.log(data[i]); i++; }; }; dirfilter(file_path, extension, callback);
$(document).ready(function(){ // VARIABLES var alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); var computerChoice = alphabet[Math.floor(Math.random() * alphabet.length)]; var winCounter = 0; var loseCounter = 0; var guessCounter = 9; var guessedLetters = []; // FUNCTIONS function addWin(){ winCounter++; var winner = document.getElementById("wins"); winner.innerHTML = winCounter; } function addLoss(){ loseCounter++; var loser = document.getElementById("losses"); loser.innerHTML = loseCounter; } function subtractGuess(){ guessCounter--; var guesses = document.getElementById("guesses-left"); guesses.innerHTML = guessCounter; } function listOfGuesses(){ var yourGuess = document.getElementById("your-guesses"); yourGuess.innerHTML = guessedLetters; } // ONKEYUP document.onkeyup = function(event){ var letter = String.fromCharCode(event.keyCode).toLowerCase(); if(letter === computerChoice){ addWin(); // bring guessCounter back to 9. // empty guessedLetters array. } else if(letter !== computerChoice){ subtractGuess(); // add the letter to the guessedLetters array. // when guessesCounter goes below zero, add one to loseCounter. // bring guessCounter back to 9. // empty guessedLetters array. } if(guessCounter === 0){ winCounter = 0; loseCounter++; guessCounter = 9; guessedLetters = []; } } });
module.exports = { async show(req, res) { res.setHeader('Content-Type', 'application/json') return res.status(200).send(true) }, async delete(req, res) { return res.status(204).send("delete") } }
// configuring our routes // ============================================================================= app.config(function($stateProvider, $urlRouterProvider) { $stateProvider //route to show the main page //base page .state('base',{ url: '/base', templateUrl: 'templates/base.html', controller: 'formController' }) .state('base.home', { url: '/baseHome', template: '<lol-home></lol-home>' }) // .state('base.dthree', { // url: '/basedthree', // template:'<div lol-dthree bar-height="20" bar-padding="5" data="data"></div>', // controller: 'dthreeCtrl' // }) .state('base.champions', { url: '/baseChampions', template:'<lol-champions></lol-champions>' }) .state('base.items', { url: '/baseItems', template: '<lol-items></lol-items>' }) .state('base.rank', { url: '/baseRank', template: '<lol-rank></lol-rank>' }) .state('base.live',{ url:'/baseLive', template: '<lol-live></lol-live>' }) .state('base.player',{ url:'/basePlayer', template:'<lol-player></lol-player>' }) .state('base.champDetail',{ url:'/baseChampDetail', template:'<lol-championdetail></lol-championdetail>' }) .state('base.home.general',{ url:'/baseChampionGeneral', template: '<lol-champions-general></lol-champions-general>' }) .state('base.home.champions',{ url:'/baseChampionChampions', template: '<lol-champions-champions></lol-champions-champions>' }) .state('base.home.charts',{ url:'/baseChampionCharts', template: '<lol-champions-charts></lol-champions-charts>' }) .state('base.home.match',{ url:'/baseChampionMatch', template: '<lol-champions-match></lol-champions-match>' }) .state('base.home.matchDetail',{ url:'/baseChampionMatchDetail', template: '<lol-champions-match-detail></lol-champions-match-detail>' }) ; $urlRouterProvider.otherwise('/base/baseHome'); });
import { publicApi } from '../api/api'; export default { fetchToken(userId, code) { return publicApi .get(`/api/token/${userId}/${code}`); } }
const chai = require('chai'); const chaiHttp = require('chai-http'); const mongoose = require("mongoose"); let server = require('../src/server'); let PokemonModel = require('../api/models/pokemon.model'); chai.use(chaiHttp); let should = chai.should(); describe('Pokemon', () => { beforeEach((done) => { //Before each test we empty the database PokemonModel.deleteMany({}, (err) => { done(); }) }); describe('/GET Pokemons', () => { it('it should GET all the pokemons', (done) => { chai.request(server) .get('/api/pokemons') .end((err, res) => { res.should.have.status(200); res.body.should.be.a('array'); done(); }); }); }); describe('/POST Pokemons', () => { it('it should POST a pokemon', (done) => { let pokemon = { number:"001", name:"Bulbasaur", generation:"Generation I", about:"Bulbasaur can be seen napping in bright sunlight. There is a seed on its back. By soaking up the sun's rays, the seed grows progressively larger.", types:["Grass","Poison"], resistant:["Water","Electric","Grass","Fighting","Fairy"], weaknesses:["Fire","Ice","Flying","Psychic"], fastAttack:[{"Name":"Tackle","Type":"Normal","Damage":12}, {"Name":"Vine Whip","Type":"Grass","Damage":7}], specialAttack:[{"Name":"Power Whip","Type":"Grass","Damage":70}, {"Name":"Seed Bomb","Type":"Grass","Damage":40}, {"Name":"Sludge Bomb","Type":"Poison","Damage":55}], weight:{"Minimum":"6.04kg","Maximum":"7.76kg"}, height:{"Minimum":"0.61m","Maximum":"0.79m"}, buddyDistance:"3km (Medium)", baseStamina:"90 stamina points.", baseAttack:"118 attack points.", baseDefense:"118 defense points.", baseFleeRate:"10% chance to flee.", nextEvolutionRequirements:{Amount:25,Name:"Bulbasaur candies"}, nextEvolution:[{Number:2,Name:"Ivysaur"},{Number:3,Name:"Venusaur"}], maxCP:951, maxHP:1071 } chai.request(server) .post('/api/pokemons') .send(pokemon) .end((err, res) => { res.should.have.status(200); res.body.should.be.a('object'); done(); }); }); }); afterEach((done) => { //Before each test we empty the database PokemonModel.deleteMany({}, (err) => { done(); }) }); });
_socialQueue.push({ url: 'http://api.flattr.com/js/0.6/load.js?mode=auto&uid=gargamel&language=sv_SE&category=text', id: '<?php echo $this->name; ?>', onload: function(f) { if ('<?php echo $this->fadeIn; ?>') { f.awaitRender({ buttons: document.getElementsByClassName('coi-social-button-<?php echo $this->name; ?>'), duration: '<?php echo $this->fadeIn; ?>', isRendered: function(element) { return element.getElementsByTagName('IFRAME')[0]; }, renderedMethod: function(b, d) { f.iframeOnload(b.getElementsByTagName('IFRAME')[0], b, d); } }); } } });
$(document).ready(function () { //PARTICLES SETUP particlesJS('particles-js', { "particles": { "number": { "value": 65, "density": { "enable": true, "value_area": 800, }, }, "color": { "value": "#d9d9d9", }, "shape": { "type": "circle", "stroke": { "width": 0, "color": "#000000", }, "polygon": { "nb_sides": 5, }, }, "opacity": { "value": 1, "random": false, "anim": { "enable": false, "speed": 1, "opacity_min": 0.1, "sync": false, }, }, "size": { "value": 5, "random": true, "anim": { "enable": false, "speed": 40, "size_min": 0.1, "sync": false, }, }, "line_linked": { "enable": true, "distance": 150, "color": "#ffffff", "opacity": 0.4, "width": 2, }, "move": { "enable": true, "speed": 3, "direction": "bottom", "random": false, "straight": false, "out_mode": "out", "bounce": false, "attract": { "enable": false, "rotateX": 600, "rotateY": 1200, }, }, }, "interactivity": { "detect_on": "canvas", "events": { "onhover": { "enable": true, "mode": "grab", }, "onclick": { "enable": false, "mode": "push", }, "resize": true, }, "modes": { "grab": { "distance": 150, "line_linked": { "opacity": 1, }, }, "bubble": { "distance": 400, "size": 40, "duration": 2, "opacity": 8, "speed": 3, }, "repulse": { "distance": 200, "duration": 0.4, }, "push": { "particles_nb": 4, }, "remove": { "particles_nb": 2, }, }, }, "retina_detect": true, } , function() { console.log('callback - particles.js config loaded'); }); //----------- $("#listSearch").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#friendList li").filter(function() { $(this).toggle($(this).attr('username_friend').toLowerCase().indexOf(value) > -1) }); }); $('.button_request_yes').on('click',function(e){ $.ajax({ type:'POST', url:'accept_friend/' + $(this).attr('username_btn'), data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(json){ request_refresh_inbox(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }); $('.remove_friend_btn').on('click',function(e){ console.log('POST: /remove_friend/' + $(this).attr('username_value')); $.ajax({ type:'POST', url:'/remove_friend/' + $(this).attr('username_value'), data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(json){ //$("div button[username_value='" + json.username + "']").remove(); request_refresh_friend_list(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }); $('.clear_btn').on('click',function(e){ $.ajax({ type:'POST', url:'clear_notifications', data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(json){ $("li[username_req='" + json.username + "']").remove(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }); $(window).resize(function() { $('.social_tab').css('height','100%').css('height','-=83px'); }); $('.social_tab').css('height','100%').css('height','-=83px'); var toggledFriends = false; $('.toggle_friends').on("click", function(){ if(toggledFriends==true){ $('.social_tab').css('margin-right','-418px'); toggledFriends=false; } else{ $('.social_tab').css('margin-right','0'); toggledFriends=true; } }) }); function fill_notifications(data) { notification_list = document.querySelector('.live_notify_list'); notification_list.innerHTML = ""; template_notification = document.querySelector('#template_notification'); var notif_count = 0; for (var i = 0; i < data.unread_list.length; i++) { msg = data.unread_list[i]; if(data.unread_list[i].data.type === 'NOTIFICATION'){ notif_count++; list_item = template_notification.content.cloneNode(true); list_item.querySelector('.notification_verb').textContent = data.unread_list[i].verb; console.log(list_item); list_item.querySelector('.selectable-notification').setAttribute('notification_id', data.unread_list[i].id); list_item.querySelector('.username_link').setAttribute('href',data.unread_list[i].data.href); list_item.querySelector('.username_link').textContent = data.unread_list[i].data.username + " "; list_item.querySelector('.profile_img_req').setAttribute('src', data.unread_list[i].data.image_path); var close_btn = list_item.querySelector('.close_notification'); var x = data; var y = i; list_item.querySelector('.accept_transfer_button').onclick = function(){ console.log(x); console.log(y); window.location.href = x.unread_list[y].data.href; }; console.log(data.unread_list[i]); notification_list.appendChild(list_item); itm = notification_list.childNodes[notification_list.childNodes.length-1]; console.log('SOAAAAAAA') console.log(itm); document.querySelector('#notification_count').childNodes[0]; close_btn.onclick = function(e){ console.log('CLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOSEEEEEEEEEEEEEE'); if (!e) e = window.event; //IE9 & Other Browsers if (e.stopPropagation) { e.stopPropagation(); } //IE8 and Lower else { e.cancelBubble = true; } $.ajax({ type:'POST', url:'/clear_notification/' + data.unread_list[y].id, data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(json){ request_refresh_inbox(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }; } } document.querySelector('#notification_count').childNodes[0].nodeValue ="Notifications (" + notif_count + ")"; } function fill_friend_requests(data) { request_refresh_friend_list(); notification_list = document.querySelector('.live_friend_request_list'); notification_list.innerHTML = ""; template_notification = document.querySelector('#template_friend_request'); var request_count = 0; for (var i = 0; i < data.unread_list.length; i++) { msg = data.unread_list[i]; if(data.unread_list[i].data.type === 'FRIEND_REQUEST'){ request_count++; list_item = template_notification.content.cloneNode(true); list_item.querySelector('.request_verb').textContent = data.unread_list[i].verb; list_item.querySelector('.username_link').setAttribute('href',data.unread_list[i].data.href); list_item.querySelector('.username_link').textContent = data.unread_list[i].data.username + " "; list_item.querySelector('.profile_img_req').setAttribute('src', data.unread_list[i].data.image_path); var x = data; var y = i; list_item.querySelector('.accept_friend_button').onclick = function(){ $.ajax({ type:'POST', url: x.unread_list[y].data.href, data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(json){ request_refresh_inbox(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }; var close_btn = list_item.querySelector('.close_friend_request'); close_btn.onclick = function(e){ console.log('CLOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOSEEEEEEEEEEEEEE'); if (!e) e = window.event; //IE9 & Other Browsers if (e.stopPropagation) { e.stopPropagation(); } //IE8 and Lower else { e.cancelBubble = true; } $.ajax({ type:'POST', url:'/decline_friend/' + data.unread_list[y].data.username, data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(json){ request_refresh_inbox(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }; notification_list.appendChild(list_item); } } document.querySelector('#friend_request_count').childNodes[0].nodeValue ="Friend Requests (" + request_count + ")"; } function refresh_friend_list(data){ console.log('REFRESH FRIEND LIST') console.log(data) friendListElement = document.querySelector('#friendList'); friendListElement.innerHTML=""; template_notification = document.querySelector('#templateFriend'); for(var i = 0; i < data.length; i++){ var friend = data[0]; new_friend = template_notification.content.cloneNode(true); console.log(friend); new_friend.querySelector(".friend_username").textContent = friend.username; new_friend.querySelector(".set_username_friend").setAttribute('username_friend',friend.username); new_friend.querySelector(".profile_img_friend").src = friend.imageurl; new_friend.querySelector(".set_profile_href").href = '/profile/' + friend.username; new_friend.querySelector(".set_start_session_href").href = '/live_transfer/' + friend.username; new_friend.querySelector(".set_username_value").setAttribute('username_value', friend.username); console.log(new_friend); console.log(friendListElement); friendListElement.appendChild(new_friend); } document.querySelector('#friend_count').textContent = "Friend List (" + data.length + ")"; $('.remove_friend_btn').on('click',function(e){ console.log('POST: /remove_friend/' + $(this).attr('username_value')); $.ajax({ type:'POST', url:'/remove_friend/' + $(this).attr('username_value'), data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(json){ //$("div button[username_value='" + json.username + "']").remove(); request_refresh_friend_list(); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }); /* <a class="dropdown-toggle inline set_text_content" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ friend.username }} </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <a class="dropdown-item set_profile_href" href="{% url 'accounts:profile' friend.username %}">View profile</a> <a class="dropdown-item set_start_session_href" href="{% url 'transfers:start_session_user' friend.username %}">Send files...</a> <button style="border:0;background:inherit;margin:0;padding-left:10px;" username_value = "{{friend.username}}" class="set username_value dropdown-item remove_friend_btn">Remove Friend</button> </div> */ } function request_refresh_friend_list(){ //GET /inbox/notifications/api/unread_list/?max=5 console.log('GET /friend_list/'); $.ajax({ type:'GET', url:'/friend_list/', data:{ }, success:function(data){ refresh_friend_list(data) }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); } function request_refresh_inbox(){ //GET /inbox/notifications/api/unread_list/?max=5 $.ajax({ type:'GET', url:'/inbox/notifications/api/unread_list/?max=5', data:{ csrfmiddlewaretoken: window.csrf_token, }, success:function(data){ fill_notifications(data); fill_friend_requests(data); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console }, }); }
import {FEED_BREED_DATA} from '../types/BreedsTypes'; const INITIAL_STATE = { breeds: {}, }; const BreedsReducer = (state = INITIAL_STATE, action) => { switch (action.type) { case FEED_BREED_DATA: return { ...state, breeds: {...state.breeds, ...action.payload}}; default: return state; } }; export default BreedsReducer;
import React, { Component } from 'react'; class Signinbutton extends Component { render() { return <div> <div className="container"> <div className="row"> <div className="col s12 center-align button-margin button-style"> <a className="waves-effect waves-light btn black" onClick={() => location.href='/auth/uber'}>SIGN IN</a> </div> </div> </div> </div> } } export default Signinbutton;
function changeColorRed(){ document.getElementById('free').style.borderTop = "5px solid red"; } function changeColorBlue(){ document.getElementById('professional').style.borderTop = "5px solid blue"; } function changeColorOrange(){ document.getElementById('enterprise').style.borderTop = "5px solid orange"; }