text
stringlengths
7
3.69M
import React from 'react'; import SelectDifficulty from './SelectDifficulty.jsx'; const App = () => { return( <div> <SelectDifficulty /> </div> ) }; export default App;
(function(){ angular .module('linguine.documentation', ['ui.router']) .config(config); function config($stateProvider){ $stateProvider .state('linguine.documentation', { url: '/documentation', abstract: true, template: '<div ui-view />' }) .state('linguine.documentation.index', { url: '', templateUrl: 'templates/documentation/index', controller: 'DocumentationIndexController', }) .state('linguine.documentation.tutorial', { url: '/tutorial', templateUrl: 'templates/documentation/tutorial', controller: 'DocumentationTutorialController', }) .state('linguine.documentation.about', { url: '/about', templateUrl: 'templates/documentation.about', controller: 'DocumentationAboutController', }); } })();
var searchData= [ ['engine_5falgdesc',['Engine_AlgDesc',['../struct_engine___alg_desc.html',1,'']]], ['engine_5falginfo',['Engine_AlgInfo',['../struct_engine___alg_info.html',1,'']]], ['engine_5falginfo2',['Engine_AlgInfo2',['../struct_engine___alg_info2.html',1,'']]], ['engine_5fattrs',['Engine_Attrs',['../struct_engine___attrs.html',1,'']]], ['engine_5fdesc',['Engine_Desc',['../struct_engine___desc.html',1,'']]], ['engine_5fdllalgdesc',['Engine_DllAlgDesc',['../struct_engine___dll_alg_desc.html',1,'']]] ];
const firebaseConfig = { apiKey: "AIzaSyApVRh5Uz9BtABcNACC0XYsmY_9uE1KvA0", authDomain: "emah-john-easy.firebaseapp.com", databaseURL: "https://emah-john-easy.firebaseio.com", projectId: "emah-john-easy", storageBucket: "emah-john-easy.appspot.com", messagingSenderId: "131347695943", appId: "1:131347695943:web:b498870fe2ce2cfa23e462" }; export default firebaseConfig;
/** * Module dependencies. */ var passport = require('passport-strategy') , util = require('util'); /** * `BasicStrategy` constructor. * * The HTTP Basic authentication strategy authenticates requests based on * userid and password credentials contained in the `Authorization` header * field. * * Applications must supply a `verify` callback which accepts `userid` and * `password` credentials, and then calls the `done` callback supplying a * `user`, which should be set to `false` if the credentials are not valid. * If an exception occured, `err` should be set. * * Optionally, `options` can be used to change the authentication realm. * * Options: * - `realm` authentication realm, defaults to "Users" * * Examples: * * passport.use(new BasicStrategy( * function(userid, password, done) { * User.findOne({ username: userid, password: password }, function (err, user) { * done(err, user); * }); * } * )); * * For further details on HTTP Basic authentication, refer to [RFC 2617: HTTP Authentication: Basic and Digest Access Authentication](http://tools.ietf.org/html/rfc2617) * * @param {Object} options * @param {Function} verify * @api public */ function BasicStrategy(options, verify) { if (typeof options == 'function') { verify = options; options = {}; } if (!verify) throw new Error('HTTP Basic authentication strategy requires a verify function'); passport.Strategy.call(this); this.name = 'basic'; this._verify = verify; this._realm = options.realm || 'Users'; this._passReqToCallback = options.passReqToCallback; } /** * Inherit from `passport.Strategy`. */ util.inherits(BasicStrategy, passport.Strategy); /** * Authenticate request based on the contents of a HTTP Basic authorization * header. * * @param {Object} req * @api protected */ BasicStrategy.prototype.authenticate = function(req) { var authorization = req.headers['authorization']; if (!authorization) { return this.fail(this._challenge()); } var parts = authorization.split(' ') if (parts.length < 2) { return this.fail(400); } var scheme = parts[0] , credentials = new Buffer(parts[1], 'base64').toString().split(':'); if (!/Basic/i.test(scheme)) { return this.fail(this._challenge()); } if (credentials.length < 2) { return this.fail(400); } var userid = credentials[0]; var password = credentials[1]; if (!userid || !password) { return this.fail(this._challenge()); } var self = this; function verified(err, user) { if (err) { return self.error(err); } if (!user) { return self.fail(self._challenge()); } self.success(user); } if (self._passReqToCallback) { this._verify(req, userid, password, verified); } else { this._verify(userid, password, verified); } } /** * Authentication challenge. * * @api private */ BasicStrategy.prototype._challenge = function() { return 'Basic realm="' + this._realm + '"'; } /** * Expose `BasicStrategy`. */ module.exports = BasicStrategy;
import React from 'react'; import classes from './Entries.module.css'; import Meal from './Meal/Meal'; const Entries = ({entryData, handleEditClick, handleDeleteClick}) => { return ( <div className={classes.container}> {entryData.map((m, i) => <Meal key={i} date={m.time} foods={m.foods} totalCal={m.totalCalories} editClick={() => handleEditClick(i)} deleteClick={() => handleDeleteClick(m._id)} /> )} </div> ) }; export default Entries;
import React,{Component} from 'react'; import Menu from '@material-ui/core/Menu'; //Components import RctDropdownItem from './RctDropdownItem'; class RctDropdownMenu extends Component { state = { anchorEl: null, }; handleClick = event => { this.setState({ anchorEl: event.currentTarget }); }; handleClose = () => { this.setState({ anchorEl: null }); }; render() { const { anchorEl } = this.state; const { children } = this.props; return ( <div> <div aria-owns={anchorEl ? 'rct-dropdown-menu' : null} aria-haspopup="true" onClick={this.handleClick} > {children} </div> <Menu id="rct-dropdown-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={this.handleClose} > <RctDropdownItem> {children} </RctDropdownItem> </Menu> </div> ); } } export default RctDropdownMenu;
// Version 1.0.1 // Permitted deviation in Minkowski dot product for input points const MDP_INPUT_TOLERANCE = 1e-9; /* Given a string `text` that is a JSON encoding of an Array of points with the * specified number of coordinates, (themselves Arrays), return the decoding, * raising informative exceptions if this fails. */ function parse_points(text, expected_length) { var new_points; try { new_points = JSON.parse(text); } catch(e) { throw 'Points not valid JSON'; } if (!Array.isArray(new_points)) { throw 'Points input must be an array of points.'; } $.each(new_points, function(i, point) { if (!Array.isArray(point) || point.length != expected_length) { throw 'Point ' + i + ' has length ' + point.length + ', should be ' + expected_length + '.'; } $.each(point, function(j, value) { if (isNaN(value)) { throw 'Point co-ordinates must be numeric!'; } }); }); return new_points; } /* Given a string `text` that is a JSON encoding of an Array of points on the * Poincaré disc, return the decoded points as points on the hyperboloid, * raising informative exceptions if this fails. */ function parse_poincare_disc_points(text) { var new_ppoints = parse_points(text, 2); // expect 2 coords per point var new_points = [] $.each(new_ppoints, function(index, ppoint) { if (norm(ppoint) >= 1) { throw 'Point ' + index + ' is outside of the Poincaré disc!'; } new_points.push(disc_to_hyperboloid(ppoint)); }); return new_points; } /* Given a string `text` that is a JSON encoding of an Array of hyperboloid * points (themselves Arrays), return the decoding, raising informative * exceptions if this fails. */ function parse_hyperboloid_points(text) { var new_points = parse_points(text, 3); // expect 3 coords per point $.each(new_points, function(i, point) { var mdp = minkowski_dot(point, point); if (Math.abs(mdp + 1) > MDP_INPUT_TOLERANCE) { throw 'Point ' + i + ' has Minkowski dot product ' + mdp + ' != -1.'; } }); return new_points; } /* Given a string that is a JSON-encoding of the edge data, return the edge * data, or raise an informative error message if this fails. */ function parse_edges(text, last_index) { var new_edges; try { new_edges = JSON.parse(text); } catch(e) { throw 'Edges not valid JSON.'; } if (!Array.isArray(new_edges)) { throw 'Edges list should be an array.'; } $.each(new_edges, function(i, edge) { if (!Array.isArray(edge) || edge.length != 2) { throw 'Each edge should be an array of length 2.'; } $.each(edge, function(j, value) { if (!Number.isInteger(value)) { throw 'Edge index ' + value + ' is not an integer!'; } if (value < 0 || value > last_index) { throw 'Edge index ' + value + ' is out of range (use 0-offset).'; } }); }); return new_edges; } /* Return a pretty string representation of the provided array. */ function array_to_pretty_string(values) { return JSON.stringify(values).split(',').join(', ').split('],').join('],\n'); }
/** * Created by griga on 11/30/15. */ import React from 'react' import axios from 'axios' import {SubmissionError} from 'redux-form' import {connect} from 'react-redux' import moment from 'moment' import Loader, {Visibility as LoaderVisibility} from '../../../../components/Loader/Loader' import WidgetGrid from '../../../../components/widgets/WidgetGrid' import JarvisWidget from '../../../../components/widgets/JarvisWidget' import Datatable from '../../../../components/tables/Datatable' import Msg from '../../../../components/i18n/Msg' import Moment from '../../../../components/utils/Moment' import FeeStructureForm from './FeeStructureForm' import EditGeneralInfo from './EditGeneralInfo' import submit, {remove} from './submit' import mapForCombo, {getWebApiRootUrl, instanceAxios} from '../../../../components/utils/functions' class FeeStructuresPages extends React.Component { constructor(props){ super(props); this.state = { feeTypeId: 0 } } componentWillMount() { LoaderVisibility(true); } componentDidMount(){ console.log('componentDidMount --> FeeStructuresPages'); $('#FeeStructureGrid').on('click', 'td', function(event) { if ($(this).find('#dele').length > 0) { var id = $(this).find('#dele').data('tid'); remove(id, $(this)); } }); // call before modal open $('#FeeStructurePopup').on('show.bs.modal', function (e) { var button = $(e.relatedTarget); // Button that triggered the modal var feeTypeId = button.data('id'); // Extract info from data-* attributes this.setState({feeTypeId}); }.bind(this)); // call on modal close $('#FeeStructurePopup').on('hidden.bs.modal', function (e) { this.setState({ feeTypeId: 0 }); var table = $('#FeeStructureGrid').DataTable(); table.clear(); table.ajax.reload(null, false); // user paging is not reset on reload }.bind(this)); LoaderVisibility(false); } render() { var self = this; return ( <div id="content"> <WidgetGrid> {/* START ROW */} <div className="row"> {/* NEW COL START */} <article className="col-sm-12 col-md-12 col-lg-12"> {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} editbutton={false} color="blueLight" custombutton={false} deletebutton={false} > <header> <span className="widget-icon"> <i className="fa fa-edit"/> </span> <h2><Msg phrase="FeeStructures" /></h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body no-padding"> <div className="widget-body-toolbar"> <div className="row"> <div className="col-xs-9 col-sm-5 col-md-5 col-lg-5"> </div> <div className="col-xs-3 col-sm-7 col-md-7 col-lg-7 text-right"> <button className="btn btn-primary" data-toggle="modal" data-target="#FeeStructurePopup"> <i className="fa fa-plus"/> <span className="hidden-mobile"><Msg phrase="AddNewText" /></span> </button> </div> </div> </div> <Loader isLoading={this.props.isLoading} /> <Datatable id="FeeStructureGrid" options={{ ajax: {"url": getWebApiRootUrl() +'/api/FeeStructures/All', "dataSrc": ""}, columnDefs: [ { // The `data` parameter refers to the data for the cell (defined by the // `data` option, which defaults to the column being worked with, in // this case `data: 0`. "render": function ( data, type, row ) { return '<a data-toggle="modal" data-id="' + data + '" data-target="#FeeStructurePopup"><i id="edi" class=\"glyphicon glyphicon-edit\"></i><span class=\"sr-only\">Edit</span></a>'; }, "className": "dt-center", "sorting": false, "targets": 8 } ,{ "render": function ( data, type, row ) { return '<a id="dele" data-tid="' + data + '"><i class=\"glyphicon glyphicon-trash\"></i><span class=\"sr-only\">Edit</span></a>'; }.bind(self), "className": "dt-center", "sorting": false, "targets": 9 } ], columns: [ {data: "FeeStructureID"}, {data: "ClassName"}, {data: "FeeTypeName"}, {data: "FeeCycleName"}, {data: "FeeDueOnFrequencyName"}, {data: "Fee"}, {data: "DiscountValue"}, {data: "NetFee"}, {data: "FeeStructureID"}, {data: "FeeStructureID"} ], buttons: [ 'copy', 'excel', 'pdf' ] }} paginationLength={true} className="table table-striped table-bordered table-hover" width="100%"> <thead> <tr> <th><Msg phrase="IDText"/></th> <th><Msg phrase="ClassText"/></th> <th><Msg phrase="FeeTypes"/></th> <th><Msg phrase="FeeCycleText"/></th> <th><Msg phrase="FeeDueOnFrequencyText"/></th> <th><Msg phrase="FeeText"/></th> <th><Msg phrase="DiscountValueText"/></th> <th><Msg phrase="FeeAmountAfterDiscountText"/></th> <th></th> <th></th> </tr> </thead> </Datatable> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} </article> {/* END COL */} </div> {/* END ROW */} </WidgetGrid> {/* end widget grid */} <div className="modal fade" id="FeeStructurePopup" tabIndex="-1" role="dialog" data-backdrop="static" data-keyboard="false" aria-labelledby="FeeStructurePopupLabel" aria-hidden="true"> <div className="modal-dialog modal-lg"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h4 className="modal-title" id="FeeStructurePopupLabel"> { this.state.feeTypeId > 0 ? <Msg phrase="ManageText" /> : <Msg phrase="AddNewText"/> } </h4> </div> <div className="modal-body"> { this.state.feeTypeId > 0 ? <EditGeneralInfo FeeTypeID={this.state.feeTypeId} onSubmit={submit} /> : <FeeStructureForm FeeTypeID={this.state.feeTypeId} onSubmit={submit} /> } </div> </div> {/* /.modal-content */} </div> {/* /.modal-dialog */} </div> {/* /.modal */} </div> ) } } export default FeeStructuresPages;
<!-- function SetFontStyle(obj, StyleName) //Bold,Italic,Underline,StrikeThrough... { var m_objTextRange = obj.document.selection.createRange(); m_objTextRange.execCommand(StyleName); } function SetFontName(obj, FontName) { var m_objTextRange = obj.document.selection.createRange(); m_objTextRange.execCommand("FontName", false, FontName); } function SetFontSize(obj, FontSize) { var m_objTextRange = obj.document.selection.createRange(); m_objTextRange.execCommand("FontSize", "", FontSize); } function SetFontForeColor(obj, FontColor) { var m_objTextRange = obj.document.selection.createRange(); m_objTextRange.execCommand("ForeColor", "", FontColor); } function SetFontBackColor(obj, FontColor) { var m_objTextRange = obj.document.selection.createRange(); m_objTextRange.execCommand("BackColor", "", FontColor); } function InsertImage(obj, ImageFileName) { obj.insertAdjacentHTML("BeforeEnd", "<img src=\"" + ImageFileName + "\">"); } -->
export const getMarkas = async () =>{ const response = await fetch('http://34.72.0.144/api/v1.0/cars/markas/',{ method:'GET', headers:{'Content-Type': 'application/json'} }) const data = await response.json() return data.allMarkas }
module.exports = function fromWhere(vrn) { if (vrn.startsWith('CY')) { return "Bellville"; } else if (vrn.startsWith('CJ')) { return "Paarl"; } else if (vrn.startsWith('CA')) { return "Cape Town"; } else { return "Some other place!"; } }
import React from "react"; export const LineChartIcon = ({ className, style, width, onClick }) => { return ( <svg className={className || ""} style={style || {}} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width={width || "24"} onClick={onClick} > <path d="M0 0h24v24H0z" fill="none" /> <path d="M3.5 18.49l6-6.01 4 4L22 6.92l-1.41-1.41-7.09 7.97-4-4L2 16.99z" /> </svg> ); };
import React from 'react'; import './Check.css'; import { Row, Col } from 'react-bootstrap'; import Sidebar_Advisor from "./Advisor/Sidebar_Advisor"; import {BlockCheck_Advisor} from "./Advisor/BlockCheck_Advisor"; function Check() { return ( <Row className="content"> <Col> <Sidebar_Advisor /> </Col> <Col> <BlockCheck_Advisor /></Col> </Row> ); } export default Check;
var $pageAddForm = $("#pageAddForm"); var $formValidator; var $font_element; $(function () { // 初始化验证器 initValidate(); $("#template").val("page"); $("#pageAddBtn").click(function () { var name = $(this).attr("name"); // 同步ckeditor内容 var contents = pageEditor.getData(); $("#postContent").val(contents); $formValidator = $pageAddForm.validate(); var flag = $formValidator.form(); if (flag) { if (name === "save") { $.post("/system/cms/page/add", $pageAddForm.serialize(), function (r) { if (r.code === 200) { refresh(); closeModal(); $Jtk.n_success(r.msg); } else $Jtk.n_danger(r.msg); }); } if (name === "update") { $.post("/system/cms/page/update", $pageAddForm.serialize(), function (r) { if (r.code === 200) { refresh(); closeModal(); $Jtk.n_success(r.msg); } else $Jtk.n_danger(r.msg); }); } } }); $("#addPageModal .btn-close").click(function () { closeModal(); }); }) function closeModal() { $("#pageAddBtn").attr("name", "save"); $formValidator.resetForm(); pageEditor.setData(""); $Jtk.closeAndRestModal("addPageModal"); $("#template").val("page"); } function initValidate(){ $formValidator= $('#pageAddForm').validate({ ignore: ".ignore", // 插件默认不验证隐藏元素,这里可以自定义一个不验证的class,即验证隐藏元素,不验证class为.ignore的元素 focusInvalid: false, // 禁用无效元素的聚焦 //用覆盖onfocusout 解决ckeditor5无法校验的问题 onfocusout: function(ele){ // console.log("element.....失去校验"); }, rules: { postTitle: { required: true, minlength: 2, maxlength: 50 } }, errorPlacement: function errorPlacement(error, element) { var $parent = $(element).parents('.form-group'); if ($parent.find('.invalid-feedback').length) { return; } $(element).addClass('is-invalid'); $parent.append(error.addClass('invalid-feedback')); }, unhighlight: function(element) { $(element).removeClass('is-invalid'); }, }) }
import AQIScaleTable from './AQIScaleTable'; import AQNotifications from './AQNotifications'; import ExperimentsDetails from './ExperimentsDetails'; import ExperimentsDateSelector from './ExperimentsDateSelector'; import FireMap from './FireMap'; import ForecastMap from './ForecastMap'; import ForecastPointDetails from './ForecastPointDetails'; import HistoricalFireDetails from './HistoricalFireDetails'; import HistoricFireMap from './HistoricFireMap'; import MainMap from './MainMap'; import MeasurementsCharts from './MeasurementsCharts'; import MeasurementsTable from './MeasurementsTable'; import PreviewMap from './PreviewMap'; import PrivateRoute from './PrivateRoute'; import QuerySiteDetails from './QuerySiteDetails'; import Questionnaire from './Questionnaire'; import SelectedFireDetails from './SelectedFireDetails'; import SiteMap from './SiteMap'; import SiteTable from './SiteTable'; import SvgIcon from './SvgIcon'; import TrafficMap from './TrafficMap'; export { AQIScaleTable, AQNotifications, ExperimentsDetails, ExperimentsDateSelector, FireMap, ForecastMap, ForecastPointDetails, HistoricalFireDetails, HistoricFireMap, MainMap, MeasurementsCharts, MeasurementsTable, PreviewMap, PrivateRoute, QuerySiteDetails, Questionnaire, SelectedFireDetails, SiteMap, SiteTable, SvgIcon, TrafficMap, };
// set the dimensions and margins of the graph var margin = {top: 20, right: 10, bottom: 20, left: 40}, width = 1200 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; // set the ranges var x = d3.scaleBand() .range([0, width]) .padding(0.1); var y = d3.scaleLinear() .range([height, 0]); // used to format the Y axis var formatHMS = function(d) { var sec_num = parseInt(d, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} return hours+':'+minutes; } // append the svg object to the body of the page // append a 'group' element to 'svg' // moves the 'group' element to the top left margin d3.select("body").append("h1").text("Working time per day") var perDayElem = d3.select("body").append("svg") .attr("id", "perDay") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); perDay = $perDay; // format the data perDay.forEach(function(d) { d.time = +d.time; }); // Scale the range of the data in the domains x.domain(perDay.map(function(d) { return d.day; })); y.domain([0, d3.max(perDay, function(d) { return d.time; })]); // append the rectangles for the bar chart perDayElem.selectAll(".bar") .data(perDay) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.day); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.time); }) .attr("height", function(d) { return height - y(d.time); }); // add the x Axis perDayElem.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); // y axis perDayElem.append("g") .call( d3.axisLeft(y) .tickFormat(formatHMS) ); /** TIME PER PROJECT **/ d3.select("body").append("h1").text("Working time per project") var perProjectElem = d3.select("body").append("svg") .attr("id", "perProject") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); perProject = $perProject; x.domain(perProject.map(function(d) { return d.project; })); y.domain([0, d3.max(perProject, function(d) { return d.time; })]); perProjectElem.selectAll(".bar") .data(perProject) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.project); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.time); }) .attr("height", function(d) { return height - y(d.time); }); // add the x Axis perProjectElem.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); perProjectElem.append("g") .call( d3.axisLeft(y) .tickFormat(formatHMS) ); /** TIME PER ISSUE **/ d3.select("body").append("h1").text("Working time per issues") var perIssueElem = d3.select("body").append("svg") .attr("id", "perIssues") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); perIssues = $perIssue; x.domain(perIssues.map(function(d) { return d.issue; })); y.domain([0, d3.max(perIssues, function(d) { return d.time; })]); perIssueElem.selectAll(".bar") .data(perIssues) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.issue); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.time); }) .attr("height", function(d) { return height - y(d.time); }); // add the x Axis perIssueElem.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); perIssueElem.append("g") .call( d3.axisLeft(y) .tickFormat(formatHMS) );
const redux = require('redux') const combineReducers = redux.combineReducers // 商品 const products = (state = {}, action) => { return state } // おかいものカート const cart = (state = [], action) => { switch(action.type){ case 'ADD_PRODUCT': return [...state, action.payload] default: return state } } // item + computed module.exports = combineReducers({ cart: cart, products: products })
export { ReceiveFundsMobileFooter } from './receive-funds-mobile-footer';
import { createMessagesReducer, createMessage, createSelector } from 'redux-msg'; export const NAME = 'just-input'; export const MODEL = { value: '' }; export const reducer = createMessagesReducer(NAME)(MODEL); export const message = createMessage(NAME); export const select = createSelector(NAME)(MODEL); export const changeValue = value => message({ value }, 'change value');
import React from 'react'; import "./Feed.css" class Feed extends React.Component { constructor(props){ super(props) } render() { return ( <div class="parent-div-feed"> <div class="feed-div"> <div class="feed-input"> <div class="feed-p"> <p>با عضویت در خبرنامه از بیشنهاد های شگفت انگیز ما زود تر از بقیه باخبر میشین</p> </div> <button> <p>عضویت در خبرنامه</p> </button> <input type="email" placeholder="آدرس ایمیلتان را وارد کنید"></input> </div> </div> <div class="img-div-feed"> <img src={require("./feedimg.png")}></img> </div> </div> ) } } export default Feed;
describe('Programs list view', function() { beforeEach(() => { cy.visit('/en/programs/'); cy.injectAxe(); }); it('passes axe a11y checks', () => { cy.contains('Programs') cy.checkA11y(); }); });
import '@testing-library/jest-dom'; import { server } from './mocks/server'; class ResizeObserver { disconnect() {} observe() {} unobserve() {} } window.ResizeObserver = ResizeObserver; process.env.GATSBY_ADDSEARCH_API_KEY = 'shh-do-not-tell-to-anyone'; jest.mock('@ably/ui/src/core/utils/syntax-highlighter', () => ({ highlightSnippet: jest.fn, registerDefaultLanguages: jest.fn, })); jest.mock('@ably/ui/src/core/utils/syntax-highlighter-registry', () => ({ __esModule: true, default: [], })); // Establish API mocking before all tests. beforeAll(() => server.listen()); // Reset any request handlers that we may add during the tests, // so they don't affect other tests. afterEach(() => server.resetHandlers()); // Clean up after the tests are finished. afterAll(() => server.close());
import React, { useEffect, useState } from 'react'; import Sidebar from '../../Sidebar/Sidebar'; import OrderItem from './OrderItem/OrderItem'; const Orders = () => { const [orders, setOrders] = useState([]); useEffect(() => { fetch('https://insurance-agency-server.herokuapp.com/orders') .then(res => res.json()) .then(data => setOrders(data)) }, []) return ( <div className="container-fluid row"> <div className="col-md-2 pl-0"> <Sidebar></Sidebar> </div> <div className="col-md-10"> <div className="container mt-5"> <div className="row"> <table className="table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Email</th> <th scope="col">Service</th> <th scope="col">price</th> <th scope="col">Status</th> </tr> </thead> <tbody> { orders.map(pd => <OrderItem key={pd._id} order={pd}></OrderItem>) } </tbody> </table> </div> </div> </div> </div> ); }; export default Orders;
$(function(){ //轮播图 picShow(picInfo); }); var picInfo=[{ "img":"images/bg1.jpg", "title":"CHINA IMPORTED FRUITS MARKET PRICE", "url":"", "detail":"Guidance Before Quoting", "buttonInfo":"Read More" },{ "img":"images/bg2.jpg", "title":"Global Fruits Arrival Data ", "url":"", "detail":"Guidance before delivery", "buttonInfo":"Read More" },{ "img":"images/bg3.jpg", "title":"Post selling<br/><span> & buying Information </span>", "url":"", "detail":"Attract new business conversation", "buttonInfo":"Read More" },{ "img":"images/bg4.jpg", "title":"Industrial News <br/> & Announcements", "url":"", "detail":"Industry news Business Promotion Campaign<br/>Intergrated Knowledge About Importing Fruits", "buttonInfo":"Read More" },{ "img":"images/bg5.jpg", "title":"Company Profile Display, Registration Free to create and edit ", "url":"", "detail":"More Business Opportunites", "buttonInfo":"Read More" }]; function picShow(picInfo) { if(!picInfo) { return false; } genelatePic(picInfo); } var $picShow = $('#picShow'); var $smallNav = $('#smallNav'); var picData = $picShow.get(0); function genelatePic(picInfo){ var str1='',str2=''; $picShow.add($smallNav).html(''); for(var i=0;i<picInfo.length;i++){ str1 += '<li class="picLi" > <img src="../images/bg1.jpg" style="width:100%;height:auto;max-width:100%;"/><div class="wrap"><div class="title"><h2>'+picInfo[i].title +'</h2><hr class="line"/><div class="moreDetail">'; str1 += '<a class="smalltext" href='+picInfo[i].url +'><span class="pictext2">'+picInfo[i].detail +'</span><span class="picArrow"><em>'+picInfo[i].buttonInfo +'</em><svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg_arrow"></use></svg></span></a></div></div></div></li>'; if(i==0){ str2 +='<li class="bg"></li>'; }else{ str2 +='<li></li>'; } } $picShow.html(str1); $smallNav.html(str2); picData.complete=true; if(!picData.complete){ return false; } picData.len = picInfo.length; picData.num = -1; scrollPic(); $('#boxPrev').click(function(){ clearInterval(picData.time); picData.num = $("#smallNav .bg").index(); if(picData.num==0){ picData.num = picData.len-1; }else{ picData.num =picData.num-1; } changePic(picData.num); }); $('#boxNext').click(function(){ clearInterval(picData.time); picData.num = $("#smallNav .bg").index(); picData.num= (picData.num +1)% picData.len; changePic(picData.num ); }); $("#smallNav li").each(function(i,elem){ $('#picShow li').eq(i).attr("id","pic"+i); $(elem).click(function(){ var index = $(this).index(); changePic(index ); }); }); } function scrollPic(){ //autoPic(); $("#smallNav li").hover(function(){ clearInterval(picData.time); },function(){ autoPic(); }) } function autoPic(){ picData.time=setInterval(function(){ junmper() },6000); } function junmper() { picData.num++; if(picData.num > picData.len) { picData.num = 0; } changePic(picData.num); } function changePic(index) { var $target = $(".nav ul li").eq(index); var $target2 = $(".pic ul li").eq(index); $target.addClass("bg").siblings().removeClass("bg"); $target2.fadeIn().siblings().hide(); }
var express= require("express"); var app = express(); var restRouter = require("./routes/rest.js"); var mongoose = require("mongoose"); var config = require("./config.js"); var server = require('http').Server(app); var io = require('socket.io')(server); mongoose.connect(config.path); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.use("/api/v1", restRouter); var UserController = require('./user/UserController'); app.use('/api/v1/auth', UserController); app.listen(3000, function(){ console.log("App started listening on port 3000"); });
const { createTask } = require("./utils"); // ------------------------------------------------------------------------------------- const { fillPayNewForm, openSettings } = require("./functions/pay.google.com"); const { addNewAdsAccount, selectAdsAccountToWorkWith, createAdsAccountInExpertMode, setupBilling, insertScript, runScript, } = require("./functions/ads.google.com"); // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------- // createTask(func, descs, url); const openPaySettings = async () => { const name = "openPaySettings"; const url = "https://pay.google.com/gp/w/u/0/home/settings?hl=en"; const descs = [ "Result of the function is added card to payment profile", "Manual execution: ", " -- be sure that payment profile added to account", " -- card added to payment profile", ]; return await createTask(openSettings, descs, url, name); }; const createPHAdsAccount = async () => { const name = "createPHAdsAccount"; const url = "https://ads.google.com/selectaccount?hl=en"; const descs = [ "Result of the function is created account for Philippines", "Manual execution: ", " -- be sure that ads account creted on philippines and currency is PHP", ]; return await createTask(addNewAdsAccount, descs, url, name); }; const selecAdsAccountToWork = async () => { const name = "selecAdsAccountToWork"; const url = "https://ads.google.com/selectaccount?hl=en"; const descs = [ "Simply select ads account.", "Manual execution: ", " -- Add account id in field 'current', and continue execution", ]; return await createTask(selectAdsAccountToWorkWith, descs, url, name); }; const createAdsAccountinExpertMode_taskCreator = async () => { const name = "createAdsAccountinExpertMode"; const url = "https://ads.google.com/selectaccount?hl=en"; const descs = [ "Create account in Expert mode without campaigns", "Manual execution: ", " -- Create account ", " -- select Philippines Country", " -- select PHP currency", ]; return await createTask(createAdsAccountInExpertMode, descs, url, name); }; const taskSetupBillingInAdsAccount_taskCreator = async () => { const name = "setupBillingInAdsAccount"; const url = "https://ads.google.com/selectaccount?hl=en"; const descs = [ "Setup billing with philippines payment profile", "Manual execution: ", " -- Open billing summaty ", " -- select Philippines Country", " -- select added earlier card", " -- save setup", ]; return await createTask(setupBilling, descs, url, name); }; const taskScriptAddedInAdsAccount_creator = async () => { const name = "taskScriptAddedInAdsAccount"; const url = "https://ads.google.com/selectaccount?hl=en"; const descs = [ "Insert script to execute in account and save it", "Manual execution: ", " -- Open script manager ", " -- create new script", " -- insert code", " -- save script ", ]; return await createTask(insertScript, descs, url, name); }; const taskScriptLaunchedInAdsAccount_creator = async () => { const name = "taskScriptLaunchedInAdsAccount"; const url = "https://ads.google.com/selectaccount?hl=en"; const descs = [ "Setup script schedule", "Manual execution: ", " -- Open script manager ", " -- setup schedule for our script 'Hourly'", ]; return await createTask(runScript, descs, url, name); }; async function enrichTasksWithFunctions(steps, session) { session.funcs = {}; console.log("enrichTasksWithFunctions ...."); console.log("steps.length", steps.length); for (let s of steps) { const { name } = s; if (name === "openPaySettings") { s.main = openSettings; } if (name === "createPHAdsAccount") { s.main = addNewAdsAccount; } session.funcs[name] = s; } } module.exports = { openPaySettings, createPHAdsAccount, enrichTasksWithFunctions, selecAdsAccountToWork, createAdsAccountinExpertMode_taskCreator, taskSetupBillingInAdsAccount_taskCreator, taskScriptAddedInAdsAccount_creator, taskScriptLaunchedInAdsAccount_creator, };
var eeModal = (function (eeUtil) { var body, modal; var methods = { open: open }; function open(tpl) { body = document.getElementsByTagName('BODY')[0]; if (modal) { return modal; } modal = new Modal(tpl); return modal; } var Modal = function (tpl) { var _self = this; var container = document.createElement('DIV'); container.className = 'ee-modal-container'; var bg = document.createElement('DIV'); bg.className = 'ee-modal-bg'; var modalView = document.createElement('DIV'); modalView.className = 'ee-modal'; bg.addEventListener('click', function () { //todo flag in cfg? _self.close(); }); modalView.innerHTML = tpl; container.appendChild(bg); container.appendChild(modalView); body.appendChild(container); eeUtil.toggleClass(body, 'ee-modal-open', true); this.container = container; return this; }; Modal.prototype.close = function () { body.removeChild(this.container); eeUtil.toggleClass(body, 'ee-modal-open', false); modal = undefined; }; return methods; }(eeUtil));
export * from './modular'
class Enemy extends Phaser.GameObjects.Sprite{ constructor(scene, x, y, texture, frame, index) { super(scene, x, y, texture, frame); scene.add.existing(this); scene.physics.add.existing(this); this.setOrigin(0.5, 1); this.body.allowGravity = false; this.body.setSize(48, 48, 16, 0); this.body.setVelocity(-100, 0).setBounce(1).setCollideWorldBounds(true); this.idx = index; this.initialY = y; this.jsonObj = []; this.past_pos = []; const enterPlatePlayer = (_this, _player) => { _player.kill(); this.clock = this.scene.time.delayedCall(1000, () => { _player.scene.scene.restart(); // restart current scene }, null, this); }; scene.physics.add.overlap( this, scene.player, enterPlatePlayer, null, this ); scene.doors.forEach(door => { scene.physics.add.collider(door, this); }); this.createAnims(); this.anims.play("walk"); scene.enemyEmitters.push(this.scene.particleManager.createEmitter({ x: x, y: y-60, angle: { min: 180, max: 360 }, // try adding steps: 1000 👍 speed: { min: 50, max: 200, steps: 5000 }, frequency: 200, gravityY: 980, lifespan: 800, quantity: 6, scale: { start: 0.1, end: 0.5 }, tint: [ 0xff9000, 0xff0000], bounce: { min: 0.5, max: 0.9, steps: 5000 }, bounds: { x: this.x-1000, y: this.y, w: 2000, h: 0 }, collideTop: false, collideBottom: true, })); } update(){ if (!this.scene.player.teleporting){ this.addTimeStamp(); } this.scene.enemyEmitters[this.idx].setPosition(this.x, this.y - 50); if (this.body.velocity["x"] < 0){ this.flipX = true; } else { this.flipX = false; } if (this.body.velocity["y"] != 0){ this.body.setVelocityY(0); } if (this.y != this.initialY){ this.y = this.initialY; } } addTimeStamp(){ let item = {}; item ["x"] = this.x; item ["forwards"] = this.body.velocity["x"] > 0; // If we are exceeding the maximum recorded actions, remove the first elem of jsonObj if (this.jsonObj.push(item) >= this.scene.player.TIME_JUMP){ this.past_pos = this.jsonObj.shift(); } else { this.past_pos = this.jsonObj[0]; } } revert(){ let tween = this.scene.tweens.add({ targets: this, x: { from: this.x, to: this.past_pos["x"] }, ease: Phaser.Math.Easing.Quadratic.InOut, // 'Cubic', 'Elastic', 'Bounce', 'Back' duration: this.scene.player.TELEPORT_TIME, repeat: 0, // -1: infinity yoyo: false }); if (this.past_pos['forwards']){ this.body.setVelocity(100, 0); } else { this.body.setVelocity(-100, 0); } this.jsonObj = []; } createAnims(){ // Setup Walk Animation this.anims.create({ key: 'walk', frames: this.anims.generateFrameNames('enemy', { prefix: 'walk', start: 1, end: 7 }), frameRate: 8, repeat: -1 }); } }
require('./server') require('../app/main')
import { extend } from 'flarum/extend'; import app from 'flarum/app'; import Post from 'flarum/models/Post'; import Model from 'flarum/Model'; import NotificationGrid from 'flarum/components/NotificationGrid'; import addReactionAction from 'datitisev/reactions/addReactionAction'; import PostReactedNotification from 'datitisev/reactions/components/PostReactedNotification'; // import addLikesList from 'datitisev/reactions/addLikesList'; app.initializers.add('datitisev-reactions', () => { app.notificationComponents.postReacted = PostReactedNotification; Post.prototype.canReact = Model.attribute('canReact'); Post.prototype.reactions = Model.hasMany('reactions'); addReactionAction(); extend(NotificationGrid.prototype, 'notificationTypes', function (items) { items.add('postReacted', { name: 'postReacted', icon: 'smile-o', label: app.translator.trans('flarum-likes.forum.settings.notify_post_reacted_label') }); }); });
import React from 'react'; import "./WhiteboardMastDetails.css"; const WhiteboardMastDetails = () => { return ( <div className="row"> <img className="col-4 wbmastimg" src={require("../../img/poster.gif")} alt={"pm"}/> <h2 className="col-8 wbmasthdr">THE WHITEBOARD IS A VALUABLE TOOL USED IN PROJECT MANAGEMENT. USE IT TO HELP YOUR TEAM "VISUALIZE" YOUR PROJECT, DEVELOP AND SHARE IDEAS, OR DESIGN YOUR PROJECT'S STRUCTURE"</h2> </div> ); } export default WhiteboardMastDetails;
#!/usr/bin/node const args = process.argv; if (isNaN(args[2])) { console.log(1); } else { console.log(factorial(args[2])); } function factorial (num) { if (num === 0) { return (1); } else { return (num * factorial(num - 1)); } }
$(document).ready(function () { var tabInfoCompte; //Permet de get les infos du compte en BDD $.ajax({ type: "POST", // methode de transmission des données au fichier php url: "php/getInfosCompte.php", // url du fichier php success: function (msg) { tabInfoCompte = jQuery.parseJSON(msg); //On parse le JSON //Remplissage des champs $('#nom').val(tabInfoCompte["nom"]); $('#prenom').val(tabInfoCompte["prenom"]); $('#mail').val(tabInfoCompte["mail"]); $('#derby_name').val(tabInfoCompte["derby_name"]); } }); $('#changePassword').modal(); });
var express = require('express') var app = express() app.use(express.static('public')) app.listen(80, function () { console.log('Now listening on port 80') })
new (function() { var ext = this; function getVocative(name, callback){ console.log("vocative from",name); $.ajax({ url: 'https://nlp.fi.muni.cz/projekty/declension/names/process.py?np='+name+'&output=json', dataType: 'json', success: function(data){ console.log("success",data); callback(data["name"]); } }); } function getGender(name, callback){ $.ajax({ url: 'https://nlp.fi.muni.cz/projekty/declension/names/process.py?np='+name+'&output=json', dataType: 'json', success: function(data){ callback(data["gender"]); } }); } function getPoliteness(text, callback){ console.log("politeness",text); $.ajax({ url: 'https://nlp.fi.muni.cz/projekty/topicks/rude.py?text='+text+'&format=json', dataType: 'json', success: function(data){ console.log("politeness response",data); callback(data["politeness"]); } }); } function getTopics(sentence, callback){ console.log("topics",sentence); $.ajax({ url: 'https://nlp.fi.muni.cz/projekty/topicks/process.py?text='+sentence+'&format=json', dataType: 'json', success: function(data){ console.log("response",data); callback(data["response"][0]); } }); } function getPolarity(sentence){ console.log("polarity",sentence); $.ajax({ url: 'https://nlp.fi.muni.cz/projekty/declension/names/polarity.py?topic='+sentence+'&output=json', dataType: 'json', success: function(data){ console.log("response",data); return data["polarity"]; } }); } // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { return {status: 2, msg: 'Ready'}; }; // Functions for block with type 'w' will get a callback function as the // final argument. This should be called to indicate that the block can // stop waiting. ext.get_vocative = function(name, callback) { var name = name.replace(/ /g, "+"); console.log('Getting vocative for ' + name+", callback "+callback); getVocative(name, callback); }; ext.get_gender = function(name, callback) { var name = name.replace(/ /g, "+"); console.log('Getting gender for ' + name+", callback "+callback); getGender(name, callback); }; ext.get_polarity = function(sentence) { var sentence = sentence.replace(/ /g, "+"); console.log('Getting polarity for ' + sentence+", callback "+callback); getPolarity(polarity); }; ext.get_topics = function(sentence, callback) { var sentence = sentence.replace(/ /g, "+"); console.log('Getting topics for ' + sentence+", callback "+callback); getTopics(sentence, callback); }; ext.get_politeness = function(sentence, callback) { var sentence = sentence.replace(/ /g, "+"); console.log('Getting politeness level for ' + sentence+", callback "+callback); getPoliteness(sentence, callback); }; // Block and block menu descriptions var descriptor = { blocks: [ ['R', 'Get vocative for the name %s', 'get_vocative', 'kamarád'], ['R', 'Get gender for the name %s', 'get_gender', 'm'], ['b', 'Get polarity for sentence %s', 'get_polarity', 1], ['R', 'Get topics for sentence %s', 'get_topics', ''], ['R', 'Get politeness level for sentence %s', 'get_politeness', ''], ] }; // Register the extension ScratchExtensions.register('Czech chatbot support', descriptor, ext); })({});
import React, { Component } from 'react' import {Row,Col } from 'react-bootstrap'; import Ownericon from './images/ownericon.png'; export class ownerdetails extends Component { render() { return ( <div className="text img-thumbnail thumbnailnext" id="ca9c4a"> <h4>Himanshu</h4> <h6>Owner</h6> <div className="interestedformownerdetails"> <h6>+9123XXX345678</h6> <button className="propertydetailsbutton">Click to view Number</button> </div> </div> ) } } export default ownerdetails
const initialState = { todoID: 0, todos:[] }; export default (state = initialState, action) => { const { todos, todoID } = state; const { type, payload } = action; switch (type) { case 'ADD_TODO': { return {...state, todoID:todoID+1, todos:[{ id: (todoID + 1), text: payload }, ...todos]}; } case 'REMOVE_TODO': return state.todos.filter(todo => todo.id !== payload); // pendiente de ver si funciona default: return state; } }; /* approach: case 'ADD_TODO': { return {...state, todos:[{ id: (todoID + 1), text: payload }, ...todos]}; } esto me esta generando keys duplicadas, ya que no se esta seteando el nuevo ID en el state alternativa para no mutar el todoID del state? */
const jwt = require('jsonwebtoken'); // const jwtDecode = require('jwt-decode'); const UserConstants = require('../services/util.service').UserConstants; function verifyToken(_token){ // console.log(_token) let validToken = false; let decoded="Nothing"; try{ const isValid = jwt.verify(_token,UserConstants.jwt.key); // console.log(isValid) if(isValid){ validToken = isValid; // decoded = jwt_decode(token); // console.log(decoded); } }catch(error){ } return validToken ; } module.exports={ verifyToken }
const CONTACTS = 'contacts'; const MY_WALLETS = 'my-wallets'; const RECEIVE_FUNDS = 'receive-funds'; const SEND_FUNDS = 'send-funds'; export const ROUTES = { CONTACTS, MY_WALLETS, RECEIVE_FUNDS, SEND_FUNDS, };
var config = { apiKey: "AIzaSyCFdh7BeiKB9Gzgsv5XwgJoecodrCqPJAU", authDomain: "train-e4dfb.firebaseapp.com", databaseURL: "https://train-e4dfb.firebaseio.com", projectId: "train-e4dfb", storageBucket: "", messagingSenderId: "550458782796" }; firebase.initializeApp(config); // Create a variable to reference the database var database = firebase.database(); // Capture Button Click $("#submit").on("click", function (event) { // prevent page from refreshing when form tries to submit itself event.preventDefault(); // creating vars for storing input info var trainName = $("#train-name").val().trim(); var destinN = $("#destination").val().trim(); var firstTrain = moment($("#first-train").val().trim(), "HH:mm").format("X"); var freqCy = $("#frequency").val().trim(); // Console log each of the user inputs to confirm we are receiving them var newTrain = { name: trainName, destiNew: destinN, firstArriv: firstTrain, frequan: freqCy }; database.ref().push(newTrain); console.log(newTrain.name); console.log(newTrain.destiNew); console.log(newTrain.firstArriv); console.log(newTrain.frequan); // Alert alert("New Train successfully added"); // Clear all of the text-boxes $("#train-name").val(""); $("#destination").val(""); $("#first-train").val(""); $("#frequency").val(""); }); // Create Firebase event for adding new train to the database and a row in the html when a user adds an entry database.ref().on("child_added", function (childSnapshot, prevChildKey) { console.log(childSnapshot.val()); // Store everything into a variable. var trainName = childSnapshot.val().name; var destinN = childSnapshot.val().destiNew; var firstTrain = childSnapshot.val().firstArriv; var freqCy = childSnapshot.val().frequan; // Train Info console.log(trainName); console.log(destinN); console.log(firstTrain); console.log(freqCy); // Prettify the arrival time var now = moment().format("HH:mm") //var now = moment().format("HH:mm:ss a"); $("#headerClock").text("Current Time: " + now); // First Time (pushed back 1 year to make sure it comes before current time) var newArrivalTime = moment(firstTrain, "hh:mm").subtract(1, "years"); console.log("newArrivalTime:" + newArrivalTime); //calculate the minutes left to the next arrival var diffTime = moment().diff(moment(newArrivalTime), "minutes"); console.log("DIfference in time: " + diffTime); //Time apart var tRemainder = diffTime % freqCy; console.log(tRemainder); //Minutes Until Train var tMinutesTillTrain = freqCy - tRemainder; console.log("Minutes Till this Train: " + tMinutesTillTrain); //Next Train var nextTrain = moment().add(tMinutesTillTrain, "minutes").format("HH:mm"); console.log("Arrival Time: " + moment(nextTrain)); //Add each train's data into the table $("#train-table > tbody").append("<tr><td>" + trainName + "</td><td>" + destinN + "</td><td>" + freqCy + "</td><td>" + nextTrain + "</td><td>" + tMinutesTillTrain + "</td></tr>"); });
const EventEmitter = require("events"); class Emitter extends EventEmitter{ } let emitter = new Emitter(); /* emitter.on("test",()=>{ console.log("hello"); }) */ emitter.on("test",(arg1,arg2)=>{ console.log(arg1,arg2); }) emitter.emit("test","hello","world");
const CategoryModel = require('../models/category'); module.exports.createCategory = async (req, res) => { if (req.body && req.userId) { try { const data = req.body; data.userId = req.userId; const doc = await CategoryModel.create(data); if (doc) res.send({ msg: 'Create successfully!', data: doc }); } catch (err) { console.error(err); res.status(500).send({ msg: 'Internal server error', err }); } } else { res.status(401).send({ msg: 'Missing required fields' }); } } module.exports.updateCategory = async (req, res) => { if (req.params.categoryId) { try { const doc = await CategoryModel.findByIdAndUpdate({ _id: req.params.categoryId }, { $set: req.body }, { new: true }) .exec(); if (doc) { const data = await CategoryModel.findById(req.params.categoryId).exec(); res.send({ msg: 'Updated successfully!', data: data }); } else { res.status(404).send({ msg: 'Data not found', err }); } } catch (err) { console.error(err); res.status(500).send({ msg: 'Internal server error', err }); } } else { res.status(401).send({ msg: 'Missing required fields' }); } } module.exports.deleteCategory = async (req, res) => { if (req.params.categoryId) { try { const doc = await CategoryModel.findByIdAndDelete(req.params.categoryId).exec(); if (doc) res.send({ msg: 'Deleted successfully!', data: doc }); } catch (err) { console.error(err); res.status(500).send({ msg: 'Internal server error', err }); } } else { res.status(401).send({ msg: 'Missing required fields' }); } } module.exports.getCategory = async (req, res) => { if (req.params.categoryId) { try { const doc = await CategoryModel.findById(req.params.categoryId).exec(); if (doc) res.send({ msg: 'Query successfull!', data: doc }); } catch (err) { console.error(err); res.status(500).send({ msg: 'Internal server error', err }); } } else { res.status(401).send({ msg: 'Missing required fields' }); } } module.exports.getCategories = async (req, res) => { if (req.userId) { const where = { userId: req.userId }; if ('isDeleted' in req.query) where.isDeleted = req.query.isDeleted; const docs = await CategoryModel.find(where) .exec(); res.send({ msg: 'Query successfully', data: docs }); } else { res.status(401).send({ msg: 'Missing required fields' }); } }
var express = require('express'); var router = express.Router(); // router.get('/', function(req, res, next) { // res.sendFile(__dirname + "/views/item.html"); // }); var test = "Test Object Name"; router.get('/item', function(req, res) { console.log("item.js route used") res.render(__dirname + '/views/item.html', { name:test, price:"$900" }); }); module.exports = router;
//config file for mongo var config = {}; config.mongoURI = { test: 'mongodb://localhost/travis-test', development: 'mongodb://localhost/travis' }; module.exports = config;
import React, { useState } from 'react'; import { Container, Button, Form } from 'react-bootstrap'; import axios from 'axios'; const ResetPassword = () => { const [email, setEmail] = useState(null); const handleSubmit = (event) => { event.preventDefault(); const form = event.target; axios .get(`/api/password?email=${email}`) .then((res) => { console.log(res); form.reset(); }) .catch((error) => console.log(error)); }; return ( <div id="background" style={{ color: 'white' }}> <Container className="d-flex flex-column align-items-center justify-content-center fullscreen"> <h1 className="mt-5">Reset Password</h1> <Form onSubmit={handleSubmit}> <Form.Group> <Form.Label className="mt-3">Email address</Form.Label> <Form.Control type="email" required autoComplete="off" onChange={(event) => setEmail(event.target.value)} /> </Form.Group> <Form.Group> <Button className="mt-1" type="submit"> Send Email </Button> </Form.Group> </Form> </Container> </div> ); }; export default ResetPassword;
'use strict'; angular.module('instangularApp').controller('MainCtrl', function ($scope) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; $scope.greet = function(){ $scope.message = 'hi, ' + $scope.user.name; }; $scope.herro = { something : 'herro' }; $scope.developers = [ { name: "Jesus", country: "Spain" }, { name: "Dave", country: "Canada" }, { name: "Wesley", country: "USA" }, { name: "Krzysztof", country: "Poland" } ]; $scope.attemptLogout = function(){ var that = this; console.log('hey'); $.ajax({ url: "/home", type: "POST", data: {logout : true}, success: function(data){ //that.showLockedAlert('You are now logged out.<br>Redirecting you back to the homepage.'); console.log('logged out') }, error: function(jqXHR){ console.log(jqXHR.responseText+' :: '+jqXHR.statusText); } }); } });
var mongoose = require('mongoose'); // keeps track of any deleted user profiles var deletedUserSchema = new mongoose.Schema( { user: {type: mongoose.Schema.Types.Mixed, required: true} }); module.exports = mongoose.model('Deleted_User', deletedUserSchema);
import React from 'react'; import NewQuoteButton from './NewQuoteButton'; import TweetButton from './TweetButton'; export default function QuotePanel(props) { const { text, author, newQuoteHandler, isLoading } = props; return ( <div className="box"> <div className="hero"> <div className="hero-body"> <h1 className="title"> <span className="icon is-medium"> <i className="fa fa-quote-left" /> </span> {text} <span className="icon is-medium"> <i className="fa fa-quote-right" /> </span> </h1> <h2 className="subtitle is-pulled-right">- {author}</h2> </div> <div className="hero-foot"> <div className="field is-grouped"> <p className="control"> <TweetButton text={text} author={author} isLoading={isLoading} /> </p> <p className="control"> <NewQuoteButton onClickHandler={newQuoteHandler} isLoading={isLoading} /> </p> </div> </div> </div> </div> ); }
/** * @ngdoc component * @name lineChart * @module shared * @param data: A data object in the format * @description A component which is responsible for rendering a line chart based on input data */ (function (angular) { 'use strict'; function LineChartController($element) { var ctrl = this; ctrl.wrapper = $element[0]; ctrl.$onChanges = function (changes) { if (changes.hasOwnProperty('data') && changes.data.currentValue !== null) { ctrl.drawChart(changes.data.currentValue); } }; /** * @ngdoc function * @name drawChart * @param data: a data object * @description Set up and draw the chart */ ctrl.drawChart = function (data) { // Making sure the element we want to draw in is empty. d3 .select(ctrl.wrapper) .selectAll('*') .remove(); var defaultHeight = window.innerHeight / 2; var defaultWidth = window.innerWidth / 2; // initialize the dimensions of the chart. ctrl.chartWrapper = d3.select(ctrl.wrapper) .append("svg") .attr('width', defaultWidth + 'px') .attr('height', defaultHeight + 'px'); var margin = {top: 20, right: 20, bottom: 50, left: 40}; var width = defaultWidth - margin.left - margin.right; var height = defaultHeight - margin.top - margin.bottom; // group all chart components inside a <g> element ctrl.g = ctrl.chartWrapper.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // initialize the scale of the x axis ctrl.x = d3.scaleTime() .rangeRound([0, width]); // initialize the scale of the y axis ctrl.y = d3.scaleLinear() .rangeRound([height, 0]); ctrl.line = d3.line() .x(function(d) { return ctrl.x(d.Date); }) .y(function(d) { return ctrl.y(d.Output); }); ctrl.x.domain(d3.extent(data, function(d) { return d.Date; })); ctrl.y.domain(d3.extent(data, function(d) { return d.Output; })); ctrl.g.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(ctrl.x) .tickFormat(function (d) { var formatTime = d3.timeFormat("%B %d, %Y"); return formatTime(d) })) .select(".domain") .remove(); ctrl.g.append("g") .call(d3.axisLeft(ctrl.y)) .append("text") .attr("fill", "#000") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text(ctrl.yUnit); ctrl.g.append("path") .datum(data) .attr("fill", "none") .attr("stroke", "rgb(76, 175, 80)") .attr("stroke-linejoin", "round") .attr("stroke-linecap", "round") .attr("stroke-width", 1.5) .attr("d", ctrl.line); } } angular.module('shared') .component('lineChart', { bindings: { data: '<', yUnit: '@' }, controller: LineChartController }) })(angular);
// var Tools = global.load_library('Tools') // var project_model = global.load_model('project_model') require(__dirname+'/Client') // fs.readFileSync( __dirname+'/Client.js', 'utf8'); module.exports = class Project extends Client { test(event, req, res, params) { res.sendFile(global.APPPATH+'views/client/index.html'); // res.sendFile(global.APPPATH+'views/client/navbar.html'); } }
import React, { Component } from 'react'; import { AuthService, CartService } from '../../service/index'; import CartGame from './CartGame'; class CartPage extends Component { constructor(props) { super(props); this.state = { games: [], }; } componentDidMount() { this.loadGames(); } render() { return ( <div className={' bg-dark text-white'}> <div className={ 'container-fluid d-flex flex-column justify-content-between bg-dark p-3 h-50' } > <div className={'row'}> <div className={'col-md-10 offset-md-1 border rounded'}> {this.listGames().length === 0 ? ( <div className={ 'd-flex flex-row justify-content-center align-items-center' } > <h1>Cart is empty</h1> </div> ) : ( this.listGames() )} </div> </div> <div className={'bg-dark'}> <div className={'row'}> <div className={ 'd-flex flex-row col-md-10 offset-1 py-3 border rounded' } > <div className={'col-md-6'}> <div className={ 'd-flex flex-row justify-content-start align-items-center h-100' } > <h3>Total:</h3> <h1 className={'px-5'}> {this.state.games.length === 0 ? 0 + ' $' : this.state.games.length === 1 ? this.state.games[0].price : this.state.games.reduce( (v1, v2) => v1.price + v2.price ) + ' $'} </h1> </div> </div> <div className={'col-md-6'}> <div className={ 'd-flex flex-row justify-content-end align-items-center h-100' } > <button onClick={this.clearGames} className={'btn btn-danger h-100 p-3 px-3 mx-3'} > <h4>Clear</h4> </button> <button onClick={this.buyGames} className={'btn btn-primary h-100 p-3 px-4'} > <h4>Buy</h4> </button> </div> </div> </div> </div> </div> </div> </div> ); } listGames = () => { return this.state.games.map((game) => { return ( <CartGame handleGameSelect={this.props.handleGameSelect} handleGameRemove={this.handleGameRemove} game={game} /> ); }); }; handleGameRemove = () => { this.loadGames(); }; loadGames = () => { let user = AuthService.getCurrentUser(); if (user) { CartService.fetchCartGames(user.username).then((response) => { this.setState({ games: response.data, }); }); } }; buyGames = () => { let user = AuthService.getCurrentUser(); if (user) { CartService.buyCart(user.username).then((response) => { this.setState({ games: response.data, }); }); } }; clearGames = () => { let user = AuthService.getCurrentUser(); if (user) { CartService.clearCart(user.username).then((response) => { this.setState({ games: response.data, }); }); } }; } export default CartPage;
module.exports = (sequelize, DataTypes) => { const Game = sequelize.define('Game', { WinnerScore: { type: DataTypes.INTEGER, allowNull: false, }, LoserScore: { type: DataTypes.INTEGER, allowNull: false }, IsTournamentGame: { type: DataTypes.BOOLEAN, defaultValue: false } }); Game.associate = (models) => { Game.belongsTo(models.Player, {foreignKey : 'WinnerId'}); Game.belongsTo(models.Player, {foreignKey : 'LoserId'}); }; return Game; };
const api = "http://localhost:3001" // Generate a unique token for storing data on the backend server. let token = localStorage.token if (!token) token = localStorage.token = Math.random().toString(36).substr(-8) const headers = { 'Accept': 'application/json', 'Authorization': token } // Get all categories for the app export const getCategories = () => fetch(`${api}/categories`, { headers }) .then(res => res.json()) .then(data => data.categories) // Add a new post export const addPost = (post) => fetch(`${api}/posts`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ ...post }) }).then(res => res.json()) // Delete a post export const deletePost = (postId) => fetch(`${api}/posts/${postId}`, { method: 'DELETE', headers }).then(res => res.json()) // Downvote a post export const downVotePost = (postId) => fetch(`${api}/posts/${postId}`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ option: 'downVote' }) }).then(res => res.json()) // Get the details of a single post export const getPost = (id) => fetch(`${api}/posts/${id}`, { method: 'GET', headers }).then(res => res.json()) // Get all of the posts for a particular category // If category is undefined, get all of the posts export const getPosts = (category) => fetch(category ? `${api}/${category}/posts` : `${api}/posts`, { method: 'GET', headers }).then(res => res.json()) // Edit a post export const updatePost = (post) => fetch(`${api}/posts/${post.id}`, { method: 'PUT', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ ...post }) }).then(res => res.json()) // UpVote a post export const upVotePost = (postId) => fetch(`${api}/posts/${postId}`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ option: 'upVote' }) }).then(res => res.json()) // Add a new comment export const addComment = (comment) => fetch(`${api}/comments`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ ...comment }) }).then(res => res.json()) // Delete a comment export const deleteComment = (commentId) => fetch(`${api}/comments/${commentId}`, { method: 'DELETE', headers }).then(res => res.json()) // Downvote a comment export const downVoteComment = (commentId) => fetch(`${api}/comments/${commentId}`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ option: 'downVote' }) }).then(res => res.json()) // Get all the comments for a single post export const getComments = (id) => fetch(`${api}/posts/${id}/comments`, { method: 'GET', headers }).then(res => res.json()) // Edit a comment export const updateComment = (comment) => fetch(`${api}/comments/${comment.id}`, { method: 'PUT', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ ...comment }) }).then(res => res.json()) // Upvote a comment export const upVoteComment = (commentId) => fetch(`${api}/comments/${commentId}`, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ option: 'upVote' }) }).then(res => res.json())
import { Industry } from "../../../db/models/"; const industryQueries = { industryRandom: async () => { const Qty = await Industry.find().countDocuments(); const random = Math.floor(Math.random() * Qty); return await Industry.findOne().skip(random); } }; export default industryQueries;
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const baiseConfig = require('./config'); const plugins = [ new HtmlWebpackPlugin({ title: 'webpack babel react revisited', filename: path.join(baiseConfig.appDist, 'index.html'), }), new ExtractTextPlugin({ filename: "[name].css" }), new webpack.optimize.UglifyJsPlugin({minimize: true}), new webpack.ProvidePlugin({$: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery'}), ]; module.exports = config;
"use strict"; exports.defaultOptions = defaultOptions; exports.Scrollable = exports.defaultOptionRules = exports.ScrollablePropsType = exports.viewFunction = void 0; var _inferno = require("inferno"); var _vdom = require("@devextreme/vdom"); var _base_props = require("../common/base_props"); var _scrollable_props = require("./scrollable_props"); var _scrollable_native = require("./scrollable_native"); var _scrollable_simulated = require("./scrollable_simulated"); var _utils = require("../../../core/options/utils"); var _devices = _interopRequireDefault(require("../../../core/devices")); var _support = require("../../../core/utils/support"); var _widget = require("../common/widget"); var _scrollable_simulated_props = require("./scrollable_simulated_props"); var _excluded = ["aria", "bounceEnabled", "children", "classes", "direction", "disabled", "forceGeneratePockets", "height", "inertiaEnabled", "needScrollViewContentWrapper", "needScrollViewLoadPanel", "onBounce", "onEnd", "onPullDown", "onReachBottom", "onScroll", "onStart", "onStop", "onUpdated", "pullDownEnabled", "pulledDownText", "pullingDownText", "reachBottomEnabled", "reachBottomText", "refreshingText", "rtlEnabled", "scrollByContent", "scrollByThumb", "showScrollbar", "updateManually", "useKeyboard", "useNative", "useSimulatedScrollbar", "visible", "width"]; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var viewFunction = function viewFunction(viewModel) { var _viewModel$props = viewModel.props, aria = _viewModel$props.aria, bounceEnabled = _viewModel$props.bounceEnabled, children = _viewModel$props.children, direction = _viewModel$props.direction, disabled = _viewModel$props.disabled, forceGeneratePockets = _viewModel$props.forceGeneratePockets, height = _viewModel$props.height, inertiaEnabled = _viewModel$props.inertiaEnabled, needScrollViewContentWrapper = _viewModel$props.needScrollViewContentWrapper, needScrollViewLoadPanel = _viewModel$props.needScrollViewLoadPanel, onBounce = _viewModel$props.onBounce, onEnd = _viewModel$props.onEnd, onPullDown = _viewModel$props.onPullDown, onReachBottom = _viewModel$props.onReachBottom, onScroll = _viewModel$props.onScroll, onStart = _viewModel$props.onStart, onStop = _viewModel$props.onStop, onUpdated = _viewModel$props.onUpdated, pullDownEnabled = _viewModel$props.pullDownEnabled, pulledDownText = _viewModel$props.pulledDownText, pullingDownText = _viewModel$props.pullingDownText, reachBottomEnabled = _viewModel$props.reachBottomEnabled, reachBottomText = _viewModel$props.reachBottomText, refreshingText = _viewModel$props.refreshingText, rtlEnabled = _viewModel$props.rtlEnabled, scrollByContent = _viewModel$props.scrollByContent, scrollByThumb = _viewModel$props.scrollByThumb, showScrollbar = _viewModel$props.showScrollbar, updateManually = _viewModel$props.updateManually, useKeyboard = _viewModel$props.useKeyboard, useNative = _viewModel$props.useNative, useSimulatedScrollbar = _viewModel$props.useSimulatedScrollbar, visible = _viewModel$props.visible, width = _viewModel$props.width, restAttributes = viewModel.restAttributes, scrollableNativeRef = viewModel.scrollableNativeRef, scrollableSimulatedRef = viewModel.scrollableSimulatedRef; return useNative ? (0, _inferno.normalizeProps)((0, _inferno.createComponentVNode)(2, _scrollable_native.ScrollableNative, _extends({ "aria": aria, "width": width, "height": height, "disabled": disabled, "visible": visible, "rtlEnabled": rtlEnabled, "direction": direction, "showScrollbar": showScrollbar, "scrollByThumb": scrollByThumb, "updateManually": updateManually, "pullDownEnabled": pullDownEnabled, "reachBottomEnabled": reachBottomEnabled, "forceGeneratePockets": forceGeneratePockets, "needScrollViewContentWrapper": needScrollViewContentWrapper, "needScrollViewLoadPanel": needScrollViewLoadPanel, "onScroll": onScroll, "onUpdated": onUpdated, "onPullDown": onPullDown, "onReachBottom": onReachBottom, "pulledDownText": pulledDownText, "pullingDownText": pullingDownText, "refreshingText": refreshingText, "reachBottomText": reachBottomText, "useSimulatedScrollbar": useSimulatedScrollbar }, restAttributes, { children: children }), null, scrollableNativeRef)) : (0, _inferno.normalizeProps)((0, _inferno.createComponentVNode)(2, _scrollable_simulated.ScrollableSimulated, _extends({ "aria": aria, "width": width, "height": height, "disabled": disabled, "visible": visible, "rtlEnabled": rtlEnabled, "direction": direction, "showScrollbar": showScrollbar, "scrollByThumb": scrollByThumb, "updateManually": updateManually, "pullDownEnabled": pullDownEnabled, "reachBottomEnabled": reachBottomEnabled, "forceGeneratePockets": forceGeneratePockets, "needScrollViewContentWrapper": needScrollViewContentWrapper, "needScrollViewLoadPanel": needScrollViewLoadPanel, "onScroll": onScroll, "onUpdated": onUpdated, "onPullDown": onPullDown, "onReachBottom": onReachBottom, "pulledDownText": pulledDownText, "pullingDownText": pullingDownText, "refreshingText": refreshingText, "reachBottomText": reachBottomText, "inertiaEnabled": inertiaEnabled, "bounceEnabled": bounceEnabled, "scrollByContent": scrollByContent, "useKeyboard": useKeyboard, "onStart": onStart, "onEnd": onEnd, "onBounce": onBounce, "onStop": onStop }, restAttributes, { children: children }), null, scrollableSimulatedRef)); }; exports.viewFunction = viewFunction; var ScrollablePropsType = { useNative: _scrollable_props.ScrollableProps.useNative, direction: _scrollable_props.ScrollableProps.direction, showScrollbar: _scrollable_props.ScrollableProps.showScrollbar, bounceEnabled: _scrollable_props.ScrollableProps.bounceEnabled, scrollByContent: _scrollable_props.ScrollableProps.scrollByContent, scrollByThumb: _scrollable_props.ScrollableProps.scrollByThumb, updateManually: _scrollable_props.ScrollableProps.updateManually, pullDownEnabled: _scrollable_props.ScrollableProps.pullDownEnabled, reachBottomEnabled: _scrollable_props.ScrollableProps.reachBottomEnabled, forceGeneratePockets: _scrollable_props.ScrollableProps.forceGeneratePockets, needScrollViewContentWrapper: _scrollable_props.ScrollableProps.needScrollViewContentWrapper, needScrollViewLoadPanel: _scrollable_props.ScrollableProps.needScrollViewLoadPanel, aria: _widget.WidgetProps.aria, disabled: _base_props.BaseWidgetProps.disabled, visible: _base_props.BaseWidgetProps.visible, inertiaEnabled: _scrollable_simulated_props.ScrollableSimulatedProps.inertiaEnabled, useKeyboard: _scrollable_simulated_props.ScrollableSimulatedProps.useKeyboard }; exports.ScrollablePropsType = ScrollablePropsType; var defaultOptionRules = (0, _utils.createDefaultOptionRules)([{ device: function device(_device) { return !_devices.default.isSimulator() && _devices.default.real().deviceType === "desktop" && _device.platform === "generic"; }, options: { bounceEnabled: false, scrollByContent: _support.touch, scrollByThumb: true, showScrollbar: "onHover" } }, { device: function device() { return !_support.nativeScrolling; }, options: { useNative: false } }]); exports.defaultOptionRules = defaultOptionRules; var Scrollable = /*#__PURE__*/function (_InfernoWrapperCompon) { _inheritsLoose(Scrollable, _InfernoWrapperCompon); function Scrollable(props) { var _this; _this = _InfernoWrapperCompon.call(this, props) || this; _this.state = {}; _this.scrollableNativeRef = (0, _inferno.createRef)(); _this.scrollableSimulatedRef = (0, _inferno.createRef)(); _this.content = _this.content.bind(_assertThisInitialized(_this)); _this.scrollBy = _this.scrollBy.bind(_assertThisInitialized(_this)); _this.update = _this.update.bind(_assertThisInitialized(_this)); _this.release = _this.release.bind(_assertThisInitialized(_this)); _this.refresh = _this.refresh.bind(_assertThisInitialized(_this)); _this.scrollTo = _this.scrollTo.bind(_assertThisInitialized(_this)); _this.scrollToElement = _this.scrollToElement.bind(_assertThisInitialized(_this)); _this.scrollHeight = _this.scrollHeight.bind(_assertThisInitialized(_this)); _this.scrollWidth = _this.scrollWidth.bind(_assertThisInitialized(_this)); _this.scrollOffset = _this.scrollOffset.bind(_assertThisInitialized(_this)); _this.scrollTop = _this.scrollTop.bind(_assertThisInitialized(_this)); _this.scrollLeft = _this.scrollLeft.bind(_assertThisInitialized(_this)); _this.clientHeight = _this.clientHeight.bind(_assertThisInitialized(_this)); _this.clientWidth = _this.clientWidth.bind(_assertThisInitialized(_this)); _this.validate = _this.validate.bind(_assertThisInitialized(_this)); _this.getScrollElementPosition = _this.getScrollElementPosition.bind(_assertThisInitialized(_this)); return _this; } var _proto = Scrollable.prototype; _proto.validate = function validate(e) { return this.scrollableRef.validate(e); }; _proto.content = function content() { return this.scrollableRef.content(); }; _proto.scrollBy = function scrollBy(distance) { this.scrollableRef.scrollBy(distance); }; _proto.update = function update() { this.scrollableRef.update(); }; _proto.release = function release() { return this.scrollableRef.release(); }; _proto.refresh = function refresh() { this.scrollableRef.refresh(); }; _proto.scrollTo = function scrollTo(targetLocation) { this.scrollableRef.scrollTo(targetLocation); }; _proto.scrollToElement = function scrollToElement(element) { this.scrollableRef.scrollToElement(element); }; _proto.scrollHeight = function scrollHeight() { return this.scrollableRef.scrollHeight(); }; _proto.scrollWidth = function scrollWidth() { return this.scrollableRef.scrollWidth(); }; _proto.scrollOffset = function scrollOffset() { return this.scrollableRef.scrollOffset(); }; _proto.scrollTop = function scrollTop() { return this.scrollableRef.scrollTop(); }; _proto.scrollLeft = function scrollLeft() { return this.scrollableRef.scrollLeft(); }; _proto.clientHeight = function clientHeight() { return this.scrollableRef.clientHeight(); }; _proto.clientWidth = function clientWidth() { return this.scrollableRef.clientWidth(); }; _proto.getScrollElementPosition = function getScrollElementPosition(element, direction) { return this.scrollableRef.getElementLocation(element, direction); }; _proto.render = function render() { var props = this.props; return viewFunction({ props: _extends({}, props), scrollableNativeRef: this.scrollableNativeRef, scrollableSimulatedRef: this.scrollableSimulatedRef, validate: this.validate, scrollableRef: this.scrollableRef, restAttributes: this.restAttributes }); }; _createClass(Scrollable, [{ key: "scrollableRef", get: function get() { if (this.props.useNative) { return this.scrollableNativeRef.current; } return this.scrollableSimulatedRef.current; } }, { key: "restAttributes", get: function get() { var _this$props = this.props, aria = _this$props.aria, bounceEnabled = _this$props.bounceEnabled, children = _this$props.children, classes = _this$props.classes, direction = _this$props.direction, disabled = _this$props.disabled, forceGeneratePockets = _this$props.forceGeneratePockets, height = _this$props.height, inertiaEnabled = _this$props.inertiaEnabled, needScrollViewContentWrapper = _this$props.needScrollViewContentWrapper, needScrollViewLoadPanel = _this$props.needScrollViewLoadPanel, onBounce = _this$props.onBounce, onEnd = _this$props.onEnd, onPullDown = _this$props.onPullDown, onReachBottom = _this$props.onReachBottom, onScroll = _this$props.onScroll, onStart = _this$props.onStart, onStop = _this$props.onStop, onUpdated = _this$props.onUpdated, pullDownEnabled = _this$props.pullDownEnabled, pulledDownText = _this$props.pulledDownText, pullingDownText = _this$props.pullingDownText, reachBottomEnabled = _this$props.reachBottomEnabled, reachBottomText = _this$props.reachBottomText, refreshingText = _this$props.refreshingText, rtlEnabled = _this$props.rtlEnabled, scrollByContent = _this$props.scrollByContent, scrollByThumb = _this$props.scrollByThumb, showScrollbar = _this$props.showScrollbar, updateManually = _this$props.updateManually, useKeyboard = _this$props.useKeyboard, useNative = _this$props.useNative, useSimulatedScrollbar = _this$props.useSimulatedScrollbar, visible = _this$props.visible, width = _this$props.width, restProps = _objectWithoutProperties(_this$props, _excluded); return restProps; } }]); return Scrollable; }(_vdom.InfernoWrapperComponent); exports.Scrollable = Scrollable; function __createDefaultProps() { return _extends({}, ScrollablePropsType, (0, _utils.convertRulesToOptions)(defaultOptionRules)); } Scrollable.defaultProps = __createDefaultProps(); var __defaultOptionRules = []; function defaultOptions(rule) { __defaultOptionRules.push(rule); Scrollable.defaultProps = _extends({}, __createDefaultProps(), (0, _utils.convertRulesToOptions)(__defaultOptionRules)); }
import React from 'react'; import {Helmet} from "react-helmet"; import Typography from 'typography' import funstonTheme from 'typography-theme-funston' import injectFonts from 'typography-inject-fonts' import Globe from 'react-globe.gl'; import ReactTextCollapse from 'react-text-collapse'; import './App.css'; import {countriesQuery, antoineQuery, booksQuery, maxBillQuery, airAccidentsQuery} from './utils/queries'; import {execute} from './utils/queryParser'; import {StyledSlider, Thumb, Track} from './slider'; const typography = new Typography(funstonTheme) typography.injectStyles() injectFonts(typography) const TEXT_COLLAPSE_OPTIONS = { collapse: false, // default state when component rendered collapseText: '... show query', // text to show when collapsed expandText: '... hide query', // text to show when expanded minHeight: 50, // component height when closed maxHeight: 200, // expanded to textStyle: { // pass the css for the collapseText and expandText here color: "white", fontSize: "20px" } } function App() { const [globeLabels, setGlobeLabels] = React.useState([]); const [currentQuery, setCurrentQuery] = React.useState('Click button to see a query.'); const [booksCounter, setBooksCounter] = React.useState(1000); const [billCounter, setBillCounter] = React.useState(1000); return ( <div className="App"> <header className="App-header"> <Helmet> <meta charSet="utf-8" /> <title>Sparql Visualizer</title> </Helmet> <div style={styles.splitScreen}> <div style={styles.leftPane}> <ReactTextCollapse options={TEXT_COLLAPSE_OPTIONS}> <p> {currentQuery} </p> </ReactTextCollapse> <button color='primary' onClick={() => execute(setGlobeLabels, setCurrentQuery, countriesQuery)} block>Show populations of the World</button> <button color='primary' onClick={() => execute(setGlobeLabels, setCurrentQuery, antoineQuery)} block>Show birthplace of people with name Antoine</button> <button color='primary' onClick={() => execute(setGlobeLabels, setCurrentQuery, airAccidentsQuery)} block>Show air accidents query</button> <br></br> <center> Year of books less than: <StyledSlider min={0} max={2021} defaultValue={booksCounter} renderTrack={Track} renderThumb={Thumb} onChange={val => setBooksCounter(val)} /> </center> <button color='primary' onClick={() => execute(setGlobeLabels, setCurrentQuery, booksQuery(booksCounter))} block>Show books query</button> <br></br> <center> Year of Max Bill's works grater than: <StyledSlider min={1} max={2021} defaultValue={billCounter} renderTrack={Track} renderThumb={Thumb} onChange={val => setBillCounter(val)} /> </center> <button color='primary' onClick={() => execute(setGlobeLabels, setCurrentQuery, maxBillQuery(billCounter))} block>Show max bill query</button> </div> <div style={styles.rightPane}> <Globe globeImageUrl="//unpkg.com/three-globe/example/img/earth-night.jpg" backgroundImageUrl="//unpkg.com/three-globe/example/img/night-sky.png" width={1000} height={1000} labelsData={globeLabels} labelLat={d => d.properties.latitude} labelLng={d => d.properties.longitude} labelText={d => d.properties.name} labelSize={d => Math.sqrt(d.properties.pop_max) * 0.0001} labelDotRadius={d => Math.sqrt(d.properties.pop_max) * 0.00005} labelColor={() => 'rgba(255, 165, 0, 0.75)'} labelResolution={2} /> </div> </div> </header> </div> ); } const styles = { splitScreen: { display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContnent: 'center' }, leftPane: { width: '50%', display: 'flex', flexDirection: 'column', }, rightPane: { width: '50%', }, }; export default App;
module.exports = { 'extends': 'airbnb', 'parser': 'babel-eslint', 'env': { 'jest': true, }, 'rules': { 'linebreak-style': 'off', 'no-use-before-define': 'off', 'react/jsx-filename-extension': 'off', 'react/prefer-stateless-function': 'off', 'import/prefer-default-export': 'off', 'import/no-useless-path-segments': 'off', 'react/forbid-prop-types': 'off', // TODO: see if there is a way to detect style proptypes and remove this 'react/destructuring-assignment': false, 'react/prop-types': 'off', 'no-console': 'off', 'react/no-did-update-set-state':'off' }, };
$(function () { $(document).on("click", ".add-department", function (e) { var $this = $(this); var $container = $this.closest("form").find(".container-add-department"); var index = $container.find(":input").size() + 1; $container.append('<input type="text" style="margin-top:3px;" name="helpdesk_department[]" />'); e.preventDefault(); }); });
import React, { Component } from 'react'; import ExpertCard from './ExpertCard' import axios from 'axios'; import StarRating from 'react-star-rating' class AllExperts extends Component { constructor(props) { super(props); this.state = { members: [], }; } componentDidMount() { axios .get("http://localhost:5000/api/members/getexperts") .then(res => { this.setState({ members: res.data }) console.log(this.state.members) }) .catch(error => console.log("ay 7aga ")); } render() { return ( this.state.members.map((member) => { return <ExpertCard name = {member.name} email = {member.email} Skills = {member.Skills} Available Daily Hours = {member.availableDailyHours} location = {member.location} Review = {member.review}/> }) ); } } export default AllExperts;
/** * Created by czh on 2016/11/16. */ import React, {Component} from 'react'; import Button from 'material-ui/Button'; import {Modal, Table} from 'material-ui'; import {TableBody, TableCell, TableHead, TableRow} from 'material-ui/Table'; import classzz from '@/classes' import {withStyles} from 'material-ui/styles'; import 'jquery' import Spin from '@/components/spin' import Message from '@/components/Message' const styles = theme => ({ primary: classzz.Button.primary, modalCancel: classzz.Button.modalCancel, addDataAuthBtn: { color: 'rgba(0,0,0,0.65)', background: '#fff', float: 'right', marginRight: '20px', marginTop: '5px' }, addNoBtn: { color: 'rgba(0,0,0,0.65)', background: '#DFDFDF', float: 'right', marginRight: '20px', marginTop: '5px', cursor: "not-allowed" } }); @withStyles(styles) class DataPermiss extends Component { constructor(props) { super(props) this.state = { delVisible: false, dataPermissList: [], sort: '', row: '' }; } //type: 1,//0:新增,1测试(测试)2点击测试之后成功(编辑,删除)3点击测试之后失败(取消,确定)4编辑(取消,确定) componentDidMount() { //数据权限列表 if (this.props.menuId) { this.props.actions.getPermissDataAuthListSetParam({menuId: this.props.menuId}, (list) => { let authList = this.getDataAuthList(list, this.state.dataPermissList) this.setState({dataPermissList: authList}) }) } else { this.props.actions.getPermissDataAuthList([]) this.setState({dataPermissList: []}) } } componentWillReceiveProps(nextProps) { if (nextProps.menuId && nextProps.menuId !== this.props.menuId) { this.props.actions.getPermissDataAuthListSetParam({menuId: nextProps.menuId}, (list) => { let authList = this.getDataAuthList(list, this.state.dataPermissList) this.setState({dataPermissList: authList}) }) } if (nextProps.menuId === "" && nextProps.menuId !== this.props.menuId) { this.props.actions.getPermissDataAuthList([]) this.setState({dataPermissList: []}) } } getDataAuthList(data, data1) { let result1 = [] data.forEach((item, i) => { var flag = false; data1.forEach((item1, j) => { if (item1.paramValue) { if (item.paramValue === item1.paramValue) { result1.push(item1); if (data1[j + 1]) { if (data1[j + 1].expanded) { result1.push(data1[j + 1]) } if (data1[j + 1].errMsg) { result1.push(data1) } } flag = true } } }) if (!flag) { if (item.add) { result1.push({...item, type: 0}) } else { result1.push({...item, type: 1}) } } }) return result1; } //关闭弹窗 onModalClose() { this.setState({delVisible: false}) } //新增 onAddedRows() { let result = this.props.data.dataAuthList let resultData = []; if (result[0]) { if (!result[0].add) { result.unshift({add: 1, order: 1, type: 0}) } } else { result.unshift({add: 1, order: 1, type: 0}) } this.state.dataPermissList.forEach((item) => { if (item.type === 4) { resultData.push({...item, type: 1}) } else { resultData.push(item) } }) let authList = this.getDataAuthList(result, resultData) this.setState({dataPermissList: authList}) } //测试 onDataAuthTest(row, rowId) { let dataPerList = this.state.dataPermissList this.props.actions.getPermissDataAuthTest({params: {paramValue: row.paramValue}, load: true}, (list) => { this.props.actions.getPermissDataAuthListSetParam({menuId: this.props.menuId}, (dataList) => { if (typeof(list.data) === 'string') { dataPerList.splice(rowId, 1, {...row, type: 3}, {expanded: true, data: list.data}) } else { dataPerList.splice(rowId, 1, {...row, type: 2}, {expanded: true, data: list.data}) } let authList = this.getDataAuthList(dataList, dataPerList) this.setState({dataPermissList: authList}) }) }) } //编辑 onDataAuthEdit(row, rowId) { let result = this.state.dataPermissList let dataListResult = this.props.data.dataAuthList let resultData = []; if (result[0]) {//删除新增的 if (result[0].add) { result.splice(0, 1) result.splice(rowId - 1, 2, {...row, type: 4}) } else if (result[0].addError) { result.splice(0, 2) result.splice(rowId - 2, 2, {...row, type: 4}) } else { result.splice(rowId, 2, {...row, type: 4}) } } if (dataListResult[0]) {//删除新增的(this.props.data.dataAuthList) if (dataListResult[0].add) { dataListResult.splice(0, 1) } else if (dataListResult[0].addError) { dataListResult.splice(0, 2) } } result.forEach((item, i) => { if (item.type === 4) { if (item.id === row.id) { resultData.push({...item, type: 4}) } else { resultData.push({...item, type: 1}) } } else { resultData.push(item) } }) let authList = this.getDataAuthList(dataListResult, resultData) this.setState({dataPermissList: authList}) } //取消(删除) onDataAuthCancel(row, rowId) { let result = this.state.dataPermissList; if (row.type === 0) {//新增 if (result[rowId + 1]) { if (result[rowId + 1].errMsg) { result.splice(rowId, 2) } else { result.splice(rowId, 1) } } else { result.splice(rowId, 1) } this.setState({dataPermissList: result}) } else if (row.type === 2 || row.type === 1) {//删除(测试成功和测试的) this.setState({delVisible: true, dataPermissList: result, sort: rowId, row: row}) } else if (row.type === 3) {//测试失败的取消(删除) if (row.addError) {//新增 result.splice(rowId, 2) this.setState({dataPermissList: result}) } else {//编辑后测试失败--删除 this.setState({delVisible: true, dataPermissList: result, sort: rowId, row: row}) } } else {//编辑的取消 result.splice(rowId, 1, {...row, type: 1}) this.setState({dataPermissList: result}) } } //保存 onDataAuthSave(row, i) { let result = this.state.dataPermissList; let nameInpVal = $('.nameInpVal' + i).val() let interFaceInpVal = $('.interFaceInpVal' + i).val() if (result[i + 1]) {//删除校验信息 if (result[i + 1].errMsg) { result.splice(i + 1, 1) } } if (result[i + 1]) {//删除测试接口的错误信息 if (result[i + 1].expanded) { result.splice(i + 1, 1) } } let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$/ //ip地址校验 let regLength = /^[\u4e00-\u9fa5_a-zA-Z_]{1,30}$/ //校验 if (nameInpVal === "" && interFaceInpVal === "") { result.splice(i + 1, 0, {errMsg: {error1: '必填项', error2: '必填项'}}) this.setState({dataPermissList: result}) } else if (nameInpVal === "" && interFaceInpVal !== "") { if (!(reg.test(interFaceInpVal))) { result.splice(i + 1, 0, {errMsg: {error1: '必填项', error2: '接口不是正确的url地址'}}) } else { result.splice(i + 1, 0, {errMsg: {error1: '必填项'}}) } this.setState({dataPermissList: result}) } else if (nameInpVal !== "" && interFaceInpVal === "") { if (!(regLength.test(nameInpVal))) { result.splice(i + 1, 0, {errMsg: {error1: '只能包含汉字,英文且30个字节', error2: '必填项'}}) } else { result.splice(i + 1, 0, {errMsg: {error2: '必填项'}}) } this.setState({dataPermissList: result}) } else if (nameInpVal !== "" && interFaceInpVal !== "") { if (!(regLength.test(nameInpVal)) && reg.test(interFaceInpVal)) { result.splice(i + 1, 0, {errMsg: {error1: '只能包含汉字,英文且30个字节'}}) this.setState({dataPermissList: result}) } else if (regLength.test(nameInpVal) && !(reg.test(interFaceInpVal))) { result.splice(i + 1, 0, {errMsg: {error2: '接口不是正确的url地址'}}) this.setState({dataPermissList: result}) } else if (!(regLength.test(nameInpVal)) && !(reg.test(interFaceInpVal))) { result.splice(i + 1, 0, {errMsg: {error1: '只能包含汉字,英文且30个字节', error2: '接口不是正确的url地址'}}) this.setState({dataPermissList: result}) } else {//保存---新增,编辑,测试失败的保存 if (this.props.menuId) { this.props.actions.getPermissDataAuthTest({params: {paramValue: interFaceInpVal}}, (list) => {//测试接口是否可以调用 if (typeof(list.data) === 'string') {//测试失败 if (row.type === 0) {//新增 result.splice(i, 1, { paramKey: nameInpVal, paramValue: interFaceInpVal, type: 3, addError: true }, {expanded: true, data: list.data}) } else { result.splice(i, 1, { ...row, paramKey: nameInpVal, paramValue: interFaceInpVal, type: 3 }, {expanded: true, data: list.data}) } this.setState({dataPermissList: result}) } else { let dataList = this.props.data.dataAuthList if (dataList[0]) {//删除新增数据(自己添加的) if (dataList[0].add) { dataList.splice(0, 1) } } let params = {}; let dataListResult = []; if (row.id) {//3,4 dataList.forEach((item) => { if (item.id === row.id) { dataListResult.push({ paramKey: nameInpVal, paramValue: interFaceInpVal, menuId: this.props.menuId }) } else { dataListResult.push({ paramKey: item.paramKey, paramValue: item.paramValue, menuId: this.props.menuId }) } }) params = {list: dataListResult} } else {//新增 dataListResult = [{ paramKey: nameInpVal, paramValue: interFaceInpVal, menuId: this.props.menuId }]; dataList.forEach((item) => { dataListResult.push({ paramKey: item.paramKey, paramValue: item.paramValue, menuId: this.props.menuId }) }) params = {list: dataListResult} } this.props.actions.getPermissDataAuthAdd(params, (msg) => { if(msg.httpCode === 400){ result.splice(i + 1, 0, {errMsg: {error2: msg.data}}) }else{ this.props.actions.getPermissDataAuthListSetParam({menuId: this.props.menuId}, (dataList) => { let msg = '编辑成功!' if (row.type === 3) {//测试失败 result.splice(i, 2, { ...row, paramKey: nameInpVal, paramValue: interFaceInpVal, type: 1 }) } else if (row.type === 4) { result.splice(i, 1, { ...row, paramKey: nameInpVal, paramValue: interFaceInpVal, type: 1 }) } else { result.splice(i, 1) msg = '新增成功!' } let authList = this.getDataAuthList(dataList, result) Message.success(msg) this.setState({dataPermissList: authList}) }) } }) } }) } else { this.setState({dataPermissList: []}) Message.info("页面信息没保存") } } } } //删除 onModalDeleteSave() { this.props.actions.getPermissDataAuthDel({id: this.state.row.id}, (data) => { this.props.actions.getPermissDataAuthListSetParam({menuId: this.props.menuId}, (list) => {//刷新 let result = this.state.dataPermissList if (result.length !== this.state.sort) {//判断是否有扩展项 result.splice(this.state.sort, 2) } else { result.splice(this.state.sort, 1) } let authList = this.getDataAuthList(list, result) this.setState({delVisible: false, dataPermissList: authList, visible: true}) Message.success("删除成功") }) }) } render() { const {classes} = this.props; const {dataPermissList} = this.state; return ( <div className="dataAuth"> <Spin loading={this.props.data.dataAuthLoad}> <div className="contentTitle">数据权限 {dataPermissList[0] ? dataPermissList[0].add || dataPermissList[0].addError ? AuthorityComponent.default(() => { return ( <Button className={classes.addNoBtn}>新增数据权限</Button> ) }, 'authority_permiss_addData') : AuthorityComponent.default(() => { return ( <Button className={classes.addDataAuthBtn} onClick={() => this.onAddedRows()}>新增数据权限</Button> ) }, 'authority_permiss_addData') : AuthorityComponent.default(() => { return ( <Button className={classes.addDataAuthBtn} onClick={() => this.onAddedRows()}>新增数据权限</Button> ) }, 'authority_permiss_addData') } </div> <div style={{background: '#fff'}} className="dataAuthTable"> <Table className="opreationAuthTable"> <TableHead> <TableRow> <TableCell>数据权限名</TableCell> <TableCell>接口</TableCell> <TableCell>操作</TableCell> </TableRow> </TableHead> <TableBody> {dataPermissList.length > 0 ? dataPermissList.map((row, i) => { if (row.expanded) { return ( <TableRow className="expandRow" key={"expandRow" + i}> <TableCell colSpan="3" className={typeof(row.data) === 'string' ? "errMsg" : ""}> {typeof(row.data) === 'string' ? <div key={'expandError'} className="errMsg">{row.data}</div> : row.data.map((item, j) => { return ( <div key={'expand' + j} className="changShang">{item.name + "(" + item.key + ")"}</div> ) })} </TableCell> </TableRow> ) } else if (row.add) { return ( <TableRow key={"add" + i}> <TableCell><input placeholder="请输入" className={"nameInpVal" + i}/></TableCell> <TableCell><input placeholder="请输入" className={"interFaceInpVal" + i}/></TableCell> <TableCell className='action'> <span style={{marginRight: '5px'}} onClick={(e) => this.onDataAuthSave(row, i)}>确定</span> <span onClick={() => this.onDataAuthCancel(row, i)}>取消</span> </TableCell> </TableRow> ) } else if (row.errMsg) { return ( <TableRow className="expandRow" key={"errMsg" + i}> <TableCell className="errMsg">{row.errMsg.error1 ? row.errMsg.error1 : ''}</TableCell> <TableCell className="errMsg">{row.errMsg.error2 ? row.errMsg.error2 : ''}</TableCell> <TableCell></TableCell> </TableRow> ) } else { return ( <TableRow key={i}> {row.type === 3 || row.type === 4 ? <TableCell><input placeholder="请输入" defaultValue={row.paramKey} className={"nameInpVal" + i}/></TableCell> : <TableCell>{row.paramKey}</TableCell> } {row.type === 3 || row.type === 4 ? <TableCell><input placeholder="请输入" defaultValue={row.paramValue} className={"interFaceInpVal" + i}/></TableCell> : <TableCell>{row.paramValue}</TableCell> } {row.type === 3 || row.type === 4 ? <TableCell className='action'> <span style={{marginRight: '5px'}} onClick={(e) => this.onDataAuthSave(row, i)}>确定</span> <span onClick={() => this.onDataAuthCancel(row, i)}>取消</span> </TableCell> : row.type === 2 ? <TableCell className='action'> {AuthorityComponent.default(() => { return ( <span style={{marginRight: '5px'}} onClick={() => this.onDataAuthEdit(row, i)}>编辑</span> ) }, 'authority_permiss_editData')} {AuthorityComponent.default(() => { return ( <span onClick={() => this.onDataAuthCancel(row, i)}>删除</span> ) }, 'authority_permiss_deleteData')} </TableCell> : <TableCell className='action'> <span style={{marginRight: '5px'}} onClick={() => this.onDataAuthTest(row, i)}>测试</span> {AuthorityComponent.default(() => { return ( <span onClick={() => this.onDataAuthCancel(row, i)}>删除</span> ) }, 'authority_permiss_deleteData')} </TableCell> } </TableRow> ) } }) : <TableRow><TableCell colSpan="4" style={{textAlign: "center",fontSize:'12px'}}>暂无数据</TableCell></TableRow>} </TableBody> </Table> <Modal open={this.state.delVisible} onClose={() => this.onModalClose()}> <div id="myModal"> <Spin loading={this.props.data.dataAuthLoad} wrapperStyle={true}> <div className="modalHeader">提示 <i className="close fa fa-close" onClick={() => this.onModalClose()}></i> </div> <div className="modalContent"> <div className="modalContentMsg">确认要删除该权限吗?</div> <div className="modalContentWarn">删除后不可恢复</div> </div> <div className="modalFooter"> <Button className={classes.modalCancel} onClick={() => this.onModalClose()}>取消</Button> <Button className={classes.primary} onClick={() => this.onModalDeleteSave()}>确定</Button> </div> </Spin> </div> </Modal> </div> </Spin> </div> ); } } export default DataPermiss
(function(){ if (typeof digitnexus == 'undefined') { digitnexus = {}; } if (typeof digitnexus.utils == 'undefined') { digitnexus.utils = { getStringWidthAsPix : function(str) { var span = document.getElementById("widthTester"); if(span == null) { span = document.createElement('span'); } span.style = "font-size:10pt"; document.body.appendChild(span); var oldWidth = span.offsetWidth; span.innerText= str; oldWidth = span.offsetWidth-oldWidth; span.innerHTML=''; if(null != span) { document.body.removeChild(span); } return oldWidth; }, getTimeAsMills: function() { return new Date().getTime(); }, strByteLength: function(str) { var i; var len; len = 0; for (i=0;i<str.length;i++) { if (str.charCodeAt(i)>255) len+=2; else len++; } return len; }, isIngeger: function (value) { if (/^(\+|-)?\d+$/.test(value )){ return true; }else { return false; } }, isFloat: function(value){ if (/^(\+|-)?\d+($|\.\d+$)/.test(value )){ return true; }else{ return false; } } , checkUrl: function (value){ var myReg = /^((http:[/][/])?\w+([.]\w+|[/]\w*)*)?$/; return myReg.test( value ); }, checkEmail: function (value){ var myReg = /^([-_A-Za-z0-9\.]+)@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/; return myReg.test(value); }, checkIP: function (value) { var re=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/; if(re.test( value )) { if( RegExp.$1 <256 && RegExp.$2<256 && RegExp.$3<256 && RegExp.$4<256) return true; } return false; }, getAsync : function(url, data,callback) { if(callback == null) { throw 'callback handler cannot be null'; } this.__ajax(url,data,'GET',true, function (jsonStr, status, xhr) { callback('(' + jsonStr + ')'); }, function(jsonStr, status, xhr){ if(jsonStr.status == 200) { callback('(' + jsonStr.responseText + ')'); }else { //console.log('error: ' + status); callback(null); } }); }, getSync : function(url, data,callback) { this.__ajax(url,data,'GET',false, function (jsonStr, status, xhr) { if(callback != null) { callback('(' + jsonStr + ')'); } }, function(jsonStr, status, xhr){ if(jsonStr.status == 200) { callback('(' + jsonStr.responseText + ')'); } else { //console.log('error: ' + status); callback(null); } }); }, postSync : function(url, data,successhandler, errorHandler) { this.__ajax(url,data,'POST',false,successhandler,errorHandler); }, postAsync : function(url, data,successhandler, errorHandler) { this.__ajax(url,data,'POST',true,successhandler,errorHandler); }, __ajax : function(url, postData, menthod, async, successHandler, errorHandler) { if(successHandler == null) { throw 'success handler cannot be null'; } //handler format : function(data, textStatus, jqXHR) $.ajax({ 'url': url, 'type': menthod, 'data': postData, 'contentType': 'application/json', 'dataType': 'application/json', 'success': successHandler, 'error': errorHandler, 'async': async }); }, extend: function(ctor, superCtor){ var f = function() {}; f.prototype = superCtor.prototype; ctor.prototype = new f(); ctor.prototype.constructor = ctor; } } digitnexus.utils.Constants={ // debug level INFO:'INFO', DEBUG:'DEBUG', ERROR:'ERROR', FINAL:'FINAL', DEFAULT:'DEFAULT' } digitnexus.utils.DebugMessage = function() { //info this.level = digitnexus.utils.Constants.INFO; this.msg = null; this.timeStamp = new Date(); this.nodeId = -1; }; digitnexus.utils.DebugMessage.prototype.toString = function() { var timeStr= ''+ this.timeStamp.getFullYear()+',' + this.timeStamp.getMonth()+ ',' + this.timeStamp.getDate() + ' ' + this.timeStamp.getHours() +':'+ this.timeStamp.getMinutes()+':' +this.timeStamp.getSeconds(); return timeStr +" [" + this.level+ "] Node ID[" + this.nodeId +'] '+ this.msg; } digitnexus.utils.List = function() { this.data = []; } digitnexus.utils.List.prototype.size = function() { if (null == this.data) { return 0; } return this.data.length; }; digitnexus.utils.List.prototype.removeAll = function() { this.data.splice(0,this.data.length); } digitnexus.utils.List.prototype.add = function (element) { if (null == this.data) { return this.data = Array(); } for(var i = 0; i< this.data.length; i++) { if(this.data[i] == null) { this.data[i] = element; return; } } this.data.push(element); }; digitnexus.utils.List.prototype.get = function (index) { if (null == this.data) { return null; } if (index >= this.size()) { return null; } return this.data[index]; }; digitnexus.utils.List.prototype.remove = function (element) { if (null == this.data) { return; } var index = this._getIndex(element); if (index == -1) { return; } this.data.splice(index,1) }; digitnexus.utils.List.prototype.contains = function (element) { if (null == this.data) { return false; } var index = this._getIndex(element); if (index == -1) { return false; } return true; }; digitnexus.utils.List.prototype.removeAll = function () { if (null == this.data) { return; } for ( var index = 0; index < this.data.length; index++) { if (null == this.data[index]) { continue; } this.data.splice(index,1) } }; digitnexus.utils.List.prototype.addAll = function (elements) { if (null == elements || elements.size() < 0) { return; } if(null == this.data) { this.data = new Array(); } for ( var index = 0; index < this.elements.length; index++) { if (null == this.elements[index]) { continue; } this.data.push(this.elements[index]); } }; /** * .Hide */ digitnexus.utils.List.prototype._getIndex = function(element) { if (null == this.data) { return -1; } var result = -1; for ( var index = 0; index < this.data.length; index++) { if (null == this.data[index]) { continue; } if (this.data[index].equals(element)) { result = index; break; } } return result; }; /** * ***************************Set class similar to java.util.Set * interface********************** */ /** * This implementation is very strange that set inherit from List. just work * well for me! will be modified if any problem occurs. */ digitnexus.utils.Set = function() { digitnexus.utils.List.apply(this, arguments); }; digitnexus.utils.Set.prototype = new digitnexus.utils.List(); digitnexus.utils.Set.prototype.constructor = digitnexus.utils.Set; /** * Overwrite this method to guarantee every element is unique in the set. If * the added element is exist, delete the old element before adding. Must * overwrite the equals() method of the element if need */ digitnexus.utils.Set.prototype.add = function(element) { if (null == this.data) { return this.data = Array(); } if (this.contains(element)) { this.remove(element); } this.data.push(element); }; digitnexus.utils.Set.prototype.contains = function (element) { if (null == this.data) { return false; } var index = this._getIndex(element); if (index == -1) { return false; } return true; }; digitnexus.utils.Set.prototype.remove = function (element) { if (null == this.data) { return; } var index = this._getIndex(element); if (index == -1) { return; } this.data.splice(index,1) }; digitnexus.utils.Set.prototype.addAll = function (elements) { if (null == elements || elements.size() < 0) { return; } if(null == this.data) { this.data = new Array(); } for ( var index = 0; index < elements.size(); index++) { var e = elements.get(index); if (null == e) { continue; } this.add(e); } }; digitnexus.utils.Set.prototype._getIndex = function (element) { if (null == this.data) { return -1; } var result = -1; for ( var index = 0; index < this.data.length; index++) { if (null == this.data[index]) { continue; } if((this.data[index].equals != null) && (this.data[index].equals(element))) { result = index; }else if (this.data[index] === element) { result = index; } if(result != -1) { break; } } return result; }; digitnexus.utils.Set.prototype.size = function () { if (null == this.data) { return 0; } return this.data.length; }; digitnexus.utils.Set.prototype.get = function (index) { if (null == this.data) { return null; } if (index >= this.size()) { return null; } return this.data[index]; }; digitnexus.utils.MapEntity = function(key, value) { this.key = key; this.value = value; }; digitnexus.utils.HashMap = function() { this.data = new Array(); }; digitnexus.utils.HashMap.prototype.put = function(key, value) { if (null == this.data) { this.data = new Array(); this.data.push(new digitnexus.utils.MapEntity(key, value)); return; } if (null == key) { throw "key can't be null"; } if (this.contains(key)) { this.remove(key); } this.data.push(new digitnexus.utils.MapEntity(key, value)); }; digitnexus.utils.HashMap.prototype.keySet = function() { if (null == this.data || this.data.length <= 0) { return null; } var ks = new digitnexus.utils.Set(); for ( var index = 0; index < this.data.length; index++) { if (null == this.data[index]) { continue; } ks.add(this.data[index].key); } return ks; }; digitnexus.utils.HashMap.prototype.addAll = function(parameters) { var size = parameters.size(); if (null == parameters || size <= 0) { return; } if (null == this.data) { this.data = new Array(); } size = -1; var ks = parameters.keySet(); size = ks.size(); for ( var index = 0; index < size; index++) { var key = ks.get(index); if (null == key) { continue; } var value = parameters.get(key); this.put(key, value); } }; digitnexus.utils.HashMap.prototype.get = function(key) { if (null == this.data || null == key) { return null; } var index = this._getIndex(key); if (-1 == index) { return null; } return this.data[index].value; }; digitnexus.utils.HashMap.prototype.contains = function(key) { if (null == this.data || null == key) { return false; } var index = this._getIndex(key); if (-1 == index) { return false; } return true; }; digitnexus.utils.HashMap.prototype.remove = function(key) { if (null == this.data || null == key) { return; } var index = -1; index = this._getIndex(key); if (-1 != index) { this.data.splice(index,1) } }; digitnexus.utils.HashMap.prototype.removeAll = function() { if (null == this.data) { return; } for ( var index = 0; index < this.data.length; index++) { if (null == this.data[index]) { continue; } this.data.splice(index,1) } }; digitnexus.utils.HashMap.prototype.size = function() { if (null == this.data) { return 0; } var count = 0; for ( var index = 0; index < this.data.length; index++) { if (null == this.data[index]) { continue; } count++; } return count; }; /** * .Hide */ digitnexus.utils.HashMap.prototype._getIndex = function(key) { if (null == this.data || null == key) { return -1; } var result = -1; for ( var index = 0; index < this.data.length; index++) { if (null == this.data[index]) { continue; } if (this.data[index].key == key) { result = index; break; } } return result; } /******************************HTML table********************************/ digitnexus.utils.Table = function(style) { this.init(style); }; digitnexus.utils.Table.prototype.init = function(style) { this.table = document.createElement('table'); if(style != null) { this.table.className = style; } this.table.style.border = 2; this.table.style.width = '100%'; this.table.style.height = '100%'; this._tbody = document.createElement('tbody') this.table.appendChild(this._tbody); this.inputlist = new digitnexus.utils.HashMap(); } digitnexus.utils.Table.prototype.addRow = function(style) { this.__currentRow = document.createElement('tr'); if(style != null) { this.__currentRow.className = style; } this._tbody.appendChild(this.__currentRow); return this.__currentRow; } digitnexus.utils.Table.prototype.addTd = function(elt,style) { var td = document.createElement('td'); if(null!= style) { td.className = style; } if(null != this.__currentRow) { this.__currentRow.appendChild(td); } if(elt != null) { if(typeof(elt) == 'string') { mxUtils.write(td, elt); }else if(typeof(elt) == 'object'){ td.appendChild(elt); } if(elt.nodeName == 'INPUT' || elt.nodeName == 'DIV' || elt.nodeName == 'P' || elt.nodeName == 'TEXTAREA') { this.inputlist.put(elt.name,elt); } } return td; } // utils for form digitnexus.utils.Table.prototype.addTextRow = function(label,name,value) { this.addRow(); this.addTd(mxResources.get(label,null,label)); var input = digitnexus.utils.formFactory.createTextbox(name,value); this.inputlist.put(name,input); this.addTd(input); } digitnexus.utils.Table.prototype.addTextarea = function(label,name,value,rows,cols) { this.addRow(); this.addTd(label); var input = digitnexus.utils.formFactory.createTextarea(name,value,rows,cols) this.inputlist.put(name,input); this.addTd(input); } digitnexus.utils.Table.prototype.addLabel = function(label) { this.addTd(label); } digitnexus.utils.Table.prototype.addRadioRow = function(label,name,value,defaultValue) { this.addRow(); this.addTd(label); var input = digitnexus.utils.formFactory.createRadiobox(name,value,defaultValue); this.inputlist.put(name,input); this.addTd(input); } digitnexus.utils.Table.prototype.addCheckboxRow= function(label,name,values,checkValues) { this.addRow(); this.addTd(label); this.addTd(label); var input = digitnexus.utils.formFactory.createCheckbox(name,values,checkValues); this.inputlist.put(name,input); this.addTd(input); } digitnexus.utils.Table.prototype.addCheckboxRow= function(label,name,values,checkValues) { this.addRow(); this.addTd(label); var input = digitnexus.utils.formFactory.createCheckbox(name,values,checkValues); this.inputlist.put(name,input); this.addTd(input); } //name, isMultiSelect, size, labels, values, selectValues digitnexus.utils.Table.prototype.addComboboxRow= function(label,name,isMultiSelect, size, labels, values, selectValues) { this.addRow(); this.addTd(label); var input = digitnexus.utils.formFactory.createCombobox(name, isMultiSelect, size, labels, values, selectValues); this.inputlist.put(name,input); this.addTd(input); } digitnexus.utils.Table.prototype.addButton= function() { } digitnexus.utils.Table.prototype.removeRow = function(row) { if(row != null) { this._tbody.removeChild(row); return true; } return false; } digitnexus.utils.Table.prototype.getAllRows = function() { return this._tbody.childNodes; } digitnexus.utils.Table.prototype.removeAllRows = function() { if(this._tbody.childNodes == null) { return; } var children = this._tbody.childNodes; for(var index = 0; index < children.length;) { if(!this.removeRow(children[index])) { index++ } } } digitnexus.utils.Table.prototype.hiddenAllRows = function(rows) { this._setInputDisplay(rows,'none'); } digitnexus.utils.Table.prototype.showAllRows = function(rows) { this._setInputDisplay(rows,''); } digitnexus.utils.Table.prototype._setInputDisplay = function(rows,display) { if(rows == null) { return; } var size = rows.size(); for(var index = 0; index < size; index++) { var input = rows.get(index); if(input == null) { continue; } input.style.display= display; } } /******************************End HTML table****************************/ } /*********************************Form Factory*******************************/ if(digitnexus.utils.formFactory == null || digitnexus.utils.formFactory == 'undefined') { digitnexus.utils._FormFactory = function() { } digitnexus.utils._FormFactory.prototype.createTextbox = function(name,value) { return this.createInput(name,value,'text'); } digitnexus.utils._FormFactory.prototype.createPassword = function(name,value) { return this.createInput(name,value,'password'); } digitnexus.utils._FormFactory.prototype.createHidden = function(name,value) { return this.createInput(name,value,'hidden'); } digitnexus.utils._FormFactory.prototype.createFile = function(name,value) { return this.createInput(name,value,'file'); } digitnexus.utils._FormFactory.prototype.createSubmit= function(name,value) { return this.createInput(name,value,'submit'); } digitnexus.utils._FormFactory.prototype.createReset= function(name,value) { return this.createInput(name,value,'reset'); } digitnexus.utils._FormFactory.prototype.createImage= function(name,imageFile) { var image = this.createInput(name,value,'image'); image.src = imageFile; return image; } digitnexus.utils._FormFactory.prototype.createRadiobox = function(name,values,defaultValue) { var radios = document.createElement('div'); radios.name = name; //default is array var valuesArray = values; if(typeof(values) == 'string') { valuesArray = this.__parseAvaiableValue(values,','); } if(null != valuesArray && valuesArray.length > 0) { for(var i = 0; i< valuesArray.length; i++) { var elt = this.createInput(name,valuesArray[i],'radio'); if(defaultValue != null && defaultValue == valuesArray[i]) { elt.checked='checked'; } mxUtils.write(radios, valuesArray[i]); radios.appendChild(elt); } } return radios; } digitnexus.utils._FormFactory.prototype.createCheckbox = function(name,values,checkedValues) { var radios = document.createElement('div'); radios.name = name; var valuesArray = values; if(typeof(values) == 'string') { valuesArray = this.__parseAvaiableValue(values,','); } var defaultValues = checkedValues; if(typeof(checkedValues) == 'string') { defaultValues = this.__parseAvaiableValue(checkedValues,','); } if(null != valuesArray && valuesArray.length > 0) { for(var i = 0; i< valuesArray.length; i++) { var elt = this.createInput(name,valuesArray[i],'checkbox'); if(defaultValues != null && defaultValues != 'undefined') { for(var ii = 0; ii< defaultValues.length; ii++) { if(valuesArray[i] == defaultValues[ii]) { elt.checked='checked'; } } } mxUtils.write(radios, valuesArray[i]); radios.appendChild(elt); } } return radios; } digitnexus.utils._FormFactory.prototype.createTextarea = function(name, value, rows, cols){ var input = document.createElement('textarea'); if (mxClient.IS_NS){ rows--; } input.setAttribute('rows', rows || 5); input.setAttribute('cols', cols || 40); input.value = value; input.name = name; return input; }; digitnexus.utils._FormFactory.prototype.createCombobox = function(name, isMultiSelect, size, labels, values, selectValues) { var select = document.createElement('select'); select.style.width = 150+'px'; select.name = name; if (size != null){ select.setAttribute('size', size); } if (isMultiSelect){ select.setAttribute('multiple', 'true'); } if(null != labels && typeof(labels) == 'string') { labels = this.__parseAvaiableValue(labels,','); } if(null != values && typeof(values) == 'string') { values = this.__parseAvaiableValue(values,','); } var selectValues = selectValues; if(null != selectValues && typeof(selectValues) == 'string') { selectValues = this.__parseAvaiableValue(selectValues,','); } if(null != values && values.length > 0) { for(var i = 0; i< values.length; i++) { var option = document.createElement('option'); mxUtils.writeln(option, labels[i]); option.setAttribute('value', values[i]); if(selectValues != null && selectValues != 'undefined') { for(var ii = 0; ii< selectValues.length; ii++) { if(values[i] == selectValues[ii]) { option.setAttribute('selected', true); } } } select.appendChild(option); } } return select; } digitnexus.utils._FormFactory.prototype.createInput = function(name,value,type) { var input = document.createElement('input'); input.value = value == null ? '': value; input.name = name == null? '': name; input.type = type == null? '': type; return input; } digitnexus.utils._FormFactory.prototype.__parseAvaiableValue = function(availableValue,seperator){ if(availableValue == null || availableValue == '') { return; } if(seperator == null) { seperator = ','; } var values = availableValue.split(seperator); if(null == values || values.length < 1) { return; } return values; } digitnexus.utils._FormFactory.prototype.getNodeValue = function(node){ var nodeName = node.nodeName; if(node == null) { return null; } if(nodeName=="INPUT") { if(node.type =='radio' || node.type =='checkbox') { if( node.checked ) { return node.value; }else { return null; } } return node.value; } else if(nodeName=="OPTION") { if(node.selected){ return node.value; } } else if(nodeName == "TEXTAREA") { return node.value; } if(nodeName!="DIV" && nodeName != 'P') { return null; } var subNodes = node.childNodes; if(null == subNodes || subNodes.length < 1) { return null; } var value = null; for(var index = 0 ; index < subNodes.length; index++) { var subNode = subNodes[index]; if(subNode == null) { continue; } var v = this.getNodeValue(subNode); if(v != null && value != null) { value = value +','+ v; }else if(v != null) { value = v; } } return value; } digitnexus.utils.formFactory = new digitnexus.utils._FormFactory(); } /******************************End HTML Form Factory****************************/ /******************************Tree view****************************/ /* * TreeModel requre below: * hasChildren(): whether exist child * getChildren() : return all the children, the type must a Set or List * getParent(): get parent * getLabel(); return the name of the node; */ digitnexus.utils._SettingModel = function(key,value) { if(value == null || key == null) { throw 'model key and value cannot be NULL'; } this.value = value; this.key = key; } digitnexus.utils._SettingModel.prototype.getChildren = function(){ return null; } digitnexus.utils._SettingModel.prototype.getLabel = function(){ return this.key; } digitnexus.utils.SettingsTreeModelAdapter = function(origalObj,fromRoot) { this.setModel(origalObj,fromRoot); } digitnexus.utils.SettingsTreeModelAdapter.prototype.setModel = function(origalObj,fromRoot){ if(origalObj == null) { throw 'origal object cannot be null when create TreeModelAdapter'; } this.origalObj = origalObj; } digitnexus.utils.SettingsTreeModelAdapter.prototype.hasChildren = function(node){ if(node == null) { return false; } if(node.getChildrend == 'undefined' || typeof(node.getChildrend) != 'function') { return false; } var children = node.getChildrend(); if(children == 'undefined' || typeof(children.size) != 'function') { return false; } var size = children.size(); if(size == 'undefined' || size < 1) { return false; } return true; } digitnexus.utils.SettingsTreeModelAdapter.prototype.getChildren = function(){ if(this.origalObj == null) { return null; } var nameList = this.origalObj.keySet(); if(nameList == null) { return null; } var size = nameList.size(); var array = []; for(var index = 0 ; index < size; index++ ) { var key = nameList.get(index); if(key == null) { continue; } var obj = this.origalObj.get(key); if(obj == null || obj.size() < 1) { continue; } array.push(new digitnexus.utils._SettingModel(key,obj)); } return array } digitnexus.utils.SettingsTreeModelAdapter.prototype.getLabel = function(){ return null; } digitnexus.utils.SettingsTreeModelAdapter.prototype.getParent = function(){ } digitnexus.utils.TreeView = function(container, clickCallback) { //instance of digitnexus.utils.TreeModel if(null == container ) { throw 'Tree view must get one container'; } if(null == clickCallback ) { throw 'clickCallback cannot be NULL'; } this.container = container; this.clickCallback = clickCallback; this.root = null; }; digitnexus.utils.TreeView.prototype.setRootModel = function(root) { //instance of digitnexus.utils.TreeModel if(null == root ) { //console.log( 'model is null'); } this.root = root; this.updateTree(); }; digitnexus.utils.TreeView.prototype.checkNode = function(node){ if(node == null) { return false; } if(node.getChildrend == 'undefined' || typeof(node.getChildrend) != 'function') { return false; } var children = node.getChildrend(); if(children == 'undefined' || typeof(children.size) != 'function') { return false; } var size = children.size(); if(size == 'undefined' || size < 1) { return false; } } digitnexus.utils.TreeView.prototype.remove = function(treeNode){ if(null == treeNode) { return; } if(treeNode.children != null) { var children = treeNode.children; for(var index = 0; index < children.length; index++) { this.remove(children[index]); } } if(treeNode.parent != null && treeNode.parent != this.container) { treeNode.parent.removeChild(treeNode); } } digitnexus.utils.TreeView.prototype.createTreeViewNode = function(node,ulContainer){ if(node == null) { return; } if(null == ulContainer) { throw 'container is NULL'; } var nodeName = null; if(node.getLabel != null && typeof(node.getLabel) == 'function') { nodeName = node.getLabel(); }else if(node.getAttribute != null && typeof(node.getAttribute) == 'function') { nodeName = node.getAttribute('name'); }else if(node.toString != null && typeof(node.toString) == 'function') { nodeName = node.toString(); } else { throw 'tree node must be one of menthod: getAttribute, getLabel or toString'; } var uiNode = null; if(node.getChildren != null && typeof(node.getChildren) == 'function') { var children = node.getChildren(); if(children != null && children.length > 0) { uiNode = this._createOneUINode('ul',nodeName); ulContainer.appendChild(uiNode); for(var index = 0 ; index < children.length; index++) { this.createTreeViewNode(children[index],uiNode); } } else { uiNode = this._createOneUINode('li',nodeName); ulContainer.appendChild(uiNode); } } else { uiNode = this._createOneUINode('li',nodeName); ulContainer.appendChild(uiNode); } } digitnexus.utils.TreeView.prototype._createOneUINode = function(nodeType,name){ if(nodeType == null || nodeType.trim() == '') { throw 'node type cannot be null'; } var uiNode = document.createElement(nodeType); if(name != null && name.trim() != '') { mxEvent.addListener(uiNode,'click',this.clickCallback); mxUtils.write(uiNode, mxResources.get(name, null,name) ); } return uiNode; } digitnexus.utils.TreeView.prototype.updateTree = function(){ if(this.checkNode(this.root)) { return; } this.remove(this.container); this.createTreeViewNode(this.root,this.container); } /******************************End Tree view****************************/ /******************************End List view****************************/ digitnexus.utils.ListView = function(container, clickCallback,model) { if(container == null) { return; } this.container = container; this.clickCallback = clickCallback; this.model = null; if(model != null) { this.model = model; } } digitnexus.utils.ListView.prototype.LIST_STYLE='ListStyle'; digitnexus.utils.ListView.prototype.setModel = function(model) { if(null == model) { return; } this.model = model; this.onModelChange(); } digitnexus.utils.ListView.prototype.onModelChange = function() { this.remove(); if(this.model == null || this.model.getList == 'undefined' || typeof(this.model.getList) != 'function') { return; } var list = this.model.getList(); if(list == null || list.length < 1) { return; } var ulContainer = this.createUINode(null,'ul','listViewUlStyle'); this.container.appendChild(ulContainer); for(var index = 0 ; index < list.length; index++) { var val = list[index]; if(val == null) { continue; } var uiNode = this.createUINode(val,'li','listViewLiStyle'); if(uiNode != null) { ulContainer.appendChild(uiNode); } } } digitnexus.utils.ListView.prototype._getLabel = function(node) { if(node == null) { return ''; } var nodeName = null; if(node.getLabel != null && typeof(node.getLabel) == 'function') { nodeName = node.getLabel(); }else if(node.getAttribute != null && typeof(node.getAttribute) == 'function') { nodeName = node.getAttribute('name'); }else if(node.toString != null && typeof(node.toString) == 'function') { nodeName = node.toString(); } else { throw 'tree node must be one of menthod: getAttribute, getLabel or toString'; } return nodeName; } digitnexus.utils.ListView.prototype.createUINode = function(val,nodeType,style) { var label = this._getLabel(val); if(nodeType == null || nodeType.trim() == '') { throw 'node type cannot be null'; } var uiNode = document.createElement(nodeType); if(style == null) { style = this.LIST_STYLE; } uiNode.name = uiNode.id = label; uiNode.className = style; if(label != null && label.trim() != '') { if(this.clickCallback != null) { mxEvent.addListener(uiNode,'click',this.clickCallback); } mxUtils.write(uiNode, mxResources.get(label.trim(), null, label)); } return uiNode; } digitnexus.utils.ListView.prototype.remove = function(){ if(null == this.container) { return; } if( this.container.children != null) { var children = this.container.children; for(var index = 0; index < children.length; index++) { this.container.remove(children[index]); } } } /******************************End List view****************************/ /**********************Properties listener*****************************/ digitnexus.utils.PropertiesChangeManager= function(){ var listeners_ = new digitnexus.utils.List(); } /** * */ digitnexus.utils.PropertiesChangeManager.PropertiesListener = function(propertyName,listenerName) { if(listenerName || propertyName) { throw new Error('listenerName ='+listenerName +',propertyName=' + propertyName); } this.propertyName = propertyName; this.listenerName = listenerName; } digitnexus.utils.PropertiesChangeManager.PropertiesListener.prototype.propertyChange = function(event){ throw new Error('not support'); } digitnexus.utils.PropertiesChangeManager.Event = function(src,propertyName, newValue,oldValue) { this.src = src; this.propertyName = propertyName; this.newValue = newValue; this.oldValue = oldValue; } digitnexus.utils.PropertiesChangeManager.prototype.addListener = function(listener){ if(!listener || typeof listener !== 'function' || !listener.listenerName || !listener.propertyName) { return; } this.listeners_.add(listener); } digitnexus.utils.PropertiesChangeManager.prototype.removeListener = function(listenerName){ if(this.listeners_ == null || this.listeners_.size < 1) { return; } var size = this.listeners_.size(); for(var index = 0; index < size; index++) { var lis = this.listeners_.get(index); if(!lis && lis.listenerName === listenerName) { this.listeners_.remove(lis); return; } } } digitnexus.utils.PropertiesChangeManager.prototype.propertyChange = function(event){ if(!event || !event.propertyName) { return; } if(typeof event.propertyName === 'string') { event.propertyName = event.propertyName.trim(); } if(!this.listeners_) { return; } var size = this.listeners_.size(); for(var index = 0; index < size; index++) { var lis = this.listeners_.get(index); if(lis && lis.propertyName && lis.propertyName == event.propertyName) { lis.propertyChange(event); } } } /***********************************************/ })();
import Quill from 'devextreme-quill'; import { isObject } from '../../../core/utils/type'; var ExtLink = {}; if (Quill) { var Link = Quill.import('formats/link'); ExtLink = class ExtLink extends Link { static create(data) { var HREF = data && data.href || data; var node = super.create(HREF); if (isObject(data)) { if (data.text) { node.innerText = data.text; } if (!data.target) { node.removeAttribute('target'); } } return node; } static formats(domNode) { return { href: domNode.getAttribute('href'), target: domNode.getAttribute('target') }; } formats() { var formats = super.formats(); var { href, target } = ExtLink.formats(this.domNode); formats.link = href; formats.target = target; return formats; } format(name, value) { if (name === 'link' && isObject(value)) { if (value.text) { this.domNode.innerText = value.text; } if (value.target) { this.domNode.setAttribute('target', '_blank'); } else { this.domNode.removeAttribute('target'); } this.domNode.setAttribute('href', value.href); } else { super.format(name, value); } } static value(domNode) { return { href: domNode.getAttribute('href'), text: domNode.innerText, target: !!domNode.getAttribute('target') }; } }; } export default ExtLink;
const emojis = [ {code:"👍", label:"-"}, {code:"👐", label:"-"}, {code:"🙌", label:"-"}, {code:"👏", label:"-"}, {code:"👎", label:"-"}, {code:"👊", label:"-"}, {code:"✊", label:"-"}, {code:"🤛", label:"-"}, {code:"🤜", label:"-"}, {code:"🤞", label:"-"}, {code:"🤟", label:"-"}, {code:"🤘", label:"-"}, {code:"👌", label:"-"}, {code:"👈", label:"-"}, {code:"👉", label:"-"}, {code:"👆", label:"-"}, ]; ['🏻', '🏼', '🏽', '🏾', '🏿'].reverse(); export default emojis;
import React from 'react' const calc = (amount, currency) => (amount * currency).toFixed(2) const Currency = (props) => { return ( <div className="input-group mt-3 w-25"> <div className="input-group-prepend"> <span className="input-group-text">{props.currency}</span> </div> <input className="form-control" readOnly value={props.amount} /> </div> ) } const Euro = ({amount}) => <Currency currency="€" amount={calc(amount, 0.86)} /> const Pound = ({amount}) => <Currency currency="£" amount={calc(amount, 0.76)} /> export { Euro, Pound }
/** * The MIT License (MIT) * Copyright (c) 2016, Jeff Jenkins @jeffj. */ const React = require('react'); const SearchActions = require('../actions/SearchActions'); const SearchItem = require('./SearchItem.react'); const Loader = require('react-loader'); import { Link } from 'react-router'; const SearchStore = require('../stores/SearchStore'); const _ = require('lodash'); const _initalSkip = 0; const _count = 20; ///Move Mee to another file const getState = function() { return { results: SearchStore.getAll(), url: SearchStore.getURL() } } const fetch = function(q, skip, clearData) { SearchActions.getList(_count, skip, q, clearData); } const SearchResults = React.createClass({ contextTypes:{ router: React.PropTypes.object.isRequired }, propTypes:{ q: React.PropTypes.string.isRequired }, getInitialState: function() { return getState(); }, componentDidMount: function() { SearchStore.addChangeListener(this._onChange); const q = this.props.q; const clearData = true; fetch(q, _initalSkip, clearData) }, componentWillUnmount: function() { SearchStore.removeChangeListener(this._onChange); }, componentWillReceiveProps: function(newProps){ const q = newProps.q; const clearData = true; fetch(q, _initalSkip, clearData) }, render :function() { if (!this.state.results){return <Loader />}//undefined means that no search response has arrived. const resultsData = this.state.results; const url = this.state.url; const length = Object.keys(resultsData).length; const createURL = url? (<span>But you can <Link to={"/new?site="+url} >add this site to Galactic.</Link></span>): null; const results = length>0?_.map(resultsData, function(result, i) { return <SearchItem key={i} item={result} /> }): <div clasName="row" style={{marginTop:'20px'}}> No Results Found. {createURL} </div>; return <div className="row"> {results} </div> }, /** * Event handler for 'change' events coming from the SearchStore */ _onChange: function() { this.setState(getState()) } }) module.exports = SearchResults;
var mongoose = require('mongoose'); module.exports = mongoose.createConnection("mongodb://mongo/chat");
import React from 'react'; import './App.css'; import NewTweet from './NewTweet'; import Tweets from './Tweets'; class App extends React.Component { constructor(props) { super(props); this.state = { tweets: [ { name: 'Jung', text: 'Hello World.' }, { name: 'Kim', text: 'I can do it!' } ] } this.handleNewTweet = this.handleNewTweet.bind(this); } handleNewTweet(e) { this.setState({ tweets: [...this.state.tweets, e] }) } render() { return ( <div> Tweet Test! <NewTweet click={this.handleNewTweet} /> <ul> <Tweets tweets={this.state.tweets} /> </ul> </div> ); } } export default App;
ack.lang({ 'Reader Cloud' : 'Reader Cloud', 'make a book your own' : 'make a book your own', 'Connectivity Problem' : 'Connectivity Problem', 'You don\'t appear to be connected to the internet' : 'You don\'t appear to be connected to the internet', 'Please reconnect to the internet and try again' : 'Please reconnect to the internet and try again', 'Error' : 'Error', 'There was a problem communicating with the server.' : 'There was a problem communicating with the server.', 'Do you want to try reloading the widget?' : 'Do you want to try reloading the widget?', 'There was a problem communicating with the server.' : 'There was a problem communicating with the server.', 'Do you want to try reloading the widget?' : 'Do you want to try reloading the widget?', 'A link to these attachments will be added:' : 'A link to these attachments will be added:', 'Compose a new Tweet' : 'Compose a new Tweet', 'Back' : 'Back', 'Tweet' : 'Tweet', 'Share or Export with Reader Cloud' : 'Share or Export with Reader Cloud', 'Just one more step...' : 'Just one more step...', 'We need to know your e-mail address & link your twitter account.' : 'We need to know your e-mail address & link your twitter account.', 'Linked with Twitter' : 'Linked with Twitter', 'Linked with Facebook' : 'Linked with Facebook', 'Avatar' : 'Avatar', 'Update' : 'Update', 'Save' : 'Save', 'your book data' : 'your book data', 'Load' : 'Load', 'Sign in to save or load your book data.' : 'Sign in to save or load your book data.', 'You only need to do this once' : 'You only need to do this once', 'Sign in with Reader Cloud' : 'Sign in with Reader Cloud', 'Not registered?' : 'Not registered?', 'Create a free account in seconds' : 'Create a free account in seconds', 'Sign out' : 'Sign out', 'Close' : 'Close', 'Sign up to Reader Cloud' : 'Sign up to Reader Cloud', 'It\'s free and all you need is an e-mail address' : 'It\'s free and all you need is an e-mail address', 'Sign in to Reader Cloud' : 'Sign in to Reader Cloud', 'Signout' : 'Signout', 'Load from Reader Cloud' : 'Load from Reader Cloud', 'Save to Reader Cloud' : 'Save to Reader Cloud', 'Change account email address' : 'Change account email address', 'Update your email' : 'Update your email', 'Enter your new email address below' : 'Enter your new email address below', 'Your new email address is the same as your current one' : 'Your new email address is the same as your current one', 'All done' : 'All done', 'Your email address has been changed' : 'Your email address has been changed', 'You need to be connected to the internet to use this widget' : 'You need to be connected to the internet to use this widget', 'Continue anyway' : 'Continue anyway', 'This action' : 'This action', 'saves' : 'saves', 'your data from this book to the cloud.' : 'your data from this book to the cloud.', 'You can access it later and continue where you left off' : 'You can access it later and continue where you left off', 'Cancel' : 'Cancel', 'Next' : 'Next', 'loads' : 'loads', 'any saved data for this book from the cloud.' : 'any saved data for this book from the cloud.', 'Any updates you\'ve made to this book since you last saved to the cloud will be overwritten, you may want to save it to the cloud first.' : 'Any updates you\'ve made to this book since you last saved to the cloud will be overwritten, you may want to save it to the cloud first.', 'Saving to Reader Cloud' : 'Saving to Reader Cloud', 'Saving your book to Reader Cloud. If it\'s taking a while why not grab a coffee?' : 'Saving your book to Reader Cloud. If it\'s taking a while why not grab a coffee?', 'Finish' : 'Finish', 'Load from Reader Cloud' : 'Load from Reader Cloud', 'Loading your book from Reader Cloud. If it\'s taking a while why not grab a coffee?' : 'Loading your book from Reader Cloud. If it\'s taking a while why not grab a coffee?', 'Okay' : 'Okay', 'Yes' : 'Yes', 'No' : 'No', 'Adult Help Needed...' : 'Adult Help Needed...', 'This is what you\'re trying to do:' : 'This is what you\'re trying to do:', 'To allow this please answer the question below' : 'To allow this please answer the question below', 'What is' : 'What is', 'add' : 'add', 'Back' : 'Back', 'Verify' : 'Verify', 'Whoops!' : 'Whoops!', 'The answer you gave wasn\'t correct. Please try again' : 'The answer you gave wasn\'t correct. Please try again', 'Working' : 'Working', 'Database Error' : 'Database Error', 'There was a problem with database. You may experience unwanted side effects. The error was' : 'There was a problem with database. You may experience unwanted side effects. The error was', 'Your E-mail address' : 'Your E-mail address', 'you@email.com' : 'you@email.com', 'Your Password' : 'Your Password', 'Forgotten your password?' : 'Forgotten your password?', 'By signing in with Reader Cloud you agree to the terms and conditions found' : 'By signing in with Reader Cloud you agree to the terms and conditions found', 'here' : 'here', 'Authenticate with Reader Cloud' : 'Authenticate with Reader Cloud', 'Reset Complete' : 'Reset Complete', 'Instructions on how to reset your password have been e-mailed to you' : 'Instructions on how to reset your password have been e-mailed to you', 'Incorrect Password' : 'Incorrect Password', 'The password you entered was not correct' : 'The password you entered was not correct', 'Logout from Reader Cloud' : 'Logout from Reader Cloud', 'Are you sure you want to Sign out?' : 'Are you sure you want to Sign out?', 'If you Sign out and don\'t sync your book with Reader Cloud you will lose all your Reader Cloud data' : 'If you Sign out and don\'t sync your book with Reader Cloud you will lose all your Reader Cloud data', 'Sign out' : 'Sign out', 'Upload to Reader Cloud & Sign out' : 'Upload to Reader Cloud & Sign out', 'A link to these attachments will be added:' : 'A link to these attachments will be added:', 'What\'s on your mind?' : 'What\'s on your mind?', 'Back' : 'Back', 'Post' : 'Post', 'Share or Export with Reader Cloud' : 'Share or Export with Reader Cloud', 'We need to know your e-mail address & link your facebook account.' : 'We need to know your e-mail address & link your facebook account.', 'Attachments' : 'Attachments', 'To' : 'To', 'to@email.com' : 'to@email.com', 'Subject' : 'Subject', 'Share or Export with Reader Cloud' : 'Share or Export with Reader Cloud', 'Please Complete' : 'Please Complete', 'You need to enter the address of someone to send the email to' : 'You need to enter the address of someone to send the email to', 'You need to enter a subject' : 'You need to enter a subject', 'We need to know who to send the email from.' : 'We need to know who to send the email from.', 'Reader Cloud terms and conditions' : 'Reader Cloud terms and conditions', 'These are also available online at' : 'These are also available online at', 'Email' : 'Email', 'Twitter' : 'Twitter', 'Facebook' : 'Facebook', "Updates available" : "Updates available", "Updates for this widget have been found. Would you like to apply them now?" : "Updates for this widget have been found. Would you like to apply them now?", "Your link will be automatically added" : "Your link will be automatically added", "Evernote" : "Evernote", 'These attachments will be saved' : 'These attachments will be saved', 'Notebook name' : 'Notebook name', 'Leave this blank to save to your default notebook' : 'Leave this blank to save to your default notebook', 'We need to know your e-mail address so that we can save this to Evernote.' : 'We need to know your e-mail address so that we can save this to Evernote.', 'My Notebook' : 'My Notebook', 'Evernote email notes to address' : 'Evernote email notes to address', 'user.1234@m.evernote.com' : 'user.1234@m.evernote.com', 'This is not your normal e-mail address. You can find this under your evernote settings' : 'This is not your normal e-mail address. You can find this under your evernote settings', 'You need to enter your evernote notes to address' : 'You need to enter your evernote notes to address', 'Your evernote notes to address normally ends with "@m.evernote.com"' : 'Your evernote notes to address normally ends with "@m.evernote.com"', 'To find this address follow the steps below…' : 'To find this address follow the steps below…', 'Open the evernote app or website' : 'Open the evernote app or website', 'Visit your account setting' : 'Visit your account setting', 'Then find your "Evernote email address"' : 'Then find your "Evernote email address"', 'Room pin' : 'Room pin', 'Rooms let you share information with a few select people that you choose.' : 'Rooms let you share information with a few select people that you choose.', 'Learn more' : 'Learn more', 'Join' : 'Join', 'Join a Room' : 'Join a Room', 'Join a Room with Reader Cloud' : 'Join a Room with Reader Cloud', 'Whoops' : 'Whoops', 'It doesn\'t look like that room exists. Check the pin again and try again.' : 'It doesn\'t look like that room exists. Check the pin again and try again.', 'Create a room so that you can share information privately with other readers' : 'Create a room so that you can share information privately with other readers', 'More about Rooms' : 'More about Rooms', 'Create' : 'Create', 'Create a Room' : 'Create a Room', 'Create a Room with Reader Cloud' : 'Create a Room with Reader Cloud', 'Here\'s the pin for your room. Give this to other readers so that they can join your room' : 'Here\'s the pin for your room. Give this to other readers so that they can join your room', 'Join me in my Reader Cloud room. The pin is' : 'Join me in my Reader Cloud room. The pin is', 'Share your room pin' : 'Share your room pin', 'How do you want to share your room pin?' : 'How do you want to share your room pin?', 'All done!' : 'All done!', 'The email has been sent' : 'The email has been sent', 'The tweet has been sent' : 'The tweet has been sent', 'Your status has been updated' : 'Your status has been updated', 'This has been saved to your notebook' : 'This has been saved to your notebook', 'Reader Cloud Rooms' : 'Reader Cloud Rooms', 'Room' : 'Room', 'Leave Room' : 'Leave Room', 'Current Room' : 'Current Room', 'Screen Name' : 'Screen Name', 'Bob' : 'Bob', 'This is how other readers will see you' : 'This is how other readers will see you', 'We need to know your email address to create a room' : 'We need to know your email address to create a room', 'Reader Cloud Rooms let you connect and interact with other readers of the same book – locally or remotely and in realtime For example, from within an iBook an educator can create a Room for a particular lesson and invite students to join that Room (physically or virtually). Once participating in the same Room, educators and students can:' : 'Reader Cloud Rooms let you connect and interact with other readers of the same book – locally or remotely and in realtime For example, from within an iBook an educator can create a Room for a particular lesson and invite students to join that Room (physically or virtually). Once participating in the same Room, educators and students can:', 'Educators' : 'Educators', 'See who is in the Room.' : 'See who is in the Room.', 'See widget data entered by each student e.g. quiz answers.' : 'See widget data entered by each student e.g. quiz answers.', 'Drive widget page mirroring for students to follow in real-time.' : 'Drive widget page mirroring for students to follow in real-time.', 'Students' : 'Students', 'Follow the educator’s progression in real-time.' : 'Follow the educator’s progression in real-time.', 'Enter data into the widgets and submit to the educator.' : 'Enter data into the widgets and submit to the educator.', 'Save data for later.' : 'Save data for later.', 'To create a room you will need to enter a screen name and e-mail address. You’ll be provided with a pin number to share with your other collaborators. To join a room it’s even simpler. Just enter an optional screen name and the room and you’re there.' : 'To create a room you will need to enter a screen name and e-mail address. You’ll be provided with a pin number to share with your other collaborators. To join a room it’s even simpler. Just enter an optional screen name and the room and you’re there.', 'Guest' : 'Guest', 'Change your screen name' : 'Change your screen name', 'Update your Screen Name' : 'Update your Screen Name', 'Enter your new screen name below' : 'Enter your new screen name below', 'All done' : 'All done', 'Your screen name has been changed' : 'Your screen name has been changed', 'The maximum number of users in this room has been reached' : 'The maximum number of users in this room has been reached', 'To add more you can visit your Reader Cloud' : 'To add more you can visit your Reader Cloud', 'account page' : 'account page', 'Share' : 'Share', 'How do you want to share this?' : 'How do you want to share this?', 'This book has many great interactive features that need adult supervision such as saving and emailing pictures' : 'This book has many great interactive features that need adult supervision such as saving and emailing pictures', 'zero' : 'zero', 'one' : 'one', 'two' : 'two', 'three' : 'three', 'four' : 'four', 'five' : 'five', 'six' : 'six', 'seven' : 'seven', 'eight' : 'eight', 'nine' : 'nine', 'To continue please enter the code' : 'To continue please enter the code', 'For grown ups' : 'For grown ups', 'wipes' : 'wipes', 'all Reader Cloud data stored on this device.' : 'all Reader Cloud data stored on this device.', 'Warning' : 'Warning', 'Any updates you\'ve made to this book will be lost. This cannot be undone.' : 'Any updates you\'ve made to this book will be lost. This cannot be undone.', 'Wipe this book' : 'Wipe this book', 'Wiping the data on this device' : 'Wiping the data on this device', 'Are you sure?' : 'Are you sure?' }); ack.lang({ 'Undo' : 'Undo', 'Redo' : 'Redo', 'Erase' : 'Erase', 'Color' : 'Color', 'Width' : 'Width', 'Share' : 'Share', 'Are you sure you want to delete your drawing and start again?' :'Are you sure you want to delete your drawing and start again?', "Do you want to email this drawing to yourself?<br/>You will need to create a free account with Bookry - it's free and takes seconds. Would you like to do this now?" : "Do you want to email this drawing to yourself?<br/>You will need to create a free account with Bookry - it's free and takes seconds. Would you like to do this now?", "Great! Your drawing has been e-mailed to you." : "Great! Your drawing has been e-mailed to you.", "Email Drawing" : "Email Drawing", "Do you want to e-mail a copy of your drawing to yourself?" : "Do you want to e-mail a copy of your drawing to yourself?", 'By doing this you are agreeing to share your drawing and e-mail address with the author.' : 'By doing this you are agreeing to share your drawing and e-mail address with the author.', 'By doing this you are agreeing to share your e-maill address with the author.' : 'By doing this you are agreeing to share your e-maill address with the author.', 'By doing this you are agreeing to share your drawing with the author.' : 'By doing this you are agreeing to share your drawing with the author.', 'Email Drawing' : 'Email Drawing', 'Message' : 'Message', 'All done!' : 'All done!', 'Are you sure?' : 'Are you sure?', 'How do you want to share your drawing' : 'How do you want to share your drawing', 'Share what you\'ve drawn' : 'Share what you\'ve drawn', 'The tweet has been sent' : 'The tweet has been sent', 'Your status has been updated' : 'Your status has been updated', 'This has been saved to your notebook' : 'This has been saved to your notebook' });
//#region BLOCK_TYPES var btIndex = 0; var blockPartialClassName = "Block"; window.BLOCK_TYPES = { Names: { Clear: { ID: ++btIndex, ClassName: blockPartialClassName + "Clear" } , End: { ID: ++btIndex, ClassName: blockPartialClassName + "End" } , Move: { ID: ++btIndex, ClassName: blockPartialClassName + "Move" } , Start: { ID: ++btIndex, ClassName: blockPartialClassName + "Start" } , Wall: { ID: ++btIndex, ClassName: blockPartialClassName + "Wall" } } , Indexes: {} }; for(var blockTypeName in window.BLOCK_TYPES.Names) BLOCK_TYPES.Indexes[BLOCK_TYPES.Names[blockTypeName].ID] = BLOCK_TYPES.Names[blockTypeName]; delete blockTypeName; delete blockPartialClassName; delete btIndex; //#endregion (function() { try { //#region _DIRECTIONS var iDirID = -1; //luego hacerlo un diccionario que tenga dos entradsa al mismo valor, numerico y "key" con el nombre de la direccion. //Par que asi su acceso sea dinamico y tambien facil. //The direction are relative to the screen. var _DIRECTIONS = [ {ID: ++iDirID, Name: "Left" ,MX:-1 ,MY:0} //Left , {ID: ++iDirID, Name: "Up" ,MX:0 ,MY:-1} //Up , {ID: ++iDirID, Name: "Right" ,MX:1 ,MY:0} //Right , {ID: ++iDirID, Name: "Down" ,MX:0 ,MY:1} //Down , {ID: ++iDirID, Name: "Up-Left" ,MX:-1 ,MY:-1} //Up-Left , {ID: ++iDirID, Name: "Up-Right" ,MX:-1 ,MY:1} //Up-Right , {ID: ++iDirID, Name: "Down-Right" ,MX:1 ,MY:1} //Down-Right , {ID: ++iDirID, Name: "Down-Left" ,MX:1 ,MY:-1} //Down-Left ]; delete iDirID; //#endregion //#region _POSITION_STATUS_TYPES var pstIndex = -1; var _POSITION_STATUS_TYPES = { Clear: ++pstIndex , End: ++pstIndex , Possible: ++pstIndex , Sealed: ++pstIndex , Start: ++pstIndex , Visited: ++pstIndex }; delete pstIndex; //#endregion //#region PRIVATE_ATTRIBUTES_OBJECT var PRIVATE_ATTRIBUTES_OBJECT = function(options) { try { /* The variable "MyReference" is used inside the methods to keep the reference to "this" object. */ var MyReference = this; for (var opt in options) MyReference[opt] = options[opt]; //#region Set optional options default values //if(!MyReference.Controler) //throw new Error('Controler must be configured.'); if(!MyReference.DirectionsCount) MyReference.DirectionsCount = 4; if(!MyReference.Events) MyReference.Events = {}; //if(!MyReference.Events.onMoveComplete) //MyReference.Events.onMoveComplete = function(x,y){ alert("x:'" + x + "',y:'" + y + "'") }; if(!MyReference.Events.onError) MyReference.Events.onError = function(error){ window.status = error.Message; } //#endregion //#region Attributes /* The property "MyReference.Public" will be used to set the public stuff to the real instance. */ MyReference.Public = {}; //#region Properties MyReference.Controler = null; MyReference.CurrentStatus = null; MyReference.Directions = []; for(var iDir = 0; iDir < MyReference.DirectionsCount; iDir++) MyReference.Directions.push(_DIRECTIONS[iDir]); MyReference.Id = PRIVATE_ATTRIBUTES_OBJECT.InstancesCount++; MyReference.IsRendered = false; //MyReference.isNotComplete = true; MyReference.Move = null; // MyReference.MoveInterval = 1; MyReference.PossibleWaysCollection = {}; MyReference.PossibleWaysList = []; MyReference.Stage = null; //#endregion //#region Methods MyReference.Initialize = function(mapMatrixMM) { try { var mapMatrixJSON = mapMatrixMM.GetMatrixJSON(); MyReference.Stage = MyReference.GetStage(mapMatrixJSON); MyReference.CurrentStatus = { //X:mapMatrixJSON.PointStart.X + 1 //,Y:mapMatrixJSON.PointStart.Y + 1 Dir:_DIRECTIONS[1] /* Usually start to the "Up" direcction. */ }; MyReference.Move = MyReference.DoFirstMove; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.DoFirstMove = function() { try { var nextDirection = null; var oldPossiblePoint = { dir : null, data : null }; //Direccions var ld = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + MyReference.Directions.length - 1) % MyReference.Directions.length]; var fd = MyReference.Directions[MyReference.CurrentStatus.Dir.ID]; var rd = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + 1) % MyReference.Directions.length]; var bd = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + (MyReference.Directions.length/2)) % MyReference.Directions.length]; //Coordinates var lx = MyReference.CurrentStatus.X + ld.MX; var ly = MyReference.CurrentStatus.Y + ld.MY; var fx = MyReference.CurrentStatus.X + fd.MX; var fy = MyReference.CurrentStatus.Y + fd.MY; var rx = MyReference.CurrentStatus.X + rd.MX; var ry = MyReference.CurrentStatus.Y + rd.MY; var bx = MyReference.CurrentStatus.X + bd.MX; var by = MyReference.CurrentStatus.Y + bd.MY; //Points var leftPoint = MyReference.Stage[lx][ly]; var forwardPoint = MyReference.Stage[fx][fy]; var rightPoint = MyReference.Stage[rx][ry]; var backwardPoint = MyReference.Stage[bx][by]; //Set visited the last position MyReference.Stage[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = _POSITION_STATUS_TYPES.Visited; // // left point // if(leftPoint == _POSITION_STATUS_TYPES.Clear) { MyReference.Stage[lx][ly] = _POSITION_STATUS_TYPES.Possible; var foothCollection = {}; foothCollection[MyReference.CurrentStatus.X] = {}; foothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:1 ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }; MyReference.PossibleWaysList.push({ ID:MyReference.PossibleWaysList.length ,X:lx ,Y:ly ,FoothList:[{ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }] ,FoothCollection:foothCollection }); if(MyReference.PossibleWaysCollection[lx] == null ) MyReference.PossibleWaysCollection[lx] = {}; MyReference.PossibleWaysCollection[lx][ly] = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; //Keep reference oldPossiblePoint.data = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; oldPossiblePoint.dir = nextDirection = ld; } else if(leftPoint == _POSITION_STATUS_TYPES.End) { return MyReference.DoMove(MyReference.CurrentStatus.Y + ld.MY - 1, MyReference.CurrentStatus.X + ld.MX - 1, 0); //MyReference.isNotComplete = false; // setTimeout(MyReference.Move, MyReference.MoveInterval); //return; } // // forward point // if(forwardPoint == _POSITION_STATUS_TYPES.Clear) { MyReference.Stage[fx][fy] = _POSITION_STATUS_TYPES.Possible; var foothCollection = {}; foothCollection[MyReference.CurrentStatus.X] = {}; foothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:1 ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }; MyReference.PossibleWaysList.push({ ID:MyReference.PossibleWaysList.length ,X:fx ,Y:fy ,FoothList:[{ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }] ,FoothCollection:foothCollection }); if(MyReference.PossibleWaysCollection[fx] == null) MyReference.PossibleWaysCollection[fx] = {}; MyReference.PossibleWaysCollection[fx][fy] = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; //Keep reference // if((oldPossiblePoint.data != null)&&(oldPossiblePoint.data.ID < MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1].ID)) if(oldPossiblePoint.data != null) { nextDirection = MyReference.Directions[oldPossiblePoint.dir.ID]; } else { oldPossiblePoint.data = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; oldPossiblePoint.dir = nextDirection = fd; } } else if(forwardPoint == _POSITION_STATUS_TYPES.End) { return MyReference.DoMove(MyReference.CurrentStatus.Y + fd.MY - 1, MyReference.CurrentStatus.X + fd.MX - 1, 0); //MyReference.isNotComplete = false; // setTimeout(MyReference.Move, MyReference.MoveInterval); //return; } // // right point // if(rightPoint == _POSITION_STATUS_TYPES.Clear) { MyReference.Stage[rx][ry] = _POSITION_STATUS_TYPES.Possible; var foothCollection = {}; foothCollection[MyReference.CurrentStatus.X] = {}; foothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:1 ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }; MyReference.PossibleWaysList.push({ ID:MyReference.PossibleWaysList.length ,X:rx ,Y:ry ,FoothList:[{ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }] ,FoothCollection:foothCollection }); if(MyReference.PossibleWaysCollection[rx] == null) MyReference.PossibleWaysCollection[rx] = {}; MyReference.PossibleWaysCollection[rx][ry] = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; //Keep reference // if((oldPossiblePoint.data != null)&&(oldPossiblePoint.data.ID < MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1].ID)) if(oldPossiblePoint.data != null) { nextDirection = MyReference.Directions[oldPossiblePoint.dir.ID]; } else { oldPossiblePoint.data = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; oldPossiblePoint.dir = nextDirection = rd; } } else if(rightPoint == _POSITION_STATUS_TYPES.End) { return MyReference.DoMove(MyReference.CurrentStatus.Y + rd.MY - 1, MyReference.CurrentStatus.X + rd.MX - 1, 0); //MyReference.isNotComplete = false; // setTimeout(MyReference.Move, MyReference.MoveInterval); //return; } // // backward point // if(backwardPoint == _POSITION_STATUS_TYPES.Clear) { MyReference.Stage[bx][by] = _POSITION_STATUS_TYPES.Possible; var foothCollection = {}; foothCollection[MyReference.CurrentStatus.X] = {}; foothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:1 ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }; MyReference.PossibleWaysList.push({ ID:MyReference.PossibleWaysList.length ,X:bx ,Y:by ,FoothList:[{ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }] ,FoothCollection:foothCollection }); if(MyReference.PossibleWaysCollection[bx] == null) MyReference.PossibleWaysCollection[bx] = {}; MyReference.PossibleWaysCollection[bx][by] = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; //Keep reference // if((oldPossiblePoint.data != null)&&(oldPossiblePoint.data.ID < MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1].ID)) if(oldPossiblePoint.data != null) { nextDirection = MyReference.Directions[oldPossiblePoint.dir.ID]; } else { nextDirection = bd; } } else if(backwardPoint == _POSITION_STATUS_TYPES.End) { return MyReference.DoMove(MyReference.CurrentStatus.Y + bd.MY - 1, MyReference.CurrentStatus.X + bd.MX - 1, 0); //MyReference.isNotComplete = false; // setTimeout(MyReference.Move, MyReference.MoveInterval); //return; } //Move conclusion. if(!nextDirection) { //MyReference.isNotComplete = false; //alert("No move is possible."); return; } else { //Move 1 place depending the final direction. MyReference.CurrentStatus.Dir = nextDirection; //MyReference.CurrentStatus.X += nextDirection.MX; //MyReference.CurrentStatus.Y += nextDirection.MY; MyReference.UpdatePosiblesWays(); //Set MyReference.Move. MyReference.Move = MyReference.GoToNextPoint; return MyReference.DoMove(MyReference.CurrentStatus.Y += nextDirection.MY - 1, MyReference.CurrentStatus.X + nextDirection.MX - 1); } } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.DoMove = function (y, x) { return { position: { y: y, x: x, }, }; /* //Use a settmeout to fire the event after finish the current stack. setTimeout( function() { MyReference.Events.onMoveComplete(y, x, 0); MyReference.Play(); }, 1 );*/ }; MyReference.GetId = function() { return MyReference.Id; }; MyReference.GetStage = function(matrixJSON) { var stage = null; try { if(!matrixJSON) { return stage; } else { var realWidth = matrixJSON.Size.Width + 2; var realHeight = matrixJSON.Size.Height + 2; stage = new Array(realWidth); for(var iCol = 0; iCol < stage.length; iCol++) { stage[iCol] = new Array(realHeight); for(var iRow = 0; iRow < stage[iCol].length; iRow++) stage[iCol][iRow] = _POSITION_STATUS_TYPES.Clear; } /* Set external walls. */ for(var iCol = 0; iCol < realWidth; iCol++) stage[iCol][0] = _POSITION_STATUS_TYPES.Sealed; for(var iRow = 0; iRow < realHeight; iRow++) stage[0][iRow] = _POSITION_STATUS_TYPES.Sealed; for(var iCol = 0; iCol < realWidth; iCol++) stage[iCol][realHeight-1] = _POSITION_STATUS_TYPES.Sealed; for(var iRow = 0; iRow < realHeight; iRow++) stage[realWidth-1][iRow] = _POSITION_STATUS_TYPES.Sealed; /* Map the rest of the map stage json. */ for(var y = 0; y < matrixJSON.Matrix.length; y++) //for(var x in matrixJSON.Matrix) { var row = matrixJSON.Matrix[y]; for(var x = 0; x < row.length; x++) //for(var y in col) { var cell = row[x]; var posStatusType; if(cell.BlockType.ID == BLOCK_TYPES.Names.Clear.ID) posStatusType = _POSITION_STATUS_TYPES.Clear; else if(cell.BlockType.ID == BLOCK_TYPES.Names.Wall.ID) posStatusType = _POSITION_STATUS_TYPES.Sealed; stage[x + 1][y + 1] = posStatusType; } } stage[matrixJSON.PointStart.X + 1][matrixJSON.PointStart.Y + 1] = _POSITION_STATUS_TYPES.Start; stage[matrixJSON.PointEnd.X + 1][matrixJSON.PointEnd.Y + 1] = _POSITION_STATUS_TYPES.End; } } catch(Error){ MyReference.Events.onError(Error); } return stage; }; MyReference.GoToLastPossible = function() { try { var lastPossiblePoint = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; var nextDirection = null; var nextPosible = null; //Direccions var ld = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + MyReference.Directions.length - 1) % MyReference.Directions.length]; var fd = MyReference.Directions[MyReference.CurrentStatus.Dir.ID]; var rd = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + 1) % MyReference.Directions.length]; //Coordinates var lx = MyReference.CurrentStatus.X + ld.MX; var ly = MyReference.CurrentStatus.Y + ld.MY; var fx = MyReference.CurrentStatus.X + fd.MX; var fy = MyReference.CurrentStatus.Y + fd.MY; var rx = MyReference.CurrentStatus.X + rd.MX; var ry = MyReference.CurrentStatus.Y + rd.MY; // // left point // if((lastPossiblePoint.X == lx)&&(lastPossiblePoint.Y == ly)) { //Set current status MyReference.CurrentStatus.Dir = ld; //MyReference.CurrentStatus.X = lx; //MyReference.CurrentStatus.Y = ly; MyReference.UpdatePosiblesWays(); //Set MyReference.Move MyReference.Move = MyReference.GoToNextPoint; return MyReference.DoMove(ly - 1, lx - 1, 0); // //Call itself again // setTimeout(MyReference.Move, MyReference.MoveInterval); //Continue regular moving //return; } else if((lastPossiblePoint.FoothCollection[lx]) && (lastPossiblePoint.FoothCollection[lx][ly])) { nextDirection = ld; nextPosible = lastPossiblePoint.FoothCollection[lx][ly]; } // // forward point // //Only search in MyReference.PossibleWaysCollection points. if((lastPossiblePoint.X == fx)&&(lastPossiblePoint.Y == fy)) { //Set current status MyReference.CurrentStatus.Dir = fd; //MyReference.CurrentStatus.X = fx; //MyReference.CurrentStatus.Y = fy; MyReference.UpdatePosiblesWays(); //Set MyReference.Move MyReference.Move = MyReference.GoToNextPoint; return MyReference.DoMove(fy - 1, fx - 1, 0); // //Call itself again // setTimeout(MyReference.Move, MyReference.MoveInterval); //Continue regular moving //return; } else if(((lastPossiblePoint.FoothCollection[fx]) && (lastPossiblePoint.FoothCollection[fx][fy])) && ((!nextPosible) || (lastPossiblePoint.FoothCollection[fx][fy].ID < nextPosible.ID))) { nextDirection = fd; nextPosible = lastPossiblePoint.FoothCollection[fx][fy]; } // // right point // //Only search in MyReference.PossibleWaysCollection points. if((lastPossiblePoint.X == rx)&&(lastPossiblePoint.Y == ry)) { //Set current status MyReference.CurrentStatus.Dir = rd; //MyReference.CurrentStatus.X = rx; //MyReference.CurrentStatus.Y = ry; MyReference.UpdatePosiblesWays(); //Set MyReference.Move MyReference.Move = MyReference.GoToNextPoint; return MyReference.DoMove(ry - 1, rx - 1, 0); // //Call itself again // setTimeout(MyReference.Move, MyReference.MoveInterval); //Continue regular moving //return; } else if(((lastPossiblePoint.FoothCollection[rx]) && (lastPossiblePoint.FoothCollection[rx][ry])) && ((!nextPosible) || (lastPossiblePoint.FoothCollection[rx][ry].ID < nextPosible.ID))) { nextDirection = rd; nextPosible = lastPossiblePoint.FoothCollection[rx][ry]; } //Continue go to the last posible //Set current status MyReference.CurrentStatus.Dir = nextDirection; //MyReference.CurrentStatus.X = nextPosible.X; //MyReference.CurrentStatus.Y = nextPosible.Y; MyReference.UpdatePosiblesWays(); return MyReference.DoMove(nextPosible.Y - 1, nextPosible.X - 1, 0); // //Call itself again // setTimeout(MyReference.GoToLastPossible, MyReference.MoveInterval); } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.GoToNextPoint = function() { try { var nextDirection = null; var oldPossiblePoint = { dir : null, data : null }; //Direccions var ld = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + MyReference.Directions.length - 1) % MyReference.Directions.length]; var fd = MyReference.Directions[MyReference.CurrentStatus.Dir.ID]; var rd = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + 1) % MyReference.Directions.length]; //Coordinates var lx = MyReference.CurrentStatus.X + ld.MX; var ly = MyReference.CurrentStatus.Y + ld.MY; var fx = MyReference.CurrentStatus.X + fd.MX; var fy = MyReference.CurrentStatus.Y + fd.MY; var rx = MyReference.CurrentStatus.X + rd.MX; var ry = MyReference.CurrentStatus.Y + rd.MY; //Points var leftPoint = MyReference.Stage[lx][ly]; var forwardPoint = MyReference.Stage[fx][fy]; var rightPoint = MyReference.Stage[rx][ry]; //Set visited the last position MyReference.Stage[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = _POSITION_STATUS_TYPES.Visited; // // left point // if(leftPoint == _POSITION_STATUS_TYPES.Clear) { MyReference.Stage[lx][ly] = _POSITION_STATUS_TYPES.Possible; var foothCollection = {}; foothCollection[MyReference.CurrentStatus.X] = {}; foothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:1 ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }; MyReference.PossibleWaysList.push({ ID:MyReference.PossibleWaysList.length ,X:lx ,Y:ly ,FoothList:[{ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }] ,FoothCollection:foothCollection }); if(MyReference.PossibleWaysCollection[lx] == null ) MyReference.PossibleWaysCollection[lx] = {}; MyReference.PossibleWaysCollection[lx][ly] = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; //Keep reference oldPossiblePoint.data = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; oldPossiblePoint.dir = nextDirection = ld; } else if(leftPoint == _POSITION_STATUS_TYPES.Possible) { oldPossiblePoint.data = MyReference.PossibleWaysCollection[lx][ly]; oldPossiblePoint.dir = nextDirection = ld; } else if(leftPoint == _POSITION_STATUS_TYPES.End) { return MyReference.DoMove(MyReference.CurrentStatus.Y + ld.MY - 1, MyReference.CurrentStatus.X + ld.MX - 1, 0); //MyReference.isNotComplete = false; // setTimeout(MyReference.Move, MyReference.MoveInterval); //return; } // // forward point // if(forwardPoint == _POSITION_STATUS_TYPES.Clear) { MyReference.Stage[fx][fy] = _POSITION_STATUS_TYPES.Possible; var foothCollection = {}; foothCollection[MyReference.CurrentStatus.X] = {}; foothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:1 ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }; MyReference.PossibleWaysList.push({ ID:MyReference.PossibleWaysList.length ,X:fx ,Y:fy ,FoothList:[{ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }] ,FoothCollection:foothCollection }); if(MyReference.PossibleWaysCollection[fx] == null) MyReference.PossibleWaysCollection[fx] = {}; MyReference.PossibleWaysCollection[fx][fy] = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; //Keep reference // if((oldPossiblePoint.data != null)&&(oldPossiblePoint.data.ID < MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1].ID)) if(oldPossiblePoint.data != null) { nextDirection = MyReference.Directions[oldPossiblePoint.dir.ID]; } else { oldPossiblePoint.data = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; oldPossiblePoint.dir = nextDirection = fd; } } else if(forwardPoint == _POSITION_STATUS_TYPES.Possible) { if((oldPossiblePoint.data != null)&&((MyReference.PossibleWaysCollection[fx])&&(MyReference.PossibleWaysCollection[fx][fy])&&(oldPossiblePoint.data.ID < MyReference.PossibleWaysCollection[fx][fy].ID))) { nextDirection = MyReference.Directions[oldPossiblePoint.dir.ID]; } else { oldPossiblePoint.data = MyReference.PossibleWaysCollection[fx][fy]; oldPossiblePoint.dir = nextDirection = fd; } } else if(forwardPoint == _POSITION_STATUS_TYPES.End) { return MyReference.DoMove(MyReference.CurrentStatus.Y + fd.MY - 1, MyReference.CurrentStatus.X + fd.MX - 1, 0); //MyReference.isNotComplete = false; // setTimeout(MyReference.Move, MyReference.MoveInterval); //return; } // // right point // if(rightPoint == _POSITION_STATUS_TYPES.Clear) { MyReference.Stage[rx][ry] = _POSITION_STATUS_TYPES.Possible; var foothCollection = {}; foothCollection[MyReference.CurrentStatus.X] = {}; foothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:1 ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }; MyReference.PossibleWaysList.push({ ID:MyReference.PossibleWaysList.length ,X:rx ,Y:ry ,FoothList:[{ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }] ,FoothCollection:foothCollection }); if(MyReference.PossibleWaysCollection[rx] == null) MyReference.PossibleWaysCollection[rx] = {}; MyReference.PossibleWaysCollection[rx][ry] = MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1]; //Keep reference // if((oldPossiblePoint.data != null)&&(oldPossiblePoint.data.ID < MyReference.PossibleWaysList[MyReference.PossibleWaysList.length-1].ID)) if(oldPossiblePoint.data != null) { nextDirection = MyReference.Directions[oldPossiblePoint.dir.ID]; } else { nextDirection = rd; } } else if(rightPoint == _POSITION_STATUS_TYPES.Possible) { if((oldPossiblePoint.data != null)&&((MyReference.PossibleWaysCollection[rx])&&(MyReference.PossibleWaysCollection[rx][ry])&&(oldPossiblePoint.data.ID < MyReference.PossibleWaysCollection[rx][ry].ID))) { nextDirection = MyReference.Directions[oldPossiblePoint.dir.ID]; } else { nextDirection = rd; } } else if(rightPoint == _POSITION_STATUS_TYPES.End) { return MyReference.DoMove(MyReference.CurrentStatus.Y + rd.MY - 1, MyReference.CurrentStatus.X + rd.MX - 1, 0); //MyReference.isNotComplete = false; // setTimeout(MyReference.Move, MyReference.MoveInterval); //return; } if(!nextDirection) { //Turn back the direcction MyReference.CurrentStatus.Dir = MyReference.Directions[(MyReference.CurrentStatus.Dir.ID + (MyReference.Directions.length/2)) % MyReference.Directions.length]; //Set MyReference.Move MyReference.Move = MyReference.GoToLastPossible; //Go to the last Possible Point MyReference.GoToLastPossible(); } else { //Move 1 place depending the final direction. MyReference.CurrentStatus.Dir = nextDirection; //MyReference.CurrentStatus.X += nextDirection.MX; //MyReference.CurrentStatus.Y += nextDirection.MY; MyReference.UpdatePosiblesWays(); return MyReference.DoMove(MyReference.CurrentStatus.Y + nextDirection.MY - 1, MyReference.CurrentStatus.X + nextDirection.MX - 1, 0); //Call itself again // setTimeout(MyReference.Move, MyReference.MoveInterval); } } catch(Error){ MyReference.Events.onError(Error); } }; //MyReference.Public.isNotComplete = function() { // return MyReference.isNotComplete; //}; MyReference.Public.Play = MyReference.Play = function() { try { MyReference.Start(); //MyReference.Move(); } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Render = function() { try { MyReference.MapDom = MyReference.Controler.GetMapDom(); MyReference.FactorSize = MyReference.Controler.GetFactorSize(); MyReference.AvatarDom = document.createElement('div'); MyReference.AvatarDom.style['position'] = 'absolute'; MyReference.AvatarDom.style['width'] = MyReference.FactorSize + 'px'; MyReference.AvatarDom.style['height'] = MyReference.FactorSize + 'px'; MyReference.Render_DirDownStatic(); MyReference.MapDom.appendChild(MyReference.AvatarDom); MyReference.IsRendered = true; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Render_DirDownStatic = function() { try { MyReference.AvatarDom.style['background-image'] = 'url("styles/img/avatar-static.png")'; MyReference.AvatarDom.style['background-size'] = '290px 110px'; MyReference.AvatarDom.style['background-position'] = '-5px -138px'; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Render_DirDownWalking = function() { try { MyReference.AvatarDom.style['background-image'] = 'url("styles/img/avatar-walking.gif")'; MyReference.AvatarDom.style['background-size'] = '290px 110px'; MyReference.AvatarDom.style['background-position'] = '-60px -110px'; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Render_DirLeftWalking = function() { try { MyReference.AvatarDom.style['background-image'] = 'url("styles/img/avatar-walking.gif")'; MyReference.AvatarDom.style['background-size'] = '290px 110px'; MyReference.AvatarDom.style['background-position'] = '-175px -110px'; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Render_DirRightWalking = function() { try { MyReference.AvatarDom.style['background-image'] = 'url("styles/img/avatar-walking.gif")'; MyReference.AvatarDom.style['background-size'] = '290px 110px'; MyReference.AvatarDom.style['background-position'] = '-175px -60px'; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Render_DirUpWalking = function() { try { MyReference.AvatarDom.style['background-image'] = 'url("styles/img/avatar-walking.gif")'; MyReference.AvatarDom.style['background-size'] = '290px 110px'; MyReference.AvatarDom.style['background-position'] = '-60px -60px'; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Public.Render_Finish = MyReference.Render_Finish = function() { try { MyReference.Render_DirDownStatic(); } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Public.Start = MyReference.Start = function() { try { //Ask controler for permission to move. MyReference.Controler.AskForPermissionToMove(MyReference); } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Public.SetControler = MyReference.SetControler = function(controler) { try { MyReference.Controler = controler; } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.Public.SetCurrentPosition = MyReference.SetCurrentPosition = function(position, callback) { try { var wasRendered = MyReference.IsRendered; if (MyReference.IsRendered == false) MyReference.Render(); var x = position.x + 1, y = position.y + 1, prevX = MyReference.CurrentStatus.X, prevY = MyReference.CurrentStatus.Y; MyReference.CurrentStatus.Y = position.y + 1; MyReference.CurrentStatus.X = position.x + 1; //Render direction if (prevX - x < 0) MyReference.Render_DirRightWalking(); else if (prevX - x > 0) MyReference.Render_DirLeftWalking(); else if (prevY - y < 0) MyReference.Render_DirDownWalking(); else if (prevY - y > 0) MyReference.Render_DirUpWalking(); //Update position in the dom. If it is not hgte initial position, use an animation. if (wasRendered == true) { $(MyReference.AvatarDom).animate( { top: (position.y * MyReference.FactorSize) + 'px', left: (position.x * MyReference.FactorSize) + 'px', }, { complete: callback, duration: 500, easing: 'linear', } ); } else { MyReference.AvatarDom.style['top'] = (position.y * MyReference.FactorSize) + 'px'; MyReference.AvatarDom.style['left'] = (position.x * MyReference.FactorSize) + 'px'; if (callback) callback(); } } catch(Error){ MyReference.Events.onError(Error); } }; MyReference.UpdatePosiblesWays = function() { try { //Remove from MyReference.PossibleWaysList & MyReference.PossibleWaysCollection. if((MyReference.PossibleWaysCollection[MyReference.CurrentStatus.X] != null) && (MyReference.PossibleWaysCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] != null)) { MyReference.PossibleWaysList.splice(MyReference.PossibleWaysCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y].ID, 1); delete MyReference.PossibleWaysCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y]; } //Update MyReference.PossibleWaysList. For reference update MyReference.PossibleWaysCollection. for(var ipp = 0; ipp < MyReference.PossibleWaysList.length; ipp++) { MyReference.PossibleWaysList[ipp].ID = ipp; MyReference.PossibleWaysList[ipp].FoothList.push({ X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y }); if(!MyReference.PossibleWaysList[ipp].FoothCollection[MyReference.CurrentStatus.X]) MyReference.PossibleWaysList[ipp].FoothCollection[MyReference.CurrentStatus.X] = {} MyReference.PossibleWaysList[ipp].FoothCollection[MyReference.CurrentStatus.X][MyReference.CurrentStatus.Y] = { ID:MyReference.PossibleWaysList[ipp].FoothList.length ,X:MyReference.CurrentStatus.X ,Y:MyReference.CurrentStatus.Y } } } catch(Error){ MyReference.Events.onError(Error); } }; //#endregion //#endregion } catch(Error) { Global.ShowError(Error); } }; PRIVATE_ATTRIBUTES_OBJECT.Constructor = function (map, options) { try { var MyReference = new PRIVATE_ATTRIBUTES_OBJECT(options); MyReference.Initialize(map); //#region Public Attributes for(var publicAttrib in MyReference.Public) this[publicAttrib] = MyReference.Public[publicAttrib]; //#endregion } catch(Error) { Global.ShowError(Error); } } PRIVATE_ATTRIBUTES_OBJECT.InstancesCount = 0; //#endregion window.PathFinderCaracol = PRIVATE_ATTRIBUTES_OBJECT.Constructor; } catch(Error) { Global.ShowError(Error); } })(); //Para ahorrar memoria y trabajo definir las coordenadas de cada lugar qeu l orodea en el momento adecuado.
import FrameLoop from './FrameLoop'; describe('FrameLoop', function() { it('queues and runs functions in a step', function() { var loop = new FrameLoop(); var update = jasmine.createSpy('update'); var context = {}; var data = {}; loop.onNextTick(update, context, data); loop.step(); expect(update.calls.count()).toEqual(1); expect(update).toHaveBeenCalledWith(data, jasmine.any(Number)); expect(update.calls.first().object).toBe(context); }); });
'use strict' const vbTemplate = require('claudia-bot-builder').viberTemplate module.exports = function whatIsApod() { return [ new vbTemplate.Text(`The Astronomy Picture of the Day is one of the most popular websites at NASA. In fact, this website is one of the most popular websites across all federal agencies. It has the popular appeal of a Justin Bieber video.`).get(), new vbTemplate.Text(`Each day a different image or photograph of our fascinating universe is featured, along with a brief explanation written by a professional astronomer.`) .addReplyKeyboard(true) .addKeyboardButton(`<font color="#FFFFFF"><b>Visit Website</b></font>`, 'http://apod.nasa.gov/apod/', 6, 2, { TextSize: 'large', BgColor: '#f6d95e', BgMediaType: 'picture', BgMedia: 'https://raw.githubusercontent.com/stojanovic/space-explorer-bot-viber/master/images/galaxy.jpeg' }) .addKeyboardButton(`<font color="#FFFFFF"><b>Back</b></font>`, 'APOD', 6, 2, { TextSize: 'large', BgColor: '#000000' }) .get() ] }
!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Word Guesser Starter Code</title> </head> <body> <div id="guess_display"></div> <form id="guess_form"> <label>Guess a letter: <input type="text" id="guess_input"> </label> </form> <div id="guess_status"></div> <script> // Store DOM elements in variables var guessForm = document.getElementById("guess_form"); var guessDisplay = document.getElementById("guess_display"); var guessLettersDisplay = document.getElementById("guess_letters_display"); var guessInput = document.getElementById("guess_input"); var guessStatus = document.getElementById("guess_status"); // Initialize game state variables var secretWord = "banana"; var guessedWord = []; var guessedLetters = []; for (var i = 0; i < secretWord.length; i++) { guessedWord[i] = "_"; } // Returns true if its a correct guess - // if the letter is anywhere in the word // Also updates guessedWord and guessedLetters var checkLetterGuess = function(letter) { var foundLetter = false; for (var i = 0; i < secretWord.length; i++) { if (secretWord[i] == letter) { guessedWord[i] = letter; foundLetter = true; } } guessedLetters.push(letter); return foundLetter; }; // Returns true if they guessed the whole word var hasWon = function() { for (var i = 0; i< secretWord.length;i++) //using a loop if (secretWord[i] != guessedWord[i]) { //if (secretWord == guessedWord.join("")) { return false; //reversed false/true } return true; }; var displayGuessedWord = function() { guessDisplay.innerHTML = "Current correct: " +"<br>" +guessedWord.join(" "); //console.log(guessedWord); }; var displayGuessedLetters = function() { //console.log(guessedLetters); guessLettersDisplay.innerHTML = "Letters guessed: " +"<br>" +guessedLetters; }; guessForm.addEventListener("submit", function(event) { event.preventDefault(); var foundLetter = checkLetterGuess(guessInput.value); if (foundLetter) { guessStatus.innerHTML = "Yay you found one!"; //displayGuessedLetters(); } else { guessStatus.innerHTML = "Sorry, not correct :("; //displayGuessedLetters(); } if (hasWon()) { guessStatus.innerHTML = "WINNER WINNER!" +"<br>" + "Found them all!"+"<br>" + "WOOOHOOO!"; } displayGuessedWord(); displayGuessedLetters(); guessInput.value = ""; }); displayGuessedWord(); displayGuessedLetters(); // Step 0: Read through the code and understand it // Step 1: Implement guessLetter // Step 2: Implement hasWon // Bonus Steps: // - Randomly generate a word for each game // by pulling from an array // - Come up with a scoring mechanism -- // you can declare game over in a # of guesses // or just track number of guesses and display it // - Display the letters they've already guessed // - Implement error checking for duplicate guesses // - Make way cooler win and lose states! </script> </body> </html>
import React, {useEffect, useState} from 'react'; import './App.css'; import io from 'socket.io-client'; import Chat from './comp/Chat' import Theater from './comp/Theater'; import Seating from './comp/Seating'; //MAIN SERVER: https://chickenriot.herokuapp.com/ TEST:https://superchatt.herokuapp.com/ let socketio = io('https://chickenriot.herokuapp.com/'); function App() { //link the user gives to share to everyone const [Link, setLink] = useState('') //user data const [UserData, setUserData] = useState(); //user id const [UserId, setUserId] = useState(); //bool const [Searched, setSearched] = useState(false) // synced video const [SyncedV, setSyncedV] = useState([]); const [SYNCED, setSYNCED] = useState(false) //link submission functions const handleChange = e =>{ e.preventDefault(); setLink(e.target.value) } // creates the video τνΠ const handleSubmit = e =>{ e.preventDefault(); console.log(Link) socketio.emit( 'iframe' , Link.toString()); // when serach is submitted then the html decided if its youtube or not setSearched(true) } // SYNC BUTTON (ノ`Д)ノo w (ノ`Д)ノo const SyncHandle= e =>{ e.preventDefault(); socketio.emit( 'sync', SyncedV.toString()); console.log('link, sink', Link , SyncedV.toString()); setLink(SyncedV.toString()) handleSubmit(e); } useEffect(() => { // INIT CONNECT socketio.emit('client connected'); // create random room function later socketio.emit('room', 'new room') // COLLECT CONNECTIONS socketio.on('client connected', data => setUserData(data) ) // VIDEO SYNC SOCKET socketio.on('sync', syncVideo =>{ setSyncedV(syncVideo) }) socketio.on('userId', data => setUserId(data)) }, []) if(Searched){ return ( <> <form onSubmit={e => handleSubmit(e)} className="searchbar" > <input className="search-input" placeholder="paste a link here to start sharing!" name="links" onChange={e => handleChange(e)} /> <button onSubmit={e => handleSubmit(e)}> Search </button> <button onClick={e => SyncHandle(e)} disabled="true"> sync </button> </form> <div className="App"> {Link != undefined && Link.includes('youtube') ? <div className="theater"> <Theater socketio={socketio} Link={Link}/> </div>: <iframe crossorigin="anonymous" className="frame" src={Link}></iframe>} <div className="chat"> <Chat socketio={socketio}/> </div> </div> {UserData ? <Seating socketio={socketio} users={UserData} userId={UserId}/> : <div>loading</div> } </> )}else{ return( <> <form onSubmit={e => handleSubmit(e)} className="searchbar" > <input className="search-input" placeholder="paste a link here to start sharing!" name="links" onChange={e => handleChange(e)} /> <button onSubmit={e => handleSubmit(e)}> Search </button> <button onClick={e => SyncHandle(e)} disabled="true"> sync </button> </form> <div className="App"> <div className="vid"> <iframe width="960" height="540" src="https://www.youtube.com/embed/MbWPI9SYvks" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> <div className="chat"> <Chat socketio={socketio}/> </div> </div> {UserData ? <Seating socketio={socketio} users={UserData} userId={UserId}/> : <div>loading</div> } </> ) } } export default App;
import Vue from 'vue'; import router from './route'; import './config.js'; import './axios_intercept.js'; import Main from './Main'; new Vue({ router, render: h => h(Main), }).$mount('#app') // new Vue({ // el: '#app', // router, // components: { Main }, // template: '<Main></Main>', // });
let fs=require("fs"); var dataAccessLayerbulkexport=require("../dataAccessLayer/bulkexport"); function transferdata(path,index,type){ return new Promise(function(resolve,reject){ fs.readFile(path,'utf8',function(err,data){ data=JSON.parse(data); console.log("file read"); preparedataforExport(data,index,type).then(dataarry=>{ calldataAccesslayerforExport(dataarry).then(result=>{ resolve(result); },err=>{ console.log("error occured in data fire"); }); },err=>{ }); }); }); } function preparedataforExport(data,indexname,type){ return new Promise(function(resolve,reject){ var bulkbody=[]; var preparedata=function(){ for(var i=0;i<data.length;i++){ var item=data[i]; bulkbody.push({"index":{ "_id":item._key, "_index":indexname, "_type":type }}); delete item._id; bulkbody.push(item); } }; //console.log("before"); preparedata(); //console.log("after",bulkbody[0]); resolve(bulkbody); }); } function calldataAccesslayerforExport(data){ return new Promise(function(resolve,reject){ dataAccessLayerbulkexport.bulkexport(data) .then(result=>{ fs.writeFile("./jsonfiles/data1.json", JSON.stringify(result),"utf8",function(err,data){ }); resolve(result); },err=>{ reject("err occured in preparedataforExport"); }) }) } module.exports={ transferdata }
var MailboxRepository = function() {}; const HttpStatus = require('http-status'); MailboxRepository.prototype.getFakeMail = function() { const fakeMailList = [{ "from": "B", "to": "A", "message": "Message A" }, { "from": "C", "to": "A", "message": "Message B" } ]; return fakeMailList; }; MailboxRepository.prototype.postFakeMail = function(){ return HttpStatus.OK; } module.exports = new MailboxRepository();
const express = require("express"); const app = express(); const bodyParser = require("body-parser"); app.use(express.json()); app.use(express.static("public")); app.use(bodyParser.json()); app.get('/', function(req, res) { res.send('index.html'); }); let data = []; app.get("/messages", function(req, res) { res.json(data[req.query.lastindex - 1]); }) app.post("/messages", function(req, res) { let newMessage = { index: data.length + 1, sender: req.body.sender, message: req.body.message } data.push(newMessage); res.json(newMessage); }) app.listen(3000, function() { console.log("server started"); })
const readlineSync = require("readline-sync"); let tab1 = [1, 2, 3, 4, 5]; let tab2 = [...tab1]; console.log(tab2); var num = 0; var arr = []; var y=Number(readlineSync.question("please put in a number")); function inj(){ //let num = 0; while(num<y){ n = readlineSync.question("How many numbers should we ask you for?"); arr.push(n) num++ } return arr; } console.log(Math.min(...inj())); console.log(Math.max(...inj()));
const express = require('express'); const UserController = require('../controllers/UserController'); const router = express.Router(); router.get('/', UserController.getUsers); router.get('/:userId(\\d+)', UserController.getUserById); router.post('/new', UserController.createNewUser); router.post('/auth', UserController.auth); router.post('/2fa', UserController.twoFactorAuth); router.post('/logout', UserController.logout); router.delete('/:userId(\\d+)', UserController.deleteUser); module.exports = router;
const commandLineArgs = require('command-line-args') const Capture = require('./lib/capture') process.on('unhandledRejection', (error) => { console.error(error) process.exit(1) }) const optionDefinitions = [ { name: 'url', type: String }, { name: 'device', type: String, defaultValue: 'pc' }, ] const options = commandLineArgs(optionDefinitions) const cap = new Capture(options); (async () => { await cap.openBrowser() await cap.goto() await cap.save(true) console.log(await cap.response()) await cap.close() })()
crel = require('crel') var page = crel('div', crel('h1', 'Title'), crel('p', 'some text')) document.body.appendChild(page)
// This is the where all of the database information is // This is for demonstration purposes, because any changes to this information // won't be saved accross page loads, but can be used to demonstrate functionality // within a page // Person's name, will have to have a least a first and a last name // That's what the default arguments are for the class below function Name(first_name, last_name){ this.name = [first_name, last_name] } // Prototype functions in JavaScript is similar to Method functions in Java or C++ Name.prototype.getName = function(i){ return this.name[i] } // Assume this is an US bank account function Address(home, country, state, city){ this.home = home this.country = country this.state = state this.city = city } Address.prototype.getHome = function(){ return this.home } Address.prototype.getCountry = function(){ return this.country } Address.prototype.getState = function(){ return this.state } Address.prototype.getCity = function(){ return this.city } // This is the super type, the one that aggregates the above and // is the summary of the account function Account(username, password, name, address, balance, pending){ this.username = username this.password = password this.name = name this.address = address this.balance = balance this.pending = pending } Account.prototype.deposit = function(amount){ this.balance += parseFloat(amount) } Account.prototype.withdrawl = function(amount){ this.balance -= parseFloat(amount) } // Here is all of the client data // Names var Names = [] Names[0] = new Name('Frank', 'Jones') Names[1] = new Name('Ron', 'Harrison') Names[2] = new Name('James', 'Carriker') Names[3] = new Name('Bob', 'Crump') Names[4] = new Name('John', 'Medlin') Names[5] = new Name('Tom', 'Smith') Names[6] = new Name('Rob', 'Almond') Names[7] = new Name('Jim', 'Jackson') // Addresses var Addresses = [] Addresses[0] = new Address('123 Here Street', 'USA', 'NC', 'Aoville') Addresses[1] = new Address('345 Here Street', 'USA', 'Va', 'Boville') Addresses[2] = new Address('678 Here Street', 'USA', 'NY', 'Coville') Addresses[3] = new Address('910 Here Street', 'USA', 'MA', 'Doville') Addresses[4] = new Address('1112 Here Street', 'USA', 'PA', 'Eoville') Addresses[5] = new Address('1314 Here Street', 'USA', 'SC', 'Foville') Addresses[6] = new Address('1516 Here Street', 'USA', 'CA', 'Goville') Addresses[7] = new Address('1718 Here Street', 'USA', 'SD', 'Hoville') // Accounts var Accounts = [] Accounts[0] = new Account('User0', 'password0', Names[0], Addresses[0], 36001.01) Accounts[1] = new Account('User1', 'password1', Names[1], Addresses[1], 500.01) Accounts[2] = new Account('User2', 'password2', Names[2], Addresses[2], 285.01) Accounts[3] = new Account('User3', 'password3', Names[3], Addresses[3], 851.01) Accounts[4] = new Account('User4', 'password4', Names[4], Addresses[4], 7822.01) Accounts[5] = new Account('User5', 'password5', Names[5], Addresses[5], 305.01) Accounts[6] = new Account('User6', 'password6', Names[6], Addresses[6], 5020.01) Accounts[7] = new Account('User7', 'password7', Names[7], Addresses[7], 168.50)
(function(angular) { 'use strict'; // Referencia para o nosso app var app = angular.module('app'); // Cria um service chamado 'Group' app.factory('Group', [function(User) { // Modelo do grupo function Group(data) { if (data) this.setData(data); }; // Métodos do grupo Group.prototype = { setData: function(data) { angular.extend(this, data); }, save: function() { var groups = Group.all(); groups.push(this); localStorage.setItem('groups', JSON.stringify(groups)); }, delete: function() { Group.delete(this); } }; // Métodos estáticos // Retorna todas as grupos Group.all = function() { var json = localStorage.getItem('groups') || '[]'; return JSON.parse(json); } // Procura por grupos do usuário Group.findMyGroups = function(user) { var groups = Group.all(); var found = []; var equals = false; for (var i in groups) { if (groups[i].owner.email == user.email) { equals = true; } else { for (var j in groups[i].users) { if (groups[i].users[j].email == user.email) { equals = true; break; } } } if (equals) found.push(groups[i]); } return found; } Group.addUser = function(user, group) { var json = localStorage.getItem('groups') || '[]'; var groups = []; group.users.push(user); json = JSON.parse(json); for (var i in json) { if (json[i].id == group.id) groups.push(group); else groups.push(new Group(json[i])); } localStorage.setItem('groups', angular.toJson(groups)); } Group.isInGroup = function(user, group) { if(group.owner.id == user.id) return true for(var i in group.users) { if(group.users[i].id == user.id) return true; } return false; } Group.removeUser = function(user, group) { var newData = { id : group.id, name : group.name, users : [], owner : group.owner }; for(var i in group.users) { if(group.users[i].id != user.id) newData.users.push(group.users[i]); } var newRemovedGroup = new Group(newData) var json = localStorage.getItem('groups') || '[]'; var groups = []; json = JSON.parse(json); for (var i in json) { if (json[i].id == group.id) groups.push(newRemovedGroup); else groups.push(json[i]); } localStorage.setItem('groups', angular.toJson(groups)); } Group.findOwnerByEmail = function(email) { var groups = Group.all(); var found = []; var equals = false; for (var i in groups) { if (groups[i].owner.email == email) found.push(posts[i]); } return found; } // Remove um grupo Group.delete = function(group) { var json = localStorage.getItem('groups') || '[]'; var groups = []; json = JSON.parse(json); for (var i in json) { if (json[i].id == group.id) continue; groups.push(new Group(json[i])); } localStorage.setItem('groups', JSON.stringify(groups)); } return Group; }]); })(window.angular);
import reducer, { featuresInitSucceeded, featuresChanged, } from './features'; const features = { enableAccountAdministration: true, }; const featuresUpdate = { enableAccountAdministration: { current: false, }, }; describe('features', () => { test('getting initial features', () => { expect(reducer({ enableAccountAdministration: false, }, featuresInitSucceeded(features))) .toEqual({ enableAccountAdministration: true, }); }); test('getting feature changes', () => { expect(reducer({ enableAccountAdministration: true, }, featuresChanged({ features: featuresUpdate }))) .toEqual({ enableAccountAdministration: false, }); }); });
import React from 'react'; import rainbowLoader from '../../assets/rainbowLoader.gif'; export default function Loader() { return ( <div className='loading-icon-wrapper'> <img className='loading-icon' src={rainbowLoader} alt='loading icon, the projects are loading' /> </div> ) }
// フォト exports.createWindow = function(_type, _articleData){ Ti.API.debug('[func]winPhoto.createWindow:'); Ti.API.debug('_type:' + _type); var loginUser = model.getLoginUser(); // 初回読み込み時 var initFlag = true; // blur用 var commentField = null; // 記事データの取得件数 var articleCount = 10; var articleLastId = null; // 続きを読むフラグ var nextArticleFlag = false; var nextTarget = null; // コメント上限数 var commentMax = 10; // テキストフィールドのblurの処理 var blurCommentField = function() { Ti.API.debug('[func]blurCommentField:'); if (commentField && commentField.focusFlag) { commentField.blur(); commentField.focusFlag = false; return true; } else { return false; } }; // ライクボタンクリック時の処理 var clickLikeStampImage = function(e) { Ti.API.debug('[func]clickLikeStampImage:'); // 多重クリック防止 listView.touchEnabled = false; var item = listSection.getItemAt(e.itemIndex); if (likeStampImage.clickFlag) { // ライクの削除 likeStampImage.image = 'images/icon/b_like_before.png'; item.photoLikeStampImage = likeStampImage; listSection.updateItemAt(e.itemIndex, item); model.removeCloudLikeList({ postId: _articleData.id, reviewId: likeStampImage.reviewId }, function(e) { Ti.API.debug('[func]removeCloudLikeList.callback:'); if (e.success) { Ti.API.debug('Success:'); likeStampImage.clickFlag = false; if (photoWin.prevWin != null) { photoWin.prevWin.fireEvent('refresh', {index:_articleData.index, like:-1, comment:0}); } // ローカルから削除 model.removeLocalLikeList({ userId: loginUser.id, article: _articleData.id }); } else { util.errorDialog(e); likeStampImage.image = 'images/icon/b_like_after.png'; item.photoLikeStampImage = likeStampImage; listSection.updateItemAt(e.itemIndex, item); } listView.touchEnabled = true; }); } else { // ライクの追加 likeStampImage.image = 'images/icon/b_like_after.png'; item.photoLikeStampImage = likeStampImage; listSection.updateItemAt(e.itemIndex, item); model.addCloudLikeList({ postId: _articleData.id, articleData: _articleData, }, function(e) { Ti.API.debug('[func]addCloudLikeList.callback:'); if (e.success) { Ti.API.debug('Success:'); likeStampImage.clickFlag = true; likeStampImage.reviewId = e.reviews[0].id; if (photoWin.prevWin != null) { photoWin.prevWin.fireEvent('refresh', {index:_articleData.index, like:1, comment:0}); } // ローカルに登録 var likeList = [{user:loginUser.id, article:_articleData.id, review:e.reviews[0].id}]; model.addLocalLikeList(likeList); } else { util.errorDialog(e); likeStampImage.image = 'images/icon/b_like_before.png'; item.photoLikeStampImage = likeStampImage; listSection.updateItemAt(e.itemIndex, item); } listView.touchEnabled = true; }); } }; /* // コメントクリック時の処理 var clickCommentActionView = function(e) { Ti.API.debug('[func]clickCommentActionView:'); listView.touchEnabled = false; var item = listSection.getItemAt(e.itemIndex); item.photoCommentActionView.backgroundColor = 'white'; listSection.updateItemAt(e.itemIndex, item); dummyField.focus(); item.photoCommentActionView.backgroundColor = '#f5f5f5'; listSection.updateItemAt(e.itemIndex, item); listView.touchEnabled = true; }; */ // コメントデータの取得 var getCommentItem = function(review) { Ti.API.debug('[func]getCommentItem:'); var icon = ''; var nameValue = ''; var userValue = ''; var time = ''; var commentUserId = null; if (review.user) { var user = review.user; if (user.photo != null && user.photo.urls != null) { icon = user.photo.urls.square_75; } if (user.custom_fields && user.custom_fields.name != null && user.custom_fields.name != '') { nameValue = user.custom_fields.name; } else { // nameValue = user.first_name + ' ' + user.last_name; nameValue = (user.username.indexOf('@') > 0) ? user.username.substring(0,user.username.indexOf('@')) : user.username; } if (review.custom_fields && review.custom_fields.postDate != null) { // time = util.getFormattedDateTime(util.getDate(review.custom_fields.postDate)); var date = util.getDateElement(review.custom_fields.postDate); time = date.year + '/' + date.month + '/' + date.day + ' ' + date.hour + ":" + date.minute; } commentUserId = user.id; } else { // コメント追加時 icon = loginUser.icon; if (loginUser.name != '') { nameValue = loginUser.name; } else { nameValue = loginUser.user; } time = review.time; commentUserId = loginUser.id; } var newColor = 'white'; if ( review.newFlag ) { newColor = '#87CEFA'; } var commentItem = [{ template: 'comment', userId: commentUserId, reviewId: review.id, photoCommentFrameView: { backgroundColor: newColor, }, photoCommentUserIconView: { // backgroundImage: icon, }, photoCommentUserIconImage: { image: icon, }, photoCommentNameLabel: { text: nameValue, }, photoCommentTextLabel: { text: review.content, }, photoCommentTimeLabel: { text: time, } }]; return commentItem; }; // コメントリストの更新 var updateComment = function() { Ti.API.debug('[func]updateComment:'); /* // 初回のみコメントの読み込み中を表示 if (initFlag) { var loadItem = [{ template: 'load', photoCommentLoadLabel: { text: '読み込み中', hegiht: '20dp' }, }]; listSection.appendItems(loadItem); } */ // コメントリストの取得 model.getCloudCommentList({ lastId: articleLastId, userId: loginUser.id, postId: _articleData.id, limit: articleCount, }, function(e) { if (e.success) { Ti.API.debug('[func]getCloudCommentList.callback:'); if (e.reviews.length > 0) { for (var i=0; i<e.reviews.length; i++) { listSection.appendItems(getCommentItem(e.reviews[i])); } } if (nextTarget != null) { // 続きを読むの行をdeleteだとうまくいかないのでupdateで高さを0にし、追加後に反映 listSection.updateItemAt(nextTarget.index, nextTarget.item); nextTarget = null; }; if (e.meta.total_results <= articleCount) { nextArticleFlag = false; } else { nextArticleFlag = true; var nextItem = [{ template: 'next', photoCommentNextLabel: { text: '続きを読む', }, }]; listSection.appendItems(nextItem, {animationStyle: Titanium.UI.iPhone.RowAnimationStyle.FADE}); // 最後の記事のIDを保管 articleLastId = e.reviews[e.reviews.length-1].id; } /* var bottomItem = [{ template: 'bottom', }]; listSection.appendItems(bottomItem); // 初回のみコメントの読み込み中を削除 if (initFlag) { // 続きを読むの行をdeleteだとうまくいかないのでupdateで高さを0にし、追加後に反映 var item = listSection.getItemAt(2); item.photoCommentLoadLabel.text = ''; item.photoCommentLoadLabel.height = '0dp'; listSection.updateItemAt(2, item); initFlag = false; } */ } else { util.errorDialog(e); } }); }; // コメントの追加 var addComment = function(text) { Ti.API.debug('[func]addComment:'); actInd.show(); tabGroup.add(actInd); var date = util.getFormattedNowDateTime(); var commentData = { no: _articleData.no, seq: null, user: loginUser.id, date: date, text: text }; // コメントリストに追加 model.addCloudCommentList({ postId: _articleData.id, comment: text, date: date, ownerId: _articleData.userId, reviewedPhoto: _articleData.photo }, function(e) { Ti.API.debug('[func]addCloudCommentList.callback:'); if (e.success) { Ti.API.debug('Success:'); var review = { user:null, content:text, id:e.reviews[0].id, time:util.getFormattedNowDateTime(), newFlag: true }; // コメント入力の直下に追加 listSection.insertItemsAt(2, getCommentItem(review), {animated: true}); // listSection.insertItemsAt(listSection.items.length, getCommentItem(review), {animated: true}); listView.scrollToItem(0, 2, {animated: true}); actInd.hide(); text = ''; _articleData.comment++; if (photoWin.prevWin != null) { photoWin.prevWin.fireEvent('refresh', {index:_articleData.index, like:0, comment:1}); } } else { actInd.hide(); util.errorDialog(e); } }); }; // --------------------------------------------------------------------- var photoWin = Ti.UI.createWindow(style.photoWin); // タイトルの表示 var titleView = Ti.UI.createView(style.photoTitleView); photoWin.titleControl = titleView; var titleIconView = Ti.UI.createView(style.photoTitleIconView); // titleIconView.backgroundImage = _articleData.icon; titleView.add(titleIconView); titleView.titleIconView = titleIconView; var titleIconImage = Ti.UI.createImageView(style.photoTitleIconImage); titleIconImage.image = _articleData.icon; titleIconView.add(titleIconImage); var nameView = Ti.UI.createView(style.photoTitleNameView); titleView.add(nameView); var titleUserLabel = Ti.UI.createLabel(style.photoTitleUserLabel); titleUserLabel.text = _articleData.user; if (_articleData.name != '') { var titleNameLabel = Ti.UI.createLabel(style.photoTitleNameLabel); titleNameLabel.text = _articleData.name; nameView.add(titleNameLabel); titleUserLabel.height = '16dp'; } nameView.add(titleUserLabel); // 戻るボタンの表示 var backButton = Titanium.UI.createButton(style.commonBackButton); photoWin.leftNavButton = backButton; // ロード用画面 var actInd = Ti.UI.createActivityIndicator(style.commonActivityIndicator); // ライクボタンの表示 var likeStampImage = {}; if (_type == "friends") { var likeReviewId = model.getLocalLikeReviewId({ userId: loginUser.id, article: _articleData.id }); if (likeReviewId != null) { likeStampImage.image = 'images/icon/b_like_after.png'; likeStampImage.clickFlag = true; likeStampImage.reviewId = likeReviewId; } likeStampImage.visible = true; } /* // コメントフィールドの表示 var commentField = Ti.UI.createTextField(style.photoCommentField); var dummyField = Ti.UI.createTextField(style.photoCommentField); dummyField.top = '-50dp'; dummyField.keyboardToolbar = [commentField]; photoWin.add(dummyField); dummyField.addEventListener('focus',function(e){ Ti.API.debug('[event]dummyField.focus:'); commentField.focus(); }); // コメントフィールドでキーボード確定でコメントリストに追加 commentField.addEventListener('return',function(e){ Ti.API.debug('[event]commentField.return:'); addComment(); }); */ var articleListTemplate = { properties: style.photoArticleList, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoArticleView', properties: style.photoArticleView, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoPhotoView', properties: style.photoPhotoView, childTemplates: [{ type: 'Ti.UI.ImageView', bindId: 'photoPhotoImage', properties: style.photoPhotoImage, }], events: { 'click': function (e) { Ti.API.debug('[event]photoPhotoView.click:'); if ( blurCommentField() == false ) { photoWin.close({animated:true}); } } } },{ type: 'Ti.UI.View', bindId: 'photoArticleTextView', properties: style.photoArticleTextView, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoTextView', properties: style.photoTextView, childTemplates: [{ type: 'Ti.UI.Label', bindId: 'photoTimeLabel', properties: style.photoTimeLabel, },{ type: 'Ti.UI.Label', bindId: 'photoTextLabel', properties: style.photoTextLabel, }] },{ type: 'Ti.UI.ImageView', bindId: 'photoLikeStampImage', properties: style.photoLikeStampImage, events: { 'click': function(e) { // テキストフィールド入力中でないかチェック if ( blurCommentField() == false ) { clickLikeStampImage(e); } } } }] }] }] }; var actionListTemplate = { properties: style.photoActionList, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoActionView', properties: style.photoActionView, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoCommentActionView', properties: style.photoCommentActionView, childTemplates: [{ type: 'Ti.UI.ImageView', bindId: 'photoCommentActionImage', properties: style.photoCommentActionImage, },{ type: 'Ti.UI.TextField', bindId: 'photoCommentField', properties: style.photoCommentField, events: { 'focus': function(e) { if (_articleData.comment == commentMax) { var alertDialog = Titanium.UI.createAlertDialog({ title: '投稿できるコメントは\n最大20件です。', buttonNames: ['OK'], }); alertDialog.show(); } else { commentField = e.source; commentField.focusFlag = true; } }, 'return': function(e) { if (e.source.value != '') { addComment(e.source.value); e.source.value = ''; blurCommentField(); } } } }] /* },{ type: 'Ti.UI.View', bindId: 'photoShareActionView', properties: style.photoShareActionView, childTemplates: [{ type: 'Ti.UI.ImageView', bindId: 'photoShareActionImage', properties: style.photoShareActionImage, },{ type: 'Ti.UI.Label', bindId: 'photoShareActionLabel', properties: style.photoShareActionLabel, }] */ }] }] }; var loadListTemplate = { properties: style.photoCommentLoadList, childTemplates: [{ type: 'Ti.UI.Label', bindId: 'photoCommentLoadLabel', properties: style.photoCommentLoadLabel, }] }; var commentListTemplate = { properties: style.photoCommentList, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoCommentFrameView', properties: style.photoCommentFrameView, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoCommentView', properties: style.photoCommentView, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoCommentUserIconView', properties: style.photoCommentUserIconView, childTemplates: [{ type: 'Ti.UI.ImageView', bindId: 'photoCommentUserIconImage', properties: style.photoCommentUserIconImage, }], events: { 'click': function (e) { Ti.API.debug('[event]photoCommentUserIconView.click:'); var item = e.section.getItemAt(e.itemIndex); if (item.userId != loginUser.id) { listView.touchEnabled = false; // ユーザデータの取得 model.getCloudUser(item.userId, function(e) { Ti.API.debug('[func]getCloudUser.callback:'); if (e.success) { if (e.userList[0]) { item.photoCommentUserIconView.opacity = 0.5; var profileWin = win.createProfileWindow(e.userList[0]); win.openTabWindow(profileWin, {animated:true}); item.photoCommentUserIconView.opacity = 1.0; listView.touchEnabled = true; } } else { util.errorDialog(e); listView.touchEnabled = true; } }); } } } },{ type: 'Ti.UI.View', bindId: 'photoCommentTextView', properties: style.photoCommentTextView, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoCommentNameView', properties: style.photoCommentNameView, childTemplates: [{ type: 'Ti.UI.Label', bindId: 'photoCommentNameLabel', properties: style.photoCommentNameLabel, }] },{ type: 'Ti.UI.Label', bindId: 'photoCommentTextLabel', properties: style.photoCommentTextLabel, events: { 'click': function (e) { Ti.API.debug('[event]photoCommentTextLabel.click:'); if ( blurCommentField() == false ) { photoWin.close({animated:true}); } } } },{ type: 'Ti.UI.Label', bindId: 'photoCommentTimeLabel', properties: style.photoCommentTimeLabel, }] }] }] }], events: { 'longpress': function (e) { Ti.API.debug('[event]photoCommentView.longpress:'); var item = e.section.getItemAt(e.itemIndex); // 削除できるのは自分のコメントのみ if (item.userId == loginUser.id) { listView.touchEnabled = false; var targetView = e.source; targetView.backgroundColor = '#dedede'; var deleteIndex = e.itemIndex; var alertDialog = Titanium.UI.createAlertDialog({ title: 'コメントを削除しますか?', buttonNames: ['キャンセル','OK'], cancel: 1 }); alertDialog.show(); alertDialog.addEventListener('click',function(alert){ // OKの場合 if(alert.index == 1){ model.removeCloudCommentList({ postId: _articleData.id, reviewId: item.reviewId }, function(e) { Ti.API.debug('[func]removeCloudCommentList.callback:'); if (e.success) { Ti.API.debug('Success:'); listSection.deleteItemsAt(deleteIndex, 1, {animated:true}); _articleData.comment--; if (photoWin.prevWin != null) { photoWin.prevWin.fireEvent('refresh', {index:_articleData.index, like:0, comment:-1}); } } else { util.errorDialog(e); } targetView.backgroundColor = 'white'; listView.touchEnabled = true; }); } else { targetView.backgroundColor = 'white'; listView.touchEnabled = true; } }); } } } }; var nextListTemplate = { properties: style.photoCommentNextList, childTemplates: [{ type: 'Ti.UI.Label', bindId: 'photoCommentNextLabel', properties: style.photoCommentNextLabel, }], events: { 'click': function (e) { Ti.API.debug('[event]photoCommentNextList.click:'); listView.touchEnabled = false; var item = e.section.getItemAt(e.itemIndex); // 続きを読むの行をdeleteだとうまくいかないのでupdateで高さを0にし、追加後に反映 item.photoCommentNextLabel.text = ''; item.photoCommentNextLabel.height = '0dp'; nextTarget = {index:e.itemIndex, item:item}; updateComment(); listView.touchEnabled = true; } } }; /* var bottomListTemplate = { properties: style.photoBottomList, childTemplates: [{ type: 'Ti.UI.View', bindId: 'photoCommentBottomView', properties: style.photoCommentBottomView, }] }; */ var listView = Ti.UI.createListView(style.photoTableListView); listView.templates = { 'article': articleListTemplate, 'action': actionListTemplate, 'load': loadListTemplate, 'comment': commentListTemplate, 'next': nextListTemplate, // 'bottom': bottomListTemplate }; var listSection = Ti.UI.createListSection(); listView.setSections([listSection]); photoWin.add(listView); var articleItem = [{ template: 'article', photoPhotoImage: { image: _articleData.photo }, photoTimeLabel: { text: util.getFormattedMD(_articleData.date) }, photoTextLabel: { text: _articleData.text }, photoLikeStampImage: likeStampImage }]; listSection.appendItems(articleItem); var actionItem = [{ template: 'action', photoCommentActionView: { // }, // photoShareActionView: { } }]; listSection.appendItems(actionItem); if (_type == "friends") { // 初回読み込み時に、コメントリストの更新 updateComment(); } // --------------------------------------------------------------------- // 戻るボタンをクリック backButton.addEventListener('click', function(e){ Ti.API.debug('[event]backButton.click:'); photoWin.close({animated:true}); }); // タイトルクリックでプロフィールを表示 titleView.addEventListener('click',function(e){ Ti.API.debug('[event]titleView.click:'); if (e.source.objectName == 'photoTitleIconView' || e.source.objectName == 'photoTitleNameView') { if (_articleData.userId != loginUser.id) { titleIconView.touchEnabled = false; // ユーザデータの取得 model.getCloudUser(_articleData.userId, function(e) { Ti.API.debug('[func]getCloudUser.callback:'); if (e.success) { if (e.userList[0]) { titleView.titleIconView.opacity = 0.5; var profileWin = win.createProfileWindow(e.userList[0]); win.openTabWindow(profileWin, {animated:true}); titleView.titleIconView.opacity = 1.0; titleIconView.touchEnabled = true; } } else { util.errorDialog(e); titleIconView.touchEnabled = true; } }); } } }); // 右スワイプで前の画面に戻る photoWin.addEventListener('swipe',function(e){ Ti.API.debug('[event]photoWin.swipe:'); if (e.direction == 'right') { photoWin.close({animated:true}); } }); listView.addEventListener('click', function(e){ Ti.API.debug('[event]listView.click:'); var item = e.section.getItemAt(e.itemIndex); }); /* listView.addEventListener('itemclick', function(e){ Ti.API.debug('[event]listView.itemclick:'); var item = e.section.getItemAt(e.itemIndex); if (item.template == 'article') { if( e.bindId == 'photoPhotoImage' // || e.bindId == 'photoArticleTextView' // || e.bindId == 'photoTextView' // || e.bindId == 'photoTimeLabel' // || e.bindId == 'photoTextLabel' ) { // テキストフィールド入力中でないかチェック if ( blurCommentField() == false ) { photoWin.close({animated:true}); } } } else if (item.template == 'comment' && e.bindId == 'photoCommentUserIconImage') { if (item.userId != loginUser.id) { listView.touchEnabled = false; // ユーザデータの取得 model.getCloudUser(item.userId, function(e) { Ti.API.debug('[func]getCloudUser.callback:'); if (e.success) { if (e.userList[0]) { item.photoCommentUserIconView.opacity = 0.5; var profileWin = win.createProfileWindow(e.userList[0]); win.openTabWindow(profileWin, {animated:true}); item.photoCommentUserIconView.opacity = 1.0; listView.touchEnabled = true; } } else { util.errorDialog(e); listView.touchEnabled = true; } }); } } else if (item.template == 'next') { listView.touchEnabled = false; // 続きを読むの行をdeleteだとうまくいかないのでupdateで高さを0にし、追加後に反映 item.photoCommentNextLabel.text = ''; item.photoCommentNextLabel.height = '0dp'; nextTarget = {index:e.itemIndex, item:item}; updateComment(); listView.touchEnabled = true; } }); listView.addEventListener('longpress', function(e){ Ti.API.debug('[event]listView.longpress:'); var item = e.section.getItemAt(e.itemIndex); if (item.template == 'comment') { if (_articleData.userId != loginUser.id) { var alertDialog = Titanium.UI.createAlertDialog({ title: 'コメントを削除しますか?', buttonNames: ['キャンセル','OK'], cancel: 1 }); alertDialog.show(); alertDialog.addEventListener('click',function(alert){ // OKの場合 if(alert.index == 1){ listView.touchEnabled = false; model.removeCloudCommentList({ postId: _articleData.id, reviewId: item.reviewId }, function(e) { Ti.API.debug('[func]removeCloudCommentList.callback:'); if (e.success) { Ti.API.debug('Success:'); listSection.deleteItemsAt(e.itemIndex, 1); if (photoWin.prevWin != null) { photoWin.prevWin.fireEvent('refresh', {index:_articleData.index, like:0, comment:-1}); } } else { util.errorDialog(e); } listView.touchEnabled = true; }); } }); } } }); */ return photoWin; };
//synchronously example var fs = require("fs"); var buffer = fs.readFileSync("us-states.txt"); var bufferString = buffer.toString(); var newLineCount = bufferString.split("\n").length; console.log("There are " + newLineCount + " lines in the file"); console.log("Oh, you've finished reading the file."); console.log("Oh, where has Oregon? She's gone to Arizona."); // When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.
/** * 题目描述 在数组 arr 末尾添加元素 item。 不要直接修改数组 arr,结果返回新的数组 */ function append(arr, item) { var arrcopy = arr.slice(0); arrcopy.push(item); return arrcopy; }
// for "accounts" route const logInPath = "/accounts/user/login/" const logOutPath = "/accounts/user/logout/" const registerPath = "/accounts/user/register/" const apiTokenPath = "/accounts/api/token/" const apiRefreshTokenPath = "/accounts/api/token/refresh/" // for "api-blog" route const allPostsPath = "/api-blog/" const allCategoriesPath = "/api-blog/categories/" const newPostPath = "/api-blog/new/" const editPostPath = "/api-blog/edit/" const featuredPostPath = "/api-blog/breaking/" // path("categories/<category_name>", views.CategoryDetailView.as_view()), // path("<slug>/", views.BlogEntryDetailView.as_view()), // path("<slug>/edit", views.BlogEntryEditView.as_view()), export { logInPath, logOutPath, registerPath, apiTokenPath, apiRefreshTokenPath, allPostsPath, allCategoriesPath, newPostPath, editPostPath, featuredPostPath, }
const resolve = { data: { auth: { token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlYzZlNWE2NzhjNDBkNmM0YmNjY2RlYiIsIm5hbWUiOiJBZG1pbmlzdHJhZG9yIiwidXNlcm5hbWUiOiJyb290IiwiZW1haWwiOiJhZG1pbkB5b3VyZG9tYWluLmNvbSIsInBob25lIjoiMTE3Nzc3Nzc3NyIsInJvbGUiOnsicGVybWlzc2lvbnMiOlsiU0VDVVJJVFlfVVNFUl9DUkVBVEUiLCJTRUNVUklUWV9VU0VSX0VESVQiLCJTRUNVUklUWV9VU0VSX0RFTEVURSIsIlNFQ1VSSVRZX1VTRVJfU0hPVyIsIlNFQ1VSSVRZX0dST1VQX0NSRUFURSIsIlNFQ1VSSVRZX0dST1VQX0VESVQiLCJTRUNVUklUWV9HUk9VUF9ERUxFVEUiLCJTRUNVUklUWV9HUk9VUF9TSE9XIiwiU0VDVVJJVFlfUk9MRV9DUkVBVEUiLCJTRUNVUklUWV9ST0xFX1NIT1ciLCJTRUNVUklUWV9ST0xFX0VESVQiLCJTRUNVUklUWV9ST0xFX0RFTEVURSIsIlNFQ1VSSVRZX0RBU0hCT0FSRF9TSE9XIiwiQ1VTVE9NSVpBVElPTl9TSE9XIiwiQ1VTVE9NSVpBVElPTl9DT0xPUlNfVVBEQVRFIiwiQ1VTVE9NSVpBVElPTl9MT0dPX1VQREFURSIsIkNVU1RPTUlaQVRJT05fTEFOR19VUERBVEUiLCJQRVJTT05fQ1JFQVRFIiwiUEVSU09OX1VQREFURSIsIlBFUlNPTl9ERUxFVEUiLCJQRVJTT05fU0hPVyIsIkxJVklOR1BMQUNFVFlQRV9VUERBVEUiLCJJTVBPUlRfQ1NWIiwiTElWSU5HUExBQ0VUWVBFX0NSRUFURSIsIkxJVklOR1BMQUNFVFlQRV9ERUxFVEUiLCJBUElLRVlfQ1JFQVRFIiwiQVBJS0VZX1VQREFURSIsIkFQSUtFWV9ERUxFVEUiLCJTT0NJT0VDT05PTUlDTEVWRUxfVVBEQVRFIiwiU09DSU9FQ09OT01JQ0xFVkVMX0NSRUFURSIsIlNPQ0lPRUNPTk9NSUNMRVZFTF9ERUxFVEUiLCJDQU1QQUlHTl9DUkVBVEUiLCJDQU1QQUlHTl9TSE9XIiwiQ0FNUEFJR05fREVMRVRFIiwiQ0FNUEFJR05fVVBEQVRFIl0sIl9pZCI6IjVlYzZlNWE2NzhjNDBkNmM0YmNjY2RlYSIsIm5hbWUiOiJhZG1pbiIsImRlbGV0ZWQiOmZhbHNlLCJkZWxldGVkQXQiOm51bGwsIl9fdiI6MCwiaWQiOiI1ZWM2ZTVhNjc4YzQwZDZjNGJjY2NkZWEifSwiZ3JvdXBzIjpbeyJ1c2VycyI6W10sIl9pZCI6IjVlYzdmMDUwZDMxMzk4MDAxMjFiZWE5MCIsIm5hbWUiOiJBZG1pbmlzdHJhZG9yZXMiLCJjb2xvciI6IiMzMDcwOTEiLCJkZWxldGVkIjpmYWxzZSwiZGVsZXRlZEF0IjpudWxsLCJfX3YiOjAsImlkIjoiNWVjN2YwNTBkMzEzOTgwMDEyMWJlYTkwIn1dLCJhdmF0YXJ1cmwiOiJodHRwOi8vMTkyLjE2OC4yMC40MDo1MDcwL21lZGlhL2F2YXRhci9yb290LnBuZz9JbHoiLCJpZFNlc3Npb24iOiI1ZWU0ZmFhNzcxMzBhMDAwMTE2NjRkZmEiLCJpYXQiOjE1OTIwNjQ2NzksImV4cCI6MTU5MjE1MTA3OX0.hMKjyBOQvT-KqxO6ipJ9ZZFKBMgRYdXp2jQTM8Zqj_s", __typename: "Token" } } } export default resolve
module.exports={ cookieSecret: "info-site", db:"info-site", url:'mongodb://localhost:27017/info-site' }
import React, { Component } from 'react'; import { scaleLinear, scaleTime } from 'd3-scale'; import { isoParse } from 'd3-time-format'; import { select, selectAll, mouse as d3Mouse } from 'd3-selection'; import { extent, bisector } from 'd3-array'; import { axisBottom, axisLeft } from 'd3-axis'; import { line } from 'd3-shape'; import PropTypes from 'prop-types'; import Map from 'lodash/map'; import 'scss/components/graph.scss'; class LineGraph extends Component { // onMouseOut = () => { // const svg = select('svg'); // svg.select('.mouse-line').style('opacity', '0'); // select('.mouse-per-line circle').style('opacity', '0'); // }; // onMouseOver = () => { // const svg = select('svg'); // svg.select('.mouse-line').style('opacity', '1'); // select('.mouse-per-line circle').style('opacity', '1'); // }; // onMouseMove = (chartData, x) => { // const lines = document.querySelectorAll('.line > path'); // const { height, dataKey } = this.props; // const rect = select('rect'); // rect.on('mousemove', () => { // const mouse = d3Mouse(this); // select('.mouse-line').attr('d', `M${mouse[0]},${height} ${mouse[0]},0`); // selectAll('.mouse-per-line') // .data(chartData) // .attr('transform', (d, i) => { // const xDate = x.invert(mouse[0]); // const bisect = bisector((data) => { // return data.timestamp; // }).right; // const idx = bisect(d[dataKey], xDate); // let beginning = 0; // let end = lines[i].getTotalLength(); // const target = null; // function positionCalc(t, lns) { // const pos = lns[i].getPointAtLength(t); // const posTartget = Math.floor((beginning + end) / 2); // // if ( // // (posTartget === end || posTartget === beginning) && // // pos.x !== mouse[0] // // ) // if (pos.x > mouse[0]) end = posTartget; // else if (pos.x < mouse[0]) beginning = posTartget; // } // while (true) { // const pos = positionCalc(target, lines); // console.log(pos); // console.log(`translate(${mouse[0]},${pos.y})`); // return `translate(${mouse[0]},${pos.y})`; // } // }); // }); // }; render() { const chartData = []; Map(this.props.data, (el, i) => { chartData[i] = { timestamp: isoParse(el.timestamp), }; chartData[i][this.props.dataKey] = el[this.props.dataKey]; }); // x축 (timestamp) 구간 범위 정의 = width만큼 const xScale = scaleTime() .domain(extent(chartData, this.props.selectX)) // 실제 데이터 범위 .range([0, this.props.width]); // 화면에 보여줄 구간의 범위 // y축 (sensor 데이터 혹은 score) 구간 범위 정의 = height만큼 const yScale = scaleLinear() .domain(extent(chartData, this.props.selectY)) .range([this.props.height, 0]); const xAxis = axisBottom() .scale(xScale) .ticks(7); const yAxis = axisLeft() .scale(yScale) .ticks(5); const selectScaledX = data => xScale(this.props.selectX(data)); const selectScaledY = data => yScale(this.props.selectY(data)); const drawLine = line() .x(selectScaledX) .y(selectScaledY); const linePath = drawLine(chartData); return this.props.main ? ( // 메인그래프 <svg className="Graph-main-container" width={ this.props.width + this.props.margin.left + this.props.margin.right } height={ this.props.height + this.props.margin.top + this.props.margin.bottom } > <text x="0" y="-35" fontSize="18px"> {this.props.dataKey} </text> {/* x축 */} <g className="xAxis" ref={node => select(node).call(xAxis)} style={{ transform: `translateY(${this.props.height}px)`, }} /> {/* y축 */} <g className="yAxis" ref={node => select(node).call(yAxis)} /> {/* 그래프 라인 */} <g className="line"> <path d={linePath} /> </g> {/* 마우스 이벤트 <g className="mouse-over-effects"> <path className="mouse-line" /> <g className="mouse-per-line"> <circle r={3} fill="#f9a825" /> </g> </g> <rect width={this.props.width} height={this.props.height} fill="none" pointerEvents="all" onMouseOut={this.onMouseOut} onMouseOver={this.onMouseOver} onMouseMove={() => this.onMouseMove(chartData, xScale)} /> */} </svg> ) : ( // 서브그래프 <div> <svg className="Graph-sub-container" onClick={() => this.props.changeMainGraph(this.props.dataKey)} width={ this.props.width + this.props.margin.left + this.props.margin.right } height={ this.props.height + this.props.margin.top + this.props.margin.bottom } > {/* x축 */} <g className="xAxis" ref={node => select(node).call(xAxis)} style={{ transform: `translateY(${this.props.height}px)`, }} /> {/* y축 */} <g className="yAxis" ref={node => select(node).call(yAxis)} /> {/* 그래프 라인 */} <g className="line"> <path d={linePath} /> </g> {/* 마우스 이벤트 <g className="mouse-over-effects"> <path className="mouse-line" /> <g className="mouse-per-line"> <circle r={2} fill="#f9a825" /> </g> </g> <rect width={this.props.width} height={this.props.height} fill="none" pointerEvents="all" onMouseLeave={this.onMouseOut} onMouseEnter={this.onMouseOver} onMouseMove={() => this.onMouseMove(chartData, xScale)} /> */} </svg> <span className="Graph-sub-labels"> <br /> {this.props.dataKey} </span> </div> ); } } LineGraph.defaultProps = { main: true, data: [ { timestamp: 0, score: 0, co2: 0, dust: 0, temp: 0, humid: 0, voc: 0, }, ], height: 200, width: 400, selectX: data => data.timestamp, selectY: null, margin: { top: 0, right: 0, bottom: 0, left: 0, }, }; LineGraph.propTypes = { main: PropTypes.bool, data: PropTypes.arrayOf( PropTypes.shape({ timestamp: PropTypes.number, score: PropTypes.number, co2: PropTypes.number, dust: PropTypes.number, temp: PropTypes.number, humid: PropTypes.number, voc: PropTypes.number, }), ), height: PropTypes.number, width: PropTypes.number, selectX: PropTypes.func, selectY: PropTypes.func, dataKey: PropTypes.string.isRequired, margin: PropTypes.shape({ top: PropTypes.number, right: PropTypes.number, bottom: PropTypes.number, left: PropTypes.number, }), changeMainGraph: PropTypes.func.isRequired, }; export default LineGraph;
'use strict'; module.exports = function (config, title, name) { config = config || {}; if (typeof config == 'string') { var configStr = config.split('/'); var lastObj = configStr.pop(); var configStrUrl = configStr.join('/'); config = { fileUrl: 'components' + configStrUrl + '/', name: lastObj, title: title }; if (title && typeof title == 'string' && title[0] == "/") { config.path = title; config.title = title.slice(1); if (name && typeof name == 'string') { config.title = name; } } } var configs = { fileUrl: 'components/', fileType: '.vue', path: '/', name: '', component: null }; var extends_if = function extends_if(keyName, keyName1, CaseBool) { keyName1 = keyName1 || keyName; if (config[keyName1]) { if (CaseBool) { configs[keyName] = config[keyName1].toLocaleLowerCase(); } else { configs[keyName] = config[keyName1]; } } switch (keyName1) { case 'name': configs.path = '/' + config[keyName1].toLocaleLowerCase(); break; } }; for (var i in config) { configs[i] = config[i]; }; var vueComponent = require('@/' + configs.fileUrl + configs.name + '.vue'); if (vueComponent.default) { configs.component = vueComponent.default; } else { configs.component = vueComponent; } extends_if('name', null, true); extends_if('name', 'title', true); extends_if('path'); extends_if('component'); return configs; };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Songs</title> </head> <body> <div id="detailsArea"> <span class="detail" id="title"></span> <span class="detail" id="artist"></span> <span class="detail" id="album"></span> <span class="detail" id="year"></span> </div> <div id="albumArea"></div> </body> <script> let songs = [ { title: "Getting Away with It (All Messed Up)", artist: "James", album: "Pleased to Meet You", year: 2001, art: "https://upload.wikimedia.org/wikipedia/en/2/2a/JamesPleasedToMeetYou.jpg" }, { title: "Renaissance Affair", artist: "Hooverphonic", album: "Blue Wonder Power Milk", year: 1998, art: "https://upload.wikimedia.org/wikipedia/en/1/17/Hooverphonic-Blue_Wonder_Power_Milk.jpg" }, { title: "White Nights", artist: "Oh Land", album: "Oh Land", year: 2011, art: "https://upload.wikimedia.org/wikipedia/en/6/68/Oh_Land_%28album%29.png" } ] songs.forEach((song) =>{ let albumArea = document.getElementById("albumArea"); let img = document.createElement("img"); img.setAttribute("src", song.art) img.setAttribute("onclick", loadDetails('${song.title}', '${song.artist}', '${song.album}', '${song.year}')); albumArea.appendChild(img); }) function loadDetails(title, artist, album, year){ document.getElementById("title").innerHTML = title document.getElementById("artist").innerHTML = artist document.getElementById("album").innerHTML = album document.getElementById("year").innerHTML = year } </script> </html>
import React from 'react'; import {Link} from 'react-router-dom' import { Form, Input } from '@rocketseat/unform' import * as Yup from 'yup' import logo from '../../assets/logo.svg' export default function SignIn() { function handleSubmit(data){ console.log(data) } const schema = Yup.object().shape({ nome: Yup.string().required("Insira seu nome."), email: Yup.string().email("Insira um e-mail válido.").required("Insira um e-mail."), senha: Yup.string().required("Insira uma senha.") }) return ( <> <img src={logo} alt=""/> <Form schema={schema} onSubmit={handleSubmit}> <Input name="nome" placeholder="Nome completo"/> <Input name="email" type="email" placeholder="Seu e-mail"/> <Input name="senha" type="password" placeholder="Sua senha"/> <button type="submit">Registrar-se</button> <Link to="/">Já tenho conta</Link> </Form> </> ); }
import React from 'react'; import ReactDOM from 'react-dom'; import { I18nextProvider } from 'react-i18next'; import { renderToString } from 'react-dom/server'; import { Provider } from 'react-redux'; import { StaticRouter } from 'react-router'; import createBrowserHistory from 'history/createBrowserHistory'; import createMemoryHistory from 'history/createMemoryHistory'; import { ConnectedRouter } from 'react-router-redux'; import template from './index.ejs'; import configureStore from './store/configure'; import Root from './components/Root/Root'; import i18n from './i18n'; if (typeof document !== 'undefined') { const history = createBrowserHistory(); const store = configureStore(history); ReactDOM.render( <Provider store={ store }> <ConnectedRouter history={ history }> <I18nextProvider i18n={ i18n }> <Root /> </I18nextProvider> </ConnectedRouter> </Provider>, document.getElementById('root') ); } export default ({ path, webpackStats }) => { const history = createMemoryHistory(); const store = configureStore(history); const assetFilenames = Object.keys(webpackStats.compilation.assets); const context = {}; const renderPath = (path) => template({ htmlWebpackPlugin: { options: { stylesheet: assetFilenames.find(filename => filename.includes('.css')), script: assetFilenames.find(filename => filename.includes('.js')), html: renderToString( <Provider store={ store }> <StaticRouter context={ context } location={ path }> <I18nextProvider i18n={ i18n }> <Root /> </I18nextProvider> </StaticRouter> </Provider> ), }, }, }); const html = renderPath(path); return context.url ? renderPath(context.url) : html; };
'use strict' const webpack = require('webpack') const { VueLoaderPlugin } = require('vue-loader') const HtmlWebpackPlugin = require('html-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') const utils = require('./utils') const path = require('path') module.exports = { entry: path.resolve(__dirname, './../src/index.js'), mode: 'development', devServer: { hot: true }, module: { rules: [{ test: /\.(js|vue)$/, use: 'eslint-loader', enforce: 'pre' }, { test: /\.vue$/, use: 'vue-loader' }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { // should come after vue loader test: /\.js$/, use: 'babel-loader' } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', '@': path.resolve(__dirname, './../src') } }, plugins: [ new VueLoaderPlugin(), // necessary for vue loader to work new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true }), new CopyWebpackPlugin([{ // static content from: utils.resolve('static/img'), to: utils.resolve('dist/static/img'), toType: 'dir' }]) ] }