text
stringlengths
7
3.69M
import React from "react" import { Flex } from "rebass" import PaginationDot from "./dot" export default ({ onChangeIndex, index, dots, bottom, right, top, left }) => { const handleClick = (_, index) => { onChangeIndex(index) } const children = [] for (let i = 0; i < dots; i += 1) { children.push( <PaginationDot key={i} index={i} active={i === index} onClick={handleClick} /> ) } return ( <Flex style={{ position: `absolute`, bottom: bottom ? bottom : "", right: right ? right : "", top: top ? top : "", left: left ? left : "", }} > {children} </Flex> ) }
import React from "react"; import ReactDOM from "react-dom"; import { Provider } from "react-redux"; import { configureStore } from "./store"; import MessageList from "./components/MessageList"; import { ThemeProvider, createTheme, makeStyles, } from "@material-ui/core/styles"; const useGlobalStyles = makeStyles({ "@global": { body: { padding: 0, margin: 0, fontFamily: "Playfair Display", }, }, }); const theme = createTheme({ typography: { h1: { fontSize: "3rem", fontFamily: "Playfair Display", }, h2: { fontSize: "2.75rem", fontFamily: "Playfair Display", }, h3: { fontSize: "2.5rem", fontFamily: "Playfair Display", }, h4: { fontSize: "2rem", fontFamily: "Playfair Display", }, h5: { fontFamily: "Playfair Display", }, subtitle1: { fontFamily: "Playfair Display", }, }, }); const store = configureStore(); function App() { useGlobalStyles(); return ( <Provider store={store}> <ThemeProvider theme={theme}> <MessageList /> </ThemeProvider> </Provider> ); } ReactDOM.render(<App />, document.getElementById("root"));
var $APP = (function(){ var $q = document.getElementById('q'); var $page = document.getElementById('page'); var $lightbox = document.getElementById('lightbox'); var $lightboxOverlay = document.getElementById('lightboxOverlay'); var $lightboxContent = document.getElementById('lightboxContent'); var $navNext = document.getElementById('navNext'); var $navPrev = document.getElementById('navPrev'); var $filters = document.getElementById('filters'); var response = {}; var args = {q:$q.value,page:$page.value}; var current_data = {}; var isMobile = function(){ if(window.innerWidth < 768){ return true; } return false; } var isEmpty = function(obj) { for(var prop in obj) { if(obj.hasOwnProperty(prop)){ return false; } } return true; }; var bindListener = function(){ var form = document.getElementById('search') || document.forms[0]; var elems = form.elements; var serialized = []; var len = elems.length var _args = {}; for(var i = 0; i < len; i += 1){ var type = elems[i].type; switch(type){ case 'radio': case 'checkbox': case 'select-one': elems[i].addEventListener('change', function(){ $APP.onSubmit(null, {page:1}); }); break; default: break; } } }; var getFormData = function(){ //collect form data and returns an object representation of it var form = document.getElementById('search') || document.forms[0]; var elems = form.elements; var serialized = []; var len = elems.length var _args = {}; for(var i = 0; i < len; i += 1) { var element = elems[i]; var type = element.type; var name = element.name; var value = element.value; switch(type) { case 'text': case 'textarea': case 'hidden': _args[name] = value; break; case 'radio': case 'checkbox': if(element.checked){ _args[name] = value; } break; case 'select-one': _args[element.name] = element.options[element.selectedIndex].value; break; default: break; } } return _args; }; var onSubmit = function(event, _args){ if(event){ //set to page 1 event.preventDefault(); $page.value = 1; } args = $HTTP.extend({}, getFormData(), _args); //make the call $HTTP.get(args); }; var onClick = function(index){ current_data = $APP.response.hits[index]; var image = document.createElement('img'); var titleBar = document.createElement('div'); var top = window.pageYOffset || document.documentElement.scrollTop; $lightboxContent.innerHTML = ''; image.onload = function(){ $lightbox.style.marginLeft = image.width*-0.5+'px'; if(isMobile()){ $lightbox.style.marginTop = top+'px'; } else{ $lightbox.style.marginTop = image.height*-0.5+'px'; } $lightbox.style.display = 'block'; $lightboxOverlay.style.display = 'block'; } image.setAttribute('src', current_data.webformatURL); titleBar.setAttribute('class', 'lightbox-title'); titleBar.innerHTML = current_data.tags; $lightboxContent.appendChild(image); $lightboxContent.appendChild(titleBar); updateNav(index); }; var imageLoaded = function(_this){ if(_this.parentNode !== null){ _this.parentNode.querySelector('.spinner').style.display = 'none'; fadeIn(_this); } }; var updateNav = function(current_index){ var has_next = (current_index < $APP.response.hits.length-1)?true:false; var has_prev = current_index; if(has_next){ $navNext.style.display = 'block'; $navNext.setAttribute('onclick', '$APP.onClick('+(current_index+1)+')'); } else{ $navNext.style.display = 'none'; } if(has_prev){ $navPrev.style.display = 'block'; $navPrev.setAttribute('onclick', '$APP.onClick('+(current_index-1)+')'); } else{ $navPrev.style.display = 'none'; } }; var toggleFilter = function(_this){ if($filters.style.display != 'block'){ _this.style.opacity = 1; $filters.style.display = 'block'; } else{ _this.style.opacity = 0.4; //so that it appears when the window is resized $filters.removeAttribute('style'); } }; var fadeOut = function(){ $lightbox.style.display = 'none'; $lightboxOverlay.style.display = 'none'; }; var fadeIn = function(el) { var opacity = 0; el.style.opacity = 0; el.style.filter = ''; var last = +new Date(); var tick = function() { opacity += (new Date() - last) / 400; el.style.opacity = opacity; el.style.filter = 'alpha(opacity=' + (100 * opacity)|0 + ')'; last = +new Date(); if (opacity < 1) { (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16); } }; tick(); } var updateFields = function(){ $page.value = args.page; }; return{ onSubmit: onSubmit, onClick: onClick, bindListener: bindListener, updateFields: updateFields, imageLoaded: imageLoaded, toggleFilter: toggleFilter, fadeOut: fadeOut, response: response, getFormData: getFormData } })();
mercadopagoApp.controller('homeCtrl', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) { var vm = this; var url = "https://api.mercadopago.com/v1/payments"; vm.sendUser = sendUser; console.log("Sending post to MercadoLibre..."); //https://www.mercadopago.com.ar/developers/es/solutions/payments/custom-checkout/charge-with-creditcard/javascript/ Mercadopago.setPublishableKey("TEST-9a10f136-859d-4015-a7e0-f295e9ce34ba"); Mercadopago.getIdentificationTypes(function(res, data) { vm.docTypeOptions = data; console.debug("Document Type Options: "); console.debug(data); }); function sendUser(){ }; }]);
function MashupNode(){ } MashupNode.prototype.editor = null; MashupNode.prototype.graph = null; MashupNode.prototype.model = null; MashupNode.prototype.multiplicities = null;
requirejs.config({ baseUrl: "js", paths: { b: "b" } }); requirejs(["b"], function(b) { console.log(b); console.log("Success!"); });
import React, { Component } from 'react'; import echarts from 'echarts/lib/echarts'; import axios from "axios"; require("echarts/lib/chart/pie"); require('echarts/lib/component/tooltip'); require('echarts/lib/component/title'); require('echarts/lib/component/legend'); class StatePieEcharts extends Component { state={ data:[], } // constructor(props){ // super(props) // // } componentWillMount() { axios.post('/api/worktt/task/countByStatus.action') .then((response)=>{ let data=[]; response.data.datas.map( (item)=> data.push({value: item[1], name: item[0]}) ) // console.log(data) this.setState({data:data}); // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main03')); // 绘制图表 myChart.setOption({ title : { text: '按状态统计', x:'center' }, tooltip : { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { orient: 'vertical', left: 'left', data: response.data.datas.status }, series : [ { name: '状态', type: 'pie', color: ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42','#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'], radius : '55%', center: ['50%', '60%'], data:data, itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }); }) .catch(function(error){ console.log(error); }); } render() { return ( <div id="main02" style={{width: 510, height: 350, padding: 40}}/> ); } } export default StatePieEcharts;
import React from 'react'; import {withRouter} from "react-router"; import * as ReactDOM from "react-dom"; class ReactFitText extends React.Component{ componentDidMount() { window.addEventListener("resize", this._onBodyResize); this._onBodyResize(); } componentWillUnmount() { window.removeEventListener("resize", this._onBodyResize); } componentDidUpdate(prevProps, prevState, snapshot) { this._onBodyResize(); } // componentDidUpdate() { // this._onBodyResize(); // } _onBodyResize = function() { var element = this; var width = element.offsetWidth; element.style.fontSize = Math.max( Math.min((width / (this.props.compressor*10)), parseFloat(this.props.maxFontSize)), parseFloat(this.props.minFontSize)) + 'px'; } _renderChildren = function(){ var _this = this; return this.props.children; } render() { console.log(this._renderChildren()) return (<React.Fragment>this._renderChildren()</React.Fragment>); } } export default withRouter(ReactFitText);
function attachLatticeFunctions(states, lattice) { for (var i = 0; i < states.length; i++) { states[i].lattice = lattice.l; if (lattice.pre) lattice.pre(states[i]); switch (states[i].type) { case 'variableDeclaration': states[i].f = lattice.variableDeclaration; break; case 'readVariable': states[i].f = lattice.readVariable; break; case 'writeVariable': states[i].f = lattice.writeVariable; break; case 'readProperty': states[i].f = lattice.readProperty; break; case 'writeProperty': states[i].f = lattice.writeProperty; break; case 'operation': states[i].f = lattice.operation; break; case 'ifstart': states[i].f = lattice.ifstart; break; case 'ifend': states[i].f = lattice.ifend; break; case 'while': states[i].f = lattice.whilebody; break; case 'for': states[i].f = lattice.forbody; break; case 'functionDeclaration': states[i].f = lattice.functionDeclaration; break; case 'parameterDeclaration': states[i].f = lattice.parameterDeclaration; break; case 'functionExpression': states[i].f = lattice.functionExpression; break; case 'callEntry': states[i].f = lattice.callEntry; break; case 'callExit': states[i].f = lattice.callExit; break; default: states[i].f = lattice.defaultState; break; }; }; }; function clean(states) { for (var i = 0; i < states.length; i++) { states[i].smap.clean(); states[i].f = undefined; }; }; function init(states, lattice) { attachLatticeFunctions(states, lattice); }; function run(states) { var fixed = false; //var start = 0; //var next_start = 0; while (!fixed) { fixed = true; //console.log('new round'); for (var i = 0; i < states.length; i++) { //var j = (i + start) % states.length; //console.log('state: '+states[i].id); var ch = states[i].f.apply(states[i], []);; //console.log(ch); if (ch) { //next_start = i; //console.log('something has really changed'); fixed = false; }; }; //start = next_start + 1; }; }; function printVariablesAtTheEnd(lastState) { //console.log(lastState.id); for (v in lastState.getVariables()) { if (v.lastIndexOf('__v_') == -1) { console.log('Variable ' + v + ' = ' + lastState.getVariableValue(v)); }; }; }; function printAllVariablesAtTheEnd(lastState) { //console.log(lastState.id); var variables = lastState.getVariables(); for (var i = 0; i < variables.length; i++) { console.log('Variable ' + variables[i] + ' = ' + lastState.getVariableValue(variables[i])); }; }; module.exports.clean = clean; module.exports.init = init; module.exports.run = run; module.exports.printVariablesAtTheEnd = printVariablesAtTheEnd; module.exports.printAllVariablesAtTheEnd = printAllVariablesAtTheEnd;
var iOS = (Ti.Platform.name === 'iPhone OS') ; var nav ; function cleanFields(e){ $.pl_min.value = ""; $.pl_max.value = ""; $.roe_min.value = ""; $.roe_max.value = ""; $.divptr_min.value = ""; $.divptr_max.value = ""; }; function setScreenEnable(enable) { $.pl_min.enabled = enable; $.pl_max.enabled = enable; $.roe_min.enabled = enable; $.roe_max.enabled = enable; $.divptr_min.enabled = enable; $.divptr_max.enabled = enable; $.btn_limpar.enabled = enable ; $.btn_buscar.enabled = enable ; if (enable) { $.loading.hide() ; } else { $.loading.show() ; } } function dismissKeyboard(e) { this.blur() ; } function isNumber(n) { return (n.length == 0) || (!isNaN(parseFloat(n)) && isFinite(n)) ; } function validateNumber(e) { Ti.API.info("validateNumber: " + e.value) ; if ( ! isNumber(e.value) ) { e.source.color = "red" ; } else { e.source.color = "black" ; } } function search(e) { // Valida os campos if ( ! isNumber($.pl_min.value) || ! isNumber($.pl_max.value) || ! isNumber($.roe_min.value) || ! isNumber($.roe_max.value) || ! isNumber($.divptr_min.value) || ! isNumber($.divptr_max.value) ) { alert("Digite um número válido nos campos marcados.") return ; } // Monta url var url = "https://buscadorpapeis-prospeccaohtml5.rhcloud.com/buscadorpapeis/rest/papeis/buscar?" ; if ( $.pl_min.value.length > 0 ) url += "&plMin=" + $.pl_min.value ; if ( $.pl_max.value.length > 0 ) url += "&plMax=" + $.pl_max.value ; if ( $.roe_min.value.length > 0 ) url += "&roeMin=" + ($.roe_min.value/100) ; if ( $.roe_max.value.length > 0 ) url += "&roeMax=" + ($.roe_max.value/100) ; if ( $.divptr_min.value.length > 0 ) url += "&divBrutaMin=" + $.divptr_min.value ; if ( $.divptr_max.value.length > 0 ) url += "&divBrutaMax=" + $.divptr_max.value ; Ti.API.info(url) ; setScreenEnable(false) ; var xhr = Ti.Network.createHTTPClient(); xhr.onload = function() { try { var papeis = JSON.parse(this.responseText); var data = []; for (var i = 0; i < papeis.length; i++) { var papel = papeis[i]; var resultItem = Alloy.createController('resultItem', { papel: papel, nav: nav }).getView(); data.push(resultItem); }; var resultWindow = Alloy.createController('result', data).getView(); nav.open(resultWindow) ; setScreenEnable(true) ; } catch(e) { alert("Error: "+ e); setScreenEnable(true) ; } } ; xhr.onerror = function(e) { Ti.API.info(JSON.stringify(e)); alert("Erro de conexão: " + e) ; } ; //xhr.setRequestHeader("Content-Type", "application/json-rpc"); xhr.open("GET", url); Ti.API.info("Chamando request...") ; xhr.send(); }; function demo(e) { var demoWindow = Alloy.createController('demo', {nav:nav}).getView(); nav.open(demoWindow) ; } // Configura o loading $.loading.hide() ; // Cria navigationGroup para iOS if ( iOS ) { var newWindow = Titanium.UI.createWindow(); nav = Titanium.UI.iPhone.createNavigationGroup({ window: $.index }); newWindow.add(nav); newWindow.open(); } else { // Workaround para funcionar o nav.open no Android (no iOS o nav representa um NavigationGroup) var WindowOpener = function() { this.open = function(win, args) { if ( ! args ) { args = {navBarHidden:false} ; } else { args.navBarHidden = false ; } win.open(args) ; } } nav = new WindowOpener() ; $.index.open() ; }
'use strict'; // Create an instance var slimsurfer = {}; // Init & load audio file document.addEventListener('DOMContentLoaded', function() { slimsurfer = SlimSurfer.create({ container: document.querySelector('#waveform'), plugins: [SlimSurfer.cursor.create()] }); // Load audio from URL slimsurfer.load('../media/demo.wav'); // Play button var button = document.querySelector('[data-action="play"]'); button.addEventListener('click', slimsurfer.playPause.bind(slimsurfer)); });
import path from 'path'; import merge from 'webpack-merge'; import nodeExternals from 'webpack-node-externals'; import baseConfig from './webpack.config.base'; import resolveRules from './builder/resolve'; import babelLoader from './builder/loaders/babel'; export default merge( baseConfig, { output: { devtoolModuleFilenameTemplate: '[absolute-resource-path]', devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]' }, module: { rules: [ { test: /\.(js|ts)/, include: path.resolve('src'), // instrument only testing sources with Istanbul, after ts-loader runs loader: 'istanbul-instrumenter-loader' }, ] }, externals: [nodeExternals()], devtool: "inline-cheap-module-source-map" }, resolveRules, babelLoader );
import React, { useEffect, useState } from 'react'; import axios from 'axios' import { Route, Switch } from 'react-router-dom'; import FilmsPage from './pages/FilmsPage'; import PeoplesPage from './pages/PeoplesPage'; import PlanetsPage from './pages/PlanetsPage'; import SpeciesPage from './pages/SpeciesPage'; import StarshipsPage from './pages/StarshipsPage'; import VehiclesPage from './pages/VehiclesPage'; import NotFoundPage from './pages/NotFoundPage'; const Routes = () => { const [people, setPeople] = useState([]) const [films, setFilms] = useState([]) const [vehicles, setVehicles] = useState([]) const [starship, setStarships] = useState([]) const [specie, setSpecies] = useState([]) const [planet, setPlanets] = useState([]) const [isLoading, setIsLoading] = useState([true]) useEffect(() => { const fetchPeople = async () => { let response = await axios.get(`https://swapi.dev/api/people/`) let result_people = await response.data.results; // console.log(response.data.results) setPeople(result_people) setIsLoading(false) } fetchPeople() }, []) useEffect(() => { const fetchStarships = async () => { let response = await axios.get(`https://swapi.dev/api/starships/`) let result_starship = await response.data.results // console.log(result) setStarships(result_starship) setIsLoading(false) } fetchStarships() }, []) useEffect(() => { const fetchVehicles = async () => { let response = await axios.get(`https://swapi.dev/api/vehicles/`) let result_vehicle = await response.data.results // console.log(result) setVehicles(result_vehicle) setIsLoading(false) } fetchVehicles() }, []) useEffect(() => { const fetchFilms = async () => { let response = await axios.get(`https://swapi.dev/api/films/`) let result_film = await response.data.results // console.log(result) setFilms(result_film) setIsLoading(false) } fetchFilms() }, []) useEffect(() => { const fetchSpecies = async () => { let response = await axios.get(`https://swapi.dev/api/species/`) let result_specie = await response.data.results // console.log(result) setSpecies(result_specie) setIsLoading(false) } fetchSpecies() }, []) useEffect(() => { const fetchPlanets = async () => { let response = await axios.get(`https://swapi.dev/api/planets/`) let result = await response.data.results console.log(result) setPlanets(result) setIsLoading(false) } fetchPlanets() }, []) return ( <Switch> <Route exact path='/'> <FilmsPage result_film={films} isLoading={isLoading} /> </Route> <Route path='/films'> <FilmsPage result_film={films} isLoading={isLoading} /> </Route> <Route path='/people'> <PeoplesPage result_people={people} isLoading={isLoading} /> </Route> <Route path='/planets'> <PlanetsPage result={planet} isLoading={isLoading} /> </Route> <Route path='/species'> <SpeciesPage result_specie={specie} isLoading={isLoading} /> </Route> <Route path='/starships'> <StarshipsPage result_starship={starship} isLoading={isLoading} /> </Route> <Route path='/vehicles'> <VehiclesPage result_vehicle={vehicles} isLoading={isLoading} /> </Route> <Route path='/404' component={NotFoundPage} /> </Switch> ); } export default Routes;
import styled from "@emotion/styled"; export const Container = styled.div` padding: 25px; ` export const Title = styled.h2` margin-bottom: 15px; `
App.Views.App = Backbone.View.extend({ initialize: function() { new App.Views.Gifs({ collection: App.RandomList, el: $("#app") }); } }) App.Views.Gifs = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.$el.empty(); this.collection.each(this.AddOne, this); $(".image_c").fadeIn(1000); return this; }, AddOne: function(contact) { var singleContact = new App.Views.Gif({ model: contact }); this.$el.append(singleContact.$el); } }) App.Views.Gif = Backbone.View.extend({ tagName: "div", className: "col-md-4", template: App.template("gif-id"), initialize: function() { this.render(); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }) App.Views.Serch = Backbone.View.extend({ el: "#input_s", initialize: function() {}, events: { "click": "clik", "input": "chenge" }, chenge: function() { if ($("#input_s").val() == "") { $(".image_c").fadeOut(1000); var gifs = new App.Views.Gifs({ collection: App.RandomList, el: $("#app") }); $(".image_c").fadeIn(1000); } else { this.search(); } }, search: _.debounce(function() { App.SerchList.fetch({ query: $("#input_s").val() }).then(function() { if (App.SerchList.length > 0) { $(".image_c").fadeOut(1000); new App.Views.Gifs({ collection: App.SerchList, el: $("#app") }); } else { $(".image_c").fadeOut(1000); $("#app").empty().append("<div class='col-md-12 not_found_conteiner'><span class='not_found_span'>Not Found</span><img src='img/notFound.gif' class='not_found_img' alt=''></div>"); $(".image_c").fadeIn(1000); } }) }, 300) })
const Mongo = require('./mongo') const { ObjectID } = require('bson') async function main() { const URI = "mongodb://localhost:27017?useUnifiedTopology=true" const mongo = new Mongo(URI) await mongo.connect() const cursor = await mongo.find("test", "restaurants", {}) let processed = 0 while (await cursor.hasNext()){ if (processed % 100 === 0){ console.log(`${processed} itens processados.`) } const next = await cursor.next() if (next.address.coord.length === 2){ const updateDoc = { $set: { "address.coordv5": { type: "Point", coordinates: next.address.coord } }, } const result = await mongo.updateOne("test", "restaurants", {_id: next._id}, updateDoc) } processed++ } await mongo.close() } main()
OC.L10N.register( "settings", { "Unable to change password" : "Չկարողացա փոխել գաղտնաբառը", "Unable to delete group." : "Չկարողացա ջնջել խումբը", "Saved" : "Պահված", "Email sent" : "Էլ. նամակը ուղարկվեց", "Invalid mail address" : "Անվավեր էլ. հասցե", "Unable to delete user." : "Չկարողացա ջնջել օգտատիրոջը", "Forbidden" : "Արգելված", "Invalid user" : "Անվավեր օգտատեր", "Unable to change mail address" : "Չկարողացա փոխել էլ. հասցեն", "Unable to change full name" : "Չկարողացա փոխել լրիվ անունը", "Create" : "Ստեղծել", "Delete" : "Ջնջել", "Share" : "Կիսվել", "Language changed" : "Լեզուն փոխվեց", "Invalid request" : "Անվավեր հայց", "Unknown user" : "Անհայտ օգտատեր", "All" : "Ամենը", "Enabled" : "Միացված", "Not enabled" : "Չմիացված", "Updating...." : "Թարմացնում եմ...", "Updated" : "Թարմացվեց", "App update" : "Ափփ թարմացում", "Experimental" : "Փորձարարական", "Valid until {date}" : "Վավեր մինչ {date}", "Disconnect" : "Անջատել", "Very weak password" : "Շատ թույլ գաղտնաբառ", "Weak password" : "Թույլ գաղտնաբառ", "So-so password" : "Միջինոտ գաղտնաբառ", "Good password" : "Լավ գաղտնաբառ", "Strong password" : "Ուժեղ գաղտնաբառ", "Groups" : "Խմբեր", "undo" : "ետարկել", "never" : "երբեք", "deleted {userName}" : "ջնջված {userName}", "add group" : "խումբ ավելացնել", "enabled" : "միացված", "Cheers!" : "Չը՛խկ", "Language" : "Լեզու", "by %s" : "%s կողմից", "days" : "օր", "Save" : "Պահել", "Log" : "Լոգ", "Server address" : "Սերվերի հասցե", "Port" : "Պորտ", "Send email" : "Ուղարկել նամակ", "Android app" : "Android ափփ", "iOS app" : "iOS ափփ", "Add" : "Ավելացնել", "Cancel" : "Չեղարկել", "Full name" : "Լրիվ անուն", "Email" : "Էլ. հասցե", "Password" : "Գաղտնաբառ", "Current password" : "Ընթացիկ գաղտնաբառ", "New password" : "Նոր գաղտնաբառ", "Change password" : "Փոխել գաղտնաբառը", "Help translate" : "Օգնել թարգմանել", "Browser" : "Զննիչ", "Name" : "Անուն", "Username" : "Օգտանուն", "Version" : "Տարբերակ", "New Password" : "Նոր գաղտնաբառ", "Personal" : "Անձնական", "Admin" : "Ադմին", "Settings" : "Կարգավորումներ", "E-Mail" : "Էլ. նամակ", "Add Group" : "Ավելացնել խումբ", "Group" : "Խումբ", "Everyone" : "Բոլորը", "Admins" : "Ադմիններ", "Unlimited" : "Անսահման", "Other" : "Այլ", "Full Name" : "Լրիվ անուն", "Last Login" : "Վերջին մուտք", "change full name" : "փոխել լրիվ անունը", "change email address" : "փոխել էլ. հասցեն", "Default" : "Լռելյայն" }, "nplurals=2; plural=(n != 1);");
$(document).ready(function(){ $('.navbar .menu li a').click(function(){ $('html').css("scrollBehavior", "smooth"); }); $('.burger').click(function(){ $('.navbar .menu').toggleClass("active"); $('.burger img').toggleClass("active"); }); });
const arr = [1,2,3,4,5,6,7,8,9]; const newArr =[]; function up (arr) { for (let i=0; i < arr.length ; i++) { newArr.push(arr[i]+3); } } up(arr); console.log(arr); console.log(newArr);
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import Button from './Button'; const useStyles = makeStyles(theme => ({ root: { display: 'flex', flexWrap: 'wrap', '& > *': { margin: theme.spacing(1), width: theme.spacing(16), height: theme.spacing(16) }, }, })); const h1Style = { marginLeft: "25%", marginTop:"20%" } const SimplePaper = props => { const classes = useStyles(); return ( <div className={classes.root}> <Paper><h1 style={h1Style}>{props.seconds}</h1></Paper> <Button startTimer={props.startTimer} stopTimer={props.stopTimer} seconds={props.seconds} restartTimer={props.restartTimer} /> </div> ); } export default SimplePaper
import _ from 'lodash'; import percent from './../util/percent'; export const weapons = {}; export class Weapon { constructor(params) { this.name = params.name; this.damageType = params.type; this.leverage = params.leverage || 1; this.skill = params.skill || ''; this.size = params.size; this.power = params.power || 0; this.slow = params.slow || false; this.armorPiercing = params.ap || 0; } set damageType(val) { this._powerType = val; } get damageType() { return this._powerType; } set name(val) { if (!_.isString(val)) { throw new Error('non string value set to name'); } if (!val) { throw new Error('weapon must have name'); } this._name = val; } get name() { return this._name; } set leverage(val) { this._leverage = val; } get leverage() { return this._leverage; } set power(val) { this._power = val || 0; } get power() { return this._power; } set size(val) { this._size = val; } get size() { return this._size; } set skill(val) { this._skill = val; } get skill() { return this._skill; } set slow(val) { this._slow = val; } get slow() { return this._slow ? true : false; } set armorPiercing(val) { this._armorPiercing = val; } get armorPiercing() { return this._armorPiercing; } } /** Hand Weapons */ const sizes = require('./../data/json/leverage-Leverage.json') .map(size => { for (let prop in size) { if (size.hasOwnProperty(prop)) { size[prop] = percent(size[prop]); } } return size; }); const weaponTypes = require('./../data/json/weapons-Weapons.json') .map(weapon => { let out = {}; for (let prop in weapon) { const lcProp = prop.toLowerCase(); if (weapon.hasOwnProperty(prop)) { out[lcProp] = percent(weapon[prop]); } } return out; }); for (let size of sizes) { for (let type of weaponTypes) { let name = `${size.Size} ${type.name.toLowerCase()}`; let params = _.extend({}, type, { skill: 'Hand Weapons', leverage: size[type.type], name: name }); let weapon = new Weapon(params); weapons[weapon.name] = weapon; } }
import React from 'react'; import Helmet from 'react-helmet'; export default () => { return <div> <Helmet htmlAttributes={{ lang: 'en' }} titleTemplate="Apple Job - %s" defaultTitle="Apple Job" meta={[ { name: 'description', content: 'This is apple job site' }, ]} /> <h1>THIS IS APPLE</h1> </div> }
/** * Created by hugo on 05/06/2017. */ $(function () { $(".ui.login.modal") .modal('setting', 'closable', false).modal("show"); $("a.addservice").click(function () { $(".ui.addservice.modal").modal("show") }) $('.ui.item.logout') .popup({ popup : $('.ui.logout.popup'), on : 'click' }) ; $('.modal .cards .image').dimmer({ on: 'hover' }); $('.addLikeMeter.modal') .modal('attach events', '.addService.modal .button.likemeter') ; $('.addGuestbook.modal') .modal('attach events', '.addService.modal .button.guestbook') ; $('.addNewsletter.modal') .modal('attach events', '.addService.modal .button.newsletter') ; });
import React, {useState, useEffect} from 'react' import {useSelector, useDispatch} from 'react-redux' import './FavoritePlaces.css' import FavoriteIcon from "@material-ui/icons/Favorite" import FavoriteBorderIcon from "@material-ui/icons/FavoriteBorder" import { GetData } from '../redux/WeatherActions' const storage = window.localStorage; function FavoritePlaces() { const appState = useSelector(state => state.results); const city = appState.city; const dispatch = useDispatch(); const [liked, setLiked] = useState(false); const [favoriteCities, setFavoriteCities] = useState([]); useEffect(() => { try { let result = storage.getItem("FavoriteCity"); let resultArr = result.split(',') setFavoriteCities(resultArr); }catch(err){ } },[]) const handleSelected = e => { const cityZip = e.target.value; const zip = cityZip.split('|')[1]; dispatch(GetData(zip)); } const saveToFavorite = () => { let result = ''; try { result = storage.getItem("FavoriteCity"); }catch(err) { //new Set([city]) storage.setItem("FavoriteCity", city) } console.log(result) if(result === '') { return; } if(result && result.indexOf(city) > -1) { return; } if(!result || result === '') result = city else result = result + "," + city storage.setItem("FavoriteCity", result) setLiked(!liked); let resultArr = result.split(',') setFavoriteCities(resultArr); } return ( <div className="favoriteBar" > <span>Save {city} To Favorite</span> <div className="favoriteBar__button"> {liked? (<FavoriteIcon fontSize="large" onClick={saveToFavorite} />) : <FavoriteBorderIcon fontSize="large" onClick={saveToFavorite} /> } </div> <select onChange={e => handleSelected(e)}> { favoriteCities.map(favorCity => ( <option key={favorCity} value={favorCity} >{favorCity}</option> )) } </select> </div> ) } export default FavoritePlaces
import { takeLatest } from "@redux-saga/core/effects"; import axios from "axios"; import { put } from "redux-saga/effects"; function* postProvider(action) { try { yield axios.post('/api/provider', action.payload); } catch (error) { console.log('Error in providerRegistration saga', error); } } function* putProviderAddress(action) { try { yield axios.put('/api/provider/address', action.payload); } catch (error) { console.log('Error in providerRegistration saga, putProviderAddress', error); } } function* postWorkHistoryItems(action) { try { yield axios.post('/api/provider/workhistoryitem', action.payload); } catch (error) { console.log('Error in providerRegistration saga, addWorkHistoryItem', error); } } function* putWorkHistory(action) { try { yield axios.put('/api/provider/workhistory', action.payload); } catch (error) { console.log('Error in providerRegistration saga, addWorkHistory', error); } } function* postEducationHistoryItems(action) { try { yield axios.post('/api/provider/educationhistoryitem', action.payload); } catch (error) { console.log('Error in providerRegistration saga, addWorkHistory', error); } } function* putLastMission(action) { try{ yield axios.put('/api/provider/lastmission', action.payload); } catch (error) { console.log('Error in providerRegistration saga, putLastMission', error); } } function* postMissionHistoryItems(action){ try{ yield axios.post('/api/provider/missionhistoryitem', action.payload); } catch (error) { console.log('Error in providerRegistration saga, addMissionHistoryItem', error); } } function* postInsuranceItems (action) { try { yield axios.post('/api/provider/insuranceitem', action.payload); } catch (error) { console.log('Error in providerRegistration saga, addInsuranceItem', error); } } function* completeRegistration () { try { yield axios.put('/api/provider/completeregistration'); put({ type: 'GET_PROVIDER_LANDING' }) } catch (error) { console.log('error completing registration', error); } } function* addCredentialHistoryData(action){ try { yield axios.post('/api/provider/credentialhistory', action.payload); } catch (error) { console.error(`Error in providerRegistration.saga, addCredentialHistoryData ${error}`); } } function* postImageDB(action) { try { yield axios.post('/api/image/db', action) } catch (error) { console.log('error in postImageSaga',error) } } function* providerRegistrationSaga() { yield takeLatest('POST_PROVIDER_GENERAL', postProvider); yield takeLatest('PUT_PROVIDER_ADDRESS', putProviderAddress); yield takeLatest('POST_WORK_HISTORY_ITEMS', postWorkHistoryItems); yield takeLatest('PUT_WORK_HISTORY', putWorkHistory); yield takeLatest('POST_EDUCATION_HISTORY_ITEMS', postEducationHistoryItems); yield takeLatest('PUT_LAST_MISSION', putLastMission); yield takeLatest('POST_MISSION_HISTORY_ITEMS', postMissionHistoryItems); yield takeLatest('ADD_CREDENTIAL_HISTORY_DATA', addCredentialHistoryData); yield takeLatest('POST_INSURANCE_ITEMS', postInsuranceItems); yield takeLatest('COMPLETE_REGISTRATION', completeRegistration) yield takeLatest('POST_IMAGE_TO_DB', postImageDB) } export default providerRegistrationSaga;
var kSelSlider = new Slider(document.getElementById("kanji_selector_slider"), document.getElementById("kanji_selector_slider_input"), "vertical"); kSelSlider.setMinimum(100); kSelSlider.setMaximum(2500); kSelSlider.setBlockIncrement(50); kSelSlider.onchange = function () { var new_val = 20 * Math.round(kSelSlider.getValue()/20); document.getElementById("kanji_count_div").innerHTML = new_val; if (new_val != lastSliderVal) { lastSliderVal = new_val; setVisibleRTLevel(new_val); } }; lastSliderVal = 500; //Default value setVisibleRTLevel(lastSliderVal); kSelSlider.setValue(lastSliderVal); window.onresize = function () { kSelSlider.recalculate(); };
import PropTypes from 'prop-types' import React from 'react' import { withRouter } from 'react-router' const extractModuleName = /.*\/(?<fileName>[\w-..]*)/ /** * Because of issue: * https://github.com/facebook/react/issues/14254 * * we can't reload module * */ class LazyLoadingErrorBoundary extends React.Component { static displayName = 'LazyLoadingErrorBoundary' static propTypes = { children: PropTypes.node, history: PropTypes.object } constructor (props) { super(props) this.state = { hasError: false, moduleName: null } } static getDerivedStateFromError (error) { if (error.request) { const moduleName = error.request.match(extractModuleName).groups.fileName // error.request // Update state so the next re/der will show the fallback UI. return { hasError: true, moduleName } } return null } // Log the error to an error reporting service // componentDidCatch (error, info) { // logErrorToMyService(error, info); // } render () { const { hasError, moduleName } = this.state if (hasError) { // propose to refresh page return ( <div className='alert alert-danger' role='alert'> We failed to load module <strong>{moduleName}</strong>.<br /> Go&nbsp; <button className='btn btn-primary btn-sm' onClick={() => this.props.history.goBack()}>back</button> &nbsp;or&nbsp; <button className='btn btn-secondary btn-sm' onClick={() => this.props.history.go(0)}>refresh</button>. </div> ) } return this.props.children } } export default withRouter(LazyLoadingErrorBoundary)
import prettyInput from './prettyInput.vue' export default { name: 'pretty-checkbox', input_type: 'checkbox', mixins: [prettyInput] }
import React from 'react'; import { setGameState } from '../../../../functions'; export const totalImages = 124; export const screens = { lobby: 'lobby', intro: 'intro', upload: 'upload', caption: 'caption', vote: 'vote', dankestMeme: 'dankest-meme', scores: 'scores' } export class Meme { constructor(index, uploadingPlayer, image) { this.index = index; this.uploader = uploadingPlayer.index; this.uploaderName = uploadingPlayer.name; this.image = image; this.caption = null; this.captioner = null; this.captionerName = null; this.votes = 0; this.bonusVotes = 0; } } export class Score { constructor(player) { this.playerIndex = player.index; this.playerName = player.name; this.points = 0; } } export const renderMeme = (meme, i, specialClass) => ( <div className={`meme${specialClass ? ` ${specialClass}` : ''}`} id={'meme-' + i} key={i}> <div className="caption">{meme.caption}</div> <img alt="meme" src={Number.isInteger(meme.image) ? `/assets/img/meme/templates/${meme.image}.jpg` : meme.image} /> </div> ) export const assignCaptionersToMemes = (memes, players) => { let mapPlayerIndexToNumberOfPairs = {}; players.forEach(player=>{ mapPlayerIndexToNumberOfPairs[player.index] = 0; // goal is to pair each player to 2 memes }); let playersAvailable = players.map(player => player.index); // select a player to caption the meme, not the same as the uploader! const selectCaptioner = (uploader) => { let captioner; // player index to be returned by function if (playersAvailable.length === 1) { let lastPlayer = playersAvailable[0]; if (lastPlayer===uploader) { //swap with a random meme that's already been assigned let replacementMeme; while(true) { const rndX = Math.floor(Math.random()*(memes.length-1)); replacementMeme = memes[rndX]; if (replacementMeme.captioner && replacementMeme.captioner !== uploader && replacementMeme.uploader !== uploader) break; } captioner = replacementMeme.captioner; replacementMeme.captioner = uploader; replacementMeme.captionerName = players.find(p => p.index === uploader).name; } else { captioner = lastPlayer; } } else { const options = playersAvailable.filter(index => index !== uploader); const rndX = Math.floor(Math.random()*options.length); captioner = options[rndX]; } mapPlayerIndexToNumberOfPairs[captioner]++; if (mapPlayerIndexToNumberOfPairs[captioner]===2) { playersAvailable = playersAvailable.filter(index=>index!==captioner); } return captioner; } memes.forEach(meme=>{ meme.captioner = selectCaptioner(meme.uploader); meme.captionerName = players.find(p => p.index === meme.captioner).name; }); return memes; } // returns array of paired indices. e.g. [[1,4],[3,5]...] export const pairMemes = memes => { let pairs = []; let remainingIndices = memes.map(meme => meme.index); const getRndX = ()=> Math.floor(Math.random()*remainingIndices.length); while (remainingIndices.length) { let pair = []; let rndX = getRndX(); const index1 = remainingIndices[rndX]; pair.push(index1); remainingIndices.splice(rndX, 1); while(true) { rndX = getRndX(); const index2 = remainingIndices[rndX]; //don't let them have the same captioner if (memes.find(m => m.index === index1).captioner === memes.find(m => m.index === index2).captioner) { if (remainingIndices.length > 1) { continue; } else { //swap with the first one, which we already know won't be the same captioner bc each player only writes 2 captions pair.push(pairs[0][0]); pairs[0][0] = index2; remainingIndices = []; break; } } else { pair.push(index2); remainingIndices.splice(rndX, 1); break; } } pairs.push(pair); } return pairs; } export function handlePlayersGone(playersGone, props) { const { screen, memes } = props.gameState; const unusedMemes = props.gameState.unusedMemes || []; if (screen === screens.caption) { playersGone.forEach(playerIndex => { const playerWithNoMemes = props.players.find(p => !memes.filter(m => m.captioner === p.index).length); for (let i = 0; i < memes.length; i++) { const meme = memes[i]; if (meme.captioner === playerIndex) { if (playerWithNoMemes) { meme.captioner = playerWithNoMemes.index; meme.captionerName = playerWithNoMemes.name; } else { unusedMemes.push(meme); memes.splice(i, 1); i--; } } } }); setGameState(props.code, {unusedMemes, memes}); } } export function handlePlayersJoined(playersJoined, newPlayers, props) { const { screen, memes } = props.gameState; const unusedMemes = props.gameState.unusedMemes || []; if (screen === screens.caption) { playersJoined.forEach(playerIndex => { if (unusedMemes.length) { for (let i = 0; i < 2 && unusedMemes.length; i++) { const meme = unusedMemes.shift(); meme.captioner = playerIndex; meme.captionerName = newPlayers.find(p => p.index === playerIndex).name; memes.push(meme); } } }); setGameState(props.code, {unusedMemes, memes}); } }
const express = require('express'); const router = express.Router(); /* GET users listing. */ function usersRouter(connection, db) { router.get('/', async function(req, res, next) { // const connection = await connect(); const iduser = req.query.id; const query = iduser ? `select first_name, last_name from users where id = ? and role = 'Vendedor'` : `select first_name, last_name from users where role = 'Vendedor'`; // query to database. Mysql and Oracle modules have different ways to query, this is why the if is needed. if (db === 'oracle') { try { const results = await connection.execute(query, [iduser]); res.send(results.rows); } catch (err) { console.log('Ouch!', err) } } else { const request = connection.query(query, [iduser], (error, results, fields) => { if (error) throw error; res.send(results); }) console.log(request.sql) } }); return router; } module.exports = usersRouter;
import React, { useEffect, useState } from 'react' import { Button, Col, Container, Modal, Row, ToggleButton, ToggleButtonGroup } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import { getCurrentStep, getIsLoading } from '../../../store/lessonSteps/selectors' import Loader from '../../Loader/Loader' import { loadTestStep, updateTestStep } from '../../../store/lessonSteps/test.thunk' import { useTranslation } from 'next-i18next' import { clearCurrentStep } from '../../../store/lessonSteps/reducer' const TestStepEditor = ({ stepId }) => { const { t } = useTranslation('steps') const [show, setShow] = useState(false) const dispatch = useDispatch() const isLoading = useSelector(getIsLoading) const currentStep = useSelector(getCurrentStep) const [testInfo, setTestInfo] = useState(null) useEffect(() => { dispatch(clearCurrentStep()) dispatch(loadTestStep(stepId)) }, [stepId]) useEffect(() => { setTestInfo(currentStep) }, [currentStep]) if (!currentStep || !testInfo) { return <Loader/> } const onChangeQuestion = (event) => { setTestInfo((prevState) => { return { ...prevState, question: event.target.value } }) } const onChangeOption = (event, optionIndex) => { const options = [...testInfo.options] options[optionIndex] = event.target.value setTestInfo((prevState) => { return { ...prevState, options: options } }) } const onAddOption = () => { setTestInfo((prevState) => { return { ...prevState, options: [...prevState.options, ''] } }) } const onDeleteOption = (optionValue) => { const options = [...testInfo.options] const valueIndex = options.findIndex((option) => option === optionValue) const newOptions = [ ...options.slice(0, valueIndex), ...options.slice(valueIndex + 1)] setTestInfo((prevState) => ({ ...prevState, options: newOptions })) } const onChangeAnswerType = (event) => { const newType = event.target.value let answers = [...testInfo.answers] if (newType === 'single') { answers = answers.slice(0, 1) } setTestInfo((prevState) => { return { ...prevState, answers: answers, type: event.target.value } }) } const onSingleChange = (event) => { setTestInfo((prevState) => { return { ...prevState, answers: [event.target.value] } }) } const onMultipleChange = (event) => { let answers = [...testInfo.answers] const checkboxValue = event.target.value if (answers.includes(checkboxValue)) { answers = answers.filter((item) => { return item !== checkboxValue }) } else { answers = [...answers, checkboxValue] } setTestInfo((prevState) => ({ ...prevState, answers: answers })) } const onUpdateTestStep = () => { dispatch(updateTestStep(currentStep._id, testInfo)) } const optionsBlock = testInfo?.options?.map((option, index) => { return ( <div className="form-check d-flex profile-courses-one my-3 align-items-center" key={'option' + index}> {testInfo.type === 'single' ? ( <input className="checkbox-editor mx-3" type="radio" onChange={onSingleChange} checked={testInfo.answers.includes(option)} value={option}/> ) : ( <input value={option} onChange={onMultipleChange} className="checkbox-editor mx-3" type="checkbox" checked={testInfo.answers.includes(option)}/> )} <input className={'input-checkbox-editor'} type="variant" placeholder="Variant" value={option} onChange={(event) => onChangeOption(event, index)} name="variant" id="variant"/> <div style={{ margin: 'auto 20px' }}> <a style={{ textDecoration: 'none' }}> <button className="lesson-delete-btn d-flex" onClick={() => onDeleteOption(option)}> <i className="fas fa-trash-alt"/> </button> </a> </div> </div> ) }) return ( <div> <h3 className="editor-lesson-title mt-5 mb-3">Write your question down below</h3> <textarea onChange={onChangeQuestion} value={testInfo.question} cols="40" rows="5"/> <h3 className="editor-lesson-title mt-5 mb-3">Write score of your question</h3> <input value={testInfo.score} type={'number'} min={1} onChange={(event) => setTestInfo((prevState) => ({ ...prevState, score: +event.target.value }))} className={'input-checkbox-editor'} /> <h3 className="editor-lesson-title mt-5 mb-3">Write possible answers</h3> <ToggleButtonGroup type="radio" name="options" defaultValue={testInfo.type} style={{ borderRadius: '8px' }}> <ToggleButton id="tbg-radio-1" value={'single'} onClick={onChangeAnswerType}> Single answer </ToggleButton> <ToggleButton id="tbg-radio-2" value={'multiple'} onClick={onChangeAnswerType}> Multiple answers </ToggleButton> </ToggleButtonGroup> {optionsBlock} <Button variant="primary" onClick={onAddOption} style={{ borderRadius: '8px', width: '70px' }}> <i className="fas fa-plus"/> </Button> <h3 className="editor-lesson-title mt-5 mb-3">Choose right answer(s)</h3> <br/> <Button onClick={onUpdateTestStep} className="mt-3" type={'submit'} disabled={isLoading}>{isLoading ? t('saving') : t('save')}</Button> <Modal show={show} onHide={() => setShow(false)} size="md" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Body closeButton> <Container> <Row> <Col xs={12} md={6}> <img className="content-image" src="/bucket.png" alt="photo"/> </Col> <Col xs={12} md={6} className="d-flex" style={{ alignItems: 'center' }}> <div className="m-auto"> <h3 className="profile-welcome-title d-block">Are you sure?</h3> <span className="modal-task-subtitle d-block">Do you want to permanently delete everything now?</span> </div> </Col> </Row> </Container> </Modal.Body> <Modal.Footer> <Button className="btn-danger" style={{ borderRadius: '8px' }}>Yes, delete</Button> <Button onClick={() => setShow(false)} className="btn-primary" style={{ borderRadius: '8px' }}>Close</Button> </Modal.Footer> </Modal> </div> ) } export default TestStepEditor
import React from "react"; import { render } from "@testing-library/react"; import App from "../App"; import Header from "../components/Header"; import { shallow, mount } from "enzyme"; import Enzyme from "enzyme"; import Adapter from "enzyme-adapter-react-16"; import Home from "../components/Home"; describe("App test suite", () => { Enzyme.configure({ adapter: new Adapter() }); //Title test it("Sport Spots is displayed in the nav and the home page component", async () => { const { findAllByText } = render(<App />); const linkElement = await findAllByText("Sport Spots"); //Check to make sure that there are two instances of the title expect(linkElement.length).toBe(2); for (let i = 0; i < linkElement.length; ++i) { //Check to make sure that each of the individual elements are in the doc expect(linkElement[i]).toBeInTheDocument(); } }); //Component tests to ensure all are still being rendered it("Renders the header component at the top of the page", async () => { const wrapper = shallow(<App />); expect(wrapper.exists()).toBe(true); expect(wrapper.containsMatchingElement(<Header />)).toEqual(true); }); it("Verify the home child component is rendered", () => { const wrapper = mount(<App />); expect(wrapper.exists()).toBe(true); expect(wrapper.containsMatchingElement(<Home />)).toEqual(true); }) });
var _parent = require('./dev').require('hyperloop-java').type; exports.Class = _parent.Class;
const array = [{ thought: "What ?", author: "Bob" }]; module.exports = array;
/* * @Author: your name * @Date: 2020-08-01 15:35:37 * @LastEditTime: 2020-08-01 16:03:22 * @LastEditors: Please set LastEditors * @Description: 开发文档 * @FilePath: /supply-chian-system/docs/index.js */ import Vue from 'vue'; import router from '@docs/router'; import App from '@docs/app.js'; new Vue( { el: '#app', router, render: h => h( App ) } );
var dir_9c354dbc1623f3256abce439ee79c1dc = [ [ "C1ConnectorCompleteSessionService.h", "_c1_connector_complete_session_service_8h_source.html", null ], [ "C1ConnectorEntitlementService.h", "_c1_connector_entitlement_service_8h_source.html", null ], [ "C1ConnectorExternalSessionService.h", "_c1_connector_external_session_service_8h_source.html", null ], [ "C1ConnectorGetOffersService.h", "_c1_connector_get_offers_service_8h_source.html", null ], [ "C1ConnectorOptInService.h", "_c1_connector_opt_in_service_8h_source.html", null ], [ "C1ConnectorPurchaseService.h", "_c1_connector_purchase_service_8h_source.html", null ], [ "C1ConnectorRegisterDeviceService.h", "_c1_connector_register_device_service_8h_source.html", null ], [ "C1ConnectorRegisterUserService.h", "_c1_connector_register_user_service_8h_source.html", null ], [ "C1ConnectorService.h", "_c1_connector_service_8h_source.html", null ], [ "C1ConnectorServiceSessionService.h", "_c1_connector_service_session_service_8h_source.html", null ], [ "C1ConnectorSessionService.h", "_c1_connector_session_service_8h_source.html", null ], [ "C1ConnectorTrackEventsService.h", "_c1_connector_track_events_service_8h_source.html", null ], [ "C1ConnectorUserContractorService.h", "_c1_connector_user_contractor_service_8h_source.html", null ], [ "C1ConnectorUserDataService.h", "_c1_connector_user_data_service_8h_source.html", null ], [ "C1ConnectorUserGroupsService.h", "_c1_connector_user_groups_service_8h_source.html", null ], [ "C1ConnectorUserMasterDataService.h", "_c1_connector_user_master_data_service_8h_source.html", null ] ];
import { StatusBar } from 'expo-status-bar'; import React from 'react'; import { StyleSheet, Text, View, FlatList, Image, TouchableOpacity, InteractionManager } from 'react-native'; import Icon from '@expo/vector-icons/FontAwesome5'; const arrayEmoji = [ { id: 1, name: 'sad-cry', color: '#F32A1D' }, { id: 2, name: 'sad-tear', color: '#F37E1D' }, { id: 3, name: 'meh-blank', color: '#F3E01D' }, { id: 4, name: 'grin-wink', color: '#A2F31D' }, { id: 5, name: 'grin-hearts', color: '#51F31D' }, ] const pontosMelhoria = [ { id: 1, ponto: 'Atendimento', selecionado: false }, { id: 2, ponto: 'Alimento', selecionado: false }, { id: 3, ponto: 'Reposição', selecionado: false }, { id: 4, ponto: 'Sabor', selecionado: false }, { id: 5, ponto: 'Bebida', selecionado: false }, { id: 6, ponto: 'Outros', selecionado: false }, ] export default function Perguntas({ navigation }) { return ( <View style={styles.container}> <StatusBar style="auto" /> <View style={styles.header}> <View style={styles.areaTitle}> <Text style={styles.stTitle}>Qual a sua avaliação para o nosso serviço ?</Text> </View> <View style={styles.areaSatisfacao}> <FlatList data={arrayEmoji} horizontal={true} keyExtractor={(item) => item.id} renderItem={({ item }) => { return ( <View key={item.id} style={styles.areaEmoji}> <TouchableOpacity> <Icon name={item.name} color={item.color} size={40} /> </TouchableOpacity> </View> ) }} /> </View> </View> <View style={styles.body}> {/* <FlatList data={pontosMelhoria} style={styles.verPontos} keyExtractor={(item) => item.id} renderItem={({ item }) => { return ( <View style={{ padding: 10 }}> <Text>{item.ponto}</Text> </View> ) }} /> */} </View> <View style={styles.botton}> </View> </View> ) } const styles = StyleSheet.create({ container: { flexDirection: 'column', marginTop: 20, flex: 1, backgroundColor: '#333' }, header: { flex: 2, }, areaTitle: { flex: 1, justifyContent: 'center', alignSelf: 'center' }, areaSatisfacao: { flex: 1, justifyContent: 'center', alignSelf: 'center' }, stTitle: { color: "#fafafa", fontSize: 18, fontWeight: 'bold' }, areaEmoji: { marginHorizontal: 17 }, body: { flex: 5, }, verPontos: { flex: 1, flexDirection: 'row' }, botton: { flex: 2, } })
import React, { useEffect, useRef, useState } from 'react'; import { StyleSheet, View, Text, useWindowDimensions, ScrollView, TouchableOpacity } from 'react-native'; import * as Location from 'expo-location'; import MapView, { Marker, PROVIDER_GOOGLE } from 'react-native-maps'; import Carousel, { Pagination } from 'react-native-snap-carousel'; const MapScreen = ({ navigation }) => { const mapRef = useRef(null); const carouselRef = useRef(null); const [currentLocation, setCurrentLocation] = useState({ latitude: 34.0686145, longitude: -118.4450876, }); const [region, setRegion] = useState({ latitude: 34.0686145, longitude: -118.4450876, latitudeDelta: 0.05, longitudeDelta: 0.05, }); const [markers, setMarkers] = useState([{ name: 'You Are Here', address: '', coordinate: currentLocation, }]); useEffect(() => { let initialMarker = { name: 'You Are Here', address: '', coordinate: currentLocation, }; (async () => { const { status } = await Location.requestPermissionsAsync(); if (status !== 'granted') { return; } const location = await Location.getCurrentPositionAsync({}); if(location) { const latlong = { latitude: location.coords.latitude, longitude: location.coords.longitude, }; initialMarker.coordinate = latlong; setCurrentLocation(latlong); setRegion({ ...latlong, latitudeDelta: region.latitudeDelta, longitudeDelta: region.longitudeDelta, }); } })(); const nearbyMarkers = testMarkers; // TODO: GET FROM ROUTE setMarkers([initialMarker, ...nearbyMarkers]); }, []); const [ind, setInd] = useState(0); const jumpTo = (i) => { setInd(i); mapRef.current?.animateToRegion({ ...markers[i].coordinate, latitudeDelta: region.latitudeDelta, longitudeDelta: region.longitudeDelta, }); } const onRegionChange = (region) => setRegion(region); const CarouselItem = ({item, index}) => { return ( <View key={index} style={{ flex: 1, alignItems: 'center', justifyContent: 'center', marginTop: 5, }} > <TouchableOpacity onPress={() => { if(index) { navigation.navigate('HomeScreen', /*{id: item.id}*/); // TODO: update to business's stamps list screen } else { navigation.navigate('UserScreen'); } }} style={{ width: '90%', height: '100%', flex: 1, alignItems: 'center', borderRadius: 10, borderWidth: 2, }} > <Text style={{ fontSize: 20, fontWeight: '700', }} > {item.name} </Text> <ScrollView> <Text numberOfLines={1} style={{flex: 1, textAlign: 'center',}} > {item.address} </Text></ScrollView> </TouchableOpacity> </View> ); }; const dimensions = useWindowDimensions(); return ( <View style={{...dimensions}}> <MapView ref={mapRef} provider={PROVIDER_GOOGLE} region={region} onRegionChangeComplete={onRegionChange} style={StyleSheet.absoluteFillObject} > {markers.map((marker, i) => ( <Marker key={i} title={marker.name} description={marker.address} coordinate={marker.coordinate} onPress={() => { jumpTo(i); }} pinColor={i===0 ? 'blue' : 'red'} /> ))} </MapView> <View style={{ position: 'absolute', top: 0, backgroundColor: '#fff', width: dimensions.width, height: dimensions.height * 0.2, flex: 1, alignItems: 'center', justifyContent: 'center', }}> <Carousel ref={carouselRef} data={markers} renderItem={CarouselItem} sliderWidth={dimensions.width} itemWidth={dimensions.width} onSnapToItem={i => { jumpTo(i); }} /> <Pagination dotsLength={markers.length} activeDotIndex={ind} carouselRef={carouselRef} tappableDots={true} dotStyle={{ width: 12, height: 12, borderRadius: 6, }} inactiveDotScale={0.8} /> </View> </View> ); }; export default MapScreen; const testMarkers = [ { name: 'Boba Guys Culver City', address: '8820 Washington Blvd #107, Culver City, CA 90232', coordinate: { latitude: 34.0272141, longitude: -118.3895074, }, }, { name: 'Wushiland Boba WCC', address: '10250 Santa Monica Blvd Ste 2770, Los Angeles, CA 90067', coordinate: { latitude: 34.0593723, longitude: -118.4221478, }, }, { name: 'Redstraw', address: '10250 Santa Monica Blvd, Los Angeles, CA 90067', coordinate: { latitude: 34.0594111, longitude: -118.4374687, }, }, { name: 'Boba Time', address: '11207 National Blvd, Los Angeles, CA 90064', coordinate: { latitude: 34.0274306, longitude: -118.4469587, }, }, { name: "It's Boba Time", address: '10946 Weyburn Ave, Los Angeles, CA 90024', coordinate: { latitude: 34.0624556, longitude: -118.4642974, }, }, { name: 'Sharetea', address: '1055 Broxton Ave, Los Angeles, CA 90024', coordinate: { latitude: 34.0624556, longitude: -118.4642974, }, }, { name: 'Bubble Boba', address: '2829 Ocean Park Blvd, Santa Monica, CA 90405', coordinate: { latitude: 34.008967, longitude: -118.4987671, }, }, { name: 'Boba Lab', address: '711 Pico Blvd, Santa Monica, CA 90405', coordinate: { latitude: 34.0339368, longitude: -118.4457237, }, }, { name: 'Boba Tea & Me', address: '1328 Wilshire Blvd, Santa Monica, CA 90403', coordinate: { latitude: 34.0210615, longitude: -118.4932739, }, }, ];
module.exports = { up: async opts => { const { connection } = opts; return connection.schema.createTable('entry', table => { table.increments(); table.integer('happy'); table.integer('social'); table.integer('energy'); table.text('notes'); table.timestamp('created_at').defaultTo(connection.fn.now()).index(); }); }, down: async opts => { const { connection } = opts; if (await connection.schema.hasTable('entry')) { return connection.schema.dropTable('entry'); } else { console.error('No entry table'); } }, }
db.apauth.insert({ "id":"aauth", "username":"a", "email":"a", "password":"a", "roles":["user"], "type":"user", "active":true, "registrationDate":[2016, 1, 1, 0, 0], "registered":true, "entityId": "a" }) db.user.insert({ "id":"a", "authId":"aauth" }) db.apauth.insert({ "id":"bauth", "username":"b", "email":"b", "password":"b", "roles":["user"], "type":"user", "active":true, "registrationDate":[2016, 1, 1, 0, 0], "registered":true, "entityId": "b" }) db.user.insert({ "id":"b", "authId":"bauth" }) db.apauth.insert({ "id":"cauth", "username":"c", "email":"c", "password":"c", "roles":["user"], "type":"user", "active":true, "registrationDate":[2016, 1, 1, 0, 0], "registered":true, "entityId": "c" }) db.user.insert({ "id":"c", "authId":"cauth" }) db.apauth.insert({ "id":"sauth", "username":"samael", "email":"s", "password":"s", "roles":["user"], "type":"user", "active":true, "registrationDate":[2016, 1, 1, 0, 0], "registered":true, "entityId": "s" }) db.user.insert({ "id":"s", "authId":"sauth" })
const log = require('log4js').getLogger('application'); const db = require('../shared/dataSource'); const PurchaseOrder = db.PurchaseOrder; function create(poParams) { const purchaseOrder = new PurchaseOrder(poParams); return purchaseOrder.save(); } function getAll() { return PurchaseOrder.find(); } function getById(id) { return PurchaseOrder.findById(id); } function update(id, poParams) { return PurchaseOrder.findByIdAndUpdate(id, { $set: poParams }, function (err, result) { if (err) log.error(err); log.info('Updating purchase order record:', result); }) } function _delete(id) { return PurchaseOrder.findByIdAndDelete(id); } module.exports = { create, getAll, getById, update, delete: _delete }
// React import React from 'react'; import {TouchableOpacity, StyleSheet} from 'react-native'; // Redux import {removeFactFromEverywhere} from '../Redux/MultipleActions'; import {useDispatch} from 'react-redux'; // Icons import Icon from 'react-native-vector-icons/AntDesign'; export default function DeleteIcon({fact}) { const dispatch = useDispatch(); return ( // Delete Fact Functionality <TouchableOpacity style={styles.touchableIcon} onPress={() => { dispatch(removeFactFromEverywhere(fact._id)); }}> <Icon name="delete" size={40} color="#000000" /> </TouchableOpacity> ); } const styles = StyleSheet.create({ touchableIcon: { marginHorizontal: 20, }, });
import React, { useState } from 'react' import { AddTodo, RemoveTodo, DeleteTodo } from '../Actions/actions' import { useDispatch ,useSelector } from 'react-redux' import '../App.css' function Todo() { const [inputData, setInputData] = useState('') const dispatch = useDispatch() const list = useSelector((state) => state.Reducer.list) return ( <div className='todo'> <h1>Add your todos</h1> <div className='todo_input'> <input value={inputData} onChange={(e) => setInputData(e.target.value)} placeholder='Add todos here' /> <button onClick={() => dispatch(AddTodo(inputData))} className='add'>add</button> </div> <div> {list.map((e) => { return( <div key={e.id}> <h3>{e.data}</h3> <button onClick={() => dispatch(DeleteTodo(inputData))}>delete</button> </div> ) })} </div> </div> ) } export default Todo
import React from 'react'; import { useRecoilState } from 'recoil'; import { cartState } from './state'; function AvailableItems({ inventory }) { const [cart, setCart] = useRecoilState(cartState); return ( <div className="container"> <h2 className="title">Available Items</h2> <ul> {Object.entries(inventory).map(([id, { name, price }]) => { return ( <li key={id}> {name} ${price.toFixed(2)} <button className="button" onClick={() => setCart({ ...cart, [id]: (cart[id] || 0) + 1 })}>Add</button> {cart[id] ? <button className="button" onClick={() => { const copy = { ...cart }; if (copy[id] === 1) { delete copy[id]; setCart(copy) } else { setCart({ ...copy, [id]: copy[id] - 1 }) } }}>Remove</button> : null} </li> ) })} </ul> </div> ) }; export default AvailableItems
angular.module('authServices', []) .factory('Auth', function($http) { //creo el objeto nuevo usuario var authFactory = {}; //user.Create(regData) authFactory.login = function(loginData){ //se crea el usuario en la bd con los datos de logindata return $http.post('/api/authenticate', loginData).then(function(data){ console.log(data.data.token); return data; }); } return authFactory; //devuelvo usuario registrado }) .factory('AuthToken', function(){ //creo el objeto para asignar el token al usuario q ingreso var authTokenFactory = {}; // al objeto le asignamos el token creado authTokenFactory.setToken = function(token){ $window.localStorage.setItem('token', token); } //devuelvo usuario autenticado return authTokenFactory; });
import axios from "axios"; class EmployeService { getAllEmploye =()=>{ return axios.get(`/api/employes`) } createEmployes=(employe)=>{ axios.post(`/api/employes`, employe); } getEmploye =id=>{ return axios.get(`/api/employes/${id}`); } deleteEmploye =id=>{ return axios.delete(`/api/employes/${id}`); } } export default new EmployeService();
{ let containerProduse = document.getElementById('produse'); let produse = containerProduse.children; let listaProduse = JSON.parse(localStorage.getItem('ListaProduse')); // let numarProduse = listaProduse.lenght; // console.log(produse); // console.log(listaProduse); for (let i=0; i<produse.length; i++) { produse[i].onclick = function(e) { e.stopPropagation(); let idProdus = produse[i].id; console.log(idProdus); var produsClick = listaProduse.filter(produs => { return produs.id == idProdus }) console.log(produsClick[0]); localStorage.setItem('ProdusVizitat', JSON.stringify(produsClick[0])); localStorage.setItem('ProdusVizitatId', JSON.stringify(idProdus)); window.location.href = `produs.html?produs=${idProdus}`; // window.location.href = `produs.html`; } } }
import {Platform, StyleSheet} from 'react-native'; import colors from '../../util/colors.json'; // const BORDER_RADIUS = 10 const BASE_FONT_SIZE = Platform.OS === 'android' ? 12 : 16; export default StyleSheet.create({ container: { flex: 1, backgroundColor: colors.black, }, background: { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', resizeMode: 'contain', opacity: 0.1, tintColor: colors.lightBlue, }, contentContainer: { flex: 1, }, content: { flex: 1, padding: 16, }, section: { marginBottom: 16, }, subsection: { marginTop: 4, }, header: { color: colors.yellow, fontSize: BASE_FONT_SIZE * 1.5, }, subHeader: { color: colors.lightBlue, fontWeight: 'bold', fontSize: BASE_FONT_SIZE * 1.2, }, question: { color: colors.lightBlue, fontSize: BASE_FONT_SIZE, fontWeight: 'bold', }, text: { color: colors.white, fontSize: BASE_FONT_SIZE, }, highlight: { color: colors.yellow, }, code: { fontSize: BASE_FONT_SIZE * 0.8, fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace', fontWeight: 'bold', color: colors.lightBlue, borderWidth: 1, padding: 4, }, variable: { fontFamily: Platform.OS === 'ios' ? 'Courier' : 'monospace', fontStyle: 'italic', }, tmdb: { maxWidth: '50%', marginHorizontal: 10, alignSelf: 'center', tintColor: colors.white, }, });
import React, { Component } from "react"; import { Link, animateScroll as scroll } from "react-scroll"; import { Nav, Navbar, Container } from 'react-bootstrap'; export default class Navigations extends Component { scrollToTop = () => { scroll.scrollToTop(); }; render() { return ( <Navbar bg="light" expand="lg"> <Container> <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="me-auto"> <Link activeClass="active" to="home" spy={true} smooth={true} offset={-70} duration={500} >Acceuil</Link> <Link activeClass="active" to="services" spy={true} smooth={true} offset={-70} duration={500} >Services</Link> <Link activeClass="active" to="about" spy={true} smooth={true} offset={-70} duration={500} >About</Link> <Link activeClass="active" to="contact" spy={true} smooth={true} offset={-70} duration={500} >Contact</Link> </Nav> </Navbar.Collapse> </Container> </Navbar> ); } } /* <nav className="nav" id="navbar"> <div className="nav-content"> logo <ul className="nav-items"> <li className="nav-item"> <Link activeClass="active" to="home" spy={true} smooth={true} offset={-70} duration={500} > Acceuil </Link> </li> <li className="nav-item"> <Link activeClass="active" to="services" spy={true} smooth={true} offset={-70} duration={500} > Services </Link> </li> <li className="nav-item"> <Link activeClass="active" to="about" spy={true} smooth={true} offset={-70} duration={500} > About </Link> </li> <li className="nav-item"> <Link activeClass="active" to="contact" spy={true} smooth={true} offset={-70} duration={500} > Contact </Link> </li> </ul> </div> </nav> */
import * as actionCreators from './algo'; import axios from 'axios'; import { store } from '../../reduxRelated'; describe('algo actions', () => { it('should get all my algorithms', async () => { axios.get = jest.fn(() => { return Promise.resolve({ status: 200, data: {} }); }); await store.dispatch(actionCreators.getAllMyAlgorithm()); }); it('should fail to submit an algorithm', async () => { const name = ''; const descr = ''; const snippets = ['', '', '', '']; axios.post = jest.fn(() => { return Promise.reject(new Error('')); }); await store.dispatch(actionCreators.submitAlgo(name, descr, snippets)); }); it('should fail to submit an algorithm', async () => { const name = ''; const descr = ''; const snippets = ['', '', '', '']; axios.post = jest.fn(() => { return Promise.resolve({ status: 400, data: {} }); }); await store.dispatch(actionCreators.submitAlgo(name, descr, snippets)); }); it('submit an algorithm', async () => { const name = ''; const descr = ''; const snippets = ['', '', '', '']; window.confirm = jest.fn(() => { return true; }); axios.post = jest.fn((url) => { if (url === '/api/algo') return Promise.resolve({ status: 201, data: { id: 0 } }); else if (url === '/api/algo/backtest') return Promise.resolve({ status: 200, data: {} }); }); await store.dispatch(actionCreators.submitAlgo(name, descr, snippets)); }); it('submit an algorithm but fail confirm', async () => { const name = ''; const descr = ''; const snippets = ['', '', '', '']; axios.post = jest.fn(() => { return Promise.resolve({ status: 201 }); }); window.confirm = jest.fn(() => { return false; }); await store.dispatch(actionCreators.submitAlgo(name, descr, snippets)); }); it('should delete an algorithm', async () => { axios.delete = jest.fn(() => { return Promise.resolve({ status: 204 }); }); await store.dispatch(actionCreators.deleteAlgo(0)); axios.delete = jest.fn(() => { return Promise.reject(new Error('')); }); await store.dispatch(actionCreators.deleteAlgo(0)); }); it('should share an algorithm', async () => { axios.put = jest.fn(() => { return Promise.resolve({ status: 200, data: {} }); }); await store.dispatch(actionCreators.shareAlgo(0, true)); }); it('should not share an algorithm', async () => { axios.put = jest.fn(() => { return Promise.resolve({ status: 200, data: {} }); }); await store.dispatch(actionCreators.shareAlgo(0, false)); }); it('should fail to share an algorithm', async () => { axios.put = jest.fn(() => { return Promise.reject(new Error('')); }); await store.dispatch(actionCreators.shareAlgo(0, true)); }); it('should share algorithm but get bad response', async () => { axios.put = jest.fn(() => { return Promise.resolve({ status: 400, data: {} }); }); await store.dispatch(actionCreators.shareAlgo(0, true)); }); it('should getAllAlgorithm', async () => { axios.get = jest.fn(() => { return Promise.resolve({ status: 200, data: {} }); }); await store.dispatch(actionCreators.getAllAlgorithm()); }); it('should getAllAlgorithm but get bad response', async () => { axios.get = jest.fn(() => { return Promise.resolve({ status: 400, data: {} }); }); await store.dispatch(actionCreators.getAllAlgorithm()); }); });
const Author = require('../../../models/Author'); const ErrorHandler = require('../../../handlers/error.handler'); const removeDuplicates = (arr) =>{ var uniqueArray=[]; for(var i=0; i < arr.length; i++){ if(uniqueArray.filter(e => e.id == arr[i].id).length == 0){ uniqueArray.push(arr[i]); } } return uniqueArray; } module.exports = (event, context, callback) => { Author.retrieveAll(event.queryStringParameters || {}) .then((searchResult) => { callback(null, { statusCode: 200, body: JSON.stringify(Object.assign(searchResult, { results: removeDuplicates(searchResult.results.map(result => result.getInfo())), })), }); }) .catch(err => ( ErrorHandler.handle(err) )) .catch(err => ( setTimeout(() => ( err.send(callback) )) )); };
import React from 'react'; import { Admin, Resource} from 'react-admin'; import restProvider from 'ra-data-simple-rest'; import {PostList} from './components/PostList'; import {PostCreate} from './components/PostCreate'; import {PostEdit} from './components/PostEdit'; function App() { return ( <Admin dataProvider={restProvider('http://localhost:3000')}> <Resource name="posts" list={PostList} create={PostCreate} edit={PostEdit}/> </Admin> ); } export default App;
const path = require('path'); const HtmlWebpackPlugin = require("html-webpack-plugin"); // Get all js files and turn modern javascript functions into older ones for backwards compability // Bundle all files in dist folder in order to reduce resource load at each request module.exports = { entry: "./src/index.js", //relative to root of the application output : { filename : './index.js', publicPath: '/' }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.html$/, use: [ { loader: "html-loader" } ] }, { test: /\.css$/, loader: "style-loader!css-loader" }, { test : /\.(jpg|png)$/, loader : 'url-loader?limit=25000' } ] }, devServer: { historyApiFallback: true, }, plugins: [ new HtmlWebpackPlugin({ hash: true, template: "./src/index.html", filename: './index.html' }) ] }
import './App.css'; import { useState } from 'react' import 'bootstrap/dist/css/bootstrap.min.css'; import { SeccionTask } from './components/SeccionTask' import { Alert } from 'react-bootstrap'; import { ModalElement } from './components/Modal' import { NewTask } from './components/NewTask' function App() { const [visible, setVisible] = useState(false) const [search, setSearch] = useState('') const [tarea, setTarea] = useState([]) const filterTask = (complete) => { if(search){ const searchTask = tarea.filter(item => item.task.toLocaleLowerCase().includes(search.toLocaleLowerCase())) return searchTask.filter(item => item.complete === complete) } return tarea.filter(item => item.complete === complete) } return ( <> <div className="container"> <h3 className="text-center p-2">Lista de tareas</h3> <div className="row justify-content-center"> <div className="col-12 col-md-5"> <input placeholder='Buscar tarea' onChange={event => setSearch(event.target.value)} className="form-control" /> </div> </div> <div className="row justify-content-center mt-4"> {filterTask(false).map(item => ( <div className="col-12 col-md-7 mb-3" key={item.id}> <SeccionTask task={item} setTarea={setTarea} tarea={tarea} /> </div> ))} {!filterTask(false).length && ( <div className="col-12 col-md-7"> <Alert variant='danger'> No hay tareas disponibles </Alert> </div> )} </div> <h3 className="text-center p-2">Completados</h3> <div className="row justify-content-center mt-4"> {filterTask(true).map(item => ( <div className="col-12 col-md-7 mb-3" key={item}> <SeccionTask task={item} setTarea={setTarea} tarea={tarea} /> </div> ))} </div> <div className="row justify-content-center mt-4"> <div className="col-5"> <button className="btn btn-info form-control" onClick={() => setVisible(true)}>Nueva tarea</button> </div> </div> <ModalElement open={visible} setOpen={setVisible}> <NewTask setOpen={setVisible} setTarea={setTarea} tarea={tarea} /> </ModalElement> </div> </> ); } export default App;
function changePopUpInfoTitle(newTitle) { return { type: "NORMAL", payload: newTitle, }; } function changePopUpInfoDescription(newDescription) { return { type: "CKEDITOR", payload: newDescription, }; } export { changePopUpInfoTitle, changePopUpInfoDescription };
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.action.encode.ActuateProjectStateAction'); goog.require('audioCat.action.Action'); goog.require('audioCat.state.events'); goog.require('audioCat.ui.dialog.DialogText'); goog.require('goog.asserts'); goog.require('goog.dom.classes'); /** * An action that takes a binary blob encoding of a project and actuates it - * overriding existing content and making the new project state the encoded one. * @param {!audioCat.utility.support.SupportDetector} supportDetector Detects * support for various features and formats. * @param {!audioCat.utility.dialog.DialogManager} dialogManager Manages * dialogs. * @param {!audioCat.state.StatePlanManager} statePlanManager Encodes and * decodes the state of the project. * @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions. * @constructor * @extends {audioCat.action.Action} */ audioCat.action.encode.ActuateProjectStateAction = function( supportDetector, dialogManager, statePlanManager, domHelper) { goog.base(this); /** * @private {!audioCat.state.StatePlanManager} */ this.statePlanManager_ = statePlanManager; /** * @private {!audioCat.utility.dialog.DialogManager} */ this.dialogManager_ = dialogManager; /** * @private {!audioCat.utility.DomHelper} */ this.domHelper_ = domHelper; /** * The name of the project file to import. Null if no encoding process is * happening now. * @private {string?} */ this.projectName_ = null; /** * The blob that is about to be encoded. May be null if no encoding process is * happening now. * @private {ArrayBuffer} */ this.encoding_ = null; }; goog.inherits(audioCat.action.encode.ActuateProjectStateAction, audioCat.action.Action); /** * Sets the name of the project file to import. Must be called before each call * to this action being done. Null to clear. * @param {string?} projectName The name of the project file. */ audioCat.action.encode.ActuateProjectStateAction.prototype.setFileName = function(projectName) { this.projectName_ = projectName; }; /** * Sets the encoding about to be actuated. Must be called before each call to * this action being done. Null to clear. * @param {ArrayBuffer} encoding The encoding. */ audioCat.action.encode.ActuateProjectStateAction.prototype.setEncoding = function(encoding) { this.encoding_ = encoding; }; /** * Makes the project reflect the encoding of the project state, overriding any * current content. After that, nulls out the current encoding remembered by * this action. * @override */ audioCat.action.encode.ActuateProjectStateAction.prototype.doAction = function() { goog.asserts.assert(!goog.isNull(this.encoding_)); goog.asserts.assert(!goog.isNull(this.projectName_)); var domHelper = this.domHelper_; var dialogManager = this.dialogManager_; var waitContent = domHelper.createDiv(); var innerContent = domHelper.createDiv( goog.getCssName('innerContentWrapper')); domHelper.setTextContent( innerContent, 'Loading ' + this.projectName_ + ' ...'); domHelper.appendChild(waitContent, innerContent); var waitDialog = dialogManager.obtainDialog(waitContent); var issueDecodingError = function(errorMessage) { // Issues a decoding error message. goog.asserts.assert(!goog.isNull(this.projectName_)); var errorContent = domHelper.createDiv(goog.getCssName('topBufferedDialog')); var innerErrorContent = domHelper.createDiv( goog.getCssName('innerContentWrapper')); goog.dom.classes.add(innerErrorContent, goog.getCssName('warningBox')); errorMessage = 'Error loading ' + this.projectName_ + ': ' + errorMessage; domHelper.setTextContent(innerErrorContent, errorMessage); domHelper.appendChild(errorContent, innerErrorContent); var errorDialog = dialogManager.obtainDialog( errorContent, audioCat.ui.dialog.DialogText.CLOSE); dialogManager.showDialog(errorDialog); }; goog.global.setTimeout(function() { // Asynchronously show the dialog to avoid being blocked by the main thread. dialogManager.showDialog(waitDialog); }, 1); // When loading the project terminates for whatever reason, handle it. this.statePlanManager_.listenOnce(audioCat.state.events.DECODING_ENDED, function(e) { e = /** @type {!audioCat.state.DecodingEndedEvent} */ (e); var error = e.getError(); if (error.length) { issueDecodingError(error); } // Unset values relevant to the previous decoding. this.projectName_ = null; this.encoding_ = null; goog.global.setTimeout(function() { // Hide the dialog. // Use a time out so it happens after the previous timeout. dialogManager.hideDialog(waitDialog); }, 2); }, false, this); this.statePlanManager_.decode(this.encoding_); };
db.movies.find( {$and:[ {category:{ $all:["adventure"] }}, {ratings:{ $elemMatch:{$gte:103} }} ]}, {_id:false,title:true,ratings:true,category:true} )
'use strict'; class HeaderController { /** @ngInject */ constructor($scope, Authentication, $state, TemplatesService) { Object.assign(this, {$scope, Authentication, $state, TemplatesService}); this.user = this.Authentication.user; $scope.$on('updateUserInfo', (event, user) => { angular.copy(user, this.user); }); } toggleSidebar() { this.$scope.$emit('toggleSidebar'); } } angular.module('core').controller('HeaderController', HeaderController);
import styled from 'styled-components'; export const Container = styled.div` padding: 20px 45px 0px; `; export const ResultMovieCard = styled.div` display: inline-flex; flex-direction : column; flex-wrap : wrap; margin: auto; box-shadow: 0 1px 1px rgba(0,0,0,0.15); background-color:white; border: 1px solid #efefef; border-radius: 4px; `; export const ResultMovieNameLink = styled.a` display : block; font-family: "Lato", sans-serif; text-decoration: none; font-style: unset; font-size: 15px; font-weight: 600; color: black; border: 0.5px 0.5px 0.5px 0.5px; width: fit-content; margin: 0px 0px 0px 8px; margin-right: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 12ch; `; export const ResultMovieYear = styled.p` display : block; color: #9e9e9e; margin-top: 0.5px; margin-left: 8px; margin-bottom: 0.5px; margin-right: 0.5px; padding-right: 8px; width: fit-content; font-family: 'Lato', sans-serif ; font-size : 13px; `; export const PlaceholderImg = styled.img` display : block; height: 140px; `; export const EmptyStateMsg = styled.p` display : block; font-size : 20px; width: 100%; text-align: center; margin-top:20%; margin-bottom:10%; `; export const EmptyStateMsgContainer = styled.div` width: 100%; align : center; `;
var intf = require("../scripts/intf-core.js"); var assert = require("assert"); function newDb() { var db = {}; return function(id) { return db[id]; } } var test = {}; test.testGeneral = function() { intf = createSampleThread3(); var linkages = [["1006", "1002"], ["1010", "1004"], ["1009", "1003"], ["1005", "1002"], ["1002", "1001"], ["1008", "1001"], ["1016", "1008"], ["1008", "1003"], ["1007", "1001"], ["1004", "1001"], ["1003", "1001"]]; intf.postdb.print(); linkPosts(intf, linkages); } test.testGeneral2 = function() { var sauce = [ {id:"0", parentIds:[]}, {id:"1", parentIds:["0"]}, {id:"2", parentIds:["1"]}, {id:"3", parentIds:["1"]}, {id:"4", parentIds:["0"]}, {id:"5", parentIds:["4"]}, {id:"6", parentIds:["0", "1", "2"]}, {id:"7", parentIds:["6"]}, {id:"8", parentIds:["6", "4"]}, {id:"9", parentIds:["6"]}, {id:"10", parentIds:["9", "3", "6"]}, {id:"11", parentIds:["6"]}, {id:"12", parentIds:["0", "1", "4"]}, {id:"13", parentIds:["0", "4", "10"]}, {id:"14", parentIds:["13", "8"]}, {id:"15", parentIds:["13"]}, {id:"16", parentIds:[]}, {id:"17", parentIds:["0", "1"]} ] var intf = createThreadFromSource(sauce); var linkages = [["1", "0"], ["2", "1"], ["6", "2"], ["4", "0"], ["6", "2"], ["7", "6"], ["1", "0"], ["4", "0"], ["6", "0"], ["4", "0"], ["6", "0"]] intf.postdb.print(); linkPosts(intf, linkages); } test.testGeneral3 = function() { var sauce = [ {id:"0", parentIds:[]}, {id:"1", parentIds:["0"]}, {id:"2", parentIds:["1"]}, {id:"3", parentIds:["1"]}, {id:"4", parentIds:["0"]}, {id:"5", parentIds:["4"]}, {id:"6", parentIds:["0", "1", "2"]}, {id:"7", parentIds:["6"]}, {id:"8", parentIds:["6", "4"]}, {id:"9", parentIds:["6"]}, {id:"10", parentIds:["9", "3", "6"]}, {id:"11", parentIds:["6"]}, {id:"12", parentIds:["0", "1", "4"]}, {id:"13", parentIds:["0", "4", "10"]}, {id:"14", parentIds:["13", "8"]}, {id:"15", parentIds:["13"]}, {id:"16", parentIds:[]}, {id:"17", parentIds:["0", "1"]} ] var intf = createThreadFromSource(sauce); var linkages = [["1", "0"], ["4", "0"], ["6", "0"], ["12", "0"], ["13", "0"], ["14", "13"], ["4", "0"], ["8", "4"], ["14", "8"], ["6", "0"], ["13", "0"], ["4", "0"], ["1", "0"], ["4", "0"], ["1", "0"], ["4", "0"], ["6", "0"], ["12", "0"], ["13", "0"], ["12", "0"], ["1", "0"], ["4", "0"], ["6", "0"], ["12", "0"], ["4", "0"], ["8", "6"]]; intf.postdb.print(); linkPosts(intf, linkages); } test.testCreation = function() { intf = intf.newModule(); var id, body; id = 1001; body = [ "git out", ].join("\n"); var post1 = intf.newPost({id: id, body: body}); assert.equal(post1.id, id); assert.equal(post1.body, body); assert.deepEqual(post1.parentIds, []); assert.equal(post1.norder.nextpost, null); assert.equal(post1.norder.prevpost, null); id = 1002; body = "nope"; var post2 = intf.newPost({id: id, body: body}); assert.equal(post2.id, id); assert.equal(post2.body, body); assert.deepEqual(post2.parentIds, []); assert.equal(intf.prevnorder(post2), post1); assert.equal(intf.nextnorder(post2), null); id = 1003; body = ">>1001 >>1002 yep"; var post3 = intf.newPost({id: id, body: body}); assert.equal(post3.id, id); assert.equal(post3.body, body); assert.deepEqual(post3.parentIds, [1001, 1002]); assert.equal(intf.nextnorder(post1), post2); assert.equal(intf.nextnorder(post2), post3); assert.equal(intf.nextnorder(post3), null); assert.equal(intf.prevnorder(post3), post2); assert.equal(intf.prevnorder(post2), post1); assert.equal(intf.prevnorder(post1), null); } test.testLinking = function() { intf = intf.newModule(); var post = createSampleThread1(intf); assert.equal(intf.nextsib(post[2], 1001), post[4]); assert.equal(intf.nextsib(post[4], 1001), post[5]); assert.equal(intf.nextsib(post[5], 1001), post[6]); assert.equal(intf.nextsib(post[6], 1001), post[2]); assert.equal(intf.prevsib(post[6], 1001), post[5]); assert.equal(intf.prevsib(post[5], 1001), post[4]); assert.equal(intf.prevsib(post[4], 1001), post[2]); assert.equal(intf.prevsib(post[2], 1001), post[6]); assert.equal(intf.nextsib(post[3], 1002), post[5]); assert.equal(intf.nextsib(post[5], 1002), post[3]); assert.equal(intf.prevsib(post[5], 1002), post[3]); assert.equal(intf.prevsib(post[3], 1002), post[5]); assert.equal(intf.nextsib(post[6], 1004), post[7]); assert.equal(intf.nextsib(post[7], 1004), post[6]); assert.equal(intf.prevsib(post[7], 1004), post[6]); assert.equal(intf.prevsib(post[6], 1004), post[7]); assert.equal(intf.nextsib(post[8], 1005), post[8]); assert.equal(intf.prevsib(post[8], 1005), post[8]); assert.deepEqual(intf.childrenIds(post[1]), [1002, 1004, 1005, 1006]); assert.deepEqual(intf.childrenIds(post[2]), [1003, 1005]); assert.deepEqual(intf.childrenIds(post[3]), []); assert.deepEqual(intf.childrenIds(post[4]), [1006, 1007]); assert.deepEqual(intf.childrenIds(post[5]), [1008]); assert.deepEqual(intf.childrenIds(post[6]), []); assert.deepEqual(intf.childrenIds(post[7]), []); assert.deepEqual(intf.childrenIds(post[8]), [1009]); assert.deepEqual(intf.childrenIds(post[9]), []); assert.equal(post[1].numReplies, 4); assert.equal(post[2].numReplies, 2); assert.equal(post[3].numReplies, 0); assert.equal(post[4].numReplies, 2); assert.equal(post[5].numReplies, 1); assert.equal(post[6].numReplies, 0); assert.equal(post[7].numReplies, 0); assert.equal(post[8].numReplies, 1); assert.equal(post[9].numReplies, 0); } test.testInNorderCase = function() { function aliases(intf) { var al = {}; al.p = intf.getPost.bind(intf); al.subt = function(id) { return intf.getSubthread(intf.getPost(id)); } al.supt = function(id) { return intf.getSupthread(intf.getPost(id)); } al.subtIds = function(id) { return intf.getSubthreadIds(intf.getPost(id)); } al.suptIds = function(id) { return intf.getSupthreadIds(intf.getPost(id)); } return al; } intf = createSampleThread2(); var al = aliases(intf); function assertEndPostIndented(id) { var posts = al.subt(id); assert.ok(intf.isIndented(posts[posts.length-1])); } intf.postdb.print(); // - both inNorder intf.attachToParent(al.p(1002), al.p(1001)); intf.postdb.print(); //assert.deepEqual(al.subtIds(1001), ["1001", "1002", "1003", "1004"]); //assertEndPostIndented(1001); validateState(intf, 1001, ["1001", "1002", "1003", "1004"]); validateInn(intf); intf.attachToParent(al.p(1014), al.p(1012)); intf.postdb.print(); validateState(intf, 1012, ["1012", "1014"]); validateState(intf, 1001, ["1001", "1002", "1003", "1004"]); validateInn(intf); intf.attachToParent(al.p(1015), al.p(1008)); intf.postdb.print(); validateState(intf, 1008, ["1008", "1015", "1016"]); validateState(intf, 1012, ["1012", "1014"]); validateState(intf, 1001, ["1001", "1002", "1003", "1004"]); validateInn(intf); // undented(parent), indented(parent) intf.attachToParent(al.p(1003), al.p(1001)); intf.postdb.print(); validateState(intf, 1008, ["1008", "1015", "1016"]); validateState(intf, 1012, ["1012", "1014"]); validateState(intf, 1001, ["1001", "1003", "1004", "1007"]); validateInn(intf); // undented(parent), innorder(parent) intf.attachToParent(al.p(1002), al.p(1001)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1003", "1004"]); validateState(intf, 1008, ["1008", "1015", "1016"]); validateState(intf, 1012, ["1012", "1014"]); validateInn(intf); // innorder(parent), indented(parent) intf.attachToParent(al.p(1015), al.p(1011)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1003", "1004"]); validateState(intf, 1012, ["1012", "1014"]); validateState(intf, 1008, ["1008", "1016"]); validateState(intf, 1011, ["1011", "1015"]); validateInn(intf); intf.clearSubthread(al.p(1011), null, true); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1003", "1004"]); validateState(intf, 1012, ["1012", "1014"]); validateState(intf, 1008, ["1008", "1016"]); assert.ok(intf.isInNorder(al.p(1011))); assert.ok(intf.isInNorder(al.p(1015))); validateInn(intf); intf.attachToParent(al.p(1014), al.p(1006)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1003", "1004"]); validateState(intf, 1006, ["1006", "1014"]); validateState(intf, 1008, ["1008", "1016"]); validateInn(intf); // siblings intf.attachToParent(al.p(1004), al.p(1002)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1004", "1007", "1005"]); validateState(intf, 1006, ["1006", "1014"]); validateState(intf, 1008, ["1008", "1016"]); validateInn(intf); intf.attachToParent(al.p(1004), al.p(1005)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1005", "1004"]); validateState(intf, 1006, ["1006", "1014"]); validateState(intf, 1008, ["1008", "1016"]); validateInn(intf); // ancestor intf.attachToParent(al.p(1014), al.p(1006)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1005", "1004"]); validateState(intf, 1006, ["1006", "1014"]); validateState(intf, 1008, ["1008", "1016"]); intf.attachToParent(al.p(1002), al.p(1001)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1002", "1005", "1004"]); validateState(intf, 1006, ["1006", "1014"]); validateState(intf, 1008, ["1008", "1016"]); validateInn(intf); intf.attachToParent(al.p(1004), al.p(1001)); intf.postdb.print(); //validateState(intf, 1001, ["1001", "1004", "1007", "1008"]); validateState(intf, 1001, ["1001", "1004", "1007"]); validateState(intf, 1006, ["1006", "1014"]); validateState(intf, 1008, ["1008", "1016"]); validateInn(intf); intf.attachToParent(al.p(1014), al.p(1004)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1004", "1014", "1013", "1010"]); validateState(intf, 1008, ["1008", "1016"]); validateInn(intf); intf.attachToParent(al.p(1008), al.p(1014)); intf.postdb.print(); validateState(intf, 1001, ["1001", "1004", "1014", "1008", "1016"]); validateInn(intf); } var validateInn = function(intf) { var innPosts = intf.postdb.inNorderPosts(); innPosts.forEach(function(post) { var ind = intf.isIndented(post); var inn = intf.isInNorder(post); assert.ok(!ind && inn, post.id + " is inNorder but ind="+ind + " inn="+inn); }); } var validateState = function(intf, id, expected) { var post = intf.getPost(id) if (!intf.isSubthreadRoot(post)) { console.warn("** validating a non-root post", id, "skipping..."); return; } var ids = intf.getSubthreadIds(post); var bid = ids[ids.length-1]; assert.deepEqual(ids, expected); assert.deepEqual(ids.slice(0).reverse(), intf.getSupthreadIds(intf.getPost(bid))); assertAll(intf.getSubthread(id), function(post) { return !intf.isInNorder(post); }); assert.ok(intf.isIndented(intf.getPost(bid))); } function createSampleThread1(intf) { var post = {}; post[1] = intf.newPost({ id: 1001, body: "'sup" }); post[2] = intf.newPost({ id: 1002, body: ">>1001 stfu" }); post[3] = intf.newPost({ id: 1003, body: ">>1002 no u" }); post[4] = intf.newPost({ id: 1004, body: ">>1001 no" }); post[5] = intf.newPost({ id: 1005, body: ">>1001 >>1002 no u" }); post[6] = intf.newPost({ id: 1006, body: ">>1001 >>1004 yes", }); post[7] = intf.newPost({ id: 1007, body: ">>1004 no what", }); post[8] = intf.newPost({ id: 1008, body: ">>1005 yes u", }); post[9] = intf.newPost({ id: 1009, body: ">>1008 no u fok u", }); return post; } function createSampleThread2() { mod = intf.newModule(); mod.newPost({id: 1001, body:""}); mod.newPost({id: 1002, body: ">>1001"}); mod.newPost({id: 1005, body: ">>1002"}); //1004 mod.newPost({id: 1006, body: ">>1002"}); //1014 // 1007 // 1004 mod.newPost({id: 1003, body: ">>1001"}); // 1007 mod.newPost({id: 1009, body: ">>1003"}); // 1011 // 1008 mod.newPost({id: 1004, body: ">>1001 >>1002 >>1005"}); mod.newPost({id: 1010, body: ">>1004"}); mod.newPost({id: 1011, body: ">>1004 >>1003"}); // 1015 mod.newPost({id: 1012, body: ">>1004"}); mod.newPost({id: 1014, body: ">>1012 >>1006 >>1004"}); mod.newPost({id: 1013, body: ">>1004"}); mod.newPost({id: 1007, body: ">>1001 >>1002 >> 1003"}); mod.newPost({id: 1008, body: ">>1001 >>1003 >>1014"}); mod.newPost({id: 1015, body: ">>1008 >>1011"}); mod.newPost({id: 1016, body: ">>1008"}); return mod; } function createSampleThread3() { mod = intf.newModule(); var posts = [ {id: 1001, body:""}, {id: 1002, body: ">>1001"}, {id: 1005, body: ">>1002"}, {id: 1006, body: ">>1002"}, {id: 1003, body: ">>1001"}, {id: 1009, body: ">>1003"}, {id: 1004, body: ">>1001 testing >>1002 123\nmumble>>1005jumble"}, {id: 1010, body: ">>1004"}, {id: 1011, body: ">>1004 >>1003"}, {id: 1012, body: ">>1004"}, {id: 1014, body: ">>1012 >>1006 >>1004"}, {id: 1013, body: ">>1004"}, {id: 1007, body: ">>1001 >>1002 >> 1003"}, {id: 1008, body: ">>1001 >>1003 >>1014"}, {id: 1015, body: ">>1008 >>1011"}, {id: 1016, body: ">>1008"}, ].forEach(function(data) { mod.newPost(data); }); return mod; } function createThreadFromSource(srcThread) { mod = intf.newModule(); srcThread.forEach(function(data) { mod.newPost(data); }); return mod; } function assertAll(list, p) { assert.ok(forAll(list, p)); } function forAll(xs, p) { var b = 1; xs.forEach(function(x) { b = b && p(x); }); return b; } function ids(postlist) { return postlist.map(function(post) { return post.id }); } function idm(postlist) { return toSet(ids(postlist)); } function toSet(list) { var m ={}; list.forEach(function(x) { m[x] = true; }); return m; } function linkPosts(intf, linkages) { linkages.forEach(function(link) { intf.attachToParent(intf.getPost(link[0]), intf.getPost(link[1])); intf.postdb.print(); validateInn(intf); }); } for (var name in test) { if (name.search("test") != 0) continue; console.log("*** Testing", name); test[name](); }
export const VALIDAR_FORMULARIO = 'VALIDAR_FORMULARIO' export const VALIDAR_FORMULARIO_EXITO = 'VALIDAR_FORMULARIO_EXITO' export const VALIDAR_FORMULARIO_ERROR = 'VALIDAR_FORMULARIO_ERROR' export const AGREGAR_PRODUCTO = 'AGREGAR_PRODUCTO' export const AGREGAR_PRODUCTO_EXITO = 'AGREGAR_PRODUCTO_EXITO' export const AGREGAR_PRODUCTO_ERROR = 'AGREGAR_PRODUCTO_ERROR' export const COMENZAR_DESCARGA_PRODUCTOS = 'COMENZAR_DESCARGA_PRODUCTO' export const COMENZAR_DESCARGA_PRODUCTOS_EXITOSA = 'COMENZAR_DESCARGA_PRODUCTO_EXITOSA' export const COMENZAR_DESCARGA_PRODUCTOS_ERROR = 'COMENZAR_DESCARGA_PRODUCTO_ERROR' export const OBTENER_PRODUCTO_ELIMINAR = 'OBTENER_PRODUCTO_ELIMINAR' export const PRODUCTO_ELIMINADO_EXITO = 'PRODUCTO_ELIMINADO_EXITO' export const PRODUCTO_ELIMINADO_ERROR = 'PRODUCTO_ELIMINADO_ERROR' export const OBTENER_PRODUCTO_EDITAR = 'OBTENER_PRODUCTO_EDITAR' export const PRODUCTO_EDITAR_EXITO = 'PRODUCTO_EDITAR_EXITO' export const PRODUCTO_EDITAR_ERROR = 'PRODUCTO_EDITAR_ERROR' export const COMENZAR_EDICION_PRODUCTO = 'COMENZAR_EDICION_PRODUCTO' export const PRODUCTO_EDITADO_EXITO = 'PRODUCTO_EDITADO_EXITO' export const PRODUCTO_EDITADO_ERROR = 'PRODUCTO_EDITADO_ERROR' export const COMENZAR_DESCARGA_PERSONAS = 'COMENZAR_DESCARGA_PERSONAS' export const COMENZAR_DESCARGA_PERSONAS_EXITO = 'COMENZAR_DESCARGA_PERSONAS_EXITO' export const COMENZAR_DESCARGA_PERSONAS_ERROR = 'COMENZAR_DESCARGA_PERSONAS_ERROR' export const OBTENER_PERSONA_ELIMINAR = 'OBTENER_PERSONA_ELIMINAR' export const PERSONA_ELIMINADO_EXITO = 'PERSONA_ELIMINADO_EXITO' export const PERSONA_ELIMINADO_ERROR = 'PERSONA_ELIMINADO_ERROR'
/** * Created by Bram on 4/11/2014. */ 'use sctrict' var _ = require('lodash'); var Categorie = require('./categorie.model'); //Lijst van vakantiecategories weergeven exports.index = function(reg, res){ Categorie.find(function(err, categories){ if(err){return handleError(res, err);} return res.json(200,categories); }); }; //Een vakantiecategorie weergeven exports.show = function(reg, res){ Categorie.findById(reg.param.id, function(err, categorie){ if(err){return handleError(res, err);} if(!categorie){res.send(404);} return res.json(categorie); }); }; //Maakt een nieuwe vakantieCategorie aan in de db exports.create = function(req, res) { Categorie.create(req.body, function(err, categorie) { if(err) { return handleError(res, err); } return res.json(201, categorie); }); }; // Updates de bestaande vakantiecategorie exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Categorie.findById(req.params.id, function (err, categorie) { if (err) { return handleError(res, err); } if(!categorie) { return res.send(404); } var updated = _.merge(categorie, req.body); updated.save(function (err) { if (err) { return handleError(res, err); } return res.json(200, categorie); }); }); }; //Verwijderd een vakantiecategorie exports.destroy = function(req, res) { Categorie.findById(req.params.id, function (err, categorie) { if(err) { return handleError(res, err); } if(!categorie) { return res.send(404); } categorie.remove(function(err) { if(err) { return handleError(res, err); } return res.send(204); }); }); }; function handleError(res, err) { return res.send(500, err); }
module.exports = { data: require($.lib.path.join( $.basedir, 'data/configuration' )) }
import React, { Component } from "react"; import "./App.css"; import $ from "jquery"; import PageList from './components/PageList/pageList' const searchURL = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search="; class App extends Component { state = { isLoaded: false, showInput: false, text: "", results: [] }; handleInput = e => { this.setState({ text: e.target.value }); }; // using jquery ajax, in order to get access to jsonp handleEnter = e => { let URL = searchURL + this.state.text; if (e.which === 13 && this.state.text !== "") { $.when( $.ajax({ url: URL, dataType: "jsonp" }) ).then(result => { this.setState({ isLoaded: true, text: "", results: result }); }); } }; render() { // after the first search is completed if (this.state.isLoaded && this.state.results !== []) { return ( <div className="AppAfter"> <input className="animated fadeIn" onKeyPress={this.handleEnter} type="text" onChange={this.handleInput} value={this.state.text} placeholder="Wikipedia..." />{" "} <br /> <a className="animated fadeIn" href="https://en.wikipedia.org/wiki/Special:Random" target="_blank" rel="noopener noreferrer" > <button className="btn btn-primary">Random page</button> </a> <PageList items={this.state.results} heading={this.state.results[1]} /> </div> ); } return ( <div className="landing-wrapper"> <div className = 'branding'> <p>Created by <a href = 'https://twitter.com/kris_bogdanov' target="_blank" rel="noopener noreferrer">Kris Bogdanov</a></p> </div> <input className="input animated fadeInUp" onKeyPress={this.handleEnter} type="text" onChange={this.handleInput} value={this.state.text} placeholder="Search on Wikipedia" /> <a className="animated fadeInUp" href="https://en.wikipedia.org/wiki/Special:Random" target="_blank" rel="noopener noreferrer" > <button className="btn btn-primary">Random page</button> </a> </div> ); } } export default App;
angular.module('shop2App') .controller('baoxiu',['$scope','$location',"$http",function($scope,$location,$http){ $scope.xingming="" $scope.tel="" $scope.num="" $scope.xiangqing="" $scope.jin="" $scope.zyx_bc=function(){ if($scope.xingming!=""&&$scope.num!=""&&$scope.xiangqing!=""&&$scope.jin!=""){ $http({ url:"http://47.88.16.225:412/baoxiu", method:"post", data:{ "uid":$scope.xingming , "shouji":$scope.tel,"zhuzhi":$scope.num ,"xiangqing":$scope.xiangqing,"zhuangtai":"未处理" } }).then(function(e){ $scope.data=e.data $location.url("/manage") }) }else{ alert("数据不完整") } } }]);
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.addColumn( 'Users', 'resetPasswordExpires', { type: Sequelize.DATE } ); }, down (queryInterface) { return queryInterface.removeColumn( 'Users', 'resetPasswordExpires' ); } }
'use strict' angular.module('videoSemana') .component('videoSemana', { templateUrl: 'home/video-semana/video-semana.template.html', controller: function($scope){ $scope.videoUrl = "url"; //pegar da api } });
layui.use(['jquery','layer'],function(){ var $ = layui.jquery, layer = layui.layer; var map = new BMap.Map("container"); var point = new BMap.Point(116.404, 39.915); map.centerAndZoom(point,10); map.enableScrollWheelZoom(); //鼠标缩放 map.enableKeyboard(); // 键盘平移 map.enableContinuousZoom(); // 连续缩放效果 map.enableInertialDragging(); // 惯性拖拽效果 map.addControl(new BMap.NavigationControl()); // 平移缩放控件 $.ajax({ type: "POST", url: "/route/allRoute", success: function (strData) { var data; if(typeof(strData) == "string"){ data = JSON.parse(strData); //部分用户解析出来的是字符串,转换一下 }else{ data = strData; } $(data.pole).each(function(i,n){ var point =new BMap.Point(n.lng,n.lat); // console.log(n.lng,n.lat); var myIcon = new BMap.Icon("/images/timg.png",new BMap.Size(16,16)); var marker =new BMap.Marker( point,{title:n.id}); // 创建点 map.addOverlay(marker); //增加点 //添加右键菜单 addRight(marker); }); // console.log(data.code); // console.log(data); } }); function addRight(marker){ //添加右键菜单 var menu = new BMap.ContextMenu(); var txtMenuItem=[ { text:"删除", callback:function(){ $.ajax({ type: "POST", url: "/route/delPole", data:{'id':marker.getTitle()}, success: function (strData) { var data; if(typeof(strData) == "string"){ data = JSON.parse(strData); //部分用户解析出来的是字符串,转换一下 }else{ data = strData; } console.log(data.code); console.log(data); if(data.code==200){ map.removeOverlay(marker); }else{ layer.msg('塔杆已加入路线,请先删除路线'); return false; } } }); } } ]; for(var i = 0;i<txtMenuItem.length;i++){ menu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100)); } marker.addContextMenu(menu); } // 动态添加坐标 map.addEventListener("click",addDian); //点击添加塔杆 function addDian(e){ var title = prompt("请输入坐标名称"); // var title = layer.confirm('请输入坐标名'); if(title!=null &&title!=''){ var zuobiao = new BMap.Point(e.point.lng, e.point.lat); // var myIcon = new BMap.Icon("res/images/timg.png",new BMap.Size(16,16)); var marker = new BMap.Marker(zuobiao,{title:title}); $.ajax({ type: "POST", url: "/route/addPole", data:{'title':title,'lng':e.point.lng,'lat':e.point.lat}, success: function (strData) { var data; if(typeof(strData) == "string"){ data = JSON.parse(strData); //部分用户解析出来的是字符串,转换一下 }else{ data = strData; } console.log(data.code); console.log(data); if(data.code==200){ map.addOverlay(marker); addRight(marker); }else{ layer.msg('塔杆编号已存在'); return false; } } }); }else{ return false; } } });
const Comment = require('../models/comment'); const Project = require('../models/project'); const { body, validationResult } = require('express-validator/check'); const { sanitizeBody } = require('express-validator/filter'); exports.sanitize = function(req, res, next) { sanitizeBody('text'); next(); } exports.validate = function(route) { switch(route) { case 'saveNewComment': { return [ body('comment.text').not().isEmpty().withMessage('Message body is empty.').trim() ] } } } // create comment - post (create new in databases) exports.saveComment = function(req, res) { const errors = validationResult(req); if (!errors.isEmpty()) { console.log("ERRORS::") for (let err in errors.array) { console.log(err.msg) } // console.log(errors.array) res.redirect('/project/' + req.params.id) return; } Project.findById(req.params.id, (err, proj) => { if (err) { console.error(err); return res.redirect('/' + req.user.username) // redirect to global feed } else { comment = new Comment({ text: req.body.comment.text, 'author.id': req.user._id, 'author.username': req.user.username }); comment.save((err, savedComment) => { if (err) { return console.log(err); } else { // link new comment to project proj.comments.push(savedComment) proj.save() res.redirect('/project/' + proj._id) } }) } }) } // delete comment - post (delete in database) // update comment - get (show update form) // update comment - post (post update to database)
import axios from "axios"; /** Action Types */ export const UPDATE_QUIZ_DATA = "update-quiz-data"; export const UPDATE_ERROR = "update-error"; export const fetchQuizData = (callback, callbackError) => { const url = createPlatformURL("api.php"); const params = { amount: 10, difficulty: "hard", type: "boolean" }; return dispatch => { axios .get(url, createMutationHeaders(params)) .then(res => { dispatch(updateQuizData(res.data)); callback && callback(); }) .catch(error => { dispatch(updateError(error)); callbackError && callbackError(); }); }; }; export const updateQuizDataWithAnswers = (data, callback) => { return dispatch => { dispatch(updateQuizData(data)); callback && callback(); }; }; export const createPlatformURL = api => { let publicUrl = `${"https://opentdb.com/"}/${api}`; return encodeURI(publicUrl); }; export const createMutationHeaders = additionalParams => { return { params: Object.assign({}, additionalParams) }; }; export const updateQuizData = data => { return { type: UPDATE_QUIZ_DATA, payload: data }; }; export const updateError = data => { return { type: UPDATE_ERROR, payload: data }; };
import DashBoard from './DashBoard'; export{DashBoard};
$('.ms-dlgContent').prevObject[0].activeElement.href = page + "?IsDlg=1"; // Possível problema de click no IE. location.replace(url + "?IsDlg=1"); // Menor e mais eficiente nos navegadores.
import axios from 'axios'; import * as actions from '../constants'; export const fetchWeatherStart = () => ({ type: actions.FETCH_WEATHER_START, }); export const fetchWeatherSuccess = (data) => ({ type: actions.FETCH_WEATHER_SUCCESS, payload: data, }); export const fetchWeatherFailure = (err) => ({ type: actions.FETCH_WEATHER_FAILURE, payload: err, }); export const fetchCoordsSuccess = (data, coords) => ({ type: actions.FETCH_COORDS_SUCCESS, payload: { data, coords, }, }); export const setError = (err) => ({ type: actions.SET_ERROR, payload: err, }); export const fetchForecastSuccess = (data) => ({ type: actions.FETCH_FORECAST_SUCCESS, payload: data, }); export const fetchForecastFailure = (err) => ({ type: actions.FETCH_WEATHER_FAILURE, payload: err, }); export const fetchWeatherByCoords = ({ coords, key }) => async (dispatch) => { axios .get(`https://api.openweathermap.org/data/2.5/weather?lat=${coords.lat}&lon=${coords.lon}&appid=${key}&units=metric`) .then((res) => { dispatch(fetchCoordsSuccess(res.data, coords)); }) .catch((err) => { dispatch(fetchWeatherFailure(err.response ? err.response.data.message : err.message)); }); }; export const fetchForecast = ({ name, key }) => async (dispatch) => { dispatch(fetchWeatherStart()); axios .get(`https://api.weatherbit.io/v2.0/forecast/daily?city=${name}&key=${key}`) .then((res) => { dispatch(fetchForecastSuccess(res.data)); }) .catch((err) => { dispatch(fetchForecastFailure(err.response ? err.response.data.message : err.message)); }); }; export const fetchWeatherByName = (forecast, url) => async (dispatch) => { dispatch(fetchWeatherStart()); axios .get(url) .then((city) => { if (city.statusText !== 'No Content') { if (forecast) { dispatch(fetchForecastSuccess(city.data)); const newurl = `${window.location.protocol}//${window.location.host}/forecast/${city.data.city_name}`; window.history.pushState({ path: newurl }, '', newurl); } else { dispatch(fetchWeatherSuccess(city.data)); } } else { dispatch(fetchWeatherFailure('City not found')); } }) .catch((err) => { dispatch(fetchWeatherFailure(err.response ? err.response.data.message : err.message)); }); }; export const fetchForecastAuto = (name, key) => async (dispatch) => { dispatch(fetchWeatherStart()); axios .get(`https://api.weatherbit.io/v2.0/forecast/daily?city=${name}&key=${key}`) .then((res) => { dispatch(fetchForecastSuccess(res.data)); }) .catch((err) => { dispatch(fetchForecastFailure({ msg: err.response ? err.response.data.message : err.message, })); }); }; export const fetchSearchListStart = () => ({ type: actions.FETCH_SEARCH_LIST_START, }); export const fetchSearchListSuccess = (data) => ({ type: actions.FETCH_SEARCH_LIST_SUCCESS, payload: data, }); export const fetchSearchListFailure = () => ({ type: actions.FETCH_SEARCH_LIST_FAILURE, }); export const resetSearchList = () => ({ type: actions.FETCH_SEARCH_LIST_FAILURE, }); export const setActiveSearchListElement = (val) => ({ type: actions.SET_ACTIVE_SEARCH_LIST_ELEMENT, payload: val, }); export const setActiveSearchListElementByMouseover = (val) => ({ type: actions.SET_ACTIVE_SEARCH_LIST_ELEMENT_BY_MOUSEOVER, payload: val, }); export const fetchSearchList = (query) => async (dispatch) => { if (query.trim().length > 2) { dispatch(fetchSearchListStart()); axios .get(`https://public.opendatasoft.com/api/records/1.0/search/?dataset=worldcitiespop&q=${query}&rows=5&sort=population`) .then((res) => { const list = []; for (let i = 0; i < res.data.records.length; i += 1) { if (res.data.records[i].fields.population) list.push(res.data.records[i]); } dispatch(fetchSearchListSuccess(list)); }) .catch(() => { dispatch(fetchSearchListFailure()); }); } else dispatch(fetchSearchListFailure()); }; export const fetchHourlyByNameSuccess = (data) => ({ type: actions.FETCH_HOURLY_BY_NAME_SUCCESS, payload: data, }); export const fetchHourlyByNameFailure = (err) => ({ type: actions.FETCH_HOURLY_BY_NAME_FAILURE, payload: err, }); export const fetchHourlyByName = (name, fKey, wKey) => async (dispatch) => { dispatch(fetchWeatherStart()); axios .get(`https://api.weatherbit.io/v2.0/forecast/daily?city=${name}&key=${fKey}`) .then((res) => { axios .get(`https://api.openweathermap.org/data/2.5/onecall?lat=${res.data.lat}&lon=${res.data.lon}&exclude=current,minutely,daily&appid=${wKey}&units=metric`) .then((data) => { let result = data.data; result = { ...result, city_name: res.data.city_name, country_code: res.data.country_code, }; dispatch(fetchHourlyByNameSuccess(result)); }) .catch(() => { dispatch(fetchHourlyByNameFailure('City not found')); }); }) .catch((err) => { dispatch(fetchHourlyByNameFailure(err.response ? err.response.data.message : err.message)); }); };
function facebook(){ var provider = new firebase.auth.FacebookAuthProvider(); firebase.auth().signInWithPopup(provider) .then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(user) var x = document.getElementById("btnss"); x.setAttribute('class','hide') ////////////////////////////////////////////////////////// // var userName = document.querySelector("#userName") // userName.innerHTML = user.displayName; /////////////////////////////////////////////////////////// ////firebase database/// // var xyz = document.getElementById("userName").innerHTML = user.displayName; // console.log(xyz) // var message = document.getElementById("message").value; // firebase.database().ref("chatapp").push().set({ // "sender": xyz, // "message": message // }) /////////////////////////////////////////////////////////////////////////////////////// // var xyz = document.getElementById("userName").innerHTML = user.displayName; // console.log(xyz) // var message = document.getElementById("message").value; // var sendBtn = // firebase.database().ref("chatapp").push().set({ // "sender": xyz, // "message": message // }) //////////////////////////////////////////////////////////////////////////////////////// var sendBtn = document.querySelector("#sendBtn") var xyz = document.getElementById("userName").innerHTML = user.displayName; var userMessage = document.querySelector("#message") sendBtn.addEventListener('click', function(){ var userMessageInput = userMessage.value; var key = firebase.database().ref('student').push().key firebase.database().ref('student/' + key ).set({ name: xyz, message: userMessageInput, key: key, }) //////////////////not working////////////////////////////////// // document.getElementById("chatting").value = ""; // document.getElementById("chatting").focus(); /////////////////////////////////////////////////////////////////// // firebase.database().ref('student').on('child_added', function(snapshot){ // var html = ""; // html += "<li>"; // html += snapshot.val().name + ": " + snapshot.val().message; // html +="</li>"; // document.getElementById("chatting").innerHTML += html; // }); //get data on li firebase.database().ref("student").on("child_added", (data) => { let ul = document.getElementById("chatting"); let li = document.createElement("li"); li.setAttribute("id", "li"); li.innerHTML = data.val().name + " : " + data.val().message; ul.appendChild(li); document.getElementById("message").value = ""; }) }).catch(function(error) { console.log(error.message) } )} )}
import React from 'react'; import { shallow } from 'enzyme'; import App from './App'; import List from './List'; describe('App', () => { let wrapper, form; beforeEach(() => { wrapper = shallow(<App />); form = wrapper.find('form'); }); it('should add an item on submit', () => { expect(wrapper.find(List).props().items.length).toEqual(0); form.simulate('submit', { preventDefault: jest.fn() }); expect(wrapper.find(List).props().items.length).toEqual(1); }); it('should add two items on submit', () => { form.simulate('submit', { preventDefault: jest.fn() }); form.simulate('submit', { preventDefault: jest.fn() }); expect(wrapper.find(List).props().items.length).toEqual(2); }); it('should mock preventDefault', () => { const mockPreventDefault = jest.fn(); form.simulate('submit', { preventDefault: mockPreventDefault }); expect(mockPreventDefault).toHaveBeenCalledTimes(1); }); it('should add a ref to state on change', () => { const value = 'Hello world'; const input = wrapper.find('input'); input.simulate('change', { target: { value } }); form.simulate('submit', { preventDefault: jest.fn() }); expect(wrapper.find(List).props().items[0]).toBe(value); }); });
const plugins = [ [ "module-resolver", { root: ["./app/"], alias: { "_assets": "./app/assets", "_shared":"./app/shared", "_screens":"./app/screens", "_theme":"./app/theme", "_navigation":"./app/navigation" } } ] ]; module.exports = { presets: ["babel-preset-expo"], plugins: [...plugins], }
AdjustmentsView = React.createClass({ mixins: [ReactMeteorData], getMeteorData: function() { var currentUser = Meteor.user().username; return { adjustments: Adjustments.findOne(), }; }, editAdjustments: function() { var ap = parseInt(document.getElementById("ap").value); var travel = parseInt(document.getElementById("travel").value); Meteor.call("editAdjustments", ap, travel); this.exit(); }, exit: function() { Meteor.call("setMode", "apptView"); }, render: function() { return ( <div> <p>AP: $<input type="text" id="ap" defaultValue={this.data.adjustments.ap} /></p> <p>Travel: $<input type="text" id="travel" defaultValue={this.data.adjustments.travel} /></p> <p><button className="btn btn-raised btn-default" onClick={this.exit}>Cancel</button> <button className="btn btn-raised btn-primary" onClick={this.editAdjustments}>Submit</button></p> </div> ); } });
function idCard(){ var first = document.getElementById('firstName').value; var last = document.getElementById('lastName').value; var Address = document.getElementById('Address').value; var idCard = "I am " + first +" "+ last; var idCard1 = Address; document.getElementById("postFullName").innerHTML = idCard ; document.getElementById("postAddress").innerHTML = idCard1 ; var Age = document.getElementById('Age').value; var phoneNumber = document.getElementById('phoneNumber').value; var numberArray = [Age, phoneNumber]; for (var i=0; i < numberArray.length; i++){ if (numberArray[i] <= 100){ document.getElementById('postAge').innerHTML = Age; } if (numberArray[i] > 100){ document.getElementById('postPhoneNumber').innerHTML = phoneNumber; } } }
var app = getApp(); Page({ data: { selectStatus: 0, monthObj: { name: "月份", id: "" }, companyObj: { name: "班组人员选择", id: "" }, classObj: { name: "状态", id: "" }, blockIsShow: true, time: "获取验证码", countTime: 60, disabled: false, codeVal: "", }, onLoad: function (options) { this.setData({ groupId: options.groupId, groupName: options.groupName, userPhone: app.globalData.userPhone }) wx.setNavigationBarTitle({ title: options.groupName+"工作量" }) }, onShow: function () { var that = this; let groupId = that.data.groupId // 月份(groupId必传) app.wxRequest("gongguan/api/wechat/groupQuantityMonth", { groupId: groupId}, "post", function (res) { var data = res.data.data; console.log("月份:",res.data.data) if (res.data.code == 0) { that.setData({ headerDate: data }) } else { app.showLoading(res.data.msg, "none"); } }) // 班组人员(groupId必传) app.wxRequest("gongguan/api/wechat/groupQuantityPerson", { groupId: groupId }, "post", function (res) { var data = res.data.data; console.log("班组人员:",res.data.data) if (res.data.code == 0) { that.setData({ perData: data }) } else { app.showLoading(res.data.msg, "none"); } }) // 状态(groupId必传) app.wxRequest("gongguan/api/wechat/salaryStatus", { groupId: groupId }, "post", function (res) { var data = res.data.data; console.log("状态人员:", res.data.data) if (res.data.code == 0) { that.setData({ statusData: data }) } else { app.showLoading(res.data.msg, "none"); } }) // tab上面数据(projectId) app.wxRequest("gongguan/api/wechat/groupQuantity", { projectId: "" }, "post", function (res) { var data = res.data.data; console.log("列表:",res.data.data) if (res.data.code == 0) { that.setData({ workData: data }) } else { app.showLoading(res.data.msg, "none"); } }) // 表格 that.getList(groupId,1,"","","") }, // 获取列表 getList: function (groupId, page, month, status, personId){ var that = this; // 表格 app.wxRequest("gongguan/api/wechat/groupQuantityDetail", { groupId: groupId, page: page, month: month, status: status, personId: personId }, "post", function (res) { var data = res.data.data; console.log("表格数据:", res.data.data) if (res.data.code == 0) { var arr = data.t; for (var i = 0; i < arr.length; i++) { arr[i].isChecked = false } that.setData({ tabData: data }) } else { app.showLoading(res.data.msg, "none"); } }) }, //多选框点击 checkboxChange: function (e) { let isChecked = e.currentTarget.dataset.ischecked;//是否选中 let idx = e.currentTarget.dataset.idx;//下标 console.log(e.currentTarget.dataset) var tabData = 'tabData.t[' + idx + '].isChecked' this.setData({ [tabData]: !isChecked }) }, // 全选 allCheckbox: function (e) { var data = this.data.tabData; var arr = data.t var allCheck = this.data.allCheck; this.setData({ allCheck: !allCheck }) if (allCheck) { for (var i = 0; i < arr.length; i++) { arr[i].isChecked = false } } else { for (var i = 0; i < arr.length; i++) { arr[i].isChecked = true } } this.setData({ tabData: data }) }, // 全部确定 allConfirm: function () { var that = this; let data = that.data.tabData.t; let groupId = that.data.groupId; var arr = []; for (var i = 0; i < data.length; i++) { arr.push(data[i].id) } var ids = arr.join(','); that.setData({ ids: ids, blockIsShow: false, }) }, // 呼出浮层 confirmTap: function () { var that = this; let data = that.data.tabData.t; var arr = []; for (var i = 0; i < data.length; i++) { if (data[i].isChecked) { arr.push(data[i].id) } } var ids = arr.join(','); console.log(ids) that.setData({ ids:ids, blockIsShow: false }) }, // 月份 peojectTap: function () { var that = this; if (that.data.selectStatus == 1 ){ this.setData({ selectStatus: 0 }) }else{ this.setData({ selectStatus: 1 }) } }, // 班组人员 companyTap: function () { var that = this; if (that.data.selectStatus == 2) { this.setData({ selectStatus: 0 }) } else { this.setData({ selectStatus: 2 }) } }, // 状态 classTap: function () { var that = this; if (that.data.selectStatus == 3) { this.setData({ selectStatus: 0 }) } else { this.setData({ selectStatus: 3 }) } }, //查看详情 goDetails: function (e) { let month = e.currentTarget.dataset.month; // wx.navigateTo({ // url: "/page/tabBar/homePages/stayworkDetails/stayworkDetails?groupId=" + this.data.groupId + "&month=" + month // }) }, //多选框点击 checkboxChange: function (e) { let isChecked = e.currentTarget.dataset.ischecked;//是否选中 console.log(isChecked) let idx = e.currentTarget.dataset.idx;//下标 var tabData = 'tabData.t[' + idx + '].isChecked' this.setData({ [tabData]: !isChecked }) }, // 月份选择 peojectList: function (e) { var that = this; // 月份 let month = e.currentTarget.dataset.month || ""; // 班组id let groupId = that.data.groupId; // 人员id let personid = that.data.companyObj.id || ""; // 状态 let status = that.data.classObj.id || ""; // 分页 let page = 1; var obj = { name: month || "月份", id: month } that.getList(groupId, page, month, status,personid) that.setData({ selectStatus: 0, monthObj: obj }) }, // 班组人员选择 companyList: function (e) { var that = this; // 月份 let month = that.data.monthObj.id || ""; // 班组id let groupId = this.data.groupId; // 人员id let personid = e.currentTarget.dataset.personid || ""; let name = e.currentTarget.dataset.name; // 状态 let status = that.data.classObj.id || ""; // 分页 let page = 1; var obj = { name: name || "班组人员选择", id: personid || "" } that.getList(groupId, page, month, status, personid) this.setData({ selectStatus: 0, companyObj: obj }) }, // 状态选择 classList: function (e) { var that = this; // 月份 let month = that.data.monthObj.id || ""; // 班组id let groupId = that.data.groupId; // 人员id let personid = that.data.companyObj.id || ""; // 状态 let status = e.currentTarget.dataset.status || ""; // 分页 let page = 1; var obj = { name: status || "状态", id: status } that.getList(groupId, page, month, status, personid) this.setData({ selectStatus: 0, classObj: obj }) }, // 取消 no_tap: function () { this.setData({ blockIsShow: true }) }, // 获取验证吗 getCode: function () { var that = this; // 验证码倒计时 that.setData({ disabled: true }) var countTime = that.data.countTime var interval = setInterval(function () { countTime-- that.setData({ time: countTime + 's' }) if (countTime <= 0) { clearInterval(interval) that.setData({ time: '重新发送', countTime: 60, disabled: false }) } }, 1000) app.wxRequest("gongguan/front/isSendSmsCode.action", { tel: that.data.userPhone }, "post", function (res) { console.log("验证码:", res.data.data); if (res.data.code == 0) { var data = res.data.data; } else { app.showLoading(res.data.msg, "none"); } }) }, // 获取输入的code get_val: function (e) { this.setData({ codeVal: e.detail.value }) }, // 确定 confirmBtn: function () { var that = this; if (that.data.ids) { // 全部确定 app.wxRequest("gongguan/api/wechat/groupQuantityConfirm", { ids: that.data.ids, groupId: that.data.groupId, verificationCode: that.data.codeVal }, "post", function (res) { console.log("确定", res.data.data) if (res.data.code == 0) { wx.navigateBack() } else { app.showLoading(res.data.msg, "none"); } }) } else { app.showLoading("最少勾选一项", "none") } } })
$(document).ready(function () { $("#simpleBtn").click(function (e) { $('#addPerson').lightbox_me({ centered: true, onLoad: function () { } }); e.preventDefault(); }); $(".deleteBtn").click(function () { $("#deletePerson").val($(this).attr("userId")); $("#deletePerson").click(); }); $("tbody").mousemove(function () { var buttons = $(this).find("button"); buttons.css("opacity", 0.8); }); $("tbody").mouseout(function () { var buttons = $(this).find("button"); buttons.css("opacity", 0.3); }); $("#search").change(function () { searchUsers($("#search").val()); }); }); function searchUsers(login) { $.getJSON("/TelephoneBook/searchPersons", { searchInitial: login}) .done(function (foundList) { for (var i = 0; i < foundList.length; i++) { var data = {user: foundList[i]}; console.log(data); } }) .fail(function () { alert("Ошибка при обновлении списка"); }); }
import styled from "styled-components"; export let HeadingContainer = styled.h3` font-size: ${(props) => props.size}; font-weight: 400; text-align: right; width: 55%; position: absolute; right: 2.3rem; bottom: 3rem; color: white; z-index: 10; span { padding: 1rem 1.5rem; -webkit-box-decoration-break: clone; box-decoration-break: clone; line-height: 1; background-image: linear-gradient( to bottom right, rgba(125, 213, 111, 0.85), rgba(40, 180, 135, 0.85) ); } `;
import React, { PropTypes } from 'react'; import { DropTarget, XYCoord } from 'react-dnd'; import TextOverlay from './TextOverlay' import Button from '@material-ui/core/Button'; import Icon from '@material-ui/core/Icon'; import IconButton from '@material-ui/core/IconButton'; const styles = { overlay_icon: { position: 'absolute', top: '0px', right: '0px' } } const dropTarget = { drop(props, monitor) { const item = monitor.getItem() console.log(monitor) console.log(item) const delta = monitor.getDifferenceFromInitialOffset() console.log(delta) const left = Math.round(item.left + delta.x) const top = Math.round(item.top + delta.y) props.dispatches.updateOverlay({ left: left, top: top, _id: item._id }); } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } class PreviewImage extends React.Component { render () { const { connectDropTarget } = this.props return connectDropTarget( <div className='contains-hover'> <IconButton aria-label="Add overlay" onClick={this.props.addOverlay} className='overlay-icon show-on-hover' style={styles.overlay_icon}> <Icon>font_download</Icon> </IconButton> <img src={this.props.src} onBlur={this.props.onBlur} style={this.props.style} onClick={this.props.onClick} /> { this.props.overlays.map(overlay => ( <TextOverlay overlay={overlay} key={overlay._id} dispatches={this.props.dispatches} /> ))} </div> ) } } export default DropTarget('textOverlay', dropTarget, collect)(PreviewImage)
const PATH_COLORS = ["#6BFF2A", "#C2FF2A", "#FFF22A", "#FFB22A", "#FF372A"]; function getPathColor (value, limits) { for (let idx in limits) { if (value <= limits[idx]) { return PATH_COLORS[idx]; } }; return PATH_COLORS[PATH_COLORS.length-1] }; export default { PATH_COLORS, getPathColor, }
const GECKO_DRIVER = require('geckodriver'); const IE_DRIVER = require('iedriver'); const SELENIUM_SERVER = require('selenium-server'); module.exports = { src_folders: ["src/tests"], page_objects_path: ["page-objects"], output_folder: "output/reports", parallel_process_delay: 10, "test_workers": { "enabled": false, "workers": "auto" }, selenium: { start_process: true, start_session: false, server_path: SELENIUM_SERVER.path, port: 4444, cli_args: { "webdriver.gecko.driver": GECKO_DRIVER.path, "webdriver.ie.driver": IE_DRIVER.path } }, test_settings: { default: { launch_url: "http://localhost", selenium_port: 4444, selenium_host: "localhost", desiredCapabilities: { browserName: "firefox", } }, headlessFirefox: { desiredCapabilities: { browserName: "firefox", marionette: true, javascriptEnabled: true, acceptSslCerts: true, "moz:firefoxOptions": { args: ['--headless'] } } }, ie: { desiredCapabilities: { browserName: 'internet explorer', javascriptEnabled: true } } } }
/*~~~~~~~~~~~~~~~~~~~~ Begin Boiler Plate ~~~~~~~~~~~~~~~~~~*/ const readline = require('readline'); const readlineInterface = readline.createInterface(process.stdin, process.stdout); function ask(questionText) { return new Promise((resolve, reject) => { readlineInterface.question(questionText, resolve); }); } /*~~~~~~~~~~~~~~~~~~~~~~End Boiler Plate~~~~~~~~~~~~~~~~~~~~*/ //Classes class Room { constructor(name, description, inventory, canChangeTo){ this.name = name; this.description = description; this.roomInventory = inventory; this.canChangeTo = canChangeTo; } } class Item{ constructor(name, description, canPickUp, pickUpText, inventoryText, openText){ this.name = name; this.description = description; this.canPickUp = canPickUp; this.pickUpText = pickUpText; this.inventoryText = inventoryText; this.openText = openText; } } class Player { constructor(currentState, playerInventory) { this.currentState = currentState; this.playerInventory = playerInventory; } actions(actionToDo, item) { this[actionToDo] ? this[actionToDo](item) : console.log(`I do not know how to ${actionToDo}`); getInput(); } look() { console.log(roomLookupTable[this.currentState].description); getInput(); } read(item){ if(roomLookupTable[this.currentState].roomInventory.includes(lookUpItems[item]) || this.playerInventory.includes(lookUpItems[item])){ console.log(lookUpItems[item].description); }else{ console.log(`I'm sorry I can't read the ${item}`); } getInput(); } take(item){ if(roomLookupTable[this.currentState].roomInventory.includes(lookUpItems[item]) && lookUpItems[item].canPickUp){ let index = roomLookupTable[this.currentState].roomInventory.indexOf(lookUpItems[item]) this.playerInventory.push(roomLookupTable[this.currentState].roomInventory[index]); // console.log(this.playerInventory); console.log(lookUpItems[item].pickUpText) }else if(roomLookupTable[this.currentState].roomInventory.includes(lookUpItems[item])){ console.log(lookUpItems[item].pickUpText); }else{ console.log(`I'm sorry I can't take the ${item}.`); } getInput(); } drop(item){ if(player.playerInventory.includes(lookUpItems[item])){ //console.log(`The player does have ${item} in their inventory`); let index = player.playerInventory.indexOf(lookUpItems[item]); roomLookupTable[this.currentState].roomInventory.push(player.playerInventory[index]); player.playerInventory.splice(index, 1);; console.log(`You dropped the ${item}`); getInput(); } else { console.log(`I'm sorry you can't drop the ${itemName}`); getInput(); } } open(item){ if(lookUpItems[item].openText){ console.log(lookUpItems[item].openText); }else{ console.log(`I'm sorry I can't open ${item}`) } getInput(); } code(number){ if(roomLookupTable[this.currentState] === mainSt && number === '12345'){ console.log(`Success! The door opens. You enter the foyer and the door shuts behind you.`); enterState('foyer', 'mainSt'); }else if(roomLookupTable[this.currentState] === mainSt && number !== '12345'){ console.log(`Bzzzzt! The door is still locked.`); getInput(); }else{ console.log('There is no keypad on this side.'); getInput(); } } inventory(){ if(player.playerInventory.length < 1){ console.log("You have nothing.") return getInput(); } else { player.playerInventory.forEach(function(element) { console.log(element.inventoryText); }); return getInput(); } } move(newState){ if(Object.keys(roomLookupTable).includes(newState) && this.currentState !== "mainSt"){ console.log(this.currentState); enterState(newState, this.currentState); console.log(this.currentState.description) } else { console.log(`I can't move to ${newState}`) } getInput(); } async xyzzy(){ let newRoom = await ask("Which room would you like to go to mainSt or foyer?") if(Object.keys(roomLookupTable).includes(newRoom)){ this.currentState = newRoom; console.log(roomLookupTable[player.currentState].name); console.log(roomLookupTable[player.currentState].description); }else{ console.log(`That isn't a choice. Please try again`); return xyzzy(); } return getInput(); } } //Items const paper = new Item( "Seven Days", "Some kind of newspaper with bands you've never heard of.", true, `You pick up the paper and leaf through it looking for comics and ignoring the articles, just like everybody else does.`, "You are carrying Seven Days, Vermonts Alt-Weekly", "You flip through the pages. Nothing catches your eye." ); const sign = new Item( "Sign", `Welcome to Burlington Code Academy! Come on up to the third floor. If the door is locked, use the code 12345`, false, "That would be selfish. How will other students find their way?", "", "", ); const door = new Item( "door", "182 Main St", false, "It's locked and I don't know how you'd carry it.", "", "The door is locked. There is a keypad on the door handle." ); //Rooms let mainSt = new Room( "182 Main St.", `You are standing on Main Street between Church and South Winooski. There is a door here. A keypad sits on the handle. On the door is a handwritten sign.`, [sign, door], ['mainSt', 'foyer'] ); let foyer = new Room( '182 Main St. - Foyer', `You are in a foyer. Or maybe it's an antechamber. Or a vestibule. Or an entryway. Or an atrium. Or a narthex. But let's forget all that fancy flatlander vocabulary, and just call it a foyer. In Vermont, this is pronounced "FO-ee-yurr". A copy of Seven Days lies in a corner.`, [paper], ['street', 'roomThree'], ); //Do we need a lookup table for [current].description to work? Marshall mentioned that you can't have the first //key be a variable unless you use a lookup table to convert the strimovng to an object by naming itself const roomLookupTable = { mainSt: mainSt, foyer: foyer, "street": mainSt //roomThree: roomThree } let player = new Player( 'street', [] ); const lookUpItems = { paper: paper, "seven days": paper, sign: sign, door: door, } //Transition between rooms function enterState(newState, currentRoom) { // console.log(roomLookupTable[currentRoom].canChangeTo) // console.log(`Entering enterState() the currenState is: ${roomLookupTable[currentRoom].canChangeTo}`); // console.log(`enterState with ${newState} as the argument`); if(roomLookupTable[currentRoom].canChangeTo.includes(newState)){ player.currentState = newState; console.log(roomLookupTable[player.currentState].name); console.log(roomLookupTable[player.currentState].description); getInput(); }else{ throw 'Invalid state transition attempted - from ' + currentRoom + ' to ' + newState; } } function start() { console.log("Please enter your commands as two words. For example 'open door' or 'read sign'."); player.currentState = 'mainSt'; enterState('mainSt', 'mainSt'); } async function getInput() { let input = await ask("\nWhat would you like to do?\n>_"); let arrInput = input.toLowerCase().split(" "); if(arrInput[1] === 'seven' && arrInput[2] === 'days'){ arrInput.push('seven days'); } if(arrInput.includes('enter', 'code') || arrInput.includes('key', 'in')){ return player.code(arrInput[2]); } checkInput(arrInput[0], arrInput[arrInput.length-1], arrInput); } function checkInput(arg1, arg2, arrInput){ if(arg1 === 'i' || (arg1 === 'take' && arg2 === 'inventory')){ arg1 = 'inventory'; // if(player.playerInventory.length < 1){ // console.log("You have nothing.") // getInput(); // } else { // console.log(`You have: ${player.playerInventory.join(" ")}`) // //console.log(player.playerInventory) // getInput(); // } } player.actions(arg1, arg2); } start();
import React, { useEffect, useState } from 'react' import { Card, Text, Image, Button } from 'react-native-elements' import { StyleSheet } from 'react-native' import Icon from 'react-native-vector-icons/Entypo' import useWaterPlant from '../hooks/useWaterPlants' import SeedImages from '../assets/images/SeedImages' const selectPlantImage = (plant) => { const plantName = plant.seedName.toLowerCase() const plantAge = calculateAge(plant.age) let image = SeedImages(plantName) if (plantAge <= 2){ return image.sproot } if (plantAge <= 4) { return image.young } if (plantAge > 4) { return image.madure } } const calculateAge = (plantDate) => { const oneDay = 24*60*60*1000 const birthDate = new Date(plantDate) return Math.round(Math.abs((Date.now() - birthDate) / oneDay)) } const PlantCard = ({ initialPlant, seed }) => { const [waterPlant, plant] = useWaterPlant(initialPlant) useEffect(() => { }, [plant.status]) const age = calculateAge(plant.age) const needsWater = plant.status let waterButton if (needsWater === 'Thirsty') { waterButton = <Button icon={ <Icon name={'water'} color={'#5458CC'} size={13}/> } onPress={() => { waterPlant(plant._id) }} type="outline" buttonStyle={{ borderWidth: 1, borderColor: '#5458CC' }} /> } const image = selectPlantImage(plant) return( <Card containerStyle={ styles.cardStyle }> <Text style={{textAlign: 'center', fontSize: 18}}>{seed}</Text> <Image source={ image } style={{ width: 70, height: 70, alignSelf: 'center' }} /> <Text style={{textAlign: 'center', fontSize: 14}}>{plant.status}</Text> <Text style={{textAlign: 'center'}}>Age: {age} days</Text> {waterButton} </Card> ) } const styles = StyleSheet.create({ cardStyle: { borderRadius: 5, margin: 5, paddingRight: 10, paddingLeft: 10, paddingTop: 5, paddingBottom: 5, } }) export default PlantCard
import K from 'keras-js'; export class KerasJSModel { constructor(path, gpu = true) { this.model = new K.Model({ filepath: path, transferLayerOutputs: false, pauseAfterLayerCalls: false, gpu: gpu, filesystem: true, visualizations: [] }); } async init() { try { await this.model.ready(); console.warn('Model loaded'); } catch(e) { console.error(e); } } predict(data, batchSize = 1) { if(!Array.isArray(data)) throw 'Data must be passed as array'; return this.model.predict({ 'input': new Float32Array(data) }); } }
var { Enumerable } = require("../Sequence/Enumerable"); const { getType } = require("../Utils/TypeUtils"); const { EqualityComparers } = require("../Utils/EqualityComparers"); const { IEnumerable } = require("../Sequence/IEnumerable"); class HashSet extends IEnumerable { /** * () * source * source, comparer * comparer */ constructor(arg1, comparer) { super(function* () { for (let t of this._data) for (let k of t[1]) yield k; }); this._count = 0; this._data = new Map(); comparer = comparer || EqualityComparers.PrimitiveComparer; if (arg1 === undefined) { // 1 this._comparer = comparer; } else if (getType(arg1) === "Object" || getType(arg1) === "null") { // 4 this._comparer = arg1 || EqualityComparers.PrimitiveComparer; } else { // 2, 3 this._comparer = comparer; for (let t of arg1) this.Add(t); } } get Comparer() { return this._comparer; } get CountNative() { return this._count; } Add(item) { if (this._data.has(this._comparer.GetHashCode(item))) { for (let t of this._data.get(this._comparer.GetHashCode(item))) { if (this._comparer.Equals(t, item)) return false; } this._data.get(this._comparer.GetHashCode(item)).push(item); } else { this._data.set(this._comparer.GetHashCode(item), [item]); } this._count++; return true; } Clear() { this._data.clear(); this._count = 0; } ContainsNative(item) { if (this._data.has(this._comparer.GetHashCode(item))) { for (let t of this._data.get(this._comparer.GetHashCode(item))) { if (this._comparer.Equals(t, item)) return true; } } return false; } CopyTo(array, arrayIndex = 0, count = this._count) { let i = 0; for (let t of this) { if (i >= count) break; array[arrayIndex + i++] = t; } } CreateSetComparer() { return { Equals: (x, y) => x.SetEquals(y), GetHashCode: (obj) => obj.CountNative, }; } ExceptWith(other) { // the same equality comparer as the current for (let t of other) this.Remove(t); } IntersectWith(other) { // the same equality comparer as the current let oth = Enumerable.From(other).ToHashSet(this._comparer); this.RemoveWhere((t) => !oth.ContainsNative(t)); } IsProperSubsetOf(other) { let numThisContains = 0, numThisNotContains = 0; for (let t of Enumerable.From(other).Distinct(this._comparer)) { this.ContainsNative(t) ? numThisContains++ : numThisNotContains++; if (numThisContains === this.CountNative && numThisNotContains > 0) return true; } return numThisContains === this.CountNative && numThisNotContains > 0; } IsProperSupersetOf(other) { if (this.CountNative === 0) return false; let numOther = 0; for (let t of Enumerable.From(other).Distinct(this._comparer)) { if (!this.ContainsNative(t) || this.CountNative <= ++numOther) return false; } return true; } IsSubsetOf(other) { let numThisContains = 0; for (let t of Enumerable.From(other).Distinct(this._comparer)) { if (this.ContainsNative(t)) numThisContains++; if (numThisContains === this.CountNative) return true; } return numThisContains === this.CountNative; } IsSupersetOf(other) { let numOther = 0; for (let t of Enumerable.From(other).Distinct(this._comparer)) { if (!this.ContainsNative(t) || this.CountNative < ++numOther) return false; } return true; } Overlaps(other) { return Enumerable.From(other).Any((t) => this.ContainsNative(t)); } Remove(item) { if (this._data.has(this._comparer.GetHashCode(item))) { let i = 0; for (let t of this._data.get(this._comparer.GetHashCode(item))) { if (this._comparer.Equals(t, item)) { this._data.get(this._comparer.GetHashCode(item)).splice(i, 1); if (this._data.get(this._comparer.GetHashCode(item)).length === 0) { this._data.delete(this._comparer.GetHashCode(item)); } this._count--; return true; } i++; } } return false; } RemoveWhere(match) { let itemsToRemove = this.Where(match).ToArray(); this.ExceptWith(itemsToRemove); return itemsToRemove.length; } SetEquals(other) { let num = 0; for (let t of Enumerable.From(other).Distinct(this._comparer)) { if (!this.ContainsNative(t)) return false; num++; } return num === this.CountNative; } SymmetricExceptWith(other) { Enumerable.From(other) .Distinct(this._comparer) .ForEach((t) => (this.ContainsNative(t) ? this.Remove(t) : this.Add(t))); } TryGetValue(equalValue) { if (this._data.has(this._comparer.GetHashCode(equalValue))) { for (let t of this._data.get(this._comparer.GetHashCode(equalValue))) { if (this._comparer.Equals(t, equalValue)) return { actualValue: t, contains: true }; } } return { actualValue: undefined, contains: false }; } UnionWith(other) { for (let t of other) this.Add(t); } } module.exports = { HashSet };
const path = require('path'); const express = require('express'); const socketIO = require('socket.io'); const http = require('http'); // for server port const port = process.env.PORT || 3000; const publicPath = path.join(__dirname, '../public'); // for public resource : path join outputs absolute path const app = express(); // for socketIO to work - http module is reqd. and to create a different server instead of express var server = http.createServer(app); var io = socketIO(server); // track users connection io.on('connection', (socket) => { console.log('New user connected'); socket.on('disconnect', () => { console.log('user disconnected'); }); }); app.use(express.static(publicPath)); // for public - frontend app.get('/', (req,res) => { res.send(`<h1>Hello</h1>`); }); // instead of app.listen change to server.listen in order for socketIO to work server.listen(port, () => { console.log('server started at port ', port); }); // after enabling socketIO , a js library - socket.io.js and wen socket connection handling features are enabled // js library - localhost:3000/socket.io/socket.io.js - load this js file in public files // // SOCKETIO features // Both client and server can emit and listen to events - eg. email app client & server
import React from 'react'; import ReactDOM from 'react-dom'; import Message from './Message'; import MessageStore from '../stores/MessageStore'; export default React.createClass({ getInitialState(){ return { messages: [] }; }, _onChange() { this.setState({messages: MessageStore.getAllMessages()}); }, componentDidMount() { MessageStore.addChangeListener(this._onChange); }, componentWillUnmount() { MessageStore.removeChangeListener(this._onChange); }, /** * scroll to bottom */ componentDidUpdate() { var node = ReactDOM.findDOMNode(this); node.scrollTop = node.scrollHeight; }, render() { var messages = this.state.messages; return ( <div className="message-list"> {messages.map(msg => <Message message={msg} key={msg.id}/> )} </div> ); } });
export default { SET_SESSION(state, { user, token }) { state.token = token; state.user = user; }, SET_SEARCH_RESULTS(state, results) { state.results = results; }, UPDATE_USER(state, user) { state.user = user; }, UPDATE_LIST(state, lists) { state.user.lists = lists; }, UPDATE_LIST_NAME(state, { listId, newName }) { state.user.lists[listId].name = newName; }, REMOVE_LIST(state, index) { state.user.lists.splice(index, 1); }, ADD_GAME(state, { gameId, listId }) { state.user.lists[listId].games.push(gameId); }, ADD_LIST(state, listName) { const newList = { games: [], name: listName, }; state.user.lists.push(newList); }, REMOVE_GAME(state, { gameId, listId }) { state.user.lists[listId].games.splice(state.user.lists[listId].games.indexOf(gameId), 1); }, CACHE_GAME_DATA(state, data) { data.forEach((game) => { if (!state.games[game.id]) { state.games = { ...state.games, [game.id]: game }; } }); }, CLEAR_SESSION(state) { state.token = null; state.user = null; }, };
import { StyleSheet } from 'react-native'; export default StyleSheet.create({ 'tags span': { 'textTransform': 'uppercase' }, 'titleArticle': { 'textTransform': 'uppercase' }, 'download-link a': { 'display': 'inline-block' }, 'download-link svg': { 'display': 'inline-block' }, 'otherArticle a': { 'display': 'inline-block' }, 'tags a': { 'display': 'inline-block' }, 'articleWrap': { 'overflow': 'hidden', 'margin': [{ 'unit': 'px', 'value': 30 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 60 }, { 'unit': 'string', 'value': 'auto' }], 'padding': [{ 'unit': 'px', 'value': 30 }, { 'unit': 'px', 'value': 30 }, { 'unit': 'px', 'value': 30 }, { 'unit': 'px', 'value': 30 }], 'width': [{ 'unit': 'px', 'value': 750 }], 'height': [{ 'unit': 'string', 'value': 'auto' }], 'background': '#fff', 'boxShadow': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 30 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'rgba(0,0,0,.2)' }] }, 'body': { 'backgroundColor': '#f6f9fc' }, 'titleArticle': { 'marginTop': [{ 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 20 }, { 'unit': 'px', 'value': 0 }], 'width': [{ 'unit': '%H', 'value': 1 }], 'borderBottom': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': 'rgba(33,33,33,.08)' }], 'color': '#666', 'textAlign': 'left', 'letterSpacing': [{ 'unit': 'px', 'value': 1 }], 'fontWeight': '700', 'fontSize': [{ 'unit': 'px', 'value': 30 }], 'lineHeight': [{ 'unit': 'px', 'value': 1.5 }] }, 'leftMain': { 'float': 'left', 'width': [{ 'unit': '%H', 'value': 1 }], 'height': [{ 'unit': 'string', 'value': 'auto' }] }, '#J_dotLine': { 'position': 'absolute', 'left': [{ 'unit': '%H', 'value': 0.5 }], 'marginLeft': [{ 'unit': 'px', 'value': -550 }], 'width': [{ 'unit': 'px', 'value': 825 }], 'height': [{ 'unit': 'px', 'value': 200 }], 'color': '#fff' }, 'articleHeader': { 'position': 'relative', 'top': [{ 'unit': 'px', 'value': -10 }], 'left': [{ 'unit': 'px', 'value': 0 }], 'zIndex': '1', 'height': [{ 'unit': 'px', 'value': 150 }], 'background': '#9ac26b' }, 'articleHeader h1': { 'color': '#fff', 'textAlign': 'center', 'letterSpacing': [{ 'unit': 'px', 'value': 1 }], 'fontSize': [{ 'unit': 'px', 'value': 50 }], 'lineHeight': [{ 'unit': 'px', 'value': 150 }] }, 'h2': { 'marginBottom': [{ 'unit': 'px', 'value': 0 }] }, 'articleDetail': { 'height': [{ 'unit': 'px', 'value': 50 }], 'color': '#999', 'lineHeight': [{ 'unit': 'px', 'value': 50 }] }, 'articleDetail i': { 'marginRight': [{ 'unit': 'px', 'value': 20 }], 'color': '#aaa', 'fontStyle': 'normal' }, 'tags': { 'padding': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 0 }], 'borderTop': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#ccc' }], 'borderBottom': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#ccc' }] }, 'tags span': { 'marginRight': [{ 'unit': 'px', 'value': 14 }], 'color': '#f04e37', 'fontWeight': '400', 'fontSize': [{ 'unit': 'px', 'value': 18 }] }, 'otherArticle a span': { 'marginRight': [{ 'unit': 'px', 'value': 10 }] }, 'tags a': { 'marginRight': [{ 'unit': 'px', 'value': 10 }] }, 'tags a': { 'boxSizing': 'content-box', 'padding': [{ 'unit': 'px', 'value': 6 }, { 'unit': 'px', 'value': 20 }, { 'unit': 'px', 'value': 6 }, { 'unit': 'px', 'value': 20 }], 'borderRadius': '3px', 'background': '#f04e37', 'color': '#fff', 'textOverflow': 'clip', 'font': [{ 'unit': 'px', 'value': 400 }, { 'unit': 'string', 'value': 'medium/normal' }, { 'unit': 'string', 'value': 'Arial,Helvetica,sans-serif' }], 'cursor': 'pointer' }, 'articleSource i': { 'fontStyle': 'normal' }, 'download-link i': { 'fontStyle': 'normal' }, 'otherArticle i': { 'fontStyle': 'normal' }, 'articleSource': { 'padding': [{ 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }], 'color': '#666', 'letterSpacing': [{ 'unit': 'px', 'value': 1 }], 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.5 }] }, 'otherArticle a': { 'float': 'left', 'overflow': 'hidden', 'width': [{ 'unit': '%H', 'value': 0.5 }], 'height': [{ 'unit': 'px', 'value': 30 }], 'color': '#888', 'textOverflow': 'ellipsis', 'whiteSpace': 'nowrap', 'lineHeight': [{ 'unit': 'px', 'value': 30 }], 'cursor': 'pointer' }, 'myattachment': { 'color': '#999', 'cursor': 'pointer' }, 'otherArticle': { 'height': [{ 'unit': 'px', 'value': 42 }] }, 'download-link': { 'textAlign': 'center', 'position': 'relative', 'overflow': 'hidden', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 9 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }], 'padding': [{ 'unit': 'px', 'value': 14 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 14 }, { 'unit': 'px', 'value': 0 }], 'height': [{ 'unit': 'px', 'value': 44 }], 'borderRadius': '4px', 'backgroundColor': '#f8f9f9', 'fontWeight': '300', 'fontSize': [{ 'unit': 'px', 'value': 1 }], 'fontFamily': 'Open Sans,sans-serif', 'lineHeight': [{ 'unit': 'px', 'value': 24 }], 'borderLeftColor': '#3f4652', 'textRendering': 'optimizelegibility' }, 'download-link img': { 'width': [{ 'unit': 'px', 'value': 30 }], 'height': [{ 'unit': 'px', 'value': 30 }] }, 'download-link a': { 'verticalAlign': 'middle', 'lineHeight': [{ 'unit': 'px', 'value': 44 }] }, 'download-link img': { 'verticalAlign': 'middle', 'lineHeight': [{ 'unit': 'px', 'value': 44 }] }, 'download-link a': { 'marginRight': [{ 'unit': 'px', 'value': 1 }], 'height': [{ 'unit': 'px', 'value': 44 }] }, 'download-link svg': { 'width': [{ 'unit': 'px', 'value': 20 }], 'height': [{ 'unit': 'px', 'value': 20 }], 'verticalAlign': 'text-bottom', 'lineHeight': [{ 'unit': 'px', 'value': 44 }], 'fill': '#aaa' }, 'download-link i': { 'marginRight': [{ 'unit': 'px', 'value': 2 }] }, 'en': { 'fontFamily': 'arial,helvetica,sans-serif!important' }, 'en': { 'wordBreak': 'keep-all' }, 'en p': { 'wordBreak': 'keep-all' }, 'articleContent': { 'overflow': 'hidden', 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }], 'color': '#888', 'textAlign': 'justify', 'textIndent': '0', 'letterSpacing': [{ 'unit': 'px', 'value': 1 }], 'fontWeight': '400', 'lineHeight': [{ 'unit': 'em', 'value': 1.6 }] }, 'articleContent p': { 'color': '#888!important', 'lineHeight': [{ 'unit': 'px', 'value': 26 }], 'fontFamily': '"Microsoft YaHei"!important', 'fontSize': [{ 'unit': 'px', 'value': 16 }] }, 'articleContent span': { 'color': '#888!important', 'lineHeight': [{ 'unit': 'px', 'value': 26 }], 'fontFamily': '"Microsoft YaHei"!important', 'fontSize': [{ 'unit': 'px', 'value': 16 }] }, 'en p': { 'color': '#888!important', 'lineHeight': [{ 'unit': 'px', 'value': 26 }], 'fontFamily': 'arial,helvetica,sans-serif!important', 'fontSize': [{ 'unit': 'px', 'value': 18 }] }, 'en span': { 'color': '#888!important', 'lineHeight': [{ 'unit': 'px', 'value': 26 }], 'fontFamily': 'arial,helvetica,sans-serif!important', 'fontSize': [{ 'unit': 'px', 'value': 18 }] }, 'articleContent li': { 'listStyle': 'disc' }, 'articleContent ol': { 'listStyle': 'disc' }, 'articleContent ul': { 'listStyle': 'disc' }, 'articleContent img': { 'marginTop': [{ 'unit': 'px', 'value': 10 }] }, 'articleContent a': { 'textDecoration': 'underline' }, 'articleContent p': { 'marginBottom': [{ 'unit': 'px', 'value': 26 }] }, 'articleContent b': { 'fontWeight': '700!important' }, 'articleContent em': { 'fontWeight': '700!important' }, 'articleContent strong': { 'fontWeight': '700!important' }, 'articleContent table': { 'display': 'block', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }] } });
/** * Created by xiaochuanzhi on 2017/6/13. */ 'use strict'; module.exports.Market = require('./lib/Market'); module.exports.Trade = require('./lib/Trade');
import React, { useState, useContext } from 'react'; import Header from '../../components/header'; import Footer from '../../components/footer'; import ErrorBox from '../../components/errorBox'; import AuthContext from '../../AuthContext'; import { useHistory } from 'react-router-dom'; import styles from './index.module.css'; const LoginPage = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState({ show: false, errorInfo: ''}); const { login } = useContext(AuthContext); const history = useHistory(); const toggleError = (errorInfo) => { setError({ show: true, errorInfo }); setTimeout(() => { setError({ show: false, errorInfo: '' }) }, 5000); } const signInHandler = async (e) => { e.preventDefault(); const promise = await fetch('http://localhost:8000/api/user/login', { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); if(!promise.ok) return toggleError('Invalid username or password!'); const user = await promise.json(); const token = promise.headers.get('Authorization'); login(user, token); history.push('/'); } return ( <> <Header /> <ErrorBox show={error.show} errorInfo={error.errorInfo}/> <form id="login-form" className={`text-center p-5 ${styles['form-layout']}`} action="#" method="POST"> <p className="h4 mb-4">Sign in</p> <input type="text" id="defaultRegisterFormUsername" name="username" className="form-control mb-4" placeholder="Username" onChange={(e) => { setUsername(e.target.value); }} /> <input type="password" id="defaultRegisterFormPassword" name="password" className="form-control" placeholder="Password" onChange={(e) => { setPassword(e.target.value); }}/> <hr /> <button className="btn btn-danger w-25 m-auto my-4 btn-block" type="submit" onClick={signInHandler}>Sign in</button> </form> <Footer /> </> ); } export default LoginPage;
const fs = require('fs'); const st_dev_community_1 = -1001233882429; const st_dev_report_chat = -1001161646688; const development = { BOT_TOKEN: "494907220:AAHMhxNkcnatkyhzqwuGtbUS-U6AvDg0MO4" ,ENV: "development" ,POLICE_COMMUNITIES: [ st_dev_community_1 ] ,ANNOUNCEMENTS_CHAT_ID : -1001320680086 ,REPORT_CHAT_ID : st_dev_report_chat ,CHAT_TYPE_SUPERGROUP : 'supergroup' ,CHAT_TYPE_GROUP : 'group' ,CHAT_TYPE_PRIVATE : 'private' //Scam Alert Config ,MESSAGE_ON_KICK: fs.readFileSync('../telegram/messages/KickedMessage.txt', 'utf8') ,HOLD_OFF_SCAM_ALERT_SEC: 10 //Repeate Message Config ,REPEATE_IN_CHATS : [ st_dev_community_1 ] ,REPEATE_MESSAGE_SEC: 1 * 10 ,MESSAGE_TO_REPEATE: fs.readFileSync('../telegram/messages/ScamAlert.txt', 'utf8') //Scan user chats ,SCAN_USERS_CHATS : [ st_dev_community_1 ] //Scan link in chats ,SCAN_LINKS_CHATS : [ st_dev_community_1 ] //REPEATED CHAT PIN MSG ID ,REPEATE_PINNED_MSG_TEXT : "Thanks for a successful token sale! The sale has ended. The Simple Token team has provided answers to many of the most common questions. [link]" ,REPEATED_CHAT_PIN_MSG_ID : st_dev_community_1 ,PUBLIC_COMMUNITY_USERNAME : "stdevcommunity" ,REPEATED_CHAT_MSG_LIMIT : 2 }; /* BEGIN : DO NOT TOUCH THESE */ const CHAT_SIMPLETOKEN_COMMUNITY = -1001138398611; const CHAT_ST_BOT_ACTIVITY_REPORTS = -1001376936450; /* END OF: DO NOT TOUCH THESE */ const production = { BOT_TOKEN: "448852266:AAHQ1IGFBMfyx_XCtLFzE6b1XvVY6V5S3Ls" ,ENV: "production" ,POLICE_COMMUNITIES: [ CHAT_SIMPLETOKEN_COMMUNITY ] ,ANNOUNCEMENTS_CHAT_ID : -1001320680086 ,REPORT_CHAT_ID : CHAT_ST_BOT_ACTIVITY_REPORTS ,CHAT_TYPE_SUPERGROUP : 'supergroup' ,CHAT_TYPE_GROUP : 'group' ,CHAT_TYPE_PRIVATE : 'private' //Scam Alert Config ,MESSAGE_ON_KICK: fs.readFileSync('../telegram/messages/KickedMessage.txt', 'utf8') ,HOLD_OFF_SCAM_ALERT_SEC: 300 //Repeate Message Config ,REPEATE_IN_CHATS : [ CHAT_SIMPLETOKEN_COMMUNITY ] ,REPEATE_MESSAGE_SEC: 3*60*60 ,MESSAGE_TO_REPEATE: fs.readFileSync('../telegram/messages/ScamAlert.txt', 'utf8') //Scan user chats ,SCAN_USERS_CHATS : [CHAT_SIMPLETOKEN_COMMUNITY] //Scan link in chats ,SCAN_LINKS_CHATS : [CHAT_SIMPLETOKEN_COMMUNITY] //Repeate Pinned Message. ,REPEATED_CHAT_PIN_MSG_ID : null ,PUBLIC_COMMUNITY_USERNAME : "stofficial" ,REPEATED_CHAT_MSG_LIMIT : 10 }; const availableConfigs = { "production": production, "development": development }; var commandArgs = process.argv.slice(2); var exportedConfig = development; if ( commandArgs && commandArgs.length > 0 ) { var configFlavour = commandArgs[0].toLowerCase(); exportedConfig = availableConfigs[ configFlavour ] || exportedConfig; } module.exports = exportedConfig; /* Other Thinngs that might be usefull. */ // rachins bot const OfficiaLSimpLeToken_bot = "330790032:AAH2l8hR3bw2t3yM_mRalgQKTQty1qH5h1Q"; // @benjaminbollens_bot t.me/benjaminbollens_bot const BEN_BADBOT_ID = 383374001; const BOT_BENJAMINBOLLEN = "438311760:AAEZnwm-sPvkcCBMRlgswO38VNuh_bcODmI";
import React from 'react'; import GithubBtn from '../../components/Button/Github'; import { Icon } from 'antd'; import { Link } from 'react-router-dom'; import './GithubRepos.less'; //project/PlenipotentSS/SSStackedPageView/github/17587590/all const GithubRepos = ({ repos }) => { return ( <div className="GithubRepos"> <div className="GithubRepos__container"> <h4 className="GithubRepos__title"><Icon type="github"/> Your Projects</h4> <div className="GithubRepos__divider"></div> {repos.length ? <div> <ul> {repos.map(project => ( <li key={project.id}> <Link to={`/project/${project.full_name}/github/${project.id}/all`}> <Icon type="github"/> {project.full_name} </Link> <p className="announcement"> <small> <Link to={`/write-announcement/${project.id}`}> <Icon type="notification"/> Add announcement </Link> </small> </p> </li> ))} </ul> </div> : <div>No repositories found</div> } <GithubBtn /> </div> </div> ) } export default GithubRepos;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './styles.less'; import bemHelper from '../../libs/utils/bemHelper'; import { API } from '../../constants'; const getClassName = bemHelper('About-Container'); export class Demo extends Component { render() { const { query } = this.props; return ( <div className={getClassName('@')}> <button onClick={() => query.run(true)}>Fetch Data</button> <button onClick={() => query.ttl(0).run()}>Force Fetch Data</button> </div> ); } static propTypes = { query: PropTypes.object.isRequired, } } export default class About extends Component { // eslint-disable-line render() { return ( <div> <h1>About</h1> <Demo query={this.query} /> </div> ); } get query() { const { CRUD } = this.props; return CRUD(API.MARKET) .findAll() .options({}); } static propTypes = { CRUD: PropTypes.func, }; static defaultProps = { CRUD: () => {}, }; }
import { Login } from "./login.js"; import { signUp } from './services/user_services.js'; import { STORE } from './store.js'; import { Expenses } from "./expenses.js"; export function SignUp(parentElement) { return { parent: document.querySelector(parentElement), render() { const html = ` <section> <h2>Sign Up</h2> <form class="js-form-signup"> <div> <label for="email">Email</label><br /> <input type="email" id="email" name="email"> </div> <div> <label for="password">Password</label><br /> <input type="password" id="password" name="password"> </div> <div> <label for="first_name">First name</label><br /> <input type="text" id="first_name" name="first_name"> </div> <div> <label for="last_name">Last name</label><br /> <input type="text" id="last_name" name="last_name"> </div> <div> <label for="phone">Phone</label><br /> <input type="text" id="phone" name="phone"> </div> <div> <button type="submit">Submit</button> </div> <a class="js-redirect-login" href="#">Login</a> </form> </section> `; this.parent.innerHTML = html; this.addFormSubmitListener(); this.renderLoginView(); }, addFormSubmitListener() { const form = this.parent.querySelector(".js-form-signup"); console.log(form) form.addEventListener("submit", async (e) => { e.preventDefault(); try { const { email, password, first_name, last_name, phone } = form; const data = await signUp( email.value, password.value, first_name.value, last_name.value, phone.value ); sessionStorage.setItem('token', data.token) STORE.user = data; const expenses = Expenses(parentElement); expenses.render(); } catch (e) { console.log(e); } }); }, renderLoginView() { const trigger = this.parent.querySelector(".js-redirect-login"); trigger.addEventListener("click", (e) => { e.preventDefault(); const login = Login(parentElement); login.render(); }); }, }; }
export function addMessage(message) { return { type: 'ADD_MESSAGE', message: message }; } export function addMessages(messages) { return { type: 'ADD_MESSAGES', messages: messages }; } export function resetMessages() { return { type: 'RESET_MESSAGES' }; } export function addPrivateMessages(messages) { return { type: 'ADD_PRIVATE_MESSAGES', messages: messages }; } export function receivePrivateChats(users) { return { type: 'ADD_PRIVATE_CHATS', users: users }; }
import React from "react"; import {Link} from "react-scroll"; const ListGroup = (props) => { const { items, textProperty, valueProperty, selectedItem, onItemSelect, } = props; return ( <div className="list-group item-category"> {Array.isArray(items) && items.map((item) => ( <div id="category" className="bucket" key={item[valueProperty]} onClick={() => onItemSelect(item)} className={item === selectedItem ? "bucket active" : "bucket"} style={{ cursor: "pointer", backgroundImage: `url(${item.imageURL}`, backgroundSize: "cover" }} > <Link to="item" smooth={true} duration={1000}> {item[textProperty]}</Link> </div> ))} </div> ); }; ListGroup.defaultProps = { valueProperty: "_id", textProperty: "name", }; export default ListGroup;