text
stringlengths 7
3.69M
|
|---|
import React, { Component } from "react";
import { Link } from 'react-router-dom';
class DriverRow extends Component {
constructor(props) {
super(props);
this.state = {
first_name: props.driver.first_name,
last_name: props.driver.last_name,
id: props.driver.id,
contact: props.driver.contact,
active: props.driver.active,
editMode: false
}
}
handleEdit = (event) => {
this.setState((prev_state) => ({
editMode: !prev_state.editMode
}))
}
handleCancel = () => {
this.setState((prev_state, props) => ({
first_name: props.driver.first_name,
last_name: props.driver.last_name,
id: props.driver.id,
contact: props.driver.contact,
active: props.driver.active,
editMode: false
}))
}
handleSave = () => {
let payload = {
first_name: this.state.first_name,
last_name: this.state.last_name,
active: this.state.active,
contact: this.state.contact,
}
this.props.handleUpdate(this.state.id,payload);
this.setState({
editMode:false
});
}
handleInputChange = (event) => {
let name = event.target.name;
this.setState({
[name]: event.target.value
})
}
render() {
let { first_name, last_name, id, editMode, active, contact } = this.state;
return (
<tr>
<td>{id}</td>
<td>{editMode ? <input className="form-control" type="text" value={first_name} name="first_name" onChange={this.handleInputChange} /> : first_name}</td>
<td>{editMode ? <input className="form-control" type="text" value={last_name} name="last_name" onChange={this.handleInputChange} /> : last_name}</td>
<td>{editMode ? <input className="form-control" type="text" value={active} name="active" onChange={this.handleInputChange} /> : active}</td>
<td>{editMode ? <input className="form-control" type="text" value={contact} name="contact" onChange={this.handleInputChange} /> : contact}</td>
<td>
{
editMode ? (
<div>
<button type="button" className="btn btn-danger" onClick={this.handleCancel}>Cancel</button>{" "}
<button type="button" className="btn btn-primary" onClick={this.handleSave}>Save</button>
</div>)
: <button type="button" className="btn btn-success" onClick={this.handleEdit}>Edit</button>
}
</td>
<td><Link to={`/drivers/${id}/shifts`}><button type="button" className="btn btn-success" onClick={this.handleEdit}>Add/Edit</button></Link></td>
<td><Link to={`/drivers/${id}/cars`}><button type="button" className="btn btn-success" onClick={this.handleEdit}>Add/Edit</button></Link></td>
</tr>
)
}
}
export default DriverRow;
|
import axios from '../../axios-orders';
import * as actionTypes from './actionTypes';
export const addIngedient = ig => {
return {
type: actionTypes.ADD_INGREDIENT,
payload: { ingredient: ig },
};
};
export const removeIngedient = (ig, currentQuantity) => {
return {
type: actionTypes.REMOVE_INGREDIENT,
payload: {
ingredient: ig,
currentQuantity: currentQuantity,
},
};
};
//Init ingredients
const setIngredients = ingredients => {
return {
type: actionTypes.SET_INGREDIENTS,
payload: {
ingredients: ingredients,
},
};
};
const fetchIngredientsFailed = _ => {
return {
type: actionTypes.FETCH_INGREDIENTS_FAILED,
};
};
export const initIngredients = _ => {
return dispatch => {
axios
.get('/ingredients.json')
.then(res => {
dispatch(setIngredients(res.data));
})
.catch(err => {
dispatch(fetchIngredientsFailed());
});
};
};
//Init prices
const setPrices = prices => {
return {
type: actionTypes.SET_PRICES,
payload: {
initialPrice: prices.initialPrice,
ingredientPrices: prices.ingredientPrices,
},
};
};
export const initPrices = _ => {
return dispatch => {
axios
.get('/prices.json')
.then(res => {
dispatch(setPrices(res.data));
})
.catch(err => {
dispatch(fetchIngredientsFailed());
});
};
};
|
import React, { Component, PropTypes } from 'react';
import SessionStore from '../flux/stores/SessionStore'
class FormComponent extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.setValue = this.setValue.bind(this);
}
componentDidMount() {
this.setState({});
}
static getStores() {
return [SessionStore];
}
static getPropsFromStores() {
return SessionStore.getState();
}
setValue(event) {
var object = {};
object[event.target.id] = event.target.value;
this.setState(object);
}
handleSubmit()
{
}
}
export default FormComponent;
|
import React, { useContext, useReducer } from 'react';
import { SAVE_TWEET_ID, REMOVE_TWEET_ID, SET_ERROR_MESSAGE, CLEAR_ALL_SAVED_TWEETS_IDS } from './constants';
import { retrieveSavedTweetsFromLS, savedTweetsToTweetsIds } from './utils';
const AppStateContext = React.createContext(null);
export function useAppReducer() {
return useContext(AppStateContext)[1];
}
export function useAppState() {
return useContext(AppStateContext)[0];
}
function appStateReducer(state, action) {
switch (action.type) {
case SAVE_TWEET_ID: {
const { tweetId } = action;
if (state.savedTweetsIds.includes(tweetId)) {
return state;
}
return {
...state,
savedTweetsIds: [...state.savedTweetsIds, tweetId],
};
}
case REMOVE_TWEET_ID: {
const { tweetId } = action;
const savedTweetsIds = [...state.savedTweetsIds];
const tweetIdIndex = savedTweetsIds.indexOf(tweetId);
if (tweetIdIndex === -1) {
return state;
}
savedTweetsIds.splice(tweetIdIndex, 1);
return {
...state,
savedTweetsIds,
};
}
case CLEAR_ALL_SAVED_TWEETS_IDS: {
return {
...state,
savedTweetsIds: []
}
}
case SET_ERROR_MESSAGE: {
return {
...state,
errorMessage: action.errorMessage,
};
}
default:
return state;
}
}
export function AppStateProvider({ children }) {
const savedTweets = retrieveSavedTweetsFromLS();
const initialState = {
savedTweetsIds: savedTweetsToTweetsIds(savedTweets),
errorMessage: null,
};
const value = useReducer(appStateReducer, initialState);
return (
<AppStateContext.Provider value={value}>
{children}
</AppStateContext.Provider>
);
}
|
import { tagName } from '@ember-decorators/component';
import BaseFormElementLabel from 'ember-bootstrap/components/base/bs-form/element/label';
@tagName('')
export default class FormElementLabel extends BaseFormElementLabel {}
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "71470e1c080a324265d1596c7ce7eb23",
"url": "/react_js_calculator/index.html"
},
{
"revision": "ec9944e174b452f499c6",
"url": "/react_js_calculator/static/css/main.8fd525f6.chunk.css"
},
{
"revision": "7e6e81811165e8045acf",
"url": "/react_js_calculator/static/js/2.93baa0b9.chunk.js"
},
{
"revision": "d705cb622423d72c5defbf368ca70dcc",
"url": "/react_js_calculator/static/js/2.93baa0b9.chunk.js.LICENSE"
},
{
"revision": "ec9944e174b452f499c6",
"url": "/react_js_calculator/static/js/main.fb92bf97.chunk.js"
},
{
"revision": "89c266ab7fd7ce6b7a6d",
"url": "/react_js_calculator/static/js/runtime-main.e53ad146.js"
}
]);
|
import React,{Component} from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'
import './App.css'
import Loader from './component/Loader/Loader';
import Group from './component/Group/Group';
import AddTrainer from './component/Trainer/AddTrainer';
import EditTrainer from './component/Trainer/EditTrainer';
import ListTrainer from './component/Trainer/ListTrainer';
import Navbar from './component/NavbarTrainer/Navbar';
import Header from './component/Header/Header.js';
import Main from './component/Main/Main';
import AddGroup from './component/Group/AddGroup';
import ListStudent from './component/Student/ListStudent';
import AddStudent from './component/Student/AddStudent';
import EditStudent from './component/Student/EditStudent';
function App() {
return (
<div className="containers">
<Router>
<div className="header">
<Header />
</div>
<div className="main">
<Navbar />
<div className="wrapper">
<Switch>
<Route path="/" exact component={Main} />
<Route path="/main" exact component={Main} />
<Route path="/group" component={Group} />
<Route path="/add-group" component={AddGroup} />
<Route path="/students" component={ListStudent} />
<Route path="/add-student" component={AddStudent} />
<Route path="/edit-student" component={EditStudent} />
<Route path="/trainers" component={ListTrainer} />
<Route path="/add-trainer" component={AddTrainer} />
<Route path="/edit-trainer" component={EditTrainer} />
</Switch>
</div>
</div>
</Router>
</div>
);
}
export default App;
|
import './MusicTable.css';
const MusicTable = props => {
return (
<table>
<thead>
<tr>
<th>Index</th>
<th>Id</th>
<th>Title</th>
<th>Danceability</th>
<th>Energy</th>
<th>Mode</th>
<th>Acousticness</th>
<th>Tempo</th>
<th>Duration MS</th>
<th>Num Section</th>
<th>Num Segments</th>
</tr>
</thead>
<tbody>
{props.music.map((singleTrack, index) => (
<tr key={singleTrack['id']}>
<td>{index + 1}</td>
<td>{singleTrack['id']}</td>
<td>{singleTrack['title']}</td>
<td>{singleTrack['danceability']}</td>
<td>{singleTrack['energy']}</td>
<td>{singleTrack['mode']}</td>
<td>{singleTrack['acousticness']}</td>
<td>{singleTrack['tempo']}</td>
<td>{singleTrack['duration_ms']}</td>
<td>{singleTrack['num_sections']}</td>
<td>{singleTrack['num_segments']}</td>
</tr>
))}
</tbody>
</table>
)
}
export default MusicTable;
|
app.factory('resourceMngrSvc', function ($http, $q) {
return {
loginUrl: '/api/Login/',
login: function (userLogin) {
var deferred = $q.defer();
$http({ method: 'put', url: this.loginUrl, data: userLogin })
.success(function (data) {
deferred.resolve(data);
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
registerUser: function (userRegistration) {
var deferred = $q.defer();
$http({ method: 'post', url: this.loginUrl, data: userRegistration })
.success(function (data) {
deferred.resolve(data);
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
checkUserAuthentication: function () {
var deferred = $q.defer();
$http({ method: 'get', url: this.loginUrl })
.success(function (data) {
deferred.resolve(data);
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
logOffUser: function () {
var deferred = $q.defer();
$http({ method: 'put', url: this.loginUrl, data: { Action: 1 } })
.success(function (data) {
deferred.resolve(data);
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
};
});
|
'use strict'
const _ = {
isEqual: require('lodash.isequal')
}
const { Trait } = require('@northscaler/mutrait')
const { MissingRequiredArgumentError } = require('@northscaler/error-support')
const property = require('@northscaler/property-decorator')
/**
* Imparts an `id` property with backing property `_id`.
*/
const Identifiable = Trait(superclass =>
class extends superclass {
@property()
_id
_testSetId (id) {
if (id === null || id === undefined) { throw new MissingRequiredArgumentError({ message: 'id' }) }
return id
}
identifies (that) {
if (!that || !that._id || !this._id) return false
return _.isEqual(this._id, that._id)
}
}
)
module.exports = Identifiable
|
"use strict";
var request = require('request');
var assert = require('assert');
var nconf = require('nconf');
var fs = require('fs');
var baseUrl = require('../../common').baseUrl;
var csMock = require('../mock/customerSuccess');
var customerMock = require('../mock/customerSession');
describe('api', function () {
var cid, csid, rid;
before(function (done) {
csMock.create(function (res) {
var data = JSON.parse(res.body);
csid = data.msg.csid;
done();
});
});
before(function (done) {
customerMock.create(function (res) {
var customer = JSON.parse(res.body);
cid = customer.msg.cid;
done();
});
});
after(function (done) {
csMock.delete(csid, done);
});
after(function (done) {
customerMock.delete(cid, done);
});
describe('#rate', function () {
describe('POST /rates/', function () {
it('should response with success', function (done) {
request.post({
url: baseUrl + '/rates',
form: {cid: cid, csid: csid, rate: 80}
}, function (err, res) {
assert.ifError(err);
var rate = JSON.parse(res.body);
assert.equal(rate.code, 200);
rid = rate.msg.uuid;
done();
});
});
});
describe('GET /rates/report', function () {
it('should response with rate data', function (done) {
request.get(baseUrl + '/rates/report', function (err, res) {
assert.ifError(err);
var data = JSON.parse(res.body);
assert.equal(data.code, 200);
done();
});
});
});
describe('GET /rates/:uuid', function () {
it('should response with rate data', function (done) {
request.get(baseUrl + '/rates/' + rid, function (err, res) {
assert.ifError(err);
var data = JSON.parse(res.body);
assert.equal(data.code, 200);
done();
});
});
});
describe('GET /rates/customer/:cid', function () {
it('should response with rate data', function (done) {
request.get(baseUrl + '/rates/customer/' + cid, function (err, res) {
assert.ifError(err);
var data = JSON.parse(res.body);
assert.equal(data.code, 200);
done();
});
});
});
describe('GET /rates/customersuccess/:csid', function () {
it('should response with rate data', function (done) {
request.get(baseUrl + '/rates/customersuccess/' + csid, function (err, res) {
assert.ifError(err);
var data = JSON.parse(res.body);
assert.equal(data.code, 200);
done();
});
});
});
describe('PATCH /rates/:uuid', function () {
it('should response with success info', function (done) {
request.patch({
url: baseUrl + '/rates/' + rid,
form: {rate: 90}
}, function (err, res) {
assert.ifError(err);
var data = JSON.parse(res.body);
assert.equal(data.code, 200);
done();
});
});
});
describe('DELETE /rates/:uuid', function () {
it('should response with rate data', function (done) {
request.delete(baseUrl + '/rates/' + rid, function (err, res) {
assert.ifError(err);
var data = JSON.parse(res.body);
assert.equal(data.code, 200);
done();
});
});
});
});
});
|
window.node = function (node) {
this.el = this.node = node;
};
node.prototype.append = function(n) {
if (Array.isArray(n)) {
for (var i = 0; i < n.length; ++i) {
if(n[i]) this.node.appendChild(n[i] instanceof node ? n[i].node : n[i]);
}
}
else {
if(n) this.node.appendChild(n instanceof node ? n.node : n);
}
return this;
};
node.prototype.before = function(newNode, refNode) {
if (newNode instanceof node) { newNode = newNode.node; }
if (refNode instanceof node) { refNode = refNode.node; }
this.node.insertBefore(newNode, refNode);
return this;
};
node.prototype.delay = function(time, fn) {
return window.setTimeout(fn.bind(this), time);
};
node.prototype.text = function() {
if(arguments.length > 0) {
var append = arguments.length > 1 && arguments[1];
if(append) {
if (Array.isArray(arguments[0])) {
for(var i = 0; i < arguments[0].length; ++i) {
this.node.appendChild(document.createTextNode(arguments[0][i]));
this.node.appendChild(document.createElement('br'));
}
}
else {
this.node.appendChild(document.createTextNode(arguments[0]));
this.node.appendChild(document.createElement('br'));
}
return this;
}
else {
this.node.textContent = Array.isArray(arguments[0]) ? arguments[0].join(", ") : arguments[0];
return this;
}
}
else {
return this.node.textContent;
}
};
node.prototype.next = function() {
if (arguments.length > 0) {
var selector = arguments[0], n = this.node;
if (selector.length === 0) {
return n.nextElementSibling;
}
while((n = n.nextElementSibling) != null) {
if (Sizzle.matchesSelector(n, selector)) {
return new node(n);
}
}
return null;
}
var n = this.node.nextElementSibling;
if (n == null) { return null; }
else return new node(n);
};
node.prototype.previous = node.prototype.prev = function() {
if (arguments.length > 0) {
var selector = arguments[0], n = this.node;
if (selector.length === 0) {
return n.previousElementSibling;
}
while((n = n.previousElementSibling) != null) {
if (Sizzle.matchesSelector(n, selector)) {
return new node(n);
}
}
return null;
}
var n = this.node.previousElementSibling;
if (n == null) { return n; }
else return new node(n);
};
node.prototype.remove = function() {
if(arguments.length > 0 && (arguments[0] instanceof node || arguments[0] instanceof Node || arguments[0] instanceof Element)) {
for (var i = 0; i < arguments.length; ++i)
this.node.removeChild(arguments[i] instanceof node ? arguments[i].node : arguments[i]);
return this;
}
else {
if (this.node.parentNode)
this.node.parentNode.removeChild(this.node);
}
return null;
};
node.prototype.removeChildren = node.prototype.clear = function() {
while(this.node.lastChild) {
this.node.removeChild(this.node.lastChild);
}
return this;
};
node.prototype.replace = function(newNode) {
this.node.parentNode.replaceChild(newNode instanceof node ? newNode.node : newNode, this.node);
this.node = this.el = newNode instanceof node ? newNode.node : newNode;
return this;
}
node.prototype.class = node.prototype.toggleClass = function() {
this.node.classList.toggle.apply(this.node.classList, arguments);
return this;
};
node.prototype.removeClass = function() {
this.node.classList.remove.apply(this.node.classList, arguments);
return this;
};
node.prototype.addClass = function() {
this.node.classList.add.apply(this.node.classList, arguments);
return this;
};
node.prototype.hasClass = function(className) {
return this.node.classList.contains(className);
}
node.prototype.attr = function(props) {
if (props == null) return this;
if (arguments.length === 1 && typeof props === "string") {
return this.node.getAttribute(props);
}
else if (arguments.length === 2) {
this.node.setAttribute(props, arguments[1]);
}
else {
for (var property in props) {
if (props.hasOwnProperty(property)) {
if (property.toLowerCase() == "text") {
this.text(props[property]);
}
else
this.node.setAttribute(property, props[property]);
}
}
}
return this;
};
node.prototype.removeAttr = function(attr) {
this.node.removeAttribute(attr);
return this;
}
node.prototype.style = function(styles) {
if (styles == null) return this;
if (typeof styles === "string") {
return this.node.style[styles];
}
for (var property in styles) {
if (styles.hasOwnProperty(property)) {
this.node.style[property] = styles[property];
}
}
return this;
};
node.prototype.data = function(key) {
if (typeof key === "string") {
if (arguments.length == 2) {
this.node.setAttribute("data-" + key, arguments[1]);
return this;
}
else {
return this.node.getAttribute("data-" + key);
}
}
else {
for (var property in key) {
if (key.hasOwnProperty(property)) {
this.node.setAttribute("data-" + property, props[property]);
}
}
return this;
}
};
node.prototype.on = function(event, fn) {
this.node.addEventListener(event, fn);
return this;
};
node.prototype.off = function(event, fn) {
this.node.removeEventListener(event, fn);
return this;
};
node.prototype.value = function() {
if(arguments.length == 1) {
if(typeof this.node.value !== "undefined") {
this.node.value = arguments[0];
}
else {
this.node.setAttribute("value", arguments[0]); // nodeValue?
}
return this;
}
else {
if (typeof this.node.value !== "undefined") return this.node.value;
else return this.node.getAttribute('value');
}
};
node.prototype.parent = function() {
return new node(this.node.parentNode);
};
node.prototype.firstElement = function() {
var el = this.node.firstElementChild || this.node.children.length > 0 ? this.node.children[0] : null;
return el == null ? null : new node(el);
};
node.prototype.children = function(selector) {
return dom(selector, this.node);
};
node.prototype.first = function() {
if (arguments.length > 0) {
var selector = arguments[0];
return dom(selector + ':first', this.node)[0];
}
else {
return this.node.firstChild;
}
};
node.prototype.last = function() {
if (arguments.length > 0) {
var selector = arguments[0];
return dom(selector + ':last', this.node)[0];
}
else {
return this.node.lastChild;
}
};
node.prototype.transitionEnd = function(callback) {
if (typeof callback === "function") {
this.node.addEventListener(dom.transitionEvent, callback);
}
return this;
};
node.prototype.animationEvent = function(type, callback) {
var pfx = ["webkit", "moz", "MS", "o", ""];
for (var p = 0; p < pfx.length; p++) {
if (!pfx[p]) type = type.toLowerCase();
this.node.addEventListener(pfx[p]+type, callback, false);
}
return this;
};
node.prototype.animationStart = function(callback) {
return this.animationEvent("AnimationStart", callback);
};
node.prototype.animationEnd = function(callback) {
return this.animationEvent("AnimationEnd", callback);
};
node.prototype.animationIteration = function(callback) {
return this.animationEvent("AnimationIteration", callback);
};
/*node.prototype.ripple = function() {
var ripple = dom.div().style({
position: "absolute",
top: "0px",
left: "0px",
height: "100%",
width: "100%",
"border-radius": "50%",
"background-color": "rgba(0, 0, 0, 0.870588)",
opacity: 0,
transform: "scale(1)",
transition: "opacity 2s cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 1s cubic-bezier(0.23, 1, 0.32, 1) 0ms"
}).transitionEnd(function() {
ripple.remove();
console.log("removed");
});
this.append(ripple);
ripple.node.style.opacity = 1;
return this;
};*/
/***********************************************************
* DOM
***********************************************************/
var dom = function(selector) {
var target = arguments.length > 1 ? arguments[1] : document;
var count = arguments.length > 2 ? arguments[2] : -1;
//add , support
if (arguments.length === 2 && !(arguments[1] instanceof Node || arguments[1] instanceof Element)) {
//console.warn(arguments);
return dom.create(arguments[0], arguments[1]);
}
else if (selector instanceof Node) {
return new node(selector);
}
else if (selector instanceof node) {
return selector;
}
else if (selector == null || selector.length == 0) {
return null;
}
else if (selector.charAt(0) == '#') {
return new node(document.getElementById(selector.substr(1)));
}
else {
var els = Sizzle(selector, target);
for (var i = els.length - 1; i >= 0; --i) {
els[i] = new node(els[i]);
if (count > 0 && (els.length - i > count))
return els;
}
return els;
}
};
dom.create = function(tag, props) {
var n = new node(document.createElement(tag));
return n.attr(props);
};
dom.a = function(href, props) {
if (props == null) props = {};
props.href = href;
return this.create('a', props);
};
dom.div = function() {
var props = arguments.length == 1 ? arguments[0] : null;
return this.create('div', props);
};
dom.span = function() {
var props = arguments.length == 1 ? arguments[0] : null;
return this.create('span', props);
};
dom.label = function() {
var props = arguments.length == 1 ? arguments[0] : null;
return this.create('label', props);
};
dom.p = function() {
var props = arguments.length == 2 ? arguments[1] : {};
if(arguments.length == 1) {
props.text = arguments[0];
}
return this.create('p', props);
};
dom.td = function() {
var props = arguments.length == 2 ? arguments[1] : {};
if(arguments.length > 0) {
if (typeof arguments[0] === "string") props.text = arguments[0];
}
var n = this.create('td', props);
if (arguments.length > 0 && arguments[0] instanceof node || arguments[0] instanceof Node || arguments[0] instanceof Element) {
return n.append(arguments[0]);
}
return n;
};
dom.input = function(type) {
var props = arguments.length == 2 ? arguments[1] : {};
props.type = type;
return this.create('input', props);
};
dom.icon = function(icon) {
return this.create('i', {class: 'material-icons', text: icon}); //
};
dom.fontawesome = function(icon) {
return this.create('i', {class: 'fa fa-' + icon});
};
dom.onload = function(f) {
var old = window.onload;
if (typeof window.onload != 'function') {
window.onload = f;
} else {
window.onload = function () {
old();
f();
}
}
};
/*dom.toast = function(text) {
var icon = arguments.length > 1 && typeof arguments[1] === "string" ? dom.icon(arguments[1]).style({float:'left'}) : (arguments.length > 2 && typeof arguments[2] === "string" ? dom.icon(arguments[2]).style({float:'left'}) : null);
var onclick = arguments.length > 1 && typeof arguments[1] === "function" ? arguments[1] : arguments.length > 2 && typeof arguments[2] === "function" ? arguments[2] : null;
var snack;
var hide = function() {
snack.removeClass('show');
if (dom.toast.stack && dom.toast.stack.length) {
var nxt = dom.toast.stack.pop();
setTimeout(function() { dom.toast(nxt.text, nxt.icon, nxt.callback); }, 1000);
}
};
if (document.getElementById('snackbar')) {
snack = dom("#snackbar");
if (snack.hasClass('show')) {
if (!dom.toast.stack) { dom.toast.stack = []; }
dom.toast.stack.push({text:text, icon: arguments.length > 1 && typeof arguments[1] === "string" ? arguments[1] : arguments.length > 2 && typeof arguments[2] === "string" ? arguments[2] : null, callback: onclick});
}
else {
snack.remove();
snack = dom.create('div', {id: 'snackbar'});
if (onclick) {
snack.on('click', onclick);
}
dom(document.body).append(snack.text(text).append(icon).addClass('show'));
setTimeout(hide, 3000);
}
}
else {
snack = dom.create('div', {id: 'snackbar'});
if (onclick) {
snack.on('click', onclick);
}
dom(document.body).append(snack.text(text).append(icon).addClass('show'));
setTimeout(hide, 3000);
}
};*/
dom.url = function() {
return [location.protocol, '//', location.host, location.pathname].join('');
};
dom.transitionEvent = function() {
var t;
var el = document.createElement('span');
var transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
}
for(t in transitions){
if( el.style[t] !== undefined ){
return transitions[t];
}
}
}();
(function() {
var change = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1) || window.location.hash.substr(window.location.hash.lastIndexOf('?')).substr(1);
dom.query = {};
while (match = search.exec(query))
dom.query[decode(match[1])] = decode(match[2]);
};
window.addEventListener("hashchange", change);
window.addEventListener("popstate", change);
change();
})();
dom.debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
window.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
window.setTimeout( callback, 1000 / 60 );
};
var ajax = function(opts) {
if (!(this instanceof ajax)) {
return new ajax(opts);
}
this.type = opts.type ? (ajax.REQUESTS[opts.type.toUpperCase()] ? opts.type : ajax.REQUESTS.GET) : ajax.REQUESTS.GET;
this.url = ajax.getUrl(opts.url);
this.data = opts.data ? opts.data : null;
this.xhr = _ajax(this.url, this.type, opts.oncomplete, opts.onerror, opts.responseType, this.data);
};
/*ajax.prototype.on = function(event, fn) {
};*/
dom.ajax = ajax;
var _ajax = function() {
var REQUESTS = window.ajax.REQUESTS = { GET:"GET", POST:"POST" };
var RESPONSE_TYPES = window.ajax.RESPONSE_TYPES = { ArrayBuffer:"arraybuffer", Blob:"blob", Document:"document", JSON:"json", DomString:"text" };
var STATUS_CODES = window.ajax.STATUS_CODES = { OK:200, NOT_FOUND:404 };
//var CallBacks = { };
var RESPONSE_HANDLERS = {
ArrayBufferHandler:function(e, callback, error) {
if (e.status == STATUS_CODES.OK) {
if(isFunction(callback)) { callback(e); }
}
else { if(isFunction(error)) { error(e); } }
},
BlobHandler:function(e, callback, error) {
if (e.status == STATUS_CODES.OK) {
if(isFunction(callback)) { callback(e); }
}
else { if(isFunction(error)) { error(e); } }
},
DocumentHandler:function(e, callback, error) {
if (e.status == STATUS_CODES.OK) {
if(isFunction(callback)) { callback(e); }
}
else { if(isFunction(error)) { error(e); } }
},
JSONHandler:function(e, callback, error) {
if (e.status == STATUS_CODES.OK) {
if(isFunction(callback)) { callback(e, JSON.parse(e.responseText)); }
}
else { if(isFunction(error)) { error(e); } }
},
DomStringHandler:function(e, callback, error) {
if (e.status == STATUS_CODES.OK) {
if(isFunction(callback)) { callback(e); }
}
else { if(isFunction(error)) { error(e); } }
},
};
/*for(var key in RESPONSE_TYPES) {
CallBacks[key] = [];
}*/
function isFunction(object) {
return !!(object && object.constructor && object.call && object.apply);
}
window.ajax.getUrl = function(url) {
if (url == null || typeof url === "undefined") {
throw "Invalid URL specified";
}
var urlExp = new RegExp('^(?:[a-z]+:)?//', 'i');
if(urlExp.test(url)) {
return url;
}
else {
if (url.length && url.charAt(0) == '/') {
return window.location.origin + url;
}
else {
return window.location.origin + '/' + url;
}
}
}
/*function SetCallback(response_type, callback) {
CallBacks[response_type.toLowerCase()] = callback;
}*/
var ajax = function(url, type, oncomplete, onerror, response_type)
{
var data = arguments.length > 5 ? arguments[5] : null;
if (data && !(data instanceof FormData)) {
var params = typeof data == 'string' ? data : Object.keys(data).map(
function(k){
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
}
).join('&');
data = params;
}
if (typeof data === "string" && type.toUpperCase() == REQUESTS.GET) {
url += "?" + data;
}
if(response_type == undefined)
response_type = "";
var xhr = new XMLHttpRequest();
xhr.responseType = response_type;
xhr.open(type, url, true);
xhr.withCredentials = true;
switch(response_type.toLowerCase())
{
case RESPONSE_TYPES.ArrayBuffer:
xhr.onload = function() { RESPONSE_HANDLERS.ArrayBufferHandler(this, oncomplete, onerror); };
break;
case RESPONSE_TYPES.Blob:
xhr.onload = function() {RESPONSE_HANDLERS.BlobHandler(this, oncomplete, onerror); };
break;
case RESPONSE_TYPES.Document:
xhr.onload = function() { RESPONSE_HANDLERS.DocumentHandler(this, oncomplete, onerror); };
break;
case RESPONSE_TYPES.JSON:
xhr.responseType = RESPONSE_TYPES.DomString; //WebKit doesn't support json yet
xhr.onload = function() { RESPONSE_HANDLERS.JSONHandler(this, oncomplete, onerror); };
break;
case RESPONSE_TYPES.DomString:
xhr.onload = function() { RESPONSE_HANDLERS.DomStringHandler(this, oncomplete, onerror); };
break;
default:
xhr.onload = function(e) { RESPONSE_HANDLERS.DomStringHandler(this, oncomplete, onerror); };
break;
}
if (data) {
xhr.send(data);
}
else {
xhr.send();
}
return xhr;
};
return ajax;
}();
|
if(!!window.performance && window.performance.navigation.type === 2) {
window.location.reload();
}
document.addEventListener("DOMContentLoaded", function(event) {
var colors = [
[
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500'
],
[
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500',
'mdl-color--blue-500'
]
];
var rentUtils_progress_container = document.querySelector('.graph_holder');
var openButton = document.getElementsByClassName('my-fab')[0];
var newCatNameField = document.getElementById('new_cat_name_field');
var newCatLimitField = document.getElementById('new_cat_limit_field');
var createButton = document.getElementById('create_dialog');
var dismissButton = document.getElementById('dismiss_dialog');
var dialog = document.querySelector('dialog');
newCatNameField.addEventListener('input', isValidForm);
newCatLimitField.addEventListener('input', isValidForm);
openButton.addEventListener('click', function() {
dialog.showModal();
});
createButton.addEventListener('click', function(){
addCategory(newCatNameField.value, newCatLimitField.value);
dialog.close();
newCatNameField.value = '';
newCatLimitField.value = '';
(newCatNameField.parentNode).MaterialTextfield.checkDirty();
(newCatNameField.parentNode).MaterialTextfield.change();
(newCatLimitField.parentNode).MaterialTextfield.checkDirty();
(newCatLimitField.parentNode).MaterialTextfield.change();
});
dismissButton.addEventListener('click', function(){
dialog.close();
newCatNameField.value = '';
newCatLimitField.value = '';
(newCatNameField.parentNode).MaterialTextfield.checkDirty();
(newCatNameField.parentNode).MaterialTextfield.change();
(newCatLimitField.parentNode).MaterialTextfield.checkDirty();
(newCatLimitField.parentNode).MaterialTextfield.change();
});
requestAllCategories(initAllCategories);
function requestAllCategories(callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.readyState == 4 && xhr.status == 200){
console.log("GET: CATEGORIES: /cats");
console.log('GOT: ');
console.log(JSON.parse(xhr.responseText));
console.log("________________________");
callback(JSON.parse(xhr.responseText));
}
else
huh('Failed to Fetch Categories')
};
xhr.open("GET", '/cats', true);
xhr.send(null);
function huh(message){
var handler = function(event) {};
var snackbarContainer = document.querySelector('#demo-snackbar-example');
var data = {
message: message,
timeout: 2500,
actionHandler: handler,
actionText: 'OK'
};
snackbarContainer.MaterialSnackbar.showSnackbar(data);
}
}
function initAllCategories(rawJson){
var allCats = rawJson['categories'];
var temp = 0;
allCats.forEach(function(item){
if(temp == 0){
// Handle rentUtils
temp = 1;
var rentUtils = document.getElementById('card_frame');
rentUtils.querySelector('.card-limit-label').textContent = item['cost'];
rentUtils.querySelector('a').addEventListener('click', function(){
document.getElementById('cat_rentUtils').submit();
});
}
else {
addNewCard(item['name'], item['cost']/item['limit'], item['cost'], item['limit']);
}
})
}
/**
* Validates form before attempting POST in order to create new Category
*/
function isValidForm(){
if(newCatNameField.value.length > 0 && checkDuplicateName(newCatNameField.value) &&
newCatLimitField.validity.valid && newCatLimitField.value.length > 0){
createButton.classList.remove('mdl-button--disabled');
}
else {
createButton.classList.add('mdl-button--disabled');
}
}
/**
* Checks for redundant Category Creation
*
* @param proposedName The current name in the form before submitting
* @returns {boolean} indicates whether category name already exists
*/
function checkDuplicateName(proposedName){
var allCatNames = document.querySelectorAll('h4');
for (var i = 0; i < allCatNames.length; i++) {
if(allCatNames[i].textContent == proposedName)
return false;
}
return true
}
/**
* Builds a new card by cloning default rentUtils purchases card and populating
* specified values to match the category
*
* @param cat_name the name of category being added
* @param percent the percentage of specified budget
*/
function addNewCard(cat_name, percent, cost, limit){
var parent = document.getElementById('cat_holder');
var cloned_card = document.getElementById('card_frame').cloneNode(true);
cloned_card.firstElementChild.classList.remove('mdl-color--grey');
cloned_card.firstElementChild.classList.add(colors[Math.round(Math.random())][Math.floor(Math.random()*6)]);
var f = cloned_card.querySelector('form');
f.querySelector('input').setAttribute('value', cat_name);
f.querySelector('a').addEventListener('click', function(){
f.submit();
});
cloned_card.querySelector('h4').firstChild.textContent = cat_name;
cloned_card.querySelector('.card-limit-label').textContent = cost+" / "+limit;
parent.appendChild(cloned_card);
setProgress(cloned_card.querySelector('.graph_holder'), percent);
}
/**
* Initlizes the progress bar of a category card
*
* @param container the specfic graph container to be populated
* @param progress the percentage of limit (specify with floats)
*/
function setProgress(container, progress){
var bar = new ProgressBar.SemiCircle(container, {
strokeWidth: 6,
color: '#fff',
trailColor: '#e0e0e0',
trailWidth: 1,
easing: 'easeInOut',
duration: 1400,
svgStyle: null,
text: {
value: '',
alignToBottom: false
},
from: {color: '#fff'},
to: {color:'#fff'},
// Set default step function for all animate calls
step: (state, bar) => {
bar.path.setAttribute('stroke', state.color);
var value = Math.round(bar.value() * 100);
if (value === 0) {
bar.setText('0%');
} else {
bar.setText(value+"%");
}
bar.text.style.color = state.color;
}
});
bar.text.style.fontFamily = '"Roboto", Helvetica, sans-serif';
bar.text.style.fontSize = '2rem';
bar.animate(progress); // Number from 0.0 to 1.0
}
/**
* Sends a post to the /cats endpoint in order to create a new category
*
* @param categoryName the name of the category whos creation is being requested
* @param categoryLimit the limit of the category whos creation is being requested
*/
function addCategory(categoryName, categoryLimit){
if(categoryName.length > 0){
var cat_object = JSON.stringify(
{
new_cat_name: categoryName,
new_cat_limit: categoryLimit
}
);
var xhr = new XMLHttpRequest();
xhr.open("POST", '/cats', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
var res = JSON.parse(xhr.responseText);
if(xhr.status !== 200){
signal("Network Error:"+xhr.status);
}
if(res["completed"]){
signal('New category was created');
console.log("NEW CATEGORY, POST: /cats");
console.log('SENT: ');
console.log(cat_object);
console.log('GOT: ');
console.log(res);
console.log("_________________________");
addNewCard(categoryName,.0, 0, categoryLimit)
}
else {
signal('Failed to create new category');
}
};
xhr.send(cat_object);
function signal(message){
var handler = function(event) {};
var snackbarContainer = document.querySelector('#demo-snackbar-example');
var data = {
message: message,
timeout: 2500,
actionHandler: handler,
actionText: 'OK'
};
snackbarContainer.MaterialSnackbar.showSnackbar(data);
}
}
}
});
|
import React, {useState} from "react";
import styled from "styled-components";
import axios from "axios";
import {Redirect} from "react-router-dom";
import {
FormControl,
Input,
InputLabel,
Button as MuiButton,
Paper,
Typography
} from "@mui/material";
import {spacing} from "@mui/system";
const Button = styled(MuiButton)(spacing);
const Wrapper = styled(Paper)`
padding: ${props => props.theme.spacing(6)};
${props => props.theme.breakpoints.up("md")} {
padding: ${props => props.theme.spacing(10)};
}
`;
function ResetPassword() {
const [mail, setMail] = useState(false);
function sendflask(event) {
event.preventDefault();
console.log("executed");
axios
.post(process.env.REACT_APP_SERVER_URL + "forgotpassword", {
email: event.target.email.value
})
.then(function (response) {
console.log(response.data);
setMail(true);
})
.catch(function (error) {
console.log(error.data);
});
}
return (
<Wrapper>
<Typography component="h1" variant="h4" align="center" gutterBottom>
Reset password
</Typography>
{mail && (
<Redirect to='/auth/sign-in'/>
)}
<Typography component="h2" variant="body1" align="center">
Please enter your email. We send you a link to reset your password.
</Typography>
<form onSubmit={sendflask}>
<FormControl margin="normal" required fullWidth>
<InputLabel htmlFor="email">Email Address</InputLabel>
<Input id="email" name="email" autoComplete="email" autoFocus/>
</FormControl>
<Button
type="Submit"
to=""
fullWidth
variant="contained"
color="primary"
mt={2}
>
Reset password
</Button>
</form>
</Wrapper>
);
}
export default ResetPassword;
|
var React=require('react');
var addons = require('react-addons');
var ReactDOM=require('react-dom');
var DragArea=React.createClass({
getInitialState:function(){
return {
left: 0,
top: 0,
currentX: 0,
currentY: 0,
flag: false
}
},
startDrag:function(e){
// var dragBox=document.getElementById('form');
var newState={};
var event=e||window.event;
event.preventDefault();
// var computedStyle=document.defaultView.getComputedStyle(dragBox,null);
// newState.left=computedStyle.left;
// newState.top=computedStyle.top;
newState.currentX=event.clientX;
newState.currentY=event.clientY;
newState.flag=true;
this.props.callbackParent(newState);
},
render:function(){
return (
<div className="drag" id="drag" onMouseDown={this.startDrag}>在我身上按住鼠标可以把From拖走!</div>
);
}
});
module.exports=DragArea;
|
const bookingData = [
{
icon: '',
status: 'Done',
title: 'Info card title',
desc: 'Some quick example text to build on the card title and make up the bulk of the card\'s content.'
},
{
icon: '',
status: 'Pending',
title: 'Info card title',
desc: 'Some quick example text to build on the card title and make up the bulk of the card\'s content.'
},
{
icon: '',
status: 'On Goning',
title: 'Info card title',
desc: 'Some quick example text to build on the card title and make up the bulk of the card\'s content.'
},
]
|
import { Workbox } from "workbox-window";
let wb;
if ("serviceWorker" in navigator) {
wb = new Workbox("service-worker.js");
// Assuming the user accepted the update, the listener
// will reload the page as soon as the previously waiting
// service worker is activated and has taken control.
wb.addEventListener("controlling", () => {
console.log("new content, reload!!")
window.location.reload();
});
// Register the service worker after event listeners have been added.
wb.register();
} else {
wb = null;
}
export default wb;
|
var fs = require('fs');
var sax = require('sax');
var Factory = require('../domain/src/Factory.js')
var stream = sax.createStream();
var factory = new Factory();
var connection = factory.createDBConnection();
var registerASiteAction = factory.createRegisterASiteAction();
const FILE = process.argv[2]
let siteData = {};
let actions = 0;
stream.on("opentag", node => {
if (node.attributes) {
if(node.attributes.LAT) {
siteData.coordinate = {
x: Number(node.attributes.LAT),
y: Number(node.attributes.LON)
}
}
if (node.attributes.K == 'name') {
siteData.name = node.attributes.V
actions++;
readStream.pause()
registerASiteAction.run(siteData).then( (site) => {
if(actions <= 1){
readStream.resume()
}
actions--;
});
siteData = {};
}
}
});
stream.on("end", () => {
console.log("Finished parsing");
setTimeout( () => {
console.log("Finished populating");
connection.end();
}, 5000);
});
readStream = fs.createReadStream(__dirname + FILE)
readStream.pipe(stream)
|
var app = getApp()
Page({
data: {
userInfo:"",
pic_url:[
"../image/carpack2.jpg",
"../image/carpack1.jpg",
],
pickurl1:[
"../image/carpack3.jpg"
],
detailgood:[],
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 100,
hideif:true,
name:'',
tel:'',
address:'',
qq:'',
id:'',
openid:"",
off:""
},
onLoad: function (options) {
wx.getStorage({
key: 'openid',
fail: () => { wx.redirectTo({ url: '../index/index', }) },
})
// 页面初始化 options为页面跳转所带来的参数
var id = options.id;
var that = this;
console.log("taocan"+id);
that.setData({
id:options.id
})
wx.request({
url: 'https://www.lieyanwenhua.com/packageid',
data: {
packid:id
},
method: 'POST',
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: (res) => {
console.log(res.data);
that.setData({
detailgood:res.data
})
if(res.data.packid==2){
that.setData({
pic_url:that.data.pickurl1
})
}
console.log(that.data.detailgood);
}
})
},
onReady: function () {
var that = this;
wx.getStorage({
key: 'userInfo',
success: function (res) {
console.log("cheng");
that.setData({
userInfo: res.data
})
console.log("jia");
},
});
wx.getStorage({
key: 'openid',
success: function (res) {
console.log(res)
console.log(res.data)
that.setData({
openid: res.data
})
console.log(that.data.openid)
},
});
// 页面渲染完成
},
onShow: function () {
// 页面显示
},
onHide: function () {
// 页面隐藏
},
onUnload: function () {
// 页面关闭
},
purchase: function () {
var that = this
console.log(that.data.hideif);
that.setData({
hideif:false
})
},
cancelthis:function(){
var that=this
that.setData({
hideif:true
})
},
name: function (e) {
this.setData({
name: e.detail.value
})
},
tel: function (e) {
this.setData({
tel: e.detail.value
})
},
address: function (e) {
this.setData({
address: e.detail.value
})
},
qq: function (e) {
this.setData({
qq: e.detail.value
})
},
nexttap:function(){
var that = this
console.log(this.data.name + this.data.tel + this.data.address + this.data.qq)
wx.request({
url: 'https://www.lieyanwenhua.com/testform',
data: {
openid: that.data.openid
},
method: 'POST',
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: (res) => {
console.log(res.data);
that.setData({
off: res.data
})
console.log(that.data.off);
}
})
// 这里判断重复报名
if(that.data.off){
wx.showToast({
title: '检测到您已经报名',
})
}
else{
//首先判断必填项是否为空,为空提示,不为空则继续下一步
if (this.data.name == "" | this.data.tel == "" | this.data.address == "" | this.data.qq == "") {
wx.showToast({
title: '必填项缺失',
})
}
else {
wx.navigateTo({
url: '../formpay/formpay?name=' + that.data.name + '&tel=' + that.data.tel + '&address=' + that.data.address + '&qq=' + that.data.qq + '&car=' + that.data.id + '&packname=' + that.data.detailgood.packname,
})
}
}
}
})
|
module.exports = {
getTargetList: '/dataapi/target/getTargetList', //获取指标列表
getTargetConfig: '/dataapi/target/getTargetConfig', //获取指标配置 //下拉列表数据
getParaTreeInfo: '/dataapi/inface/getParaTreeInfo', //获取参数树状图联动数据
editTarget: '/dataapi/target/editTarget', //添加、编辑指标
getRuleList: '/dataapi/target/getRuleList', //获取指标规则列表
getParaRuleTreeInfo: '/dataapi/inface/getParaRuleTreeInfo', //获取参数树状图联动数据--指标规则
getTargetRuleConfig: '/dataapi/target/getTargetRuleConfig', //获取指标规则配置
editRule: '/dataapi/target/editRule', //添加规则
changeRuleStatus: '/dataapi/target/changeRuleStatus', //修改指标规则状态
changeTargetStatus: '/dataapi/target/changeTargetStatus', //修改指标状态
getTargetInfo: '/dataapi/target/getTargetInfo', //获取指标信息
}
|
import Ember from 'ember';
export default Ember.Component.extend({
historyMean: Ember.computed('history.@each',function(){
var meanHistory = this.get('history')
var sum = 0,
meanSum =0,
meanSumRound;
meanHistory.forEach(function (a) {
sum += +a.get('time');
});
meanSum = sum/meanHistory.toArray().length;
meanSumRound = meanSum.toFixed(1);
return meanSumRound;
}),
history: undefined,
historyObj: Ember.observer('history.@each',function() {
var meanHistory = this.get('history');
var sum = {};
meanHistory.forEach(function (a) {
if (sum[a.get('rentalpoint')]) {
sum[a.get('rentalpoint')] += +a.get('time');
} else {
sum[a.get('rentalpoint')] = +a.get('time');
}
});
for (var i in sum) {
var len = meanHistory.toArray().filter((record) => i === record.get('rentalpoint')).length;
sum[i] = sum[i]/len;
sum[i] = sum[i].toFixed(1);
}
meanHistory.forEach(function (a) {
a.set('mean', sum[a.get('rentalpoint')]);
})
})
});
|
function RenderResults(newsItemDetails) {
var details = JSON.parse(newsItemDetails);
jQuery("#news-page-title").append("<h1>" + details.itemTitle + "</h1>");
jQuery("#news-page-body").append("<img src='" + details.itemImage + "' align='left' class='news-page-image' />");
jQuery("#news-page-body").append("<p>" + details.itemBody + "</p>");
}
|
#!/usr/bin/env node
// cmd line entry point
const args = require('yargs-parser')(process.argv.slice(2));
const configUtils = require('./config');
const shell = require('shelljs');
const format = require('./tool');
const galleryGenerator = require('./gallery-generator/generate-gallery');
if (args.listStyles) {
console.log('Available Styles: ', configUtils.getAvailableStyles().join(', '));
process.exit(0);
}
if (args.listModes) {
console.log('Available Modes: ', configUtils.getAvailableModes().join(', '));
process.exit(0);
}
if (args.help) {
const help = {
'--input': 'input file - can be passed many times',
'--style': 'one of the available styles, example: standard, airbnb, google, etc',
'--output': 'output file',
'--debug': 'TODO',
'--mode': 'TODO',
'--list-styles': 'list available styles',
'--list-modes': 'list available modes',
};
const helpStr = JSON.stringify(help, 0, 2);
console.log(`
Usage:
$ tools --input src/some.js --style airnbn
Options:
${helpStr}
`);
process.exit(0);
}
// main !
const config = {
input: args.input,
style: args.style,
output: args.output,
debug: args.debug,
mode: args.mode || configUtils.getDefaultMode(),
eslintPath: args.eslintPath,
buildGallery: args.buildGallery,
};
// used as gallery-generator
if (config.buildGallery) {
galleryGenerator.buildGallery(config);
process.exit(0);
}
// validate in case is used as formatted
if (!config.input && !config.source) {
console.log('Invalid call you must provide --input, aborting');
process.exit(1);
}
if (!config.mode || configUtils.getAvailableModes().indexOf(config.mode) === -1) {
console.log(`Invalid mode ${config.mode}. Aborting`);
process.exit(1);
}
config.eslintPath = config.eslintPath || configUtils.getEslintRcFor(config.style) || './.eslintrc.json';
if (!shell.test('-f', config.eslintPath)) {
console.log(`Invalid style ${config.style}. Aborting`);
process.exit(1);
}
format(config);
|
import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import * as Facebook from 'expo-facebook'
import { StyleSheet, Text, View,TextInput,TouchableOpacity,Alert } from 'react-native';
import { SocialIcon } from 'react-native-elements'
import firebase from '../firebase/firebaseDb'
export default class App extends React.Component {
constructor(props){
super(props)
this.state=({
email:"",
password:""
})
}
loginUser=(email,password)=>{
try {
firebase.auth().signInWithEmailAndPassword(email,password).then(function(user){
console.log(user)
})
} catch (error) {
console.log(error.toString())
}
finally{
Alert.alert(error.toString())
}
}
async loginWithFacebook(){
try {
await Facebook.initializeAsync({
appId: '207688944162040',
});
const {
type,
token,
expirationDate,
permissions,
declinedPermissions,
} = await Facebook.logInWithReadPermissionsAsync({
permissions: ['public_profile'],
});
if (type === 'success') {
// Get the user's name using Facebook's Graph API
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
this.props.navigation.navigate('Home')
Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
} else {
// type === 'cancel'
}
} catch ({ message }) {
console.log(`Facebook Login Error: ${message}`)
}
finally{
Alert.alert(`Facebook Login Error: ${message}`)
}
}
render(){
return (
<View style={styles.container}>
<Text style={styles.logo}>EmpAPP</Text>
<View style={styles.inputView} >
<TextInput
style={styles.inputText}
placeholder="Email..."
placeholderTextColor="#003f5c"
onChangeText={email => this.setState({email})}/>
</View>
<View style={styles.inputView} >
<TextInput
style={styles.inputText}
placeholder="Password..."
placeholderTextColor="#003f5c"
secureTextEntry={true}
onChangeText={password => this.setState({password})}/>
</View>
<TouchableOpacity onPress={()=>this.loginUser(this.state.email,this.state.password)} style={styles.loginBtn}>
<Text style={styles.loginText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity onPress= {()=>this.props.navigation.navigate('SignUp')} style={styles.loginBtn} >
<Text style={styles.loginText}>Sign Up</Text>
</TouchableOpacity>
<SocialIcon onPress= {()=>this.loginWithFacebook()}
title='Sign In With Facebook'
button
type='facebook'
/>
</View>
);
}
}
export const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#003f5c',
alignItems: 'center',
justifyContent: 'center',
},
logo:{
fontWeight:"bold",
fontSize:50,
color:"#fb5b5a",
marginBottom:40
}, inputView:{
width:"80%",
backgroundColor:"#465881",
borderRadius:25,
height:50,
marginBottom:20,
justifyContent:"center",
padding:20
}, inputText:{
height:60,
color:"white"
},forgot:{
color:"white",
fontSize:11
},loginBtn:{
width:"30%",
backgroundColor:"#fb5b5a",
borderRadius:25,
height:50,
alignItems:"center",
justifyContent:"center",
marginTop:30,
marginBottom:5
}
});
|
'use strict';
angular.module('angularTest')
.controller('EditCtrl', function ($http, $scope, EditService, staticTemplateService, fileUpload, $rootScope) {
var edit = this;
$scope.username = "situ";
$scope.sampleText = 'f dasf asdfa dfadsf adsfad sfdas fasf dasfas dfdas fadsf adsfads fads fasdf asdfas df';
$scope.default = {
"balloonFlyOut": '.balloonFlyOut'
};
$scope.newArticle = {};
$scope.newBlog = {};
$scope.locationMap = {};
// Get all the default menu items from template.json
staticTemplateService.all().then(function(data) { $scope.menuStack = data; });
// Get all the default menu items which needs to be added to user.json
staticTemplateService.all().then(function(data) { $scope.originalmenuStack = data; });
// Gets all the default settings of user.json
EditService.all()
.then(function(data) {
$scope.data = data;
window.scopedData = $scope;
// $scope.contactForm = data.menuList[getJSONIndex("Item4")].content.formElements.fields;
}).finally(function() {
// Init Method Call
$scope.onDataLoaded();
});
$scope.onDataLoaded = function() {
$scope.setMenuScroll();
};
$scope.showTemplateFlyOut = function() {
if($($scope.default.balloonFlyOut).hasClass("fadeOut")) {
$($scope.default.balloonFlyOut).addClass("fadeIn").removeClass("fadeOut");
} else {
$($scope.default.balloonFlyOut).removeClass("fadeIn").addClass("fadeOut");
}
};
$scope.addTemplate = function(copy) {
var copy = $scope.originalmenuStack.menuList[copy],
checkPoint = false;
$.each($scope.data.menuList, function(key, value) {
if(value.menuId == copy.menuId) {
checkPoint = true;
return;
}
});
$(".balloonFlyOut").removeClass("fadeIn").addClass("fadeOut");
// Check for no-repeating sections in a page.
(!checkPoint) ? $scope.data.menuList.push(copy) : '';
};
$scope.deleteTemplate = function(id) {
$scope.data.menuList.splice(id,1);
};
$scope.setMenuScroll = function() {
$(".topNav ul").delegate( "li", "click", function() {
if($(this).find("a").attr("data")) {
$(".topNav ul li").removeClass("active");
var top = $($(this).find("a").attr("data")).position().top - 58;
$('html,body').animate({
scrollTop: top
}, 1000);
$(this).addClass("active");
event.preventDefault();
}
});
};
$scope.deleteRecordHandler = function(array, index){
array.splice(index, 1);
};
$scope.openOverlay = function (elem) {
$("#"+elem).find("overlay-component").show();
$("body").append("<div class='overlayScreen'></div>");
};
$scope.closeOverlay = function(parentElem) {
$("#"+parentElem).find("overlay-component").hide()
$(".overlayScreen").remove();
};
$scope.saveArticle = function (isValid) {
if($scope.newArticle && isValid) {
$scope.data.menuList[0].content.description.push($scope.newArticle);
$scope.closeOverlay('section1');
}
$scope.newArticle = {};
};
$scope.saveBlogPost = function (isValid, form) {
var date = new Date(),
days = ["January","February","March","April","Map","June","July","August","September","october","November","Deecmber"],
today = days[date.getMonth()] + " " + date.getDay(),
jsonindex = $("form[name='"+form+"']").find("input[name='JSONIndex']").val();
if($scope.newBlog && isValid) {
var blogIndexInJSON = getJSONIndex(jsonindex);
$scope.newBlog["date"] = today;
$scope.data.menuList[blogIndexInJSON].content.blogs.push($scope.newBlog);
$scope.closeOverlay('section5');
}
//$scope.$apply();
$scope.newBlog = {};
};
$scope.saveContactForm = function(isValid, form) {
var jsonindex = $("form[name='"+form+"']").find("input[name='JSONIndex']").val(),
blogIndexInJSON = getJSONIndex(jsonindex),
existingItems = $scope.data.menuList[blogIndexInJSON].content.formElements.fields.items;
$scope.closeOverlay('section4');
};
$scope.updateLocation = function(isValid, form) {
var geocoder = new google.maps.Geocoder(),
jsonindex = $("form[name='"+form+"']").find("input[name='JSONIndex']").val();
if($scope.locationMap && isValid) {
var blogIndexInJSON = getJSONIndex(jsonindex),
address = $scope.locationMap.address;
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var updatedPosition = results[0].geometry.location;
$scope.data.menuList[blogIndexInJSON].content.position.lat = updatedPosition.lat();
$scope.data.menuList[blogIndexInJSON].content.position.lng = updatedPosition.lng();
$scope.initializeMap(document.getElementById('googleMapContact'), updatedPosition);
} else {
alert('Address entered was not valid for the following reason: ' + status);
}
});
$scope.closeOverlay('section11');
}
// Clearing the temp Obj
$scope.locationMap = {};
};
$scope.sortingLog = [];
$scope.sortableOptions = {
// called after a node is dropped
stop: function(e, ui) {
// var logEntry = {
// ID: $scope.sortingLog.length + 1,
// Text: 'Moved element: ' + ui.item.scope().listItem
// };
// $scope.sortingLog.push(logEntry);
}
};
var getJSONIndex = function(sectionRef) {
var currentJSONList = $scope.data.menuList;
var row;
$.each(currentJSONList, function(key, value) {
if(value.menuId == sectionRef) {
row = key;
}
});
return row;
};
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "app/common/api/fileUpload.php";
fileUpload.uploadFileToUrl(file, uploadUrl);
// var file_data = $('#sortpicture').prop('files')[0];
// var form_data = new FormData();
// form_data.append('file', file_data);
// debugger;
// $.ajax({
// url: 'app/common/api/fileUpload.php', // point to server-side PHP script
// dataType: 'text', // what to expect back from the PHP script, if anything
// cache: false,
// contentType: false,
// processData: false,
// data: form_data,
// type: 'post',
// success: function(php_script_response){
// alert(php_script_response); // display response from the PHP script, if any
// }
// });
};
$scope.onFileSelect = function($files) {
$scope.message = "";
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'app/common/api/fileUpload.php',
method: 'POST',
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
}).error(function(data, status) {
$scope.message = data;
});
}
};
$scope.initializeMap = function(elem, myLatLng) {
// Create a map object and specify the DOM element for display.
setTimeout(function() {
// Specify features and elements to define styles.
var styleArray = [{
featureType: "all",
stylers: [
{ saturation: 20 }
]
},{
featureType: "road.arterial",
elementType: "geometry",
stylers: [
{ hue: "#0061FF" },
{ saturation: 70 }
]
},{
featureType: "poi.business",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}];
// Create a map object and specify the DOM element for display.
var map = new google.maps.Map(elem, {
center: myLatLng,
scrollwheel: false,
// Apply the map style array to the map.
styles: styleArray,
zoom: 18
});
// Create a marker and set its position.
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: 'Hello World!'
});
}, 100);
};
// JQUERY DOM EVENT BINDINGS
(function($) {
$("body").delegate( ".sliderToggleBtn", "click", function() {
if(parseInt($(".sideBar").css("width")) == 52) {
$(".sideBar").css("width", "220px");
$(".editArea").css("margin-left", "220px");
$(".topNav .logo").css("width", "220px");
$(".sideBar").removeClass("collapsed");
} else {
$(".sideBar").addClass("collapsed");
$(".sideBar").css("width", "52px");
$(".editArea").css("margin-left", "52px");
$(".topNav .logo").css("width", "52px");
}
});
$(".addBtnCombo").click(function() {
$(this).siblings(".balloonFlyOut").toggle();
});
$(".themeOptions .themes input[type='radio'").change(function() {
$scope.data.theme = $(this).val()
$scope.$apply();
});
$(".themeOptions .textColor input[type='radio'").change(function() {
$scope.data.textColor = $(this).val()
$scope.$apply();
});
})($);
})
;
|
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import logos from "./../../assets/Icons/dashboardIcon/logos.svg";
import classes from "./navbarHome.module.css";
import Cookies from "js-cookie";
import account from "../../assets/Icons/home/account.svg";
import { Button, Menu, MenuItem } from "@material-ui/core";
import ArrowDropDownIcon from "@material-ui/icons/ArrowDropDown";
import MobileNavbar from "./MobileNavbar";
const NavbarHome = () => {
const [anchorEl, setAnchorEl] = useState(null);
const [isMobileWidth, setIsMobileWidth] = useState(false);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
useEffect(() => {
window.addEventListener("resize", () => {
if (window.innerWidth <= 600) setIsMobileWidth(true);
else setIsMobileWidth(false);
});
if (window.innerWidth <= 600) setIsMobileWidth(true);
else setIsMobileWidth(false);
return () => {};
}, []);
return isMobileWidth ? (
<MobileNavbar mobile={isMobileWidth} />
) : (
<nav className={classes.navbarbox}>
<Menu
style={{ marginTop: "2.5rem" }}
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
"aria-labelledby": "basic-button",
}}
>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="/ProjectsList">
طراحی و گرافیک
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="">
تولید محتوا
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="">
ترجمه و تایپ
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="">
دیجیتال مارکتینگ سئو
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="">
عکس , انیمشین و ویدئو
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="">
طراحی سایت
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="">
برنامه نویسی,نرم افزار
</Link>
</MenuItem>
<MenuItem onClick={handleClose}>
<Link className={classes.linkMenu} to="">
سایر کسب و کارها
</Link>
</MenuItem>
</Menu>
<div className={classes.logoBox}>
<img src={logos} alt="parkJab-logo" />
</div>
<div className={classes.navItems}>
<Link to="/">صفحه اصلی</Link>
<Button
className={classes.dropdownList}
id="basic-button"
aria-controls="basic-menu"
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
endIcon={<ArrowDropDownIcon />}
onClick={handleClick}
>
پروژه ها
</Button>
<Link to="/Freelancers">فریلنسرها</Link>
<Link to="/PricingTableCommonPage">طرح های عضویت</Link>
<Link to="/HomeAboutUs">درباره ما</Link>
</div>
<div className={classes.navBtn}>
{Cookies.getJSON("login") ? (
<button className={`${classes.btnAccount} ${classes.btn}`}>
<img src={account} alt="account-svg" />
<Link to={{ pathname: "/dashboard", data: false }}>
حساب کاربری
</Link>
</button>
) : (
<>
<button className={`${classes.btnSignIn} ${classes.btn}`}>
<Link to={{ pathname: "/login", data: true }}> ورود</Link>
</button>
<button className={`${classes.btnSignUp} ${classes.btn}`}>
<Link to={{ pathname: "/signUp", data: false }}> ثبت نام</Link>
</button>
</>
)}
</div>
</nav>
);
};
export default NavbarHome;
|
import { VotingAll } from '../routes'
import ROUTE_PATHS from 'app/constants/routePaths'
export default [
{
name: 'VotingAll',
path: ROUTE_PATHS.VOTING_ALL,
exact: true,
component: VotingAll
}
]
|
/**
* autoSelect
* author : zhangdawei
* description : '下拉控件'
* data : 2014-9-10
* version : 1.0
*/
;(function ($) {
$.fn.autoSelect = function (setting) {
var _this = $(this);
var opts = {
defaultVal:setting.defaultVal,//true/false是否开启默认值,如果开启默认值,而且input的data-value有值默认为data-value ,如果没有默认值为列表中第一行数据,如果不开启及为false,这个时候默认值为空
disabled : setting.disabled,//是否禁用下拉列表
requestName : setting.requestName,//确定获取的数据中的value(提交的value)和对应的name(对应的显示数据) 如:requestName = [name,value]
readOnly:setting.readOnly,//是否开启写入模式 如果要设置写入则 readOnly : 'off',否则默认为不可写入的
zIndex : setting.zIndex || 9999,//默认下拉的层级index可以根据情况自行设定
dataUrl : setting.dataUrl || '',//设置获取数据的url 注意数据的模式
data : setting.data || ''//data和dataUrl一样,传入的时候根据自己的需求选择一种数据传入方式
};
if (!_this.parent(".selectIptWrap").length) {
var elsHtml = $("<div class='selectWrap'><div class='selectIptWrap'></div></div>").insertAfter(_this),
selectIptWrap = elsHtml.find(".selectIptWrap"),
selectIpt = _this.appendTo(selectIptWrap),
selectListId = 'selectLstWrap_' + selectIpt.attr('id'),
writeValue = $("<input class='writeValue' type='hidden'/>").appendTo(selectIptWrap),
sltBtn = $("<span class='selectBtn'><i class='trangle trangle-b'></i></span>").appendTo(elsHtml.find(".selectIptWrap")),
sltList = $("<div id="+selectListId+" class='selectList' style = 'z-index:" + opts.zIndex + "'></div>").appendTo($('body')),
wrapW = _this.width() - sltBtn.outerWidth(),
iptH = _this.outerHeight();
/*设置整体框架的尺寸、样式*/
selectIptWrap.width(_this.width(wrapW).outerWidth() + sltBtn.outerWidth());
elsHtml.width(selectIptWrap.outerWidth());
selectIptWrap.height(iptH);
sltList.css('top', selectIptWrap.outerHeight());
sltList.width(selectIptWrap.innerWidth()).hide();
writeValue.attr('name',_this.attr('name'));
_this.removeAttr('name');
getPosition();
//判断是select状态
} else {
selectIptWrap = _this.parent(".selectIptWrap"),
sltBtn = selectIptWrap.find(".selectBtn"),
elsHtml = selectIptWrap.parent(".selectWrap"),
selectListId = 'selectLstWrap_' + _this.attr('id'),
sltList = $('#'+selectListId).hide(),
writeValue = selectIptWrap.find(".writeValue");
}
//判断是select状态
opts.readOnly== 'off' ? _this.removeAttr('readOnly') : _this.attr('readOnly','readOnly');
if (opts.disabled) {
selectDisabled(selectIptWrap, sltBtn);
}else {
selectIptWrap.removeClass('disabled');
sltBtn.on('click',sltButton);
_this.on('focus',sltFocus);
}
getSelectData(opts.defaultVal,opts.dataUrl, opts.data, opts.requestName, elsHtml, writeValue, sltList);
$(document).click(function(event){
if(!clickPoint(elsHtml,event)){
sltList.hide();
}
});
//todo:位置存在1px问题
window.onload = function () {
getPosition();
};
$(window).on('resize',getPosition);
function getPosition() {
var iptLeft = elsHtml.offset().left,iptTop = elsHtml.offset().top;
sltList.css({'left':iptLeft,'top':iptTop+selectIptWrap.outerHeight()});
}
function sltButton() {
if (sltList.is(":visible")) {
sltList.hide();
sltList.find(".selectItem").show();
} else {
sltList.show();
}
}
function sltFocus() {
sltList.show();
sltList.find(".selectItem").show();
if(!$(this).attr('readOnly')) {
$(this).keyup(function () {
var keyValue = $(this).val();
var pattern = new RegExp(keyValue, 'i');
sltList.hide();
sltList.find(".selectItem").each(function (index) {
$(this).removeClass("current");
if (pattern.test($(this).text())) {
$(this).show();
sltList.show();
} else {
$(this).hide();
}
});
})
}
}
//获取event target的包含关系
function clickPoint(parentObj, e) {
return $(e.target).closest(parentObj).length ? true : false;
}
//开启不可用状态下的操作
function selectDisabled(selectIptWrap, sltBtn) {
selectIptWrap.addClass("disabled");
_this.attr('readonly','readonly');
sltBtn.off('click');
_this.off('focus');
_this.off('keyup');
}
function getSelectData(defaultVal,dataUrl, data, requestName, elsHtml, writeValue, sltList) {
if (requestName){
var name = requestName[0],
value = requestName[1];
}
if (data) {
sltList.html('');
for (var i = 0; i < data.length; i++) {
sltList.append('<div class="selectItem" data-value="' + data[i][value] + '">' + data[i]['name'] + '</div>');
}
dataHandle(writeValue, sltList);
defaultValue(defaultVal,data, name, value, writeValue,sltList)
}
if (dataUrl) {
sltList.html('');
$.ajax({
url: dataUrl,
type: 'get',
success: function (data) {
//return data;
for (var i = 0; i < data.length; i++) {
sltList.append('<div class="selectItem" data-value="' + data[i][value] + '">' + data[i][name] + '</div>');
}
dataHandle(writeValue, sltList);
defaultValue(defaultVal,data, name, value, writeValue,sltList)
}
})
}
}
function defaultValue(defaultVal,data, name, value, writeValue,sltList) {
/* if (!_this.attr('data-value')) {
_this.val(data[0][name]);
writeValue.val(data[0][value]);
sltList.find(".selectItem").eq(0).trigger('click');
} else {
writeValue.val(selectIpt.attr('data-value'));
}
*/
var dataValue = _this.attr('data-value'),
selectItem = sltList.find(".selectItem");
if(defaultVal) {
if(dataValue){
for(var i = 0 ; i < data.length ; i++) {
if(data[i][value] == dataValue) {
selectItem.eq(i).trigger('click');
}
}
}else {
_this.val(data[0][name]);
writeValue.val(data[0][value]);
selectItem.eq(0).trigger('click');
}
}
}
//select下拉列表的时间绑定
function dataHandle(writeValue, sltList) {
sltList.on('click','.selectItem', function () {
var dataValue = $(this).attr('data-value');
$(this).addClass("current").siblings().removeClass("current");
writeValue.val($(this).attr('data-value'));
_this.val($(this).text());
_this.attr('data-value',dataValue);
sltList.hide();
});
}
}
;$(function(){
if( $("input[data-select]").length> 0) {
$("input[data-select]").each(function(){
var dataSelect = $(this).data('select');
dataSelect = strToJson(dataSelect);
$(this).autoSelect(dataSelect);
})
}
function strToJson(str){
var json = (new Function("return " + str))();
return json;
}
});
// $("input[data-select]").autoSelect()
})(jQuery);
|
$(document).ready(function(){
$("#addstan").click(function(){
$(".notcorrect").empty();
$("#dialog_stanyt").dialog('option', 'position', {
my: "left+20 top",
at: "left bottom",
of: "#addstan"
});
$("#dialog_stanyt").dialog("open");
});
$("#dialog_stanyt").dialog({
autoOpen: false,
heigh: 235,
width: 320,
modal: true,
buttons:{
"save":{
text: "Зберегти",
id: "save",
click: function(){
var stan = $("#stan").val().trim();
var characterReg = /^\s*[а-яА-ЯїЇіІєЄ"'a-zA-Z0-9,-\s]+\s*$/;
var i = 0;
var txt;
var values = $("#idselstan>option").map(function() {
txt = $(this).text();
if(txt.trim().toLowerCase() == stan.trim().toLowerCase()){
i++;
}
});
if(i>0) {
$(".notcorrect").empty();
$(".notcorrect").append("<p id=\"notcor\">Така станиця є в списку!</p>");
}else{
if(stan == "" || !characterReg.test(stan)){
$(".notcorrect").empty();
$(".notcorrect").append("<p id=\"notcor\">Поля повинні бути обов'язково заповнені коректно!</p>");
} else {
$("#idselstan").empty();
$.ajax({
type: "get",
url: "addnewstan.html",
data: "namestan="+stan,
cach: false,
success: function(xml){
$(xml).find("stanytsya").each(function(){
var id = $(this).find("id").text();
var namestan = $(this).find("namestan").text();
stanytsya = "<option value='"+id+"'>" + namestan + "</option>";
$("#idselstan").append(stanytsya);
})
}
});
var temp=0;
var currentValue, maxValue;
$('#idselstan option').each(function(){
currentValue = $("#idselstan").val();
// alert('currentValue = '+currentValue);
maxValue = Math.max(temp, currentValue);
temp=currentValue;
});
$("#idselstan option[value=" + maxValue + "]").attr('selected', 'true');
$(this).dialog("close");
}
}
}
},
"cancel":{
text: "Відмінити",
id: "cancel",
click: function(){
$(this).dialog("close");
}
}
}
});
});
|
import api from 'user/api';
export const LOGIN_REQUEST = 'LOGIN_REQUEST';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILED = 'LOGIN_FAILED';
export const loginRequest = () => ({
type: LOGIN_REQUEST
});
export const loginSuccess = (data) => ({
type: LOGIN_SUCCESS,
payload: {
id: data.id,
email: data.email
}
});
export const loginFailed = () => ({
type: LOGIN_FAILED
});
const getError = (error) => {
if (typeof error === 'string') {
return {
message: error
};
}
if (error.response) {
return error.response.data.error;
}
return {
message: 'Failed to login'
};
};
export const tryLogin = (email, password) => {
return dispatch => {
dispatch(loginRequest());
return api.login(email, password)
.then(data => dispatch(loginSuccess(data)))
.catch(error => {
dispatch(loginFailed(error));
return Promise.reject(getError(error));
});
};
};
export const tryRegister = (email, password) => {
return dispatch => {
dispatch(loginRequest());
return api.register(email, password)
.then(data => dispatch(loginSuccess(data)))
.catch(error => {
dispatch(loginFailed(error));
return Promise.reject(getError(error));
});
};
};
export const updateSettings = (user) => {
return dispatch => {
dispatch(loginRequest());
return api.updateSettings(user)
.then(data => dispatch(loginSuccess(data)))
.catch(error => {
dispatch(loginFailed(error));
return Promise.reject(getError(error));
});
};
};
|
/**
* @file 首页
* @author dongkunshan(windwithfo@yeah.net)
*/
import React from 'react';
import { observer } from 'mobx-react';
@observer
class DetailPage2 extends React.Component {
render() {
return (
<div>
<input maxLength='25' value={this.props.store.page2Text} onChange={this.change}></input><br/>
<button onClick={this.change}>click me to change text</button><br/>
this is {this.props.store.page2Text}
</div>
);
}
change = (event) => {
let val = event.target.value || 'change';
this.props.store.textChange(val);
}
}
export default DetailPage2;
|
var classes____4__8js_8js =
[
[ "classes__4_8js", "classes____4__8js_8js.html#a78edc33bbfa5400644d13f4de972c3b5", null ]
];
|
var routes = {
}
export default {
route: function (router) {
router.map(routes);
},
routes : function () {
return routes;
}
}
|
const fp = require('lodash/fp')
const { Maybe, Container } = require('./support')
// 练习1
{
let maybe = Maybe.of([5, 6, 1])
let ex1 = () => {
return maybe.map(fp.map(v => fp.add(v, v)))._value
}
console.log('练习1', ex1()); // 练习1 [ 10, 12, 2 ]
}
// 练习2
{
let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do'])
let ex2 = () => {
return xs.map(fp.first)._value
}
console.log('练习2', ex2()); // do
}
// 练习3
{
let safeProp = fp.curry(function (x, o) {
return Maybe.of(o[x])
})
let user = { id: 2, name: 'Albert' }
let ex3 = () => {
return safeProp('name', user).map(fp.first)._value
}
console.log('练习3', ex3()); // 练习3 A
}
// 练习4
{
// let ex4 = function (n) {
// if(n){
// return parseInt(n)
// }
// }
let ex4 = function (n) {
return Maybe.of(n).map(parseInt)._value
}
console.log('练习4', ex4(10.22)); // 练习4 10
console.log('练习4', ex4(null)); // 练习4 null
}
|
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return this.store.findRecord('candidate', params.candidate_id, { include: 'mean-samples', reload: true });
}
});
|
import { ceil, sum, random, range } from './util'
// divide()
//
// divide player_total and bonus_total into 3 parts
// by player_ratio, @default[1,5,10] and bonus_ratio @default[5,2,1]
//
// e.g.:
//
// player_total: 7
// bonus_total: --
// player_ratio: 2:2:3
// bonus_ratio: 3:2:1
//
// |. .
// | . .
// | . . .
// +--------------
//
function divide(player_total, bonus_total, player_ratio, bonus_ratio){
player_ratio = player_ratio && typeof player_ratio == 'object' ? player_ratio : [1, 5, 10]
bonus_ratio = bonus_ratio && typeof bonus_ratio == 'object' ? bonus_ratio : [5, 2, 1]
var sum_player_ratio = sum(player_ratio)
// console.log('SUM player_ratio %d', sum_player_ratio)
var p0 = ceil(player_total * player_ratio[0] / sum_player_ratio)
var p1 = ceil(player_total * player_ratio[1] / sum_player_ratio)
var p2 = player_total - p0 - p1
while (p2 < 0 ) {
p1--
p2++
}
var bonus_ratio_product = [
p0 * bonus_ratio[0],
p1 * bonus_ratio[1],
p2 * bonus_ratio[2]
]
var sum_bonus_ratio = sum(bonus_ratio_product)
var b0 = bonus_total * bonus_ratio_product[0] / sum_bonus_ratio
var b1 = bonus_total * bonus_ratio_product[1] / sum_bonus_ratio
var b2 = bonus_total * bonus_ratio_product[2] / sum_bonus_ratio
return {
0: {
player: p0,
bonus: b0/p0,
},
1: {
player: p1,
bonus: b1/p1,
},
2: {
player: p2,
bonus: b2/p2,
},
}
}
// incline()
//
// make a horizon line into a oblique line
//
// making the bonus greater for player came first,
// and smaller for later ones
//
// e.g.:
//
// before
//
// |
// |
// |. . . . .
// |
// |
// +----------
//
// after
//
// |.
// | .
// | .
// | .
// | .
// +----------
//
function incline(group, delta_y){
var player_arr = range(0, group.player)
var dy = (delta_y[1] - delta_y[0]) / group.player
var dx = 1
player_arr = player_arr.map((i,idx)=>{
return delta_y[1] - (group.player - idx) * dy / dx
})
return player_arr
}
// randomize()
//
// randomize bonus in array, and make final match the bonus total
// e.g.:
//
// before
//
// |.
// | .
// | .
// | .
// | .
// +----------
//
// after
// |.
// | .
// |
// | . .
// |
// | .
// +----------
//
//
function randomize(bonus_arr, bonus_total){
var avg_t = (bonus_total - sum(bonus_arr)) / bonus_arr.length
// console.log('before fix %d', avg_t)
bonus_arr = bonus_arr.map(i=>parseInt(i+avg_t))
// console.log("before %d", sum(bonus_arr) )
var norm_len = ceil(bonus_total / bonus_arr.length / 20)
// console.log("norm_len %d", norm_len)
// loop each
var r_t = sum(bonus_arr) - bonus_total
var r = random(-norm_len, norm_len)
bonus_arr = bonus_arr.map(i=>{
var k = i + r
r_t += r
if (r_t > norm_len) {
r = random(-norm_len, 0)
} else if (r_t < -norm_len) {
r = random(0, norm_len)
} else {
r = random(-norm_len, norm_len)
}
if (k <= 0) {
k = random(1, norm_len)
}
return k
})
// console.log("after %d", sum(bonus_arr) )
// loop exceeds and cut down /add up each bonus by 1
var exceeds = bonus_total - sum(bonus_arr)
// console.log("after exceeds %d", exceeds )
var i = 0
while (exceeds) {
if (exceeds > 0) {
bonus_arr[i]++
exceeds--
} else {
if (bonus_arr[i] > 1) {
bonus_arr[i]--
exceeds++
}
}
i++
if (i >= bonus_arr.length) {
i=0 // restart when reach arr end
}
// console.log('exceeds', exceeds)
}
// console.log("justify %d", sum(bonus_arr) )
return bonus_arr
}
// get the delta ys (y0 and y1 of bonus) for each player group
function get_delta_ys(groups){
var avg_b = [groups[0].bonus, groups[1].bonus, groups[2].bonus]
var joints = [(avg_b[0] + avg_b[1])/2, (avg_b[1] + avg_b[2])/2]
var delta_ys = [
[avg_b[0] + avg_b[0] - joints[0], joints[0]],
[joints[0], joints[1]],
[joints[1], 1],
]
return delta_ys
}
module.exports = function (player_total, bonus_total, player_ratio, bonus_ratio){
const groups = divide(player_total, bonus_total, player_ratio, bonus_ratio)
const delta_ys = get_delta_ys(groups)
const plain = []
.concat(incline(groups[0], delta_ys[0]))
.concat(incline(groups[1], delta_ys[1]))
.concat(incline(groups[2], delta_ys[2]))
const randomized = randomize(plain, bonus_total)
return {randomized, plain}
}
|
import React from "react";
function Jumbotron() {
return (
<div className="jumbotron jumbotron-fluid mb-0 pb-4 pt-3" style={{backgroundImage: "url(images/flowers-background.jpg)", backgroundSize: "cover", backgroundPosition: "bottom"}}>
<div className="container text-center">
<h1 className="display-4 font-weight-bold text-white" style={{textShadow: "3px 3px 2px #3e8503, 3px -3px 2px #3e8503, -3px 3px 2px #3e8503, -3px -3px 2px #3e8503"}}>Bouquet - Memory Game</h1>
<h2 className="font-weight-bold text-white" style={{textShadow: "3px 3px 2px #3e8503, 3px -3px 2px #3e8503, -3px 3px 2px #3e8503, -3px -3px 2px #3e8503"}}>Pick flowers and make a bouquet</h2>
<h2 className="font-weight-bold text-white" style={{textShadow: "3px 3px 2px #3e8503, 3px -3px 2px #3e8503, -3px 3px 2px #3e8503, -3px -3px 2px #3e8503"}}>We like diversity so don't click on a particular flower more than once!</h2>
</div>
</div>
);
}
export default Jumbotron;
|
// Promise 是一个构造函数
// 创建Promise容器
// 1. 给别人一个承诺,
// 2. Promise容器,一旦创建就自动执行
// 3. Promise本身不是异步,但是内部往往都封装了一个异步任务
// 4. 当异步成功了 resolve(data),当异步失败了 reject(err)
// 5. 真正有用的是我们 resolve 一个Promise对象,然后采用.then的方式,实现链式调用
// 6. 当return一个Promise对象的时候,后续then方法的第一个函数将作为p2的resolve方法,第二个函数作为p2的 reject方法
const fs = require('fs')
const p1 = new Promise((resolve, reject) => {
fs.readFile('../a.txt', 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
const p2 = new Promise((resolve, reject) => {
fs.readFile('../b.txt', 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
const p3 = new Promise((resolve, reject) => {
fs.readFile('../c.txt', 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
p1.then((data) => {
console.log(data)
return p2
})
.then((data) => {
console.log(data)
return p3
})
.then((data) => {
console.log(data)
})
.catch(err => console.log(err))
|
import React, { Component } from 'react';
import { Container, Col, Row } from 'reactstrap';
import CarouselC from "../Components/Carousel";
import { Link } from 'react-router-dom';
import { css } from "@emotion/core";
import ScaleLoader from "react-spinners/ScaleLoader";
import dayjs from 'dayjs';
var relativeTime = require('dayjs/plugin/relativeTime');
class Home extends Component{
constructor(props){
super(props);
this.state = {
keyword: "",
tags: []
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
keyword: event.target.value
});
}
render(){
let count=0;
const displayTopBlogs = this.props.errMess === null? (
this.props.blogs.map((blog) => {
dayjs.extend(relativeTime);
if(count<3){
count=count+1;
return(
<Link to ={`/blogs/${blog.blogId}`} style={{ textDecoration: 'none', color: "black" }} key={blog.blogId} >
<Container className="hover-decoration">
<Row className="align-items-center">
<Col xs="4" md="4"><img className="user-image" alt="user profile" src={blog.userImage}/></Col>
<Col className="userimage-padding">
<p>{blog.title}</p>
<p><i> - {blog.userHandle}, {dayjs(blog.createdAt).fromNow()}</i></p>
</Col>
</Row>
<hr/>
</Container>
</Link>
);
}
else{
return(<div></div>);
}
}
)) :(<div> An error occured please try again </div>)
function sortByFrequency(array) {
var frequency = {};
var sortAble = [];
var newArr = [];
array.forEach(function(value) {
if ( value in frequency )
frequency[value] = frequency[value] + 1;
else
frequency[value] = 1;
});
for(var key in frequency){
sortAble.push([key, frequency[key]])
}
sortAble.sort(function(a, b){
return b[1] - a[1]
})
sortAble.forEach(function(obj){
for(var i=0; i < obj[1]; i++){
newArr.push(obj[0]);
}
})
return newArr;
}
function uniq(a) {
return a.filter(function(item, pos, ary) {
return !pos || item !== ary[pos - 1];
});
}
var newArr = [];
if(this.props.errMess=== null && !this.props.isLoading){
let tagList = [];
tagList = this.props.blogs.map((blog) => {
let tagt=[];
tagt=blog.tags.split(",");
return tagt;
});
for(var i = 0; i < tagList.length; i++)
{
newArr = newArr.concat(tagList[i]);
}
newArr = sortByFrequency(newArr);
newArr = uniq(newArr);
}
let tagCnt=0;
const displayTags = this.props.errMess === null? (
newArr.map((elem) => {
if(tagCnt<3){
tagCnt++;
return(
<Col xs="12" md="12" className="hover-decoration">#{elem}</Col>
);
}
else return(null);
})
) :(null);
const displaySearchedBlogs = this.props.errMess === null? (
this.props.blogs.map((blog) => {
dayjs.extend(relativeTime);
if(this.state.keyword!=="" &&
(blog.title.search(this.state.keyword)!== -1 ||
blog.userHandle.search(this.state.keyword)!== -1 ||
blog.tags.search(this.state.keyword)!== -1 )){
return(
<Link to ={`/blogs/${blog.blogId}`} style={{ textDecoration: 'none', color: "black" }} key={blog.blogId} >
<Container className="hover-decoration">
<Row className="align-items-center">
<Col xs="4" md="4"><img className="user-image" alt="user profile" src={blog.userImage}/></Col>
<Col className="userimage-padding">
<p>{blog.title}</p>
<p><i> - {blog.userHandle}, {dayjs(blog.createdAt).fromNow()}</i></p>
</Col>
</Row>
<hr/>
</Container>
</Link>
);
}
else{
return (<div></div>);
}
}
)) :(<div>An error occured please try again</div>)
const override = css`
margin-left: 40%;
`;
return(
<Container>
<Row>
<Col><CarouselC/></Col>
</Row>
<Row >
<Col className="blog-card" xs="11" sm="11" md="7">
<Row>
<Col xs="2" md="1">
<span className="fa fa-search fa-lg ml-4 mt-3"></span>
</Col>
<Col className="no-border">
<input type="text" name="keyword" value={this.state.keyword} onChange={this.handleChange}
className="form-control" placeholder="Search for blogs based on title, author or keyword.." />
</Col>
</Row>
<hr/>
<ScaleLoader
css={override}
color={"#5FB394"}
loading={this.props.isLoading}
/>
{displaySearchedBlogs}
</Col>
<Col>
<Row xs="11">
<Col className="blog-card">
<h3>Trending tags</h3>
<hr/>
<ScaleLoader
css={override}
color={"#5FB394"}
loading={this.props.isLoading}
/>
{displayTags}
</Col>
</Row>
<Row xs="11">
<Col className="blog-card" >
<h3>Top blogs of the week!</h3>
<hr/>
<ScaleLoader
css={override}
color={"#5FB394"}
loading={this.props.isLoading}
/>
{displayTopBlogs}
</Col>
</Row>
</Col>
</Row>
</Container>
);
}
}
export default Home;
|
/* ----- Vuex 模块 ---- */
/*
Vuex 是一个专门为 Vue.js 应用设计的 状态管理模型 + 库。
Vuex操作简述:
页面动作触发actions,提交需要做什么操作(commit)给mutations,然后由mutations去让数据(state)发生
变化(mutate),继而,页面上view层就会相应更新。
流程:
页面操作 => actions ( commit )=> mutations ( mutate )=> state => 更新view层
*/
/* ----- 加载模块 ---- */
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex); //安装store插件
//引入动作行为
import actions from './actions'
// 引入变化(突变)模块
import mutations from './mutations/mutations'
import toggleSidebar from './mutations/toggleSidebar'
import visitedViews from './mutations/visitedViews'
import getters from './getters'
import Cookies from 'js-cookie';
//项目中只需维护actions,mutations,getters 即可
//定义值
const state = {
count: 20,
token: null,
adminleftnavnum: '1',
user: {
userinfo: {
userInfoCarrier: '',
tokenCarrier: '',
}
},
data: {
current: '',
},
//
// sidebar: {
// opened: !+Cookies.get('sidebarStatus'),
// },
visitedViews: [],
//这里只是分配路径
mock: {
//mock - test 测试路径
base: "http://BroccoliSpring/gcx/api",
branch: {
test: {
mockDef: '/test/mockDef',
mockForm: '/test/mockForm'
},
// user: {
// userinfo: '/user/userinfo'
// },
// front: {
// login: '/front/login',
// reg: '/front/reg',
// regCheck: '/front/regCheck'
// },
bench: {
roleMenu: '/role/menu'
}
}
}
};
/* ----- 导出Store 对象 ---- */
export default new Vuex.Store({
state,
actions,
mutations,
toggleSidebar,
visitedViews,
getters,
strict: true //严格的state模式,乱改会有警告
})
|
// This plugin combines a set of assets into a single asset
// This should be only used with text assets,
// otherwise the result is unpredictable.
export default class CombineAssetsPlugin {
constructor ({ input, output }) {
this.input = input
this.output = output
}
apply (compiler) {
compiler.plugin('after-compile', (compilation, callback) => {
let newSource = ''
this.input.forEach((name) => {
const asset = compilation.assets[name]
if (!asset) return
newSource += `${asset.source()}\n`
// We keep existing assets since that helps when analyzing the bundle
})
compilation.assets[this.output] = {
source: () => newSource,
size: () => newSource.length
}
callback()
})
}
}
|
//import cleanDeep from 'clean-deep'; // Cannot read property "__core-js_shared__" from undefined
//import deepEqual from 'fast-deep-equal';
//──────────────────────────────────────────────────────────────────────────────
// Enonic XP libs (in jar file, resolved runtime)
//──────────────────────────────────────────────────────────────────────────────
import {toStr} from '/lib/enonic/util';
import {
createUser,
getPrincipal,
//getProfile,
modifyProfile,
modifyUser
} from '/lib/xp/auth';
import {get as getContext} from '/lib/xp/context';
import {sanitize} from '/lib/xp/common';
import {connect} from '/lib/xp/node';
import {
//list,
progress
} from '/lib/xp/task';
//──────────────────────────────────────────────────────────────────────────────
// App libs (transpiled to /build and resolved runtime)
//──────────────────────────────────────────────────────────────────────────────
import {get as paginate} from '../../services/paginate/paginate.es';
import {get as graphRequest} from '../../services/graph/graph.es';
import {currentTimeMillis} from '../../lib/microsoftGraph/util/currentTimeMillis.es';
import {deepen} from '../../lib/microsoftGraph/util/deepen.es';
import getIsMaster from '../../lib/microsoftGraph/cluster/isMaster.es';
import {isString} from '../../lib/microsoftGraph/util/isString.es';
import {runAsSu} from '../../lib/microsoftGraph/context/runAsSu';
import {connectRepo} from '../../lib/microsoftGraph/repo/connectRepo';
//import {sortObject} from '../../lib/microsoftGraph/util/sortObject.es';
//──────────────────────────────────────────────────────────────────────────────
// Private constants
//──────────────────────────────────────────────────────────────────────────────
//const TASK_NAME = `${app.name}:sync`;
//const STATE_FINISHED = 'FINISHED';
const connection = runAsSu(() => connectRepo({repoId: 'system-repo'}));
const PROFILE_CONFIG = {
decideByType: true,
enabled: true,
nGram: true,
fulltext: true,
includeInAllText: true,
indexValueProcessors: []
};
//──────────────────────────────────────────────────────────────────────────────
// Private function
//──────────────────────────────────────────────────────────────────────────────
/*function isAlreadyRunning() {
const runningTasks = list({
name: TASK_NAME,
state: 'RUNNING'
});
log.info(toStr({runningTasks}));
return runningTasks.some((runningTask) => {
const info = runningTask.progress.info ? JSON.parse(runningTask.progress.info) : {};
log.info(toStr({info}));
const {state} = info;
if (state && state !== STATE_FINISHED) {
log.warning(`Task already running! ${toStr({runningTask})}`);
return true;
}
return false;
});
}*/
function pushValues(obj, arr) {
Object.keys(obj).forEach((k) => {
const v = obj[k];
if (isString(v)) {
arr.push(v);
} else {
pushValues(obj[k], arr); // recurse
}
});
} // function pushValues
function buildprofile({mapping, user}) {
const profile = {};
Object.keys(mapping).forEach((k) => {
const field = mapping[k];
if (isString(field)) {
profile[k] = user[field];
} else { // Scope
profile[k] = buildprofile({mapping: mapping[k], user}); // recurse
}
}); // forEach
return profile;
} // function buildprofile
//──────────────────────────────────────────────────────────────────────────────
// Public function
//──────────────────────────────────────────────────────────────────────────────
export function run(params) {
if (!getIsMaster) {
progress({
info: JSON.stringify({
error: 'Task only allowed to run on the master node'
})
});
return;
}
runAsSu(() => {
//if (isAlreadyRunning()) { return; }
//log.info(toStr({params}));
const {userStore} = params;
if (!userStore) {
progress({
info: JSON.stringify({
error: 'Parameter userStore is required'
})
});
return;
}
const startTime = currentTimeMillis();
connection.refresh();
const afterFirstRefreshMs = currentTimeMillis();
log.info(toStr({
startTime,
afterFirstRefreshMs,
durationRefreshMs: afterFirstRefreshMs - startTime
}));
const config = deepen(app.config)[userStore]; //log.info(toStr({config: sortObject(config)}));
const select = ['userPrincipalName']; // userPrincipalName is used in resource requests
if (config.mapping) { select.concat(Object.keys(config.mapping).map(k => config.mapping[k])); }
if (config.profile && config.profile.mapping) {
pushValues(config.profile.mapping, select);
}
const requestParams = {
params: {
resource: 'users',
select: select.filter((v, i, a) => a.indexOf(v) === i).join(','),
userStore
}
}; //log.info(toStr({requestParams}));
progress({
info: JSON.stringify({
state: 'Getting list of users from MS Graph API'
})
});
const usersRes = paginate(requestParams);
//log.info(toStr({usersRes}));
let userArr = [];
usersRes.body.graphResponses.forEach((r) => {
userArr = userArr.concat(r.body.value);
});
//log.info(toStr({userArr}));
let current = 0;
const total = userArr.length;
const users = {};
// TODO Get list if users from Enonic and delete the ones that no longer exist in Graph
userArr.forEach((user) => {
current += 1;
const name = sanitize(user[config.mapping.name]);
progress({
current,
info: JSON.stringify({
name,
state: 'Getting user data from MS Graph API',
time: `${currentTimeMillis() - startTime}ms`,
userStore
}),
total
});
const key = `user:${userStore}:${name}`;
try {
const displayName = user[config.mapping.displayName];
const email = user[config.mapping.email];
// Just returns null even though the user doesn't exist.
const principal = getPrincipal(key); //log.debug(toStr({principal}));
if (principal) {
if (principal.displayName !== displayName || principal.email !== email) {
const modifyUserRes = modifyUser({
key,
editor: (u) => {
u.displayName = displayName; // eslint-disable-line no-param-reassign
u.email = email; // eslint-disable-line no-param-reassign
return u;
}
});
log.info(toStr({modifyUserRes}));
users[user.userPrincipalName] = modifyUserRes;
} else {
users[user.userPrincipalName] = principal;
}
} else {
const createUserParams = {
displayName,
email,
name,
userStore
};
//log.info(toStr({createUserParams}));
const createRes = createUser(createUserParams);
log.info(toStr({createRes}));
users[user.userPrincipalName] = createRes;
//const beforeRefreshMs = currentTimeMillis();
connection.refresh();
/*const afterRefreshMs = currentTimeMillis();
log.info(toStr({
beforeRefreshMs,
afterRefreshMs,
durationRefreshMs: afterRefreshMs - beforeRefreshMs
}));*/
} // if !principal
connection.modify({
key,
editor: (node) => {
let hasProfileConfig = false;
node._indexConfig.configs = node._indexConfig.configs.map((c) => { // eslint-disable-line no-param-reassign
if (c.path === 'profile') {
hasProfileConfig = true;
c.config = PROFILE_CONFIG; // eslint-disable-line no-param-reassign
}
return c;
}); // map
if (!hasProfileConfig) {
node._indexConfig.configs.push({
path: 'profile',
config: PROFILE_CONFIG
});
}
return node;
} // editor
});
const newProfile = buildprofile({mapping: config.profile.mapping, user}); //log.debug(toStr({newProfile}));
if (config.resources) {
const resources = config.resources.replace(/ +/g, '').split(','); //log.debug(toStr({resources}));
const graphRequestParams = {
params: {
select: resources.join(','),
resource: `/users/${user.userPrincipalName}`,
userStore
}
}; //log.debug(toStr({graphRequestParams}));
//log.info('service/sync.get() before graphRequest');
const graphResponse = graphRequest(graphRequestParams);
//log.info('service/sync.get() after graphRequest');
if (graphResponse.status === 200 && graphResponse.body) {
resources.forEach((resource) => {
if (graphResponse.body[resource]) {
newProfile.graph[resource] = graphResponse.body[resource];
}
}); // forEach resource
}
} // if config.resources
/*const currentProfile = getProfile({key}); // log.debug(toStr({currentProfile}));
const cleanedNewProfile = cleanDeep(newProfile);
if (deepEqual(currentProfile, cleanedNewProfile)) {
log.info(toStr({equal: {currentProfile, cleanedNewProfile}}));
users[user.userPrincipalName].profile = currentProfile;
} else {
log.info(toStr({notEqual: {currentProfile, cleanedNewProfile}}));*/
const modifyProfileRes = modifyProfile({
key,
editor: () => newProfile /*(currentProfile) => { // eslint-disable-line no-unused-vars
// NOTE deepmerge will keep duplicating array contents!
const updatedProfile = merge(currentProfile, newProfile); //log.info(toStr({updatedProfile}));
return newProfile;
}*/
});
log.info(toStr({modifyProfileRes}));
users[user.userPrincipalName].profile = modifyProfileRes; //getProfile({key});
//}
} catch (e) {
log.error(`Something went wrong while processing user:${key} e:${e}`);
}
}); // forEach user
const beforeLastRefreshMs = currentTimeMillis();
connection.refresh();
const afterLastRefreshMs = currentTimeMillis();
log.info(toStr({
beforeLastRefreshMs,
afterLastRefreshMs,
durationRefreshMs: afterLastRefreshMs - beforeLastRefreshMs
}));
progress({
current,
info: JSON.stringify({
//state: STATE_FINISHED,
time: `${currentTimeMillis() - startTime}ms`,
userStore
}),
total
});
}); // runAsSu
}
|
/*
* Copyright (C) 2009-2014 SAP SE or an SAP affiliate company. All rights reserved
*/
jQuery.sap.declare("sap.ca.ui.utils.resourcebundle");
jQuery.sap.require("sap.ui.model.resource.ResourceModel");
//dialog interface for the applications
sap.ca.ui.utils.resourcebundle = (function() {
var oI18nModel = new sap.ui.model.resource.ResourceModel({
bundleUrl: jQuery.sap.getModulePath("sap.ca.ui.i18n.i18n", ".properties"),
});
sap.ui.getCore().setModel(oI18nModel, "sap.ca.ui.i18n");
return oI18nModel.getResourceBundle();
}());
|
/**
* PubSub
* version: 0.0.4
* author: Wojciech Ludwin 2016.
* contact: ludekarts@gmail.com, wojciech.ludwin@katalysteducation.org
* description: Basic implementation of Publish/Subscribe Pattern
**/
const PubSub = (_logger) => {
const logger = _logger && typeof _logger === 'function' ? _logger : undefined;
const subscriptions = [];
const API = {
subscribe (topic, observer) {
subscriptions[topic] || (subscriptions[topic] = [])
subscriptions[topic].push(observer)
return API;
},
unsubscribe (topic, observer) {
if (!subscriptions[topic]) return API;
let index = subscriptions[topic].indexOf(observer)
if (~index) subscriptions[topic].splice(index, 1)
return API;
},
publish (topic, message) {
if (logger) logger(topic, message);
if (!subscriptions[topic]) return API;
for (let i = subscriptions[topic].length - 1; i >= 0; i--){
subscriptions[topic][i](message);
}
return API;
},
trace () {
console.log(subscriptions);
return API;
}
}
// Public API.
return API;
};
export default PubSub;
|
import React from 'react';
import BaseContainer from '../BaseContainer';
import ChangePinForm from '../../components/ChangePinForm/ChangePinForm';
import { connect } from 'react-redux';
import { changePin } from '../../actions/crediCards';
class CreditCardEditPinContainer extends BaseContainer {
onSendChangePin = body => this.props
.changePin({
newPin: body.newPin,
id: this.props.match.params.id
})
.then(() => this.setState({ successMessage: "Pin changed" }))
.catch(er => {
if (er && er.status && er.status === 400)
this.setState({ errorMessage: er.data });
});
render() {
return (
<ChangePinForm onSendChangePin={this.onSendChangePin} />
);
}
}
export default connect(
state => ({
}),
dispatch => ({
changePin: body => dispatch(changePin(body))
})
)(CreditCardEditPinContainer);
|
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Build from '@/components/Build'
import Contact from '@/components/Contact'
import History from '@/components/About/History'
import Rules from '@/components/About/Rules'
import Scoring from '@/components/About/Scoring'
import Sponsors from '@/components/About/Sponsors'
import Teams from '@/components/About/Teams'
import Combine from '@/components/NewsEvents/Combine'
import Gallery from '@/components/NewsEvents/Gallery'
import Playoffs from '@/components/NewsEvents/Playoffs'
import Records from '@/components/NewsEvents/Records'
import Videos from '@/components/NewsEvents/Videos'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/buildteam',
name: 'Build',
component: Build
},
{
path: '/contact',
name: 'Contact',
component: Contact
},
{
path: '/history',
name: 'History',
component: History
},
{
path: '/rules',
name: 'Rules',
component: Rules
},
{
path: '/scoring',
name: 'Scoring',
component: Scoring
},
{
path: '/sponsors',
name: 'Sponsors',
component: Sponsors
},
{
path: '/teams',
name: 'Teams',
component: Teams
},
{
path: '/combine',
name: 'Combine',
component: Combine
},
{
path: '/gallery',
name: 'Gallery',
component: Gallery
},
{
path: '/playoffs',
name: 'Playoffs',
component: Playoffs
},
{
path: '/records',
name: 'Records',
component: Records
},
{
path: '/videos',
name: 'Videos',
component: Videos
}
],
mode: 'history'
})
|
import React, { useState, useEffect } from 'react';
import { Text, View, TextInput, StyleSheet, Button, Alert } from 'react-native';
import ContactForm from '../components/ContactForm';
import { Avatar } from 'react-native-elements';
//redux
import { editContact } from '../actions/index';
import { connect } from 'react-redux';
const EditContact = ({ navigation, editContact, route, getData }) => {
const { id } = route.params;
const Detail = getData.find(
(Detail) => Detail.id === id
);
const onPressHandler = (firstName, lastName, age, id) => {
console.log(id, firstName, lastName, age);
editContact(id, firstName, lastName, age, () => navigation.navigate('Show',));
};
return (
<View style={style.screen}>
<View style={style.center}>
<ContactForm
initialValues={{ id: Detail.id, firstName: Detail.firstName, lastName: Detail.lastName, age: `${Detail.age}`, title: "Edit contact" }}
onSubmit={onPressHandler}
></ContactForm>
</View>
</View>
);
};
const style = StyleSheet.create({
screen: {
flex: 1,
alignItems: 'center',
backgroundColor: 'white'
},
center: {
flex: 1,
width: "85%",
paddingTop: 30
},
button: {
borderRadius: 10
}
});
const mapStateToProps = state => {
return { getData: state.contacts }
}
export default connect(mapStateToProps, { editContact })(EditContact);
|
T9n.setLanguage('fr');
let email = AccountsTemplates.removeField('email');
let password = AccountsTemplates.removeField('password');
password.minLength = 3;
// Ajout des champs [Prénom, Nom]
AccountsTemplates.addFields([
{
_id: 'prenom',
type: 'text',
displayName: 'Prénom',
placeholder: 'Prénom',
required: true,
minLength: 3,
trim: true
},
{
_id: 'nom',
type: 'text',
displayName: 'Nom',
placeholder: 'Nom',
required: true,
minLength: 3,
trim: true
},
email,
password
]);
AccountsTemplates.configure({
forbidClientAccountCreation: false,
sendVerificationEmail: false
});
|
G.DeclareManifest({
name:'Example mod manifest',
updates:{
'Example mod*':'mod.js',//we're updating any mod with a name that begins with "Example mod"
//you could declare other mod updates here if you wanted
}
});
|
/**
* Created by az on 2017/7/18.
*/
import React, {Component} from 'react';
/*eslint-disable*/
class QbSwitcher extends Component {
renderCircle(circleDiameter, bar) {
const {switchState} = this.props;
if (!switchState) {
return (
<div style={{
position: 'absolute',
left: 0,
top: -(circleDiameter - bar.height)/2,
width: circleDiameter,
height: circleDiameter,
backgroundColor: '#cccccc',
border: 'solid 1px #cccccc',
borderRadius: 100
}}/>
)
} else {
return (
<div style={{
position: 'absolute',
right: 0,
top: -(circleDiameter - bar.height)/2,
width: circleDiameter,
height: circleDiameter,
backgroundColor: '#192230',
border: 'solid 1px #192230',
borderRadius: 100
}}/>
)
}
}
render() {
const {diameter, barStyle, clickHandler} = this.props;
let circleDiameter = diameter?diameter:14;
let bar = barStyle?{width: barStyle.width, height: barStyle.height}: {width: 24, height: 8};
let circle = this.renderCircle(circleDiameter, bar);
return (
<div style={{position: 'relative', width: bar.width}} onClick={()=> {
clickHandler();
}}>
<div style={{
height: bar.height,
width: '100%',
borderRadius: 100,
backgroundColor: '#e8e8ea',
}}>
</div>
{circle}
</div>
);
}
}
export default QbSwitcher;
|
import { shallow } from 'enzyme'
import React from 'react'
import { Button } from '@b2wads/grimorio-ui'
import MainButton from './button'
const props = {
onClick: jest.fn(),
}
const wrapper = shallow(<MainButton {...props} />)
it('prim', () => {
window.alert = jest.fn()
jest.spyOn(window, 'alert')
expect(wrapper.debug()).toMatchSnapshot()
wrapper
.find(Button)
.props()
.onClick()
expect(window.alert).toHaveBeenCalled()
})
|
// 1
var fullname ='Esra GUmrukculer';
var x = 4;
var myfavnumber = '3';
'true';
var nameletters =['e', 's', 'r', 'a'];
var nameandsurname ="esra " + "gumrukculer";
var equalto100 ='z';
var x = 60;
var y = 40;
var z = x + y;
// 2
console.log('e','a');
// 3
var supercalifragilisticexpialidocious = ['s', 'u', 'p', 'e','r', 'c', 'a', 'l','i', 'f', 'r', 'a','g', 'i', 'l', 'i', 's','t', 'i', 'c', 'e','x', 'p', 'i', 'a','l', 'i', 'd', 'o', 'c', 'i', 'o','u', 's'];
console.log(supercalifragilisticexpialidocious.length);
// 4
console.log (gumrukculer.length) == console.log (esra.length);
// 5
var studentsHere == ['Esra', 'Evelin', 'Prithi','Emily', 'Emil' ,'Kristen','Yangchen', 'Yaren', 'Jahyun', 'Seowon', 'Soyeon','Vincent', 'Vinny', 'Khe', 'Shuting'];
console.log(studentsHere.length)=15;
var allstudents == 15;
if ( studentsHere == 15 ) {
console.log("the students are in class");
} else if ( hour > 15 ) {
console.log("not everyone is here");
}
if ( hour == 0 ) {
// 6
var nameletters = ['e', 's', 'r', 'a'];
for ( var i = 0; i < nameletters.length; i++ ) {
console.log( nameletters[i] + '' + i );
}
// 7-8
var date = new Date;
var time = date.getHours();
if ( time > 7 && time < 9:40 ) {
console.log("checked");
}
else if ( date = monday ) {
console.log("hi monday");
}
else if ( date = tuesday ) {
console.log("hi tuesday");
}else if ( date = wednsday ) {
console.log("hi wednsday");
}else if ( date = thursday ) {
console.log("hi thursday");
}else if ( date = friday ) {
console.log("hi friday");
}else if ( date = saturday ) {
console.log("hi saturday");
}
else {
console.log("sunday");
}
// 9
var favFood =['avocado', 'mango', 'tomatos'];
var favAnimals =['ocelot', 'bonoboMonkey', 'parot'];
var favPlaces =['Izmir', 'Torino', 'Havana'];
var favPokemon =['idk-1', 'idk-2', 'idk-3'];
var favs = [favFood, favAnimals, favPlaces, favPokemon];
// 10
|
//提交的方法名称
$(function(){
//加载表格数据
$('#grid').datagrid({
title: '员工信息列表',
url:'emp_listByPage',
columns:[[
{checkbox:true},
{field:'uuid',title:'编号',width:100},
{field:'username',title:'系统登陆名称',width:100},
{field:'name',title:'真实姓名',width:100},
{field:'gender',title:'性别',width:100,formatter:function(gender){
switch(gender){
case 0: return '女';
case 1: return '男';
default: return '未知';
}
}},
{field:'email',title:'电子邮箱地址',width:100},
{field:'tele',title:'联系电话',width:100},
{field:'address',title:'联系地址',width:100},
{field:'birthday',title:'出生年月日',width:100,formatter:function(birthday){
if(birthday){
return new Date(birthday).Format("yyyy-MM-dd");
}
return "";
}},
{field:'dep',title:'部门',width:100,formatter:function(dep){
if(dep){
return dep.name;
}
return "";
}},
{field:'-',title:'操作',width:200,formatter:function(value,row,index){
var operation = '<a href="javascript:void(0)" onclick="updatePwd_reset(' + row.uuid + ')">重置密码</a> ';
return operation;
}}
]],
singleSelect: true,
pagination: true,
rownumbers: true
});
//初始化编辑窗口
$('#editDlg').dialog({
title: '重置密码',//窗口标题
width: 300,//窗口宽度
height: 150,//窗口高度
closed: true,//窗口是是否为关闭状态, true:表示关闭
modal: true,//模式窗口
buttons:[{
text:'重置密码',
iconCls: 'icon-save',
handler:function(){
//用记输入的部门信息
var submitData= $('#editForm').serializeJSON();
$.ajax({
url: 'emp_updatePwd_reset',
data: submitData,
dataType: 'json',
type: 'post',
success:function(rtn){
//{success:true, message: 操作失败}
$.messager.alert('提示',rtn.message, 'info',function(){
if(rtn.success){
//关闭弹出的窗口
$('#editDlg').dialog('close');
//刷新表格
$('#grid').datagrid('reload');
}
});
}
});
}
},{
text:'关闭',
iconCls:'icon-cancel',
handler:function(){
//关闭弹出的窗口
$('#editDlg').dialog('close');
}
}]
});
});
/**
* 修改
*/
function updatePwd_reset(uuid){
//弹出窗口
$('#editDlg').dialog('open');
//清空表单内容
$('#editForm').form('clear');
$('#uuid').val(uuid);
}
|
import React from 'react'
import Button from './Button'
function ButtonCore() {
return <Button>Core</Button>
}
ButtonCore.config = { name: 'Button', nameDisplay: 'Button', parent: 'Core' }
export default ButtonCore
|
import React, { useState } from "react";
import { Pie } from "react-chartjs-2";
export default function App() {
const questions = [
{
questionText: " Pakistan is located in the?",
answerOptions: [
{ answerText: " East Asia", isCorrect: false },
{ answerText: "West Asia", isCorrect: false },
{ answerText: "South Asia", isCorrect: true },
{ answerText: "Central Asia", isCorrect: false }
]
},
{
questionText: "What is the capital of Pakistan?",
answerOptions: [
{ answerText: "Karachi", isCorrect: false },
{ answerText: "Islamabad", isCorrect: true },
{ answerText: "Lahore", isCorrect: false },
{ answerText: "Rawalpindi", isCorrect: false }
]
},
{
questionText: "Which animal is the national animal of Pakistan??",
answerOptions: [
{ answerText: "Markhor", isCorrect: true },
{ answerText: "Tiger", isCorrect: false },
{ answerText: "Lion", isCorrect: false },
{ answerText: "Monkey", isCorrect: false }
]
},
{
questionText: "Who is the captain of Pakistan's National Cricket Team?",
answerOptions: [
{ answerText: "Imad Wasim", isCorrect: false },
{ answerText: "Sarfraz Ahmad", isCorrect: false },
{ answerText: "Shoaib Malik", isCorrect: false },
{ answerText: "Babar Azam", isCorrect: true }
]
},
{
questionText: "What is the real name of Harry Potter is?",
answerOptions: [
{ answerText: "John Smith", isCorrect: false },
{ answerText: "Daren Criss", isCorrect: false },
{ answerText: "James Weasly", isCorrect: false },
{ answerText: "Daniel Radcliffe", isCorrect: true }
]
},
{
questionText: "“Pakistan Day” is celebrated each year on?",
answerOptions: [
{ answerText: "1 May", isCorrect: false },
{ answerText: "4 July", isCorrect: false },
{ answerText: "6 September", isCorrect: false },
{ answerText: "23 March", isCorrect: true }
]
},
{
questionText: "Badshahi Mosque is situated in?",
answerOptions: [
{ answerText: "Hyderabad", isCorrect: false },
{ answerText: "Multan", isCorrect: false },
{ answerText: "Islamabad", isCorrect: false },
{ answerText: "Lahore", isCorrect: true }
]
},
{
questionText: " 2 * 22 = ?",
answerOptions: [
{ answerText: "16", isCorrect: false },
{ answerText: "4", isCorrect: false },
{ answerText: "60", isCorrect: false },
{ answerText: "44", isCorrect: true }
]
},
{
questionText: "CPU stands for?",
answerOptions: [
{ answerText: "Control Processing Unit", isCorrect: false },
{ answerText: "Central Programing Unit", isCorrect: false },
{ answerText: "Common Processing Unit", isCorrect: false },
{ answerText: "Central Processing Unit ", isCorrect: true }
]
},
{
questionText: "The largest dam in Pakistan is?",
answerOptions: [
{ answerText: "Bhasha Dam", isCorrect: false },
{ answerText: "Mangla Dam", isCorrect: false },
{ answerText: "Kalabagh Dam", isCorrect: false },
{ answerText: "Tarbela Dam", isCorrect: true }
]
}
];
const [currentQuestion, setCurrentQuestion] = useState(0);
const [showScore, setShowScore] = useState(false);
const [score, setScore] = useState(0);
const [inCorrectScore, setInCorrectScore] = useState(0);
const handleAnswerOptionClick = (isCorrect) => {
if (isCorrect) {
setScore(score + 1);
} else {
setInCorrectScore(inCorrectScore + 1);
}
const nextQuestion = currentQuestion + 1;
if (nextQuestion < questions.length) {
setCurrentQuestion(nextQuestion);
} else {
setShowScore(true);
}
};
return (
<div className="main-container">
<h1 className="heading">Quiz App</h1>
<div className="app">
{showScore ? (
<div className="score-section">
You scored {score} out of {questions.length}
<Pie
data={{
labels: ["CorrectAnswer", "InCorrectAnswer"],
datasets: [
{
data: [score, inCorrectScore],
backgroundColor: ["green", "red"]
}
]
}}
width={400}
height={400}
/>
</div>
) : (
<div className="container">
<div className="question-section">
<div className="question-Label">
<h3>Question {currentQuestion + 1}</h3>
</div>
<div className="question-text">
{currentQuestion + 1} :{" "}
{questions[currentQuestion].questionText}
</div>
</div>
<div className="answer-section">
{questions[currentQuestion].answerOptions.map((answerOption) => (
<button
className="btn"
onClick={() =>
handleAnswerOptionClick(answerOption.isCorrect)
}
>
{answerOption.answerText}
</button>
))}
</div>
<p className="last-title">
Question {currentQuestion + 1}/{questions.length}
</p>
</div>
)}
</div>
</div>
);
}
|
import React from "react";
import { storiesOf } from "@storybook/react";
import Form from "./SchemaBlockForm";
import raceBlocks from "../src/blocks/raceBlocks";
import genderBlocks from "../src/blocks/genderBlocks";
storiesOf("Race", module).add("Default", () => {
return <Form schemaBlocks={raceBlocks} />;
});
storiesOf("Gender", module).add("Default", () => {
return <Form schemaBlocks={genderBlocks} />;
});
|
var entities = require('@jetbrains/youtrack-scripting-api/entities');
var hasValidNonemptyRepeatField = require('./has-valid-nonempty-repeat-field').hasValidNonemptyRepeatField;
exports.rule = entities.Issue.onSchedule({
title: 'Clone this issue to the next Repeat Date and change its State to Obsolete',
// TODO: maybe add 'StartDateAndTime' to search
search: '#Unresolved has: {Repeat}',
// For format details refer to http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html
// Fire at 4:30 every night
cron: '0 30 4 * * ?',
// TODO: to mute notifications for changes that are applied by this rule, set to true
muteUpdateNotifications: false,
guard: function(ctx) {
var fields = ctx.issue.fields;
if (!fields.Repeat) {
return false;
}
// This check allows skipping automatic obsoleteness for issues with invalid 'Repeat' (like '+', 'manualrepeat', 'on', etc.)
if (!hasValidNonemptyRepeatField(fields.Repeat)) {
return false;
}
// 'FinishDateAndTime' determines whether the issue is obsolete
// TODO: test taking into account FinishDateAndTime
if (fields.FinishDateAndTime) {
return fields.FinishDateAndTime < Date.now();
}
// If 'FinishDateAndTime' is undefined, then 'StartDateAndTime' determines obsoleteness
return fields.StartDateAndTime && fields.StartDateAndTime < Date.now();
},
action: function(ctx) {
var issue = ctx.issue;
issue.fields.State = ctx.State.Obsolete;
},
requirements: {
State: {
type: entities.State.fieldType,
Obsolete: {}
},
Repeat: {
type: entities.Field.stringType
},
StartDateAndTime: {
type: entities.Field.dateTimeType,
name: 'Start date and time'
},
FinishDateAndTime: {
type: entities.Field.dateTimeType,
name: 'Finish date and time'
}
}
});
|
import React from 'react';
import { Router, Switch, Route } from 'react-router';
import createHistory from 'history/createBrowserHistory';
import CallComponent from './call';
import AnswerComponent from './answer';
const ConferenceRouter = () => {
const history = createHistory();
return (
<div>
<Router history={history}>
<Switch>
<Route
path="/conference/answer"
component={AnswerComponent}
/>
<Route path="/conference/call" component={CallComponent} />
</Switch>
</Router>
</div>
);
};
export default ConferenceRouter;
|
/*
create by woody
date 20170301
审批页面controller
*/
angular.module('myapp').controller('SettingCtrl', ['$scope', 'Init', 'Alert', 'localStorageService', '$ionicPopup', 'Confirm','JumpUtil','LoadUtil','$cordovaFileTransfer','$cordovaFileOpener2','$rootScope',function ($scope, Init, Alert, localStorageService, $ionicPopup,Confirm,JumpUtil,LoadUtil,$cordovaFileTransfer,$cordovaFileOpener2,$rootScope) {
//检查用户是否登录
if(localStorageService.get("ifLogin") == undefined || localStorageService.get("ifLogin") == null || localStorageService.get("ifLogin") == "" || localStorageService.get("ifLogin") != "0"){
var data={gotoData:{url:'login'}};
JumpUtil.goFun(data);
return;
}
//用户姓名
$scope.nickName = localStorageService.get("nickName");
//单位名称
$scope.epName = localStorageService.get("epName");
//退出登录
$scope.logout = function (){
var data = {title:"提示",content:"是否确定退出?"};
var result = Confirm.confirmTemplate(data,function(res){
if(res) {
LoadUtil.showLoad('注销中...');
Init.iwbhttp("/user/logout",{},function(data,header,config,status){
if(data.resFlag == "0"){
var data={gotoData:{url:'login'}};
Alert.myToastBottom({mess: "注销成功!", height:-160});
localStorageService.clearAll();
JumpUtil.goFun(data);
}else{
Alert.myToastBottom({mess: data.msg, height:-160});
}
//隐藏load层
LoadUtil.hideLoad();
},function(data,header,config,status){
var data={gotoData:{url:'login'}};
Alert.myToastBottom({mess: "注销成功!", height:-160});
localStorageService.clearAll();
JumpUtil.goFun(data);
});
} else {
}
});
}
//版本校验更新
var myPopup;
var download = "";
//下载进度百分比
$scope.downloadProgress_show = '';
$scope.checkAppVersion = function (){
Init.iwbhttp("/appVersion/checkAppVersion",{appId:$rootScope.appId,appVersion:$rootScope.appVersion},function(data,header,config,status){
if(data.resFlag == "0"){
$scope.noticeContent = "已有新版本,立即更新?";
myPopup = $ionicPopup.show({
template: '<div align="center">{{noticeContent}}</div>',
title: '',
subTitle: '',
scope: $scope,
buttons: [
{ text: '取消',
onTap: function(e) {
if(download != ""){
//中断下载
download.abort();
download = "";
}
}
},
{
text: '确定',
type: 'button-positive btn-my',
onTap: function(e) {
e.preventDefault();
var obj = {
url:$rootScope.apkPath,
fileDir:$rootScope.apkFileDir+$rootScope.apkName,
trustHosts : true,
options : {}
};
downloadFile(obj);
}
},
]
});
}else{
Alert.myToastBottom({mess: data.msg, height: -160});
}
LoadUtil.hideLoad();
},function(data,header,config,status){
var data={gotoData:{url:'login'}};
Alert.myToastBottom({mess: "注销成功!", height:-160});
localStorageService.clearAll();
JumpUtil.goFun(data);
});
}
//下载文件
var downloadFile = function(obj)
{
if(download != ""){
Alert.myToastBottom({mess: "下载中,请勿重复下载!", height:-160});
return false;
}
download = $cordovaFileTransfer.download(obj.url,obj.fileDir,obj.options,obj.trustHosts);
download.then(function (success) {
$scope.downloadProgress = 100;
$scope.downloadProgress_show = '100%';
$scope.noticeContent = "请稍等,已下载"+$scope.downloadProgress_show;
myPopup.close();
download = "";
$cordovaFileOpener2.open(obj.fileDir, 'application/vnd.android.package-archive')
.then(function () {
}, function (err) {
});
}, function (error) {
download = "";
Alert.myToastBottom({mess: "下载失败!", height:-160});
}, function (progress) {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
$scope.downloadProgress_show = parseInt($scope.downloadProgress)+'%';
$scope.noticeContent = "请稍等,已下载"+$scope.downloadProgress_show;
});
}
}]);
|
function test() {
return x = x + 1;
}
console.log(test())
var x = 1;
function test() {
return x = x + 3;
}
console.log(test())
function test1(c) {
var code = 1;
setTimeout(() => {
this.code = c
})
}
var a = 1;
var b = {
code: '2'
}
test1.apply(b, [a]);
console.log(b.code + a);
|
var express = require('express');
var app = express()
var router = express.Router();
var db = require('../models')
// parser will allow us to parse json data
// In this file we will be defining routes
router.get('/',function(req,res){
db.Todo.find()
.then(function(todos){
res.json(todos)
})
.catch(function(err){
res.send(err)
})
})
router.post('/',function(req,res){
db.Todo.create(req.body)
.then(function(newTodo){
res.json(newTodo)
})
.catch(function(err){
res.send(err)
})
// console.log(req.body)
})
module .exports = router
|
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const jwt= require('jsonwebtoken');
const zquery=require("./mysql-zwf.js");
router.get('/list',(req,res) => {
let token = req.headers['token'];
let decoded = jwt.verify(token, 'SALLEN-JWT');
let sql = "SELECT id,title,time FROM blog WHERE author=? ORDER BY ID DESC";
zquery(sql,[decoded.name],(err,vals,fields) => {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
let response ={status:1,data:vals,total:vals.length};
res.send(JSON.stringify(response));
})
});
router.get('/all',(req,res) => {
let sql = "SELECT * FROM blog ORDER BY ID DESC";
zquery(sql,[],(err,vals,fields) => {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
let response ={status:1,data:vals,total:vals.length};
res.send(JSON.stringify(response));
})
});
router.post('/submit',(req,res) => {
let token = req.headers['token'];
let decoded = jwt.verify(token, 'SALLEN-JWT');
let time =Date.parse( new Date());
let sql = "INSERT INTO blog(title,content,author,time) VALUES(?,?,?,?)"
zquery(sql,[req.body.data.title,req.body.data.content,decoded.name,time],(err,vals,fie) => {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
res.send("success");
})
});
router.get('/detail',(req,res) => {
let sql = "SELECT * FROM blog WHERE id=? ";
zquery(sql,[req.query.id],(err,vals,fields) => {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
let response ={status:1,data:vals};
res.send(JSON.stringify(response));
})
});
module.exports = router;
|
var bodyElements = [...document.body.getElementsByTagName('*')];
// Array of all elements inside the body tag
// Function that loops through the new bodyElements array
function findAndReplace(){
bodyElements.forEach(element =>{
element.childNodes.forEach(child =>{
if(child.nodeType === 3){
replaceText(child);
}
});
});
}
// Function to replace the text within the findAndReplace function
function replaceText (node) {
let value = node.nodeValue;
value = value.replace(/free/gi, 'taxpayer-funded');
value = value.replace(/Free/gi, 'Taxpayer-funded');
value = value.replace(/tuition free/gi, 'taxpayer-funded');
value = value.replace(/tuition-free/gi, 'taxpayer-funded');
value = value.replace(/Bernie/gi, 'Our Glorious Comrade');
value = value.replace(/Sanders/gi, 'Sanders, may he live forever');
value = value.replace(/socialism/gi, 'wealth confiscation');
value = value.replace(/Socialism/gi, 'Wealth confiscation');
value = value.replace(/Green New Deal/gi, 'Economic Reversal Deal');
value = value.replace(/Medicare for All/gi, 'Glorious Healthcare for All');
value = value.replace(/Medicare for All/gi, 'Glorious Healthcare for All');
node.nodeValue = value;
}
window.onload = findAndReplace();
|
import React from "react";
import { Grid, Typography,TextField,Box } from "@material-ui/core";
import { makeStyles } from "@mui/styles";
import logo from '../Images/logo.svg';
const useStyles = makeStyles((theme) => ({
body: {
display: "flex",
justifyContent: "center",
height:"100%",
backgroundColor :"black",
},
itemcontainer: {
justifyContent: "center",
flexDirection: "coloumn",
height: "100%"
},
header : {
margin: "75px 0px 0px 0px"
},
title:{
fontSize: "24px",
fontWeight: "bold",
fontFamily: "Mulish",
lineHeight : "30px",
},
subTitle:{
fontSize: "12px",
lineHeight:"20px",
fontFamily: "Mulish",
margin: "13px 0px 0px 0px"
},
form:{
margin: "20px 0px 0px 0px",
}
}));
const Login = () => {
const classes = useStyles();
return (
<Grid container className={classes.body}>
<Grid container className={classes.itemcontainer}>
<Grid
item
style={{ width: "365px", height: "582px", backgroundColor: "white",margin:"82px",padding:"28px"}}
>
<div className={classes.header}>
<Typography align="center">
<img src={logo} alt="tejimandi logo"></img>
</Typography>
<Box margin="41px">
<Typography className={classes.title} variant="inherit">
Log in to Admin CMS
</Typography>
<Typography className={classes.subTitle} >
Enter your email and password below
</Typography>
</Box>
</div>
<form className="form">
<Grid container>
<Grid item xs={12} sm={12} md={12} lg={12}>
<Typography>
Email
</Typography>
</Grid>
<Grid item >
<TextField id="outlined-basic" label="Outlined" variant="outlined" fullWidth/>
</Grid>
</Grid>
<Grid container spacing={9}>
<Grid item>
<Typography>
Password
</Typography>
</Grid>
<Grid item>
<Typography>
Forget password
</Typography>
</Grid>
</Grid>
</form>
</Grid>
</Grid>
</Grid>
);
};
export default Login;
|
import React, { useEffect } from 'react';
import Aos from 'aos';
import 'aos/dist/aos.css';
import { } from 'react-bootstrap';
import './product.css'
function Product() {
useEffect(() => {
Aos.init({ duration: 2000 });
}, []);
return (
<section id='ourservices' className='mv3'>
<span id="goto" style = {{marginTop: "-300px", paddingBottom: "300px", display: "block"}}> </span>
<h2 data-aos='fade-down' className='b'>
Our Products
</h2>
<div className="row">
<div className="col-sm-6">
<div data-aos='fade-right' className="pa2 center grow pointer card">
<div className="card-body">
<h5 className="card-title">HCV & LCV SPARES</h5>
<p className="card-text">
We deal in all types of original spares in Tata, Eicher, Leyland, AMW, Bharat Benz, Mahindra Navi-star and other LCV's & HCV's running in India.
</p>
</div>
</div>
</div>
<div className="col-sm-6">
<div data-aos='fade-left' className="pa2 center grow pointer card">
<div className="card-body">
<h5 className="card-title">LUBRICANTS & OIL</h5>
<p className="card-text">
We deal in Castrol, Valvoline, Tata Motors, TVS and other best quality lubricants available in Indian Market.
</p>
</div>
</div>
</div>
</div>
</section>);
}
export default Product;
|
import React from "react"
import PropTypes from "prop-types"
import Squad from './Squad'
class AllSquads extends React.Component {
handleDelete(id) {
console.log('AllSquads handleDelete (id: ' + id + ')')
this.props.handleDelete(id);
}
onUpdate(squad) {
console.log('AllSquads onUpdate (squad: ' + squad + ')')
this.props.onUpdate(squad);
}
render () {
console.log('AllSquads render')
var context = this;
var squads = this.props.squads.map((squad) => {
return (
<div key={squad.id}>
<Squad squad={squad}
handleDelete={this.handleDelete.bind(this, squad.id)}
handleUpdate={this.onUpdate}/>
</div>
)
});
return (
<React.Fragment>
{squads}
</React.Fragment>
);
}
}
export default AllSquads
|
import React from 'react';
import { Layer, Box, Heading, Text, Button } from 'grommet';
import { Validate, Alert } from 'grommet-icons';
const NotifyLayer = ({ message, isSuccess, onClose, size }) => (
message ?
<Layer align='top' onEsc={onClose} size={size || 'medium'}>
<Box pad={{ horizontal: 'medium', top: 'medium' }}>
<Heading level={2} margin='medium'>
{isSuccess ?
<Validate size='large' /> :
<Alert size='large' />
}
</Heading>
<Box margin={{ horizontal: 'none' }}>
<Text>
{message}
</Text>
<Box align='start' margin={{ vertical: 'medium', top: 'large' }}>
<Button primary={true} label='Okay' onClick={onClose} />
</Box>
</Box>
</Box>
</Layer> : null);
export default NotifyLayer;
|
var str = "Apple";
var str1 = "Apples";
var str2 = "Apple";
var str3 = "Ananas";
console.log(str.localeCompare(str1));
console.log(str.localeCompare(str2));
console.log(str.localeCompare(str3));
|
import React from 'react';
import { StyleSheet, Text, View,TextInput,Button,ScrollView } from 'react-native';
import * as firebase from 'firebase';
import {styles} from './styles'
export default class App extends React.Component {
constructor(){
super();
this.state = {nome:'',senha:''}
}
static navigationOptions = {
title: 'Login',
headerStyle: {
backgroundColor: '#836FFF',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
};
entrar(){
firebase.auth().signInWithEmailAndPassword(this.state.nome, this.state.senha).then(() =>{
alert('usuário logado!');
this.props.navigation.navigate('home');
}).catch(function(error) {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode);
alert(errorMessage);
});
}
cadastrar(){
firebase.auth().createUserWithEmailAndPassword(this.state.nome, this.state.senha)
.then( () => {
alert("Cadastro realizado com sucesso!!Tente entrar agora. :)")
})
.catch(function(error) {
const errorCode = error.code;
const errorMessage = error.message;
alert('Erro ao cadastrar usuário! Por favor tente novamente.'+errorMessage)
});
}
esconder(tamanho){
let asterisco = ''
for (let i=0; i<tamanho;i++){
asterisco += '*'
}
return asterisco;
}
render() {
return (
<ScrollView style = {[styles.container,{backgroundColor:'#B5B5B5',height:'200%'}]}>
<View>
<Text style={styles.logo}>IMC</Text>
</View>
<View>
<Text style={[styles.title,{color:'white'}]}>Nome de usuário:</Text>
<TextInput
style={styles.caixaTexto}
placeholder="Login"
onChangeText={
(texto) =>{ this.setState({nome:texto})}
}/>
<Text style={[styles.title,{color:'white'}]}>Senha:</Text>
<TextInput
style={styles.caixaTexto}
placeholder="Senha"
keyboardType='visible-password'
onChangeText={
(texto) =>{ this.setState({senha:texto})}
}
value ={this.esconder(this.state.senha.length)}
/>
</View>
<View style={{}}>
<View style={styles.botao}>
<Button title='entrar'
color={'#836FFF'}
onPress={this.entrar.bind(this)}/>
</View>
<View style={styles.botao}>
<Button title='cadastre-se!'
color={'#836FFF'}
onPress={this.cadastrar.bind(this)}/>
</View>
</View>
</ScrollView>
);
}
}
|
const fs = require("fs")
const path = require("path")
const crypto = require("crypto")
let verbose = 1
if (process.argv[2] == "-q") {
process.argv.shift()
verbose = 0
}
const profiles_path = process.argv[2]
function error(msg) {
console.error(msg)
process.exit(1)
}
if (!fs.existsSync(profiles_path)) {
error("USAGE: node check-fw-id.js <targets-folder>")
}
function log(msg) {
if (verbose)
console.log(msg)
}
const fwById = {}
const fwByName = {}
for (const dn of fs.readdirSync(profiles_path)) {
if (dn[0] == "_")
continue
const prof_folder = path.join(profiles_path, dn, "profile")
for (const fn of fs.readdirSync(prof_folder)) {
if (!fn.endsWith(".c"))
continue
const profile_fn = path.join(prof_folder, fn)
const src = fs.readFileSync(profile_fn, "utf8")
const m = /FIRMWARE_IDENTIFIER\(((0x)?[0-9a-f]+),\s*"([^"]+)"\)/.exec(src)
if (!m)
error("FIRMWARE_IDENTIFIER(0x..., \"...\") missing")
let dev_class = parseInt(m[1])
const dev_class_name = m[3]
if (!dev_class) {
dev_class = ((crypto.randomBytes(4).readUInt32LE() >>> 4) | 0x30000000) >>> 0
const trg = "0x" + dev_class.toString(16)
let src2 = src.replace(m[0], `FIRMWARE_IDENTIFIER(${trg}, "${dev_class_name}")`)
if (src == src2) throw "whoops"
src2 = src2.replace("// The 0x0 will be replaced with a unique identifier the first time you run make.\n", "")
fs.writeFileSync(profile_fn, src2)
console.log(`Patching ${profile_fn}: dev_class ${m[1]} -> ${trg}`)
}
// log(`${profile_fn} -> 0x${dev_class.toString(16)} "${dev_class_name}"`)
if ((dev_class >> 28) != 3)
error("invalid FIRMWARE_IDENTIFIER() format")
if (fwById[dev_class]) {
error(`${fwById[dev_class]} and ${profile_fn} both use 0x${dev_class.toString(16)} as firmware identifier\n` +
`Replace it with "0" in the newer of the two files and run "make" again.`)
}
if (fwByName[dev_class_name]) {
error(`${fwById[dev_class]} and ${profile_fn} both use "${dev_class_name}"\n` +
`Rename it in the newer of the two files and run "make" again.`)
}
fwById[dev_class] = profile_fn
fwByName[dev_class_name] = profile_fn
}
}
|
const { sort } = require('ramda');
const sortAlphabetical = sort((a, b) => a.localeCompare(b));
module.exports = sortAlphabetical;
|
(function () {
'use strict';
/**
* @ngdoc service
* @name activityForm.factory:ActivityForm
*
* @description
*
*/
angular
.module('activityForm')
.factory('ActivityForm', ActivityForm);
function ActivityForm($http,consts) {
var ActivityFormBase = {};
ActivityFormBase.getActivity = function(activityId) {
return $http({
method: "GET",
url: consts.serverUrl + "Activity/GetActivity",
params: {
activityId: activityId
}
});
};
ActivityFormBase.save = function(activity) {
var fd = new FormData();
fd.append("Id", activity.Id);
fd.append("Name", activity.Name);
if (activity.Description != undefined) fd.append("Description", activity.Description);
if (activity.File != undefined) fd.append("File", activity.File);
if (activity.IsAuthorizedContent != undefined) fd.append("IsAuthorizedContent", activity.IsAuthorizedContent);
activity.Tags.forEach(function(tag, index) {
fd.append("Tags[" + index + "].Id", tag.Id);
fd.append("Tags[" + index + "].TagName", tag.TagName);
});
return $http({
method: "POST",
url: consts.serverUrl + "Activity/SaveActivity",
data: fd,
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
});
};
ActivityFormBase.getTags = function() {
return $http({
method: "GET",
url: consts.serverUrl + "Tag/GetTags"
});
}
return ActivityFormBase;
}
}());
|
/**
* 商品详情
*/
import React, { Component, PureComponent } from "react";
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
Image,
ScrollView,
TouchableOpacity
} from "react-native";
import { connect } from "rn-dva";
import Header from "../../components/Header";
import CommonStyles from "../../common/Styles";
import ImageView from "../../components/ImageView";
import Line from "../../components/Line";
import Content from "../../components/ContentItem";
import * as requestApi from "../../config/requestApi";
import math from '../../config/math.js';
const { width, height } = Dimensions.get("window");
class GoodsDetail extends PureComponent {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
const params = this.props.navigation.state.params || {};
this.state = {
discountParams:params.discountParams || {},
editor: false,
modelVisible: false,
id: params.id,
currentShop: params.currentShop || {},
detail: {
goods: {
category: {}
},
goodsSkuAttrsVO: {},
goodsSkuVOList: []
},
refundsList: params.refundsList || [],
callback: params.callback || (() => {}),
industrys: [],
serviceCatalogs: [],
industrysName: [],
serviceCatalogsName: [],
goodsClassificationName: "",
goodsTypeIdName: "",
industryId1Name: "",
industryId2Name: "",
canEdit: params.canEdit ? true : false
};
}
getDetail = () => {
Loading.show();
requestApi.shopOBMDetail({
id: this.state.id,
shopId: this.state.currentShop.id
})
.then(data => {
console.log(data);
let auditStatus1;
switch (data.goods.auditStatus) {
case "UNAPPROVED":
auditStatus1 = "未通过";
break;
case "UNAUDITED":
// auditStatus1 = "未申请";
auditStatus1 = "未审核";
break;
case "VERIFIED":
auditStatus1 = "已通过";
break;
case "OTHER":
auditStatus1 = "其他";
break;
}
let goodsStatus1;
switch (data.goods.goodsStatus) {
case "UP":
goodsStatus1 = "上架";
break;
case "DOWN":
goodsStatus1 = "下架";
break;
}
data.goods.refound1 = "否";
for (let item of this.state.refundsList) {
item.key == data.goods.refunds
? (data.goods.refound1 = item.title)
: null;
}
data.goods.goodsStatus1 = goodsStatus1;
data.goods.auditStatus1 = auditStatus1;
requestApi
.shopAndCatalogQList({
shopId: this.state.currentShop.id
})
.then(res => {
let newCate = [];
let category = data.goods.category;
let name = {
goodsClassificationName: "",
goodsTypeIdName: "",
industryId1Name: "",
industryId2Name: ""
};
for (let item of res.serviceCatalogs) {
let cate = [];
if (item.code == category.goodsTypeId) {
name.goodsTypeIdName = item.name || "";
}
for (item2 of item.goodsCatalogs) {
cate.push(item2.name);
if (
item2.id == category.goodsClassificationId
) {
console.log(item2.name);
name.goodsClassificationName =
item2.name || "";
}
}
newCate.push({ [item.name]: cate });
}
let newInd = [];
for (let item of res.industrys) {
let ind = [];
if (
data.goods.id &&
item.code == category.industryId1
) {
name.industryId1Name = item.name || "";
}
for (item2 of item.children) {
ind.push(item2.name || "");
if (
data.goods.id &&
item2.code == category.industryId2
) {
name.industryId2Name = item2.name || "";
}
}
newInd.push({ [item.name]: ind });
}
let skuAttrValue = data.goodsSkuVOList || [];
for (let item of skuAttrValue) {
item.originalPrice =math.divide(item.originalPrice || 0,100);
item.discountPrice =math.divide(item.discountPrice || 0,100);
}
this.setState({
detail: data,
industrysName: newInd,
serviceCatalogsName: newCate,
industrys: res.industrys,
serviceCatalogs: res.serviceCatalogs,
...name
});
}).catch((err)=>{
console.log(err)
});
}).catch(()=>{
});
};
componentDidMount() {
this.getDetail();
}
componentWillUnmount() {}
render() {
const { navigation} = this.props;
const {
detail,
currentShop,
refundsList,
industrys,
serviceCatalogs,
industrysName,
serviceCatalogsName,
goodsClassificationName,
goodsTypeIdName,
industryId1Name,
industryId2Name,
canEdit,
discountParams
} = this.state;
let commonItems = [
{ title: "商品编号", value: detail.goods.id },
{ title: "名称", value: detail.goods.goodsName },
{
title: "商品分类",
value: `${
goodsTypeIdName ? goodsTypeIdName + "/" : ""
}${goodsClassificationName}`
},
{
title: "店铺分类",
value: `${
industryId1Name ? industryId1Name + "/" : industryId1Name
}${industryId2Name}`
},
{ title: "审核状态", value: detail.goods.auditStatus1 },
{ title: "在架状态", value: detail.goods.goodsStatus1 }
// { title: '是否需要预约', value: '需在线预约' },
];
let serviceItems = [
...commonItems,
{
title: "是否可加购商品",
value: detail.goods.purchased == 1 ? "是" : "否"
},
{ title: "退款设置", value: detail.goods.refound1 },
{
title: "是否能免费下单",
value: detail.goods.free == 1 ? "是" : "否"
},
{
title: "是否作为订金使用",
value: detail.goods.deposit == 1 ? "是" : "否"
},
{
title: "是否最后结算时付款",
value: detail.goods.zeroOrder == 1 ? "是" : "否"
}
];
let goodsItems = [
...commonItems,
// {
// title: "是否可加购商品",
// value: detail.goods.purchased == 1 ? "是" : "否"
// },
// { title: "退款设置", value: detail.goods.refound1 },
{ title: "是否最后结算时付款", value: detail.goods.free == 1 ? "是" : "否" }
];
let zhusuItems = [
...commonItems,
{ title: "退款设置", value: detail.goods.refound1 }
];
let items = commonItems;
switch (goodsTypeIdName) {
case "服务类":
items = serviceItems;
break;
case "商品类":
items = goodsItems;
break;
case "住宿类":
items = zhusuItems;
break;
}
return (
<View style={styles.container}>
<Header
title="商品详情"
navigation={navigation}
goBack={true}
rightView={
canEdit ? (
<TouchableOpacity
onPress={() =>
navigation.navigate("GoodsEditor", {
currentGoods: detail,
refundsList,
currentShop,
industrys,
serviceCatalogs,
industrysName,
serviceCatalogsName,
goodsClassificationName,
goodsTypeIdName,
industryId1Name,
industryId2Name,
discountParams,
callback: (tabPage) => {
this.state.callback(tabPage);
this.getDetail();
}
})
}
style={{ width: 50 }}
>
<Text style={{ fontSize: 17, color: "#fff" }}>
编辑
</Text>
</TouchableOpacity>
) : null
}
/>
<ScrollView alwaysBounceVertical={false} style={{ flex: 1 }} contentContainerStyle={{paddingBottom:CommonStyles.footerPadding}}>
<View style={styles.content}>
<Content>
{items.map((item, index) => {
return (
<Line
title={item.title}
value={item.value}
point={null}
rightValueStyle={{
flex: 1,
textAlign: "right"
}}
key={index}
type={item.type ? item.type : ""}
onPress={() => {
item.onPress
? item.onPress()
: null;
}}
/>
);
})}
</Content>
<Content>
<Line title="规格" point={null} />
{detail.goodsSkuAttrsVO.attrList &&
detail.goodsSkuAttrsVO.attrList.map(
(item, index) => {
return (
<View
key={index}
style={[
styles.scaleView,
{
borderBottomWidth:
index ==
detail
.goodsSkuAttrsVO
.attrList
.length -
1
? 0
: 1
}
]}
>
<Text style={styles.title}>
规格类型{index + 1}:
<Text
style={{
color: "#777777"
}}
>
{" "}
{item.name}
</Text>
</Text>
<View
style={{
marginTop: 15,
flexDirection: "row"
}}
>
<Text style={styles.title}>
规格:
</Text>
<View
style={{
flexDirection: "row"
}}
>
{item.attrValues &&
item.attrValues.map(
(
item,
index
) => {
return (
<View
style={
styles.scaleTextView
}
key={
index
}
>
<Text
style={
styles.scaleText
}
>
{
item.name
}
</Text>
</View>
);
}
)}
</View>
</View>
</View>
);
}
)}
</Content>
<Content>
<Line title="价格" point={null} />
{detail.goodsSkuVOList &&
detail.goodsSkuVOList.map((item, index) => {
return (
<View
style={[ styles.contentCon,
{
flexWrap:'wrap',
paddingBottom: index == detail.goodsSkuVOList .length - 1 ? 18 : 0
}
]}
key={index}
>
<Text
style={[
styles.title,
{ color: "#777777",width:'30%' }
]}
>
{item.skuName.replace("|", "+")}
</Text>
<View style={{ flexDirection: "row" ,flexWrap:'wrap',justifyContent:'flex-end',flex:1}} >
<Text style={[ styles.title, { color: "#777777", marginRight:15 } ]} >
¥{item.originalPrice}
{goodsTypeIdName == "外卖类" || goodsTypeIdName == "在线购物" ? `${"/" + item.weight}g` : ''}
</Text>
<Text
style={[
styles.title,
{
color: "#777777",
marginRight:0,
textAlign: "right"
}
]}
>
{discountParams.shopDiscountType=='THE_CUSTOM_DISCOUNT'?'会员价':'折扣价'}:
<Text style={{ color: "#FF545B", width: 100 }} > ¥{item.discountPrice} </Text>
</Text>
</View>
</View>
);
})}
</Content>
<Content>
<Line
title="查看评价"
type="horizontal"
point={null}
onPress={() =>
navigation.navigate("Comment", {
shopId: currentShop.id,
goodsId: detail.goods.id
})
}
/>
</Content>
<Content>
<Line title="商品介绍" point={null} />
<Text style={styles.introduction}>
{detail.goods.details || "无"}
</Text>
</Content>
<Content>
<Line title="展示图片" point={null} />
<View style={{ padding: 15, paddingBottom: 0 }}>
{detail.goods.showPics &&
detail.goods.showPics.map((item, index) => {
return (
<ImageView
source={{ uri: item }}
key={index}
sourceWidth={width - 50}
sourceHeight={180}
resizeMode={"cover"}
style={{ marginBottom: 15 }}
/>
);
})}
</View>
</Content>
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
backgroundColor: CommonStyles.globalBgColor
},
content: {
alignItems: "center",
paddingBottom: 10
},
scaleView: {
borderColor: "#F1F1F1",
paddingVertical: 15,
width: width - 35,
marginLeft: 15
},
scaleRightView: {
width: width - 20,
borderTopWidth: 1,
borderColor: "#F1F1F1",
marginTop: 13
},
title: {
fontSize: 14,
color: "#222222"
},
scaleTextView: {
borderWidth: 1,
borderColor: "#4A90FA",
borderRadius: 16,
marginRight: 10
},
scaleText: {
fontSize: 12,
color: "#4A90FA",
paddingHorizontal: 10,
lineHeight: 16,
height: 16
},
contentCon: {
marginTop: 15,
flexDirection: "row",
justifyContent: "space-between",
paddingHorizontal: 15
},
introduction: {
padding: 15,
color: "#777777",
fontSize: 14,
width: width - 20
}
});
export default connect(
state => ({ store: state }),
)(GoodsDetail);
|
import React from 'react';
import FBLoader from './FBLoader';
export default class FBComment extends React.Component {
constructor() {
super();
this.state = {
fbLoaded: false,
};
this.loaded = false;
}
componentWillUpdate(nextProps, nextState) {
if (!this.loaded && nextState.fbLoaded && !this.state.fbLoaded) {
this.loaded = true;
// sleep: https://davidwalsh.name/javascript-sleep-function
const sleep = new Promise((resolve) => setTimeout(resolve, 200));
sleep.then(() => {
global.window.FB.XFBML.parse(this._scope);
});
}
}
render() {
return (
<div>
<FBLoader title={this.props.title} onFbLoad={() => this.setState({fbLoaded: true})}>
<div ref={(s) => this._scope = s}>
<div className="fb-comments"
data-width="100%"
data-href={this.props.fbPluginUrl} data-numposts="10">
</div>
</div>
</FBLoader>
</div>
);
}
}
|
function add (a, b) {
return a + b;
}
function subtract (a, b) {
return a - b;
}
function multiply (a, b) {
return a * b;
}
function divide (a, b){
return a / b;
}
function power(a, b) {
return Math.pow(a, b);
}
function bigNumberFit(num){
let stringNum = num.toString();
let firstNum = stringNum.substring(0, 1);
let decimalNum = firstNum + '.';
let restOfNum = stringNum.substring(1, 10);
let numLength = stringNum.length;
display.innerText = decimalNum + restOfNum + "e+" + (numLength - 1);
}
function ePlusFit(num){
let stringNum = num.toString();
let eIndex = stringNum.indexOf("e+");
let noENum = stringNum.substring(0, eIndex);
let ePlusNum = stringNum.substring(eIndex);
noENum = +noENum;
let fixed = noENum.toFixed(9);
display.innerText = fixed + ePlusNum;
}
function bigDecimalFit(num){
let stringNum = num.toString();
let decimalIndex = stringNum.indexOf('.');
let number = stringNum.substring(0, decimalIndex);
let decimal = stringNum.substring(decimalIndex);
let toFixedLen = 15 - number.length;
decimal = +decimal;
let toFixedNum = decimal.toFixed(toFixedLen);
display.innerText = +number + +toFixedNum;
}
function operate(operator, a, b){
let expr = 0;
switch (operator){
case '+':
expr = add(+a, +b);
break;
case '-':
expr = subtract(+a, +b);
break;
case '*':
expr = multiply(+a, +b);
break;
case '/':
expr = divide(+a, +b);
break;
case '^':
expr = power(+a, +b);
break;
}
if(expr > 999999999999999 && expr.toString().indexOf("e+") === -1 && expr !== Infinity){
bigNumberFit(expr);
}
else if(expr.toString().indexOf("e+") !== -1){
ePlusFit(expr);
}
else if(expr.toString().length > 16){
bigDecimalFit(expr);
}
else{
display.innerText = expr;
}
return expr;
}
const clear = document.getElementById('clear');
const display = document.getElementById('display');
const buttons = document.querySelectorAll('button');
const equals = document.getElementById('equals');
const buttonsArr = Array.from(buttons);
const numbers = buttonsArr.filter(button => (button.value !== ""));
const functions = document.getElementById('functions');
let childFunctions = functions.children;
childFunctions = Array.from(childFunctions);
childFunctions = childFunctions.filter(button => (button.value !== ""));
let operand1 = '';
let operator = '';
let deleteInner = false;
equals.addEventListener('click', function(){
operand1 = operate(operator, operand1, display.innerText);
operateMode = false;
deleteInner = true;
this.animate([
{backgroundColor: 'rgb(255, 69, 0, 0.6)'},
{backgroundColor: 'rgb(255, 69, 0)'}
], {
duration: 200
});
})
let operateMode = false;
let operateModeEnable = false;
clear.addEventListener('click', function(){display.innerText = ""; operand1 = ''; operand2 = ''; operator = ''; operateMode = false; operateModeEnable = false; childFunctions.forEach(button => button.style.cssText = 'background-color: orange');});
numbers.forEach(button => button.addEventListener('click', function(){
switch(this.value){
case '+':
case '-':
case '*':
case '/':
case '^':
operateMode ? operand1 = operate(operator, operand1, display.innerText) : operand1 = display.innerText;
operator = this.value;
operateModeEnable = true;
operateMode = false;
break;
case '.':
if(display.innerText.indexOf('.') === -1 && operateModeEnable == false){
display.innerText += '.';
} else if(operateModeEnable == true && display.innerText !== '-0'){
display.innerText = '0.';
} else{
if(display.innerText.indexOf('.') === -1){
display.innerText += '.';
}
}
break;
case '(-)':
if(operateModeEnable && display.innerText !== '0.'){
display.innerText = '-0';
} else if(display.innerText.indexOf('-') === -1) {
{
display.innerText = '-' + display.innerText;
}
} else{
display.innerText = display.innerText.substring(1);
}
break;
case '%':
display.innerText /= 100;
break;
default:
if(operateModeEnable == true && display.innerText !== '0.' && display.innerText !== '-0' && display.innerText !== '-0.'){
display.innerText = '';
}
if(operateModeEnable){
operateMode = true;
operateModeEnable = false;
childFunctions.forEach(button => button.style.cssText = 'background-color: orange');
}
if(deleteInner == true && display.innerText !== '0.' && display.innerText !== '-0' && display.innerText !== '-0.'){
display.innerText = '';
deleteInner = false;
}
if(display.innerText == '-0'){
display.innerText = '-';
}
if(display.innerText.length < 15){
display.innerText += this.value;
}
break;
}
switch(this.value){
case '+':
case '-':
case '*':
case '/':
childFunctions.forEach(button => button.style.cssText = 'background-color: orange; color: black');
this.style.backgroundColor = 'rgb(32, 34, 37)';
this.style.color = 'orange';
break;
default:
break;
}
}));
|
import React from 'react';
import Box from '@material-ui/core/Box';
import Grid from '@material-ui/core/Grid';
import Typing from 'react-typing-animation';
import ReactDOM from 'react-dom';
import { themes } from './themes.js';
import Header from './Header';
import Projects from './Projects';
import SocialMedia from './SocialMedia';
import AboutMe from './AboutMe';
function renderPage() {
var projects = document.getElementById('projects');
// var aboutMe = document.getElementById('aboutMe');
var load = document.getElementById('load');
var socialMedia = document.getElementById('socialMedia');
projects.classList.add("projectsBG");
projects.classList.add("projects");
projects.classList.add("shadow");
// aboutMe.classList.add("fillScreen");
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
projects.classList.remove("fillScreen");
// aboutMe.classList.add("aboutMeMobile");
socialMedia.classList.add("socialMedia");
ReactDOM.render(<SocialMedia />, document.getElementById('socialMedia'));
}
else {
projects.classList.add("fillScreen");
// aboutMe.classList.add("aboutMe");
}
ReactDOM.render(<Header />, document.getElementById('header'));
ReactDOM.render(<Projects />, document.getElementById('projects'));
// ReactDOM.render(<AboutMe />, document.getElementById('aboutMe'));
ReactDOM.unmountComponentAtNode(load);
};
const Load = () => {
const theme = themes();
return (
<Box id={"load"} className={theme.load}>
<Typing className="typingText" speed={50} cursorClassName={"cursor"} onFinishedTyping={renderPage()}>
<span >programmer</span>
<Typing.Delay ms={200} />
<Typing.Backspace count={12} />
<Typing.Delay ms={400} />
<span>gamer</span>
<Typing.Delay ms={400} />
<Typing.Backspace count={8} />
<Typing.Delay ms={400} />
</Typing>
</Box>
);
}
export default Load;
|
import { combineReducers } from 'redux';
import configureStore from './create-store'
import rootSaga from '../sagas'
export const reducers = combineReducers({ login: require('./LoginReducer').reducer, language: require('./LanguageReducer').reducer });
export default () => {
let finalReducers = reducers
let { store, sagasManager, sagaMiddleware } = configureStore(finalReducers, rootSaga)
if (module.hot) {
module.hot.accept(() => {
const nextRootReducer = require('./').reducers
store.replaceReducer(nextRootReducer)
const newYieldedSagas = require('../sagas').default
sagasManager.cancel()
sagasManager.done.then(() => {
sagasManager = sagaMiddleware.run(newYieldedSagas)
})
})
}
return store
}
|
import React,{useContext,useState,useEffect} from 'react';
import {AuthContext} from './Context/AuthContext';
import axios from 'axios';
import { geolocated } from "react-geolocated";
import Navbar from './Components/Navbar';
import Login from './Components/Login';
import Register from './Components/Register';
import MapComponent from './Components/MapComponent';
import MenuComponent from './Components/MenuComponent';
import SearchComponent from './Components/SearchComponent';
import IndexComponent from './Components/IndexComponent';
import InfoComponent from './Components/InfoComponent';
import ReviewComponent from './Components/ReviewComponent';
import Profile from './Components/Profile';
import BillComponent from './Components/BillComponent';
import Exit from './Components/Exit';
import Home from './Components/Home';
import {BrowserRouter,Route} from 'react-router-dom';
import './app.css'
function App() {
const {user,setUser,isAuthenticated,setIsAuthenticated}=useContext(AuthContext);
console.log(user);
console.log(isAuthenticated);
return (
<div className="App">
<BrowserRouter>
<Navbar/>
<Route exact path='/' component={Home}/>
<Route path='/map' component={MapComponent}/>
<Route path='/search/:collectionID?' component={SearchComponent}/>
<Route path='/index' component={IndexComponent}/>
<Route path='/menu' component={MenuComponent}/>
<Route path='/reviews' component={ReviewComponent}/>
<Route path='/info/:rID' component={InfoComponent}/>
<Route path='/profile' component={Profile}/>
<Route path='/bill' component={BillComponent}/>
<Route path='/success' component={Exit}/>
<Route path='/register' component={Register}/>
<Route path='/login' component={Login} />
<footer className='center'>
<a href="https://icons8.com/icon/51071/restaurant">Restaurant icon by Icons8</a>
</footer>
</BrowserRouter>
</div>
);
}
const MainWithGeoloc=geolocated({
positionOptions: {
enableHighAccuracy: false,
},
userDecisionTimeout: 5000,
})(App);
export default MainWithGeoloc;
|
import React, {Component} from 'react';
import { Table,Modal, Button,Input,message } from 'antd';
const Search = Input.Search;
export default class Linknext extends Component{
constructor(props){
super(props)
this.state={
checked:[], // radio是否选中
dataSource:{}, // 列表数据
current:1, // 当前页数
visible:true
}
this.search = '';
}
componentDidMount(){
this.handleSearchData()
}
handleCancel = ()=>{
this.setState({visible:false})
this.props.handleSupplyName();
this.search='';
}
//分页以及按查询条件查询数据
// url:`/txieasyui?taskFramePN=AlternativeSupplierDao&command=AlternativeSupplierDao.getAlternativeSupplierList&colname=json&colname1={"dataform":"eui_datagrid_data"}`,
// data:{queryValue:this.search},
handleSearchData=()=>{
const that = this;
ajax({
url:`/txieasyui?taskFramePN=supplierRegister&command=supplierRegister.getSupplier&colname=json_ajax&colname1={%27dataform%27:%27eui_datagrid_data%27,%27tablename%27:%27detail0%27}`,
data:{queryparams:JSON.stringify({page:this.state.current,rows:10,devState:this.props.devState,keywords:this.search})},
type:"GET",
success:function(res){
if(res.EAF_ERROR) {
message.error(res.EAF_ERROR);
return;
}
that.setState({dataSource:res});
},
error:function(res){
message.error(res.EAF_ERROR)
}
})
}
// 点击搜索查询数据
searchData = (value)=>{
this.search = value.replace(/\s/g,'');
this.handleSearchData();
}
// 点击行选中该供应商
clickLine = (record)=>{
this.setState({checked:{[record.COMPANYID]:true}})
this.props.handleSupplyName(record);
this.setState({visible:false})
}
// 分页查询数据
onChangePage = (page)=>{
console.log(page)
this.setState({current:page},()=>{
this.handleSearchData('changepage');
});
}
// 分页器初始化
handlePage = ()=>{
// const total = this.props.sellerData&&this.props.sellerData.total;
return(
{
current:this.state.current,
defaultCurrent:1,
defaultPageSize:10,
showQuickJumper:true,
onChange: (pageNumber) => this.onChangePage(pageNumber),
total:this.state.dataSource.total?Number(this.state.dataSource.total):0
}
)
}
render(){
const title=()=>{
return(
<div style={{height:30}}>
<div style={{float:'left'}}>供应商列表:</div>
<div style={{float:'right'}}>
<Search
placeholder={this.props.seachTitle}
onSearch={this.searchData}
style={{ width: 400 }}
enterButton
/>
</div>
</div>
)
}
return(
<div>
<Modal
title={title()}
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
destroyOnClose = {true}
footer={null}
width={800}
wrapClassName='supplyName'
>
<Table loading={!(this.state.dataSource&&this.state.dataSource.rows)} dataSource={this.state.dataSource.rows}
pagination={this.handlePage()}
onRow={(record) => {
return {
onClick: ()=>this.clickLine(record), // 点击行
}
} } columns={this.props.columns} />
</Modal>
</div>
)
}
}
|
// var countryA = $(".ytick")[0].firstChild.textContent;
// var casesA = $(".ytick")[1].firstChild.textContent;
//
// var countryB = $(".ytick2")[1].firstChild.textContent;
// var casesB = $(".ytick2")[0].firstChild.textContent;
//
// $("#firstPlace").text(countryB);
// $("#firstPlaceCount").text("Cases: " + casesB);
// $("#secondPlace").text(countryA);
// $("#secondPlaceCount").text("Cases: " + casesA);
//
|
const PatientActionTypes = {
GET_ALL_PATIENTS: "GET_ALL_PATIENTS",
CREATE_PATIENT: "CREATE_PATIENT",
UPDATE_PATIENT: "UPDATE_PATIENT",
DELETE_PATIENT: "DELETE_PATIENT",
CLEAR_DATA: "CLEAR_DATA",
GET_ERRORS: "GET_ERRORS",
CLEAR_ERRORS: "CLEAR_ERRORS",
SET_SHOW_PATIENT_DIALOG: "SET_SHOW_PATIENT_DIALOG",
SET_SHOW_ADD_PATHOLOGY_DIALOG: "SET_SHOW_ADD_PATHOLOGY_DIALOG",
GET_PATIENT_INFO: "GET_PATIENT_INFO",
SET_SELECTED_PATIENT: "SET_SELECTED_PATIENT",
GET_PATIENT_BY_ID: "GET_PATIENT_BY_ID"
};
export default PatientActionTypes;
|
require.config({
paths: {
"react": "bower_components/react/react-with-addons.min",
"react-dom": "bower_components/react/react-dom.min",
"react-router": "bower_components/react-router/umd/ReactRouter.min",
"babel": "bower_components/requirejs-react-jsx/babel-5.8.34.min",
"jsx": "bower_components/requirejs-react-jsx/jsx",
"text": "bower_components/requirejs-text/text",
"jquery": "bower_components/jquery/dist/jquery",
"materialize": "bower_components/Materialize/dist/js/materialize.min",
"hammerjs": "bower_components/hammerjs/hammer.min",
"jquery-hammerjs": "bower_components/jquery-hammerjs/jquery.hammer",
},
shim : {
"react": {
"exports": "React"
},
'materialize': {
deps: ['jquery', 'jquery-hammerjs']
},
'jquery': {
exports: '$'
}
},
config: {
babel: {
sourceMaps: "inline", // One of [false, 'inline', 'both']. See https://babeljs.io/docs/usage/options/
fileExtension: ".jsx" // Can be set to anything, like .es6 or .js. Defaults to .jsx
}
}
});
require(['jsx!app'], function(App){
var app = new App();
app.init();
});
|
// Import outside libraries
const Phaser = require('phaser');
// Local Modules
const SerialPortReader = require('./SerialPortReader');
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
};
const serial = new SerialPortReader();
var map;
// Phaser setup
function create() {
cursors = this.input.keyboard.createCursorKeys();
map = this.add.graphics({
fillStyle: { color: 0xff66ff },
lineStyle: { width: 3, color: 0xeeeeee }
});
}
function update(totalTime, deltaTime) {
cursors = this.input.keyboard.createCursorKeys();
map.clear();
map.save();
map.translate(config.width/2, config.height/2);
map.fillCircle(0,0,100);
map.restore();
// Keyboard controls
if (cursors.down.isDown) {
map = this.add.graphics({
fillStyle: { color: 0x00ffff }
});
}
else if (cursors.up.isDown) {
map = this.add.graphics({
fillStyle: { color: 0xff66ff }
});
}
}
function onSerialMessage(msg) {
// Put your serial reading code in here. msg will be a string
// if(command === 't') {
// map = this.add.graphics({
// fillStyle: { color: 0x00ffff }
// });
// }
// else if(command === 'b') {
// map = this.add.graphics({
// fillStyle: { color: 0xff66ff }
// });
// }
console.log(msg);
}
config.scene = {
create: create,
update: update
}
let game;
// Exported Module so game can be initialized elseware
const GameManager = {
init: () => {
// Set serial port listener. To keep the code clean we use a helper function defined above
serial.setListener(onSerialMessage);
// The openPort function takes a callback function for finding the correct arduino from a list
// and whatever you want your delimiter to be between packets
serial.openPort(p => /Arduino/.test(p.manufacturer), '-');
game = new Phaser.Game(config);
},
};
module.exports = GameManager;
|
import React, { useState, useEffect } from "react";
import { Header, Grid, Form, Radio, Input, Button } from "semantic-ui-react";
import Kulukorvaus from "./Kulukorvaus";
import Login from "./Login";
const Welcome = () => {
const [form, setForm] = useState("kulukorvaus")
const [nextPage, goNextPage] = useState(false)
useEffect(() => {
window.scroll(0,0)
}, [nextPage])
let component;
if (nextPage) {
if (form === "kulukorvaus") {
component = <Kulukorvaus />
}
}
else {
component = <Login form={form} setForm={setForm} goNextPage={goNextPage} />
}
return (
<Grid columns={1} style={{ marginTop: "1em", marginBottom: "4em" }}>
<Grid.Row>
<Grid.Column textAlign="center">
<Header as="h1">RET:n lomakepankki</Header>
</Grid.Column>
</Grid.Row>
{component}
<Grid.Row>
<Grid.Column textAlign="center">
<Button
content="Alkuun"
onClick={() => goNextPage(false)}
/>
</Grid.Column>
</Grid.Row>
</Grid>
)
}
export default Welcome;
|
'use strict';
// Depends
const path = require('path');
const SvgStore = require('../src/svgstore');
module.exports = function(_path) {
// define local variables
var distPath = path.join(_path, 'example', 'dist');
return {
entry: {
app: path.join(_path, 'example', 'static', 'js', 'index.js')
},
output: {
path: distPath,
filename: '[chunkhash].[name].js',
chunkFilename: '[chunkhash].[id].js',
publicPath: '/example/'
},
resolve: {
extensions: ['.js']
},
module: {
rules: [
{
test: /\.(svg|woff2?|ttf|eot|jpe?g|png|gif)(\?.*)?$/i,
use: ['file-loader'],
},
]
},
plugins: [
// create svgStore instance object
new SvgStore({
svgoOptions: {
plugins: [
{ removeTitle: true }
]
}
})
]
};
};
|
global.api.REDIS = {};
|
import { connect, styled } from "frontity";
import colors from "../styles/colors";
function HomeSection1() {
return (
<Container className="container">
<div className="text-content">
<hr />
<h5>LEAVE BLURRY VISION BEHIND</h5>
<h3>
THE FUTURE IS <b>BRIGHT,</b>
</h3>
<h3>
YOU DESERVE TO SEE IT <b>CLEARLY</b>
</h3>
<p>
Our team is passionate about improving lives through clear vision.
Many of us have had LASIK and know how life changing it is see life
clearly.{" "}
</p>
</div>
<img
src="https://res.cloudinary.com/verrb-inc/image/upload/v1628907765/travelling_aetc30.webp"
alt="travelling friends"
/>
</Container>
);
}
export default connect(HomeSection1);
const Container = styled.section`
display: flex;
justify-content: space-around;
padding: 100px;
background-color: #e5e5e5;
& .text-content {
display: flex;
flex-direction: column;
width: 50%;
font-family: "Poppins", sans-serif;
}
& h5 {
letter-spacing: 5px;
margin: 10px 0px;
margin: 15px 0px;
font-size: 20px;
}
& h3 {
font-size: 30px;
margin: 0;
letter-spacing: 2px;
line-height: 32px;
}
& img {
height: 100%;
}
& hr {
width: 40%;
left: 0p;
left: 0px;
position: absolute;
font-weight: bold;
}
& p {
width: 50%;
line-height: 30px;
font-size: 20px;
font-family: monospace;
}
& button {
height: 50px;
background-color: ${colors.navy};
width: 300px;
color: white;
margin-top: 100px;
font-size: 20px;
font-family: "Poppins", sans-serif;
}
@media (max-width: 1000px) {
padding: 50px;
& img {
height: 100%;
width: 400px;
}
& .text-content > h5 {
font-size: 13px;
}
& .text-content > h3 {
font-size: 20px;
line-height: 24px;
}
& p {
width: 80%;
font-size: 18px;
line-height: 24px;
}
}
@media (max-width: 800px) {
flex-direction: column;
& .text-content {
width: 100%;
margin: 20px 0px;
order: 2;
}
& img {
width: 100%;
order: 1;
}
}
@media (max-width: 800px) {
& p {
width: 100%;
}
}
`;
|
// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');
const fs = require('fs');
// Creates a client
const client = new vision.ImageAnnotatorClient();
exports.test = function(req, res, next){
res.send("Hello darkness my old friend");
};
exports.getFruit = async function (req, res, next) {
try{
const fileName = __dirname+'/test.jpg';
const request = {
image: {content: fs.readFileSync(fileName)},
};
const [result] = await client.objectLocalization(request);
const objects = result.localizedObjectAnnotations;
let objs_to_return = [];
objects.forEach(object => {
objs_to_return.push({
name: object.name,
confidence: object.score
});
const vertices = object.boundingPoly.normalizedVertices;
vertices.forEach(v => console.log(`x: ${v.x}, y:${v.y}`));
});
console.log(objs_to_return);
res.send(objs_to_return);
}catch(exc){
console.log("ERROR IS:");
console.log("------------------------------------------------------------");
console.log(exc);
console.log("------------------------------------------------------------");
res.send("Bad Req");
}
};
|
// @ts-check
/**
* @typedef {import("mocha")}
*/
import { expect } from "chai";
import sinon from "sinon";
import createReducer from "../createReducer";
describe("Test createReducer", () => {
let reducer;
beforeEach(() => {
reducer = createReducer((state, action) => state && action, {});
});
describe("Test dispatch", () => {
it("basic dispatch", () => {
const [store, dispatch] = reducer;
const action = { aaa: "bbb" };
dispatch(action);
expect(store.getState()).to.deep.equal(action);
});
it("dispatch empty", () => {
const [store, dispatch] = reducer;
dispatch();
expect(store.getState()).to.be.empty;
});
it("could support text dispatch", () => {
const [store, dispatch] = reducer;
dispatch("xxx");
expect(store.getState()).to.deep.equal({ type: "xxx" });
});
it("it could dispatch with function", () => {
const [store, dispatch] = reducer;
dispatch(() => "xxx");
expect(store.getState()).to.deep.equal("xxx");
dispatch((/** @type any*/ prev) => prev + "yyy");
expect(store.getState()).to.deep.equal("xxxyyy");
});
it("it could dispatch boolean", () => {
const [store, dispatch] = createReducer(
(_state, action) => ({ foo: action }),
{ foo: true }
);
expect(store.getState()).to.deep.equal({ foo: true });
dispatch(false);
expect(store.getState()).to.deep.equal({ foo: false });
dispatch(true);
expect(store.getState()).to.deep.equal({ foo: true });
});
});
it("Emit with custom event", (done) => {
const [store, dispatch] = reducer;
const callback = sinon.spy();
store.addListener(callback);
dispatch();
setTimeout(() => {
expect(callback.called).to.be.true;
done();
});
});
it("Test lazy initState with number", () => {
const [store, dispatch] = createReducer(
(state, action) => state && action && 111,
() => 111
);
dispatch(null);
expect(store.getState()).to.equal(111);
});
it("Test lazy initState with object", () => {
const [store, dispatch] = createReducer(
(state, action) => state && action,
() => ({ foo: "bar" })
);
dispatch(null);
expect(store.getState()).to.deep.equal({});
});
it("Test reset", () => {
const [store, dispatch] = createReducer(
(state, action) => state && action && "foo",
"foo"
);
dispatch(null);
expect(store.getState()).to.equal("foo");
});
it("Test reset event", (done) => {
const [store, dispatch] = reducer;
const callback = sinon.spy();
store.addListener(callback);
dispatch();
setTimeout(() => {
expect(callback.callCount).to.equal(1);
store.reset();
dispatch();
setTimeout(() => {
expect(callback.callCount).to.equal(1);
done();
});
});
});
});
|
/**
* @author v.lugovsky
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.app.import.productinformation', [])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('app.import.productinformation', {
url: '/productinformation',
templateUrl: 'app/pages/app/import/productinformation/productinformation.html',
controller: 'ProductInformationPageCtrl',
title: 'import.productinformation',
sidebarMeta: {
icon: 'ion-android-home',
order: 1,
},
});
}
})();
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const model = def => ({
table: 'businesses',
columns: {
id: 'serial',
name: 'varchar',
created_at: 'timestamp',
updated_at: 'timestamp',
},
relations: {
owners: def.belongsToMany('Users', 'BusinessOwners', 'business_id'),
bikes: def.hasMany('Bikes')
}
});
exports.default = model;
|
var request = require('request'),
async = require('async'),
moment = require('moment'),
util = require('util');
module.exports = {
list: function(req, res) {
var userid = req.session.profile.id
res.format({
html: function() {
console.log('sending html...')
res.render( 'teams/list.hdb',
{ 'layout': 'short_cs_layout',
'title': 'My Teams',
'url': '/teams/list',
'config': app.config
});
},
json: function() {
var usersRef = app.Firebase.child('users')
var userRef = usersRef.child(userid)
var list = []
var teams = []
console.log("Teams for:", userid)
var userTeamsRef = userRef.child('teams').once( 'value', function(snapshot ) {
snapshot.forEach(function(msgSnapshot) {
var data = msgSnapshot.val();
var teamName = data['owns'] || data['member']
teams.push(teamName)
})
console.log("user teams:", teams)
// setup the callback
var getTeamInfo = function( team, cb ) {
var teamsRef = app.Firebase.child('teams');
var teamRef = teamsRef.child(team);
teamRef.once('value', function(team_data) {
var hash = team_data.val()
hash['ref']=team_data.name()
console.log("team hash:", util.inspect(hash))
var members = []
for( m in hash.members) {
var item = hash.members[m];
var userid = item['member']
console.log('member:', userid, ' team:', teamRef.name())
members.push(userid)
}
hash['users'] = [];
// retrieve the profile for each member of the team
var getProfileInfo = function(member, cb) {
// let's retrieve the ac for that member
var ac = userRef.child('ac');
ac.once('value', function(data) {
var accessToken = data.val();
var url1 = app.get('apiBaseUrl')+'/profile?access_token='+accessToken
request.get( url1, function(err, response, body ) {
hash['users'].push(JSON.parse(body))
cb(null);
})
})
};
async.each(members, getProfileInfo, function(err) {
list.push(hash);
cb(null);
})
})
}
// go through all teams
async.each(teams, getTeamInfo, function(err) {
console.log('list teams create json...%j', list)
data = { list: list };
res.json(data);
})
})
}
})
},
// join team
join: function(req, res) {
var teamid = req.params['id'];
var userid = req.session.profile.id;
console.log("user:", userid, " joins team:", teamid)
var teamsRef = app.Firebase.child('teams');
var teamRef = teamsRef.child(teamid);
var membersRef = teamRef.child('members')
// make sure that this user is not already a member of that team
var teamMember = false;
membersRef.once('value', function(members) {
members.forEach(function(item) {
var data = item.val();
var member_id = data['member'];
if( member_id == userid ) {
console.log('team already a member', userid, teamid)
teamMember = true
}
})
// not a team member, add it
if( !teamMember) {
console.log('add it to the team...')
var member = membersRef.push()
member.update( {member: userid })
}
teamMember = false; // reset for next check
// let add the team to that user
var usersRef = app.Firebase.child('users');
var userRef = usersRef.child(userid);
var teamsRef = userRef.child('teams')
// check if user is not already
teamsRef.once('value', function(members) {
members.forEach(function(item) {
var data = item.val();
var member_id = data['member'] || data['owns'];
if( member_id == userid ) {
console.log('user already a member', userid, teamid)
teamMember = true
}
})
})
if( !teamMember) {
console.log('add team to the user...')
var member = teamsRef.push()
member.update( {member: teamid })
}
res.redirect('/')
})
},
// show team info
show: function(req, res) {
var teamid = req.params['id'];
res.format({
html: function() {
console.log('sending html...')
res.render( 'teams/show.hdb',
{ 'layout': 'short_cs_layout',
'title': 'Show Team',
'url': '/teams/'+teamid,
'config': app.config
});
},
json: function() {
var teamsRef = app.Firebase.child('teams');
var teamRef = teamsRef.child(teamid);
console.log("pulling team:", teamRef.toString())
teamRef.once('value', function(team_data) {
var hash = team_data.val()
hash['ref']=team_data.name()
console.log("got team:", hash)
console.log('sending teams show json...%j', hash)
data = { team: hash };
res.json(data);
})
}
})
},
// edit exsiting team metadata
edit: function(req, res) {
var teamid = req.params['id']
res.format({
html: function() {
console.log('sending html...')
res.render( 'teams/edit.hdb',
{ 'layout': 'short_cs_layout',
'title': 'Edit Team',
'url': '/teams/edit/'+teamid,
'config': app.config
});
},
json: function() {
var teamsRef = app.Firebase.child('teams');
var teamRef = teamsRef.child(teamid);
teamRef.once('value', function(team_data) {
var hash = team_data.val()
hash['ref']=team_data.name()
console.log('sending teams show json...%j', hash)
data = { user: req.session.profile,
team: hash };
res.json(data);
})
}
})
},
// send invite to a friend to join the team
share: function(req, res) {
var teamid = req.params['id']
res.format({
html: function() {
console.log('sending html...')
res.render( 'teams/share.hdb',
{ 'layout': 'short_cs_layout',
'title': 'Send Invite To The Team',
'url': '/teams/share/'+teamid,
'config': app.config
});
},
json: function() {
var teamsRef = app.Firebase.child('teams');
var teamRef = teamsRef.child(teamid);
console.log("pulling team:", teamRef.toString())
teamRef.once('value', function(team_data) {
var hash = team_data.val()
hash['ref'] = teamid
console.log('sending teams show json...%j', hash)
data = { team: hash,
profile: req.session.profile,
config: app.config
};
console.log('sending teams show json...%j', data)
res.json(data);
})
}
})
},
// send invite email
invite: function(req, res) {
console.log("invite %j", req.body);
if( req.body['cancel']) return res.redirect('/')
var id = req.session.profile.id;
var email = req.session.profile.email;
app.sendgrid.send({
to: req.body.email,
from: req.body.from,
subject: req.body.subject,
text: req.body.description
}, function(success, message) {
if (!success) {
console.log(message);
res.send("email sent")
} else {
res.send("email error")
}
})
},
// destroy exisiting team
destroy: function(req, res) {
var teamid = req.params['id']
res.send('destroy:'+teamid)
},
// create new team
create: function(req,res) {
res.format({
html: function() {
console.log('sending html...')
res.render( 'teams/create.hdb',
{ 'layout': 'short_cs_layout',
'title': 'Create New Team',
'url': '/teams/create',
'config': app.config
});
},
json: function() {
console.log('sending teams create json...%j', req.session.profile)
data = { user: req.session.profile };
res.json(data);
}
})
},
// update team metadata
update: function(req, res) {
var teamid = req.params['id'];
var now = moment().format();
var userid = req.session.profile.id
var team = {
name: req.body.name,
location: req.body.location,
logo: req.body.url,
description: req.body.description,
created_at: req.body.created_at,
updated_at: now,
owner: userid
}
var teamsRef = app.Firebase.child('teams');
var teamRef = teamsRef.child(teamid);
teamRef.set(team, function(error) {
console.log("team updated error:"+error)
})
res.redirect('/')
},
// new team
submit: function(req,res) {
var userid = req.session.profile.id
var now = moment().format();
var team = {
name: req.body.name,
location: req.body.location,
logo: req.body.url,
description: req.body.description,
created_at: now,
updated_at: now,
owner: userid
}
var teamsRef = app.Firebase.child('teams');
var newTeam = teamsRef.push();
console.log("newTeam: %j" + team)
newTeam.set(team, function(error) {
console.log("team saved error:"+error)
})
// update user teams
var usersRef = app.Firebase.child('users')
var userRef = usersRef.child(userid)
var userTeamsRef = userRef.child('teams')
var uTeam = userTeamsRef.push()
uTeam.update( {owns: newTeam.name() })
res.send("team created: %j", team)
}
}
|
var express = require('express');
var router = express.Router();
var async = require('async');
var _ = require('underscore');
var api = require('local-cms-api');
var Pager = require('local-pager');
var tkd = require('../tkd.json');
//频道列表页
router.get('/:id.html',function(req,res){
//res.render('list',{'title':'hello'});
//获取当前channel_id
var category_id = req.params.id || '';
var pageSize = 10; // 显示个数
var curPage = Number(req.query.page) || 1; // 当前页码
api.parallel(
{lady:[
{
"key":"listPage",
params:{
category_id:category_id,
page:curPage
}
}
]},
function(err,data){
data.Title = tkd.list.t;
data.Keywords = tkd.list.k;
data.Description = tkd.list.d;
data.rightData = data.listPage.block;
data.pager = new Pager({
pageSize:pageSize, //显示的条数
totalCount:Math.ceil(data.listPage.count / pageSize), //page总数
curPage:curPage, //当前页码,
numCount:data.listPage.pages, //显示[1,2,3,4,5...]的个数
pageUrl:'/list/' + category_id + '.html'
});
console.log(data);
res.render('list', data);
}
);
});
module.exports= router;
|
var playlist = {
"Michael Jackson" : "Thriller",
"Lenny Kravitz" : "American Woman"
};
function updatePlaylist(playlistObj, artistName, songTitle) {
playlistObj[artistName] = songTitle;
return playlistObj;
}
function removeFromPlaylist(playlistObj, artistName) {
delete playlistObj[artistName];
return playlistObj;
}
|
tippy('#albums-bluegrass', {
theme: 'light-border',
arrow: false,
allowHTML: true,
placement: 'right',
touch: false,
maxWidth: 550,
interactive: true,
interactiveBorder: 1,
content: '<div class="article-component"><h1>Bluegrass</h1><ul><li>Kruger Brothers, The Suite, Vol. 1 (2007)</li><li>Nickel Creek, A Dotted Line (2014)</li><li>Punch Brothers, All Ashore (2018)</li><li>Punch Brothers, Antifogmatic (2010)</li><li>Punch Brothers, The Phosphorescent Blues (2015)</li><li>Punch Brothers, Who’s Feeling Young Now? (2012)</li></ul></div>'
});
|
// JavaScript Document
// JavaScript Document
function convert()
{
var oprt = document.getElementById("operators").value;
var slct = document.getElementById("selectors").value;
if(slct==="l")
{ var l= parseFloat(document.getElementById("inpt").value);
if(oprt === "l")
{
document.getElementById("result").value = l;
}
else if(oprt === "m")
{
document.getElementById("result").value = l;
}
else if(oprt === "c")
{
document.getElementById("result").value = l*0.0001;
}
else if(oprt === "f")
{
document.getElementById("result").value = l*0.09290304;
}
else if(oprt === "fl")
{
document.getElementById("result").value = l*0.02322576;
}
else if(oprt === "n")
{
document.getElementById("result").value = l*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = l*0.0001;
}
}
if(slct==="m")
{ var m= parseFloat(document.getElementById("inpt").value);
if(oprt === "l")
{
document.getElementById("result").value = m;
}
else if(oprt === "m")
{
document.getElementById("result").value = m;
}
else if(oprt === "c")
{
document.getElementById("result").value = m*0.0001;
}
else if(oprt === "f")
{
document.getElementById("result").value = m*0.09290304;
}
else if(oprt === "fl")
{
document.getElementById("result").value = m*0.02322576;
}
else if(oprt === "n")
{
document.getElementById("result").value = m*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = m*0.0001;
}
}
if(slct==="c")
{ var c= parseFloat(document.getElementById("inpt").value);
if(oprt === "l")
{
document.getElementById("result").value = c/0.0001;
}
else if(oprt === "m")
{
document.getElementById("result").value = (c/0.0001);
}
else if(oprt === "c")
{
document.getElementById("result").value = (c/0.0001)*0.0001;
}
else if(oprt === "f")
{
document.getElementById("result").value = (c/0.0001)*0.09290304;
}
else if(oprt === "fl")
{
document.getElementById("result").value = (c/0.0001)*0.02322576;
}
else if(oprt === "n")
{
document.getElementById("result").value = (c/0.0001)*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = (c/0.0001)*0.0001;
}
}
if(slct==="f")
{ var f= parseFloat(document.getElementById("inpt").value);
if(oprt === "l")
{
document.getElementById("result").value = f/0.09290304;
}
else if(oprt === "m")
{
document.getElementById("result").value = (f/0.09290304);
}
else if(oprt === "c")
{
document.getElementById("result").value = (f/0.09290304)*0.0001;
}
else if(oprt === "f")
{
document.getElementById("result").value = (f/0.09290304)*0.09290304;
}
else if(oprt === "fl")
{
document.getElementById("result").value = (f/0.09290304)*0.02322576;
}
else if(oprt === "n")
{
document.getElementById("result").value = (f/0.09290304)*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = (f/0.09290304)*0.0001;
}
}
if(slct==="fl")
{ var fl= parseFloat(document.getElementById("inpt").value);
if(oprt === "l")
{
document.getElementById("result").value = fl/0.02322576;
}
else if(oprt === "m")
{
document.getElementById("result").value = (fl/0.02322576);
}
else if(oprt === "c")
{
document.getElementById("result").value = (fl/0.02322576)*0.0001;
}
else if(oprt === "f")
{
document.getElementById("result").value = (fl/0.02322576)*0.09290304;
}
else if(oprt === "fl")
{
document.getElementById("result").value = (fl/0.02322576)*0.02322576;
}
else if(oprt === "n")
{
document.getElementById("result").value = (fl/0.02322576)*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = (fl/0.02322576)*0.0001;
}
}
if(slct==="n")
{ var n= parseFloat(document.getElementById("inpt").value);
if(oprt === "l")
{
document.getElementById("result").value = n/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = (n/1000);
}
else if(oprt === "c")
{
document.getElementById("result").value = (n/1000)*0.0001;
}
else if(oprt === "f")
{
document.getElementById("result").value = (n/1000)*0.09290304;
}
else if(oprt === "fl")
{
document.getElementById("result").value = (n/1000)*0.02322576;
}
else if(oprt === "n")
{
document.getElementById("result").value = (n/1000)*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = (n/1000)*0.0001;
}
}
if(slct==="p")
{ var p= parseFloat(document.getElementById("inpt").value);
if(oprt === "l")
{
document.getElementById("result").value = p/0.0001;
}
else if(oprt === "m")
{
document.getElementById("result").value = (p/0.0001);
}
else if(oprt === "c")
{
document.getElementById("result").value = (p/0.0001)*0.0001;
}
else if(oprt === "f")
{
document.getElementById("result").value = (p/0.0001)*0.09290304;
}
else if(oprt === "fl")
{
document.getElementById("result").value = (p/0.0001)*0.02322576;
}
else if(oprt === "n")
{
document.getElementById("result").value = (p/0.0001)*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = (p/0.0001)*0.0001;
}
}
}
|
/* Autor: Pablo Gadhi Rodriguez Marcucci
Fecha: 01/06/2017
Descripción: Control de las animaciones de ondas estacionarias.
*/
/* Animaciones de la simulación se ejecutan al cargar la página*/
$(document).ready(function() {
$("#waveOpen").css("opacity", "0")
$("#masaM").velocity({translateX: "150px", translateY: "-50px"}, {duration: 4000, loop: true});
$("#forceVector").velocity({translateX: "150px", translateY: "-50px"}, {duration: 4000, loop: true});
$("#cuerdaM").velocity({transformOriginX:"50%", transformOriginY:"1%", rotateZ: "-24.5deg"}, {duration: 4000, loop: true});
$("#waveClose").velocity({opacity: 0}, {duration: 4000, loop: true});
$("#waveOpen").velocity({opacity: 0.9}, {duration: 4000, loop: true});
});
var contador = 0; //Contador para verificación de clicks del botón siguiente
/* Función que se ejecuta al presionar el botón siguiente y va mostrando la linea de las respuestas, dependiendo del valor del contador.*/
function mostrarPasos(){
contador = contador + 1;
switch(contador){
case 1:
$("#p1").velocity({opacity: 1}, {duration: 2000});
break;
case 2:
$("#p2").velocity({opacity: 1}, {duration: 2000});
break;
case 3:
$("#p3").velocity({opacity: 1}, {duration: 2000});
break;
case 4:
$("#p4").velocity({opacity: 1}, {duration: 2000});
break;
case 5:
$("#p5").velocity({opacity: 1}, {duration: 2000});
break;
case 6:
$("#p6").velocity({opacity: 1}, {duration: 2000});
break;
case 7:
$("#p7").velocity({opacity: 1}, {duration: 2000});
break;
case 8:
$("#p8").velocity({opacity: 1}, {duration: 2000});
break;
case 9:
$("#p9").velocity({opacity: 1}, {duration: 2000});
break;
case 10:
$("#p10").velocity({opacity: 1}, {duration: 2000});
break;
case 11:
$("#p11").velocity({opacity: 1}, {duration: 2000});
break;
}
}
|
import {html, render} from '../node_modules/lit-html/lit-html.js';
const listTemplate = (data) => html`
<ul>
${data.map(t => html`
<li> ${t}</li>`)}
</ul>`;
document.getElementById('btnLoadTowns').addEventListener('click', onClick);
function onClick(event) {
event.preventDefault();
const root = document.getElementById('root');
const towns = document.getElementById('towns').value.split(',').map(t => t.trim());
render(listTemplate(towns), root);
}
|
const mongoose = require('mongoose');
const cfenv = require('cfenv');
const logger = require('log4js').getLogger('db');
const localConfig = require('./../config/local');
const appenv = cfenv.getAppEnv({ vcap: localConfig });
const { services } = appenv;
const { credentials } = services['compose-for-mongodb'][0];
const { uri } = credentials;
let options = {
useMongoClient: true
};
if (credentials.ca_certificate_base64) {
const ca = [new Buffer(credentials.ca_certificate_base64, 'base64')];
options = {
...options,
ssl: true,
sslValidate: true,
sslCA: ca
};
}
mongoose.Promise = Promise;
mongoose.connect(uri, options, err => {
if (err) {
logger.error(`Mongoose connection error: ${err}`);
process.exit(1);
}
});
mongoose.connection.on('connected', () => logger.info(`Mongoose connected to ${uri}`));
mongoose.connection.on('error', err => logger.error(`Mongoose connection error: ${err}`));
mongoose.connection.on('disconnected', () => logger.info(`Mongoose disconnected from: ${uri}`));
|
import React, { useMemo } from 'react';
import { useTable, useSortBy, useGlobalFilter, usePagination } from 'react-table';
import MOCK_DATA from './MOCK_DATA.json';
import { COLUMNS } from './columns';
import {GlobalFilter} from './GlobalFilter';
export const PaginationTable = () => {
const columns= useMemo(() => COLUMNS, []);
const data = useMemo(() => MOCK_DATA, []);
//destructuring:
const {
getTableProps,
getTableBodyProps,
headerGroups, //an array, use map method for this
page,
nextPage, //helper functions
previousPage,
canNextPage,
canPreviousPage,
pageOptions,
gotoPage,
pageCount,
setPageSize,
prepareRow,
state,
setGlobalFilter,
} = useTable({
columns: columns, //can also use shorthand
data: data
},
useGlobalFilter,
useSortBy,
usePagination
);
//destructuring
const {globalFilter } = state;
const {pageIndex, pageSize} = state;
return (
<>
{/* receives 2 props globalFilter and setGlobalFilter */}
<div className="table__filter flex justify-between items-center">
<GlobalFilter filter ={globalFilter} setFilter ={setGlobalFilter} />
<div className="per-page flex justify-between items-center">
<span className="table__filter-name text-green-600 font-bold text-left block mr-4">Show</span>
<select value={pageSize} onChange={e => setPageSize(Number(e.target.value))} className="w-24 border border-green-500 rounded-sm text-green-600">
{
[10,25,50].map(pageSize => (
<option key={pageSize} value={pageSize}>{pageSize}</option>
))
}
</select>
</div>
</div>
<div>
<table className="test-table border-collapse w-full text-lg shadow my-4 rounded overflow-hidden"
{...getTableProps()}>
<thead>
{
headerGroups.map( headerGroup => (
<tr className="thead-row bg-yellow-600 text-white text-left"
{...headerGroup.getHeaderGroupProps()}>
{
headerGroup.headers.map( column => (
<th className="p-5"
{...column.getHeaderProps(column.getSortByToggleProps())}>
{/* for sorting added the column.getSortByToggleProps method */}
{column.render('Header')}
<span className="sorting-icon ml-2">
{column.isSorted ? (column.isSortedDesc ? '🔽' : '🔼'): ''}
</span>
</th> //renders the Header property
))
}
</tr>
))
}
<tr>
<th></th>
</tr>
</thead>
<tbody {...getTableBodyProps()}>
{
page.map(row => {
prepareRow(row)
return (
<tr className="table-row text-left bg-gray-50 hover:bg-white"
{...row.getRowProps()}>
{
row.cells.map( cell => {
return <td className="p-4"
{...cell.getCellProps()}>{cell.render('Cell')}</td>
})
}
</tr>
)
})
}
</tbody>
</table>
<div className="flex items-center justify-center">
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage} className="border-2 border-green-600 bg-green-500 text-white w-12 rounded-sm font-bold flex justify-center items-center py-4 px-6">{'<<'} </button>
<button onClick={() => previousPage()} disabled={!canPreviousPage} className="border-2 border-green-600 bg-green-500 text-white w-32 block rounded-sm font-bold py-4 px-6 mx-2 flex justify-center items-center">Previous</button>
<button onClick={() => nextPage()} disabled={!canNextPage} className="border-2 border-green-600 bg-green-500 text-white w-32 block rounded-sm font-bold py-4 px-6 mx-2 flex justify-center items-center">Next</button>
<button onClick={()=> gotoPage(pageCount -1)} disabled={!canNextPage} className="border-2 border-green-600 bg-green-500 text-white w-12 rounded-sm font-bold flex justify-center items-center py-4 px-6">{'>>'}</button>
</div>
<div className="flex items-center justify-center mb-2">
<span className="text-green-600">
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>
</span>
</div>
</div>
</>
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.