text stringlengths 7 3.69M |
|---|
(function () {
App.Collections.Books = Parse.Collection.extend({
model: App.Models.Book
});
}());
|
export default /* glsl */`
void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {
dReflDirW = normalize(-reflect(viewDir, worldNormal));
}
`;
|
// this class is not really related to a sampleToc but can be used for any TOC
import API from 'src/util/api';
import Versioning from 'src/util/versioning';
let defaultOptions = {
group: 'all',
varName: 'sampleToc',
viewName: 'sample_toc',
filter: (entry) => !entry.value.hidden,
sort: (a, b) => {
if (a.value.modified && a.value.modified > b.value.modified) {
return -1;
} else if (
a.value.modificationDate &&
a.value.modificationDate > b.value.modificationDate
) {
return -1;
} else if (a.value.modified && a.value.modified < b.value.modified) {
return 1;
} else if (
a.value.modificationDate &&
a.value.modificationDate < b.value.modificationDate
) {
return 1;
} else {
return 0;
}
},
};
class Toc {
/**
* Create an object managing the Toc
* @param {object} [options={}]
* @param {object} [roc=undefined]
* @param {string} [options.group='mine'] Group to retrieve products. mine, all of a specific group name
* @param {string} [options.varName='sampleToc']
* @param {string} [options.viewName='sample_toc']
* @param {function} [options.sort] Callback, by default sort by reverse date
* @param {function} [options.filter] Callback to filter the result
*/
constructor(roc, options = {}) {
this.roc = roc;
this.options = Object.assign({}, defaultOptions, options);
}
setFilter(filter) {
this.options.filter = filter;
return this.refresh();
}
/**
* Retrieve the toc and put the result in the specified variable
*
*/
refresh(options = {}) {
let {
group,
sort,
filter,
viewName,
limit,
startkey,
endkey,
key,
descending,
} = Object.assign({}, this.options, options);
let mine = 0;
let groups = '';
group = String(group);
if (group === 'mine') {
mine = 1;
} else if (group !== 'all') {
groups = group;
}
return this.roc
.query(viewName, {
groups,
mine,
sort,
filter,
limit,
startkey,
endkey,
key,
descending,
varName: this.options.varName,
})
.then((entries) => {
if (this.options.callback) {
entries.forEach(this.options.callback);
}
return entries;
});
}
async initializeSampleFilter(options = {}) {
const {
twigVarName = 'sampleFilterTwig',
varName = 'sampleFilter',
cookieName = 'eln-default-sample-filter',
filter,
autoRefresh = true,
listAllGroups = false,
} = options;
let groups = [];
if (listAllGroups) {
groups = (await this.roc.getGroupsInfo()).map((g) => g.name);
} else {
groups = (await this.roc.getGroupMembership()).map((g) => g.name);
}
const defaultSampleFilter = {
group: 'mine',
startEpoch: 24 * 3600 * 1000 * 31,
endEpoch: '',
};
const sampleFilter = localStorage.getItem(cookieName)
? JSON.parse(localStorage.getItem(cookieName))
: defaultSampleFilter;
delete sampleFilter.startEpoch;
delete sampleFilter.endEpoch;
if (sampleFilter.previousGroup && !sampleFilter.group) {
sampleFilter.group = sampleFilter.previousGroup;
}
this.updateOptions(sampleFilter);
API.createData(varName, sampleFilter);
const sampleFilterTwig = `
{% if sampleFilter.startEpoch %}
<span style="color: red; font-size: 1.3em; font-weight: bold">Searching for a specific sample.</span> <button onclick="resetFilterOptions()">Reset</button>
{% else %}
<div style="display: flex">
<div>
Group: <select name="group">
<option value='all'>All</option>
<option value='mine'>Mine</option>
${groups.map((group) => '<option value="' + group + '">' + group + '</option>')}
</select>
</div>
<div> </div>
<div>
Modified: <select name="dateRange">
<option value='${24 * 3600 * 1000 * 31}'>Last month</option>
<option value='${24 * 3600 * 1000 * 91}'>Last 3 months</option>
<option value='${24 * 3600 * 1000 * 182}'>Last 6 months</option>
<option value='${24 * 3600 * 1000 * 365}'>Last year</option>
<option value='${24 * 3600 * 1000 * 730}'>Last 2 years</option>
<option value='${24 * 3600 * 1000 * 1830}'>Last 5 years</option>
<option value=''>Any time</option>
</select>
</div>
</div>
{% endif %}
<script>
function resetFilterOptions() {
const sampleFilter = API.getData('sampleFilter');
sampleFilter.endEpoch = undefined;
sampleFilter.startEpoch = undefined;
if (sampleFilter.previousGroup) {
sampleFilter.group = sampleFilter.previousGroup;
}
sampleFilter.triggerChange()
}
</script>
`;
API.createData(twigVarName, sampleFilterTwig);
if (autoRefresh) {
await this.refresh(filter);
}
let mainData = Versioning.getData();
mainData.onChange((evt) => {
if (evt.jpath[0] === varName) {
const currentSampleFilter = API.getData(varName).resurrect();
localStorage.setItem(cookieName, JSON.stringify(currentSampleFilter));
this.updateOptions(currentSampleFilter);
this.refresh();
}
});
}
updateOptions(options) {
this.options.group = options.group;
if (options.startEpoch || options.endEpoch) {
this.options.startkey = options.startEpoch;
this.options.endkey = options.endEpoch;
} else {
this.options.startkey = options.dateRange
? Date.now() - options.dateRange
: undefined;
this.options.endkey = undefined;
}
}
/**
* Retrieve the allowed groups for the logged in user and create 'groupForm'
* variable and 'groupFormSchema' (for onde module). It will keep in a cookie
* the last selected group. Calling this method should reload automatically
* @param {object} [options={}]
* @param {string} [varName='groupForm'] contains the name of the variable containing the form value
* @param {string} [schemaVarName='groupFormSchema'] contains the name of the variable containing the form schema
* @param {string} [cookieName='eln-default-sample-group''] cookie name containing the last selected group
* @param {string} [filter] filter applied on first refresh
* @param {string} [autoRefresh=true] refresh least after initialization
* @param {boolean} [listAllGroups=true] select from any group, even if not the a member
* @return {string} the form to select group}
*/
async initializeGroupForm(options = {}) {
const {
schemaVarName = 'groupFormSchema',
varName = 'groupForm',
cookieName = 'eln-default-sample-group',
filter,
autoRefresh = true,
listAllGroups = false,
} = options;
let groups = [];
if (listAllGroups) {
groups = (await this.roc.getGroupsInfo()).map((g) => g.name);
} else {
groups = (await this.roc.getGroupMembership()).map((g) => g.name);
}
var possibleGroups = ['all', 'mine'].concat(groups);
var defaultGroup = localStorage.getItem(cookieName);
if (possibleGroups.indexOf(defaultGroup) === -1) {
defaultGroup = 'all';
}
var schema = {
type: 'object',
properties: {
group: {
type: 'string',
enum: possibleGroups,
default: defaultGroup,
required: true,
},
},
};
API.createData(schemaVarName, schema);
let groupForm = await API.createData(varName, { group: defaultGroup });
this.options.group = groupForm.group;
if (autoRefresh) {
await this.refresh(filter);
}
let mainData = Versioning.getData();
mainData.onChange((evt) => {
if (evt.jpath[0] === varName) {
localStorage.setItem(cookieName, groupForm.group);
this.options.group = String(groupForm.group);
this.refresh();
}
});
return groupForm;
}
}
module.exports = Toc;
|
var readline = require('readline');
// Module démo à supprimer
var moduleDemo = require('./module-demo');
// pour faciliter l'écriture des logs et la répétition des "console.log"
var lg = console.log;
// liste des modules
// si vous créer un nouveau module, n'oubliez pas de mettre à jour cette liste
var listeModules = [moduleDemo];
lg('**** EvalMe - Console Administration ****');
// affichage du menu
listeModules.forEach(function(module, index) {
lg(index + 1 + '.', module.titre);
});
// création d'un objet permet de lire l'entrée de la console
// l'équivalent du Scanner(System.in) Java SE
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// lecture de l'entrée de la console
// la variable `numero` représente la saisie effectuée, ici un chiffre est attendu
rl.question('Choisir une entité :', function(numero) {
// invocation de la méthode `demarrer` du module choisi.
// => chaque module doit exposer une méthode qui demarrer(rl)
listeModules[numero-1].demarrer(rl);
});
|
let user_dao = require('../models/user_dao');
module.exports = {
// 获取用户
async getUserByN_P(u_name,u_password) {
let users = await user_dao.getUserByN_P(u_name, u_password);
if(users.length === 0){
return {
success:false,
message:'用户名或密码错误'
}
}
return {
success:true,
message:'登录成功',
role: users[0].u_role,
userName:users[0].u_show_name
}
},
// 添加游客
async saveGuest(u_show_name, u_email, u_head_img) {
let users = await user_dao.saveGuest(u_show_name, u_email, u_head_img);
return users.insertId
},
} |
"use strict";
var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var app = angular.module("petshopDapp", ['ionic']);
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'views/menu.html',
controller: 'MenuController'
})
// .state('app.transit', {
// url: '/transit',
// views: {
// 'menuContent': {
// templateUrl: 'views/transit.html',
// controller: 'TransitController'
// }
// }
// })
.state('app.packages', {
url: '/packages',
views: {
'menuContent': {
templateUrl: 'views/packages.html',
controller: 'PackagesController'
}
}
})
// .state('app.packageDetails', {
// url: '/packages/:id',
// views: {
// 'menuContent': {
// templateUrl: 'views/packageDetails.html',
// controller: 'PackageDetailsController'
// }
// }
// })
// .state('app.contract', {
// url: '/contract',
// views: {
// 'menuContent': {
// templateUrl: 'views/contract.html',
// controller: 'SmartContractController'
// }
// }
// })
;
$urlRouterProvider.otherwise('/app/main');
// angular.extend(toastrConfig, {
// autoDismiss: false,
// containerId: 'toast-container',
// maxOpened: 0,
// newestOnTop: true,
// positionClass: 'toast-bottom-full-width',
// preventDuplicates: false,
// preventOpenDuplicates: false,
// target: 'body'
// });
}) |
import React, { Component, } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity, } from 'react-native';
import PropTypes from 'prop-types';
import { connect, } from 'react-redux';
import ThemeFactory, { ColorFlags, DimenFlags, } from '../../res/style/ThemeFactory';
import { WhiteSpace, WingBlank, Button, List, } from '@ant-design/react-native';
import RouteHub from '../../RouteHub';
import NavigationUtil from '../../util/NavigationUtil';
import Item from '@ant-design/react-native/lib/list/ListItem';
class MinePage extends Component {
_loginPress = () => {
NavigationUtil.goPage({}, RouteHub.LOGIN);
}
render() {
const { userInfo, navigation, } = this.props;
const Header = () => {
if (userInfo && JSON.stringify(userInfo) != '{}') {
return <LoginHeader userInfo={userInfo} />;
}
return <UnLoginHeader
onPress={this._loginPress}
/>;
};
return (
<View style={[styles.container,]}>
<Header />
<View style={[styles.row, { justifyContent: 'space-between', padding: 23, backgroundColor: 'white', },]}>
<View style={styles.imageWrapper}>
<Image
source={require('../../res/drawable/user_all_orders.png')}
style={styles.imageFunc}
/>
<Text>全部订单</Text>
</View>
<View style={styles.imageWrapper}>
<Image
source={require('../../res/drawable/user_staying.png')}
style={styles.imageFunc}
/>
<Text>待出行</Text>
</View>
<View style={styles.imageWrapper}>
<Image
source={require('../../res/drawable/user_to_be_paid.png')}
style={styles.imageFunc}
/>
<Text>待支付</Text>
</View>
<View style={styles.imageWrapper}>
<Image
source={require('../../res/drawable/user_refund_form.png')}
style={styles.imageFunc}
/>
<Text>退款单</Text>
</View>
</View>
<WhiteSpace />
<List>
<Item arrow="horizontal">邀请好友</Item>
<Item arrow="horizontal">收藏</Item>
<Item arrow="horizontal">我的银行卡</Item>
<Item arrow="horizontal">房券</Item>
<Item arrow="horizontal">地址</Item>
<Item arrow="horizontal">常用旅客</Item>
</List>
<WhiteSpace />
<List>
<Item arrow="horizontal">安全中心</Item>
</List>
</View>
);
}
}
class LoginHeader extends Component {
static propTypes = {
settingPress: PropTypes.func,
}
render() {
const { userInfo, } = this.props;
return (
<View style={{ paddingHorizontal: DimenFlags.HorizontalMargin, backgroundColor: 'white', paddingTop: 32, }}>
<View style={[styles.row, { marginBottom: 23, },]}>
<WingBlank>
<Image source={{ uri: userInfo.iconUrl, }}
style={styles.avater}
/>
</WingBlank>
<View style={[styles.column, { flex: 1, },]}>
<Text style={{ fontSize: 16, color: ColorFlags.Black, }}>{userInfo.userName}</Text>
<View style={styles.row}>
<Text>Lv{userInfo.userLevel}</Text>
<WingBlank>
<Text style={{ fontSize: 14, color: ColorFlags.Grey, }}>会员权益</Text>
</WingBlank>
</View>
<Text style={{ fontSize: 12, color: ColorFlags.Grey, }}>UID:{userInfo.userId}</Text>
</View>
<TouchableOpacity onPress={() => { NavigationUtil.goPage({}, RouteHub.SETTING); }}>
<Image
source={require('../../res/drawable/ic_setting.png')}
style={[styles.imageButton, { marginRight: 17, },]}
/>
</TouchableOpacity>
<Image
source={require('../../res/drawable/ic_message.png')}
style={styles.imageButton}
/>
</View>
<Account userInfo={userInfo} />
</View>
);
}
}
class Account extends Component {
render() {
const { userInfo, } = this.props;
return (
<View style={{ backgroundColor: ColorFlags.Green, padding: 20, borderRadius: 5, }}>
<View style={[styles.row, { justifyContent: 'space-between', },]}>
<Text style={{ fontSize: 14, }}>升级还需75成长值</Text>
<Text style={{ fontSize: 12, }}>成长值说明
<Image source={require('../../res/drawable/ic_arrow_right.png')}
style={{ width: 6, height: 11, marginLeft: 9, }}
/></Text>
</View>
<Text styel={{}}>我的玩贝(个)</Text>
<View style={[styles.row, { alignItems: 'center', },]}>
<Text style={{ fontSize: 25, }}>7000</Text>
<Text style={{ fontSize: 12, marginLeft: 40, }}>查看账户</Text>
</View>
</View>
);
}
}
class UnLoginHeader extends Component {
static propTypes = {
onPress: PropTypes.func,
}
render() {
return (
<View style={[styles.row, { alignItems: 'center', paddingTop: 32, backgroundColor: 'white', paddingHorizontal:DimenFlags.HorizontalMargin,},]}>
<Image
source={require('../../res/drawable/ic_avater.png')}
style={{ width: 39, height: 39, }}
/>
<Text style={{ fontSize: 16, color: ColorFlags.Black, flex: 1, marginLeft: 15, }}>登陆获取更多信息</Text>
<Button onPress={this.props.onPress}
style={{ backgroundColor: ColorFlags.Green, }}
> 登录</Button>
</View >
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F3F7F9',
},
row: {
flexDirection: 'row',
},
column: {
flexDirection: 'column',
},
imageButton: {
width: 20,
height: 20,
},
avater: {
width: 40,
height: 40,
borderRadius: 20,
},
imageFunc: {
marginBottom: 14,
width: 30,
height: 30,
},
imageWrapper: {
justifyContent: 'center',
alignItems: 'center',
},
});
const mapStateToProps = (state) => ({
userInfo: state.user.userInfo,
});
const mapDispatchToProps = dispatch => ({
// checkLogin: () => dispatch(action.checkLogin()),
});
export default connect(mapStateToProps, mapDispatchToProps)(MinePage);
|
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import App from './App';
describe('App', () => {
let wrapper;
let mockState;
beforeEach(() => {
wrapper = shallow(<App />);
mockState = {
range: [0, 85],
channelSet: '',
originalRange: [0, 86],
};
});
it('renders correctly', () => {
expect(wrapper).toMatchSnapshot();
});
});
|
function addEvent(obj, evType, fn)
{
if (obj.addEventListener)
{
obj.addEventListener(evType, fn, false);
return true;
}
else if (obj.attachEvent)
{
var r = obj.attachEvent('on'+evType, fn);
return r;
}
else
{
alert('Handler could not be attached');
}
}
|
var Config = {
// ray-tracing constants
MaxRecursionDepth: 3,
MaxRayDepth: 1000,
HitpointOffset: 0.0001,
FiniteLightsourceSamples: 100,
AirRefractionIndex: 1.0,
ShowLightsources: true,
// canvas constants
CanvasWidth: 640,
CanvasHeight: 480,
CanvasId: 'canvas',
ShowProgressInTitle: true,
// constants for random scene generation
RandomSceneNumObjects: 80,
RandomSceneObjectSpreadX: 10,
RandomSceneObjectSpreadY: 10,
RandomSceneObjectSpreadZ: 10,
RandomSceneObjectOffsetX: -5,
RandomSceneObjectOffsetY: -5,
RandomSceneObjectOffsetZ: 0,
RandomSceneSphereProbability: 0.8,
RandomSceneBoxProbability: 0.2,
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const THREE = SupEngine.THREE;
const CameraUpdater_1 = require("./CameraUpdater");
class CameraMarker extends SupEngine.ActorComponent {
constructor(actor) {
super(actor, "Marker");
this.viewport = { x: 0, y: 0, width: 1, height: 1 };
this.projectionNeedsUpdate = true;
const geometry = new THREE.Geometry();
for (let i = 0; i < 24; i++)
geometry.vertices.push(new THREE.Vector3(0, 0, 0));
this.line = new THREE.LineSegments(geometry, new THREE.LineBasicMaterial({ color: 0xffffff, opacity: 0.5, transparent: true }));
this.actor.threeObject.add(this.line);
this.line.updateMatrixWorld(false);
}
setIsLayerActive(active) { this.line.visible = active; }
setConfig(config) {
this.setOrthographicMode(config.mode === "orthographic");
this.setFOV(config.fov);
this.setOrthographicScale(config.orthographicScale);
this.setViewport(config.viewport.x, config.viewport.y, config.viewport.width, config.viewport.height);
this.setNearClippingPlane(config.nearClippingPlane);
this.setFarClippingPlane(config.farClippingPlane);
this.projectionNeedsUpdate = false;
this._resetGeometry();
}
setOrthographicMode(isOrthographic) {
this.isOrthographic = isOrthographic;
this.projectionNeedsUpdate = true;
}
setFOV(fov) {
this.fov = fov;
if (!this.isOrthographic)
this.projectionNeedsUpdate = true;
}
setOrthographicScale(orthographicScale) {
this.orthographicScale = orthographicScale;
if (this.isOrthographic)
this.projectionNeedsUpdate = true;
}
setViewport(x, y, width, height) {
this.viewport.x = x;
this.viewport.y = y;
this.viewport.width = width;
this.viewport.height = height;
this.projectionNeedsUpdate = true;
}
setNearClippingPlane(nearClippingPlane) {
this.nearClippingPlane = nearClippingPlane;
this.projectionNeedsUpdate = true;
}
setFarClippingPlane(farClippingPlane) {
this.farClippingPlane = farClippingPlane;
this.projectionNeedsUpdate = true;
}
setRatio(ratio) {
this.ratio = ratio;
this.projectionNeedsUpdate = true;
}
_resetGeometry() {
const near = this.nearClippingPlane;
const far = this.farClippingPlane;
let farTopRight;
let nearTopRight;
if (this.isOrthographic) {
let right = this.orthographicScale / 2 * this.viewport.width / this.viewport.height;
if (this.ratio != null)
right *= this.ratio;
farTopRight = new THREE.Vector3(right, this.orthographicScale / 2, far);
nearTopRight = new THREE.Vector3(right, this.orthographicScale / 2, near);
}
else {
const tan = Math.tan(THREE.Math.degToRad(this.fov / 2));
farTopRight = new THREE.Vector3(far * tan, far * tan, far);
nearTopRight = farTopRight.clone().normalize().multiplyScalar(near);
}
const vertices = this.line.geometry.vertices;
// Near plane
vertices[0].set(-nearTopRight.x, nearTopRight.y, -near);
vertices[1].set(nearTopRight.x, nearTopRight.y, -near);
vertices[2].set(nearTopRight.x, nearTopRight.y, -near);
vertices[3].set(nearTopRight.x, -nearTopRight.y, -near);
vertices[4].set(nearTopRight.x, -nearTopRight.y, -near);
vertices[5].set(-nearTopRight.x, -nearTopRight.y, -near);
vertices[6].set(-nearTopRight.x, -nearTopRight.y, -near);
vertices[7].set(-nearTopRight.x, nearTopRight.y, -near);
// Far plane
vertices[8].set(-farTopRight.x, farTopRight.y, -far);
vertices[9].set(farTopRight.x, farTopRight.y, -far);
vertices[10].set(farTopRight.x, farTopRight.y, -far);
vertices[11].set(farTopRight.x, -farTopRight.y, -far);
vertices[12].set(farTopRight.x, -farTopRight.y, -far);
vertices[13].set(-farTopRight.x, -farTopRight.y, -far);
vertices[14].set(-farTopRight.x, -farTopRight.y, -far);
vertices[15].set(-farTopRight.x, farTopRight.y, -far);
// Lines
vertices[16].set(-nearTopRight.x, nearTopRight.y, -near);
vertices[17].set(-farTopRight.x, farTopRight.y, -far);
vertices[18].set(nearTopRight.x, nearTopRight.y, -near);
vertices[19].set(farTopRight.x, farTopRight.y, -far);
vertices[20].set(nearTopRight.x, -nearTopRight.y, -near);
vertices[21].set(farTopRight.x, -farTopRight.y, -far);
vertices[22].set(-nearTopRight.x, -nearTopRight.y, -near);
vertices[23].set(-farTopRight.x, -farTopRight.y, -far);
this.line.geometry.verticesNeedUpdate = true;
}
_destroy() {
this.actor.threeObject.remove(this.line);
this.line.geometry.dispose();
this.line.material.dispose();
this.line = null;
super._destroy();
}
update() {
if (this.projectionNeedsUpdate) {
this.projectionNeedsUpdate = false;
this._resetGeometry();
}
}
}
/* tslint:disable:variable-name */
CameraMarker.Updater = CameraUpdater_1.default;
exports.default = CameraMarker;
|
'use strict';
const expect = require('chai').expect;
const compression = require('../../src/util/compression');
describe('compression', () => {
it('should compress primitive values', () => {
expect(compression(42, 43)).to.deep.equal(43);
expect(compression(true, false)).to.deep.equal(false);
});
it('should copy new value if type changes', () => {
expect(compression(42, true)).to.deep.equal(true);
expect(compression(42, 'foobar')).to.deep.equal('foobar');
});
describe('objects', () => {
it('should find new properties', () => {
expect(compression({}, { a: 42 })).to.deep.equal({ a: 42 });
});
it('should ignore unchanged properties', () => {
expect(compression({ a: 42 }, { a: 42 })).to.deep.equal({});
});
it('should deep find new properties', () => {
expect(compression({}, { a: { b: 7 } })).to.deep.equal({ a: { b: 7 } });
});
it('should ignore unchanged properties', () => {
expect(compression({ a: { b: 7 } }, { a: { b: 7, c: 3 } })).to.deep.equal({ a: { c: 3 } });
});
it('should remove the same object completely', () => {
const object = { a: { b: { c: 42 } } };
expect(compression(object, object)).to.deep.equal({});
});
it('should remove the same object also when blacklisting', () => {
const object = { a: { b: { c: 42 } } };
expect(compression(object, object, [['unrelated', 'blacklist']])).to.deep.equal({});
});
it('should mark all values as new', () => {
expect(compression(undefined, { a: { b: 7, c: 3 } })).to.deep.equal({ a: { b: 7, c: 3 } });
});
});
describe('arrays', () => {
it('should report empty next array as empty arrays', () => {
expect(compression({ data: [1, 2] }, { data: [] })).to.deep.equal({ data: [] });
});
it('should report complete new array when the length differs', () => {
expect(compression({ data: [1, 2] }, { data: [1, 2, 3] })).to.deep.equal({ data: [1, 2, 3] });
expect(compression({ data: [1, 2, 3] }, { data: [1, 2] })).to.deep.equal({ data: [1, 2] });
});
it('should report undefined when array is shallow unchanged', () => {
expect(compression({ data: [1, 2, 3] }, { data: [1, 2, 3] })).to.deep.equal({});
expect(compression({ data: [1] }, { data: [1] })).to.deep.equal({});
expect(compression({ data: [] }, { data: [] })).to.deep.equal({});
});
it('should resend the whole array when any of the values changes', () => {
expect(compression({ data: [1, 2, 3] }, { data: [1, 2, 4] })).to.deep.equal({ data: [1, 2, 4] });
});
});
describe('blacklisting', () => {
it('should always report properties which have been blacklisted for compression', () => {
expect(
compression(
{
blacklistedPrimitiveRoot: 12,
nonBlacklistedPrimitiveRoot: 13,
changingPrimitiveRoot: 14,
path: {
nonBlacklistedPrimitive: 42,
nonBlacklistedObject: { foo: 'bar' },
nonBlacklistedArray: [1, 2, 3],
blacklistedPrimitive: 43,
blacklistedObject: { foo: 'baz' },
blacklistedArray: [1, 2, 3],
changingPrimitive: 42,
changingObject: { bar: 'foo' },
changingArray: [1, 2, 3]
}
},
{
blacklistedPrimitiveRoot: 12,
nonBlacklistedPrimitiveRoot: 13,
changingPrimitiveRoot: 15,
path: {
nonBlacklistedPrimitive: 42,
nonBlacklistedObject: { foo: 'bar' },
nonBlacklistedArray: [1, 2, 3],
blacklistedPrimitive: 43,
blacklistedObject: { foo: 'baz' },
blacklistedArray: [1, 2, 3],
changingPrimitive: 666,
changingObject: { bar: 'boo' },
changingArray: [1, 2, 3, 4]
}
},
[
['blacklistedPrimitiveRoot'],
['path', 'blacklistedPrimitive'],
['path', 'blacklistedObject'],
['path', 'blacklistedArray']
]
)
).to.deep.equal({
blacklistedPrimitiveRoot: 12,
changingPrimitiveRoot: 15,
path: {
blacklistedPrimitive: 43,
blacklistedObject: { foo: 'baz' },
blacklistedArray: [1, 2, 3],
changingPrimitive: 666,
changingObject: { bar: 'boo' },
changingArray: [1, 2, 3, 4]
}
});
});
it('blacklisting should work for the same object, too', () => {
const object = {
blacklistedPrimitiveRoot: 12,
nonBlacklistedPrimitiveRoot: 13,
path: {
nonBlacklistedPrimitive: 42,
nonBlacklistedObject: { foo: 'bar' },
nonBlacklistedArray: [1, 2, 3],
blacklistedPrimitive: 43,
blacklistedObject: { foo: 'baz' },
blacklistedArray: [1, 2, 3]
}
};
expect(
compression(object, object, [
['blacklistedPrimitiveRoot'],
['path', 'blacklistedPrimitive'],
['path', 'blacklistedObject'],
['path', 'blacklistedArray']
])
).to.deep.equal({
blacklistedPrimitiveRoot: 12,
path: {
blacklistedPrimitive: 43,
blacklistedObject: { foo: 'baz' },
blacklistedArray: [1, 2, 3]
}
});
});
});
});
|
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
TouchableOpacity,
TextInput,
View,
Text,
StatusBar,
ImageBackground,
TouchableHighlight,
Modal,
} from 'react-native';
import { SearchBar } from 'react-native-elements';
import { Image } from 'react-native';
import Feather from 'react-native-vector-icons/Feather';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Foundation from 'react-native-vector-icons/Foundation';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import EvilIcons from 'react-native-vector-icons/EvilIcons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import Entypo from 'react-native-vector-icons/Entypo';
import FireBaseFunctions from "../APIs/FireBaseFunctions";
class LikesList extends React.Component {
services = services = new FireBaseFunctions();
posts = [];
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
isloading: true,
IsActiveBtnEnable: 'Timeline',
modalVisible: false,
}
// this.posts = this.services.getAllData("PostBlock");
// console.log(this.posts.ImageURL);
}
// setModalVisible = (visible) => {
// this.setState({ modalVisible: visible });
// }
onPress = (url, index, event) => {
// url and index of the image you have clicked alongwith onPress event.
}
updateSearch = (text) => {
console.log(text);
this.setState({ email: false });
}
render() {
return (
<View style={{ backgroundColor: "#e5e9f7", height: "100%" }}>
<View style={styles.CommentsTop}>
<View style={{ flexDirection: "row" }}>
<View style={{ width: "20%", }}>
<TouchableOpacity
style={{ margin: 20 }}>
<AntDesign name="left" size={30} style={{ margin: 10, color: "black", }} />
</TouchableOpacity>
</View>
<View style={{ width: "55%", }}>
<Text style={styles.HeadingText}>Likes(4)</Text>
</View>
</View>
</View>
<View>
<SearchBar
placeholder="Type Here..."
onChangeText={this.updateSearch}
value={this.state.email}
inputStyle={{ backgroundColor: 'white' }}
leftIconContainerStyle={{backgroundColor: 'white',}}
inputContainerStyle={{backgroundColor: 'white',height:40}}
containerStyle={{ backgroundColor: 'white', borderRadius: 5,width:"90%",margin:10,marginLeft:20,borderWidth: 1,height:55 }}
/>
</View>
<View style={{ flexDirection: "row", backgroundColor: "white", margin: 5, borderRadius: 10, }}>
<View style={{ flexDirection: "row", width: "80%" }}>
<View style={{ margin: 5 }}>
<Image source={require('../Images/user.jpg')}
style={{
height: 60,
width: 60,
borderRadius: 10,
}} />
</View>
<View style={{ margin: 5, marginLeft: 10 }}>
<Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>User Name</Text>
<Text style={{ fontWeight: "bold", fontSize: 20 }}>@UserName</Text>
</View>
</View>
<View style={{ width: "20%" }}>
<TouchableOpacity
onPress={
() => this.ChangePage('Friends')
} style={{ width: 50, margin: 20, borderColor: "black", borderWidth: 1, borderRadius: 10, alignItems: 'center', }}>
<Text style={{ margin: 5, fontSize: 20, fontWeight: "bold", }}><AntDesign name="heart" size={30} style={{ margin: 20, color: "red" }} /></Text>
</TouchableOpacity>
</View>
</View>
<View style={{ flexDirection: "row", backgroundColor: "white", margin: 5, borderRadius: 10, }}>
<View style={{ flexDirection: "row", width: "80%" }}>
<View style={{ margin: 5 }}>
<Image source={require('../Images/user.jpg')}
style={{
height: 60,
width: 60,
borderRadius: 10,
}} />
</View>
<View style={{ margin: 5, marginLeft: 10, }}>
<Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>User Name</Text>
<Text style={{ fontWeight: "bold", fontSize: 20 }}>@UserName</Text>
</View>
</View>
<View style={{ width: "20%" }}>
<TouchableOpacity
onPress={
() => this.ChangePage('Friends')
} style={{ width: 50, margin: 20, borderColor: "#f1033a", borderWidth: 1, borderRadius: 10, alignItems: 'center', }}>
<Text style={{ margin: 5, fontSize: 20, fontWeight: "bold", }}><AntDesign name="heart" size={30} style={{ margin: 20, color: "#f1033a" }} /></Text>
</TouchableOpacity>
</View>
</View>
<View style={{ flexDirection: "row", backgroundColor: "white", margin: 5, borderRadius: 10, }}>
<View style={{ flexDirection: "row", width: "80%" }}>
<View style={{ margin: 5 }}>
<Image source={require('../Images/user.jpg')}
style={{
height: 60,
width: 60,
borderRadius: 10,
}} />
</View>
<View style={{ margin: 5, marginLeft: 10 }}>
<Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>User Name</Text>
<Text style={{ fontWeight: "bold", fontSize: 20 }}>@UserName</Text>
</View>
</View>
<View style={{ width: "20%" }}>
<TouchableOpacity
onPress={
() => this.ChangePage('Friends')
} style={{ width: 50, margin: 20, alignItems: 'center', }}>
<Text style={{ margin: 5, fontSize: 20, fontWeight: "bold", }}><AntDesign name="heart" size={30} style={{ margin: 20, color: "#f1033a" }} /></Text>
</TouchableOpacity>
</View>
</View>
<View style={{ flexDirection: "row", backgroundColor: "white", margin: 5, borderRadius: 10, }}>
<View style={{ flexDirection: "row", width: "85%" }}>
<View style={{ margin: 10 }}>
<Image source={require('../Images/user.jpg')}
style={{
height: 50,
width: 50,
borderRadius: 10,
}} />
</View>
<View style={{ margin: 10, marginLeft: 10 }}>
<Text style={{ fontWeight: "bold", fontSize: 20, color: "black" }}>User Name</Text>
<Text style={{ fontWeight: "bold", fontSize: 15 }}>@UserName</Text>
</View>
</View>
<View style={{ width: "15%" }}>
<TouchableOpacity
onPress={
() => this.ChangePage('Friends')
} style={{ width: 50, margin: 5, marginTop: 10, alignItems: 'center', }}>
<Text style={{ margin: 10, fontSize: 20, fontWeight: "bold", }}><AntDesign name="heart" size={30} style={{ margin: 20, color: "#f1033a" }} /></Text>
</TouchableOpacity>
</View>
</View>
</View>
);
};
}
const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
//alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5
},
openButton: {
backgroundColor: "#F194FF",
height: 40,
borderRadius: 20,
padding: 10,
elevation: 2,
marginTop: "20%"
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
//textAlign: "center"
},
HeadingText: {
color: "black",
margin: 30,
fontSize: 20,
fontWeight: "bold",
},
CommentsTop: {
width: "100%",
height: "10%",
borderBottomColor: "black",
borderBottomWidth: 1,
marginBottom: 10
},
});
export default LikesList;
|
import React, {Component} from 'react'
import {fetchFinding} from '../../Actions/FindingActions'
import {connect} from 'react-redux'
import {formtTime} from '../Common'
class ScanSummary extends Component {
renderSummary(scanSummary) {
return (
<div class="row">
<div class='col-sm-3'>
<div>
<label class="scan-summary">Application Name:</label>
<span>
{scanSummary.name}
</span>
</div>
<div>
<label class="scan-summary">Status:</label>
<span>{scanSummary.status}</span>
</div>
</div>
<div class='col-sm-4'>
<div>
<label class="scan-summary">Start Time:</label>
<span>{formtTime(scanSummary.startTime)}</span>
</div>
<div>
<label class="scan-summary">End Time:</label>
<span>{formtTime(scanSummary.endTime)}</span>
</div>
</div>
<div class='col-sm-5'>
<div>
<label class="scan-summary">Files Processed:</label>
<span></span>
</div>
<div>
<label class="scan-summary">Application Languages:</label>
<span></span>
</div>
</div>
<div class='col-sm-12'>
<label class="scan-summary">Target:</label>
<span>{scanSummary.target}</span>
</div>
</div>
);
}
render() {
const {scanSummary} = this.props;
if (scanSummary != null) {
return (
<div class="finding-sumary">
{this.renderSummary(scanSummary)}
</div>
);
} else {
return (
<div class="finding-sumary">
<h4>
No Scan Summary
</h4>
</div>
);
}
}
}
const mapStateToProps = (state) => ({scanSummary: state.findings.findingsSummary});
export default connect(mapStateToProps)(ScanSummary);
|
function salir() {
}
|
var _loginVue = new Vue({
el:"#login",
data:{
loginname : "",
password : "",
},
created : function(){
},
methods:{
cleanFormRegister : function(){
this.loginname = "";
this.password = "";
},
showMessage:function(ppMessage){
var _this = this;
$("#message").html(ppMessage);
setTimeout(function(){
_this.cleanMessage();
},'2000');
},
cleanMessage:function(){
var _this = this;
_this.showMessage("");
},
toLogin : function(){
var _this = this;
if(!_this.loginname){
_this.showMessage("请填写登录账号!");
return false;
}
if(!_this.password){
_this.showMessage("请填写登录密码!");
return false;
}
layer.open({type:3});
$.post('../admin/login', {
account : _this.loginname,
password : _this.password,
rdm:Math.random()
}, function(ppData) {
if (ppData != null) {
layer.closeAll("loading");
if (ppData != null) {
if(ppData != null){
var mmData = ppData;
var result = mmData.result;
var message = mmData.message;
var data = mmData.resultContent;
if(result == "1"){
_this.showMessage("登录成功!");
setTimeout(function(){
location.href="/index.html";
},'1000');
}else{
_this.showMessage(message);
}
}
}
}
},"json");
}
}
}) |
const animalQueries = require("../db/queries.animals.js");
var multer = require("multer");
var cors = require("cors");
module.exports = {
index(req, res, next) {
animalQueries.getAllAnimals((err, animals) => {
if (err) {
console.log(err);
} else {
res.json(animals);
}
});
},
availableAnimals(req, res, next) {
animalQueries.getAvailableAnimals((err, animals) => {
if (err) {
console.log(err);
} else {
res.json(animals);
}
});
},
adoptedAnimals(req, res, next) {
animalQueries.getAdoptedAnimals((err, animals) => {
if (err) {
console.log(err);
} else {
res.json(animals);
}
});
},
pendingAdoptions(req, res, next) {
animalQueries.getPendingAdoptions((err, animals) => {
if (err) {
console.log(err);
} else {
res.json(animals);
}
});
},
show(req, res, next) {
animalQueries.getAnimal(req.params.id, (err, animal) => {
if (err || animal == null) {
res.json("That animal does not exist.");
} else {
res.json(animal);
}
});
},
getType(req, res, next) {
animalQueries.getAnimalType(
req.params.column,
req.params.option,
(err, animals) => {
if (err || animals == null) {
res.json("No Animals available");
} else {
res.json(animals);
}
}
);
},
sortedAnimals(req, res, next) {
console.log(
"This is the query in the controller" + JSON.stringify(req.query)
);
animalQueries.getSortedAnimals(req.query, (err, animals) => {
if (err) {
console.log(err);
} else {
res.json(animals);
}
});
},
upload(req, res, err) {
console.log(err);
res.json(req.file);
},
create(req, res, next) {
let newAnimal = {
type: req.body.type,
size: req.body.size,
age: req.body.age,
breed: req.body.breed,
gender: req.body.gender,
status: req.body.status,
name: req.body.name,
description: req.body.description,
photo: req.body.photo
};
animalQueries.addAnimal(newAnimal, (err, animal) => {
if (err) {
console.log(err);
res.json({ message: "That didn't work. Please try again" });
} else {
res.json({ animal, message: "Animal successfully created!" });
}
});
},
update(req, res, next) {
animalQueries.updateAnimal(req, req.body, (err, animal) => {
if (err || animal == null) {
res.json({ message: "That animal does not exist." });
} else {
res.json({ animal, message: "Animal has been successfully updated" });
}
});
}
};
|
import createDataContext from './createDataContext'
import api from '../api/api'
import { navigate, clearNav } from '../navigateRef'
import { AsyncStorage } from 'react-native'
const authReducer = (state, action) => {
switch(action.type) {
case 'signin':
return { errorMessage: '', token: action.payload.token, user: action.payload.user }
case 'signup':
return { errorMessage: '', token: action.payload.token, user: action.payload.user }
case 'logout':
return { errorMessage: '', token: null, user: null }
case 'add_error':
return { ...state, errorMessage: action.payload }
case 'clear_error_message':
return { ...state, errorMessage: '' }
default:
return state
}
}
const tryLocalSignin = dispatch => async() => {
const payload = {
token: "",
user: {},
}
payload.token = await AsyncStorage.getItem('token')
payload.user = JSON.parse(await AsyncStorage.getItem('user'))
try {
if (payload.token && payload.user) {
dispatch({ type: 'signin', payload: payload })
navigate('Todo')
}else{
navigate('Login')
}
}catch(err){
console.log(err)
}
}
const clearErrorMessage = dispatch => () => {
console.log("cleaning error message")
dispatch({ type: 'clear_error_message' })
}
const signin = (dispatch) => async({ email, password }) => {
try {
const response = await api.post('/signin', { email, password })
dispatch({ type: 'signin', payload: response.data})
await AsyncStorage.setItem('token', response.data.token)
await AsyncStorage.setItem('user', JSON.stringify(response.data.user))
navigate('Todo')
} catch(err) {
console.log(err)
dispatch({
type: 'add_error',
payload: 'Wrong email or password'
})
}
}
const signup = (dispatch) => async({ email, username, password}) => {
try{
const response = await api.post('/signup', { email, password, username })
dispatch({ type: 'signup', payload: response.data })
await AsyncStorage.setItem('token', response.data.token)
await AsyncStorage.setItem('user', JSON.stringify(response.data.user))
navigate('Todo')
}catch(err) {
dispatch({
type: 'add_error',
payload: 'Invalid data'
})
}
}
const logout = (dispatch) => async() => {
dispatch({ type: 'logout' })
navigate('Login')
await clearNav()
await AsyncStorage.clear()
}
export const { Provider, Context } = createDataContext(
authReducer,
{ signin, signup, logout, tryLocalSignin, clearErrorMessage },
{ token: null, user: null, errorMessage: ''}
) |
export default class Button {
constructor(number, listener) {
this.number = number;
this.listener = listener;
}
setButton() {
const btn = document.createElement("button");
const innerText = document.createTextNode(" " + this.number + " ");
btn.appendChild(innerText);
btn.setAttribute("class", "num-btn");
btn.setAttribute("value", this.number);
btn.addEventListener("click", this.listener);
return btn;
}
}
|
import { createStore, combineReducers, compose, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducers from './ducks'
const rootReducer = combineReducers(reducers)
export default createStore(
rootReducer,
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
)
|
import React from 'react'
import IntlMessageFormat from 'intl-messageformat'
import load from 'load-script'
import { defaultFormats, DEFAULT_LOCALE, DEFAULT_LOCALE_PARAM_NAME } from './constants'
import { warn } from './polyfill'
import { getDescendantProp, determineLocale, xss, getCurrentLocale } from './helper'
const shouldPolyfill = !window.Intl
require('intl')
const OPTIONS = {
locales: {}, // 国际化数据: {"en-US":{"key1":"value1"},"zh-CN":{"key1":"值1"}}
/**
* 支持的语言资源列表,用于远程获取国际化资源,可以是 object 或 functon
* {"en-US":"{host}/en-US/index.json","zh-CN":"{host}/zh-CN/index.json"}
* function(request) {}
*/
locale: null, // 传入的语言,正常情况不应该去指定这个值,这个值应该是自动检测得来
defaultLocale: DEFAULT_LOCALE, // 默认语言,用于自动检测语言失败时使用
determineLocale: determineLocale, // 没有设置 locale 时自动获取语言的函数,默认会依次 从 URL,cookie,浏览器中获取当前语言信息
localeParamName: DEFAULT_LOCALE_PARAM_NAME, // 从 URL,cookie 中获取当前语言信息时的参数名
remotePrefix: 'https://g.alicdn.com/react-intl-universal/locale-data/1.0.0'
}
class IntlUniversal {
constructor() {
this._error = 0
this.options = {}
}
init(options) {
this.options = Object.assign({}, OPTIONS, options)
this.options.formats = Object.assign({}, this.options.formats, defaultFormats)
const { request, locales, locale, determineLocale } = this.options
if (!locale) {
this.options.locale = determineLocale(this.options)
}
const currentLocale = getCurrentLocale(this.options) // 运行期使用的语言
this.options.currentLocale = currentLocale
let t = locales[currentLocale]
let getLocaleFn
if (t) {
if (typeof t === 'object') {
getLocaleFn = () => Promise.resolve(t)
} else {
if (request) {
getLocaleFn = () => {
return request.call(this, t, currentLocale)
}
}
}
}
if (!getLocaleFn) {
getLocaleFn = () => Promise.reject(new Error(''))
}
return getLocaleFn()
.then(data => {
this.options.data = data || {}
return this._init()
})
.catch(err => {
warn(err)
this._error += 1
const error = this._error
if (error === 1) {
this.options.locale = this.options.defaultLocale
return this.init(this.options)
} else {
return this._init()
}
})
}
/**
* 获取当前语言
*/
getLocale() {
const { locale, currentLocale } = this.options
return {
locale,
currentLocale
}
}
/**
* 设置当前语言
*/
setLocale(lang) {
const { localeParamName } = this.options
let exist = false
if (location.search && location.search.indexOf(`${localeParamName}=`) > -1) {
exist = true
}
if (location.search) {
if (exist) {
location.search = location.search.replace(
new RegExp(`${localeParamName}=?([^&]*)`),
`${localeParamName}=${lang}`
)
} else {
location.search = location.search + `&${localeParamName}=${lang}`
}
} else {
location.search = `?${localeParamName}=${lang}`
}
}
/**
* Get the formatted message by key
*/
get(key, defaultValue, variables) {
const { data, currentLocale, formats } = this.options
if (!variables && typeof defaultValue === 'object') {
variables = defaultValue
defaultValue = key
}
if (defaultValue === undefined) {
defaultValue = key
}
let msg = getDescendantProp(data, key)
if (msg == null) {
warn(`"${key}" not defined in ${currentLocale}`)
return defaultValue
}
if (variables) {
variables = xss(Object.assign({}, variables))
}
try {
msg = new IntlMessageFormat(msg, currentLocale, formats)
msg = msg.format(variables)
return msg
} catch (err) {
warn(`format message failed for key='${key}'`, err)
return defaultValue
}
}
/**
* Get the formatted html message by key.
*/
getHTML(key, defaultValue, variables) {
if (!variables && typeof defaultValue === 'object') {
variables = defaultValue
defaultValue = key
}
if (defaultValue === undefined) {
defaultValue = key
}
const msg = this.get(key, defaultValue, variables)
const el = React.createElement('span', {
dangerouslySetInnerHTML: {
__html: msg
}
})
return el
}
/**
* As same as get(...) API
*/
formatMessage({ id, defaultMessage }, variables) {
return this.get(id, defaultMessage, variables)
}
/**
* As same as getHTML(...) API
*/
formatHTMLMessage({ id, defaultMessage }, variables) {
return this.getHTML(id, defaultMessage, variables)
}
/**
* Initialize properties and load CLDR locale data according to currentLocale
* @returns {Promise}
*/
_init() {
const { currentLocale, remotePrefix } = this.options
return new Promise((resolve, reject) => {
const lang = currentLocale.split('-')[0].split('_')[0]
if (shouldPolyfill) {
load(`${remotePrefix}/${lang}.js`, (err, script) => {
if (err) {
reject(err)
} else {
resolve()
}
})
} else {
resolve()
}
})
}
}
module.exports = new IntlUniversal()
|
export default {
metadata: {
name: 'Box - Slide Out',
duration: 1000,
},
box: {
styles: {
transform: [
0, inputs => t => `translate3d(${inputs.offset * (t * t)}px, 0, 0) scale(${1 - t})`,
],
opacity: [
0, 1,
1000, 0,
],
},
},
};
|
var global = this;
if(typeof global._i18n_lang == 'undefined') global._i18n_lang = {};
global._i18n_lang.ru = {
desc: {
fullname: "Русский",
shortname: "ru"
},
data: {
"hello world" : [ "привет, мир" ],
"nonexistent_test.gif" : ["nonexistent_test_ru.gif"],
"registar" : [ "регистратор", "регистраторы" ],
"tvpanel" : ["тв-панель", "тв-панели" ],
"ipanel" : ["инд. панель", "инд. панели"],
"operator" : ["оператор", "операторы"],
"Operator" : ["Оператор", "Операторы"],
"Select language" : ["Выберите язык"],
"Select theme": ["Выберите тему"],
"Please select component" : ["Пожалуйста, выберите компонент"],
"admin" : ["администратор"],
"Administrator" : ["Aдминистратор"],
"Current client":["Текущий клиент"],
"Operator panel": ["Панель оператора"],
"Served":["Обслужен"],
"Rejected" : ["Отказано"],
"Route forward": ["Далее по маршруту"],
"Settings" :["Настройки"],
"Other options": ["Другие действия"],
"Other settings" : ["Прочие настройки"],
"Admin panel" : ["Панель администратора"],
"Service" : ["Услуга", "Услуги"],
"Schedule" : ["Расписание", "Расписания"],
"User" : ["Пользователь", "Пользователи"],
"Please enter user name and password": ["Пожалуйста, введите имя пользователя и пароль"],
"login/password incorrect" : ["Неверный логин или пароль"],
"Password": ["Пароль"],
"Role" : ["Роль","Роли"],
"Apply changes": [ "Применить изменения" ],
"Delete": ["Удалить"],
"Set password" : ["Задать пароль"],
"Create user" : ["Создать пользователя"],
"User name" : ["Имя пользователя"],
"Cancel" : ["Отмена"],
"Ok" : ["Ok"],
"User name can not be empty":["Имя пользователя не должно быть пустым"],
"Remove user %s?" : ["Удалить пользователя %s?"],
"Change user %s password?": ["Сменить пароль пользователя %s ?"],
"Operation" : ["Операция", "Операции"],
"Short Name" : ["Короткое имя"],
"Full Name" : ["Полное имя"],
"Translated full Names" : [ "Переводы длинных имён"],
"Translated short Names" : [ "Переводы коротких имён"],
"Language" : [ "Язык", "Языки"],
"Default" : ["По умолчанию"],
"Optional settings (may be unset)" : [ "Необязательные настройки (можно не запонять)" ],
"Languages, other than default, can be set here if they are used in multilingual queue. If the queue is single-lingual, this settings can reamin unset" :
["Языки, отличные от языка по умолчанию, могут быть настроены здесь для мультиязычной очереди. Если очередь одноязычная, эти настройки можно не устанавливать"],
"Average time for operation" : ["Среднее время на операцию"],
"Maximum time for operation" : ["Максимальное время на операцию"],
"Min." : ["Мин."],
"Add operation" : [ "Добавить операцию" ],
"Delete operation" : ["Удалить операцию" ],
"Add translation" : ["Добавить перевод"],
"Save" : ["Сохранить"],
"Add service" : ["Добавить услугу"],
"Delete service" : ["Удалить услугу"],
"Add service group" : ["Добавить группу услуг"]
}
};
|
import React from 'react';
// import os from 'os';
require('es6-promise').polyfill();
require('isomorphic-fetch');
export const post = {
users: {
user: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/user`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/_log/user`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
user: data,
date: date
})
});
},
location: function (id, data, date) {
let data_location = {
coords: {
accuracy: data.coords.accuracy,
altitude: data.coords.altitude,
altitudeAccuracy: data.coords.altitudeAccuracy,
heading: data.coords.heading,
latitude: data.coords.latitude,
longitude: data.coords.longitude,
speed: data.coords.speed,
},
timestamp: data.timestamp
}
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/location`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data_location)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/_log/location`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
location: data_location,
date: date
})
});
},
profile: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/profile`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/_log/profile`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
profile: data,
date: date
})
});
}
},
share: {
location: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/location`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/location`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
location: data,
date: date
})
});
},
date: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/date`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/date`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
data: data,
date: date
})
});
},
max_number: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/max_number`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/max_number`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
max_number: data,
date: date
})
});
},
sex: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/sex`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/sex`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sex: data,
date: date
})
});
},
owner: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: data,
date: date
})
});
},
member: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
member: data,
date: date
})
});
},
alert: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/alert`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/alert`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
alert: data,
date: date
})
});
},
chat: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/chat`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/chat`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat: data,
date: date
})
});
}
},
status: {
process: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/process`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/process`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
process: data,
date: date
})
});
},
share: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/share`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/share`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
share: data,
date: date
})
});
},
owner: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: data,
date: date
})
});
},
member: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
member: data,
date: date
})
});
},
alert: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/alert`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/alert`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
alert: data,
date: date
})
});
}
},
history: {
id: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/history/${id}`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
// fetch(`http://localhost:5000/share-we-go-project/us-central1/api/history/${id}/_log`, {
// mode: 'no-cors',
// method: 'post',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({
// history: data,
// date: date
// })
// });
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
share_id: "",
uid: id,
value: "false"
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
share_id: "",
uid: id,
value: "false"
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: {
share_id: "",
uid: id,
value: "false"
},
date: date
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: {
share_id: "",
uid: id,
value: "false"
},
date: date
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/member`, {
method: 'delete',
headers: { 'Content-Type': 'application/json' },
});
// window.location.reload();
}
},
report: {
id: function (id, data, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/report/${id}`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/report/${id}/_log`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
report: data,
date: date
})
});
}
}
}
export const get = {
users: {
all: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/all`).then(
function (res) {
return res.json();
}
)
},
id: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}`).then(
function (res) {
return res.json();
}
)
},
profile: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/profile`).then(
function (res) {
return res.json();
}
)
},
location: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/location`).then(
function (res) {
return res.json();
}
)
},
user: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/user`).then(
function (res) {
return res.json();
}
)
},
log: {
profile: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/_log/profile`).then(
function (res) {
return res.json();
}
)
},
location: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/_log/location`).then(
function (res) {
return res.json();
}
)
},
user: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/users/${id}/_log/user`).then(
function (res) {
return res.json();
}
)
}
}
},
share: {
all: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/all`).then(
function (res) {
return res.json();
}
)
},
id: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}`).then(
function (res) {
return res.json();
}
)
},
location: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/location`).then(
function (res) {
return res.json();
}
)
},
date: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/date`).then(
function (res) {
return res.json();
}
)
},
max_number: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/max_number`).then(
function (res) {
return res.json();
}
)
},
sex: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/sex`).then(
function (res) {
return res.json();
}
)
},
owner: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/owner`).then(
function (res) {
return res.json();
}
)
},
member: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/member`).then(
function (res) {
return res.json();
}
)
},
alert: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/alert`).then(
function (res) {
return res.json();
}
)
},
chat: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/chat`).then(
function (res) {
return res.json();
}
)
},
log: {
location: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/location`).then(
function (res) {
return res.json();
}
)
},
date: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/date`).then(
function (res) {
return res.json();
}
)
},
max_number: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/max_number`).then(
function (res) {
return res.json();
}
)
},
sex: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/sex`).then(
function (res) {
return res.json();
}
)
},
owner: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/owner`).then(
function (res) {
return res.json();
}
)
},
member: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/member`).then(
function (res) {
return res.json();
}
)
},
chat: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/_log/chat`).then(
function (res) {
return res.json();
}
)
}
}
},
status: {
all: function () {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/all`).then(
function (res) {
return res.json();
}
)
},
id: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}`).then(
function (res) {
return res.json();
}
)
},
process: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/process`).then(
function (res) {
return res.json();
}
)
},
share: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/share`).then(
function (res) {
return res.json();
}
)
},
owner: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/owner`).then(
function (res) {
return res.json();
}
)
},
member: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/member`).then(
function (res) {
return res.json();
}
)
},
alert: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/alert`).then(
function (res) {
return res.json();
}
)
},
log: {
process: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/process`).then(
function (res) {
return res.json();
}
)
},
share: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/share`).then(
function (res) {
return res.json();
}
)
},
owner: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/owner`).then(
function (res) {
return res.json();
}
)
},
member: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/member`).then(
function (res) {
return res.json();
}
)
},
alert: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${id}/_log/alert`).then(
function (res) {
return res.json();
}
)
}
}
},
history: {
id: function (id) {
return fetch(`http://localhost:5000/share-we-go-project/us-central1/api/history/${id}`).then(
function (res) {
return res.json();
}
)
},
}
}
export const d = {
share: {
id: function (id, uid, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/member`, {
method: 'delete',
headers: { 'Content-Type': 'application/json' },
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
share_id: "",
uid: id,
value: "false"
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
share_id: "",
uid: id,
value: "false"
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/_log/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: {
share_id: "",
uid: id,
value: "false"
},
date: date
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/_log/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: {
share_id: "",
uid: id,
value: "false"
},
date: date
})
});
// window.location.reload();
},
member: function (id, uid, date) {
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/share/${id}/member/${uid}`, {
method: 'delete',
headers: { 'Content-Type': 'application/json' },
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
share_id: "",
uid: id,
value: "false"
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
share_id: "",
uid: id,
value: "false"
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/_log/owner`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: {
share_id: "",
uid: id,
value: "false"
},
date: date
})
});
fetch(`http://localhost:5000/share-we-go-project/us-central1/api/status/${uid}/_log/member`, {
mode: 'no-cors',
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
owner: {
share_id: "",
uid: id,
value: "false"
},
date: date
})
});
// window.location.reload();
},
}
}
|
var myNum = parseInt(prompt("Enter a number"));
switch (myNum) {
case 1:
console.log(1);
break;
case 2:
console.log(2);
break;
case 3:
console.log(3);
break;
case 4:
console.log(4);
break;
case 5:
console.log(5);
break;
}
|
$(document).on("submit", "form", function (event) { // kada je submitovana forma za kreiranje novog zaposlenog
event.preventDefault();
var namee = $("#namee").val();
var lastName = $("#lastName").val();
var password = $("#password").val();
var adress = $("#adress").val();
var email = $("#email").val();
var city = $("#city").val();
var country = $("#country").val();
var phoneNumber = $("#phoneNumber").val();
var newUserJSON = formToJSON(namee,lastName, password, adress, email, city, country, phoneNumber); // pozivamo pomoćnu metodu da kreira JSON
$.ajax({
type: "POST", // HTTP metoda je POST
url: "http://localhost:8081/systemadmins/signupAdmin", // URL na koji se šalju podaci
dataType: "json", // tip povratne vrednosti
contentType: "application/json", // tip podataka koje šaljemo
data: newUserJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function () {
alert("success");
window.location.href = "adminSystemHomePage.html";
},
error: function (error) {
alert(error);
}
});
});
function formToJSON(namee,lastName, password, adress, email, city, country, phoneNumber) {
return JSON.stringify(
{
"namee": namee,
"lastName": lastName,
"password": password,
"adress": adress,
"email": email,
"city": city,
"country": country,
"phoneNumber": phoneNumber
}
);
}; |
function LoginController()
{
// bind event listeners to button clicks //
$('#retrieve-password-submit').click(function(){ $('#get-credentials-form').submit();});
$('#login #forgot-password').click(function(){
$('#cancel').html('Cancel');
$('#retrieve-password-submit').show();
$('#get-credentials').modal('show');
});
$('#login .button-rememember-me').click(function(e) {
var span = $(this).find('span');
if (span.hasClass('glyphicon-unchecked')){
span.addClass('glyphicon-ok');
span.removeClass('glyphicon-unchecked');
} else{
span.removeClass('glyphicon-ok');
span.addClass('glyphicon-unchecked');
}
});
// automatically toggle focus between the email modal window and the login form //
$('#get-credentials').on('shown.bs.modal', function(){ $('#email-tf').focus(); });
$('#get-credentials').on('hidden.bs.modal', function(){ $('#user-tf').focus(); });
} |
import React from 'react'
import { Scene, Router } from 'react-native-router-flux'
import LoginForm from './components/LoginForm'
import MovieList from './components/MovieList'
import Movie from './components/Movie'
const RouterComponent = () => (
<Router sceneStyle={{ paddingTop: 65 }}>
<Scene key='auth'>
<Scene
key='login'
component={LoginForm}
title='Please Login'
/>
</Scene>
<Scene key='main'>
<Scene
key='movieList'
component={MovieList}
title='Movies'
initial
/>
<Scene
key='movieShow'
component={Movie}
title='Movie'
/>
</Scene>
</Router>
)
export default RouterComponent
|
var filenamify = require('filenamify');
var exportPath = process.env.GATHERBASE_EXPORT_PATH || __dirname + '/../devopsbase/gathered'; // '/_crawled'
module.exports = {
port: 3000,
parallelDiscoverJobs: 2,
parallelRetrieveJobs: 3,
parallelHandleJobs: 6,
jobAttempts: 3,
removeCompletedJobs: true,
removalDelay: 1000 * 60 * 5, // 5 min
rediscovery: false,
discoverers: [
{
name: 'Chef Supermarket Discovery',
//impl: require(__dirname + '/../gatherbase-chef').ChefDiscoverer,
impl: require(__dirname + '/lib/discover/ChefDiscoverer'),
config: {
exclude: {
application_nodejs: [ '2.0.0' ],
wemux: [ '0.1.0' ],
'magento-toolbox': [ '0.0.1' ],
apache_vhosts: [ '20140108' ],
httplivestreamsegmenter: [ '0.0.2' ],
hollandbackup: [ '0.0.2' ],
zabbix_windows: [ '0.0.1' ],
windows_print: [ '0.1.0' ],
windirstat: [ '1.0.0' ],
system: [ '0.3.2' ],
serf: [ '0.1' ],
pinba: [ '0.1.0' ],
'php-box': [ '0.0.1' ],
phing: [ '0.0.1' ],
'getting-orche': [ '0.4.0' ],
'magento-toolbox': [ '0.0.1' ],
cloudpassage: [ '0.0.2' ],
application_zf: [ '0.0.3', '0.0.4', '0.0.5' ],
collectd: [ '1.0.0' ]
}
},
transform: function(jobData) {
jobData.properties.gatherbase_origin = 'chef-supermarket';
return jobData;
}
},
{
name: 'Juju Charm Store Discovery',
impl: require(__dirname + '/lib/discover/JujuDiscoverer'),
transform: function(jobData) {
jobData.properties.gatherbase_origin = 'juju-charmstore';
return jobData;
}
},
{
name: 'Ubuntu Cloud Image Discovery',
impl: require(__dirname + '/lib/discover/UbuntuDiscoverer'),
transform: function(jobData) {
jobData.properties.gatherbase_origin = 'ubuntu-cloud-image-locator';
return jobData;
}
},
{
name: 'Docker Hub Discovery',
impl: require(__dirname + '/lib/discover/DockerDiscoverer'),
transform: function(jobData) {
jobData.properties.gatherbase_origin = 'docker-hub';
return jobData;
}
}
],
handlers: [
{
name: 'Chef Handler',
impl: require(__dirname + '/lib/handle/ChefHandler'),
select: function(jobData) {
if (jobData.properties.gatherbase_origin === 'chef-supermarket') {
return 1;
}
return false;
}
},
{
name: 'String Match-based Classification',
impl: require(__dirname + '/lib/handle/StringMatchClassifier'),
select: function(jobData) { return 100; },
config: {
taxonomyKeywords: require(__dirname + '/../devopsbase/build/taxonomy_keywords.json'),
}
},
{
name: 'File Export',
impl: require(__dirname + '/lib/handle/FileExporter'),
select: function(jobData) { return 200; },
config: function(jobData) {
var c = { format: 'json' };
var dir = exportPath;
//var suffix = jobData.properties.name.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
if (jobData.properties.gatherbase_origin === 'chef-supermarket') {
c.path = dir + '/chef_supermarket/' + filenamify(jobData.properties.chef_cookbook_name); //suffix.substr(0, 3) + '.yml';
} else if (jobData.properties.gatherbase_origin === 'juju-charmstore') {
c.path = dir + '/juju_charmstore/' + filenamify(jobData.properties.juju_charm_name);
} else if (jobData.properties.gatherbase_origin === 'ubuntu-cloud-image-locator') {
c.path = dir + '/ubuntu/' + filenamify(jobData.properties.ubuntu_image_provider);
} else if (jobData.properties.gatherbase_origin === 'docker-hub') {
c.path = dir + '/docker_hub/' + filenamify(jobData.properties.docker_name);
} else {
c.path = dir + '/others';
}
c.path += '__' + filenamify(jobData.properties.revision);
if (jobData.properties.latest) c.path += '__latest';
c.path += '.' + c.format;
return c;
}
}
],
retriever: { //TODO: allow inclusion of custom retrievers to support proprietary protocols; use select functions as used for handlers
destination: __dirname + '/_temp'
},
/*status: {
redis: {
db: 5
}
},*/
queue: {
prefix: 'gatherbase',
disableSearch: false,
redis: {
port: 6379,
host: '127.0.0.1',
//auth: 'password',
db: 3,
options: {
// https://github.com/mranney/node_redis
}
}
}
}
|
import React, { useEffect } from 'react'
import Link from 'next/link'
import styled from 'styled-components'
import { ReactSVG } from 'react-svg'
import { useRouter } from 'next/router'
import Images from '../../theme/Images'
import { useAuth } from '../../context/useAuth'
import { Menu, Layout, Dropdown, Avatar } from 'antd'
import { UserOutlined, LogoutOutlined } from '@ant-design/icons'
const links = [
{
label: 'Предметы',
url: '/subjects',
iconUrl: '',
dot: false,
allowedUsers: ['user', 'admin']
},
{
label: 'Форум',
url: '/forms',
iconUrl: '',
dot: false,
allowedUsers: ['user', 'admin']
},
{
label: 'Блог',
url: '/posts',
iconUrl: '',
dot: false,
allowedUsers: ['user', 'admin']
}
]
const RigthColumn = styled.div``
const MainContainer = styled.div`
display: flex;
`
const MainLogo = styled.div`
float: left;
line-height: 20px;
padding: 20px;
color: #71bd65;
font-size: 30px;
`
const MenuItam = styled.div`
padding: 0px 6px 0px 6px;
margin-right: 20px;
border-bottom-color: transparent;
cursor: pointer;
${p =>
p.selected &&
`
background: #71bd65;
`};
`
const MenuItemText = styled.p`
color: #000;
${p =>
!p.selected &&
`:hover {color: #71bd65;
}`};
${p =>
p.selected &&
`
color: #fff;
`};
`
function MainMenu() {
const router = useRouter()
const { user, logout } = useAuth()
const { checkUserIsLoggedIn } = useAuth()
useEffect(() => {
if (!checkUserIsLoggedIn()) {
router.push('/login')
}
}, [])
const linksByRole = links.filter(
link => user && link.allowedUsers.includes(user.role)
)
const renderLinks = pathname => {
return linksByRole.map(({ url, label }) => (
<Link
key={label}
href={{
pathname: url,
query: {},
shallow: true
}}
passHref
>
<MenuItam selected={url === pathname}>
<MenuItemText selected={url === pathname}>{label}</MenuItemText>
</MenuItam>
</Link>
))
}
const menu = (
<Menu>
<Menu.Item
key="0"
onClick={() => {
router.push({ pathname: '/profile', query: {} })
}}
>
<UserOutlined /> Профиль
</Menu.Item>
<Menu.Divider />
<Menu.Item key="1" onClick={() => logout()}>
<LogoutOutlined /> Выйти
</Menu.Item>
</Menu>
)
return (
<Layout.Header
style={{
display: 'flex',
justifyContent: 'space-between',
background: '#fff',
borderBottom: '1px solid rgba(0, 0, 0, 0.25)'
}}
>
<MainLogo>ProEnt</MainLogo>
<MainContainer>{renderLinks(router.pathname)}</MainContainer>
{user && user.username ? (
<Dropdown overlay={menu}>
<RigthColumn>
<Avatar icon={<UserOutlined />} />
</RigthColumn>
</Dropdown>
) : (
<RigthColumn>
<div onClick={() => logout()} style={{ color: '#333333' }}>
<LogoutOutlined /> Выйти
</div>
</RigthColumn>
)}
</Layout.Header>
)
}
export default MainMenu
|
function multiplyNumeric(obj){
for (let prop in obj){
if(typeof obj[prop] == "number"){
obj[prop] = obj[prop] * 2;
}
}
}
// before the call
let menu = {
width: 200,
height: 300,
title: "My menu"
};
multiplyNumeric(menu);
// after the call
menu = {
width: 400,
height: 600,
title: "My menu"
};
|
import React from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { routerActions } from 'react-router-redux'
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from 'material-ui/styles';
import { bknActions } from '../modules/bukken'
import Drawer from 'material-ui/Drawer';
import AppBar from 'material-ui/AppBar';
import Tabs, { Tab } from 'material-ui/Tabs';
import Toolbar from 'material-ui/Toolbar';
import IconButton from 'material-ui/IconButton';
import Divider from 'material-ui/Divider';
import Paper from 'material-ui/Paper';
import Typography from 'material-ui/Typography';
import MoreVertIcon from 'material-ui-icons/MoreVert';
import MainMenu from '../components/main_menu'
import { ConnectedKtpht } from './ktpht';
import { contextPath } from '../config'
const drawerWidth = 240;
const bknStyles = theme => ({
root: {
width: '100%',
minHeight: '100vh',
margin: 0,
zIndex: 1,
overflow: 'hidden',
padding:0,
},
flex: {
flex: 1,
},
appFrame: {
position: 'relative',
display: 'flex',
width: '100%',
//height: '100%',
},
appBar: {
position: 'fixed',
top: 0,
left: 'auto',
right: 0,
width: `calc(100% - ${drawerWidth}px)`,
// backgroundColor: theme.primary[500],
},
'appBar-left': {
marginLeft: drawerWidth,
},
menuButton: {
},
drawerDocked: {
width: drawerWidth,
},
drawerPaper: {
width: drawerWidth,
height: '100%',
display: 'flex',
flex: '1 0 auto',
position: 'fixed',
top: 0,
},
drawerHeader: {
backgroundColor: theme.palette.primary[500],
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
padding: '0 8px',
...theme.mixins.toolbar,
},
drawerHeaderText: {
color: theme.palette.common.white,
},
submenu: {
backgroundColor: theme.palette.common.white,
height: 48,
position: 'fixed',
width: `calc(100% - ${drawerWidth}px)`,
zIndex: 1000,
},
content: {
flex: '1 1 100%',
margin: '0 auto',
backgroundColor: theme.palette.background.defaults,
width: `calc(100% - ${drawerWidth}px)`,
height: '100%',
//marginTop: 56,
[theme.breakpoints.up('sm')]: {
height: 'calc(100% - 64px)',
marginTop: 64,
},
},
contentContainer: {
display: 'flex',
minHeight: '100vh',
width: '100%',
alignItems: 'stretch'
},
});
function TabContainer(props) {
return (
<Typography component="div" style={{ marginTop: 48, padding: 8 * 2 }}>
{props.children}
</Typography>
);
}
class BknContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
anchor: 'left',
};
}
componentWillMount() {
this.props.onInit();
};
handleChange = event => {
this.setState({
anchor: event.target.value,
});
};
render() {
const { classes } = this.props;
const { anchor } = this.state;
const drawer = (
<Drawer
type="permanent"
className={classes.drawerDocked}
classes={{
paper: classes.drawerPaper,
}}
anchor={anchor}
>
<div className={classes.drawerHeader}>
<Typography className={classes.drawerHeaderText} type="body1" gutterBottom align="left">施工管理システム かん助</Typography>
<Typography className={classes.drawerHeaderText} type="caption" gutterBottom align="left">v.2.0.0</Typography>
</div>
<Divider />
<Divider />
<MainMenu />
</Drawer>
);
let leftDrawer = drawer;
let kinoContent = null;
if (this.props.match.params.kinoId === 'ktpht') {
kinoContent = <ConnectedKtpht />
}
let bknId = this.props.bknId;
return (
<div className={classes.root}>
<div className={classes.appFrame}>
<AppBar className={classNames(classes.appBar, classes[`appBar-${anchor}`])}>
<Toolbar>
<Typography type="title" color="inherit" noWrap className={classes.flex}>
{this.props.bknName}
</Typography>
<IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
<MoreVertIcon />
</IconButton>
</Toolbar>
</AppBar>
<div className={classes.contentContainer}>
{leftDrawer}
<main className={classes.content}>
<Paper className={classes.submenu}
elevation={4}
square={true}>
<Tabs value={1}
textColor="primary"
scrollable
scrollButtons="auto"
>
<Tab label="シート一覧" href={`${contextPath}/buken/${bknId}/kotei/`}/>
<Tab label="工程写真管理" />
<Tab label="画像管理" />
<Tab label="図書管理" />
<Tab label="掲示板" />
<Tab label="使用量" href="http://www.google.co.jp" />
<Tab label="物件設定" />
</Tabs>
</Paper>
<TabContainer>{kinoContent}</TabContainer>
</main>
</div>
</div>
</div>
);
}
}
BknContainer.propTypes = {
classes: PropTypes.object.isRequired,
};
// Container Component
export const ConnectedBknContainer = connect(
// mapStateToProps
state => ({
...state.bkn
}),
// mapDispatchToProps
(dispatch) => ({ dispatch }),
// mergeProps
(stateProps, dispatchProps, ownProps) => {
const dispatch = dispatchProps.dispatch;
return Object.assign({}, ownProps, stateProps, {
routerActions: bindActionCreators(Object.assign({}, routerActions), dispatch),
onInit: () => {
dispatch(bknActions.select(ownProps.match.params.bknId));
}
});
}
)(withStyles(bknStyles)(BknContainer));
|
"use strict";
const Car = require('../models').Car;
exports.list = function (req, res) {
Car.findAll().then(Car => {
res.jsonp(Car);
});
};
exports.create = function (req, res) {
res.jsonp(Car.create(req.body));
};
exports.findById = function (req, res) {
let id = req.params.id;
Car.findById(id).then(Car => {
res.jsonp(Car);
});
};
exports.update = function (req, res) {
let id = req.params.id;
Car.findById(id).then(Car => {
Car.update(req.body);
});
res.jsonp(Car);
};
exports.delete = function (req, res) {
let id = req.params.id;
Car.findById(req.params.id)
.then(Car => {
if (!Car) {
return res.status(400).send({
message: 'Car Not Found',
});
}
return Car
.destroy()
.then(() => res.status(204).send())
.catch(error => res.status(400).send(error));
})
.catch(error => res.status(400).send(error));
}; |
/* **********************************************************
* File: test/components/App.spec.js
*
* Brief: Test for the app component
*
* Authors: George Whitfield, Craig Cheney
*
* 2017.10.12 CC - Refactored for App container
* 2017.07.28 GW - Document Created
*
********************************************************* */
import React from 'react';
import { shallow } from 'enzyme';
import App from '../../app/components/App';
const app = shallow(<App />);
/* Test suite */
describe('App', () => {
it('Renders one App', () => {
expect(app).toHaveLength(1);
});
it('Contains a header', () => {
const header = app.find('Header');
expect(header).toBeDefined();
});
});
/* [] - END OF FILE */
|
import configureContainer from '../../container';
function makeDeliveryLambdaGetJobKeyByGuid({ getJobKeyByGuid, getLogger }) {
return async function delivery(input) {
const { jobGuid } = input;
const logger = getLogger();
logger.addContext('guid', jobGuid);
logger.addContext('input', input);
logger.debug('start');
const jobKey = await getJobKeyByGuid(jobGuid);
return {
jobStatic: {
key: jobKey,
},
};
};
}
export const delivery = configureContainer().build(makeDeliveryLambdaGetJobKeyByGuid);
|
import React from 'react'
import PropTypes from 'prop-types'
import {translateError} from '../../../locales/translate'
export const FieldError = (props) => {
const { locale, isWarning, error } = props
if (!error) {
return null
}
return <div className={isWarning ? 'warning' : 'error'}>{translateError(error, locale)}</div>
}
FieldError.propTypes = {
error: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
]),
isWarning: PropTypes.bool,
locale: PropTypes.string
}
|
import ChordParser from './parser';
import InputOutput from './io';
import _ from 'lodash';
class ChordSage {
constructor() {
this.config = {
freeStrings: ['E', 'A', 'D', 'G', 'B', 'E'],
fretSpread: 4,
fretPosition: 1,
chordInput: 'Dmaj7/F#'
};
this.parser = new ChordParser(this.config);
this.io = new InputOutput(this.parser);
this.setupInput();
var that = this;
_.each(this.config, function (value, key) {
let input = document.getElementById(key);
if (input) {
input.value = value;
if (key === 'chordInput') that.onInputChange(value);
}
});
}
setupInput() {
this.io.bindEvent('chordInput', 'input', (value) => {
this.onInputChange(value);
});
this.io.bindEvent('fretSpread', 'change', (value) => {
this.config.fretSpread = value;
this.onInputChange();
});
this.io.setValue('curPosition', this.config.fretPosition);
this.io.bindEvent('posHigher', 'click', () => {
if (this.config.fretPosition < 22) this.config.fretPosition++;
this.io.setValue('curPosition', this.config.fretPosition);
this.onInputChange();
});
this.io.bindEvent('posLower', 'click', () => {
if (this.config.fretPosition > 1) this.config.fretPosition--;
this.io.setValue('curPosition', this.config.fretPosition);
this.onInputChange();
});
}
onInputChange(value) {
let result = value === undefined ? this.parser.reparse() : this.parser.parse(value);
if (result === true) {
this.io.setValue('result', this.parser.toString());
this.io.draw(this.parser.getModel());
this.io.play(this.parser.getModel());
} else {
this.io.setValue('result', "What? " + result);
this.io.draw(null);
}
}
}
export default ChordSage;
|
var app = new Vue({
el: '#app',
data: {
list: ['apple', 'banna', 'strovery'],
}
});
|
import Container from './styles'
import {FontAwesomeIcon as Icon} from '@fortawesome/react-fontawesome'
import search from '@fortawesome/fontawesome-free-solid/faSearch'
export default ({onChange}) => (
<Container>
<input type="text" placeholder="Search" onChange={onChange} />
<Icon icon={search} />
</Container>
)
|
import React, { Component } from "react";
import _ from "lodash";
import {
Control,
Field,
Input,
Label,
Textarea,
Select,
Option
} from "react-bulma-components/lib/components/form";
import { withRouter } from "react-router-dom";
import Loader from "../Loader/index";
import generateUUID from "../../utils/generateUUID";
import { Button, Card, Content } from "react-bulma-components";
class FeedbackForm extends Component {
state = {
questions: [],
feedbacks: [],
submittedAnswer: "",
loading: true
};
componentDidMount = async () => {
console.log(this.props)
this.loadQuestions();
this.loadFeedbacks();
};
loadFeedbacks = async () => {
const { userSession,match,username } = this.props;
const options = {
decrypt: false
};
try{
let result = await userSession.getFile(
`feedback-${match.params.post_id}.json`,
options
);
if(result){
this.setState({
feedbacks: JSON.parse(result)
});
}
}catch(e){
console.log(e.message)
}
}
loadQuestions = async () => {
const { userSession } = this.props;
const options = {
decrypt: false
};
try {
const result = await userSession.getFile(`questions.json`, options);
if (result) {
this.setState({
questions: JSON.parse(result)
});
const { questions } = this.state;
var questionFeedback = questions;
_.forEach(questionFeedback, (question, index) => {
question.submittedAnswer = "";
});
this.setState({
questions: questionFeedback,
loading: false
});
}
} catch (e) {
console.log(e.message);
}
};
onChange = (question, e) => {
question.question[e.target.name] = e.target.value;
this.setState({
[e.target.name]: e.target.value
});
};
addFeedback = async () => {
const { userSession, match, username } = this.props;
const options = {
encrypt: false
};
const id = generateUUID();
console.log(this.props)
const { history } = this.props;
const { questions, feedbacks } = this.state;
const userId = match.params.post_id;
const timestamp = new Date().getTime();
console.log(userId)
console.log(timestamp)
const params = {
id,
userId,
timestamp,
username,
...questions
};
try {
if(feedbacks.length>0){
console.log("going into this")
let result = await userSession.putFile(
`feedback-${match.params.post_id}.json`,
JSON.stringify([...feedbacks,params]),
options
);
}else{
console.log("going out")
let result = await userSession.putFile(
`feedback-${match.params.post_id}.json`,
JSON.stringify([feedbacks,params]),
options
);
}
this.setState({
submittedAnswer : ''
}, history.push(`/admin/${username}/users`))
} catch (e) {
console.log(e.message);
}
};
onSubmit = e => {
e.preventDefault();
// const { type } = this.props;
this.addFeedback();
// return type === 'edit' ? this.editPost() : this.createPost()
};
render() {
const { questions, loading } = this.state;
if (loading) {
return <Loader />;
}
return (
<form onSubmit={this.onSubmit} className="feedback-form">
<Field>
{_.map(questions, (question, index) => {
if (question.id) {
return (
<div key={question.id}>
<Label>
Question-{index}:{question.question}
</Label>
<Input
name="submittedAnswer"
onChange={e => this.onChange({ question }, e)}
placeholder="Review your answer between 1-10"
value={question.submittedAnswer}
/>
</div>
);
}
})}
</Field>
<Field kind="group">
<Control>
<Button>Cancel</Button>
</Control>
<Control>
<Button color="link" type="submit">
Submit
</Button>
</Control>
</Field>
</form>
);
}
}
export default withRouter(FeedbackForm);
|
'use strict';
const {packRes, packError } = require("../libs/utils");
const hello = async (event) => {
try {
const obj = [{
message: 'Go Serverless v1.1! Your function executed successfully!',
input: event
}];
return packRes(...obj);
} catch (err) {
packError(err, "helloError");
}
};
module.exports = {
hello
} |
const request = require('request-promise-native');
const { INTEGRATION_TESTS } = require('../../resources/envs/local');
class HTTPService {
constructor() {
/**
* Generates an option object used by the request package
* @param {*} app the targeted app object
*/
const generateOption = (app) => {
const opt = {
// Build the uri to request our own api
uri: `${app.PROTOCOL}://${app.HOST}:${app.PORT}/`,
rejectUnauthorized: false,
};
return opt;
};
this.options = generateOption(INTEGRATION_TESTS);
}
/**
* get All records
* @returns {Promise<*>} the sent request to the server
*/
getAllParkings() {
return request.get(this.options);
}
/**
* get record by ID
* @param {*} recordid the id of the requested record
* @returns {Promise<*>} the sent request to the server
*/
getParkingByRecordID(recordid) {
const { ...option } = this.options;
option.uri += INTEGRATION_TESTS.PARAM;
option.uri += recordid;
return request.get(option);
}
}
module.exports = HTTPService;
|
var _ = {
chunk(arr, quantity = 1) {
var outputArrays,
arrLength = arr.length,
inc = function() {
var counter = quantity;
if (quantity === arrLength) {
counter = 1;
} else if (quantity === 0 || quantity === 1) {
counter = arrLength;
}
return counter;
}();
if (quantity <= 1) {
outputArrays = arr;
} else {
outputArrays = [];
for (var i = 0; i < arrLength; i += inc) {
outputArrays.push(arr.splice(0, quantity));
}
}
return outputArrays;
},
compact(arr) {
return arr.filter((elem) => {
return !!elem;
})
},
first(arr) {
return arr.length ? arr.slice(0, 1) : undefined;
},
difference(arrToInspect, excludeItems) {
},
drop(arr, quantity = 1) {
var _l = arr.length;
return quantity > _l ? [] : arr.slice(-(_l - quantity));
},
dropRight(arr, quantity = 1) {
var _l = arr.length;
return quantity > _l ? [] : arr.reverse().slice(-(_l - quantity)).reverse();
},
fill(arr, value, start = 0, end = arr.length) {
}
};
var array = [1, 2, 3];
_.fill(array, 'a');
console.log(array);
// → ['a', 'a', 'a']
_.fill(Array(3), 2);
// → [2, 2, 2]
_.fill([4, 6, 8], '*', 1, 2);
// → [4, '*', 8] |
//deployed version under Grozeries private credentials here:
//export const baseUrl = 'https://grozeries.herokuapp.com'
//mind that this DB is currently empty.
//see login credentials sheet for heroku creds.
export const baseUrl = 'https://grozeries3.herokuapp.com'
//export const baseUrl = 'http://localhost:4000'
export const localStorageJwtKey = 'currentUserJwt'
export const lsUserId = 'currentUserId' |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
// import Vue from 'vue'
// import Vue from 'https://unpkg.com/vue'
// import App from './App'
var $ = require('jquery')
window.jQuery = $
var jQuery = $ // eslint-disable-line
import gsGrid from './Table'
import gsContact from '../components/Contact'
import gsFooter from '../components/Footer'
import loadmore from '@/components/Loadmore'
import '../assets/css/gs.common.css'
import gsDialog from '@/components/Dialog'
import {debugAjaxError, getCookie, blue03emMsg, setCookie, stringFormat, QueryData, isWX} from '@/util' // eslint-disable-line
import {pagination} from '@/jquery.pagination' // eslint-disable-line
import Vue from 'vue'
// import Paginate from 'vuejs-paginate'
// Vue.component('paginate', Paginate)
// import vsPage from 'v-page'
// import '/static/js/jquery.pagination.js'
/* global DEBUG_GS */
// Vue.config.productionTip = false
// var apiURL = 'http://localhost:8888'
// var apiURL = ''
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { gsGrid, gsContact, gsFooter, gsDialog, loadmore },
data: {
dtlBuyer: '',
dtlGridColumns: ['起运港', '提单日期', '毛重(吨)', '数量', '单位', '商品'],
dtlGridData: [],
gridColumns: ['采购商', '起运港', '提单日期', '货量', '商品'],
gridData: [],
goods: 'AIR',
highLightText: '',
order: 'def',
orderEntry: [{'value':'def', 'label':'默认'},
{'value':'teu', 'label':'按货量排序'},
{'value':'date', 'label':'按提单日期排序'}],
portOpt: 'def',
portOptEntry: [{'value':'def', 'label':'默认'},
{'value':'inclcn', 'label':'包含中国港口'},
{'value':'onlycn', 'label':'只查询中国港口'},
{'value':'spec', 'label':'指定港口'}],
port: '',
buyerPage: 0,
openId: '',
blQueryPoints: '',
t_bl_user_query_opt: undefined,
pointNeededForOrder: 0,
pointNeededForPort:0,
stage: 1,
STAGE_LIST: 1,
STAGE_DETAIL: 2,
infoMsg: '',
infoBtnName: '知道了',
infoCloseEventId: 0,
btnCount: 1,
pageSet: {
totalRow: 0, // required option
language: 'en', // default: 'cn'
pageSizeMenu: [20, 100] // default: [10, 20, 50, 100]
},
loading: false
},
watch: {
order: function () {
var self = this
if (self.order === 'def') {
self.pointNeededForOrder = self.blQueryPoints.orderDef
} else if (self.order === 'teu') {
self.pointNeededForOrder = self.blQueryPoints.orderTeu
} else if (self.order === 'date') {
self.pointNeededForOrder = self.blQueryPoints.orderDate
}
},
portOpt: function () {
var self = this
if (self.portOpt === 'def') {
self.pointNeededForPort = self.blQueryPoints.portDef
} else if (self.portOpt === 'inclcn') {
self.pointNeededForPort = self.blQueryPoints.portInclCn
} else if (self.portOpt === 'onlycn') {
self.pointNeededForPort = self.blQueryPoints.portOnlyCn
} else if (self.portOpt === 'spec') {
self.pointNeededForPort = self.blQueryPoints.portSpecified
}
}
},
created: function () {
var self = this
if (!isWX && !DEBUG_GS) {
window.location.href = '/wechat/information.html?msg=inWechat'
} else {
self.ajaxGetOpenId()
self.ajaxGetQueryPoints()
}
},
mounted: function () {
$.fn.pagination = pagination
// this.showPagination(103, 3)
},
methods: {
ajaxGetOpenId: function () {
var self = this
if (!self.openId) {
var queryParm = new QueryData(location.search, false)
var oid = getCookie('oid')
// self.showInfo('oid=' + oid)
$.ajax({
url: '/location/getopenid',
type: 'POST',
dataType: 'json',
contentType:'application/json',
data: JSON.stringify({"code": queryParm['code'], 'state': queryParm['state']}), // eslint-disable-line
success: function (data) {
if (data.code === '0') {
self.openId = data.result.openid
if (oid !== self.openId) {
oid = self.openId
setCookie('oid', oid)
}
// self.showInfo('success: oid=' + oid)
} else { // cannot get the open ID from WX, then use the one in cookie
if (DEBUG_GS) {
console.log(data)
}
self.openId = oid
// self.showInfo('failed: oid=' + oid)
}
self.ajaxGetUserQueryOpt()
},
error: debugAjaxError
})
}
},
ajaxGetUserQueryOpt: function () {
var self = this
$.ajax({
url: '/location/getUserQueryOpt',
type: 'POST',
dataType: 'json',
contentType:'application/json',
data: JSON.stringify({"openId": self.openId}), // eslint-disable-line
success: function (data) {
if (data.code === '0') {
self.t_bl_user_query_opt = data.result
} else {
if (DEBUG_GS) {
console.log(data)
}
}
},
error: debugAjaxError
})
},
ajaxGetQueryPoints: function () {
var self = this
$.ajax({
url: '/static/conf/bl_query_points.json',
type: 'GET',
dataType: 'json',
data: null,
success: function (data) {
self.blQueryPoints = data
},
error: debugAjaxError
})
},
buyerList: function () {
var self = this
// clear data
self.gridData = []
$('#listPagination').empty()
self.highLightText = self.goods
self.ajaxGetBuyerList(true)
},
buyerListGetPage: function (page_index, jq) {
this.ajaxGetBuyerList(false, page_index)
},
ajaxGetBuyerList: function (firstQuery, page) {
var self = this
if (firstQuery) {
self.buyerPage = 0
} else {
self.buyerPage = page
}
$.ajax({
url: '/location/blQueryList',
type: 'POST',
dataType: 'json',
contentType:'application/json',
data: JSON.stringify({"openId": self.openId,"goods": self.goods,"order": self.order,"portOpt": self.portOpt,"port": self.port,"page": self.buyerPage}), // eslint-disable-line
success: function (data) {
self.loading = false
if (data.code === '0') {
// list data
// var reg = new RegExp(self.highLightText, 'gi')
self.gridData = []
for (var i in data.result) {
var row = data.result[i]
var x = []
x.push(row.importername)
x.push(row.portofshipment)
x.push(row.latestbillofladingdateStr)
x.push(row.containercount)
// x.push(row.goodsdescription.replace(reg, '<span style="background: #ffff00;">$&</span>'))
x.push(row.goodsdescription)
self.gridData.push(x)
}
if (firstQuery) {
// pagination
if (data.totalPages > 1) {
self.showListPagination(data.totalPages, self.buyerPage)
}
}
} else {
self.ajaxFailed(data)
}
},
error: debugAjaxError
})
self.loading = true
},
showListPagination: function (totalPage, currentPage) {
var self = this
var page = $('#listPagination')
page.pagination(totalPage, {
current_page: currentPage,
num_edge_entries: 1, // 边缘页数
num_display_entries: 5, // 主体页数
callback: self.buyerListGetPage,
items_per_page: 1, // 每页显示1项
prev_text: '',
next_text: ''
})
},
buyerDtl: function (evtId, buyer) {
var self = this
self.stage = self.STAGE_DETAIL
self.dtlBuyer = buyer
$('#dtlPagination').empty()
self.dtlGridData = []
self.ajaxGetBuyerDetail(true, 0, self.dtlBuyer)
},
buyerDtlGetPage: function (page_index, jq) {
this.ajaxGetBuyerDetail(false, page_index, this.dtlBuyer)
},
ajaxGetBuyerDetail: function (firstQuery, page, buyer) {
var self = this
if (firstQuery) {
page = 0
}
$.ajax({
url: '/location/blQueryDetail',
type: 'POST',
dataType: 'json',
contentType:'application/json',
data: JSON.stringify({"openId": self.openId,"goods": self.goods,"order": self.order,"portOpt": self.portOpt,"port": self.port,"page": page, "buyer": buyer.substring(0, 18)}), // eslint-disable-line
success: function (data) {
self.loading = false
if (data.code === '0') {
self.dtlGridData = []
for (var i in data.result) {
var row = data.result[i]
var x = []
// dtlGridColumns: ['起运港', '提单日期', '毛重', '数量', '单位', '商品'],
x.push(row.portofshipment)
x.push(row.billofladingdatestr)
x.push(row.grossweight)
x.push(row.number)
x.push(row.unit)
x.push(row.goodsdescription)
self.dtlGridData.push(x)
}
if (firstQuery) {
// pagination
if (data.totalPages > 1) {
self.showDtlPagination(data.totalPages, page)
}
}
} else {
self.ajaxFailed(data)
}
},
error: debugAjaxError
})
self.loading = true
},
showDtlPagination: function (totalPage, currentPage) {
var self = this
var page = $('#dtlPagination')
page.pagination(totalPage, {
current_page: currentPage,
num_edge_entries: 1, // 边缘页数
num_display_entries: 5, // 主体页数
callback: self.buyerDtlGetPage,
items_per_page: 1, // 每页显示1项
prev_text: '',
next_text: ''
})
},
showInfo: function (key) {
var self = this
var msg = key
var pointTemplate = '{0}: <span style="color:#ff0000;">{1}</span> 积分<br>'
if (key === 'order') {
if (self.blQueryPoints !== '') {
msg = stringFormat(pointTemplate, self.orderEntry[0].label, self.blQueryPoints.orderDef)
msg = msg + stringFormat(pointTemplate, self.orderEntry[1].label, self.blQueryPoints.orderTeu)
msg = msg + stringFormat(pointTemplate, self.orderEntry[2].label, self.blQueryPoints.orderDate)
}
} else if (key === 'port') {
if (self.blQueryPoints !== '') {
msg = stringFormat(pointTemplate, self.portOptEntry[0].label, self.blQueryPoints.portDef)
msg = msg + stringFormat(pointTemplate, self.portOptEntry[1].label, self.blQueryPoints.portInclCn)
msg = msg + stringFormat(pointTemplate, self.portOptEntry[2].label, self.blQueryPoints.portOnlyCn)
msg = msg + stringFormat(pointTemplate, self.portOptEntry[3].label, self.blQueryPoints.portSpecified)
}
} else if (key === 'dtl') {
if (self.blQueryPoints !== '') {
msg = stringFormat(pointTemplate, '查看采购商', self.blQueryPoints.buyerDetail)
}
}
self.infoMsg = msg
},
resetInfo: function () {
var self = this
self.infoBtnName = '知道了'
self.infoCloseEventId = 0
self.btnCount = 1
},
onInfoClose: function (eventId) {
var self = this
if (eventId === 99) {
self.resetInfo()
self.showInfo(self.getPointRules())
}
},
getPointRules: function () {
var msg = '积分规则<br>'
msg = msg + '<div class="left">'
msg = msg + '1. 使用本站优惠券购物后,发送淘宝订单号到本公众号,可得积分(订单金额1元=1积分)。<br>'
msg = msg + '2. 联系微信号' + blue03emMsg('www_GrowSmilingly_cn') + '(可扫描二维码加好友)进行人工充值(1元=10积分)。'
msg = msg + '</div>'
msg = msg + '<img src="/static/img/wx_gs_name_card.jpg">'
return msg
},
ajaxFailed: function (data) {
var self = this
if (DEBUG_GS) {
console.log(data)
}
if (data.code === '30001') {
self.infoBtnName = '积分规则'
self.infoCloseEventId = 99
self.btnCount = 2
self.showInfo(data.description)
self.ajaxGetUserQueryOpt()
} else if (data.code === '10005') {
self.showInfo('找不到符合条件的记录。请输入完整的英文单词,如:' + blue03emMsg('COOL') + '是查不到' + blue03emMsg('COOLER') + '的记录的, 必须输入' + blue03emMsg('COOLER') + '才能查到。')
}
}
}
})
|
const Promise = require('bluebird');
const models = require('../../models');
// const obtainInformation = require('./obtainInformation');
const Sequelize = require('sequelize');
var { sequelize } = models;
const eventMethods = {};
const Op = Sequelize.Op;
eventMethods.setPreference = function(){
return new Promise((resolve,reject) => {
models.Event.findAll({
raw : true
})
.then(res => {
if(res.length == 0){
models.Event.create({flag : 1})
.then(re => {
resolve(re)
})
.catch(er => {
reject(er)
})
}
else{
models.Event.update({flag : 1},{
where : {
flag : 0
}
})
.then(re => {
resolve(re)
})
.catch(er => {
resolve(er)
})
}
})
.catch(err => {
reject(err)
})
})
}
eventMethods.unsetPreference = function(){
return new Promise((resolve,reject) => {
models.Event.findAll({
raw : true
})
.then(res => {
if(res.length == 0){
models.Event.create({flag : 0})
.then(re => {
resolve(re)
})
.catch(er => {
reject(er)
})
}
else{
models.Event.update({flag : 0},{
where : {
flag : 1
}
})
.then(re => {
resolve(re)
})
.catch(er => {
resolve(er)
})
}
})
.catch(err => {
reject(err)
})
})
}
module.exports = eventMethods
|
/**
* Created by elie.
*/
/**
* Create one stacked histogram, with zoom, resize, transition and popup features.
* @param div {Object} D3 encapsulated parent div element.
* @param svg {Object} D3 encapsulated parent svg element, direct child of div parameter.
* @param mydiv {String} Div identifier.
* @param urlJson {String} Url to request the data to the server.
*/
function createHisto2DStackSimple(div,svg,mydiv, urlJson){
d3.json(urlJson, function (error, json) {
svg.margin.left = 50;
svg.margin.right = 50;
console.log(json);
//test json conformity
if (testJson(json) || error) {
console.log("incorrect url/data");
noData(div, svg,mydiv, error?error:json&&json.response&&json.response.data&&json.response.data.length === 0?
"No data to display for the given interval":json&&json.response&&json.response.errMsg?json.response.errMsg:"error result conformity");
return false;
}
//json ok, graph creation
//table for legend
svg.tableWidth = 200;
var clientRect = div.node().getBoundingClientRect();
var divWidth = Math.max(1.15 * svg.tableWidth + svg.margin.left + svg.margin.right + 1, clientRect.width),
divHeight = Math.max(svg.margin.bottom + svg.margin.top + svg.margin.zero + 1, clientRect.height);
svg.attr("width", divWidth - 1.15 * svg.tableWidth).attr("height", divHeight);
svg.width = divWidth - 1.15 * svg.tableWidth - svg.margin.left - svg.margin.right;
svg.height = divHeight - svg.margin.bottom - svg.margin.top;
svg.x = d3.scaleLinear()
.range([0, svg.width]);
svg.y = d3.scaleLinear().clamp(true);
svg.svg = svg.append("svg").attr("x", svg.margin.left).attr("y", svg.margin.top).attr("width", svg.width).attr("height", svg.height).classed("crisp",true);
svg.grid = svg.svg.append("g").classed("grid", true);
//Will contain the chart itself, without the axis
svg.chart = svg.svg.append("g");
//Will contain the axis and the rectselec, for a better display of scaling
svg.frame = svg.svg.append("g");
svg.selec = svg.frame.append("rect").attr("class", "rectSelec");
json = json.response;
var jsonData = json.data;
var jsonContent = json.content;
console.log(json);
var contentItemValue = searchItemValue(jsonContent);
var contentDateValue = searchDateValue(jsonContent);
var contentAmountValue = searchAmountValue(jsonContent);
//optional display value for legend, no guaranty on uniqueness/existence.
var contentDisplayValue = searchDisplayValue(jsonContent);
//if no display value, then the display value is the item value.
if (contentDisplayValue === false){
contentDisplayValue = contentItemValue;
}
//if no item/date/amount value found, the graph can't be done.
if(contentItemValue === false || contentDateValue === false || contentAmountValue === false){
noData(div,svg,mydiv, "error no value found");
return;
}
//Now, no more nodata can happen,so we create the table
var divtable = div.append("div").classed("diagram divtable", true);
divtable.append("h4").classed("tableTitle", true).text("Legend");
var table = divtable.append("table").classed("diagram font2 tableLegend", true).style("width", svg.tableWidth + "px").style("max-height",
(divHeight - 2 * parseInt(div.style("font-size"),10) - 60) + "px");
svg.units = unitsStringProcessing(json.units);
svg.values = [];
var dataLength = jsonData.length;
var colorMap = new Map();
svg.sumMap = new Map();
var sumMapByX = new Map();
var i, elemJson, elemToPush, elemSumMap;
svg.timeMin = Infinity;
var timeMax = 0;
svg.hourShift = getTimeShift(urlJson) * 3600000;
var itemType = jsonContent[contentItemValue];
// Data are processed and sorted.
for(i = 0; i < dataLength; i++){
elemJson = jsonData[i];
if(+elemJson[contentAmountValue] === 0){
continue;
}
elemToPush = {
x: (new Date(elemJson[contentDateValue])).getTime() + svg.hourShift,
height: +elemJson[contentAmountValue],
item: (elemJson[contentItemValue] === "")?" Remainder ":elemJson[contentItemValue]
};
elemToPush.display = (elemToPush.item === " Remainder ")?" Remainder ":(elemJson[contentDisplayValue] === "")?elemToPush.item:
(itemType === "portproto")?elemToPush.item + " (" + elemJson[contentDisplayValue] + ")": elemJson[contentDisplayValue];
if(!sumMapByX.has(elemToPush.x)){
sumMapByX.set(elemToPush.x,elemToPush.height);
}{
sumMapByX.set(elemToPush.x,sumMapByX.get(elemToPush.x) + elemToPush.height);
}
svg.timeMin = Math.min(svg.timeMin,elemToPush.x);
timeMax = Math.max(timeMax,elemToPush.x);
svg.values.push(elemToPush);
}
//Compute 1% of total amount by date.
sumMapByX.forEach(function(value, key){
sumMapByX.set(key,value/100)
});
var elemValue, valuesLength = svg.values.length;
i = 0;
while(i < valuesLength){
elemValue = svg.values[i];
if(elemValue.height < sumMapByX.get(elemValue.x)){
svg.values.splice(i,1);
valuesLength --;
}else{
i++;
}
}
//values are sorted according primarily x (date) then height.
svg.values.sort(sortValues);
console.log(sumMapByX);
//step = 1 hour by default
svg.step = (urlJson.indexOf("pset=DAILY") === -1)?3600000:86400000;
svg.values.forEach(function(elem,i){
elem.x = (elem.x - svg.timeMin)/svg.step;
if (!svg.sumMap.has(elem.item)) {
svg.sumMap.set(elem.item, {sum: elem.height,display: elem.display});
} else {
elemSumMap = svg.sumMap.get(elem.item);
elemSumMap.sum += elem.height;
}
svg.values[i] = {x:elem.x,height:elem.height,item:elem.item};
});
var xMax = (timeMax - svg.timeMin)/svg.step + 1;
var sumArray = [];
var f = colorEval();
svg.sumMap.forEach(function (value, key) {
sumArray.push({item: key, sum: value.sum, display: value.display});
});
console.log(sumArray);
sumArray.sort(sortArrayVolume);
i = 0;
if (sumArray[0].item == " Remainder " || sumArray[0].item == "OTHERS") {
colorMap.set(sumArray[0].item, "#f2f2f2");
i = 1;
}
while (i < sumArray.length) {
colorMap.set(sumArray[i].item, f());
i++;
}
console.log(colorMap);
sumArray.sort(sortAlphabet);
//Evaluation of the abscissa domain
svg.x.domain([-0.625, xMax - 0.375]);
var totalSum = [];
var x = svg.values[0].x;
var sum;
i = 0;
while (x < xMax) {
sum = 0;
while (i < svg.values.length && svg.values[i].x == x) {
sum += svg.values[i].height;
svg.values[i].y = sum;
i++;
}
totalSum.push(sum);
x++;
}
var total = d3.max(totalSum);
svg.y.range([svg.height, 0]);
//the *1.05 operation allow a little margin
svg.y.domain([0, total * 1.05]);
svg.newX = d3.scaleLinear().range(svg.x.range()).domain(svg.x.domain());
svg.newY = d3.scaleLinear().range(svg.y.range()).domain(svg.y.domain());
var dataWidth = 0.75 * (svg.x(svg.x.domain()[0] + 1) - svg.x.range()[0]);
var selection = svg.chart.selectAll(".data")
.data(svg.values)
.enter().append("rect")
.classed("data", true)
.attr("x", function (d) {
return svg.x(d.x - 0.375);
})
.attr("y", function (d) {
return svg.y(d.y);
})
.attr("height", function (d) {
return svg.y.range()[0] - svg.y(d.height);
})
.attr("width", dataWidth)
.attr("fill", function (d) {
return colorMap.get(d.item);
})
.attr("stroke", "#000000");
//Tooltip creation
createTooltipHisto(svg,selection,svg.sumMap);
var blink = blinkCreate(colorMap);
svg.activeItem = null;
function activationElems(d) {
if (svg.popup.pieChart !== null) {
return;
}
svg.activeItem = d.item;
function testitem(data) {
return d.item == data.item;
}
trSelec.filter(testitem).classed("outlined", true);
selection.filter(testitem).each(blink);
}
function activationElemsAutoScroll(d) {
if (svg.popup.pieChart !== null) {
return;
}
svg.activeItem = d.item;
function testitem(data) {
return d.item == data.item;
}
var elem = trSelec.filter(testitem).classed("outlined", true);
scrollToElementTableTransition(elem,table);
selection.filter(testitem).each(blink);
}
function activationElemsAutoScrollPopup(d) {
svg.activeItem = d.item;
function testitem(data) {
return d.item == data.item;
}
var elem = trSelec.filter(testitem).classed("outlined", true);
scrollToElementTableTransition(elem,table);
}
function deactivationElems() {
if (svg.activeItem == null || svg.popup.pieChart !== null) {
return;
}
function testitem(data) {
return data.item == svg.activeItem;
}
trSelec.filter(testitem).classed("outlined", false);
selection.filter(testitem).interrupt().attr("stroke", "#000000").attr("fill", colorMap.get(svg.activeItem));
svg.activeItem = null;
}
selection.on("mouseover", activationElemsAutoScroll).on("mouseout", deactivationElems);
svg.axisx = svg.append("g")
.attr("class", "axisGraph")
.attr('transform', 'translate(' + [svg.margin.left, svg.height + svg.margin.top] + ")");
svg.axisx.call(d3.axisBottom(svg.x));
legendAxisX(svg);
yAxeSimpleCreation(svg);
optionalYAxeSimpleCreation(svg);
gridSimpleGraph(svg);
if(svg.hasPopup){
addPopup(selection,div,svg,function(data){
deactivationElems();
activationElemsAutoScrollPopup(data);},
deactivationElems);
}else{
svg.popup = [];
svg.popup.pieChart = null;
}
//Legend creation
var trSelec = table.selectAll("tr").data(sumArray).enter().append("tr");
tableLegendTitle(svg,trSelec);
trSelec.append("td").append("div").classed("lgd", true).style("background-color", function (d) {
return colorMap.get(d.item);
});
trSelec.append("td").text(function (d) {
return d.display;
});
trSelec.on("mouseover", activationElems).on("mouseout", deactivationElems);
//zoom
addZoomSimple(svg, updateHisto2DStackSimple);
d3.select(window).on("resize." + mydiv, function () {
console.log("resize");
redrawHisto2DStackSimple(div, svg);
});
hideShowValuesSimple(svg, trSelec, selection, xMax);
});
}
/**
* Effectively redraws the stacked histogram on call.
* @param svg {Object} D3 encapsulated parent svg element.
*/
function updateHisto2DStackSimple(svg){
/*
svg.chartOutput.attr("transform","matrix(" + (svg.scalex*svg.scale) + ", 0, 0, " + (svg.scaley*svg.scale) + ", " + svg.translate[0] + "," + svg.translate[1] + ")" );
svg.chartInput.attr("transform","matrix(" + (svg.scalex*svg.scale) + ", 0, 0, " + (svg.scaley*svg.scale) + ", " + svg.translate[0] + "," + (svg.translate[1] - (svg.scaley*svg.scale-1)*svg.margin.zero) + ")" );
*/
var newydom0 = svg.newY(svg.y.domain()[0]);
var dataWidth = 0.75*(svg.newX(svg.newX.domain()[0] + 1) - svg.newX.range()[0]);
svg.chart.selectAll(".data")
.attr("x",function(d){return svg.newX(d.x - 0.375);})
.attr("y", function(d){return svg.newY(d.y);})
.attr("height", function(d){return newydom0 - svg.newY(d.height);})
.attr("width", dataWidth);
svg.axisx.call(d3.axisBottom(svg.newX));
legendAxisX(svg);
yAxeSimpleUpdate(svg);
optionalYAxeSimpleUpdate(svg);
gridSimpleGraph(svg);
}
/**
* Computes internal variables after a modification then redraws the stacked histogram accordingly.
* @param div {Object} D3 encapsulated parent div element.
* @param svg {Object} D3 encapsulated parent svg element, direct child of div parameter.
*/
function redrawHisto2DStackSimple(div,svg){
var clientRect = div.node().getBoundingClientRect();
var divWidth = Math.max(1.15*svg.tableWidth + svg.margin.left + svg.margin.right + 1, clientRect.width),
divHeight = Math.max(svg.margin.bottom + svg.margin.top + svg.margin.zero + 1, clientRect.height);
//console.log("width " + divWidth );
var oldsvgheight = svg.height;
var oldsvgwidth = svg.width;
svg.attr("width",divWidth-1.15*svg.tableWidth).attr("height",divHeight);
svg.width = divWidth-1.15*svg.tableWidth - svg.margin.left - svg.margin.right;
svg.height = divHeight - svg.margin.bottom - svg.margin.top;
div.select("table").style("max-height",
(divHeight - 2*parseInt(div.style("font-size"),10) -60) + "px");
var ratiox = svg.width/oldsvgwidth;
var ratioy = svg.height/oldsvgheight;
svg.x.range([0, svg.width]);
svg.y.range([svg.height,0]);
svg.svg.attr("width",svg.width).attr("height",svg.height);
svg.frame.select(".rectOverlay").attr("height",svg.height);
svg.transform.x = svg.transform.x*ratiox;
svg.transform.y = svg.transform.y*ratioy;
var scaleytot = svg.transform.k*svg.scaley;
var scalextot = svg.transform.k*svg.scalex;
svg.transform.k = Math.max(scalextot,scaleytot);
svg.scalex = scalextot/svg.transform.k;
svg.scaley = scaleytot/svg.transform.k;
svg.newX.range([0,svg.width]);
svg.newY.range([svg.height,0]);
svg.axisx.attr('transform', 'translate(' + [svg.margin.left, svg.height+svg.margin.top] + ")");
svg._groups[0][0].__zoom.k =svg.transform.k;
svg._groups[0][0].__zoom.x =svg.transform.x;
svg._groups[0][0].__zoom.y =svg.transform.y;
updateHisto2DStackSimple(svg);
redrawPopup(div.overlay, svg);
}
/**
* Add a zoom feature to a simple 2D graph.
* @param svg {Object} D3 encapsulated parent svg element.
* @param updateFunction {Function} The function that will be called to update the graph's view.
*/
function addZoomSimple(svg,updateFunction){
if(svg.frame == undefined){
svg.frame=svg.chart;
}
if(svg.svg == undefined){
svg.svg=svg;
}
//Scales to update the current view (if not already implemented for specific reasons)
if(svg.newX == undefined){
svg.newX = d3.scaleLinear().range(svg.x.range()).clamp(true).domain(svg.x.domain());
}
if(svg.newY == undefined) {
svg.newY = d3.scaleLinear().range(svg.y.range()).clamp(true).domain(svg.y.domain());
}
//Selection rectangle for zooming (if not already implemented for better display control)
if(svg.selec == undefined){
svg.selec = svg.chart.append("rect").attr("class", "rectSelec");
}
//to stop triggering animations during rectselec
var rectOverlay = svg.frame.append("rect").attr("x",0).attr("y",0)
.attr("height",svg.height).attr("width",0).attr("fill-opacity",0).classed("rectOverlay",true);
var startCoord = [NaN,NaN];
var mouseCoord = [NaN,NaN];
svg.scalex = 1;
svg.scaley = 1;
//coordinates within the x&y ranges frames, points towards the top left corner of the actual view
//workaround for the zoom.translate([0,0]) which doesn't work as intended.
svg.transform = {k:1,x:0,y:0};
//Vector pointing towards the top left corner of the current view in the x&y ranges frame
//Calculated from svg.translate
var actTranslate = [0,0];
var event = {k:1,x:0,y:0};
var calcCoord =[];
svg.zoom = d3.zoom().scaleExtent([1, Infinity]).on("zoom", function () {
rectOverlay.attr("width",svg.width);
if(isNaN(startCoord[0])){
var lastEvent = {k:event.k,x:event.x,y:event.y};
event = d3.event.transform;
if(event.k == lastEvent.k){
//case: translation
//Avoid some "false" executions
if(event.k != 1){
svg.style("cursor", "move");
}
//actualization of the translation vector (translate) within the x&y ranges frames
svg.transform.x = Math.min(0, Math.max(event.x,svg.width - event.k*svg.scalex*svg.width ));
svg.transform.y = Math.min(0, Math.max(event.y,svg.height - event.k*svg.scaley*svg.height ));
}else{
//case: zoom
var coefScale = event.k/lastEvent.k;
//Retrieve the cursor coordinates. Quick dirty fix to accept double click while trying to minimize side effects.
calcCoord[0] = -svg.margin.left-(event.x -lastEvent.x*coefScale)/(coefScale -1);
calcCoord[1] = -svg.margin.top-(event.y -lastEvent.y*coefScale)/(coefScale -1);
var mouse = d3.mouse(svg.svg.node());
//console.log("x: " + (calcCoord[0] - mouse[0]).toFixed(5) + " y: " + (calcCoord[1] - mouse[1]).toFixed(5));
var lastScalex = svg.scalex;
var lastScaley = svg.scaley;
//Actualization of the local scales
svg.scalex = Math.max(1/event.k, svg.scalex);
svg.scaley = Math.max(1/event.k, svg.scaley);
//Evaluation of the scale changes by axis
var xrel = coefScale*svg.scalex/lastScalex;
var yrel = coefScale*svg.scaley/lastScaley;
//actualization of the translation vector with the scale change
svg.transform.x*= xrel;
svg.transform.y*= yrel;
//actualization of the translation vector (translate) to the top left corner of our view within the standard x&y.range() frame
//If possible, the absolute location pointed by the cursor stay the same
//Since zoom.translate(translate) doesn't work immediately but at the end of all consecutive zoom actions,
//we can't rely on d3.event.translate for smooth zooming and have to separate zoom & translation
svg.transform.x = Math.min(0, Math.max(svg.transform.x - calcCoord[0]*(xrel - 1),svg.width - event.k*svg.scalex*svg.width ));
svg.transform.y = Math.min(0, Math.max(svg.transform.y - calcCoord[1]*(yrel - 1),svg.height- event.k*svg.scaley*svg.height ));
svg.transform.k = event.k;
}
actTranslate[0] = -svg.transform.x/(svg.scalex*event.k);
actTranslate[1] = -svg.transform.y/(svg.scaley*event.k);
//actualization of the current (newX&Y) scales domains
svg.newX.domain([ svg.x.invert(actTranslate[0]), svg.x.invert(actTranslate[0] + svg.width/(svg.transform.k*svg.scalex)) ]);
svg.newY.domain([ svg.y.invert(actTranslate[1] + svg.height/(svg.transform.k*svg.scaley)), svg.y.invert(actTranslate[1]) ]);
updateFunction(svg);
} else {
mouseCoord = d3.mouse(svg.frame.node());
//Drawing of the selection rect
console.log("carré mousecoord " + mouseCoord + " start " + startCoord );
mouseCoord[0] = Math.min(Math.max(mouseCoord[0],svg.x.range()[0]),svg.x.range()[1]);
mouseCoord[1] = Math.min(Math.max(mouseCoord[1],svg.y.range()[1]),svg.y.range()[0]);
svg.selec.attr("x", Math.min(mouseCoord[0],startCoord[0]))
.attr("y", Math.min(mouseCoord[1],startCoord[1]))
.attr("width", Math.abs(mouseCoord[0] - startCoord[0]))
.attr("height", Math.abs(mouseCoord[1] - startCoord[1]));
}
})
.on("start",function () {
svg.on("contextmenu.zoomReset",null);
clearTimeout(svg.timer);
event = {k:svg.transform.k,x:svg.transform.x,y:svg.transform.y};
console.log("zoomstart");
if(null !== d3.event.sourceEvent && d3.event.sourceEvent.shiftKey){
console.log("key is down start");
startCoord = d3.mouse(svg.frame.node());
startCoord[0] = Math.min(Math.max(startCoord[0],svg.x.range()[0]),svg.x.range()[1]);
startCoord[1] = Math.min(Math.max(startCoord[1],svg.y.range()[1]),svg.y.range()[0]);
svg.style("cursor","crosshair");
}
})
.on("end", function () {
console.log("zoomend");
rectOverlay.attr("width",0);
if(!isNaN(startCoord[0]) && !isNaN(mouseCoord[0])){
svg.selec.attr("width", 0)
.attr("height", 0);
var sqwidth = Math.abs(mouseCoord[0] - startCoord[0]);
var sqheight = Math.abs(mouseCoord[1] - startCoord[1]);
if(sqwidth != 0 && sqheight != 0){
var lastScale = svg.transform.k;
var lastScalex = svg.scalex;
var lastScaley = svg.scaley;
//Top left corner coordinates of the selection rectangle
var xmin = Math.min(mouseCoord[0],startCoord[0]);
var ymin = Math.min(mouseCoord[1],startCoord[1]);
//Repercussion on the translate vector
svg.transform.x -= xmin;
svg.transform.y -= ymin;
//Evaluation of the total scale change from the beginning, by axis.
svg.scalex = svg.width*svg.transform.k*svg.scalex/sqwidth;
svg.scaley = svg.height*svg.transform.k*svg.scaley/sqheight;
//Evaluation of the global scale
svg.transform.k = Math.max(svg.scalex,svg.scaley);
//Evaluation of the local scale change (with 0<svg.scalen<=1 &&
// total scale change for n axis == svg.scalen*svg.scale >=1)
svg.scalex = svg.scalex/svg.transform.k;
svg.scaley = svg.scaley/svg.transform.k;
//Evaluation of the ratio by axis between the new & old scales
var xrel = (svg.scalex * svg.transform.k)/(lastScale * lastScalex);
var yrel = (svg.scaley * svg.transform.k)/(lastScale * lastScaley);
//Actualization of the translate vector
svg.transform.x*= xrel;
svg.transform.y*= yrel;
//actualization of the current (newX&Y) scales domains
svg.newX.domain([ svg.newX.invert(xmin), svg.newX.invert(xmin + sqwidth)]);
svg.newY.domain([ svg.newY.invert(ymin + sqheight),svg.newY.invert(ymin) ]);
updateFunction(svg);
}
}
//update of the zoom behavior
svg._groups[0][0].__zoom.k =svg.transform.k;
svg._groups[0][0].__zoom.x =svg.transform.x;
svg._groups[0][0].__zoom.y =svg.transform.y;
startCoord = [NaN,NaN];
mouseCoord = [NaN,NaN];
svg.style("cursor","auto");
svg.on("contextmenu.zoomReset",simpleZoomReset(svg, updateFunction));
});
svg.call(svg.zoom);
//A fresh start...
svg._groups[0][0].__zoom.k =svg.transform.k;
svg._groups[0][0].__zoom.x =svg.transform.x;
svg._groups[0][0].__zoom.y =svg.transform.y;
}
/**
* Allows the possibility to hide/show data inside a simple stacked histogram according their item value.
* @param svg {Object} D3 encapsulated parent svg element.
* @param trSelec {Object} D3 selection of tr elements from the legend's table.
* @param selection {Object} D3 selection of the rect elements that may be masked/displayed.
* @param xlength {Number} The maximal value + 1 a x property from the bound data can take.
*/
function hideShowValuesSimple(svg,trSelec,selection,xlength){
var duration = 800;
var trSelecSize = trSelec.size();
var hiddenValues = [];
var stringified = JSON.stringify(svg.values);
var newValues = JSON.parse(stringified);
var valuesTrans = JSON.parse(stringified);
selection.data(valuesTrans);
console.log(newValues);
trSelec.on("click",function(d){
var clickedRow = d3.select(this);
svg.transition("hideshow").duration(duration).tween("",function(){
var totalSum = [];
var x = svg.values[0].x;
var sum;
var i = 0;
if(svg.popup.pieChart !==null){
return;
}
var index = hiddenValues.indexOf(d.item);
if( index === -1){
//Hide the data
hiddenValues.push(d.item);
clickedRow.classed("strikedRow",true);
while(x < xlength){
sum=0;
while(i < newValues.length && newValues[i].x == x){
if(newValues[i].item === d.item){
newValues[i].height = 0;
}
sum += newValues[i].height;
newValues[i].y = sum;
i++;
}
totalSum.push(sum);
x++;
}
}else{
//Show the data
hiddenValues.splice(index,1);
clickedRow.classed("strikedRow",false);
while(x < xlength){
sum=0;
while(i < newValues.length && newValues[i].x == x){
if(newValues[i].item === d.item){
newValues[i].height = svg.values[i].height;
}
sum += newValues[i].height;
newValues[i].y = sum;
i++;
}
totalSum.push(sum);
x++;
}
}
var valuesStart = JSON.parse(JSON.stringify(valuesTrans));
var newTotal;
if(hiddenValues.length === trSelecSize){
newTotal=1;
}else {
newTotal = d3.max(totalSum);
}
var oldTotal = svg.y.domain()[1]/1.05;
var t0,totalTrans;
return function(t){
t0 = (1-t);
valuesTrans.forEach(function(elem,i){
elem.y = t0*valuesStart[i].y + t*newValues[i].y;
elem.height = t0*valuesStart[i].height + t*newValues[i].height;
});
totalTrans = oldTotal* t0 + newTotal*t;
var actTranslate1 = -svg.transform.y/(svg.scaley*svg.transform.k);
svg.y.domain([0,totalTrans*1.05]);
svg.newY.domain([svg.y.invert(actTranslate1 + svg.height/(svg.transform.k*svg.scaley)), svg.y.invert(actTranslate1)]);
updateHisto2DStackSimple(svg);
}
});
});
trSelec.on("contextmenu",function(d) {
d3.event.preventDefault();
var clickedRow = d3.select(this);
svg.transition("hideshow").duration(duration).tween("",function(){
var totalSum = [];
var x = svg.values[0].x;
var sum;
var i=0;
if(svg.popup.pieChart !==null){
return;
}
var index = hiddenValues.indexOf(d.item);
if((index !== -1) || (trSelecSize - 1 !== hiddenValues.length )){
//Hide all data except this one
hiddenValues = trSelec.data().map(function(elem){return elem.item;});
hiddenValues.splice(hiddenValues.indexOf(d.item),1);
trSelec.classed("strikedRow",true);
clickedRow.classed("strikedRow",false);
while(x < xlength){
sum=0;
while(i < newValues.length && newValues[i].x == x){
if(newValues[i].item !== d.item){
newValues[i].height = 0;
}else{
newValues[i].height = svg.values[i].height;
}
sum += newValues[i].height;
newValues[i].y = sum;
i++;
}
totalSum.push(sum);
x++;
}
}else{
//index === -1 && hiddenValues.length == trSelec.size() -1
// ->show all data.
hiddenValues = [];
trSelec.classed("strikedRow",false);
while(x < xlength){
sum=0;
while(i < newValues.length && newValues[i].x == x){
newValues[i].height = svg.values[i].height;
sum += newValues[i].height;
newValues[i].y = sum;
i++;
}
totalSum.push(sum);
x++;
}
}
var valuesStart = JSON.parse(JSON.stringify(valuesTrans));
var newTotal = Math.max(0.000000001,d3.max(totalSum));
var oldTotal = svg.y.domain()[1]/1.05;
var t0,totalTrans;
return function(t){
t=Math.min(1,Math.max(0,t));
t0 = (1-t);
valuesTrans.forEach(function(elem,i){
elem.y = t0*valuesStart[i].y + t*newValues[i].y;
elem.height = t0*valuesStart[i].height + t*newValues[i].height;
});
totalTrans = oldTotal* t0 + newTotal*t;
var actTranslate1 = -svg.transform.y/(svg.scaley*svg.transform.k);
svg.y.domain([0,totalTrans*1.05]);
svg.newY.domain([svg.y.invert(actTranslate1 + svg.height/(svg.transform.k*svg.scaley)), svg.y.invert(actTranslate1) ]);
updateHisto2DStackSimple(svg);
}
});
});
}
|
import React, { useMemo } from "react";
import styled from "styled-components";
import InternalRouting from "./InternalRouting";
import Service from "./Service";
import Database from "./Database";
import PlacedLink from "./PlacedLink";
import Cloud from "./Cloud";
import { ComponentTypes } from "../constants";
const Wrapper = styled.div`
height: 100%;
width: 100%;
position: relative;
`;
function groupServices(config) {
const links = [];
const services = config.services || [];
const serviceMap = {};
services.forEach((x) => {
serviceMap[x.id] = x;
if (x.Component) {
return;
}
if (x.type === ComponentTypes.Service) {
x.Component = Service;
} else if (x.type === ComponentTypes.InternalRouting) {
x.Component = InternalRouting;
} else if (x.type === ComponentTypes.Database) {
x.Component = Database;
} else if (x.type === ComponentTypes.Cloud) {
x.Component = Cloud;
}
});
let linkCounter = 1;
services.forEach((x) => {
if (x.links) {
x.links.forEach((originalLink) => {
const l = { ...originalLink };
l.end = {
placement: l.end,
service: serviceMap[l.id],
};
l.start = {
placement: l.start,
service: x,
};
l.counter = linkCounter++;
links.push(l);
});
}
});
return { services, links };
}
export default function ReactArchitectureDiagram({ config = {} }) {
const { services, links } = useMemo(() => {
return groupServices(config);
}, [config]);
return (
<Wrapper>
{services.map((x, index) => {
return <x.Component key={`s-${index}`} {...x} />;
})}
{links.map((link, index) => (
<PlacedLink key={`l-${index}`} link={link} />
))}
</Wrapper>
);
}
|
import React from 'react';
import Bg from 'images/crayons.jpeg'
const styles={
background:{
background: `url(${Bg})`,
height: "100vh",
backgroundSize: "cover",
position: "fixed",
textAlign:"center",
padding:10
},
title:{
paddingTop:30,
fontSize:"2rem",
fontWeight:"bold"
}
}
export default function NoMobile(){
return(
<div style={styles.background}>
<h1 style={styles.title}>Lache un peu ton portable!</h1>
<p>Cette version de esquisse en ligne est optimisée pour fonctionner sur un ordinateur. Désolé ça viendra peut-être un jour...</p>
</div>
)
} |
angular.module('starter.eventosControl', [])
.controller('eventosControl', function($scope,$http,
eventosFactoria
) {
$scope.eventos;
//$scope.sesion = sesionFactoria.get();
//alert( $scope.sesion );
consultarEventos($http,$scope);
$scope.cargarEventos = function(response) {
try
{
eventosFactoria.cargar(response);
$scope.eventos = eventosFactoria.all();
}
catch(e){
console.log(e);
}
};
})
|
let express = require('express');
// var router = express.Router();
let app = express();
let categoryC=require('../Controller/CategoryC');
//the view engine
//define your router here
app.get('/',async (req,res)=>{
categoryC
.getAll()
.then(data => {
res.locals.categoryC=data;
res.render('index');
})
.catch()
});
app.get('/sync',(req,res)=>{
let models=require('../models');
models.sequelize.sync()
.then(()=>{
res.send('database sync completed!');
});
});
// app.get('/:page',(req,res) =>{
// let banners = {
// blog: 'Our Blog',
// category: 'Shop category',
// cart: 'Shopping Cart',
// checkout: 'Product Checkout',
// confirmation: 'Order Confirmation',
// contact: 'Contact Us',
// login: 'Login / Register',
// register: 'Register',
// };
// let page=req.params.page;
// res.render(page,{banner: banners[page]});
// })
module.exports = app;
|
/**
* Handle record selected.
*
* @param {JSEvent} event the event that triggered the action
*
* @private
*
* @properties={typeid:24,uuid:"5CD69DCB-C52C-40A0-83C2-DECDFD81ABF7"}
* @AllowToRunInFind
*/
function onRecordSelection(event)
{
var frm = forms.agd_cl_dettaglio_esterni_tbl;
var fs = frm.foundset;
if(fs && fs.find())
{
fs.iddittaclassificazione = foundset.iddittaclassificazione;
fs.search();
}
}
|
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path:'/',
redirect:'/recommend'
},
{
path:'/recommend',
name:'recommend',
component: () => import('pages/recommend/recommend'),
children: [
{
path:'/recommend/:id',
name:'songsheet',
component: () => import('pages/recommend/components/songsheet')
}
]
},
{
path:'/singer',
name:'singer',
component: () => import('pages/singer/singer'),
children: [
{
path:'/singer/:id',
name:'singer-detail',
component: () => import('pages/singer/components/singer-detail')
}
]
},
{
path:'/rank',
name:'rank',
component: () => import('pages/rank/rank'),
children: [
{
path:'/rank/:id',
name:'rank-detail',
component: () => import('pages/rank/components/rank-detail')
}
]
},
{
path:'/search',
name:'search',
component: () => import('pages/search/search'),
children: [
{
path:'/search/:id',
component: () => import('pages/singer/components/singer-detail')
}
]
},
{
path:'/user',
name:'user',
component: () => import('pages/user/user')
}
]
}) |
import React, {Component, Fragment} from 'react';
import {Link} from 'react-router-dom';
import {Button, message, Popconfirm, Divider, BackTop, Icon, Input, Table} from 'antd';
import ProveedorForm from './ProveedorForm';
import * as proveedoresActions from '../../redux/actions/administracion/proveedoresActions';
import {connect} from 'react-redux';
import {bindActionCreators} from "redux";
import MainLoader from "../common/Main Loader";
import TablePageB from "../clientes/TablePageB";
const style={
customFilterDropdown: {
padding: 8,
borderRadius: 6,
backgroundColor: 'white',
boxShadow: '0 1px 6px rgba(0, 0, 0, .2)'
},
customFilterDropdownInput: {
width: 130,
marginRight: 8,
}
};
class ProovedorPage extends Component {
state = {
visible: false,
selectedRowKeys:[],
on:true,
data:[],
filterDropdownVisible: false,
searchText: '',
filtered: false,
canReset:false
};
showModal = () => {
this.setState({
visible: true,
});
};
handleCancel = () => {
this.setState({
visible: false,
});
const form = this.form;
form.resetFields();
};
deleteProveedor=()=>{
let keys = this.state.selectedRowKeys;
for(let i in keys){
this.props.proveedoresActions.deleteProveedor(keys[i])
.then(r=>{
console.log(r)
}).catch(e=>{
console.log(e)
})
}
this.setState({selectedRowKeys:[]})
};
confirm=(e)=> {
console.log(e);
this.deleteProveedor();
message.success('Deleted successfully');
};
cancel=(e) =>{
console.log(e);
};
onSelectChange = (selectedRowKeys) => {
console.log('selectedRowKeys changed: ', selectedRowKeys);
this.setState({ selectedRowKeys });
};
saveFormRef = (form) => {
this.form = form;
};
handleCreate = (e) => {
const form = this.form;
e.preventDefault();
form.validateFields((err, values) => {
if (!err) {
console.log(values);
this.props.proveedoresActions.saveProveedor(values)
.then(r=>{
message.success('Guardado con éxito');
form.resetFields();
this.setState({ visible: false });
})
.catch(r=>{
message.error('El RFC ingresado ya existe!')
console.log(values)
})
}else{message.error('Algo fallo, verifica los campos');}
});
};
checkRfc = (rule, value, callback) => {
if (value === undefined) {
callback('Verifica el RFC ingresado');
} else {
if(value.length < 12 ){
callback('RFC de 12 a 13 dígitos');
}
callback()
}
};
checkPhone = (rule, value, callback) => {
if (value === undefined) {
callback('El número ingresa debe contener 10 dígitos.');
} else {
if(value.length < 10){
callback('Ingresa un número de 10 dígitos');
}
callback()
}
};
handleChange = e => {
this.setState({
contacto_directo: e.target.checked
})
};
handleChangeOn = ()=>{
this.setState({
on: !this.state.on
})
};
onInputChange = (e) => {
this.setState({ searchText: e.target.value });
console.log(e.target.value)
};
onSearch = () => {
//let basePath = 'http://localhost:8000/api/egresos/proveedores/?q=';
let basePath = 'https://rancho.davidzavala.me/api/egresos/proveedores/?q=';
let url = basePath+this.state.searchText;
this.props.proveedoresActions.getProveedores(url);
this.setState({canReset:true})
};
resetFilter = () => {
//let basePath = 'http://localhost:8000/api/egresos/proveedores/';
let basePath = 'https://rancho.davidzavala.me/api/egresos/proveedores/?q=';
this.props.proveedoresActions.getProveedores(basePath)
this.setState({
searchText: '',
canReset: false,
});
};
/*handlePagination=(pagina)=>{
console.log(this.props.proveedores);
let basePath = 'http://localhost:8000/api/egresos/proveedores/?page=';
let newUrl = basePath +pagina;
this.props.proveedoresActions.getProveedores(newUrl);
};*/
handlePagination=(pagina)=>{
let nextLength = pagina.toString().length;
let newUrl = this.props.proveedoresData.next;
if(newUrl===null){
newUrl = this.props.proveedoresData.previous;
}
if( pagina ==1 && this.props.proveedoresData.count <= 20){
newUrl='https'+newUrl.slice(4,newUrl.length);
}else{
newUrl='https'+newUrl.slice(4,newUrl.length-nextLength)+pagina;
}
this.props.proveedoresActions.getProveedores(newUrl);
};
handleSearch=(e)=>{
this.setState({searchText:e.target.value})
};
render() {
const columns = [
{
title: 'Proveedor',
dataIndex: 'provider',
render: (provider,obj) =><Link to={`/admin/proveedores/${obj.id}`}>{ provider && provider !== null ? provider: "No Proveedor"}</Link>,
key:'provider',
},
{
title: 'Dirección',
dataIndex: 'address',
},
{
title: 'E-mail',
dataIndex: 'email'
},
{
title: 'RFC',
dataIndex: 'rfc'
},
];
const { visible, selectedRowKeys, data, filtered, searchText, canReset } = this.state;
const canDelete = selectedRowKeys.length > 0;
const rowSelection = {
selectedRowKeys,
onChange: this.onSelectChange,
};
let {proveedores, fetched, proveedoresData} = this.props;
if(!fetched)return(<MainLoader/>);
return (
<Fragment>
<div style={{marginBottom:10, color:'rgba(0, 0, 0, 0.65)' }}>
Administración
<Divider type="vertical" />
Proveedores
</div>
<h1>Proveedores</h1>
<div style={{paddingBottom:'1%'}}>
<Input.Search
enterButton
onSearch={this.onSearch}
onChange={this.handleSearch}
value={searchText}
style={{ width: 400 }}
placeholder={'Busca por nombre...'}
/>
</div>
<BackTop visibilityHeight={100} />
<Table
dataSource={proveedores}
columns={columns}
rowSelection={rowSelection}
rowKey={record => record.id}
scroll={{x:650}}
style={{marginBottom:10}}
pagination={{
pageSize: 10,
total:proveedoresData.count,
onChange:this.handlePagination,
showTotal:total => `Total: ${total} Proveedores`
}}
/>
<Button type="primary" onClick={this.showModal}>Agregar</Button>
<ProveedorForm
ref={this.saveFormRef}
visible={visible}
onCancel={this.handleCancel}
onCreate={this.handleCreate}
rfc={this.checkRfc}
phone={this.checkPhone}
handleChange={this.handleChange}
on = {this.state.on}
handleChangeOn={this.handleChangeOn}
/>
<Divider
type={'vertical'}/>
<Popconfirm title="Are you sure delete this proveedor?" onConfirm={this.confirm} onCancel={this.cancel} okText="Yes" cancelText="No">
<Button disabled={!canDelete} type="primary" >Eliminar</Button>
</Popconfirm>
<Divider type={'vertical'} />
<Button type="primary" disabled={!canReset} onClick={this.resetFilter}>Borrar filtro</Button>
</Fragment>
);
}
}
function mapStateToProps(state, ownProps) {
return {
proveedoresData:state.proveedores.allData,
proveedores:state.proveedores.list,
fetched:state.proveedores.list!==undefined && state.proveedores.allData,
}
}
function mapDispatchToProps(dispatch) {
return {
proveedoresActions:bindActionCreators(proveedoresActions, dispatch)
}
}
ProovedorPage = connect(mapStateToProps,mapDispatchToProps)(ProovedorPage);
export default ProovedorPage; |
import Image from 'next/image';
import styled from 'styled-components';
import Button from './Button';
const Img = styled(Image)`
object-fit: cover;
`;
const Container = styled.div`
height: 450px;
margin: 8px;
cursor: pointer;
&:hover {
box-shadow: rgb(92 84 122 / 14%) 0px 4px 18px;
transition: all 0.3s ease-in 0s;
}
`;
const Body = styled.div`
padding: 16px;
height: 150px;
width: 100%;
position: relative;
display: flex;
flex-direction: column;
justify-content: space-between;
`;
const Title = styled.h3`
font-weight: 700;
font-size: 16px;
line-height: 20px;
margin: 0;
`;
const Price = styled.span`
line-height: 22px;
color: #e6215d;
font-weight: 700;
font-size: 18px;
letter-spacing: 0.4px;
`;
const Discount = styled.span`
color: #8d8d9d;
font-size: 14px;
line-height: 20px;
text-decoration: line-through;
margin-left: 8px;
`;
function Card({ name, price, imageURL, discount }) {
return (
<Container>
<Img alt='Hey Arnold Porcelana' src={imageURL} width={250} height={300} />
<Body>
<Title>{name}</Title>
<Price>
AR${price} <Discount>AR${discount}</Discount>
</Price>
<Button content='Comprar ahora' />
</Body>
</Container>
);
}
export default Card;
|
'use strict';
const dialogflow = require('dialogflow');
const config = require('../config/keys');
const structjson = require('structjson');
const projectID = config.googleProjectId;
const credentials = {
client_email:config.googleClientEmail,
private_key:config.googlePrivateKey
}
const sessionClient = new dialogflow.SessionsClient({projectID,credentials});
const sessionPath = sessionClient.sessionPath(config.googleProjectID,config.dialogFlowSessionID);
module.exports = {
textQuery: async function(text, parameters = {}) {
let self = module.exports;
const request = {
session: sessionPath,
queryInput: {
text: {
text: text,
languageCode: config.dialogFlowSessionLanguageCode
}
},
queryParams:{
payload:{
data:parameters
}
}
};
let responses = await sessionClient
.detectIntent(request);
responses = self.handleAction(responses)
return responses;
},
eventQuery: async function(event, parameters = {}) {
let self = module.exports;
const request = {
session: sessionPath,
queryInput: {
event: {
name: event,
parameters:structjson.jsonToStructProto(parameters),
languageCode: config.dialogFlowSessionLanguageCode
}
}
};
let responses = await sessionClient
.detectIntent(request);
responses = self.handleAction(responses)
return responses;
},
handleAction: function(responses){
return responses;
},
} |
function LoadWeaponData() {
var Weapons = {
'Link': {
0: {
ClassName: {
EN: 'Hylian Sword',
DE: 'Einhänder',
FR: 'Épée à une main',
ES: 'Espadas'
},
Weapons: {
0: {
Name: {
EN: 'Knight\'s Sword',
DE: 'Ritterschwert',
FR: 'Épée de chevalier',
ES: 'Espada de caballero'
},
Level: 'Level 1',
WeaponID: 0x00,
},
1: {
Name: {
EN: 'White\'s Sword',
DE: 'Edelschwert',
FR: 'Épée blanche',
ES: 'Espada blanca'
},
Level: 'Level 2',
WeaponID: 0x01,
},
2: {
Name: {
EN: 'Magical Sword',
DE: 'Magisches Schwert',
FR: 'Épée magique',
ES: 'Espada mágica'
},
Level: 'Level 3',
WeaponID: 0x02,
},
3: {
Name: {
EN: 'Magical Sword +',
DE: 'Magisches Schwert +',
FR: 'Épée magique DX',
ES: 'Espada mágica +'
},
Level: 'Level 4',
WeaponID: 0x3d,
},
4: {
Name: {
EN: 'Darkmagic Sword',
DE: 'Magisches Finsterschwert',
FR: 'Épée magique des ténèbres',
ES: 'Espada mágica oscura'
},
Level: 'Level 4+',
WeaponID: 0xc3,
},
},
},
1: {
ClassName: {
EN: 'Magic Rod',
DE: 'Zauberstab',
FR: 'Baguette',
ES: 'Cetros'
},
Weapons: {
0: {
Name: {
EN: 'Fire Rod',
DE: 'Feuerstab',
FR: 'Baguette de feu',
ES: 'Cetro de fuego'
},
Level: 'Level 1',
WeaponID: 0x03,
},
1: {
Name: {
EN: 'Prism Rod',
DE: 'Roter Stab',
FR: 'Baguette rouge',
ES: 'Cetro carmesí'
},
Level: 'Level 2',
WeaponID: 0x04,
},
2: {
Name: {
EN: 'Magical Rod',
DE: 'Magischer Stab',
FR: 'Baguette magique',
ES: 'Cetro mágico'
},
Level: 'Level 3',
WeaponID: 0x05,
},
3: {
Name: {
EN: 'Magical Rod +',
DE: 'Magischer Stab +',
FR: 'Baguette magique DX',
ES: 'Cetro mágico +'
},
Level: 'Level 4',
WeaponID: 0x3e,
},
4: {
Name: {
EN: 'Crackling Rod',
DE: 'Magischer Blitzstab',
FR: 'Baguette de foudre',
ES: 'Cetro del rayo'
},
Level: 'Level 4+',
WeaponID: 0xaf,
},
},
},
2: {
ClassName: {
EN: 'Great Fairy',
DE: 'Große Fee',
FR: 'Grande fée',
ES: 'Grandes Hadas'
},
Weapons: {
0: {
Name: {
EN: 'Great Fountain Fairy',
DE: 'Große Fee der Quelle',
FR: 'Gde fée de la fontaine',
ES: 'Gran Hada de la fuente'
},
Level: 'Level 1',
WeaponID: 0x06,
},
1: {
Name: {
EN: 'Great Forest Fairy',
DE: 'Große Fee des Waldes',
FR: 'Grande fée sylvestre',
ES: 'Gran Hada del bosque'
},
Level: 'Level 2',
WeaponID: 0x07,
},
2: {
Name: {
EN: 'Great Sky Fairy',
DE: 'Große Fee des Himmels',
FR: 'Grande fée céleste',
ES: 'Gran Hada del cielo'
},
Level: 'Level 3',
WeaponID: 0x08,
},
3: {
Name: {
EN: 'Great Sky Fairy +',
DE: 'Große Fee des Himmels +',
FR: 'Grande fée céleste DX',
ES: 'Gran Hada del cielo +'
},
Level: 'Level 4',
WeaponID: 0x3f,
},
4: {
Name: {
EN: 'Great Fairy of Tempests',
DE: 'Große Fee des Gewitters',
FR: 'Grande fée de la foudre',
ES: 'Gran Hada del trueno'
},
Level: 'Level 4+',
WeaponID: 0xc4,
},
},
},
3: {
ClassName: {
EN: 'Gauntlets',
DE: 'Handschuhe',
FR: 'Gants',
ES: 'Gauntes'
},
Weapons: {
0: {
Name: {
EN: 'Silver Gauntlets',
DE: 'Silberhandschuhe',
FR: 'Gantelets d\'argent',
ES: 'Gauntes de plata'
},
Level: 'Level 1',
WeaponID: 0x09,
},
1: {
Name: {
EN: 'Golden Gauntlets',
DE: 'Goldhandschuhe',
FR: 'Gantelets d\'or',
ES: 'Guantes de oro'
},
Level: 'Level 2',
WeaponID: 0x0a,
},
2: {
Name: {
EN: 'Power Gauntlets',
DE: 'Krafthandschuhe',
FR: 'Gants de puissance',
ES: 'Guantes de fuerza'
},
Level: 'Level 3',
WeaponID: 0x0b,
},
3: {
Name: {
EN: 'Power Gloves +',
DE: 'Krafthandschuhe +',
FR: 'Gants de puissance DX',
ES: 'Guantes de fuerza +'
},
Level: 'Level 4',
WeaponID: 0x40,
},
4: {
Name: {
EN: 'Burning Gloves',
DE: 'Brandhandschuhe',
FR: 'Gants de feu',
ES: 'Guantes ígneos'
},
Level: 'Level 4+',
WeaponID: 0x9b,
},
},
},
4: {
ClassName: {
EN: 'Master Sword',
DE: 'Master-Schwert',
FR: 'Épée de légende',
ES: 'Espada Maestra'
},
Weapons: {
0: {
Name: {
EN: 'Master Sword',
DE: 'Master-Schwert',
FR: 'Épée de légende',
ES: 'Espada Maestra'
},
Level: 'Level 1',
WeaponID: 0x3c,
},
},
},
5: {
ClassName: {
EN: 'Horse',
DE: 'Epona',
FR: 'Épona',
ES: 'Epona'
},
Weapons: {
0: {
Name: {
EN: 'Epona',
DE: 'Epona',
FR: 'Épona',
ES: 'Epona'
},
Level: 'Level 1',
WeaponID: 0x5a,
},
1: {
Name: {
EN: 'Twilight Epona',
DE: 'Schatten-Epona',
FR: 'Épona du Crépuscule',
ES: 'Epona del Crepúsculo'
},
Level: 'Level 2',
WeaponID: 0x5b,
},
2: {
Name: {
EN: 'Epona of Time',
DE: 'Zeit-Epona',
FR: 'Épona du temps',
ES: 'Epona del Tiempo'
},
Level: 'Level 3',
WeaponID: 0x5c,
},
3: {
Name: {
EN: 'Epona of Time +',
DE: 'Zeit-Epona +',
FR: 'Épona du temps DX',
ES: 'Epona del Tiempo +'
},
Level: 'Level 4',
WeaponID: 0x83,
},
4: {
Name: {
EN: 'Stormy-Eyed Epona',
DE: 'Zeitsturm Epona',
FR: 'Épona de la foudre',
ES: 'Epna del Trueno'
},
Level: 'Level 4+',
WeaponID: 0xc9,
},
},
},
6: {
ClassName: {
EN: 'Spinner',
DE: 'Gleiter',
FR: 'Aérouage',
ES: 'Aerodiscos'
},
Weapons: {
0: {
Name: {
EN: 'Ancient Spinner',
DE: 'Gleiter',
FR: 'Aérouage',
ES: 'Aerodisco'
},
Level: 'Level 1',
WeaponID: 0x60,
},
1: {
Name: {
EN: 'Enhanced Spinner',
DE: 'Schnellgleiter',
FR: 'Aérouage supérieur',
ES: 'Aerodisco azul'
},
Level: 'Level 2',
WeaponID: 0x61,
},
2: {
Name: {
EN: 'Triforce Spinner',
DE: 'Magischer Gleiter',
FR: 'Aérouage magique',
ES: 'Aerodisco mágico'
},
Level: 'Level 3',
WeaponID: 0x62,
},
3: {
Name: {
EN: 'Triforce Spinner +',
DE: 'Magischer Gleiter +',
FR: 'Aérouage magique DX',
ES: 'Aerodisco mágico +'
},
Level: 'Level 4',
WeaponID: 0x85,
},
4: {
Name: {
EN: 'Hydro-Spinner',
DE: 'Magischer Wassergleiter',
FR: 'Aérouage d\'eau',
ES: 'Aerodisco de agua'
},
Level: 'Level 4+',
WeaponID: 0xca,
},
},
},
},
'Zelda': {
0: {
ClassName: {
EN: 'Rapier',
DE: 'Rapier',
FR: 'Rapière',
ES: 'Floretes'
},
Weapons: {
0: {
Name: {
EN: 'Polished Rapier',
DE: 'Platinrapier',
FR: 'Rapière en platine',
ES: 'Florete de platino'
},
Level: 'Level 1',
WeaponID: 0x15,
},
1: {
Name: {
EN: 'Glittering Rapier',
DE: 'Glimmerrapier',
FR: 'Rapière scintillante',
ES: 'Florete ondulado'
},
Level: 'Level 2',
WeaponID: 0x16,
},
2: {
Name: {
EN: 'Gleaming Rapier',
DE: 'Lichtrapier',
FR: 'Rapière étincelante',
ES: 'Florete brillante'
},
Level: 'Level 3',
WeaponID: 0x17,
},
3: {
Name: {
EN: 'Gleaming Rapier +',
DE: 'Lichtrapier +',
FR: 'Rapière étincelante DX',
ES: 'Florete brillante +'
},
Level: 'Level 4',
WeaponID: 0x44,
},
4: {
Name: {
EN: 'Gloomy Rapier',
DE: 'Finsterlichtrapier',
FR: 'Rapière des ténèbres',
ES: 'Florete brillante oscuro'
},
Level: 'Level 4+',
WeaponID: 0xc6,
},
},
},
1: {
ClassName: {
EN: 'Baton',
DE: 'Taktstock',
FR: 'Baguette',
ES: 'Batutas'
},
Weapons: {
0: {
Name: {
EN: 'Wind Waker',
DE: 'Taktstock des Windes',
FR: 'Baguette du vent',
ES: 'Batuta de los vientos'
},
Level: 'Level 1',
WeaponID: 0x18,
},
1: {
Name: {
EN: 'Sacred Baton',
DE: 'Heiliger Taktstock',
FR: 'Baguette sacrée',
ES: 'Batuta sagrada'
},
Level: 'Level 2',
WeaponID: 0x19,
},
2: {
Name: {
EN: 'Glorious Baton',
DE: 'Taktstock der Güte',
FR: 'Baguette de bonté',
ES: 'Batuta de la bondad'
},
Level: 'Level 3',
WeaponID: 0x1a,
},
3: {
Name: {
EN: 'Glorious Baton +',
DE: 'Taktstock der Güte +',
FR: 'Baguette de bonté DX',
ES: 'Batuta de la bondad +'
},
Level: 'Level 4',
WeaponID: 0x45,
},
4: {
Name: {
EN: 'Liquid Glorious Baton',
DE: 'Wassertaktstock der Güte',
FR: 'Baguette d\'eau',
ES: 'Batuta del agua'
},
Level: 'Level 4+',
WeaponID: 0xb2,
},
},
},
2: {
ClassName: {
EN: 'Dominion Rod',
DE: 'Kopierstab',
FR: 'Bâton Anima',
ES: 'Cetros de dominio'
},
Weapons: {
0: {
Name: {
EN: 'Old Dominion Rod',
DE: 'Kopierstab',
FR: 'Bâton Anima',
ES: 'Cetro de dominio'
},
Level: 'Level 1',
WeaponID: 0x63,
},
1: {
Name: {
EN: 'High Dominion Rod',
DE: 'Variant-Kopierstab',
FR: 'Bâton Anima modifié',
ES: 'Cetro de dominio rúnico'
},
Level: 'Level 2',
WeaponID: 0x64,
},
2: {
Name: {
EN: 'Royal Dominion Rod',
DE: 'Royal-Kopierstab',
FR: 'Bâton Anima royal',
ES: 'Cetro de dominio real'
},
Level: 'Level 3',
WeaponID: 0x65,
},
3: {
Name: {
EN: 'Royal Dominion Rod +',
DE: 'Royal-Kopierstab +',
FR: 'Bâton Anima royal DX',
ES: 'Cetro de dominio real +'
},
Level: 'Level 4',
WeaponID: 0x86,
},
4: {
Name: {
EN: 'Volcanic Dominion Rod',
DE: 'Royal-Feuerkopierstab',
FR: 'Bâton Anima de feu',
ES: 'Cetro real de fuego'
},
Level: 'Level 4+',
WeaponID: 0xcb,
},
},
},
},
'Sheik': {
0: {
ClassName: {
EN: 'Harp',
DE: 'Lyra',
FR: 'Lyre',
ES: 'Liras'
},
Weapons: {
0: {
Name: {
EN: 'Goddess\'s Harp',
DE: 'Lyra der Göttin',
FR: 'Lyre de la Déesse',
ES: 'Lira de la Diosa'
},
Level: 'Level 1',
WeaponID: 0x24,
},
1: {
Name: {
EN: 'Typhoon Harp',
DE: 'Lyra des Sturms',
FR: 'Lyre des tempêtes',
ES: 'Lira de la tormenta'
},
Level: 'Level 2',
WeaponID: 0x25,
},
2: {
Name: {
EN: 'Triforce Harp',
DE: 'Lyra der Shiekah',
FR: 'Lyre des Sheikahs',
ES: 'Lira sheikah'
},
Level: 'Level 3',
WeaponID: 0x26,
},
3: {
Name: {
EN: 'Triforce Harp +',
DE: 'Lyra der Shiekah +',
FR: 'Lyre des Sheikahs DX',
ES: 'Lira sheikah +'
},
Level: 'Level 4',
WeaponID: 0x49,
},
4: {
Name: {
EN: 'Shining Harp',
DE: 'Lichtharfe',
FR: 'Lyre de lumière',
ES: 'Lira resplandeciente'
},
Level: 'Level 4+',
WeaponID: 0x9c,
},
},
},
},
'Impa': {
0: {
ClassName: {
EN: 'Giant Blade',
DE: 'Grossschwert',
FR: 'Épée géante',
ES: 'Espadas gigantes'
},
Weapons: {
0: {
Name: {
EN: 'Giant\'s Knife',
DE: 'Langschwert',
FR: 'Épée gravée',
ES: 'Espada grabada'
},
Level: 'Level 1',
WeaponID: 0x1b,
},
1: {
Name: {
EN: 'Biggoron\'s Knife',
DE: 'Biggoron-Klinge',
FR: 'Épée affilée',
ES: 'Hoja de Biggoron'
},
Level: 'Level 2',
WeaponID: 0x1c,
},
2: {
Name: {
EN: 'Biggoron\'s Sword',
DE: 'Biggoron-Schwert',
FR: 'Épée supérieure',
ES: 'Espada de Biggoron'
},
Level: 'Level 3',
WeaponID: 0x1d,
},
3: {
Name: {
EN: 'Biggoron\'s Sword +',
DE: 'Biggoron-Schwert +',
FR: 'Épée supérieure DX',
ES: 'Espada de Biggoron +'
},
Level: 'Level 4',
WeaponID: 0x46,
},
4: {
Name: {
EN: 'Biggoron\'s Sunblade',
DE: 'Biggoron-Glanzschwert',
FR: 'Épée supérieure de lumière',
ES: 'Espada de Biggoron brillante'
},
Level: 'Level 4+',
WeaponID: 0xc7,
},
},
},
1: {
ClassName: {
EN: 'Naginata',
DE: 'Naginata',
FR: 'Naginata',
ES: 'Naginatas'
},
Weapons: {
0: {
Name: {
EN: 'Guardian Naginata',
DE: 'Naginata der Hüterin',
FR: 'Naginata du gardien',
ES: 'Naginata del guardián'
},
Level: 'Level 1',
WeaponID: 0x1e,
},
1: {
Name: {
EN: 'Scorching Naginata',
DE: 'Glut-Naginata',
FR: 'Naginata enflammé',
ES: 'Naginata ígnea'
},
Level: 'Level 2',
WeaponID: 0x1f,
},
2: {
Name: {
EN: 'Sheikah Naginata',
DE: 'Naginata der Ahnen',
FR: 'Naginata clanique',
ES: 'Naginata heredada'
},
Level: 'Level 3',
WeaponID: 0x20,
},
3: {
Name: {
EN: 'Sheikah Naginata +',
DE: 'Naginata der Ahnen +',
FR: 'Naginata clanique DX',
ES: 'Naginata heredada +'
},
Level: 'Level 4',
WeaponID: 0x47,
},
4: {
Name: {
EN: 'Crackling Naginata',
DE: 'Blitzaginata der Ahnen',
FR: 'Naginata de foudre',
ES: 'Naginata del rayo'
},
Level: 'Level 4+',
WeaponID: 0xb0,
},
},
},
},
'Ganondorf': {
0: {
ClassName: {
EN: 'Great Swords',
DE: 'Breitschwerter',
FR: 'Grandes épées',
ES: 'Espadas dobles'
},
Weapons: {
0: {
Name: {
EN: 'Swords of Despair',
DE: 'Schwerter des Bösen',
FR: 'Épées du mal',
ES: 'Espadas del Mal'
},
Level: 'Level 1',
WeaponID: 0x21,
},
1: {
Name: {
EN: 'Swords of Darkness',
DE: 'Schwerter der Finsternis',
FR: 'Épées des ténèbres',
ES: 'Espadas tenebrosas'
},
Level: 'Level 2',
WeaponID: 0x22,
},
2: {
Name: {
EN: 'Swords of Demise',
DE: 'Todbringer-Schwerter',
FR: 'Épées du néant',
ES: 'Espadas del Heraldo'
},
Level: 'Level 3',
WeaponID: 0x23,
},
3: {
Name: {
EN: 'Swords of Demise +',
DE: 'Todbringer-Schwerter +',
FR: 'Épées du néant DX',
ES: 'Espadas del Heraldo +'
},
Level: 'Level 4',
WeaponID: 0x48,
},
4: {
Name: {
EN: 'Swords of Renewal',
DE: 'Todbringer-Hellschwerter',
FR: 'Épées du néant de lumière',
ES: 'Esp. del Heraldo resplandecientes'
},
Level: 'Level 4+',
WeaponID: 0xc8,
},
},
},
1: {
ClassName: {
EN: 'Trident',
DE: 'Dreizack',
FR: 'Trident',
ES: 'Tridentes'
},
Weapons: {
0: {
Name: {
EN: 'Thief\'s Trident',
DE: 'Diebesdreizack',
FR: 'Trident des voleurs',
ES: 'Tridente del ladrón'
},
Level: 'Level 1',
WeaponID: 0x6e,
},
1: {
Name: {
EN: 'King of Evil Trident',
DE: 'Dämonendreizack',
FR: 'Trident du roi démon',
ES: 'Tridente del rey demonio'
},
Level: 'Level 2',
WeaponID: 0x6f,
},
2: {
Name: {
EN: 'Trident of Demise',
DE: 'Todbringerdreizack',
FR: 'Trident de néant',
ES: 'Tridente del Heraldo'
},
Level: 'Level 3',
WeaponID: 0x70,
},
3: {
Name: {
EN: 'Trident of Demise +',
DE: 'Todbringerdreizack +',
FR: 'Trident de néant DX',
ES: 'Tridente del Heraldo +'
},
Level: 'Level 4',
WeaponID: 0x89,
},
4: {
Name: {
EN: 'Burning Trident',
DE: 'Feuer-Todbringerdreizack',
FR: 'Trident de feu',
ES: 'Tridente ígneo'
},
Level: 'Level 4+',
WeaponID: 0xb3,
},
},
},
},
'Darunia': {
0: {
ClassName: {
EN: 'Hammer',
DE: 'Hammer',
FR: 'Marteau',
ES: 'Martillos'
},
Weapons: {
0: {
Name: {
EN: 'Magic Hammer',
DE: 'Hammer',
FR: 'Marteau magique',
ES: 'Martillo mágico'
},
Level: 'Level 1',
WeaponID: 0x27,
},
1: {
Name: {
EN: 'Igneous Hammer',
DE: 'Brandhammer',
FR: 'Marteau enflammé',
ES: 'Martillo ígneo'
},
Level: 'Level 2',
WeaponID: 0x28,
},
2: {
Name: {
EN: 'Megaton Hammer',
DE: 'Stahlhammer',
FR: 'Masse des titans',
ES: 'Martillo Megatón'
},
Level: 'Level 3',
WeaponID: 0x29,
},
3: {
Name: {
EN: 'Megaton Hammer +',
DE: 'Stahlhammer +',
FR: 'Masse de titans DX',
ES: 'Martillo Megatón +'
},
Level: 'Level 4',
WeaponID: 0x4a,
},
4: {
Name: {
EN: 'Darkfire Hammer',
DE: 'Dunkelhammer',
FR: 'Masse des ténèbres',
ES: 'Martillo oscuro'
},
Level: 'Level 4+',
WeaponID: 0x9e,
},
},
},
},
'Ruto': {
0: {
ClassName: {
EN: 'Zora Scale',
DE: 'Magische Schuppen',
FR: 'Accessoire magique',
ES: 'Escamas zora'
},
Weapons: {
0: {
Name: {
EN: 'Silver Scale',
DE: 'Silberne Schuppen',
FR: 'Écaille d\'argent',
ES: 'Escama de Plata'
},
Level: 'Level 1',
WeaponID: 0x2a,
},
1: {
Name: {
EN: 'Golden Scale',
DE: 'Goldene Schuppen',
FR: 'Écaille d\'or',
ES: 'Escama de Oro'
},
Level: 'Level 2',
WeaponID: 0x2b,
},
2: {
Name: {
EN: 'Water Dragon Scale',
DE: 'Wasserdrachenschuppen',
FR: 'Écaille dragon d\'eau',
ES: 'Escama de dragón'
},
Level: 'Level 3',
WeaponID: 0x2c,
},
3: {
Name: {
EN: 'Water Dragon Scale +',
DE: 'Wasserdrachenschuppen +',
FR: 'Écaille dragon d\'eau DX',
ES: 'Escama de dragón +'
},
Level: 'Level 4',
WeaponID: 0x4b,
},
4: {
Name: {
EN: 'Sun Dragon Scale',
DE: 'Lichtdrachenschuppen',
FR: 'Écaille de lumière',
ES: 'Escama de luz'
},
Level: 'Level 4+',
WeaponID: 0x9f,
},
},
},
},
'Agitha': {
0: {
ClassName: {
EN: 'Parasol',
DE: 'Schirm',
FR: 'Ombrelle',
ES: 'Parasoles'
},
Weapons: {
0: {
Name: {
EN: 'Butterfly Parasol',
DE: 'Schmetterlingsschirm',
FR: 'Ombrelle de papillon',
ES: 'Parasol de mariposa'
},
Level: 'Level 1',
WeaponID: 0x2d,
},
1: {
Name: {
EN: 'Luna Parasol',
DE: 'Luna-Schirm',
FR: 'Ombrelle Luna',
ES: 'Parasol de luna'
},
Level: 'Level 2',
WeaponID: 0x2e,
},
2: {
Name: {
EN: 'Princess Parasol',
DE: 'Prinzessinnenschirm',
FR: 'Ombrelle princière',
ES: 'Parasol de princesa'
},
Level: 'Level 3',
WeaponID: 0x2f,
},
3: {
Name: {
EN: 'Princess Parasol +',
DE: 'Prinzessinnenschirm +',
FR: 'Ombrelle princière DX',
ES: 'Parasol de princesa +'
},
Level: 'Level 4',
WeaponID: 0x4c,
},
4: {
Name: {
EN: 'Incandescent Parasol',
DE: 'Flammenschirm',
FR: 'Ombrelle de feu',
ES: 'Parasol incandescente'
},
Level: 'Level 4+',
WeaponID: 0xa0,
},
},
},
},
'Midna': {
0: {
ClassName: {
EN: 'Shackle',
DE: 'Fessel',
FR: 'Accessoire maudit',
ES: 'Grilletes'
},
Weapons: {
0: {
Name: {
EN: 'Cursed Shackle',
DE: 'Fluchfessel',
FR: 'Anneau maudit',
ES: 'Grillete maldito'
},
Level: 'Level 1',
WeaponID: 0x30,
},
1: {
Name: {
EN: 'Twilight Shackle',
DE: 'Schattenfessel',
FR: 'Anneau des ombres',
ES: 'Grillete del Crepúsculo'
},
Level: 'Level 2',
WeaponID: 0x31,
},
2: {
Name: {
EN: 'Sol Shackle',
DE: 'Sol-Fessel',
FR: 'Anneau Astre',
ES: 'Grillete de Taiyo'
},
Level: 'Level 3',
WeaponID: 0x32,
},
3: {
Name: {
EN: 'Sol Shackle +',
DE: 'Sol-Fessel +',
FR: 'Anneau Astre DX',
ES: 'Grillete de Taiyo +'
},
Level: 'Level 4',
WeaponID: 0x4d,
},
4: {
Name: {
EN: 'Thunderhead Shackle',
DE: 'Donnerfessel',
FR: 'Anneau de foudre',
ES: 'Grillete del rayo'
},
Level: 'Level 4+',
WeaponID: 0xa1,
},
},
},
},
'Fi': {
0: {
ClassName: {
EN: 'Goddess Blade',
DE: 'Schwert der Göttin',
FR: 'Épée céleste',
ES: 'Espadas divinas'
},
Weapons: {
0: {
Name: {
EN: 'Goddess Sword',
DE: 'Schwert der Göttin',
FR: 'Épée divine',
ES: 'Espada divina'
},
Level: 'Level 1',
WeaponID: 0x33,
},
1: {
Name: {
EN: 'Goddess Longsword',
DE: 'Langschwert der Göttin',
FR: 'Longue épée divine',
ES: 'Gran espada divina'
},
Level: 'Level 2',
WeaponID: 0x34,
},
2: {
Name: {
EN: 'True Goddess Blade',
DE: 'Weißes Schwert',
FR: 'Blanche épée divine',
ES: 'Espada divina alba'
},
Level: 'Level 3',
WeaponID: 0x35,
},
3: {
Name: {
EN: 'True Goddess Blade +',
DE: 'Weißes Schwert +',
FR: 'Blanche épée divine DX',
ES: 'Espada divina alba +'
},
Level: 'Level 4',
WeaponID: 0x4e,
},
4: {
Name: {
EN: 'Liquid Goddess Blade',
DE: 'Weißwasserschwert',
FR: 'Blanche épée d\'eau',
ES: 'Espada acuática'
},
Level: 'Level 4+',
WeaponID: 0xa2,
},
},
},
},
'Ghirahim': {
0: {
ClassName: {
EN: 'Demon Blade',
DE: 'Dämonenschwert',
FR: 'Épée démoniaque',
ES: 'Espadas demoníacas'
},
Weapons: {
0: {
Name: {
EN: 'Demon Tribe Sword',
DE: 'Dämonenschwert',
FR: 'Épée des démons',
ES: 'Espada tribal'
},
Level: 'Level 1',
WeaponID: 0x36,
},
1: {
Name: {
EN: 'Demon Longsword',
DE: 'Dämonenlangschwert',
FR: 'Longue épée démons',
ES: 'Gran espada demoníaca'
},
Level: 'Level 2',
WeaponID: 0x37,
},
2: {
Name: {
EN: 'True Demon Blade',
DE: 'Schwarzes Schwert',
FR: 'Noire épée démons',
ES: 'Espada mágica oscura'
},
Level: 'Level 3',
WeaponID: 0x38,
},
3: {
Name: {
EN: 'True Demon Blade +',
DE: 'Schwarzes Schwert +',
FR: 'Noire épée démons DX',
ES: 'Espada mágica oscura +'
},
Level: 'Level 4',
WeaponID: 0x4f,
},
4: {
Name: {
EN: 'Darkfire Demon Blade',
DE: 'Schwarzes Feuerschwert',
FR: 'Noire épée de feu',
ES: 'Espada ígnea oscura'
},
Level: 'Level 4+',
WeaponID: 0xb5,
},
},
},
},
'Zant': {
0: {
ClassName: {
EN: 'Scimitars',
DE: 'Krummsäbel',
FR: 'Épées courbes',
ES: 'Cimitarras'
},
Weapons: {
0: {
Name: {
EN: 'Usurper\'s Scimitars',
DE: 'Säbel des Usurpators',
FR: 'Sabres de l\'usurpateur',
ES: 'Cimitarras del usurpador'
},
Level: 'Level 1',
WeaponID: 0x39,
},
1: {
Name: {
EN: 'Shadow Scimitars',
DE: 'Schattensäbel',
FR: 'Sabres de l\'ombre',
ES: 'Cimitarras tenebrosas'
},
Level: 'Level 2',
WeaponID: 0x3a,
},
2: {
Name: {
EN: 'Scimitars of Twilight',
DE: 'Säbel der Düsternis',
FR: 'Sabres du Crépuscule',
ES: 'Cimitarras crepusculares'
},
Level: 'Level 3',
WeaponID: 0x3b,
},
3: {
Name: {
EN: 'Scimitars of Twilight +',
DE: 'Säbel der Düsternis +',
FR: 'Sabres du Crépuscule DX',
ES: 'Cimitarras crepusculares +'
},
Level: 'Level 4',
WeaponID: 0x50,
},
4: {
Name: {
EN: 'Darkwater Scimitars',
DE: 'Wassersäbel d. Düsternis',
FR: 'Sabres d\'eau',
ES: 'Cimitarras del agua'
},
Level: 'Level 4+',
WeaponID: 0xb4,
},
},
},
},
'Lana': {
0: {
ClassName: {
EN: 'Book of Sorcery',
DE: 'Zauberbuch',
FR: 'Grimoire',
ES: 'Libros de hechizos'
},
Weapons: {
0: {
Name: {
EN: 'Spirit\'s Tome',
DE: 'Zauberbuch des Geistes',
FR: 'Grimoire de l\'esprit',
ES: 'Libro de espíritus'
},
Level: 'Level 1',
WeaponID: 0x0c,
},
1: {
Name: {
EN: 'Sealing Tome',
DE: 'Versiegeltes Zauberbuch',
FR: 'Grimoire du sceau',
ES: 'Libro sellado'
},
Level: 'Level 2',
WeaponID: 0x0d,
},
2: {
Name: {
EN: 'Sorceress Tome',
DE: 'Zauberbuch der Himmel',
FR: 'Grimoire céleste',
ES: 'Libro del firmamento'
},
Level: 'Level 3',
WeaponID: 0x0e,
},
3: {
Name: {
EN: 'Sorceress Tome +',
DE: 'Zauberbuch der Himmel +',
FR: 'Grimoire céleste DX',
ES: 'Libro del firmamento +'
},
Level: 'Level 4',
WeaponID: 0x41,
},
4: {
Name: {
EN: 'Tome of the Night',
DE: 'Zauberbuch des Dunkels',
FR: 'Grimoire des ténèbres',
ES: 'Libro oscuro'
},
Level: 'Level 4+',
WeaponID: 0xc5,
},
},
},
1: {
ClassName: {
EN: 'Spear',
DE: 'Stab',
FR: 'Grand arbre',
ES: 'Lanzas'
},
Weapons: {
0: {
Name: {
EN: 'Deku Spear',
DE: 'Deku-Stab',
FR: 'Drageon mojo',
ES: 'Lanza deku'
},
Level: 'Level 1',
WeaponID: 0x0f,
},
1: {
Name: {
EN: 'Kokiri Spear',
DE: 'Kokiri-Stab',
FR: 'Drageon kokiri',
ES: 'Lanza kokiri'
},
Level: 'Level 2',
WeaponID: 0x10,
},
2: {
Name: {
EN: 'Faron Spear',
DE: 'Phirone-Stab',
FR: 'Drageon de Firone',
ES: 'Lanza de Farone'
},
Level: 'Level 3',
WeaponID: 0x11,
},
3: {
Name: {
EN: 'Faron Spear +',
DE: 'Phirone-Stab +',
FR: 'Drageon de Firone DX',
ES: 'Lanza de Farone +'
},
Level: 'Level 4',
WeaponID: 0x42,
},
4: {
Name: {
EN: 'Sun Faron Spear',
DE: 'Phirone-Lichtstab',
FR: 'Drageon de lumière',
ES: 'Lanza de luz'
},
Level: 'Level 4+',
WeaponID: 0xb1,
},
},
},
2: {
ClassName: {
EN: 'Summoning Gate',
DE: 'Portal',
FR: 'Porte d\'invocation',
ES: 'Portales'
},
Weapons: {
0: {
Name: {
EN: 'Gate of Time',
DE: 'Zeitportal',
FR: 'Porte du temps',
ES: 'Portal del Tiempo'
},
Level: 'Level 1',
WeaponID: 0x12,
},
1: {
Name: {
EN: 'Guardian\'s Gate',
DE: 'Hüterportal',
FR: 'Porte des veilleurs',
ES: 'Portal del Guardián'
},
Level: 'Level 2',
WeaponID: 0x13,
},
2: {
Name: {
EN: 'Gate of Souls',
DE: 'Seelenportal',
FR: 'Porte des âmes',
ES: 'Portal de las Almas'
},
Level: 'Level 3',
WeaponID: 0x14,
},
3: {
Name: {
EN: 'Gate of Souls +',
DE: 'Seelenportal +',
FR: 'Porte des âmes DX',
ES: 'Portal de las Almas +'
},
Level: 'Level 4',
WeaponID: 0x43,
},
4: {
Name: {
EN: 'Gate of Tides',
DE: 'Portal der Gezeiten',
FR: 'Porte d\'eau',
ES: 'Portal de las Mareas'
},
Level: 'Level 4+',
WeaponID: 0x9d,
},
},
},
},
'Cia': {
0: {
ClassName: {
EN: 'Scepter',
DE: 'Zepter',
FR: 'Sceptre',
ES: 'Báculos'
},
Weapons: {
0: {
Name: {
EN: 'Scepter of Time',
DE: 'Zepter der Zeit',
FR: 'Sceptre du temps',
ES: 'Báculo del tiempo'
},
Level: 'Level 1',
WeaponID: 0x51,
},
1: {
Name: {
EN: 'Guardian\'s Scepter',
DE: 'Zepter der Hüterin',
FR: 'Sceptre des veilleurs',
ES: 'Báculo del Guardián'
},
Level: 'Level 2',
WeaponID: 0x52,
},
2: {
Name: {
EN: 'Scepter of Souls',
DE: 'Zepter der Seelen',
FR: 'Sceptre des âmes',
ES: 'Báculo de las Almas'
},
Level: 'Level 3',
WeaponID: 0x53,
},
3: {
Name: {
EN: 'Scepter of Souls +',
DE: 'Zepter der Seelen +',
FR: 'Sceptre des âmes DX',
ES: 'Báculo de las Almas +'
},
Level: 'Level 4',
WeaponID: 0x80,
},
4: {
Name: {
EN: 'Crackling Scepter',
DE: 'Blitz-Zepter der Seelen',
FR: 'Sceptre de foudre',
ES: 'Báculo del rayo'
},
Level: 'Level 4+',
WeaponID: 0xb6,
},
},
},
},
'Volga': {
0: {
ClassName: {
EN: 'Dragon Spear',
DE: 'Drachenspeer',
FR: 'Lance martiale',
ES: 'Picas'
},
Weapons: {
0: {
Name: {
EN: 'Dragonbone Pike',
DE: 'Drachenbein',
FR: 'Os massif de dragon',
ES: 'Pica del dragón'
},
Level: 'Level 1',
WeaponID: 0x54,
},
1: {
Name: {
EN: 'Stonecleaver Claw',
DE: 'Bergspalter',
FR: 'Griffe volcanique',
ES: 'Pica ígnea'
},
Level: 'Level 2',
WeaponID: 0x55,
},
2: {
Name: {
EN: 'Flesh-Render Fang',
DE: 'Blutfang',
FR: 'Croc sanguinolent',
ES: 'Pica sanguinaria'
},
Level: 'Level 3',
WeaponID: 0x56,
},
3: {
Name: {
EN: 'Flesh-Render Fang +',
DE: 'Blutfang +',
FR: 'Croc sanguinolent DX',
ES: 'Pica sanguinaria +'
},
Level: 'Level 4',
WeaponID: 0x81,
},
4: {
Name: {
EN: 'Darkfire Fang',
DE: 'Finsternisblutfang',
FR: 'Croc des ténèbres',
ES: 'Pica oscura'
},
Level: 'Level 4+',
WeaponID: 0xb7,
},
},
},
},
'Wizzro': {
0: {
ClassName: {
EN: 'Ring',
DE: 'Ring',
FR: 'Bague',
ES: 'Anillos'
},
Weapons: {
0: {
Name: {
EN: 'Blue Ring',
DE: 'Blauer Ring',
FR: 'Bague bleue',
ES: 'Anillo azul'
},
Level: 'Level 1',
WeaponID: 0x57,
},
1: {
Name: {
EN: 'Red Ring',
DE: 'Roter Ring',
FR: 'Bague rouge',
ES: 'Anillo carmesí'
},
Level: 'Level 2',
WeaponID: 0x58,
},
2: {
Name: {
EN: 'Magical Ring',
DE: 'Magischer Ring',
FR: 'Bague magique',
ES: 'Anillo mágico'
},
Level: 'Level 3',
WeaponID: 0x59,
},
3: {
Name: {
EN: 'Magical Ring +',
DE: 'Magischer Ring +',
FR: 'Bague magique DX',
ES: 'Anillo mágico +'
},
Level: 'Level 4',
WeaponID: 0x82,
},
4: {
Name: {
EN: 'Darkwater Ring',
DE: 'Magischer Wasserring',
FR: 'Bague d\'eau',
ES: 'Anillo del agua'
},
Level: 'Level 4+',
WeaponID: 0xb8,
},
},
},
},
'Twili Midna': {
0: {
ClassName: {
EN: 'Mirror',
DE: 'Spiegel',
FR: 'Miroir',
ES: 'Espejos'
},
Weapons: {
0: {
Name: {
EN: 'Mirror of Shadows',
DE: 'Düsterspiegel',
FR: 'Miroir obscur',
ES: 'Espejo de las sombras'
},
Level: 'Level 1',
WeaponID: 0x5d,
},
1: {
Name: {
EN: 'Mirror of Silence',
DE: 'Dämmerungsspiegel',
FR: 'Miroir du Crépuscule',
ES: 'Espejo del anochecer'
},
Level: 'Level 2',
WeaponID: 0x5e,
},
2: {
Name: {
EN: 'Mirror of Twilight',
DE: 'Schattenspiegel',
FR: 'Miroir des ombres',
ES: 'Espejo del Crepúsculo'
},
Level: 'Level 3',
WeaponID: 0x5f,
},
3: {
Name: {
EN: 'Mirror of Twilight +',
DE: 'Schattenspiegel +',
FR: 'Miroir des ombres DX',
ES: 'Espejo del Crepúsculo +'
},
Level: 'Level 4',
WeaponID: 0x84,
},
4: {
Name: {
EN: 'Darklight Mirror',
DE: 'Schatterlichtspiegel',
FR: 'Miroir de lumière',
ES: 'Espejo de la luz'
},
Level: 'Level 4+',
WeaponID: 0xb9,
},
},
},
},
'Young Link': {
0: {
ClassName: {
EN: 'Mask',
DE: 'Maske',
FR: 'Masque',
ES: 'Máscaras'
},
Weapons: {
0: {
Name: {
EN: 'Fierce Deity Mask',
DE: 'Grimmige Gottheit',
FR: 'Dieu démon',
ES: 'Fiera Deidad'
},
Level: 'Level 1',
WeaponID: 0x66,
},
1: {
Name: {
EN: 'Furious Deity Mask',
DE: 'Zornige Gottheit',
FR: 'Dieu démon véritable',
ES: 'Verdadera Deidad'
},
Level: 'Level 2',
WeaponID: 0x67,
},
2: {
Name: {
EN: 'Vengeful Deity Mask',
DE: 'Rasende Gottheit',
FR: 'Dieu démon ultime',
ES: 'Máxima Deidad'
},
Level: 'Level 3',
WeaponID: 0x68,
},
3: {
Name: {
EN: 'Vengeful Deity Mask +',
DE: 'Rasende Gottheit +',
FR: 'Dieu démon ultime DX',
ES: 'Máxima Deidad +'
},
Level: 'Level 4',
WeaponID: 0x87,
},
4: {
Name: {
EN: 'Inflamed Deity\'s Mask',
DE: 'Feurige Gottheit',
FR: 'Dieu démon de feu',
ES: 'Ígnea Deidad'
},
Level: 'Level 4+',
WeaponID: 0xa3,
},
},
},
},
'Tingle': {
0: {
ClassName: {
EN: 'Balloon',
DE: 'Ballon',
FR: 'Ballon',
ES: 'Globos'
},
Weapons: {
0: {
Name: {
EN: 'Rosy Balloon',
DE: 'Rosiger Ballon',
FR: 'Ballon pétale de rose',
ES: 'Globo rojizo'
},
Level: 'Level 1',
WeaponID: 0x69,
},
1: {
Name: {
EN: 'Love-Filled Balloon',
DE: 'Liebesballon',
FR: 'Ballon de la passion',
ES: 'Globo amoroso'
},
Level: 'Level 2',
WeaponID: 0x6a,
},
2: {
Name: {
EN: 'Mr. Fairy Balloon',
DE: 'Feen-Ballon',
FR: 'Ballon de M. Fée',
ES: 'Globo del hada'
},
Level: 'Level 3',
WeaponID: 0x6b,
},
3: {
Name: {
EN: 'Mr. Fairy Balloon +',
DE: 'Feen-Ballon +',
FR: 'Ballon de M. Fée DX',
ES: 'Globo del hada +'
},
Level: 'Level 4',
WeaponID: 0x88,
},
4: {
Name: {
EN: 'Liquid Fire Balloon',
DE: 'Feen-Wasserballon',
FR: 'Ballon d\'eau',
ES: 'Globo del agua'
},
Level: 'Level 4+',
WeaponID: 0xba,
},
},
},
},
'Ganon': {
0: {
ClassName: {
EN: 'Ganon',
DE: 'Ganon',
FR: 'Ganon',
ES: 'Ganon'
},
Weapons: {
0: {
Name: {
EN: 'Ganon\'s Rage ',
DE: 'Ganon\'s Rage ',
FR: 'Ganon\'s Rage ',
ES: 'Ganon\'s Rage '
},
Level: 'Level 1',
WeaponID: 0x6c,
},
},
},
},
'Cucco': {
0: {
ClassName: {
EN: 'Giant\'s Cucco',
DE: 'Giant\'s Cucco',
FR: 'Giant\'s Cucco',
ES: 'Giant\'s Cucco'
},
Weapons: {
0: {
Name: {
EN: 'Cucco\'s Spirit',
DE: 'Cucco\'s Spirit',
FR: 'Cucco\'s Spirit',
ES: 'Cucco\'s Spirit'
},
Level: 'Level 1',
WeaponID: 0x6d,
},
},
},
},
'Linkle': {
0: {
ClassName: {
EN: 'Crossbows',
DE: 'Armbrüste',
FR: 'Arbalètes',
ES: 'Ballestas'
},
Weapons: {
0: {
Name: {
EN: 'Simple Crossbows',
DE: 'Armbrüste',
FR: 'Arbalètes',
ES: 'Ballestas básicas'
},
Level: 'Level 1',
WeaponID: 0x71,
},
1: {
Name: {
EN: 'Hylian Crossbows',
DE: 'Trainings-Armbrüste',
FR: 'Arbalètes d\'entrainement',
ES: 'Ballestas hylianas'
},
Level: 'Level 2',
WeaponID: 0x72,
},
2: {
Name: {
EN: 'Legend\'s Crossbows',
DE: 'Legendäre Armbrüste',
FR: 'Arbalètes du guide',
ES: 'Ballestas legendarias'
},
Level: 'Level 3',
WeaponID: 0x73,
},
3: {
Name: {
EN: 'Legend\'s Crossbows +',
DE: 'Legendäre Armbrüste +',
FR: 'Arbalètes du guide DX',
ES: 'Ballestas legendarias +'
},
Level: 'Level 4',
WeaponID: 0x8a,
},
4: {
Name: {
EN: 'Luminous Crossbows',
DE: 'Legendäre Lichtarmbrüste',
FR: 'Arbalètes de lumière',
ES: 'Ballestas resplandecientes'
},
Level: 'Level 4+',
WeaponID: 0xcc,
},
},
},
1: {
ClassName: {
EN: 'Boots',
DE: 'Stiefel',
FR: 'Bottes',
ES: 'Botas'
},
Weapons: {
0: {
Name: {
EN: 'Winged Boots',
DE: 'Schwingenstiefel',
FR: 'Bottes ailées',
ES: 'Botas aladas'
},
Level: 'Level 1',
WeaponID: 0x97,
},
1: {
Name: {
EN: 'Roc Boots',
DE: 'Heilige Stiefel',
FR: 'Bottes sacrées',
ES: 'Botas de Roc'
},
Level: 'Level 2',
WeaponID: 0x98,
},
2: {
Name: {
EN: 'Pegasus Boots',
DE: 'Pegasusstiefel',
FR: 'Bottes de Pégase',
ES: 'Botas Pegaso'
},
Level: 'Level 3',
WeaponID: 0x99,
},
3: {
Name: {
EN: 'Pegasus Boots +',
DE: 'Pegasusstiefel +',
FR: 'Botte de Pégase DX',
ES: 'Botas Pegaso +'
},
Level: 'Level 4',
WeaponID: 0x9a,
},
4: {
Name: {
EN: 'Gleambolt Pegasus Boots',
DE: 'Lichtblitz-Pegasusstiefel',
FR: 'Bottes de lumière',
ES: 'Botas Pegaso resplandecientes'
},
Level: 'Level 4+',
WeaponID: 0xd0,
},
},
},
},
'Skull Kid': {
0: {
ClassName: {
EN: 'Ocarina',
DE: 'Okarina',
FR: 'Ocarina',
ES: 'Ocarinas'
},
Weapons: {
0: {
Name: {
EN: 'Fairy Ocarina',
DE: 'Feen-Okarina',
FR: 'Ocarina des fées',
ES: 'Ocarina de las Hadas'
},
Level: 'Level 1',
WeaponID: 0x74,
},
1: {
Name: {
EN: 'Lunar Ocarina',
DE: 'Mond-Okarina',
FR: 'Ocarina de la lune',
ES: 'Ocarina de la luna'
},
Level: 'Level 2',
WeaponID: 0x75,
},
2: {
Name: {
EN: 'Majora\'s Ocarina',
DE: 'Majoras Okarina',
FR: 'Ocarina de Majora',
ES: 'Ocarina de Majora'
},
Level: 'Level 3',
WeaponID: 0x76,
},
3: {
Name: {
EN: 'Majora\'s Ocarina +',
DE: 'Majoras Okarina +',
FR: 'Ocarina de Majora DX',
ES: 'Ocarina de Majora +'
},
Level: 'Level 4',
WeaponID: 0x8b,
},
4: {
Name: {
EN: 'Crackling Ocarina',
DE: 'Schock-Okarina',
FR: 'Ocarina de foudre',
ES: 'Ocarina del rayo'
},
Level: 'Level 4+',
WeaponID: 0xa4,
},
},
},
},
'Toon Link': {
0: {
ClassName: {
EN: 'Light Sword',
DE: 'Kurzschwert',
FR: 'Épée à une main',
ES: 'Espadas'
},
Weapons: {
0: {
Name: {
EN: 'Hero\'s Sword',
DE: 'Heroenschwert',
FR: 'Épée du Héros',
ES: 'Espada del hèroe'
},
Level: 'Level 1',
WeaponID: 0x77,
},
1: {
Name: {
EN: 'Phantom Sword',
DE: 'Phantomschwert',
FR: 'Épée spectrale',
ES: 'Espada del Más Allá'
},
Level: 'Level 2',
WeaponID: 0x78,
},
2: {
Name: {
EN: 'Lokomo Sword',
DE: 'Lokomo-Schwert',
FR: 'Épée Locomo',
ES: 'Espada Trenebunda'
},
Level: 'Level 3',
WeaponID: 0x79,
},
3: {
Name: {
EN: 'Lokomo Sword +',
DE: 'Lokomo-Schwert +',
FR: 'Épée Locomo DX',
ES: 'Espada Trenebunda +'
},
Level: 'Level 4',
WeaponID: 0x8c,
},
4: {
Name: {
EN: 'Lokomo Sword of Oceans',
DE: 'Lokomo-Wasserschwert',
FR: 'Épée Locomo d\'eau',
ES: 'Espada Trenebunda de agua'
},
Level: 'Level 4+',
WeaponID: 0xcd,
},
},
},
1: {
ClassName: {
EN: 'Sand Wand',
DE: 'Sandstab',
FR: 'Baguette des sables',
ES: 'Báculos de las arenas'
},
Weapons: {
0: {
Name: {
EN: 'Sand Wand',
DE: 'Sandstab',
FR: 'Baguette des sables',
ES: 'Báculo de las Arenas'
},
Level: 'Level 1',
WeaponID: 0xab,
},
1: {
Name: {
EN: 'Jeweled Sand Wand',
DE: 'Juwelen-Sandstab',
FR: 'Baguette des sables mod.',
ES: 'Báculo superior'
},
Level: 'Level 2',
WeaponID: 0xac,
},
2: {
Name: {
EN: 'Nice Sand Wand',
DE: 'Deluxe-Sandstab',
FR: 'Great baguette des sables',
ES: 'Báculo chulo'
},
Level: 'Level 3',
WeaponID: 0xad,
},
3: {
Name: {
EN: 'Nice Sand Wand +',
DE: 'Deluxe-Sandstab +',
FR: 'Great baguette des sables DX',
ES: 'Báculo chulo +'
},
Level: 'Level 4',
WeaponID: 0xae,
},
4: {
Name: {
EN: 'Darkfire Nice Sand Wand',
DE: 'Schwarzer Deluxe-Sandstab',
FR: 'Baguette des ténèbres',
ES: 'Báculo chulo oscuro'
},
Level: 'Level 4+',
WeaponID: 0xd2,
},
},
},
},
'Tetra': {
0: {
ClassName: {
EN: 'Cutlass',
DE: 'Säbel',
FR: 'Sabre d\'abordage',
ES: 'Sables'
},
Weapons: {
0: {
Name: {
EN: 'Pirate Cutlass',
DE: 'Piratensäbel',
FR: 'Sabre de pirate',
ES: 'Sable pirata'
},
Level: 'Level 1',
WeaponID: 0x7a,
},
1: {
Name: {
EN: 'Jeweled Cutlass',
DE: 'Königssäbel',
FR: 'Sabre royal',
ES: 'Sable real'
},
Level: 'Level 2',
WeaponID: 0x7b,
},
2: {
Name: {
EN: 'Regal Cutlass',
DE: 'Schwingensäbel',
FR: 'Sabre inestimable',
ES: 'Sable supremo'
},
Level: 'Level 3',
WeaponID: 0x7c,
},
3: {
Name: {
EN: 'Regal Cutlass +',
DE: 'Schwingensäbel +',
FR: 'Sabre inestimable DX',
ES: 'Sable supremo +'
},
Level: 'Level 4',
WeaponID: 0x8d,
},
4: {
Name: {
EN: 'Cutlass of Light',
DE: 'Lichtschwingensäbel',
FR: 'Sabre de lumière',
ES: 'Sable resplandeciente'
},
Level: 'Level 4+',
WeaponID: 0xa5,
},
},
},
},
'King Daphnes': {
0: {
ClassName: {
EN: 'Sail',
DE: 'Segel',
FR: 'Voile',
ES: 'Velas'
},
Weapons: {
0: {
Name: {
EN: 'Windfall Sail',
DE: 'Bootsegel',
FR: 'Voile de bateau',
ES: 'Vela'
},
Level: 'Level 1',
WeaponID: 0x7d,
},
1: {
Name: {
EN: 'Swift Sail',
DE: 'Siebenmeilen-Segel',
FR: 'Voile rapide',
ES: 'Vela veloz'
},
Level: 'Level 2',
WeaponID: 0x7e,
},
2: {
Name: {
EN: 'Sail of Red Lions',
DE: 'Triforce-Segel',
FR: 'Voile de la Triforce',
ES: 'Vela del Mascarón Rojo'
},
Level: 'Level 3',
WeaponID: 0x7f,
},
3: {
Name: {
EN: 'Sail of Red Lions +',
DE: 'Triforce-Segel +',
FR: 'Voile de la Triforce DX',
ES: 'Vela del Mascarón Rojo +'
},
Level: 'Level 4',
WeaponID: 0x8e,
},
4: {
Name: {
EN: 'Supercharged Sail',
DE: 'Blitzsegel',
FR: 'Voile de foudre',
ES: 'Vela del rayo'
},
Level: 'Level 4+',
WeaponID: 0xa6,
},
},
},
},
'Medli': {
0: {
ClassName: {
EN: 'Rito Harp',
DE: 'Orni-Lyra',
FR: 'Lyre',
ES: 'Arpas'
},
Weapons: {
0: {
Name: {
EN: 'Sacred Harp',
DE: 'Heilige Lyra',
FR: 'Lyre sacrée',
ES: 'Arpa sagrada'
},
Level: 'Level 1',
WeaponID: 0x8f,
},
1: {
Name: {
EN: 'Earth God\'s Harp',
DE: 'Terragott-Lyra',
FR: 'Lyre Dieu de la terre',
ES: 'Arpa de la Tierra'
},
Level: 'Level 2',
WeaponID: 0x90,
},
2: {
Name: {
EN: 'Din\'s Harp',
DE: 'Dins Lyra',
FR: 'Lyre de Din',
ES: 'Arpa de Din'
},
Level: 'Level 3',
WeaponID: 0x91,
},
3: {
Name: {
EN: 'Din\'s Harp +',
DE: 'Dins Lyra +',
FR: 'Lyre de Din DX',
ES: 'Arpa de Din +'
},
Level: 'Level 4',
WeaponID: 0x92,
},
4: {
Name: {
EN: 'Din\'s Harp of Oceans',
DE: 'Dins Wasser-Lyra',
FR: 'Lyre d\'eau',
ES: 'Arpa de Din oceánica'
},
Level: 'Level 4+',
WeaponID: 0xce,
},
},
},
},
'Marin': {
0: {
ClassName: {
EN: 'Bell',
DE: 'Glocke',
FR: 'Cloche',
ES: 'Campanas'
},
Weapons: {
0: {
Name: {
EN: 'Sea Lily Bell',
DE: 'Nixenglöckchen',
FR: 'Cloche des Algues',
ES: 'Campana del Mar'
},
Level: 'Level 1',
WeaponID: 0x93,
},
1: {
Name: {
EN: 'Wavelet Bell',
DE: 'Glocke der Wellen',
FR: 'Cloche de l\'Onde',
ES: 'Campana de las Olas'
},
Level: 'Level 2',
WeaponID: 0x94,
},
2: {
Name: {
EN: 'Awakening Bell',
DE: 'Glocke des Erwachens',
FR: 'Cloche de l\'Éveil',
ES: 'Campana del Despertar'
},
Level: 'Level 3',
WeaponID: 0x95,
},
3: {
Name: {
EN: 'Awakening Bell +',
DE: 'Glocke des Erwachens +',
FR: 'Cloche de l\'Éveil DX',
ES: 'Campana del Despertar +'
},
Level: 'Level 4',
WeaponID: 0x96,
},
4: {
Name: {
EN: 'Awakening Sunbell',
DE: 'Glanzglocke des Erwachens',
FR: 'Cloche de lumière',
ES: 'Campana del Despertar luminosa'
},
Level: 'Level 4+',
WeaponID: 0xcf,
},
},
},
},
'Toon Zelda': {
0: {
ClassName: {
EN: 'Phantom Arms',
DE: 'Phantomwaffen',
FR: 'Épée de gardien',
ES: 'Espadas espectrales'
},
Weapons: {
0: {
Name: {
EN: 'Protector Sword',
DE: 'Beschützerschwert',
FR: 'Épée de spectre',
ES: 'Espada espectral'
},
Level: 'Level 1',
WeaponID: 0xa7,
},
1: {
Name: {
EN: 'Warp Sword',
DE: 'Teleportschwert',
FR: 'Épée de téléporteur',
ES: 'Espada disruptora'
},
Level: 'Level 2',
WeaponID: 0xa8,
},
2: {
Name: {
EN: 'Wrecker Sword',
DE: 'Trümmerschwert',
FR: 'Épée d\'acier',
ES: 'Espada de acero'
},
Level: 'Level 3',
WeaponID: 0xa9,
},
3: {
Name: {
EN: 'Wrecker Sword +',
DE: 'Trümmerschwert +',
FR: 'Épée d\'acier',
ES: 'Espada de acero +'
},
Level: 'Level 4',
WeaponID: 0xaa,
},
4: {
Name: {
EN: 'Flaming Wrecker Sword',
DE: 'Flammendes Trümmerschwert',
FR: 'Épée d\'acier de feu',
ES: 'Espada de acero ígnea'
},
Level: 'Level 4+',
WeaponID: 0xd1,
},
},
},
},
'Ravio': {
0: {
ClassName: {
EN: 'Rental Hammer',
DE: 'Leih-Hammer',
FR: 'Marteau',
ES: 'Martillos de alquiler'
},
Weapons: {
0: {
Name: {
EN: 'Wooden Hammer',
DE: 'Holzhammer',
FR: 'Marteau en bois',
ES: 'Martillo de madera'
},
Level: 'Level 1',
WeaponID: 0xbb,
},
1: {
Name: {
EN: 'White Bunny Hammer',
DE: 'Hasenhammer',
FR: 'Marteau du lapin blanc',
ES: 'Martillo de conejo'
},
Level: 'Level 2',
WeaponID: 0xbc,
},
2: {
Name: {
EN: 'Nice Hammer',
DE: 'Super-Hammer',
FR: 'Great marteau',
ES: 'Martillo chulo'
},
Level: 'Level 3',
WeaponID: 0xbd,
},
3: {
Name: {
EN: 'Nice Hammer +',
DE: 'Super-Hammer +',
FR: 'Great marteau DX',
ES: 'Martillo chulo +'
},
Level: 'Level 4',
WeaponID: 0xbe,
},
4: {
Name: {
EN: 'Crackling Nice Hammer',
DE: 'Schock-Super-Hammer',
FR: 'Marteau de foudre',
ES: 'Martillo chulo del trueno'
},
Level: 'Level 4+',
WeaponID: 0xd3,
},
},
},
},
'Yuga': {
0: {
ClassName: {
EN: 'Picture Frame',
DE: 'Bilderrahmen',
FR: 'Cadre',
ES: 'Marcos'
},
Weapons: {
0: {
Name: {
EN: 'Wooden Frame',
DE: 'Holzrahmen',
FR: 'Cadre en bois',
ES: 'Marco de madera'
},
Level: 'Level 1',
WeaponID: 0xbf,
},
1: {
Name: {
EN: 'Frame of Sealing',
DE: 'Siegelrahmen',
FR: 'Cadre du sceau',
ES: 'Marco del sello'
},
Level: 'Level 2',
WeaponID: 0xc0,
},
2: {
Name: {
EN: 'Demon King\'s Frame',
DE: 'Dämonenkönig-Rahmen',
FR: 'Cadre du roi démon',
ES: 'Marco demoniaco'
},
Level: 'Level 3',
WeaponID: 0xc1,
},
3: {
Name: {
EN: 'Demon King\'s Frame +',
DE: 'Dämonenkönig-Rahmen +',
FR: 'Cadre du roi démon DX',
ES: 'Marco demoniaco +'
},
Level: 'Level 4',
WeaponID: 0xc2,
},
4: {
Name: {
EN: 'Burning Frame',
DE: 'Feuerrahmen',
FR: 'Cadre de feu',
ES: 'Marco demoniaco ígneo'
},
Level: 'Level 4+',
WeaponID: 0xd4,
},
},
},
},
}
return Weapons;
} |
const isValidString =
param =>
typeof param === 'string' && param.length > 0
const startsWith =
(string, start) =>
string[0] === start
const isSelector =
param =>
isValidString(param) && (startsWith(param, '.') || startsWith(param, '#'))
const TAGS = {
badge: 'div.material-icons.mdl-badge',
fab: 'button.mdl-button.mdl-js-button.mdl-button--fab',
btn: 'button.mdl-button.mdl-js-button',
iconBtn: 'button.mdl-button.mdl-js-button.mdl-button--icon',
miniFab: 'button.mdl-button.mdl-js-button.mdl-button--fab.mdl-button--mini-fab',
txtField: 'div.mdl-textfield.mdl-js-textfield',
txtInput: 'input.mdl-textfield__input',
txtLabel: 'label.mdl-textfield__label',
slider: 'input.mdl-slider.mdl-js-slider',
icon: 'i.material-icons',
menu: 'ul.mdl-menu.mdl-js-menu',
menuItem: 'li.mdl-menu__item',
tooltip: 'div.mdl-tooltip',
dataTable: 'div.mdl-data-table.mdl-js-data-table',
thCell: 'th.mdl-data-table__cell--non-numeric',
tdCell: 'td.mdl-data-table__cell--non-numeric',
_switch: 'label.mdl-switch.mdl-js-switch',
cbSwitch: 'input.mdl-switch__input',
lblSwitch: 'span.mdl-switch__label',
spinner: 'div.mdl-spinner.mdl-js-spinner',
list: 'ul.mdl-list',
listItem: 'li.mdl-list__item',
liPrimary: 'span.mdl-list__item-primary-content',
liIcon: 'i.material-cons.mdl-list__item-icon',
liLink: 'a.mdl-list__item-secondary-action',
liSecondary: 'a.mdl-list__item-secondary-content',
liBody: 'span.mdl-list__item-text-body',
layout: 'div.mdl-layout.mdl-js-layout',
header: 'header.mdl-layout__header',
headerRow: 'div.mdl-layout__header-row',
title: 'div.mdl-layout-title',
spacer: 'div.mdl-layout-spacer',
nav: 'nav.mdl-navigation',
navLink: 'a.mdl-navigation__link',
drawer: 'div.mdl-layout__drawer',
content: 'main.mdl-layout__content',
grid: 'div.mdl-grid',
cell_1: 'div.mdl-cell.mdl-cell--1-col',
cell_2: 'div.mdl-cell.mdl-cell--2-col',
cell_3: 'div.mdl-cell.mdl-cell--3-col',
cell_4: 'div.mdl-cell.mdl-cell--4-col',
cell_5: 'div.mdl-cell.mdl-cell--5-col',
cell_6: 'div.mdl-cell.mdl-cell--6-col',
cell_7: 'div.mdl-cell.mdl-cell--7-col',
cell_8: 'div.mdl-cell.mdl-cell--8-col',
cell_9: 'div.mdl-cell.mdl-cell--9-col',
cell_10: 'div.mdl-cell.mdl-cell--10-col',
cell_11: 'div.mdl-cell.mdl-cell--11-col',
cell_12: 'div.mdl-cell.mdl-cell--12-col',
card: 'div.mdl-card',
cardTitle: 'div.mdl-card__title',
cardMenu: 'div.mdl-card__menu'
}
const node = h =>
tagName =>
(first, ...rest) => {
var tag = TAGS[tagName]
if (isSelector(first)) {
if (typeof rest[0] === 'Object') {
rest[0] = Object.assign({}, {'upgrade-hook': new UpgradeHook() }, rest[0])
}
return h(tag + first, ...rest)
} else {
if (typeof first === 'Object') {
first = Object.assign({}, {'upgrade-hook': new UpgradeHook() }, first)
}
return h(tag, first, ...rest)
}
}
const materialTags = h => {
const createTag = node(h)
const exported = { }
Object.keys(TAGS).forEach(n => {
exported[n] = createTag(n)
})
return exported
}
module.exports = materialTags
function UpgradeHook (){}
UpgradeHook.prototype.hook = (node, propertyName, previousValue) => {
if (!componentHandler && console) {
return console.log('componentHander not found')
}
setTimeout(_ => componentHandler.upgradeElement(node), 0)
}
|
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "././navbar.css";
class Navbar extends Component {
state = {};
render() {
return (
<React.Fragment>
<header>
<div
className="container-fluid sticky"
style={{ background: "white", width: "100%" }}
>
<div className="container">
<div className="row">
<div className="col-sm-4 h-logowidth"></div>
<div
className="topnav col-sm-8 text-center text-secondary headz h-headz"
id="myTopnav"
>
<a className="h-home" href="/">
HOME
</a>
<a className="h-abpc" href="/about">
ABOUT
</a>
<a className="h-abpc" href="/services">
SERVICES
</a>
<a className="h-abpc" href="/projects">
PROJECTS
</a>
<a className="h-contact" href="/contacts">
CONTACT
</a>
</div>
</div>
</div>
</div>
</header>
</React.Fragment>
);
}
}
export default Navbar;
|
class PerkingArea {
constructor() {
this.name = 'Stasiun Manggarai';
this.MAX_AREA = 50;
this.availableArea = this.MAX_AREA;
this.CAR_PARKING_FEE = 5000;
this.MOTOR_PARKING_FEE = 2000;
this._cash = 0;
this.parkedList = [];
}
set cash(value) {
this._cash = value
}
isParkingAvailable(vehicle) {
return this.availableArea > vehicle.PARKING_SIZE_AREA
}
isTheVehicleParked(vehicle) {
return parkingArea.parkedList.indexOf(vehicle) >= 0
}
deleteVehichleList(vehicle) {
parkingArea.parkedList = parkingArea.parkedList.filter((item) => item !== vehicle);
}
calcParkingFee(vehicle) {
let ONE_HOUR_ASSUMPTION = 3000; // 3000 milisecond
let parkingTime = parseInt(Math.abs((new Date - vehicle._parkingTicket.entryTime)) / ONE_HOUR_ASSUMPTION);
if (vehicle instanceof Car) return this.CAR_PARKING_FEE * parkingTime
if (vehicle instanceof MotorCycle) return this.MOTOR_PARKING_FEE * parkingTime
}
sayHello() {
console.log(
`Selamat datang di Parking Area ${this.name}
biaya parkir mobil adalah Rp${this.CAR_PARKING_FEE}/jam
biaya parkir motor adalah Rp${this.MOTOR_PARKING_FEE}/jam`);
}
}
class ParkingMachine {
constructor(id) {
this.machineId = id;
this.cash = 0;
this.lastTicketNumber = 100;
}
getTicket() {
this.lastTicketNumber++
return `${this.id}${this.lastTicketNumber}`
}
vehicleIn(vehicle) {
if (parkingArea.isTheVehicleParked(vehicle)) return `${vehicle.name} telah parkir sebelumnya`
if (!parkingArea.isParkingAvailable(vehicle)) return `parkiran penuh`;
parkingArea.parkedList.push(vehicle);
parkingArea.availableArea -= vehicle.PARKING_SIZE_AREA;
this.lastTicketNumber++;
let newTicket = `${this.machineId}${this.lastTicketNumber}`
vehicle.parkingTicket = {
entryTime: new Date(),
ticketNumber: newTicket
}
return `nomor tiket ${vehicle.name} adalah ${newTicket}`
}
vehicleOut(vehicle) {
if (!parkingArea.isTheVehicleParked(vehicle)) return `${vehicle.name} tidak parkir disini`
parkingArea.deleteVehichleList(vehicle);
parkingArea.availableArea += vehicle.PARKING_SIZE_AREA;
let parkingFee = parkingArea.calcParkingFee(vehicle);
this.cash += parkingFee;
vehicle.parkingTicket = {
entryTime: null,
ticketNumber: null
}
return `Biaya parkir ${vehicle.name} adalah Rp${parkingFee}`;
}
}
class Vehicle {
constructor(name) {
this.name = name;
this.parkingSizeArea;
this._parkingTicket;
}
set parkingTicket(value) {
this._parkingTicket = value
}
get parkingTicket() {
return this._parkingTicket
}
}
class Car extends Vehicle {
constructor(name) {
super(name);
this.PARKING_SIZE_AREA = 20;
}
}
class MotorCycle extends Vehicle {
constructor(name) {
super(name);
this.PARKING_SIZE_AREA = 5;
}
}
let parkingArea = new PerkingArea();
let parkMachineA = new ParkingMachine('A');
let parkMachineB = new ParkingMachine('B');
let motorCycle1 = new MotorCycle('Honda Blade');
let motorCycle2 = new MotorCycle('Yamaha Mio');
let motorCycle3 = new MotorCycle('Suzuki Thunder');
let car1 = new Car('Toyota Avanza');
let car2 = new Car('Suzuki Ertiga');
let car3 = new Car('Honda Jazz');
// class Person {
// constructor(name, gender, origin) {
// this.name = name;
// this.gender = gender;
// this.origin = origin;
// }
// sayHello() {
// console.log(
// `Hallo nama saya ${this.name} saya berasal dari ${this.origin}`
// );
// }
// }
// class Admin extends Person {
// constructor(name, gender, origin) {
// super(name, gender, origin);
// }
// sayHello() {
// console.log(`Hallo saya ${this.name}. Mau booking kamar hotel? `);
// }
// checkInVisitor(visitor, room) {
// if (!room.reservationStatus) {
// visitor.bookedRoom.push(room);
// room.setReservationStatus(true);
// console.log(visitor);
// // console.log(room);
// } else {
// console.log("Kamar sudah di booking orang lain");
// }
// }
// checkOutVisitor(visitor, room) {
// let findIndexOfTheRoom = visitor.bookedRoom.indexOf(room);
// if (findIndexOfTheRoom >= 0) {
// visitor.bookedRoom.remove(findIndexOfTheRoom);
// room.setReservationStatus(false);
// console.log(visitor);
// } else {
// console.log(
// `Kamar nomor ${room.roomID} belum dibooking sebelumnya`
// );
// }
// }
// }
// class Visitor extends Person {
// constructor(name, gender, origin) {
// super(name, gender, origin);
// this.bookedRoom = [];
// }
// }
// class Room {
// constructor(roomID) {
// this.roomID = roomID;
// this.reservationStatus = false;
// }
// setReservationStatus(value) {
// this.reservationStatus = value;
// }
// }
// class RoomType1 extends Room {
// constructor(roomID) {
// super(roomID);
// this.price = 300000;
// this.amenities = [
// "King Bed",
// "WiFi",
// "AC",
// "TV",
// "Kitchen",
// "Free Parking",
// ];
// }
// }
// class RoomType2 extends Room {
// constructor(roomID) {
// super(roomID);
// this.price = 200000;
// this.amenities = ["Queen Bed", "WiFi", "AC", "TV"];
// }
// }
// // Array Remove - By John Resig (MIT Licensed)
// Array.prototype.remove = function (from, to) {
// var rest = this.slice((to || from) + 1 || this.length);
// this.length = from < 0 ? this.length + from : from;
// return this.push.apply(this, rest);
// };
// let putri = new Admin("Putri", "Perempuan", "Jogja");
// let rafi = new Visitor("Rafi", "Laki-laki", "Padang");
// let alfian = new Visitor("Alfian", "Laki-laki", "Bandung");
// let room1 = new RoomType1(1);
// let room2 = new RoomType1(2);
// let room3 = new RoomType2(3);
// let room4 = new RoomType2(4);
// putri.sayHello() |
import React from 'react';
import Textarea from 'react-textarea-autosize';
import { connect } from 'react-redux';
import { getViewValue } from '../../Store/View';
import { changeView } from '../../Store/Store';
const style = {
base: {
boxSizing: 'border-box',
width: '100%',
border: 'none',
borderBottom: '1px solid #ccc',
fontSize: '0.9em',
},
};
export class TextEditor extends React.Component {
static defaultValue() {
return '';
}
static validate(scheme, val) {
if (scheme.required && (!val || val==''))
return ['required'];
return [];
}
onChange(event) {
this.props.dispatch(changeView(this.props.view, event.target.value));
}
render() {
return <Textarea minRows={1}
maxRows={12}
value={this.props.value}
onChange={this.onChange.bind(this)}
style={style.base} />;
}
}
const connectComponent = connect((state, props) => {
return {
value: getViewValue(state.microcastle, props.view),
};
});
export default connectComponent(TextEditor);
|
import React from 'react'
import { Link } from 'react-router-dom'
const TodolistIndexTile = (props) => {
return(
<div>
<Link to={`/${props.id}`}>{props.title}</Link>
<br/>
</div>
)
}
export default TodolistIndexTile
|
import tw from 'tailwind-styled-components'
const SVGWrapper = tw.div`
absolute
top-0
h-full
w-8
flex
justify-center
items-center
`
const SearchSVG = tw.svg`
w-4
h-4
text-gray-400
`
export const StyledSearchInputSVG = () =>
{
return <SVGWrapper>
<SearchSVG xmlns="http://www.w3.org/2000/svg"
fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2"
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
</SearchSVG>
</SVGWrapper>
}
|
import request from '@/utils/request'
import { urlCrowd } from '@/api/commUrl'
// 线上地址
const url = urlCrowd + 'crowdInfo/'
// 群升级圈页面-查询、单个通过拒绝、批量通过拒绝---线上
const getToCircleUrl = urlCrowd + 'crowdToCircleApply/getCrowdToCircleApplyList'
const singleArUrl = urlCrowd + 'crowdToCircleApply/saveAuditInfo'
const batchArUrl = urlCrowd + 'crowdToCircleApply/saveAuditInfoByList'
// 马保玉本地地址(勿删)
// const url = 'http://192.168.1.144:8080/fwas-crowd-admin/sys/crowdInfo/'
// 群升级圈页面-查询、单个通过拒绝、批量通过拒绝---马保玉本地
// const getToCircleUrl = 'http://192.168.1.144:8080/fwas-crowd-admin/sys/crowdToCircleApply/getCrowdToCircleApplyList'
// const singleArUrl = 'http://192.168.1.144:8080/fwas-crowd-admin/sys/crowdToCircleApply/saveAuditInfo'
// const batchArUrl = 'http://192.168.1.144:8080/fwas-crowd-admin/sys/crowdToCircleApply/saveAuditInfoByList'
// 群信息管理
const dissolutionUrl = url + 'dispersedCrowd'
const frozenUrl = url + 'frozenCrowd'
const unfrozenUrl = url + 'thawCrowd'
const upgradeUrl = url + 'CrowdToCircle'
const querySortUrl = url + 'queryDidcByType'
const detailUrl = url + 'getCrowdInfoDetail'
const saveDetailUrl = url + 'saveCrowdInfo'
const SortListUrl = url + 'getCrowdInfo'
const changePicUrl = url + 'uploadFile'
const laberVerifyUrl = url + 'verifyCircleNameAvailable'
const getPicsUrl = url + ''
const editSaveUrl = url + ''
// 群信息管理--查找按钮和页面刷新加载数据列表 (已调)
export function searchPort(params) {
return request({
url: url + 'getCrowdInfo',
method: 'post',
data: params
})
}
// 群组管理-群升级圈-查找
export function getToCircle(params) {
return request({
url: getToCircleUrl,
method: 'post',
data: params
})
}
// 群组管理-群升级圈-单个同意拒绝
export function singleAr(params) {
return request({
url: singleArUrl,
method: 'post',
data: params
})
}
// 群组管理-群升级圈-批量同意拒绝
export function batchAr(params) {
return request({
url: batchArUrl,
method: 'post',
data: params
})
}
// 群信息管理--解散(已调)
export function dissolution(params) {
return request({
url: dissolutionUrl,
method: 'post',
data: params
})
}
// 群信息管理--冻结(已调)
export function frozen(params) {
return request({
url: frozenUrl,
method: 'post',
data: params
})
}
// 群信息管理--解冻(已调)
export function unfrozen(params) {
return request({
url: unfrozenUrl,
method: 'post',
data: params
})
}
// 群组====群升级成为圈
export function upgrade(params) {
return request({
url: upgradeUrl,
method: 'post',
data: params
})
}
// 群组===群升级成为圈==标签不重名校验
export function laberVerify(params) {
return request({
url: laberVerifyUrl,
method: 'post',
data: params
})
}
// 群信息管理----群详情
export function detail(params) {
return request({
url: detailUrl,
method: 'post',
data: params
})
}
// 群信息管理----群详情编辑
export function saveDetail(params) {
return request({
url: saveDetailUrl,
method: 'post',
data: params
})
}
// 图片空间
export function getPics(params) {
return request({
url: getPicsUrl,
method: 'post',
data: params
})
}
// 修改群信息 群名称和群头像
export function editSave(params) {
return request({
url: editSaveUrl,
method: 'post',
data: params
})
}
// 群信息管理---- 排序列表渲染
export function querySort(params) {
return request({
url: querySortUrl,
method: 'post',
data: params
})
}
// 群信息管理---- 排序列表渲染
export function SortList(params) {
return request({
url: SortListUrl,
method: 'post',
data: params
})
}
// 群信息管理---- 编辑详情里面的修改头像
export function changePic(params) {
return request({
url: changePicUrl,
method: 'post',
data: params
})
}
|
import React, { Component } from 'react';
import ChildLifecycle from './ChildLifecycle';
class ParentLifecycle extends Component {
constructor(props) {
super(props)
this.state = {
name: 'Chinmay'
}
console.log('Parent lifecycle constructor');
}
static getDerivedStateFromProps(props, state){
console.log('Parent lifecycle getDerivedStateFromProps');
return null;
}
componentDidMount(){
console.log('Parent lifecycle componentDidMount');
}
shouldComponentUpdate(){
console.log('Parent lifecycle shouldComponentUpdate');
return true
}
getSnapshotBeforeUpdate(prevPrps, prevState){
console.log('Parent lifecycle getSnapshotBeforeUpdate');
return null;
}
componentDidUpdate(){
console.log('Parent lifecycle componentDidUpdate');
}
changeState = () => {
this.setState({
name: 'State changed'
})
}
render() {
console.log('Parent lifecycle render');
return (
<div>
<h1>ParentLifecycle</h1>
<button onClick={this.changeState}>Change state</button>
<ChildLifecycle/>
</div>
);
}
}
export default ParentLifecycle;
|
export { default } from "./ClosetPanel"; |
import React from "react";
import { List, ListItem, CardHeader, CardContent, CardFooter, Card, Button, Link } from 'framework7-react';
import crypto from 'crypto-js';
import { dict } from "../../Dict";
const TimeSheetList = (props) => {
if (props.time_sheets) {
return (
<Card>
<CardHeader>
{props.header}
</CardHeader>
<CardContent>
<List mediaList className='fs-11'>
{props.time_sheets.map((time_sheet) =>
<ListItem
className='fs-11'
key={crypto.lib.WordArray.random(32)}
link={"/time_sheets/" + time_sheet.id}
ignoreCache={true}
title={time_sheet.jdate}
after=""
subtitle={time_sheet.profile.fullname}
text=""
>
<img slot="media" src={time_sheet.profile.avatar} width="28" height="28"/>
</ListItem>
)}
</List>
</CardContent>
<CardFooter>
<Link></Link>
<Button onClick={() => props.loadMore(props.page)}>{dict.more}</Button>
</CardFooter>
</Card>
)
} else {
return (<ul></ul>)
}
}
export default TimeSheetList;
|
/**
* This is the actions file
*
* Actions here can call an api, and return the response body to reducers
*/
import request from 'superagent';
export const TOGGLE_EXPAND = 'TOGGLE_EXPAND';
export function deployTag(tag_id) {
return { fired: true, tag_id };
}
export function expandRepo(repoId) {
return {
type: TOGGLE_EXPAND,
repoId
};
}
|
'use strict';
module.exports = [
'./node_modules/jquery/dist/jquery.min.js',
'./node_modules/jquery.maskedinput/src/jquery.maskedinput.js',
'./node_modules/slick-carousel/slick/slick.min.js',
'./node_modules/lightslider/dist/js/lightslider.min.js',
'./node_modules/lightgallery/dist/js/lightgallery.min.js',
'./node_modules/magnific-popup/dist/jquery.magnific-popup.min.js',
]; |
import React, { Component } from 'react';
import { Container, Table } from 'react-bootstrap';
import axios from 'axios';
const endpoint = '/get_chain'
class Transactions extends Component {
constructor(props){
super(props);
this.state = {
transactions: [],
}
}
componentDidMount() {
axios.get(endpoint)
.then(res => {
const transactions = res.data.chain;
this.setState({ transactions });
})
}
render(){
return (
<Container>
<h3><b> Transactions </b></h3>
<p>(Sync to get the latest transactions in the blockchain)</p>
<Table responsive>
<thead>
<tr>
<th>From</th>
<th>To</th>
<th>Amount (Sudo)</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
{ this.state.transactions.slice(0).reverse().map(transaction =>
transaction.transactions.map( t =>
<tr key={t}>
<td><b style={{color: '#007bff'}}>0x{t.sender}</b></td>
<td><b style={{color: '#007bff'}}>0x{t.receiver}</b></td>
<td><b style={{color: '#007bff'}}>{parseFloat(t.amount).toFixed(5)} </b></td>
<td><b style={{color: '#007bff'}}>{t.time}</b></td>
</tr>
))}
</tbody>
</Table>
</Container>
);
}
}
export default Transactions;
|
import React from 'react';
import './GirlsHomepage.css';
import LillyBeyond from '../../../assets/girlswhoproduct-homepage/lilly_beyond.jpg';
export default function GirlsHomepage() {
return (
<div className="girl-main-container">
<div className="girl-title-content">
<h6 className="section-subtitle">PODCAST</h6>
<h2 className="section-title">#GIRLSWHOPRODUCT</h2>
<p className="section-p">
#GirlsWhoProduct is a series of interviews with women that have been
able to beat the ‘product’ ceiling and get into the profession. Our
mission is to inspire, connect and empower more women to get into
product roles and help them consider ‘product’ as a venue of personal
and professional growth.
</p>
</div>
<div className="girl-cards-container">
<div className="girl-cards">
<img src={LillyBeyond} alt="Lilly Beyond" />
</div>
</div>
<a
href="https://www.meetup.com/Productized/"
target="_blank"
rel="noopener noreferrer"
>
<button className="girls-button">JOIN THE NEXT #GWP</button>
</a>
</div>
);
}
|
var assert = require('assert');
var test = require('../../src/eps');
var testCases = [
{i: {src: {x: 1, y: 2}, dst: {x: 3, y: 4}, stroke: {r: 255, g: 255, b: 0}, strokeWidth: 1},
o: "gsave newpath 1 1 0 setrgbcolor 1 setlinewidth 1 2 moveto 3 4 lineto stroke grestore\n"}
];
describe('eps', function() {
describe('_drawLine', function() {
it('draws a valid postscript line command', function() {
var eps = new test.EPS({width: 10, height: 10});
testCases.forEach(function (t) {
assert.equal(eps._drawLine(t.i), t.o);
});
});
});
});
|
'use strict';
/**
* @ngdoc service
* @name seedApp.allBrandsService
* @description
* # allBrandsService
* Service in the seedApp.
*/
angular.module('seedApp')
.service('allBrandsService', function ($http) {
var url = 'https://places.leadinglocally.com/api/brands';
this.get = function() {
return $http({
method: 'GET',
url: url
})
.success(function(resp){
window.console.log('Success: allBrandsService.get : ', resp );
})
.error(function(resp){
window.console.log('Failed: allBrandsService.get : ', resp );
});
};
});
|
import React, { Component } from 'react'
import PropTypes from 'prop-types';
import styles from './Styles/CounterStyle'
import {
TouchableOpacity,
Text,
View
} from 'react-native'
import RoundedButton from './RoundedButton'
const BlueButton = (props) => (
<TouchableOpacity style={styles.increaseButton}>
<Text style={styles.buttonText} onPress={props.onPress}>{props.text}</Text>
</TouchableOpacity>
)
const RedButton = (props) => (
<TouchableOpacity style={styles.decreaseButton}>
<Text style={styles.buttonText} onPress={props.onPress}>{props.text}</Text>
</TouchableOpacity>
)
export default class Counter extends Component {
// // Prop type warnings
static propTypes = {
value: PropTypes.number,
onSyncIncrease: PropTypes.func,
onSyncDecrease: PropTypes.func,
onAsyncIncrease: PropTypes.func,
onAsyncDecrease: PropTypes.func
}
//
// Defaults for props
static defaultProps = {
value: 0
}
render = () => (
<View style={styles.container}>
<View style={styles.syncButton} >
<BlueButton text='SYNC+' onPress={this.props.onSyncIncrease} />
<RedButton text='SYNC-' onPress={this.props.onSyncDecrease} />
</View>
<Text style={styles.resultText}>{this.props.value}</Text>
<View style={styles.asyncButton} >
<BlueButton text='ASYN+' onPress={this.props.onAsyncIncrease} />
<RedButton text='ASYN-' onPress={this.props.onAsyncDecrease} />
</View>
</View>
)
}
|
import { Environment, Network, Store, RecordSource } from 'relay-runtime';
import { createFetch } from 'relay-local-schema';
import schema from './schema';
/**
* This will execute queries against the specified schema locally,
* rather than against a separate GraphQL server.
*/
const environment = new Environment({
network: Network.create(createFetch({ schema })),
store: new Store(new RecordSource()),
});
export default environment; |
console.log("You are at " + window.location);
console.log(DATA); |
import React from 'react';
import PropTypes from 'prop-types';
import Average from '../../components/Average/Average';
import './AveragesView.css';
const AveragesView = ({ dataHelper }) =>
(
<section className="averages-view">
<h2>Averages</h2>
<Average dataHelper={dataHelper} channelSet="power" />
<Average dataHelper={dataHelper} channelSet="heartRate" />
<Average dataHelper={dataHelper} channelSet="cadence" />
<Average dataHelper={dataHelper} channelSet="temperature" />
<Average dataHelper={dataHelper} channelSet="elevation" />
<Average dataHelper={dataHelper} channelSet="speed" />
</section>
);
export default AveragesView;
AveragesView.propTypes = {
dataHelper: PropTypes.shape({
originalData: PropTypes.shape({}),
minuteData: PropTypes.arrayOf(PropTypes.shape({})),
channels: PropTypes.arrayOf(PropTypes.string),
GPSCoords: PropTypes.arrayOf(PropTypes.shape({})),
}).isRequired,
};
|
import React from 'react';
import {Mana, Health, Damage} from '../pieces';
import styles from './grid.scss';
const getPiece = (type, idx) => {
const pieces = {
1: <Mana level="low" />,
2: <Mana level="mid" />,
3: <Mana level="high" />,
4: <Health />,
5: <Damage />,
};
return (
<div key={idx} className={styles.piece}>
{pieces[type]}
</div>
);
};
export const Grid = ({data}) => (
<div className={styles.grid}>
{data.map(getPiece)}
</div>
);
|
var app = app || {};
(function() {
app.DayView = Backbone.View
.extend({
el : '#day',
events : {
//'keypress #day-food-input' : 'createOnEnter',
//'keypress #day-food-input' : 'searchAutocomplete'
},
initialize : function() {
console.log('initializing day view');
this.listenTo(this.model, 'change', this.render);
this.listenTo(app.days, 'change', this.render);
app.days.fetch({
reset : true
});
var foodSelected = this.foodSelected;
this.foods = new Backbone.AutocompleteList(
{
url : function() {
var term = $.param({
q : $('#day-food-input').val()
});
return 'https://apibeta.nutritionix.com/v2/autocomplete?appId=52be4fe3&appKey=f046c68c4dc175477d1378818e4415e7&'
+ term;
},
filter : null,
el : $('#day-food-input'),
results: $('form#food-search .autocomplete-results'),
template : _
.template('<p><%= text.replace(new RegExp("(" + $("day-food-input").val() + ")", "i") ,"<b>$1</b>") %></p>'),
delay : 100,
minLength : 3,
value : function(model) {
return model.get('text')
},
click : foodSelected
});
this.render();
},
render : function() {
console.log('rendering day view');
this.$el.removeClass('hidden');
},
createOnEnter : function(e) {
if (e.keyCode === ENTER_KEY) {
console.log('entered');
}
},
foodSelected : function(food) {
console.log(food);
}
});
})(); |
import Vue from 'vue'
import Toolbar from 'src/components/Toolbar'
describe('Toolbar.vue', () => {
it('exists and visible', () => {
const vm = new Vue({
template: '<hi-toolbar title="Hello World!"></hi-toolbar>',
components: { 'hi-toolbar': Toolbar },
replace: false
}).$mount()
vm.$el.querySelector('.toolbar').should.exist
vm.$el.querySelector('.toolbar-content').should.be.visible
})
it('should render title', () => {
const vm = new Vue({
template: '<hi-toolbar title="Hello World!"></hi-toolbar>',
components: { 'hi-toolbar': Toolbar },
replace: false
}).$mount()
expect(vm.$el.querySelector('h1').textContent).to.contain('Hello World!')
})
it('should render title in slot', () => {
const vm = new Vue({
template: '<hi-toolbar><h2>Hello World!</h2></hi-toolbar>',
components: { 'hi-toolbar': Toolbar },
replace: false
}).$mount()
expect(vm.$el.querySelector('h2').textContent).to.contain('Hello World!')
})
})
|
const itemService = require('../services/item.service');
const chatService = require('../services/chat.service');
const { to, ReE, ReS } = require('../services/util.service');
const get_items = async function(req, res){
let err, items;
[err, items] = await to(itemService.get_items(req));
if(err) return ReE(res, err, 422);
var jsonArrayData = [];
var length = items.length;
for (var i = 0 ; i < length ; i++)
{
var item = items[i];
jsonArrayData.push(item.toJSON());
}
return ReS(res, {length : length , data : jsonArrayData});
}
module.exports.get_items = get_items;
const get_my_items = async function(req, res){
let err, items;
[err, items] = await to(itemService.get_my_items(req));
if(err) return ReE(res, err, 422);
var jsonArrayData = [];
var length = items.length;
for (var i = 0 ; i < length ; i++)
{
var item = items[i];
jsonArrayData.push(item.toJSON());
}
return ReS(res, {length : length , data : jsonArrayData});
}
module.exports.get_my_items = get_my_items;
const get_item = async function(id, req, res){
let err, item;
[err, item] = await to(itemService.get_item(id,req ,res));
if(err) return ReE(res, err, 422);
return ReS(res, { data : item});
}
module.exports.get_item = get_item;
const del_item = async function(id, req, res){
let err, item;
[err, item] = await to(itemService.del_item(id,req ,res));
if(err) return ReE(res, err, 422);
return ReS(res, { success:true});
}
module.exports.del_item = del_item;
const get_items_count = async function(req, res){
let err, count;
[err ,count]= await to(itemService.get_items_count(req));
//count = itemService.get_items_count(req);
return ReS(res, {count : count });
}
module.exports.get_items_count = get_items_count;
const add_new_item = async function(req, res){
let err, item;
[err, item] = await to(itemService.add_new_item(req));
if(err) return ReE(res, err, 422);
return ReS(res, {success : true , fail_reason : "" , item_id : item.id});
}
module.exports.add_new_item = add_new_item;
const update_item = async function(item_id,req, res){
let err, item;
[err, item] = await to(itemService.update_item(item_id ,req));
if(err) return ReE(res, err, 422);
return ReS(res, {type : 0 , fail_reason : "" , item_id : item.id});
}
module.exports.update_item = update_item;
const add_item_images = async function(req, res){
let err, item;
[err, item] = await to(itemService.add_item_images(req));
if(err) return ReE(res, err, 422);
return ReS(res, {type : 0 , fail_reason : "" , item_id : item.id});
}
module.exports.add_item_images = add_item_images; |
describe('Los estudiantes login', function() {
it('Visits los estudiantes and fails at login', function() {
cy.visit('https://losestudiantes.co')
cy.contains('Cerrar').click()
cy.contains('Ingresar').click()
cy.get('.cajaLogIn').find('input[name="correo"]').click().type("wrongemail@example.com")
cy.get('.cajaLogIn').find('input[name="password"]').click().type("1234")
cy.get('.cajaLogIn').contains('Ingresar').click()
cy.contains('El correo y la contraseña que ingresaste no figuran en la base de datos. Intenta de nuevo por favor.')
})
it('Visits los estudiantes and success at login', function() {
cy.visit('https://losestudiantes.co')
cy.contains('Cerrar').click()
cy.contains('Ingresar').click()
cy.get('.cajaLogIn').find('input[name="correo"]').click().type("taller2miso4208@yopmail.com")
cy.get('.cajaLogIn').find('input[name="password"]').click().type("cypress123")
cy.get('.cajaLogIn').contains('Ingresar').click()
cy.get('button[id="cuenta"]').click()
})
})
describe('Creación de cuenta', function() {
it('Creación de cuenta con un usuario existente', function() {
cy.visit('https://losestudiantes.co')
cy.contains('Cerrar').click()
cy.contains('Ingresar').click()
cy.get('.cajaSignUp').find('input[name="nombre"]').click().type("Pedro")
cy.get('.cajaSignUp').find('input[name="apellido"]').click().type("Salazar")
cy.get('.cajaSignUp').find('input[name="correo"]').click().type("taller2miso4208@yopmail.com")
cy.get('.cajaSignUp').find('input[name="password"]').click().type("cypress123")
cy.get('.cajaSignUp').find('select[name="idPrograma"]').select('Ingeniería de Sistemas y Computación')
cy.get('.cajaSignUp').find('input[name="acepta"]').check()
cy.get('.cajaSignUp').contains('Registrarse').click()
cy.contains("Error: Ya existe un usuario registrado con el correo 'taller2miso4208@yopmail.com'")
})
})
describe('Búsqueda de profesores', function() {
it('Búsqueda de profesores exitosa', function() {
cy.visit('https://losestudiantes.co')
cy.contains('Cerrar').click()
cy.get('.buscador').find('input').click({force:true}).type('Mario',{force:true})
})
})
describe('Redireccionar a la página de un profesor', function() {
it('Redirección exitosa a la página de profesor', function() {
cy.visit('https://losestudiantes.co')
cy.contains('Cerrar').click()
cy.get('.profesor').first().find('a').click()
})
})
describe('Página de profesor', function() {
it('Filtros por materia', function() {
cy.visit('https://losestudiantes.co/universidad-de-los-andes/ingenieria-de-sistemas/profesores/mario-linares-vasquez')
cy.get('.materias').find("input[name='id:ISIS1206']").click()
cy.wait(2000)
cy.get('.columnMiddle').find('.post')
.each(($el, index, $list)=>{
cy.wrap($el).find('label.labelHover>a').should('contain', 'Estructuras De Datos')
})
})
}) |
var hook_8h =
[
[ "MUTT_HOOK_NO_FLAGS", "hook_8h.html#af90ba352be78a79717b1efeb2cfc867a", null ],
[ "MUTT_FOLDER_HOOK", "hook_8h.html#a2fde17cbd1c23f84f7f005010971f9a1", null ],
[ "MUTT_MBOX_HOOK", "hook_8h.html#ab53cdfc68467d6ca2071ed11ab4a7f0d", null ],
[ "MUTT_SEND_HOOK", "hook_8h.html#a365ef87efead32b0e7a8265927171dc1", null ],
[ "MUTT_FCC_HOOK", "hook_8h.html#a3fc9dcc20330703d6d36e77a21613c95", null ],
[ "MUTT_SAVE_HOOK", "hook_8h.html#a353e4feaac6dfcc1795362f859e4fc54", null ],
[ "MUTT_CHARSET_HOOK", "hook_8h.html#af4d7c96f476707180849db93d755594b", null ],
[ "MUTT_ICONV_HOOK", "hook_8h.html#a2898def3d66169282bf026066838b4ae", null ],
[ "MUTT_MESSAGE_HOOK", "hook_8h.html#ac4fada4e7df870f12ec6387389bba8c4", null ],
[ "MUTT_CRYPT_HOOK", "hook_8h.html#a9fd41150f144668ac8d3f5d24ac0de2a", null ],
[ "MUTT_ACCOUNT_HOOK", "hook_8h.html#a51588262a10f6f5da4265eca580ccc33", null ],
[ "MUTT_REPLY_HOOK", "hook_8h.html#ab6ec93bff7f691fb01cb5233f4040f62", null ],
[ "MUTT_SEND2_HOOK", "hook_8h.html#a709891b042fc13265a7971b2401081c9", null ],
[ "MUTT_OPEN_HOOK", "hook_8h.html#a2023ebfafb21558f2adf582b9f182523", null ],
[ "MUTT_APPEND_HOOK", "hook_8h.html#a608d073646dabfa996b8460a6041393a", null ],
[ "MUTT_CLOSE_HOOK", "hook_8h.html#a4dc1443d223770a18d42c237f7748e66", null ],
[ "MUTT_IDXFMTHOOK", "hook_8h.html#aea642d87228d0d28d6e8265066a76b74", null ],
[ "MUTT_TIMEOUT_HOOK", "hook_8h.html#ab8406fddb444137067dc1c1a8b5c3f25", null ],
[ "MUTT_STARTUP_HOOK", "hook_8h.html#a694243a6a9e9eb8775505e1df4105a15", null ],
[ "MUTT_SHUTDOWN_HOOK", "hook_8h.html#ae3cff219e66c36cea5d0e1ee59fb9f1e", null ],
[ "MUTT_GLOBAL_HOOK", "hook_8h.html#a68bd099f7c7df9c686f63450d6a6c44b", null ],
[ "HookFlags", "hook_8h.html#a3bbd2f4f806a3cef595e60429f0c91af", null ],
[ "mutt_account_hook", "hook_8h.html#a4d4e38013bebd1e23d668454609a3def", null ],
[ "mutt_crypt_hook", "hook_8h.html#adce4d617e1b3ef99bec1a7969dd08a43", null ],
[ "mutt_default_save", "hook_8h.html#a567b4b83522b84d353609dbdb265b8fa", null ],
[ "mutt_delete_hooks", "hook_8h.html#a3b113188a50152ee8ff8f54975ea5897", null ],
[ "mutt_find_hook", "hook_8h.html#a5b0861b9e36e5debdf8b6509a22e6738", null ],
[ "mutt_folder_hook", "hook_8h.html#a6c1eb72c5e9a39b354d9c394f9116f50", null ],
[ "mutt_idxfmt_hook", "hook_8h.html#a23f48f56f7a277b90c9e0c7e3a1ed867", null ],
[ "mutt_message_hook", "hook_8h.html#af487ca5e3f7da21c86e3ad61fdb55faa", null ],
[ "mutt_parse_idxfmt_hook", "hook_8h.html#a006e34e81efbb903f3eba1c8887f0d87", null ],
[ "mutt_parse_hook", "hook_8h.html#a4b6e4f5a7cf7c50a1d32450735eba6f9", null ],
[ "mutt_parse_unhook", "hook_8h.html#adc980182d2656aa6d6169c7bff6800dc", null ],
[ "mutt_select_fcc", "hook_8h.html#a6d228c86f5a1900b27af0fde26991a63", null ],
[ "mutt_startup_shutdown_hook", "hook_8h.html#a346f2e985b8be4ee687b08eab1879561", null ],
[ "mutt_timeout_hook", "hook_8h.html#a1b93f7bc501b2c75f04350d3ba184885", null ],
[ "C_DefaultHook", "hook_8h.html#ae267efcdd4850ad846989ad681b350e0", null ],
[ "C_ForceName", "hook_8h.html#a8c942c1f06402cbaa14e3d08b9626442", null ],
[ "C_SaveName", "hook_8h.html#a3165c36713939fdeee7a8a3cee0f5b85", null ]
]; |
import React from 'react';
import barracuda from '../SliderImages/barracuda-school-dreamstime_s_30848576-sm350.jpg';
import './singleImg.css';
const slide3 = () => {
return (
<div className='slides'>
<div>
<img src={barracuda} alt="barracuda"/>
</div>
</div>
)
}
export default slide3; |
var SongsView = Backbone.View.extend({
render: function () {
this.$el.html('SONGS VIEW');
return this
}
});
var SingleSongView = Backbone.View.extend({
initialize: function(data){
this.songId = data.songId;
},
render: function () {
this.$el.html('SINGLE SONG VIEW -> '+ this.songId);
return this
}
});
var MoviesView = Backbone.View.extend({
render: function () {
this.$el.html('MOVIES VIEW');
return this
}
});
var BooksView = Backbone.View.extend({
render: function () {
this.$el.html('BOOKS VIEW');
return this
}
});
var ApplicationRouter = Backbone.Router.extend({
routes: {
"songs": "songsView",
"songs/:songId": "singleSongView",
"movies": "moviesView",
"books": "booksView",
"*other": "defaultView"
},
songsView: function(){
var view = new SongsView({el: "#content-container"});
view.render();
},
singleSongView: function(songId){
var view = new SingleSongView({songId: songId, el: "#content-container"});
view.render();
},
moviesView: function(){
var view = new MoviesView({el: "#content-container"});
view.render();
},
booksView: function(){
var view = new BooksView({el: "#content-container"});
view.render();
}
});
var router = new ApplicationRouter();
Backbone.history.start();
var NavigationView = Backbone.View.extend({
el: '.items',
events: {
'click': 'onClick'
},
onClick: function(e){
var $li = $(e.target);
//BEZ TRIGGER TRUE USTAWIANY JEST HASH ADRES
//ALE NIE JEST ZMIENIANY CONTENT STRONY
router.navigate($li.attr('data-url'), {trigger: true});
}
});
var navigation = new NavigationView(); |
// 定义一个函数:rand
// 参数:最小整数,最大整数
// 返回:两个整数之间的一个随机整数
function rand(min,max){
return parseInt(Math.random()*(max-min+1))+min;
}
// 返回一个随机的颜色16进制
function color(){
var str = "#";
for(var i=0;i<6;i++){
str += rand(0,15).toString(16);
}
return str;
}
// 返回指定dom节点的attr样式值
function getStyle(dom,attr){
if(window.getComputedStyle){
// 说明有getComputedStyle方法
return window.getComputedStyle(dom,null)[attr]
}else{
return dom.currentStyle[attr]
}
}
// 根据id获取元素
function $id(id){
return document.getElementById(id);
}
// 单属性缓动
function move(dom,attr,target,callback){
/*
dom:要运动的节点
attr:要运动的样式名
target:运动到的目标值
callback:运动完成的回调函数
*/
// 动画需要定时器
clearInterval(dom.timer);
dom.timer = setInterval(function(){
// 1 获取元素当前位置
if(attr == "opacity"){
var current = parseInt(getStyle(dom,attr)*100);
}else{
var current = parseInt(getStyle(dom,attr));
}
// 2 计算速度
var speed = target-current>0?Math.ceil((target-current)/10):Math.floor((target-current)/10);
// 3 计算下一个位置
if(attr=='zIndex'){
var next = target;//zIndex一步到位
}else{
var next = current+speed;
}
// 4 定位元素
if(attr=="zIndex"){
dom.style.zIndex = target;
}else if(attr=="opacity"){
dom.style.opacity = next/100;
dom.style.filter = "alpha(opacity="+next+")";
}else{
dom.style[attr] = next+"px";
}
// 停止定时器
if(next==target){
clearInterval(dom.timer);
typeof callback==='function'&&callback()
}
},20)
}
// 多属性缓动
function animate(dom,json,callback){
clearInterval(dom.timer)
// 要运动要定时器
dom.timer = setInterval(function(){
// 每20毫秒
var flag = true;
// json有几个属性,就要运动几次
for(var attr in json){
// 1 获取当前位置
if(attr=="opacity"){
// 透明度在获取当前值的是要乘100
var current = parseInt(getStyle(dom,attr)*100);
}else{
var current = parseInt(getStyle(dom,attr));
}
// 2 计算速度
var speed = json[attr]-current>0?Math.ceil((json[attr]-current)/10):Math.floor((json[attr]-current)/10)
// 3 计算下一个位置
if(attr=="zIndex"){
var next = json[attr];
}else{
var next = current + speed;
}
// 4 定位元素
if(attr=="zIndex"){
dom.style[attr] = next;
}else if(attr=="opacity"){
dom.style.opacity = next/100;
dom.style.filter = "alpha(opacity="+next+")";
}else{
dom.style[attr] = next+"px";
}
// 判断是否到达目标
if(next!=json[attr]){
flag = false;
}
}
if(flag){
clearInterval(dom.timer);
}
},20)
}
// 返回页面被卷曲的距离:垂直,水平
function scroll(){
return {
top:document.body.scrollTop||document.documentElement.scrollTop||window.pageYOffset,
left:document.body.scrollLeft||document.documentElement.scrollLeft||window.pageXOffset
}
}
// 返回节点距离页面的距离
function distance(dom){
return {
left:"",
top:""
}
}
// 计算节点距离页面的距离
function getDistance(dom){
var distance = {
left:0,
top:0
}
while(true){
distance.left = distance.left+dom.offsetLeft;
distance.top = distance.top+dom.offsetTop
dom = dom.offsetParent;
if(dom.nodeName=="BODY"){
return distance;
}
}
}
|
import { get, pick, reduce, toString } from 'lodash'
import { airports } from '../../data'
const SourceApiCreator = (mappings) => class SourceApi {
static mapEndpoint (code) {
const codeLower = code.toLowerCase()
const airport = get(mappings, `airports.${codeLower}`)
if (airport) {
return { name: airport, isGroup: false }
}
const group = get(mappings, `groups.${codeLower}`)
if (group) {
return { name: group, isGroup: true }
}
throw Error(`${airports[code].name} is not supported by this airline`)
}
static mapFareType (fareType) {
return get(mappings, `fareTypes.${fareType || 'cash'}`)
}
static mapTripType (tripType) {
return get(mappings, `tripTypes.${tripType || 'oneWay'}`)
}
static parseOptions (options) {
const fareType = this.mapFareType(get(options, 'fareType'))
const tripType = this.mapTripType(get(options, 'tripType'))
const passengerTypes = ['adults', 'children', 'infants']
const passengers = reduce(passengerTypes,
(a, v) => ({ ...a, [v]: toString(get(options, v, 0))}), {})
passengers.adults = Math.max(passengers.adults, 1)
return { fareType, tripType, passengers }
}
static getRequestData (originCode, destinationCode, date, options) {
throw new Error('Not implemented')
}
static async search (originCode, destinationCode, date, options) {
throw new Error('Not implemented')
}
}
export default SourceApiCreator
|
const invoices = [
{
date: '2018-10-31',
items: [
{ code: '2143', amount: 222 },
{ code: '2111', amount: 500 }
]
},
{
date: '2018-07-12',
items: [
{ code: '2222', amount: 231 },
{ code: '2143', amount: 333 }
]
},
{
date: '2018-02-02',
items: [
{ code: '2143', amount: 111 },
{ code: '7777', amount: 999 }
]
},
];
module.exports = app => {
app.get('/invoices', (req, res) => res.json(invoices));
}
|
import React from 'react';
import { connect } from 'react-redux';
import SampleHeading from './components/SampleHeading.jsx';
import SampleComponent1 from './components/SampleComponent1.jsx';
import IdiotCounter from './components/IdiotCounter';
import Action from './actions';
import ReduxCounter from './components/ReduxCounter';
const topicStyle = {
fontSize: '20px',
color: '#581845'
}
function App(props) {
return (
<div>
<p style={topicStyle}>Sample Components with props parsing</p>
<SampleHeading name="borBier" />
<hr/>
<p style={topicStyle}>Parsing some props to another components</p>
<SampleComponent1 length={5} width={5} />
<hr/>
<p style={topicStyle}>Just an idiot counter (with React hook)</p>
<IdiotCounter />
<hr/>
<p style={topicStyle}>Idiot counter (with React Redux)</p>
<ReduxCounter
value={props.counter}
onIncrement={() => props.increment()}
onDecrement={() => props.decrement()}
/>
</div>
);
}
const mapStateToProps = (state) => ({
counter: state.counter
})
const mapDispatchtoProps = (dispatch) => ({
increment: () => dispatch({type: Action.INCREMENT, text: "INCREMENT Redux"}),
decrement: () => dispatch({type: Action.DECREMENT, text: "DECREMENT Redux"})
})
export default connect(mapStateToProps, mapDispatchtoProps)(App);
|
const router = require("express").Router();
const Controller = require("../controllers/userController");
const { multerMiddleware } = require("../middlewares/multer");
const { postImage } = require("../middlewares/uploadImage");
router.post("/user/reset-password", Controller.generateLinkReset);
router.post("/login", Controller.login);
router.post("/loginGoogle", Controller.loginGoogle);
router.post("/reset-password/", Controller.resetPassword);
router.post("/register", multerMiddleware, postImage, Controller.register);
module.exports = router;
|
"use strict";
$(document).ready(function() {
$(".new-tweet form textarea").bind("keyup", function(event) {
let counter = 140 - this.value.length
let counterObj = $(this).parent().children(".counter")
counterObj.prepend()
counterObj.text(counter)
if (counter < 0) {
counterObj.css("color","red")
} else {
counterObj.css("color","black")
}
})
});
|
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var bodyParser = require("body-parser");
var itemRouter = require("./routes/item");
var auth = require("./routes/auth");
var app = express();
var helmet = require("helmet");
var app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(helmet());
var mongoose = require("mongoose");
var myConfig = require("./config/config.js");
mongoose.connect(
myConfig.dbURL,
{ autoIndex: false }
);
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: "false" }));
app.use(express.static(path.join(__dirname, "build")));
app.use("/api/auth", auth);
app.use("/api/items", itemRouter);
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "frontend/build")));
app.get("*", (req, res) => {
res.sendFile(
path.resolve(__dirname, "frontend", "build", "index.html")
);
});
}
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
console.log(err);
if (req.app.get("env") !== "development") {
delete err.stack;
}
res.status(err.statusCode || 500).json(err);
});
module.exports = app;
|
// 'use strict'
// module.exports.fb = {
// clientId: process.env.fbClientId || fbConstants.clientId,
// redirectUri: process.env.fbRedirectUri || fbConstants.redirectUri,
// clientSecret: process.env.fbClientSecret || fbConstants.clientSecret,
// tokenUrl: process.env.tokenUrl || fbConstants.tokenUrl
// };
// module.exports.jwt = {
// secret: process.env.jwtSecret || jwtConstants.secret,
// expirationInMinutes: process.env.jwtExpiration || jwtConstants.expirationInMinutes
// }; |
const express = require('express');
const router = express.Router();
const getYelp = require('../api/api.js');
const mockData = require('../api/mockData/mockData.json');
const filterRestaurants = require('../util/filterRestaurants');
router.get('/:latitude/:longitude/:category', async (req, res) => {
const params = ({ latitude, longitude, category } = req.params);
let restaurants;
if (process.env.NODE_ENV !== 'production') {
restaurants = {
data: mockData,
};
} else {
try {
restaurants = await getYelp(params);
} catch (error) {
console.error(error);
}
}
const filteredRestaurants = filterRestaurants(restaurants.data.businesses);
res.json(filteredRestaurants);
});
module.exports = router;
|
function setFuckingText(index)
{
var fucking_text = new Array();
fucking_text[0] = "Get the fuck up and exercise!";
fucking_text[1] = "Fuck the Seahawks";
fucking_text[2] = "Make every fucking day count";
fucking_text[3] = "Stop fucking comb-overs";
fucking_text[4] = "No one gives a fuck, so stop thinking they do";
fucking_text[5] = "Stop fucking having expectations and just live";
fucking_text[6] = "Stop being a fucking afraid";
fucking_text[7] = "Stop fucking following the status quo";
fucking_text[8] = "Fucking stop swag";
fucking_text[9] = "Don't raise your voice, improve your fucking argument";
fucking_text[10] = "Stop fucking procrastinating";
fucking_text[11] = "Life is your attitude, not your fucking situation";
fucking_text[12] = "Don't blame others for their mistakes, it makes you fucking weak";
fucking_text[13] = "Don't try to be the best, it makes you fucking arrogant";
fucking_text[14] = "Late people never fucking win";
fucking_text[15] = "Fucking no ragrets";
document.getElementById('bigfuckingtext').innerHTML = fucking_text[index];
}
function loadText()
{
var index = gup("p");
if( index == "" )
{
changeFuckingText();
}
else
{
var num = parseInt(index);
if( num < 16 )
{
setFuckingText(num);
}
else
{
changeFuckingText();
}
}
}
function changeFuckingText()
{
var i = Math.floor(16*Math.random());
setFuckingText(i);
} |
const talents = [
"private tutoring",
"removal",
"gardening",
"household / housekeeping",
"office tasks",
"administration help",
"regulatory documents help",
"shopping aid",
"repair (electr.)",
"repair (mech.)",
"computer (hardware/software)",
"sewing",
"household cleaning",
"car cleaning",
"pets cats/dogs",
"holiday (pets/plant/house/garden)",
"elderly mentorinmg"
]
// export students here:
//module.exports = talents |
#!/usr/bin/env node
/**
* `grunt test_bin` selects this file for the `conjure --server` option.
*/
var express = require('express');
var app = express();
var pid = '/tmp/parapsyc-test-server.pid';
var port = 8174;
app.use(express.static(__dirname + '/../test/fixture/express-static'));
app.listen(port);
|
import React, {useState, useEffect, useRef} from 'react'
const Assets = () => {
// let intervalID = '';
// const [data, setData] = useState(0);
// const getData = () => {
// fetch('https://pro.tomya.com/api/providers/trading/trades?asset=BTCUSDT')
// .then(response => response.json())
// .then(data => {
// setData(data.trades);
// intervalID = setTimeout(getData.bind(this), 1000);
// });
// }
// useEffect(() => {
// getData();
// return () => {
// clearTimeout(this.intervalID);
// };
// }, []);
// if (data[0] === undefined) {
// return <span>Yükleniyor...</span>;
// } else {
var isLogin = [];
let user = 1;
if(user== 0){
isLogin=
<div>
</div>
}
else{
isLogin=
<div className="ml-2">
<p> Kullanılabilir BTC : 0.124214</p>
<p> Kullanılabilir USDT : 4.124216</p>
</div>
}
return (
<div>
<div className="crypt-boxed-area">
<div className="no-gutters">
<div className="row">
<h6 style={{marginLeft:"30px", marginTop:"20px"}}>Varlıklarım</h6>
</div>
<div className="row">
<div className="col ml-2">
<button style={{width:"100%"}}className="percent-btn">Yatırım</button>
</div>
<div className="col mr-2">
<button style={{width:"100%"}} className="percent-btn">Çekim</button>
</div>
</div>
{isLogin}
</div>
</div>
</div>
)
}
export default Assets; |
export default function application(state = { excitement: 0, todos: [], events: {}, roles: {1: { id: '1', name: 'City Planning' }, 2: { id: '2', name: 'Law Enforcement' } } }, action) {
let newState;
switch (action.type) {
case 'GET_EXCITED': {
newState = Object.assign({}, state, {
excitement: state.excitement += 1
});
break;
}
case 'ADD_TODO': {
newState = Object.assign({}, state, {
todos: state.todos.push({name: action.name, link: action.link})
});
break;
}
case 'UPDATE_ROLES': {
newState = Object.assign({}, state, {
roles: action.roles
});
break;
}
case 'UPDATE_EVENTS': {
newState = Object.assign({}, state, {
events: action.events
});
break;
}
case 'TOGGLE_TODO': {
newState = Object.assign({}, state, {
excitement: state.excitement += 1
});
break;
}
default: {
newState = state;
}
}
return newState;
}
|
import React from 'react'
import { Column, FlexContainer, RightAlign } from '../../../../components/layout'
import { Button, Input } from '../../../../components/reusable'
import { CharacterDetailsWrapper } from './styles'
const CharacterDetails = (props) => {
const {
editMode,
character,
save
} = props
const [name, setName] = React.useState("")
const [tags, setTags] = React.useState("")
React.useEffect(() => {
if (character) {
setName(character.name)
}
})
const saveDetails = () => {
const splitTags = tags.split(',')
save({
name,
tags: splitTags
})
}
return (
<CharacterDetailsWrapper>
<FlexContainer>
<Column>
<Input
label="Name"
onChange={setName}
value={name}
placeholder="What is your character's name?"
uneditable={!editMode}
/>
</Column>
</FlexContainer>
<FlexContainer>
<Column>
<Input
label="Tags"
placeholder="A comma-separated list of tags you can use to search for your scene later"
onChange={setTags}
value={tags}
uneditable={!editMode}
/>
</Column>
</FlexContainer>
<br />
<FlexContainer>
<RightAlign>
<Button onClick={saveDetails}>Submit</Button>
</RightAlign>
</FlexContainer>
</CharacterDetailsWrapper>
)
}
export default CharacterDetails |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.