text stringlengths 7 3.69M |
|---|
$(document).ready(function() {
var registerModal = $('div#register-modal');
var hbsRadioTmpl = $('script#server-item-temp');
var revisitButton = $('.ui.blue.labeled.icon.button.active#revisit');
var submitButton = $('div#eventSubmit');
var registerButton = $('.ui.blue.labeled.icon.button#register-service');
var keyProvider = $('input[type=text]#register-key');
var nameProvider = $('input[type=text]#register-name');
var serverSupplierFunc = function() {
return $('input[type=radio][data-value][checked=checked]').attr('data-value');
};
// Sends a request to dbcheck.php to register the event if not done so already.
// The JSON Response will contain a message if there was a non-exceptional failure.
function registerEvent(apiKey, eventName) {
$.ajax({
type: 'POST',
dataType: 'json',
data: {tkn: apiKey, evt: eventName, srv: serverSupplierFunc()},
success: function(data, stat, something) {
alert(data.isValidEvent);
if(data.isValidEvent) {
alert(eventName + " has been successfully registered!");
} else if(data.msg == null){
alert("Could not register event due to an unknown error!");
} else {
alert(data.msg);
}
},
error: function(something, stat, error) {
alert("Register Request Failed!: " + String(stat) + " - " + String(error));
}
})
}
// Redirects the page to the Leaderboards for the indicated event
// Validity is checked first.
function goToEvent(eventName) {
$.ajax({
type: 'POST',
dataType: 'json',
data: {evt: eventName},
success: function(data, stat, ignore) {
if(data.isValidEvent) {
$.redirect('./leaderboard/' + eventName);
} else {
alert('Could Not Find ' + eventName + "...");
}
},
error: function(ignore, stat, error) {
alert("Event Request Failed!: " + String(stat) + " - " + String(error));
}
});
//TODO Notify user that the request failed
}
// Attempt to Redirect when Submit is clicked.
submitButton.on('click', function() {
var evtName = $(this).siblings('input').val();
goToEvent(evtName);
});
// Open Event Registry Modal on Click
// If Approved, then obtain the apiKey and eventName and register the event.
// Open Event Registry Modal on Click
// If Approved, then obtain the apiKey and eventName and register the event.
registerButton.on('click', function() {
registerModal
.modal({
closable: false,
onApprove: function() {
var apiKey = keyProvider.val();
var evtName = nameProvider.val();
var server = serverSupplierFunc();
if(apiKey === '' || evtName === ''){
// If either is empty, return false to allow the user to
// either cancel or fix their input.
return false;
}
if(!server) {
alert('Please select a server!');
return false;
}
registerEvent(apiKey, evtName, server);
return true;
},
onHide: function() {
keyProvider.val('');
nameProvider.val('');
}
})
.modal('show');
});
revisitButton.on('click', function() {
$.ajax({
type: 'POST',
url: '/leaderboard',
dataType: 'json',
success: function(data, stat, ignore) {
if(!data.isSuccess) {
alert(data.eventName + ' is no longer available');
// Disable Button
revisitButton.removeClass('active');
revisitButton.addClass('disabled');
} else {
alert('Going to ' + data.eventName);
goToEvent(data.eventName);
}
},
error: function(ignore, stat, error) {
alert('Cookie Request Failed!: ' + String(stat) + " - " + String(error));
}
});
});
var _SERVER_TEMPLATE = Handlebars.compile(hbsRadioTmpl.html());
function renderList() {
$.ajax({
type:'OPTIONS',
url:'/servers',
dataType: 'json',
success: function(data, stat, ignore) {
var menu = $('#server-menu');
var eastFound = false;
console.log(menu);
data.forEach(function(element) {
if(typeof element === 'object' && element.hasOwnProperty('displayName')) {
console.log(element.displayName + " Loaded! -- " + element.url);
if(!eastFound && element.displayName.indexOf('East') > 0) {
menu.append(_SERVER_TEMPLATE({text: element.displayName, serverurl: element.url, checked: 'id=east-checkbox'}));
eastFound = true;
} else {
menu.append(_SERVER_TEMPLATE({text: element.displayName, serverurl: element.url, checked: ''}));
}
}
});
// The US East Server is set to be the first Checked
$('input[type=radio][data-value]#east-checkbox').attr('checked', 'checked');
// Initialize Checkbox with a super fun workaround for Semantic UI not working correctly.
// The 'checked' class was not being removed, this handles that broken task...
// FIXME Optimize
$('.ui.radio.checkbox').checkbox({
onChange: function() {
var removing = $('input[type=radio][data-value][checked=checked]');
removing.parent('div').removeClass('checked');
removing.removeAttr('checked');
var adding = $('div.ui.radio.checked');
adding.children('input').first().attr('checked', 'checked');
}
});
},
error: function(ignore, stat, error) {
console.error(error);
}
});
}
function renderRevisitButton() {
$.ajax({
type: 'POST',
url: '/leaderboard',
dataType: 'json',
success: function(data, stat, ignore) {
var button = revisitButton;
if(!data.isSuccess) {
button.removeClass('active');
button.addClass('disabled');
} else {
button.removeClass('disabled');
button.addClass('active');
}
},
error: function(ignore, stat, error) {
alert('Cookie Request Failed!: ' + String(stat) + " - " + String(error));
}
})
}
renderList();
renderRevisitButton();
}); |
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _class, _temp, _class2, _temp2;
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Field from './Field';
import * as utils from './utils';
/**
* 提供对浏览器原生表单控件的封装
* 支持以下类型表单元素:
* - input[type=xx]
* - textarea
* - select
*/
var EasyField = (_temp = _class = function (_Component) {
_inherits(EasyField, _Component);
function EasyField() {
_classCallCheck(this, EasyField);
return _possibleConstructorReturn(this, (EasyField.__proto__ || Object.getPrototypeOf(EasyField)).apply(this, arguments));
}
_createClass(EasyField, [{
key: 'getChildContext',
value: function getChildContext() {
var _this2 = this;
return {
$getFieldProps: function $getFieldProps() {
return _this2.$fieldProps;
}
};
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props = this.props,
name = _props.name,
defaultValue = _props.defaultValue,
$defaultValue = _props.$defaultValue,
$defaultState = _props.$defaultState,
$validators = _props.$validators,
$asyncValidators = _props.$asyncValidators,
$onFieldChange = _props.$onFieldChange,
$parser = _props.$parser,
$formatter = _props.$formatter,
validMessage = _props.validMessage,
typeStr = _props.type,
checked = _props.checked,
unchecked = _props.unchecked,
_onChange = _props.onChange,
_onFocus = _props.onFocus,
_onBlur = _props.onBlur,
otherProps = _objectWithoutProperties(_props, ['name', 'defaultValue', '$defaultValue', '$defaultState', '$validators', '$asyncValidators', '$onFieldChange', '$parser', '$formatter', 'validMessage', 'type', 'checked', 'unchecked', 'onChange', 'onFocus', 'onBlur']);
var defaultErrMsg = 'Error';
var _typeStr$split = typeStr.split('.'),
_typeStr$split2 = _slicedToArray(_typeStr$split, 2),
type = _typeStr$split2[0],
groupType = _typeStr$split2[1];
var fieldProps = {
name: name,
$onFieldChange: $onFieldChange,
$defaultState: $defaultState,
$validators: Object.assign({
required: function required($value, check) {
return check === false || (type === 'checkbox' || type === 'radio' ? $value === checked : !!($value + '')) || validMessage.required || defaultErrMsg + ': required';
},
maxLength: function maxLength($value, len) {
return len === false || utils.isEmpty($value) || $value.length <= len * 1 || validMessage.maxLength || defaultErrMsg + ': maxLength: ' + len;
},
minLength: function minLength($value, len) {
return len === false || utils.isEmpty($value) || $value.length >= len * 1 || validMessage.minLength || defaultErrMsg + ': minLength: ' + len;
},
max: function max($value, limit) {
return limit === false || utils.isEmpty($value) || $value * 1 <= limit || validMessage.max || defaultErrMsg + ': max: ' + limit;
},
min: function min($value, limit) {
return limit === false || utils.isEmpty($value) || $value * 1 >= limit || validMessage.min || defaultErrMsg + ': min: ' + limit;
},
pattern: function pattern($value, regexp) {
return regexp === false || utils.isEmpty($value) || regexp.test($value) || validMessage.pattern || defaultErrMsg + ': pattern: ' + regexp;
}
}, $validators),
$asyncValidators: $asyncValidators,
validMessage: validMessage
};
Object.keys(Object.assign({}, fieldProps.$validators, $asyncValidators)).forEach(function (prop) {
if (prop in otherProps) {
fieldProps[prop] = otherProps[prop];
if (!utils.isValidProp(prop)) {
delete otherProps[prop];
}
}
});
if ('defaultValue' in this.props) {
fieldProps.$defaultValue = defaultValue;
}
if ('$defaultValue' in this.props) {
fieldProps.$defaultValue = $defaultValue;
}
var Element = void 0;
switch (type) {
case 'select':
case 'textarea':
Element = type;
break;
case 'group':
Element = 'div';
if (groupType === 'checkbox' && !('$defaultValue' in fieldProps)) {
fieldProps.$defaultValue = [];
}
break;
default:
Element = 'input';
break;
}
return React.createElement(
Field,
fieldProps,
function (props) {
if (type === 'group') {
_this3.$fieldProps = {
$fieldutil: props,
$onFieldChange: _onChange,
$onFieldFocus: _onFocus,
$onFieldBlur: _onBlur,
$parser: $parser,
$formatter: $formatter,
$groupType: groupType,
$FieldName: name
};
var children = otherProps.children,
restProps = _objectWithoutProperties(otherProps, ['children']);
var childProps = Object.assign({}, props, {
Field: EasyFieldGroupItem
});
return React.createElement(
Element,
restProps,
typeof children === 'function' ? children(childProps) : React.Children.map(children, function (child) {
return React.cloneElement(child, childProps);
})
);
}
var elemProps = void 0;
switch (type) {
case 'checkbox':
case 'radio':
elemProps = {
checked: $formatter(props.$value) === checked,
onChange: function onChange(ev) {
props.$render($parser(ev.target.checked ? checked : unchecked));
_onChange && _onChange(ev);
}
};
break;
default:
elemProps = {
value: 'compositionValue' in _this3 ? _this3.compositionValue : $formatter(props.$value),
onCompositionEnd: function onCompositionEnd(ev) {
_this3.composition = false;
delete _this3.compositionValue;
elemProps.onChange(ev);
},
onCompositionStart: function onCompositionStart() {
return _this3.composition = true;
},
onChange: function onChange(ev) {
var value = ev.target.value;
if (_this3.composition) {
_this3.compositionValue = value;
_this3.forceUpdate();
} else {
props.$render($parser(value));
_onChange && _onChange(ev);
}
}
};
break;
}
return React.createElement(Element, Object.assign({}, otherProps, {
type: type,
name: name
}, elemProps, {
onFocus: function onFocus(ev) {
props.$setFocused(true);
_onFocus && _onFocus(ev);
},
onBlur: function onBlur(ev) {
if (props.$untouched) {
props.$setTouched(true);
}
props.$setFocused(false);
_onBlur && _onBlur(ev);
}
}));
}
);
}
}]);
return EasyField;
}(Component), _class.displayName = 'React.formutil.EasyField', _class.propTypes = {
type: PropTypes.string.isRequired,
defaultValue: PropTypes.any,
checked: PropTypes.any,
unchecked: PropTypes.any,
validMessage: PropTypes.object,
$parser: PropTypes.func,
$formatter: PropTypes.func
}, _class.childContextTypes = {
$getFieldProps: PropTypes.func
}, _class.defaultProps = {
type: 'text',
checked: true,
unchecked: false,
validMessage: {},
$parser: function $parser(value) {
return value;
},
$formatter: function $formatter(value) {
return value;
}
}, _temp);
var EasyFieldGroupItem = (_temp2 = _class2 = function (_Component2) {
_inherits(EasyFieldGroupItem, _Component2);
function EasyFieldGroupItem() {
_classCallCheck(this, EasyFieldGroupItem);
return _possibleConstructorReturn(this, (EasyFieldGroupItem.__proto__ || Object.getPrototypeOf(EasyFieldGroupItem)).apply(this, arguments));
}
_createClass(EasyFieldGroupItem, [{
key: 'render',
value: function render() {
var _props2 = this.props,
$value = _props2.$value,
_onChange2 = _props2.onChange,
_onFocus2 = _props2.onFocus,
_onBlur2 = _props2.onBlur,
others = _objectWithoutProperties(_props2, ['$value', 'onChange', 'onFocus', 'onBlur']);
var _context$$getFieldPro = this.context.$getFieldProps(),
$fieldutil = _context$$getFieldPro.$fieldutil,
$onFieldChange = _context$$getFieldPro.$onFieldChange,
$onFieldFocus = _context$$getFieldPro.$onFieldFocus,
$onFieldBlur = _context$$getFieldPro.$onFieldBlur,
$FieldName = _context$$getFieldPro.$FieldName,
$groupType = _context$$getFieldPro.$groupType,
$parser = _context$$getFieldPro.$parser,
$formatter = _context$$getFieldPro.$formatter;
var elemProps = $groupType === 'radio' ? {
checked: $formatter($fieldutil.$value) === $value,
onChange: function onChange(ev) {
$fieldutil.$render($parser($value));
_onChange2 && _onChange2(ev);
$onFieldChange && $onFieldChange(ev);
}
} : $groupType === 'checkbox' ? {
checked: $formatter($fieldutil.$value).indexOf($value) > -1,
onChange: function onChange(ev) {
$fieldutil.$render($parser(ev.target.checked ? $fieldutil.$value.concat($value) : $fieldutil.$value.filter(function (value) {
return value !== $value;
})));
_onChange2 && _onChange2(ev);
$onFieldChange && $onFieldChange(ev);
}
} : {
value: $formatter($fieldutil.$value),
onChange: function onChange(ev) {
$fieldutil.$render($parser(ev.target.value));
_onChange2 && _onChange2(ev);
$onFieldChange && $onFieldChange(ev);
}
};
return React.createElement('input', Object.assign({}, others, elemProps, {
type: $groupType,
name: $FieldName,
onFocus: function onFocus(ev) {
$fieldutil.$setFocused(true);
_onFocus2 && _onFocus2(ev);
$onFieldFocus && $onFieldFocus(ev);
},
onBlur: function onBlur(ev) {
if ($fieldutil.$untouched) {
$fieldutil.$setTouched(true);
}
$fieldutil.$setFocused(false);
_onBlur2 && _onBlur2(ev);
$onFieldBlur && $onFieldBlur(ev);
}
}));
}
}]);
return EasyFieldGroupItem;
}(Component), _class2.displayName = 'react.formutil.EasyField.GroupItem', _class2.propTypes = {
$value: PropTypes.any.isRequired
}, _class2.contextTypes = {
$getFieldProps: PropTypes.func
}, _temp2);
export default EasyField; |
(function (exports) {
var MusicResolver = function (entity) {
this.entity = entity;
};
MusicResolver.prototype.acceptsUri = function (uri) {
return uri.match(/^entity\:\/\/music\/track/i) != null;
};
MusicResolver.prototype.request = function (method, uri, data) {
var promise = new Promise();
var query = {};
try {
query = parseQueryString(uri.split('?')[1]);
} catch (e) {
}
setTimeout(function () {
var response = {
'data': [],
'status': 'OK'
};
var song = {
'name': query.q,
'uri': '',
'artists':[
{
'name': 'track.artist.name',
'uri': 'track.artist.link'
}
],
'album': {
'name': 'track.album.name',
'uri': ''
}
};
response.data.push(song);
promise.setDone(response);
}, 100);
return promise;
};
exports.MusicResolver = MusicResolver;
})(this);
|
import IndexRoutesPage from '@pages/base';
import { HashRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from '@store/index';
import '@style/App.scss';
import { getToken } from '@/utils/auth';
import { _Actions } from '@/store/actions/index';
/*
import { useState, useEffect } from 'react';
import { HashRouter, useLocation, useHistory } from 'react-router-dom';
import {
CSSTransition
} from 'react-transition-group';
function AnimationCom(props) {
const location = useLocation();
const history = useHistory();
const [ inProp, setProp ] = useState(false);
useEffect(() => {
const k = history.listen((state, name) => {
setProp(!inProp);
});
return () => k();
}, [ inProp, history ]);
return (
<div style={{ height: '100vh', padding: 0, margin: 0 }}>
{ `${inProp}` }
<CSSTransition
in={inProp}
classNames="fade"
timeout={800}
key={location.pathname}>
<IndexRoutesPage />
</CSSTransition>
</div>
);
}
*/
const token = getToken() || '';
store.dispatch(_Actions.token(token));
// store.dispatch();
function App() {
return <HashRouter>
<Provider store={store}>
<IndexRoutesPage />
</Provider>
</HashRouter>;
}
export default App;
|
import React from "react"
import {
View,
Image,
ImageBackground,
TouchableOpacity,
Text,
Button,
Switch,
TextInput,
StyleSheet,
ScrollView
} from "react-native"
import Icon from "react-native-vector-icons/FontAwesome"
import { CheckBox } from "react-native-elements"
import { connect } from "react-redux"
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp
} from "react-native-responsive-screen"
import { getNavigationScreen } from "@screens"
export class Blank extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
render = () => (
<ScrollView
contentContainerStyle={{ flexGrow: 1 }}
style={styles.ScrollView_1}
>
<View style={styles.View_2} />
<TouchableOpacity
style={styles.TouchableOpacity_831_1342}
onPress={() =>
this.props.navigation.navigate(getNavigationScreen("791_66"))
}
>
<View style={styles.View_I831_1342_791_37}>
<View style={styles.View_I831_1342_791_38}>
<Text style={styles.Text_I831_1342_791_38}>Light</Text>
</View>
</View>
<View style={styles.View_I831_1342_791_39}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/f050/9616/fb213d1cd6b31745d25e8f75ffe964fd"
}}
style={styles.ImageBackground_I831_1342_791_39_280_4541}
/>
</View>
</TouchableOpacity>
<TouchableOpacity
style={styles.TouchableOpacity_831_1343}
onPress={() =>
this.props.navigation.navigate(getNavigationScreen("791_67"))
}
>
<View style={styles.View_I831_1343_791_41}>
<View style={styles.View_I831_1343_791_42}>
<Text style={styles.Text_I831_1343_791_42}>Use device theme</Text>
</View>
</View>
</TouchableOpacity>
<TouchableOpacity
style={styles.TouchableOpacity_831_1344}
onPress={() =>
this.props.navigation.navigate(getNavigationScreen("791_67"))
}
>
<View style={styles.View_I831_1344_791_41}>
<View style={styles.View_I831_1344_791_42}>
<Text style={styles.Text_I831_1344_791_42}>Dark</Text>
</View>
</View>
</TouchableOpacity>
<View style={styles.View_831_1394}>
<View style={styles.View_I831_1394_654_33}>
<View style={styles.View_I831_1394_654_34}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/3d59/441b/1eed4ad1a718cb5e2479f01e85da3ad5"
}}
style={styles.ImageBackground_I831_1394_654_34_280_5123}
/>
</View>
<View style={styles.View_I831_1394_654_35}>
<Text style={styles.Text_I831_1394_654_35}>Theme</Text>
</View>
<View style={styles.View_I831_1394_654_36}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/f4af/a790/3402b06379130266366e0cc6bde93de6"
}}
style={styles.ImageBackground_I831_1394_654_36_280_12186}
/>
</View>
</View>
</View>
<View style={styles.View_831_1581}>
<View style={styles.View_I831_1581_217_6977} />
</View>
<View style={styles.View_831_1486}>
<View style={styles.View_I831_1486_816_137}>
<View style={styles.View_I831_1486_816_138}>
<Text style={styles.Text_I831_1486_816_138}>9:41</Text>
</View>
</View>
<View style={styles.View_I831_1486_816_139}>
<View style={styles.View_I831_1486_816_140}>
<View style={styles.View_I831_1486_816_141}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/42fe/75df/eee86effef9007e53d20453d65f0d730"
}}
style={styles.ImageBackground_I831_1486_816_142}
/>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/323b/7a56/3bd8d761d4d553ed17394f5c34643bfe"
}}
style={styles.ImageBackground_I831_1486_816_145}
/>
</View>
<View style={styles.View_I831_1486_816_146} />
</View>
<View style={styles.View_I831_1486_816_147}>
<View style={styles.View_I831_1486_816_148} />
<View style={styles.View_I831_1486_816_149} />
<View style={styles.View_I831_1486_816_150} />
<View style={styles.View_I831_1486_816_151} />
</View>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/6a2b/c9ca/21b52f3f9fca9a68ca91e9ed4afad110"
}}
style={styles.ImageBackground_I831_1486_816_152}
/>
</View>
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
ScrollView_1: { backgroundColor: "rgba(255, 255, 255, 1)" },
View_2: { height: hp("111%") },
TouchableOpacity_831_1342: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("7%"),
minHeight: hp("7%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("15%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1342_791_37: {
flexGrow: 1,
width: wp("9%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I831_1342_791_38: {
width: wp("9%"),
minWidth: wp("9%"),
minHeight: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
justifyContent: "flex-start"
},
Text_I831_1342_791_38: {
color: "rgba(13, 14, 15, 1)",
fontSize: 11,
fontWeight: "500",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_I831_1342_791_39: {
flexGrow: 1,
width: wp("9%"),
height: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("87%"),
top: hp("1%"),
backgroundColor: "rgba(0, 0, 0, 0)",
overflow: "hidden"
},
ImageBackground_I831_1342_791_39_280_4541: {
flexGrow: 1,
width: wp("6%"),
height: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%")
},
TouchableOpacity_831_1343: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("7%"),
minHeight: hp("7%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("29%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1343_791_41: {
flexGrow: 1,
width: wp("32%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I831_1343_791_42: {
width: wp("32%"),
minWidth: wp("32%"),
minHeight: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
justifyContent: "flex-start"
},
Text_I831_1343_791_42: {
color: "rgba(13, 14, 15, 1)",
fontSize: 11,
fontWeight: "500",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
TouchableOpacity_831_1344: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("7%"),
minHeight: hp("7%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("22%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1344_791_41: {
flexGrow: 1,
width: wp("9%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I831_1344_791_42: {
width: wp("9%"),
minWidth: wp("9%"),
minHeight: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
justifyContent: "flex-start"
},
Text_I831_1344_791_42: {
color: "rgba(13, 14, 15, 1)",
fontSize: 11,
fontWeight: "500",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_831_1394: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("9%"),
minHeight: hp("9%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("6%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1394_654_33: {
flexGrow: 1,
width: wp("91%"),
height: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I831_1394_654_34: {
width: wp("9%"),
minWidth: wp("9%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)",
overflow: "hidden"
},
ImageBackground_I831_1394_654_34_280_5123: {
flexGrow: 1,
width: wp("6%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%")
},
View_I831_1394_654_35: {
width: wp("66%"),
minWidth: wp("66%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("13%"),
top: hp("0%"),
justifyContent: "center"
},
Text_I831_1394_654_35: {
color: "rgba(33, 35, 37, 1)",
fontSize: 14,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_I831_1394_654_36: {
width: wp("9%"),
minWidth: wp("9%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("83%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)",
overflow: "hidden"
},
ImageBackground_I831_1394_654_36_280_12186: {
flexGrow: 1,
width: wp("6%"),
height: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%")
},
View_831_1581: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("5%"),
minHeight: hp("5%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("106%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I831_1581_217_6977: {
flexGrow: 1,
width: wp("36%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("32%"),
top: hp("3%"),
backgroundColor: "rgba(0, 0, 0, 1)"
},
View_831_1486: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("6%"),
minHeight: hp("6%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1486_816_137: {
flexGrow: 1,
width: wp("14%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("5%"),
top: hp("2%")
},
View_I831_1486_816_138: {
width: wp("14%"),
minWidth: wp("14%"),
minHeight: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
justifyContent: "flex-start"
},
Text_I831_1486_816_138: {
color: "rgba(22, 23, 25, 1)",
fontSize: 12,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: -0.16500000655651093,
textTransform: "none"
},
View_I831_1486_816_139: {
flexGrow: 1,
width: wp("18%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("78%"),
top: hp("2%")
},
View_I831_1486_816_140: {
width: wp("7%"),
minWidth: wp("7%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("11%"),
top: hp("0%")
},
View_I831_1486_816_141: {
width: wp("7%"),
height: hp("2%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
ImageBackground_I831_1486_816_142: {
width: wp("6%"),
minWidth: wp("6%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%")
},
ImageBackground_I831_1486_816_145: {
width: wp("0%"),
minWidth: wp("0%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("6%"),
top: hp("1%")
},
View_I831_1486_816_146: {
width: wp("5%"),
minWidth: wp("5%"),
height: hp("1%"),
minHeight: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("0%"),
backgroundColor: "rgba(22, 23, 25, 1)",
borderColor: "rgba(76, 217, 100, 1)",
borderWidth: 1
},
View_I831_1486_816_147: {
width: wp("5%"),
height: hp("1%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
View_I831_1486_816_148: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("1%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1486_816_149: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1486_816_150: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("3%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I831_1486_816_151: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
ImageBackground_I831_1486_816_152: {
width: wp("4%"),
minWidth: wp("4%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("6%"),
top: hp("0%")
}
})
const mapStateToProps = state => {
return {}
}
const mapDispatchToProps = () => {
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Blank)
|
var app = app || {
addStory: function (id) {
let self = this;
let storyContainer = document.getElementById('stories-container');
let story = document.createElement('div');
story.setAttribute('id', `story-${id}`)
story.innerHTML = 'loading story...';
storyContainer.appendChild(story);
self.getStoryById(id);
},
updateStory: function (id, title, author, url) {
let self = this;
let story = document.getElementById(`story-${id}`);
story.innerHTML = self.template(title, author, url);
},
clearStories: function () {
let element = document.getElementById("stories-container");
element.innerHTML = '';
},
template: (title, author, url) => {
return `<div><h2><a href="${url}"> ${title}</a><h2></div><div>by ${author}</div>`;
},
getStoryById: function (id) {
let self = this;
let success = function (e) {
if (e.target.response) {
const story = JSON.parse(e.target.response);
self.updateStory(story.id, story.title, story.by, story.url);
}
};
let error = function (e) {
console.log('request failed. Ex:');
console.log(e);
};
service.request('GET', `/api/news/${id}`).then(success, error);
},
getNewStories: function () {
let self = this;
let success = function (e) {
//pre-render the div's while loading
if (e.target.response) {
const storyIdArray = JSON.parse(e.target.response);
storyIdArray.forEach(id => {
self.addStory(id);
});
}
};
let error = function (e) {
console.log('request failed. Ex:');
console.log(e);
};
service.request('GET', '/api/news').then(success, error);
},
}
window.addEventListener('load', (event) => {
app.getNewStories();
}); |
var searchRegex = new RegExp(Object.keys(swaps).join("|"), "g");
var trimNoWordRegex = new RegExp(trimPattern, "g");
var pageLoaded = false;
var swapIsInProcess = false;
var enableLogging = false;
var replacedStrings = new Array();
function SwapWords() {
if (swapIsInProcess) return;
swapIsInProcess = true;
if (enableLogging) console.log("SWAPPING...");
var start = new Date();
document.title = ReplaceString(document.title);
var all = document.getElementsByTagName("*");
var count = 0;
for (var i = 0, max = all.length; i < max; i++) {
if (all[i].childNodes.length == 1) {
if (all[i].nodeName.toLowerCase() != 'script') {
if (all[i].firstChild.nodeType == 3) {
all[i].innerHTML = ReplaceString(all[i].innerHTML);
}
}
}
else {
for (var j = 0; j < all[i].childNodes.length; j++) {
if (all[i].childNodes[j].nodeType == 3) {
all[i].childNodes[j].data = ReplaceString(all[i].childNodes[j].data);
}
}
}
}
var end = new Date();
if (enableLogging) console.log(end - start);
swapIsInProcess = false;
}
function ReplaceString(value) {
if (replacedStrings.indexOf(value) > -1) return value;
var replacedString = value.replace(searchRegex, function (matched) {
if (matched in swaps) return swaps[matched];
else {
var trimmedValue = matched.replace(trimNoWordRegex, "");
var valStartIdx = matched.indexOf(trimmedValue);
var trimmedStartCharacter = matched.substring(0, valStartIdx);
var trimmedEndCharacter = matched.substring(valStartIdx + trimmedValue.length);
var dictionaryKeyValue = strictWordBeginPattern + trimmedValue + strictWordEndPattern;
if (dictionaryKeyValue in swaps) {
return trimmedStartCharacter + swaps[dictionaryKeyValue] + trimmedEndCharacter;
}
else {
return matched;
}
}
});
replacedStrings.push(replacedString);
return replacedString;
}
window.addEventListener("load", function () {
pageLoaded = true;
if (!swapIsInProcess) {
SwapWords();
}
});
chrome.extension.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action == 'swap_words') {
if (!swapIsInProcess && pageLoaded) {
SwapWords();
}
}
});
|
import { THEM_SO_THANH_VIEN, DEM_SO_THANH_VIEN, LAY_THONG_TIN_CALO_THANH_VIEN } from '../../asset/MyConst'
const initialState = {
soThanhVien: 0,
thongTinThanhVien: []
}
export default function (state = initialState, action) {
switch (action.type) {
case DEM_SO_THANH_VIEN:
case THEM_SO_THANH_VIEN:
{
return { ...state, soThanhVien: action.soThanhVien }
}
default:
return state
}
}
|
import {connect} from 'react-redux'
import {StyleSheet, Text, View} from 'react-native'
import React, {Component} from 'react'
import {getCardsLength} from '../utils/helpers'
import {getData} from '../utils/api'
import {purple, white, red, orange} from '../utils/colors'
import ActionButton from '../components/ActionButton'
class DeckView extends Component {
render() {
const deck = this.props.navigation.state.params.entryId
const {decks} = this.props
const questions = decks[deck].questions
return (
<View style={styles.container}>
<View style={styles.card}>
<Text style={styles.mainText}>
{decks[deck].title}
</Text>
<Text style={styles.subText}>
{questions ? getCardsLength(questions) : null}
</Text>
<ActionButton
styles={actionBtnStyle}
text={'Add Card'}
color={purple}
onPress={() => this.props.navigation.navigate('AddCard', {entryId: deck})}/>
<ActionButton
styles={actionBtnStyle}
text={'Start Quiz'}
color={red}
onPress={() => this.props.navigation.navigate('Quiz', {entryId: deck})}/>
</View>
</View>
)
}
}
const actionBtnStyle = StyleSheet.create({
iosBtn: {
padding: 10,
borderRadius: 7,
height: 45,
margin: 5,
width: 170
},
submitBtnText: {
color: white,
fontSize: 22,
textAlign: 'center'
}
})
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
card: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'stretch',
backgroundColor: orange,
margin: 10,
borderRadius: 10,
shadowColor: 'rgba(0,0,0,0.34)',
shadowOffset: {
width: 0,
height: 3
},
shadowRadius: 4,
shadowOpacity: 1
},
mainText: {
color: white,
fontSize: 40
},
subText: {
color: white,
fontSize: 30,
marginBottom: 160
}
});
function mapStateToProps({decks}) {
return {decks}
}
export default connect(mapStateToProps)(DeckView) |
import React from 'react';
const Index = () => {
return (
<div className="footer">
<div className="footer--about">
<span className="footer--about__title">Endereços</span>
<span className="footer--about__subtitle">Rua Descampado, 222 - São Paulo, SP</span>
<span className="footer--about__subtitle">Avenida Joaquim Alves Corrêa, 3224 - Valinhos, SP</span>
</div>
<div className="footer--about">
<span className="footer--about__title">Contato</span>
<span className="footer--about__subtitle"><i class="fab fa-whatsapp"></i> (11) 95030-0039</span>
<span className="footer--about__subtitle"><i class="far fa-envelope"></i> valibrasil@terra.com.br</span>
</div>
</div>
);
};
export default Index;
|
if (typeof define !== 'function') {
var define = function (f) { module.exports = f (require); }
}
/**
* This module exports an array of Level objects.
*/
define(function(require) {
'use strict';
var Level = require('./level');
return [
new Level ({
solids:[[
{"x":100,"y":100,"c":false},{"x":191,"y":438,"c":true},{"x":502,"y":432,"c":true},
{"x":630,"y":285,"c":false},{"x":726,"y":177,"c":true},{"x":751,"y":199,"c":true},
{"x":935,"y":284,"c":false},{"x":1036,"y":339,"c":false},{"x":1249,"y":339,"c":false},
{"x":1249,"y":712,"c":false},{"x":10,"y":714,"c":false},{"x":12,"y":100,"c":false}
]]
})
];
});
|
var urlid = $_GET('id')
var team = null
console.log("From URL", urlid)
function $_GET(param) {
var vars = {};
window.location.href.replace(location.hash, '').replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function(m, key, value) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if (param) {
return vars[param] ? vars[param] : null;
}
return vars;
}
const dataSource = JSON.parse(localStorage.getItem("fe1-local_data"))
console.log("Wow : new data source ::", dataSource)
console.log("Wow : data source type ::", typeof(dataSource))
function findDataFromLS(ID) {
const objArray = JSON.parse(localStorage.getItem("fe1-local_data"));
return filterObj = objArray.filter(function(e) {
return e.UUID == ID;
})[0];
}
function findTeamFromLS(PID) {
const objArray = JSON.parse(localStorage.getItem("fe1-local_data"));
return filterObj = objArray.filter(function(e) {
return e.PUUID == PID;
});
}
// // mapReduce = (a -> b, (b,a) -> b, (b,a) -> b)
// const mapReduce = (m,r) =>
// (acc,x) => r (acc, m (x))
// // concatMap :: (a -> [b]) -> [a] -> [b]
// const concatMap = f => xs =>
// xs.reduce (mapReduce (f, concat), [])
// // concat :: ([a],[a]) -> [a]
// const concat = (xs,ys) =>
// xs.concat (ys)
// // id :: a -> a
// const id = x =>
// x
// // flatten :: [[a]] -> [a]
// const flatten =
// concatMap (id)
// mapReduce = (a -> b, (b,a) -> b, (b,a) -> b)
const mapReduce = (m,r) =>
(acc,x) => r (acc, m (x))
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = f => xs =>
xs.reduce (mapReduce (f, concat), [])
// concat :: ([a],[a]) -> [a]
const concat = (xs,ys) =>
xs.concat (ys)
// id :: a -> a
const id = x =>
x
// flatten :: [[a]] -> [a]
const flatten =
concatMap (id)
// deepFlatten :: [[a]] -> [a]
const deepFlatten =
concatMap (x =>
Array.isArray (x) ? deepFlatten (x) : x)
var dataObj = findDataFromLS(urlid)
// var image = id="user-image-cont"
var img = document.createElement("img");
img.src = dataObj.Image;
console.log(img)
var div = document.getElementById("user-image-cont");
console.log(div)
div.appendChild(img);
console.log("We are dealing with ..", dataObj)
document.getElementById("user-name-title").innerHTML = dataObj.FirstName + " " + dataObj.LastName
document.getElementById("nextUrgent").innerHTML = dataObj.nextAction
document.getElementById("nextActionIcon").innerHTML = dataObj.nextAction
document.getElementById("nextActionIcon1").innerHTML = dataObj.nextAction
document.getElementById("next3Urgent").innerHTML = dataObj.next3Action
document.getElementById("next6Urgent").innerHTML = dataObj.next6Action
/* team leader stuff */
if (dataObj.PUUID == null ) { /* this means a team leader */
//console.log("We got a Team Leader Here")
team = findTeamFromLS(dataObj.UUID)
var arrTeamFiles = team.map( member => member.files )
var arrNextAction = team.map( member => member.nextAction )
var arrNext3Action = team.map( member => member.next3Action )
var arrNext6Action = team.map( member => member.next6Action )
var arrNextActionDay = team.map( member => member.nextActionDay )
// nextActionDay
console.log("Got the arrTeamFiles here", arrTeamFiles)
var newArrTeam = flatten( arrTeamFiles )
console.log("Got the FLat arrTeamFiles here", newArrTeam)
console.log("Got the arrNext6Action here", arrNext6Action)
let teamMoments = newArrTeam.map(d => moment(d.ctime, 'MM/DD/YYYY'))
let teamMinDate = moment.min(teamMoments)
//arrNextActionDay = arrNextActionDay.sort((a, b) => a - b)
console.log("smallest num was", arrNextActionDay[0])
// document.getElementById("team-urgent-sum").innerHTML = arrNextAction.reduce(getSum, 0)
//let arrActionDay = arrNextActionDay
// sort action days and get min number
// use min number to make a date in correct format
// display on page in team section
// let maxDate = moment.max(moments)
// let minDate = moment.min(moments)
// // numArray = numArray.sort((a, b) => a - b);
// var sizes = dataFile.map(s => s.size )
// sizes = sizes.sort((a, b) => a - b)
// console.log(sizes)
// if(sizes.length == 0) {
// sizes = [0]
// }
// function getSum(total, num) {
// return total + num;
// }
console.log("we reckon this is an sum of 17 0 40 0 & 3 !! ", arrNextAction.reduce(getSum, 0))
var userTableHeader = `
<div class="row user-block">
<section class="content">
<div class="col-md-12">
<div class="panel panel-default">
<h2>Team Members</h2>
<div class="panel-body">
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-success btn-filter" data-target="items-clear">Clear</button>
<button type="button" class="btn btn-warning btn-filter" data-target="items-pending">3 Month Warning</button>
<button type="button" class="btn btn-danger btn-filter" data-target="items-overdue">Overdue</button>
<button type="button" class="btn btn-default btn-filter" data-target="all">All</button>
</div>
</div>
<div class="table-container">
<table class="table table-filter">
<tbody>
`
var userTable = team.map( user => `
<tr data-status="items-overdue">
<td>
<div class="ckbox">
<input type="checkbox" id="checkbox2">
<label for="checkbox2"></label>
</div>
</td>
<td>
<a href="javascript:;" class="star">
<i class="glyphicon glyphicon-star"></i>
</a>
</td>
<td>
<div class="media">
<a href="detail.html?id=${user.UUID}" class="pull-left">
<img src="${user.Image}" class="media-photo">
</a>
<div class="media-body">
<span class="media-meta pull-right"><i>last login</i>Febrero 13, 2016</span>
<h4 class="title">
<a href="detail.html?id=${user.UUID}">${user.FirstName} ${user.LastName} (${user.UserName})</a>
<span class="pull-right items-overdue">(items-overdue)</span>
</h4>
</br>
<p class="summary">| Total Files: ${user.TotalFiles} | | <span class="red"><b>Next Action URGENT : ${user.nextAction}</b></span> | | <span class="purple">Next Action 3 months : ${user.next3Action}</span> | | <span class="green">Next Action 6 months : ${user.next6Action} |</p>
</div>
</div>
</td>
</tr>
`).join('\n')
var userTableFooter = `<tr data-status="items-clear">
<td>
<div class="ckbox">
<input type="checkbox" id="checkbox1">
<label for="checkbox1"></label>
</div>
</td>
<td>
<a href="javascript:;" class="star">
<i class="glyphicon glyphicon-star"></i>
</a>
</td>
<td>
<div class="media">
<a href="#" class="pull-left">
<img src="https://s3.amazonaws.com/uifaces/faces/twitter/fffabs/128.jpg" class="media-photo">
</a>
<div class="media-body">
<span class="media-meta pull-right">Febrero 13, 2016</span>
<h4 class="title">
Lorem Impsum
<span class="pull-right items-clear">(Review Soon)</span>
</h4>
<p class="summary">Has files that should be reviewed within 3 months.</p>
</div>
</div>
</td>
</tr>
<tr data-status="items-pending">
<td>
<div class="ckbox">
<input type="checkbox" id="checkbox3">
<label for="checkbox3"></label>
</div>
</td>
<td>
<a href="javascript:;" class="star">
<i class="glyphicon glyphicon-star"></i>
</a>
</td>
<td>
<div class="media">
<a href="#" class="pull-left">
<img src="https://s3.amazonaws.com/uifaces/faces/twitter/fffabs/128.jpg" class="media-photo">
</a>
<div class="media-body">
<span class="media-meta pull-right">Febrero 13, 2016</span>
<h4 class="title">
Lorem Impsum
<span class="pull-right items-pending">(items-pending)</span>
</h4>
<p class="summary">Ut enim ad minim veniam, quis nostrud exercitation...</p>
</div>
</div>
</td>
</tr>
<tr data-status="items-overdue">
<td>
<div class="ckbox">
<input type="checkbox" id="checkbox2">
<label for="checkbox2"></label>
</div>
</td>
<td>
<a href="javascript:;" class="star">
<i class="glyphicon glyphicon-star"></i>
</a>
</td>
<td>
<div class="media">
<a href="#" class="pull-left">
<img src="https://s3.amazonaws.com/uifaces/faces/twitter/fffabs/128.jpg" class="media-photo">
</a>
<div class="media-body">
<span class="media-meta pull-right">Febrero 13, 2016</span>
<h4 class="title">
Lorem Impsum
<span class="pull-right items-overdue">(items-overdue)</span>
</h4>
<p class="summary">Ut enim ad minim veniam, quis nostrud exercitation...</p>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
</div>`
//document.getElementById("team-block-list"). innerHTML
var teamTable = userTableHeader + userTable + userTableFooter
let elem = document.getElementById("team-block")
let localTeamFiles = team.map( (src, index) => {
if(src.files == undefined) {
src.files = []
}
let FileArray = src.files.map( file => file.size )
return FileArray
})
console.log("LocalFIles Before Butchers", localTeamFiles)
// concatMap :: (a -> [b]) -> [a] -> [b]
// const concatMap = f => xs =>
// xs.reduce (mapReduce (f, concat), [])
// mapReduce = (a -> b, (b,a) -> b, (b,a) -> b)
// const mapReduce = (m,r) =>
// (acc,x) => r (acc, m (x))
// // concat :: ([a],[a]) -> [a]
// const concat = (xs,ys) =>
// xs.concat (ys)
// deepFlatten :: [[a]] -> [a]
const deepFlatten =
concatMap (x =>
Array.isArray (x) ? deepFlatten (x) : x)
//console.log (deepFlatten (localTeamFiles))
var newArr = deepFlatten (localTeamFiles)
console.log("localTeamFiles", localTeamFiles)
newArr = newArr.sort((a, b) => a - b)
console.log("newArr", newArr)
// const teamFileTotal = localTeam.files.map( (src, index) => {
// //console.log(src.files.length)
// })
let teamNextAction = arrNextAction.reduce(getSum, 0)
let teamNext3Action = arrNext3Action.reduce(getSum, 0)
let teamNext6Action = arrNext6Action.reduce(getSum, 0)
console.log("TNA", teamNextAction)
elem.innerHTML = `
<div class="row team-div-main tile_count team_tile_count">
<h3>Team Members (${(team.length) ? (team.length) : 0})</h3>
${(team.length) ? '<div class="container"> \
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo">Toggle Team Details</button> \
<div id="demo" class="collapse"> \
<div id="team-block-list" class="container">' + teamTable + ' \
</div> \
</div> \
</div>': 0}
<div class="col-md-2 col-sm-6 col-xs-12 tile_stats_count">
<span class="count_top"><i class="fa fa-file"></i><b>Team </b> Total Files</span>
<div id="team-total-files" class="count">${newArr.length}</div>
<!-- <span class="count_bottom"><i class="green">4% </i> From last Week</span> -->
</div>
<div class="col-md-2 col-sm-6 col-xs-12 tile_stats_count">
<span class="count_top"><i class="fa fa-clock-o"></i><b>Team </b> Oldest File</span>
<div id="team-oldest-file" class="count">25 Mar 99</div>
<span id="team-human-oldest" class="count_bottom red">......</span>
</div>
<div class="col-md-2 col-sm-6 col-xs-12 tile_stats_count">
<span class="count_top"><i class="fa fa-file"></i><b>Team </b> Largest File</span>
<div id="team-largest-file" class="count green">${ humanFileSize(newArr[newArr.length - 1], true) } </div>
<!-- <span class="count_bottom"><i class="green"><i class="fa fa-sort-asc"></i>34% </i> From last Week</span> -->
</div>
<div class="col-md-2 col-sm-6 col-xs-12 tile_stats_count">
<span class="count_top"><i class="fa fa-file"></i><b>Team </b> Total Usage</span>
<div id="team-total-usage" class="count">${ humanFileSize(newArr.reduce(getSum, 0), true) }</div>
<!-- <span class="count_bottom"><i class="red"><i class="fa fa-sort-desc"></i>12% </i> From last Week</span> -->
</div>
<div class="col-md-2 col-sm-6 col-xs-12 tile_stats_count">
<span class="count_top"><i class="fa fa-clock-o"></i> Next Action</span>
<div id="team-total-next-action" class="count">......</div>
<!-- <span class="count_bottom"><i class="green"><i class="fa fa-sort-asc"></i>34% </i> From last Week</span> -->
</div>
<div class="col-md-2 col-sm-6 col-xs-12 tile_stats_count">
<span class="count_top"><i class="fa fa-clock-o"></i><b>Team </b> Next Action</span></br>
<span style="color:coral" class="count_top"><i class="fa fa-calendar"></i> ${teamNextAction} Actions Urgent </span></br>
<span class="purple"><i class=" fa fa-calendar"></i> ${teamNext3Action} Action in next 3 months </span></br>
<span class="green"><i class=" fa fa-calendar"></i> ${teamNext6Action} action in next 6 months </span></br>
<span class="green"></span>
</div>
</div>
`
//console.log(team)
if ( arrNextActionDay[0] >= 7 ) {
document.getElementById("team-total-next-action").classList.add("green")
document.getElementById("team-total-next-action").innerHTML = moment().add( arrNextActionDay[0], 'days' ).format("DD MMM YY")
// document.getElementById("oldest-file").innerHTML = minDate.format("DD MMM YY")
// document.getElementById("human-oldest").innerHTML = minDate.fromNow()
// console.log("Max Date", maxDate.format('DD-MM-YYYY'))
// console.log("Min Date", minDate)
// document.getElementById("next-footer-date").innerHTML = moment().add( dataObj.nextActionDay, 'days' ).fromNow('days') + " from Now" // moment( dataObj.nextActionDay ).fromNow()
// document.getElementById("nextActionDay").innerHTML = dataObj.nextActionDay + " days time"
} else {
document.getElementById("team-total-next-action").classList.add("red")
document.getElementById("team-total-next-action").innerHTML = moment().add( arrNextActionDay[0], 'days' ).format("DD MMM YY") // format("DD MMM YY")moment( dataObj.nextActionDay ).fromNow()
// document.getElementById("next-footer-date").innerHTML = "<span class='red'><i class='red fa fa-ban'></i>" + moment().add( dataObj.nextActionDay, 'days' ).fromNow('days') + " overdue </span>"
// document.getElementById("nextActionDay").innerHTML = dataObj.nextActionDay + " days overdue"
}
document.getElementById("team-oldest-file").innerHTML = teamMinDate.format("DD MMM YY")
document.getElementById("team-human-oldest").innerHTML = teamMinDate.fromNow()
}
if ( dataObj.nextActionDay >= 7 ) {
document.getElementById("total-file-date").classList.add("green")
document.getElementById("total-file-date").innerHTML = moment().add( dataObj.nextActionDay, 'days' ).format("DD MMM YY") // moment( dataObj.nextActionDay ).fromNow()
// next-footer-date
// document.getElementById("oldest-file").innerHTML = minDate.format("DD MMM YY")
// document.getElementById("human-oldest").innerHTML = minDate.fromNow()
// console.log("Max Date", maxDate.format('DD-MM-YYYY'))
// console.log("Min Date", minDate)
document.getElementById("next-footer-date").innerHTML = moment().add( dataObj.nextActionDay, 'days' ).fromNow('days') + " from Now" // moment( dataObj.nextActionDay ).fromNow()
document.getElementById("nextActionDay").innerHTML = dataObj.nextActionDay + " days time"
} else {
document.getElementById("total-file-date").classList.add("red")
document.getElementById("total-file-date").innerHTML = moment().add( dataObj.nextActionDay, 'days' ).format("DD MMM YY") // format("DD MMM YY")moment( dataObj.nextActionDay ).fromNow()
document.getElementById("next-footer-date").innerHTML = "<span class='red'><i class='red fa fa-ban'></i>" + moment().add( dataObj.nextActionDay, 'days' ).fromNow('days') + " overdue </span>"
document.getElementById("nextActionDay").innerHTML = dataObj.nextActionDay + " days overdue"
}
if(dataObj.files == undefined) {
dataObj.files = []
}
var dataFile = dataObj.files
var top20 = dataFile.slice(0, 15)
var remain = dataFile.slice(15, dataFile.length)
console.log("DataFiles Array length ", dataFile.length)
document.getElementById("total-files").innerHTML = dataFile.length
//
document.getElementById("btn-open-more").innerHTML = remain.length
console.log("Actual File Info", dataFile)
console.log("top20", top20)
console.log("remain", remain)
/*
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
*/
var fileListHtml = top20.map((src, index) => `
<tr id="row-${src.uuid}" class="${ (index%2) ? "odd" : "even" } pointer">
<td class="a-center ">
<select id="${src.uuid}" onchange="changedSelect(this)" class="form-control">
<option value="#f9f9f9" style="background-color: #f9f9f9;"><i class="fa fa-file"></i>please select</option>
<option value="lightgreen" style="background-color: lightgreen"><i class="fa fa-file"></i>No Action</option>
<option value="lightblue" style="background-color: lightblue"><i class="fa fa-file"></i>Moved</option>
<option value="yellow" style="background-color: yellow"><i class="fa fa-file"></i>Archived</option>
<option value="lightpink" style="background-color: lightpink"><i class="fa fa-file"></i>Lost/unknown</option>
</select>
<!-- <div class="icheckbox_flat-green" style="position: relative;"><input type="checkbox" class="flat" name="table_records" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div>
-->
</td>
<td class=" ">
${src.atime}
</td>
<td title="${src.fullpath}" class=" ">
${src.fullpath.substring(0,20)}...
</td>
<td class=" ">${humanFileSize(src.size, true)}</td>
<td class=" " title="${src.uuid}">${src.uuid.substring(0, 8)}...</td>
<td class=" ">${src.extension}</td>
<td class="a-right a-right ">${src.mimetype}</td>
<td class=" last"><a href="#">${src.filename}</a>
</td>
</tr>
`).join('\n')
function changedSelect(e) {
console.log("selected", e.value)
console.log("this select", e.id)
var random = Math.random()
console.log(random*1000 + 1000)
setTimeout(function(){ document.getElementById("row-" + e.id).setAttribute('style', `background-color:${e.value}`); }, 1500);
//document.getElementById("row-" + e.id).setAttribute('style', `background-color:${e.value}`); // += e.value
}
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
var fileListHtmlex = remain.map((src, index) => `
<tr id="row-${src.uuid}" class="${ (index % 2) ? "odd" : "even" } pointer">
<td class="a-center ">
<select id="${src.uuid}" onchange="changedSelect(this)" class="form-control">
<option value="#f9f9f9" style="background-color: #f9f9f9;"><i class="fa fa-file"></i>please select</option>
<option value="lightgreen" style="background-color: lightgreen"><i class="fa fa-file"></i>No Action</option>
<option value="lightblue" style="background-color: lightblue"><i class="fa fa-file"></i>Moved</option>
<option value="yellow" style="background-color: yellow"><i class="fa fa-file"></i>Archived</option>
<option value="lightpink" style="background-color: lightpink"><i class="fa fa-file"></i>Lost/unknown</option>
</select>
<!-- <div class="icheckbox_flat-green" style="position: relative;"><input type="checkbox" class="flat" name="table_records" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div>
-->
</td>
<td class=" ">
${src.atime}
</td>
<td title="${src.fullpath}" class=" ">
${src.fullpath.substring(0,20)}...
</td>
<td class=" ">${humanFileSize(src.size, true)}</td>
<td class=" " title="${src.uuid}">${src.uuid.substring(0, 8)}...</td>
<td class=" ">${src.extension}</td>
<td class="a-right a-right ">${src.mimetype}</td>
<td class=" last"><a href="#">${src.filename}</a>
</td>
</tr>
`).join('\n')
var theader = `<table class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings$">
<th class="column-title" style="display: table-cell;">Action Type</th>
<th class="column-title" style="display: table-cell;">Acessed Date</th>
<th class="column-title" style="display: table-cell;">Full Path</th>
<th class="column-title" style="display: table-cell;">Size (bytes)</th>
<th class="column-title" style="display: table-cell;">MD5 Hash </th>
<th class="column-title" style="display: table-cell;">Extension </th>
<th class="column-title" style="display: table-cell;">Extension Desc </th>
<th class="column-title no-link last" style="display: table-cell;"><span class="nobr">File Name</span>
</th>
<th class="bulk-actions" colspan="7" style="display: none;">
<a class="antoo" style="color:#fff; font-weight:500;">Bulk Actions ( <span class="action-cnt">1 Records Selected</span> ) <i class="fa fa-chevron-down"></i></a>
</th>
</tr>
</thead>
<tbody>`;
// <tr class="odd pointer">
// <td class="a-center ">
// <div class="icheckbox_flat-green" style="position: relative;"><input type="checkbox" class="flat" name="table_records" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div>
// </td>
// <td class=" ">121000039</td>
// <td class=" ">May 28, 2014 11:30:12 PM</td>
// <td class=" ">121000208</td>
// <td class=" ">John Blank L</td>
// <td class=" ">Paid</td>
// <td class="a-right a-right ">$741.20</td>
// <td class=" last"><a href="#">View</a>
// </td>
// </tr>
var tableFooter = `</tbody>
</table>`
var fullTable = theader + fileListHtml + tableFooter
var extraTable = theader + fileListHtmlex + tableFooter
console.log("The FileList ", fileListHtml)
document.getElementById("table-block").innerHTML = fullTable
document.getElementById("table-block-ex").innerHTML = extraTable
let moments = dataFile.map(d => moment(d.ctime, 'MM/DD/YYYY'))
let maxDate = moment.max(moments)
let minDate = moment.min(moments)
// numArray = numArray.sort((a, b) => a - b);
var sizes = dataFile.map(s => s.size )
sizes = sizes.sort((a, b) => a - b)
console.log(sizes)
if(sizes.length == 0) {
sizes = [0]
}
function getSum(total, num) {
return total + num;
}
document.getElementById("total-usage").innerHTML = humanFileSize(sizes.reduce(getSum, 0), true)
console.log("sizes", sizes[sizes.length - 1])
document.getElementById("largest-file").innerHTML = humanFileSize(sizes[sizes.length - 1], true)
document.getElementById("oldest-file").innerHTML = minDate.format("DD MMM YY")
document.getElementById("human-oldest").innerHTML = minDate.fromNow()
console.log("Max Date", maxDate.format('DD-MM-YYYY'))
console.log("Min Date", minDate)
// Graph stuff start paste
let myChart = document.getElementById("myChart").getContext("2d");
// Global Options
// Chart.defaults.global.defaultFontFamily = "Lato";
// Chart.defaults.global.defaultFontSize = 18;
// Chart.defaults.global.defaultFontColor = "#777";
function genRandom() {
return Math.floor((Math.random() * 10) + 4);
}
let massPopChart = new Chart(myChart, {
type: "line", // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data: {
labels: [
"type1",
"type2",
"type3",
"type4"
],
datasets: [
{
// label: "Population",
data: [ genRandom(), genRandom(), genRandom(), genRandom() ],
//backgroundColor:'green',
backgroundColor: [
"rgba(255, 99, 132, 0.6)",
"rgba(54, 162, 235, 0.6)",
"rgba(255, 206, 86, 0.6)",
"rgba(75, 192, 192, 0.6)",
"rgba(153, 102, 255, 0.6)",
"rgba(255, 159, 64, 0.6)",
"rgba(255, 99, 132, 0.6)"
],
borderWidth: 1,
borderColor: "#777",
hoverBorderWidth: 3,
hoverBorderColor: "#000"
}
]
},
options: {
title: {
display: true,
text: "Absolute classification",
fontSize: 12
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#000"
}
},
layout: {
padding: {
left: 0,
right: 0,
bottom: 0,
top: 0
}
},
tooltips: {
enabled: true
}
}
});
// Graph stuff end paste
/*
<tr class="even pointer">
<td class="a-center ">
<div class="icheckbox_flat-green" style="position: relative;"><input type="checkbox" class="flat" name="table_records" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div>
</td>
<td class=" ">121000040</td>
<td class=" ">May 23, 2014 11:47:56 PM </td>
<td class=" ">121000210 <i class="success fa fa-long-arrow-up"></i></td>
<td class=" ">John Blank L</td>
<td class=" ">Paid</td>
<td class="a-right a-right ">$7.45</td>
<td class=" last"><a href="#">View</a>
</td>
</tr>
<tr class="odd pointer">
<td class="a-center ">
<div class="icheckbox_flat-green" style="position: relative;"><input type="checkbox" class="flat" name="table_records" style="position: absolute; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div>
</td>
<td class=" ">121000039</td>
<td class=" ">May 23, 2014 11:30:12 PM</td>
<td class=" ">121000208 <i class="success fa fa-long-arrow-up"></i>
</td>
<td class=" ">John Blank L</td>
<td class=" ">Paid</td>
<td class="a-right a-right ">$741.20</td>
<td class=" last"><a href="#">View</a>
</td>
</tr>
*/
// // Chart options
// const options = {
// chart: {
// height: 350,
// width: "35%",
// type: "bar",
// background: "#f4f4f4",
// foreColor: "#333"
// },
// plotOptions: {
// bar: {
// horizontal: false
// }
// },
// series: [
// {
// name: "Population",
// data: [
// 8550405,
// 3971883,
// 2720546,
// 2296224,
// 1567442,
// 1563025,
// 1469845,
// 1394928,
// 1300092,
// 1026908
// ]
// }
// ],
// xaxis: {
// categories: [
// "New York",
// "Los Angeles",
// "Chicago",
// "Houston",
// "Philadelphia",
// "Phoenix",
// "San Antonio",
// "San Diego",
// "Dallas",
// "San Jose"
// ]
// },
// fill: {
// colors: ["#00ff00", "#ffff00", "#00ffff", "#0000ff", "#ff00ff", "#00ff00", "#ffff00", "#00ffff", "#0000ff", "#ff00ff" ]
// },
// dataLabels: {
// enabled: false
// },
// title: {
// text: "Absolute classification",
// align: "center",
// margin: 20,
// offsetY: 20,
// style: {
// fontSize: "25px"
// }
// }
// };
// // Init chart
// const chart = new ApexCharts(document.querySelector("#chart"), options);
// // Render chart
// chart.render();
// // Event example
// document.querySelector("#change").addEventListener("click", () =>
// chart.updateOptions({
// plotOptions: {
// bar: {
// horizontal: true
// }
// }
// })
// );
// document.querySelector("#change2").addEventListener("click", () =>
// chart.updateOptions({
// plotOptions: {
// bar: {
// horizontal: false
// }
// }
// })
// );
var optionsGauge1 = {
chart: {
type: 'radialBar',
height: 316
},
plotOptions: {
radialBar: {
startAngle: -90,
endAngle: 90,
track: {
background: "#e7e7e7",
strokeWidth: '97%',
margin: 5, // margin is in pixels
shadow: {
enabled: true,
top: 2,
left: 0,
color: '#999',
opacity: 1,
blur: 2
}
},
dataLabels: {
name: {
show: false
},
value: {
offsetY: 15,
fontSize: '22px'
}
}
}
},
fill: {
gradient: {
enabled: true,
shade: 'light',
shadeIntensity: 0.4,
inverseColors: false,
opacityFrom: 1,
opacityTo: 1,
stops: [0, 50, 53, 91]
},
},
series: [ genRandom() ],
labels: ['Average Results'],
height: '100px'
}
var optionsGauge2 = {
chart: {
type: 'radialBar',
height: 316
},
plotOptions: {
radialBar: {
startAngle: -90,
endAngle: 90,
track: {
background: "#e7e7e7",
strokeWidth: '97%',
margin: 5, // margin is in pixels
shadow: {
enabled: true,
top: 2,
left: 0,
color: '#999',
opacity: 1,
blur: 2
}
},
dataLabels: {
name: {
show: false
},
value: {
offsetY: 15,
fontSize: '22px'
}
}
}
},
fill: {
gradient: {
enabled: true,
shade: 'light',
shadeIntensity: 0.4,
inverseColors: false,
opacityFrom: 1,
opacityTo: 1,
stops: [0, 50, 53, 91]
},
},
series: [ genRandom() ],
labels: ['Average Results'],
height: '100px'
}
var optionsGauge3 = {
chart: {
type: 'radialBar',
height: 316
},
plotOptions: {
radialBar: {
startAngle: -90,
endAngle: 90,
track: {
background: "#e7e7e7",
strokeWidth: '97%',
margin: 5, // margin is in pixels
shadow: {
enabled: true,
top: 2,
left: 0,
color: '#999',
opacity: 1,
blur: 2
}
},
dataLabels: {
name: {
show: false
},
value: {
offsetY: 15,
fontSize: '22px'
}
}
}
},
fill: {
gradient: {
enabled: true,
shade: 'light',
shadeIntensity: 0.4,
inverseColors: false,
opacityFrom: 1,
opacityTo: 1,
stops: [0, 50, 53, 91]
},
},
series: [ genRandom() ],
labels: ['Average Results'],
height: '100px'
}
// var optionsGauge4 = {
// chart: {
// type: 'radialBar',
// height: 316
// },
// plotOptions: {
// radialBar: {
// startAngle: -90,
// endAngle: 90,
// track: {
// background: "#e7e7e7",
// strokeWidth: '97%',
// margin: 5, // margin is in pixels
// shadow: {
// enabled: true,
// top: 2,
// left: 0,
// color: '#999',
// opacity: 1,
// blur: 2
// }
// },
// dataLabels: {
// name: {
// show: false
// },
// value: {
// offsetY: 15,
// fontSize: '22px'
// }
// }
// }
// },
// fill: {
// gradient: {
// enabled: true,
// shade: 'light',
// shadeIntensity: 0.4,
// inverseColors: false,
// opacityFrom: 1,
// opacityTo: 1,
// stops: [0, 50, 53, 91]
// },
// },
// series: [ genRandom() ],
// labels: ['Average Results'],
// height: '100px'
// }
var chartGauge1 = new ApexCharts(
document.querySelector("#chartGuage1"),
optionsGauge1
);
var chartGauge2 = new ApexCharts(
document.querySelector("#chartGuage2"),
optionsGauge2
);
var chartGauge3 = new ApexCharts(
document.querySelector("#chartGuage3"),
optionsGauge3
);
// var chartGauge4 = new ApexCharts(
// document.querySelector("#chartGuage4"),
// optionsGauge4
// );
chartGauge1.render();
chartGauge2.render();
chartGauge3.render();
//chartGauge4.render();
function humanFileSize(bytes, si) {
var thresh = si ? 1000 : 1024;
if(Math.abs(bytes) < thresh) {
return bytes + ' B';
}
var units = si
? ['kB','MB','GB','TB','PB','EB','ZB','YB']
: ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];
var u = -1;
do {
bytes /= thresh;
++u;
} while(Math.abs(bytes) >= thresh && u < units.length - 1);
return bytes.toFixed(1)+' '+units[u];
}
var optionsarea2 = {
chart: {
id: 'chartyear',
type: 'area',
height: 320,
background: '#F6F8FA',
toolbar: {
show: false,
autoSelected: 'pan'
},
events: {
mounted: function (chart) {
var commitsEl = document.querySelector('div span.commits');
var commits = chart.getSeriesTotalXRange(chart.w.globals.minX, chart.w.globals.maxX)
commitsEl.innerHTML = commits
},
updated: function (chart) {
var commitsEl = document.querySelector('.cmeta span.commits');
var commits = chart.getSeriesTotalXRange(chart.w.globals.minX, chart.w.globals.maxX)
commitsEl.innerHTML = commits
}
}
},
colors: ['#FF7F00'],
stroke: {
width: 0,
curve: 'smooth'
},
dataLabels: {
enabled: false
},
fill: {
opacity: 1,
type: 'solid'
},
series: [{
name: 'files',
data: githubdata.series
}],
yaxis: {
tickAmount: 3,
labels: {
show: false
}
},
xaxis: {
type: 'datetime',
}
}
var chartarea2 = new ApexCharts(
document.querySelector("#chart-area2"),
optionsarea2
);
chartarea2.render();
var optionsArea = {
chart: {
height: 360,
type: 'area',
background: '#F6F8FA',
toolbar: {
autoSelected: 'selection',
},
brush: {
enabled: true,
target: 'chartyear'
},
selection: {
enabled: true,
xaxis: {
min: new Date('05 Jan 2014').getTime(),
max: new Date('04 Jan 2015').getTime()
}
},
},
colors: ['#7BD39A'],
dataLabels: {
enabled: false
},
stroke: {
width: 0,
curve: 'smooth'
},
series: [{
name: 'files',
data: githubdata.series
}],
fill: {
opacity: 1,
type: 'solid'
},
legend: {
position: 'top',
horizontalAlign: 'left'
},
xaxis: {
type: 'datetime'
},
}
var chartArea = new ApexCharts(
document.querySelector("#chart-area"),
optionsArea
);
chartArea.render();
var products = [
{
"name": "Burnify 1",
"points": 120,
"lastSprint": 13,
"mvpSprint": 10,
"sprints": [
{
"planned": 10,
"done": 10
}, {
"planned": 12,
"done": 10
}, {
"planned": 10,
"done": 10
}, {
"planned": 10,
"done": 6,
"added": 52
}, {
"planned": 14,
"done": 8,
"added": 12
}, {
"planned": 14,
"done": 8,
"added": 2,
"removed": 20
}, {
"planned": 12,
"done": 4
}, {
"planned": 10,
"done": 6,
"added": 2
}
]
}, {
"name": "Burnify 2",
"points": 220,
"lastSprint": 10,
"mvpSprint": 8,
"sprints": [{
"done": 18
}, {
"done": 24
}, {
"done": 16
}, {
"done": 22
}, {
"done": 8,
"added": 32
}, {
"done": 20,
"removed": 20
}, {
"done": 30,
"added": 2
}
]
}, {
"name": "Burnify 3",
"points": 120,
"lastSprint": 10,
"mvpSprint": 10,
"sprints": [{
"done": 10
}, {
"done": 10
}, {
"done": 10
}
]
}, {
"name": "Burnify 4",
"points": 200,
"lastSprint": 10,
"mvpSprint": 8,
"sprints": [{
"done": 20
}, {
"done": 20
}, {
"done": 20
}
]
}
];
// b1 = new Burnify("#product1", products[0], 800, 550);
b1 = new Burnify("#product1", products[0], 400, 250);
b1.onSprintBarClick = function(sprintNumber, sprint) { alert('Sprint ' + sprintNumber + ' (done: '+ sprint.done + ')'); };
b1.onFullScopeAreaClick = function(p) { alert('Project ' + p.name + ' full scope area!'); };
b1.onDoneScopeAreaClick = function(p) { alert('Project ' + p.name + ' done scope area!'); };
b1.onOutScopeAreaClick = function(p) { alert('Project ' + p.name + ' out scope area!'); };
b1.draw();
new Burnify("#product2", products[1], 400, 250).draw();
new Burnify("#product3", products[2], 400, 250).draw();
new Burnify("#product4", products[3], 400, 250).draw();
function generateData(count, yrange) {
var i = 0;
var series = [];
while (i < count) {
var x = 'w' + (i + 1).toString();
var y = Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min;
series.push({
x: x,
y: y
});
i++;
}
return series;
}
var optionsHeat = {
chart: {
height: 350,
type: 'heatmap',
},
dataLabels: {
enabled: false
},
colors: ["#008FFB"],
series: [{
name: 'Old Files',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'Secure Files',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'Large Files',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'System Files',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'config Files',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'Doc Files',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'Files',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'Directories',
data: generateData(12, {
min: 0,
max: 90
})
},
{
name: 'Archives',
data: generateData(12, {
min: 0,
max: 90
})
}
],
title: {
text: ''
},
}
var chartHeat = new ApexCharts(
document.querySelector("#chartHeat"),
optionsHeat
);
chartHeat.render();
window.Apex = {
stroke: {
width: 3
},
markers: {
size: 0
},
tooltip: {
fixed: {
enabled: true,
}
}
};
var randomizeArray = function (arg) {
var array = arg.slice();
var currentIndex = array.length,
temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// // data for the sparklines that appear below header area
// var sparklineData = [47, 45, 54, 38, 56, 24, 65, 31, 37, 39, 62, 51, 35, 41, 35, 27, 93, 53, 61, 27, 54, 43, 19, 46];
// var spark1 = {
// chart: {
// type: 'area',
// height: 160,
// sparkline: {
// enabled: true
// },
// },
// stroke: {
// curve: 'straight'
// },
// fill: {
// opacity: 0.3,
// gradient: {
// enabled: false
// }
// },
// series: [{
// data: randomizeArray(sparklineData)
// }],
// yaxis: {
// min: 0
// },
// colors: ['#DCE6EC'],
// title: {
// text: '$424,652',
// offsetX: 0,
// style: {
// fontSize: '24px',
// cssClass: 'apexcharts-yaxis-title'
// }
// },
// subtitle: {
// text: 'Sales',
// offsetX: 0,
// style: {
// fontSize: '14px',
// cssClass: 'apexcharts-yaxis-title'
// }
// }
// }
// var spark2 = {
// chart: {
// type: 'area',
// height: 160,
// sparkline: {
// enabled: true
// },
// },
// stroke: {
// curve: 'straight'
// },
// fill: {
// opacity: 0.3,
// gradient: {
// enabled: false
// }
// },
// series: [{
// data: randomizeArray(sparklineData)
// }],
// yaxis: {
// min: 0
// },
// colors: ['#DCE6EC'],
// title: {
// text: '$235,312',
// offsetX: 0,
// style: {
// fontSize: '24px',
// cssClass: 'apexcharts-yaxis-title'
// }
// },
// subtitle: {
// text: 'Expenses',
// offsetX: 0,
// style: {
// fontSize: '14px',
// cssClass: 'apexcharts-yaxis-title'
// }
// }
// }
// var spark3 = {
// chart: {
// type: 'area',
// height: 160,
// sparkline: {
// enabled: true
// },
// },
// stroke: {
// curve: 'straight'
// },
// fill: {
// opacity: 0.3,
// gradient: {
// enabled: false
// }
// },
// series: [{
// data: randomizeArray(sparklineData)
// }],
// xaxis: {
// crosshairs: {
// width: 1
// },
// },
// yaxis: {
// min: 0
// },
// title: {
// text: '$135,965',
// offsetX: 0,
// style: {
// fontSize: '24px',
// cssClass: 'apexcharts-yaxis-title'
// }
// },
// subtitle: {
// text: 'Profits',
// offsetX: 0,
// style: {
// fontSize: '14px',
// cssClass: 'apexcharts-yaxis-title'
// }
// }
// }
// var spark1 = new ApexCharts(document.querySelector("#spark1"), spark1);
// spark1.render();
// var spark2 = new ApexCharts(document.querySelector("#spark2"), spark2);
// spark2.render();
// var spark3 = new ApexCharts(document.querySelector("#spark3"), spark3);
// spark3.render();
// var options1 = {
// chart: {
// type: 'line',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// series: [{
// data: [25, 66, 41, 89, 63, 25, 44, 12, 36, 9, 54]
// }],
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// var options2 = {
// chart: {
// type: 'line',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// series: [{
// data: [12, 14, 2, 47, 42, 15, 47, 75, 65, 19, 14]
// }],
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// var options3 = {
// chart: {
// type: 'line',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// series: [{
// data: [47, 45, 74, 14, 56, 74, 14, 11, 7, 39, 82]
// }],
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// var options4 = {
// chart: {
// type: 'line',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// series: [{
// data: [15, 75, 47, 65, 14, 2, 41, 54, 4, 27, 15]
// }],
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// var options5 = {
// chart: {
// type: 'bar',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// plotOptions: {
// bar: {
// columnWidth: '80%'
// }
// },
// series: [{
// data: [25, 66, 41, 89, 63, 25, 44, 12, 36, 9, 54]
// }],
// labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
// xaxis: {
// crosshairs: {
// width: 1
// },
// },
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// var options6 = {
// chart: {
// type: 'bar',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// plotOptions: {
// bar: {
// columnWidth: '80%'
// }
// },
// series: [{
// data: [12, 14, 2, 47, 42, 15, 47, 75, 65, 19, 14]
// }],
// labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
// xaxis: {
// crosshairs: {
// width: 1
// },
// },
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// var options7 = {
// chart: {
// type: 'bar',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// plotOptions: {
// bar: {
// columnWidth: '80%'
// }
// },
// series: [{
// data: [47, 45, 74, 14, 56, 74, 14, 11, 7, 39, 82]
// }],
// labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
// xaxis: {
// crosshairs: {
// width: 1
// },
// },
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// var options8 = {
// chart: {
// type: 'bar',
// width: 100,
// height: 35,
// sparkline: {
// enabled: true
// }
// },
// plotOptions: {
// bar: {
// columnWidth: '80%'
// }
// },
// series: [{
// data: [25, 66, 41, 89, 63, 25, 44, 12, 36, 9, 54]
// }],
// labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
// xaxis: {
// crosshairs: {
// width: 1
// },
// },
// tooltip: {
// fixed: {
// enabled: false
// },
// x: {
// show: false
// },
// y: {
// title: {
// formatter: function (seriesName) {
// return ''
// }
// }
// },
// marker: {
// show: false
// }
// }
// }
// new ApexCharts(document.querySelector("#schart1"), options1).render();
// new ApexCharts(document.querySelector("#schart2"), options2).render();
// new ApexCharts(document.querySelector("#schart3"), options3).render();
// new ApexCharts(document.querySelector("#schart4"), options4).render();
// new ApexCharts(document.querySelector("#schart5"), options5).render();
// new ApexCharts(document.querySelector("#schart6"), options6).render();
// new ApexCharts(document.querySelector("#schart7"), options7).render();
// new ApexCharts(document.querySelector("#schart8"), options8).render();
var optionsRadialBar = {
chart: {
height: 350,
type: 'radialBar',
},
plotOptions: {
radialBar: {
dataLabels: {
name: {
fontSize: '22px',
},
value: {
fontSize: '16px',
},
total: {
show: true,
label: 'Total',
formatter: function (w) {
// By default this function returns the average of all series. The below is just an example to show the use of custom formatter function
return 249
}
}
}
}
},
series: [44, 55, 67, 83],
labels: ['Apples', 'Oranges', 'Bananas', 'Berries'],
}
var chartRadialBar = new ApexCharts(
document.querySelector("#chartRadialBar"),
optionsRadialBar
);
chartRadialBar.render();
$( "#btn-toggle-table" ).click(function() {
$( "#table-block-ex" ).toggle();
});
$("#table-block-ex").css("display", "none");
var radarOptions = {
chart: {
height: 350,
type: 'radar',
dropShadow: {
enabled: true,
blur: 1,
left: 1,
top: 1
}
},
series: [{
name: 'Series 1',
data: [80, 50, 30, 40, 100, 20],
}, {
name: 'Series 2',
data: [20, 30, 40, 80, 20, 80],
}, {
name: 'Series 3',
data: [44, 76, 78, 13, 43, 10],
}],
title: {
text: 'Radar Chart - Multi Series'
},
stroke: {
width: 0
},
fill: {
opacity: 0.4
},
markers: {
size: 0
},
labels: ['2011', '2012', '2013', '2014', '2015', '2016']
}
var radarChart = new ApexCharts(
document.querySelector("#radarChart"),
radarOptions
);
radarChart.render();
function update() {
function randomSeries() {
var arr = []
for(var i = 0; i < 6; i++) {
arr.push(Math.floor(Math.random() * 100))
}
return arr
}
radarChart.updateSeries([{
name: 'Series 1',
data: randomSeries(),
}, {
name: 'Series 2',
data: randomSeries(),
}, {
name: 'Series 3',
data: randomSeries(),
}])
} |
/*jshint esversion: 6 */
var should = require('should');
var bubbleSort = require('./bubbleSort.js');
var sinon = require('sinon');
describe('bubbleSort', function() {
it('should exist', function() {
should.exist(bubbleSort);
});
it('should be a function', function() {
bubbleSort.should.be.a.Function();
});
// Note: Any comparison here needs to use eql. Otherwise Mocha will test for
// exact equality (identity)
it('should sort an array numerically', function() {
var input = [1, 2, 43, 100, 100, 21, 21];
var expected = [1, 2, 21, 21, 43, 100, 100];
bubbleSort(input).should.eql(expected);
});
it('should sort arrays with decimal numbers', function() {
var input = [24.7, 24.3, 23, 9, 3, 3, 100, 25, 100];
var expected = [3, 3, 9, 23, 24.3, 24.7, 25, 100, 100];
bubbleSort(input).should.eql(expected);
});
it('should sort reverse sorted arrays', function() {
bubbleSort([5, 4, 3, 2, 1]).should.eql([1, 2, 3, 4, 5]);
});
it('should handle presorted arrays', function() {
bubbleSort([1, 2, 3, 4, 5]).should.eql([1, 2, 3, 4, 5]);
});
it('should sort arrays with negative numbers', function() {
var input = [20, -10, -10.1, 2, 4, 299];
var expected = [-10.1, -10, 2, 4, 20, 299];
bubbleSort(input).should.eql(expected);
});
});
|
'use strict';
import angular from 'angular';
import FooterModule from './footer/footer.module';
import NavbarModule from './navbar/navbar.module';
/**
* @const {String} CommonModule
*/
const CommonModule = angular
.module('app.common', [
NavbarModule,
FooterModule
])
.name;
export default CommonModule;
|
/*EXPECTED
0
1
2
*/
class _Main {
static function main (args : string[]) : void {
// Instead of `Generator.<void,int>`, just writing `int` at the place of return type.
function * foo () : int {
var c = 0;
while (true)
yield c++;
}
var gen : Generator.<void,int> = foo();
log gen.next().value;
log gen.next().value;
log gen.next().value;
}
}
|
import web3 from 'Services/Web3'
import log from 'Utilities/log'
import { toChecksumAddress, toBigNumber } from 'Utilities/convert'
import { web3SendTx } from './util'
import EthereumWallet from './EthereumWallet'
const checkAccountAvailable = (address) => Promise.resolve(address)
.then((resolvedAddress) => web3.eth.getAccounts()
.then((accounts) => accounts
.map((account) => account.toLowerCase())
.includes(resolvedAddress.toLowerCase()))
.then((isAvailable) => {
if (!isAvailable) {
throw new Error(`Could not find web3 Ethereum account ${resolvedAddress}`)
}
}))
export default class EthereumWalletWeb3 extends EthereumWallet {
static type = 'EthereumWalletWeb3';
constructor(address, providerName) {
super()
if (!address) {
throw new Error('Wallet address must be provided')
}
this.address = address
this.providerName = providerName || web3.providerName
}
getType() { return EthereumWalletWeb3.type }
getTypeLabel() { return this.providerName === 'faast' ? 'Web3 Wallet' : this.providerName }
getAddress() { return this.address }
isSignTransactionSupported() { return web3.providerName !== 'MetaMask' }
_checkAvailable() { return checkAccountAvailable(this.address) }
_signAndSendTx(tx, options) {
return web3SendTx(tx.txData, false, options)
.then((txId) => ({ id: txId }));
}
_signTx(tx) {
const { txData } = tx
const { value, gasLimit, gasPrice, nonce } = txData
return web3.eth.signTransaction({
...txData,
value: toBigNumber(value),
gas: toBigNumber(gasLimit).toNumber(),
gasPrice: toBigNumber(gasPrice),
nonce: toBigNumber(nonce).toNumber()
})
}
static fromDefaultAccount() {
const { defaultAccount, getAccounts } = web3.eth
let addressPromise
if (defaultAccount) {
addressPromise = Promise.resolve(toChecksumAddress(defaultAccount))
} else {
addressPromise = getAccounts()
.catch((err) => {
log.error(err)
throw new Error(`Error retrieving ${web3.providerName} account`)
})
.then(([address]) => {
if (!address) {
throw new Error(`Unable to retrieve ${web3.providerName} account. Please ensure your account is unlocked.`)
}
return address
})
}
return addressPromise.then((address) => new EthereumWalletWeb3(address))
}
}
|
import React, {Component} from 'react'
import axios from 'axios'
import IndividualReadyProduct from './IndividualReadyProduct'
class ReadyProducts extends Component {
constructor() {
super()
this.state = {
vendorEmail: '',
products: [],
loading: true
}
this.fetchReadyProducts = this.fetchReadyProducts.bind(this)
this.dispatch = this.dispatch.bind(this)
}
fetchReadyProducts() {
this.setState({
loading: true
})
const vendor = {
vendorEmail: this.state.vendorEmail
}
axios.post('http://localhost:4000/vendor/getReadyProducts', vendor)
.then(res => {
this.setState({
products: res.data.message,
loading: false
});
})
.catch(err => {
console.log(err)
this.setState({
products: [],
loading: false
})
})
}
componentDidMount() {
this.setState({
vendorEmail: this.props.vendorEmail
},() => this.fetchReadyProducts())
}
dispatch(id) {
console.log('dispatching')
const product = {
id: id
}
axios.post('http://localhost:4000/vendor/dispatchProduct', product)
.then(res => {
this.fetchReadyProducts()
})
.catch(err => {
console.log(err)
})
}
render() {
const ReadyProducts = this.state.products.map(product => <IndividualReadyProduct key = {product._id} item = {product} dispatch = {this.dispatch}/>)
return (
<div>
{this.state.loading === true ?
<p>Loading ...</p>:
<div className = 'container-fluid fill' style = {{marginTop: '60px'}}>
<div className ="flex-container">
{ReadyProducts}
</div>
</div>
}
</div>
)
}
}
export default ReadyProducts |
var makeSet = function(){
var set = Object.create(setPrototype);
set._storage = {};
extend(set, setPrototype);
return set;
};
var setPrototype = {};
setPrototype.add = function(input){
var jsonInput = JSON.stringify(input);
this._storage[jsonInput] = (jsonInput in this._storage) ? this._storage[jsonInput] : true;
};
setPrototype.contains = function(input){
var jsonInput = JSON.stringify(input);
return (jsonInput in this._storage) ? true : false;
};
setPrototype.remove = function(input){
var jsonInput = JSON.stringify(input);
delete this._storage[jsonInput];
};
var extend = function(to, from){
for (var keys in from){
to[keys] = from[keys];
}
}; |
import React, {Fragment} from 'react';
import {MemeContext} from "./MemeContext";
import _ from "lodash";
import styled from "styled-components";
import ShareButtons from './sharebuttons';
import UrlOutput from './urloutput';
import MemeSelect from './memeselect';
import MemeText from './memetext';
const MemeCanvas = styled.img`
object-fit: contain;
width: 50vw;
height: 60vh;
text-align: center;
padding: 1em;
box-sizing: border-box;
width: 100%
image-border: solid 1px black;
font-family:Arial;
`;
const MemeSubmit = styled.button`
-moz-box-shadow:inset 0px 1px 3px 0px #91b8b3;
-webkit-box-shadow:inset 0px 1px 3px 0px #91b8b3;
box-shadow:inset 0px 1px 3px 0px #91b8b3;
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #768d87), color-stop(1, #6c7c7c));
background:-moz-linear-gradient(top, #768d87 5%, #6c7c7c 100%);
background:-webkit-linear-gradient(top, #768d87 5%, #6c7c7c 100%);
background:-o-linear-gradient(top, #768d87 5%, #6c7c7c 100%);
background:-ms-linear-gradient(top, #768d87 5%, #6c7c7c 100%);
background:linear-gradient(to bottom, #768d87 5%, #6c7c7c 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#768d87', endColorstr='#6c7c7c',GradientType=0);
background-color:#768d87;
-moz-border-radius:5px;
-webkit-border-radius:5px;
border-radius:5px;
border:1px solid #566963;
cursor:pointer;
color:#ffffff;
font-family:Arial;
font-size:15px;
font-weight:bold;
text-decoration:none;
text-shadow:0px -1px 0px #2b665e;
:hover{
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #6c7c7c), color-stop(1, #768d87));
background:-moz-linear-gradient(top, #6c7c7c 5%, #768d87 100%);
background:-webkit-linear-gradient(top, #6c7c7c 5%, #768d87 100%);
background:-o-linear-gradient(top, #6c7c7c 5%, #768d87 100%);
background:-ms-linear-gradient(top, #6c7c7c 5%, #768d87 100%);
background:linear-gradient(to bottom, #6c7c7c 5%, #768d87 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#6c7c7c', endColorstr='#768d87',GradientType=0);
background-color:#6c7c7c;
}
`;
const Toolbar = styled.form`
background: hsl(204, 14%, 50%);
border: 1px solid white;
`;
function makeMemeQuery(array) {
return _.map(array, formatMemeArray).join('&');
}
function formatMemeArray(value, index) {
return `boxes[${index}][text]=${value.text}`
}
function MemeEditor() {
const {memeId, memesMap, memeUrl, dispatch, inputs} = React.useContext(MemeContext);
const handleSubmit = (evt) => {
evt.preventDefault();
if(inputs.some(value => !!value)) {
const submittedText = _.reduce(inputs, (acc, value) => {
acc.push({ text: value });
return acc;
}, []);
const MemeTemplatePath =`https://cors-anywhere.herokuapp.com/https://api.imgflip.com/caption_image?template_id=${memeId}&${makeMemeQuery(submittedText)}&username=IvyDoyle&password=mypassword`;
fetch(MemeTemplatePath, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Origin': '*'
}
}).then((response) => {
return response.json();
}).then((json) => {
dispatch({ memeUrl: json.data.url });
});
}};
const memeMetaData = _.get(memesMap, memeId, {"box_count": 0, "memeId": ""})
const inputArray = [];
for (let i = 0; i < memeMetaData.box_count; i++) {
inputArray.push(<MemeText key={i} index={i} />);
}
return (
<Fragment>
<Toolbar onSubmit={handleSubmit}>
<MemeSelect />
{inputArray}
<MemeSubmit type="submit">Submit</MemeSubmit>
</Toolbar>
<MemeCanvas src={memeUrl || memeMetaData.url} alt="Edited meme goes here!"/>
<UrlOutput url={memeUrl} />
<ShareButtons url={memeUrl} />
</Fragment>
);
}
export default MemeEditor;
|
module.exports = angular
.module('modal', [
'ui.bootstrap',
'ui.router',
'ct.ui.router.extras'
])
.run(function($rootScope, $modal, $previousState) {
var stateBehindModal = {};
var modalInstance = null;
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
// Implementing 'isModal':
// perform the required action to transitions between 'modal states' and 'non-modal states'.
//
if (!fromState.isModal && toState.isModal) {
//
// Non-modal state ---> modal state
//
stateBehindModal = {
state: fromState,
params: fromParams
};
$previousState.memo('modalInvoker');
// Open up modal
modalInstance = $modal.open({
template: '<div ui-view="modal"></div>',
backdrop: 'static'
});
modalInstance.result.finally(function() {
// Reset instance to mark that the modal has been dismissed.
modalInstance = null
// Go to previous state
$state.go(stateBehindModal.state, stateBehindModal.params);
});
} else if (fromState.isModal && !toState.isModal) {
//
// Modal state ---> non-modal state
//
// Directly return if the instance is already dismissed.
if (!modalInstance) {
return;
}
// Dismiss the modal, triggering the reset of modalInstance
modalInstance.dismiss();
}
});
}); |
import { connect } from 'react-redux';
const StatusStrip = ({shallWait,err}) => (
<footer className="bg-dark text-light fixed-bottom">
<div className="col-sm-6 mx-auto p-2 text-center">
{err && <strong>ERRor! {err} </strong>}
{shallWait && <strong>Please wait while loading...</strong>}
{!err && !shallWait && <strong>All Good And Ready..!</strong> }
</div>
</footer>
);
const mapStateToProps = (state) => ({
shallWait: state.shallWait,
err: state.errMsg
});
const mapDispatchToProps = null;
const connectToStore = connect(mapStateToProps, mapDispatchToProps);
export default connectToStore(StatusStrip); |
const axios = require('axios');
const client_id = 'todo';
const client_secret = 'todo';
async function getToken(code) {
const url = 'https://github.com/login/oauth/access_token'
let body = { client_id, client_secret, code }
try {
const response = await axios.post(url, body);
console.log(response.data);
obj = {};
for (const i of response.data.split('&')) {
[k, v] = i.split('=');
obj[k] = decodeURIComponent(v);
}
return obj;
} catch (error) {
console.log(error);
return error;
}
};
// Test with:
// curl -X POST http://localhost:7071/api/localtrigger -H "Content-Type: application/json" -d '{"code":"put-code-here"}'
module.exports = async function (context, req) {
context.log(req)
/* Azure does not accept POST with query params,
so will never have anything in req.query.code.
*/
if (req.body && req.body.code) {
token = await getToken(req.body.code)
context.res = {
// status: 200, /* Defaults to 200 */
body: token
};
}
else {
context.log("No code");
context.res = {
status: 400,
body: "Code is missing"
};
}
};
|
module.exports = function(rootProcess, data) {
let ScriptTemplates = function(callback) {
let templateScriptStream = $.lib.mergeStream()
for(let templateScriptSettings of data) {
if(templateScriptSettings.handlebars) {
let layouts = $.lib.gulp
.src(templateScriptSettings.src.globs, templateScriptSettings.src.options)
.pipe($.lib.handlebars({
handlebars: require('handlebars')
}))
.pipe(Tasks.Subtasks.Wrap(templateScriptSettings.wrap.layouts))
.pipe(Tasks.Subtasks.Declare(templateScriptSettings.declare.layouts))
let partials = $.lib.gulp
.src(templateScriptSettings.src.globs, templateScriptSettings.src.options)
.pipe($.lib.handlebars({
handlebars: require('handlebars')
}))
.pipe(Tasks.Subtasks.Wrap(templateScriptSettings.wrap.partials))
let templateScript = templateScriptStream.add(layouts, partials)
.pipe(Tasks.Subtasks.Concat(templateScriptSettings.concat))
.pipe($.lib.dest(...templateScriptSettings.dest))
} else if(templateScriptSettings.ejs) {
let layouts = $.lib.gulp
.src(templateScriptSettings.src.globs, templateScriptSettings.src.options)
.pipe(Tasks.Subtasks.Wrap(templateScriptSettings.wrap))
.pipe(Tasks.Subtasks.Declare(templateScriptSettings.declare))
let templateScript = templateScriptStream.add(layouts)
.pipe(Tasks.Subtasks.Concat(templateScriptSettings.concat))
.pipe($.lib.dest(...templateScriptSettings.dest))
}
}
templateScriptStream.on('finish', () => {
if($.lib.browserSync.has('boilerplate')) {
$.lib.browserSync.get('boilerplate').reload()
}
})
return templateScriptStream
}
return ScriptTemplates
}
|
$(function() {
$.getJSON( "alows.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( '<div class="list notify"><div class="info"><span class="group">'+ val.grupoId +'</span> <h3>'+ val.texto +'</h3></div><ul class="options"><li class="report">Relatorio</li><li class="exlude icon-trash"></li></ul></div>' );
});
$( "<div/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( ".main" );
$('.options li.exlude').click( function() {
$(this).parent().parent().remove();
});
});
$('.next-step').click( function(e) {
$_next = $(this).attr('href');
$('.etapa1').fadeOut( "fast", function() {
$($_next).fadeIn( "fast");
});
e.preventDefault();
});
$('.modal-close').click( function() {
$('.etapa1').css('display', 'block');
$('.etapa2').css('display', 'none');
});
$('.menu').click( function(e) {
if ( $( window ).width() < 840)
$('.sidebar nav').toggleClass('open');
e.preventDefault();
});
//Colocar url aqui
$('input.submit').click( function() {
alert($('form.notificacao').serialize());
});
}); |
/*
* the route command allows to create a routing file
* in the appropriate folder allowing to specify for each
* routes the verbs of HTTP requests that should be used
*/
// --route -all to allow all the different verbs for http requests
// -r -A as shortcut
// for the update verb, PUT will be use over PATCH but,
// it will be possible to change it with `-P -path` parameter
|
var tplWarn = require('../templates/warn.string');
SPA.defineView('warn', {
html: tplWarn,
//绑定tab切换插件
plugins: ['delegated'],
//初始化一些数据,定义一些共用的
init: {
mySwiper: null
},
//tab切换
bindActions: {
'warn.slide': function(e, data) {
//console.log(e)
//console.log(data)
//变class颜色
$(e.el).addClass('active').siblings().removeClass('active');
this.mySwiper.slideTo($(e.el).index());
},
//模态窗
'modal':function(){
SPA.open('modal',{
ani:{
name:'actionSheet',
distance:-1
}
})
}
},
//swiper切换
bindEvents: {
show: function() {
this.mySwiper = new Swiper('#warn-swiper', {
loop: false,
onSlideChangeStart: function(swiper) {
var index = swiper.activeIndex;
var $lis = $('section ul li');
$lis.eq(index).addClass('active').siblings().removeClass('active');
}
})
}
}
});
//SPA.defineView('home',{
// html: tblHome,
// plugins: ['delegated'],
// init: {
// mySwiper:null
// },
// bindActions: {
// 'active': function (e) {
// //console.log(e)
// // 视图切换
// $(e.el).addClass('active').siblings().removeClass('active');//变色
// this.mySwiper.slideTo($(e.el).index());//切换
// }
// },
// bindEvents: {
// 'show': function () {
//// var mySwiper = new Swiper ('#swiper', {
//// loop: true,
//// autoplay: 3000,
//// // 如果需要分页器
//// pagination: '.swiper-pagination'
//// });
// this.mySwiper = new Swiper('#sectSwiper', {
// loop: false,
// onSlideChangeStart: function (swiper) {
// var index = swiper.activeIndex;
// var $lis = $('.home nav li');
// $lis.eq(index).addClass('active').siblings().removeClass('active');
// }
// })
// }
// }
//});
|
var express = require('express');
var exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
var request = require('request');
var http = require('http');
var https = require('https');
var path = require('path');
var fs = require('fs');
// !!! To make the Dropbox API work with a different domain, we need to replace the getBaseUrl function
// in ../node_modules/dropbox/src/get-base-url
//
var Dropbox = require('dropbox');
// Config needs to contain CLIENT_ID, CLIENT_SECRET, and REDIRECT_URL. It may also contain OAUTH_BASE to auth to
// service other than Dropbox.
//
module.exports = function(config)
{
var log = require('./../lib/logger').getLogger("server");
log.info("Dropbox:", Dropbox);
// SSL support
//
// For raw key/cert, use SSL_KEY and SSL_CERT. To refer to key and/or cert files, use SSL_KEY_PATH and SSL_CERT_PATH.
//
// Note: It will generally be the case that SSL is terminated upstream from this server. When an upstream proxy terminates SSL, it
// should add an "x-arr-ssl" header to the request to indicate to this server that the connection was secure (arr is for Application
// Request Routing). The upstream proxy that terminates SSL should also either deny non-SSL requests or ensure that the "x-arr-ssl"
// request header is not present on non-SSL requests. Microsoft Azure terminates SSL and adds this header automatically.
//
// Note: This server will serve HTTP *OR* HTTPS, but not both. This is by design. HTTP should only be used for local development, or
// in production when SSL is terminated upstream. There is no use case where serving both HTTP and HTTPS would be appropriate.
//
var sslOptions = { key: config.get("SSL_KEY"), cert: config.get("SSL_CERT") };
if (!sslOptions.key)
{
var keyPath = config.get("SSL_KEY_PATH");
if (keyPath)
{
sslOptions.key = fs.readFileSync(keyPath);
}
}
if (!sslOptions.cert)
{
var certPath = config.get("SSL_CERT_PATH");
if (certPath)
{
sslOptions.cert = fs.readFileSync(certPath);
}
}
if (!sslOptions.key || !sslOptions.cert)
{
sslOptions = null;
}
var app = express();
app.use(cookieParser("cookie_secret_420"));
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.get('/auth', function(req, res)
{
log.info("Auth callback from OAuth:", req.query);
var form =
{
code: req.query.code, // required The code acquired by directing users to /oauth2/authorize?response_type=code.
grant_type: "authorization_code", // required The grant type, which must be authorization_code.
client_id: config.get('CLIENT_ID'), // If credentials are passed in POST parameters, this parameter should be present and should be the app's key (found in the App Console).
client_secret: config.get('CLIENT_SECRET'), // If credentials are passed in POST parameters, this parameter should be present and should be the app's secret.
redirect_uri: config.get('REDIRECT_URL') // Only used to validate that it matches the original /oauth2/authorize, not used to redirect again.
}
request.post({ url: config.get('OAUTH_BASE') + "token", form: form }, function (e, r, body)
{
if (e || r.statusCode !== 200)
{
log.error("Error getting token from code:", e, r.statusCode);
res.status(500).send('Error getting token from code');
}
else
{
var tokenResponse = JSON.parse(body);
// The token response body should look like this:
//
// {
// access_token: '<bunch of hex>',
// token_type: 'bearer',
// uid: '99999999',
// account_id: 'dbid:<bunch of hex with dashes>'
// }
log.info("Got token response:", tokenResponse);
var dbx = new Dropbox({ accessToken: tokenResponse.access_token });
dbx.usersGetCurrentAccount()
.then(function(response) {
log.info("Got current account:", response);
res.cookie("dbx_access_token", tokenResponse.access_token, { signed: true });
res.cookie("dbx_user_email", response.email, { signed: true });
res.redirect('/');
})
.catch(function(error) {
log.error(error)
});
}
});
});
app.get('/login', function(req, res)
{
log.info("Logging in (redirecting to OAuth at provider)");
// The Dropbox JS SDK doesn't support OAuth "code flow" directly, so we just build the auth endpoint URI the hard way...
//
var authUrl = config.get('OAUTH_BASE') + "authorize?response_type=code&client_id=" + config.get('CLIENT_ID') + "&redirect_uri=" + config.get('REDIRECT_URL');
log.info("Auth url:", authUrl);
res.redirect(authUrl);
});
app.get('/logout', function(req, res)
{
log.info("Clearing access token cookie");
res.clearCookie("dbx_access_token", { signed: true });
res.redirect('/');
});
if (config.get('DEV_MODE'))
{
// Allow scripts edited during dev to show up in browser in real-time
//
app.use('/public', express.static('public'))
}
else
{
// Let the browser cache scripts so the response is a little snappier
//
app.use('/public', express.static('public', { maxage: '2h' }))
}
app.get('/download', function (req, res)
{
if (req.signedCookies && req.signedCookies.dbx_access_token)
{
var filepath = decodeURI(req.query.file);
log.info("Download path:", filepath)
var dbx = new Dropbox({ accessToken: req.signedCookies.dbx_access_token });
dbx.filesDownload({path: filepath})
.then(function(response) {
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename=' + path.basename(filepath),
'Content-Length': response.size
});
res.end(response.fileBinary, 'binary');
})
.catch(function(error) {
log.error(error);
});
}
else
{
log.error("No access token");
}
});
app.get('/', function (req, res)
{
res.redirect('/home');
})
app.get('/search', function (req, res)
{
if (req.signedCookies && req.signedCookies.dbx_access_token)
{
var query = decodeURI(req.query.query)
log.info("Search, query:", query)
var dbx = new Dropbox({ accessToken: req.signedCookies.dbx_access_token });
dbx.filesSearch({ path: '/', query: query }).then(function(response)
{
log.info("Got search response:", JSON.stringify(response))
var matches = []
if (response.matches)
{
response.matches.forEach(function (match)
{
var entry = match.metadata
if (entry['.tag'] === 'folder')
{
entry.folder = true
}
entry.parent = entry.path_display.slice(0, - (entry.name.length + 1))
log.debug("Found match:", entry)
matches.push(entry)
})
}
var pathElements = [{ name: "Home", link: "/" }, { name: "Search Results" }];
res.render('home', {
dropboxApiEndpoint: g_dropboxApiEndpoint,
token: req.signedCookies.dbx_access_token,
email: req.signedCookies.dbx_user_email,
path: '/',
pathElements: pathElements,
entries: matches,
search: true
});
})
.catch(function(error)
{
log.error(error);
})
}
else
{
log.error("No access token");
}
})
app.get(['/home', '/home/*?'], function (req, res)
{
if (req.signedCookies && req.signedCookies.dbx_access_token)
{
var dirpath = '/' + (req.params[0] || '');
log.info("Path:", dirpath)
var pathElements = dirpath.split('/');
pathElements[0] = { name: "Home", link: "/home" };
if ((pathElements.length > 1) && (pathElements[pathElements.length-1] === ''))
{
pathElements.pop();
}
if (pathElements.length > 1)
{
var currPath = "/home";
for (var i = 1; i < pathElements.length; i++)
{
currPath += "/" + pathElements[i]
pathElements[i] = { name: pathElements[i], link: currPath };
}
}
delete pathElements[pathElements.length-1].link;
log.info("Path elements:", pathElements);
if (dirpath === '/')
{
dirpath = '';
}
log.info("Access token present, doing Dropbox stuff");
var dbx = new Dropbox({ accessToken: req.signedCookies.dbx_access_token });
dbx.filesListFolder({path: dirpath}).then( function(response)
{
log.info("List folder response:", response)
response.entries.forEach(function(entry)
{
if (entry['.tag'] === 'folder')
{
entry.folder = true;
}
})
log.info("api endpoint:", g_dropboxApiEndpoint)
res.render('home', {
dropboxApiEndpoint: g_dropboxApiEndpoint,
token: req.signedCookies.dbx_access_token,
email: req.signedCookies.dbx_user_email,
path: dirpath,
cursor: response.cursor,
pathElements: pathElements,
entries: response.entries,
folder: true
});
})
.catch(function(error) {
log.error(error);
});
}
else
{
log.info("No access token");
res.render('notconnected');
}
});
var server;
if (sslOptions)
{
server = https.createServer(sslOptions, app);
}
else
{
server = http.createServer(app);
}
return server;
}
|
var c_version=2;
var EPS=0.00000001; // 144-Number.EPSILON was 144 at the time :| [17/07/18]
var ZEPS=0.00000001; //z-index EPS
var REPS=((Number&&Number.EPSILON)||EPS);
var CINF=999999999999999;
var really_old=new Date(); really_old.setYear(1970);
var colors={
"range":"#93A6A2",
"armor":"#5C5D5E",
"resistance":"#6A5598",
"attack":"#DB2900",
"str":"#F07F2F",
"int":"#3E6EED",
"dex":"#44B75C",
"for":"#5F3085",
"speed":"#36B89E",
"cash":"#5DAC40",
"hp":"#FF2E46",
//"mp":"#365DC5",
"mp":"#3A62CE",
"stat_xp":"#4570B1",
"party_xp":"#AD73E0",
"xp":"#CBFFFF",
"luck":"#2A9A3D",
"gold":"gold",
"male":"#43A1C6",
"female":"#C06C9B",
"server_success":"#85C76B",
"server_failure":"#C7302C",
"poison":"#41834A",
"ability":"#ff9100", // nice-green #66ad0f - neon-orange #ff9100
"xmas":"#C82F17",
"xmasgreen":"#33BF6D",
"code_blue":"#32A3B0",
"code_pink":"#E13758",
"code_error":"#E13758",
"A":"#39BB54",
"B":"#DB37A3",
"npc_white":"#EBECEE",
"white_positive":"#C3FFC0",
"white_negative":"#FFDBDC",
"positive_greeb":"#85C76B",
"serious_red":"#BC0004",
"serious_green":"#428727",
"heal":"#EE4D93",
"lifesteal":"#9A1D27",
"manasteal":"#353C9C",
"inspect":"#7F75CA",
"property":"#EF7A4D",
"string":"#D3637E",
}
var trade_slots=[],check_slots=["elixir"];
for(var i=1;i<=48;i++) trade_slots.push("trade"+i),check_slots.push("trade"+i);
var bank_packs={
"items0":["bank",0,0],
"items1":["bank",0,0],
"items2":["bank",75000000,600],
"items3":["bank",75000000,600],
"items4":["bank",100000000,800],
"items5":["bank",100000000,800],
"items6":["bank",112500000,900],
"items7":["bank",112500000,900],
"items8":["bank_b",0,0],
"items9":["bank_b",475000000,1000],
"items10":["bank_b",675000000,1150],
"items11":["bank_b",825000000,1150],
"items12":["bank_b",975000000,1200],
"items13":["bank_b",975000000,1200],
"items14":["bank_b",975000000,1200],
"items15":["bank_b",975000000,1200],
"items16":["bank_b",975000000,1200],
"items17":["bank_b",1075000000,1200],
"items18":["bank_b",1175000000,1200],
"items19":["bank_b",1275000000,1200],
"items20":["bank_b",1375000000,1200],
"items21":["bank_b",1475000000,1200],
"items22":["bank_b",1575000000,1200],
"items23":["bank_b",1675000000,1200],
"items24":["bank_u",0,0],
"items25":["bank_u",2075000000,1350],
"items26":["bank_u",2075000000,1350],
"items27":["bank_u",2075000000,1350],
"items28":["bank_u",2075000000,1350],
"items29":["bank_u",3075000000,1350],
"items30":["bank_u",3075000000,1350],
"items31":["bank_u",3075000000,1350],
"items32":["bank_u",3075000000,1350],
"items33":["bank_u",3075000000,1350],
"items34":["bank_u",3075000000,1350],
"items35":["bank_u",4075000000,1450],
"items36":["bank_u",5075000000,1450],
"items37":["bank_u",6075000000,1450],
"items38":["bank_u",7075000000,1450],
"items39":["bank_u",8075000000,1450],
"items40":["bank_u",9075000000,1650],
"items41":["bank_u",9075000000,1650],
"items42":["bank_u",9975000000,1650],
"items43":["bank_u",9975000000,1650],
"items44":["bank_u",9975000000,1650],
"items45":["bank_u",9975000000,1850],
"items46":["bank_u",9975000000,1850],
"items47":["bank_u",9995000000,1850],
};
var character_slots=["ring1","ring2","earring1","earring2","belt","mainhand","offhand","helmet","chest","pants","shoes","gloves","amulet","orb","elixir","cape"];
var attire_slots=["helmet","chest","pants","shoes","gloves","cape"];
var riches_slots=["ring1","ring2","earring1","earring2","amulet"];
var booster_items=["xpbooster","luckbooster","goldbooster"];
var doublehand_types=["axe","basher","great_staff"];
var offhand_types={
"quiver":"Quiver",
"shield":"Shield",
"misc_offhand":"Misc Offhand",
"source":"Source"
};
var weapon_types={
"sword":"Sword",
"short_sword":"Short Sword",
"great_sword":"Great Sword",
"axe":"Axe",
"wblade":"Magical Sword",
"basher":"Basher",
"dartgun":"Dart Gun",
"bow":"Bow",
"crossbow":"Crossbow",
"rapier":"Rapier",
"spear":"Spear",
"fist":"Fist Weapon",
"dagger":"Dagger",
"stars":"Throwing Stars",
"mace":"Mace",
"pmace":"Priest Mace",
"staff":"Staff",
"wand":"Wand",
};
var cxtype_to_slot={
"armor":"skin",
"body":"skin",
"character":"skin",
"face":"face",
"makeup":"makeup",
"a_makeup":"makeup",
"beard":"chin",
"mask":"chin",
"tail":"tail",
"s_wings":"back",
"wings":"back",
"hat":"hat",
"a_hat":"hat",
"head":"head",
"hair":"hair",
"gravestone":"gravestone",
};
var free_cx=["makeup105","makeup117","mmakeup00","fmakeup01","fmakeup02","fmakeup03"];
var can_buy={};
var T={}; // sprite-type
function process_game_data()
{
G.quests={};
for(var name in G.monsters)
{
if(G.monsters[name].charge) continue;
if(G.monsters[name].speed>=60) G.monsters[name].charge=round(G.monsters[name].speed*1.20);
else if(G.monsters[name].speed>=50) G.monsters[name].charge=round(G.monsters[name].speed*1.30);
else if(G.monsters[name].speed>=32) G.monsters[name].charge=round(G.monsters[name].speed*1.4);
else if(G.monsters[name].speed>=20) G.monsters[name].charge=round(G.monsters[name].speed*1.6);
else if(G.monsters[name].speed>=10) G.monsters[name].charge=round(G.monsters[name].speed*1.7);
else G.monsters[name].charge=round(G.monsters[name].speed*2);
G.monsters[name].max_hp=G.monsters[name].hp; // So default value adoption logic is easier [16/04/18]
}
for(var c in G.classes)
{
if(!G.classes[c].xcx) G.classes[c].xcx=[];
free_cx.forEach(function(cx){ if(!G.classes[c].xcx.includes(cx)) G.classes[c].xcx.push(cx); });
G.classes[c].looks.forEach(function(l){
if(!G.classes[c].xcx.includes(l[0])) G.classes[c].xcx.push(l[0]);
for(var slot in l[1])
{
if(!G.classes[c].xcx.includes(l[1][slot])) G.classes[c].xcx.push(l[1][slot]);
}
})
}
for(var s in G.sprites)
{
var current=G.sprites[s],matrix=current.matrix;
if(current.skip) continue;
for(var i=0;i<matrix.length;i++)
for(var j=0;j<matrix[i].length;j++)
{
if(!matrix[i][j]) continue;
T[matrix[i][j]]=current.type||"full";
}
}
for(var name in G.maps)
{
var map=G.maps[name];
if(map.ignore) continue;
// var M=map.data={x_lines:(G.geometry[name].x_lines||[]).slice(),y_lines:(G.geometry[name].y_lines||[]).slice()},LD=5;
var M=map.data=G.geometry[name];
// Instead of extending lines, applied the emulated move forward logic everywhere [18/07/18]
// G.geometry[name].x_lines=[]; G.geometry[name].y_lines=[]; // New system [17/07/18]
// map.data.x_lines.forEach(function(line){
// G.geometry[name].x_lines.push([line[0]-LD,line[1]-LD,line[2]+LD]);
// G.geometry[name].x_lines.push([line[0]+LD,line[1]-LD,line[2]+LD]);
// });
// G.geometry[name].x_lines.sort(function(a,b){return (a[0] > b[0]) ? 1 : ((b[0] > a[0]) ? -1 : 0);});
// map.data.y_lines.forEach(function(line){
// G.geometry[name].y_lines.push([line[0]-LD,line[1]-LD,line[2]+LD]);
// G.geometry[name].y_lines.push([line[0]+LD,line[1]-LD,line[2]+LD]); // The extra 4px is roughly the size of character shoes
// });
// G.geometry[name].y_lines.sort(function(a,b){return (a[0] > b[0]) ? 1 : ((b[0] > a[0]) ? -1 : 0);});
map.items={};
map.merchants=[];
map.ref=map.ref||{};
(map.npcs||[]).forEach(function(npc){
if(!npc.position) return;
var coords={map:name,"in":name,x:npc.position[0],y:npc.position[1],id:npc.id},data=G.npcs[npc.id];
if(data.items)
{
map.merchants.push(coords);
data.items.forEach(function(name){
if(!name) return;
if(G.items[name].cash)
{
G.items[name].buy_with_cash=true;
if(!G.items[name].p2w) return;
}
map.items[name]=map.items[name]||[];
map.items[name].push(coords);
can_buy[name]=true;
G.items[name].buy=true;
});
}
map.ref[npc.id]=coords;
if(data.role=="newupgrade") map.upgrade=map.compound=coords; // Refactored the NPC's, but decided to leave these [26/06/18]
if(data.role=="exchange") map.exchange=coords;
if(data.quest) G.quests[data.quest]=coords;
});
}
for(var id in G.items)
G.items[id].id=id;
}
function test_logic()
{
for(var id in G.items)
{
G.items[id].cash=0;
G.items[id].g=G.items[id].g||1; // actual values now
}
for(var id in G.monsters)
{
G.monsters[id].xp=0;
}
}
function map_cx(player)
{
var cx={};
for(var c in (player.p&&player.p.acx||player.acx||{}))
{
if(G.cosmetics.bundle[c])
G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=c; })
else if(G.cosmetics.map[c])
cx[G.cosmetics.map[c]]=c;
else
cx[c]=c;
}
return cx;
}
function all_cx(player,send)
{
var cx={};
for(var c in (player.p&&player.p.acx||player.acx||{}))
{
if(G.cosmetics.bundle[c])
G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)+1; })
else if(G.cosmetics.map[c])
cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)+1;
else
cx[c]=(cx[c]||0)+1;
}
if(send)
{
for(var s in (player.cx||{}))
{
var c=player.cx[s];
if(G.cosmetics.bundle[c])
G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)-1; })
else if(G.cosmetics.map[c])
cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)-1;
else
cx[c]=(cx[c]||0)-1;
}
[player.skin].forEach(function(c){
if(G.cosmetics.bundle[c])
G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)-1; })
else if(G.cosmetics.map[c])
cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)-1;
else
cx[c]=(cx[c]||0)-1;
});
}
(player.p&&player.p.xcx||player.xcx||[]).forEach(function(c){
if(G.cosmetics.bundle[c])
G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)+0.01; })
else if(G.cosmetics.map[c])
cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)+0.01;
else
cx[c]=(cx[c]||0)+0.01;
});
(G.classes[player.ctype||player.type].xcx||[]).forEach(function(c){
if(G.cosmetics.bundle[c])
G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)+0.01; })
else if(G.cosmetics.map[c])
cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)+0.01;
else
cx[c]=(cx[c]||0)+0.01;
});
return cx;
}
function prune_cx(cx,skin)
{
if(skin && cx.upper && cx.upper=="skin") delete cx.upper;
for(var sname in cx)
{
if(!cx[sname] || sname=="upper" && T[cx[sname]]!="body" && T[cx[sname]]!="armor" || sname!="upper" && cxtype_to_slot[T[cx[sname]]]!=sname)
{
delete cx[sname];
continue;
}
}
}
function hx(color)
{
return eval("0x"+color.replace("#",""));
}
function hardcore_logic()
{
for(var id in G.items)
{
// if(G.items[id].tier==2) G.items[id].a=0;
}
G.npcs.premium.items[3]="computer";
G.npcs.premium.items[4]="tracker";
G.npcs.premium.items.forEach(function(item){
if(item)
{
G.items[item].cash=0;
G.items[item].g=parseInt(G.items[item].g*2);
}
});
for(var id in G.monsters)
{
if(G.monsters[id].respawn!=-1)
G.monsters[id].respawn=1;
}
for(var id in G.tokens)
{
for(var m in G.tokens[id])
{
G.tokens[id][m]=1;
}
}
G.tokens.monstertoken.fieldgen0=20;
G.items.offering.g=parseInt(G.items.offering.g/2);
G.items.xptome.g=99999999;
G.items.computer.g=1;
G.items.tracker.g=1;
G.items.gemfragment.e=10;
G.items.leather.e=5;
G.maps.main.monsters.push({"type":"wabbit","boundary":[-282,702,218,872],"count":1});
G.npcs.scrolls.items[9]="vitscroll";
G.monsters.wabbit.evasion=96.0;
G.monsters.wabbit.reflection=96.0;
G.monsters.phoenix.respawn=1;
G.monsters.mvampire.respawn=1;
delete G.items.test_orb.upgrade;
G.items.test_orb.compound={};
// G.items.gem0.a=0;
// G.items.gem1.a=0;
// G.items.armorbox.a=0;
// G.items.weaponbox.a=0;
}
function can_stack(a,b,d)
{
if(a && b && a.name && G.items[a.name].s && a.name==b.name && a.l==b.l && a.q+b.q+(d||0)<=(G.items[a.name].s===true&&9999||G.items[a.name].s) && (a.name!="cxjar" || a.data==b.data) && (a.name!="emotionjar" || a.data==b.data)) return true;
return false;
}
function can_add_item(player,new_item,args) // long requested feature [18/10/18]
{
if(!args) args={};
if(!new_item.name) new_item=create_new_item(new_item,args.q||1);
if(is_array(player)) // for "bank"/"swap"
{
player={items:player};
for(var i=0;i<42;i++) if(!player.items[i]) return true;
}
if(player.esize>0) return true;
if(G.items[new_item.name].s)
{
for(var i=0;i<player.items.length;i++)
{
var item=player.items[i];
if(can_stack(item,new_item))
{
return true;
}
}
}
return false;
}
function can_add_items(player,items,args)
{
if(!args) args={};
var needed=items.length,overhead=[];
if(player.esize+(args.space||0)>=needed || !needed) return true;
items.forEach(function(new_item){
if(G.items[new_item.name].s)
{
for(var i=0;i<player.items.length;i++)
{
var item=player.items[i];
if(can_stack(item,new_item,overhead[i]||0))
{
overhead[i]=(overhead[i]||0)+new_item.q;
needed--;
}
}
}
});
if(player.esize+(args.space||0)>=needed) return true;
return false;
}
var deferreds={},current_deferred=null;
function deferred()
{
var self=this;
this.promise=new Promise(function(resolve,reject){
self.reject = reject;
self.resolve = resolve;
});
}
function push_deferred(name)
{
var current=new deferred();
if(["attack","heal"].includes(name))
current.start=new Date();
if(!deferreds[name]) deferreds[name]=[];
deferreds[name].push(current);
if(deferreds[name].length>3200) deferreds[name].shift(); // outbreak
return current.promise;
}
function push_deferreds(name,count)
{
var deferreds=[];
for(var i=0;i<count;i++)
deferreds.push(push_deferred(name));
return deferreds;
}
function resolve_deferreds(name,data)
{
while(deferreds[name] && deferreds[name].length) resolve_deferred(name,data);
delete deferreds[name];
}
function reject_deferreds(name,data)
{
while(deferreds[name] && deferreds[name].length) reject_deferred(name,data);
delete deferreds[name];
}
function resolve_deferred(name,data)
{
if(name=="attack" && (!deferreds.attack || !deferreds.attack.length) && deferreds.heal && deferreds.heal.length) name="heal"; // cupid logic [23/09/19]
if(name=="heal" && (!deferreds.heal || !deferreds.heal.length) && deferreds.attack && deferreds.attack.length) name="attack"; // ~impossible to perfectly predict the call/result
if(!deferreds[name] || !deferreds[name].length) return console.error("Weird resolve_deferred issue: "+name),console.log("If you emit socket events manually, ignore this message");
current_deferred=deferreds[name].shift();
if(!deferreds[name].length) delete deferreds[name];
if(deferreds[name] && deferreds[name].length && deferreds[name][deferreds[name].length-1].start) push_ping(mssince(deferreds[name][deferreds[name].length-1].start)); // if there's a promise bug, this covers the .ping outbreak issue
else if(current_deferred.start) push_ping(mssince(current_deferred.start));
try{
current_deferred.resolve(data);
}catch(e){
try{
// never called in chrome because resolve exceptions are automatically chained as secondary rejects
call_code_function("game_log","resolve_callback_exception: "+e,colors.code_error);
current_deferred.reject({exception:"resolve_callback_exception",reason:"exception"});
}catch(e){
};
}
current_deferred=null
}
function reject_deferred(name,data)
{
if(!deferreds[name] || !deferreds[name].length) return console.error("Weird reject_deferred issue: "+name),console.log("If you emit socket events manually, ignore this message");
current_deferred=deferreds[name].shift();
if(!deferreds[name].length) delete deferreds[name];
try{
current_deferred.reject(data);
}catch(e){
try{
// reject exceptions are automatically chained as secondary rejects too
call_code_function("game_log","reject_callback_exception: "+e,colors.code_error);
current_deferred.reject({exception:"reject_callback_exception",reason:"exception"});
}catch(e){};
}
current_deferred=null
}
function rejecting_promise(data)
{
return new Promise(function(resolve,reject){ reject(data); });
}
function resolving_promise(data)
{
return new Promise(function(resolve,reject){ resolve(data); });
}
function object_sort(o,algorithm)
{
function lexi(x,y)
{
if(x[0]<y[0]) return -1;
return 1;
}
function random(x,y)
{
return 0.5-Math.random();
}
function vsort(x,y)
{
if(x[1]<y[1]) return -1;
else if(x[1]==y[1] && x[0]<y[0]) return -1;
return 1;
}
function gsort(x,y)
{
// console.log(x);
if(G.items[x[0]].g<G.items[y[0]].g) return -1;
else if(G.items[x[0]].g<G.items[y[0]].g && x[0]<y[0]) return -1;
return 1;
}
function hpsort(x,y)
{
if(x[1].hp!=y[1].hp) return x[1].hp-y[1].hp;
if(x[0]<y[0]) return -1;
return 1;
}
var a=[];
for(var id in o) a.push([id,o[id]]);
if(algorithm=="hpsort") a.sort(hpsort);
else if(algorithm=="random") a.sort(random);
else if(algorithm=="value") a.sort(vsort);
else if(algorithm=="gold_value") a.sort(gsort);
else a.sort(lexi);
return a;
}
function direction_logic(entity,target,mode)
{
if(entity!=target)
{
entity.a_angle=Math.atan2(get_y(target)-get_y(entity),get_x(target)-get_x(entity))*180/Math.PI;
// if(is_server && entity.moving) return; // maybe add the is_server [06/10/19]
entity.angle=entity.a_angle;
}
if(is_game && !new_attacks && entity.moving) return;
set_direction(entity,entity.moving&&"soft"||mode);
}
function within_xy_range(observer,entity)
{
if(observer['in']!=entity['in']) return false
if(!observer.vision) return false;
var x=get_x(entity),y=get_y(entity),o_x=get_x(observer),o_y=get_y(observer);
if(o_x-observer.vision[0]<x && x<o_x+observer.vision[0] && o_y-observer.vision[1]<y && y<o_y+observer.vision[1]) return true;
return false;
}
function distance(a,b,in_check)
{
if(in_check && a['in']!=b['in']) return 99999999;
if(get_width(a) && get_width(b))
{
var min_d=99999999,a_w=get_width(a),a_h=get_height(a),b_w=get_width(b),b_h=get_height(b),dist;
// a_h*=0.75; b_h*=0.75; // This seems better, thanks to draw_circle REVISIT!!
var a_x=get_x(a),a_y=get_y(a),b_x=get_x(b),b_y=get_y(b);
// [{x:a_x-a_w/2,y:a_y},{x:a_x+a_w/2,y:a_y},{x:a_x+a_w/2,y:a_y-a_h},{x:a_x-a_w/2,y:a_y-a_h}].forEach(function(p1){
// [{x:b_x-b_w/2,y:b_y},{x:b_x+b_w/2,y:b_y},{x:b_x+b_w/2,y:b_y-b_h},{x:b_x-b_w/2,y:b_y-b_h}].forEach(function(p2){
// dist=simple_distance(p1,p2);
// if(dist<min_d) min_d=dist;
// })
// });
[{x:a_x-a_w/2,y:a_y-a_h/2},{x:a_x+a_w/2,y:a_y-a_h/2},{x:a_x,y:a_y},{x:a_x,y:a_y-a_h}].forEach(function(p1){
[{x:b_x-b_w/2,y:b_y-b_h/2},{x:b_x+b_w/2,y:b_y-b_h/2},{x:b_x,y:b_y},{x:b_x,y:b_y-b_h}].forEach(function(p2){
dist=simple_distance(p1,p2);
if(dist<min_d) min_d=dist;
})
});
// console.log(min_d);
return min_d;
}
return simple_distance(a,b);
}
function random_away(x,y,R) // https://stackoverflow.com/a/5838055/914546
{
var t=2*Math.PI*Math.random();
var u=Math.random()*2;
var r=u>1&&(2-u)||u;
return [x+R*r*Math.cos(t),y+R*r*Math.sin(t)];
}
function can_transport(entity)
{
return can_walk(entity);
}
function can_walk(entity)
{
if(is_game && entity.me && transporting && ssince(transporting)<8 && !entity.c.town) return false;
if(is_code && entity.me && parent.transporting && ssince(parent.transporting)<8 && !entity.c.town) return false;
return !is_disabled(entity);
}
function is_silenced(entity)
{
if(!entity || is_disabled(entity) || (entity.s && entity.s.silenced)) return true;
}
function is_disabled(entity)
{
if(!entity || entity.rip || (entity.s && (entity.s.stunned || entity.s.fingered || entity.s.stoned || entity.s.deepfreezed))) return true;
}
function calculate_item_grade(def,item)
{
if(!(def.upgrade || def.compound)) return 0;
if((item&&item.level||0)>=(def.grades||[9,10,11,12])[3]) return 4;
if((item&&item.level||0)>=(def.grades||[9,10,11,12])[2]) return 3;
if((item&&item.level||0)>=(def.grades||[9,10,11,12])[1]) return 2;
if((item&&item.level||0)>=(def.grades||[9,10,11,12])[0]) return 1;
return 0;
}
function calculate_item_value(item,m)
{
if(!item) return 0;
if(item.gift) return 1;
var def=G.items[item.name]||G.items.placeholder_m,value=def.cash&&def.g||def.g*(m||0.6),divide=1; // previously 0.8
if(def.markup) value/=def.markup;
if(def.compound && item.level)
{
var grade=0,grades=def.grades||[11,12],s_value=0;
for(var i=1;i<=item.level;i++)
{
if(i>grades[1]) grade=2;
else if(i>grades[0]) grade=1;
if(def.cash) value*=1.5;
else value*=3.2;
value+=G.items["cscroll"+grade].g/2.4;
}
}
if(def.upgrade && item.level)
{
var grade=0,grades=def.grades||[11,12],s_value=0;
for(var i=1;i<=item.level;i++)
{
if(i>grades[1]) grade=2;
else if(i>grades[0]) grade=1;
s_value+=G.items["scroll"+grade].g/2;
if(i>=7) value*=3,s_value*=1.32;
else if(i==6) value*=2.4;
else if(i>=4) value*=2;
if(i==9) value*=2.64,value+=400000;
if(i==10) value*=5;
//if(i==11) value*=2;
if(i==12) value*=0.8;
}
value+=s_value;
}
if(item.expires) divide=8;
return round(value/divide)||0;
}
var prop_cache={}; // reset at reload_server
function damage_multiplier(defense) // [10/12/17]
{
return min(1.32,max(0.05,1-(max(0,min(100,defense))*0.00100+
max(0,min(100,defense-100))*0.00100+
max(0,min(100,defense-200))*0.00095+
max(0,min(100,defense-300))*0.00090+
max(0,min(100,defense-400))*0.00082+
max(0,min(100,defense-500))*0.00070+
max(0,min(100,defense-600))*0.00060+
max(0,min(100,defense-700))*0.00050+
max(0,defense-800)*0.00040)+
max(0,min(50,0-defense))*0.00100+ // Negative's / Armor Piercing
max(0,min(50,-50-defense))*0.00075+
max(0,min(50,-100-defense))*0.00050+
max(0,-150-defense)*0.00025
));
}
function dps_multiplier(defense) // [10/12/17]
{
return 1-(max(0,min(100,defense))*0.00100+
max(0,min(100,defense-100))*0.00100+
max(0,min(100,defense-200))*0.00095+
max(0,min(100,defense-300))*0.00090+
max(0,min(100,defense-400))*0.00082+
max(0,min(100,defense-500))*0.00070+
max(0,min(100,defense-600))*0.00060+
max(0,min(100,defense-700))*0.00050+
max(0,defense-800)*0.00040)+
max(0,min(50,0-defense))*0.00100+ // Negative's / Armor Piercing
max(0,min(50,-50-defense))*0.00075+
max(0,min(50,-100-defense))*0.00050+
max(0,-150-defense)*0.00025
}
function calculate_item_properties(def,item)
{
var prop_key=def.name+item.name+(def.card||"")+"|"+item.level+"|"+item.stat_type+"|"+item.p;
if(prop_cache[prop_key]) return prop_cache[prop_key];
//#NEWIDEA: An item cache here [15/11/16]
var prop={
"gold":0,
"luck":0,
"xp":0,
"int":0,
"str":0,
"dex":0,
"vit":0,
"for":0,
"charisma":0,
"cuteness":0,
"awesomeness":0,
"bling":0,
"hp":0,
"mp":0,
"attack":0,
"range":0,
"armor":0,
"resistance":0,
"pnresistance":0,
"firesistance":0,
"fzresistance":0,
"stun":0,
"blast":0,
"explosion":0,
"breaks":0,
"stat":0,
"speed":0,
"level":0,
"evasion":0,
"miss":0,
"reflection":0,
"lifesteal":0,
"manasteal":0,
"attr0":0,
"attr1":0,
"rpiercing":0,
"apiercing":0,
"crit":0,
"critdamage":0,
"dreturn":0,
"frequency":0,
"mp_cost":0,
"mp_reduction":0,
"output":0,
"courage":0,
"mcourage":0,
"pcourage":0,
"set":null,
"class":null,
};
var mult={
"gold":0.5,
"luck":1,
"xp":0.5,
"int":1,
"str":1,
"dex":1,
"vit":1,
"for":1,
"armor":2.25,
"resistance":2.25,
"speed":0.325,
"evasion":0.325,
"reflection":0.150,
"lifesteal":0.15,
"manasteal":0.040,
"rpiercing":2.25,
"apiercing":2.25,
"crit":0.125,
"dreturn":0.5,
"frequency":0.325,
"mp_cost":-0.6,
"output":0.175,
};
if(item.p=="shiny")
{
if(def.attack)
{
prop.attack+=4;
if(doublehand_types.includes(G.items[item.name].wtype)) prop.attack+=3;
}
else if(def.stat)
{
prop.stat+=2;
}
else if(def.armor)
{
prop.armor+=12;
prop.resistance=(prop.resistance||0)+10;
}
else
{
prop.dex+=1;
prop['int']+=1;
prop.str+=1;
}
}
else if(item.p=="glitched")
{
var roll=Math.random();
if(roll<0.33)
{
prop.dex+=1;
}
else if(roll<0.66)
{
prop['int']+=1;
}
else
{
prop.str+=1;
}
}
else if(item.p && G.titles[item.p])
{
for(var p in G.titles[item.p])
if(p in prop)
prop[p]+=G.titles[item.p][p];
}
if(def.upgrade||def.compound)
{
var u_def=def.upgrade||def.compound;
level=item.level||0;
prop.level=level;
for(var i=1;i<=level;i++)
{
var multiplier=1;
if(def.upgrade)
{
if(i==7) multiplier=1.25;
if(i==8) multiplier=1.5;
if(i==9) multiplier=2;
if(i==10) multiplier=3;
if(i==11) multiplier=1.25;
if(i==12) multiplier=1.25;
}
else if(def.compound)
{
if(i==5) multiplier=1.25;
if(i==6) multiplier=1.5;
if(i==7) multiplier=2;
if(i>=8) multiplier=3;
}
for(p in u_def)
{
if(p=="stat") prop[p]+=round(u_def[p]*multiplier);
else prop[p]+=u_def[p]*multiplier; // for weapons with float improvements [04/08/16]
if(p=="stat" && i>=7) prop.stat++;
}
}
}
if(item.level==10 && prop.stat && def.tier && def.tier>=3) prop.stat+=2;
for(p in def)
if(prop[p]===null) prop[p]=def[p];
else if(prop[p]!=undefined) prop[p]+=def[p];
if(item.p=="legacy" && def.legacy)
{
for(var name in def.legacy)
{
if(def.legacy[name]===null) delete prop[name];
else prop[name]=(prop[name]||0)+def.legacy[name];
}
}
for(p in prop)
if(!in_arr(p,["evasion","miss","reflection","dreturn","lifesteal","manasteal","attr0","attr1","crit","critdamage","set","class","breaks"])) prop[p]=round(prop[p]);
if(def.stat && item.stat_type)
{
prop[item.stat_type]+=prop.stat*mult[item.stat_type];
prop.stat=0;
}
// for(p in prop) prop[p]=floor(prop[p]); - round probably came after this one, commenting out [13/09/16]
prop_cache[prop_key]=prop;
return prop;
}
function random_one(arr)
{
if(!is_array(arr)) return random_one(Object.values(arr));
if(!arr.length) return null;
return arr[parseInt(arr.length*Math.random())];
}
function floor_f2(num)
{
return parseInt(num*100)/100.0;
}
function to_pretty_float(num)
{
if(!num) return "0";
var hnum=floor_f2(num).toFixed(2),num=parseFloat(hnum);
if(parseFloat(hnum)==parseFloat(num.toFixed(1))) hnum=num.toFixed(1);
if(parseFloat(hnum)==parseFloat(parseInt(num))) hnum=parseInt(num);
return hnum;
}
function to_pretty_num(num)
{
if(!num) return "0";
num=round(num);
var pretty="";
while(num)
{
var current=num%1000;
if(!current) current="000";
else if(current<10 && current!=num) current="00"+current;
else if(current<100 && current!=num) current="0"+current;
if(!pretty) pretty=current;
else pretty=current+","+pretty;
num=(num-num%1000)/1000;
}
return ""+pretty;
}
function smart_num(num,edge)
{
if(!edge) edge=10000;
if(num>=edge) return to_pretty_num(num);
return num;
}
function to_shrinked_num(num)
{
if(!num) return "0";
num=round(num);
if(num<1000) return ""+num;
var arr=[[1000,"K"],[1000000,"M"],[1000000000,"B"],[1000000000000,"T"]];
for(var i=0;i<arr.length;i++)
{
var current=arr[i];
if(num>=1000*current[0]) continue;
var whole=floor(num/current[0]);
var remainder=floor((num%current[0])/(current[0]/10));
var pretty=whole+"."+remainder;
pretty=pretty.substr(0,3);
if(pretty.endsWith(".00")) pretty=pretty.replace(".00","");
if(pretty.endsWith(".0")) pretty=pretty.replace(".0","");
if(pretty.endsWith(".")) pretty=pretty.replace(".","");
return pretty+current[1];
}
return "LOTS";
}
var valid_file_chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz_-.+ ";
function to_filename(name)
{
var c="",v=valid_file_chars.split("");
(""+name).split("").forEach(function(ch){
if(v.includes(ch)) c+=ch;
})
return c;
}
function e_array(num)
{
var array=[];
for(var i=0;i<num;i++) array.push(null);
return array;
}
function set_xy(entity,x,y)
{
if("real_x" in entity) entity.real_x=x,entity.real_y=y;
else entity.x=x,entity.y=y;
}
function get_xy(e)
{
return [get_x(e),get_y(e)];
}
function get_x(e)
{
if("real_x" in e) return e.real_x;
return e.x;
}
function get_y(e)
{
if("real_y" in e) return e.real_y;
return e.y;
}
function get_width(e) // visual width
{
if(e.proxy_character) return e.awidth;
if("awidth" in e) return e.awidth;
return (e.width||0)/(e.mscale||1);
}
function get_height(e) // visual height
{
if(e.proxy_character) return e.aheight;
if("aheight" in e) return e.aheight;
return (e.height||0)/(e.mscale||1);
}
function simple_distance(a,b)
{
var a_x=get_x(a),a_y=get_y(a),b_x=get_x(b),b_y=get_y(b);
if(a.map && b.map && a.map!=b.map) return 9999999;
return Math.sqrt((a_x-b_x)*(a_x-b_x)+(a_y-b_y)*(a_y-b_y))
}
function calculate_vxy(monster,speed_mult)
{
if(!speed_mult) speed_mult=1;
monster.ref_speed=monster.speed;
var total=0.0001+sq(monster.going_x-monster.from_x)+sq(monster.going_y-monster.from_y);
total=sqrt(total);
monster.vx=monster.speed*speed_mult*(monster.going_x-monster.from_x)/total;
monster.vy=monster.speed*speed_mult*(monster.going_y-monster.from_y)/total;
if(1 || is_game) monster.angle=Math.atan2(monster.going_y-monster.from_y,monster.going_x-monster.from_x)*180/Math.PI; // now the .angle is used on .resync [03/08/16]
// -90 top | 0 right | 180/-180 left | 90 bottom
// if(monster==character) console.log(monster.angle);
}
function recalculate_vxy(monster)
{
if(monster.moving && monster.ref_speed!=monster.speed)
{
if(is_server) monster.move_num++;
calculate_vxy(monster);
}
}
function is_in_front(observer,entity)
{
var angle=Math.atan2(get_y(entity)-get_y(observer),get_x(entity)-get_x(observer))*180/Math.PI;
// console.log(angle+" vs existing "+observer.angle);
if(observer.angle!==undefined && Math.abs(observer.angle-angle)<=45) return true; // drawn at notebook 2, based on those drawings [11/09/16]
return false;
}
function calculate_movex(map, cur_x, cur_y, target_x, target_y) {
if(target_x==Infinity) target_x=CINF;
if(target_y==Infinity) target_y=CINF;
//console.log(cur_x+" "+cur_y+" "+target_x+" "+target_y);
var going_down = cur_y < target_y;
var going_right = cur_x < target_x;
var x_lines = map.x_lines || [];
var y_lines = map.y_lines || [];
var min_x = min(cur_x, target_x);
var max_x = max(cur_x, target_x);
var min_y = min(cur_y, target_y);
var max_y = max(cur_y, target_y);
var dx = target_x - cur_x;
var dy = target_y - cur_y;
var dydx = dy / (dx + REPS);
//console.log(dydx);
var dxdy = 1 / dydx;
var XEPS=10*EPS; // 1 EPS isn't enough, can's move along line[0]+EPS with can_move
for (var i = bsearch_start(x_lines,min_x); i < x_lines.length; i++) {
var line = x_lines[i];
var line_x = line[0],line_xE=line_x+XEPS;
if(going_right) line_xE=line_x-XEPS;
if(max_x < line_x) break;
if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) {
continue;
}
var y_intersect = cur_y + (line_x - cur_x) * dydx;
if(eps_equal(cur_x,target_x) && eps_equal(cur_x,line_x)) // allows you to move parallelly right into the lines
{
line_xE=line_x;
if (going_down) y_intersect=min(line[1],line[2])-XEPS, target_y=min(target_y, y_intersect), max_y = target_y;
else y_intersect=max(line[1],line[2])+XEPS, target_y=min(target_y, y_intersect), min_y = target_y;
continue;
}
if (y_intersect < line[1] || y_intersect > line[2]) {
continue;
}
if (going_down) {
target_y = min(target_y, y_intersect);
max_y = target_y;
} else {
target_y = max(target_y, y_intersect);
min_y = target_y;
}
if (going_right) {
target_x = min(target_x, line_xE); // Can never be directly on the lines themselves
max_x = target_x;
} else {
target_x = max(target_x, line_xE);
min_x = target_x;
}
}
for (var i = bsearch_start(y_lines,min_y); i < y_lines.length; i++) {
var line = y_lines[i];
var line_y = line[0],line_yE=line_y+XEPS;
if(going_down) line_yE=line_y-XEPS;
if(max_y < line_y) break;
if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) {
continue;
}
var x_intersect = cur_x + (line_y - cur_y) * dxdy;
if(eps_equal(cur_y,target_y) && eps_equal(cur_y,line_y))
{
line_yE=line_y;
if (going_right) x_intersect=min(line[1],line[2])-XEPS, target_x=min(target_x, x_intersect), max_x = target_x;
else x_intersect=max(line[1],line[2])+XEPS, target_x=min(target_x, x_intersect), min_x = target_x;
continue;
}
if (x_intersect < line[1] || x_intersect > line[2]) {
continue;
}
if (going_right) {
target_x = min(target_x, x_intersect);
max_x = target_x;
} else {
target_x = max(target_x, x_intersect);
min_x = target_x;
}
if (going_down) {
target_y = min(target_y, line_yE);
max_y = target_y;
} else {
target_y = max(target_y, line_yE);
min_y = target_y;
}
}
// console.log(target_x+" "+target_y);
return {
x: target_x,
y: target_y
};
}
function set_base(entity)
{
var type=entity.mtype||entity.type;
entity.base={h:8,v:7,vn:2};
if(G.dimensions[type] && G.dimensions[type][3])
{
entity.base.h=G.dimensions[type][3];
entity.base.v=min(9.9,G.dimensions[type][4]); // v+vn has to be <12
}
else
{
entity.base.h=min(12,(get_width(entity)||0)*0.80);
entity.base.v=min(9.9,(get_height(entity)||0)/4.0);
if(!entity.base.h) entity.base.h=8,entity.base.v=7;
}
}
function calculate_move_v2(map, cur_x, cur_y, target_x, target_y) // improved, v2 - all movements should originate from cur_x and cur_y
{
if(target_x==Infinity) target_x=CINF;
if(target_y==Infinity) target_y=CINF;
var move=calculate_movex(map, cur_x, cur_y, target_x, target_y);
if(move.x!=target_x && move.y!=target_y) // this is a smooth move logic - if a line hit occurs, keeps moving in the movable direction
{
var move2=calculate_movex(map, cur_x,cur_y, target_x, move.y);
if(move2.x==move.x)
{
var move2=calculate_movex(map, cur_x,cur_y, move2.x, target_y);
}
return move2;
}
// return move_further(cur_x,cur_y,move.x,move.y,100);
return move;
}
var m_calculate=false,m_line_x=false,m_line_y=false,line_hit_x=null,line_hit_y=null,m_dx,m_dy; // flags so can_calculate and can_move work in synergy
function calculate_move(entity,target_x,target_y) // v5, calculate 4 edges, choose the minimal move [18/07/18]
{
// -8,+8 left/right 0,-7 down/up
m_calculate=true;
var map=entity.map,cur_x=get_x(entity),cur_y=get_y(entity);
var corners=[[0,0]];
var moves=[[target_x,target_y]],x_moves=[];
if(entity.base) corners=[[-entity.base.h,entity.base.vn],[entity.base.h,entity.base.vn],[-entity.base.h,-entity.base.v],[entity.base.h,-entity.base.v]];
// Test the movement limits of all 4 corners of an entity, and record the [mmx,mmy] at the limit
corners.forEach(function(mxy){
for(var i=0;i<3;i++)
{
var mx=mxy[0],my=mxy[1];
var dx=target_x+mx,dy=target_y+my;
if(i==1) dx=cur_x+mx;
if(i==2) dy=cur_y+my;
var cmove=calculate_movex(G.geometry[map]||{},cur_x+mx,cur_y+my,dx,dy);
var cdist=point_distance(cur_x+mx,cur_y+my,cmove.x,cmove.y);
// add_log(cdist,"orange");
mx=cmove.x-mx;
my=cmove.y-my;
// add_log("mx/y: "+mx+","+my);
if(!in_arrD2([mx,my],moves)) moves.push([mx,my]);
// New logic, just check all possibilities, original logic just checked the min cdist
// Sometimes the minimum move is just a stuck corner in another move angle, so all possibilities need to be checked
// if(Math.abs(mx-round(mx))<40*EPS && !in_arrD2([mx,cur_y],moves)) moves.push([mx,cur_y]);
// x- if(Math.abs(mx-round(mx))<40*EPS && !in_arrD2([mx,target_y],moves) || 1) moves.push([mx,target_y]);
// if(Math.abs(my-round(my))<40*EPS && !in_arrD2([cur_x,my],moves)) moves.push([cur_x,my]);
// x- if(Math.abs(my-round(my))<40*EPS && !in_arrD2([target_x,my],moves) || 1) moves.push([target_x,my]);
}
});
// console.log(moves);
var max=-1,move={x:cur_x,y:cur_y},min=CINF;
// Test all boundary coordinates, if none of them work, don't move
function check_move(xy)
{ // This is the smooth move logic, even if you hit a line, you might still move along that line
var x=xy[0],y=xy[1];
if(can_move({map:map,x:cur_x,y:cur_y,going_x:x,going_y:y,base:entity.base}))
{
// var cdist=point_distance(cur_x,cur_y,x,y);
// if(cdist>max)
// {
// max=cdist;
// move={x:x,y:y};
// }
var cdist=point_distance(target_x,target_y,x,y);
// #IDEA: If the angle difference between intended angle, and move angle is factored in too, the selected movement could be the most natural one [20/07/18]
if(cdist<min)
{
min=cdist;
move={x:x,y:y};
}
}
if(line_hit_x!==null) x_moves.push([line_hit_x,line_hit_y]),line_hit_x=null,line_hit_y=null;
}
moves.forEach(check_move);
// console.log(x_moves);
x_moves.forEach(check_move);
//add_log("Intention: "+target_x+","+target_y);
//add_log("Calculation: "+move.x+","+move.y+" ["+max+"]");
//add_log(point_distance(cur_x,cur_y,move.x,move.y),"#FC5066");
if(point_distance(cur_x,cur_y,move.x,move.y)<10*EPS) move={x:cur_x,y:cur_y}; // The new movement has a bouncing effect, so for small moves, just don't move
m_calculate=false;
return move;
}
// Why are there so many imperfect, mashed up movement routines? [17/07/18]
// First of all there is no order to lines, the map maker inserts lines randomly, so they are not polygons etc.
// Even if they were polygons, there are non-movable regions inside movable regions
// So all in all, the game evolved into a placeholder, non-perfect, not well-thought line system, that became permanent
// One other challenge is visuals, the x,y of entities and their bottom points, so if they move too close to the lines, the game doesn't look appealing
// Anyway, that's pretty much what's going on here, the latest iterations are pretty complex in a bad way, but they account for all the issues and challenges, include improvements
// If there's even a slightest mismatch, any edge case not handled, it will cause a player or monster to walk out the lines, be jailed, and mess up the game
// [19/07/18] - Finally solved all the challenges, by considering entities as 4 cornered rectangles, and making sure all 4 corners can move
// Caveats of the 4-corner - if there's a single line, for example a fence line, the player rectangle can be penetrated
function point_distance(x0,y0,x1,y1)
{
return Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0))
}
function recalculate_move(entity)
{
move=calculate_move(entity,entity.going_x,entity.going_y);
entity.going_x=move.x;
entity.going_y=move.y;
}
function bsearch_start(arr,value)
{
var start=0,end=arr.length-1,current;
while(start<end-1)
{
current=parseInt((start+end)/2);
if(arr[current][0]<value) start=current;
else end=current-1;
}
// while(start<arr.length && arr[start][0]<value) start++;
// If this line is added, some of the can_move + calculate_movex conditions can be removed [19/07/18]
return start;
}
function base_points(x,y,base)
{
return [[x-base.h,y+base.vn],[x+base.h,y+base.vn],[x-base.h,y-base.v],[x+base.h,y-base.v]];
}
function can_move(monster,based)
{
// An XY-tree would be ideal, but the current improvements should be enough [16/07/18]
var GEO=G.geometry[monster.map]||{},c=0;
var x0=monster.x,y0=monster.y,x1=monster.going_x,y1=monster.going_y,next,minx=min(x0,x1),miny=min(y0,y1),maxx=max(x0,x1),maxy=max(y0,y1);
if(!based && monster.base) // If entity is a rectangle, check all 4 corner movements
{
var can=true;
[[-monster.base.h,monster.base.vn],[monster.base.h,monster.base.vn],[-monster.base.h,-monster.base.v],[monster.base.h,-monster.base.v]].forEach(function(mxy){
var mx=mxy[0],my=mxy[1];
if(!can || !can_move({map:monster.map,x:x0+mx,y:y0+my,going_x:x1+mx,going_y:y1+my},1)) can=false;
});
if(1) // fence logic, orphan lines - at the destination, checks whether we can move from one rectangle point to the other, if we can't move, it means a line penetrated the rectangle
{ // [20/07/18]
var px0=monster.base.h,px1=-monster.base.h; m_line_x=max;// going left
if(x1>x0) px0=-monster.base.h,px1=monster.base.h,mcy=m_line_x=min; // going right
var py0=monster.base.vn,py1=-monster.base.v; m_line_y=max; // going up
if(y1>y0) py0=-monster.base.v,py1=monster.base.vn,m_line_y=min; // going down
m_dx=-px1; m_dy=-py1; // Find the line hit, then convert to actual coordinates
if(!can || !can_move({map:monster.map,x:x1+px1,y:y1+py0,going_x:x1+px1,going_y:y1+py1},1)) can=false;
if(!can || !can_move({map:monster.map,x:x1+px0,y:y1+py1,going_x:x1+px1,going_y:y1+py1},1)) can=false;
m_line_x=m_line_y=false;
}
return can;
}
function line_hit_logic(ax,ay,bx,by)
{
line_hit_x=m_line_x(ax,bx),line_hit_x=m_line_x(line_hit_x+6*EPS,line_hit_x-6*EPS)+m_dx;
line_hit_y=m_line_y(ay,by),line_hit_y=m_line_y(line_hit_y+6*EPS,line_hit_y-6*EPS)+m_dy;
}
for(var i=bsearch_start(GEO.x_lines||[],minx);i<(GEO.x_lines||[]).length;i++)
{
if(is_server) perfc.roam_ops+=1;
var line=GEO.x_lines[i]; // c++;
if(line[0]==x1 && (line[1]<=y1 && line[2]>=y1 || line[0]==x0 && y0<=line[1] && y1>line[1])) // can't move directly onto lines - or move over lines, parallel to them
{
if(m_line_y) line_hit_logic(line[0],line[1],line[0],line[2]);
return false;
}
if(minx>line[0]) continue; // can be commented out with: while(start<arr.length && arr[start][0]<value) start++;
if(maxx<line[0]) break; // performance improvement, we moved past our range [16/07/18]
next=y0+(y1-y0)*(line[0]-x0)/(x1-x0+REPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue; // Fixed EPS [16/07/18]
//add_log("line clash")
if(m_line_y) line_hit_logic(line[0],line[1],line[0],line[2]);
return false;
}
for(var i=bsearch_start(GEO.y_lines||[],miny);i<(GEO.y_lines||[]).length;i++)
{
if(is_server) perfc.roam_ops+=1;
var line=GEO.y_lines[i]; // c++;
if(line[0]==y1 && (line[1]<=x1 && line[2]>=x1 || line[0]==y0 && x0<=line[1] && x1>line[1]))
{
if(m_line_x) line_hit_logic(line[1],line[0],line[2],line[0]);
return false;
}
if(miny>line[0]) continue;
if(maxy<line[0]) break;
next=x0+(x1-x0)*(line[0]-y0)/(y1-y0+REPS);
if(!(line[1]-EPS<=next && next<=line[2]+EPS)) continue;
if(m_line_x) line_hit_logic(line[1],line[0],line[2],line[0]);
return false;
}
// console.log(c);
return true;
}
function closest_line(map,x,y)
{
var min=16000;
[[0,16000],[0,-16000],[16000,0],[-16000,0]].forEach(function(mxy){
var mx=mxy[0],my=mxy[1];
var move=calculate_move({map:map,x:x,y:y},x+mx,y+my);
// console.log(move);
var cdist=point_distance(x,y,move.x,move.y);
if(cdist<min) min=cdist;
});
return min;
}
function unstuck_logic(entity) // handles the case where you can blink onto a line
{
if(!can_move({map:entity.map,x:get_x(entity),y:get_y(entity),going_x:get_x(entity),going_y:get_y(entity)+EPS/2,base:entity.base}))
{
var fixed=false;
if(can_move({map:entity.map,x:get_x(entity),y:get_y(entity)+8.1,going_x:get_x(entity),going_y:get_y(entity)+8.1+EPS/2,base:entity.base}))
{
set_xy(entity,get_x(entity),get_y(entity)+8.1); fixed=true;
}
else if(can_move({map:entity.map,x:get_x(entity),y:get_y(entity)-8.1,going_x:get_x(entity),going_y:get_y(entity)-8.1-EPS/2,base:entity.base}))
{
set_xy(entity,get_x(entity),get_y(entity)-8.1); fixed=true;
}
if(!fixed) console.log("#CRITICAL: Couldn't fix blink onto line issue");
else console.log("Blinked onto line, fixed");
}
}
function stop_logic(monster)
{
if(!monster.moving) return;
var x=get_x(monster),y=get_y(monster);
// old: if((monster.from_x<=monster.going_x && x>=monster.going_x) || (monster.from_x>=monster.going_x && x<=monster.going_x) || abs(x-monster.going_x)<0.3 || abs(y-monster.going_y)<0.3)
if(((monster.from_x<=monster.going_x && x>=monster.going_x-0.1) || (monster.from_x>=monster.going_x && x<=monster.going_x+0.1)) &&
((monster.from_y<=monster.going_y && y>=monster.going_y-0.1) || (monster.from_y>=monster.going_y && y<=monster.going_y+0.1)))
{
set_xy(monster,monster.going_x,monster.going_y);
//monster.going_x=undefined; - setting these to undefined had bad side effects, where a character moves in the client side, stops in server, and going_x becoming undefined mid transit client side [18/06/18]
//monster.going_y=undefined;
if(monster.loop)
{
monster.going_x=monster.positions[(monster.last_m+1)%monster.positions.length][0];
monster.going_y=monster.positions[(++monster.last_m)%monster.positions.length][1];
monster.u=true;
start_moving_element(monster);
return;
}
monster.moving=monster.amoving||false;
monster.vx=monster.vy=0; // added these 2 lines, as the character can walk outside when setTimeout ticks at 1000ms's [26/07/16]
// if(monster.me) console.log(monster.real_x+","+monster.real_y);
if(monster.name_tag) stop_name_tag(monster);
if(monster.me)
{
resolve_deferreds("move",{reason:"stopped"});
showhide_quirks_logic();
}
}
}
function is_door_close(map,door,x,y)
{
var def=G.maps[map],spawn=def.spawns[door[6]];
if(point_distance(x,y,spawn[0],spawn[1])<40)
return true;
if(distance({x:x,y:y,width:26,height:35},{x:door[0],y:door[1],width:door[2],height:door[3]})<40)
return true;
return false;
}
function can_use_door(map,door,x,y) // this one is costly, so only check when is_door_close [14/09/18]
{
var def=G.maps[map],spawn=def.spawns[door[6]];
if(point_distance(x,y,spawn[0],spawn[1])<40 && can_move({map:map,x:x,y:y,going_x:spawn[0],going_y:spawn[1]}))
{
//console.log("SPAWNACCESS"+spawn);
return true;
}
if(distance({x:x,y:y,width:26,height:35},{x:door[0],y:door[1],width:door[2],height:door[3]})<40)
{
var can=false;
[
[0,0],
[-door[2]/2,0],
[door[2]/2,0],
[-door[2]/2,-door[3]],
[door[2]/2,-door[3]],
[0,-door[3]],
].forEach(function(mxy){
var mx=mxy[0],my=mxy[1];
if(can_move({map:map,x:x,y:y,going_x:door[0]+mx,going_y:door[1]+my}))
{
//console.log("DOORLINEACCESS"+(door[0]+mx)+","+(door[1]+my));
can=true;
}
})
if(can) return true;
}
return false;
}
function is_point_inside(p,polygon)
{
var isInside = false;
var minX = polygon[0][0], maxX = polygon[0][0];
var minY = polygon[0][1], maxY = polygon[0][1];
for (var n = 1; n < polygon.length; n++) {
var q = polygon[n];
minX = Math.min(q[0], minX);
maxX = Math.max(q[0], maxX);
minY = Math.min(q[1], minY);
maxY = Math.max(q[1], maxY);
}
if (p[0] < minX || p[0] > maxX || p[1] < minY || p[1] > maxY) {
return false;
}
var i = 0, j = polygon.length - 1;
for (i, j; i < polygon.length; j = i++) {
if ( (polygon[i][1] > p[1]) != (polygon[j][1] > p[1]) &&
p[0] < (polygon[j][0] - polygon[i][0]) * (p[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0] ) {
isInside = !isInside;
}
}
return isInside;
}
function random_point(polygon,base)
{
var minX = polygon[0][0], maxX = polygon[0][0];
var minY = polygon[0][1], maxY = polygon[0][1];
var defX = polygon[0][0], defY = polygon[0][1]
for (var n = 1; n < polygon.length; n++) {
var q = polygon[n];
if(q[0] < minX || q[0]==minX && q[1]>defY)
{
}
maxX = Math.max(q[0], maxX);
minY = Math.min(q[1], minY);
maxY = Math.max(q[1], maxY);
}
for(var i=0;i<200;i++)
{
var rX=minX+Math.random()*(maxX-minX);
var rY=minY+Math.random()*(maxY-minY);
if(is_point_inside([rX,rY],polygon))
{
var valid=true;
if(base)
base_points(rX,rY,base).forEach(function(xy){
if(!is_point_inside([xy[0],xy[1]],polygon)) valid=false;
})
if(valid) return [rX,rY];
}
}
if(base) return [defX,defY];
return [defX,defY];
}
function trigger(f)
{
setTimeout(f,0);
}
function to_number(num)
{
try{
num=round(parseInt(num));
if(num<0) return 0;
if(!num) num=0;
}catch(e){num=0};
return num;
}
function is_nun(a)
{
if(a===undefined || a===null) return true;
return false;
}
function nunv(a,b)
{
if(a===undefined || a===null) return b;
return a;
}
function is_number(obj)
{
try{
if(!isNaN(obj) && 0+obj===obj) return true;
}catch(e){}
return false;
}
function is_string(obj)
{ try{
return Object.prototype.toString.call(obj) == '[object String]';
} catch(e){} return false; }
function is_array(a)
{ try{
if (Array.isArray(a)) return true;
} catch(e){} return false; }
function is_function(f)
{ try{
var g = {};
return f && g.toString.call(f) === '[object Function]';
} catch(e){} return false; }
function is_object(o)
{ try{
return o!==null && typeof o==='object';
} catch(e){} return false; }
function clone(obj,args) {
// http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
if(!args) args={};
if(!args.seen && args.seen!==[]) args.seen=[]; // seen modification - manual [24/12/14]
if(null == obj) return obj;
if(args.simple_functions && is_function(obj)) return "[clone]:"+obj.toString().substring(0,40);
if ("object" != typeof obj) return obj;
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
if (obj instanceof Array) {
args.seen.push(obj);
var copy = [];
for (var i = 0; i < obj.length; i++) {
copy[i] = clone(obj[i],args);
}
return copy;
}
if (obj instanceof Object) {
args.seen.push(obj);
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr))
{
if(args.seen.indexOf(obj[attr])!==-1) { copy[attr]="circular_attribute[clone]"; continue; }
copy[attr] = clone(obj[attr],args);
}
}
return copy;
}
throw "type not supported";
}
function safe_stringify(obj,third) // doesn't work for Event's - clone also doesn't work [31/08/15]
{
var seen = [];
try{
if(obj===undefined) return "undefined";
var result=JSON.stringify(obj, function(key, val) {
if (val != null && typeof val == "object") {
if (seen.indexOf(val) >= 0) {
return;
}
seen.push(val);
if("x" in val) // amplify - also in functions.js game_stringify
{
var new_val={};
["x","y","width","height"].forEach(function(p){
if(p in val) new_val[p]=val[p];
});
for(var p in val) new_val[p]=val[p];
val=new_val;
}
}
return val;
},third);
try{
if("x" in obj) // amplify - also in functions.js game_stringify
{
result=JSON.parse(result);
result.x=obj.x;
result.y=obj.y;
result=JSON.stringify(result);
}
}catch(e){}
return result;
}
catch(e)
{
return "safe_stringify_exception";
}
}
function smart_eval(code,args)
{
// window[cur.func] usages might execute the corresponding string and cause an exception - highly unlikely [22:32]
if(!code) return;
if(args && !is_array(args)) args=[args];
if(is_function(code))
{
if(args) code.apply(this,clone(args)); // if args are not cloned they persist and cause irregularities like mid persistence [02/08/14]
else code();
}
else if(is_string(code)) eval(code);
}
function is_substr(a,b)
{
if(is_array(b))
{
for(var i=0;i<b.length;i++)
{
try{ if(a && a.toLowerCase().indexOf(b[i].toLowerCase())!=-1) return true; } catch(e){}
}
}
else{
try{ if(a && a.toLowerCase().indexOf(b.toLowerCase())!=-1) return true; } catch(e){}
}
return false;
}
function seed0() // as a semi-persistent seed
{
return parseInt((new Date()).getMinutes()/10.0)
}
function seed1() // as a semi-persistent seed
{
return parseInt((new Date()).getSeconds()/10.0)
}
function to_title(str)
{
return str.replace(/\w\S*/g,function(txt){return txt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase();});
}
function ascending_comp(a, b)
{
return a-b;
}
function delete_indices(array,to_delete)
{
to_delete.sort(ascending_comp);
for (var i=to_delete.length-1;i>=0;i--)
array.splice(to_delete[i],1);
}
function array_delete(array,entity) // keywords: remove, from
{
var index=array.indexOf(entity);
if (index > -1) {
array.splice(index, 1);
}
}
function in_arr(i,kal)
{
if(is_array(i))
{
for(var j=0;j<i.length;j++)
for(var el in kal) if(i[j]===kal[el]) return true;
}
for(var el in kal) if(i===kal[el]) return true;
return false;
}
function in_arrD2(el,arr)
{
for(var i=0;i<arr.length;i++)
{
if(el[0]==arr[i][0] && el[1]==arr[i][1]) return true;
}
return false;
}
function c_round(n)
{
if(window.floor_xy) return Math.floor(n);
if(!window.round_xy) return n;
return Math.round(n);
}
function round_float(f)
{
return Math.round(f*100)/100;
}
rf=round_float;
function round(n)
{
return Math.round(n);
}
function sq(n)
{
return n*n;
}
function sqrt(n)
{
return Math.sqrt(n);
}
function floor(n)
{
return Math.floor(n);
}
function ceil(n)
{
return Math.ceil(n);
}
function eps_equal(a,b)
{
return Math.abs(a-b)<5*EPS;
}
function abs(n)
{
return Math.abs(n);
}
function min(a,b)
{
return Math.min(a,b);
}
function max(a,b)
{
return Math.max(a,b);
}
function shuffle(a)
{
var j, x, i;
for (i = a.length;i;i--)
{
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
return a;
}
function cshuffle(a)
{
var b=a.slice();
shuffle(b);
return b;
}
function random_binary()
{
var s="";
for(var i=0;i<2+parseInt(Math.random()*12);i++)
{
if(Math.random()<0.5) s+="0";
else s+="1";
}
return s;
}
function random_binaries()
{
var s="";
for(var i=0;i<7+parseInt(Math.random()*23);i++)
{
s+=random_binary()+" ";
}
return s;
}
function randomStr(len) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",schars="ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var str = '';
for (var i=0; i<len; i++) {
if(i==0)
{
var rnum = Math.floor(Math.random() * schars.length);
str += schars.substring(rnum,rnum+1);
}
else
{
var rnum = Math.floor(Math.random() * chars.length);
str += chars.substring(rnum,rnum+1);
}
}
return str;
}
function lstack(arr,el,limit) // used for logging purposes, last entry becomes first element
{
arr.unshift(el);
while(arr.length>limit) arr.pop();
}
String.prototype.toTitleCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
String.prototype.replace_all = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
function html_escape(html)
{
var escaped = ""+html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]];
for(var item in findReplace)
escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);
return escaped;
}
/*"*/
function he(html){return html_escape(html);}
function future_ms(ms)
{
var c=new Date();
c.setMilliseconds(c.getMilliseconds()+ms);
return c;
}
function future_s(s)
{
var c=new Date();
c.setSeconds(c.getSeconds()+s);
return c;
}
function future_m(m)
{
return future_s(60*m);
}
function future_h(h)
{
return future_m(60*h);
}
function mssince(t,ref)
{
if(!ref) ref=new Date();
return ref.getTime() - t.getTime();
}
function ssince(t,ref) { return mssince(t,ref)/1000.0; }
function msince(t,ref) { return mssince(t,ref)/60000.0; }
function hsince(t,ref) { return mssince(t,ref)/3600000.0; }
function sleep(ms)
{
return new Promise(resolve=>setTimeout(resolve,ms));
}
function log_trace(place,err)
{
console.log('\n====================');
if(typeof err==='object')
{
if(err.message) console.log('Exception['+place+']:\n'+err.message);
if (err.stack)
{
console.log('Stacktrace:');
//console.log('====================');
console.log(err.stack);
//console.log(Object.keys(err.stack));
}
}
else console.log('log_trace: argument is not an object on :'+place);
console.log('====================\n');
}
var TYPE_MIN = 'min';
var TYPE_MAX = 'max';
function Heap(array, type, compareFunction) {
// https://gist.github.com/fabianuribe/5eeeaf5370d03f66f739
var x={
buildHeap: function () {
var last = this.array.length - 1;
var middle = Math.floor(last/2);
var i;
for (i = middle; i >= 0; i -= 1) {
this._heapify(i);
}
},
sort: function () {
var limit = this._getLastIdx();
while (limit > 0) {
this._swap(0, limit);
limit -= 1;
if (limit) {
this._heapify(0, limit);
}
}
},
insert: function (element) {
this.array.push(element);
this._bubbleUp(this._getLastIdx());
},
removeTop: function () {
var top = this.array[0];
this._swap(0, this._getLastIdx());
this.array.pop();
this._heapify(0);
return top;
},
defaultCompareFunction: function (a, b) {
if (a > b) {
return 1;
}
if (b > a) {
return -1;
}
return 0;
},
_heapify: function (startIdx, limitIdx) {
limitIdx = limitIdx || this._getLastIdx();
var topIdx = startIdx;
var top = this.array[topIdx];
var leftIdx = this._getLeftChild(startIdx, limitIdx);
var rightIdx = this._getRightChild(startIdx, limitIdx);
var left = leftIdx && this.array[leftIdx];
var right = rightIdx && this.array[rightIdx];
if (startIdx > limitIdx) {
return;
}
if (left &&
((this.type === TYPE_MIN && this.compare(left, top) < 0) ||
(this.type === TYPE_MAX && this.compare(left, top) > 0))) {
topIdx = leftIdx;
top = left;
}
if (right &&
((this.type === TYPE_MIN && this.compare(right, top) < 0) ||
(this.type === TYPE_MAX && this.compare(right, top) > 0))) {
topIdx = rightIdx;
top = right;
}
if (startIdx !== topIdx) {
this._swap(startIdx, topIdx);
this._heapify(topIdx, limitIdx);
}
},
_swap: function (a, b) {
var temp = this.array[a];
this.array[a] = this.array[b];
this.array[b] = temp;
},
_bubbleUp: function(index) {
var parentIdx = this._getParent(index);
var parent = (parentIdx >= 0) ? this.array[parentIdx] : null;
var value = this.array[index];
if (parent === null) {
return;
}
if ((this.type === TYPE_MIN && this.compare(value, parent) < 0) ||
(this.type === TYPE_MAX && this.compare(value, parent) > 0)) {
this._swap(index, parentIdx);
this._bubbleUp(parentIdx);
}
},
_getLeftChild: function (parent, limit) {
limit = limit || this._getLastIdx();
var childIndex = parent * 2 + 1;
return (childIndex <= limit) ? childIndex : null;
},
_getRightChild: function (parent, limit) {
limit = limit || this._getLastIdx();
var childIndex = parent * 2 + 2;
return (childIndex <= limit) ? childIndex : null;
},
_getParent: function (index) {
if (index % 2) {
// Is left child
return (index - 1)/2;
}
// Is right child
return (index/2) - 1;
},
_getLastIdx: function () {
var size = this.array.length;
return size > 1 ? size - 1 : 0;
}
};
x.array = array || [];
x.type = type === TYPE_MIN ? TYPE_MIN : TYPE_MAX;
x.compare = (typeof compareFunction === 'function') ? compareFunction : this.defaultCompareFunction;
x.buildHeap();
return x;
}
function vHeap()
{
return Heap([],'min',function (a, b) {
if (a.value > b.value) {
return 1;
}
if (b.value > a.value) {
return -1;
}
return 0;
});
}
// try{
// asadasdasd=asdasdda;
// }
// catch(e){log_trace("test",e);}
function rough_size( object ) {
//reference: http://stackoverflow.com/a/11900218/914546
var objectList = [];
var stack = [ object ];
var bytes = 0;
while ( stack.length ) {
var value = stack.pop();
if ( typeof value === 'boolean' ) {
bytes += 4;
}
else if ( typeof value === 'string' ) {
bytes += value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes += 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList.push( value );
for( var i in value ) {
stack.push( value[ i ] );
}
}
}
return bytes;
} |
const ffixFactory = (name, age, quote) => {
return {
name: name,
age: age,
quote: quote
}
};
const tZidane = ffixFactory('Zidane Tribal', 16, 'You don\'t need a reason to help people.');
const aGarnet = ffixFactory('Garnet Til Alexandros XVII', 16, 'Someday I will be queen, but I will always be myself.');
const oVivi = ffixFactory('Vivi Ornitier', 9, 'How do you prove that you exist...? Maybe we don\'t exist...');
const aSteiner = ffixFactory('Adelbert Steiner', 33, 'Having sworn fealty, must I spend my life in servitude?');
const cAmarant = ffixFactory('Amarant Coral', 26, 'The only dependable thing about the future is uncertainty.');
const cFreya = ffixFactory('Freya Crescent', 21, 'To be forgotten is worse than death.');
const qQuina = ffixFactory('Quina Quen', 89, 'I do what I want! You have problem!?');
const cEiko = ffixFactory('Eiko Carol', 6, 'I don\'t wanna be alone anymore...');
const tKuja = ffixFactory('Kuja', 24, 'The weak lose their freedom to the strong. Such is the way of the strong. And it is the providence of nature that only the strong survive. That is why I needed strength.');
const charLookup = {
Zidane:tZidane,
Garnet:aGarnet,
}
$('#games button').on('click',function(e){
var characterClicked = $(e.target).attr('Character');
var lookup = charLookup[characterClicked];
$('#quoteBox').removeClass('hidden');
$('#charName').html(lookup.name);
$('#charAge').html(lookup.age);
$('#charQuote').html(lookup.quote);
}) |
var socket = io.connect('http://' + location.host, {
'max reconnection attempts': 100000
});
var rColor = new RColor();
var roomContents = {};
var usernameColors = {};
function playSound(name, volume) {
if (settings[name] == null) return;
var audio = new Audio('/sounds/' + settings[name] + '.mp3');
if (volume) audio.volume = volume;
audio.play();
}
// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
if (localStorage.name == null) {
localStorage.name = prompt("What's your name?");
}
if (localStorage.settings == null) localStorage.settings = "{}";
socket.emit('adduser', localStorage.name || "Anonymous");
//updateCharList();
});
// Register an event on error with the Socket.IO connection
socket.on('error', function (error) {
console.log('error from socket', error);
if (error == 'handshake error') {
notAuthorized();
return;
}
if (typeof(error) != 'string') error = 'Something bad happened on the server';
var html =[];
html.push('<div class="alert alert-warning alert-dismissable">');
html.push('<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>');
html.push('<strong>Error!</strong> ' + error);
html.push('</div>');
$('#content').append(html.join(''));
});
//Connection failure
function notAuthorized() {
var html =[];
html.push('<div class="authorization-error alert alert-warning alert-dismissable">');
html.push('<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>');
html.push('<strong>Warning!</strong> No session found. Logging in...');
html.push('</div>');
$('#content').append(html.join(''));
$.get('/login', function(data) {
$('.authorization-error .close').click();
// When login is done, we need to reconnect to the socket
// If we don't reconnect, the browser will not restart the handshake with the Socket.IO server
socket.socket.reconnect();
});
}
// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', processMessage);
function getUsernameColor(username) {
if (usernameColors[username] != null) return usernameColors[username];
usernameColors[username] = rColor.get(true, 0.95, 0.95);
return usernameColors[username];
}
function getMessageHtml(data) {
var html = [ '<div>'];
html.push('<span class="dateTime">(' + (data.time || new Date().toLocaleTimeString()) + ')</span> ');
var style = '';
if (getSetting('usernameColors') == 'on') {
var color = getUsernameColor(data.user);
//var color = hex_md5(data.user);
// color = color.substr(0,6)
//color = parseInt(color.substr(0,6), 16);
//color = parseFloat("0." + color);
//color = rColor.get(true, 0.5, 0.95, color);
style += 'color: ' + color + ';';
//rColor.get(true, 0.25, 0.8, parseFloat("0." + parseInt(hex_md5(data.user).substr(4,8), 16)))
}
if (data.impersonate != null && data.impersonate.length > 0) {
html.push('<span class="user impersonated" title="Impersonated by ' + data.user + '" style="' + style + '">' + data.impersonate + '</span>');
}
else {
html.push('<span class="user" style="' + style + '">' + data.user + '</span>');
}
if (data.emote == null || data.emote == false) html.push(':');
html.push(' ');
html.push('<span class="message');
if (data.messageClass != null) html.push(' ' + data.messageClass);
html.push('">');
if (data.message == null)
html.push(data);
else
html.push(prettify(data.message));
html.push('</span>');
html.push('</div>');
return html.join('');
}
function processMessage(data) {
var html = getMessageHtml(data);
document.title = data.user + ' says...';
setTimeout(function(){ document.title = settings.defaultTitle;}, 2000);
var roomContentsDiv = $('#chatList .roomContents');
if (roomContents[data.room] == null) {
roomContents[data.room] = $('<div class="roomContents" data-room-id="' + data.room + '" />');
console.log("Unknown room!");
}
roomContents[data.room].append(html);
if(roomContentsDiv.length == 0) {
switchToRoom(data.room);
} else if (data.silent == null && $('#chatList .roomContents').attr('data-room-id') != data.room) {
$('#rooms [data-id="' + data.room +'"]').addClass('hasNew');
}
if ($('#autoScrollButton').hasClass('glyphicon-play')) {
roomContentsDiv.prop('scrollTop', roomContentsDiv.prop('scrollHeight'));
}
if (!$('#toggleAudio').hasClass('glyphicon-volume-off')){
var volume = $('#toggleAudio').hasClass('glyphicon-volume-up') ? 1 : 0.33;
playSound('soundReceive', volume);
}
}
// listener, whenever the server emits 'updaterooms', this updates the room the client is in
socket.on('updaterooms', function(rooms, joined_rooms) {
var html = [];
$.each(rooms, function(key, value) {
if (roomContents[value] == null) roomContents[value] = $('<div class="roomContents" data-room-id="' + value + '" />');
html.push('<div data-id="' + value + '" class="');
if (~joined_rooms.indexOf(value)){
html.push('joined');
}
html.push('"><span class="roomName">' + value + '</span><span class="roomIndicator"></span></div>');
});
$('#rooms').html(html.join(''));
if ($('#rooms .selected').length == 0) $('#rooms>div:first-child .roomName').click();
});
socket.on('updatebacklog', function(backlog){
var currentRoom = $('#chatList .roomContents').attr('data-room-id');
var html = {};
for(var r in roomContents) {
if (!roomContents.hasOwnProperty(r) || roomContents[r] == null) continue;
roomContents[r].empty();
html[r] = [];
}
for(var c = 0, l = backlog.length; c < l; c++) {
if (backlog[c].room != null && html[backlog[c].room] != null) html[backlog[c].room].push(getMessageHtml(backlog[c]));
}
for (var room in html) {
if (html.hasOwnProperty(room)) roomContents[room].append(html[room].join(''));
}
currentRoom = currentRoom || $('#rooms>div:first-child').attr('data-id');
if (currentRoom != null && currentRoom != '') switchToRoom(currentRoom);
});
socket.on('updateusers', function(users) {
var html = [];
$.each(users, function(key, value){
html.push('<div>' + value + '</div>');
});
$('#onlineList').html(html);
});
function joinRoom(room){
socket.emit('joinRoom', room);
}
function leaveRoom(room){
socket.emit('leaveRoom', room);
}
function switchToRoom(room){
$('#rooms [data-id="' + room + '"]').addClass('selected').removeClass('hasNew').siblings().removeClass('selected');
$('#chatList .roomContents').detach();
$('#chatList').append(roomContents[room]);
if ($('#autoScrollButton').hasClass('glyphicon-play')) {
$('#chatList .roomContents').prop('scrollTop', $('#chatList .roomContents').prop('scrollHeight'));
}
}
function prettify(message) {
var regex = new RegExp("<(?!\\s*\\/?(i|b|u|s|strong|sub)\\b)[^>]+>","gi"),
linkRegex = /([^ ]*:\/\/[^ ]*)/ig,
result = message.replace(regex, '');
result = result.replace(linkRegex, '<a href="$1" target="_blank">$1</a> ');
// /(<\/?[a|b|i|br]( [^>]*)?>)/ig - regex for matching tags including a
return result;
}
function sendMessage() {
var message = $('#inputField').val();
$('#inputField').val('');
if (message == null || message.length == 0) return;
var impersonate = $('#impersonateAs').val();
var room = $('#rooms .selected').attr('data-id');
// tell server to execute 'sendchat' and send along one parameter
socket.emit('sendchat', room, {
message: message,
impersonate: impersonate
});
}
function updateCharList() {
$('#charList').empty();
$('#charList').append('<option>' + localStorage.name + '</option>');
if (localStorage.characters != null && localStorage.characters.length > 0) {
$.each(localStorage.characters.split(','), function(name){
$('#charList').append('<option>' + name + '</option>');
});
}
}
function setHideRooms(val) {
if (val == 'on') $('body').addClass('no-rooms');
else $('body').removeClass('no-rooms');
}
function setHideUsers(val) {
if (val == 'on') $('body').addClass('no-users');
else $('body').removeClass('no-users');
}
// on load of page
$(function(){
// when the client clicks SEND
$('#submitButton').click(sendMessage);
// For room links
$('#rooms').on('click', '.roomIndicator', function(){
var room = $(this).parent().attr('data-id');
if($(this).parent().hasClass('joined')) {
leaveRoom(room);
} else {
joinRoom(room);
}
});
$('#rooms').on('click', '.roomName', function(){
var room = $(this).parent().attr('data-id');
if(!$(this).parent().hasClass('joined')) joinRoom(room);
switchToRoom(room);
});
$('#autoScrollButton').on('click', function(){
if ($(this).hasClass('glyphicon-play')){
$(this).removeClass('glyphicon-play').addClass('glyphicon-stop');
} else {
$(this).addClass('glyphicon-play').removeClass('glyphicon-stop');
}
});
$('#toggleAudio').on('click', function(){
if ($(this).hasClass('glyphicon-volume-up')){
$(this).removeClass('glyphicon-volume-up').addClass('glyphicon-volume-down');
setSetting('volume', 'low');
} else if($(this).hasClass('glyphicon-volume-down')) {
$(this).removeClass('glyphicon-volume-down').addClass('glyphicon-volume-off');
setSetting('volume', 'off');
} else {
$(this).addClass('glyphicon-volume-up').removeClass('glyphicon-volume-off');
setSetting('volume', 'on');
}
});
switch(getSetting('volume')) {
case 'low':
$('#toggleAudio').removeClass('glyphicon-volume-off').removeClass('glyphicon-volume-up').addClass('glyphicon-volume-down');
break;
case 'on':
$('#toggleAudio').removeClass('glyphicon-volume-off').removeClass('glyphicon-volume-down').addClass('glyphicon-volume-up');
break;
}
setHideRooms(getSetting('hideRooms'));
setHideUsers(getSetting('hideUsers'));
// when the client hits ENTER on their keyboard
$('#inputField').keypress(function(e) {
if(e.which == 13 && !e.shiftKey) {
sendMessage();
return false;
}
});
$('#logout').click(function(){
localStorage.clear();
if (socket.disconnect) socket.disconnect();
location.href = 'http://www.cynicslair.com/jtf';
});
$('#settingsModal').on('show.bs.modal', function () {
if (localStorage.settings == null) return;
var settings = JSON.parse(localStorage.settings);
for (var c in settings) {
if (!settings.hasOwnProperty(c)) continue;
$('#settingsModal select[name="' + c + '"]').val(settings[c]);
if (settings[c] == $('#settingsModal input[type="checkbox"]').val()) $('#settingsModal input[type="checkbox"]').prop('checked', true);
else $('#settingsModal input[type="checkbox"]').prop('checked', false);
}
});
$('#settingsModal button[type="submit"]').on('click', function(ev){
ev.preventDefault();
var arr = $('#settingsModal form').serializeArray();
var settings = {};
for(var c = 0, l = arr.length; c < l; c++) {
settings[arr[c].name] = arr[c].value;
}
localStorage.settings = JSON.stringify(settings);
switchStyles(settings.theme);
setHideUsers(settings.hideUsers);
setHideRooms(settings.hideRooms);
});
// FROM http://web.enavu.com/daily-tip/maxlength-for-textarea-with-jquery/
$('textarea[maxlength]').keyup(function(){
//get the limit from maxlength attribute
var limit = parseInt($(this).attr('maxlength'));
//get the current text inside the textarea
var text = $(this).val();
//check if there are more characters then allowed
if(text.length > limit){
//and if there are use substr to get the text before the limit
text = text.substr(0, limit);
//and change the current text with the new text
$(this).val(text);
}
var indicator = $(this).attr('data-maxlength-target');
if (indicator != null && indicator.length > 0) {
$('#' + indicator).text(text.length + '/' + limit);
}
});
}); |
/*var i =15
for (var i = 1; i < i; i=i+2) {
if (i%i == i, 1 && i%5!=0) {
console.log (i, 'es primo');
} else {console.log (i, 'no es primo');
}
}
if (i%5!=0 && i%3!=0 && i%2!=0) {
console.log (num, 'es primo');
} else {console.log (num, 'no es primo');
}
}
*/
var num = 11;
var esprimo= 'es primo';
for (var i = 2; i < num; i++) {
if (num % i == 0) {
esprimo = 'no es primo'
break
}
}
console.log (num, esprimo); |
'use babel';
const d3 = require('d3');
const moment = require('moment');
const Base64 = require('js-base64').Base64;
const _ = require('underscore');
const DEFAULT_WIDTH = 800;
const DEFAULT_HEIGHT = 400;
const DATE_FORMAT = 'YYYY-MM-DD';
const DEFAULT_COLORS = ['#222', '#555', '#888', '#bbb'];
const LEGEND_X = 10;
const LEGEND_Y = 2.5;
const LEGEND_PAD = 3;
const CURVES = new Map([
['basis', d3.curveBasis],
['cardinal', d3.curveCardinal],
['catmullRom', d3.curveCatmullRom],
['linear', d3.curveLinear],
['monotoneX', d3.curveMonotoneX],
['monotoneY', d3.curveMonotoneY],
['step', d3.curveStep],
['stepAfter', d3.curveStepAfter],
['stepBefore', d3.curveStepBefore]
]); //check http://bl.ocks.org/d3indepth/b6d4845973089bc1012dec1674d3aff8
function validateSettings(settings) {
if (!settings) {
throw "No settings";
}
if (!settings.svg || settings.svg.tagName.toLowerCase() !== 'svg') {
throw "No svg";
}
validateData(settings);
validateMargins(settings);
validateStyles(settings);
validateDrawOptions(settings);
validateCurveOptions(settings);
}
function validateData(settings) {
if (!settings.data) {
throw "No data";
}
if (!settings.data.entries) {
throw "No data entries";
}
if (!Array.isArray(settings.data.entries)) {
throw "Data entries not an array";
}
if (!settings.data.entries.length) {
throw "Empty data entries";
}
if (!settings.data.keys) {
throw "No keys defined"
} else {
settings.data.reverseKeys = [...settings.data.keys].reverse();
}
if (_.isArray(settings.data.entries[0])) {
transformData(settings);
}
}
function transformData(settings) {
//the given data entries itself are arrays
let transformedEntries = [];
for (let entry of settings.data.entries) {
let transformedEntry = {}
//the first value of the array must be the date
transformedEntry.date = getMoment(entry[0]);
//the following entries must be the values in order of the given keys
let i = 1;
for (let key of settings.data.keys) {
transformedEntry[key] = entry[i];
i++;
}
transformedEntries.push(transformedEntry);
}
settings.data.entries = transformedEntries;
}
function validateMargins(settings) {
if (!settings.margin) {
settings.margin = {
top: 50,
right: 70,
bottom: 50,
left: 40
}
} else {
if (!('top' in settings.margin)) {
settings.margin.top = 50;
}
if (!('right' in settings.margin)) {
settings.margin.right = 70;
}
if (!('bottom' in settings.margin)) {
settings.margin.bottom = 50;
}
if (!('left' in settings.margin)) {
settings.margin.left = 40;
}
}
if (!('width' in settings)) {
settings.width = DEFAULT_WIDTH;
}
settings.innerWidth = settings.width - settings.margin.left - settings.margin.right;
if (!('height' in settings)) {
settings.height = DEFAULT_HEIGHT;
}
settings.innerHeight = settings.height - settings.margin.top - settings.margin.bottom;
}
function validateStyles(settings) {
if (!settings.style) {
settings.style = {
fontSize: 12,
fontFamily: 'sans-serif',
color: '#222',
backgroundColor: '#fff'
};
settings.style.markers = {
backgroundColor: settings.style.backgroundColor,
color: settings.style.color
};
settings.style.axis = {
color: settings.style.color,
};
} else {
if (!settings.style.fontSize) {
settings.style.fontSize = 12;
}
if (!settings.style.fontFamily) {
settings.style.fontFamily = 'sans-serif';
}
if (!settings.style.color) {
settings.style.color = '#222';
}
if (!settings.style.backgroundColor) {
settings.style.backgroundColor = '#fff';
}
if (!settings.style.axis) {
settings.style.axis = {
color: settings.style.color
}
} else {
if (!settings.style.axis.color) {
settings.style.axis.color = settings.style.color
}
}
if (!settings.style.markers) {
settings.style.markers = {
backgroundColor: settings.style.backgroundColor,
color: settings.style.color
}
} else {
if (!settings.style.markers.backgroundColor) {
settings.style.markers.backgroundColor = settings.style.backgroundColor;
}
if (!settings.style.markers.color) {
settings.style.markers.color = settings.style.color;
}
}
}
}
function validateDrawOptions(settings) {
if (!settings.drawOptions) {
settings.drawOptions = ['title', 'axis', 'legend', 'markers', 'focus'];
}
}
function validateCurveOptions(settings) {
if (!settings.curve) {
settings.curve = {
type: 'linear'
}
} else if (!settings.curve.type) {
settings.curve.type = 'linear';
}
}
function prepareSVG(settings) {
settings.d3svg = d3.select(settings.svg);
settings.d3svg
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('width', settings.width)
.attr('height', settings.height);
settings.g = settings.d3svg.append("g");
if (settings.margin.left || settings.margin.top) {
settings.g.attr("transform", "translate(" + settings.margin.left + "," + settings.margin.top + ")");
}
}
function getStartOfDay(date) {
return getMoment(date).startOf('day');
}
function getMoment(date) {
return moment(date);
}
function prepareScales(settings) {
settings.x = d3.scaleTime()
.range([0, settings.innerWidth]);
settings.y = d3.scaleLinear()
.range([settings.innerHeight, 0]);
}
function prepareDataFunctions(settings) {
let curve = CURVES.get(settings.curve.type);
if (settings.curve.type == 'cardinal' && settings.curve.tension) {
curve = curve.tension(settings.curve.tension);
} else if (settings.curve.type == 'catmullRom' && settings.curve.alpha) {
curve = curve.alpha(settings.curve.alpha);
}
//alpha, beta, tension
settings.stack = d3.stack();
settings.area = d3.area()
.curve(curve)
.x(function (d) {
return settings.x(getStartOfDay(d.data.date));
})
.y0(function (d) {
return settings.y(d[0]);
})
.y1(function (d) {
return settings.y(d[1]);
});
settings.fromDate = settings.fromDate ? getStartOfDay(settings.fromDate) : settings.fromDate;
settings.toDate = settings.toDate ? getStartOfDay(settings.toDate) : settings.toDate;
let xRange = d3.extent(settings.data.entries, function (d) {
return getStartOfDay(d.date);
});
if (settings.fromDate) {
xRange[0] = settings.fromDate;
}
if (settings.toDate) {
xRange[1] = settings.toDate;
}
settings.x.domain(xRange);
settings.stack.keys(settings.data.keys);
settings.y.domain([0, d3.max(settings.data.entries, function (d) {
let sum = 0;
for (let i = 0, n = settings.data.keys.length; i < n; i++) {
sum += d[settings.data.keys[i]];
}
return sum;
})]);
}
function drawLayers(settings) {
let layer = settings.g.selectAll('.layer')
.data(settings.stack(settings.data.entries.filter(function (d) {
return isDateInRange(d.date, settings);
})))
.enter()
.append('g')
.attr('class', 'layer');
layer
.append('path')
.attr('class', 'area')
.style('fill', function (d) {
return getColor(d.key, settings);
})
.style('stroke', function (d) {
return getStroke(d.key, settings);
})
.style('stroke-width', '.5')
.attr('d', settings.area);
}
function drawFocus(settings) {
if (settings.drawOptions.includes('focus')) {
const lineHeight = settings.style.fontSize;
let drawFocusItems = function (dataSet) {
hideFocus();
let x = settings.x(dataSet.date) + 0.5; //perfect align marker
let y = LEGEND_Y + lineHeight / 2;
let row = 0.5;
let width = 0;
let y1 = settings.innerHeight;
let y2 = 0;
if (!dataSet.date.isSame(settings.toDate) || !settings.drawOptions.includes('axis')) {
//as we have an axis at the right side, we only draw
//the marker if its not directly on top of the axis
if (x > 0.5) {
markerBackground
.attr('x1', x)
.attr('y1', y1)
.attr('x2', x)
.attr('y2', y2)
.style('display', null);
}
marker
.attr('x1', x)
.attr('y1', y1)
.attr('x2', x)
.attr('y2', y2)
.style('display', null);
}
focus
.attr('x', (x + 2))
.attr('y', (y - LEGEND_PAD))
.attr('height', (.5 + row + dataSet.__count) * lineHeight)
.style('display', null);
let count = 0;
for (let key of _.keys(dataSet)) {
if (!key.startsWith('__')) {
focusItems[count]
.attr('x', x + LEGEND_PAD + 2)
.attr('y', key == 'date' ? y + row * lineHeight : y + (0.5 + row) * lineHeight)
.style('display', null)
.text(key == 'date' ? getMoment(dataSet[key]).format(DATE_FORMAT) : round(dataSet[key]) + ' ' + key)
try {
let length = focusItems[count].node().getComputedTextLength();
width = Math.max(width, length + 2 * LEGEND_PAD);
} catch (e) {
//JSDOM is not able to operate with getComputedTextLength
//therefore this code is not going to run in the tests
}
row++;
count++;
}
}
focus.attr('width', width);
if (x + 2 + width >= settings.innerWidth) {
let offset = - (2 + width);
focus.attr('x', x + offset);
for (let focusItem of focusItems) {
focusItem.attr('x', x + LEGEND_PAD + offset);
}
}
}
let mousemove = function () {
let date = getStartOfDay(settings.x.invert(d3.mouse(this)[0]));
let lastDate = getLastEntryDate(settings);
if (date.isAfter(lastDate)) {
date = lastDate;
}
let dataSet = getDataSet(date, settings);
if (dataSet && dataSet.__count > 1) {
drawFocusItems(dataSet);
} else {
hideFocus();
}
}
let hideFocus = function () {
focus.style('display', 'none');
for (let focusItem of focusItems) {
focusItem.style('display', 'none');
}
markerBackground.style('display', 'none');
marker.style('display', 'none');
}
let focus = settings.g.append("rect")
.attr('fill', settings.style.backgroundColor)
.attr('stroke', settings.style.color)
.attr('class', 'focus-item')
.attr('width', lineHeight)
.attr('height', lineHeight)
.style('display', 'none');
let focusItems = [];
for (let i = 0; i < 40; i++) {
let focusItem = settings.g.append('text')
.attr('dy', dy(settings))
.attr('font-size', settings.style.fontSize + 'px')
.attr('font-family', settings.style.fontFamily)
.style('text-anchor', 'start')
.style('fill', settings.style.color)
.style('display', 'none')
.text('');
focusItems.push(focusItem);
}
let markerBackground = settings.g.append('line')
.style('display', 'none')
.style('stroke-width', '3')
.style('stroke', settings.style.markers.backgroundColor);
let marker = settings.g.append('line')
.style('display', 'none')
.style('stroke-width', '1')
.style('stroke', settings.style.markers.color);
settings.g.append("rect")
.attr('width', settings.innerWidth + settings.margin.right)
.attr('height', settings.innerHeight)
.attr('fill', 'transparent')
.on('mousemove', mousemove)
.on('mouseout', hideFocus);
}
}
function hasData(settings) {
for (let entry of settings.data.entries) {
if (_.isArray(entry)) {
for (let i = 1; i < entry.length; i++) {
if (entry[i]) {
return true;
}
}
} else if (entry) {
for (let key of settings.data.keys) {
if (entry[key]) {
return true;
}
}
}
}
return false;
}
function hasDataForKey(key, settings) {
let keyIndex = -1;
if (settings.data.keys) {
keyIndex = settings.data.keys.indexOf(key);
}
for (let entry of settings.data.entries) {
if (_.isArray(entry) && keyIndex >= 0 && entry[keyIndex + 1]) {
return true;
} else if (entry && entry[key]) {
return true;
}
}
return false;
}
function getColor(key, settings) {
if (settings.style[key] && settings.style[key].color) {
return settings.style[key].color;
} else {
let index = settings.data.reverseKeys.indexOf(key) % DEFAULT_COLORS.length;
return DEFAULT_COLORS[index];
}
}
function getStroke(key, settings) {
if (settings.style[key] && settings.style[key].stroke) {
return settings.style[key].stroke;
} else {
return settings.style.backgroundColor;
}
}
function getDataSet(date, settings) {
for (let entry of settings.data.entries) {
if (getMoment(entry.date).isSame(date, 'day')) {
//sort the result
let result = {
date: getStartOfDay(entry.date),
__sum: 0,
__count: 1
}
for (let key of settings.data.reverseKeys) {
if (_.isNumber(entry[key]) && entry[key] > 0) {
//count only positive numbers
result[key] = entry[key];
result.__sum += entry[key];
result.__count += 1;
}
}
return result;
}
}
return null;
}
function isDateInRange(date, settings) {
let dataFromDate, dataToDate;
let momentDate = getStartOfDay(date);
dataFromDate = getFirstEntryDate(settings);
dataToDate = getLastEntryDate(settings);
if (settings.fromDate && momentDate.isBefore(settings.fromDate)) {
return false;
} else if (!settings.fromDate && momentDate.isBefore(dataFromDate)) {
return false;
}
if (settings.toDate && momentDate.isAfter(settings.toDate)) {
return false;
} else if (!settings.toDate && momentDate.isAfter(dataToDate)) {
return false;
}
return true;
}
function drawAxis(settings) {
if (settings.drawOptions.includes('axis')) {
let xAxis = settings.g.append('g')
.attr('transform', 'translate(0,' + settings.innerHeight + ')')
.call(d3.axisBottom(settings.x).ticks(Math.floor(settings.innerWidth / 120)).tickFormat(d3.timeFormat("%b %d")));
xAxis
.selectAll('path')
.style('stroke', settings.style.axis.color);
xAxis
.selectAll('line')
.style('stroke', settings.style.axis.color);
xAxis
.selectAll('text')
.style('fill', settings.style.axis.color)
.attr('text-anchor', 'start')
.attr('font-size', settings.style.fontSize + 'px')
.attr('font-family', settings.style.fontFamily);
let yAxis = settings.g.append('g')
.attr('transform', 'translate(' + settings.innerWidth + ' ,0)')
.call(d3.axisRight(settings.y).ticks(Math.floor(settings.innerHeight / 50)));
yAxis
.selectAll('path')
.style('stroke', settings.style.axis.color);
yAxis
.selectAll('line')
.style('stroke', settings.style.axis.color);
yAxis
.selectAll('text')
.style('fill', settings.style.axis.color)
.style('text-anchor', 'start')
.attr('font-size', settings.style.fontSize + 'px')
.attr('font-family', settings.style.fontFamily);
}
}
function drawMarkers(settings) {
let mark = function (date, label) {
let x1 = settings.x(getStartOfDay(date)) + 0.5;
let y1 = settings.innerHeight;
let y2 = 0;
if (!getStartOfDay(date).isSame(settings.toDate) || !settings.drawOptions.includes('axis')) {
//as we have an axis at the right side, we only draw
//the marker if its not directly on top of the axis
if (x1 > 0.5) {
settings.g.append('line')
.attr('x1', x1)
.attr('y1', y1)
.attr('x2', x1)
.attr('y2', y2)
.style('stroke-width', '3')
.style('stroke', settings.style.markers.backgroundColor);
}
settings.g.append('line')
.attr('x1', x1)
.attr('y1', y1)
.attr('x2', x1)
.attr('y2', y2)
.style('stroke-width', '1')
.style('stroke', settings.style.markers.color);
}
drawTextWithBackground({
text: (label ? label : getMoment(date).format(DATE_FORMAT)),
x: x1,
y: -15,
color: settings.style.markers.color,
textAnchor: 'start',
background: settings.style.backgroundColor,
settings: settings
});
}
if (settings.drawOptions.includes('markers') && settings.markers) {
settings.markers.forEach(m => {
if (isDateInRange(m.date, settings)) {
mark(m.date, m.label);
}
});
}
}
function getFirstEntryDate(settings) {
return getStartOfDay(settings.data.entries[0].date);
}
function getLastEntryDate(settings) {
let entry = getStartOfDay(settings.data.entries[settings.data.entries.length - 1].date);
if (settings.toDate && settings.toDate.isBefore(entry)) {
return settings.toDate;
} else {
return entry;
}
}
function dy(settings) {
return settings.style.fontSize / 3 + 'px';
}
function round(number) {
return Math.round(number * 100) / 100;
}
function drawTextWithBackground({
text,
textAnchor,
x,
y,
color,
background,
settings
}) {
let bkg = settings.g.append('rect')
.style('fill', background);
let txt = settings.g.append('text')
.attr('x', x)
.attr('y', y)
.attr('dy', dy(settings))
.attr('font-size', settings.style.fontSize + 'px')
.attr('font-family', settings.style.fontFamily)
.style('fill', color)
.style('text-anchor', textAnchor ? textAnchor : 'start')
.text(text);
try {
let length = txt.node().getComputedTextLength();
if (textAnchor == 'middle') {
bkg.attr('x', x - length / 2);
} else if (textAnchor == 'end') {
bkg.attr('x', x - length);
} else {
bkg.attr('x', x);
}
bkg.attr('y', y - settings.style.fontSize / 2)
.attr('width', length)
.attr('height', settings.style.fontSize);
} catch (e) {
//JSDOM is not able to operate with getComputedTextLength
//therefore this code is not going to run in the tests
}
}
function drawLegend(settings) {
const lineHeight = settings.style.fontSize;
const isDataAvailable = hasData(settings);
const drawLegendItem = function ({
text,
x,
y,
fill
}) {
return settings.g.append('text')
.attr('x', x)
.attr('y', y)
.attr('dy', dy(settings))
.attr('font-size', settings.style.fontSize + 'px')
.attr('font-family', settings.style.fontFamily)
.style('text-anchor', 'start')
.style('fill', fill)
.text(text);
}
const drawRectangle = function ({
x,
y,
width,
height,
fill,
stroke
}) {
return settings.g.append('rect')
.attr('x', x)
.attr('y', y)
.attr('width', width)
.attr('height', height)
.style('fill', fill ? fill : settings.style.backgroundColor)
.style('stroke', stroke ? stroke : settings.style.backgroundColor);
}
if (settings.drawOptions.includes('title')) {
//title
if (settings.title) {
drawLegendItem({
text: settings.title,
x: LEGEND_X - LEGEND_PAD,
y: -35,
fill: settings.style.color
});
}
}
if (settings.drawOptions.includes('legend')) {
let hasTitle = settings.legendTitle;
let background = drawRectangle({
x: LEGEND_X - LEGEND_PAD,
y: LEGEND_Y + lineHeight / 2 - LEGEND_PAD,
width: settings.style.fontSize * 6,
height: ((hasTitle ? 2 : 0.5) + settings.data.keys.length) * lineHeight,
stroke: settings.style.color
});
//legend headline
if (settings.legendTitle) {
drawLegendItem({
text: settings.legendTitle,
x: LEGEND_X,
y: LEGEND_Y + lineHeight,
fill: settings.style.color
});
}
let legendLine = 0;
settings.data.reverseKeys.forEach((key, index) => {
if (!isDataAvailable || hasDataForKey(key, settings)) {
drawRectangle({
x: LEGEND_X,
y: LEGEND_Y + ((hasTitle ? 2 : 0.5) + legendLine) * lineHeight,
width: lineHeight,
height: lineHeight,
fill: getColor(key, settings)
});
let item = drawLegendItem({
text: key,
x: LEGEND_X + lineHeight * 1.62,
y: LEGEND_Y + ((hasTitle ? 2.5 : 1) + legendLine) * lineHeight,
fill: settings.style.color
});
//adjust background width
try {
width = background.attr('width');
let length = item.node().getComputedTextLength();
background.attr('width', Math.max(width, length + 2.6 * lineHeight));
} catch (e) {
//JSDOM is not able to operate with getComputedTextLength
//therefore this code is not going to run in the tests
}
legendLine++;
}
});
background.attr('height', ((hasTitle ? 2 : 0.5) + legendLine) * lineHeight);
}
}
/**
* <a href='https://travis-ci.com/ulfschneider/stacked-area'><img src='https://travis-ci.com/ulfschneider/stacked-area.svg?branch=master'/></a>
* <a href='https://coveralls.io/github/ulfschneider/stacked-area?branch=master'><img src='https://coveralls.io/repos/github/ulfschneider/stacked-area/badge.svg?branch=master' /></a>
* <a href='https://badge.fury.io/js/stacked-area'><img src='https://badge.fury.io/js/stacked-area.svg' /></a>
*
* Draw SVG Stacked Area Charts.
*
* <img src="https://raw.githubusercontent.com/ulfschneider/stacked-area/master/stacked-area.png"/>
*
* Install in your Node project with
* <pre>
* npm i stacked-area
* </pre>
*
* and use it inside your code via
*
* <pre>
* const stackedArea = require('stacked-area');
* </pre>
*
* or, alternatively
*
* <pre>
* import stackedArea from 'stacked-area';
* </pre>
*
* Create the new stackedArea objects via
*
* <pre>
* let diagram = stackedArea(settings);
* </pre>
* @constructor
* @param {Object} settings - The configuration object for the diagram.
* All data for the diagram is provided with this object.
* In this configuration object, whenever a date is to be given,
* it can be an [ISO 8601 String](https://en.wikipedia.org/wiki/ISO_8601)
* or a JavaScript [Date](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date) object.
* A [Moment](https://momentjs.com) object is also fine.
* @param {String} [settings.title] - The title for the diagram.
* @param {String} [settings.legendTitle] - The title for the legend.
* @param {Object} settings.svg - The DOM tree element, wich must be an svg tag.
* The diagram will be attached to this DOM tree element. Example:
* <pre>settings.svg = document.getElementById('stackedAreaDiagram');</pre>
* <code>'stackedAreaDiagram'</code> is the id of a svg tag.
* @param {Number} [settings.width] - The width of the diagram in pixels, the margin settings have to be included in that width.
* @param {Number} [settings.height] - The height of the diagram in pixels, the margin settings have to be included in that height.
* @param {{top: Number, right: Number, bottom: Number, right: Number}} [settings.margin] - The margin for the diagram.
* Default values are:
* <pre>settings.margin = {
* top: 50,
* right: 50,
* bottom: 50,
* left: 50 }
* </pre>
* @param {String|Date} [settings.fromDate] - The start date for the diagram. Example:
* <pre>settings.fromDate = '2018-09-01';</pre>
* @param {String|Date} [settings.toDate] - The end date for the diagram. Example:
* <pre>settings.toDate = '2018-09-05';</pre>
* @param {{date:(String|Date), label:String}[]} [settings.markers] - Highlight specific dates inside of the diagram
* with markers. Each marker is an object with a date for the marker and an optional label. Example:
* <pre>settings.markers = [
* { date: '2018-09-03', label: 'M1' },
* { date: '2018-09-10', label: 'M2' }];</pre>
* @param {String[]} [settings.drawOptions] - An array to determine the parts to be drawn. Possible options:
* <pre>'title' - draw the title
* 'axis' - draw the x and y axis
* 'legend' - draw the legend information
* 'markers' - draw the markers
* 'focus' - draw detailed data when hovering the diagram
* </pre> By default all of these draw options are on.
* @param {Object} [settings.style] - Influence the appearance of the diagram with typeface and colors. The defaults are:
* <pre>settings.style = {
* fontSize: 12,
* fontFamily: 'sans-serif',
* color: '#222',
* backgroundColor: '#fff',
* axis: {color: '#222'},
* markers: {color: '#222', backgroundColor: '#fff'}
* }</pre>
* You may configure colors for each stacked area, like for a chart with stacked areas named
* 'Highest', 'High', 'Medium' and 'Low':
* <pre>
* settings.style.Highest = { color: 'chartreuse', stroke: 'white' };
* settings.style.High = { color: 'cornflowerblue', stroke: 'white' };
* settings.style.Medium = { color: 'darkorange', stroke: 'white' };
* settings.style.Low = { color: 'firebrick', stroke: 'white' };
* </pre>
* @param {{keys: String[], entries: Object[]}} settings.data - The data for the diagram. Example:
* <pre>settings.data = {
* keys: ['Low', 'Medium', 'High', 'Highest'],
* entries: [
* { date: '2018-09-03', Highest: 0, High: 0, Medium: 0, Low: 0 },
* { date: '2018-09-04', Highest: 1, High: 0, Medium: 0, Low: 0 },
* { date: '2018-09-05', Highest: 1, High: 1, Medium: 0, Low: 0 },
* { date: '2018-09-06', Highest: 1, High: 0, Medium: 1, Low: 1 },
* { date: '2018-09-07', Highest: 2, High: 1, Medium: 0, Low: 2 },
* { date: '2018-09-08', Highest: 1, High: 1, Medium: 2, Low: 2 },
* { date: '2018-09-09', Highest: 0, High: 0, Medium: 1, Low: 5 },
* { date: '2018-09-10', Highest: 1, High: 1, Medium: 0, Low: 5 }
* ]}</pre>
* Each entry object must contain a date and the counts for the keys.
* Each key will be rendered as a stacked layer.
* The rendering of the stacked layers will follow the order
* of the keys. Hereby left to right keys leads to stacked areas from bottom to top.
*/
function StackedArea(settings) {
this.settings = settings;
this.defaultWidth = DEFAULT_WIDTH;
this.defaultHeight = DEFAULT_HEIGHT;
}
StackedArea[Symbol.species] = StackedArea;
/**
* Draw the Stacked Area Chart inside of the provided <code>settings.svg</code> DOM tree element.
*/
StackedArea.prototype.draw = function () {
validateSettings(this.settings);
this.remove();
prepareSVG(this.settings);
prepareScales(this.settings);
prepareDataFunctions(this.settings);
drawLayers(this.settings);
drawAxis(this.settings);
drawMarkers(this.settings);
drawLegend(this.settings);
drawFocus(this.settings);
}
/**
* Clear the chart from the provided <code>settings.svg</code> DOM tree element
*/
StackedArea.prototype.remove = function () {
if (this.settings.svg) {
let svg = this.settings.svg;
while (svg.firstChild) {
svg.removeChild(svg.firstChild);
}
}
}
/**
* Draw the Stacked Area Chart inside of the provided <code>settings.svg</code> DOM tree element
* and return the result as a string which can be assigned to the SRC attribute of an HTML IMG tag.
* @returns {string}
*/
StackedArea.prototype.imageSource = function () {
this.draw();
let html = this.settings.svg.outerHTML;
return 'data:image/svg+xml;base64,' + Base64.encode(html);
}
/**
* Draw the Stacked Area Chart inside of the provided <code>settings.svg</code> DOM tree element
* and return the result as a SVG tag string.
* @returns {string}
*/
StackedArea.prototype.svgSource = function () {
this.draw();
return this.settings.svg.outerHTML;
}
module.exports = function (settings) {
return new StackedArea(settings);
}
|
import React from "react";
import Link from "next/link";
import { Container } from "./style";
import Images from "./Images";
import Content from "./Content";
import Counters from "./Counters";
const index = ({ postData, directToPostPage }) => {
const countersData = {
postId: postData._id,
price: postData.price,
favorites: postData.favorites,
viewCount: postData.viewCount,
};
const imageData = {
image: postData.images[0],
isAvailable: postData.isAvailable,
isSold: postData.isSold,
};
const contentData = {
title: postData.title,
lengthFt: postData.lengthFt,
lengthIn: postData.lengthIn,
width: postData.width,
depth: postData.depth,
volume: postData.volume,
condition: postData.condition,
location: postData.location,
shaper: postData.shaper,
model: postData.model,
};
return (
<Link
scroll={false}
href={
directToPostPage
? `/postdetails/${postData._id}`
: `/?postId=${postData._id}`
}
as={`/postdetails/${postData._id}`}
>
<Container>
<Images data={imageData} />
<Content data={contentData} />
<Counters data={countersData} />
</Container>
</Link>
);
};
export default index;
|
var app = getApp();
var taskid = ""
Page({
data: {
items: [{
title: app.language('camera.id_photo'),
id: 0,
defaultImg: "../../images/zhenjian.jpg",
src: "../../images/add.png"
},
{
title: app.language('camera.full_photo'),
id: 1,
defaultImg: "../../images/quanshen.jpg",
src: "../../images/add.png"
}
],
curid: 0, // 当前的图片id
devicePosition: "back", // back 后置摄像头; front 前置摄像头
flash: "auto", // 闪光灯 auto on off
isShow: false, // true:显示拍照界面
username: "", // 用户输入参数
age: "", // 用户输入参数
agreement: 0, // true:同意协议
needBorder: true
},
onLoad: function (options) {
console.log(options)
var that = this
that.setData({
taskid: options.taskid,
})
wx.setNavigationBarTitle({
title: options.taskid
})
wx.getStorage({
key: 'langIndex',
success: function(res) {
that.setData({
langIndex: res.data
})
}
});
that.setLang()
},
setLang() {
const set = wx.T._
this.setData({
camera: set('camera'),
})
},
bindNameInput: function (e) {
this.setData({
username: e.detail.value
});
},
bindAgeInput: function (e) {
this.setData({
age: e.detail.value
});
},
bindAgreement: function (e) {
this.data.agreement = e.detail.value.length;
},
submit: function () {
var username = this.data.username;
var age = this.data.age;
var that = this;
if (this.data.username === "") {
wx.showToast({
title: app.language('validator.username'),
icon: "none",
duration: 1500
});
} else if (this.data.age === "") {
wx.showToast({
title: app.language('validator.age'),
icon: "none",
duration: 1500
});
} else if (this.data.agreement === 0) {
wx.showToast({
title: app.language('validator.check'),
icon: "none",
duration: 1500
});
} else {
wx.switchTab({
url: "../index/index"
});
}
},
// 开始拍照
chooseimage: function (e) {
var that = this;
var id = e.currentTarget.dataset.id;
that.data.curid = id;
var isshow = that.data.isShow;
if (that.data.curid === 1) {
that.setData({
needBorder: false
});
} else {
that.setData({
needBorder: true
});
}
wx.getSetting({
success(res) {
if (!res.authSetting['scope.camera']) {
wx.authorize({
scope: 'scope.camera',
success() {
that.setData({
isShow: !isshow
})
},
fail() {
wx.showModal({
title: app.language('validator.tips'),
content: app.language('validator.notused'),
showCancel: false,
success: function (res) {
wx.navigateTo({
url: '../setting/index',
})
wx.setStorage({
key: "function",
data: 'camera',
})
}
})
}
})
} else {
that.setData({
isShow: !isshow
});
}
}
})
},
// 快门
takePhoto() {
var that = this;
const ctx = wx.createCameraContext();
var isshow = that.data.isShow;
ctx.takePhoto({ // 拍照后即开始上传
quality: "high", // high
success: function(res) {
var imgsrc = res.tempImagePath;
that.data.items[that.data.curid].src = imgsrc;
if (that.data.curid === 1) {
that.data.needBorder = that.data.noneed;
that.setData({
isShow: !isshow,
items: that.data.items
});
} else {
that.data.needBorder = that.data.need;
that.setData({
isShow: !isshow,
items: that.data.items
});
}
// 上传图片
var keytoken = getUploadToken(that, res.tempImagePath);
console.log(keytoken)
uploadPhoto(that, res.tempImagePath, keytoken[0], keytoken[1])
}
});
},
deviceRadioChange: function (e) {
var devicePosition = this.data.devicePosition;
if (devicePosition === "front") {
this.setData({
devicePosition: "back"
});
} else {
this.setData({
devicePosition: "front"
});
}
},
});
function uploadPhoto(that, filename, key, token) {
wx.chooseImage({
count: 1,
success: function (res) {
var filePath = res.tempFilePaths[0];
// 交给七牛上传
qiniuUploader.upload(filePath, function(res) {
that.setData({
imageObject: res
});
},
function(error) {
console.error("error: " + JSON.stringify(error));
}, { // hard coding seapub_todo
region: "ECN", // ECN, SCN, NCN, NA, ASG : 华东 华南 华北 北美 新加坡
uptoken: token,
key: key,
shouldUseQiniuFileName: false,
domain: "https://s301.fanhantech.com"
},
function(progress) {
console.log("上传进度", progress.progress);
console.log("已经上传的数据长度", progress.totalBytesSent);
console.log(
"预期需要上传的数据总长度",
progress.totalBytesExpectedToSend
);
},
function(cancelTask) {
that.setData({
cancelTask
})}
);
}
});
}
function getUploadToken(that, filename) {
wx.request({
url: cfg.getAPIURL() + "/api/projects/" + that.data.taskid + "/token",
data: {
taskid: that.data.taskid,
filename: filename,
},
header: {
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": app.getCookie()
},
method: "POST",
success: function (res) {
if (res.data.code === 0) {
return [res.data.key, res.data.token];
} else {
wx.showToast({
title: app.language('validator.uploadfail'),
icon: "none",
duration: 1500
});
}
}
});
}
|
import { takeEvery, put, call } from "redux-saga/effects";
import * as R from "ramda";
import { getErrorMessage } from "helpers/tools";
import { api } from "utils/api";
import { renderNotify } from "utils/notify";
import { routerActions } from "store/router/actions";
import { recipeActions } from "./actions";
import { recipeTypes } from "./types";
function* getItems(action) {
try {
const query = action.payload;
const result = yield call(api.service("recipe").find, query);
yield put(recipeActions.getItemsSuccess(result));
} catch (error) {
renderNotify({
title: "Error get recipes",
text: getErrorMessage("Error get recipes")(error),
});
yield put(recipeActions.getItemsFailure(error));
}
}
function* getItem(action) {
try {
const result = yield call(api.service("recipe").get, action.payload);
yield put(recipeActions.getItemSuccess(result));
} catch (error) {
renderNotify({
title: "Error get recipe",
text: getErrorMessage("Error get recipe")(error),
});
yield put(recipeActions.getItemFailure(error));
}
}
function* changeLike(action) {
try {
const { userId, recipeId } = action.payload;
if (R.isNil(userId)) {
renderNotify({
title: "Вы не авторизованы",
text: "Что бы ставить лайки рецептам, необходисо авторизоваться",
});
} else {
const result = yield call(api.service("like").create, {
userId,
recipeId,
});
yield put(recipeActions.changeLikeSuccess(result));
}
} catch (error) {
renderNotify({
title: "Error change Like",
text: getErrorMessage("Error change Like")(error),
});
yield put(recipeActions.changeLikeFailure(error));
}
}
function* create(action) {
try {
const data = action.payload;
yield call(api.service("recipe").create, data);
yield put(routerActions.push("/"));
} catch (error) {
renderNotify({
title: "Error create Recipe",
text: getErrorMessage("Error create Recipe")(error),
});
yield put(recipeActions.createFailure(error));
}
}
function* update(action) {
try {
const { id, data } = action.payload;
yield call(api.service("recipe").update, id, data);
yield put(routerActions.push("/"));
} catch (error) {
renderNotify({
title: "Error update Recipe",
text: getErrorMessage("Error update Recipe")(error),
});
yield put(recipeActions.updateFailure(error));
}
}
export function* recipeSaga() {
yield takeEvery(recipeTypes.RECIPE_GET_ITEMS, getItems);
yield takeEvery(recipeTypes.RECIPE_GET_ITEM, getItem);
yield takeEvery(recipeTypes.CHANGE_LIKE_ITEM, changeLike);
yield takeEvery(recipeTypes.RECIPE_CREATE, create);
yield takeEvery(recipeTypes.RECIPE_UPDATE, update);
}
|
var str = "hello worldrdsfds";
console.log(str); |
'use strict';
const fs = require('fs');
const path = require('path');
const CliProgress = require('cli-progress');
const Promise = require('bluebird');
const ignoreForeverFileName = '.eslintignore';
const cwd = process.cwd();
const {exec} = require('child_process');
function debug(...args)
{
console.log(args.join(' '));
}
function getIgnoredFiles(files, ignoreFilePath) {
if (!fs.existsSync(ignoreFilePath))
{
debug(`ignore file not found in path ${ignoreFilePath}, assuming there are no ignores`);
return [];
}
const allIgnored = fs.readFileSync(ignoreFilePath, 'utf-8')
.split('\n')
.map((file)=>file.trim())
.filter((file)=>file)
.map((file)=>path.resolve(ignoreFilePath, '../', file).replace(`${cwd}/`, ''));
if (files[0] === '.')
{
return allIgnored;
}
return allIgnored
.filter((ignoredFileName)=>files.some((fileIncludedInCheck)=>ignoredFileName.startsWith(fileIncludedInCheck.replace(`${cwd}/`, ''))));
}
function getIgnoredForeverFiles(files) {
if (!fs.existsSync(ignoreForeverFileName))
{
return [];
}
const allIgnored = fs.readFileSync(ignoreForeverFileName, 'utf-8')
.split('\n')
.map((file)=>file.trim())
.filter((file)=>file)
.map((file)=>path.resolve(ignoreForeverFileName, '../', file).replace(cwd, ''));
if (files[0] === '.')
{
return allIgnored;
}
return allIgnored
.filter((ignoredFileName)=>files.some((fileIncludedInCheck)=>ignoredFileName.startsWith(fileIncludedInCheck)));
}
async function countFiles(files)
{
return Promise.reduce(files, (res, file)=>{
return new Promise((resolve, reject)=>{
exec(`find ${file} -type f -name "*.js" ! -path "*/node_modules/*" | wc -l`, (error, stdout, stderr) => {
if (error)
{
reject(error);
return;
}
resolve(res + parseInt(stdout, 10));
});
});
}, 0)
.catch((err)=>debug(err));
}
/**
*
* @param {Object} [options]
* @param {boolean} [options.ignoreBad] do not check bad files
* @param {string} [options.eslintPath] path to ESLint
* @param {string} [options.ignoreFilePath] path to slowlint ignore file
* @param {Array[String]} [options.files] array of files to check
* @returns {Object} bad files's filenames and a number of good files
*/
async function lintAll(options = {}) {
let progressBar;
let showProgress = !options.noProgress;
let total = 0;
if (showProgress)
{
total = await countFiles(options.files);
}
if (!total)
{
showProgress = false;
}
// debug(`lintAll options: ${JSON.stringify(options, null, 3)}`);
const eslintPath = path.resolve(cwd, options.eslintPath);
// eslint-disable-next-line global-require,import/no-dynamic-require
const {CLIEngine} = require(eslintPath);
const opts = {
useEslintrc: true,
plugins: ['counter'],
};
let ignoredFilesNum = 0;
opts.ignorePattern = getIgnoredForeverFiles(options.files);
if (options.ignoreBad) {
const ignoredFiles = getIgnoredFiles(options.files, options.ignoreFilePath);
ignoredFilesNum = ignoredFiles.length;
opts.ignorePattern = opts.ignorePattern.concat(ignoredFiles);
}
total -= opts.ignorePattern.length;
if (showProgress)
{
progressBar = new CliProgress.Bar({
format: 'Linting [{bar}] {percentage}% | ETA: {eta}s | Processed: {value}/{total} | Current: {currentFile}',
etaBuffer: 200,
fps: 1,
}, CliProgress.Presets.shades_classic);
progressBar.start(total, 0, {
currentFile: 'N/A',
});
}
// debug(`lintAll opts: ${JSON.stringify(opts, null, 3)}`);
const cli = new CLIEngine(opts);
let counter = 0;
const myPath = path.resolve('.');
cli.addPlugin('counter', {
processors: {
'.js': {
preprocess(text, filename) {
counter++;
if (showProgress)
{
progressBar.update(counter, {
currentFile: filename.replace(myPath, ''),
});
}
return [text];
},
postprocess(messages) {
return messages[0];
},
},
},
});
const report = cli.executeOnFiles(options.files || ['.']);
const formatter = cli.getFormatter();
const errorReport = CLIEngine.getErrorResults(report.results);
const badFilesFound = errorReport
.map((data) => data.filePath.replace(`${cwd}/`, ''));
let logs = formatter(errorReport);
if (logs.length > 1000) {
logs = `${logs.substr(0, 1000)}...`;
}
if (showProgress)
{
progressBar.setTotal(counter);
progressBar.stop();
}
return {
ignoredFilesNum,
badFiles: badFilesFound,
goodFilesNum: counter - badFilesFound.length,
badFilesNum: badFilesFound.length,
logs,
};
}
module.exports = {
lintAll,
getIgnoredFiles,
getIgnoredForeverFiles,
ignoreForeverFileName,
};
|
var searchData=
[
['group',['Group',['../structGroup.html',1,'']]],
['groupnode',['GroupNode',['../structGroupNode.html',1,'']]]
];
|
/*global define*/
define([
'jquery',
'underscore',
'backbone',
'text!templates/menu/sub-menu.tpl'
], function ($, _, Backbone, subMenuTpl) {
'use strict';
return Backbone.View.extend({
tagName: 'ul',
template: _.template(subMenuTpl),
initialize: function() {
// Rend la vue dès l'initialisation.
this.render();
},
render : function() {
// l'attribut sub_item a été passé en paramètre à partir de
// la vue MenuView.js. Un attribut inconnu à backbone ce récupère
// comme tel "this.options.sub_item". Sinon this.model, this.collection...
this.$el.html(this.template({
item_main_menu_id : this.options.item_main_menu_id,
items : this.options.sub_item,
}));
return this;
}
});
}); |
let add = document.querySelector("#add"); // assigned
let list = document.querySelector("#list");
add.onclick = (addList) => {
addList.preventDefault(); //stop executing default process
let listItem = document.querySelector("#listitem"); // listitem id place assigned
if (listItem.value !== "") {
let li = document.createElement("li"); // list element created
li.innerHTML = listItem.value; //adding
let closeButton = document.createElement("button");
closeButton.className = "close";
closeButton.innerHTML = "\u00D7";
li.appendChild(closeButton);
list.appendChild(li); // li element added next to the list .
listItem.value = ""; // empty the list after adding text .
li.addEventListener("click", (appendList) => {
//each event appended to next.
appendList.target.style.textDecoration = "line-through"; //text style changed.
});
closeButton.addEventListener("click", (deleteList) => {
deleteList.target.parentElement.style.display = "none"; //delete the text using close button
});
} else {
alert("Empty Input...! \n Type Important Do List");
}
};
|
import QualityService from '@/services/hy/quality';
import { notification } from 'antd';
export default {
namespace: 'quality',
state: {
list: [],
modalDeliveryOrderList: [],
},
effects: {
*getDataList({ payload, callback }, { call, put }) {
const response = yield call(QualityService.getDatalList, payload);
if (response.status === 'success') {
callback && callback(response.data);
} else {
notification.error({
message: `请求错误 ${response.status}: ${response.url}`,
description: response.message,
});
}
},
*handleQuality({ payload, callback }, { call, put }) {
const response = yield call(QualityService.handleQuality, payload);
if (response.status === 'success') {
callback && callback(response.data);
} else {
notification.error({
message: `请求错误 ${response.status}: ${response.url}`,
description: response.message,
});
}
},
*handleResetQuality({ payload, callback }, { call, put }) {
const response = yield call(QualityService.handleResetQuality, payload);
if (response.status === 'success') {
callback && callback(response.data);
} else {
notification.error({
message: `请求错误 ${response.status}: ${response.url}`,
description: response.message,
});
}
},
},
reducers: {
save(state, action) {
return {
...state,
...action.payload,
};
},
},
};
|
export const Form = function() {
return (
<div>Form!</div>
)
}
|
"use strict";
use(function () {
var column = granite.resource.properties["columns"];
var columns = column.split("-");
return columns;
}); |
import {useEffect, useState} from 'react';
import loadImage from '../utils/loadImage';
const useWorkList = (initWorkList = [], preloadImages) => {
const [workList, setWorkList] = useState(initWorkList);
const [loading, setLoading] = useState(false);
useEffect(() => {
(async function getPages() {
setLoading(true);
const response = await fetch(`/data/work/list.json`);
if (response.ok) {
try {
const json = await response.json();
if (Array.isArray(json)) {
if (preloadImages) {
for (let work of json.filter(work => work.imageLink)) {
await loadImage(work.imageLink);
}
}
setWorkList(json);
}
} catch (e) {
}
}
setLoading(false);
})();
}, [preloadImages]);
return {workList, setWorkList, loading};
};
export default useWorkList;
|
export default class Branch {
constructor(parent, level, maxLevels, x, y, surface) {
this.parent = parent;
this.surface = surface;
this.branches = [];
this.p0 = parent ? parent.p1 : { x, y };
this.p1 = { x, y };
this.level = level;
this.maxLevels = maxLevels;
this.date = new Date();
this.hue = ~(this.date.getSeconds() * 10);
this.life = 10;
this.angle = 0;
this.vx = 0;
this.vy = 0;
this.mult = 10;
}
distance = (a, b, c, d) => {
const radius = Math.sqrt(((a - c) * (a - c) + (b - d) * (b - d)));
return radius;
};
getRandomPoint = (radius) => {
const angle = Math.random() * Math.PI * 2;
return {
x: Math.cos(angle) * radius,
y: Math.sin(angle) * radius,
angle,
};
};
sproutLeaves = (p0, p1, amt) => {
this.surface.lineWidth = 3;
const radius = ~~(this.distance(p0.x, p0.y, p1.x, p1.y));
for (let i = 0; i < amt; i++) {
const hue = `hsla(${this.hue + (i * 20)},100%,50%,0.75)`;
const rndPoint = this.getRandomPoint(radius);
this.surface.fillStyle = hue;
this.surface.moveTo(p0.x + rndPoint.x + radius, this.parent.p0.y);
this.surface.arc(p0.x + rndPoint.x, p0.y + rndPoint.y, radius * 0.35, 0, 2 * Math.PI, false);
this.surface.fill();
}
}
newBranch = (parent) => {
const branch = new Branch(parent,
parent.level - 1, this.maxLevels, parent.p1.x, parent.p1.y, this.surface);
branch.angle = (parent.level === this.maxLevels) ? (-89.5) + ~~(0.25 - Math.random() * 0.5) : Math.atan2(
parent.p1.y - parent.p0.y,
parent.p1.x - parent.p0.x
) + (Math.random() * 1.0 - 0.5);
branch.vx = Math.cos(branch.angle) * this.mult;
branch.vy = Math.sin(branch.angle) * this.mult;
branch.life = branch.level === 1 ? this.mult : Math.round(Math.random() * (branch.level * 2)) + 3;
return branch;
};
grow = () => {
for (let i = 0; i < this.branches.length; i++) {
this.branches[i].grow();
}
if (this.life > 1) {
this.p1.x += this.vx;
this.p1.y += this.vy;
this.surface.beginPath();
this.surface.lineCap = 'round';
const lineWidth = this.level * 5 - 4;
if (this.level) {
this.surface.lineWidth = lineWidth;
this.surface.strokeStyle = `hsla(${30 + (10 - (this.level * 5))},100%,10%,1)`;
if (this.parent) {
this.surface.moveTo(this.parent.p0.x, this.parent.p0.y);
this.surface.quadraticCurveTo(this.p0.x, this.p0.y, this.p1.x, this.p1.y);
}
this.surface.stroke();
} else {
const amt = ~~(Math.random() * 4) + 2;
this.sproutLeaves(this.p0, this.p1, amt);
}
}
if (this.life === 1 && this.level > 0 && this.level < this.maxLevels) {
this.branches.push(this.newBranch(this));
this.branches.push(this.newBranch(this));
if (Math.random() > 0.85 && this.level < 2) {
this.branches.push(this.newBranch(this));
this.branches.push(this.newBranch(this));
}
}
this.life --;
};
}
|
/**
* Created by vadimushka_d on 019 - 19 мар.
*/
var helloWorld = document.getElementById('test');
helloWorld.innerHTML = "Hello World"; |
import {PieceBag} from "../src/PieceBag.js";
import {FallingPiece} from "../src/FallingPiece.js";
function firstNPiecesOfBag(number) {
let pieceBag = new PieceBag();
let pieces = [];
for (let i = 0; i < number; i++) {
pieces.push(pieceBag.takePiece());
}
return pieces;
}
function pieceDistribution(pieces) {
let pieceTypes = {};
for (let piece of pieces) {
if (piece.tetrominoType in pieceTypes) {
pieceTypes[piece.tetrominoType]++;
} else {
pieceTypes[piece.tetrominoType] = 1;
}
}
return pieceTypes;
}
describe('PieceBag', () => {
"use strict";
it('should produce infinite pieces', () => {
let pieceBag = new PieceBag();
let pieces = [];
for (let i = 0; i < 100; i++) {
let newPiece = pieceBag.takePiece();
pieces.push(newPiece);
expect(newPiece).to.be.an.instanceof(FallingPiece);
}
expect(pieces.length).to.equal(100);
});
it('should have even piece distribution with 7 pieces', () => {
let pieces = firstNPiecesOfBag(7);
let pieceTypes = pieceDistribution(pieces);
expect(pieceTypes).to.deep.equal({
I: 1, J: 1, L: 1, O: 1, S: 1, Z: 1, T:1
});
});
it('should have even piece distribution with 14 pieces', () => {
let pieces = firstNPiecesOfBag(14);
let pieceTypes = pieceDistribution(pieces);
expect(pieceTypes).to.deep.equal({
I: 2, J: 2, L: 2, O: 2, S: 2, Z: 2, T:2
});
});
it('should have even piece distribution with 21 pieces', () => {
let pieces = firstNPiecesOfBag(21);
let pieceTypes = pieceDistribution(pieces);
expect(pieceTypes).to.deep.equal({
I: 3, J: 3, L: 3, O: 3, S: 3, Z: 3, T:3
});
});
describe('.peekNextPiece()', () => {
it ('should show the next piece without removing it', ()=> {
let pieceBag = new PieceBag();
for (let i = 0; i < 100; i++) {
let peekedPiece = pieceBag.peekNextPiece();
let takenPiece = pieceBag.takePiece();
expect(peekedPiece.tetrominoType).to.equal(takenPiece.tetrominoType);
}
});
});
}); |
/*
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
*/
'use strict'
const R = require('ramda')
//const _ = require('lodash/fp')
const isPrime = num => {
if (num % 2 === 0) return false // Optimization
const tmp = range(3, Math.ceil(Math.sqrt(num))) // Optimization
// const tmp = range(3, num - 1)
return tmp.every(x => num % x != 0)
}
const rangeRecursive = (start, end, arr) => {
if (start > end) return arr
return [start].concat(range(start + 1, end))
}
const range = R.curry((start, end) => {
const arr = []
for (let i = start; i <= end; i++) {
arr.push(i)
}
return arr
})
const _filter = R.curry((fn, arr) => arr.filter(fn))
const _reduce = R.curry((fn, initial, arr) => arr.reduce(fn, initial))
const _add = R.curry((a, b) => a + b)
const _sum = _reduce(_add, 0)
const primeSum = R.compose(_sum, _filter(isPrime), range)
//console.log(array)
console.log(primeSum(1, 200000)) // Original: below 2 million
|
const fs = require('fs')
// 创建一个可读流。
const readStream = fs.createReadStream('./1.txt')
// 创建一个可写流。
const writeStream = fs.createWriteStream('./2.txt')
// 将可读流读取的数据,通过管道pipe推送到写入流中,即可将1.txt的内容,写入到2.txt中。
readStream.pipe(writeStream)
// 读取出现错误时会触发error事件。
readStream.on('error', (error) => {
console.error(error)
})
// 写入完成时,触发finish事件。
writeStream.on('finish', () => {
console.log('finish')
})
|
/**
* This communicator is used for saving the data into the Redis and send the message via RSMQ
* to the PigeonPost
*/
const config = require('config');
const redis = require('redis');
const redisClient = redis.createClient({
db: config.get('REDIS_DB')
});
const RedisSMQ = require('rsmq');
const rsmq = new RedisSMQ({ host: config.get('REDIS_HOST'), port: config.get('REDIS_PORT') });
const rsmqConfigs = {
qname: config.get('RSMQ_QUEUE_NAME')
};
const REDIS_TWEETS_SET = `${config.get('REDIS_TWEETS_SET')}:${config.get('TWITTER_USER_ID_TO_FOLLOW')}`;
/**
* Checks if queue for messaging exists. If not - creating a new queue
*
* @returns {Promise}
*/
function init() {
return new Promise((resolve) => {
rsmq.getQueueAttributes(rsmqConfigs, (err, response) => {
if (response) {
return resolve();
}
createRSMQQueue().then(() => {
resolve();
});
});
});
}
/**
* Creates a new Queue for RSMQ
*
* @returns {Promise}
*/
function createRSMQQueue() {
return new Promise((resolve, reject) => {
rsmq.createQueue(rsmqConfigs, (error) => {
if (error) {
reject(error);
throw new Error(`Couldn't create new Redis Queue, ${error}`);
}
resolve();
});
});
}
/**
* Maps the tweet to redis-friendly format
*
* @param tweet - tweet message
* @returns {*[]} - mapped tweet
*/
function mapTweet(tweet) {
return [
'id', tweet.id,
'text', tweet.text,
'entities', tweet.entities,
'user:name', tweet.user.name,
'user:url', tweet.user.url,
'created_at', tweet.created_at,
'user:profileImageUrlHttps', tweet.user.profile_image_url_https
];
}
/**
* Parses the received tweet(s) and passing it forward for saving and etc
*
* @param tweets - the tweet collection (can be just single tweet object)
* @returns {Promise}
*/
function parse(tweets) {
if (!Array.isArray(tweets)) {
tweets = [ tweets ];
}
const promises = [];
for (const tweet of tweets) {
const promise = processTweet(tweet);
promises.push(promise);
}
return Promise.all(promises);
}
/**
* Adds tweet id to the set with tweets
*
* @param tweetsSet - tweets set key
* @param tweet - tweet that should be added
* @returns {Promise}
*/
function addTweetIdToTweetsSet(tweetsSet, tweet) {
return new Promise((resolve) => {
redisClient.sadd(tweetsSet, tweet.id, (err) => {
if (err) {
throw new Error(err);
}
resolve();
});
});
}
/**
* Processes tweet for saving. Checks if the instance already exists in redis.
*
* @param tweet - tweet that should be processed
* @returns {Promise}
*/
function processTweet(tweet) {
return new Promise((resolve, reject) => {
const tweetKey = getTweetKey(tweet.id);
const tweetsSet = REDIS_TWEETS_SET;
if (!tweet.id) {
return resolve();
}
redisClient.sismember(tweetsSet, tweet.id, (error, member) => {
if (error) {
reject(error);
}
if (!member) {
addTweetIdToTweetsSet(tweetsSet, tweet);
}
checkIfTweetExists(tweetKey).then(resolve,
() => {
saveTweet(tweet).then(resolve, reject);
}
);
});
});
}
/**
* Checks if tweet exists in db
*
* @param tweetKey - key that should be checked
* @returns {Promise}
*/
function checkIfTweetExists(tweetKey) {
return new Promise((resolve, reject) => {
redisClient.exists(tweetKey, (err, exists) => {
if (err) {
reject(err);
}
if (!exists) {
reject();
}
resolve();
});
});
}
/**
* Saves the tweet to the redis and sends message to the RQMS queue
*
* @param tweet - a new tweet that should be saved
* @returns {Promise}
*/
function saveTweet(tweet) {
return new Promise((resolve, reject) => {
const mappedTweet = mapTweet(tweet);
const stringifyMappedTweet = JSON.stringify(mappedTweet);
const tweetKey = getTweetKey(tweet.id);
redisClient.set(tweetKey, stringifyMappedTweet, (err) => {
if (err) {
reject(err);
}
sendRsmqMessage(mappedTweet).then(() => {
resolve();
});
});
});
}
/**
* Generates redis tweet record key based on id
*
* @param id - tweet id
* @returns {string} - redis tweet record key
*/
function getTweetKey(id) {
return `${config.get('REDIS_TWEET_PREFIX')}${id}`;
}
/**
* Sends message with new tweet via RSMQ
*
* @param mappedTweet - already mapped tweet
* @returns {Promise}
*/
function sendRsmqMessage(mappedTweet) {
return new Promise((resolve, reject) => {
const messageConfig = createMessageConfig(mappedTweet);
rsmq.sendMessage(messageConfig, (err) => {
if (err) {
reject(err);
}
resolve();
});
});
}
/**
* Creates a message configs (message body as well) that would be sent
*
* @param mappedTweet - mapped tweet body
* @returns {*}
*/
function createMessageConfig(mappedTweet) {
return Object.assign({}, rsmqConfigs, {
message: JSON.stringify({
data: mappedTweet
})
});
}
module.exports = {
parse,
init
}; |
//Local Storage
localStorage.setItem("name", "foo");
localStorage.setItem("cutlery", "spoon");
const nameValue = localStorage.getItem("name");
console.log(nameValue);
const countries = ["France", "Germany"];
localStorage.setItem("countries", JSON.stringify(countries));
countriesValue = localStorage.getItem("countries");
console.log("Countries from Storage =>", JSON.parse(countriesValue));
const product = {
name: "Coke",
size: "Small",
price: 3.99,
};
localStorage.setItem("product", JSON.stringify(product));
localStorage.removeItem("cutlery");
//Session Storage
sessionStorage.setItem("id", 239874);
//Cookies
document.cookie = `name=Joldo; expires=` + new Date(2021, 9, 8);
|
import React from 'react'
import { View, TouchableOpacity, ImageBackground } from 'react-native'
import { BoldText, RegularText } from '../../../components/UIComponents/Text';
import styles from '../../../theme/Styles';
import { COLORS } from '../../../theme/Theme';
const AboutItem = ({ item }) => {
return (
<View style={[styles.aboutItemWrapper, styles.vhCenter]}>
<RegularText style={[styles.bold, styles.itemHeader, {color: COLORS.black}]}>{item.title}</RegularText>
<RegularText style={[styles.itemDesc, {color: COLORS.dark}]}>{item.desc}</RegularText>
</View>
)
}
export default AboutItem |
'user strict'
angular.module("softtechApp")
.controller('ActivitiesCtrl',['$scope','$http', '$dataFactory', 'DTOptionsBuilder', 'Notification',function($scope, $http, $dataFactory, DTOptionsBuilder, Notification){
$dataFactory.menuActive = "Actividades";
// DataTables configurable options
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withDisplayLength(10)
.withOption('bLengthChange', false)
.withOption('autoWidth', true)
.withOption('scrollY', "200px")
.withOption('oLanguage', {"sEmptyTable": "No hay datos..." })
.withOption('scrollCollapse', true);
//Functions
$scope.refresh = function(){
$scope.formOpt = false;
$scope.tablBtnsOpt = false;
$scope.formDetailsOpt = false;
$scope.addBtnOpt = true;
$scope.delBtnOpt = false;
$scope.itemObjectActived = {};
// Get Data from server
$http.get('/v1/activities').then(function(response){
$scope.items = response.data;
})
};
// Activate Form to modify or add data
$scope.formActivate = function(item){
if(item != null){ // Update
$scope.itemObjectActived = item;
}else{ // Insert
$scope.delBtnOpt = true;
}
$scope.formOpt = true;
$scope.tablBtnsOpt = true;
$scope.addBtnOpt = false;
};
// Activate Form to modify or add data
$scope.formDetailsActivate = function(item){
$scope.itemObjectActived = item;
$scope.formDetailsOpt = true;
$scope.addBtnOpt = false;
$scope.tablBtnsOpt = true;
};
$scope.validateEmptyData = function(item){
return softechUtil.validateEmptyData(item);
};
$scope.validateNumberData = function(item){
return softechUtil.validateDataNumber(item);
};
// Remove an item
$scope.removeItem = function(id){
$http.delete('/v1/activities/'+id).then(function(response){
Notification.success({title:'Exitoso', message:'Removido exitosamente!'});
$scope.refresh();
}, function(error){
if(error.status === 400){
Notification.error({title:'Error', message:'Por favor verifique sus datos y vuelva a intentarlo!'});
}else if(error.status === 500){
Notification.error({title:'Error', message:'Ocurrio un error en el servidor, intentelo mas tarde!'});
}else{
Notification.error({title:'Error', message:'Error desconocido, refresque la pagina y vuelva a intentarlo!'});
}
console.log('Error: ' + error.data.message);
$scope.refresh();
});
};
// Add a new Item
$scope.addNewItem = function(){
var data = {
nombreActividad : softechUtil.validateEmptyData($scope.itemObjectActived.nombreActividad),
detalle : softechUtil.validateEmptyData($scope.itemObjectActived.detalle),
duracion : softechUtil.validateDataNumber($scope.itemObjectActived.duracion),
repeticiones : softechUtil.validateDataNumber($scope.itemObjectActived.repeticiones),
peso : softechUtil.validateDataNumber($scope.itemObjectActived.peso)
};
$http.post('/v1/activities/', data).then(function(response){
Notification.success({title:'Exitoso', message:'Ingresado exitosamente!'});
$scope.refresh();
}, function(error){
if(error.status === 400){
Notification.error({title:'Error', message:'Por favor verifique sus datos y vuelva a intentarlo!'});
}else if(error.status === 500){
Notification.error({title:'Error', message:'Ocurrio un error en el servidor, intentelo mas tarde!'});
}else{
Notification.error({title:'Error', message:'Error desconocido, refresque la pagina y vuelva a intentarlo!'});
}
console.log('Error: ' + error.data.message);
$scope.refresh();
});
};
// Modify an existing item
$scope.updateItem = function(){
var data = {
nombreActividad : softechUtil.validateEmptyData($scope.itemObjectActived.nombreActividad),
detalle : softechUtil.validateEmptyData($scope.itemObjectActived.detalle),
duracion : softechUtil.validateDataNumber($scope.itemObjectActived.duracion),
repeticiones : softechUtil.validateDataNumber($scope.itemObjectActived.repeticiones),
peso : softechUtil.validateDataNumber($scope.itemObjectActived.peso)
};
$http.put('/v1/activities/'+$scope.itemObjectActived._id, data).then(function(response){
Notification.success({title:'Exitoso', message:'Modificado exitosamente!'});
$scope.refresh();
}, function(error){
if(error.status === 400){
Notification.error({title:'Error', message:'Por favor verifique sus datos y vuelva a intentarlo!'});
}else if(error.status === 500){
Notification.error({title:'Error', message:'Ocurrio un error en el servidor, intentelo mas tarde!'});
}else{
Notification.error({title:'Error', message:'Error desconocido, refresque la pagina y vuelva a intentarlo!'});
}
console.log('Error: ' + error.data.message);
$scope.refresh();
});
};
$scope.confirmChanges = function(){
if(!$scope.delBtnOpt){
$scope.updateItem();
}else{
$scope.addNewItem();
}
}
$scope.refresh();
}]);
|
(function() {
Handlebars.registerHelper("ifCover", function(conditional, options) {
var noImageUrl;
noImageUrl = "http://bookshelf.deseretbook.com/images/detail_missing.png";
if (conditional === noImageUrl) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper("ifCurrentBook", function(options) {
if (CropSwap.currentBookId !== void 0) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Handlebars.registerHelper("ifSvg", function(options) {
if (Modernizr.svg) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
}).call(this);
|
ASSET_ROOT = "http://localhost:3000"
CHARACTER_STATUS = ""
function resetMainTagHTML() {
MAINTAG.innerHTML = ""
createAppendElement("div", "", MAINTAG, { id: "container" })
}
async function getCharactersByUserId(user_id) {
return fetch(`${ASSET_ROOT}/characters/${user_id}/find-user`)
.then(function (response) {
return response.json()
}).then(function (response) {
return response
})
}
async function getCharacterByCharacterId(user_id) {
return fetch(`${ASSET_ROOT}/characters/${user_id}/find-characer`)
.then(function (response) {
return response.json()
}).then(function (response) {
return response
})
}
function createAppendElement(tag, input, parent, attributes = {}) {
const createdTag = document.createElement(tag)
createdTag.innerText = input
for (attribute in attributes) {
createdTag.setAttribute(attribute, attributes[attribute])
}
parent.append(createdTag)
return createdTag
}
function createPrependElement(tag, input, parent, attributes = {}) {
const createdTag = document.createElement(tag)
createdTag.innerText = input
for (attribute in attributes) {
createdTag.setAttribute(attribute, attributes[attribute])
}
parent.prepend(createdTag)
return createdTag
}
async function getUserMoney(user_id) {
return fetch(`${ASSET_ROOT}/users/${user_id}/getmoney`)
.then(function (response) {
return response.json()
})
.then((response) => response)
}
async function subtractMoney(user_id, money) {
return fetch(`${ASSET_ROOT}/users/${user_id}/substract-money`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
money: money
})
}).then((response) => {
return response.json()
})
.then((response) => {
return response
})
}
async function fetchCharacterData() {
return fetch("http://localhost:3000/characters")
.then(function (response) {
return response.json()
})
.then(function (characters) {
return characters
})
}
function getAllCharacters() {
return fetch(`${ASSET_ROOT}/list-chars`)
.then((result) => {
return result.json()
}).then((result) => {
return result
})
}
async function createCharacter(character_info, user_id) {
return fetch(`${ASSET_ROOT}/characters/create`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
user_id: user_id,
image: character_info.image,
name: character_info.name,
earnings: character_info.earnings
})
}).then((response) => response.json())
.then((response) => response)
}
function createAlert(tag, text, type, action, attributes = {}) {
const alert = document.createElement("div")
tag = document.querySelector(tag)
alert.innerText = text
alert.style.textAlign = "center"
for (attribute in attributes) {
alert.setAttribute(attribute, attributes[attribute])
}
alert.setAttribute("class", `alert alert-${type}`)
alert.setAttribute("role", "alert")
if (action == "append") {
tag.append(alert)
} else {
tag.prepend(alert)
}
}
function getAndRemoveElement(name) {
found = document.querySelectorAll(name)
if (found) {
found.forEach((item) => item.remove())
} else {
return "no item found"
}
}
function removeClassByIds(ids, classToRemove) {
let tag = ""
let currentClasses = null
newClasses = null
for (id of ids) {
tag = document.getElementById(id)
currentClasses = tag.getAttribute("class")
newClasses = currentClasses.replace(classToRemove, "")
tag.setAttribute("class", newClasses)
}
}
function addClassById(id, classToAdd) {
const tag = document.getElementById(id)
const currentClasses = tag.getAttribute("class")
const new_classes = currentClasses + " " + classToAdd
tag.setAttribute("class", new_classes)
}
function getRandomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function createCard(character) {
if(!document.getElementById("container")){
container = createAppendElement("div", "", MAINTAG, {id: "container"})
}
container = document.getElementById("container")
container.style.display = "flex"
container.style.flexWrap = "wrap"
const card = document.createElement("div")
card.setAttribute("class", "card")
card.style.width = "18rem"
card.style.margin = "0 auto"
container.append(card)
const cardBody = document.createElement("div")
cardBody.setAttribute("class", "card-body")
createProgressBar(character, cardBody, card)
const title = document.createElement("h5")
title.setAttribute("class", "card-title")
title.innerText = character.name
cardBody.append(title)
const cardText = document.createElement("p")
cardText.setAttribute("class", "card-text")
cardBody.append(cardText)
card.append(cardBody)
// const state = document.createElement("p")
// state.innerText = `Status: ${character.status}`
// cardBody.append(state)
const StatusButton = document.createElement("button")
StatusButton.setAttribute("class", "btn btn-primary")
StatusButton.setAttribute("id", "status-button")
cardBody.append(StatusButton)
getCharacterByCharacterId(character.id).then((updatedCharacter) => {
if (updatedCharacter.status === "awake") {
CHARACTER_STATUS = "awake"
StatusButton.innerText = "sleep"
} else if (updatedCharacter.status == "sleeping"){
CHARACTER_STATUS = "sleeping"
StatusButton.innerText = "wake up"
}else{
StatusButton.innerText = "Dead"
}
if (updatedCharacter.status != "dead"){
StatusButton.addEventListener("click", (e) => sleepToggle(updatedCharacter, LOGGED_IN_USER_ID))
}
})
}
function sleepToggle(character, userId) {
console.log(CHARACTER_STATUS)
if (CHARACTER_STATUS == "awake") {
status = "sleeping"
} else if (CHARACTER_STATUS == "sleeping"){
status = "awake"
}
fetch(`${ASSET_ROOT}/characters/${userId}/update-status`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
character: character.id,
status: status
})
}).then((response) => response.json())
.then((response) => {
// state.innerText =
console.log("response: "+ response.status)
statusButton = document.getElementById("status-button")
if (response.status === "awake") {
CHARACTER_STATUS = "awake"
statusButton.innerText = "sleep"
} else if (response.status == "sleeping"){
CHARACTER_STATUS = "sleeping"
statusButton.innerText = "wake up"
}
})
}
function createProgressBar(character, cardBody, card){
const image = document.createElement("img")
if (character.status == "dead"){
image.setAttribute("src", `${IMAGE_PATH}/add-ons/gravestone.png`)
image.style.height = "333px"
image.style.width = "286px"
progressBar(0, "Hunger", cardBody)
progressBar(0, "Thirst", cardBody)
progressBar(0, "Social", cardBody)
progressBar(0, "Sleep", cardBody)
}else{
image.setAttribute("src", `${IMAGE_PATH}/${character.image}`)
progressBar(character.hungry, "Hunger", cardBody)
progressBar(character.thirsty, "Thirst", cardBody)
progressBar(character.social, "Social", cardBody)
progressBar(character.sleepy, "Sleep", cardBody)
}
card.append(image)
}
updateDataEveryHour()
async function updateDataEveryHour() {
const interval = setInterval(() => {
const date = new Date(Date.now())
if ((date.getMinutes() === 00 && date.getSeconds() >= 10)) {
getCharactersByUserId(LOGGED_IN_USER_ID).then((characters) => {
document.querySelector("body").innerHTML = ""
characters.forEach(function (character) {
createCard(character)
})
})
getUserMoney(LOGGED_IN_USER_ID).then((user) => {
})
setTimeout(() => {
updateDataEveryHour()
//waits 59minutes before calling function again
}, 3540000)
return clearInterval(interval)
}
}, 1000);
}
function createMenue() {
const headerTag = document.querySelector("header")
const navBar = createPrependElement("ul", "", headerTag, { id: "navbar" })
const homeLi = createAppendElement("li", "", navBar)
createAppendElement("a", "Home", homeLi)
homeLi.addEventListener("click", function () {
CONTAINER.innerHTML = ""
if (document.getElementById("store-container")){
document.getElementById("store-container").remove()
}
loadMain(LOGGED_IN_USER_ID)
})
const charactersLi = createAppendElement("li", "", navBar)
createAppendElement("a", "Characters", charactersLi)
charactersLi.addEventListener("click", function () {
if (document.getElementById("container")){
document.getElementById("container").innerHTML = ""
}
if (document.getElementById("store-container")){
document.getElementById("store-container").remove()
}
characterMenue()
})
const storeLi = createAppendElement("li", "", navBar)
createAppendElement("a", "Store", storeLi)
storeLi.addEventListener("click", function () {
if (document.getElementById("container")){
document.getElementById("container").remove()
}
if (document.getElementById("store-container")){
document.getElementById("store-container").remove()
}
showShopMenue()
})
const logoutLi = createAppendElement("li", "", navBar)
createAppendElement("a", "Logout", logoutLi)
logoutLi.addEventListener("click", () => logout(navBar))
const moneyLi = createAppendElement("li", "", navBar)
const moneyA = createPrependElement("a", "", moneyLi, { id: "money" })
getUserMoney(LOGGED_IN_USER_ID).then((money) => moneyA.innerText = `${money} G`)
}
function logout(navBar) {
localStorage.clear()
navBar.remove()
loginForm()
}
async function updateCharacter(character, stats_to_update){
return fetch(`${ASSET_ROOT}/characters/${character.id}/update`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
stats_to_update
})
}).then((response) => response.json())
.then((response) => response)
}
// fetch(`${ASSET_ROOT}/characters/user_id`, {
// method: "PATCH",
// headers: {
// "Content-Type": "application/json"
// },
// body: JSON.stringify({
// status: sleep
// })
// }).then((response) => response.json())
// .then((response) => {
// response
// }) |
// Call the dataTables jQuery plugin
$(document).ready(function () {
window.queryParams = function (params) {
if (params.sort && params.order == 'desc')
params.sort = '-' + params.sort;
if (params.offset !== undefined)
params.skip = params.offset;
if (params.search !== "")
params.query = JSON.stringify({
'name': {
'$regex' : '(' + params.search + ')', '$options' : 'i'
}
})
delete params.offset;
delete params.search;
delete params.order;
return params;
}
window.responseHandler = function (data, res) {
console.log(res)
let total = res.getResponseHeader('X-Total-Count');
if (total === null) return data;
else {
data = { total: total, rows: data }
return data;
}
}
window.dateFormat = function (value, row) {
if (!value) return '';
return timeConvert(value, true)
}
window.roleFormat = function (value, row) {
let result = value;
(window.roles || []).forEach((item) => { if (item.role == value) result = item.name })
return result
}
window.timeConvert = function timeConvert(timestamp, ms, gmt) {
try {
var date = new Date(Number(timestamp));
var offset = gmt ? 0 : (date.getTimezoneOffset() / 60);
date.setHours(date.getHours() - offset);
return (date).toISOString().replace(/[TZ]/g, ' ').trim().substring(0, ms ? 23 : 19)
} catch (e) { return timestamp }
}
window.userActions = function (value, row, index) {
if (window.role != 'user')
return '<button class="btn btn-sm btn-info editRecUser" data-i18n="[data-original-title]db.edit" title="" data-original-title="'
+ i18next.t('db.edit')
+ '" data-id="' + row.id + '"> <i class="glyphicon glyphicon-pencil"></i></button> <button class="btn btn-sm btn-danger removeRecUser" data-i18n="[data-original-title]db.removeUser" title="" data-original-title="'
+ i18next.t('db.removeUser')
+ '" data-id="' + row.id + '"><i class="glyphicon glyphicon-trash"></i></button>'
else return '';
};
$('#usersTbl')
.bootstrapTable({
exportDataType: 'all',
height: ($(window).height() - 207).toString(),
responseHandler: function (res, x) {
let total = x.getResponseHeader('X-Total-Count');
if (total === null) return res;
else {
data = { total: total, rows: res }
return data;
}
},
undefinedText: ''
}
);
var counterGetLogsUser = 0;
var timerGetLogsUser;
function requestLogsUser() {
$('#usersTbl').bootstrapTable('refresh', {
url: '/api/v1/User'
});
}
$('#usersTbl').on('load-error.bs.table', function (e, data) {
counterGetLogsUser++;
clearTimeout(timerGetLogsUser);
if (counterGetLogsUser > 15) {
counterGetLogsUser = 0;
$("#loadingModal").modal('hide');
$("#infoModal").find('.modal-body').html(i18next.t('modal.info.getData'));
$("#infoModal").modal('show');
} else {
timerGetLogsUser = setTimeout(function() {
requestLogsUser();
}, counterGetLogsUser * 1500);
}
});
$('#usersTbl').on('load-success.bs.table', function (data) {
clearTimeout(timerGetLogsUser);
$("#loadingModal").modal('hide');
});
$('#usersTbl').on('post-body.bs.table', function (e, data) {
setTimeout(function () {
$('.editRecUser').click(function (e) {
var id = $(this).attr('data-id');
console.log('edit user id', id);
var rec;
$('#usersTbl')
.bootstrapTable('getData', false)
.forEach(function (item) {
if (item.id == id) {
if (!rec)
rec = item;
};
});
if (!rec) return;
$("#editRecordUserForm").trigger("reset");
$('[name="id"]', " #editRecordUserForm").val(rec.id);
$('[name="username"]', " #editRecordUserForm").val(rec.name);
$('[name="password"]', " #editRecordUserForm").val('');
$('[name="role"]', " #editRecordUserForm").val(rec.role);
setTimeout(function () { $('.selectpicker', " #editRecordUserForm").selectpicker('refresh') }, 0);
$("#editRecordUserModalLabel").text(i18next.t('modal.addUser.titleEdit'))
$("#editRecordUserModal").modal('show');
e.preventDefault();
e.stopPropagation();
});
$('.removeRecUser').click(function (e) {
var id = $(this).attr('data-id');
console.log('remove user id', id);
$("#removeModalUser")
.attr('data-id', id)
.modal('show');
e.preventDefault();
e.stopPropagation();
});
$('[title]').tooltip({ trigger: 'hover' })
}, 0)
});
$(this).on('shown.bs.tab', function (e) {
window.activeTab = $(e.target).attr('aria-controls');
$('#video1').get(0).pause();
$('.tab-content>.tab-pane.active .table-striped').bootstrapTable('resetView')
$('#appTab>.nav-item>.nav-link').removeClass('active');
$(e.target).addClass('active');
switch (window.activeTab) {
case 'usersTable':
$("#loadingModal").modal('show');
requestLogsUser();
break;
case 'videoArchive':
$('#videoSourceSelector').selectpicker('val', window.curNodeId);
break;
}
});
$('.addRecUser').click(function (e) {
console.log('add user');
$("#editRecordUserForm").trigger("reset");
$('[name="id"]', "#editRecordUserForm").val('');
$('[name="username"]', "#editRecordUserForm").val('');
$('[name="password"]', "#editRecordUserForm").val('');
$('[name="role"]', "#editRecordUserForm").val('');
setTimeout(function () { $('.selectpicker', "#editRecordUserForm").selectpicker('refresh') }, 0);
$("#editRecordUserModalLabel").text(i18next.t('modal.addUser.title'));
$("#editRecordUserModal").modal('show');
})
});
|
const {
postCoupon,
getPromoByIdModel,
patchPromo,
deletePromoModel,
} = require("../model/promoModel");
const helper = require("../helper/response");
// const qs = require("querystring");
module.exports = {
createCoupon: async (req, res) => {
try {
const {
coupon_code,
start_coupon,
end_coupon,
coupon_discount,
product_id,
} = req.body;
const setDataPromo = await {
coupon_code,
start_coupon,
end_coupon,
coupon_discount,
product_id,
};
const result = await postCoupon(setDataPromo);
console.log(result);
return helper.response(res, 200, "Success Post Promo", result);
} catch {
return helper.response(res, 400, "Bad Request", error);
}
},
getPromoById: async (req, res) => {
try {
const { id } = req.params;
const result = await getPromoByIdModel(id);
if (result.length > 0) {
return helper.response(res, 200, "Success Get Promo By Id", result);
} else {
return helper.response(res, 404, `Promo By Id : ${id} Not Found`);
}
} catch (error) {
console.log(error);
return helper.response(res, 400, "Bad Request", error);
}
},
updatePromo: async (req, res) => {
try {
const { id } = req.params;
const {
coupon_code,
start_coupon,
end_coupon,
coupon_discount,
product_id,
} = req.body;
const setData = {
coupon_code,
start_coupon,
end_coupon,
coupon_discount,
product_id,
};
const checkId = await getPromoByIdModel(id);
if (checkId.length > 0) {
const result = await patchPromo(setData, id);
console.log(result);
return helper.response(res, 200, `Success update promo`, result);
} else {
return helper.response(res, 404, `Coupon By Id : ${id} Not Found`);
}
} catch (error) {
console.log(error);
return helper.response(res, 400, "Bad Request", error);
}
},
deletePromo: async (req, res) => {
try {
const { id } = req.params;
const checkId = await getPromoByIdModel(id);
if (checkId.length > 0) {
const result = await deletePromoModel(id);
return helper.response(res, 200, `Promo has been deleted`, result);
} else {
return helper.response(res, 404, `Product By Id : ${id} Not Found`);
}
} catch {
return helper.response(res, 400, "Bad Request", error);
}
},
};
|
/*=============================================================================
#
# Copyright (C) 2016 All rights reserved.
#
# Author: Larry Wang
#
# Created: 2016-07-12 21:41
#
# Description:
#
=============================================================================*/
import { SET_SIGN_UP, SET_ERROR_TEXT, SET_SIGN_LOADING
, SET_SNACK_MESSAGE, SET_DRAWER_OPEN, SET_PROGRESS_LOADING
, SET_DIALOG_DATA
, SET_MESSAGE_KEYBOARD_OPEN, SET_MESSAGE_TRAGET_DEVICE_ID
, MESSAGE_TYPE, MESSAGE_DELETE}
from 'actions/ui';
export default (state = {
isSignUp: false,
isSignLoading: false,
errorText: {
username: '',
password: '',
confirm: ''
},
snackMessage: '',
isDrawerOpen: false,
isProgressLoading: false,
// We assume there is only one dialog on screen a time.
// Use specific attr to identify defferent dialogs if you need.
dialogData: {
isShow: false
// There should some other attrs here, depends on specific dialog.
},
// Flags for message view.
message: {
isKeyboardOpen: true,
targetDeviceId: -1,
content: []
}
}, action) => {
switch (action.type) {
case SET_SIGN_UP:
return Object.assign({}, state, {isSignUp: action.isSignUp});
case SET_ERROR_TEXT:
return Object.assign({}, state, {
errorText: action.errorText,
isSignLoading: false
});
case SET_SIGN_LOADING:
return Object.assign({}, state, {
isSignLoading: action.isSignLoading
});
case SET_SNACK_MESSAGE:
return Object.assign({}, state, {
snackMessage: action.snackMessage
});
case SET_DRAWER_OPEN:
return Object.assign({}, state, {
isDrawerOpen: action.isDrawerOpen
});
case SET_PROGRESS_LOADING:
return Object.assign({}, state, {
isProgressLoading: action.isProgressLoading
});
case SET_DIALOG_DATA:
return Object.assign({}, state, {
dialogData: Object.assign({}, state.dialogData
, action.dialogData)
});
case SET_MESSAGE_KEYBOARD_OPEN:
return Object.assign({}, state, {
message: Object.assign({}, state.message, {
isKeyboardOpen: action.isKeyboardOpen
})
});
case SET_MESSAGE_TRAGET_DEVICE_ID:
return Object.assign({}, state, {
message: Object.assign({}, state.message, {
targetDeviceId: action.targetDeviceId
})
});
case MESSAGE_TYPE:
const content1 = state.message.content.slice(0);
content1.push(action.value);
return Object.assign({}, state, {
message: Object.assign({}, state.message, {content: content1})
});
return;
case MESSAGE_DELETE:
const content2 = state.message.content.slice(0);
content2.pop();
return Object.assign({}, state, {
message: Object.assign({}, state.message, {content: content2})
});
return;
default:
return state;
}
};
|
'use strict';
import _ from 'lodash';
import Users from '../login/login.model';
import hduserroles from '../hduserroles/hduserroles.model';
import tickets from '../ticket/ticket.model';
import category from '../category/category.model';
var nodemailer = require('nodemailer');
var sjcl = require('sjcl');
function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if (entity) {
// res.status(statusCode).json(entity);
res.send({"statusCode":200,"data":entity});
}
};
};
function removeEntity(res) {
return function(entity) {
if (entity) {
return entity.remove()
.then(() => {
res.status(200).json("200").end();
});
}
};
};
function handleError(res, statusCode) {
statusCode = statusCode || 500;
return function(err) {
// res.status(statusCode).send(err);
res.send({"statusCode":500,"data":err});
};
};
function handleEntityNotFound(res) {
return function(entity) {
if (!entity) {
res.status(404).end();
return null;
}
return entity;
};
}
export function manageuser(req, res) {
var encryptedInfo = sjcl.encrypt("password", "MagikMinds");
var userdata ={
firstname:req.body.firstName,
lastname:req.body.lastName,
employeeid:req.body.employeeid,
emailid:req.body.emailid,
active:req.body.active,
usertype:req.body.userType,
designation:req.body.role,
hdroles : req.body.hdroles,
//-->Siva Changes Start
password: encryptedInfo,
profilefilename : "undefined.jpg"
//<--End
}
Users.find({ $or: [ {employeeid:req.body.employeeid},
{emailid:req.body.emailid} ] },
function (err, recs) {
if(recs!=''){
var response={
message:"already exists",
statusCode:400
}
res.send(response);
}
else{
return Users.create(userdata)
.then(respondWithResult(res, 200))
.catch(handleError(res));
}
});
};
function saveUpdates(updates) {
console.log("showing updat", updates)
return function(entity) {
var updated = _.merge(entity, updates);
return updated.save()
.then(updated => {
return updated;
});
};
}
export function getusers(req, res) {
return Users.find().exec()
.then(respondWithResult(res))
.catch(handleError(res));
};
export function deleteuser(req,res){
tickets.find({$and :[{Assigned_to : req.body.emailid}, {status : {$not : {$in : ['Cancel','Closed']}} } ] }
,function(err,docus){
if (docus.length > 0) {
return res.status(203).json(("203"));
} else {
category.find({$or : [{'executives' : req.body.emailid},{'categoryhead' : req.body.emailid}]},function(exeerr,cate_recs){
if (cate_recs.length > 0) {
return res.status(202).json(("202"));
} else {
hduserroles.find({'useremailid':req.body.emailid},function(err,docs){
docs[0].remove();
return Users.findById(req.body._id).exec()
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
});
}
});
}
});
// hduserroles.find({'useremailid':req.body.emailid},function(err,docs){
// docs[0].remove();
// return Users.findById(req.body._id).exec()
// .then(handleEntityNotFound(res))
// .then(removeEntity(res))
// .catch(handleError(res));
// });
};
export function modifyuser(req,res){
var userdata ={
// _id : req.body._id,
firstname:req.body.firstName,
lastname:req.body.lastName,
employeeid:req.body.employeeid,
emailid:req.body.emailid,
active:req.body.active,
usertype:req.body.userType,
designation:req.body.role,
hdroles : req.body.hdroles
}
return Users.update({_id: req.body._id},userdata)
.then(function(data){return updatedrecord(req,res)})
//.then(respondWithResult(res))
.catch(handleError(res));
};
function updatedrecord(req,res){
return Users.findById(req.body._id).exec()
.then(respondWithResult(res))
.catch(handleError(res));
}
export function sendloginmail( req,res){
var user = req.body;
console.log("sending mail to....", req.body)
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'mmconnectemail@gmail.com',
pass: 'mm@12345'
},
secure: true
});
var salutation = 'Dear ' + 'User' + ',';
var signature = 'Regards,' + '\n' + 'MMConnect Team';
var body = "Your MM Resume Builder account credentials are:" + '\n\n' +
'Username: ' + user.emailid + '\n' + 'Password: ' + user.password;
var message = salutation + '\n\n' + body + '\n\n' + signature;
var mailOptions = { from: 'mmconnectemail@gmail.com', // sender address
to: user.emailid, // list of receivers
subject: 'MMConnect Notification', // Subject line
text: message //, // plaintext body
// html: '<b>Hello world ✔</b>' // You can choose to send an HTML body instead
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error)
res.status(500).json(error);
} else {
res.status(200).json("200");
};
transporter.close();
});
// var Mailinfo = getmailDetailsFor('Owner' , createdtickethistory);
// sendMail(Mailinfo[0] ,Mailinfo[1])
// // sendMail(ownermailBody,ownermailOptions)
// sendMail(headmailBody,headmailOptions)
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import StoryPage from './components/StoryPage/StoryPage'
import { Route, Link, BrowserRouter as Router } from 'react-router-dom'
import * as serviceWorker from './serviceWorker';
import DetailsPage from "./components/DetailsPage/DetailsPage";
import 'bootstrap/dist/css/bootstrap.min.css';
import LogIn from "./components/LogIn"
import Register from "./components/Register/Register"
import {AuthProvider} from "./Auth";
import EventDetails from "./components/EventDetails/EventDetails"
import DonateForm from "./components/DonateForm.js"
const routing=(
<AuthProvider>
<Router>
<div>
<Route exact path="/stories" component={StoryPage}/>
<Route exact path="/donateForm" component={DonateForm}/>
<Route exact path="/login" component={LogIn}/>
<Route exact path="/register" component={Register}/>
<Route exact path="/details/:id" component={DetailsPage}/>
<Route exact path="/events/:location" component={EventDetails}/>
<Route exact path="/" component={App}/>
</div>
</Router>
</AuthProvider>
)
ReactDOM.render(routing, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
// pages/orderInfo/orderInfo.js
var app = getApp();
const {
$Message
} = require('../../lib/dist/base/index');
Page({
/**
* 页面的初始数据
*/
data: {
orderData: [],
baseUrl: app.globalData.host,
roomId: 0,
allMoney: 0,
orderDetail: []
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
const eventChannel = this.getOpenerEventChannel()
eventChannel.on('acceptDataFromOpenerPage', function (data) {
console.log(data);
that.setData({
roomId: data.data
})
})
wx.getStorage({
key: 'token',
success(res) {
that.setData({
token: res.data
})
// 获取图片
that.getOrder()
}
})
},
// 获取菜单
getOrder() {
var that = this;
wx.request({
url: app.globalData.host + 'web/getMenuItems',
method: 'get',
dataType: 'json',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
token: that.data.token
},
success: (res) => {
that.setData({
orderData: res.data.data
})
},
fail: () => {},
complete: () => {}
});
},
// 加菜
addItem(e) {
let orderData = this.data.orderDetail
let item = {
id: e.currentTarget.dataset.id,
money: e.currentTarget.dataset.money,
name: e.currentTarget.dataset.name
}
orderData.push(item);
this.setData({
allMoney: this.data.allMoney + e.currentTarget.dataset.money,
orderDetail: orderData
})
},
//添加订单
addOrder() {
var that = this
if (that.data.allMoney == 0) {
$Message({
content: '请点菜',
type: 'warning'
});
return;
}
wx.navigateTo({
url: '../placeOrder/placeOrder',
success: function (res) {
// 通过eventChannel向被打开页面传送数据
res.eventChannel.emit('acceptDataFromOpenerPage', {
orderData: that.data.orderDetail,
roomType: that.data.roomId,
money: that.data.allMoney
})
}
})
}
}) |
import React, { useState, useEffect } from 'react';
const HoverRect = ({
rect,
attr, // the actual data (from api attributes:{})
handleHoverDate,
handleHoverLeaveDate,
xAxisAttribute, // name of 'date' field - Date / StatisticsProfileDate
handleTextBox,
selected,
date,
selectRect,
}) => {
const [isHovered, setIsHovered] = useState(false);
//set for first time
useEffect(() => {
selectRect(date);
// eslint-disable-next-line
}, []);
const localHandleHover = (e) => {
setIsHovered(true);
handleHoverDate(e, attr);
};
const localHandleHoverLeave = (e) => {
setIsHovered(false);
handleHoverLeaveDate(e);
};
const localHandleTextBox = (attr) => {
selectRect(date);
handleTextBox(attr, xAxisAttribute);
};
const x = rect.x;
const half = x - rect.xOffset;
const y = rect.y;
const w = rect.rectWidth;
return (
<g>
<polygon
opacity={`${selected ? '1' : '0'}`}
stroke="var(--yellow)"
strokeWidth="0.15rem"
strokeLinejoin='round'
fill="var(--yellow)"
points={`
${x},${y}
${x - w / 2},${y -(w/1.2) }
${x + half},${y -(w/1.2) }
`}
/>
<rect
key={rect.key}
onMouseEnter={(e) => localHandleHover(e)}
onMouseLeave={(e) => localHandleHoverLeave(e)}
x={rect.xOffset}
y={rect.y}
width={rect.rectWidth}
height={rect.height}
fill="var(--white)" // for dark graph theme
style={{ transition: 'all 0.005s linear', cursor: 'pointer' }}
opacity={`${isHovered ? '0.2' : selected ? '0.1' : '0'}`}
onClick={() => localHandleTextBox(attr)}
/>
</g>
);
};
export default HoverRect;
|
'use strict';
var React = require('react/addons');
require('styles/ProgressBar2.scss');
var divStyle = [{width: '15%'}, {width: '30%'}, {width: '20%'}];
var option = '';
var ProgressBar2 = React.createClass({
mixins: [],
getInitialState: function() {
return {};
},
getDefaultProps: function() {},
componentWillMount: function() {},
componentDidMount: function() {
},
shouldComponentUpdate: function() {},
componentDidUpdate: function() {},
componentWillUnmount: function() {},
updateProgress: function(barRef, offset) {
var bar = React.findDOMNode(this.refs[barRef]);
bar.style.width = (parseFloat(bar.style.width) <= Math.abs(offset)) && offset < 0
? '0' : ((parseFloat(bar.style.width) + offset) + '%');
bar.parentNode.lastChild.innerText = parseFloat(bar.style.width) + '%';
bar.style.backgroundColor = parseFloat(bar.style.width) > 100 ? '#d9534f' : '#337ab7';
},
handleClickAdd10: function() {
option = React.findDOMNode(this.refs.select).value;
this.updateProgress(option, 10);
},
handleClickSub10: function() {
option = React.findDOMNode(this.refs.select).value;
this.updateProgress(option, -10);
},
handleClickAdd25: function() {
option = React.findDOMNode(this.refs.select).value;
this.updateProgress(option, 25);
},
handleClickSub25: function() {
option = React.findDOMNode(this.refs.select).value;
this.updateProgress(option, -25);
},
render: function () {
return (
<div className="ProgressBar2">
<h3>Prototype 2 Responvsive</h3>
<div className="progress">
<div className="progress-bar progress-bar-striped" ref="progressBar1" style={divStyle[0]}></div>
<span>{divStyle[0]}</span>
</div>
<div className="progress">
<div className="progress-bar progress-bar-striped" ref="progressBar2" style={divStyle[1]}></div>
<span>{divStyle[1]}</span>
</div>
<div className="progress">
<div className="progress-bar progress-bar-striped" ref="progressBar3" style={divStyle[2]}></div>
<span>{divStyle[2]}</span>
</div>
<select ref="select">
<option value="progressBar1" ref="option1">ProgressBar1</option>
<option value="progressBar2" ref="option2">ProgressBar2</option>
<option value="progressBar3" ref="option3">ProgressBar3</option>
</select>
<div className="button-container">
<input type="button" value="-25" onClick={this.handleClickSub25} />
<input type="button" value="-10" onClick={this.handleClickSub10} />
<input type="button" value="+10" onClick={this.handleClickAdd10} />
<input type="button" value="+25" onClick={this.handleClickAdd25} />
</div>
</div>
);
}
});
module.exports = ProgressBar2;
|
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3700';
export const fetchContact = createAsyncThunk(
'contacts/fetchContacts',
async (_, { rejectWithValue }) => {
try {
const { data } = await axios.get('/contacts');
return data;
} catch (error) {
return rejectWithValue(error.message);
}
},
);
export const addContact = createAsyncThunk(
'contacts/addContacts',
async ({ name, number }, { rejectWithValue }) => {
try {
const { data } = await axios.post('/contacts', {
name,
number,
});
return data;
} catch (error) {
return rejectWithValue(error.message);
}
},
);
export const deleteContact = createAsyncThunk(
'contacts/deleteContacts',
async (id, { rejectWithValue }) => {
try {
await axios.delete(`/contacts/${id}`);
return id;
} catch (error) {
return rejectWithValue(error.message);
}
},
);
|
// 账号安全页面
const express = require('express')
const nodemailer = require('nodemailer')
const { generateToken, verifyToken } = require('../utils/jwt')
const utils = require('../utils/utils')
const { collection } = require('../utils/mongodb')
const { ObjectId } = require('bson')
const { sendOneSms } = require('../utils/sms') // sendOneSmsRouter 依赖
const r = express.Router()
/**
* 依赖
*/
const userInfoTable = collection('user_info')
const userLoginTable = collection('user_login')
// 邮箱配置
const transporter = nodemailer.createTransport({
host: 'smtp.163.com', // 这是腾讯的邮箱 host
port: 465, // smtp 端口
secureConnection: true,
auth: {
user: 'gaowujie2019', // 发送邮件的邮箱名
pass: 'PMRYKCAMVGYXCPJS', // 邮箱的授权码,也可以使用邮箱登陆密码
},
})
/**
* @params{ Object }, 原生 smsParams
TemplateId: "1009319", 默认 // 通用模板
*/
function sendOneSmsRouter(smsParams) {
// 当前 手机号(ID代替) 和 短信验证码验证,是否匹配
sendOneSmsRouter.authVerifyCode = function({id, verify}) {
return module.successArray.find(obj => obj.id===id && String(obj.verify)=== String(verify) )
}
// 删除 successArray中成功的
sendOneSmsRouter.smsOk = function({id}) {
const i = module.successArray.findIndex(obj => obj.id===id)
if (i>=0) {
module.successArray.splice(i, 1)
}
}
//element: 手机号 发送过的队列 - 1分内不能重复发送
module.phoneArray || (module.phoneArray = []) // 可能在一个模块内 调用多次
//element: {id:xxxxxx, verify:12345, } 成功发送验证码的队列 - 8分钟有效期
module.successArray || (module.successArray=[]) // 可能在一个模块内 调用多次
return async function(req,res,next) {try {
let uphone = req.query.uphone || req.query.phone || req.body.uphone || req.body.phone
uphone = uphone.trim()
if (!/^1\d{10}$/.test(uphone)) {
return res.resParamsErr('手机号格式有误')
}
// 1分钟内, 不能发送多次
if (module.phoneArray.find(v => v === uphone)) {
// 找到了,重复
return res.resBadErr('1分钟内,不能多次发送')
}
// 1分钟内,不能多次发送
module.phoneArray.push(uphone)
// 1分钟以后取消
setTimeout(_ => {
const i = module.phoneArray.findIndex(v => v === uphone)
if (i >= 0) {
module.phoneArray.splice(i, 1)
}
}, 60*1000)
// 参数通过
let verify = Math.random().toString().substr(2, 5)
let smsParamsDetail = {
PhoneNumberSet: [`+86${uphone}`],
TemplateId: "1009319", // 通用默认模板
TemplateParamSet: [verify, 8] // 验证码, 8分钟
}
Object.assign(smsParamsDetail, smsParams)
// 发送验证码
const [err, resObj] = await sendOneSms(smsParamsDetail) // 对 reject promise已经处理了
if (err) {
return res.resParamsErr('未知错误 短信发送失败')
}
if (resObj.ok == 1) {
// OK - 返回 ID
const id = resObj.id
//element: {id:xxxxxx, verify:12345, uphone:17538590302, }
module.successArray.push({id, verify})
// 8分钟内失效
setTimeout(_ => {
const findId = id
const i = module.successArray.findIndex(obj => obj.id===findId)
if (i >= 0) {
module.successArray.splice(i, 1)
}
}, 8*60*1000)
return res.resOk({result: {id}})
} else {
return res.resParamsErr('短信发送失败'+resObj.statusObj.Code)
}
} catch(e) {
res.resParamsErr(e)
}}
}
// 零、公共的
// 发送验证码 - query - uphone字段。
r.get('/sendSms', sendOneSmsRouter())
// 零、获取安全信息 - GET
r.get('/safeInfo', async(req,res) => { try {
let _id = ObjectId(req.user.uid)
let query = {_id}
let need = {
projection:{ //需要哪些字段
_id: 0, //uid
uname: 1,
uphone: 1,
umail: 1
}
}
const [err, resObj] = await utils.capture( userLoginTable.findOne(query, need) )
if (err) {
return res.resBadErr(err.message)
}
if (!resObj) {
return res.resBadErr('空的结果')
}
// OK 某些字段可能还没有值
// if (resObj.uphone) {
// resObj.uphone = resObj.uphone.substr(0,3) + '****' + resObj.uphone.substr(-4)
// }
return res.resOk({result: resObj})
// END----------------
} catch(e) {
return res.resParamsErr('代码错误'+e.message)
}})
// 一、修改用户名 - PUT
r.put('/uname',async(req,res) => {try {
let uid = ObjectId(req.user.uid)
let uname = req.query.uname.trim()
if (!/^\w{4,12}$/.test(uname)) { return res.resParamsErr('用户名4-12位字母数字_') }
let infoQuery = { uid }
let loginQuery = { _id: uid }
let upData = {
$set: {
uname: uname
}
}
const promise1 = userInfoTable.updateOne(infoQuery, upData)
const promise2 = userLoginTable.updateOne(loginQuery, upData)
const [err, resArr] = await utils.capture( Promise.all([promise1, promise2]) )
if (err) {
return res.resBadErr('数据库出错'+err.message)
}
if ( resArr[0].modifiedCount===0 ||
resArr[1].modifiedCount===0
) {
return res.resBadErr('请勿重复修改')
}
// OK
res.resOk('修改成功')
} catch(e) {
res.resParamsErr('代码出错,参数不符合'+e.message)
}})
// 二、修改手机号 开始修改 - PUT
r.put('/phone', async(req,res) => { try {
// 携带 id , verify, newPhone
let uid = ObjectId(req.user.uid)
let {id, verify, newPhone} = req.body
if (
!/^1\d{10}$/.test(newPhone) )
{
return res.resParamsErr('手机号格式有误')
}
// id 和 验证码 是否匹配
if (
!sendOneSmsRouter.authVerifyCode({id, verify}) ){
return res.resBadErr('验证码错误')
}
// 更改数据库
const query = { _id: uid }
const update = { $set: { uphone: newPhone} }
let [err, resObj] = await utils.capture( userLoginTable.updateOne(query, update) )
if (err) {
return res.resBadErr('修改失败')
}
if (resObj.modifiedCount===0) {
return res.resBadErr('不要重复点击')
}
// Ok
sendOneSmsRouter.smsOk({id}) //删除
return res.resOk()
// END___------
} catch(e) {
res.resParamsErr('代码有误'+e)
}})
// 发送短信验证码
// 三、绑定邮箱 - PUT
// 发送邮箱验证 - 点击链接
r.get('/sendEmail', (req,res) => {
let email = req.query.email
if ( !/^\w+@\w+[.][a-z]+$/.test(email) ) {
return res.resParamsErr('邮箱格式错误')
}
let tokenData = {
uid: req.user.uid, // 用户ID, 是哪个用户的
umail: email,
isOk: true
}
let url = 'https://tj.testw.top/v1/profile/emailUpdate?token='+generateToken(tokenData)
let text = `尊敬的用户,
您好!欢迎您成为我们的会员!
你的邮箱还没有验证!验证完成后可以使用此邮箱号登录,请<b>点击<b>以下链接验证您的邮箱:
<h4>
<a href="${url}">${url}<a>
</h4>
(如无法点击此链接,请手工将链接复制至浏览器地址栏打开)`
transporter.sendMail(
{
from: 'gaowujie2019@163.com', // 发送人邮箱 必须要和 对应邮箱一直的授权码
to: email, // 接收人邮箱,多个使用数组或用逗号隔开
subject: '途家北京版。', // 主题
html: text, // 邮件正文 可以为 HTML 或者 text
},
(err, info) => {
if (err) {
return res.resDataErr(err)
}
return res.resOk('发送成功,注册查收')
})
})
// 通过验证后绑定邮箱
r.get('/emailUpdate', async(req,res) => {
const tokenData = verifyToken(req.query.token) || {}
if (tokenData.isOk!==true) {
return res.send('<h1>验证过期,请再次提交验证</h1>')
}
// token通过
const query = {_id: ObjectId(tokenData.uid)}
const update = { $set:{ umail: tokenData.umail } }
const [err, resObj] = await utils.capture( userLoginTable.updateOne(query, update) )
if (err) {
return res.send(`<h1>验证失败${err.message}</h1>`)
}
if (resObj.modifiedCount === 0) {
return res.send(`<h1>验证失败${'修改失败'}</h1>`)
}
// OK
res.send('<h1 style="color:rgb(68, 211, 159);"><img src="https://img0.baidu.com/it/u=1891268412,1488093108&fm=26&fmt=auto&gp=0.jpg">验证成功<h1>')
})
// 四、修改密码
r.put('/pwd', async(req, res) => {
try {
//-提交表单: 比对 successArray,
//-报错数据库
//-返回本次提交结果
let uid = ObjectId(req.user.uid)
let newPwd = req.body.newPwd.trim()
let id = req.body.id.trim()
let verify = req.body.verify.trim()
if (newPwd.length < 6 || newPwd.length > 18) {
return res.resParamsErr('密码长度6-18位')
}
// 全是小写字符
if ( /^[a-z]{6,18}$/.test(newPwd) ) {
return res.resParamsErr('密码不能全是小写字母')
}
// 全是大写字母
if ( /^[A-Z]{6,18}$/.test(newPwd) ) {
return res.resParamsErr('密码不能全是大写字母')
}
// 全是数字
if ( /^[0-9]{6,18}$/.test(newPwd) ) {
return res.resParamsErr('密码不能全是数字')
}
if ( /^[.]{6,18}$/.test(newPwd) ) {
return res.resParamsErr('密码不能全是.')
}
if ( /^_{6,18}$/.test(newPwd) ) {
return res.resParamsErr('密码不能全是_')
}
// 包含特殊字符
if (/[^0-9a-zA-Z._@-]/.test(newPwd)) {
return res.resParamsErr('密码不能包含特殊字符')
}
// 密码通过
// 短信验证码进行验证。 id - verify
const authOk = sendOneSmsRouter.authVerifyCode({id, verify})
if ( !authOk ) {
// 超时
return res.resBadErr('验证码过期,请重试')
}
// 验证码OK
// 有值, 保存数据库
const query = {_id: uid}
const upObj = {$set: { upwd:newPwd }}
const [err, resObj] = await utils.capture( userLoginTable.updateOne(query, upObj) )
if (err) {
return res.resBadErr('修改失败'+err.message)
}
if(resObj.modifiedCount===0) {
return res.resBadErr('不要重复修改')
}
res.resOk('修改成功')
sendOneSmsRouter.smsOk({id})
return
//---------- END
} catch(e) {
res.resParamsErr('代码出错'+e.message)
}})
// 发送验证码
// 五、注销账号
r.delete('/user', async(req, res) => { try{
let _id = ObjectId(req.user.uid)
// 谨慎操作。 暂时关闭
return res.resOk('危险操作暂时关闭')
const [err,resObj] = await utils.capture( userLoginTable.deleteOne({_id}) )
const [err2, resObj2] = await utils.capture( userInfoTable.deleteOne({uid:_id}) )
if (err || err2) {
return res.resBadErr('数据库遇到错误'+err.message+err2.message)
}
if (resObj.deletedCount === 0 || resObj2.deletedCount === 0) {
return res.resBadErr('删除失败,稍后重试, 当前账号可能不存在')
}
// delete ok
return res.resOk('删除OK')
// END-----------------
} catch(e) {
res.resParamsErr('代码出错'+e.message)
}})
module.exports = r |
import React from 'react';
import {
BrowserRouter as Router,
Route,
Redirect
} from 'react-router-dom';
import * as ROUTES from '../../constants/routes';
import * as KEYS from '../../constants/strings';
import Home from '../Home/Home';
import SignIn from '../SignIn/SignIn';
import Edit from '../Edit/Edit';
import Resources from '../Resources/Resources';
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
localStorage.getItem(KEYS.STORAGE_KEY)
? <Component {...props} />
: <Redirect to='/signin' />
)} />
)
const App = () => (
<Router>
<div className="body">
<PrivateRoute exact path={ROUTES.HOME} component={Home} />
<Route path={ROUTES.SIGNIN} component={SignIn} />
<PrivateRoute path={ROUTES.EDIT} component={Edit} />
<PrivateRoute path={ROUTES.RESOURCES} component={Resources} />
</div>
</Router>
);
export default App;
|
import React from "react";
export default function PetSupply(props) {
const clog = (msg) => {
console.log(msg);
};
function openTitch() {
window.open("https://www.twitch.tv/directory/following/live");
}
const { name, brand, img } = props;
const Image = ({ img }) => <img src={img} alt="Bird food" />;
const Name = ({ name }) => <h1>{name}</h1>;
const Brand = ({ brand }) => (
<h4 style={({ color: "#e6e6e6" }, { fontSize: ".75rem" })}>{brand}</h4>
);
return (
<article className="petsupply">
<Image img={img}></Image>
<Name name={name} />
<Brand brand={brand} />
<button
onMouseEnter={(evt) => console.log(evt)}
onMouseLeave={() => clog("wtf")}
onDoubleClick={openTitch}
>
Ir ao site
</button>
</article>
);
}
|
import mongoose from 'mongoose';
import validator from 'validator';
// name, email, photo, password, confirmPassword
const UserSchema = mongoose.Schema({
name: {
type: String,
required: [true, 'A User must have a name'],
minlength: [4, 'A User name has to have a minimum of 4 characters'],
maxlength: [20, 'A User name has to have a maximum of 20 characters'],
// validate: [
// validator.isAlphanumeric,
// 'A User name must only contain alphabetic characters or numbers',
// ],
},
email: {
type: String,
required: [true, 'A User must have an email'],
// unique: true,
lowercase: true,
validate: [validator.isEmail, 'Please provide a valid email'],
},
photo: {
type: String,
default: 'default.jpg',
},
password: {
type: String,
required: [true, 'A User must have a password'],
minlength: [7, 'A User password must have minimum of 7 characters'],
select: false,
},
passwordConfirm: {
type: String,
// validate: {
// validator: function (pass) {
// return pass === this.password;
// },
// message: 'Passwords are not the same!',
// },
},
});
const User = mongoose.model('User', UserSchema);
export default User;
|
let express = require('express');
let path = require('path');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let lessMiddleware = require('less-middleware');
let index = require('./routes');
let control = require('./routes/control');
let privacy = require('./routes/privacy');
let testing = require('./routes/testing');
let restv1 = require('./routes/v1/rest');
let apmMiddleware = require('./routes/v1/apmMiddleware');
let v1PatchMiddleware = require('./routes/v1/v1patchmiddleware');
let app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(lessMiddleware(path.join(__dirname, 'public')));
express.static.mime.define({'application/json': ['apple-app-site-association']});
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', apmMiddleware);
app.use('/', v1PatchMiddleware);
app.use('/', index);
app.use('/Control', control);
app.use('/Privacy', privacy);
app.use('/Testing', testing);
app.use('/', restv1);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
function Verify() {
let draftAjax = $.Deferred()
draftAjax.resolve();
return draftAjax.promise();
}
function Save() {
_formInfo = {
formGuid: __FormGuid,
formNum: __FormNum,
flag: true
}
let draftAjax = $.Deferred()
// draftAjax.resolve();
//呼叫信用卡預算控管API
$.when(CreditBudgetSave(__FormGuid)).always(function (data) {
if (data.Status) {
draftAjax.resolve();
} else {
_formInfo.flag = false
draftAjax.reject();
}
}
)
return draftAjax.promise();
}
function completedToFiis() {
let draftAjax = $.Deferred()
$.ajax({
type: 'post',
dataType: 'json',
url: "/EPO/completedToFiis?id=" + __FormNum + "&FillInEmpNum=" + $("#FillInEmpNum").val(),
success: function (data) {
if (data.returnStatus != "S") {
_formInfo.flag = false
draftAjax.reject(data.returnMessage);
// alert("傳送結案資料發生錯誤");
alert("【傳送結案資料發生錯誤】" + data.returnMessage);
}
else {
draftAjax.resolve();
}
console.log(data)
},
error: function () {
draftAjax.reject("傳送結案資料發生錯誤");
alert("傳送結案資料發生錯誤");
}
}
).always(function () {
$("input[Amount]").each(function () {
$(this).val(fun_accountingformatNumberdelzero($(this).val()))
})
})
return draftAjax.promise()
}
$(function () {
$("[Amount]").each(function () {
$(this).text(fun_accountingformatNumberdelzero($(this).text()))
})
$(document).on('click', '#ExpandAllEPODetail', function () {
if ($(this).find('.list-open-icon').length > 0) {
//SwitchHideDisplay([], [$('.EPODetail')]);
$('.EPODetail').show()
$('.AmoDetail').show()
$(this).closest('table').find(".EPODetailSerno").find(".glyphicon-chevron-down").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up")
$(this).closest('table').find(".ExpandInnerDetail a span").text("收合")
} else {
//SwitchHideDisplay([$('.EPODetail')], []);
$('.EPODetail').hide()
$('.AmoDetail').hide()
$(this).closest('table').find(".EPODetailSerno").find(".glyphicon-chevron-up").removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down')
$(this).closest('table').find(".ExpandInnerDetail a span").text("展開")
}
$(this).find('.toggleArrow').toggleClass('list-close-icon list-open-icon')
});
$('[name="ExpandEPODetail"]').on('click', function () {
let tbody = $(this).closest('tbody');
if ($(this).find(".glyphicon-chevron-down").length > 0) {
$(tbody).children('tr').not(':first').not().show()
$(this).find(".glyphicon-chevron-down").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up")
}
else {
$(tbody).children('tr').not(':first').hide()
$(this).find(".glyphicon-chevron-up").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down")
}
});
//分攤明細的展開及收合
$(document).on('click', '.ExpandInnerDetail', function () {
if ($(this).find('span').text() == '展開') {
$(this).parents('.AmoDetail').next().show(200);
$(this).find('span').text('收合');
}
else if ($(this).find('span').text() == '收合') {
$(this).parents('.AmoDetail').next().hide(200);
$(this).find('span').text('展開');
}
//$(this).find('span').toggleText('展開', '收合');
});
//分攤明細層全展開與收合
$(document).on('click', '#EPOAmoIN [name=ExpandAllEPOAmoINDetail]', function () {
if ($(this).find('.list-open-icon').length > 0) {
$(this).closest("table").find("tbody").each(function () {
$(this).find('.glyphicon-chevron-down').removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up")
$(this).find("tr").not(":first").show()
})
$(this).find('.list-open-icon').removeClass('list-open-icon').addClass('list-close-icon')
} else {
$(this).closest("table").find("tbody").each(function () {
$(this).find('.glyphicon-chevron-up').removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down")
$(this).find("tr").not(":first").hide()
})
$(this).find('.list-close-icon').removeClass('list-close-icon').addClass('list-open-icon')
}
});
//分攤明細展開收合
$(document).on('click', '#EPOAmoIN [name="EPOAmoINDetail"]', function () {
let tbody = $(this).closest('tbody');
if ($(this).find(".glyphicon-chevron-down").length > 0) {
$(tbody).find('tr').not(':first').show()
$(this).find(".glyphicon-chevron-down").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up")
}
else {
$(tbody).find('tr').not(':first').hide()
$(this).find(".glyphicon-chevron-up").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down")
}
});
//所得稅欄位抓值
$("#IncomeTaxTable").find("[GetFiisData]").each(function () {
if ($(this).text().trim().length > 0) {
obj = $(this);
//沿用EMP FUN
$.ajax({
type: 'POST',
dataType: 'json',
url: "/EMP/GetTaxSelectedText",
async: false,
data: { sourceKeyId: __FormNum, type: $(this).attr("GetFiisData"), Code: $(this).text().trim() },
success: function (data) {
if (data) {
$(obj).append("-" + data)
}
else {
alert("取得FIIS資料失敗")
}
},
error: function (data) {
alert("讀取FIIS資料失敗")
}
});
}
})
//所得稅欄位抓值
if ($("#P_CurrentStep").val() >= 3) {
$("#accounting-stage-field").show()
}
}) |
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr(),
image: DS.attr(),
cuisine: DS.attr(),
address: DS.attr(),
latitude: DS.attr(),
longitude: DS.attr(),
description: DS.attr(),
comments: DS.hasMany('comment', {async:true})
});
|
import React from 'react';
import { LayoutContainer } from './elements';
const Layout = ({ children }) => <LayoutContainer>{children}</LayoutContainer>;
export default Layout;
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "659b4b1351cf227693d3e914326f1dba",
"url": "/index.html"
},
{
"revision": "deef6dea8736f4d30e2c",
"url": "/static/css/main.66d6f871.chunk.css"
},
{
"revision": "28e1f6e4c00be6f90c95",
"url": "/static/js/2.8fdc7c9c.chunk.js"
},
{
"revision": "deef6dea8736f4d30e2c",
"url": "/static/js/main.7fa91a92.chunk.js"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
}
]); |
import {$,createXhr} from '../../js/util/common';
export default(function(){
var arr=[];
var cart="";
var cartNum="";
if(localStorage.length>=1){
for(var i=0;i<localStorage.length;i++){
var getKey=localStorage.key(i);
var getVal=localStorage.getItem(getKey)
if(getVal!=null){
arr[i]=JSON.parse(getVal)
}
}
}
setTimeout(function(){
if(localStorage.length==0){
document.querySelector(".container>.center>.drop_down-right>ul>li>.cart>.cartNumber").style.display="none";
document.querySelector(".center>.drop_down-right>ul>li:nth-child(3)>ul:nth-child(2)>.noCart").style.display="block"
document.querySelector(".center>.drop_down-right>ul>li:nth-child(3)>ul:nth-child(2)>li").style.display="none"
}else{
document.querySelector(".center>.drop_down-right>ul>li:nth-child(3)>ul>.pr-number>span").style.display="block"
document.querySelector(".container>.center>.drop_down-right>ul>li>.cart>.cartNumber").style.display="block";
document.querySelector(".center>.drop_down-right>ul>li:nth-child(3)>ul:nth-child(2)>.noCart").style.display="none"
}
// 删除指定的商品之后再增加删除的那个商品的时候问题
var nb=0;
var sum=0;
var old_price=0;
var new_price=0;
for(var i=0;i<arr.length;i++){
nb+=arr[i].productNb;
sum+=arr[i].new_price;
cart+='<div>'
cart+='<img src="'+arr[i].imgUrl+'" align="left">'
cart+='<p>'+arr[i].productLn+'</p>'
cart+='<p>价格:¥'+arr[i].new_price
if(arr[i].old_price>0.01){
cart+='<span style="text-decoration:line-through;color:#555;margin-left:10px;">¥31996.00</span>'
}
cart+='</p>'
cart+='<p>数量:<span class="number">'+arr[i].productNb+'</span></p>'
cart+='</div>'
//打折商品
if(arr[i].new_price!=undefined&&arr[i].old_price!=undefined){
new_price+=JSON.parse(arr[i].new_price);
//未打折商品
}else if(arr[i].new_price!=undefined&&arr[i].old_price==undefined){
old_price+=JSON.parse(arr[i].new_price);
}
}
if(old_price>=1&&new_price>=1){
sum=(parseFloat(new_price)+parseFloat(old_price)).toFixed(2);
}else if(new_price>=1&&old_price<=0){
sum=(parseFloat(new_price)).toFixed(2);
}else{
sum=(parseFloat(old_price)).toFixed(2);
}
document.querySelector(".center>.drop_down-right>ul>li:nth-child(3)>ul>.pr-number>span").innerHTML=arr.length+"件商品";
document.querySelector(".Nav>.container>.center>.drop_down-right>ul>li>.cart>.cartNumber").innerHTML=nb;
$("shopping").innerHTML+=cart;
cartNum+='<span>总价:¥'+sum+'</span>'
cartNum+='<div id="goSt">去结算</div>'
document.querySelector(".center>.drop_down-right>ul>li:nth-child(3)>ul>li>.cartNum").innerHTML=cartNum
var shopp=document.querySelectorAll(".drop_down-right>ul>li:nth-child(3) ul>li>div[id=shopping]>div");
if(shopp.length>3){
$("shopping").style='height:170px;overflow-x:hidden'
}
},500)
})(); |
// @flow
import * as React from 'react';
import { View } from 'react-native';
import { Translation } from '@kiwicom/mobile-localization';
import { Text, TextIcon, StyleSheet } from '@kiwicom/mobile-shared';
import { defaultTokens } from '@kiwicom/mobile-orbit';
export default function CreditCardNumberInput() {
return (
<View style={styles.row}>
<TextIcon code="u" style={styles.icon} />
<Text style={styles.text}>
<Translation passThrough=" " />
<Translation id="mmb.trip_services.insurance.payment.header" />
</Text>
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
},
icon: {
color: defaultTokens.colorIconAttention,
fontSize: 16,
},
text: {
color: defaultTokens.colorTextAttention,
fontSize: 16,
},
});
|
import $ from 'jquery';
let updateTime = (time) => {
$('.time').text(time);
};
let percentage = (numerator) => {
var num = (numerator / global.total) * 100
return Math.round(num)
}
let updateStats = (statName) => {
let countElement = $('.' + statName + 'Count')
let newValue = Number(countElement.text()) + 1
countElement.text(newValue);
let percentElement = $('.' + statName + 'Percent')
let percent = percentage(newValue)
percentElement.text(percent + '%');
};
export { updateTime, updateStats }
|
import React, { Component } from "react";
import Header from "./containers/Header/Header.js";
import Video from "./containers/Video/Video.js";
// import Checker from "./containers/Checker/Checker.js";
import About from "./containers/About/About.js";
import Stack from "./containers/Stack/Stack.js";
import Inspiration from "./containers/Inspiration/Inspiration.js";
import Projects from "./containers/Projects/Projects.js";
import Contact from "./containers/Contact/Contact.js";
import Footer from "./containers/Footer/Footer.js";
import "./Landing.css";
class Landing extends Component {
render() {
return (
<div className="container">
<Header />
<Video />
<About />
<Stack />
<Inspiration />
{/* <Checker /> */}
<Projects />
<Contact />
<Footer />
</div>
);
}
}
export default Landing;
|
import React from 'react'
import { connect } from 'react-redux'
const PostShow = ({ post }) => {
return(
<div>
<h3> {post.title}</h3>
</div>
)
}
const mapStateToProps = (state, ownProps) =>{
const post = state.posts.find(post => post.id == ownProps.match.params.postId)
if(post){
return { post }
} else {
return { post: {} }
}
}
export default connect(mapStateToProps)(PostShow)
|
import React from 'react'
import { Icon } from 'react-native-elements'
import SectionedMultiSelect from 'react-native-sectioned-multi-select'
import { COLORS } from '../../../style/theme.style'
const ItemSelector = props => {
const {
name,
hideSearch,
items,
onSelectedItemsChange,
selectedItems
} = props
return (
<SectionedMultiSelect
selectToggleIconComponent={
<Icon name='edit' type='feather' size={20} color={COLORS.ACCENT3} />
}
items={items}
colors={{
success: COLORS.ACCENT3,
primary: COLORS.ACCENT3,
text: COLORS.WHITE,
itemBackground: COLORS.BLACK,
subItemBackground: COLORS.BLACK,
subText: COLORS.WHITE
}}
styles={{
container: { backgroundColor: COLORS.BLACK },
listContainer: { backgroundColor: COLORS.BLACK }
}}
searchPlaceholderText={`Search ${name}`}
readOnlyHeadings={true}
showDropDowns={false}
expandDropDowns={true}
selectedText='selected'
showCancelButton
uniqueKey='id'
subKey='children'
selectText={''}
showChips={false}
onSelectedItemsChange={onSelectedItemsChange}
selectedItems={selectedItems}
/>
)
}
export default ItemSelector
|
// pages/my_coupon/my_coupon.js
var myCoupons = require("../../config.js").myCoupons;
Page({
data: {
opacity: "0.4",
change_img: "https://shop1.helpmake.cn/images/icon/20170830174423.png",
change_img2: "https://wx.helpmake.cn/images/wx/hide.png"
},
onLoad: function (options) {
},
onReady: function () {
},
onShow: function () {
let that = this;
wx.request({
url: myCoupons + "?openid=" + wx.getStorageSync("openid") + "&uid=" + wx.getStorageSync("uid"), //仅为示例,并非真实的接口地址
data: {
},
header: {
'content-type': 'application/json'
},
success: function (res) {
that.setData({
"coupons_list": res.data.msg.conpons_list
})
}
})
},
onShareAppMessage: function () {
if (wx.getStorageSync("dtb_sid")) {
return {
title: wx.getStorageSync("share_title"),
path: '/pages/index/index?dtb_sid=' + wx.getStorageSync("dtb_sid") + "&md5_rtime=" + wx.getStorageSync("md5_rtime"),
imageUrl: wx.getStorageSync("share_img"),
success: function (res) {
// wx.showToast({
// title: '已发送邀请'
// })
},
fail: function (res) {
console.log(res)
}
}
} else {
return {
title: '快来吧,快来吧,这里好多惊喜!',
path: '/pages/index/index',
success: function (res) {
// 转发成功
},
fail: function (res) {
// 转发失败
}
}
}
},
click_get_coupon: function () {
let that = this;
wx.showToast({
title: '领取成功',
icon: 'success',
duration: 2000
})
}
}) |
import { ofType, combineEpics } from 'redux-observable';
import { delay, mapTo, } from 'rxjs/operators';
import { SET_TRUE, SET_FALSE, } from '../actions/types';
const epic1 = (action$, state$) => action$.pipe(
ofType(SET_TRUE),
delay(1000),
mapTo({type: SET_FALSE})
)
const epic2 = (action$, state$) => action$.pipe(
ofType(SET_FALSE),
delay(1000),
mapTo({type: SET_TRUE})
)
export default combineEpics(epic1, epic2);
|
import React, { Component } from 'react';
import { Collapse } from 'react-bootstrap';
import { connect } from 'react-redux';
import cx from 'classnames';
import LandingPage from './../../pages/Login'
class UserInfo extends Component {
state = {
isShowingUserMenu: false
};
render() {
let { user } = this.props;
let UserType = null;
let { isShowingUserMenu } = this.state;
var userObj = JSON.parse(sessionStorage.getItem('userAuth'));
var googleAuthObj = JSON.parse(sessionStorage.getItem('googleAuth'));
user.image = googleAuthObj.profileObj.imageUrl;
if (userObj.PersonType == 2)
{
UserType = "Company User"
}
else if (userObj.PersonType == 3)
{
UserType = "Postman"
}
else
{
UserType = "Customer"
}
return (
<div className="user-wrapper">
<div className="user">
<img src={user.image} alt={user.name} className="photo" />
<div className="userinfo">
<div className="username">
{userObj.FullName}
</div>
<div className="title">{UserType}</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
user: state.Auth.user
});
export default connect(mapStateToProps)(UserInfo);
|
export const Mixin = superclass => class extends superclass{
static get properties() {
return {
selected: {
type: Object,
observer: '_handlePropertyChange',
},
};
}
connectedCallback(){
super.connectedCallback();
this.shadowRoot.addEventListener('slotchange', this._resetProperty());
this._resetProperty();
// requestAnimationFrame(this._initialiseListener.bind(this));
}
_resetProperty(){
// console.log(this.firstElementChild);
// this.firstElementChild.setAttribute('selected', '');
if(!this.selected || this.selected.parentElement !== this){
this.selected = this.firstElementChild;
}
}
_handlePropertyChange(newElement, oldElement){
// console.log(oldElement);
if(oldElement){
oldElement.removeAttribute('selected');
}
// console.log(newElement);
if(newElement){
newElement.setAttribute('selected', '');
}
}
} |
"use strict";
exports.version = void 0;
var version = '21.1.6';
exports.version = version; |
$(document).ready(function () {
$('#grid_prodottialcliente').datagrid({
url:'data/attivita/readProdottiAlCliente.cfm',
rownumbers:false,
fit:true,
fitColumns:true,
singleSelect:true,
border:false,
columns:[[
{field:'idprodotto',title:'Prodotto',width:350,
formatter: function(value,row,index){
//console.log(value, row, index);
if(value.nome){
return value.nome;
} else {
return row.prodotto;
}
}
},
{field:'storicoprezzo',title:'Prezzo',width:55,
formatter: function(value){
if (isNaN(value) || value === '' || value === null){
return ("\u20ac " + '0,00'); // "\u20ac" = simbolo euro
} else {
return accounting.formatMoney(value, "\u20ac ", 2, ".", ",");
}
}
},
{field:'prezzoapplicato',title:'Prz.Finale',width:60,
formatter: function(value){
if (isNaN(value) || value === '' || value === null){
return ("\u20ac " + '0,00');
} else {
return accounting.formatMoney(value, "\u20ac ", 2, ".", ",");
}
},
editor: {
type: 'numberbox',
options:{
min:0,
precision:2,
required:true,
missingMessage:'Campo Obbligatorio',
decimalSeparator: ',',
groupSeparator: '.'
}
}
},
{field:'qty',title:'Qta',width:40,
editor: {
type: 'numberbox',
options:{
min:0,
required:true,
missingMessage:'Campo Obbligatorio'
}
}
},
{field:'staff',title:'Staff',width:85,
editor: {
type: 'combobox',
options:{
panelHeight:'auto',
valueField:'value',
textField:'value',
url:'js/attivita/staff.json'
//required:true,
//missingMessage:'Campo Obbligatorio'
}
}
},
{field:'note',title:'Note',width:220,
editor: {
type: 'textbox',
options:{
height:60,
multiline:true
}
}
},
{field:'idattivita',hidden:'true'},
{field:'ok',align:'center',width:70,
formatter:function(value,row,index){
if (row.editing){
var s = '<button type="button" onclick="salvarigaP(this)">Ok</button> ';
var c = '<br><button type="button" onclick="cancelP(this)">No</button>';
return s+c;
} else {
var e = '<button type="button" onclick="cancellarigaP(this)">X</button> ';
return e;
}
}
}
]],
onBeforeEdit:function(index,row){
row.editing = true;
updateOkP(index);
},
onAfterEdit:function(index,row){
row.editing = false;
updateOkP(index);
},
onCancelEdit:function(index,row){
row.editing = false;
updateOkP(index);
},
onClickRow: function(index, row){
$('#grid_prodottialcliente').datagrid('beginEdit',index);
}
});
});
function getIndiceRigaP(target){
var tr = $(target).closest('tr.datagrid-row');
return parseInt(tr.attr('datagrid-row-index'));
}
function updateOkP(index){
$('#grid_prodottialcliente').datagrid('updateRow',{
index: index,
row:{}
});
}
function cancelP(target){
$('#grid_prodottialcliente').datagrid('deleteRow', getIndiceRigaS(target));
clickP = false;
$('#grid_prodottialcliente').datagrid('reload');
}
function cancellarigaP(target){
$('#grid_prodottialcliente').datagrid('selectRow',getIndiceRigaP(target));
var rowDelP = $('#grid_prodottialcliente').datagrid('getSelected');
//console.log(rowDelP);
if (rowDelP){
$.messager.confirm('Conferma','Sicuro di rimuovere il Prodotto selezionato?',function(r){
if(r){
clickP = false;
$.post('data/attivita/removeProdottoAlCliente.cfm',{id:rowDelP.id});
//console.log(rowDelP);
var pid = rowDelP.idprodotto.id;
ricaricaTot2(pid);
$('#grid_prodotti').datagrid('reload');
$('#grid_elencoprodinatt').datagrid('reload');
}
$('#grid_prodottialcliente').datagrid('reload');
});
}
}
function salvarigaP(target){
var rowP = $('#grid_prodottialcliente').datagrid('getSelected');
var rowAG = $('#grid_attivitagiorno').datagrid('getSelected');
rowP.idattivita = rowAG.id;
$('#grid_prodottialcliente').datagrid('unselectRow',getIndiceRigaP(target));
$('#grid_prodottialcliente').datagrid('endEdit', getIndiceRigaP(target));
clickP = false;
$.post("data/attivita/saveProdottoAlCliente.cfm", rowP, "json");
//console.log(rowP);
//$('#grid_prodottialcliente').datagrid('reload');
$('#grid_prodottialcliente').datagrid('load',{
idattivita: rowP.idattivita
});
//$('#grid_prodotti').datagrid('reload');
if(typeof rowP.idprodotto.id !== 'undefined'){
var pid = rowP.idprodotto.id;
} else {
var pid = rowP.idprodotto;
};
ricaricaTot2(pid);
$('#grid_elencoprodinatt').datagrid('reload');
} |
import { curry } from "../curry/curry"
const _dropLast = curry((count, source) =>
count > source.length ? [] : source.slice(0, source.length - count)
)
/**
* Remove elements from end of array
*
* @param {number} count Number of element to remove (default 1)
* @param {Array} source Source array
*
* @returns {Array}
*
* @tag Array
* @signature (count: number, source: Array): Array
* @signature (source: Array): Array
*/
export const dropLast = count => {
if (Array.isArray(count)) {
return _dropLast(1, count)
}
return _dropLast(count)
}
|
import React from 'react';
import { LanguageProvider } from './src/store/language';
export const wrapRootElement = ({ element }) => {
return <LanguageProvider>{element}</LanguageProvider>;
};
|
var timeLeftElement = document.getElementById('timeLeft')
var resetBtn = document.getElementById('clear')
var pointsElementA = document.getElementById('pointsA')
var pointsElementB = document.getElementById('pointsB')
var playerTurn = document.getElementById('turn')
var speed = 1000
var score = 0
var seconds = 30
var playerAScore = null
var playerBScore = null
var timesPlayed = 0
var currentPlayer = 'playerA'
var fasterButton = document.getElementById('start')
var key = document.getElementsByClassName('key');
var divs = document.querySelectorAll("key div");
var tryMe = document.getElementById('try');
var theIntervalId = null
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var mydiv = document.getElementsByClassName('.mydiv');
var addKeysLoopInterval = null
resetBtn.addEventListener('click', function(e) {
var x = 5
if(x > 0 ){
swal({
title: "You Reset Everything",
text: "Get Ready to Start Over",
icon: "error",
buttons: true,
dangerMode: true,
})
}
})
document.addEventListener('keydown',function(e){
console.log(e.keyCode)
const keyDiv = document.querySelector(`div[data-key='${e.keyCode}']`)
var rect = keyDiv.getBoundingClientRect()
var y = rect.top;
console.log(y)
if(y >= 0 && y <= window.innerHeight) {
console.log('inside')
switch(e.keyCode) {
case 85:
case 65:
case 83:
case 68:
case 70:
case 71:
case 72:
case 74:
case 75:
case 76:
case 81:
case 87:
case 69:
case 82:
case 84:
case 89:
case 73:
case 79:
case 80:
case 90:
case 88:
case 67:
case 86:
case 66:
case 78:
case 77:
addScore()
}
} else {
minusScore()
}
});
function resetGame(){
clearInterval(theIntervalId);
clearTimeout(addKeysLoopInterval);
var keys = document.querySelectorAll(".key");
for (let i=0; i < keys.length; i++){
keys[i].classList.remove('key1');
keys[i].classList.remove('key2');
keys[i].classList.remove('key3');
}
score = 0
pointsElementA.innerHTML = ("Score A: 0")
pointsElementB.innerHTML = ("Score B: 0")
playerTurn.innerHtml = (`${!currentPlayer}`)
speed = 1000
seconds = 30
timeLeftElement.innerHTML = ("Time Left: " + seconds + " seconds")
}
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function myFunction() {
// reset the time on the DOM
resetGame();
clearInterval(theIntervalId);
var keys = Array.from(document.querySelectorAll(".key"));
var randomKeys = shuffle(keys);
addKeysLoopInterval = setTimeout(() => {
var i = 0
function loopAddClass() {
setTimeout(()=> {
console.log(randomKeys[i])
randomKeys[i].classList.toggle('key1')
i++ // increment the counter
if (i < randomKeys.length) { // if the counter < 10, call the loop function
loopAddClass(); // .. again which will trigger another
}
}, 1000)
}
loopAddClass()
}, 100)
console.log(addKeysLoopInterval)
theIntervalId = setInterval(countDown, speed)
}
function myFunction2() {
resetGame();
clearInterval(theIntervalId);
var keys = Array.from(document.querySelectorAll(".key"));
var randomKeys = shuffle(keys);
setTimeout(() => {
var i = 0
function loopAddClass() {
setTimeout(()=> {
console.log(randomKeys[i])
randomKeys[i].classList.toggle('key2')
i++ // increment the counter
if (i < randomKeys.length) { // if the counter < 10, call the loop function
loopAddClass(); // .. again which will trigger another
}
}, 1000)
}
loopAddClass()
}, 100)
theIntervalId = setInterval(countDown, speed)
}
function myFunction3() {
resetGame();
clearInterval(theIntervalId);
var keys = Array.from(document.querySelectorAll(".key"));
var randomKeys = shuffle(keys);
setTimeout(() => {
var i = 0
function loopAddClass() {
setTimeout(()=> {
console.log(randomKeys[i])
randomKeys[i].classList.toggle('key3')
i++ // increment the counter
if (i < randomKeys.length) { // if the counter < 10, call the loop function
loopAddClass(); // .. again which will trigger another
}
}, 1000)
}
loopAddClass()
}, 100)
theIntervalId = setInterval(countDown, speed)
}
function addScore(){
if (currentPlayer === 'playerA' ){
score = score + 10;
pointsElementA.innerHTML = ("Score A: " + score )
} else if (currentPlayer === 'playerB' ){
score = score + 10;
pointsElementB.innerHTML = ("Score B: " + score)
}
}
function minusScore(){
if(currentPlayer === 'playerA'){
score = score - 5;
pointsElementA.innerHTML = ("Score A: " + score)
} else if (currentPlayer === 'playerB') {
score = score - 5;
pointsElementB.innerHTML = ('Score B: ' + score)
}
}
function countDown(){
seconds = seconds - 1;
timeLeftElement.innerHTML = ( "Time Left: " + seconds + " seconds");
if (seconds <= 0){
currentPlayer = "playerB" //kyle
if (currentPlayer === "playerB"){
playerTurn.innerHTML = ('Player B')};
alert("Your score is " + score);
if(playerAScore == null){
playerAScore = score
} else {
playerBScore = score
}
timesPlayed += 1
if(timesPlayed == 2) {
if(playerAScore > playerBScore) {
swal({
title: "Player 1 You've done it",
text: "YOU WON!!!",
icon: "success",
buttons: true,
dangerMode: true,
}).then( ()=>{
location.reload();
});
}
else if(playerBScore > playerAScore) {
swal({
title: "Player 2 You've done it",
text: " YOU WON!!!",
icon: "success",
buttons: true,
dangerMode: true,
}).then( ()=>{
location.reload();
});
} else {
swal({
title: "Amazing",
text: "It's a Tie",
icon: "Warning",
buttons: true,
dangerMode: true,
}).then( ()=>{
location.reload();
});
}
}
theIntervalId = setInterval(countDown,1000)
seconds = 30
timeLeftElement.innerHTML = "Time Left: " + seconds + " seconds"
score = 0
}
}
function playSound(e){
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
if(!audio)return;
audio.currentTime = 0;
audio.play();
key.classList.add('playing');
};
function removeTransition(e){
var elements = document.getElementsByClassName("key");
var i;
for (i = 0; i < elements.length; i++) {
this.classList.remove('playing');
if (e.propertyName !== 'transform')return;
this.classList.remove('playing');
}}
const keys = document.querySelectorAll('.key');
keys.forEach(key => key.addEventListener('transitionend', removeTransition));
window.addEventListener('keydown', playSound)
|
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
//two pointers
let left = 0;
let right = 1;
let maxProfit = 0;
//if left is more than right move both
while(right<=prices.length){
//if left is less than right, save the difference
let buyPrice = prices[left];
let sellPrice = prices[right]
if(buyPrice<sellPrice){
//look at new difference and save as max profit
maxProfit = Math.max(maxProfit, sellPrice-buyPrice);
}
else {
left = right;
}
right++
//move right
}
//return max profit
return maxProfit;
};
// given an array of integers in nonsequential order
// return an integer which is the max profit choosing a single day to buy and then sell
// example: [7,1,5,3,6,4]
//1
//6
//return 5
//example 2: [7,6,4,3,1]
//0
//[3, 4, 7, 1, 2, 3, 8]
//return 4 |
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ['btn', 'reset']
disable() {
this.btnTarget.classList.add('disabled');
this.btnTarget.innerText = 'Bingo!'
}
enable() {
this.btnTarget.classList.remove('disabled');
this.btnTarget.innerText = 'Click me!'
}
} |
describe('Products', () => {
beforeEach(() => {
cy.visit('/');
});
describe('layout', () => {
it('should have header, toolbar, main, and footer', () => {
cy.get('.header').should('be.visible');
cy.get('.toolbar').should('be.visible');
cy.get('.main').should('be.visible');
cy.get('.footer').should('be.visible');
});
});
describe('header', () => {
it('should display the title', () => {
cy.get('.header').should('contain', 'Wishlist Challenge');
});
it('should display the api link', () => {
const header = cy.get('.header').should('contain', 'API');
return header.get('a').invoke('removeAttr', 'target').should('have.attr', 'href')
.then((href) => {
cy.visit(href);
});
});
});
describe('filters', () => {
it('should display type and rating selectors, pagination, and visualization', () => {
cy.get('.form-control choicesjs-stencil[name="typeFilter"]').should('be.visible');
cy.get('.form-control choicesjs-stencil[name="sortingFilter"]').should('be.visible');
cy.get('.pagination').should('be.visible');
cy.get('.btn-group').should('be.visible');
});
});
describe('products', () => {
it('should display the list of products received from the products API', () => {
cy.get('.main').find('.card').should('have.length', 20);
});
it('should display the list of products of the selected page when the page changes', () => {
cy.get('.pagination .pagination__element--arrow--right .btn').click();
cy.get('.main').find('.card').should('have.length', 20);
});
it('should change the visualization when clicking on the list view button', () => {
cy.get('.btn-group .btn').not('.active').click();
cy.get('.main').find('.card.card--horizontal').should('have.length', 20);
});
});
});
|
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
import { createBrowserHistory } from "history";
import { routerMiddleware, connectRouter } from "connected-react-router";
const history = createBrowserHistory();
const initialState = {};
const middleware = [thunk, routerMiddleware(history)];
// Для расширения ReduxDevTools
const composeEnhancers =
typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
})
: compose;
const store = createStore(
connectRouter(history)(rootReducer),
initialState,
composeEnhancers(
applyMiddleware(...middleware)
)
);
export { store, history };
|
import Taro, { Component } from '@tarojs/taro'
import { View, Picker, Input, Button } from '@tarojs/components'
import { AtIcon } from 'taro-ui'
import PropTypes from 'prop-types'
import './index.scss'
class SearchHeader extends Component {
static propTypes = {
searchTypes: PropTypes.array,
onHandleSearch: PropTypes.func
}
constructor() {
super(...arguments)
this.state = {
searchKeyword: '',
selectedType: {
key: '搜索A',
value: 'searchA'
}
}
}
static defaultProps = {
searchTypes: [
{
key: '搜索A',
value: 'searchA'
},
{
key: '搜索B',
value: 'searchB'
},
{
key: '搜索C',
value: 'searchB'
}
]
}
componentDidMount() {
const { searchTypes } = this.props
if (Array.isArray(searchTypes) && searchTypes.length > 0) {
this.setState({ selectedType: searchTypes[0] })
}
}
handleInput = ({ detail }) => {
const { value: searchKeyword } = detail
this.setState({ searchKeyword })
}
handlePickerChange = ({ detail }) => {
const { value: index } = detail
this.setState({ selectedType: this.props.searchTypes[index] })
}
render() {
const { selectedType, searchKeyword } = this.state
const { searchTypes, onHandleSearch } = this.props
return (
<View className='header'>
<View className='search-content'>
<Picker style='padding-right:4px;' className='search-type' mode='selector' range={searchTypes} rangeKey='key' onChange={this.handlePickerChange}>
<View className='customer-type'>
{selectedType.key}
<AtIcon value='chevron-down' size='24' color='rgba(117, 117, 119, 1)'></AtIcon>
</View>
</Picker>
<Input onInput={this.handleInput} className='input-content' type='string' name='keyword' placeholder='请输入查询关键字' value={searchKeyword} />
</View>
<Button className='btn-submit' type='primary' size='small' onClick={onHandleSearch.bind(this, selectedType.value, searchKeyword)}>搜索</Button>
</View>
)
}
}
export default SearchHeader
|
import React from 'react';
import { shallow, configure } from 'enzyme';
import { FeedFooter } from '../../../../../components/module/Feeds';
import Adapter from 'enzyme-adapter-react-16';
configure({adapter: new Adapter()});
describe('render <FeeFooter/> Component', () => {
let component;
beforeEach(() => {
component = shallow(<FeedFooter/>);
});
it('renders feed footer component', () => {
expect(component).toBeTruthy();
});
it('renders .feed-footer class', () => {
expect(component.hasClass('feed-footer')).toBeTruthy();
});
}); |
//imports
const express = require("express");
const bodyparser = require("body-parser");
const app = express();
//to avoid cors errors
const cors=require('cors');
app.use(cors());
//Setting up body parser
//making the request body in the JSON format
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
//setting the person routes
const topcontributorsRoute = require('./routes/topcontributors');
app.use('/topcontributors', topcontributorsRoute);
//Defining the port
const PORT = 3000 || process.env.PORT;
app.listen(PORT, () => {
console.log(`Server running at ${PORT}`);
});
|
var a = 'test'
var b = 'kjjj'
test()
function test () {
console.log('0000')
if (a > b) {
}
}
|
var app=angular.module('zyl',[]); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _mongoose = require('mongoose');
var _mongoose2 = _interopRequireDefault(_mongoose);
var _dev = require('../config/dev.config');
var _dev2 = _interopRequireDefault(_dev);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var conectToDb = async function conectToDb() {
var dbHost = _dev2.default.dbhost;
var dbPort = _dev2.default.dbport;
var dbName = _dev2.default.dbname;
await _mongoose2.default.connect('mongodb://' + dbHost + ':' + dbPort + '/' + dbName);
};
var db = _mongoose2.default.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("db connected!!");
});
exports.default = conectToDb; |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/* DtlsSession enums */
exports.DtlsVersion = Object.freeze({
// NOTE: DTLS version numbers are represented as the ones-complement of the actual values (to easily distinguish DTLS from TLS)
DTLS_1_0: 0xfeff,
properties: {
0xfeff: {name: "DTLS_1_0"},
}
});
exports.isDtlsVersionValid = function(dtlsVersion) {
return (this.DtlsVersion.properties[dtlsVersion] !== undefined);
}
exports.CipherSuite = Object.freeze({
TLS_NULL_WITH_NULL_NULL: 0x0000,
TLS_PSK_WITH_AES_128_CBC_SHA: 0x008C,
TLS_PSK_WITH_AES_256_CBC_SHA: 0x008D,
properties: {
0x0000: {name: "TLS_NULL_WITH_NULL_NULL"},
0x008C: {name: "TLS_PSK_WITH_AES_128_CBC_SHA"},
0x008D: {name: "TLS_PSK_WITH_AES_256_CBC_SHA"},
}
});
exports.isCipherSuiteValid = function(cipherSuite) {
// NOTE: we do not reject the null cipher suite here
return (this.CipherSuite.properties[cipherSuite] !== undefined);
}
exports.isCipherSuiteNull = function() {
return (this.CipherSuite === CipherSuite.TLS_NULL_WITH_NULL_NULL);
}
// NOTE: the number values assigned to KeyExchangeAlgorithm members are for our own use, not from any specification
exports.KeyExchangeAlgorithm = Object.freeze({
NULL: 0x00,
PSK: 0x01,
properties:
{
0x00: {name: "NULL"},
0x01: {name: "PSK"},
}
});
exports.isKeyExchangeAlgorithmValid = function(keyExchangeAlgorithm) {
// NOTE: we do not reject the null key exchange algorithm here
return (this.KeyExchangeAlgorithm.properties[keyExchangeAlgorithm] !== undefined);
}
// NOTE: the number values assigned to BulkEncryptionAlgorithm members are for our own use, not from any specification
exports.BulkEncryptionAlgorithm = Object.freeze({
NULL: 0x00,
AES_128_CBC: 0x01,
AES_256_CBC: 0x02,
properties:
{
0x00: {name: "NULL"},
0x01: {name: "AES_128_CBC"},
0x02: {name: "AES_256_CBC"},
}
});
exports.isBulkEncryptionAlgorithmValid = function(bulkEncryptionAlgorithm) {
// NOTE: we do not reject the null bulk encryption algorithm here
return (this.BulkEncryptionAlgorithm.properties[bulkEncryptionAlgorithm] !== undefined);
}
exports.getBulkAlgorithmKeySize = function(bulkEncryptionAlgorithm) {
switch (bulkEncryptionAlgorithm) {
case this.BulkEncryptionAlgorithm.AES_128_CBC:
return 16;
case this.BulkEncryptionAlgorithm.AES_256_CBC:
return 32;
case this.BulkEncryptionAlgorithm.NULL:
return 0;
default:
// invalid BulkEncryptionAlgorithm
return null;
}
}
exports.getBulkAlgorithmBlockSize = function(bulkEncryptionAlgorithm) {
switch (bulkEncryptionAlgorithm) {
case this.BulkEncryptionAlgorithm.AES_128_CBC:
case this.BulkEncryptionAlgorithm.AES_256_CBC:
return 16;
case this.BulkEncryptionAlgorithm.NULL:
return 1;
default:
// invalid BulkEncryptionAlgorithm
return null;
}
}
exports.getBulkAlgorithmAsString = function(bulkEncryptionAlgorithm) {
switch (bulkEncryptionAlgorithm) {
case this.BulkEncryptionAlgorithm.AES_128_CBC:
return "aes-128-cbc";
case this.BulkEncryptionAlgorithm.AES_256_CBC:
return "aes-256-cbc";
case this.BulkEncryptionAlgorithm.NULL:
return "null";
default:
// invalid BulkEncryptionAlgorithm
return null;
}
}
// NOTE: the number values assigned to MacAlgorithm members are for our own use, not from any specification
exports.MacAlgorithm = Object.freeze({
NULL: 0x00,
SHA1: 0x01,
properties:
{
0x00: {name: "NULL"},
0x01: {name: "SHA1"},
}
});
exports.isMacAlgorithmValid = function(macAlgorithm) {
// NOTE: we do not reject the null mac algorithm here
return (this.MacAlgorithm.properties[macAlgorithm] !== undefined);
}
exports.getMacAlgorithmHashSize = function(macAlgorithm) {
switch (macAlgorithm) {
case this.MacAlgorithm.SHA1:
return 20;
case this.MacAlgorithm.NULL:
return 0;
default:
// invalid MacAlgorithm
return null;
}
}
exports.CompressionMethod = Object.freeze({
// NOTE: DTLS version numbers are represented as the ones-complement of the actual values (to easily distinguish DTLS from TLS)
NULL: 0x00,
properties: {
0x00: {name: "NULL"},
}
});
exports.isCompressionMethodValid = function(compressionMethod) {
return (this.CompressionMethod.properties[compressionMethod] !== undefined);
}
exports.SessionState = Object.freeze({
NotConnected: 0,
ClientHelloSent: 1,
FinishedSent: 2,
properties:
{
0: {name: "NotConnected"},
1: {name: "ClientHelloSent"},
2: {name: "FinishedSent"},
}
});
/* DtlsRecord enums */
const MAX_DTLS_10_COOKIE_LENGTH = 32; // DTLS 1.0
exports.ProtocolType = Object.freeze({
DtlsChangeCipherSpecProtocol: 0x14,
DtlsAlertProtocol: 0x15,
DtlsHandshakeProtocol: 0x16,
DtlsApplicationDataProtocol: 0x17,
properties: {
0x14: {name: "DtlsChangeCipherSpecProtocol"},
0x15: {name: "DtlsAlertProtocol"},
0x16: {name: "DtlsHandshakeProtocol"},
0x17: {name: "DtlsApplicationDataProtocol"}
}
});
exports.isProtocolTypeValid = function(protocolType) {
return (this.ProtocolType.properties[protocolType] !== undefined);
}
exports.getMaximumCookieLength = function(version) {
if (!this.isVersionValid(version)) {
throw new RangeError();
}
switch (version) {
case this.VersionOption.DTLS_1_0:
return MAX_DTLS_10_COOKIE_LENGTH;
default:
// NOTE: this should never be reached, as the isVersionValid(...) call should have eliminated any unknown versions
throw new RangeError();
}
}
/* DtlsChangeCipherSpecMessage enums */
exports.ChangeCipherSpecType = Object.freeze({
One: 0x01,
properties: {
0x01: {name: "One"},
}
});
exports.isChangeCipherSpecTypeValid = function(type) {
return (this.ChangeCipherSpecType.properties[type] !== undefined);
}
/* DtlsHandshakeRecord enums */
exports.MessageType = Object.freeze({
ClientHello: 0x01,
ServerHello: 0x02,
HelloVerifyRequest: 0x03,
ServerHelloDone: 0x0e,
ClientKeyExchange: 0x10,
Finished: 0x14,
properties: {
0x01: {name: "ClientHello"},
0x02: {name: "ServerHello"},
0x03: {name: "HelloVerifyRequest"},
0x0e: {name: "ServerHelloDone"},
0x10: {name: "ClientKeyExchange"},
0x14: {name: "Finished"},
}
});
exports.isMessageTypeValid = function(messageType) {
return (this.MessageType.properties[messageType] !== undefined);
}
/* AlertProtocol enums */
exports.AlertLevel = Object.freeze({
Warning: 1,
Fatal: 2,
properties: {
1: {name: "Warning"},
2: {name: "Fatal"},
}
});
exports.isAlertLevelValid = function(alertLevel) {
return (this.AlertLevel.properties[alertLevel] !== undefined);
}
exports.AlertDescription = Object.freeze({
CloseNotify: 0,
// UnexpectedMessage: 10,
BadRecordMac: 20,
// DecryptionFailed: 21,
// RecordOverflow: 22,
// DecompressionFailure: 30,
// HandshakeFailure: 40,
// NoCertificateRESERVED: 41,
// BadCertificate: 42,
// UnsupportedCertificate: 43,
// CertificateRevoked: 44,
// CertificateExpired: 45,
// CertificateUnknown: 46,
// IllegalParameter: 47,
// UnknownCertificateAuthority: 48,
// AccessDenied: 49,
// DecodeError: 50,
// DecryptError: 51,
// ExportRestrictionRESERVED: 52,
// ProtocolVersion: 70,
// InsufficientSecurity: 71,
// InternalError: 80,
// UserCanceled: 90,
// NoRenegotiation: 100,
properties: {
0: {name: "CloseNotify"},
// 10: {name: "UnexpectedMessage"},
20: {name: "BadRecordMac"},
// 21: {name: "DecryptionFailed"},
// 22: {name: "RecordOverflow"},
// 30: {name: "DecompressionFailure"},
// 40: {name: "HandshakeFailure"},
// 41: {name: "NoCertificateRESERVED"},
// 42: {name: "BadCertificate"},
// 43: {name: "UnsupportedCertificate"},
// 44: {name: "CertificateRevoked"},
// 45: {name: "CertificateExpired"},
// 46: {name: "CertificateUnknown"},
// 47: {name: "IllegalParameter"},
// 48: {name: "UnknownCertificateAuthority"},
// 49: {name: "AccessDenied"},
// 50: {name: "DecodeError"},
// 51: {name: "DecryptError"},
// 52: {name: "ExportRestrictionRESERVED"},
// 70: {name: "ProtocolVersion"},
// 71: {name: "InsufficientSecurity"},
// 80: {name: "InternalError"},
// 90: {name: "UserCanceled"},
// 100: {name: "NoRenegotiation"},
}
});
exports.isAlertDescriptionValid = function(alertDescription) {
return (this.AlertDescription.properties[alertDescription] !== undefined);
}
exports.isAlertFatal = function(alertDescription) {
switch (alertDescription) {
// case this.AlertDescription.UnexpectedMessage:
case this.AlertDescription.BadRecordMac:
// case this.AlertDescription.DecryptionFailed:
// case this.AlertDescription.RecordOverflow:
// case this.AlertDescription.DecompressionFailure:
// case this.AlertDescription.HandshakeFailure:
// case this.AlertDescription.IllegalParameter:
// case this.AlertDescription.UnknownCertificateAuthority:
// case this.AlertDescription.AccessDenied:
// case this.AlertDescription.DecodeError:
// case this.AlertDescription.ProtocolVersion:
// case this.AlertDescription.InsufficientSecurity:
// case this.AlertDescription.InternalError:
return true;
default:
return false;
}
}
|
// keys for all apis
// this isn't secure or appropriate for real applications
// this is for demonstation purposes
var keys = {
oauth: "",
nytimes: "",
goodreads: {
key: "",
secret: ""
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.