text
stringlengths
7
3.69M
/** * Editor Routes */ import React from 'react'; import { Redirect, Route, Switch } from 'react-router-dom'; import { Helmet } from "react-helmet"; // async components import { AsyncQuillEditorComponent, AsyncWysiwygEditorComponent } from 'Components/AsyncComponent/AsyncComponent'; const Editor = ({ match }) => ( <div className="content-wrapper"> <Helmet> <title>Excalibur | Editors</title> <meta name="description" content="Excalibur Editors" /> </Helmet> <Switch> <Redirect exact from={`${match.url}/`} to={`${match.url}/wysiwyg-editor`} /> <Route path={`${match.url}/wysiwyg-editor`} component={AsyncWysiwygEditorComponent} /> <Route path={`${match.url}/quill-editor`} component={AsyncQuillEditorComponent} /> </Switch> </div> ); export default Editor;
import React from "react"; import { SceneDetailsWrapper } from "./styles"; import { FlexContainer, Column, RightAlign, Table, TableRow, TableCell, } from "../../../../components/layout"; import { Input, Button } from "../../../../components/reusable"; const SceneDetails = (props) => { const { editMode, scene, save } = props; const [sceneTextLink, setSceneTextLink] = React.useState(""); const [alphaPoint, setAlphaPoint] = React.useState(""); const [subplots, setSubplots] = React.useState([]); const [whatHappens, setWhatHappens] = React.useState(""); const [consequences, setConsequences] = React.useState(""); const [whyItMatters, setWhyItMatters] = React.useState(""); const [theRealization, setTheRealization] = React.useState(""); const [andSo, setAndSo] = React.useState(""); const [tags, setTags] = React.useState([]); React.useEffect(() => { if (scene) { setAlphaPoint(scene.alphaPoint); setSubplots(scene.subplots); setWhatHappens(scene.whatHappens); setConsequences(scene.consequences); setWhyItMatters(scene.whyItMatters); setTheRealization(scene.theRealization); setAndSo(scene.andSo); setTags(scene.tags.join(",")); setSceneTextLink(scene.sceneTextLink); } }, [scene]); const saveDetails = () => { const splitTags = tags.split(","); save({ alphaPoint, subplots, whatHappens, consequences, whyItMatters, theRealization, tags: splitTags, sceneTextLink, }); }; return ( <SceneDetailsWrapper> <FlexContainer> <Column> <Input label="Alpha Point" onChange={setAlphaPoint} value={alphaPoint} placeholder="The main point of the scene, e.g. why this scene needs to be in the story" uneditable={!editMode} /> </Column> </FlexContainer> <FlexContainer> <Column> <Input label="Scene Text Link" onChange={setSceneTextLink} value={sceneTextLink} placeholder="A link to the actual text of the scene" uneditable={!editMode} /> </Column> </FlexContainer> <FlexContainer> <Column> <Input label="Tags" placeholder="A comma-separated list of tags you can use to search for your scene later" onChange={setTags} value={tags} uneditable={!editMode} /> </Column> </FlexContainer> <br /> <FlexContainer> <Table> <TableRow> <TableCell size="1"> <a href="https://ashlyhilst.com/blog/2018/10/10/how-to-use-the-story-genius-scene-card"> How to use this </a> </TableCell> <TableCell size="2" heading> Cause </TableCell> <TableCell size="2" heading> Effect </TableCell> </TableRow> <TableRow> <TableCell size="1" heading> The plot </TableCell> <TableCell size="2"> <Input label="What happens" onChange={setWhatHappens} value={whatHappens} placeholder="What happens in the scene?" textarea uneditable={!editMode} /> </TableCell> <TableCell size="2"> <Input label="The consequences" onChange={setConsequences} value={consequences} placeholder="What are the external consequences of what happens?" textarea uneditable={!editMode} /> </TableCell> </TableRow> <TableRow> <TableCell size="1" heading> Third Rail </TableCell> <TableCell size="2"> <Input label="Why it matters" onChange={setWhyItMatters} value={whyItMatters} placeholder="Why does what happened matter to the protagonist's internal struggle?" textarea uneditable={!editMode} /> </TableCell> <TableCell size="2"> <Input label="The realization" onChange={setTheRealization} value={theRealization} placeholder="What does the protagonist realize as a result of all this?" textarea uneditable={!editMode} /> </TableCell> </TableRow> <TableRow> <TableCell size="1" /> <TableCell size="2" /> <TableCell size="2"> <Input label="And so?" onChange={setAndSo} value={andSo} placeholder="What is the protagonist going to do next because of this?" textarea uneditable={!editMode} /> </TableCell> </TableRow> </Table> </FlexContainer> {editMode && ( <> <br /> <FlexContainer> <RightAlign> <Button onClick={saveDetails}>Submit</Button> </RightAlign> </FlexContainer> </> )} </SceneDetailsWrapper> ); }; export default SceneDetails;
import React from 'react'; import PatternSwatch from './PatternSwatch.jsx'; import PatternSection from './PatternSection.jsx'; import PatternGrid from './PatternGrid.jsx'; import PatternBuilderControls from './PatternBuilderControls.jsx'; import PatternAppNav from './PatternAppNav.jsx'; import getPatternDecodeFromUrl from './../../utility/getPatternDecodeFromUrl'; import getPatternEncodedUrl from './../../utility/getPatternEncodedUrl'; import getContent from './../../utility/getContent'; import setUrlHash from './../../utility/util'; let defaultState = { threading: [ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ], tie_up: [ [0,0], [0,0], [0,0], [0,0] ], treadling: [ [0,0], [0,0], [0,0], [0,0], [0,0], [0,0] ], patternNumber: false } class PatternBuilder extends React.Component { constructor(props) { super(props); const data = getPatternDecodeFromUrl(window.location.hash.replace(/#/g, '')); if (data) { this.state = data; defaultState = JSON.parse(JSON.stringify(data)); } else { this.state = JSON.parse(JSON.stringify(defaultState)); } this.content = getContent('en').patterns; } componentDidUpdate() { setUrlHash(getPatternEncodedUrl(this.state)); } toggleVal = ({type = 'threading', col = 0, row = 0, val = 0}) => { let grid = this.state[type].slice(); let update = {}; if (type === 'treadling') { if (grid[row].indexOf(1) > -1 || grid[row].indexOf(2) > -1) { grid[row].forEach(function(val, i) { grid[row][i] = 0; }) } } grid[row][col] = val; update[type] = grid; this.setState(update); } modifyGrid = ({isAddCol = false, isAddRow = false, isRemoveCol = false, isRemoveRow = false, isTreadling = false, isThreading = false}) => { let update = {}; let threading = this.state.threading.slice(); let treadling = this.state.treadling.slice(); let tie_up = this.state.tie_up.slice(); const emptyRowThreading = threading[0].map(function(){ return 0; }); const emptyRowTreadling = treadling[0].map(function(){ return 0; }); const emptyRowTieUp = tie_up[0].map(function() { return 0; }); if (isThreading) { if (isAddRow && treadling.length < 25) { threading.push(emptyRowThreading); tie_up.push(emptyRowTieUp); } else if (isAddCol && threading[0].length < 25) { threading.forEach(function(row) { row.unshift(0); }); } else if (isRemoveRow) { if (threading.length > 1) { threading.splice(-1); tie_up.splice(-1); } } else if (isRemoveCol) { if (threading[0].length > 1) { threading.forEach(function(row) { row.shift(); }); } } } else if (isTreadling) { if (isAddRow && treadling.length < 25) { treadling.push(emptyRowTreadling); } else if (isAddCol && treadling[0].length < 25) { treadling.forEach(function(row) { row.unshift(0); }); tie_up.forEach(function(row) { row.unshift(0); }); } else if (isRemoveRow) { if (treadling.length > 1) { treadling.splice(-1); } } else if (isRemoveCol) { if (treadling[0].length > 1) { treadling.forEach(function(row) { row.shift(); }); tie_up.forEach(function(row) { row.shift(); }); } } } update.threading = threading; update.tie_up = tie_up; update.treadling = treadling; this.setState(update); } reset = () => { this.setState( JSON.parse(JSON.stringify(defaultState)) ); } render() { return ( <div className='pattern-builder pattern-app container'> <PatternAppNav activeLink={'Builder'}/> <div className='pattern-item'> <PatternBuilderControls onReset={this.reset} patternNumber={this.state.patternNumber} /> {['threading', 'tie_up', 'treadling'].map(function (type) { return ( <PatternSection label={this.content[type]} key={type}> <PatternGrid data={this.state[type]} type={type} patternNumber={''} subActive={0} onToggleVal={this.toggleVal} onUpdateSubActive={function(){return;}} onModifyGrid={this.modifyGrid} /> </PatternSection> ) }.bind(this))} <PatternSwatch data={this.state} subActive={0} /> </div> </div> ) } } export default PatternBuilder;
import { createStore, applyMiddleware, compose } from 'redux' import createSagaMiddleware from 'redux-saga' import { initialState } from './model.js' import sagas from './sagas.js' import toggleMenu from './actions/toggleMenu.js' import preview from './actions/preview.js' import edit from './actions/edit.js' import close from './actions/close.js' import back from './actions/back.js' import add from './actions/add.js' import submit from './actions/submit.js' import commit from './actions/commit.js' import toggleTarget from './actions/toggleTarget.js' import publish from './actions/publish.js' import remove from './actions/remove.js' import resolveError from './actions/resolveError.js' import writeScrollPosition from './actions/writeScrollPosition.js' import resetScrollPosition from './actions/resetScrollPosition.js' import clear from './actions/clear.js' const sagaMiddleware = createSagaMiddleware() const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose export default createStore( (state = initialState, action) => { switch (action.type) { case 'toggle_menu': return toggleMenu(state, action) case 'preview': return preview(state, action) case 'edit': return edit(state, action) case 'close': return close(state, action) case 'back': return back(state, action) case 'add': return add(state, action) case 'submit': return submit(state, action) case 'commit': return commit(state, action) case 'toggle_target': return toggleTarget(state, action) case 'publish': return publish(state, action) case 'remove': return remove(state, action) case 'resolve_error': return resolveError(state, action) case 'clear': return clear(state, action) case 'write_scroll_position': return writeScrollPosition(state, action) case 'reset_scroll_position': return resetScrollPosition(state, action) default: return state } }, composeEnhancers(applyMiddleware(sagaMiddleware)) ) sagaMiddleware.run(sagas)
'use strict'; juke.controller('AlbumCtrl', function($scope, $http, $rootScope, $log, AlbumFactory, PlayerFactory) { $scope.album; $scope.currentSong; $scope.playing; $scope.visible = false; var getAlbum = function(albumId){ // AlbumFactory.fetchById(albumId) // .then(function(album) { $scope.album = AlbumFactory.fetchById(albumId); PlayerFactory.setAlbum($scope.album); // }) // .catch($log.error); } // load our initial data $rootScope.$on('changeView', function(e, view){ $scope.visible = view === "album"; }) $rootScope.$on('changeAlbum', function(e,album){ getAlbum(album._id); }) $scope.toggle = function(song){ $scope.currentSong = song; PlayerFactory.toggle(song); $rootScope.$evalAsync(); }; }); // // a "true" modulo that wraps negative to the top of the range // function mod (num, m) { return ((num % m) + m) % m; }; // // jump `interval` spots in album (negative to go back, default +1) // // function next () { skip(1); }; // function prev () { skip(-1); }; // }); juke.controller("AlbumsCtrl", function($scope, $rootScope, $log, AlbumFactory) { $scope.visible = true; AlbumFactory.fetchAll .then(function (albums) { $scope.albums = albums; }) .catch($log.error); // $scope.albums = AlbumFactory.fetchAll; $rootScope.$on('changeView', function(e, view){ $scope.visible = view === "albums"; }) $scope.changeAlbum = function(album){ // $scope.visible = false; $rootScope.$emit("changeView", "album"); $rootScope.$broadcast('changeAlbum', album); } });
import React from 'react'; import s from './Post.module.css'; const Post =(props) => { return( <div className="post-item"> <div className={s.item}> <img className="img-post" src="https://i.ibb.co/Fzxbqzn/nastol-com-ua-138035.jpg" alt="post"/> <div> LIKE{ props.like } </div> <textarea></textarea> <button>Add post</button> </div> </div>); } export default Post;
'use strict'; angular.module("app.locale", [], ["$provide", function($provide) { $provide.value("$locale", { "PRODUCT": { "name": "Tên", "price": "Giá" } }); } ]);
import PgTable from "./PgTable"; export default PgTable;
/** * 2020-11-11 : 김경식 * ejs 내 사용하는 공통 스크립트 * jquery를 기본으로 사용 함. */ /////////////////////////////////////////////////////////////////////////////////// // 전역 function function fn_search() { event.preventDefault(); const keyword = $('#keyword').val(); if(keyword == '') { alert('검색어를 입력 하세요.'); return; } $('#searchForm').attr('action', '/search/result/' + $('#keyword').val()).submit(); } //////////////////////////////////////////////////////////////////////////////////// // jquery $(function () { /** * 메인 화면 검색 버튼 사용 */ $('#keyword').keypress(function (e) { if(e.keyCode != 13) { return; } fn_search(); }); /** * input type="text" 숫자만 입력 */ $('.onlyNumber').on('keyup', function (e) { $(this).val( $(this).val().replace(/[^0-9]/g, '') ); }); });
import React, { useState } from 'react'; const App = ({ name }) => { const [ counter, updateCounter ] = useState(0); const [ inputValue, updateInputValue ] = useState(1); const handleChange = delta => { updateCounter(oldCounter => oldCounter + delta); }; const handleInputChange = value => { updateInputValue(oldInputValue => oldInputValue = parseInt(value.target.value)); }; return ( <> <h1>{name}</h1> <h2>Counter: {counter}</h2> <button onClick={() => handleChange(inputValue)}> Add </button> <button onClick={() => handleChange(-inputValue)}> Subtract </button> <input type="number" value={inputValue} onChange={handleInputChange}/> </> ); } export default App;
// Copyright (c) 2013. All rights reserved. var ForgetMeKnot = { reminders: {}, hideHelp: false, // TODO: Make lastTriggered persist properly // TODO: Record a YouTube video and link from there // TODO: Make the popup show (only) the matching reminders for this page // TODO: Make the popup update when you switch tabs with it open // TODO: Make the delete buttons actually work // TODO: Insert Google Analytics for various pages/events makeTableRow: function (table, id) { // Make a row in the table for this reminder table.append('<tr id="row_' + id +'">' + '<td><div class="save button button_remove" id="button_remove_' + id + '"><img src="images/remove.png" class="small_image_button"/></div></td>' + '<td><select class="save select_match_type" id="select_match_type_' + id + '">' + '<option value="title">Title</option>' + '<option value="URL">URL</option>' + '</select></td>' + '<td><input class="save input_match" id="input_match_' + id + '"/><button class="button_get_current" id="button_get_current_' + id + '">&lt;</button></td>' + '<td><input class="save input_text" id="input_text_' + id + '"/></td>' + '<td><input class="save input_title" id="input_title_' + id + '"/></td>' + '<td><input class="save input_frequency" id="input_frequency_' + id + '" min="1" max="9999" maxlength="4" type="number"/>' + '<select class="save select_freq_type" id="select_freq_type_' + id + '">' + '<option value="1">seconds</option>' + '<option value="60">minutes</option>' + '<option value="3600">hours</option>' + '<option value="86400">days</option>' + '<option value="604800">weeks</option>' + '</select></td>' + '</tr>'); var freqTitle = "Maximum frequency to show this reminder - stops too many pop-ups if you change tabs a lot"; $(".select_match_type").attr("title", "How to match tabs against the pattern"); $(".input_match").attr("placeholder", "Regex pattern"); $(".input_match").attr("title", "Regex pattern to check when changing tabs"); $(".input_text").attr("placeholder", "Reminder text"); $(".input_text").attr("title", "Reminder to pop up for matching URLs"); $(".input_title").attr("placeholder", "Reminder title"); $(".input_title").attr("title", "Title of pop-up reminder for matching pages"); $(".input_frequency").attr("placeholder", "Limit"); $(".input_frequency").attr("title", freqTitle); $(".select_freq_type").attr("title", freqTitle); $(".button_remove").attr("title", "Delete this reminder"); // Bind remove button to delete ID $('.button_remove').unbind('click'); $('.button_remove').click(function(){ // Get reminder ID based on button_remove_ID var id = parseReminderID($(this).attr("id"), "button_remove_"); // TODO: Consolidate these two lines into a function? console.log("reminders before", ForgetMeKnot.reminders); // TODO: Is this necessary? ForgetMeKnot.getRemindersFromTable($("#reminders_table")); console.log("reminders after get", ForgetMeKnot.reminders); ForgetMeKnot.reminders[id].deleted = true; var row_id = "#row_" + id; $(row_id).hide("slow"); $("#button_remove_" +id).change(); // TODO: Does the button_remove.change() above get rid of the need for this? chrome.storage.sync.set({'SiteReminders': ForgetMeKnot.reminders, 'Reload': true}, function(){}); }); // When hovering over "remove" buttons, highlight the row that will be deleted $('.button_remove').hover( function(){ // Hover in function var id = parseReminderID($(this).attr("id"), 'button_remove_'); var row_id = "#row_" +id; $(row_id).addClass("pendingDelete"); }, function() { // Hover out function var id = parseReminderID($(this).attr("id"), 'button_remove_'); var row_id = "#row_" +id; $(row_id).removeClass("pendingDelete"); }); // Save whenever anything changes $(".save").unbind("change"); $(".save").bind("change", function(){ // TODO: Consolidate these two lines into a function? ForgetMeKnot.getRemindersFromTable($("#reminders_table")); console.log("saving", ForgetMeKnot.reminders); chrome.storage.sync.set({'SiteReminders': ForgetMeKnot.reminders, 'Reload': true}, function(){}); }); // Change tooltip of 'get current' button and reminder text based on match type $('.select_match_type').unbind('change'); $('.select_match_type').change(function(){ // Get reminder ID based on select_match_type_ID var id = parseReminderID($(this).attr('id'), 'select_match_type_'); $("#button_get_current_" + id).attr("title", "Get " + $(this).val() + " of currently selected tab"); $("#input_text_" + id).attr("title", "Reminder to pop up for matching " + $(this).val() + "s"); }); // Trigger the above to update tooltips now $('.select_match_type').change(); // Bind "get current" button to get current URL or title $('.button_get_current').unbind('click'); $('.button_get_current').click(function(){ // Get reminder ID based on button_get_current_ID var id = parseReminderID($(this).attr('id'), 'button_get_current_'); var matchType = $("#select_match_type_" + id).val(); chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ if(tabs.length > 0) { $("#input_match_" + id).val(matchType == 'title' ? tabs[0].title : tabs[0].url); } }); }); // Annoying manual handling of input type="number" $(".input_frequency").each(function(){ this.oninput = function () { if (this.value.length > this.maxLength) { this.value = this.value.slice(0,this.maxLength); } } }); }, init: function(){ chrome.storage.sync.get('SiteReminders', function(value) { ForgetMeKnot.reminders = value['SiteReminders'] || {}; for(var id in ForgetMeKnot.reminders) { var reminder = ForgetMeKnot.reminders[id]; // Make a row in the table for this reminder ForgetMeKnot.makeTableRow($("#reminders_table"), id); // Populate the table row with this reminder $("#input_match_" + id).val(reminder.matchPattern); $("#input_text_" + id).val(reminder.reminderText); $("#input_title_" + id).val(reminder.reminderTitle); $("#input_frequency_" + id).val(reminder.maxFrequency); $("#select_freq_type_" + id).val(reminder.freqMultiplier); $("#select_match_type_" + id).val(reminder.matchType); } }); chrome.storage.sync.get('HideHelp', function(value) { this.hideHelp = value['HideHelp'] || false; if (this.hideHelp) { $("#help_text").hide(); } }); $("#got_it").bind("click", function(){ $("#help_text").hide("slow"); this.hideHelp = true; chrome.storage.sync.set({'HideHelp': true}, function(){}) }); $("#button_restore_help").bind("click", function(){ this.hideHelp = false; $("#help_text").show("slow"); chrome.storage.sync.set({'HideHelp': false}, function(){}) }); $("#button_add").click(function(){ var empty_row = false; var id = null; // Call row empty if reminder text hasn't been set empty_row = $('#reminders_table tr:last .input_text').val() == '' // Reuse empty rows, rather than adding again. if(empty_row) { // Get ID of empty input_match in empty last row var input_match_id = $('#reminders_table tr:last .input_match').attr("id"); // Get reminder ID based on input_match_ID id = parseReminderID(input_match_id, 'input_match_'); } else { id = generateGuid(); // in common.js ForgetMeKnot.makeTableRow($("#reminders_table"), id); } var input_match = $("#input_match_" + id); chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ if(tabs.length > 0){input_match.val(tabs[0].title)}}); $("#select_match_type_" + id).val("title"); $("#input_title_" + id).val("Forget Me Knot!"); $("#input_frequency_" + id).val(30); $("#select_freq_type_" + id).val(60); // i.e. minutes // Go into the row $("#input_text_" + id).focus(); // TODO: Show a tooltip or similar if you're being prompted to edit existing empty rather than create new }); }, getRemindersFromTable: function (table) { var rows = table.get(0).rows; for(var i=0; i<rows.length; i++) { // Ignore header row if (rows[i].id.substring(0, 4) != 'row_') { continue; } // Get reminder ID based on row_ID id = parseReminderID(rows[i].id, 'row_'); if (id in ForgetMeKnot.reminders && ForgetMeKnot.reminders[id].deleted) { console.log("deleting a reminder" + id); delete ForgetMeKnot.reminders[id]; continue; } // Create new reminder if(!(id in ForgetMeKnot.reminders)) { ForgetMeKnot.reminders[id] = {}; ForgetMeKnot.reminders[id]['id'] = id; } ForgetMeKnot.reminders[id]['reminderText'] = $("#input_text_" + id).val(); ForgetMeKnot.reminders[id]['reminderTitle'] = $("#input_title_" + id).val(); ForgetMeKnot.reminders[id]['matchPattern'] = $("#input_match_" + id).val(); ForgetMeKnot.reminders[id]['maxFrequency'] = $("#input_frequency_" + id).val(); ForgetMeKnot.reminders[id]['freqMultiplier'] = $("#select_freq_type_" + id).val(); ForgetMeKnot.reminders[id]['matchType'] = $("#select_match_type_" + id).val(); } } } // Wait until the page is loaded if (document.addEventListener) { document.addEventListener("DOMContentLoaded", ForgetMeKnot.init, false); }
import React from 'react'; import { ThemeProvider } from 'styled-components'; import PropTypes from 'prop-types'; import { Header } from './Header'; import { Meta } from './Meta'; import { theme, StyledPage, Inner } from './styles/ContainerStyles'; export default function Page({ children }) { return ( <ThemeProvider theme={theme}> <StyledPage> <Meta /> <Header /> <Inner>{children}</Inner> </StyledPage> </ThemeProvider> ); } Page.propTypes = { children: PropTypes.object, };
import UI from 'src/util/ui'; let html = ` <style> #mfHelp { font-size: 1.4em; } </style> <div id='mfHelp'> <h1>How to enter a MF ?</h1> In a molecular formula it is possible to define multiple components, isotopes, non natural isotopic abundance as well as to use groups and parenthesis. <ul> <li>isotopes will be place in brackets: eg: [13C], C[2H]Cl3 <li>non natural abundance will be specified in curly brackets: eg: C{50,50}10 means that we have a ratio 50:50 between 12C and 13C <li>group abbreviation: you may use in molecular formula groups like Ala, Et, Ph, etc ... <li>multiple components should be separated by ' . '. eg. Et3N . HCl <li>hydrates on non-integer molecular formula may be specify with numbers in front on the MF. ex. CaSO4 . 1.5 H2O <li>parenthesis: any number of parenthesis may be used. eg. ((CH3)3C)3C6H3 </ul> </div> `; module.exports = function showMfHelp() { UI.dialog(html, { width: 500, height: 400, title: 'HELP: entering a molecular formula' }); };
let div1 = document.querySelector('#div1'); let options = { childList: true }; let observer = new MutationObserver(mCallback); var elem = document.createElement("img"); elem.setAttribute("src", "https://www.webyempresas.com/wp-content/uploads/2016/03/image.jpg"); elem.setAttribute("height", "100"); elem.setAttribute("width", "100"); elem.setAttribute("alt", "Flower"); var elem1 = document.createElement("img"); elem1.setAttribute("src", "https://www.webyempresas.com/wp-content/uploads/2016/03/image.jpg"); elem1.setAttribute("height", "100"); elem1.setAttribute("width", "100"); elem1.setAttribute("alt", "Flower"); var elem2 = document.createElement("img"); elem2.setAttribute("src", "https://www.webyempresas.com/wp-content/uploads/2016/03/image.jpg"); elem2.setAttribute("height", "100"); elem2.setAttribute("width", "100"); elem2.setAttribute("alt", "Flower"); function mCallback(mutations) { for (let mutation of mutations) { console.log('validaciones'); } observer.disconnect(); } setTimeout(function() { div1.appendChild(elem); }, 1000); setTimeout(function() { div1.appendChild(elem1); }, 3000); setTimeout(function() { div1.removeChild(elem1); }, 5000); setTimeout(function() { div1.appendChild(elem2); // observer.disconnect(); }, 7000); observer.observe(div1, options);
import NavBar from './NavBar'; import Footer from './Footer'; import Auth from './auth/Auth'; const Layout = ({ children }) => { return ( <> <NavBar /> {children} <Auth /> <Footer /> </> ); }; export default Layout;
import { connect } from 'react-redux'; import { compose } from 'redux'; import { createStructuredSelector } from 'reselect'; import injectReducer from 'utils/injectReducer'; import injectSaga from 'utils/injectSaga'; import { makeSelectRepos, makeSelectLoading, makeSelectError } from 'containers/App/selectors'; import { changeSearch, loadVenues, changeLocation } from './actions'; import { makeSelectPosition, makeSelectSearch, makeSelectTotal, makeSelectVenues, } from './selectors'; import reducer from './reducer'; import saga from './saga'; import HomePage from './HomePage'; const mapDispatchToProps = (dispatch) => ({ onChangeSearch: (evt) => dispatch(changeSearch(evt.target.value)), onSubmitForm: (evt) => { if (evt !== undefined && evt.preventDefault) evt.preventDefault(); // dispatch(loadRepos()); dispatch(loadVenues()); }, checkLocation: () => { navigator.geolocation.getCurrentPosition((position) => { dispatch(changeLocation(position)); }); } }); const mapStateToProps = createStructuredSelector({ repos: makeSelectRepos(), venues: makeSelectVenues(), search: makeSelectSearch(), total: makeSelectTotal(), loading: makeSelectLoading(), error: makeSelectError(), position: makeSelectPosition() }); const withConnect = connect(mapStateToProps, mapDispatchToProps); const withReducer = injectReducer({ key: 'home', reducer }); const withSaga = injectSaga({ key: 'home', saga }); export default compose(withReducer, withSaga, withConnect)(HomePage); export { mapDispatchToProps };
export const calculateInOut = (timeIn, timeOut) => { const milliseconds = timeOut.getTime() - timeIn.getTime(); const totalMinutes = Math.round(milliseconds / 60000); return totalMinutes; }
/* * The MIT License (MIT) * Copyright (c) 2019. Wise Wild Web * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @author : Nathanael Braun * @contact : n8tz.js@gmail.com */ import {types, validate} from "App/db/fields"; export default { alias : "User", apiRoute : "User", wwwRoute : "User", adminRoute : "Config/Utilisateurs", label : "Utilisateur", category : "Config", labelField : "login", previewField : "avatar", aliasField : "login", requireAdmin : true, searchableFields: ["login"], schema : { login: [validate.mandatory], }, fields : { "_id" : types.indexes, "login" : types.labels("Login"), "avatar" : types.media({ allowedTypes: "Image" }, "Avatar :"), "pass" : types.labels("Password"), "email" : types.labels("email"), "UserGroup" : types.picker("UserRole", { storeTypedItem: false }, "Groupe :"), "isAdmin" : types.boolean("Droit d'administration", true), "isPublisher": types.boolean("Droit de publication", true), "desc" : types.Html() } };
X.define("app", ["modules.menu.menu", "model.adminModel"], function (menu, adminModel) { $.ajaxSetup({ contentType: "application/json;charset=utf-8", xhrFields: { withCredentials: true }, crossDomain: true }); //初始化视图对象 var view = X.view.newOne({ el: $(".xbn-frame") }); //初始化控制器 var ctrl = X.controller.newOne({ view: view }); ctrl.logout = function () { adminModel.logout(function (argument) { location.href = X.config.PATH_FILE.path.root + '?m=login.login'; }); }; ctrl.addEvent("click", ".js-logout", "logout"); var initChannels = function () { //订阅服务消息 X.channels["e"] = "app.serviceError"; X.channels["i"] = "app.serviceInfo"; X.subscribe(X.channels["e"], function () { layer.alert("访问服务器错误"); }); X.subscribe(X.channels["i"], function () { layer.alert("访问服务器错误"); }); }; try { initChannels(); menu.load(); } catch (e) { //失败后,退出登录 console.error(e) } return {}; });
import { combineReducers } from 'redux'; import { ADD_NOTE } from './actions'; import { data } from '../data/data'; const notes = (state = data.notes, action) => { switch (action.type) { case ADD_NOTE: return Object.assign({}, state, action.payload); default: return state; } }; export const combinedReducers = combineReducers({ notes });
import React from 'react'; import papa from 'papaparse'; import axios from 'axios'; import {CSVLink} from 'react-csv'; import Filter from './Filter'; import 'react-notifications/lib/notifications.css' import {NotificationManager,NotificationContainer} from 'react-notifications'; class ShiftDetails extends React.Component { constructor(props) { super(props); this.onFileUpload = this.onFileUpload.bind(this); this.onFileChange = this.onFileChange.bind(this); this.updateData = this.updateData.bind(this); this.reloadPage = this.reloadPage.bind(this); } state = { // Initially, no file is selected selectedFile: null, reloaded:false }; onFileChange = event => { var fileInput = document.getElementById('fileupload'); var filePath = fileInput.value; var allowedExtensions = /(\.csv)$/i; if(!allowedExtensions.exec(filePath)){ alert("Please upload csv file in specified format"); this.reloadPage(); }else{ this.setState({ selectedFile: event.target.files[0] }); } }; onFileUpload() { var fileInput = document.getElementById('fileupload'); if(fileInput.files.length==0) { alert("Please upload a file before submitting"); } else { this.setState.isReload=true; const csvfile = this.state.selectedFile; console.log(csvfile); papa.parse(csvfile, { complete: this.updateData, skipEmptyLines: true, header: true }); } } reloadPage(){ window.location.reload(); } updateData(result) { var data = result.data; let axiosConfig = { headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", } }; axios.get(`http://192.168.44.47:8081/getAll`).then( res=>{ var json = res.data; var json1 = data; for(var i = 0; i < json.length; i++) { var obj = json[i]; for(var j=0;j<json1.length;j++) { var obj1 = json1[j]; if(obj1.day === obj.day && obj1.support_group === obj.support_group) { axios.delete(`http://192.168.44.47:8081/delete/`+obj.id,axiosConfig) .then(res => { console.log(res); console.log(res.data); }) } } } json1.forEach((element,index) => { if(element["on_call_support_group"].includes("/")) { console.log(element["on_call_support_group"]); console.log(element["on_call_support_group"].replace(/\s/g,'')); element["on_call_support_group"]= element["on_call_support_group"].replace(/\s/g,''); } }); axios.post(`http://192.168.44.47:8081/create`,json1,axiosConfig) .then(res => { console.log(res); console.log(res.data); }) } ) NotificationManager.success('','Uploaded Successfully!'); window.setTimeout(this.reloadPage,5000); } render() { const templateCsvData =[ ['on_call_support_group', 'day', 'support_engineer','support_engineer_phone'] , ['Operations_VTR', '2020-05-21' , 'Test Engineer','+911234567890'] ]; const templateFilename = "VTR-Shift_Roster.csv"; return ( <div> <div class="row"> <div class="col-md-12"> <div class="form"> <div class=""> <div> <h3 class="aligncenter">Upload VTR Shift roster</h3> <input type="file" id="fileupload" onChange={this.onFileChange}/> <input type="submit" class="" class="submitt submitbtn" value="Upload" onClick={()=>{this.onFileUpload()}}/> <CSVLink data={templateCsvData} filename={templateFilename}>Download csv template</CSVLink> </div> </div> </div> </div> </div> <br/> <Filter/> <NotificationContainer/> </div> ); } } export default ShiftDetails;
console.log('Client-side code running'); ////////////////////////////////////////////////////// ///// Send request using 'socket.io' /////////// ////////////////////////////////////////////////////// var socket = io.connect('/'); // window.onbeforeunload = function(e) { // socket.emit('disconnect', 'test'); // }; socket.on('playerLeftGame', function (player) { console.log('player: ' + player.player_id + ' has left the game.'); //update 'player' DOM state }); socket.on('playerSeated', function (player) { console.log('player: ' + player.player_id + ' has joined.'); //update 'player' DOM state const seatButton = document.getElementsByName('seat'); seatButton.forEach(function (eachButton) { if (eachButton.value == player.player_id) { eachButton.src = 'images/user.png.png'; eachButton.disabled = true; } }); }); socket.on('all', function (player) { console.log('received broadcasted msg:' + player.player_id); }); socket.on('updateMainPlayer', function (player) { console.log('update player own info'); document.getElementById('account' + player.player_id).style.display = ''; document.getElementById('accountBalance' + player.player_id).innerHTML = player.bankroll; }); socket.on('updateOtherPlayers', function (player) { console.log('update other player info'); document.getElementById('info' + player.player_id).hidden = ''; document.getElementById('bankroll' + player.player_id).innerHTML = player.bankroll; }); socket.on('showNoShowDownWinner', function (player) { document.getElementById('playerSeat' + player.player_id).style = 'transform: scale(1.2);transition: transform 1.9s;margin: 0 auto;box-shadow: rgb(241 234 8) 0px 0px 30px;'; }); socket.on('showResult', function (player) { flop0 = document.getElementById('imgFlopCard0'); flop1 = document.getElementById('imgFlopCard1'); flop2 = document.getElementById('imgFlopCard2'); turn = document.getElementById('imgTurnCard'); river = document.getElementById('imgRiverCard'); player.hand.card.forEach((e) => { console.log('currently card:' + e); console.log('url is :' + e); console.log('flop0 url:' + flop0.value); if (flop0.value == e) { flop0.style = 'border: 5px solid #f15a08;'; } else if (flop1.value == e) { flop1.style = 'border: 5px solid #f15a08;'; } else if (flop2.value == e) { flop2.style = 'border: 5px solid #f15a08;'; } else if (turn.value == e) { turn.style = 'border: 5px solid #f15a08;'; } else if (river.value == e) { river.style = 'border: 5px solid #f15a08;'; } else if ( document.getElementById('img' + player.player_id + 'a').value == e ) { document.getElementById('img' + player.player_id + 'a').style = 'border: 5px solid #f15a08;'; } else if ( document.getElementById('img' + player.player_id + 'b').value == e ) { document.getElementById('img' + player.player_id + 'b').style = 'border: 5px solid #f15a08;'; } else { alert('did not find card:' + e); } }); document.getElementById('playerSeat' + player.player_id).style = 'transform: scale(1.2);transition: transform 1.9s;margin: 0 auto;box-shadow: rgb(241 234 8) 0px 0px 30px;'; }); socket.on('removeCardHighLight', function (player) { console.log(JSON.stringify(player)); document.getElementById('imgFlopCard0').style = ''; document.getElementById('imgFlopCard1').style = ''; document.getElementById('imgFlopCard2').style = ''; document.getElementById('imgTurnCard').style = ''; document.getElementById('imgRiverCard').style = ''; document.getElementById('img' + player.player_id + 'a').style = ''; document.getElementById('img' + player.player_id + 'b').style = ''; }); socket.on('updatePlayerInfo', function (player) { console.log('player id is ' + player.player_id); console.log('bankroll is ' + player.bankroll); if ( document.getElementById('account' + player.player_id).style.display == '' ) { document.getElementById('accountBalance' + player.player_id).innerHTML = player.bankroll; } if (document.getElementById('info' + player.player_id).hidden == '') { document.getElementById('bankroll' + player.player_id).innerHTML = player.bankroll; } }); socket.on('updateButton', function (player) { if (player.role == 'button') { const button = document.getElementById('button' + player.player_id); button.style.display = ''; } else { document.getElementById('button' + player.player_id).style.display = 'none'; } }); socket.on('updateSmallBlind', function (small) { const smallBlind = document.getElementById('small' + small.player_id); smallBlind.style.display = ''; }); socket.on('updateBigBlind', function (big) { const bigBlind = document.getElementById('big' + big.player_id); bigBlind.style.display = ''; }); socket.on('updatePot', function (pot) { console.log('pot amount:' + pot); document.getElementById('potAmount').innerHTML = pot; }); socket.on('updateDefault', function (players) { players.forEach((p) => { //if ((p.status = 'active')) { document.getElementById('small' + p.player_id).style.display = 'none'; document.getElementById('big' + p.player_id).style.display = 'none'; document.getElementById('button' + p.player_id).style.display = 'none'; //FIX: clear hand cards document.getElementById('img' + p.player_id + 'a').style.display = 'none'; document.getElementById('img' + p.player_id + 'b').style.display = 'none'; //} }); document.getElementById('imgFlopCard0').style.display = 'none'; document.getElementById('imgFlopCard1').style.display = 'none'; document.getElementById('imgFlopCard2').style.display = 'none'; document.getElementById('imgTurnCard').style.display = 'none'; document.getElementById('imgRiverCard').style.display = 'none'; }); socket.on('layFlopCards', function (cards) { console.log('flop cards are: ' + cards); for (var i = 0; i < cards.length; i++) { document.getElementById('imgFlopCard' + i).style.display = ''; document.getElementById('imgFlopCard' + i).src = internal_GetCardImageUrl( cards[i] ); document.getElementById('imgFlopCard' + i).value = cards[i]; document.getElementById('imgFlopCard' + i).width = 50; document.getElementById('imgFlopCard' + i).height = 65; } }); socket.on('layTurnCard', function (cards) { console.log('turn card is: ' + cards); document.getElementById('imgTurnCard').style.display = ''; document.getElementById('imgTurnCard').src = internal_GetCardImageUrl(cards); document.getElementById('imgTurnCard').value = cards; document.getElementById('imgTurnCard').width = 50; document.getElementById('imgTurnCard').height = 65; }); socket.on('layRiverCard', function (cards) { console.log('river card is: ' + cards); document.getElementById('imgRiverCard').style.display = ''; document.getElementById('imgRiverCard').src = internal_GetCardImageUrl(cards); document.getElementById('imgRiverCard').value = cards; document.getElementById('imgRiverCard').width = 50; document.getElementById('imgRiverCard').height = 65; }); socket.on('highLightPlayer', function (playerObj) { console.log('highLight player' + JSON.stringify(playerObj)); playerObj.allPlayers.forEach((e) => { if (e.status == 'active') { if (playerObj.player.player_id != e.player_id) { document.getElementById('playerSeat' + e.player_id).style = ''; } else { document.getElementById('playerSeat' + e.player_id).style = '-webkit-box-shadow: 0 0 0px #da0f0f00;box-shadow: 0 0 30px #def108;'; } } }); }); socket.on('foldCards', function (player) { console.log('fold card from player:' + player.player_id); document.getElementById('img' + player.player_id + 'a').style.display = 'none'; document.getElementById('img' + player.player_id + 'b').style.display = 'none'; document.getElementById('playerSeat' + player.player_id).style = 'filter:grayscale(100%);'; }); socket.on('removePlayerHighlight', function (players) { console.log('remove highLight player' + JSON.stringify(players)); players.forEach((e) => { console.log(document.getElementById('playerSeat' + e.player_id).style); if (document.getElementById('playerSeat' + e.player_id).style != '') { document.getElementById('playerSeat' + e.player_id).style = ''; } }); }); socket.on('options1', function (player) { id = player.player_id; console.log('the client receives player id: ' + id); document.getElementById('fold' + id).hidden = ''; document.getElementById('call' + id).hidden = ''; document.getElementById('raise' + id).hidden = ''; if (player.bankroll > player.minToCall) { document.getElementById('myRange' + id).max = player.bankroll; document.getElementById('myRange' + id).min = player.minToCall; document.getElementById('myRange' + id).value = document.getElementById( 'myRange' + id ).min; } else { //use 'all in' button instead of 'raise', displayed options are 'fold', 'all in' } }); socket.on('options2', function (player) { id = player.player_id; console.log('the client receives player id: ' + id); document.getElementById('fold' + id).hidden = ''; document.getElementById('check' + id).hidden = ''; document.getElementById('raise' + id).hidden = ''; if (player.bankroll > player.minToCall) { document.getElementById('myRange' + id).max = player.bankroll; document.getElementById('myRange' + id).min = player.minToCall; document.getElementById('myRange' + id).value = document.getElementById( 'myRange' + id ).min; } //else show 'allIn' button }); socket.on('options3', function (player) { id = player.player_id; console.log('the client receives player id: ' + id); document.getElementById('fold' + id).hidden = ''; document.getElementById('allIn' + id).hidden = ''; document.getElementById('allIn' + id).value = player.minToCall; }); socket.on('options4', function (player) { id = player.player_id; console.log('the client receives player id: ' + id); document.getElementById('fold' + id).hidden = ''; document.getElementById('call' + id).hidden = ''; }); socket.on('playerOwnWinMsg', function (player) { id = player.player_id; console.log( 'the client receives playerOwnWinMsg event, with player id: ' + id ); document.getElementById('ownMsg' + id).hidden = ''; document.getElementById('ownMsg' + id).innerHTML = 'Congratulations! YOU WIN!'; //highlight the winning card }); socket.on('playerOwnLoseMsg', function (player) { id = player.player_id; console.log( 'the client receives playerOwnLoseMsg event, with player id: ' + id ); document.getElementById('ownMsg' + id).hidden = ''; document.getElementById('ownMsg' + id).innerHTML = 'YOU LOSE!'; //highlight the winning card }); socket.on('generalWinMsg', function (players) { playerId = players.player.player_id; winnerId = players.winner.player_id; console.log( 'the client receives generalWinMsg event, with player id: ' + playerId + ', winner ID is: ' + winnerId ); document.getElementById('ownMsg' + winnerId).hidden = ''; document.getElementById('ownMsg' + winnerId).innerHTML = "Player with ID '" + winnerId + "' wins"; }); socket.on('generalLoseMsg', function (players) { playerId = players.player.player_id; winnerId = players.winner.player_id; console.log( 'the client receives generalLoseMsg event, with player id: ' + playerId + ', loser ID is: ' + winnerId ); document.getElementById('ownMsg' + winnerId).hidden = ''; document.getElementById('ownMsg' + winnerId).innerHTML = "Player with ID '" + winnerId + "' loses"; }); const playerActionFoldButton = document.getElementsByName('fold'); playerActionFoldButton.forEach(function (eachButton) { eachButton.addEventListener('click', function (e) { console.log('fold button was clicked'); document.getElementById('fold' + eachButton.value).hidden = 'hidden'; document.getElementById('check' + eachButton.value).hidden = 'hidden'; document.getElementById('raise' + eachButton.value).hidden = 'hidden'; document.getElementById('call' + eachButton.value).hidden = 'hidden'; document.getElementById( 'allIn' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; //var socket = io.connect('/'); socket.emit('playerActionFold', { player_id: eachButton.value }); socket.on('foldMsg', function (id) { console.log('the client receives player id: ' + id + ' just folded'); }); }); }); const playerActionCallButton = document.getElementsByName('call'); playerActionCallButton.forEach(function (eachButton) { eachButton.addEventListener('click', function (e) { console.log('call button was clicked'); document.getElementById('fold' + eachButton.value).hidden = 'hidden'; document.getElementById('check' + eachButton.value).hidden = 'hidden'; document.getElementById('raise' + eachButton.value).hidden = 'hidden'; document.getElementById('call' + eachButton.value).hidden = 'hidden'; document.getElementById( 'allIn' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; //var socket = io.connect('/'); socket.emit('playerActionCall', { player_id: eachButton.value }); socket.on('callMsg', function (id) { console.log('the client receives player id: ' + id + ' just called.'); document.getElementById('fold' + id).hidden = ''; document.getElementById('check' + id).hidden = ''; document.getElementById('raise' + id).hidden = ''; document.getElementById('call' + id).hidden = ''; }); }); }); const playerActionAllInButton = document.getElementsByName('allIn'); playerActionAllInButton.forEach(function (eachButton) { eachButton.addEventListener('click', function (e) { console.log('allIn button was clicked'); document.getElementById( 'fold' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; document.getElementById( 'check' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; document.getElementById( 'raise' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; document.getElementById( 'call' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; document.getElementById( 'allIn' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; //var socket = io.connect('/'); socket.emit('playerActionAllIn', { player_id: eachButton.getAttribute('id').slice(-1), bet: eachButton.value, }); // socket.on('allInMsg', function (id) { // console.log('the client receives player id: ' + id + ' just allIn.'); // document.getElementById('fold' + id).hidden = ''; // document.getElementById('check' + id).hidden = ''; // document.getElementById('raise' + id).hidden = ''; // document.getElementById('call' + id).hidden = ''; // }); }); }); const playerActionCheckButton = document.getElementsByName('check'); playerActionCheckButton.forEach(function (eachButton) { eachButton.addEventListener('click', function (e) { console.log('check button was clicked'); document.getElementById('fold' + eachButton.value).hidden = 'hidden'; document.getElementById('check' + eachButton.value).hidden = 'hidden'; document.getElementById('raise' + eachButton.value).hidden = 'hidden'; document.getElementById('call' + eachButton.value).hidden = 'hidden'; document.getElementById( 'allIn' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; //var socket = io.connect('/'); socket.emit('playerActionCheck', { player_id: eachButton.value }); socket.on('checkMsg', function (id) { console.log('the client receives player id: ' + id + ' just checked.'); document.getElementById('fold' + id).hidden = ''; document.getElementById('check' + id).hidden = ''; document.getElementById('raise' + id).hidden = ''; document.getElementById('call' + id).hidden = ''; }); }); }); const playerActionRaiseButton = document.getElementsByName('raise'); playerActionRaiseButton.forEach(function (eachButton) { eachButton.addEventListener('click', function (e) { console.log('raise button was clicked'); document.getElementById('fold' + eachButton.value).hidden = 'hidden'; document.getElementById('check' + eachButton.value).hidden = 'hidden'; document.getElementById('raise' + eachButton.value).hidden = 'hidden'; document.getElementById('call' + eachButton.value).hidden = 'hidden'; document.getElementById( 'allIn' + eachButton.getAttribute('id').slice(-1) ).hidden = 'hidden'; document.getElementById('raiseSlider' + eachButton.value).style.display = ''; //FIX: create html entry, display/set min, max under the slide bar const range = document.getElementById( 'myRange' + eachButton.getAttribute('id').slice(-1) ); console.log(range.min); console.log(range.max); console.log(range.value); }); }); const playerActionSlideButton = document.getElementsByName('myRange'); playerActionSlideButton.forEach(function (eachButton) { eachButton.addEventListener('mouseup', function (e) { console.log('betting ammount is ' + eachButton.value); socket.emit('playerActionRaise', { player_id: eachButton.getAttribute('id').slice(-1), bet: eachButton.value, }); document.getElementById( 'raiseSlider' + eachButton.getAttribute('id').slice(-1) ).style.display = 'none'; document.getElementById( 'amount' + eachButton.getAttribute('id').slice(-1) ).innerHTML = ''; // document.getElementById( // 'check' + eachButton.getAttribute('id').slice(-1) // ).hidden = 'hidden'; // document.getElementById( // 'call' + eachButton.getAttribute('id').slice(-1) // ).hidden = 'hidden'; // document.getElementById( // 'fold' + eachButton.getAttribute('id').slice(-1) // ).hidden = 'hidden'; }); eachButton.addEventListener('input', function (e) { console.log('showing ammount ' + eachButton.value); document.getElementById( 'amount' + eachButton.getAttribute('id').slice(-1) ).innerHTML = eachButton.value; //update <p>content</p> using innerHTML }); }); function internal_GetCardImageUrl(card) { var suit = card.substring(0, 1); var rank = parseInt(card.substring(1)); rank = internal_FixTheRanking(rank); // 14 -> 'ace' etc suit = internal_FixTheSuiting(suit); // c -> 'clubs' etc return 'images/' + rank + '_of_' + suit + '.png'; } function internal_FixTheRanking(rank) { var ret_rank = 'NoRank'; if (rank === 14) { ret_rank = 'ace'; } else if (rank === 13) { ret_rank = 'king'; } else if (rank === 12) { ret_rank = 'queen'; } else if (rank === 11) { ret_rank = 'jack'; } else if (rank > 0 && rank < 11) { // Normal card 1 - 10 ret_rank = rank; } else { console.log(typeof rank); alert('Unknown rank ' + rank); } return ret_rank; } function internal_FixTheSuiting(suit) { if (suit === 'c') { suit = 'clubs'; } else if (suit === 'd') { suit = 'diamonds'; } else if (suit === 'h') { suit = 'hearts'; } else if (suit === 's') { suit = 'spades'; } else { alert('Unknown suit ' + suit); suit = 'yourself'; } return suit; } const seatButton = document.getElementsByName('seat'); seatButton.forEach(function (eachButton) { eachButton.addEventListener('click', function (e) { console.log('button was clicked'); updatePlayerSeat(eachButton.value); for (var i = 1; i < 8; i++) { //set other seats non-clickable if (i != eachButton.value) { document.getElementById('playerSeat' + i).disabled = true; } } socket.emit('joinGameEvent', { player_id: eachButton.value }); }); }); //update player DOM function updatePlayerSeat(seatId) { for (var i = 1; i < 8; i++) { if (seatId - 1 + i <= 7) { document .getElementById('playerBox' + i) .appendChild(document.getElementById('playerSeat' + (seatId - 1 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('info' + (seatId - 1 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('button' + (seatId - 1 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('small' + (seatId - 1 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('big' + (seatId - 1 + i))); document .getElementById('playerBox' + i) .appendChild( document.getElementById('playerInfoBox' + (seatId - 1 + i)) ); document .getElementById('playerInfoBox' + (seatId - 1 + i)) .appendChild(document.getElementById('account' + (seatId - 1 + i))); document .getElementById('playerInfoBox' + (seatId - 1 + i)) .appendChild( document.getElementById('accountBalance' + (seatId - 1 + i)) ); document .getElementById('cardBox' + i) .appendChild(document.getElementById('img' + (seatId - 1 + i) + 'a')); document .getElementById('cardBox' + i) .appendChild(document.getElementById('img' + (seatId - 1 + i) + 'b')); } else { document .getElementById('playerBox' + i) .appendChild(document.getElementById('playerSeat' + (seatId - 8 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('info' + (seatId - 8 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('button' + (seatId - 8 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('small' + (seatId - 8 + i))); document .getElementById('playerBox' + i) .appendChild(document.getElementById('big' + (seatId - 8 + i))); document .getElementById('playerBox' + i) .appendChild( document.getElementById('playerInfoBox' + (seatId - 8 + i)) ); document .getElementById('playerInfoBox' + (seatId - 8 + i)) .appendChild(document.getElementById('account' + (seatId - 8 + i))); document .getElementById('playerInfoBox' + (seatId - 8 + i)) .appendChild( document.getElementById('accountBalance' + (seatId - 8 + i)) ); document .getElementById('cardBox' + i) .appendChild(document.getElementById('img' + (seatId - 8 + i) + 'a')); document .getElementById('cardBox' + i) .appendChild(document.getElementById('img' + (seatId - 8 + i) + 'b')); } document.getElementById('playerSeat' + seatId).src = 'images/user.png.png'; document.getElementById('playerSeat' + seatId).disabled = true; } } socket.on('faceUpCard0', function (playerObj) { console.log('face up event a, player id:' + playerObj.player.player_id); document.getElementById( 'img' + playerObj.player.player_id + 'a' ).style.display = ''; document.getElementById( 'img' + playerObj.player.player_id + 'a' ).src = internal_GetCardImageUrl(playerObj.player.carda); document.getElementById('img' + playerObj.player.player_id + 'a').width = 50; document.getElementById('img' + playerObj.player.player_id + 'a').height = 65; }); socket.on('faceUpCard1', function (playerObj) { console.log('face up event b'); document.getElementById( 'img' + playerObj.player.player_id + 'b' ).style.display = ''; document.getElementById( 'img' + playerObj.player.player_id + 'b' ).src = internal_GetCardImageUrl(playerObj.player.cardb); document.getElementById('img' + playerObj.player.player_id + 'b').width = 50; document.getElementById('img' + playerObj.player.player_id + 'b').height = 65; }); socket.on('faceDownCard0', function (playerObj) { console.log('face down event a, player id:' + playerObj.player.player_id); document.getElementById( 'img' + playerObj.player.player_id + 'a' ).style.display = ''; document.getElementById('img' + playerObj.player.player_id + 'a').src = 'images/cardback.png'; document.getElementById('img' + playerObj.player.player_id + 'a').width = 50; document.getElementById('img' + playerObj.player.player_id + 'a').height = 65; }); socket.on('faceDownCard1', function (playerObj) { console.log('face down event b'); document.getElementById( 'img' + playerObj.player.player_id + 'b' ).style.display = ''; document.getElementById('img' + playerObj.player.player_id + 'b').src = 'images/cardback.png'; document.getElementById('img' + playerObj.player.player_id + 'b').width = 50; document.getElementById('img' + playerObj.player.player_id + 'b').height = 65; }); socket.on('showFaceDownCards', function (player) { console.log('the client receives all in: ' + player.player_id); document.getElementById( 'img' + player.player_id + 'a' ).src = internal_GetCardImageUrl(player.carda); document.getElementById('img' + player.player_id + 'a').value = player.carda; document.getElementById('img' + player.player_id + 'a').width = 50; document.getElementById('img' + player.player_id + 'a').height = 65; document.getElementById( 'img' + player.player_id + 'b' ).src = internal_GetCardImageUrl(player.cardb); document.getElementById('img' + player.player_id + 'b').value = player.cardb; document.getElementById('img' + player.player_id + 'b').width = 50; document.getElementById('img' + player.player_id + 'b').height = 65; }); ////////////////////////////////////////////////////// ///// Send http request using 'fetch' /////////// ////////////////////////////////////////////////////// // const radioButtons = document.getElementsByName('drone'); // radioButtons.forEach(function(eachButton){ // eachButton.addEventListener('click', function(e) { // console.log('button was clicked'); // fetch('/', {method: 'POST', headers: { // 'Content-Type': 'application/json;charset=utf-8' // }, body: JSON.stringify({player_id : eachButton.value})}) // .then(function(response) { // if(response.ok) { // console.log('click was recorded'); // return response.json(); // } // throw new Error('Request failed.'); // }).then(function(parsedResult) { // //parsedResult size, equals 1, show seat; equals 2, show seat, start dealing // //console.log(JSON.stringify(parsedResult[0].carda)); // parsedResult.forEach(function(eachResult) { // pos = eachResult.player_id; // document.getElementById('img'+pos+'a').src=internal_GetCardImageUrl(eachResult.carda); // document.getElementById('img'+pos+'b').src=internal_GetCardImageUrl(eachResult.cardb); // }) // // result = parsedResult[0].carda; // // document.getElementById('img1').src=internal_GetCardImageUrl(result); // }, function(statusCode) { // console.log('first player feedback.'); // }) // .catch(function(error) { // console.log(error); // }); // }); // } ) // button2.addEventListener('click', function(e) { // console.log('button was clicked'); // fetch('/', {method: 'POST', headers: { // 'Content-Type': 'application/json;charset=utf-8' // }, body: JSON.stringify(player2)}) // .then(function(response) { // if(response.ok) { // console.log('click was recorded'); // return response.json(); // } // throw new Error('Request failed.'); // }).then(function(parsedResult) { // console.log(JSON.stringify(parsedResult[0].carda)); // result = parsedResult[0].carda; // document.getElementById('img1').src=internal_GetCardImageUrl(result); // }, function(statusCode) { // console.log('first player feedback.'); // }) // .catch(function(error) { // console.log(error); // }); // });
/** * @file 注册逻辑 * @author cuiliang * @since 2018.10.17 */ const md5 = require('md5'); const {UserInfo} = require('../database'); // 注册业务逻辑 module.exports = (req, res) => { let {email, nickName} = req.body; // 查找是否有相同邮箱或者用户名 UserInfo.findOne({ $or: [ {email}, {nickName} ] }, (err, data) => { if (err) return res.status(500).json({ code: 500, msg: '服务端错误' }); if (data) return res.status(200).json({ code: 1, msg: '用户名或邮箱已经存在,换一个试试吧~' }); // 写入数据库 let password = req.body.password; // 对密码进行MD5加密 req.body.password = md5(md5(password) + 'userManage'); new UserInfo(req.body).save((err, data) => { if (err) return res.status(500).json({ code: 500, msg: '数据写入失败' }); // 设置 session req.session.user = data; res.status(200).json({ code: 0, msg: 'success' }); }) }) }
import { eventAggregator } from "./eventAggregator" import { GetCurrentTask } from "./dataController"; import { renderTaskView } from "../views/taskDetailsView" import { format } from 'date-fns' function initTaskEdit(task) { renderTaskView(task); } eventAggregator.subscribe("taskSelected", initTaskEdit);
//mongoose连接配置 const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/zys',{ useNewUrlParser: true ,useUnifiedTopology: true}); const con = mongoose.connection; con.on('error', console.error.bind(console, '连接数据库失败')); con.once('open',()=>{//con部分可省略,目的是为了检测连接以及连接成功后再进行操作 //定义一个schema let Schema = mongoose.Schema({ category:String, name:String }); Schema.methods.eat = function(){ console.log("I've eatten one "+this.name); }; //继承一个schema let Model = mongoose.model("fruit",Schema); //生成一个document let apple = new Model({ category:'apple', name:'apple' }); //存放数据 apple.save((err,apple)=>{ if(err) return console.log(err); apple.eat(); //查找数据 Model.find({name:'apple'},(err,data)=>{ console.log(data); }) }); });
import React, { createContext, useState, useEffect, useRef } from 'react'; import { io } from 'socket.io-client'; import Peer from 'simple-peer'; const SocketContext = createContext(); const socket = io('https://crochat.herokuapp.com/'); const ContextProvider = ({ children }) => { const [callAccepted, setCallAccepted] = useState(false); const [accepted, setAccepted] = useState(false); const [stream, setStream] = useState(); const [name, setName] = useState(''); const [call, setCall] = useState({}); const [me, setMe] = useState(''); const partnerVideo = useRef(); const [callEnded,setCallEnded] = useState(true); const [calling, setCalling] = useState(false); const [audioCalling, setAudioCalling] = useState(false); const [audioCall, setAudioCall] = useState(false); useEffect(() => { socket.on('me', (id) => { setMe(id) }); socket.on('callIncoming', ({ signal, from, name }) => { setCall({ isReceivingCall: true, from, name, signal }); }); socket.on("audioCall", () => { setAudioCall(true); }) }, []); const callUser = (id) => { setCallEnded(false); !audioCalling ? setCalling(true) : setAudioCalling(true); navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(currentStream => { var peer = new Peer({ initiator: true, trickle: false, stream: currentStream }); setStream(currentStream); if (peer) { if (audioCall) { socket.emit("audioCall", id); } peer.on('signal', (data) => { if (data. renegotiate || data.transceiverRequest) return socket.emit('callUser', { userToCall: id, signalData: data, from: me, name: "dd" }); }); peer.on("stream", stream => { if (partnerVideo.current) { partnerVideo.current.srcObject = stream; } }) socket.on('callAccepted', (signal) => { peer.signal(signal); setCallAccepted(true); }); socket.on("rejected", () => { setCalling(false); setCallEnded(true); setAudioCall(false); setAudioCalling(false); currentStream.getTracks().forEach(tracks => tracks.stop()); }) socket.on("hangedUp", () => { currentStream.getTracks().forEach(tracks => tracks.stop()); setCallEnded(true); setCalling(false); setAudioCall(false); setAudioCalling(false); setAccepted(false); setCallAccepted(false); }) peer.on("close",()=>{ socket.emit("hangUp",id); }) peer.on("error",(err)=>{ console.log(err); }) } }); }; const answerCall = () => { setCallEnded(false); navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(currentStream => { setStream(currentStream); setAccepted(true); var peer = new Peer({ initiator: false, trickle: false, stream: currentStream }); if (peer) { peer.on('signal', (data) => { socket.emit('answerCall', { signal: data, to: call.from }); }); peer.on('stream', stream => { if (partnerVideo.current) { partnerVideo.current.srcObject = stream; } }); peer.signal(call.signal); peer.on("error",(err)=>{ console.log(err); }) socket.on("hangedUp", () => { setCallEnded(true); currentStream.getTracks().forEach(tracks => tracks.stop()); setCalling(false); setAudioCall(false); setAudioCalling(false); setCall({}); setAccepted(false); setCallAccepted(false); }) peer.on("close",()=>{ socket.emit("hangUp",call.from); }) } }); }; let PartnerVideo; if (callAccepted) { PartnerVideo = ( <video className="vid" playsInline ref={partnerVideo} autoPlay /> ); } let CallingPartnerVideo; if (accepted) { CallingPartnerVideo = ( <video className="vid" playsInline ref={partnerVideo} autoPlay /> ); } return ( <SocketContext.Provider value={{ socket, call, setCall, callAccepted, stream, name, PartnerVideo, CallingPartnerVideo, partnerVideo, accepted, setName, audioCall, setAudioCall, calling, setCalling, audioCalling, setAudioCalling, me, callEnded, setCallEnded, callUser, answerCall, }} > {children} </SocketContext.Provider> ); }; export { ContextProvider, SocketContext };
import gql from 'graphql-tag'; export const MeQuery = gql` { me { isOk user { _id username email bio avatar } } } `; export const GetUsersQuery = gql` { getUsers { _id username } } `; export const GetQestionsQuery = gql` { getQuestions { _id text isLiked likesCount theAsker { _id username } theResponder { _id username } answer createdAt answerDate } } `; export const GetMyNotAnswerdQuestionsQuery = gql` { getMyNotAnswerdQuestions { _id text theAsker { _id username } createdAt } } `; export const GetMyNotAnsweredQuestionQuery = gql` query($questionID: ID!) { getMyNotAnsweredQuestion(questionID: $questionID) { isOk question { _id text theAsker { _id username } } } } `; export const GetUserAnsweredQuestionsQuery = gql` query($username: String!) { getUserAnsweredQuestions(username: $username) { _id text isLiked likesCount theAsker { _id username } theResponder { _id username } answer createdAt answerDate } } `; export const GetUserByUsernameQuery = gql` query($username: String!) { getUserByUsername(username: $username) { _id username bio avatar } } `; export const GetUserQuery = '';
import React from 'react' function Input({label,name,type,onChange,value,...rest}) { return ( <div className="px-4 pb-4"> <label htmlFor={name} className="text-lg block font-semibold pb-2">{label}</label> <input type={type} name={name} className="shadow appearance-none leading-tight w-full py-2 px-3 border border-blue-300 rounded text-gray-700 focus:outline-none focus:shadow-outline" onChange={onChange} placeholder={label} value={value} {...rest} /> </div> ) } export default Input
export function CustomError(message) { this.message = message; var last_part = new Error().stack.match(/[^\s]+$/); this.stack = `${this.name} at ${last_part}`; } Object.setPrototypeOf(CustomError, Error); CustomError.prototype = Object.create(Error.prototype); CustomError.prototype.name = "CustomError"; CustomError.prototype.message = ""; CustomError.prototype.constructor = CustomError;
import React from 'react'; const Weather = (props)=> ( <div> {props.toShow && ( <div> <p> Location : {props.city} , {props.country} </p> <p> Temperature : {props.city} </p> <p>Humidity : {props.humidity}</p> <p> Conditions : {props.description} </p> </div> )} {props.error && <div style={{color: 'red', fontSize: '40px'}}> {props.error} </div>} </div> ); export default Weather;
const express = require("express"); const bodyParser = require("body-parser"); const cors = require("cors"); const postsRoute = require("./routes/posts"); const placementRoute = require("./routes/placements"); const companyRoute = require("./routes/company"); const authRoutes = require("./routes/auth"); const profileRoute = require("./routes/profile"); require("./config/database"); const app = express(); app.use(cors()); app.use(express.static("public")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const port = process.env.PORT; app.listen(port, () => { console.log(`Example of app listening at http://localhost:${port}`); }); app.use("/api/auth", authRoutes); app.use("/api/posts", postsRoute); app.use("/api/placements", placementRoute); app.use("/api/company", companyRoute); app.use("/api/profile", profileRoute);
let Router = require('koa-router'); let User = require('../app/controllers/user'); let Movie = require('../app/controllers/movies'); let Codetemplate = require('../app/controllers/codetemplateController'); let Middlewares = require('../app/middlewares/middleware'); let Qiniu = require('../app/controllers/qiniu'); let QiniuCloud = require('../app/controllers/rickyCloudqiniu'); let Song = require('../app/controllers/songs'); let Album = require('../app/controllers/albums'); let Dog = require('../app/controllers/dog'); let Statistic = require('../app/controllers/statistics'); let AppUser = require('../app/controllers/appuser'); let TripCard = require('../app/controllers/tripcardcontroller'); const fs = require('fs'); let crypto = require('crypto'); let WX = require('./wx'); let axios = require('axios') module.exports = function () { // let router = new Router({ // prefix: '/api' // }); let router = new Router(); // router.get('/user/list',Middlewares.hasToken,User.getList) router.get('/api/user/list', User.getList) router.post('/api/user/login', User.userLogin) router.post('/api/user/signin', User.addUser) router.get('/api/user/logout', User.UserLogout) router.post('/api/user/update', User.UserUpodate) router.get('/api/user/current', User.getCurrentUser) router.post('/api/movie/add', Movie.addMovie) router.get('/api/movie/list', Movie.queryList) router.post('/api/codetemplate/add', Codetemplate.addTemplate) router.post('/api/codetemplate/update', (ctx, next) => Middlewares.findRecord(ctx, next, 'codetemplate'), Codetemplate.updateTemplate) router.get('/api/codetemplate/list', Middlewares.optionRequest, Codetemplate.queryList) router.post('/api/song/add', Song.addSong) router.get('/api/song/list', Song.songList) router.get('/api/uptoken', Qiniu.uptoken) router.get('/app/uptoken', QiniuCloud.uptoken) //相册 router.post('/api/album/add', Album.addAlbum) router.get('/api/album/list', Album.getAlbumList) //狗狗 router.post('/api/dog/add', Dog.addDog) router.post('/api/dog/remove', Dog.removeDog) router.post('/api/dog/update', Dog.updateDog) //小程序 router.post('/app/savetripcard',Middlewares.validateLogin, TripCard.addCard) router.get('/app/tripCardList',Middlewares.validateLogin, TripCard.getCardList) router.get('/app/allCardList',Middlewares.validateLogin, TripCard.getAllCardList) //维权统计 router.post('/statistic',Statistic.addAuthUser) //还可以是用ReadStream,更简单 router.get('/baiyue', (ctx, next) => { console.log('进入我的这个应用了') ctx.type = 'html'; ctx.body = fs.createReadStream('./dist/index.html');//以根目录为根路径 }) router.get('/wechat', (ctx, next) => { // 获取微信的请求,注意是 get let signature = ctx.query.signature; let echostr = ctx.query.echostr; let timestamp = ctx.query.timestamp; let nonce = ctx.query.nonce; // 这里的token 要和你表单上面的token一致 let token = 'fighterapp'; // 根文档上面的,我们需要对这三个参数进行字典序排序 let arr = [token, timestamp, nonce]; arr.sort(); let tmpStr = arr.join(''); // 排序完成之后,需要进行sha1加密, 这里我们使用node.js 自带的crypto模块 let sha1 = crypto.createHash('sha1'); sha1.update(tmpStr); let resStr = sha1.digest('hex'); console.log('进入了微信服务器验证!'); console.log(signature, 'resStr: ', resStr); // 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信, // 如果匹配,返回echoster , 不匹配则返回error if (resStr === signature) { ctx.body = echostr; } else { return false; } }) router.get('/api/currentuser',async function (ctx, next){ console.log('进入获取用户接口了') let code = ctx.query.code; console.log(code) let url='https://api.weixin.qq.com/sns/jscode2session?appid='+WX.AppID+'&secret='+WX.AppSecret+'&js_code='+code+'&grant_type=authorization_code'; let res=await axios.get(url); console.log(res.data) ctx.status = 200; ctx.body = res.data; // axios.get(tokenURL).then((res)=>{ // ctx.status = 200; // ctx.body = res; // }).catch((err)=>{ // console.error(err); // ctx.status = 400; // ctx.body = { // message: '获取用户信息失败' // }; // }) }); router.get('/app/login',AppUser.userLogin); router.get('/app/currentUser',AppUser.currentUser); router.post('/app/userUpdate',AppUser.updateUser); //小程序 return router };
import { Trans } from '@/plugins/i18n/Translation' const Home = () => import('@/pages/Home.vue'); const Features = () => import('@/pages/Features.vue'); const Updates = () => import('@/pages/Updates.vue'); const About = () => import('@/pages/About.vue'); const Pricing = () => import('@/pages/Pricing.vue'); const Terms = () => import('@/pages/Terms.vue'); const Privacy = () => import('@/pages/Privacy.vue'); const Security = () => import('@/pages/Security.vue'); const Cookies = () => import('@/pages/Cookies.vue'); const Values = () => import('@/pages/Values.vue'); const NotFound = () => import('@/pages/NotFound.vue'); export default [ { path: '/:lang', // create a container component component: { render (c) { return c('router-view') } }, beforeEnter: Trans.routeMiddleware, children: [ { path: '', name: 'home', component: Home, }, { path: 'features', name: 'features', component: Features, }, { path: 'updates', name: 'updates', component: Updates, }, { path: 'about', name: 'about', component: About, }, { path: 'pricing', name: 'pricing', component: Pricing, }, { path: 'security', name: 'security', component: Security, }, { path: 'values', name: 'values', component: Values, }, // Secondary pages { path: 'terms', name: 'terms', component: Terms, }, { path: 'privacy', name: 'privacy', component: Privacy, }, { path: 'cookies', name: 'cookies', component: Cookies, }, // Error pages { path: '*', component: NotFound, } ] }, { // Redirect user to supported lang version. path: '*', redirect: '/en' // redirect (to) { // return Trans.getUserSupportedLang() // } } ]
import { createSlice } from "@reduxjs/toolkit"; const initialState = { movies: [], trending: [], upcoming: [], }; const movieSlice = createSlice({ //actions name: "movie", initialState, //reducers reducers: { setMovies: (state, action) => { console.log(action.payload); state.movies = action.payload; }, setTrending: (state, action) => { state.trending = action.payload; }, setUpcoming: (state, action) => { state.upcoming = action.payload; }, }, }); export const { setMovies, setTrending, setUpcoming } = movieSlice.actions; export const selectMovie = (state) => state.movie.movies; export const selectUpComingMovies = (state) => state.movie.upcoming; export const selectTrendingMovies = (state) => state.movie.trending; export default movieSlice.reducer;
import RestfulDomainModel from '../base/RestfulDomainModel' class Model extends RestfulDomainModel { async page(pageNo, pageSize, filter, sort) { return { content: [ { id: 1, name: '新加好友问候', deviceId: 'UHKLSLLDLFFLFF', userStatus: 1, syncStatus: '同步成功' } ], pageNo: 1, pageSize: 10, total: 1 } } } export default new Model([ { id: { name: 'ID', dataOnly: true }}, { name: { name: '消息名称' }}, { deviceId: { name: '执行的设备' }}, { useStatus: { name: '使用状态' }}, { syncStatus: { name: '同步状态' }} ], '/im/profile')
import React, { Component } from 'react'; import CityCard from './CityCard'; import { connect } from 'react-redux'; import { setWeather } from '../../actions'; import Navbar from '../Navbar'; import { Grid } from '@material-ui/core'; class WeatherGrid extends Component { search(num) { const url =`http://localhost:8080/weather/${this.props.cities[num].city}` try { fetch(url, { method: 'GET', mode: "cors", dataType: 'jsonp' }).then(response => response.json()) .then(json => this.props.setWeather({ city: json.name, temp: json.temp, id: num })); } catch (e) { console.log('request error') } } render() { return ( <div > <Navbar /> <Grid container spacing={24} style={{ padding: 24 }} > <CityCard city={this.props.cities[0].city} temp={this.props.cities[0].temp} /> <CityCard city={this.props.cities[1].city} temp={this.props.cities[1].temp} /> <CityCard city={this.props.cities[2].city} temp={this.props.cities[2].temp} /> <CityCard city={this.props.cities[3].city} temp={this.props.cities[3].temp} /> </Grid> </div> ); } componentWillMount() { this.search(0); this.search(1); this.search(2); this.search(3); } } function mapStateToProps(state) { return { cities: state.weather, } } export default connect(mapStateToProps, { setWeather })(WeatherGrid);
// @depends jsutil/Object var jsutil = jsutil || {}; /** * tries to behave similar to a Location object * protocol includes everything before the // * host is the plain hostname * port is a number or null * pathname includes the first slash or is null * hash includes the leading # or is null * search includes the leading ? or is null */ jsutil.Loc = function(urlStr) { var m = this.parser.exec(urlStr); if (!m) throw new Error("cannot parse URL: " + urlStr); this.local = !m[1]; this.protocol = m[2] ? m[2] : null; // http: this.host = m[3] ? m[3] : null; // de.wikipedia.org this.port = m[4] ? parseInt(m[4].substring(1), 10) : null; // 80 this.pathname = m[5] ? m[5] : null; // /wiki/Test this.search = m[6] ? m[6] : null; // ?action=edit this.hash = m[7] ? m[7] : null; // #Industry }; jsutil.Loc.prototype = { /** matches a global or local URL */ parser: /((.+?)\/\/([^:\/]+)(:[0-9]+)?)?([^#?]+)?(\?[^#]*)?(#.*)?/, /** returns the href which is the only usable string representationn of an URL */ toString: function() { return this.hostPart() + this.pathPart(); }, /** returns everything before the pathPart */ hostPart: function() { if (this.local) return ""; return this.protocol + "//" + this.host + (this.port ? ":" + this.port : ""); }, /** returns everything local to the server */ pathPart: function() { return this.pathname + this.hash + this.search; }, /** converts the searchstring into an Array of name/value-pairs */ args: function() { if (!this.search) return []; var out = []; var split = this.search.substring(1).split("&"); for (var i=0; i<split.length; i++) { var parts = split[i].split("="); out.push([ decodeURIComponent(parts[0]), decodeURIComponent(parts[1]) ]); } return out; }, /** converts the searchString into a hash. */ argsMap: function() { var pairs = this.args(); var out = {}; for (var i=0; i<pairs.length; i++) { var pair = pairs[i]; var key = pair[0]; var value = pair[1]; // if (out.hasOwnProperty(key)) throw new Error("duplicate argument: " + key); out[key] = value; } return out; }//, };
const mongoose = require('mongoose') const stuctModels = require('./models') module.exports = ( uri ) => { mongoose.connect(uri) return stuctModels( mongoose ) }
import React, { Component } from 'react' import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import classnames from 'classnames'; import Collapse from '@material-ui/core/Collapse'; import Avatar from '@material-ui/core/Avatar'; import IconButton from '@material-ui/core/IconButton'; import Typography from '@material-ui/core/Typography'; import red from '@material-ui/core/colors/red'; import FavoriteIcon from '@material-ui/icons/Favorite'; import ShareIcon from '@material-ui/icons/Share'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import MoreVertIcon from '@material-ui/icons/MoreVert'; const styles = theme => ({ }); export class ArticleContent extends Component { render() { return ( <div> </div> ) } } export default ArticleContent
let ids = {}; const getCredentialRequestOptions = () => { const name = document.getElementById('name').value; const challenge = crypto.getRandomValues(new Uint8Array(32)); document.getElementById('authn_challenge').value = Base64.encode(challenge); const credentialRequestOptions = { 'challenge': challenge, 'allowCredentials': [{ 'type': "public-key", 'id': ids[name] }] }; return credentialRequestOptions; }; const getCredentialCreationOptions = () => { const name = document.getElementById('name').value; const challenge = crypto.getRandomValues(new Uint8Array(32)); document.getElementById('register_challenge').value = Base64.encode(challenge); const credentialCreationOptions = { 'challenge': challenge, // 登録時、認証時毎回違う値を入れる 'rp': { // Relying Partyの情報、nameのみ必須、この他に、iconというメンバーもつけられる 'name': 'localhost webAuthn Demo' }, 'user': { // 認証のユーザーの情報、全て必須。この他に、iconというメンバーもつけられる 'id': strToBin(name), 'name': name, 'displayName': name }, 'pubKeyCredParams': [ // 必須、 { 'type': 'public-key', 'alg': -7 }, { 'type': 'public-key', 'alg': -257 } ], timeout: 60000, // 必須ではない。タイムアウトまでの時間[ミリ秒] attestation: 'direct' // 認証に関するオプション // その他にもメンバーが選択できる }; return credentialCreationOptions; }; const register = () => { const publicKey = getCredentialCreationOptions(); console.log('Register PublicKey'); console.log(publicKey); const name = document.getElementById('name').value; navigator.credentials.create({ publicKey }) .then(function (newCredentialInfo) { console.log('Register Response'); console.log(newCredentialInfo); const { id, rawId, response, type } = newCredentialInfo; const { attestationObject, clientDataJSON } = response; ids[name] = rawId; attestation = CBOR.decode(attestationObject); attestation.authData = parseAuthData(attestation.authData); console.log(JSON.parse(String.fromCharCode.apply(null, new Uint8Array(clientDataJSON)))); console.log(attestation); document.getElementById('register_id').value = id; document.getElementById('register_rawid').value = formatArrayString(new Uint8Array(rawId)); document.getElementById('register_attestation').value = JSON.stringify(attestation, null, 2); document.getElementById('register_clientData').value = JSON.stringify(JSON.parse(String.fromCharCode.apply(null, new Uint8Array(clientDataJSON))), null, 2); document.getElementById('register_type').value = type; document.getElementById('register_pubKey').value = JSON.stringify(attestation.authData.credentialPublicKey, null, 2); }).catch(function (err) { console.log(err); }); }; const authn = () => { const publicKey = getCredentialRequestOptions(); console.log('Auth PublicKey'); console.log(publicKey); navigator.credentials.get({ publicKey }) .then(function (assertion) { console.log('Auth Response'); console.log(assertion); const { id, rawId, response, type } = assertion; const { authenticatorData, clientDataJSON, signature, userHandle } = response; const authenticator = parseAuthData(new Uint8Array(authenticatorData)); console.log(authenticator); document.getElementById('authn_id').value = id; document.getElementById('authn_rawid').value = formatArrayString(new Uint8Array(rawId)); document.getElementById('authn_authenticator').value = JSON.stringify(authenticator, null, 2); document.getElementById('authn_clientData').value = JSON.stringify(JSON.parse(String.fromCharCode.apply(null, new Uint8Array(clientDataJSON))), null, 2); document.getElementById('authn_signature').value = formatArrayString(new Uint8Array(signature)); document.getElementById('authn_userHandle').value = formatArrayString(new Uint8Array(userHandle)); document.getElementById('authn_type').value = type; document.getElementById('authn_pubKey').value = JSON.stringify(authenticator.credentialPublicKey, null, 2); }).catch(function (err) { console.log(err); }); }; window.addEventListener('load', () => { const registerButton = document.getElementById('register-button'); const authnButton = document.getElementById('authn-button'); registerButton.addEventListener('click', register); authnButton.addEventListener('click', authn); });
import React, { Component } from 'react' import '../assets/scss/index.scss' import '../assets/scss/global.scss' import Info from './Info' import Counter from './Counter' class Home extends Component { state = { greeting: null, lazyComponent: null, hasLazy: false, } async componentDidMount() { const res = await 'hello' this.greeting(res) } greeting = (info) => { this.setState({ greeting: info, }) } info = { name: 'name', age: 18, birthday: '1900.1.1', } toggleLazy = async () => { if (!this.state.hasLazy) { const LazyComponent = (await import('./Lazy.jsx')).default // 这里是由于webpack 4将 this.setState(prev => ({ hasLazy: !prev.hasLazy, lazyComponent: LazyComponent, })) } else { this.setState(prev => ({ hasLazy: !prev.hasLazy, lazyComponent: null, })) } } render() { return ( <div className="home"> this is a greeting: {this.state.greeting} <Info {...this.info} /> <button onClick={this.toggleLazy} >toggle lazy component</button> <div className="lazy-component">{this.state.lazyComponent}</div> <Counter /> </div> ) } } export default Home
document.addEventListener('contextmenu', function (e) { e.preventDefault(); if (documentTouched) return; if (toolSettings.getAttribute('data-tool') === 'none') { return; } if (toolSettings.getAttribute('data-tool') === 'brush') { // Also eraser toolSettingsCallback = function() { setBrushSize(toolSettings.getAttribute('data-value-log')); brushOutline_canvas.style.left = e.offsetX - brushSize * zoomFactor / 2 + 'px'; brushOutline_canvas.style.top = e.offsetY - brushSize * zoomFactor / 2 + 'px'; }; } if (toolSettings.getAttribute('data-tool') === 'zoom') { // toolSettings.setAttribute('data-value-percent', (settingsPercent * 100).toFixed(2)); } toolSettings.style.left = e.clientX + 'px'; toolSettings.style.top = e.clientY + 'px'; toolSettings.style.display = 'block'; }); document.addEventListener('click', function () { toolSettings.style.display = 'none'; }); toolSettingsKnob.addEventListener('touchstart', function (e) { if (toolSettings.getAttribute('data-tool') === 'none') { return; } if (toolSettings.getAttribute('data-tool') === 'brush') { // Also eraser toolSettingsCallback = function() { setBrushSize(toolSettings.getAttribute('data-value-log')); brushOutline_canvas.style.left = e.touches[0].offsetX - brushSize * zoomFactor / 2 + 'px'; brushOutline_canvas.style.top = e.touches[0].offsetY - brushSize * zoomFactor / 2 + 'px'; }; } document.addEventListener('touchmove', moveToolSettingsKnob); document.addEventListener('touchend', unmoveToolSettingsKnob); toolSettingsLabel.style.display = 'block'; }); toolSettingsKnob.addEventListener('mousedown', function () { document.addEventListener('mousemove', moveToolSettingsKnob); document.addEventListener('mouseup', unmoveToolSettingsKnob); toolSettingsLabel.style.display = 'block'; }); function unmoveToolSettingsKnob() { document.removeEventListener('mousemove', moveToolSettingsKnob); document.removeEventListener('mouseup', unmoveToolSettingsKnob); document.removeEventListener('touchmove', unmoveToolSettingsKnob); document.removeEventListener('touchend', unmoveToolSettingsKnob); toolSettingsLabel.style.display = 'none'; toolSettings.style.display = 'none'; toolSettingsCallback(); } function moveToolSettingsKnob(e) { let clientX = e.clientX || e.touches[0].clientX; let settingsOffset = offset(toolSettingsRail).left; let settingsMinPx = 0 - (toolSettingsKnob.clientWidth / 2); let settingsMaxPx = toolSettingsRail.clientWidth - (toolSettingsKnob.clientWidth / 2); let newSettingsPositionPx = clientX - settingsOffset - (toolSettingsKnob.clientWidth / 2); if (newSettingsPositionPx < settingsMinPx) { newSettingsPositionPx = settingsMinPx; } if (newSettingsPositionPx > settingsMaxPx) { newSettingsPositionPx = settingsMaxPx; } let settingsPercent = (newSettingsPositionPx + (toolSettingsKnob.clientWidth / 2)) / (settingsMaxPx + (toolSettingsKnob.clientWidth / 2)); let settingsLog = getLogValues(settingsPercent, 1, 3000); toolSettingsKnob.style.left = newSettingsPositionPx + 'px'; if (toolSettings.getAttribute('data-label-mode') === '%') { toolSettingsLabel.innerHTML = (settingsPercent * 100).toFixed(0) + ' %'; } else if (toolSettings.getAttribute('data-label-mode') === 'log') { toolSettingsLabel.innerHTML = settingsLog.toFixed(0) + ' px'; } else { toolSettingsLabel.innerHTML = settingsPercent.toFixed(2); } toolSettings.setAttribute('data-value-percent', (settingsPercent * 100).toFixed(2)); toolSettings.setAttribute('data-value-log', settingsLog.toFixed(2)); } function getLogValues(position, min, max) { let minP = 0; let maxP = 100; let minV = Math.log(min); let maxV = Math.log(max); let scale = (maxV - minV) / (maxP - minP); return Math.exp(minV + scale * (position * 100 - minP)); }
module.exports = { url: 'http://35.223.154.181:8080/monster-slayer', elements: { yourScoreSection: '#you-score-section', youHeader: '#you-header', youHealth: '#player-health', monsterHealth: '#monster-health', monsterHeader: '#monster-header', gameStartSection: '#game-start-section', startGameBtn: '#start-game', attackBtn: '#attack', specialAttackBtn: '#special-attack', giveUpBtn: '#give-up', healBtn: '#heal', gameScoreSection: '#game-score-section', rowLog: '#row-log', playerTurn: '.player-turn', monsterTurn: '.monster-turn', log: '#log', serviceMessage: '#service-message' } }
import React, { Component, PropTypes, } from 'react' import { View, StyleSheet, TextInput } from 'react-native' export default class MyTextInput extends Component { static defaultProps = {} static propTypes = {} constructor(props) { super(props) this.state = {} } render() { return ( <View style={styles.inputWrapper}> <TextInput style={styles.input} {...this.props} /> </View> ) } } const styles = StyleSheet.create({ inputWrapper: { flexDirection: 'row', height: 40, marginVertical : 10, backgroundColor: 'transparent' }, input: { flex: 1, paddingHorizontal: 10, backgroundColor: '#FFF' }, })
import React from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import Signup from './Signup'; import Signin from './Signin'; class Home extends React.Component { render() { return ( <Router> <div id="home"> <Switch> <Route exact component={Signup} path="/signup" /> <Route exact component={Signin} path="/signin" /> <Route exact component={Signin} path="/" /> </Switch> </div> </Router> ) } } export default Home;
/* @flow */ import express from "express"; import { notifHandler, batchHandler } from "hull/lib/utils"; import updateUser from "./update-user"; module.exports = function Server(app: express) { app.post('/notify', notifHandler({ groupTraits: true, handlers: { "user:update": (ctx, messages) => { messages.map(m => updateUser(ctx, m)); } } })); app.use("/batch", batchHandler(({ metric, client, ship }, messages) => { client.logger.debug("batch.process", { messages: messages.length }); messages.map((message) => { return updateUser({ metric, client, ship, isBatch: true }, message); }); }, { groupTraits: true, batchSize: 100 })); return app; };
import React from 'react' export const ProductTable = ({checkValue, updateSelectedProducts, productName, productGoods, selectedProducts}) => { return ( <table> <caption><h1>{productName ? productName : 'Прочее'}</h1></caption> <thead> <tr> <th>id</th> <th>Наименование товара</th> <th>Цена</th> <th>Количество</th> <th>Сумма</th> </tr> </thead> <tbody> {productGoods.map(g => { return ( <tr key={g.gid}> <td>{g.gid}</td> <td>{g.gname}</td> <td>{g.gprice}</td> <td> <form onSubmit={e => e.preventDefault()}> <input placeholder='Введите количество товара' value={selectedProducts[g.gid]?.quantity || ''} name={g.gid} type='number' min='0' inputMode='number' onKeyUp={checkValue} onChange={(e) => updateSelectedProducts(e, g.gprice, g.gname)} /> </form> </td> <td>{selectedProducts[g.gid]?.totalPrice || '0'}</td> </tr> ) })} </tbody> </table> ) }
import React, { lazy } from 'react' const Person = lazy(() => import('../Base/Person')) const PersonPage = () => { return ( <> <div className="Container-main"> <Person/> </div> </> ) } export default PersonPage
const express = require("express"); const bcrypt = require("bcrypt"); const {User, validateUser} = require("../models/Users"); const AuthUser = require("../middlewares/AuthMiddleware"); const router = express.Router(); router.post("/registeruser",async (req,res)=>{ try{ const {error} = validateUser(req.body); if (error){ console.log("Error in user creation"); return res.status(400).send(error.details[0].message); } const isUserAlreadyExists = await User.findOne({ emailId: req.body.emailId }); if(isUserAlreadyExists) return res.send({error:"Email already exists"}); const salt = await bcrypt.genSalt(10); const password = await bcrypt.hash(req.body.password, salt); const user = new User({ userName: req.body.userName, emailId: req.body.emailId, password: password }); const result = await user.save(); const response = { userName: result.userName, emailId: result.emailId } res.send(response); } catch(ex){ console.log(ex); } }); router.post('/signinuser',async (req,res)=>{ try { //dummy username as the username field is not included in the login page req.body.userName = "Login"; const { error } = validateUser(req.body); if (error){ return res.status(400).send(error.details[0].message); } const user = await User.findOne({ emailId: req.body.emailId }); if (!user) return res.status(400).send("Invalid Email Id or Password"); const validPassword = await bcrypt.compare( req.body.password, user.password ); if (!validPassword) return res.status(400).send("Invalid Email or Password"); res.send({token : user.generateAuthToken(), username: user.userName}); } catch (ex) { console.log(ex); } }); router.get('/getdemo',[AuthUser],async (req,res)=>{ const allUsers = await User.find(); res.send(allUsers); }); module.exports = router;
import React from 'react' import Field from './Field' function handleSubmit(event, onCreate) { // Prevent form from submitting as normal event.preventDefault() // Get <form> const form = event.target // Get data from the forms <input> const title = form.elements['title'].value const yearReleased = form.elements['yearReleased'].value const description = form.elements['description'].value onCreate({ title, yearReleased, description }); } export default function CreateMovieForm({ onCreate }) { return ( <form onSubmit={ (event) => handleSubmit(event, onCreate) }> <Field label="Title" name="title" /> <Field label='Year Released' name="yearReleased" /> <Field label='Description' name="description" /> <button type="submit"> Create Movie </button> </form> ) }
import NotesApi from "@/services/NotesApi"; import AccessManager from "@/services/AccessManager"; export default { namespaced: true, state: () => ({ token: "", currentRole: {} }), mutations: { AUTHENTICATE_ROLE(state, role) { state.currentRole = role; }, AUTHENTICATE_TOKEN(state, token) { state.token = token; }, CLEAR_STATE(state) { state.token = ""; state.currentRole = {}; } }, actions: { login({ dispatch }, payload) { return NotesApi.login(payload).then(async response => { const token = response.data.token; const role_id = response.data.authenticated.id; await dispatch("authenticate", token); await dispatch("loadCurrentRole"); await dispatch("Ui/initGlobalData", null, { root: true }); AccessManager.createCookies({ token, role_id }); }); }, authenticate({ commit }, token) { if (token.length > 32) { AccessManager.setAuthTokenOnApi(token); commit("AUTHENTICATE_TOKEN", token); } }, async loadCurrentRole({ commit }) { return await NotesApi.getAuthenticatedRole() .then(response => { commit("AUTHENTICATE_ROLE", response.data.data.role); }) .catch(() => { AccessManager.removeAuthTokenOnApi(); }); }, logout({ commit, dispatch }) { AccessManager.destroyCookies(); AccessManager.removeAuthTokenOnApi(); commit("CLEAR_STATE"); dispatch("Ui/clearGlobalData", null, { root: true }); }, clearState({ commit }) { commit("CLEAR_STATE"); } }, getters: { isAuth: state => { return state.token.length > 32; }, isSuper: state => { if (state.currentRole.isSuper !== undefined) { return state.currentRole.isSuper; } return false; } } };
import React, {useContext, useState} from 'react'; import { makeStyles } from '@material-ui/core/styles'; import {Modal, Backdrop, Fade, Typography} from '@material-ui/core'; import {recetaContext} from '../context/recetasContext'; const useStyles = makeStyles((theme) => ({ modal: { display: 'flex', alignItems: 'center', justifyContent: 'center', width: 500, margin: '0 auto', }, paper: { backgroundColor: theme.palette.background.paper, boxShadow: theme.shadows[5], padding: theme.spacing(2, 4, 3), }, })); export default function ModalDetalle ({setModal}) { const {setIdReceta, datosReceta, setDatosReceta} = useContext(recetaContext); const classes = useStyles(); const [open, setOpen] = useState(true); const handleClose = () => { setOpen(false); }; const detalles = () => { if (Object.keys(datosReceta).length !== 0) { console.log(datosReceta.drinks[0]); } } return ( <div> <Modal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" className={classes.modal} open={open} onClose={() => {handleClose(); setDatosReceta({}); setIdReceta(null); setModal(false);}} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={open}> <div style={{display:'flex', justifyContent:'center', flexDirection:'column', alignItems:'center'}} className={classes.paper}> <Typography style={{marginBottom:15, textAlign:'center'}} variant="h3" id="transition-modal-title">{datosReceta.strDrink}</Typography> <img style={{width:350, height:350}} src={datosReceta.strDrinkThumb}></img> <Typography style={{marginTop:10}} variant="h5" id="transition-modal-description">{datosReceta.strGlass}</Typography> <Typography style={{textAlign:'center'}} variant="subtitle1" id="transition-modal-description">Intructions: {datosReceta.strInstructions}</Typography> </div> </Fade> </Modal> </div> ); }
/* eslint-disable react/prop-types */ import { Component } from "react"; export default class LoadPage extends Component { render() { // eslint-disable-next-line react/prop-types const { pdfDoc, pageNum, pageLoaded } = this.props; if (pdfDoc) { // eslint-disable-next-line react/prop-types // eslint-disable-next-line promise/catch-or-return pdfDoc.getPage(pageNum).then((page) => { pageLoaded(page); return true; }); } return null; } }
const initialState = [ { name: 'Metrics', path: '/' }, { name: 'Geospatial', path: '/geo' }, { name: 'View Data', path: '/data' } ]; export const navigation = (state = initialState) => { return state; }; export default navigation;
const { paginationResolvers } = require('@limit0/mongoose-graphql-pagination'); const userAttributionFields = require('./user-attribution'); const Template = require('../../models/template'); module.exports = { /** * */ Template: { ...userAttributionFields, }, /** * */ TemplateConnection: paginationResolvers.connection, /** * */ Query: { /** * */ template: (root, { input }, { auth }) => { auth.check(); const { id } = input; return Template.strictFindActiveById(id); }, /** * */ allTemplates: (root, { pagination, sort }, { auth }) => { auth.check(); const criteria = { deleted: false }; return Template.paginate({ criteria, pagination, sort }); }, /** * */ searchTemplates: (root, { pagination, phrase }, { auth }) => { auth.check(); const filter = { term: { deleted: false } }; return Template.search(phrase, { pagination, filter }); }, /** * */ autocompleteTemplates: (root, { pagination, phrase }, { auth }) => { auth.check(); const filter = { term: { deleted: false } }; return Template.autocomplete(phrase, { pagination, filter }); }, }, /** * */ Mutation: { /** * */ createTemplate: (root, { input }, { auth }) => { auth.check(); const { payload } = input; const template = new Template(payload); template.setUserContext(auth.user); return template.save(); }, /** * */ updateTemplate: async (root, { input }, { auth }) => { auth.check(); const { id, payload } = input; const template = await Template.strictFindActiveById(id); template.set(payload); template.setUserContext(auth.user); return template.save(); }, /** * */ deleteTemplate: async (root, { input }, { auth }) => { auth.check(); const { id } = input; const template = await Template.strictFindActiveById(id); await template.softDelete(); return 'ok'; }, }, };
import RestfulDomainModel from '../base/RestfulDomainModel' /** * 仓库 **/ class Model extends RestfulDomainModel { async pageNoAuth(pageNo, pageSize, filter, sort) { return await this.post(`${this.baseUrl}/pageNoAuth`, { pageNo, pageSize, filter, sort }) } } export default new Model([ { id: { name: 'ID', dataOnly: true }}, { name: { name: '仓库名称' }}, { tenantId: { name: '租户', dataOnly: true }}, { description: { name: '描述' }}, { address: { name: '地址' }}, { deleted: { name: '是否删除', dataOnly: true }} ], '/ecommerse/warehouse')
/** * info:生成静态日历 author:田鑫龙 date:2017-05-05 */ (function () { var workTime = function (id, options) { this.monthDay = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; this.init(id); this.render(); this.options = options || {}; options && this.renderWrokTime(options); }; workTime.prototype = { init: function (id) { var dayTime = 24 * 60 * 60 * 1000;//1天 var step = 58 * dayTime;//58天 //var date = new Date(new Date().getTime() + dayTime); var date = new Date(); var endDate = new Date(date.getTime() + step); this.params = { date: date, startYear: date.getFullYear(), startMonth: date.getMonth() + 1, startDay: date.getDate(), endYear: endDate.getFullYear(), endMonth: endDate.getMonth() + 1, endDay: endDate.getDate() }; this.params.startString = this.params.startYear + '-' + (this.params.startMonth >= 10 ? this.params.startMonth : ('0' + this.params.startMonth)) + '-' + (this.params.startDay >= 10 ? this.params.startDay : ('0' + this.params.startDay)); this.params.endString = this.params.endYear + '-' + (this.params.endMonth >= 10 ? this.params.endMonth : ('0' + this.params.endMonth)) + '-' + (this.params.endDay >= 10 ? this.params.endDay : ('0' + this.params.endDay)); this.el = document.getElementById(id); this.today = date; this.dayTime = dayTime; }, getFebruary: function (year) {// 判断闰年 if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) { return 29; } return 28; }, runNian: function (year) {// 判断闰年 if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) { return true; } return false; }, getFirstDay: function (year, month) {// 判断某年某月的1号是星期几 var allDay = 0, y = year - 1, i = 1; allDay = y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + 1; for (; i < month; i++) { switch (i) { case 1: allDay += 31; break; case 2: if (this.runNian(year)) { allDay += 29; } else { allDay += 28; } break; case 3: allDay += 31; break; case 4: allDay += 30; break; case 5: allDay += 31; break; case 6: allDay += 30; break; case 7: allDay += 31; break; case 8: allDay += 31; break; case 9: allDay += 30; break; case 10: allDay += 31; break; case 11: allDay += 30; break; case 12: allDay += 31; break; } } return allDay % 7; }, renderCalendar: function (year, month) {// 显示日历 var i = 0, monthDay = this.monthDay[month - 1] || this.getFebruary(), html = [], _classname = "", firstDay = this.getFirstDay(year, month); html.push('<table class="his-calendar-table">'); html.push('<caption class="calendar-caption">'); //html.push('<div class="caption-title caption-sub-title">日期表</div>'); html.push('<div class="caption-title">' + year + '年' + month + '月</div>'); html.push('</caption>'); html.push('<thead>'); html.push('<tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>'); html.push('</thead>'); html.push('<tbody>'); html.push('<tr>'); for (i = 1; i <= firstDay; i++) { html.push('<td class="calendar-day calendar-empty"></td>'); } for (i = 1; i <= monthDay; i++) { var currentString = year + '-' + (month >= 10 ? month : ('0' + month)) + '-' + (i >= 10 ? i : ('0' + i)); if (currentString < this.params.startString || currentString > this.params.endString) { _classname = 'calendar-day calendar-overflow'; } else { _classname = 'calendar-day calendar-unvalid'; } html.push('<td class="' + _classname + ' $' + currentString + '" data-value="' + currentString + '"><div>' + i + '</div></td>'); firstDay = (firstDay + 1) % 7; if (firstDay === 0 && i !== monthDay) { html.push('</tr><tr>'); } } if (firstDay !== 0) { for (i = firstDay; i < 7; i++) { html.push('<td class="calendar-day calendar-empty"></td>'); } } html.push('</tr>'); html.push('</tbody>'); html.push('</table>'); return html.join(''); }, render: function () { var array = []; if (this.params.endYear === this.params.startYear) { do { array.unshift([this.params.startYear, this.params.endMonth - array.length]); } while (this.params.endMonth - array.length >= this.params.startMonth); } else { while (this.params.endMonth - array.length > 0) { array.unshift([this.params.endYear, this.params.endMonth - array.length]); } var month = 12; while (month - this.params.startMonth >= 0) { array.unshift([this.params.startYear, month--]); } } for (var i = 0, len = array.length; i < len; i++) { var date = array[i]; var div = document.createElement('div'); div.classList.add('his-calendar'); div.innerHTML = this.renderCalendar(date[0], date[1]); this.el.appendChild(div); } }, renderWrokTime: function (options) { if(options.scheduleUrl) { var startDate = this.params.startString, endDate = this.params.endString, that = this; var mask = lyb.showMask(); mask.show(); lyb.ajax(options.scheduleUrl, { type: 'get', dataType: 'json', data: {start: startDate, end: endDate}, success: function (result) { var array = result.data || []; that.iteratorDate(array, options.detailUrl); mask.close(); } }); }else { if(this.options.renderSuccess) { this.options.renderSuccess(); delete this.options.renderSuccess; } } }, iteratorDate: function (array, url) { var telFunction = function(e){ lyb.confirm('当前时间段只能通过电话预约,是否致电010-6064-7090?', { buttons: [{ label: '取消', type: 'default', onClick: function () { } }, { label: '拨打电话', type: 'primary', onClick: function () { window.location.href = 'tel: 010-6064-7090'; } }] }); }; var scheduleFunction = function(e){ window.location.href = url + '&date=' + this.dataset.value; }; var combineFunction = function(e){ var value = this.dataset.value; var telHospital = this.dataset.telhospital; var schduleHopital = this.dataset.schdulehopital; var confirm = new weui.confirm(value + '<br>'+ telHospital +':只能电话预约<br>'+ schduleHopital +':可以微信预约', { buttons: [{ label: '电话约' + telHospital, type: 'default', onClick: function () { window.location.href = 'tel: 010-6064-7090'; } }, { label: '微信约' + schduleHopital, type: 'primary', onClick: function () { window.location.href = url + '&date=' + value; } }] }); jQuery('.weui-dialog__bd').append('<span class="lyb-mock-close" style="position: absolute;right: 5px;top: 0;color: #c03e3e;"></span>') jQuery('.lyb-mock-close').click(function () { confirm.hide(); }) }; for (var i = 0, len = array.length; i < len; i++) { var item = array[i]; var app = this.el.querySelector('.\\$' + item.date); app.setAttribute('vAlign', 'bottom'); var border = app.querySelector('.hospital-border'); if (!border) { border = document.createElement('div'); border.classList.add('hospital-border'); app.appendChild(border); } var status = document.createElement('div'); status.classList.add('lest'); status.classList.add('font10'); status.style.fontSize = '10px'; status.innerText = item.hospitalName; if (Number(item.limit) <= 0) { status.classList.add('CCCCCC-bg'); app.classList.remove('calendar-valid'); app.classList.add('calendar-unvalid'); } else if (item.isFirstNumLimit || item.date === lyb.formatDate(new Date(this.today.getTime() + this.dayTime), 'yyyy-mm-dd') && Number(lyb.formatDate(this.today, 'hh')) >= 18 || item.date === lyb.formatDate(new Date(this.today.getTime()), 'yyyy-mm-dd')) {// 今天18点前只能电话预约明天 status.classList.add('E6A85F-bg'); app.classList.add('calendar-valid'); app.classList.add('only-phone'); jQuery(app).attr('data-telhospital', item.hospitalName); app.classList.remove('calendar-unvalid'); if(app.classList.contains('can-schedule')){ //如果当前日期已经有了预约标志 app.removeEventListener('click', scheduleFunction); app.addEventListener('click', combineFunction); }else{ app.addEventListener('click', telFunction); } } else { status.classList.add('A3C37A-bg'); app.classList.add('calendar-valid'); app.classList.add('can-schedule'); app.classList.remove('calendar-unvalid'); jQuery(app).attr('data-schdulehopital', item.hospitalName); if (url) { if(app.classList.contains('only-phone')){ //如果当前日期已经有了打电话标志 app.removeEventListener('click', telFunction); app.addEventListener('click', combineFunction); }else{ app.addEventListener('click', scheduleFunction); } } } border.appendChild(status); } if(this.options.renderSuccess) { this.options.renderSuccess(); delete this.options.renderSuccess; } } }; window.workTime = workTime; })();
(function (angular) { function jediListController ($scope, jediListService, jediAddService) { var that = this; $scope.search = ''; $scope.chave = 'QfSwYoD1aGlFqGlAnUGqfTpzbc8Lr3Z4Hzubjw6Ex3kUE-wyHjSeCDwC-k8P93y5LOR4RpNRyE19MJtKK6U0L1aQZheXnWF0Co0EMBlXPek3h-ktg5n0BknAV361jUMnCz4xsrgPuyyhzTFPj9Gc5Iaihj6bXHz6EmOPbp_5fqETsSbTjW0BWlLmZbI2uwZrVM-sZUqYnJnFsM0oi-_NFunDRN_XFoBomIsr0CvfgZ18AGEFUJg2k0wTFK-MK_b4GELv-zSbo7-3tEww2Vd97Q'; that.selectedRow = null; that.setSelected = function (selectedDateRow) { that.selectedRow = selectedDateRow; }; function init(){ jediListService.load().then(function(data){ that.jediObj = data; jediListService.loadStatus().then(function(data){ that.status = data; getStatus(); }); }); } function getStatus(){ for(var j = 0; j < that.jediObj.length; j++){ for(var s = 0; s < that.status.length; s++){ if(parseInt(that.jediObj[j].status) === that.status[s].id){ that.jediObj[j].status_name = that.status[s].status_name; } } } } that.addJedi = function (id, type) { jediAddService.openAddJedi(id, type); } init(); that.remove = function (id) { jediListService.remove(id).then(function (data) { }) } that.deleteJedi = function(jedi){ jediListService.deleteJedi(jedi); } that.openDeleteModal = function(jedi){ jediListService.openDeleteModal(jedi); } }; jediListController.$inject = ['$scope', 'jediListService', 'jediAddService']; app.controller('jediListController', jediListController); })(angular);
import React from 'react'; const Masterclassform = (props) => { return ( <form onSubmit={props.getMasterclass}> <h5>Masterclass id:</h5> <input type="text" name="id"/> <button>ok</button> <h6>*this will be removed later and will use the id of the signed in Masterclass or GET BY ID Will BE REMOVED AT ALL SINCE THERE IS NO PROFILE FOR A MASTERCLASS </h6> </form> ); } export default Masterclassform;
import { StatusBar } from 'expo-status-bar'; import React, { useEffect } from 'react'; import { NavigationContainer, DefaultTheme as NavigationDefaultTheme, DarkTheme as NavigationDarkTheme } from '@react-navigation/native'; import { DrawerContent } from './DrawerContent'; import { createDrawerNavigator } from '@react-navigation/drawer'; import MainTabScreen from './MainTabScreen'; import SupportScreen from './SupportScreen'; import SettingsScreen from './SettingScreen'; import BookmarkScreen from './BookmarkScreen'; import InfoScreen from './InfoScreen'; const Drawer = createDrawerNavigator(); const RootTabScreen = () => { return( <Drawer.Navigator drawerContent={props => <DrawerContent {...props} />}> <Drawer.Screen name="HomeDrawer" component={MainTabScreen} /> <Drawer.Screen name="SupportScreen" component={SupportScreen} /> <Drawer.Screen name="SettingScreen" component={SettingsScreen} /> <Drawer.Screen name="BookmarkScreen" component={BookmarkScreen} /> <Drawer.Screen name="InfoScreen" component={InfoScreen} /> </Drawer.Navigator> ); } export default RootTabScreen;
'use strict'; var isUtils = module.exports = { /* return false for null but typeof null === 'object' // <- true */ isObject: function (value) { return value !== null && typeof value === 'object'; }, isPlainObject: function (value) { return isUtils.isObject(value) && value.constructor.name === 'Object'; }, isFunction: function (value) { return typeof value === 'function'; }, isUndefined: function (value) { return typeof value === 'undefined'; }, isDefined: function (value) { return typeof value !== 'undefined'; }, isPresent: function (value) { return value !== null && isUtils.isDefined(value); } };
import 'react-datepicker/dist/react-datepicker.css'; import React, { useState, useEffect, } from 'react'; import { useForm, Controller, } from 'react-hook-form'; import Select from 'react-select'; import AsyncSelect from 'react-select/async'; import ReactDatePicker from 'react-datepicker'; import { Redirect } from 'react-router'; import { useSelector } from 'react-redux'; import TasksService from '../../services/tasks.service'; import CitiesService from '../../services/cities.service'; import handleError from '../../helpers/errors'; import ErrorMessage from '../forms/ErrorMessage'; const ACTION = { createTask: { documentTitle: 'Добавление задачи в план', formTitle: 'Заполните поля', }, updateTask: { documentTitle: 'Редактирование задачи', formTitle: 'Редактирование задачи', }, } const REQUIRED = 'Обязательное поле'; const TaskService = new TasksService(); const CityService = new CitiesService(); const prepareData = (formData) => { let data = formData; let dd = data.due_date; data.due_date = `${dd.getFullYear()}-${dd.getMonth()+1}-${dd.getDate()}`; data.site = data.site.value; data.customer = data.customer.value; if (!data.estimated_time) { delete data.estimated_time; } let directions = []; data.directions.forEach(item => directions.push(item.value)); data.directions = directions; if (!data.execution_variant) { delete data.execution_variant; } else { data.execution_variant = data.execution_variant.value; } return (data); } const TaskCreateUpdate = (props) => { const actionType = props.action; const taskId = props.match.params.id; const actionParams = ACTION[actionType] const currentUser = useSelector(state => state.auth.user); const directions = useSelector(state => state.taskOptions.directions); const executionVariants = useSelector(state => state.taskOptions.executionVariants); const [taskObj, setTaskObj] = useState(); const [customers, setCustomers] = useState([]); const [sites, setSites] = useState([]); const [cityId, setCityId] = useState(null); const [customerObj, setCustomerObj] = useState(); const [errorMessage, setErrorMessage] = useState(''); const [pathToRedirect, setPathToRedirect] = useState(null) const { control, register, handleSubmit, reset, setValue, formState: { errors } } = useForm(); document.title = actionParams.documentTitle; const retrieveTask = (id) => { console.log('Retrieve task!'); TaskService.getTask(id) .then((response) => { setTaskObj(response.data); }) .catch((error) => { console.log(error) } ); } const retrieveCustomers = () => { console.log('Retrieve customers'); TaskService.getCustomers() .then(response => { let customersList = []; response.data.results.forEach(element => { customersList.push( { value: element.id, label: element.official_name, } ) }); setCustomers(customersList); }) .catch(e => { console.log(e); }); } const retrieveSites = () => { console.log('Retrieve sites'); let params = { customerId: customerObj.value, cityId: null, } if (cityId) { params.cityId = cityId; } TaskService.getSites(params) .then(response => { let sitesList = []; response.data.results.forEach(element => { sitesList.push( { value: element.id, label: `${element.name} (${element.city.alternate_names})`, } ) }); setSites(sitesList); }) .catch(e => { console.log(e); } ); } const retrieveCities = (searchQuery) => { console.log('Retrieve cities'); let citiesList = []; CityService.searchByName(searchQuery) .then(response => { response.data.results.forEach(element => { citiesList.push( { value: element.id, label: element.alternate_names, } ) }); }) .catch(e => { console.log(e); }); return(citiesList); } const loadCityOptions = (inputValue, callback) => { setTimeout(() => { callback(retrieveCities(inputValue)); }, 100); }; const onSubmit = data => { prepareData(data); if (taskObj) { // Update existing object data.city = cityId; data.action_type = 'full_update'; console.log(data); TaskService.updateTask(taskObj.id, data) .then(response => { console.log(response.data); setErrorMessage(''); alert('Задача успешно обновлена'); setPathToRedirect(`/task/${response.data.id}/`); }) .catch((error) => { console.log(error.response) setErrorMessage(handleError(error.response)); } ); } else { // Create new object TaskService.createTask(data) .then(response => { console.log(response.data); setErrorMessage(''); setPathToRedirect(`/task/${response.data.id}/`); }) .catch((error) => { console.log(error.response) setErrorMessage(handleError(error.response)); } ); } } useEffect(() => { retrieveCustomers(); if (taskId) { retrieveTask(taskId); } }, []); useEffect(() => { if (taskObj) { console.log('Setting form values'); const customerObj = { value: taskObj.site.customer.id, label: taskObj.customer, } let directionsValue = []; const taskDirections = taskObj.directions.map((direction) => { directionsValue.push( { value: direction.id, label: direction.name, } ); }); let ev = null; if (taskObj.execution_variant) { ev = { value: taskObj.execution_variant.id, label: taskObj.execution_variant.name, } } reset({ customer: customerObj, site: { value: taskObj.site.id, label: `${taskObj.site.name} (${taskObj.city})`, }, directions: directionsValue, due_date: new Date(taskObj.due_date), srv_title: taskObj.srv_title, description: taskObj.description, estimated_time: taskObj.estimated_time, execution_variant: ev, }); setCustomerObj(customerObj) } }, [taskObj]); useEffect(() => { setValue('site', null); if (customerObj) { retrieveSites(); } }, [cityId, customerObj]) return( <div className='col-md-3 m-auto'> { pathToRedirect && <Redirect to={{ pathname: pathToRedirect, workTask: taskObj, }} /> } { currentUser && currentUser.role === 'engineer' ? <>Redirect to 403</> : <> <h3 className='text-center'> {actionParams.formTitle} {taskObj && taskObj.srv_number} </h3> <div className='card card-container'> <img // @TODO! Img src="//ssl.gstatic.com/accounts/ui/avatar_2x.png" alt="profile-img" className='profile-img-card' /> <form onSubmit={handleSubmit(onSubmit)}> <div className='form-group'> <label htmlFor='city'>Город</label> <Controller render={ ({ field: { onChange, value } }) => ( <AsyncSelect cacheOptions isClearable loadOptions={loadCityOptions} defaultOptions onChange={(e) => { if (e) { setCityId(e.value); } else { setCityId(null); } }} />) } name='city' control={control} defaultValue={null} /> <div>{errors.city?.message}</div> </div> <div className='form-group'> <label htmlFor='customer'>Заказчик</label> <Controller render={ ({ field: { onChange, value } }) => ( <Select options={customers} onChange={(e) => { setCustomerObj(e); onChange(e); }} value={value} /> ) } name='customer' control={control} defaultValue={null} rules={ { required: {value: true, message: REQUIRED }} } /> <ErrorMessage message={errors.customer} /> </div> <div className='form-group'> <label htmlFor='site'>Площадка</label> <Controller render={({ field: { onChange, value } }) => ( <Select isClearable options={sites} onChange={(e) => { onChange(e); }} value={value} /> )} name='site' control={control} defaultValue={null} rules={ { required: {value: true, message: REQUIRED }} } /> <ErrorMessage message={errors.site} /> </div> <div className='form-group'> <label htmlFor='directions'>Направления</label> <Controller render={({ field: { onChange, value } }) => ( <Select isMulti isClearable options={directions} onChange={(e) => { onChange(e); console.log(e); }} value={value} /> )} control={control} defaultValue={null} name='directions' rules={ { required: {value: true, message: REQUIRED }} } /> <ErrorMessage message={errors.directions} /> </div> <div className='form-group'> <label htmlFor='due_date'>Due date</label> <Controller render={({ field: { onChange, onBlur, value } }) => ( <ReactDatePicker onChange={onChange} onBlur={onBlur} selected={value} showWeekNumbers dateFormat='yyyy-MM-dd' />) } name='due_date' control={control} rules={ { required: {value: true, message: REQUIRED }} } /> <ErrorMessage message={errors.due_date} /> </div> <div className='form-group'> <label htmlFor='srv_title'>Название запроса</label> <input type='text' className='form-control' {...register( 'srv_title', { required: {value: true, message: REQUIRED }} ) } /> <ErrorMessage message={errors.srv_title} /> </div> <div className='form-group'> <label htmlFor='description'>Состав работ</label> <textarea className='form-control' {...register( 'description', { required: {value: true, message: REQUIRED }} ) } /> <ErrorMessage message={errors.description} /> </div> <div className='form-group'> <label htmlFor='estimated_time'>Ожидаемые трудозатраты, ч.</label> <input className='form-control' type='number' step='0.01' {...register( 'estimated_time', { min: { value: 0, message: 'Значение должно быть >= 0' }, max: { value: 40, message: 'Значение должно быть <= 40' } } ) } /> </div> {errors.estimated_time && <div className='form-group alert-danger'> {errors.estimated_time.message} </div> } <div className='form-group'> <label htmlFor='execution_variant'>Особенности исполнения</label> <Controller render={({ field: { onChange, value } }) => ( <Select isClearable options={executionVariants} onChange={(e) => { onChange(e); console.log(e); }} value={value} /> )} control={control} defaultValue={null} name='execution_variant' /> <ErrorMessage message={errors.execution_variant} /> </div> {errorMessage && ( <div className='form-group'> <div className='alert alert-danger' role='alert'> {errorMessage} </div> </div> )} <div className='form-group'> <input type='submit' value='Сохранить' className='btn btn-dark btn-block' /> </div> </form> </div> </> } </div> ); } export default TaskCreateUpdate;
(function () { angular.module('Application').controller('DashboardController', ['$scope', '$routeParams', '$location', '$window', '$mdDialog', 'appService', 'dashboardService', function ($scope, $routeParams, $location, $window, $mdDialog, appService, dashboardService) { $scope.showLoader = false; $scope.event = angular.copy(appService.event); if ($scope.event && ($scope.event._id == null || $scope.event._id == '')) $location.path('/event'); $scope.load_data = function() { $scope.showLoader = true; // Tweet Count dashboardService.getTweetCount($scope.event._id) .success(function (data) { $scope.tweetCount = data.aggregations.tweetCount.value; }) .error(function (error) { }) .finally(function () { }); // Positive Tweet Count dashboardService.getSentimentTweetCount($scope.event._id, "POSITIVE") .success(function (data) { $scope.positiveTweetCount = data.aggregations.tweetCount.value; }) .error(function (error) { }) .finally(function () { }); // Neutral Tweet Count dashboardService.getSentimentTweetCount($scope.event._id, "NEUTRAL") .success(function (data) { $scope.neutralTweetCount = data.aggregations.tweetCount.value; }) .error(function (error) { }) .finally(function () { }); // Negative Tweet Count dashboardService.getSentimentTweetCount($scope.event._id, "NEGATIVE") .success(function (data) { $scope.negativeTweetCount = data.aggregations.tweetCount.value; }) .error(function (error) { }) .finally(function () { }); // Unique User Count dashboardService.getUniqueUsers($scope.event._id) .success(function (data) { $scope.uniqueUserCount = data.aggregations.tweetCount.value; }) .error(function (error) { }) .finally(function () { }); // English Language Tweet Ratio dashboardService.getLanguageTweetCount($scope.event._id, 'en') .success(function (data) { $scope.englishLanguageTweetCount = data.aggregations.tweetCount.value; $scope.englishLanguageTweetRatio = data.aggregations.tweetCount.value / $scope.tweetCount * 100; }) .error(function (error) { }) .finally(function () { }); // Get Gender Tweet Count MALE dashboardService.getGenderSentimentTweetCount($scope.event._id, "MALE", "POSITIVE") .success(function (data) { $scope.malePositiveTweetCount = data.aggregations.tweetCount.value; dashboardService.getGenderSentimentTweetCount($scope.event._id, "MALE", "NEGATIVE") .success(function (data) { $scope.maleNegativeTweetCount = data.aggregations.tweetCount.value; $scope.maleSentimentRatio = $scope.malePositiveTweetCount / ($scope.malePositiveTweetCount + $scope.maleNegativeTweetCount) * 100; }) .error(function (error) { }) .finally(function () { }); }) .error(function (error) { }) .finally(function () { }); // Get Gender Tweet Count FEMALE dashboardService.getGenderSentimentTweetCount($scope.event._id, "FEMALE", "POSITIVE") .success(function (data) { $scope.femalePositiveTweetCount = data.aggregations.tweetCount.value; dashboardService.getGenderSentimentTweetCount($scope.event._id, "FEMALE", "NEGATIVE") .success(function (data) { $scope.femaleNegativeTweetCount = data.aggregations.tweetCount.value; $scope.femaleSentimentRatio = $scope.femalePositiveTweetCount / ($scope.femalePositiveTweetCount + $scope.femaleNegativeTweetCount) * 100; }) .error(function (error) { }) .finally(function () { }); }) .error(function (error) { }) .finally(function () { }); // Get Last Sentiment Tweet MALE dashboardService.getGenderSentimentLastTweet($scope.event._id, "MALE", "POSITIVE") .success(function (data) { if (data.hits.hits.length == 0) return; // no data yet $scope.lastMalePositiveTweet = data.hits.hits[0]._source; dashboardService.getGenderSentimentLastTweet($scope.event._id, "MALE", "NEGATIVE") .success(function (data) { $scope.lastMaleNegativeTweet = data.hits.hits[0]._source; }) .error(function (error) { }) .finally(function () { }); }) .error(function (error) { }) .finally(function () { }); // Get Last Sentiment Tweet FEMALE dashboardService.getGenderSentimentLastTweet($scope.event._id, "FEMALE", "POSITIVE") .success(function (data) { if (data.hits.hits.length == 0) return; // no data yet $scope.lastFemalePositiveTweet = data.hits.hits[0]._source; dashboardService.getGenderSentimentLastTweet($scope.event._id, "FEMALE", "NEGATIVE") .success(function (data) { $scope.lastFemaleNegativeTweet = data.hits.hits[0]._source; }) .error(function (error) { }) .finally(function () { }); }) .error(function (error) { }) .finally(function () { }); // Get Recent Tweets dashboardService.getRecentTweets($scope.event._id, 10) .success(function (data) { if (data.hits.hits.length == 0) return; // no data yet $scope.recentTweets = []; for (var i=0; i<data.hits.hits.length; i++) { $scope.recentTweets.push(data.hits.hits[i]._source); } }) .error(function (error) { }) .finally(function () { $scope.showLoader = false; }); // Get Top 10 Tweeters dashboardService.getTopTweeters($scope.event._id) .success(function (tweeters) { $scope.topTweeters = []; for (var i=0; i<tweeters.aggregations.tweetCount.buckets.length; i++) { if (i==10) break; dashboardService.getTweeterPicWithCount($scope.event._id, tweeters.aggregations.tweetCount.buckets[i].key, tweeters.aggregations.tweetCount.buckets[i].doc_count) .then(function (data) { $scope.topTweeters.push({ tweet_profile_image_url: data.tweet_profile_image_url, doc_count: data.doc_count }); }, function (error) { }); } }) .error(function (error) { }) .finally(function () { $scope.showLoader = false; }); } if ($scope.event && ($scope.event._id != null && $scope.event._id != '')) $scope.load_data(); }]); })();
function arrayPlusArray(arr1, arr2) { //return arr1 + arr2; //something went wrong var sumOne = 0; var sumTwo = 0; for ( var i = 0; i < arr1.length;i++) { sumOne = sumOne + arr1[i]; } console.log(sumOne); for ( var y = 0; y < arr2.length;y++) { sumTwo = sumTwo + arr2[y]; } console.log(sumTwo); var result = sumOne + sumTwo; return result; }
import Vue from 'vue'; import NProgress from './components/progress/nprogress'; // eslint-disable-next-line import { Row, Col, Loading, Swipe, SwipeItem, Uploader, Icon, Tabbar, TabbarItem, NavBar, Lazyload, Toast, Field, } from 'vant'; import 'amfe-flexible'; import App from './App.vue'; import router from './router'; import store from './store'; import ajaxPlugin from './plugins/ajax/index'; import './registerServiceWorker'; import './assets/nprogress.css'; import './assets/reset.css'; Vue.use(Row).use(Col); Vue.use(Loading); Vue.use(Swipe).use(SwipeItem); Vue.use(Uploader); Vue.use(Icon); Vue.use(Tabbar).use(TabbarItem); Vue.use(NavBar); // options 为可选参数,无则不传 Vue.use(Lazyload, { loading: '/img/no-img.jpeg', }); Vue.use(Toast); Vue.use(Field); // Vue.use(ajaxPlugin); Vue.prototype.$http = ajaxPlugin; // console.log(ajax) Vue.config.productionTip = false; NProgress.configure({ showSpinner: false, trickleSpeed: 200 }); router.beforeEach((to, from, next) => { NProgress.start(); next(); }); router.afterEach(() => { NProgress.done(); }); new Vue({ router, store, // eslint-disable-next-line render: (h) => h(App), }).$mount('#app');
export default { components: { }, props: ['note'], template: ` <li> <iframe width="200" height="100" :src="'https://www.youtube.com/embed/'+note.info.videoUrl" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </li> ` }
$(function() { // 瀑布流插件 $('#gallery-wrapper').pinterest_grid({ no_columns: 3, padding_x: 10, padding_y: 10, margin_bottom: 50, }) var layer = layui.layer var laypage = layui.laypage; // 顶部背景图菜单栏点击高亮 $('.tab-menu').on('click', 'a', function() { $('.tab-menu').children().children('a').removeClass('sizeColor') $(this).addClass('sizeColor') }) // 登录请求 // login() // function login() { // $.ajax({ // method: 'POST', // url: 'http://139.9.143.69:8001/oauth/login', // data: { // phone: '15393176778', // // phone: '13622779577', // password: '123456', // }, // success: function(res) { // // console.log(res); // localStorage.setItem('uid', res.data) // }, // }) // } // 调用获取个人信息 getUserInfo() // 获取个人信息 function getUserInfo() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/users/info', headers: { uid: localStorage.getItem('uid'), }, success: function(res) { if (res.code !== 0) return layer.msg('获取个人信息失败!') // 获取头像 var picHtml = template('templatePic', res.data) $('.photo').html(picHtml) // 获取个人电话QQ微信 var Phone = template('templatePhone', res.data) $('.info-list').html(Phone) // 获取昵称 var nameHtml = template('templateName', res.data) $('.username').html(nameHtml) }, }) } //  验证登录状态 $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/users/info', headers: { uid: localStorage.getItem('uid'), }, complete: function(res) { // console.log(res.status); if (res.status === 401) { // 清空本地存储中的 uid localStorage.removeItem('uid') location.href = 'index.html' } }, }) // 获取个人中心首页作品 var Works_num = '1' // 当前页 var Works_size = '12' //每页显示条数 getUserWorks() function getUserWorks() { var menuHTML = ` <a href="javascript:;" class="color_orange" id="all">全部</a> <a href="javascript:;" id="design">平面广告</a> <a href="javascript:;" id="photography">摄影</a> <a href="javascript:;" id="UI">UI设计</a> <a href="javascript:;" id="TB">淘宝电商</a>` $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/personal/works', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: Works_num, pageSize: Works_size }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取用户作品失败!') $('.menu-list').html(menuHTML) if (res.data.rows == '') { var textHtml = `<h2 class="noData">暂无作品</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var userWorksHtml = template('templateUserWorks', res) $('#gallery-wrapper').html(userWorksHtml) $(window).resize() renderPage(res.data.total) } } }) } // 分页 function renderPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: Works_size, curr: Works_num, layout: ['count', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 Works_num = obj.curr //首次不执行 if (!first) { getUserWorks() } } }); } // 点击首页 显示个人中心首页 $('#create').on('click', function() { getUserWorks() }) // 切换图片区域平面设计背景色 $('.menu-list').on('click', 'a', function() { // console.log($(this).index()); $(this).addClass('color_orange').siblings().removeClass('color_orange') }) // 获取全部分类 $('.menu-list').on('click', '#all', function() { $('#create').click() }) // 获取平面设计图片分类 $('.menu-list').on('click', '#design', function() { design() }) var design_num = '1' // 当前页 var design_size = '12' //每页显示条数 function design() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/personal/works', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: design_num, pageSize: design_size, category_id: '9' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.rows == '') { var textHtml = `<h2 class="noData">暂无作品</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var designHtml = template('templateUserWorks', res) $('#gallery-wrapper').html(designHtml) $(window).resize() designPage(res.data.total) } } }) } // 分页 function designPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: design_size, curr: design_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 design_num = obj.curr //首次不执行 if (!first) { design() } } }); } $('.menu-list').on('click', '#photography', function() { photography() }) // 获取摄影分类 var photography_num = '1' // 当前页 var photography_size = '12' //每页显示条数 function photography() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/personal/works', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: photography_num, pageSize: photography_size, category_id: '1' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.rows == '') { var textHtml = `<h2 class="noData">暂无作品</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var photographyHtml = template('templateUserWorks', res) $('#gallery-wrapper').html(photographyHtml) $(window).resize() photographyPage(res.data.total) } } }) } // 分页 function photographyPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: photography_size, curr: photography_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 photography_num = obj.curr //首次不执行 if (!first) { photography() } } }); } // UI设计分类 $('.menu-list').on('click', '#UI', function() { userUI() }) var UI_num = '1' // 当前页 var UI_size = '12' //每页显示条数 function userUI() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/personal/works', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: UI_num, pageSize: UI_size, category_id: '11' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.rows == '') { var textHtml = `<h2 class="noData">暂无作品</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var UIHtml = template('templateUserWorks', res) $('#gallery-wrapper').html(UIHtml) $(window).resize() uiPage(res.data.total) } } }) } // 分页 function uiPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: UI_size, curr: UI_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 UI_num = obj.curr //首次不执行 if (!first) { userUI() } } }); } // 淘宝分类 $('.menu-list').on('click', '#TB', function() { userTB() }) var TB_num = '1' var TB_size = '12' function userTB() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/personal/works', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: TB_num, pageSize: TB_size, category_id: '10' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.rows == '') { var textHtml = `<h2 class="noData">暂无作品</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var TBHtml = template('templateUserWorks', res) $('#gallery-wrapper').html(TBHtml) $(window).resize() tbPage(res.data.total) } } }) } // 分页 function tbPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: TB_size, curr: TB_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 TB_num = obj.curr //首次不执行 if (!first) { userTB() } } }); } // 鼠标经过显示 按钮 $('#gallery-wrapper').on('mouseover', '.white-panel', function() { $(this).children('.top-btn').stop().fadeIn(300) }) // 鼠标离开 $('#gallery-wrapper').on('mouseout', '.white-panel', function() { $(this).children('.top-btn').stop().fadeOut(300) }) // 鼠标经过按钮字体颜色改变 // $('#gallery-wrapper').on('mouseover', 'button', function() { // $(this).addClass('color_orange2') // }) // $('#gallery-wrapper').on('mouseout', 'button', function() { // $(this).removeClass('color_orange2') // }) // 经过图片区域底部 显示更多按钮颜色变化 $('.img-list').on('mouseover', 'button', function() { $(this).addClass('color_orange2') }) $('.img-list').on('mouseout', 'button', function() { $(this).removeClass('color_orange2') }) // 点击收藏按钮获取用户收藏列表 $('#userCollect').on('click', function() { getUserCollect() }) var favorites_num = '1' var favorites_size = '12' // 获取用户收藏请求 function getUserCollect() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/works/favorites', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: favorites_num, pageSize: favorites_size }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取用户收藏列表失败!') var CollectMenu = ` <a href="javascript:;" class="color_orange" id="all_favorites">全部</a> <a href="javascript:;" id="design_favorites">平面广告</a> <a href="javascript:;" id="photography_favorites">摄影</a> <a href="javascript:;" id="UI_favorites">UI设计</a> <a href="javascript:;" id="TB_favorites">淘宝电商</a>` $('.menu-list').html(CollectMenu) if (res.data.favourites == '') { var textHtml = `<h2 class="noData">暂无收藏记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var collectHtml = template('templateCollect', res.data) $('#gallery-wrapper').html(collectHtml) $(window).resize() CollectPage(res.data.total) } }, }) } // 分页 function CollectPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: favorites_size, curr: favorites_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 favorites_num = obj.curr //首次不执行 if (!first) { getUserCollect() } } }); } // 获取用户收藏全部分类 $('.menu-list').on('click', '#all_favorites', function() { $('#userCollect').click() }) // 获取用户收藏平面设计图片分类 $('.menu-list').on('click', '#design_favorites', function() { design_favorites() }) var design_favorites_num = '1' var design_favorites_size = '12' function design_favorites() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/works/favorites', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: design_favorites_num, pageSize: design_favorites_size, category_id: '9' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.favourites == '') { var textHtml = `<h2 class="noData">暂无收藏记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var design_favorites = template('templateCollect', res.data) $('#gallery-wrapper').html(design_favorites) $(window).resize() designFavoritesPage(res.data.total) } } }) } // 分页 function designFavoritesPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: design_favorites_size, curr: design_favorites_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 design_favorites_num = obj.curr //首次不执行 if (!first) { design_favorites() } } }); } // 用户收藏摄影分类 $('.menu-list').on('click', '#photography_favorites', function() { photography_favorites() }) var photography_favorites_num = '1' var photography_favorites_size = '12' function photography_favorites() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/works/favorites', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: photography_favorites_num, pageSize: photography_favorites_size, category_id: '1' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.favourites == '') { var textHtml = `<h2 class="noData">暂无收藏记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var photography_favorites = template('templateCollect', res.data) $('#gallery-wrapper').html(photography_favorites) $(window).resize() designFavoritesPage(res.data.total) } } }) } // 分页 function designFavoritesPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: photography_favorites_size, curr: photography_favorites_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 photography_favorites_num = obj.curr //首次不执行 if (!first) { photography_favorites() } } }); } // 用户收藏UI分类 $('.menu-list').on('click', '#UI_favorites', function() { UI_favorites() }) var UI_favorites_num = '1' var UI_favorites_size = '12' function UI_favorites() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/works/favorites', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: UI_favorites_num, pageSize: UI_favorites_size, category_id: '11' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.favourites == '') { var textHtml = `<h2 class="noData">暂无收藏记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var UI_favorites = template('templateCollect', res.data) $('#gallery-wrapper').html(UI_favorites) $(window).resize() uiFavoritesPage(res.data.total) } } }) } // 分页 function uiFavoritesPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: UI_favorites_size, curr: UI_favorites_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 UI_favorites_num = obj.curr //首次不执行 if (!first) { UI_favorites() } } }); } // 用户收藏淘宝电商分类 $('.menu-list').on('click', '#TB_favorites', function() { TB_favorites() }) var TB_favorites_num = '1' var TB_favorites_size = '12' function TB_favorites() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/works/favorites', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: TB_favorites_num, pageSize: TB_favorites_size, category_id: '11' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.favourites == '') { var textHtml = `<h2 class="noData">暂无收藏记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var TB_favorites = template('templateCollect', res.data) $('#gallery-wrapper').html(TB_favorites) $(window).resize() tbFavoritesPage(res.data.total) } } }) } // 分页 function tbFavoritesPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: TB_favorites_size, curr: TB_favorites_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 TB_favorites_num = obj.curr //首次不执行 if (!first) { TB_favorites() } } }); } // 取消收藏 $('#gallery-wrapper').on('click', '#delcancel', function() { var id = $(this).attr('data-index') layer.confirm('是否取消收藏?', { icon: 3, title: '取消收藏' }, function(index) { $.ajax({ method: 'delete', url: 'http://139.9.143.69:8001/usercenter/works/favorites/' + id, headers: { uid: localStorage.getItem('uid'), }, success: function(res) { if (res.code !== 0) return layer.msg('取消失败!') getUserCollect() layer.msg('取消收藏成功!') }, }) layer.close(index) }) }) // 删除个人首页展示的图片 $('#gallery-wrapper').on('click', '#deleteUserImg', function() { var id = $(this).attr('data-index') console.log(id) layer.confirm('确认删除?', { icon: 3, title: '提示' }, function(index) { //do something $.ajax({ method: 'delete', url: 'http://139.9.143.69:8001/usercenter/works/' + id, headers: { uid: localStorage.getItem('uid'), }, success: function(res) { // console.log(res) if (res.code !== 0) return layer.msg('删除失败!') getUserWorks() layer.msg('删除成功!') }, }) layer.close(index) }) }) // 修改 个人作品 $('#gallery-wrapper').on('click', '#alter', function() { var id = $(this).attr('data-id') window.location.href = '/edit.html?id=' + id sessionStorage.setItem('id', id) }) var History_num = '1' var History_size = '12' // 获取个人下载记录 function downLoadHistory() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/download_history', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: History_num, pageSize: History_size }, success: function(res) { console.log(res) if (res.code !== 0) return layer.msg('获取下载记录失败!!') var HistoryMenu = ` <a href="javascript:;" class="color_orange" id="all_download">全部</a> <a href="javascript:;" id="design_download">平面广告</a> <a href="javascript:;" id="photography_download">摄影</a> <a href="javascript:;" id="UI_download">UI设计</a> <a href="javascript:;" id="TB_download">淘宝电商</a>` $('.menu-list').html(HistoryMenu) // 判断data是否有下载记录 if (res.data.downloadHistory == '') { var textHtml = `<h2 class="noData">暂无下载记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var collectHtml = template('templateHistory', res.data) $('#gallery-wrapper').html(collectHtml) $(window).resize() downLoadHistoryPage(res.data.total) } }, }) } // 分页 function downLoadHistoryPage(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: History_size, curr: History_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 History_num = obj.curr //首次不执行 if (!first) { downLoadHistory() } } }); } // 获取记录点击事件 $('#history').on('click', function() { downLoadHistory() }) $('.menu-list').on('click', '#all_download', function() { downLoadHistory() }) // 下载记录 设计分类 $('.menu-list').on('click', '#design_download', function() { design_download() }) var design_download_num = '1' var design_download_size = '12' function design_download() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/download_history', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: design_download_num, pageSize: design_download_size, category_id: '9' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.downloadHistory == '') { var textHtml = `<h2 class="noData">暂无下载记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var design_download = template('templateHistory', res.data) $('#gallery-wrapper').html(design_download) $(window).resize() design_download_Page(res.data.total) } } }) } function design_download_Page(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: design_download_size, curr: design_download_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 design_download_num = obj.curr //首次不执行 if (!first) { design_download() } } }); } // 下载记录 摄影分类 $('.menu-list').on('click', '#photography_download', function() { photography_download() }) var photography_download_num = '1' var photography_download_size = '12' function photography_download() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/download_history', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: photography_download_num, pageSize: photography_download_size, category_id: '1' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.downloadHistory == '') { var textHtml = `<h2 class="noData">暂无下载记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var photography_download = template('templateHistory', res.data) $('#gallery-wrapper').html(photography_download) $(window).resize() photography_download_Page(res.data.total) } } }) } function photography_download_Page(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: photography_download_size, curr: photography_download_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 photography_download_num = obj.curr //首次不执行 if (!first) { photography_download() } } }); } // 下载记录 UI分类 $('.menu-list').on('click', '#UI_download', function() { UI_download() }) var UI_download_num = '1' var UI_download_size = '12' function UI_download() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/download_history', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: UI_download_num, pageSize: UI_download_size, category_id: '11' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.downloadHistory == '') { var textHtml = `<h2 class="noData">暂无下载记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var UI_download = template('templateHistory', res.data) $('#gallery-wrapper').html(UI_download) $(window).resize() UI_download_Page(res.data.total) } } }) } function UI_download_Page(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: UI_download_size, curr: UI_download_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 UI_download_num = obj.curr //首次不执行 if (!first) { UI_download() } } }); } // 下载记录 淘宝电商分类 $('.menu-list').on('click', '#TB_download', function() { TB_download() }) var TB_download_num = '1' var TB_download_size = '12' function TB_download() { $.ajax({ method: 'GET', url: 'http://139.9.143.69:8001/usercenter/download_history', headers: { uid: localStorage.getItem('uid'), }, data: { pageNum: TB_download_num, pageSize: TB_download_size, category_id: '10' }, success: function(res) { // console.log(res); if (res.code !== 0) return layer.msg('获取平面设计列表失败!') if (res.data.downloadHistory == '') { var textHtml = `<h2 class="noData">暂无下载记录</h2>` $('#gallery-wrapper').html(textHtml) $(window).resize() $('#ShowMore').html('') } else { var TB_download = template('templateHistory', res.data) $('#gallery-wrapper').html(TB_download) $(window).resize() TB_download_Page(res.data.total) } } }) } function TB_download_Page(total) { laypage.render({ elem: 'ShowMore', //注意,这里的 test1 是 ID,不用加 # 号 count: total, //数据总数,从服务端得到 limit: TB_download_size, curr: TB_download_num, layout: ['count', 'prev', 'page', 'next', 'skip'], // layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], jump: function(obj, first) { // console.log(obj.curr); //得到当前页,以便向服务端请求对应页的数据。 // console.log(obj.limit); //得到每页显示的条数 TB_download_num = obj.curr //首次不执行 if (!first) { TB_download() } } }); } // 根据id删除 个人下载记录 $('#gallery-wrapper').on('click', '#delDownLoadHistory', function() { var id = $(this).attr('data-index') console.log(id) layer.confirm('确认删除?', { icon: 3, title: '提示' }, function(index) { //do something $.ajax({ method: 'delete', url: 'http://139.9.143.69:8001/usercenter/download_history/' + id, headers: { uid: localStorage.getItem('uid'), }, success: function(res) { if (res.code !== 0) return layer.msg('删除失败!') downLoadHistory() layer.msg('删除成功!') }, }) layer.close(index) }) }) var params = new URLSearchParams(location.search) var history = params.get('history') // console.log(history); if (history === 'download') { // // 要触发的点击事件 $('#xxx').click() $('#history').click() $('#history').click() // sessionStorage.setItem("from", ""); //销毁 from 防止在b页面刷新 依然触发$('#xxx').click() } // 点击公共区域下载记录按钮 跳转到记录 // window.onload = function() { // var from = sessionStorage.getItem('from') // console.log(from) // if (from === 'pageA') { // 要触发的点击事件 $('#xxx').click() // $('#history').click() // sessionStorage.setItem('from', '') //销毁 from 防止在b页面刷新 依然触发$('#xxx').click() // } // } // 退出功能 $('.exit').on('click', function() { // 提示用户是否确认退出 layer.confirm('确定退出登录?', { icon: 3, title: '提示' }, function(index) { // 1.清空本地存储中的 uid localStorage.removeItem('uid') // 2.刷新页面 location.reload() location.href = 'index.html' // 关闭 confirm 询问框 layer.close(index); }); }) // 点击显示更多按钮 // $('.ShowMore').on('click', '#btn1', function() { // var boxHeight = $('.img-box').height() + 1300 // var num = null // var boxHeights = null // // console.log(parseInt($('#btn1').attr('data-length')) + 12); // console.log(boxHeight); // num = parseInt($('#btn1').attr('data-length')) + 12 // Works_size = parseInt(Works_size) + 12 // if (num == Works_size) { // // console.log('ok'); // if ($('.img-box').height() > 1300) { // boxHeights = boxHeight - 60 // $('.img-list').css('height', boxHeights) // } else if ($('.img-box').height() > 3930) { // boxHeights = boxHeight - 120 // $('.img-list').css('height', boxHeights) // } // getUserWorks() // } else { // $('#btn1').css('background', "#ccc"); // } // }) })
/** * Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland. * * See the file license.txt for copying permission. */ define([ 'Underscore', 'jquery', 'util/Event', 'util/FocusTracker' ], function (_, $, Event, FocusTracker) { 'use strict'; /** * Creates a FastTap object. * el - the element being fast tapped. * handler - the code executed when the user fast taps the element. * willRestoreFocus - whether focus is given back to the previous focused component before * executing the handler. * willActivate - whether the element's UI is changed to indicate that it's being hit. * willRepeat - whether the user can keep their finger on the element in order and * have the handler executable repeatedly. */ var FastTap = function (el, handler, willRestoreFocus, willActivate, willRepeat) { this.el = el; this.handler = handler; this.willRestoreFocus = willRestoreFocus; this.willRepeat = willRepeat; this.willActivate = willActivate; el.addEventListener(Event.eventName('start'), this, false); }; FastTap.prototype.fastTaps = []; // Repeat count versus repeat interval FastTap.prototype.repeatIntervals = []; (function (ar) { ar[0] = 300; ar[1] = 200; ar[5] = 100; ar[10] = 75; ar[15] = 50; ar[20] = 25; ar[30] = 10; ar[40] = 5; ar[50] = 0; }(FastTap.prototype.repeatIntervals)); FastTap.prototype.handleEvent = function (event) { switch (event.type) { case 'touchstart': case 'mousedown': this.onTouchStart(event); break; case 'touchmove': case 'mousemove': this.onTouchMove(event); break; case 'touchend': case 'mouseup': this.onTouchEnd(event); break; } }; FastTap.prototype.onTouchStart = function (event) { var locEvent = Event.getLocEvent(event); this.startCoords = { x: locEvent.clientX, y: locEvent.clientY }; this.initActive(); this.setActive(true); this.el.addEventListener(Event.eventName('end'), this, false); document.body.addEventListener(Event.eventName('move'), this, false); if (this.willRepeat) { this.repeat(event); } }; FastTap.prototype.onTouchMove = function (event) { if (!Event.inThreshold(event, this.startCoords)) { this.cancel(); } else { event.preventDefault(); } }; /** * The preventDefault isn't ideal. It stops the browser from setting focus onto the thing * being fast tapped and making it conditional currently means that this only happens * when the editable is being fast tapped. * The normal bnehaviour doesn't cause a problem on the desktop, but on the device it does * as it doesn't seem possible to find a way to re-focus on the editable after having the * focus set to it while the command is executed. */ FastTap.prototype.onTouchEnd = function (event) { if (this.willRestoreFocus) { event.preventDefault(); } this.cancel(); this.execHandler(event); }; FastTap.prototype.cancel = function () { this.setActive(false); this.el.removeEventListener(Event.eventName('end'), this, false); document.body.removeEventListener(Event.eventName('move'), this, false); this.cancelRepeat(); }; FastTap.prototype.setActive = function (value) { var func; if (this.willActivate) { func = value ? this.addFunc : this.removeFunc; $(this.el)[func]('qk_button_active'); } }; /** * Changing active state depends on the initial state. */ FastTap.prototype.initActive = function () { var isActive = $(this.el).hasClass('qk_button_active'); if (isActive) { this.addFunc = 'removeClass'; this.removeFunc = 'addClass'; } else { this.addFunc = 'addClass'; this.removeFunc = 'removeClass'; } }; /** * Stops the repeated execution of the handler. */ FastTap.prototype.cancelRepeat = function () { if (this.repeatTimeout) { clearTimeout(this.repeatTimeout); } }; /** * Repeats execution of the handler. The execution interval depends on the number of times * the handler has been executed with the interval shortening as the execution count rises. * Have to clone the event because something is changing the original event's currentTarget * which is null when the delayed function is called. */ FastTap.prototype.repeat = function (event) { var count = 0, interval = this.repeatIntervals[0], ev = _.clone(event), func = function () { var newInterval = this.repeatIntervals[++count]; interval = newInterval === undefined ? interval : newInterval; this.execHandler(ev); this.repeatTimeout = _.delay(func, interval); }.bind(this); this.repeatTimeout = _.delay(func, interval); }; /** * Executes the handler conditionally restoring focus to the editable before execution. */ FastTap.prototype.execHandler = function (event) { if (this.willRestoreFocus) { FocusTracker.restoreFocus(); } this.handler(event); }; function create(el, func, willRestoreFocus, willActivate, willRepeat) { var ft = new FastTap(el, func, willRestoreFocus, willActivate, willRepeat); FastTap.prototype.fastTaps.push(ft); } function fastTap(el, handler, context, willActivate, willRepeat) { var func = context ? handler.bind(context) : handler; create(el, func, true, willActivate, willRepeat); } /** * Fast tap without restoring the focus and selection when the handler function * is executed. */ function fastTapNoFocus(el, handler, context) { var func = context ? handler.bind(context) : handler; create(el, func, false, false, false); } /** * Assumes this isn't called between a touchstart and touchend event, so only * removes the touchstart listener and not any touchmove or touchend listeners. */ function noTap(el) { var taps = FastTap.prototype.fastTaps, i, tap; for (i = taps.length - 1; i > 0; i--) { tap = taps[i]; if (tap.el === el) { tap.el.removeEventListener(Event.eventName('start'), tap, false); taps.splice(i, 1); } } } /** * Attach a double hit handler to the given element. */ function doubleTap(el, handler) { var DOUBLE_TAP_THRESHOLD = 300, ts; el.addEventListener(Event.eventName('end'), function (event) { var now = new Date().getTime(); if (ts && (now - ts < DOUBLE_TAP_THRESHOLD)) { handler(event); ts = null; } else { ts = now; } }, false); } return { create: create, fastTap: fastTap, fastTapNoFocus: fastTapNoFocus, noTap: noTap, doubleTap: doubleTap }; });
define(['./Class', './AST', './Token'], function(Class, ASTNode, Token){ var async_wapper_token = Token.IdentifierToken('__async_waper__', Token.fack_position); var exprLeft = function exprLeft(expr){ if (expr.type === 'Val'){ return expr.token; } else if (expr.type === 'Expr'){ return exprLeft(expr.left); } else{ throw Error(); } }; var checkAsync = function checkAsync(statement){ if (statement instanceof ASTNode.AssignmentStatement){ var left_token = exprLeft(statement.right); return /^async.*/.test(left_token.content); } else { return false; } }; var transform = function transform(node){ if( !(node instanceof ASTNode.StatementsList) ){ throw Error(node.getPosition()); } var content = node.content; for (var i=0, l=content.length; i<l; i++){ var statement = content[i]; if ( checkAsync(statement) ){ var symbol = statement.symbol; var left = statement.left; var right = statement.right; content.splice(i, 1); var next = content.splice(i); var async_wapper_func = ASTNode.FunctionDefineStatement( symbol, async_wapper_token, [left], ASTNode.StatementsList(next) ); content.push(async_wapper_func); content.push( ASTNode.Expression( right, ASTNode.Expression(async_wapper_token) ) ); transform(async_wapper_func.statements_list); break; } } }; return Class('CPS', Object) .classmethod('transform', function(node){ transform(node); return node; }); });
const login = (event) => { event.preventDefault(); const fileError = document.getElementById('file-error'); const email = document.querySelector('#email').value.trim(); const password = document.querySelector('#password').value.trim(); const url = 'http://localhost:5700/api/v1/auth/login?'; const options = { method: 'POST', headers: { Accept: 'application/json, text/plain, */*', 'Content-type': 'application/json', }, body: JSON.stringify({ email, password, }), }; fetch(url, options) .then(response => response.json()) .then((data) => { const err = 'Sorry, the credentials you provided is incorrect. try again'; if (data.error === err) { fileError.innerHTML = err; document.getElementById('email').oninput = () => { fileError.innerHTML = ''; }; } if (data.status === 200) { const { token, user } = data.data[0]; localStorage.setItem('token', token); if (user.isadmin === true) { setTimeout(() => { window.location.href = ('admin_dashboard.html'); }, 5000); } else { setTimeout(() => { window.location.href = ('profile.html'); }, 5000); } } }) .catch((error) => { console.log('System error', error); }); }; document.querySelector('#login-form').addEventListener('submit', login);
$(function() { $('.patient-header').click(function() { var rightChevron = $(this).find('.glyphicon-chevron-right'); var downChevron= $(this).find('.glyphicon-chevron-down'); rightChevron.removeClass('glyphicon-chevron-right'); rightChevron.addClass('glyphicon-chevron-down'); downChevron.removeClass('glyphicon-chevron-down'); downChevron.addClass('glyphicon-chevron-right'); }) $('.dashboard-alert').click(function() { // ID is esas-alert-{{pk}} var pk = $(this).attr('id').split('-')[2]; console.log('pk'); console.log(pk); $.post('/delete-dashboard-alert', "pk=" + pk, function() { console.log('posted'); }) }) })
import {Search} from "./components/app"; const url = "https://asdf-48dbf.firebaseio.com/post.json"; const user = {}; main(); function main() { const data = new Search(url); data.Gettodo(); } document.querySelector("#add-button").addEventListener("submit", function (e) { e.preventDefault(); user.value = element.addInput.value; const search = new Search(url); search.Createtodo(user); });
import request from '@/utils/request'; import { HOST } from './config'; export async function getTagList() { return request(HOST + '/api/admin/tags', { method: 'GET', }); } /** * 更新或者增加tag * @param {*} params {... [, id: 1]} */ export async function editTag(params) { return request(HOST + '/api/admin/tags', { method: 'POST', data: params }) }
import {connect} from 'react-redux'; import * as actionCreators from './actions'; import CounterComponent from './components/CounterComponent'; let mapStateToProps = (state) => { return { value: state.counter.counter }; }; const CounterContainer = connect( mapStateToProps, actionCreators )(CounterComponent); export default CounterContainer;
const firebase = require("firebase"); // Required for side-effects require("firebase/firestore"); // Initiation var config = { apiKey: "AIzaSyAySmXtzzoLlNnPtSw1p6L1dzeCmBpnY_Y", authDomain: "hypersign-e0a0d.firebaseapp.com", databaseURL: "https://hypersign-e0a0d.firebaseio.com", projectId: "hypersign-e0a0d", storageBucket: "hypersign-e0a0d.appspot.com", messagingSenderId: "795005676642" }; firebase.initializeApp(config); const database = firebase.firestore(); export default database;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import PhotoItem from './PhotoItem'; import './PhotoList.css'; export default class PhotoList extends PureComponent { render() { const { title, photos, onFocusPhoto } = this.props; const items = photos.map((photo) => <PhotoItem key={photo.media.m} photo={photo} onFocusPhoto={onFocusPhoto} /> ); return ( <div className='PhotoList'> <h1>{title}</h1> <ul className='PhotoList-ul'> {items} </ul> </div> ); } } PhotoList.propTypes = { title: PropTypes.string, photos: PropTypes.arrayOf(PropTypes.object).isRequired, onFocusPhoto: PropTypes.func.isRequired };
import React from 'react' import Navigation from './Navigation'; import Footer from './Footer'; import { Helmet } from 'react-helmet'; export default ({ children }) => ( <header className='m-auto max-w-4xl'> <Helmet> <html lang="en" amp /> <meta charSet="utf-8" /> <meta name="author" content="Manindra Gautam" /> </Helmet> <Navigation /> <main className="w-full pt-8 px-4 md:px-0 m-auto tracking-wide"> {children} </main> <Footer /> </header> )
var express = require('express'); var path = require('path'); const app = express(); app.set('views', __dirname + '/views'); app.set('view engine', 'jsx'); app.engine('jsx', require('express-react-views').createEngine()); const data = { navigation: [ { label: "home", link : "/" }, { label: "about", link : "/about" }, { label: "contact", link : "/contact" }, { label: "help", link : "/help" } ] } const getUpdatedNavigation = (currentPage , data) => { let navigation = data.navigation.map ( (item,index) => { if(item.label === currentPage){ return Object.assign({}, item, {selected:true}) } return Object.assign({}, item); }); return {navigation}; } app.get('/', (req, res) => { res.render('index', getUpdatedNavigation("home",data)); }); app.get('/about', (req, res) => { res.render('index', getUpdatedNavigation("about", data)); }); app.get('/contact', (req, res) => { res.render('index', getUpdatedNavigation("contact", data)); }); app.get('/help', (req, res) => { res.render('index', getUpdatedNavigation("help", data)); }); app.use(express.static(path.join(__dirname, 'public'))); app.listen(4000, () => console.log('Example app listening on port 4000!'));
var get_sentence = function () { var string1 = "aaa"; var string2 = "bbb"; var num = Math.random(); if ( num < 0.5 ) { return string1; } else { return string2; } }; console.log(get_sentence());
import React from 'react' import { getPosts } from '../../services/posts' import { useState, useEffect } from 'react' import FavoriteIcon from '@material-ui/icons/Favorite'; import IconButton from '@material-ui/core/IconButton'; import "./Posts.css" export default function Posts(props) { const [posts, setPosts] = useState([]) useEffect(() => { const fetchPosts = async () => { let res = await getPosts() setPosts(res) } fetchPosts() }, []) return ( <div className='all-posts'> {posts.map((post, index) => ( <div className='post-container' key={index}> <div className="post-header" > <h2 className="username">{post.username}</h2> </div> <div className="post-image"> <img src={post.imgURL} alt="user post" /> </div> <div className="heart"> <IconButton> <FavoriteIcon fontSize="large" /> </IconButton> </div> <div className="card-content"> <p className="caption"><span className="caption-name">{post.username}</span>{post.caption}</p> </div> <br /> </div> ))} </div> ) }
/** * @author Luiz Felipe Magalhães Coelho */ var saveObj; function scormControls(engineRef){ var startDate = 0; //conexão com o Scorm this.connect = function(onConnect){ if(engineRef.config.scorm){ engineRef.SCOInitialize(); startTimer(); var completion_status = engineRef.SCOGetValue("cmi.completion_status"); if(completion_status == "passed" || completion_status == "completed"){ //scorm.disconnect(); } else { var suspend_data = engineRef.SCOGetValue("cmi.suspend_data"); //console.log(suspend_data); if(suspend_data == "" || suspend_data == "null" || suspend_data == undefined){ loadJsonLocal('configs/save.js', function(json) { saveObj = json; }); }else{ saveObj = jQuery.parseJSON(suspend_data); } } }else{ loadJsonLocal('configs/save.js', function(json) { saveObj = json; }); } setTimeout(onConnect, 1000); }; this.disconnect = function(){ engineRef.SCOFinish(); }; //Suspend data this.getSuspenData = function(){ return engineRef.SCOGetValue("cmi.suspend_data"); }; this.setSuspenData = function(data){ engineRef.SCOSetValue("cmi.suspend_data", data); engineRef.SCOCommit(); }; //Book Mark this.getBookMark = function(){ return engineRef.SCOGetValue("cmi.core.lesson_location"); }; this.setBookMark = function(mark){ engineRef.SCOSetValue("cmi.core.lesson_location", mark); engineRef.SCOCommit(); }; //Student Name this.getStudentName = function(){ return engineRef.SCOGetValue("cmi.core.student_name", mark); }; //Status do Treinamento (passed, failed, completed, incomplete) this.getCompletionStatus = function(){ return engineRef.SCOGetValue("cmi.core.lesson_status"); }; this.setCompletionStatus = function(status, raw){ if(raw != undefined){ var _this = this; _this.setRaw(raw); } engineRef.SCOSetValue("cmi.core.lesson_status", status); engineRef.SCOCommit(); }; //Score this.setMinScore = function(value){ engineRef.SCOSetValue("cmi.core.score.min", value); engineRef.SCOCommit(); }; this.setMaxScore = function(value){ engineRef.SCOSetValue("cmi.core.score.max", value); engineRef.SCOCommit(); }; this.setRaw = function(value){ console.log("Gravando Nota: " + value); var blnResult; var errorId; engineRef.g_objAPI.LMSSetValue("cmi.core.score.max", engineRef.config.maxScore); engineRef.g_objAPI.LMSSetValue("cmi.core.score.min", engineRef.config.minScore); blnResult = engineRef.g_objAPI.LMSSetValue("cmi.core.score.raw", parseFloat(value)); engineRef.SCOCommit(); console.log('Gravou Nota: ' + blnResult); errorId = engineRef.SCOGetLastError(); console.log("CODIGO ERRO RAW: " + errorId); console.log("ERRO RAW: " + engineRef.SCOGetDiagnostic(errorId)); }; this.getRaw = function(value){ console.log("Resgatando Nota: " + engineRef.SCOGetValue("cmi.core.score.raw")); return engineRef.SCOGetValue("cmi.core.score.raw"); }; //Salva as informações na plataforma Scorm. this.save = function(){ //Adicionando o objeto Save no suspend_data como string. engineRef.SCOSetValue("cmi.suspend_data", JSON.stringify(saveObj)); engineRef.SCOCommit(); }; //computando o tempo function startTimer() { startDate = new Date().getTime(); } function computeTime() { if ( startDate != 0 ) { var currentDate = new Date().getTime(); var elapsedSeconds = ( (currentDate - startDate) / 1000 ); var formattedTime = convertTotalSeconds( elapsedSeconds ); } else { formattedTime = "00:00:00.0"; } engineRef.SCOSetValue('cmi.core.session_time', formattedTime); } /******************************************************************************* ** this function will convert seconds into hours, minutes, and seconds in ** CMITimespan type format - HHHH:MM:SS.SS (Hours has a max of 4 digits & ** Min of 2 digits *******************************************************************************/ function convertTotalSeconds(ts) { var sec = (ts % 60); ts -= sec; var tmp = (ts % 3600); //# of seconds in the total # of minutes ts -= tmp; //# of seconds in the total # of hours // convert seconds to conform to CMITimespan type (e.g. SS.00) sec = Math.round(sec*100)/100; var strSec = new String(sec); var strWholeSec = strSec; var strFractionSec = ""; if (strSec.indexOf(".") != -1) { strWholeSec = strSec.substring(0, strSec.indexOf(".")); strFractionSec = strSec.substring(strSec.indexOf(".")+1, strSec.length); } if (strWholeSec.length < 2) { strWholeSec = "0" + strWholeSec; } strSec = strWholeSec; if (strFractionSec.length) { strSec = strSec+ "." + strFractionSec; } if ((ts % 3600) != 0 ) var hour = 0; else var hour = (ts / 3600); if ( (tmp % 60) != 0 ) var min = 0; else var min = (tmp / 60); if ((new String(hour)).length < 2) hour = "0"+hour; if ((new String(min)).length < 2) min = "0"+min; var rtnVal = hour+":"+min+":"+strSec; return rtnVal; } /******************************************************************************* ** Interactions *******************************************************************************/ /* interactionID:String, interactionType:String, userResp:Array, gabarito:Array Retorna um inteiro */ this.addInteraction = function(interactionID, interactionType, userResp, gabarito) { var interactionsCounter; var countInt = saveObj.countInteraction; saveObj.countInteraction = saveObj.countInteraction + 1; engineRef.SCOSetValue("cmi.interactions." + countInt + ".id", interactionID); engineRef.SCOSetValue("cmi.interactions." + countInt + ".type", interactionType); salvaResposta(userResp.join(","), gabarito.join(","), countInt); switch(interactionType) { case "choice": if (isCorrect(userResp, gabarito)) { interactionIsCorrect(countInt); }else { interactionIsWrong(countInt); } break; case "sequencing": if (isCorrectSequencing(userResp, gabarito)) { interactionIsCorrect(countInt); }else { interactionIsWrong(countInt); } break; } // alert(isCorrect(userResp, gabarito)); return isCorrect(userResp, gabarito); }; ///////////////////////////////////////////////// function salvaResposta(userResp, gabarito, idCount) { engineRef.SCOSetValue("cmi.interactions." + idCount + ".student_response", userResp.toString()); engineRef.SCOSetValue("cmi.interactions." + idCount + ".correct_responses.0.pattern", gabarito.toString()); } function interactionIsCorrect(idCount){ engineRef.SCOSetValue("cmi.interactions." + idCount + ".result", "correct"); } function interactionIsWrong(idCount){ engineRef.SCOSetValue("cmi.interactions." + idCount + ".result", "wrong"); } function isCorrect(userResp, gabarito){ var isCorrectBl = true; if(gabarito.length == userResp.length){ for (var i = 0; i < gabarito.length; i++) { if(userResp.indexOf(gabarito[i]) == -1){ isCorrectBl = false; //console.log(gabarito[i]); } } }else{ isCorrectBl = false; } return isCorrectBl; } function isCorrectSequencing(userResp, gabarito) { var isCorrectBl = true; if(gabarito.length == userResp.length){ if (gabarito.join("|") === userResp.join("|") ) { isCorrectBl = true; }else { isCorrectBl = false; } }else{ isCorrectBl = false; } return isCorrectBl; } }
var app = getApp(); import util from '../../utils/util.js'; Page({ /** * 页面的初始数据 */ data: { id: '', imgUrl: '', openId: '', staff_id: '', company_name: '', titleText: '', user_id:'', company_id:'', isShow:false }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { console.log(options) wx.setNavigationBarTitle({ title: '扫码邀请页' }); this.setData({ id: options.id, openId: options.openId }) this.data.staff_id = options.staff_id; this.data.user_id = options. user_id this.data.company_id = options.company_id;//这个是转发人的公司 // this.data.logo = options.logo;//这个是转发人的头像 }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { // 页面加载完成 判断是不是同一个人转发并进入 console.log(this.data.openId, wx.getStorageSync('openId')) if (this.data.openId != undefined && this.data.openId != null || this.data.openId != '') { if (this.data.openId != wx.getStorageSync('openId')) { if (this.data.id == '1' || this.data.id == '0' || this.data.id == '2') { wx.redirectTo({ url: '../inviteStaff/inviteStaff?id=' + this.data.id + ' &openId=' + this.data.openId + ' &staff_id=' + this.data.staff_id + '&company_id=' + this.data.company_id + '&user_id=' + this.data.user_id }) } } } }, /** * 生命周期函数--监听页面显示 */ onShow: function () { if (this.data.openId != wx.getStorageSync('openId')) { if (this.data.id == '1' || this.data.id == '0' || this.data.id == '2') { } } else { this.setData({ isShow:true }) // 这个已进入页面就取当前人所在的公司,为转发做准备 var company_name = app.loginInfoData.company_name; if (this.data.id == '0') { this.data.titleText = company_name + '公司诚邀您成为他/她的供应商,点击接受邀请?' } else if (this.data.id == '1') { this.data.titleText = company_name + '公司诚邀您加入他/她的团队,点击接受邀请?' } else if (this.data.id == '2') { this.data.titleText = company_name + '公司诚邀您成为他/她的客户,点击接受邀请?' } var _this = this; var data = { type: this.data.id }; app.netWork.postJson(app.urlConfig.myqrCodeUrl, data).then(res => { console.log(res) if (res.errorNo == '0') { _this.setData({ imgUrl: res.data }) } }).catch(err => { }) } }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, onShareAppMessage: function (res) { var openId = wx.getStorageSync('openId'); var useData = app.loginInfoData; var staff_id = useData.staff_id; var company_id = useData.company_id; var user_id = useData.user_id; if (res.from === 'menu') { // 来自页面内转发按钮 console.log(res.target) } return { title: this.data.titleText, path: '/pages/codePage/codePage?id=' + this.data.id + '&openId=' + openId + '&staff_id=' + staff_id + '&company_id=' + company_id + '&user_id=' + user_id , imageUrl: '../../images/yaoqing.jpg', success: function (res) { console.log(res) // 转发成功 }, fail: function (res) { // 转发失败 } } } })
function isOdd(num) { return num % 2 !== 0; } console.log("99 is odd: " + isOdd(99)); console.log("76 is odd: " +isOdd(76));
// 1.1 顺序查找 function seqSearch (arr, x) { const len = arr.length let location = -1, i = 0 while (i < len) { if (arr[i] == x) { i = -1 break } i++ } location = i return location } // 1.2 数组成员求和 function sum (arr) { const len = arr.length let result = 0 for(let i = 0; i < len; i++) { result += arr[i] } result result } // 1.3 冒泡排序 function exchangeSort (arr) { const len = arr.length let temp = 0 for (let i = 0; i < len; i++) { for (let j = i + 1; j < len; j++) { if (arr[j] < arr[i]) { temp = arr[i] arr[i] = arr[j] arr[j] = temp } } } return arr } // 1.4 计算两个 n * n 矩阵乘积 function matrixMult (arr1, arr2, n) { let result = []; for (let i = 0; i < n; i++) { result[i] = [] for (let j = 0; j < n; j++) { result[i][j] = 0 for (let k = 0; k < n; k++) { result[i][j] += arr1[i][k] * arr2[k][j] } } } return result }
import { takeLatest, put } from 'redux-saga/effects'; import log from '../../common/libs/logger'; import { PHOTO_GET_MANY } from '../actions/types'; import { photoSetMany, photoListReload } from '../actions'; import api from '../../common/libs/api'; export function* photoGetMany({ payload }) { log.info('photoGetMany fired...', payload); const { sectionId: id, page, limit, orderBy, reload, } = payload; const promise = yield api.collections.getCollectionPhotos(id, page, limit, orderBy) .then(data => data.json()) .then(data => data) .catch((e) => { log.error('Exception occurred: ', e); }); const result = yield promise; if (result) { // Data received log.info('[photoGetMany] Data received: ', result); if (reload) { yield put(photoListReload(result)); } else { yield put(photoSetMany(result)); } } else { // TODO: No data received, yield "404" } } export function* watchPhotoGetMany() { log.info('watchPhotoGetMany starting'); yield takeLatest(PHOTO_GET_MANY, photoGetMany); }
import express from "express"; import controllerTodo from "./controller/controllerTodo.js"; const router = express.Router(); router.get("/", controllerTodo.get); router.post("/", controllerTodo.postitem); router.delete("/:id", controllerTodo.deleteitem); router.patch("/:id", controllerTodo.updateitem); export default router;
define([ './linelabel' ], function (LineLabel) { return LineLabel.extend({ getYIdeal: function (attr) { var index = this.collection.length; var val = null; while (val === null && index > 0) { index--; val = this.graph.getYPos(index, attr); } var y0 = this.graph.getY0Pos(index, attr); return (val + y0) / 2; }, showPercentages: function () { return true; } }); });
let mongoose = require('mongoose'); let Schema = mongoose.Schema; ObjectId = Schema.ObjectId; let messageSchema = new Schema({ from: { type: ObjectId, ref:'user' }, to: { type: ObjectId, ref:'user' }, text: { type: String, }, dateTime: { type: Date } }); let MessageModel = mongoose.model('message', messageSchema); module.exports.MessageModel = MessageModel;
import React from "react"; import { EditorState } from "draft-js"; import InputEditor from "./InputEditor"; import TranslatedDisplay from "./TranslatedDisplay"; import "../styles/css/styles.css"; const Translator = (props) => { const [editorState, setEditorState] = React.useState(() => EditorState.createEmpty() ); return ( <div className="wrapper"> <InputEditor editorState={editorState} setEditorState={setEditorState} ></InputEditor> <TranslatedDisplay editorState={editorState}></TranslatedDisplay> </div> ); }; export default Translator;
import React from 'react'; import MainContainer from "./Components/MainContainer"; import HeaderNavigation from "./Components/Header"; import DrawerNavigator from "./Components/DrawerNavigator"; import { Grid } from '@material-ui/core' const App=()=> { return ( <div style={{ flexGrow : 1, padding : 12 }}> <Grid container spacing={0} style={{ overflow : 'hidden' }}> <Grid item xs={12} style={{ display : 'flex', justifyContent : 'flex-end' }}> <HeaderNavigation /> </Grid> <Grid container spacing={4}> <Grid item xs={2}> <DrawerNavigator /> </Grid> <Grid item xs={10}> <MainContainer /> </Grid> </Grid> </Grid> </div> ); }; export default App;
import { MENU_CHANGE_VIEW, MENU_CHANGE_FILTER, MENU_CHANGE_SEARCH_TERM, MENU_TOGGLE_DROPDOWN_DISPLAY, MENU_PROFILE_EDIT, MENU_PROFILE_FIELD_TOGGLE, MENU_PROFILE_FIELD_REVERT, MENU_PROFILE_DATA_SET, MENU_POPULATE_USERS, MENU_PROFILE_FIELD_LOADING, MENU_PROFILE_FIELD_COMMIT, MENU_UPDATE_CONTACT_STATE, MENU_UPDATE_USER_LASTSEEN, MENU_UPDATE_FAVORITE, MENU_UPDATE_RECENT, MENU_PASSWORD_CHANGE_INPUT } from '../actions/types'; const INITIAL_STATE = { view: 'root', //root, profile, settings* filter: 'all', filterLoading: false, searchTerm : '', dropdownDisplay: false, profile: { fullName: { loading: false, disabled: true, value: '', originalValue: '' }, email: { loading: false, disabled: true, value: '', originalValue: '' }, status: { loading: false, disabled: true, value: '', originalValue: '' }, number: { value: '' }, profilePicLink: null }, passwordChange: { oldPassword: '', newPassword: '', confirmPassword: '', error: null, success: null, loading: false }, onlineUsers: [], allUsers: [], favoriteUsers: [], recentUsers: [], notifications: {} } //helper function const profileConstructor = (profile, data) => { const newProfile = {...profile}; Object.keys(newProfile).map(x => { if (x !== 'profilePicLink'){ newProfile[x]['value'] = data[x]; newProfile[x]['originalValue'] = data[x] } else { newProfile[x] = {value: data[x]} } }); return newProfile; } export default (state = INITIAL_STATE, action) => { switch (action.type){ case MENU_PASSWORD_CHANGE_INPUT: { return {...state, passwordChange: {...state.passwordChange, [action.payload.type]: action.payload.value}} } case MENU_UPDATE_RECENT: { let newRecentList = state.recentUsers; if (newRecentList.includes(String(action.payload))){ newRecentList = newRecentList.filter(x => String(x) != String(action.payload)) } newRecentList.unshift(String(action.payload)); return {...state, recentUsers: newRecentList}; } case MENU_POPULATE_USERS: return {...state, [action.payload.id]: action.payload.data}; case MENU_PROFILE_DATA_SET: return {...state, profile: profileConstructor(state.profile, action.payload.profile), recentUsers: action.payload.recent, notifications: action.payload.notifications}; case MENU_CHANGE_VIEW: return {...state, view: action.payload, passwordChange: INITIAL_STATE.passwordChange}; case MENU_CHANGE_FILTER: return {...state, filter: action.payload, dropdownDisplay: false}; case MENU_CHANGE_SEARCH_TERM: return {...state, searchTerm: action.payload, dropdownDisplay: false}; case MENU_TOGGLE_DROPDOWN_DISPLAY: return {...state, dropdownDisplay: !state.dropdownDisplay} case MENU_PROFILE_EDIT: return {...state, profile: {...state.profile, [action.payload.id]: { value:action.payload.value, disabled:state.profile[action.payload.id].disabled, originalValue:state.profile[action.payload.id].originalValue, loading: false } } } case MENU_PROFILE_FIELD_TOGGLE: return {...state, profile: {...state.profile, [action.payload]: { value:state.profile[action.payload].value, disabled:!state.profile[action.payload].disabled, originalValue:state.profile[action.payload].originalValue, loading: false } } } case MENU_PROFILE_FIELD_LOADING: return {...state, profile: {...state.profile, [action.payload.id]: { value:state.profile[action.payload.id].value, disabled:state.profile[action.payload.id].disabled, originalValue:state.profile[action.payload.id].originalValue, loading: action.payload.loading } } } case MENU_PROFILE_FIELD_COMMIT: return {...state, profile: {...state.profile, [action.payload.id]: { value: action.payload.value, disabled:true, originalValue: action.payload.value, loading: false } } } case MENU_PROFILE_FIELD_REVERT: return {...state, profile: { ...state.profile, [action.payload]: { value:state.profile[action.payload].originalValue, disabled: true, loading: false, originalValue:state.profile[action.payload].originalValue, } } } case MENU_UPDATE_CONTACT_STATE: return {...state, onlineUsers: action.payload} case MENU_UPDATE_USER_LASTSEEN: return {...state, allUsers: state.allUsers.map(x => { if (x.number == action.payload.number){ return {...x, lastSeen: action.payload.lastSeen} } else{ return x } })} case MENU_UPDATE_FAVORITE: return {...state, favoriteUsers: action.payload, dropdownDisplay: false} default: return state } }
// Generated by https://pagedraw.io/pages/9009 import React from 'react'; import './submittableinput.css'; function render() { return <div className="submittableinput-submittableinput-1"> <div className="submittableinput-0"> <div className="submittableinput-0-0"> <div className="submittableinput-0-0-0"> <div className="submittableinput-path-1"> <div className="submittableinput-0-0-0-0-0"> <div className="submittableinput-your_comment-4"> Your comment </div> </div> </div> </div> <div className="submittableinput-0-0-1"> <div className="submittableinput-path-10" /> </div> </div> <div className="submittableinput-0-1"> <div className="submittableinput-0-1-0"> <div className="submittableinput-oval-1"> <div className="submittableinput-0-1-0-0-0"> <div className="submittableinput-_-9">{"+"}</div> </div> </div> </div> </div> </div> </div>; }; export default function(props) { return render.apply({props: props}); }
"use strict"; //This file is mocking a web API by hitting hard coded data. var imports = require('./fintracData').imports; var _ = require('lodash'); //This would be performed on the server in a real app. Just stubbing in. var _generateId = function(fintracimport) { return fintracimport.firstName.toLowerCase() + '-' + fintracimport.lastName.toLowerCase(); }; var _clone = function(item) { return JSON.parse(JSON.stringify(item)); //return cloned copy so that the item is passed by value instead of by reference }; var FintracApi = { getAllImports: function() { return _clone(imports); }, getImportById: function(id) { var fintracimport = _.find(imports, {id: id}); return _clone(fintracimport); }, saveImport: function(fintracimport) { //pretend an ajax call to web api is made here console.log('Pretend this just saved the import to the DB via AJAX call...'); if (fintracimport.id) { var existingImportIndex = _.indexOf(imports, _.find(imports, {id: fintracimport.id})); imports.splice(existingImportIndex, 1, fintracimport); } else { //Just simulating creation here. //The server would generate ids for new authors in a real app. //Cloning so copy returned is passed by value rather than by reference. fintracimport.id = _generateId(fintracimport); fintracimport.push(fintracimport); } return _clone(fintracimport); }, deleteImport: function(id) { console.log('Pretend this just deleted the import from the DB via an AJAX call...'); _.remove(imports, { id: id}); } }; module.exports = FintracApi;
"use strict"; function Templator(idstring) { this.domObject = document.getElementById(idstring); this.getObject = function () { return new Promise((resolve, reject) => { resolve(this.domObject.cloneNode(true)); // Deep clone }); }; // Init code this.domObject.parentNode.removeChild(this.domObject); // Remove the template from the page this.domObject.removeAttribute("id"); }
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import { Row, Col, AutoComplete } from 'antd'; import Navigation from '../Navigation'; import OfflineBoltIcon from '@material-ui/icons/OfflineBolt'; import OpacityIcon from '@material-ui/icons/Opacity'; import WhatshotIcon from '@material-ui/icons/Whatshot'; import PhoneIphoneIcon from '@material-ui/icons/PhoneIphone'; import RssFeedIcon from '@material-ui/icons/RssFeed'; import { Link } from "react-router-dom"; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, button: { margin: theme.spacing(1), }, emptyTable: { margin: theme.spacing(1), display: 'inline-block', paddingTop: theme.spacing(1), paddingBottom: theme.spacing(1), width: theme.spacing(15), height: theme.spacing(20), backgroundColor: '#e6eded', cursor: 'pointer', transitionDuration: '0.5s', transition: '0.5s', '&:hover': { backgroundColor: "rgb(247, 247, 247,0.8)", transition: '0.5s', }, }, paymentIcons: { fontSize: theme.spacing(15), } })); const Payments = () => { const classes = useStyles(); return ( <Row> <Col span={7} > <Navigation /> </Col> <Col span={17} > <Link to="/payment/Electrik" > <Paper elevation={3} className={classes.emptyTable} > <OfflineBoltIcon className={classes.paymentIcons} /> <p style={{ textAlign: 'center' }}>Electrik</p> </Paper> </Link> <Link to="/payment/Water" > <Paper elevation={3} className={classes.emptyTable} > <OpacityIcon className={classes.paymentIcons} /> <p style={{ textAlign: 'center' }}>Water</p> </Paper> </Link> <Link to="/payment/Energy" > <Paper elevation={3} className={classes.emptyTable} > <WhatshotIcon className={classes.paymentIcons} /> <p style={{ textAlign: 'center' }}>Energy</p> </Paper> </Link> <Link to="/payment/phonebill" > <Paper elevation={3} className={classes.emptyTable} > <PhoneIphoneIcon className={classes.paymentIcons} /> <p style={{ textAlign: 'center' }}>Phone bill</p> </Paper> </Link> <Link to="/payment/internetbill" > <Paper elevation={3} className={classes.emptyTable} > <RssFeedIcon className={classes.paymentIcons} /> <p style={{ textAlign: 'center' }}>Internet bill</p> </Paper> </Link> </Col> </Row> ) } export default Payments
import React from 'react'; const ScheduleTitles = ({ isNotFinalSchedule, theme }) => ( <div className={'schedule-titles-container' + theme} style={{ marginTop: isNotFinalSchedule ? '30px' : '0px' }}> <b className={'schedule-titles-block' + theme} style={{ width: '100px', borderRight: theme === '' ? '1px solid #dedede' : '1px solid #444', cursor: isNotFinalSchedule ? 'pointer' : 'default' }} /> <b className={'schedule-titles-block' + theme}>Monday</b> <b className={'schedule-titles-block' + theme}>Tuesday</b> <b className={'schedule-titles-block' + theme}>Wednesday</b> <b className={'schedule-titles-block' + theme}>Thursday</b> <b className={'schedule-titles-block' + theme}>Friday</b> </div> ); export default ScheduleTitles;
window.onload = function(){ search(); } function search () { var btn = document.getElementById("btn"); btn.onclick = function() { var httpRequest = new XMLHttpRequest(); var url = "superheroes.php"; httpRequest.onreadystatechange = getHeroes; httpRequest.open('GET', url); httpRequest.send(); function getHeroes(){ if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200){ var res = httpRequest.responseXML; alert(res); } else { alert ('There was an error') } } } } }
import React from 'react'; import ReactTable from 'react-table' import { connect } from 'react-redux' import { bindActionCreators, compose } from 'redux' import axios from 'axios' import Consts from '../../../../utils/consts' import { translate } from 'react-i18next' import Button from '../../../common/buttons/button' import { deleteCron } from '../cronActions' const INITIAL_STATE = { name: { label: 'name', value: null }, description: { label: 'description', value: null }, data: [] } class LoadCron extends React.Component { constructor(props) { super(props) this.selectedCron = null this.state = INITIAL_STATE this.data = [] } search = () => { let params = "?access_token=" + JSON.parse(localStorage.getItem('_user')).id axios.get(Consts.API_URL + "/PredefinedTimes" + params) .then(resp => { this.setState({ data: resp.data }) }).catch(err => { console.log(err.response.data) }) } onDeleteCron = () => { swal({ title: this.props.t("swals.deleteCronsTitle"), text: this.props.t("swals.deleteCronsText"), icon: "warning", buttons: true, dangerMode: false, }).then(async (ans) => { if (ans) { const resp = await this.props.deleteCron(this.selectedCron.id) if (resp && resp.data.error && resp.data.error.statusCode === 400) { swal({ title: this.props.t("swals.deleteCronsTitle"), text: this.props.t("swals.deleteCronsDeactivateJobs"), icon: "warning" }).then(async (del) => { if (del) { await this.props.deleteCron(this.selectedCron.id, "deactivate=true") const data = this.state.data.filter(c => c.id !== this.selectedCron.id) this.setState({ selectedCron: null, data: data }, () => { swal(this.props.t("swals.deleteCronsSuccess"), { icon: "success" }) }) } }) } else { if (resp && resp.data.error && resp.data.error.statusCode !== 500) { const data = this.state.data.filter(c => c.id !== this.selectedCron.id) this.setState({ selectedCron: null, data: data }, () => { swal(this.props.t("swals.deleteCronsSuccess"), { icon: "success" }) }) } } } }) } render() { const { t } = this.props if (this.state.data.length === 0) { this.search() } const columns = [ { Header: t("tables:headers.name"), accessor: 'name', width: 350, filterable: false, filterMethod: (filter, row) => row.name.indexOf(filter.value) !== -1, Cell: row => ( <div> <label>{row.original.name}</label> </div> ) }, { Header: t("tables:headers.description"), accessor: 'description' } ] return ( <div> <div className="row-lg-3"> <div className="row"> <div className="pull-right" style={{ marginBottom: 10, marginRight: 10 }}> <Button size="lg" color="danger" label={t("buttons.delete")} extra={"pull-right " + (this.selectedCron ? "" : "disabled")} style={{ marginRight: 5 }} onClick={this.onDeleteCron} /> </div> </div> </div> <ReactTable data={this.state.data} columns={columns} defaultPageSize={10} loading={false} className="-striped -highlight text-center " showPageSizeOptions={false} previousText={t("tables:buttons.previous")} nextText={t("tables:buttons.next")} pageText={t("tables:texts.page")} ofText={t("tables:texts.of")} noDataText={t("tables:texts.noData")} rowsText={t("tables:texts.rows")} getTrProps={(state, rowInfo, column) => { if (!rowInfo) return {} //https://tinyurl.com/yc3bqhku //https://stackoverflow.com/questions/42025991/how-to-rerender-entire-single-row-in-react-table return { onClick: (e) => { this.selectedCron = rowInfo.original this.forceUpdate() this.props.callback(this.selectedCron) }, style: { background: this.selectedCron && rowInfo.original.id === this.selectedCron.id ? '#177D5A' : '', color: this.selectedCron && rowInfo.original.id === this.selectedCron.id ? 'white' : '' } } }} /> </div> ) } } const mapStateToProps = state => ({}) const mapDispatchToProps = dispatch => bindActionCreators({ deleteCron }, dispatch) export default compose(translate('cronManager'), connect(mapStateToProps, mapDispatchToProps))(LoadCron)
import { makeActionCreator } from '../../../utils/helpers/redux'; export const LATEST_MESSAGES_REQUEST = 'chat/LATEST_MESSAGES_REQUEST'; export const LATEST_MESSAGES_SUCCESS = 'chat/LATEST_MESSAGES_SUCCESS'; export const SEND_MESSAGE_REQUEST = 'chat/SEND_MESSAGE_REQUEST'; export const SEND_MESSAGE_SUCCESS = 'chat/SEND_MESSAGE_SUCCESS'; export const MORE_MESSAGES_REQUEST = 'chat/MORE_MESSAGES_REQUEST'; export const MORE_MESSAGES_SUCCESS = 'chat/MORE_MESSAGES_SUCCESS'; export const UPDATE_MESSAGES = 'chat/UPDATE_MESSAGES'; export const START_CHAT_CHANNEL = 'chat/START_CHAT_CHANNEL'; export const CLOSE_CHAT_CHANNEL = 'chat/CLOSE_CHAT_CHANNEL'; export const latestMessagesRequest = makeActionCreator(LATEST_MESSAGES_REQUEST, 'request'); export const latestMessagesSuccess = makeActionCreator(LATEST_MESSAGES_SUCCESS, 'response'); export const sendMessageRequest = makeActionCreator(SEND_MESSAGE_REQUEST, 'request'); export const sendMessageSuccess = makeActionCreator(SEND_MESSAGE_SUCCESS, 'response'); export const moreMessagesRequest = makeActionCreator(MORE_MESSAGES_REQUEST, 'request'); export const moreMessagesSuccess = makeActionCreator(MORE_MESSAGES_SUCCESS, 'response'); export const updateMessages = makeActionCreator(UPDATE_MESSAGES, 'messages'); export const startChatChannel = makeActionCreator(START_CHAT_CHANNEL, 'request'); export const closeChatChannel = makeActionCreator(CLOSE_CHAT_CHANNEL, 'response'); export const ActionsTypes = { LATEST_MESSAGES_REQUEST, LATEST_MESSAGES_SUCCESS, SEND_MESSAGE_REQUEST, SEND_MESSAGE_SUCCESS, MORE_MESSAGES_REQUEST, MORE_MESSAGES_SUCCESS, UPDATE_MESSAGES, START_CHAT_CHANNEL, CLOSE_CHAT_CHANNEL }; export const Actions = { latestMessagesRequest, latestMessagesSuccess, sendMessageRequest, sendMessageSuccess, moreMessagesRequest, moreMessagesSuccess, updateMessages, startChatChannel, closeChatChannel, };
var mongoose = require ("mongoose"); var passportLocalMongoose = require ("passport-local-mongoose"); var userSchema = new mongoose.Schema ({ username: String, password: String, friends: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}], incoming: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}], outgoing:[{type: mongoose.Schema.Types.ObjectId, ref: "User"}], ignored: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}] // incoming: [{userId: String}], // outgoing: [{userId: String}] }); userSchema.plugin (passportLocalMongoose); module.exports = mongoose.model ("User", userSchema) ;