code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/******/ (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] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = 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; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; document.addEventListener('DOMContentLoaded', function () { var items = __webpack_require__(1), categoryDefs = __webpack_require__(2), contactDefs = __webpack_require__(3), ResultPage = __webpack_require__(4), LocationPage = __webpack_require__(5), ItemPage = __webpack_require__(6), DirectionsPage = __webpack_require__(7), DogsApp = React.createClass({ displayName: 'DogsApp', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, categoryDefs: React.PropTypes.array, contactDefs: React.PropTypes.array, items: React.PropTypes.array }, getDefaultProps: function getDefaultProps() { return { categoryDefs: categoryDefs, contactDefs: contactDefs, colors: { colorMeta: '#0a5a83', // dark blue hsv(200,92,51) colorSelected: '#80d4ff', // light blue hsx(200,50,100) colorLink: '#0000ff', // blue hsv(240,100,100) colorItem: '#000000', // black colorBackground: '#ffffff' // white }, layout: { lineHeightMeta: '2.5rem', heightCategoryList: '164px', // 4 * (2.5rem + 1px) widthSymbol: '1rem', marginNarrow: '0.5rem', marginWide: '2.5rem' // marginNarrow + 2 * widthCategorySymbol } }; }, getInitialState: function getInitialState() { var props = this.props, categoryMap = {}, indexMap = 0; props.categoryDefs.forEach(function (categoryDef) { categoryMap[categoryDef.key] = categoryDef; }); items.forEach(function (item) { // TODO: Ask Enrique if it is okay to add a property to a props object? item.categoryDef = categoryMap[item.categoryKey]; item.indexMap = ++indexMap; // demo }); return { page: React.createElement(ResultPage, { colors: props.colors, layout: props.layout, categoryDefs: props.categoryDefs, items: items, setItemPage: this.setItemPage, setLocationPage: this.setLocationPage }) }; }, setPage: function setPage(page) { this.setState({ page: page }); }, setItems: function setItems(items) { var props = this.props; this.setState({ page: React.createElement(ResultPage, { colors: props.colors, layout: props.layout, categoryDefs: props.categoryDefs, items: items, setItemPage: this.setItemPage }) }); }, setLocation: function setLocation(location) { // TODO: get items for new location this.setItems(items); }, setLocationPage: function setLocationPage() { var props = this.props, setPrevPage = this.setPage.bind(this, this.state.page); this.setState({ page: React.createElement(LocationPage, { colors: props.colors, layout: props.layout, setLocation: this.setLocation, setPrevPage: setPrevPage }) }); }, setItemPage: function setItemPage(item) { var props = this.props, setPrevPage = this.setPage.bind(this, this.state.page); this.setState({ page: React.createElement(ItemPage, { colors: props.colors, layout: props.layout, contactDefs: props.contactDefs, item: item, setPrevPage: setPrevPage, setDirectionsPage: this.setDirectionsPage }) }); }, setDirectionsPage: function setDirectionsPage(item) { var props = this.props, setPrevPage = this.setPage.bind(this, this.state.page); this.setState({ page: React.createElement(DirectionsPage, { colors: props.colors, layout: props.layout, item: item, setPrevPage: setPrevPage }) }); }, render: function render() { return this.state.page; } }); // TODO: property will become the data API object React.render(React.createElement(DogsApp, { items: items }), document.getElementsByTagName('body')[0]); }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { module.exports = [{ id: 0, categoryKey: 'park', // bar, restaurant, park, event //time: 'yyyy-mm-ddThh:mm:ss +oo:oo', // for event dogFriendly: false, // boolean if possible, otherwise string name: 'Freedom Park', address: '1900 East Boulevard', city: 'Charlotte', state: 'NC', postalCode: '28203', // zip code neighborhood: 'Dilworth, Myers Park', contacts: { phone: '(704) 432-4280', web: 'http://charmeck.org%2Fmecklenburg%2Fcounty%2Fparkandrec%2Fparks%2Fparksbyregion%2Fcentralregion%2Fpages%2Ffreedom.aspx' }, description: '', amenities: ['', ''], // list of strings, or booleans, or object? hours: '', // string? distance: 1.8, // is derived from location of item to current location location: { // unless you know that there is a more useful format latitude: '35 13 37 N', // TODO: specific format longitude: '80 50 36 W' } }, { id: 1, categoryKey: 'park', name: 'Marshall Park', address: '800 East Third Street', city: 'Charlotte', state: 'NC', postalCode: '', neighborhood: '', contacts: { phone: '', web: '' }, description: '', distance: 1.9, location: null }, { id: 2, categoryKey: 'park', name: 'Romare Bearden Park', address: '300 S Church St', city: 'Charlotte', state: 'NC', postalCode: '28202', neighborhood: 'Uptown', contacts: { phone: '', web: '' }, description: '', distance: 0.4, location: null }, { id: 3, categoryKey: 'park', dogFriendly: true, name: 'Frazier Park', address: '1201 W Trade St', city: 'Charlotte', state: 'NC', postalCode: '28202', neighborhood: 'Third Ward', contacts: { phone: '704-432-4280', web: 'http://charmeck.org/mecklenburg/county/ParkandRec/Parks/ParksByRegion/CentralRegion/Pages/frazier.aspx' }, description: '', distance: 1.9, // placeholder location: null }, { id: 4, categoryKey: 'park', dogFriendly: true, name: 'William R. Davie Park', address: '4635 Pineville-Matthews Road', city: 'Charlotte', state: 'NC', postalCode: '28226', neighborhood: 'Arboretum', contacts: { phone: '(704) 541-9880', web: 'http://charmeck.org/mecklenburg/county/ParkandRec/Parks/ParksByRegion/SouthRegion/Pages/WilliamRDavie.aspx' }, description: '', distance: 13, // placeholder location: null }, { id: 5, categoryKey: 'bar', dogFriendly: false, name: 'Dandelion Market', address: '118 W 5th St', city: 'Charlotte', state: 'NC', postalCode: '28202', neighborhood: 'Fourth Ward', contacts: { phone: '(704) 333-7989', web: 'http://www.dandelionmarketcharlotte.com' }, description: '', distance: 0.3, // placeholder location: null }]; /* { id: 7, categoryKey: '', dogFriendly: false, name: '', address: '', city: 'Charlotte', state: 'NC', postalCode: '', neighborhood: '', contacts: { phone: '', web: '' }, description: '', distance: 0, // placeholder location: null } */ /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var srcImage = function (name) { return name + '.svg'; }; module.exports = [{ key: 'bar', text: 'Bars', srcImage: srcImage('glass') }, { key: 'restaurant', text: 'Restaurants', srcImage: srcImage('cutlery') }, { key: 'park', text: 'Parks', srcImage: srcImage('compass') }, { key: 'event', text: 'Events', srcImage: srcImage('calendar') }]; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var srcImage = function (name) { return name + '.svg'; }; module.exports = [{ key: 'phone', srcImage: srcImage('phone'), callback: function (number) { window.alert('Call phone number: ' + number); } }, { key: 'web', srcImage: srcImage('external-link-square'), callback: function (address) { window.open(address); } }]; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8), CategoryList = __webpack_require__(9), ResultList = __webpack_require__(10); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, categoryDefs: React.PropTypes.array, items: React.PropTypes.array, setItemPage: React.PropTypes.func, setLocationPage: React.PropTypes.func }, getInitialState: function getInitialState() { var items = this.props.items, categoriesSelected = {}, props = this.props; props.categoryDefs.forEach(function (categoryDef) { categoriesSelected[categoryDef.key] = false; // all false means unfiltered }); return { initial: true, categoriesSelected: categoriesSelected, itemsFiltered: items.concat() // shallow copy }; }, onCategorySelected: function onCategorySelected(categoryDef) { var categoriesSelected = Object.create(this.state.categoriesSelected), key = categoryDef.key, noneSelected = true, itemsFiltered = []; categoriesSelected[key] = !categoriesSelected[key]; this.props.categoryDefs.forEach(function (categoryDef) { noneSelected = noneSelected && !categoriesSelected[categoryDef.key]; }); this.props.items.forEach(function (item) { if (noneSelected || categoriesSelected[item.categoryKey] === true) { idsFiltered.push(item); } }); this.setState({ initial: false, categoriesSelected: categoriesSelected, itemsFiltered: itemsFiltered }); }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, state = this.state, styleSideBySide = { display: 'flex', alignItems: 'flex-start', width: '100%' }, styleMap = { flexGrow: 1, flexShrink: 1, boxSizing: 'border-box', height: layout.heightCategoryList, borderColor: colors.colorMeta, borderWidth: '1px', borderLeftStyle: 'solid', borderBottomStyle: 'solid' }, initial = state.initial, linkRight = { srcImage: 'search.svg', setPage: props.setLocationPage }, map; if (!initial) { map = React.createElement('img', { style: styleMap, src: 'TODO.jpg', alt: 'Map' }); } return React.createElement( 'div', null, React.createElement(Header, { colors: colors, layout: layout, linkRight: linkRight }), React.createElement( 'div', { style: styleSideBySide }, React.createElement(CategoryList, { colors: colors, layout: layout, initial: state.initial, categoryDefs: props.categoryDefs, categoriesSelected: state.categoriesSelected, onCategorySelected: this.onCategorySelected }), map ), React.createElement(ResultList, { items: state.itemsFiltered, mapIndexDemo: !initial, colors: colors, layout: props.layout, setItemPage: props.setItemPage }) ); } }); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, item: React.PropTypes.object, setPrevPage: React.PropTypes.func }, onClickOK: function onClickOK() { // TODO setLocation() this.props.setPrevPage(); }, onClickCancel: function onClickCancel() { this.props.setPrevPage(); }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, marginWide = layout.marginWide, styleDiv = {}, styleForm = { marginLeft: marginWide, marginRight: marginWide }, styleFieldsetInput = { marginTop: '1rem' }, styleInput = { borderColor: colors.colorItem, borderWidth: '1px', borderStyle: 'solid' }, styleFieldsetButtons = { display: 'flex', alignItems: 'flex-start', marginTop: '1rem' }, styleButton = { backgroundColor: colors.colorBackground, borderColor: colors.colorItem, borderWidth: '1px', borderStyle: 'solid', padding: layout.marginNarrow, marginLeft: marginWide }; return React.createElement( 'div', { style: styleDiv }, React.createElement(Header, { colors: colors, layout: layout }), React.createElement( 'form', { style: styleForm }, React.createElement( 'fieldset', { style: styleFieldsetInput }, React.createElement('input', { type: 'text', style: styleInput }) ), React.createElement( 'fieldset', { style: styleFieldsetButtons }, React.createElement( 'button', { style: styleButton, onClick: this.onClickOK }, 'OK' ), React.createElement( 'button', { style: styleButton, onclick: this.onClickCancel }, 'Cancel' ) ) ) ); } }); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8), ResultItem = __webpack_require__(11), ContactList = __webpack_require__(12); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, contactDefs: React.PropTypes.array, item: React.PropTypes.object, setPrevPage: React.PropTypes.func, setDirectionsPage: React.PropTypes.func }, onClickDirections: function onClickDirections() { // TODO: location too? this.props.setDirectionsPage(this.props.item); }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, marginWide = layout.marginWide, // TO DO: align ContactList at bottom? styleDiv = {}, styleImage = { boxSizing: 'border-box', width: '100%', height: layout.heightCategoryList, borderWidth: '1px', borderBottomStyle: 'solid' }, styleList = { listStyle: 'none', width: '100%' }, stylePara = { display: 'flex', alignItems: 'baseline', marginLeft: marginWide }, styleDirections = { color: colors.colorLink, marginLeft: 'auto', padding: layout.marginNarrow, borderWidth: '1px', borderStyle: 'solid' }, linkLeft = { srcImage: 'angle-left.svg', setPage: props.setPrevPage }, item = props.item; // TODO: description, hours, amenities return React.createElement( 'div', { style: styleDiv }, React.createElement(Header, { colors: colors, layout: layout, linkLeft: linkLeft }), React.createElement('img', { style: styleImage, src: 'TODO.jpg', alt: 'Picture' }), React.createElement( 'ul', { style: styleList }, React.createElement(ResultItem, { colors: colors, layout: layout, item: item }), React.createElement( 'li', null, React.createElement( 'p', { style: stylePara }, React.createElement( 'span', null, item.neighborhood ), React.createElement( 'span', { style: styleDirections, onClick: this.onClickDirections }, 'Directions' ) ) ) ), React.createElement(ContactList, { colors: colors, layout: layout, contactDefs: props.contactDefs, contacts: item.contacts }) ); } }); //display: 'flex', //alignItems: 'flex-start', //alignContent: 'flex-start', //flexWrap: 'wrap', //overflow: 'hidden' /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, item: React.PropTypes.object, setPrevPage: React.PropTypes.func }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, styleDiv = {}, linkLeft = { srcImage: 'angle-left.svg', setPage: props.setPrevPage }; return React.createElement( 'div', { style: styleDiv }, React.createElement(Header, { colors: colors, layout: layout, linkLeft: linkLeft }) ); } }); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, linkLeft: React.PropTypes.object, linkRight: React.PropTypes.object }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, linkLeft = props.linkLeft, linkRight = props.linkRight, marginWide = layout.marginWide, styleHeader = { display: 'flex', alignItems: 'flex-start', boxSizing: 'border-box', lineHeight: layout.lineHeightMeta, width: '100%', paddingLeft: linkLeft ? 0 : marginWide, paddingRight: linkRight ? 0 : marginWide, color: colors.colorMeta, backgroundColor: colors.colorBackground, borderWidth: '2px', borderBottomStyle: 'solid' }, styleHeading = { flexShrink: 1, fontSize: '1.25rem' }, symbolDiv = function symbolDiv(link, alignment) { if (link) { return React.createElement(SymbolDiv, { layout: layout, srcImage: link.srcImage, alignment: alignment, setPage: link.setPage }); } }, symbolDivLeft = symbolDiv(linkLeft, 'left'), symbolDivRight = symbolDiv(linkRight, 'right'); return React.createElement( 'header', { style: styleHeader }, symbolDivLeft, React.createElement( 'h1', { style: styleHeading }, 'Dogs-in' ), symbolDivRight ); } }); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var CategoryItem = __webpack_require__(13); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, initial: React.PropTypes.bool, categoryDefs: React.PropTypes.array, categoriesSelected: React.PropTypes.object, onCategorySelected: React.PropTypes.func }, render: function render() { var props = this.props, categoriesSelected = props.categoriesSelected, onCategorySelected = props.onCategorySelected, colors = props.colors, layout = props.layout, initial = props.initial, style = { listStyle: 'none', width: initial ? '100%' : layout.marginWide }, categoryItems = props.categoryDefs.map(function (categoryDef) { return React.createElement(CategoryItem, { colors: colors, layout: layout, initial: initial, categoryDef: categoryDef, selected: categoriesSelected[categoryDef.key], onCategorySelected: onCategorySelected }); }); return React.createElement( 'ul', { style: style }, categoryItems ); } }); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ResultItem = __webpack_require__(11); module.exports = React.createClass({ displayName: 'exports', propTypes: { items: React.PropTypes.array, mapIndexDemo: React.PropTypes.bool, colors: React.PropTypes.object, layout: React.PropTypes.object, setItemPage: React.PropTypes.func }, style: { listStyle: 'none' }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, resultItems = props.items.map(function (item) { return React.createElement(ResultItem, { item: item, mapIndexDemo: props.mapIndexDemo, colors: colors, layout: layout, setItemPage: props.setItemPage }); }); return React.createElement( 'ul', { style: this.style }, resultItems ); } }); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14), MapIndex = __webpack_require__(15); module.exports = React.createClass({ displayName: 'exports', propTypes: { item: React.PropTypes.object, mapIndexDemo: React.PropTypes.bool, layout: React.PropTypes.object, setItemPage: React.PropTypes.func }, onClick: function onClick() { var props = this.props, setItemPage = props.setItemPage; if (setItemPage) { setItemPage(props.item); } }, render: function render() { var props = this.props, layout = props.layout, inResultPage = !props.setItemPage, styleItem = { display: 'flex', alignItems: 'flex-start', paddingTop: layout.marginNarrow, paddingBottom: layout.marginNarrow, borderWidth: '1px', borderBottomStyle: inResultPage ? 'none' : 'solid' }, styleDiv = { flexShrink: 1 }, styleDistance = { flexShrink: 0, marginLeft: 'auto' // align right }, item = props.item, city = function city() { if (inResultPage) { return React.createElement( 'p', null, item.city + ', ' + item.state + ' ' + item.postalCode ); } }, distance = item.distance + 'mi', index; if (props.mapIndexDemo) { index = item.indexMap; } return React.createElement( 'li', { style: styleItem, onClick: this.onClick }, React.createElement(SymbolDiv, { layout: layout, srcImage: item.categoryDef.srcImage, srcImageOptional: item.dogFriendly ? 'paw.svg' : '' }), React.createElement( 'div', { style: styleDiv }, React.createElement( 'p', null, item.name ), React.createElement( 'p', null, item.address ), city() ), React.createElement( 'span', { style: styleDistance }, distance ), React.createElement(MapIndex, { colors: props.colors, layout: layout, index: index }) ); } }); /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ContactItem = __webpack_require__(16); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, contactDefs: React.PropTypes.array, contacts: React.PropTypes.object }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, contacts = props.contacts, styleList = { listStyle: 'none', width: '100%', marginTop: layout.marginNarrow }, contactItems = []; props.contactDefs.forEach(function (contactDef) { var value = contacts[contactDef.key]; if (value) { contactItems.push(React.createElement(ContactItem, { colors: colors, layout: layout, contactDef: contactDef, value: value })); } }); return React.createElement( 'ul', { style: styleList }, contactItems ); } }); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, initial: React.PropTypes.bool, categoryDef: React.PropTypes.object, selected: React.PropTypes.bool, onCategorySelected: React.PropTypes.func }, onClick: function onClick() { this.props.onCategorySelected(this.props.categoryDef); }, render: function render() { var props = this.props, categoryDef = props.categoryDef, selected = props.selected, colors = props.colors, colorMeta = colors.colorMeta, colorBackground = colors.colorBackground, layout = props.layout, styleItem = { display: 'flex', alignItems: 'flex-start', lineHeight: layout.lineHeightMeta, color: selected ? colorBackground : colorMeta, backgroundColor: selected ? colorMeta : colorBackground, borderWidth: '1px', borderBottomStyle: 'solid' }, styleText = { flexShrink: 1, marginRight: layout.marginNarrow }; if (!props.initial) { styleText.display = 'none'; } return React.createElement( 'li', { style: styleItem, 'aria-clicked': props.selected, onClick: this.onClick }, React.createElement(SymbolDiv, { layout: layout, srcImage: categoryDef.srcImage }), React.createElement( 'span', { style: styleText }, categoryDef.text ) ); } }); /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = React.createClass({ displayName: 'exports', propTypes: { layout: React.PropTypes.object, srcImage: React.PropTypes.string, srcImageOptional: React.PropTypes.string, alignment: React.PropTypes.string, setPage: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { alignment: 'left' }; }, onClick: function onClick() { this.props.setPage(); }, render: function render() { var props = this.props, layout = props.layout, width = layout.widthSymbol, marginNarrow = layout.marginNarrow, left = props.alignment === 'left', styleDiv = { flexShrink: 0, display: 'flex', alignItems: 'flex-start', marginLeft: left ? 0 : 'auto', paddingLeft: left ? 0 : marginNarrow, paddingRight: left ? marginNarrow : 0 }, styleSpan = { flexShrink: 0, width: width, textAlign: 'center' }, styleImage = { height: width }, img = (function (_img) { function img(_x) { return _img.apply(this, arguments); } img.toString = function () { return _img.toString(); }; return img; })(function (srcImage) { if (srcImage) { return React.createElement('img', { style: styleImage, src: srcImage }); } }), span = (function (_span) { function span(_x2) { return _span.apply(this, arguments); } span.toString = function () { return _span.toString(); }; return span; })(function (srcImage) { return React.createElement( 'span', { style: styleSpan }, img(srcImage) ); }), spanImage = span(props.srcImage), spanImageOptional = span(props.srcImageOptional); return React.createElement( 'div', { style: styleDiv, onClick: this.onClick }, left ? spanImageOptional : spanImage, left ? spanImage : spanImageOptional ); } }); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, index: React.PropTypes.number }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, styleDiv = { flexShrink: 0, marginLeft: layout.marginNarrow, minWidth: '2rem', // 2 * layout.widthSymbol, textAlign: 'right' }, padding = '0.25em', styleSpan = { fontWeight: 'bold', color: colors.colorBackground, backgroundColor: colors.colorItem, paddingLeft: padding, paddingRight: padding, borderTopLeftRadius: padding, borderBottomLeftRadius: padding }, index = props.index, span; if (index) { span = React.createElement( 'span', { style: styleSpan }, index ); } return React.createElement( 'div', { style: styleDiv }, span ); } }); /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, contactDef: React.PropTypes.object, value: React.PropTypes.string }, onClick: function onClick() { var props = this.props; props.contactDef.callback(props.value); }, render: function render() { var props = this.props, layout = props.layout, styleItem = { display: 'flex', alignItems: 'flex-start', lineHeight: layout.lineHeightMeta, color: props.colors.colorLink, borderWidth: '1px', borderTopStyle: 'solid' }, styleValue = { flexShrink: 1, marginRight: layout.marginNarrow, whiteSpace: 'nowrap', // TODO: or 2 lines for web address? overflow: 'hidden', textOverflow: 'ellipsis' }; return React.createElement( 'li', { style: styleItem, onClick: this.onClick }, React.createElement(SymbolDiv, { layout: layout, srcImage: props.contactDef.srcImage }), React.createElement( 'span', { style: styleValue }, props.value ) ); } }); /***/ } /******/ ]);
Skookum-Nightshift/who-let-the-dogs-in
prototype.js
JavaScript
gpl-3.0
37,139
<?php /** * index.php用コンテナクラス * * PHP versions 5 * * LICENSE: This source file is licensed under the terms of the GNU General Public License. * * @package Magic3 Framework * @author 平田直毅(Naoki Hirata) <naoki@aplo.co.jp> * @copyright Copyright 2006-2017 Magic3 Project. * @license http://www.gnu.org/copyleft/gpl.html GPL License * @version SVN: $Id$ * @link http://www.magic3.org */ require_once($gEnvManager->getContainerPath() . '/baseWidgetContainer.php'); require_once($gEnvManager->getCurrentWidgetDbPath() . '/product_randomDb.php'); class ec_product_randomWidgetContainer extends BaseWidgetContainer { private $db; // DB接続オブジェクト private $langId; // 言語 private $currencyId; // 現在の通貨ID private $currentPageUrl; // 現在のページ private $viewStyle; // 表示モード private $viewCountArray; // 表示回数更新用 const TARGET_WIDGET = 'ec_disp'; // 呼び出しウィジェットID const PRICE_OBJ_ID = "eclib"; // 価格計算オブジェクトID const REGULAR_PRICE = 'regular'; // 通常価格 const PRODUCT_IMAGE_MEDIUM = 'standard-product'; // 中サイズ商品画像ID const PRODUCT_IMAGE_SMALL = 'small-product'; // 小サイズ商品画像ID const PRODUCT_IMAGE_LARGE = 'large-product'; // 大サイズ商品画像ID const PRODUCT_STATUS_NEW = 'new'; // 商品ステータス新規 const PRODUCT_STATUS_SUGGEST = 'suggest'; // 商品ステータスおすすめ const DEFAULT_TAX_TYPE = 'sales'; // デフォルト税種別 const VIEW_STYLE_SMALL = 'small'; // 表示スタイル(小) const VIEW_STYLE_MEDIUM = 'medium'; // 表示スタイル(中) const VIEW_STYLE_LARGE = 'large'; // 表示スタイル(大) const DEFAULT_ITEM_COUNT = 8; // デフォルトの表示項目数 const DEFAULT_TITLE = '商品ランダム表示'; // デフォルトのタイトル const CSS_FILE = '/skin.css'; // CSSファイルのパス /** * コンストラクタ */ function __construct() { // 親クラスを呼び出す parent::__construct(); // DBオブジェクト作成 $this->db = new product_randomDb(); // EC用共通オブジェクト取得 $this->ecObj = $this->gInstance->getObject(self::PRICE_OBJ_ID); //$this->ecObj->initByDefault(); // デフォルト値で初期化 $this->currencyId = $this->ecObj->getDefaultCurrency(); // 現在の通貨ID } /** * テンプレートファイルを設定 * * _assign()でデータを埋め込むテンプレートファイルのファイル名を返す。 * 読み込むディレクトリは、「自ウィジェットディレクトリ/include/template」に固定。 * * @param RequestManager $request HTTPリクエスト処理クラス * @param object $param 任意使用パラメータ。そのまま_assign()に渡る * @return string テンプレートファイル名。テンプレートライブラリを使用しない場合は空文字列「''」を返す。 */ function _setTemplate($request, &$param) { return 'index.tmpl.html'; } /** * テンプレートにデータ埋め込む * * _setTemplate()で指定したテンプレートファイルにデータを埋め込む。 * * @param RequestManager $request HTTPリクエスト処理クラス * @param object $param 任意使用パラメータ。_setTemplate()と共有。 * @param なし */ function _assign($request, &$param) { // 環境取得 $this->langId = $this->gEnv->getCurrentLanguage(); // 表示言語を取得 // 現在のページURL $this->currentPageUrl = $this->gEnv->createCurrentPageUrl(); // 表示設定を取得 $this->viewStyle = self::VIEW_STYLE_MEDIUM; // 画像中サイズ $viewCount = self::DEFAULT_ITEM_COUNT; // 表示商品数 $condition = 0; // 条件(すべて表示) $statusArray = array(); // 商品ステータス // ウィジェットパラメータ取得 $paramObj = $this->getWidgetParamObj(); if (!empty($paramObj)){ $viewCount = $paramObj->viewCount; // 表示項目数 $condition = $paramObj->condition; // 条件 $statusArray = $paramObj->statusArray; // 商品ステータス } // 商品リストを取得 $this->db->getProductSerial($this->langId, $viewCount, 0, $statusArray, $rows); shuffle($rows); // 配列をシャッフル $productCount = count($rows); for ($i = 0; $i < $productCount; $i++){ $this->productListLoop($i, $rows[$i]); } // 表示回数を更新 $viewCountSize = count($this->viewCountArray); if ($viewCountSize > 0){ // トランザクションスタート $this->db->startTransaction(); for ($i = 0; $i < $viewCountSize; $i++){ $id = $this->viewCountArray[$i][0]; $viewCount = $this->viewCountArray[$i][1] + 1; $updateParam = array(); $updateParam['pe_promote_count'] = $viewCount; $this->db->updateProductRecord($id, $this->langId, $updateParam); } // トランザクション終了 $ret = $this->db->endTransaction(); } } /** * ウィジェットのタイトルを設定 * * @param RequestManager $request HTTPリクエスト処理クラス * @param object $param 任意使用パラメータ。そのまま_assign()に渡る * @return string ウィジェットのタイトル名 */ function _setTitle($request, &$param) { return self::DEFAULT_TITLE; } /** * CSSファイルをHTMLヘッダ部に設定 * * CSSファイルをHTMLのheadタグ内に追加出力する。 * _assign()よりも後に実行される。 * * @param RequestManager $request HTTPリクエスト処理クラス * @param object $param 任意使用パラメータ。 * @return string CSS文字列。出力しない場合は空文字列を設定。 */ function _addCssFileToHead($request, &$param) { return $this->getUrl($this->gEnv->getCurrentWidgetCssUrl() . self::CSS_FILE); } /** * 取得したデータをテンプレートに設定する * * @param int $index 行番号(0~) * @param array $fetchedRow フェッチ取得した行 * @param object $param 未使用 * @return bool true=処理続行の場合、false=処理終了の場合 */ function productListLoop($index, $fetchedRow, $param = null) { $images = array();// 画像URL保存用 // 商品の詳細情報を取得 $ret = $this->db->getProductBySerial($fetchedRow['pt_serial'], $row, $row2, $row3, $row4, $row5); if ($ret){ // 商品ID $id = $row['pt_id']; if (empty($id)) $id = 0; // 参照数 $viewCount = $row['pe_promote_count']; if (empty($viewCount)) $viewCount = 0; // 価格を取得 $priceArray = $this->getPrice($row2, self::REGULAR_PRICE); $price = $priceArray['pp_price']; // 価格 $currency = $priceArray['pp_currency_id']; // 通貨 $taxType = $row['pt_tax_type_id']; // 税種別 $lang = $row['pt_language_id']; // 言語 // 表示額作成 $this->ecObj->setCurrencyType($currency, $lang); // 通貨設定 $this->ecObj->setTaxType($taxType); // 税種別設定 $totalPrice = $this->ecObj->getPriceWithTax($price, $dispPrice); // 税込み価格取得 // 画像を取得 $imageArray = $this->getImage($row3, self::PRODUCT_IMAGE_SMALL);// 商品画像小 $imageUrl_s = $imageArray['im_url']; // URL $imageArray = $this->getImage($row3, self::PRODUCT_IMAGE_MEDIUM);// 商品画像中 $imageUrl_m = $imageArray['im_url']; // URL $imageArray = $this->getImage($row3, self::PRODUCT_IMAGE_LARGE);// 商品画像大 $imageUrl_l = $imageArray['im_url']; // URL // 画像を配列に保存 $images[] = $imageUrl_s; $images[] = $imageUrl_m; $images[] = $imageUrl_l; // 商品ステータスを取得 $statusArray = $this->getStatus($row4, self::PRODUCT_STATUS_NEW);// 新規 $new = $statusArray['ps_value']; $statusArray = $this->getStatus($row4, self::PRODUCT_STATUS_SUGGEST);// おすすめ $suggest = $statusArray['ps_value']; } // 画像小 $destImg_s = ''; if ($this->viewStyle == self::VIEW_STYLE_SMALL){ $imageUrl_s = $this->getProperImage($images, 0); if (empty($imageUrl_s)){ $destImg_s = '<img id="preview_img_small" style="display:none;" '; $destImg_s .= 'width="' . $this->defaultImageSWidth . '" '; $destImg_s .= 'height="' . $this->defaultImageSHeight . '" '; $destImg_s .= '/>'; } else { // URLマクロ変換 $imgUrl = str_replace(M3_TAG_START . M3_TAG_MACRO_ROOT_URL . M3_TAG_END, $this->gEnv->getRootUrl(), $imageUrl_s); $destImg_s = '<img id="preview_img_small" src="' . $this->getUrl($imgUrl) . '" '; $destImg_s .= 'width="' . $this->defaultImageSWidth . '"'; $destImg_s .= ' height="' . $this->defaultImageSHeight . '"'; $destImg_s .= ' />'; } } // 画像中 $destImg_m = ''; if ($this->viewStyle == self::VIEW_STYLE_MEDIUM){ $imageUrl_m = $this->getProperImage($images, 1); if (empty($imageUrl_m)){ $destImg_m = '<img id="preview_img_medium" style="display:none;" '; $destImg_m .= 'width="' . $this->defaultImageMWidth . '" '; $destImg_m .= 'height="' . $this->defaultImageMHeight . '" '; $destImg_m .= '/>'; } else { // URLマクロ変換 $imgUrl = str_replace(M3_TAG_START . M3_TAG_MACRO_ROOT_URL . M3_TAG_END, $this->gEnv->getRootUrl(), $imageUrl_m); $destImg_m = '<img id="preview_img_medium" src="' . $this->getUrl($imgUrl) . '" '; $destImg_m .= 'width="' . $this->defaultImageMWidth . '"'; $destImg_m .= ' height="' . $this->defaultImageMHeight . '"'; $destImg_m .= ' />'; } } // 画像大 $destImg_l = ''; if ($this->viewStyle == self::VIEW_STYLE_LARGE){ $imageUrl_l = $this->getProperImage($images, 2); if (empty($imageUrl_l)){ // 画像が空のとき $destImg_l = '<img id="preview_img_large" style="display:none;" '; $destImg_l .= 'width="' . $this->defaultImageLWidth . '" '; $destImg_l .= 'height="' . $this->defaultImageLHeight . '" '; $destImg_l .= '/>'; } else { // URLマクロ変換 $imgUrl = str_replace(M3_TAG_START . M3_TAG_MACRO_ROOT_URL . M3_TAG_END, $this->gEnv->getRootUrl(), $imageUrl_l); $imageUrl_l = $imgUrl; $destImg_l = '<img id="preview_img_large" src="' . $this->getUrl($imgUrl) . '" '; $destImg_l .= 'width="' . $this->defaultImageLWidth . '"'; $destImg_l .= ' height="' . $this->defaultImageLHeight . '"'; $destImg_l .= ' />'; } } // 商品詳細リンクを作成 $name = '詳細'; // 名前 $linkUrl = $this->gEnv->getDefaultUrl() . '?' . M3_REQUEST_PARAM_PRODUCT_ID . '=' . $id; $link = '<a href="' . $this->getUrl($linkUrl, true) . '" >' . $name . '</a>'; // 画像にリンクを付ける if (!empty($destImg_s)) $destImg_s = '<a href="' . $this->getUrl($linkUrl, true) . '" >' . $destImg_s . '</a>'; if (!empty($destImg_m)) $destImg_m = '<a href="' . $this->getUrl($linkUrl, true) . '" >' . $destImg_m . '</a>'; $row = array( 'id' => $id, // ID 'image' => $this->getUrl($imgUrl), // 画像 'image_s' => $destImg_s, // 画像 'image_m' => $destImg_m, // 画像 'image_l_url' => $this->getUrl($imageUrl_l), // 画像URL 'name' => $this->convertToDispString($row['pt_name']), // 名前 'code' => $this->convertToDispString($row['pt_code']), // 商品コード 'disp_total_price' => $dispPrice, // 税込み価格 'description_short' => $row['pt_description'], // 簡易説明 'product_url' => $this->getUrl($linkUrl, true), // 商品詳細リンクURL 'product_link' => $link // 商品詳細リンク ); $this->tmpl->addVars('product_list', $row); $this->tmpl->parseTemplate('product_list', 'a'); // 表示回数の更新用 $this->viewCountArray[] = array($id, $viewCount); return true; } /** * 価格取得 * * @param array $srcRows 価格リスト * @param string $priceType 価格のタイプ * @return array 取得した価格行 */ function getPrice($srcRows, $priceType) { for ($i = 0; $i < count($srcRows); $i++){ if ($srcRows[$i]['pp_currency_id'] == $this->currencyId && $srcRows[$i]['pp_price_type_id'] == $priceType){ return $srcRows[$i]; } } return array(); } /** * 画像取得 * * @param array $srcRows 画像リスト * @param string $imageType 画像タイプ * @return array 取得した行 */ function getImage($srcRows, $sizeType) { for ($i = 0; $i < count($srcRows); $i++){ if ($srcRows[$i]['im_size_id'] == $sizeType){ return $srcRows[$i]; } } return array(); } /** * 商品ステータス取得 * * @param array $srcRows 取得行 * @param string $type 商品ステータスタイプ * @return array 取得した行 */ function getStatus($srcRows, $type) { for ($i = 0; $i < count($srcRows); $i++){ if ($srcRows[$i]['ps_type'] == $type){ return $srcRows[$i]; } } return array(); } /** * 最適な画像を取得 * * @param array $images 画像へのパス(優先順) * @param int $index 目的の画像のインデックス番号 * @return string パス */ function getProperImage($images, $index) { // 指定画像が存在する場合はそのまま返す if (!empty($images[$index])) return $images[$index]; for ($i = $index + 1; $i < count($images); $i++){ if (!empty($images[$i])) return $images[$i]; } for ($i = 0; $i < $index; $i++){ if (!empty($images[$i])) return $images[$i]; } return ''; } } ?>
magic3org/magic3
widgets/ec_product_random/include/container/ec_product_randomWidgetContainer.php
PHP
gpl-3.0
13,593
#include <iostream> #include <boost/program_options.hpp> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include "rt/filesystem.hpp" #include "rt/io/ImageIO.hpp" #include "rt/io/LandmarkIO.hpp" using namespace rt; namespace po = boost::program_options; namespace fs = rt::filesystem; int main(int argc, char* argv[]) { ///// Parse the command line options ///// // clang-format off po::options_description required("General Options"); required.add_options() ("help,h", "Show this message") ("moving,m", po::value<std::string>()->required(), "Moving image") ("fixed,f", po::value<std::string>()->required(), "Fixed image"); po::options_description ldmOptions("Landmark Registration Options"); ldmOptions.add_options() ("landmarks,l", po::value<std::string>()->required(), "Landmarks file"); po::options_description all("Usage"); all.add(required).add(ldmOptions); // clang-format on // Parse the cmd line po::variables_map parsed; po::store(po::command_line_parser(argc, argv).options(all).run(), parsed); // Show the help message if (parsed.count("help") > 0 || argc < 4) { std::cerr << all << std::endl; return EXIT_SUCCESS; } // Warn of missing options try { po::notify(parsed); } catch (po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl; return EXIT_FAILURE; } fs::path fixedPath = parsed["fixed"].as<std::string>(); fs::path movingPath = parsed["moving"].as<std::string>(); fs::path landmarksFileName = parsed["landmarks"].as<std::string>(); ///// Setup input files ///// // Load the fixed and moving image at 8bpc auto fixed = cv::imread(fixedPath.string()); auto moving = cv::imread(movingPath.string()); // Load the landmarks LandmarkReader landmarkReader(landmarksFileName); landmarkReader.read(); auto fixedLandmarks = landmarkReader.getFixedLandmarks(); auto movingLandmarks = landmarkReader.getMovingLandmarks(); if (fixedLandmarks.size() != movingLandmarks.size()) { std::cerr << "ERROR: Unequal number of landmarks" << std::endl; return EXIT_FAILURE; } for (const auto& p : fixedLandmarks) { cv::Point2f pt{static_cast<float>(p[0]), static_cast<float>(p[1])}; cv::circle(fixed, pt, 10, {0, 255, 0}, -1); } for (const auto& p : movingLandmarks) { cv::Point2f pt{static_cast<float>(p[0]), static_cast<float>(p[1])}; cv::circle(moving, pt, 10, {0, 255, 0}, -1); } fs::path fixedPlot = fixedPath.stem().string() + "_plot.png"; rt::WriteImage(fixedPlot, fixed); fs::path movingPlot = movingPath.stem().string() + "_plot.png"; rt::WriteImage(movingPlot, moving); }
viscenter/registration-toolkit
apps/src/PlotLandmarks.cpp
C++
gpl-3.0
2,843
/* program to compute the CLRT from 3D SFS input is a global 3D sfs file and the corresponding local windows 3D sfs file */ #include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include <cmath> #include <iomanip> using namespace std; // parse a string line to a vector of doubles void line_to_vector (string line, vector<double> & v) { stringstream ssline(line); double d; while(ssline >> d) { v.push_back(d); } } // remove the first and last values from the input vector void zero_freq_remove (vector<double> & v) { v.erase(v.begin() + 0); v.erase(v.begin() + v.size()-1); } // help factor calculation for window SFS scaling double calculate_help_fact (double globalSNPsnr, string filepath) { double help_fact; double windowsSNPsnr; int windowsnr = 0; // will count the number of windows in the windows SFS file string line; // string to store each line of the files vector<double> sfs; // vector to store the elements of each line ifstream windows_sfs (filepath); // input windows SFS file // GET WINDOWS SNPs NUMBER while (getline(windows_sfs, line)) // read windows SFS file line by line { line_to_vector(line, sfs); // parse line zero_freq_remove(sfs); // remove first and last SFS values for (int i = 0; i < sfs.size(); i++) windowsSNPsnr += sfs[i]; // sums up SNPs windowsnr += 1; sfs.clear(); } help_fact = globalSNPsnr / (windowsSNPsnr/windowsnr); // global SNPs number / mean windows SNPs number windows_sfs.close(); return help_fact; } // composite likelihood calculation double calculate_CL (vector<double> & v, double & nrSNPs, double & help_fact) { double CL = 0; double pk = 0; // the CL will be the sum of all p^k values for (int i = 0; i < v.size(); i++) { pk = log( pow((v[i]/nrSNPs), v[i]/help_fact) ); // log transformation CL+=pk; } return CL; } // CLRT calculation double calculate_CLRT (double X, double Y) { double CLRT; CLRT = 2*(X-Y); return CLRT; } // help printout void info() { fprintf(stderr,"Required arguments:\tGlobal 3D SFS file path\n"); fprintf(stderr,"\t\t\tWindows 3D SFS file path\n"); fprintf(stderr,"\t\t\tOutput file name\n"); } // // // MAIN // // // int main (int argc, char *argv[]) { // HELP PRINTOUT if (argc==1) { info(); return 0; } // CHECKING CORRECT ARGUMENT NUMBER if (argc < 4) { cout << "Error: not enough arguments\n"; return 0; // terminate } // OPENING FILES, SETTING VARIABLES ifstream global_sfs (argv[1]); // input files (the global ifstream windows_sfs (argv[2]); // and windows SFS files) if ( !global_sfs.is_open() ) { // checking that the first file was successfully open cout<<"Could not open the global SFS file\n"; return 0; // terminate } if ( !windows_sfs.is_open() ) { // checking that the second file was successfully open cout<<"Could not open the windows SFS file\n"; return 0; // terminate } ofstream clrt_output(argv[3], ios::trunc); // output file to store test results string line; // string to store each line of the files vector<double> sfs; // vector to store the elements of each line double global_CL; // double to store the global CL value double windows_CL; // double to store the CL for each window in turn double CLRT; // double to store the test results // CALCULATE THE GLOBAL COMPOSITE LIKELIHOOD getline(global_sfs, line); // retrieving the first and only line of the line_to_vector(line, sfs); // global SFS file and storing it into a vector zero_freq_remove(sfs); // remove first and last SFS values double globalSNPsnr = 0; for (int i = 0; i < sfs.size(); i++) globalSNPsnr += sfs[i]; // number of SNPs in global SFS double help_fact = calculate_help_fact(globalSNPsnr, argv[2]); global_CL = calculate_CL(sfs, globalSNPsnr, help_fact); sfs.clear(); // CALCULATE WINDOWS CL, CALCULATE AND STORE THE CL RATIO TEST RESULT help_fact = 1; while (getline(windows_sfs, line)) // read windows SFS file line by line { line_to_vector(line, sfs); // parse line zero_freq_remove(sfs); // remove first and last SFS values double windowSNPsnr = 0; for (int i = 0; i < sfs.size(); i++) windowSNPsnr += sfs[i]; // number of SNPs in windows SFS windows_CL = calculate_CL(sfs, windowSNPsnr, help_fact); CLRT = calculate_CLRT(windows_CL, global_CL); clrt_output << setprecision(10) << CLRT << " \n"; sfs.clear(); } // CLOSING FILES global_sfs.close(); windows_sfs.close(); clrt_output.close(); return 0; }
lpmdiaz/pop3D
source/pop3Dclrt.cpp
C++
gpl-3.0
5,014
#region using System; using System.Collections.Generic; using db; using db.data; using wServer.svrPackets; #endregion namespace wServer.realm.worlds { public class BattleArenaMap : World { private readonly Dictionary<string, bool> Flags = new Dictionary<string, bool>(); private readonly string[] RandomEnemies = { "Djinn", "Beholder", "White Demon", "Flying Brain", "Slime God", "Native Sprite God", "Ent God" }; private int FamePot; public List<string> Participants = new List<string>(); private string[] RandomBosses; public int Wave; private Random rand; public BattleArenaMap() { Id = ARENA_PAID; Name = "Battle Arena"; Background = 0; AllowTeleport = true; Flags.Add("started", false); Flags.Add("counting", false); rand = new Random(); base.FromWorldMap( typeof (RealmManager).Assembly.GetManifestResourceStream("wServer.realm.worlds.NewArena.wmap")); } public bool Joinable { get { return !Flags["started"]; } } public bool OutOfBounds(float x, float y) { return ((x <= 3.5 || x >= 29.5f) || (y <= 3.5f || y >= 29.5f)); } private void SpawnEnemies() { var enems = new List<string>(); var r = new Random(); for (var i = 0; i < Math.Ceiling((double) (Wave + Players.Count)/2); i++) { enems.Add(RandomEnemies[r.Next(0, RandomEnemies.Length)]); } var r2 = new Random(); foreach (var i in enems) { var id = XmlDatas.IdToType[i]; var xloc = r2.Next(6, 27) + 0.5f; var yloc = r2.Next(6, 27) + 0.5f; var enemy = Entity.Resolve(id); enemy.Move(xloc, yloc); EnterWorld(enemy); } } private void SpawnBosses() { var enems = new List<string>(); var r = new Random(); for (var i = 0; i < (1); i++) { enems.Add(RandomBosses[r.Next(0, RandomBosses.Length)]); } var r2 = new Random(); foreach (var i in enems) { var id = XmlDatas.IdToType[i]; var xloc = r2.Next(6, 27) + 0.5f; var yloc = r2.Next(6, 27) + 0.5f; var enemy = Entity.Resolve(id); enemy.Move(xloc, yloc); EnterWorld(enemy); } } public void Countdown(int s) { if (s != 0) { if (!Flags["started"]) { foreach (var i in Players) i.Value.Client.SendPacket(new NotificationPacket { Color = new ARGB(0xffff00ff), ObjectId = i.Value.Id, Text = s + " Second" + (s == 1 ? "" : "s") }); Timers.Add(new WorldTimer(1000, (w, t) => Countdown(s - 1))); } else { foreach (var i in Players) i.Value.Client.SendPacket(new NotificationPacket { Color = new ARGB(0xffff00ff), ObjectId = i.Value.Id, Text = (s == 5 ? "Wave " + Wave + " - " : "") + s + " Second" + (s == 1 ? "" : "s") }); Timers.Add(new WorldTimer(1000, (w, t) => Countdown(s - 1))); } } else { if (!Flags["started"]) { Flags["started"] = true; Flags["counting"] = false; } else { Flags["counting"] = false; SpawnEnemies(); SpawnBosses(); } } } public override void Tick(RealmTime time) { base.Tick(time); if (Players.Count > 0) { if (!Flags["started"] && !Flags["counting"]) { foreach (var i in RealmManager.Clients.Values) i.SendPacket(new TextPacket { Stars = -1, BubbleTime = 0, Name = "#Announcement", Text = "A paid arena game has been started. Closing in 1 minute!" }); Flags["counting"] = true; Countdown(60); } else if (Flags["started"] && !Flags["counting"]) { if (Enemies.Count < 1 + Pets.Count) { Wave++; if (Wave < 6) { RandomBosses = new[] {"Red Demon", "Phoenix Lord", "Henchman of Oryx"}; } if (Wave > 5 && Wave < 11) { RandomBosses = new[] {"Red Demon", "Phoenix Lord", "Henchman of Oryx", "Stheno the Snake Queen"}; } if (Wave > 10 && Wave < 16) { RandomBosses = new[] {"Elder Tree", "Stheno the Snake Queen", "Archdemon Malphas", "Septavius the Ghost God"}; } if (Wave > 15 && Wave < 21) { RandomBosses = new[] { "Elder Tree", "Archdemon Malphas", "Septavius the Ghost God", "Thessal the Mermaid Goddess", "Crystal Prisoner" }; } if (Wave > 20) { RandomBosses = new[] { "Thessal the Mermaid Goddess", "Crystal Prisoner", "Tomb Support", "Tomb Defender", "Tomb Attacker", "Oryx the Mad God 2" }; } var db = new Database(); FamePot = Wave*10/(Players.Count == 1 ? 1 : 2); foreach (var i in Players) { i.Value.CurrentFame = i.Value.Client.Account.Stats.Fame = db.UpdateFame(i.Value.Client.Account, FamePot); i.Value.UpdateCount++; i.Value.Client.SendPacket(new NotificationPacket { Color = new ARGB(0xFFFF6600), ObjectId = i.Value.Id, Text = "+" + FamePot + " Fame" }); } db.Dispose(); var Invincible = new ConditionEffect(); Invincible.Effect = ConditionEffectIndex.Invulnerable; Invincible.DurationMS = 6000; var Healing = new ConditionEffect(); Healing.Effect = ConditionEffectIndex.Healing; Healing.DurationMS = 6000; foreach (var i in Players) { i.Value.ApplyConditionEffect(new[] { Invincible, Healing }); } foreach (var i in Players) { try { if (!Participants.Contains(i.Value.Client.Account.Name)) Participants.Add(i.Value.Client.Account.Name); } catch { } } Flags["counting"] = true; Timers.Add(new WorldTimer(1000, (world, t) => Countdown(5))); } else { foreach (var i in Enemies) { if (OutOfBounds(i.Value.X, i.Value.Y)) { LeaveWorld(i.Value); } } } } } else { if (Participants.Count > 0) { new Database().AddToArenaLb(Wave, Participants); Participants.Clear(); } } } } }
dthnider/PhoenixRealms-master
wServer/realm/worlds/BattleArena.cs
C#
gpl-3.0
9,424
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # pylint: disable=too-few-public-methods """State describing the conversion to momentum transfer""" from __future__ import (absolute_import, division, print_function) import json import copy from sans.state.state_base import (StateBase, rename_descriptor_names, BoolParameter, PositiveFloatParameter, ClassTypeParameter, StringParameter) from sans.common.enums import (ReductionDimensionality, RangeStepType, SANSFacility) from sans.state.state_functions import (is_pure_none_or_not_none, is_not_none_and_first_larger_than_second, validation_message) from sans.state.automatic_setters import (automatic_setters) # ---------------------------------------------------------------------------------------------------------------------- # State # ---------------------------------------------------------------------------------------------------------------------- @rename_descriptor_names class StateConvertToQ(StateBase): reduction_dimensionality = ClassTypeParameter(ReductionDimensionality) use_gravity = BoolParameter() gravity_extra_length = PositiveFloatParameter() radius_cutoff = PositiveFloatParameter() wavelength_cutoff = PositiveFloatParameter() # 1D settings q_min = PositiveFloatParameter() q_max = PositiveFloatParameter() q_1d_rebin_string = StringParameter() # 2D settings q_xy_max = PositiveFloatParameter() q_xy_step = PositiveFloatParameter() q_xy_step_type = ClassTypeParameter(RangeStepType) # ----------------------- # Q Resolution specific # --------------------- use_q_resolution = BoolParameter() q_resolution_collimation_length = PositiveFloatParameter() q_resolution_delta_r = PositiveFloatParameter() moderator_file = StringParameter() # Circular aperture settings q_resolution_a1 = PositiveFloatParameter() q_resolution_a2 = PositiveFloatParameter() # Rectangular aperture settings q_resolution_h1 = PositiveFloatParameter() q_resolution_h2 = PositiveFloatParameter() q_resolution_w1 = PositiveFloatParameter() q_resolution_w2 = PositiveFloatParameter() def __init__(self): super(StateConvertToQ, self).__init__() self.reduction_dimensionality = ReductionDimensionality.OneDim self.use_gravity = False self.gravity_extra_length = 0.0 self.use_q_resolution = False self.radius_cutoff = 0.0 self.wavelength_cutoff = 0.0 def validate(self): is_invalid = {} # 1D Q settings if not is_pure_none_or_not_none([self.q_min, self.q_max]): entry = validation_message("The q boundaries for the 1D reduction are inconsistent.", "Make sure that both q boundaries are set (or none).", {"q_min": self.q_min, "q_max": self.q_max}) is_invalid.update(entry) if is_not_none_and_first_larger_than_second([self.q_min, self.q_max]): entry = validation_message("Incorrect q bounds for 1D reduction.", "Make sure that the lower q bound is smaller than the upper q bound.", {"q_min": self.q_min, "q_max": self.q_max}) is_invalid.update(entry) if self.reduction_dimensionality is ReductionDimensionality.OneDim: if self.q_min is None or self.q_max is None: entry = validation_message("Q bounds not set for 1D reduction.", "Make sure to set the q boundaries when using a 1D reduction.", {"q_min": self.q_min, "q_max": self.q_max}) is_invalid.update(entry) if self.q_1d_rebin_string is not None: if self.q_1d_rebin_string == "": entry = validation_message("Q rebin string does not seem to be valid.", "Make sure to provide a valid rebin string", {"q_1d_rebin_string": self.q_1d_rebin_string}) is_invalid.update(entry) elif not is_valid_rebin_string(self.q_1d_rebin_string): entry = validation_message("Q rebin string does not seem to be valid.", "Make sure to provide a valid rebin string", {"q_1d_rebin_string": self.q_1d_rebin_string}) is_invalid.update(entry) # QXY settings if self.reduction_dimensionality is ReductionDimensionality.TwoDim: if self.q_xy_max is None or self.q_xy_step is None: entry = validation_message("Q bounds not set for 2D reduction.", "Make sure that the q_max value bound and the step for the 2D reduction.", {"q_xy_max": self.q_xy_max, "q_xy_step": self.q_xy_step}) is_invalid.update(entry) # Q Resolution settings if self.use_q_resolution: if not is_pure_none_or_not_none([self.q_resolution_a1, self.q_resolution_a2]): entry = validation_message("Inconsistent circular geometry.", "Make sure that both diameters for the circular apertures are set.", {"q_resolution_a1": self.q_resolution_a1, "q_resolution_a2": self.q_resolution_a2}) is_invalid.update(entry) if not is_pure_none_or_not_none([self.q_resolution_h1, self.q_resolution_h2, self.q_resolution_w1, self.q_resolution_w2]): entry = validation_message("Inconsistent rectangular geometry.", "Make sure that both diameters for the circular apertures are set.", {"q_resolution_h1": self.q_resolution_h1, "q_resolution_h2": self.q_resolution_h2, "q_resolution_w1": self.q_resolution_w1, "q_resolution_w2": self.q_resolution_w2}) is_invalid.update(entry) if all(element is None for element in [self.q_resolution_a1, self.q_resolution_a2, self.q_resolution_w1, self.q_resolution_w2, self.q_resolution_h1, self.q_resolution_h2]): entry = validation_message("Aperture is undefined.", "Make sure that you set the geometry for a circular or a " "rectangular aperture.", {"q_resolution_a1": self.q_resolution_a1, "q_resolution_a2": self.q_resolution_a2, "q_resolution_h1": self.q_resolution_h1, "q_resolution_h2": self.q_resolution_h2, "q_resolution_w1": self.q_resolution_w1, "q_resolution_w2": self.q_resolution_w2}) is_invalid.update(entry) if self.moderator_file is None: entry = validation_message("Missing moderator file.", "Make sure to specify a moderator file when using q resolution.", {"moderator_file": self.moderator_file}) is_invalid.update(entry) is_invalid.update({"moderator_file": "A moderator file is required for the q resolution calculation."}) if is_invalid: raise ValueError("StateMoveDetectorISIS: The provided inputs are illegal. " "Please see: {0}".format(json.dumps(is_invalid))) # ---------------------------------------------------------------------------------------------------------------------- # Builder # ---------------------------------------------------------------------------------------------------------------------- class StateConvertToQBuilder(object): @automatic_setters(StateConvertToQ) def __init__(self): super(StateConvertToQBuilder, self).__init__() self.state = StateConvertToQ() def build(self): self.state.validate() return copy.copy(self.state) # ------------------------------------------ # Factory method for StateConvertToQBuilder # ------------------------------------------ def get_convert_to_q_builder(data_info): # The data state has most of the information that we require to define the q conversion. # For the factory method, only the facility/instrument is of relevance. facility = data_info.facility if facility is SANSFacility.ISIS: return StateConvertToQBuilder() else: raise NotImplementedError("StateConvertToQBuilder: Could not find any valid save builder for the " "specified StateData object {0}".format(str(data_info))) # ------------------------------------------- # Free functions # ------------------------------------------- def is_valid_rebin_string(rebin_string): is_valid = True try: values = [float(el) for el in rebin_string.split(",")] if len(values) < 2: is_valid = False elif len(values) == 2: if values[0] > values[1]: is_valid = False elif len(values) % 2 == 1: # odd number of entries step_points = values[::2] if not is_increasing(step_points): is_valid = False else: is_valid = False except: # noqa is_valid = False return is_valid def is_increasing(step_points): return all(el1 <= el2 for el1, el2 in zip(step_points, step_points[1:]))
mganeva/mantid
scripts/SANS/sans/state/convert_to_q.py
Python
gpl-3.0
10,526
package com.akoolla.financebeta.reporting; import java.util.Set; import org.joda.time.DateTime; public interface ITransactionQuery { DateTime getFromDate(); DateTime getToDate(); Set<String> getTransactionTags(); double transactionAmount(); //Range of transactionAmmounts(); double minimumTransactionAmount(); double maximumTransactionAmount(); boolean showSceduledTransactionsOnly(); }
trickyBytes/com.akoolla.financebeta
finance-beta-api/src/main/java/com/akoolla/financebeta/reporting/ITransactionQuery.java
Java
gpl-3.0
398
// // Student.cpp // HorairesExams // // Created by Quentin Peter on 19.11.13. // Copyright (c) 2013 Quentin. All rights reserved. // #include "Student.h" #include "Examen.h" Student::Student(string name, string email, int sciper): a_name(name),a_email(email),a_sciper(sciper){} string Student::name() const{ return a_name; } string Student::eMail(){ return a_email; } int Student::sciper(){ return a_sciper; } bool Student::addExam(Date date,Time time, Examen* ptrExa){ return a_timeTable.addOnDateAndTime(ptrExa, date, time); } void Student::addExam(Date date, Examen* ptr){ a_timeTable.addOnDate(ptr, date); } bool Student::fixeExam(Date date,Time time, Examen* ptrExa, int minDist){ return a_timeTable.addOnDateFarFrom(ptrExa, date, time , minDist); } vector<int> Student::nbrExamenDate(vector<Date> listDate){ vector<int> retour; for (int i(0); i<listDate.size(); i++) { retour.push_back(a_timeTable.numberObjectsOnDate(listDate[i])); } return retour; } int Student::calculerScore(){ //On calcule la distance entre les dates. si une date a plusieurs objets on récupère les crénaux horaires et on les note int score(0); Date precedant(a_timeTable.begin()->first);//La date est la première for (auto it(a_timeTable.begin()); it!= a_timeTable.end(); it++) { //On calcule le nombre de jours depuis le precedant int distanceJours(Date::distance(precedant, it->first)); if (distanceJours<3) {//Si il y a plus de trois jours le score deviens stable score+=distanceJours; } else{ score+=3; } precedant=it->first; //Maintenant on vérifie qu'il n'y aie pas trop d'exas le même jour int nombreExamen(it->second->nombreElement()); if (nombreExamen>2) { score-=10000;//On tue le score si il y a plus de deux exas, Ca ne devrait pas arriver } else if (nombreExamen==2){ score-=1000; //Si on a deux exas, il nous faut les heures vector<Time> heures(it->second->getTime()); if (heures.size()==2) { int distanceHeure (Time::distance(heures[0], heures[1])); //Si la distance est moins que deux heures, l'étudiant ne pourra pas aller a son autre exa if (distanceHeure<2*60) { score-=10000; } else if (distanceHeure<4*60){ //Si on a moins de 4 heures on perd 10 points score-=10; } else if (distanceHeure<6*60){ score -=8; } else{ score-=5; } } else{ cout << "Le score est calculé pour des exas non fixés" <<endl; } } } return score; } Student* Student::newStudent(){ return new Student(a_name,a_email,a_sciper); } void Student::afficher(ofstream& fSave){ fSave<<a_name<<endl; fSave<<a_email<<endl<<endl; for (auto it(a_timeTable.begin()); it!=a_timeTable.end(); it++) { fSave<<endl<<"\t "<<it->first<<endl<<endl; fSave<<*(it->second);//Pas de endl car déjà a la fin de chaque nom } }
impact27/QHoraires
src/objects/Student.cpp
C++
gpl-3.0
3,383
/* * Created on Nov 22, 2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package com.idega.util.logging; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; /** * A class which has helper methods for the standard Java 1.4 logging API * Copyright (c) 2003 idega software * @author <a href="tryggvi@idega.is">Tryggvi Larusson</a> */ public class LoggingHelper { private static String NEWLINE="\n"; private static String TAB="\t"; private static String COLON = ":"; private static String COLON_WITH_SPACE = " : "; private static String DOT = "."; /** * Logs the exception to the anonymous logger with loglevel Warning: * @param e the Exception to log */ public static void logException(Exception e){ Logger logger = Logger.getAnonymousLogger(); logException(e,null,logger,Level.WARNING); } /** * Logs the exception to the default logger of Object catcher with loglevel Warning: * @param e the Exception to log */ public static void logException(Exception e,Object catcher){ Logger logger = Logger.getLogger(catcher.getClass().getName()); logException(e,catcher,logger,Level.WARNING); } /** * Logs the exception to the specified logger with loglevel Warning: * @param e the Exception to log */ public static void logException(Exception e,Object catcher,Logger logger){ logException(e,catcher,logger,Level.WARNING); } public static void logException(Exception e,Object catcher,Logger logger,Level level){ //e.printStackTrace(); StackTraceElement[] ste = e.getStackTrace(); StringBuffer buf = new StringBuffer(e.getClass().getName()); buf.append(COLON_WITH_SPACE); buf.append(e.getMessage()); buf.append(NEWLINE); if(ste.length>0){ buf.append(TAB); buf.append(ste[0].getClassName()); buf.append(DOT); buf.append(ste[0].getMethodName()); buf.append(COLON); buf.append(ste[0].getLineNumber()); buf.append(NEWLINE); } String str = buf.toString(); logger.log(level,str); } public static void getLoggerInfo() { // Get the Log Manager LogManager manager = LogManager.getLogManager(); // Get all defined loggers java.util.Enumeration names = manager.getLoggerNames(); System.out.println("***Begin Logger Information"); // For each logger: show name, level, handlers etc. while (names.hasMoreElements()) { String loggername = (String)names.nextElement(); java.util.logging.Logger logger = manager.getLogger(loggername); System.out.println("-----------------------"); System.out.println("Logger name: >" + logger.getName() + "<"); System.out.println("Logger level: " + logger.getLevel()); // See if a filter is defined if (logger.getFilter() != null) { System.out.println("Using a filter"); } else { System.out.println("No filter used"); } // For each handler: show formatter, level, etc. java.util.logging.Handler[] h = logger.getHandlers(); if (h.length == 0) { System.out.println("No handlers defined"); } for (int i = 0; i < h.length; i++) { if (i == 0) { System.out.println("Handlers:"); } java.util.logging.Formatter f = h[i].getFormatter(); System.out.println(h[i].getClass().getName()); System.out.println(" using formatter: " + f.getClass().getName()); System.out.println(" using level: " + h[i].getLevel()); if (h[i].getFilter() != null) { System.out.println(" using a filter"); } else { System.out.println(" no filter"); } } // See if a parent exists java.util.logging.Logger parent = logger.getParent(); if (parent != null) { System.out.println("Parent: >" + parent.getName() + "<"); } else { System.out.println("No parent"); } } System.out.println("*** End Logger Information"); } }
idega/platform2
src/com/idega/util/logging/LoggingHelper.java
Java
gpl-3.0
4,070
function processData(allText) { var allTextLines = allText.split(/\r\n|\n/); var headers = allTextLines[0].split(','); var lines = []; for (var i=1; i<allTextLines.length; i++) { var data = allTextLines[i].split(','); if (data.length == headers.length) { var tarr = []; for (var j=0; j<headers.length; j++) { tarr.push(headers[j]+":"+data[j]); } lines.push(tarr); } } console.log(lines); } csv = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2" $(document).ready(function() { $.ajax({ type: "POST", url: "/echo/html/", dataType: "text", data: { html: csv }, success: function(data) { processData(data); } }); });
Aakast/self_website
Documents/code/GIT/self_website/scripts/showCSV.js
JavaScript
gpl-3.0
905
<?php include 'zz1.php'; ?> <title>Chat | Ballmanager.de</title> <?php if ($loggedin == 1) { ?> <script type="text/javascript" src="http://s3.amazonaws.com/ballmanager.de/js/jquery.js"></script> <script type="text/javascript"> function nachladen() { $.ajax({ url: '/chat_engine.php', data: { aktion: 'letzte_nachrichten' }, success: function(data) { $("#nachrichten").html(data); }, dataType: 'html' }); } function senden(nachricht) { $.ajax({ url: '/chat_engine.php', data: { nachricht: nachricht, aktion: 'nachricht_erzeugen' }, success: function(data) { $("#contain").text(data); document.chatform.nachricht.value = ''; nachladen(); }, dataType: 'text' }); return false; } </script> <?php } ?> <?php include 'zz2.php'; ?> <?php if ($loggedin == 1) { ?> <?php setTaskDone('open_chat'); // CHAT-SPERREN ANFANG $sql1 = "SELECT MAX(chatSperre) FROM ".$prefix."helferLog WHERE managerBestrafen = '".$cookie_id."'"; $sql2 = mysql_query($sql1); if (mysql_num_rows($sql2) > 0) { $sql3 = mysql_fetch_assoc($sql2); $chatSperreBis = $sql3['MAX(chatSperre)']; if ($chatSperreBis > 0 && $chatSperreBis > time()) { echo addInfoBox('Du bist noch bis zum '.date('d.m.Y H:i', $chatSperreBis).' Uhr für die Kommunikation im Spiel gesperrt. Wenn Dir unklar ist warum, frage bitte das <a class="inText" href="/wio.php">Ballmanager-Team.</a>'); include 'zz3.php'; exit; } } // CHAT-SPERREN ENDE // IGNORIER-LISTE ANFANG $igno1 = "SELECT f2 FROM ".$prefix."freunde WHERE f1 = '".$cookie_id."' AND typ = 'B'"; $igno2 = mysql_query($igno1); $ignoList = array(); while ($igno3 = mysql_fetch_assoc($igno2)) { $ignoList[] = $igno3['f2']; } $_SESSION['ignoList'] = serialize($ignoList); // IGNORIER-LISTE ENDE ?> <script type="text/javascript"> $(document).ready(function() { nachladen(); window.setInterval("nachladen()", 3500); }); function add_smiley(smiley_str) { document.chatform.nachricht.value = document.chatform.nachricht.value+' '+smiley_str; document.getElementById('nachricht').focus(); } function talkTo(username) { document.chatform.nachricht.value = '@'+username+' '; document.chatform.nachricht.focus(); return false; } </script> <?php } ?> <?php if ($loggedin == 1) { ?> <h1>Chat</h1> <?php // NAECHSTER CHAT ABEND ANFANG $heute_tag = date('d', time()); $heute_monat = date('m', time()); $heute_jahr = date('Y', time()); $chatAbendTime = mktime(19, 00, 00, $heute_monat, $heute_tag, $heute_jahr); while (date('w', $chatAbendTime) != 0 OR date('W', $chatAbendTime) % 2 != 0) { $chatAbendTime = getTimestamp('+1 day', $chatAbendTime); } // NAECHSTER CHAT ABEND ENDE $timeout = getTimestamp('-1 hour'); $up1 = "DELETE FROM ".$prefix."chatroom WHERE zeit < ".$timeout; $up2 = mysql_query($up1); echo '<p><strong>REPORT Username</strong> schreiben, um einen User zu melden (nur bei <a href="/regeln.php">Regelverstoß</a>)<br />'; echo '<strong>Usernamen anklicken</strong>, um einen User direkt anzusprechen'; $timeout = getTimestamp('-120 seconds'); $whosOn1 = "SELECT ids, username FROM ".$prefix."users WHERE last_chat > ".$timeout; $whosOn2 = mysql_query($whosOn1); if (mysql_num_rows($whosOn2) > 0) { $whosOnList = 'Chatbot, '; while ($whosOn3 = mysql_fetch_assoc($whosOn2)) { $whosOnList .= '<a href="/manager.php?id='.$whosOn3['ids'].'">'.$whosOn3['username'].'</a>, '; } $whosOnList = substr($whosOnList, 0, -2); echo '<br /><strong>Chatter:</strong> '.$whosOnList; echo '<br /><strong>Nächster Chat-Abend:</strong> '.date('d.m.Y H:i', $chatAbendTime).' Uhr</p>'; } else { echo '</p>'; } echo '<p> <a href="#" onclick="add_smiley(\':)\'); return false;"><img src="http://s3.amazonaws.com/ballmanager.de/images/emoticon_smile.png" alt=":)" title=":)" /></a> <a href="#" onclick="add_smiley(\':D\'); return false;"><img src="http://s3.amazonaws.com/ballmanager.de/images/emoticon_grin.png" alt=":D" title=":D" /></a> <a href="#" onclick="add_smiley(\'=D\'); return false;"><img src="http://s3.amazonaws.com/ballmanager.de/images/emoticon_happy.png" alt="=D" title="=D" /></a> <a href="#" onclick="add_smiley(\':O\'); return false;"><img src="http://s3.amazonaws.com/ballmanager.de/images/emoticon_surprised.png" alt=":O" title=":O" /></a> <a href="#" onclick="add_smiley(\':P\'); return false;"><img src="http://s3.amazonaws.com/ballmanager.de/images/emoticon_tongue.png" alt=":P" title=":P" /></a> <a href="#" onclick="add_smiley(\':(\'); return false;"><img src="http://s3.amazonaws.com/ballmanager.de/images/emoticon_unhappy.png" alt=":(" title=":(" /></a> <a href="#" onclick="add_smiley(\';)\'); return false;"><img src="http://s3.amazonaws.com/ballmanager.de/images/emoticon_wink.png" alt=";)" title=";)" /></a> </p>'; ?> <form name="chatform" action="" method="post" accept-charset="utf-8"> <p><input type="text" name="nachricht" id="nachricht" style="width:300px" /> <input type="submit" value="Senden" onclick="return<?php echo noDemoClick($cookie_id, TRUE); ?> senden(document.chatform.nachricht.value);" /></p> </form> <div id="nachrichten"><noscript>Bitte aktiviere JavaScript in Deinem Browser, um den Chat nutzen zu können!</noscript></div> <div id="contain"></div> <?php } else { ?> <h1>Chat</h1> <p>Du musst angemeldet sein, um diese Seite aufrufen zu können!</p> <?php } ?> <?php include 'zz3.php'; ?>
AnwaltDesTeufels/Ballmanager
Website/chat.php
PHP
gpl-3.0
5,308
/* DA-NRW Software Suite | ContentBroker Copyright (C) 2013 Historisch-Kulturwissenschaftliche Informationsverarbeitung Universität zu Köln This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.uzk.hki.da.cb; import static org.mockito.Mockito.mock; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import de.uzk.hki.da.grid.GridFacade; import de.uzk.hki.da.model.Node; import de.uzk.hki.da.model.Object; import de.uzk.hki.da.model.Package; import de.uzk.hki.da.model.PreservationSystem; import de.uzk.hki.da.model.User; import de.uzk.hki.da.utils.Path; /** * @author Daniel M. de Oliveira */ public class ArchiveReplicationActionTests { private static String workAreaRootPath; private static Node node = new Node(); private static PreservationSystem ps = new PreservationSystem(); Object object = new Object(); @BeforeClass public static void prepareNode() { workAreaRootPath = "src/test/resources/cb/ArchiveReplicationTests/fork/"; node.setWorkAreaRootPath(Path.make(workAreaRootPath)); node.setName("ci"); node.setIdentifier("LN"); } @Before public void setUp(){ setUpObject(); } @Test public void testHappyPath() throws FileNotFoundException, IOException{ node.setReplDestinations("a"); node.setGridCacheAreaRootPath(Path.make(workAreaRootPath)); User c = new User(); c.setShort_name("TEST"); c.setEmailAddress("noreply"); object.setContractor(c); node.setAdmin(c); node.setIdentifier("ci"); ArchiveReplicationAction action = setUpAction(node); action.implementation(); } @Test public void testReplDestsNotSet() throws FileNotFoundException, IOException{ node.setReplDestinations(null); node.setGridCacheAreaRootPath(Path.make(workAreaRootPath)); User c = new User(); c.setShort_name("TEST"); c.setForbidden_nodes("b"); c.setEmailAddress("noreply"); node.setAdmin(c); object.setContractor(c); ArchiveReplicationAction action = setUpAction(node); action.implementation(); } @Test public void testForbiddenNodesNotSet() throws FileNotFoundException, IOException{ node.setReplDestinations("a"); node.setGridCacheAreaRootPath(Path.make(workAreaRootPath)); User c = new User(); c.setEmailAddress("noreply"); c.setShort_name("TEST"); c.setForbidden_nodes(null); object.setContractor(c); ArchiveReplicationAction action = setUpAction(node); action.implementation(); } private void setUpObject(){ object.setIdentifier("identifier"); Package pkg = new Package(); pkg.setDelta(1); object.getPackages().add(pkg); } private ArchiveReplicationAction setUpAction(Node node){ ArchiveReplicationAction action = new ArchiveReplicationAction(); ps.setMinRepls(0); action.setPSystem(ps); GridFacade grid = mock (GridFacade.class); action.setGridRoot(grid); action.setObject(object); action.setLocalNode(node); return action; } }
da-nrw/DNSCore
ContentBroker/src/test/java/de/uzk/hki/da/cb/ArchiveReplicationActionTests.java
Java
gpl-3.0
3,550
package l2s.gameserver.skills.skillclasses; import java.util.List; import l2s.gameserver.model.Creature; import l2s.gameserver.model.Player; import l2s.gameserver.model.Skill; import l2s.gameserver.model.pledge.Clan; import l2s.gameserver.network.l2.components.IStaticPacket; import l2s.gameserver.network.l2.components.SystemMsg; import l2s.gameserver.templates.StatsSet; public class ClanGate extends Skill { public ClanGate(StatsSet set) { super(set); } @Override public boolean checkCondition(Creature activeChar, Creature target, boolean forceUse, boolean dontMove, boolean first) { if(!activeChar.isPlayer()) return false; Player player = (Player) activeChar; if(!player.isClanLeader()) { player.sendPacket(SystemMsg.ONLY_THE_CLAN_LEADER_IS_ENABLED); return false; } IStaticPacket msg = Call.canSummonHere(player); if(msg != null) { activeChar.sendPacket(msg); return false; } return super.checkCondition(activeChar, target, forceUse, dontMove, first); } @Override public void onEndCast(Creature activeChar, List<Creature> targets) { super.onEndCast(activeChar, targets); if(!activeChar.isPlayer()) return; Player player = (Player) activeChar; Clan clan = player.getClan(); clan.broadcastToOtherOnlineMembers(SystemMsg.COURT_MAGICIAN_THE_PORTAL_HAS_BEEN_CREATED, player); } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/skills/skillclasses/ClanGate.java
Java
gpl-3.0
1,353
#----------------------------------------------------------------------------- # Copyright (c) 2013-2020, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt, distributed with this software. # # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception) #----------------------------------------------------------------------------- """ Viewer for archives packaged by archive.py """ from __future__ import print_function import argparse import os import pprint import sys import tempfile import zlib from PyInstaller.loader import pyimod02_archive from PyInstaller.archive.readers import CArchiveReader, NotAnArchiveError from PyInstaller.compat import stdin_input import PyInstaller.log stack = [] cleanup = [] def main(name, brief, debug, rec_debug, **unused_options): global stack if not os.path.isfile(name): print(name, "is an invalid file name!", file=sys.stderr) return 1 arch = get_archive(name) stack.append((name, arch)) if debug or brief: show_log(arch, rec_debug, brief) raise SystemExit(0) else: show(name, arch) while 1: try: toks = stdin_input('? ').split(None, 1) except EOFError: # Ctrl-D print(file=sys.stderr) # Clear line. break if not toks: usage() continue if len(toks) == 1: cmd = toks[0] arg = '' else: cmd, arg = toks cmd = cmd.upper() if cmd == 'U': if len(stack) > 1: arch = stack[-1][1] arch.lib.close() del stack[-1] name, arch = stack[-1] show(name, arch) elif cmd == 'O': if not arg: arg = stdin_input('open name? ') arg = arg.strip() try: arch = get_archive(arg) except NotAnArchiveError as e: print(e, file=sys.stderr) continue if arch is None: print(arg, "not found", file=sys.stderr) continue stack.append((arg, arch)) show(arg, arch) elif cmd == 'X': if not arg: arg = stdin_input('extract name? ') arg = arg.strip() data = get_data(arg, arch) if data is None: print("Not found", file=sys.stderr) continue filename = stdin_input('to filename? ') if not filename: print(repr(data)) else: with open(filename, 'wb') as fp: fp.write(data) elif cmd == 'Q': break else: usage() do_cleanup() def do_cleanup(): global stack, cleanup for (name, arch) in stack: arch.lib.close() stack = [] for filename in cleanup: try: os.remove(filename) except Exception as e: print("couldn't delete", filename, e.args, file=sys.stderr) cleanup = [] def usage(): print("U: go Up one level", file=sys.stderr) print("O <name>: open embedded archive name", file=sys.stderr) print("X <name>: extract name", file=sys.stderr) print("Q: quit", file=sys.stderr) def get_archive(name): if not stack: if name[-4:].lower() == '.pyz': return ZlibArchive(name) return CArchiveReader(name) parent = stack[-1][1] try: return parent.openEmbedded(name) except KeyError: return None except (ValueError, RuntimeError): ndx = parent.toc.find(name) dpos, dlen, ulen, flag, typcd, name = parent.toc[ndx] x, data = parent.extract(ndx) tempfilename = tempfile.mktemp() cleanup.append(tempfilename) with open(tempfilename, 'wb') as fp: fp.write(data) if typcd == 'z': return ZlibArchive(tempfilename) else: return CArchiveReader(tempfilename) def get_data(name, arch): if isinstance(arch.toc, dict): (ispkg, pos, length) = arch.toc.get(name, (0, None, 0)) if pos is None: return None with arch.lib: arch.lib.seek(arch.start + pos) return zlib.decompress(arch.lib.read(length)) ndx = arch.toc.find(name) dpos, dlen, ulen, flag, typcd, name = arch.toc[ndx] x, data = arch.extract(ndx) return data def show(name, arch): if isinstance(arch.toc, dict): print(" Name: (ispkg, pos, len)") toc = arch.toc else: print(" pos, length, uncompressed, iscompressed, type, name") toc = arch.toc.data pprint.pprint(toc) def get_content(arch, recursive, brief, output): if isinstance(arch.toc, dict): toc = arch.toc if brief: for name, _ in toc.items(): output.append(name) else: output.append(toc) else: toc = arch.toc.data for el in toc: if brief: output.append(el[5]) else: output.append(el) if recursive: if el[4] in ('z', 'a'): get_content(get_archive(el[5]), recursive, brief, output) stack.pop() def show_log(arch, recursive, brief): output = [] get_content(arch, recursive, brief, output) # first print all TOCs for out in output: if isinstance(out, dict): pprint.pprint(out) # then print the other entries pprint.pprint([out for out in output if not isinstance(out, dict)]) def get_archive_content(filename): """ Get a list of the (recursive) content of archive `filename`. This function is primary meant to be used by runtests. """ archive = get_archive(filename) stack.append((filename, archive)) output = [] get_content(archive, recursive=True, brief=True, output=output) do_cleanup() return output class ZlibArchive(pyimod02_archive.ZlibArchiveReader): def checkmagic(self): """ Overridable. Check to see if the file object self.lib actually has a file we understand. """ self.lib.seek(self.start) # default - magic is at start of file. if self.lib.read(len(self.MAGIC)) != self.MAGIC: raise RuntimeError("%s is not a valid %s archive file" % (self.path, self.__class__.__name__)) if self.lib.read(len(self.pymagic)) != self.pymagic: print("Warning: pyz is from a different Python version", file=sys.stderr) self.lib.read(4) def run(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--log', default=False, action='store_true', dest='debug', help='Print an archive log (default: %(default)s)') parser.add_argument('-r', '--recursive', default=False, action='store_true', dest='rec_debug', help='Recursively print an archive log (default: %(default)s). ' 'Can be combined with -r') parser.add_argument('-b', '--brief', default=False, action='store_true', dest='brief', help='Print only file name. (default: %(default)s). ' 'Can be combined with -r') PyInstaller.log.__add_options(parser) parser.add_argument('name', metavar='pyi_archive', help="pyinstaller archive to show content of") args = parser.parse_args() PyInstaller.log.__process_options(parser, args) try: raise SystemExit(main(**vars(args))) except KeyboardInterrupt: raise SystemExit("Aborted by user request.") if __name__ == '__main__': run()
etherkit/OpenBeacon2
client/linux-arm/venv/lib/python3.6/site-packages/PyInstaller/utils/cliutils/archive_viewer.py
Python
gpl-3.0
8,195
/** * Copyright 2015 Google Inc. 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. */ package org.shikimori.client.gsm; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.google.android.gms.gcm.GcmListenerService; import org.json.JSONException; import org.json.JSONObject; import org.shikimori.library.tool.push.PushHelperReceiver; import java.util.Iterator; public class MyGcmListenerService extends GcmListenerService { private static final String TAG = "MyGcmListenerService"; /** * Called when message is received. * * @param from SenderID of the sender. * @param data Data bundle containing message data as key/value pairs. * For Set of keys use data.keySet(). */ // [START receive_message] @Override public void onMessageReceived(String from, Bundle data) { String message = data.getString("message"); Log.d(TAG, "From: " + from + " / " + data.toString()); if (!TextUtils.isEmpty(message)) { if(message.startsWith("{")){ try { JSONObject json = new JSONObject(message); Iterator<String> iter = json.keys(); while (iter.hasNext()) { String key = iter.next(); String value = json.optString(key); data.putString(key, value); } } catch (JSONException e) { e.printStackTrace(); } } String action = data.getString("action"); Log.d(TAG, "From: " + from); Log.d(TAG, "Message: " + message); Log.d(TAG, "action: " + action); PushHelperReceiver.onReceive(this, from, data); } //{"action":} // if (from.startsWith("/topics/")) { // // message received from some topic. // } else { // // normal downstream message. // } // [START_EXCLUDE] /** * Production applications would usually process the message here. * Eg: - Syncing with server. * - Store message in local database. * - Update UI. */ /** * In some cases it may be useful to show a notification indicating to the user * that a message was received. */ //sendNotification(message); // [END_EXCLUDE] } // [END receive_message] /** * Create and show a simple notification containing the received GCM message. * * @param message GCM message received. */ // private void sendNotification(String message) { // Intent intent = new Intent(this, MainActivity.class); // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, // PendingIntent.FLAG_ONE_SHOT); // // Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) // .setSmallIcon(R.mipmap.ic_launcher) // .setContentTitle("GCM Message") // .setContentText(message) // .setAutoCancel(true) // .setSound(defaultSoundUri) // .setContentIntent(pendingIntent); // // NotificationManager notificationManager = // (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // // notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); // } }
LeshiyGS/shikimori
app/src/main/java/org/shikimori/client/gsm/MyGcmListenerService.java
Java
gpl-3.0
4,246
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { UserPostsComponent } from './user-posts.component'; describe('UserPostsComponent', () => { let component: UserPostsComponent; let fixture: ComponentFixture<UserPostsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ UserPostsComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(UserPostsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
things-cx/ThingsWebApp
Things.WebApp/src/app/post/user-posts/user-posts.component.spec.ts
TypeScript
gpl-3.0
650
/* * Tweeteria - A minimalistic tweet reader. * Copyright (C) 2017 Andreas Weis (der_ghulbus@ghulbus-inc.de) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TWEETERIA_CLIENT_INCLUDE_GUARD_UI_MAIN_WINDOW_HPP #define TWEETERIA_CLIENT_INCLUDE_GUARD_UI_MAIN_WINDOW_HPP #include <qt_begin_disable_warnings.hpp> #include <QMainWindow> #include <QVector> #include <QBoxLayout> #include <QListWidget> #include <qt_end_disable_warnings.hpp> #include <tweeteria/id_types.hpp> #include <boost/optional.hpp> #include <memory> class CentralWidget; class DataModel; namespace tweeteria { class Tweeteria; struct User; struct Tweet; template <typename T> class MultiPageResult; } class ClientDatabase; class MainWindow : public QMainWindow { Q_OBJECT private: std::shared_ptr<tweeteria::Tweeteria> m_tweeteria; DataModel* m_dataModel; CentralWidget* m_centralWidget; std::unique_ptr<ClientDatabase> m_database; public: MainWindow(std::shared_ptr<tweeteria::Tweeteria> tweeteria, tweeteria::User const& user); ~MainWindow(); void populateUsers(); CentralWidget* getCentralWidget(); signals: void userInfoUpdate(tweeteria::UserId, bool is_friend); void userTimelineUpdate(tweeteria::UserId); void unreadForUserChanged(tweeteria::UserId, int); public slots: void markTweetAsRead(tweeteria::TweetId tweet_id, tweeteria::UserId user_id); void onUserSelectionChange(tweeteria::UserId selected_user_id); void onAdditionalTimelineTweetsRequest(tweeteria::UserId user, tweeteria::TweetId max_id); void onUserTimelineUpdate(tweeteria::UserId user_id); private: void getUserIds_impl(std::shared_ptr<tweeteria::MultiPageResult<std::vector<tweeteria::UserId>>> mpres, std::vector<tweeteria::UserId>&& acc); void getUserDetails_impl(std::vector<tweeteria::User> const& new_users, bool is_friend); void getUserTimeline_impl(tweeteria::UserId user, std::vector<tweeteria::Tweet> const& tweets); void updateLastRead(tweeteria::UserId user_id, boost::optional<tweeteria::TweetId> const& last_read_id); }; #endif
ComicSansMS/tweeteria
client/ui/main_window.hpp
C++
gpl-3.0
2,719
/** * */ package com.dotmarketing.business; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.DbConnectionFactory; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.factories.InodeFactory; import com.dotmarketing.portlets.containers.model.Container; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.structure.model.Field; import com.dotmarketing.portlets.structure.model.Structure; import com.dotmarketing.portlets.templates.model.Template; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.liferay.portal.model.User; /** * @author Jason Tesser * The purpose of this class is to pull things like Templates, Pages, and Files with their respecting permissions * This is needed because if you have a limited user in a system with many object and permissions it can be slow to pull all * WebAssets and then loop over each one filtering out based on permissions. This class provides methods which get what is needed * in 1-2 DB pulls per call. This can be faster in the large systems. */ public class PermissionedWebAssetUtil { /** * THIS METHOD WILL HIT DB AT LEAST ONCE. It loads the templatesIds to load then trys to load from Cache or go back * to DB using Hibernate to load the ones not in cache with a single Hibernate query (if there are more then 500 it will actually go back to * db for each 500 as it does an IN (..)). * NOTE: Returns working templates * @param searchString - Can be null or empty. Can be used as a filter. Will Search Template TITLE and Host (if searchHost is True) * @param dbColSort - Name of the DB Column to sort by. If left null or empty will sort by template name by default * @param offset * @param limit * @param permission - The required Permission needed to pull template * @param user * @param respectFrontEndPermissions * @return * @throws DotSecurityException * @throws DotDataException */ public static List<Template> findTemplatesForLimitedUser(String searchString, String hostName, boolean searchHost,String dbColSort ,int offset, int limit,int permission, User user, boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException{ // PermissionAPI perAPI = APILocator.getPermissionAPI(); // UserAPI uAPI = APILocator.getUserAPI(); // if(uAPI.isCMSAdmin(user)){ // if(UtilMethods.isSet(searchString)){ // return InodeFactory.getInodesOfClassByConditionAndOrderBy(Template.class, "lower(title) LIKE '%" + templateName.toLowerCase() + "%'", dbColSort,limit, offset); // }else{ // return InodeFactory.getInodesOfClass(Template.class, dbColSort,limit, offset); // } // }else{ offset = offset<0?0:offset; String hostQuery = null; if(searchHost){ Structure st = CacheLocator.getContentTypeCache().getStructureByVelocityVarName("Host"); Field hostNameField = st.getFieldVar("hostName"); List<Contentlet> list = null; try { String query = "+structureInode:" + st.getInode() + " +working:true"; if(UtilMethods.isSet(hostName)){ query += " +" + hostNameField.getFieldContentlet() + ":" + hostName; } list = APILocator.getContentletAPI().search(query, 0, 0, null, user, respectFrontEndPermissions); } catch (Exception e) { Logger.error(PermissionedWebAssetUtil.class,e.getMessage(),e); } if(list!=null){ if(list.size()>0){ hostQuery = "identifier.host_inode IN ("; } boolean first = true; for (Contentlet contentlet : list) { if(!first){ hostQuery+=","; } hostQuery+="'" + contentlet.getIdentifier() + "'"; first = false; } if(hostQuery != null){ hostQuery+=")"; } } } ArrayList<ColumnItem> columnsToOrderBy = new ArrayList<ColumnItem>(); ColumnItem templateTitle = new ColumnItem("title", "template", null, true, OrderDir.ASC); //ColumnItem hostName = new ColumnItem("title", "contentlet", "host_name", true, OrderDir.ASC); //columnsToOrderBy.add(hostName); columnsToOrderBy.add(templateTitle); List<String> tIds = queryForAssetIds("template, identifier, inode, template_version_info ", new String[] {Template.class.getCanonicalName(), Template.TEMPLATE_LAYOUTS_CANONICAL_NAME}, "template.inode", "identifier.id", "template.identifier = identifier.id and inode.inode = template.inode and " + "identifier.id=template_version_info.identifier and template_version_info.working_inode=template.inode and " + "template_version_info.deleted="+DbConnectionFactory.getDBFalse() + ( UtilMethods.isSet(searchString) ? " and (lower(template.title) LIKE '%" + searchString.toLowerCase() + "%'" +(UtilMethods.isSet(hostQuery)? " AND (" + hostQuery + ")":"") + ")": (UtilMethods.isSet(hostQuery)? " AND (" + hostQuery + ")":"") ) , columnsToOrderBy, offset, limit, permission, respectFrontEndPermissions, user); // CacheLocator.getTemplateCache(). if(tIds != null && tIds.size()>0){ StringBuilder bob = new StringBuilder(); for (String s : tIds) { bob.append("'").append(s).append("',"); } return InodeFactory.getInodesOfClassByConditionAndOrderBy(Template.class, "inode in (" + bob.toString().subSequence(0, bob.toString().length()-1) + ")", dbColSort); }else{ return new ArrayList<Template>(); } // } } /** * THIS METHOD WILL HIT DB AT LEAST ONCE. It loads the templatesIds to load then trys to load from Cache or go back * to DB using Hibernate to load the ones not in cache with a single Hibernate query (if there are more then 500 it will actually go back to * db for each 500 as it does an IN (..)). * NOTE: Returns working templates * @param searchString - Can be null or empty. Can be used as a filter. Will Search Template TITLE and Host (if searchHost is True) * @param dbColSort - Name of the DB Column to sort by. If left null or empty will sort by template name by default * @param offset * @param limit * @param permission - The required Permission needed to pull template * @param user * @param respectFrontEndPermissions * @return * @throws DotSecurityException * @throws DotDataException */ public static List<Structure> findStructuresForLimitedUser(String searchString, Integer structureType ,String dbColSort ,int offset, int limit,int permission, User user, boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException{ offset = offset<0?0:offset; ArrayList<ColumnItem> columnsToOrderBy = new ArrayList<ColumnItem>(); ColumnItem structureTitle = new ColumnItem(dbColSort, "structure", null, true, OrderDir.ASC); columnsToOrderBy.add(structureTitle); List<String> tIds = queryForAssetIds("structure, inode", new String[] {Structure.class.getCanonicalName()}, "structure.inode", "inode.inode", "inode.inode = structure.inode " + ( UtilMethods.isSet(searchString) ? " and (lower(structure.name) LIKE '%" + searchString.toLowerCase() + "%'" +(structureType!=null? " AND structuretype = "+ structureType.intValue():"") + ")": (structureType!=null? " AND structuretype = "+ structureType.intValue():"") ) , columnsToOrderBy, offset, limit, permission, respectFrontEndPermissions, user); if(tIds != null && tIds.size()>0){ StringBuilder bob = new StringBuilder(); for (String s : tIds) { bob.append("'").append(s).append("',"); } return InodeFactory.getInodesOfClassByConditionAndOrderBy(Structure.class, "inode in (" + bob.toString().subSequence(0, bob.toString().length()-1) + ")", dbColSort); }else{ return new ArrayList<Structure>(); } // } } /** * Returns the list of {@link Container} objects that the current user has * access to. This will retrieve a final list of results with a single * query, instead of programmatically traversing the total list of * containers and then filtering it to get the permissioned objects from it. * * @param searchString * - Can be null or empty. It is used as a filter to search for * container's "title". * @param hostName * - Can be null or empty. It is used as a filter to search for * containers in a specific site. The "searchHost" must be set to * {@code true}. * @param searchHost * - If {@code true}, and if "hostName" is not empty, the method * will only get the containers from the specified site. * @param dbColSort * - The column name of the DB table used to order the results. * @param offset * - The offset of records to include in the result (used for * pagination purposes). * @param limit * - The limit of records to retrieve (used for pagination * purposes). * @param permission * - The required Permission needed to pull the containers * information. * @param user * - The {@link User} that performs the operation. * @param respectFrontEndPermissions * @return The {@code List} of {@link Container} objects that the specified * user has access to. * @throws DotDataException * - If an error occurred when retrieving information from the * database. * @throws DotSecurityException * - If the current user does not have permission to perform the * required operation. */ public static List<Container> findContainersForLimitedUser( String searchString, String hostName, boolean searchHost, String dbColSort, int offset, int limit, int permission, User user, boolean respectFrontEndPermissions) throws DotDataException, DotSecurityException { offset = offset < 0 ? 0 : offset; String hostQuery = null; if (searchHost) { Structure st = CacheLocator.getContentTypeCache().getStructureByVelocityVarName("Host"); Field hostNameField = st.getFieldVar("hostName"); List<Contentlet> hostList = null; try { String query = "+structureInode:" + st.getInode() + " +working:true"; if (UtilMethods.isSet(hostName)) { query += " +" + hostNameField.getFieldContentlet() + ":" + hostName; } hostList = APILocator.getContentletAPI().search(query, 0, 0, null, user, respectFrontEndPermissions); } catch (Exception e) { Logger.error(PermissionedWebAssetUtil.class, e.getMessage(), e); } if (hostList != null) { if (hostList.size() > 0) { hostQuery = "identifier.host_inode IN ("; } boolean first = true; for (Contentlet contentlet : hostList) { if (!first) { hostQuery += ","; } hostQuery += "'" + contentlet.getIdentifier() + "'"; first = false; } if (hostQuery != null) { hostQuery += ")"; } } } ArrayList<ColumnItem> columnsToOrderBy = new ArrayList<ColumnItem>(); ColumnItem templateTitle = new ColumnItem("title", "containers", null, true, OrderDir.ASC); columnsToOrderBy.add(templateTitle); List<String> containerIds = queryForAssetIds( "containers, identifier, inode, container_version_info ", new String[] { Container.class.getCanonicalName() }, "containers.inode", "identifier.id", "containers.identifier = identifier.id and inode.inode = containers.inode and " + "identifier.id=container_version_info.identifier and container_version_info.working_inode=containers.inode and " + "container_version_info.deleted=" + DbConnectionFactory.getDBFalse() + (UtilMethods.isSet(searchString) ? " and (lower(containers.title) LIKE '%" + searchString.toLowerCase() + "%'" + (UtilMethods.isSet(hostQuery) ? " AND (" + hostQuery + ")" : "") + ")" : (UtilMethods.isSet(hostQuery) ? " AND (" + hostQuery + ")" : "")), columnsToOrderBy, offset, limit, permission, respectFrontEndPermissions, user); if (containerIds != null && containerIds.size() > 0) { StringBuilder identifiers = new StringBuilder(); for (String id : containerIds) { identifiers.append("'").append(id).append("',"); } return InodeFactory.getInodesOfClassByConditionAndOrderBy( Container.class, "inode in (" + identifiers.toString().subSequence(0, identifiers.toString().length() - 1) + ")", dbColSort); } else { return new ArrayList<Container>(); } } /** * Will execute the query to get assetIds with required permission * @param tablesToJoin - This would be the tables to include in where ie... "template,inode,indentifier" * @param assetWhereClause - ie... "inode.identifier = identifier.inode and inode.inode = template.inode and template.title LIKE '%mytitle%'" * @param colToSelect ie.. template.inode * @param colToJoinAssetIdTo The column and table to joing the asset_id or inode_id from permission tables to ie.. identifier.inode * @param orderByClause - ie... template.name ASC make sure to capitalize the ASC or DESC * @param offset * @param limit * @param requiredTypePermission * @param respectFrontendRoles * @param user * @return * @throws DotDataException * @throws DotSecurityException */ private static List<String> queryForAssetIds(String tablesToJoin,String[] permissionType ,String colToSelect, String colToJoinAssetIdTo, String assetWhereClause, List<ColumnItem> columnsToOrderBy, int offset, int limit, int requiredTypePermission, boolean respectFrontendRoles, User user) throws DotDataException,DotSecurityException { Role anonRole; Role frontEndUserRole; Role adminRole; boolean userIsAdmin = false; try { adminRole = APILocator.getRoleAPI().loadCMSAdminRole(); anonRole = APILocator.getRoleAPI().loadCMSAnonymousRole(); frontEndUserRole = APILocator.getRoleAPI().loadLoggedinSiteRole(); } catch (DotDataException e1) { Logger.error(PermissionedWebAssetUtil.class, e1.getMessage(), e1); throw new DotRuntimeException(e1.getMessage(), e1); } List<String> roleIds = new ArrayList<String>(); if(respectFrontendRoles){ // add anonRole and frontEndUser roles roleIds.add(anonRole.getId()); if(user != null ){ roleIds.add("'"+frontEndUserRole.getId()+"'"); } } //If user is null and roleIds are empty return empty list if(roleIds.isEmpty() && user==null){ return new ArrayList<String>(); } List<Role> roles; try { roles = APILocator.getRoleAPI().loadRolesForUser(user.getUserId()); } catch (DotDataException e1) { Logger.error(PermissionedWebAssetUtil.class, e1.getMessage(), e1); throw new DotRuntimeException(e1.getMessage(), e1); } for (Role role : roles) { try{ String roleId = role.getId(); roleIds.add("'"+roleId+"'"); if(roleId.equals(adminRole.getId())){ userIsAdmin = true; } }catch (Exception e) { Logger.error(PermissionedWebAssetUtil.class, "Roleid should be a long : ",e); } } StringBuilder permissionRefSQL = new StringBuilder(); String extraSQLForOffset = ""; String orderByClause = ""; String orderByClauseWithAlias = ""; String orderBySelect = ""; int count = 0; for(ColumnItem item : columnsToOrderBy){ if(DbConnectionFactory.isPostgres() || DbConnectionFactory.isMySql()){ item.setIsString(false); } orderByClause += item.getOrderClause(true) + (count<columnsToOrderBy.size()-1?", ":""); orderByClauseWithAlias += item.getAliasOrderClause() + (count<columnsToOrderBy.size()-1?", ":""); orderBySelect += item.getSelectClause(true) + (count<columnsToOrderBy.size()-1?", ":""); count++; } if(DbConnectionFactory.isOracle()){ extraSQLForOffset = "ROW_NUMBER() OVER(ORDER BY "+orderByClause+") LINENUM, "; }else if(DbConnectionFactory.isMsSql()){ extraSQLForOffset = "ROW_NUMBER() OVER (ORDER BY "+orderByClause+") AS LINENUM, "; } permissionRefSQL.append("SELECT * FROM ("); permissionRefSQL.append("SELECT ").append(extraSQLForOffset).append(colToSelect).append(" as asset_id,").append(orderBySelect).append(" "); permissionRefSQL.append("FROM "); if(!userIsAdmin){ permissionRefSQL.append("permission_reference, permission, "); } permissionRefSQL.append(tablesToJoin).append(" "); permissionRefSQL.append("WHERE "); if(!userIsAdmin){ permissionRefSQL.append("permission_reference.reference_id = permission.inode_id "); permissionRefSQL.append("AND permission.permission_type = permission_reference.permission_type "); permissionRefSQL.append("AND permission_reference.asset_id = ").append(colToJoinAssetIdTo).append(" AND "); } permissionRefSQL.append(assetWhereClause).append(" "); if(!userIsAdmin){ if(permissionType.length==1) { permissionRefSQL.append("AND permission.permission_type = '").append(permissionType[0]).append("' "); } else { permissionRefSQL.append(" AND ("); boolean first=true; for(String type : permissionType) { if(first) { first=false; } else { permissionRefSQL.append(" OR "); } permissionRefSQL.append(" permission.permission_type = '").append(type).append("' "); } permissionRefSQL.append(") "); } permissionRefSQL.append("AND permission.roleid in( "); } StringBuilder individualPermissionSQL = new StringBuilder(); if(!userIsAdmin){ individualPermissionSQL.append("select ").append(extraSQLForOffset).append(colToSelect).append(" as asset_id, ").append(orderBySelect).append(" "); individualPermissionSQL.append("FROM "); individualPermissionSQL.append("permission,"); individualPermissionSQL.append(tablesToJoin).append(" WHERE "); individualPermissionSQL.append("permission_type = 'individual' "); individualPermissionSQL.append(" and permission.inode_id=").append(colToJoinAssetIdTo).append(" AND "); individualPermissionSQL.append(assetWhereClause).append(" "); individualPermissionSQL.append(" and roleid in( "); int roleIdCount = 0; for(String roleId : roleIds){ permissionRefSQL.append(roleId); individualPermissionSQL.append(roleId); if(roleIdCount<roleIds.size()-1){ permissionRefSQL.append(", "); individualPermissionSQL.append(", "); } roleIdCount++; } if(DbConnectionFactory.isOracle()){ permissionRefSQL.append(") and bitand(permission.permission, ").append(requiredTypePermission).append(") > 0 "); individualPermissionSQL.append(") and bitand(permission, ").append(requiredTypePermission).append(") > 0 "); }else{ permissionRefSQL.append(") and (permission.permission & ").append(requiredTypePermission).append(") > 0 "); individualPermissionSQL.append(") and (permission & ").append(requiredTypePermission).append(") > 0 "); } } permissionRefSQL.append(" group by ").append(colToSelect).append(" "); if(UtilMethods.isSet(individualPermissionSQL.toString())){ individualPermissionSQL.append(" group by ").append(colToSelect).append(" "); } for(ColumnItem item : columnsToOrderBy){ if(DbConnectionFactory.isPostgres() || DbConnectionFactory.isMySql()){ item.setIsString(false); } orderBySelect = item.getSelectClause(true); permissionRefSQL.append(", ").append(orderBySelect).append(" "); if(UtilMethods.isSet(individualPermissionSQL.toString())){ individualPermissionSQL.append(", ").append(orderBySelect).append(" "); } } List<String> idsToReturn = new ArrayList<String>(); String sql = ""; DotConnect dc = new DotConnect(); String limitOffsetSQL = null; boolean limitResults = limit > 0; if(DbConnectionFactory.isOracle()){ limitOffsetSQL = limitResults ? "WHERE LINENUM BETWEEN " + (offset<=0?offset:offset+1) + " AND " + (offset + limit) : ""; sql = permissionRefSQL.toString() + (UtilMethods.isSet(individualPermissionSQL.toString())?" UNION " +individualPermissionSQL.toString():"") +" ) " + limitOffsetSQL + " ORDER BY " + orderByClauseWithAlias ; }else if(DbConnectionFactory.isMsSql()){ limitOffsetSQL = limitResults ? "AS MyDerivedTable WHERE MyDerivedTable.LINENUM BETWEEN " + (offset<=0?offset:offset+1) + " AND " + (offset + limit) : ""; sql = permissionRefSQL.toString() + (UtilMethods.isSet(individualPermissionSQL.toString())?" UNION " +individualPermissionSQL.toString():"") +" ) " + limitOffsetSQL + " ORDER BY " + orderByClauseWithAlias; }else{ limitOffsetSQL = limitResults ? " LIMIT " + limit + " OFFSET " + offset : ""; sql = permissionRefSQL.toString() + (UtilMethods.isSet(individualPermissionSQL.toString())?" UNION " +individualPermissionSQL.toString():"") +" ) " + " as t1 ORDER BY "+ orderByClauseWithAlias + " " + limitOffsetSQL; } dc.setSQL(sql); List<Map<String, Object>> results = (ArrayList<Map<String, Object>>)dc.loadResults(); for (int i = 0; i < results.size(); i++) { Map<String, Object> hash = (Map<String, Object>) results.get(i); if(!hash.isEmpty()){ idsToReturn.add((String) hash.get("asset_id")); } } return idsToReturn; } private enum OrderDir{ ASC("ASC"), DESC("DESC"); private String value; OrderDir (String value) { this.value = value; } public String toString () { return value; } }; private static class ColumnItem{ private String columnName; private String tableName; private String alias; private OrderDir orderDir; private boolean isStringColumn; public void setIsString(boolean isStringColumn){ this.isStringColumn = isStringColumn; } public ColumnItem(String columnName, String tableName, String alias, boolean isStringColumn, OrderDir orderDir){ this.columnName = columnName; this.tableName = tableName; this.alias = alias; this.isStringColumn=isStringColumn; this.orderDir = orderDir!=null?orderDir:OrderDir.ASC; } public String getOrderClause(boolean includeTableName){ String ret = ""; if(this.isStringColumn){ ret = "lower("+ (includeTableName?this.tableName+".":"") + this.columnName +") " + orderDir.toString(); }else{ ret = (includeTableName?this.tableName+".":"") + this.columnName +" " + orderDir.toString(); } return ret; } public String getAliasOrderClause(){ String ret = ""; if(this.isStringColumn){ ret = "lower("+ (UtilMethods.isSet(this.alias)?this.alias:this.columnName) +") " + orderDir.toString(); }else{ ret = (UtilMethods.isSet(this.alias)?this.alias:this.columnName) +" " + orderDir.toString(); } return ret; } public String getSelectClause(boolean includeTableName){ String ret = (includeTableName?this.tableName+".":"")+this.columnName + (UtilMethods.isSet(this.alias)?" as " + this.alias:""); return ret; } } }
guhb/core
src/com/dotmarketing/business/PermissionedWebAssetUtil.java
Java
gpl-3.0
23,096
/* * Copyright (c) 2009 Lund University * * Written by Anton Cervin, Dan Henriksson and Martin Ohlin, * Department of Automatic Control LTH, Lund University, Sweden. * * This file is part of Truetime 2.0 beta. * * Truetime 2.0 beta is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Truetime 2.0 beta is distributed in the hope that it will be useful, but * without any warranty; without even the implied warranty of * merchantability or fitness for a particular purpose. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Truetime 2.0 beta. If not, see <http://www.gnu.org/licenses/> */ #ifndef GET_CBS_PERIOD #define GET_CBS_PERIOD #include "getnode.cpp" double ttGetCBSPeriod(const char *name) { DataNode *dn; dn = (DataNode*) getNode(name, rtsys->cbsList); if (dn == NULL) { char buf[MAXERRBUF]; sprintf(buf, "ttGetCBSPeriod: Non-existent task '%s'", name); TT_MEX_ERROR(buf); return 0.0; } CBS* cbs = (CBS*) dn->data; return cbs->Ts; } #endif
sfischme/truetime
kernel/getcbsperiod.cpp
C++
gpl-3.0
1,282
from .execute import GraphNode from . import preprocess def compile(layout_dict): preprocess.proprocess(layout_dict) # get nodes without any outputs root_nodes = layout_dict["nodes"].keys() - {l[0] for l in layout_dict["links"]} graph_dict = {} out = [GraphNode.from_layout(root_node, layout_dict, graph_dict) for root_node in root_nodes] return out
Sverchok/SverchokRedux
core/compiler.py
Python
gpl-3.0
376
package com.words.model.mysqlmodel; import com.words.controller.futurewords.FutureWord; import com.words.controller.utils.DateTimeUtils; import com.words.controller.words.Word; import com.words.controller.words.WordFactory; import com.words.controller.words.wordkinds.WordComplexity; import com.words.controller.words.wordkinds.WordType; import com.words.main.EnglishWords; import com.words.model.Model; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import java.util.NavigableSet; import java.util.Objects; import java.util.Properties; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; public final class MysqlModel implements Model { private static final int REPEAT_DAYS_TO_EXPIRE = 5; private static final String GET_WORD_QUERY_WITHOUT_CONDITION = "SELECT word, translation, synonyms, bundle_date, " + "complexity_id, times_picked, last_picked_timestamp " + "FROM words " + "JOIN bundles ON words.bundle_id = bundles.bundle_id"; private static String getWordQuery(String condition) { return GET_WORD_QUERY_WITHOUT_CONDITION + " " + condition; } private final LocalDate today; private final Map<WordComplexity, Integer> complexityMap = new EnumMap<>(WordComplexity.class); private final String dbName; private final Connection con; private final Map<String, Word> wordMap = new TreeMap<>((s1, s2) -> s1.replaceAll("^to ", "").compareTo(s2.replaceAll("^to ", ""))); public static void main(String[] args) throws Exception { MysqlModel model = new MysqlModel("EnglishWordsTestDb"); System.out.println(model.getLastBundleName()); System.out.println(model.getPenultimateBundleName()); System.out.println(model.getRepeatWords()); System.out.println(model.getExpiredRepeatWords()); model.addRepeatWord("to abolish"); model.deleteRepeatWord("to abolish"); System.out.println("1 day iters = " + model.getIterationsForDays(1)); System.out.println("2 day iters = " + model.getIterationsForDays(2)); System.out.println("7 day iters = " + model.getIterationsForDays(7)); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 1))); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 2))); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 3))); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 4))); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 5))); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 6))); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 7))); System.out.println(model.isExistingBundle(LocalDate.of(2015, Month.JANUARY, 8))); } public Connection getConnection() { return con; } private Word getWordFromResultSet(ResultSet rs) throws SQLException { String englishWord = rs.getString("word"); if (wordMap.containsKey(englishWord)) return wordMap.get(englishWord); Word word = WordFactory.newWord(); word.setWord(englishWord); word.setTranslation(rs.getString("translation")); word.setSynonyms(rs.getString("synonyms")); word.setBundle(rs.getDate("bundle_date").toLocalDate()); word.setComplexity(getComplexityFromId(rs.getInt("complexity_id"))); word.setTimesPicked(rs.getInt("times_picked")); word.setLastPickedTimestamp(rs.getLong("last_picked_timestamp")); wordMap.put(englishWord, word); return word; } private void defaultExceptionHandler(Exception ex) { ex.printStackTrace(); } private void rollback() { try { con.rollback(); } catch (SQLException ignore) { } } private int getIdFromComplexity(WordComplexity complexity) { return complexityMap.getOrDefault(complexity, 1); } private WordComplexity getComplexityFromId(Integer id) { for (Map.Entry<WordComplexity, Integer> entry : complexityMap.entrySet()) { if (entry.getValue().equals(id)) return entry.getKey(); } return WordComplexity.NORMAL; } /** * Gets bundle id. Returns -1 if bundles doesn't exist. * @param bundle bundle to search * @return bundle id or -1 * @throws SQLExceptin if something happens with database */ private int getBundleId(LocalDate bundle) throws SQLException { String searchQuery = "SELECT bundle_id FROM bundles WHERE bundle_date = ?"; try (PreparedStatement ps = con.prepareCall(searchQuery)) { ps.setString(1, bundle.toString()); ResultSet rs = ps.executeQuery(); if (rs.next()) return rs.getInt("bundle_id"); return -1; } } /** * Registers new bundle and return generated id. * @param bundle bundle to insert * @return newly generated bundle id * @throws SQLException if something wrong with database or bundle exists */ private int registerNewBundle(LocalDate bundle) throws SQLException { String insertQuery = "INSERT INTO bundles (bundle_date) VALUES (?)"; try (PreparedStatement ps = con.prepareStatement( insertQuery, Statement.RETURN_GENERATED_KEYS)) { ps.setString(1, bundle.toString()); ps.executeUpdate(); try (ResultSet generatedKeys = ps.getGeneratedKeys()) { if (generatedKeys.next()) return generatedKeys.getInt(1); else throw new SQLException("Failed to add new bundle"); } } } public MysqlModel(String dbName) throws Exception { this.dbName = dbName; Properties props = new Properties(); props.load(getClass().getResource("/resources/mysql/db.properties").openStream()); // Files.newBufferedReader(PROJECT_DIRECTORY.resolve("db.properties"), // Charset.defaultCharset())); String user = props.getProperty("db.user"); String password = props.getProperty("db.password"); boolean recreate = Boolean.parseBoolean(props.getProperty("db.recreate")); boolean importDb = Boolean.parseBoolean(props.getProperty("db.import")); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost/?allowMultiQueries=true&useUnicode=true", user, password); con.setAutoCommit(false); // find if database already exists boolean dbExists = false; try (ResultSet resultSet = con.getMetaData().getCatalogs()) { while (resultSet.next()) { if (resultSet.getString(1).equals(dbName)) { dbExists = true; break; } } } if (!dbExists || recreate) createDatabase(dbName, importDb); useDatabase(dbName); // hash complexity ids try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery( "SELECT complexity_id, complexity_name FROM complexities"); while (rs.next()) { complexityMap.put(WordComplexity.valueOf( rs.getString("complexity_name")), rs.getInt("complexity_id")); } } getAllWords(); today = DateTimeUtils.getCurrentLocalDate(); getRepeatWords(); } // creates database from scratch using predefined script // deletes all table and data if exists // throws Exception if something goes wrong private void createDatabase(String dbName, boolean importDb) throws Exception { // drop database if exists try (Statement statement = con.createStatement()) { statement.executeUpdate("DROP DATABASE IF EXISTS " + dbName); int result = statement.executeUpdate("CREATE DATABASE " + dbName); if (result != 1) throw new SQLException("Error creating database"); useDatabase(dbName); Path sqlScriptPath = Paths.get(getClass() .getResource("/resources/mysql/create_tables.sql").toURI()); String sqlScript = new String(Files.readAllBytes(sqlScriptPath), StandardCharsets.UTF_8); statement.executeUpdate(sqlScript); } // init complexity table try (PreparedStatement insertComplexities = con.prepareStatement( "INSERT INTO complexities (complexity_name, weight, privileged) " + "VALUES (?, ?, ?)")) { for (WordComplexity wc : WordComplexity.sortedValues()) { insertComplexities.setString(1, wc.name()); insertComplexities.setInt(2, wc.getWeight()); insertComplexities.setBoolean(3, wc.isPrivileged()); insertComplexities.executeUpdate(); } } con.commit(); if (importDb) importFileModel(); System.out.println("Created db"); } @Override public void backup() { try { new MysqlModelToFileModel(EnglishWords.PROJECT_DIRECTORY, con) .backup(); } catch (Exception ex) { System.err.println("Error while buckuping file model"); } } private void importFileModel() throws IOException, SQLException { FileModelToMysqlModel importer = new FileModelToMysqlModel(con); importer.insert(); } private void fillDatabaseWithDefaults() throws Exception { LocalDate firstBundle = DateTimeUtils.getCurrentLocalDate(); int normalComplexityId; int firstBundleId; try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery( "SELECT complexity_id FROM complexities WHERE complexity_name='" + WordComplexity.NORMAL.name() + "'"); rs.next(); normalComplexityId = rs.getInt("complexity_id"); firstBundleId = statement.executeUpdate( "INSERT INTO bundles (bundle_name) VALUES ('" + firstBundle + "')", Statement.RETURN_GENERATED_KEYS); } try (PreparedStatement insertWords = con.prepareStatement( "INSERT INTO words (word, translation, synonyms, bundle_id, complexity_id) " + "VALUES (?, ?, ?, ?, ?)")) { for (String line : Files.readAllLines(Paths.get(getClass() .getResource("/resources/irregular_verbs").toURI()), StandardCharsets.UTF_8)) { String[] tokens = line.split("\\t+"); insertWords.setString(1, tokens[0]); insertWords.setString(2, tokens[1]); insertWords.setString(3, tokens[2]); insertWords.setInt(4, firstBundleId); insertWords.setInt(5, normalComplexityId); insertWords.executeUpdate(); } } con.commit(); } private void useDatabase(String dbName) throws SQLException { try (Statement useStatement = con.createStatement()) { useStatement.executeUpdate("USE " + dbName); } } @Override public Word getWordInstance(String wordToSearch) { Objects.requireNonNull(wordToSearch); Word word = wordMap.get(wordToSearch); if (word != null) return word; String query = getWordQuery("WHERE word = ?"); try (PreparedStatement ps = con.prepareStatement(query)) { ps.setString(1, wordToSearch); ResultSet rs = ps.executeQuery(); if (rs.next()) return getWordFromResultSet(rs); else return null; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return null; } } @Override public boolean wordExists(String word) { Objects.requireNonNull(word); String query = "SELECT 1 FROM words WHERE word IN (?, ?)"; word = word.replaceAll("^to ", ""); try (PreparedStatement ps = con.prepareStatement(query)) { ps.setString(1, word); ps.setString(2, "to " + word); ResultSet rs = ps.executeQuery(); return rs.next(); } catch (SQLException sqle) { defaultExceptionHandler(sqle); return false; } } @Override public final Map<String, Word> getAllWords() { if (!wordMap.isEmpty()) return wordMap; String query = GET_WORD_QUERY_WITHOUT_CONDITION; try (PreparedStatement ps = con.prepareStatement(query)) { ResultSet rs = ps.executeQuery(); while (rs.next()) { Word word = getWordFromResultSet(rs); wordMap.put(word.getWord(), word); } return Collections.unmodifiableMap(wordMap); } catch (SQLException sqle) { defaultExceptionHandler(sqle); return Collections.emptyMap(); } } @Override public int getTodayIterations() { String query = "SELECT iterations FROM daily_iterations WHERE local_date = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setDate(1, Date.valueOf(today)); ResultSet rs = ps.executeQuery(); if (rs.next()) return rs.getInt("iterations"); else return 0; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return 0; } } @Override public long getTotalIterations() { String query = "SELECT SUM(times_picked) AS sum FROM words"; try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery(query); rs.next(); return rs.getLong("sum"); } catch (SQLException sqle) { defaultExceptionHandler(sqle); return 0; } } @Override public int getThisWeekIterations() { return getIterationsForDays(today.getDayOfWeek().getValue()); } @Override public int getIterationsForDays(int n) { if (n <= 1) return 0; LocalDate startDate = today.minusDays(n - 1); LocalDate endDate = today.minusDays(1); String query = "SELECT SUM(iterations) FROM daily_iterations " + "WHERE local_date BETWEEN ? AND ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setDate(1, Date.valueOf(startDate)); ps.setDate(2, Date.valueOf(endDate)); ResultSet rs = ps.executeQuery(); if (rs.next()) return rs.getInt(1); else return 0; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return 0; } } @Override public void setTodayIterations(int iter) { String query = "INSERT INTO daily_iterations (local_date, iterations) " + "VALUES (?, ?) ON DUPLICATE KEY UPDATE iterations = VALUES(iterations)"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setDate(1, Date.valueOf(today)); ps.setInt(2, iter); ps.executeUpdate(); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } @Override public Collection<Word> getBundle(LocalDate bundle) { if (bundle == null) return Collections.emptyList(); String query = getWordQuery("WHERE bundle_date = ?"); Collection<Word> words = new ArrayList<>(40); try (PreparedStatement ps = con.prepareStatement(query)) { ps.setDate(1, Date.valueOf(bundle)); ResultSet rs = ps.executeQuery(); while (rs.next()) { Word word = getWordFromResultSet(rs); words.add(word); } return words; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return Collections.emptyList(); } } @Override public boolean deleteWord(String wordToDelete) { String query = "DELETE FROM words WHERE word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setString(1, wordToDelete); int result = ps.executeUpdate(); if (result != 0) { con.commit(); wordMap.remove(wordToDelete); return true; } return false; } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); return false; } } @Override public Map<String, FutureWord> getFutureWords() { Map<String, FutureWord> map = new TreeMap<>(); String query = "SELECT future_word, priority, " + "DATE_FORMAT(date_added, '%d.%m.%Y') AS 'date_added', " + "DATE_FORMAT(date_changed, '%d.%m.%Y') AS 'date_created' " + "FROM future_words"; try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery(query); while (rs.next()) { FutureWord fw = new FutureWord(rs.getString("future_word")); fw.setPriority(rs.getInt("priority")); fw.setDateAdded(rs.getString("date_added")); fw.setDateChanged(rs.getString("date_created")); map.put(fw.getWord(), fw); } return map; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return Collections.emptyMap(); } } @Override public void updateFutureWord(String word) { String query = "INSERT INTO future_words " + "(future_word, priority, date_added, date_changed) " + "VALUES(?, 0, CURDATE(), CURDATE()) " + "ON DUPLICATE KEY UPDATE " + "priority = priority + 1, date_changed = CURDATE()"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setString(1, word); ps.executeUpdate(); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } @Override public void deleteFutureWords(Collection<String> words) { String query = "DELETE FROM future_words WHERE future_word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { words.forEach(word -> { try { ps.setString(1, word); ps.executeUpdate(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } }); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } private Collection<Word> getRepeatWordsWithCondition(String condition) { String query = getWordQuery("JOIN repeat_words ON " + "words.word_id = repeat_words.word_id " + condition); Collection<Word> words = new ArrayList<>(); try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery(query); while (rs.next()) { Word w = getWordFromResultSet(rs); words.add(w); } return words; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return Collections.emptyList(); } } @Override public Collection<Word> getRepeatWords() { String query = "WHERE date_added >= DATE(DATE_SUB('" + today + "', INTERVAL " + REPEAT_DAYS_TO_EXPIRE + " DAY))"; Collection<Word> repeatWords = getRepeatWordsWithCondition(query); repeatWords.forEach(w -> w.setWordType(WordType.REPEAT)); return repeatWords; } @Override public Collection<Word> getExpiredRepeatWords() { String query = "WHERE date_added = DATE(DATE_SUB('" + today + "', INTERVAL " + (REPEAT_DAYS_TO_EXPIRE + 1) + " DAY))"; return getRepeatWordsWithCondition(query); } @Override public void addRepeatWord(String word) { LocalDate insertDate = today.plusDays(1); String query = "INSERT IGNORE INTO repeat_words (word_id, date_added) " + "SELECT word_id, ? FROM words WHERE word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setDate(1, Date.valueOf(insertDate)); ps.setString(2, word); ps.executeUpdate(); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } @Override public void deleteRepeatWord(String word) { String query = "DELETE FROM repeat_words WHERE word_id IN " + "(SELECT word_id FROM words WHERE word = ?) " + "ORDER BY date_added DESC LIMIT 1"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setString(1, word); ps.executeUpdate(); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } @Override public boolean addNewWord(Word word) { String query = "INSERT INTO words (word, translation, synonyms, " + "bundle_id, times_picked, last_picked_timestamp, complexity_id) " + "VALUES (?, ?, ?, ?, ?, ?, ?)"; int complexityId = getIdFromComplexity(word.getComplexity()); try (PreparedStatement ps = con.prepareStatement(query)) { LocalDate bundle = word.getBundle(); int bundleId = getBundleId(bundle); if (bundleId == -1) bundleId = registerNewBundle(bundle); ps.setString(1, word.getWord()); ps.setString(2, word.getTranslation()); ps.setString(3, word.getSynonyms()); ps.setInt(4, bundleId); ps.setInt(5, word.getTimesPicked()); ps.setLong(6, System.currentTimeMillis()); ps.setInt(7, complexityId); int result = ps.executeUpdate(); if (result != 0) { con.commit(); wordMap.put(word.getWord(), word); return true; } return false; } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); return false; } } @Override public boolean isExistingBundle(LocalDate bundle) { Objects.requireNonNull(bundle); String query = "SELECT 1 FROM words JOIN bundles ON " + "words.bundle_id = bundles.bundle_id WHERE bundle_date = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setDate(1, Date.valueOf(bundle)); return ps.executeQuery().next(); } catch (SQLException sqle) { defaultExceptionHandler(sqle); return false; } } @Override public LocalDate getLastBundleName() { String query = "SELECT DISTINCT bundle_date FROM bundles " + "JOIN words ON bundles.bundle_id = words.bundle_id " + "ORDER BY bundle_date DESC LIMIT 1"; try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery(query); if (rs.next()) return rs.getDate("bundle_date").toLocalDate(); else return null; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return null; } } @Override public LocalDate getPenultimateBundleName() { String query = "SELECT DISTINCT bundle_date FROM bundles " + "JOIN words ON bundles.bundle_id = words.bundle_id " + "ORDER BY bundle_date DESC LIMIT 1, 1"; try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery(query); if (rs.next()) return rs.getDate("bundle_date").toLocalDate(); else return null; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return null; } } @Override public NavigableSet<LocalDate> allBundlesSorted() { TreeSet<LocalDate> bundles = new TreeSet<>(); String query = "SELECT DISTINCT bundle_date FROM bundles " + "JOIN words ON bundles.bundle_id = words.bundle_id"; try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery(query); while (rs.next()) bundles.add(rs.getDate("bundle_date").toLocalDate()); return bundles; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return Collections.emptyNavigableSet(); } } @Override public String getDefinition(String word) { String query = "SELECT definition FROM words WHERE word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setString(1, word); ResultSet rs = ps.executeQuery(); if (rs.next()) return rs.getString("definition"); else return null; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return null; } } @Override public void setDefinition(String word, String definition) { String query = "UPDATE words SET definition = ? WHERE word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setString(1, definition); ps.setString(2, word); ps.executeUpdate(); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } @Override public void setComplexity(String word, WordComplexity complexity) { String query = "UPDATE words SET complexity_id = ? WHERE word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setInt(1, getIdFromComplexity(complexity)); ps.setString(2, word); ps.executeUpdate(); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } @Override public void setLastPickedTimestamp(String word, long timestamp) { String query = "UPDATE words SET last_picked_timestamp = ?, " + "times_picked = times_picked + 1 WHERE word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { ps.setLong(1, timestamp); ps.setString(2, word); ps.executeUpdate(); con.commit(); } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } @Override public void editWords(Map<Word, Word> map) { for (Map.Entry<Word, Word> entry : map.entrySet()) { try { Word originalWord = entry.getValue(); Word editedWord = entry.getKey(); if (!originalWord.getWord().equals(editedWord.getWord())) { String wordToDelete = originalWord.getWord(); deleteWord(wordToDelete); wordMap.remove(wordToDelete); addNewWord(editedWord); // commits changes continue; // move to the next word } String query = "UPDATE words SET translation = ? , synonyms = ?, " + "bundle_id = ?, times_picked = ?, last_picked_timestamp = ?, " + "complexity_id = ?, definition = ? WHERE word = ?"; try (PreparedStatement ps = con.prepareStatement(query)) { int complexityId = getIdFromComplexity(editedWord.getComplexity()); LocalDate bundle = editedWord.getBundle(); int bundleId = getBundleId(bundle); if (bundleId == -1) bundleId = registerNewBundle(bundle); ps.setString(1, editedWord.getTranslation()); ps.setString(2, editedWord.getSynonyms()); ps.setInt(3, bundleId); ps.setInt(4, editedWord.getTimesPicked()); ps.setLong(5, editedWord.getLastPickedTimestamp()); ps.setInt(6, complexityId); ps.setString(7, getDefinition(editedWord.getWord())); ps.setString(8, editedWord.getWord()); ps.executeUpdate(); con.commit(); wordMap.put(editedWord.getWord(), editedWord); } } catch (SQLException sqle) { rollback(); defaultExceptionHandler(sqle); } } } @Override public boolean addNewBundle(LocalDate bundle, Collection<Word> words) { if (isExistingBundle(bundle)) return false; words.forEach(word -> { word.setBundle(bundle); addNewWord(word); }); return true; } @Override public boolean isEmpty() { String query = "SELECT COUNT(word) FROM words"; try (Statement statement = con.createStatement()) { ResultSet rs = statement.executeQuery(query); rs.next(); return rs.getInt(1) == 0; } catch (SQLException sqle) { defaultExceptionHandler(sqle); return true; } } @Override public void destroy() { try (PreparedStatement ps = con.prepareStatement( "DROP DATABASE IF EXISTS ?")) { ps.setString(1, dbName); ps.executeUpdate(); } catch (SQLException ex) { } System.err.println("Model has been completely destroyed"); } }
ferrerverck/englishwords
src/com/words/model/mysqlmodel/MysqlModel.java
Java
gpl-3.0
32,111
from .google import GoogleSpeaker from .watson import WatsonSpeaker """ alfred ~~~~~~~~~~~~~~~~ Google tts. """ __all__ = [ 'GoogleSpeaker', 'WatsonSpeaker' ]
lowdev/alfred
speaker/tts/__init__.py
Python
gpl-3.0
169
<?php /** * Random Number Generator * * PHP version 5 * * Here's a short example of how to use this library: * <code> * <?php * include 'vendor/autoload.php'; * * echo bin2hex(\phpseclib\Crypt\Random::string(8)); * ?> * </code> * * @category Crypt * @package Random * @author Jim Wigginton <terrafrost@php.net> * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; /** * Pure-PHP Random Number Generator * * @package Random * @author Jim Wigginton <terrafrost@php.net> * @access public */ class Random { /** * Generate a random string. * * Although microoptimizations are generally discouraged as they impair readability this function is ripe with * microoptimizations because this function has the potential of being called a huge number of times. * eg. for RSA key generation. * * @param int $length * @return string */ static function string($length) { if (!$length) { return ''; } if (version_compare(PHP_VERSION, '7.0.0', '>=')) { try { return \random_bytes($length); } catch (\Throwable $e) { // If a sufficient source of randomness is unavailable, random_bytes() will throw an // object that implements the Throwable interface (Exception, TypeError, Error). // We don't actually need to do anything here. The string() method should just continue // as normal. Note, however, that if we don't have a sufficient source of randomness for // random_bytes(), most of the other calls here will fail too, so we'll end up using // the PHP implementation. } } if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call. // ie. class_alias is a function that was introduced in PHP 5.3 if (extension_loaded('mcrypt') && function_exists('class_alias')) { return @mcrypt_create_iv($length); } // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was, // to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4 // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both // call php_win32_get_random_bytes(): // // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392 // // php_win32_get_random_bytes() is defined thusly: // // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80 // // we're calling it, all the same, in the off chance that the mcrypt extension is not available if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) { return openssl_random_pseudo_bytes($length); } } else { // method 1. the fastest if (extension_loaded('openssl')) { return openssl_random_pseudo_bytes($length); } // method 2 static $fp = true; if ($fp === true) { // warning's will be output unles the error suppression operator is used. errors such as // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc. $fp = @fopen('/dev/urandom', 'rb'); } if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource() $temp = fread($fp, $length); if (strlen($temp) == $length) { return $temp; } } // method 3. pretty much does the same thing as method 2 per the following url: // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391 // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir // restrictions or some such if (extension_loaded('mcrypt')) { return @mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); } } // at this point we have no choice but to use a pure-PHP CSPRNG // cascade entropy across multiple PHP instances by fixing the session and collecting all // environmental variables, including the previous session data and the current session // data. // // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively) // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but // PHP isn't low level to be able to use those as sources and on a web server there's not likely // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use // however, a ton of people visiting the website. obviously you don't want to base your seeding // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled // by the user and (2) this isn't just looking at the data sent by the current user - it's based // on the data sent by all users. one user requests the page and a hash of their info is saved. // another user visits the page and the serialization of their data is utilized along with the // server envirnment stuff and a hash of the previous http request data (which itself utilizes // a hash of the session data before that). certainly an attacker should be assumed to have // full control over his own http requests. he, however, is not going to have control over // everyone's http requests. static $crypto = false, $v; if ($crypto === false) { // save old session data $old_session_id = session_id(); $old_use_cookies = ini_get('session.use_cookies'); $old_session_cache_limiter = session_cache_limiter(); $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false; if ($old_session_id != '') { session_write_close(); } session_id(1); ini_set('session.use_cookies', 0); session_cache_limiter(''); session_start(); $v = $seed = $_SESSION['seed'] = pack('H*', sha1( (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') . (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') . (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') . (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') . phpseclib_safe_serialize($GLOBALS) . phpseclib_safe_serialize($_SESSION) . phpseclib_safe_serialize($_OLD_SESSION) )); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } $_SESSION['count']++; session_write_close(); // restore old session data if ($old_session_id != '') { session_id($old_session_id); session_start(); ini_set('session.use_cookies', $old_use_cookies); session_cache_limiter($old_session_cache_limiter); } else { if ($_OLD_SESSION !== false) { $_SESSION = $_OLD_SESSION; unset($_OLD_SESSION); } else { unset($_SESSION); } } // in SSH2 a shared secret and an exchange hash are generated through the key exchange process. // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the // original hash and the current hash. we'll be emulating that. for more info see the following URL: // // http://tools.ietf.org/html/rfc4253#section-7.2 // // see the is_string($crypto) part for an example of how to expand the keys $key = pack('H*', sha1($seed . 'A')); $iv = pack('H*', sha1($seed . 'C')); // ciphers are used as per the nist.gov link below. also, see this link: // // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives switch (true) { case class_exists('\phpseclib\Crypt\AES'): $crypto = new AES(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\Twofish'): $crypto = new Twofish(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\Blowfish'): $crypto = new Blowfish(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\TripleDES'): $crypto = new TripleDES(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\DES'): $crypto = new DES(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\RC4'): $crypto = new RC4(); break; default: user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded'); return false; } $crypto->setKey($key); $crypto->setIV($iv); $crypto->enableContinuousBuffer(); } //return $crypto->encrypt(str_repeat("\0", $length)); // the following is based off of ANSI X9.31: // // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf // // OpenSSL uses that same standard for it's random numbers: // // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c // (do a search for "ANS X9.31 A.2.4") $result = ''; while (strlen($result) < $length) { $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21 $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20 $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20 $result.= $r; } return substr($result, 0, $length); } } if (!function_exists('phpseclib_safe_serialize')) { /** * Safely serialize variables * * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier. * PHP 5.3 will emit a warning. * * @param mixed $arr * @access public */ function phpseclib_safe_serialize(&$arr) { if (is_object($arr)) { return ''; } if (!is_array($arr)) { return serialize($arr); } // prevent circular array recursion if (isset($arr['__phpseclib_marker'])) { return ''; } $safearr = []; $arr['__phpseclib_marker'] = true; foreach (array_keys($arr) as $key) { // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage if ($key !== '__phpseclib_marker') { $safearr[$key] = phpseclib_safe_serialize($arr[$key]); } } unset($arr['__phpseclib_marker']); return serialize($safearr); } }
kiwi3685/kiwitrees
modules_v4/database_backup/vendor/phpseclib/phpseclib/phpseclib/Crypt/Random.php
PHP
gpl-3.0
12,319
/** Namespace NotificationsTable */ var NotificationsTable = new function() { var ns = this; // reference to the namespace ns.oTable = null; var asInitVals = []; /** Update the table to list the notifications. */ this.update = function() { ns.oTable.fnClearTable( 0 ); ns.oTable.fnDraw(); }; /** Update the table to list the notifications. */ refresh_notifications = function() { if (ns.oTable) { ns.oTable.fnClearTable( 0 ); ns.oTable.fnDraw(); } }; this.approve = function(changeRequestID) { requestQueue.register(django_url + project.id + '/changerequest/approve', "POST", { "id": changeRequestID }, function (status, text, xml) { if (status == 200) { if (text && text != " ") { var jso = JSON.parse(text); if (jso.error) { alert(jso.error); } else { refresh_notifications(); } } } else if (status == 500) { win = window.open('', '', 'width=1100,height=620'); win.document.write(text); win.focus(); } return true; }); }; this.reject = function(changeRequestID) { requestQueue.register(django_url + project.id + '/changerequest/reject', "POST", { "id": changeRequestID }, function (status, text, xml) { if (status == 200) { if (text && text != " ") { var jso = JSON.parse(text); if (jso.error) { alert(jso.error); } else { refresh_notifications(); } } } else if (status == 500) { win = window.open('', '', 'width=1100,height=620'); win.document.write(text); win.focus(); } return true; }); }; this.perform_action = function(row_id) { var node = document.getElementById('action_select_' + row_id); if (node && node.tagName == "SELECT") { var row = $(node).closest('tr'); if (1 !== row.length) { CATMAID.error("Couldn't find table row for notification"); return; } var row_data = ns.oTable.fnGetData(row[0]); var action = node.options[node.selectedIndex].value; if (action == 'Show') { SkeletonAnnotations.staticMoveTo(row_data[6], row_data[5], row_data[4], function () {SkeletonAnnotations.staticSelectNode(row_data[7], row_data[8]);}); } else if (action == 'Approve') { NotificationsTable.approve(row_data[0]); CATMAID.client.get_messages(); // Refresh the notifications icon badge } else if (action == 'Reject') { NotificationsTable.reject(row_data[0]); CATMAID.client.get_messages(); // Refresh the notifications icon badge } node.selectedIndex = 0; } }; this.init = function (pid) { ns.pid = pid; ns.oTable = $('#notificationstable').dataTable({ // http://www.datatables.net/usage/options "bDestroy": true, "sDom": '<"H"lr>t<"F"ip>', // default: <"H"lfr>t<"F"ip> "bProcessing": true, "bServerSide": true, "bAutoWidth": false, "sAjaxSource": django_url + project.id + '/notifications/list', "fnServerData": function (sSource, aoData, fnCallback) { $.ajax({ "dataType": 'json', "type": "POST", "cache": false, "url": sSource, "data": aoData, "success": fnCallback }); }, "fnRowCallback": function ( nRow, aaData, iDisplayIndex ) { // Color each row based on its status. if (aaData[3] === 'Open') { nRow.style.backgroundColor = '#ffffdd'; } else if (aaData[3] === 'Approved') { nRow.style.backgroundColor = '#ddffdd'; } else if (aaData[3] === 'Rejected') { nRow.style.backgroundColor = '#ffdddd'; } else if (aaData[3] === 'Invalid') { nRow.style.backgroundColor = '#dddddd'; } return nRow; }, "iDisplayLength": 50, "aLengthMenu": [CATMAID.pageLengthOptions, CATMAID.pageLengthLabels], "bJQueryUI": true, "aoColumns": [{ "bSearchable": false, "bSortable": true, "bVisible": false }, // id { "sClass": "center", "bSearchable": true, "bSortable": false, }, // type { "bSearchable": false, "bSortable": false, }, // description { "sClass": "center", "bSearchable": true, "bSortable": true, "sWidth": "120px" }, // status { "bSearchable": false, "bVisible": false }, // x { "bSearchable": false, "bVisible": false }, // y { "bSearchable": false, "bVisible": false }, // z { "bSearchable": false, "bVisible": false }, // node_id { "bSearchable": false, "bVisible": false }, // skeleton_id { "bSearchable": true, "bSortable": true }, // from { "bSearchable": false, "bSortable": true, "sWidth": "100px" }, // date { "sClass": "center", "bSearchable": false, "bSortable": false, "mData": null, "mRender" : function(obj, type, full) { var id = full[0]; var disabled = (full[3] == 'Open' ? '' : ' disabled'); return '<select id="action_select_' + id + '" onchange="NotificationsTable.perform_action(' + id + ')">' + ' <option>Action:</option>' + ' <option>Show</option>' + ' <option' + disabled + '>Approve</option>' + ' <option' + disabled + '>Reject</option>' + '</select>'; }, "sWidth": "100px" } // actions ] }); // filter table $.each(asInitVals, function(index, value) { if(value==="Search") return; if(value) { ns.oTable.fnFilter(value, index); } }); $("#notificationstable thead input").keyup(function () { /* Filter on the column (the index) of this element */ var i = $("thead input").index(this) + 2; asInitVals[i] = this.value; ns.oTable.fnFilter(this.value, i); }); $("#notificationstable thead input").each(function (i) { asInitVals[i+2] = this.value; }); $("#notificationstable thead input").focus(function () { if (this.className === "search_init") { this.className = ""; this.value = ""; } }); $("#notificationstable thead input").blur(function (event) { if (this.value === "") { this.className = "search_init"; this.value = asInitVals[$("thead input").index(this)+2]; } }); $('select#search_type').change( function() { ns.oTable.fnFilter( $(this).val(), 1 ); asInitVals[1] = $(this).val(); }); }; }();
catsop/CATMAID
django/applications/catmaid/static/js/widgets/table-notifications.js
JavaScript
gpl-3.0
6,977
<?php /** Copyright 2011-2012 Nick Korbel This file is part of phpScheduleIt. phpScheduleIt is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. phpScheduleIt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with phpScheduleIt. If not, see <http://www.gnu.org/licenses/>. */ interface IReservationNotificationFactory { /** * @param ReservationAction $reservationAction * @param UserSession $userSession * @return IReservationNotificationService */ function Create($reservationAction, $userSession); } ?>
gpreunin/HCRHS-ScheduleItDev
lib/Application/Reservation/Notification/IReservationNotificationFactory.php
PHP
gpl-3.0
966
define(["exports"], function (_exports) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.phpLang = phpLang; function phpLang(hljs) { var VARIABLE = { begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" }; var PREPROCESSOR = { className: "meta", begin: /<\?(php)?|\?>/ }; var STRING = { className: "string", contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR], variants: [{ begin: 'b"', end: '"' }, { begin: "b'", end: "'" }, hljs.inherit(hljs.APOS_STRING_MODE, { illegal: null }), hljs.inherit(hljs.QUOTE_STRING_MODE, { illegal: null })] }; var NUMBER = { variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE] }; return { aliases: ["php", "php3", "php4", "php5", "php6", "php7"], case_insensitive: true, keywords: "and include_once list abstract global private echo interface as static endswitch " + "array null if endwhile or const for endforeach self var while isset public " + "protected exit foreach throw elseif include __FILE__ empty require_once do xor " + "return parent clone use __CLASS__ __LINE__ else break print eval new " + "catch __METHOD__ case exception default die require __FUNCTION__ " + "enddeclare final try switch continue endfor endif declare unset true false " + "trait goto instanceof insteadof __DIR__ __NAMESPACE__ " + "yield finally", contains: [hljs.HASH_COMMENT_MODE, hljs.COMMENT("//", "$", { contains: [PREPROCESSOR] }), hljs.COMMENT("/\\*", "\\*/", { contains: [{ className: "doctag", begin: "@[A-Za-z]+" }] }), hljs.COMMENT("__halt_compiler.+?;", false, { endsWithParent: true, keywords: "__halt_compiler", lexemes: hljs.UNDERSCORE_IDENT_RE }), { className: "string", begin: /<<<['"]?\w+['"]?$/, end: /^\w+;?$/, contains: [hljs.BACKSLASH_ESCAPE, { className: "subst", variants: [{ begin: /\$\w+/ }, { begin: /\{\$/, end: /\}/ }] }] }, PREPROCESSOR, { className: "keyword", begin: /\$this\b/ }, VARIABLE, { // swallow composed identifiers to avoid parsing them as keywords begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ }, { className: "function", beginKeywords: "function", end: /[;{]/, excludeEnd: true, illegal: "\\$|\\[|%", contains: [hljs.UNDERSCORE_TITLE_MODE, { className: "params", begin: "\\(", end: "\\)", contains: ["self", VARIABLE, hljs.C_BLOCK_COMMENT_MODE, STRING, NUMBER] }] }, { className: "class", beginKeywords: "class interface", end: "{", excludeEnd: true, illegal: /[:\(\$"]/, contains: [{ beginKeywords: "extends implements" }, hljs.UNDERSCORE_TITLE_MODE] }, { beginKeywords: "namespace", end: ";", illegal: /[\.']/, contains: [hljs.UNDERSCORE_TITLE_MODE] }, { beginKeywords: "use", end: ";", contains: [hljs.UNDERSCORE_TITLE_MODE] }, { begin: "=>" // No markup, just a relevance booster }, STRING, NUMBER] }; } });
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es5-amd/node_modules/@lrnwebcomponents/code-sample/lib/highlightjs/languages/php.js
JavaScript
gpl-3.0
3,428
class Solution(object): def findPaths(self, m, n, N, i, j): """ :type m: int :type n: int :type N: int :type i: int :type j: int :rtype: int """ MOD = 1000000007 paths = 0 cur = {(i, j): 1} for i in xrange(N): next = collections.defaultdict(int) for (x, y), cnt in cur.iteritems(): for dx, dy in [[-1, 0], [0, 1], [1, 0], [0, -1]]: nx = x + dx ny = y + dy if nx < 0 or ny < 0 or nx >= m or ny >= n: paths += cnt paths %= MOD else: next[(nx, ny)] += cnt next[(nx, ny)] %= MOD cur = next return paths # 94 / 94 test cases passed. # Status: Accepted # Runtime: 232 ms # beats 75.36 %
zqfan/leetcode
algorithms/576. Out of Boundary Paths/solution.py
Python
gpl-3.0
918
import os import unittest from urlparse import urlparse from paegan.utils.asarandom import AsaRandom class AsaRandomTest(unittest.TestCase): def test_create_random_filename(self): temp_filename = AsaRandom.filename(prefix="superduper", suffix=".nc") path = urlparse(temp_filename).path name, ext = os.path.splitext(path) assert name.index("superduper") == 0 assert ext == ".nc"
asascience-open/paegan
tests/test_asarandom.py
Python
gpl-3.0
424
package eu.imagecode.scias.model.jpa; import java.io.Serializable; import javax.persistence.*; import java.util.List; /** * The persistent class for the station_group database table. * */ @Entity @Table(name = "station_group") @NamedQuery(name = "StationGroupEntity.findAll", query = "SELECT s FROM StationGroupEntity s") public class StationGroupEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "STATION_GROUP_ID_GENERATOR", sequenceName = "STATION_GROUP_ID_SEQ") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STATION_GROUP_ID_GENERATOR") private Integer id; private String name; // bi-directional many-to-one association to StationEntity @OneToMany(mappedBy = "stationGroup") private List<StationEntity> stations; // bi-directional many-to-one association to StationGroupEntity @ManyToOne @JoinColumn(name = "parent_group_id") private StationGroupEntity stationGroup; // bi-directional many-to-one association to StationGroupEntity @OneToMany(mappedBy = "stationGroup") private List<StationGroupEntity> stationGroups; public StationGroupEntity() { } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public List<StationEntity> getStations() { return this.stations; } public void setStations(List<StationEntity> stations) { this.stations = stations; } public StationEntity addStation(StationEntity station) { getStations().add(station); station.setStationGroup(this); return station; } public StationEntity removeStation(StationEntity station) { getStations().remove(station); station.setStationGroup(null); return station; } public StationGroupEntity getStationGroup() { return this.stationGroup; } public void setStationGroup(StationGroupEntity stationGroup) { this.stationGroup = stationGroup; } public List<StationGroupEntity> getStationGroups() { return this.stationGroups; } public void setStationGroups(List<StationGroupEntity> stationGroups) { this.stationGroups = stationGroups; } public StationGroupEntity addStationGroup(StationGroupEntity stationGroup) { getStationGroups().add(stationGroup); stationGroup.setStationGroup(this); return stationGroup; } public StationGroupEntity removeStationGroup(StationGroupEntity stationGroup) { getStationGroups().remove(stationGroup); stationGroup.setStationGroup(null); return stationGroup; } }
vjuranek/scias-server
water/water-server/src/main/java/eu/imagecode/scias/model/jpa/StationGroupEntity.java
Java
gpl-3.0
2,861
package org.otherobjects.cms.controllers; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; import org.otherobjects.cms.dao.DaoService; import org.otherobjects.cms.jcr.UniversalJcrDao; import org.otherobjects.cms.model.BaseNode; import org.otherobjects.cms.model.Template; import org.otherobjects.cms.model.TemplateBlockReference; import org.otherobjects.cms.model.TemplateLayout; import org.otherobjects.cms.model.TemplateRegion; import org.otherobjects.cms.util.RequestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * Controller that manages template design. * * @author rich */ @Controller public class DesignerController { private final Logger logger = LoggerFactory.getLogger(DesignerController.class); @Resource private DaoService daoService; /** * Saves arrangmement of blocks on a template. */ @RequestMapping("/designer/saveArrangement/**") public ModelAndView saveArrangement(HttpServletRequest request, HttpServletResponse response) throws Exception { UniversalJcrDao dao = (UniversalJcrDao) daoService.getDao(BaseNode.class); String templateId = request.getParameter("templateId"); String arrangement = request.getParameter("arrangement"); logger.info("Arrangement: " + arrangement); JSONArray regions = new JSONArray(arrangement); // Load existing template Template template = (Template) dao.get(templateId); Map<String, TemplateBlockReference> blockRefs = new HashMap<String, TemplateBlockReference>(); // Gather all existing blockRefs for (TemplateRegion tr : template.getRegions()) { for (TemplateBlockReference trb : tr.getBlocks()) { blockRefs.put(trb.getId(), trb); } tr.setBlocks(new ArrayList<TemplateBlockReference>()); } // Re-insert blockRefs according to arrangement for (int i = 0; i < regions.length(); i++) { JSONObject region = (JSONObject) regions.get(i); TemplateRegion tr = template.getRegion((String) region.get("name")); JSONArray blockIds = (JSONArray) region.get("blockIds"); for (int j = 0; j < blockIds.length(); j++) { String blockId = (String) blockIds.get(j); tr.getBlocks().add(blockRefs.get(blockId)); blockRefs.remove(blockId); } } dao.save(template, false); // Delete removed blocks // FIXME Need to remove deleted blocks from live for (TemplateBlockReference ref : blockRefs.values()) { dao.remove(ref.getId()); } return null; } /** * Saves arrangmement of blocks on a template. */ @RequestMapping("/designer/publishTemplate/**") public ModelAndView publishTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception { UniversalJcrDao dao = (UniversalJcrDao) daoService.getDao(BaseNode.class); String templateId = RequestUtils.getId(request); // Load existing template Template template = (Template) dao.get(templateId); Map<String, TemplateBlockReference> blockRefs = new HashMap<String, TemplateBlockReference>(); // Gather all existing blockRefs for (TemplateRegion tr : template.getRegions()) { for (TemplateBlockReference trb : tr.getBlocks()) { blockRefs.put(trb.getId(), trb); } } // Check all blocks are published for (TemplateBlockReference ref : blockRefs.values()) { if (!ref.isPublished()) dao.publish(ref, null); if (ref.getBlockData() != null && !ref.getBlockData().isPublished()) dao.publish(ref.getBlockData(), null); } // Publish template dao.publish(template, null); return null; } /** * Creates a new template for specified type. */ @RequestMapping("/designer/createTemplate/**") public ModelAndView createTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception { UniversalJcrDao dao = (UniversalJcrDao) daoService.getDao(BaseNode.class); String resourceObjectId = RequestUtils.getId(request); BaseNode resourceObject = dao.get(resourceObjectId); String templateCode = request.getParameter("code"); String layoutId = request.getParameter("layout"); Template template = new Template(); template.setPath("/designer/templates/"); template.setCode(templateCode); template.setLabel(resourceObject.getTypeDef().getLabel() + " Template"); TemplateLayout layout = (TemplateLayout) dao.get(layoutId); template.setLayout(layout); dao.save(template, false); // FIXME Need to wrap linkPath response.sendRedirect(resourceObject.getOoUrlPath()); return null; } /** * Changes layout for specified template. */ @RequestMapping("/designer/changeLayout/**") public ModelAndView changeLayout(HttpServletRequest request, HttpServletResponse response) throws Exception { return null; } }
0x006EA1E5/oo6
src/main/java/org/otherobjects/cms/controllers/DesignerController.java
Java
gpl-3.0
5,683
/** * Policy mappings (ACL) * * Policies are simply Express middleware functions which run **before** your controllers. * You can apply one or more policies to a given controller, or protect just one of its actions. * * Any policy file (e.g. `authenticated.js`) can be dropped into the `/policies` folder, * at which point it can be accessed below by its filename, minus the extension, (e.g. `authenticated`) * * For more information on policies, check out: * http://sailsjs.org/#documentation */ // var serviceStack = ADCore.policy.serviceStack([ 'policy1', 'policy2']); module.exports = { // 'opstool-process-reports/YourController': { // method: ['isAuthenticatedService'], // auth: [], // sync: serviceStack, // logout:true // } };
appdevdesigns/opstool-process-reports
config/policies.js
JavaScript
gpl-3.0
785
//---------------------------------------------------------------------------- // XC program; finite element analysis code // for structural analysis and design. // // Copyright (C) Luis Claudio Pérez Tato // // This program derives from OpenSees <http://opensees.berkeley.edu> // developed by the «Pacific earthquake engineering research center». // // Except for the restrictions that may arise from the copyright // of the original program (see copyright_opensees.txt) // XC is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This software is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // // You should have received a copy of the GNU General Public License // along with this program. // If not, see <http://www.gnu.org/licenses/>. //---------------------------------------------------------------------------- /* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.2 $ // $Date: 2003/02/14 23:00:39 $ // $Source: /usr/local/cvs/OpenSees/SRC/actor/channel/TCP_SocketNoDelay.cpp,v $ // File: ~/actor/TCP_SocketNoDelay.C // // Written: fmk 11/95 // Revised: // // Purpose: This file contains the implementation of the methods needed // to define the TCP_SocketNoDelay class interface. #include "utility/actor/channel/TCP_SocketNoDelay.h" #include <netinet/in.h> #include <netinet/tcp.h> #include "utility/matrix/Matrix.h" #include "utility/matrix/Vector.h" #include "../message/Message.h" #include "../address/ChannelAddress.h" #include "../actor/MovableObject.h" static int GetHostAddr(char *host, char *IntAddr); static void inttoa(unsigned int no, char *string, int *cnt); // TCP_SocketNoDelay(unsigned int other_Port, char *other_InetAddr): // constructor to open a socket with my inet_addr and with a port number // given by the OS. XC::TCP_SocketNoDelay::TCP_SocketNoDelay(void) :myPort(0) { // set up my_Addr bzero((char *) &my_Addr, sizeof(my_Addr)); my_Addr.sin_family = AF_INET; my_Addr.sin_addr.s_addr = htonl(INADDR_ANY); my_Addr.sin_port = htons(0); addrLength = sizeof(my_Addr); // open a socket if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not open socket\n"; } // bind local address to it if (bind(sockfd, (struct sockaddr *) &my_Addr,sizeof(my_Addr)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not bind local address\n"; } // get my_address info INET_getsockname(sockfd, &my_Addr, &addrLength); myPort = ntohs(my_Addr.sin_port); } // TCP_SocketNoDelay(unsigned int port): // constructor to open a socket with my inet_addr and with a port number port. XC::TCP_SocketNoDelay::TCP_SocketNoDelay(unsigned int port) :myPort(0) { // set up my_Addr with address given by port and internet address of // machine on which the process that uses this routine is running. char me[20]; char my_InetAddr[MAX_INET_ADDR]; gethostname(me,MAX_INET_ADDR); GetHostAddr(me,my_InetAddr); bzero((char *) &my_Addr, sizeof(my_Addr)); my_Addr.sin_family = AF_INET; my_Addr.sin_addr.s_addr = inet_addr(my_InetAddr); my_Addr.sin_port = htons(port); addrLength = sizeof(my_Addr); // open a socket if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not open socket\n"; } // bind local address to it if (bind(sockfd,(struct sockaddr *)&my_Addr,sizeof(my_Addr)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not bind local address\n"; } // get my_address info INET_getsockname(sockfd, &my_Addr, &addrLength); myPort = ntohs(my_Addr.sin_port); } // TCP_SocketNoDelay(unsigned int other_Port, char *other_InetAddr): // constructor to open a socket with my inet_addr and with a port number // given by the OS. Then to connect with a TCP_SocketNoDelay whose address is // given by other_Port and other_InetAddr. XC::TCP_SocketNoDelay::TCP_SocketNoDelay(unsigned int other_Port, char *other_InetAddr) :myPort(0) { // set up remote address bzero((char *) &other_Addr, sizeof(other_Addr)); other_Addr.sin_family = AF_INET; other_Addr.sin_addr.s_addr = inet_addr(other_InetAddr); other_Addr.sin_port = htons(other_Port); // set up my_Addr bzero((char *) &my_Addr, sizeof(my_Addr)); my_Addr.sin_family = AF_INET; my_Addr.sin_addr.s_addr = htonl(INADDR_ANY); my_Addr.sin_port = htons(0); addrLength = sizeof(my_Addr); // open a socket if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not open socket\n"; } // bind local address to it if (bind(sockfd, (struct sockaddr *) &my_Addr,sizeof(my_Addr)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not bind local address\n"; } myPort = ntohs(my_Addr.sin_port); } // ~TCP_SocketNoDelay(): // destructor XC::TCP_SocketNoDelay::~TCP_SocketNoDelay() { close(sockfd); } int XC::TCP_SocketNoDelay::setUpActor(void) { // now try to connect to socket with remote address. if (connect(sockfd, (struct sockaddr *) &other_Addr, sizeof(other_Addr))< 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not connect\n"; return -1; } // get my_address info INET_getsockname(sockfd, &my_Addr, &addrLength); // set socket so no delay int optlen; optlen = 1; if ((setsockopt(sockfd,IPPROTO_TCP, TCP_NODELAY, (char *) &optlen, sizeof(int))) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not set TCP_NODELAY\n"; } /* int flag=sizeof(int); if ((getsockopt(sockfd,IPPROTO_TCP, TCP_NODELAY, (char *) &optlen, &flag)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not set TCP_NODELAY\n"; } std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - " << optlen << " flag " << flag << std::endl; */ return 0; } int XC::TCP_SocketNoDelay::setUpShadow(void) { // wait for other process to contact me & set up connection int newsockfd; listen(sockfd, 1); newsockfd = accept(sockfd, (struct sockaddr *) &other_Addr, &addrLength); if (newsockfd < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not accept connection\n"; return -1; } // close old socket & reset sockfd close(sockfd); // we can close as we are not // going to wait for others to connect sockfd = newsockfd; // get my_address info INET_getsockname(sockfd, &my_Addr, &addrLength); myPort = ntohs(my_Addr.sin_port); // set socket so no delay int optlen; optlen = 1; if ((setsockopt(sockfd,IPPROTO_TCP, TCP_NODELAY, (char *) &optlen, sizeof(int))) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not set TCP_NODELAY\n"; } /* int flag=sizeof(int); if ((getsockopt(sockfd,IPPROTO_TCP, TCP_NODELAY, (char *) &optlen, &flag)) < 0) { std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - could not set TCP_NODELAY\n"; } std::cerr << "XC::TCP_SocketNoDelay::TCP_SocketNoDelay - " << optlen << " flag " << flag << std::endl; */ return 0; } int XC::TCP_SocketNoDelay::setNextAddress(const XC::ChannelAddress &theAddress) { SocketAddress *theSocketAddress = 0; if (theAddress.getType() == SOCKET_TYPE) { theSocketAddress = (SocketAddress *)(&theAddress); // check address is the only address a TCP_SocketNoDelay can send to if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvMsg() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } else { std::cerr << "XC::TCP_SocketNoDelay::setNextAddress() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } return 0; } int XC::TCP_SocketNoDelay::sendObj(MovableObject &theObject, FEM_ObjectBroker &theBroker, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay"; std::cerr << " address given is not that address\n"; return -1; } } return theObject.sendSelf(*this, theBroker); } int XC::TCP_SocketNoDelay::recvObj(MovableObject &theObject, FEM_ObjectBroker &theBroker, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvMsg() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } return theObject.recvSelf(*this, theBroker); } // void Recv(Message &): // Method to receive a message, also sets other_Addr to that of sender int XC::TCP_SocketNoDelay::recvMsg(Message &msg, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvMsg() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the message and // place the incoming data there int nleft,nread; char *gMsg; gMsg = msg.data; nleft = msg.length; while (nleft > 0) { nread = read(sockfd,gMsg,nleft); nleft -= nread; gMsg += nread; } return 0; } // void Send(Message &): // Method to send a message to an address given by other_Addr. int XC::TCP_SocketNoDelay::sendMsg(const Message &msg, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvMsg() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the message and // place the incoming data there int nwrite, nleft; char *gMsg; gMsg = msg.data; nleft = msg.length; while (nleft > 0) { nwrite = write(sockfd,gMsg,nleft); nleft -= nwrite; gMsg += nwrite; } return 0; } int XC::TCP_SocketNoDelay::recvMatrix(Matrix &theMatrix, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvMatrix() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the XC::Matrix and // place the incoming data there int nleft,nread; double *data = theMatrix.myData; char *gMsg = (char *)data;; nleft = theMatrix.dataSize * sizeof(double); while (nleft > 0) { nread = read(sockfd,gMsg,nleft); nleft -= nread; gMsg += nread; } return 0; } // void Send(Matrix &): // Method to send a XC::Matrix to an address given by other_Addr. int XC::TCP_SocketNoDelay::sendMatrix(const XC::Matrix &theMatrix, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } SocketAddress *theSocketAddress = 0; if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvMatrix() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the XC::Matrix and // place the incoming data there int nwrite, nleft; double *data = theMatrix.myData; char *gMsg = (char *)data; nleft = theMatrix.dataSize * sizeof(double); while (nleft > 0) { nwrite = write(sockfd,gMsg,nleft); nleft -= nwrite; gMsg += nwrite; } return 0; } int XC::TCP_SocketNoDelay::recvVector(Vector &theVector, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvVector() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the XC::Vector and // place the incoming data there int nleft,nread; double *data = theVector.theData; char *gMsg = (char *)data;; nleft = theVector.sz * sizeof(double); while (nleft > 0) { nread = read(sockfd,gMsg,nleft); nleft -= nread; gMsg += nread; } return 0; } // void Send(Vector &): // Method to send a XC::Vector to an address given by other_Addr. int XC::TCP_SocketNoDelay::sendVector(const XC::Vector &theVector, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvVector() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the XC::Vector and // place the incoming data there int nwrite, nleft; double *data = theVector.theData; char *gMsg = (char *)data; nleft = theVector.sz * sizeof(double); while (nleft > 0) { nwrite = write(sockfd,gMsg,nleft); nleft -= nwrite; gMsg += nwrite; } return 0; } int XC::TCP_SocketNoDelay::recvID(ID &theID, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvID() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the XC::ID and // place the incoming data there int nleft,nread; int *data = theID.data; char *gMsg = (char *)data;; nleft = theID.sz * sizeof(int); while (nleft > 0) { nread = read(sockfd,gMsg,nleft); nleft -= nread; gMsg += nread; } return 0; } // void Send(ID &): // Method to send a XC::ID to an address given by other_Addr. int XC::TCP_SocketNoDelay::sendID(const XC::ID &theID, ChannelAddress *theAddress) { // first check address is the only address a TCP_SocketNoDelay can send to SocketAddress *theSocketAddress = 0; if (theAddress != 0) { if (theAddress->getType() == SOCKET_TYPE) theSocketAddress = (SocketAddress *)theAddress; else { std::cerr << "XC::TCP_SocketNoDelay::sendObj() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with a TCP_SocketNoDelay"; std::cerr << " address given is not of type XC::SocketAddress\n"; return -1; } if (bcmp((char *) &other_Addr, (char *) &theSocketAddress->addr, theSocketAddress->addrLength) != 0) { std::cerr << "XC::TCP_SocketNoDelay::recvID() - a TCP_SocketNoDelay "; std::cerr << "can only communicate with one other TCP_SocketNoDelay\n"; return -1; } } // if o.k. get a ponter to the data in the XC::ID and // place the incoming data there int nwrite, nleft; int *data = theID.data; char *gMsg = (char *)data; nleft = theID.sz * sizeof(int); while (nleft > 0) { nwrite = write(sockfd,gMsg,nleft); nleft -= nwrite; gMsg += nwrite; } return 0; } unsigned int XC::TCP_SocketNoDelay::getPortNumber(void) const { return myPort; } char * XC::TCP_SocketNoDelay::addToProgram(void) { char *tcp = " 3 "; char me[20]; char my_InetAddr[MAX_INET_ADDR]; char myPortNum[8]; unsigned int thePort = this->getPortNumber(); /* char *me =(char *)malloc(30*sizeof(char)); char *my_InetAddr=(char *)malloc(30*sizeof(char)); char *myPortNum = (char *)malloc(30*sizeof(char)); for (int i=0; i<30; i++) { me[i] = ' '; my_InetAddr[i] = ' '; myPortNum[i] = ' '; } */ int start = 0; inttoa(thePort,myPortNum,&start); gethostname(me,MAX_INET_ADDR); GetHostAddr(me,my_InetAddr); char *newStuff =(char *)malloc(100*sizeof(char)); for (int i=0; i<100; i++) newStuff[i] = ' '; strcpy(newStuff,tcp); strcat(newStuff," "); strcat(newStuff,my_InetAddr); strcat(newStuff," "); strcat(newStuff,myPortNum); strcat(newStuff," "); return newStuff; } // G e t H o s t A d d r // GetHostAddr is a function to get the internet address of a host // Takes machine name host & Returns 0 if o.k, -1 if gethostbyname // error, -2 otherwise. The internet address is returned in IntAddr static int GetHostAddr(char *host, char *IntAddr) { register struct hostent *hostptr; if ( (hostptr = gethostbyname(host)) == nullptr) return (-1); switch(hostptr->h_addrtype) { case AF_INET: strcpy(IntAddr,inet_ntoa(*(struct in_addr *)*hostptr->h_addr_list)); return (0); break; default: return (-2); } } /* * i n t t o a * * Function to convert int to ascii * */ static void inttoa(unsigned int no, char *string, int *cnt) { if (no /10) { inttoa(no/10, string, cnt); *cnt = *cnt+1; } string[*cnt] = no % 10 + '0'; }
lcpt/xc
src/utility/actor/channel/TCP_SocketNoDelay.cpp
C++
gpl-3.0
24,406
using pdsharp.noosa.audio; using pdsharp.utils; using sharpdungeon.actors; using sharpdungeon.actors.mobs; using sharpdungeon.effects; using sharpdungeon.items.potions; using sharpdungeon.items.scrolls; using sharpdungeon.levels; using sharpdungeon.mechanics; using sharpdungeon.scenes; using sharpdungeon.utils; namespace sharpdungeon.items.wands { public class WandOfTelekinesis : Wand { private const string TxtYouNowHave = "You have magically transported {0} into your backpack"; public WandOfTelekinesis() { name = "Wand of Telekinesis"; HitChars = false; } protected internal override void OnZap(int cell) { var mapUpdated = false; var maxDistance = Level + 4; Ballistica.Distance = System.Math.Min(Ballistica.Distance, maxDistance); Heap heap = null; for (var i = 1; i < Ballistica.Distance; i++) { var c = Ballistica.Trace[i]; var before = Dungeon.Level.map[c]; Character ch; if ((ch = Actor.FindChar(c)) != null) { if (i == Ballistica.Distance - 1) { ch.Damage(maxDistance - 1 - i, this); } else { var next = Ballistica.Trace[i + 1]; if ((levels.Level.passable[next] || levels.Level.avoid[next]) && Actor.FindChar(next) == null) { Actor.AddDelayed(new Pushing(ch, ch.pos, next), -1); ch.pos = next; Actor.FreeCell(next); // FIXME var mob = ch as Mob; if (mob != null) Dungeon.Level.MobPress(mob); else Dungeon.Level.Press(ch.pos, ch); } else ch.Damage(maxDistance - 1 - i, this); } } if (heap == null && (heap = Dungeon.Level.heaps[c]) != null) { switch (heap.HeapType) { case Heap.Type.Heap: Transport(heap); break; case Heap.Type.Chest: Open(heap); break; } } Dungeon.Level.Press(c, null); if (before == Terrain.OPEN_DOOR && Actor.FindChar(c) == null) { levels.Level.Set(c, Terrain.DOOR); GameScene.UpdateMap(c); } else if (levels.Level.water[c]) GameScene.Ripple(c); if (!mapUpdated && Dungeon.Level.map[c] != before) mapUpdated = true; } if (mapUpdated) Dungeon.Observe(); } private void Transport(Heap heap) { var item = heap.PickUp(); if (item.DoPickUp(CurUser)) { if (item is Dewdrop) return; if ((item is ScrollOfUpgrade && ((ScrollOfUpgrade) item).IsKnown) || (item is PotionOfStrength && ((PotionOfStrength) item).IsKnown)) GLog.Positive(TxtYouNowHave, item.Name); else GLog.Information(TxtYouNowHave, item.Name); } else Dungeon.Level.Drop(item, CurUser.pos).Sprite.Drop(); } private void Open(Heap heap) { heap.HeapType = Heap.Type.Heap; heap.Sprite.Link(); heap.Sprite.Drop(); } protected internal override void Fx(int cell, ICallback callback) { MagicMissile.Force(CurUser.Sprite.Parent, CurUser.pos, cell, callback); Sample.Instance.Play(Assets.SND_ZAP); } public override string Desc() { return "Waves of magic force from this wand will affect All cells on their way triggering traps, trampling high vegetation, " + "opening closed doors and closing open ones. They also push back monsters."; } } }
hazard999/SharpDungeon
items/wands/WandOfTelekinesis.cs
C#
gpl-3.0
4,515
require 'genome/importers/delimited_row' module Genome module Importers module Civic class CivicRow < Genome::Importers::DelimitedRow attribute :civic_id attribute :gene_symbol attribute :drug_name attribute :entrez_gene_id attribute :interaction_type attribute :pmid, Array, delimiter: ',' def valid?(opts = {}) true end end end end end
ahwagner/dgi-db
lib/genome/importers/civic/civic_row.rb
Ruby
gpl-3.0
447
/* * Copyright (C) 2008, 2012 Gustavo Noronha Silva * Copyright (C) 2010 Collabora Ltd. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "InspectorClientGtk.h" #include "FileSystem.h" #include "Frame.h" #include "InspectorController.h" #include "NotImplemented.h" #include "Page.h" #include "PlatformString.h" #include "webkitversion.h" #include "webkitwebinspector.h" #include "webkitwebinspectorprivate.h" #include "webkitwebview.h" #include "webkitwebviewprivate.h" #include <wtf/text/CString.h> using namespace WebCore; namespace WebKit { static void notifyWebViewDestroyed(WebKitWebView* webView, InspectorFrontendClient* inspectorFrontendClient) { inspectorFrontendClient->destroyInspectorWindow(true); } namespace { class InspectorFrontendSettingsGtk : public InspectorFrontendClientLocal::Settings { public: virtual ~InspectorFrontendSettingsGtk() { } private: virtual String getProperty(const String& name) { notImplemented(); return String(); } virtual void setProperty(const String& name, const String& value) { notImplemented(); } }; } // namespace InspectorClient::InspectorClient(WebKitWebView* webView) : m_inspectedWebView(webView) , m_frontendPage(0) , m_frontendClient(0) {} InspectorClient::~InspectorClient() { if (m_frontendClient) { m_frontendClient->disconnectInspectorClient(); m_frontendClient = 0; } } void InspectorClient::inspectorDestroyed() { closeInspectorFrontend(); delete this; } void InspectorClient::openInspectorFrontend(InspectorController* controller) { // This g_object_get will ref the inspector. We're not doing an // unref if this method succeeds because the inspector object must // be alive even after the inspected WebView is destroyed - the // close-window and destroy signals still need to be // emitted. WebKitWebInspector* webInspector = 0; g_object_get(m_inspectedWebView, "web-inspector", &webInspector, NULL); ASSERT(webInspector); WebKitWebView* inspectorWebView = 0; g_signal_emit_by_name(webInspector, "inspect-web-view", m_inspectedWebView, &inspectorWebView); if (!inspectorWebView) { g_object_unref(webInspector); return; } webkit_web_inspector_set_web_view(webInspector, inspectorWebView); GOwnPtr<gchar> inspectorPath(g_build_filename(inspectorFilesPath(), "inspector.html", NULL)); GOwnPtr<gchar> inspectorURI(g_filename_to_uri(inspectorPath.get(), 0, 0)); webkit_web_view_load_uri(inspectorWebView, inspectorURI.get()); gtk_widget_show(GTK_WIDGET(inspectorWebView)); m_frontendPage = core(inspectorWebView); OwnPtr<InspectorFrontendClient> frontendClient = adoptPtr(new InspectorFrontendClient(m_inspectedWebView, inspectorWebView, webInspector, m_frontendPage, this)); m_frontendClient = frontendClient.get(); m_frontendPage->inspectorController()->setInspectorFrontendClient(frontendClient.release()); // The inspector must be in it's own PageGroup to avoid deadlock while debugging. m_frontendPage->setGroupName(""); } void InspectorClient::closeInspectorFrontend() { if (m_frontendClient) m_frontendClient->destroyInspectorWindow(false); } void InspectorClient::bringFrontendToFront() { m_frontendClient->bringToFront(); } void InspectorClient::releaseFrontendPage() { m_frontendPage = 0; m_frontendClient = 0; } void InspectorClient::highlight() { hideHighlight(); } void InspectorClient::hideHighlight() { // FIXME: we should be able to only invalidate the actual rects of // the new and old nodes. We need to track the nodes, and take the // actual highlight size into account when calculating the damage // rect. gtk_widget_queue_draw(GTK_WIDGET(m_inspectedWebView)); } bool InspectorClient::sendMessageToFrontend(const String& message) { return doDispatchMessageOnFrontendPage(m_frontendPage, message); } const char* InspectorClient::inspectorFilesPath() { if (m_inspectorFilesPath) m_inspectorFilesPath.get(); const char* environmentPath = getenv("WEBKIT_INSPECTOR_PATH"); if (environmentPath && g_file_test(environmentPath, G_FILE_TEST_IS_DIR)) m_inspectorFilesPath.set(g_strdup(environmentPath)); else m_inspectorFilesPath.set(g_build_filename(sharedResourcesPath().data(), "webinspector", NULL)); return m_inspectorFilesPath.get(); } InspectorFrontendClient::InspectorFrontendClient(WebKitWebView* inspectedWebView, WebKitWebView* inspectorWebView, WebKitWebInspector* webInspector, Page* inspectorPage, InspectorClient* inspectorClient) : InspectorFrontendClientLocal(core(inspectedWebView)->inspectorController(), inspectorPage, adoptPtr(new InspectorFrontendSettingsGtk())) , m_inspectorWebView(inspectorWebView) , m_inspectedWebView(inspectedWebView) , m_webInspector(webInspector) , m_inspectorClient(inspectorClient) { g_signal_connect(m_inspectorWebView, "destroy", G_CALLBACK(notifyWebViewDestroyed), (gpointer)this); } InspectorFrontendClient::~InspectorFrontendClient() { if (m_inspectorClient) { m_inspectorClient->releaseFrontendPage(); m_inspectorClient = 0; } ASSERT(!m_webInspector); } void InspectorFrontendClient::destroyInspectorWindow(bool notifyInspectorController) { if (!m_webInspector) return; GRefPtr<WebKitWebInspector> webInspector = adoptGRef(m_webInspector.leakRef()); if (m_inspectorWebView) { g_signal_handlers_disconnect_by_func(m_inspectorWebView, reinterpret_cast<gpointer>(notifyWebViewDestroyed), this); m_inspectorWebView = 0; } if (notifyInspectorController) core(m_inspectedWebView)->inspectorController()->disconnectFrontend(); if (m_inspectorClient) m_inspectorClient->releaseFrontendPage(); gboolean handled = FALSE; g_signal_emit_by_name(webInspector.get(), "close-window", &handled); ASSERT(handled); // Please do not use member variables here because InspectorFrontendClient object pointed by 'this' // has been implicitly deleted by "close-window" function. } String InspectorFrontendClient::localizedStringsURL() { GOwnPtr<gchar> stringsPath(g_build_filename(m_inspectorClient->inspectorFilesPath(), "localizedStrings.js", NULL)); GOwnPtr<gchar> stringsURI(g_filename_to_uri(stringsPath.get(), 0, 0)); // FIXME: support l10n of localizedStrings.js return String::fromUTF8(stringsURI.get()); } String InspectorFrontendClient::hiddenPanels() { notImplemented(); return String(); } void InspectorFrontendClient::bringToFront() { if (!m_inspectorWebView) return; gboolean handled = FALSE; g_signal_emit_by_name(m_webInspector.get(), "show-window", &handled); } void InspectorFrontendClient::closeWindow() { destroyInspectorWindow(true); } void InspectorFrontendClient::attachWindow() { if (!m_inspectorWebView) return; gboolean handled = FALSE; g_signal_emit_by_name(m_webInspector.get(), "attach-window", &handled); } void InspectorFrontendClient::detachWindow() { if (!m_inspectorWebView) return; gboolean handled = FALSE; g_signal_emit_by_name(m_webInspector.get(), "detach-window", &handled); } void InspectorFrontendClient::setAttachedWindowHeight(unsigned height) { notImplemented(); } void InspectorFrontendClient::inspectedURLChanged(const String& newURL) { if (!m_inspectorWebView) return; webkit_web_inspector_set_inspected_uri(m_webInspector.get(), newURL.utf8().data()); } }
cs-au-dk/Artemis
WebKit/Source/WebKit/gtk/WebCoreSupport/InspectorClientGtk.cpp
C++
gpl-3.0
8,369
""" Contains exception classes specific to this project. """
electronic-library/electronic-library-core
library/exceptions.py
Python
gpl-3.0
62
/* * Copyright (c) 2011-2013 Lp digital system * * This file is part of BackBuilder5. * * BackBuilder5 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BackBuilder5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BackBuilder5. If not, see <http://www.gnu.org/licenses/>. */ define(['tb.core'], function (Core) { 'use strict'; /** * Register every routes of bundle application into Core.routeManager */ Core.RouteManager.registerRoute('user', { prefix: 'user', routes: { index: { url: '/index', action: 'MainController:index' } } }); });
ndufreche/bb-core-js-dist
src/tb/apps/user/routes.js
JavaScript
gpl-3.0
1,111
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with foam-extend. If not, see <http://www.gnu.org/licenses/>. Global CourantNo Description Calculates and outputs the mean and maximum Courant Numbers with immersed boundary correction. \*---------------------------------------------------------------------------*/ scalar CoNum = 0.0; scalar meanCoNum = 0.0; scalar velMag = 0.0; if (mesh.nInternalFaces()) { surfaceScalarField magPhi = mag(faceIbMask*phi); surfaceScalarField SfUfbyDelta = mesh.surfaceInterpolation::deltaCoeffs()*magPhi; CoNum = max(SfUfbyDelta/mesh.magSf()) .value()*runTime.deltaT().value(); meanCoNum = (sum(SfUfbyDelta)/sum(mesh.magSf())) .value()*runTime.deltaT().value(); velMag = max(magPhi/mesh.magSf()).value(); } Info<< "Courant Number mean: " << meanCoNum << " max: " << CoNum << " velocity magnitude: " << velMag << endl; // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/immersedBoundary/immersedBoundary/include/immersedBoundaryCourantNo.H
C++
gpl-3.0
2,033
class Zone: def __init__(self, id_zone, name, region, description): self.id = id_zone self.name = name self.region = region self.description = description
Crystal-SDS/dashboard
crystal_dashboard/dashboards/crystal/zones/models.py
Python
gpl-3.0
192
#include <QtWidgets> #include "mdichild.h" MdiChild::MdiChild() { setAttribute(Qt::WA_DeleteOnClose); isUntitled = true; } void MdiChild::newFile() { static int sequenceNumber = 1; isUntitled = true; curFile = tr("document%1.txt").arg(sequenceNumber++); setWindowTitle(curFile + "[*]"); connect(document(), &QTextDocument::contentsChanged, this, &MdiChild::documentWasModified); } bool MdiChild::loadFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return false; } QTextStream in(&file); QApplication::setOverrideCursor(Qt::WaitCursor); setPlainText(in.readAll()); QApplication::restoreOverrideCursor(); setCurrentFile(fileName); connect(document(), &QTextDocument::contentsChanged, this, &MdiChild::documentWasModified); return true; } bool MdiChild::save() { if (isUntitled) { return saveAs(); } else { return saveFile(curFile); } } bool MdiChild::saveAs() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), curFile); if (fileName.isEmpty()) return false; return saveFile(fileName); } bool MdiChild::saveFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot write file %1:\n%2.") .arg(QDir::toNativeSeparators(fileName), file.errorString())); return false; } QTextStream out(&file); QApplication::setOverrideCursor(Qt::WaitCursor); out << toPlainText(); QApplication::restoreOverrideCursor(); setCurrentFile(fileName); return true; } QString MdiChild::userFriendlyCurrentFile() { return strippedName(curFile); } void MdiChild::closeEvent(QCloseEvent *event) { if (maybeSave()) { event->accept(); } else { event->ignore(); } } void MdiChild::documentWasModified() { setWindowModified(document()->isModified()); } bool MdiChild::maybeSave() { if (!document()->isModified()) return true; const QMessageBox::StandardButton ret = QMessageBox::warning(this, tr("MDI"), tr("'%1' has been modified.\n" "Do you want to save your changes?") .arg(userFriendlyCurrentFile()), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); switch (ret) { case QMessageBox::Save: return save(); case QMessageBox::Cancel: return false; default: break; } return true; } void MdiChild::setCurrentFile(const QString &fileName) { curFile = QFileInfo(fileName).canonicalFilePath(); isUntitled = false; document()->setModified(false); setWindowModified(false); setWindowTitle(userFriendlyCurrentFile() + "[*]"); } QString MdiChild::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); }
liothique/NMPharm
UI/NMPharmUI/mdichild.cpp
C++
gpl-3.0
3,430
# -*- coding: iso-8859-1 -*- # --------------------------------------------------------------------------- # # SPEEDMETER Control wxPython IMPLEMENTATION # Python Code By: # # Andrea Gavana, @ 25 Sep 2005 # Latest Revision: 10 Oct 2005, 22.40 CET # # # TODO List/Caveats # # 1. Combination Of The Two Styles: # # SM_DRAW_PARTIAL_FILLER # SM_DRAW_SECTORS # # Does Not Work Very Well. It Works Well Only In Case When The Sector Colours # Are The Same For All Intervals. # # # Thanks To Gerard Grazzini That Has Tried The Demo On MacOS, I Corrected A # Bug On Line 246 # # # For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please # Write To Me At: # # andrea.gavana@agip.it # andrea_gavan@tin.it # # Or, Obviously, To The wxPython Mailing List!!! # # MODIFIED to add native Python wx.gizmos.LEDNubmerCtrl-type display, and a number of other things. # by Jason Antman <http://www.jasonantman.com> <jason@jasonantman.com> # Modifications Copyright 2010 Jason Antman. # # # End Of Comments # --------------------------------------------------------------------------- # """Description: SpeedMeter Tries To Reproduce The Behavior Of Some Car Controls (But Not Only), By Creating An "Angular" Control (Actually, Circular). I Remember To Have Seen It Somewhere, And I Decided To Implement It In wxPython. SpeedMeter Starts Its Construction From An Empty Bitmap, And It Uses Some Functions Of The wx.DC Class To Create The Rounded Effects. Everything Is Processed In The Draw() Method Of SpeedMeter Class. This Implementation Allows You To Use Either Directly The wx.PaintDC, Or The Better (For Me) Double Buffered Style With wx.BufferedPaintDC. The Double Buffered Implementation Has Been Adapted From The wxPython Wiki Example: http://wiki.wxpython.org/index.cgi/DoubleBufferedDrawing Usage: SpeedWindow1 = SM.SpeedMeter(parent, bufferedstyle, extrastyle, mousestyle ) None Of The Options (A Part Of Parent Class) Are Strictly Required, If You Use The Defaults You Get A Very Simple SpeedMeter. For The Full Listing Of The Input Parameters, See The SpeedMeter __init__() Method. Methods And Settings: SpeedMeter Is Highly Customizable, And In Particular You Can Set: - The Start And End Angle Of Existence For SpeedMeter; - The Intervals In Which You Divide The SpeedMeter (Numerical Values); - The Corresponding Thicks For The Intervals; - The Interval Colours (Different Intervals May Have Different Filling Colours); - The Ticks Font And Colour; - The Background Colour (Outsize The SpeedMeter Region); - The External Arc Colour; - The Hand (Arrow) Colour; - The Hand's Shadow Colour; - The Hand's Style ("Arrow" Or "Hand"); - The Partial Filler Colour; - The Number Of Secondary (Intermediate) Ticks; - The Direction Of Increasing Speed ("Advance" Or "Reverse"); - The Text To Be Drawn In The Middle And Its Font; - The Icon To Be Drawn In The Middle; - The First And Second Gradient Colours (That Fills The SpeedMeter Control); - The Current Value. For More Info On Methods And Initial Styles, Please Refer To The __init__() Method For SpeedMeter Or To The Specific Functions. SpeedMeter Control Is Freeware And Distributed Under The wxPython License. Latest Revision: Andrea Gavana @ 10 Oct 2005, 22.40 CET """ #---------------------------------------------------------------------- # Beginning Of SPEEDMETER wxPython Code #---------------------------------------------------------------------- import wx import wx.lib.colourdb import wx.lib.fancytext as fancytext import wx.gizmos as gizmos # for LEDControl import exceptions from math import pi, sin, cos, log, sqrt, atan2 #---------------------------------------------------------------------- # DC Drawing Options #---------------------------------------------------------------------- # SM_NORMAL_DC Uses The Normal wx.PaintDC # SM_BUFFERED_DC Uses The Double Buffered Drawing Style SM_NORMAL_DC = 0 SM_BUFFERED_DC = 1 #---------------------------------------------------------------------- # SpeedMeter Styles #---------------------------------------------------------------------- # SM_ROTATE_TEXT: Draws The Ticks Rotated: The Ticks Are Rotated # Accordingly To The Tick Marks Positions # SM_DRAW_SECTORS: Different Intervals Are Painted In Differend Colours # (Every Sector Of The Circle Has Its Own Colour) # SM_DRAW_PARTIAL_SECTORS: Every Interval Has Its Own Colour, But Only # A Circle Corona Is Painted Near The Ticks # SM_DRAW_HAND: The Hand (Arrow Indicator) Is Drawn # SM_DRAW_SHADOW: A Shadow For The Hand Is Drawn # SM_DRAW_PARTIAL_FILLER: A Circle Corona That Follows The Hand Position # Is Drawn Near The Ticks # SM_DRAW_SECONDARY_TICKS: Intermediate (Smaller) Ticks Are Drawn Between # Principal Ticks # SM_DRAW_MIDDLE_TEXT: Some Text Is Printed In The Middle Of The Control # Near The Center # SM_DRAW_MIDDLE_ICON: An Icon Is Drawn In The Middle Of The Control Near # The Center # SM_DRAW_GRADIENT: A Gradient Of Colours Will Fill The Control # SM_DRAW_FANCY_TICKS: With This Style You Can Use XML Tags To Create # Some Custom Text And Draw It At The Ticks Position. # See wx.lib.fancytext For The Tags. # SM_DRAW_BOTTOM_TEXT: Some Text Is Printed In The Bottom Of The Control # SM_DRAW_BOTTOM_LED: A gizmos.LEDNumberCtrl-style value display is drawn at the bottom SM_ROTATE_TEXT = 1 SM_DRAW_SECTORS = 2 SM_DRAW_PARTIAL_SECTORS = 4 SM_DRAW_HAND = 8 SM_DRAW_SHADOW = 16 SM_DRAW_PARTIAL_FILLER = 32 SM_DRAW_SECONDARY_TICKS = 64 SM_DRAW_MIDDLE_TEXT = 128 SM_DRAW_MIDDLE_ICON = 256 SM_DRAW_GRADIENT = 512 SM_DRAW_FANCY_TICKS = 1024 SM_DRAW_BOTTOM_TEXT = 2048 SM_DRAW_BOTTOM_LED = 4096 #---------------------------------------------------------------------- # Event Binding #---------------------------------------------------------------------- # SM_MOUSE_TRACK: The Mouse Left Click/Drag Allow You To Change The # SpeedMeter Value Interactively SM_MOUSE_TRACK = 1 LINE1 = 1 LINE2 = 2 LINE3 = 4 LINE4 = 8 LINE5 = 16 LINE6 = 32 LINE7 = 64 DECIMALSIGN = 128 DIGIT0 = LINE1 | LINE2 | LINE3 | LINE4 | LINE5 | LINE6 DIGIT1 = LINE2 | LINE3 DIGIT2 = LINE1 | LINE2 | LINE4 | LINE5 | LINE7 DIGIT3 = LINE1 | LINE2 | LINE3 | LINE4 | LINE7 DIGIT4 = LINE2 | LINE3 | LINE6 | LINE7 DIGIT5 = LINE1 | LINE3 | LINE4 | LINE6 | LINE7 DIGIT6 = LINE1 | LINE3 | LINE4 | LINE5 | LINE6 | LINE7 DIGIT7 = LINE1 | LINE2 | LINE3 DIGIT8 = LINE1 | LINE2 | LINE3 | LINE4 | LINE5 | LINE6 | LINE7 DIGIT9 = LINE1 | LINE2 | LINE3 | LINE6 | LINE7 DASH = LINE7 DIGITALL = -1 fontfamily = range(70, 78) familyname = ["default", "decorative", "roman", "script", "swiss", "modern", "teletype"] weights = range(90, 93) weightsname = ["normal", "light", "bold"] styles = [90, 93, 94] stylesname = ["normal", "italic", "slant"] #---------------------------------------------------------------------- # BUFFERENDWINDOW Class # This Class Has Been Taken From The wxPython Wiki, And Slightly # Adapted To Fill My Needs. See: # # http://wiki.wxpython.org/index.cgi/DoubleBufferedDrawing # # For More Info About DC And Double Buffered Drawing. #---------------------------------------------------------------------- class BufferedWindow(wx.Window): """ A Buffered window class. To use it, subclass it and define a Draw(DC) method that takes a DC to draw to. In that method, put the code needed to draw the picture you want. The window will automatically be double buffered, and the screen will be automatically updated when a Paint event is received. When the drawing needs to change, you app needs to call the UpdateDrawing() method. Since the drawing is stored in a bitmap, you can also save the drawing to file by calling the SaveToFile(self,file_name,file_type) method. """ def __init__(self, parent, id, pos = wx.DefaultPosition, size = wx.DefaultSize, style=wx.NO_FULL_REPAINT_ON_RESIZE, bufferedstyle=SM_BUFFERED_DC): wx.Window.__init__(self, parent, id, pos, size, style) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None) # OnSize called to make sure the buffer is initialized. # This might result in OnSize getting called twice on some # platforms at initialization, but little harm done. self.OnSize(None) def Draw(self, dc): """ just here as a place holder. This method should be over-ridden when sub-classed """ pass def OnPaint(self, event): """ All that is needed here is to draw the buffer to screen """ if self._bufferedstyle == SM_BUFFERED_DC: dc = wx.BufferedPaintDC(self, self._Buffer) else: dc = wx.PaintDC(self) dc.DrawBitmap(self._Buffer,0,0) def OnSize(self,event): # The Buffer init is done here, to make sure the buffer is always # the same size as the Window self.Width, self.Height = self.GetClientSizeTuple() # Make new off screen bitmap: this bitmap will always have the # current drawing in it, so it can be used to save the image to # a file, or whatever. # This seems required on MacOS, it doesn't like wx.EmptyBitmap with # size = (0, 0) # Thanks to Gerard Grazzini if "__WXMAC__" in wx.Platform: if self.Width == 0: self.Width = 1 if self.Height == 0: self.Height = 1 self._Buffer = wx.EmptyBitmap(self.Width, self.Height) self.UpdateDrawing() def UpdateDrawing(self): """ This would get called if the drawing needed to change, for whatever reason. The idea here is that the drawing is based on some data generated elsewhere in the system. IF that data changes, the drawing needs to be updated. """ if self._bufferedstyle == SM_BUFFERED_DC: dc = wx.BufferedDC(wx.ClientDC(self), self._Buffer) self.Draw(dc) else: # update the buffer dc = wx.MemoryDC() dc.SelectObject(self._Buffer) self.Draw(dc) # update the screen wx.ClientDC(self).Blit(0, 0, self.Width, self.Height, dc, 0, 0) #---------------------------------------------------------------------- # SPEEDMETER Class # This Is The Main Class Implementation. See __init__() Method For # Details. #---------------------------------------------------------------------- class SpeedMeter(BufferedWindow): """ Class for a gauge-style display using an arc marked with tick marks and interval numbers, and a moving needle/hand/pointer. MODIFIED to add native Python wx.gizmos.LEDNubmerCtrl-type display, and a number of other things by Jason Antman <http://www.jasonantman.com> <jason@jasonantman.com> @todo: Need to document everything (all methods). @todo: Build example code. @todo: Find everything used internally only and prefix methods with "__" @todo: Find all "raise" statements, and any "print" statements that print an error, make them work with exceptions - IndexError, TypeError, RuntimeError, LookupError @todo: change all mentions of "hand" to "needle" @todo: make sure we have setters/getters for DrawFaded, Alignment, Value (for LED) @todo: in client, test gradients """ bottomTextBottom = None DEBUG = False # controls debugging print statements def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, extrastyle=SM_DRAW_HAND, bufferedstyle=SM_BUFFERED_DC, mousestyle=0): """ Default Class Constructor. Non Standard wxPython Parameters Are: a) extrastyle: This Value Specifies The SpeedMeter Styles: - SM_ROTATE_TEXT: Draws The Ticks Rotated: The Ticks Are Rotated Accordingly To The Tick Marks Positions; - SM_DRAW_SECTORS: Different Intervals Are Painted In Differend Colours (Every Sector Of The Circle Has Its Own Colour); - SM_DRAW_PARTIAL_SECTORS: Every Interval Has Its Own Colour, But Only A Circle Corona Is Painted Near The Ticks; - SM_DRAW_HAND: The Hand (Arrow Indicator) Is Drawn; - SM_DRAW_SHADOW: A Shadow For The Hand Is Drawn; - SM_DRAW_PARTIAL_FILLER: A Circle Corona That Follows The Hand Position Is Drawn Near The Ticks; - SM_DRAW_SECONDARY_TICKS: Intermediate (Smaller) Ticks Are Drawn Between Principal Ticks; - SM_DRAW_MIDDLE_TEXT: Some Text Is Printed In The Middle Of The Control Near The Center; - SM_DRAW_MIDDLE_ICON: An Icon Is Drawn In The Middle Of The Control Near The Center; - SM_DRAW_GRADIENT: A Gradient Of Colours Will Fill The Control; - SM_DRAW_FANCY_TICKS: With This Style You Can Use XML Tags To Create Some Custom Text And Draw It At The Ticks Position. See wx.lib.fancytext For The Tags.; - SM_DRAW_BOTTOM_TEXT: Some Text Is Printed In The Bottom Of The Control - SM_DRAW_BOTTOM_LED: A wx.gizmos.LEDNumberCtrl-style value display is printed at the bottom b) bufferedstyle: This Value Allows You To Use The Normal wx.PaintDC Or The Double Buffered Drawing Options: - SM_NORMAL_DC Uses The Normal wx.PaintDC; - SM_BUFFERED_DC Uses The Double Buffered Drawing Style. c) mousestyle: This Value Allows You To Use The Mouse To Change The SpeedMeter Value Interactively With Left Click/Drag Events: - SM_MOUSE_TRACK: The Mouse Left Click/Drag Allow You To Change The SpeedMeter Value Interactively. """ self._extrastyle = extrastyle self._bufferedstyle = bufferedstyle self._mousestyle = mousestyle if self._extrastyle & SM_DRAW_SECTORS and self._extrastyle & SM_DRAW_GRADIENT: errstr = "\nERROR: Incompatible Options: SM_DRAW_SECTORS Can Not Be Used In " errstr = errstr + "Conjunction With SM_DRAW_GRADIENT." raise errstr if self._extrastyle & SM_DRAW_PARTIAL_SECTORS and self._extrastyle & SM_DRAW_SECTORS: errstr = "\nERROR: Incompatible Options: SM_DRAW_SECTORS Can Not Be Used In " errstr = errstr + "Conjunction With SM_DRAW_PARTIAL_SECTORS." raise errstr if self._extrastyle & SM_DRAW_PARTIAL_SECTORS and self._extrastyle & SM_DRAW_PARTIAL_FILLER: errstr = "\nERROR: Incompatible Options: SM_DRAW_PARTIAL_SECTORS Can Not Be Used In " errstr = errstr + "Conjunction With SM_DRAW_PARTIAL_FILLER." raise errstr if self._extrastyle & SM_DRAW_FANCY_TICKS and self._extrastyle & SM_ROTATE_TEXT: errstr = "\nERROR: Incompatible Options: SM_DRAW_FANCY_TICKS Can Not Be Used In " errstr = errstr + "Conjunction With SM_ROTATE_TEXT." raise errstr if self._extrastyle & SM_DRAW_SHADOW and self._extrastyle & SM_DRAW_HAND == 0: errstr = "\nERROR: Incompatible Options: SM_DRAW_SHADOW Can Be Used Only In " errstr = errstr + "Conjunction With SM_DRAW_HAND." if self._extrastyle & SM_DRAW_FANCY_TICKS: wx.lib.colourdb.updateColourDB() self.SetValueMultiplier() # for LED control self.SetAngleRange() self.SetIntervals() self.SetSpeedValue() self.SetIntervalColours() self.SetArcColour() self.SetTicks() self.SetTicksFont() self.SetTicksColour() self.SetSpeedBackground() self.SetHandColour() self.SetShadowColour() self.SetFillerColour() self.SetDirection() self.SetNumberOfSecondaryTicks() self.SetMiddleText() self.SetMiddleTextFont() self.SetMiddleTextColour() self.SetBottomText() self.SetBottomTextFont() self.SetBottomTextColour() self.SetFirstGradientColour() self.SetSecondGradientColour() self.SetHandStyle() self.DrawExternalArc() self.DrawExternalCircle() # for LED control self._LEDwidth = 0 self._LEDheight = 0 self._LEDx = 0 self._LEDy = 0 self._InitLEDInternals() self.SetLEDAlignment() self.SetDrawFaded() BufferedWindow.__init__(self, parent, id, pos, size, style=wx.NO_FULL_REPAINT_ON_RESIZE, bufferedstyle=bufferedstyle) if self._mousestyle & SM_MOUSE_TRACK: self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseMotion) def Draw(self, dc): """ Draws Everything On The Empty Bitmap. Here All The Chosen Styles Are Applied. GIGANTIC HUMONGOUS UGLY function that draws I{everything} on the bitmap except for the LEDs. @param dc: the dc @type dc: L{wx.BufferedDC} """ size = self.GetClientSize() if size.x < 21 or size.y < 21: return new_dim = size.Get() if not hasattr(self, "dim"): self.dim = new_dim self.scale = min([float(new_dim[0]) / self.dim[0], float(new_dim[1]) / self.dim[1]]) # Create An Empty Bitmap self.faceBitmap = wx.EmptyBitmap(size.width, size.height) dc.BeginDrawing() speedbackground = self.GetSpeedBackground() # Set Background Of The Control dc.SetBackground(wx.Brush(speedbackground)) dc.Clear() centerX = self.faceBitmap.GetWidth()/2 centerY = self.faceBitmap.GetHeight()/2 self.CenterX = centerX self.CenterY = centerY # Get The Radius Of The Sector. Set It A Bit Smaller To Correct Draw After radius = min(centerX, centerY) - 2 self.Radius = radius # Get The Angle Of Existance Of The Sector anglerange = self.GetAngleRange() startangle = anglerange[1] endangle = anglerange[0] self.StartAngle = startangle self.EndAngle = endangle # Initialize The Colours And The Intervals - Just For Reference To The # Children Functions colours = None intervals = None if self._extrastyle & SM_DRAW_SECTORS or self._extrastyle & SM_DRAW_PARTIAL_SECTORS: # Get The Intervals Colours colours = self.GetIntervalColours()[:] textangles = [] colourangles = [] xcoords = [] ycoords = [] # Get The Intervals (Partial Sectors) intervals = self.GetIntervals()[:] start = min(intervals) end = max(intervals) span = end - start self.StartValue = start self.EndValue = end self.Span = span # Get The Current Value For The SpeedMeter currentvalue = self.GetSpeedValue() # Get The Direction Of The SpeedMeter direction = self.GetDirection() if direction == "Reverse": intervals.reverse() if self._extrastyle & SM_DRAW_SECTORS or self._extrastyle & SM_DRAW_PARTIAL_SECTORS: colours.reverse() currentvalue = end - currentvalue # This Because DrawArc Does Not Draw Last Point offset = 0.1*self.scale/180.0 xstart, ystart = self.__CircleCoords(radius+1, -endangle, centerX, centerY) xend, yend = self.__CircleCoords(radius+1, -startangle-offset, centerX, centerY) # Calculate The Angle For The Current Value Of SpeedMeter accelangle = (currentvalue - start)/float(span)*(startangle-endangle) - startangle dc.SetPen(wx.TRANSPARENT_PEN) if self._extrastyle & SM_DRAW_PARTIAL_FILLER: # Get Some Data For The Partial Filler fillercolour = self.GetFillerColour() fillerendradius = radius - 10.0*self.scale fillerstartradius = radius if direction == "Advance": fillerstart = accelangle fillerend = -startangle else: fillerstart = -endangle fillerend = accelangle xs1, ys1 = self.__CircleCoords(fillerendradius, fillerstart, centerX, centerY) xe1, ye1 = self.__CircleCoords(fillerendradius, fillerend, centerX, centerY) xs2, ys2 = self.__CircleCoords(fillerstartradius, fillerstart, centerX, centerY) xe2, ye2 = self.__CircleCoords(fillerstartradius, fillerend, centerX, centerY) # Get The Sector In Which The Current Value Is intersection = self.__GetIntersection(currentvalue, intervals) sectorradius = radius - 10*self.scale else: sectorradius = radius if self._extrastyle & SM_DRAW_PARTIAL_FILLER: # Draw The Filler (Both In "Advance" And "Reverse" Directions) dc.SetBrush(wx.Brush(fillercolour)) dc.DrawArc(xs2, ys2, xe2, ye2, centerX, centerY) if self._extrastyle & SM_DRAW_SECTORS == 0: dc.SetBrush(wx.Brush(speedbackground)) xclean1, yclean1 = self.__CircleCoords(sectorradius, -endangle, centerX, centerY) xclean2, yclean2 = self.__CircleCoords(sectorradius, -startangle-offset, centerX, centerY) dc.DrawArc(xclean1, yclean1, xclean2, yclean2, centerX, centerY) # This Is Needed To Fill The Partial Sector Correctly xold, yold = self.__CircleCoords(radius, startangle+endangle, centerX, centerY) # Draw The Sectors for ii, interval in enumerate(intervals): if direction == "Advance": current = interval - start else: current = end - interval angle = (current/float(span))*(startangle-endangle) - startangle angletext = -((pi/2.0) + angle)*180/pi textangles.append(angletext) colourangles.append(angle) xtick, ytick = self.__CircleCoords(radius, angle, centerX, centerY) # Keep The Coordinates, We Will Need Them After To Position The Ticks xcoords.append(xtick) ycoords.append(ytick) x = xtick y = ytick if self._extrastyle & SM_DRAW_SECTORS: if self._extrastyle & SM_DRAW_PARTIAL_FILLER: if direction == "Advance": if current > currentvalue: x, y = self.__CircleCoords(radius, angle, centerX, centerY) else: x, y = self.__CircleCoords(sectorradius, angle, centerX, centerY) else: if current < end - currentvalue: x, y = self.__CircleCoords(radius, angle, centerX, centerY) else: x, y = self.__CircleCoords(sectorradius, angle, centerX, centerY) else: x, y = self.__CircleCoords(radius, angle, centerX, centerY) if ii > 0: if self._extrastyle & SM_DRAW_PARTIAL_FILLER and ii == intersection: # We Got The Interval In Which There Is The Current Value. If We Choose # A "Reverse" Direction, First We Draw The Partial Sector, Next The Filler dc.SetBrush(wx.Brush(speedbackground)) if direction == "Reverse": if self._extrastyle & SM_DRAW_SECTORS: dc.SetBrush(wx.Brush(colours[ii-1])) dc.DrawArc(xe2, ye2, xold, yold, centerX, centerY) if self._extrastyle & SM_DRAW_SECTORS: dc.SetBrush(wx.Brush(colours[ii-1])) else: dc.SetBrush(wx.Brush(speedbackground)) dc.DrawArc(xs1, ys1, xe1, ye1, centerX, centerY) if self._extrastyle & SM_DRAW_SECTORS: dc.SetBrush(wx.Brush(colours[ii-1])) # Here We Draw The Rest Of The Sector In Which The Current Value Is if direction == "Advance": dc.DrawArc(xs1, ys1, x, y, centerX, centerY) x = xs1 y = ys1 else: dc.DrawArc(xe2, ye2, x, y, centerX, centerY) elif self._extrastyle & SM_DRAW_SECTORS: dc.SetBrush(wx.Brush(colours[ii-1])) # Here We Still Use The SM_DRAW_PARTIAL_FILLER Style, But We Are Not # In The Sector Where The Current Value Resides if self._extrastyle & SM_DRAW_PARTIAL_FILLER and ii != intersection: if direction == "Advance": dc.DrawArc(x, y, xold, yold, centerX, centerY) else: if ii < intersection: dc.DrawArc(x, y, xold, yold, centerX, centerY) # This Is The Case Where No SM_DRAW_PARTIAL_FILLER Has Been Chosen else: dc.DrawArc(x, y, xold, yold, centerX, centerY) else: if self._extrastyle & SM_DRAW_PARTIAL_FILLER and self._extrastyle & SM_DRAW_SECTORS: dc.SetBrush(wx.Brush(fillercolour)) dc.DrawArc(xs2, ys2, xe2, ye2, centerX, centerY) x, y = self.__CircleCoords(sectorradius, angle, centerX, centerY) dc.SetBrush(wx.Brush(colours[ii])) dc.DrawArc(xs1, ys1, xe1, ye1, centerX, centerY) x = xs2 y = ys2 xold = x yold = y if self._extrastyle & SM_DRAW_PARTIAL_SECTORS: sectorendradius = radius - 10.0*self.scale sectorstartradius = radius xps, yps = self.__CircleCoords(sectorstartradius, angle, centerX, centerY) if ii > 0: dc.SetBrush(wx.Brush(colours[ii-1])) dc.DrawArc(xps, yps, xpsold, ypsold, centerX, centerY) xpsold = xps ypsold = yps if self._extrastyle & SM_DRAW_PARTIAL_SECTORS: xps1, yps1 = self.__CircleCoords(sectorendradius, -endangle+2*offset, centerX, centerY) xps2, yps2 = self.__CircleCoords(sectorendradius, -startangle-2*offset, centerX, centerY) dc.SetBrush(wx.Brush(speedbackground)) dc.DrawArc(xps1, yps1, xps2, yps2, centerX, centerY) if self._extrastyle & SM_DRAW_GRADIENT: dc.SetPen(wx.TRANSPARENT_PEN) xcurrent, ycurrent = self.__CircleCoords(radius, accelangle, centerX, centerY) # calculate gradient coefficients col2 = self.GetSecondGradientColour() col1 = self.GetFirstGradientColour() r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue()) r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue()) flrect = float(radius+self.scale) numsteps = 200 rstep = float((r2 - r1)) / numsteps gstep = float((g2 - g1)) / numsteps bstep = float((b2 - b1)) / numsteps rf, gf, bf = 0, 0, 0 radiusteps = flrect/numsteps interface = 0 for ind in range(numsteps+1): currCol = (r1 + rf, g1 + gf, b1 + bf) dc.SetBrush(wx.Brush(currCol)) gradradius = flrect - radiusteps*ind xst1, yst1 = self.__CircleCoords(gradradius, -endangle, centerX, centerY) xen1, yen1 = self.__CircleCoords(gradradius, -startangle-offset, centerX, centerY) if self._extrastyle & SM_DRAW_PARTIAL_FILLER: if gradradius >= fillerendradius: if direction == "Advance": dc.DrawArc(xstart, ystart, xcurrent, ycurrent, centerX, centerY) else: dc.DrawArc(xcurrent, ycurrent, xend, yend, centerX, centerY) else: if interface == 0: interface = 1 myradius = fillerendradius + 1 xint1, yint1 = self.__CircleCoords(myradius, -endangle, centerX, centerY) xint2, yint2 = self.__CircleCoords(myradius, -startangle-offset, centerX, centerY) dc.DrawArc(xint1, yint1, xint2, yint2, centerX, centerY) dc.DrawArc(xst1, yst1, xen1, yen1, centerX, centerY) else: if self._extrastyle & SM_DRAW_PARTIAL_SECTORS: if gradradius <= sectorendradius: if interface == 0: interface = 1 myradius = sectorendradius + 1 xint1, yint1 = self.__CircleCoords(myradius, -endangle, centerX, centerY) xint2, yint2 = self.__CircleCoords(myradius, -startangle-offset, centerX, centerY) dc.DrawArc(xint1, yint1, xint2, yint2, centerX, centerY) else: dc.DrawArc(xst1, yst1, xen1, yen1, centerX, centerY) else: dc.DrawArc(xst1, yst1, xen1, yen1, centerX, centerY) rf = rf + rstep gf = gf + gstep bf = bf + bstep textheight = 0 # Get The Ticks And The Ticks Colour ticks = self.GetTicks()[:] tickscolour = self.GetTicksColour() if direction == "Reverse": ticks.reverse() if self._extrastyle & SM_DRAW_SECONDARY_TICKS: ticknum = self.GetNumberOfSecondaryTicks() oldinterval = intervals[0] dc.SetPen(wx.Pen(tickscolour, 1)) dc.SetBrush(wx.Brush(tickscolour)) dc.SetTextForeground(tickscolour) # Get The Font For The Ticks tfont, fontsize = self.GetTicksFont() tfont = tfont[0] myfamily = tfont.GetFamily() fsize = self.scale*fontsize tfont.SetPointSize(int(fsize)) tfont.SetFamily(myfamily) dc.SetFont(tfont) if self._extrastyle & SM_DRAW_FANCY_TICKS: facename = tfont.GetFaceName() ffamily = familyname[fontfamily.index(tfont.GetFamily())] fweight = weightsname[weights.index(tfont.GetWeight())] fstyle = stylesname[styles.index(tfont.GetStyle())] fcolour = wx.TheColourDatabase.FindName(tickscolour) textheight = 0 # Draw The Ticks And The Markers (Text Ticks) for ii, angles in enumerate(textangles): strings = ticks[ii] if self._extrastyle & SM_DRAW_FANCY_TICKS == 0: width, height, dummy, dummy = dc.GetFullTextExtent(strings, tfont) textheight = height else: width, height, dummy = fancytext.GetFullExtent(strings, dc) textheight = height lX = dc.GetCharWidth()/2.0 lY = dc.GetCharHeight()/2.0 if self._extrastyle & SM_ROTATE_TEXT: angis = colourangles[ii] - float(width)/(2.0*radius) x, y = self.__CircleCoords(radius-10.0*self.scale, angis, centerX, centerY) dc.DrawRotatedText(strings, x, y, angles) else: angis = colourangles[ii] if self._extrastyle & SM_DRAW_FANCY_TICKS == 0: x, y = self.__CircleCoords(radius-10*self.scale, angis, centerX, centerY) lX = lX*len(strings) x = x - lX - width*cos(angis)/2.0 y = y - lY - height*sin(angis)/2.0 if self._extrastyle & SM_DRAW_FANCY_TICKS: fancystr = '<font family="' + ffamily + '" size="' + str(int(fsize)) + '" weight="' + fweight + '"' fancystr = fancystr + ' color="' + fcolour + '"' + ' style="' + fstyle + '"> ' + strings + ' </font>' width, height, dummy = fancytext.GetFullExtent(fancystr, dc) x, y = self.__CircleCoords(radius-10*self.scale, angis, centerX, centerY) x = x - width/2.0 - width*cos(angis)/2.0 y = y - height/2.0 - height*sin(angis)/2.0 fancytext.RenderToDC(fancystr, dc, x, y) else: dc.DrawText(strings, x, y) # This Is The Small Rectangle --> Tick Mark rectangle = colourangles[ii] + pi/2.0 sinrect = sin(rectangle) cosrect = cos(rectangle) x1 = xcoords[ii] - self.scale*cosrect y1 = ycoords[ii] - self.scale*sinrect x2 = x1 + 3*self.scale*cosrect y2 = y1 + 3*self.scale*sinrect x3 = x1 - 10*self.scale*sinrect y3 = y1 + 10*self.scale*cosrect x4 = x3 + 3*self.scale*cosrect y4 = y3 + 3*self.scale*sinrect points = [(x1, y1), (x2, y2), (x4, y4), (x3, y3)] dc.DrawPolygon(points) if self._extrastyle & SM_DRAW_SECONDARY_TICKS: if ii > 0: newinterval = intervals[ii] oldinterval = intervals[ii-1] spacing = (newinterval - oldinterval)/float(ticknum+1) for tcount in xrange(ticknum): if direction == "Advance": oldinterval = (oldinterval + spacing) - start stint = oldinterval else: oldinterval = start + (oldinterval + spacing) stint = end - oldinterval angle = (stint/float(span))*(startangle-endangle) - startangle rectangle = angle + pi/2.0 sinrect = sin(rectangle) cosrect = cos(rectangle) xt, yt = self.__CircleCoords(radius, angle, centerX, centerY) x1 = xt - self.scale*cosrect y1 = yt - self.scale*sinrect x2 = x1 + self.scale*cosrect y2 = y1 + self.scale*sinrect x3 = x1 - 6*self.scale*sinrect y3 = y1 + 6*self.scale*cosrect x4 = x3 + self.scale*cosrect y4 = y3 + self.scale*sinrect points = [(x1, y1), (x2, y2), (x4, y4), (x3, y3)] dc.DrawPolygon(points) oldinterval = newinterval tfont.SetPointSize(fontsize) tfont.SetFamily(myfamily) self.SetTicksFont(tfont) # Draw The External Arc dc.SetBrush(wx.TRANSPARENT_BRUSH) if self._drawarc and not self._drawfullarc: dc.SetPen(wx.Pen(self.GetArcColour(), 2.0)) # If It's Not A Complete Circle, Draw The Connecting Lines And The Arc if abs(abs(startangle - endangle) - 2*pi) > 1.0/180.0: dc.DrawArc(xstart, ystart, xend, yend, centerX, centerY) dc.DrawLine(xstart, ystart, centerX, centerY) dc.DrawLine(xend, yend, centerX, centerY) else: # Draw A Circle, Is A 2*pi Extension Arc = Complete Circle dc.DrawCircle(centerX, centerY, radius) if self._drawfullarc: dc.DrawCircle(centerX, centerY, radius) # Here We Draw The Text In The Middle, Near The Start Of The Arrow (If Present) # This Is Like The "Km/h" Or "mph" Text In The Cars if self._extrastyle & SM_DRAW_MIDDLE_TEXT: middlecolour = self.GetMiddleTextColour() middletext = self.GetMiddleText() middleangle = (startangle + endangle)/2.0 middlefont, middlesize = self.GetMiddleTextFont() middlesize = self.scale*middlesize middlefont.SetPointSize(int(middlesize)) dc.SetFont(middlefont) mw, mh, dummy, dummy = dc.GetFullTextExtent(middletext, middlefont) newx = centerX + 1.5*mw*cos(middleangle) - mw/2.0 newy = centerY - 1.5*mh*sin(middleangle) - mh/2.0 dc.SetTextForeground(middlecolour) dc.DrawText(middletext, newx, newy) # Here We Draw The Text In The Bottom # This Is Like The "Km/h" Or "mph" Text In The Cars if self._extrastyle & SM_DRAW_BOTTOM_TEXT: bottomcolour = self.GetBottomTextColour() bottomtext = self.GetBottomText() # hack for two lines of text if bottomtext.find("\n") != -1: # we have a newline foo = bottomtext.partition("\n") bottomtext1 = foo[0] bottomtext2 = foo[2] bottomangle = (startangle + endangle)/2.0 bottomfont, bottomsize = self.GetBottomTextFont() bottomsize = self.scale*bottomsize bottomfont.SetPointSize(int(bottomsize)) dc.SetFont(bottomfont) mw, mh, dummy, dummy = dc.GetFullTextExtent(bottomtext1, bottomfont) newx = centerX + 1.5*mw*cos(bottomangle) - mw/2.0 newy = ystart yoffset = mh + (mh * 2) dc.SetTextForeground(bottomcolour) dc.DrawText(bottomtext1, newx, newy) mw, mh, dummy, dummy = dc.GetFullTextExtent(bottomtext2, bottomfont) newx = centerX + 1.5*mw*cos(bottomangle) - mw/2.0 newy = ystart + yoffset dc.SetTextForeground(bottomcolour) dc.DrawText(bottomtext2, newx, newy) else: bottomangle = (startangle + endangle)/2.0 bottomfont, bottomsize = self.GetBottomTextFont() bottomsize = self.scale*bottomsize bottomfont.SetPointSize(int(bottomsize)) dc.SetFont(bottomfont) mw, mh, dummy, dummy = dc.GetFullTextExtent(bottomtext, bottomfont) newx = centerX + 1.5*mw*cos(bottomangle) - mw/2.0 newy = ystart dc.SetTextForeground(bottomcolour) dc.DrawText(bottomtext, newx, newy) self.bottomTextBottom = (int)(newy + mh) # Here We Draw The Icon In The Middle, Near The Start Of The Arrow (If Present) # This Is Like The "Fuel" Icon In The Cars if self._extrastyle & SM_DRAW_MIDDLE_ICON: middleicon = self.GetMiddleIcon() middlewidth, middleheight = self.__GetMiddleIconDimens() middleicon.SetWidth(middlewidth*self.scale) middleicon.SetHeight(middleheight*self.scale) middleangle = (startangle + endangle)/2.0 mw = middleicon.GetWidth() mh = middleicon.GetHeight() newx = centerX + 1.5*mw*cos(middleangle) - mw/2.0 newy = centerY - 1.5*mh*sin(middleangle) - mh/2.0 dc.DrawIcon(middleicon, newx, newy) # Restore Icon Dimension, If Not Something Strange Happens middleicon.SetWidth(middlewidth) middleicon.SetHeight(middleheight) # Requested To Draw The Hand if self._extrastyle & SM_DRAW_HAND: handstyle = self.GetHandStyle() handcolour = self.GetHandColour() # Calculate The Data For The Hand if textheight == 0: maxradius = radius-10*self.scale else: maxradius = radius-5*self.scale-textheight xarr, yarr = self.__CircleCoords(maxradius, accelangle, centerX, centerY) if handstyle == "Arrow": x1, y1 = self.__CircleCoords(maxradius, accelangle - 4.0/180, centerX, centerY) x2, y2 = self.__CircleCoords(maxradius, accelangle + 4.0/180, centerX, centerY) x3, y3 = self.__CircleCoords(maxradius+3*(abs(xarr-x1)), accelangle, centerX, centerY) newx = centerX + 4*cos(accelangle)*self.scale newy = centerY + 4*sin(accelangle)*self.scale else: x1 = centerX + 4*self.scale*sin(accelangle) y1 = centerY - 4*self.scale*cos(accelangle) x2 = xarr y2 = yarr x3 = centerX - 4*self.scale*sin(accelangle) y3 = centerY + 4*self.scale*cos(accelangle) x4, y4 = self.__CircleCoords(5*self.scale*sqrt(3), accelangle+pi, centerX, centerY) if self._extrastyle & SM_DRAW_SHADOW: if handstyle == "Arrow": # Draw The Shadow shadowcolour = self.GetShadowColour() dc.SetPen(wx.Pen(shadowcolour, 5*log(self.scale+1))) dc.SetBrush(wx.Brush(shadowcolour)) shadowdistance = 2.0*self.scale dc.DrawLine(newx + shadowdistance, newy + shadowdistance, xarr + shadowdistance, yarr + shadowdistance) dc.DrawPolygon([(x1+shadowdistance, y1+shadowdistance), (x2+shadowdistance, y2+shadowdistance), (x3+shadowdistance, y3+shadowdistance)]) else: # Draw The Shadow shadowcolour = self.GetShadowColour() dc.SetBrush(wx.Brush(shadowcolour)) dc.SetPen(wx.Pen(shadowcolour, 1.0)) shadowdistance = 1.5*self.scale dc.DrawPolygon([(x1+shadowdistance, y1+shadowdistance), (x2+shadowdistance, y2+shadowdistance), (x3+shadowdistance, y3+shadowdistance), (x4+shadowdistance, y4+shadowdistance)]) if handstyle == "Arrow": dc.SetPen(wx.Pen(handcolour, 1.5)) # Draw The Small Circle In The Center --> The Hand "Holder" dc.SetBrush(wx.Brush(speedbackground)) dc.DrawCircle(centerX, centerY, 4*self.scale) dc.SetPen(wx.Pen(handcolour, 5*log(self.scale+1))) # Draw The "Hand", An Arrow dc.DrawLine(newx, newy, xarr, yarr) # Draw The Arrow Pointer dc.SetBrush(wx.Brush(handcolour)) dc.DrawPolygon([(x1, y1), (x2, y2), (x3, y3)]) else: # Draw The Hand Pointer dc.SetPen(wx.Pen(handcolour, 1.5)) dc.SetBrush(wx.Brush(handcolour)) dc.DrawPolygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)]) # Draw The Small Circle In The Center --> The Hand "Holder" dc.SetBrush(wx.Brush(speedbackground)) dc.DrawCircle(centerX, centerY, 4*self.scale) # here is where we draw the LEDNumberCtrl-style display at the bottom, if requested if self._extrastyle & SM_DRAW_BOTTOM_LED: self._DrawLED(dc, centerX) dc.EndDrawing() def SetIntervals(self, intervals=None): """ Sets The Intervals For SpeedMeter (Main Ticks Numeric Values). @param intervals: list of the interval end points @type intervals: L{list} of L{int}s or L{float}s, one marking the end of each interval """ if intervals is None: intervals = [0, 50, 100] self._intervals = intervals def GetIntervals(self): """ Gets The Intervals For SpeedMeter. @rtype: L{list} of L{int}s or L{float}s, one marking the end of each interval """ return self._intervals def GetBottomTextBottom(self): """ Gets the Y position of the bottom of the BottomText. Used to position the LEDNumberCtrl if one is present. @return: Y position of the bottom of the BottomText on the BufferedWindow (DC) @rtype: int """ return self.bottomTextBottom def GetWidth(self): """ Gets the whole width of the SpeedMeter. Used to position the LEDNumberCtrl if present. @return: Width (px) of the whole faceBitmap @rtype: int """ return self.faceBitmap.GetWidth() def SetSpeedValue(self, value=None): """ Sets The Current Value For SpeedMeter. Please also see L{SetValueMultiplier}() function. The value MUST be within the range specified by the L{intervals} (see L{GetIntervals}). Calling this function will trigger the L{UpdateDrawing}() method to redraw. @param value: the desired value @type value: L{int} or L{float} """ if value is None: value = (max(self._intervals) - min(self._intervals))/2.0 else: if not (isinstance(value, int) or isinstance(value, float)): raise TypeError("value parameter of SetSpeedValue must be of int or float type, not " + str(type(value))) if value < min(self._intervals): raise IndexError("value parameter of SetSpeedValue is smaller than the minimum element in the points (intervals) list") elif value > max(self._intervals): raise IndexError("value parameter of SetSpeedValue Greater Than Maximum Element In Points List") self._speedvalue = value self._speedStr = str(int(value * self._ValueMultiplier)) try: self.UpdateDrawing() except: pass def GetSpeedValue(self): """ Gets The Current Value For SpeedMeter. @rtype: L{int} or L{float} """ return self._speedvalue def SetAngleRange(self, start=0, end=pi): """ Sets The Range Of Existence For SpeedMeter. This Values *Must* Be Specifiend In RADIANS. @param start: the start angle (default 0) @type start: L{int} in radians @param end: the end angle (default pi) @type end: L{int} in radians """ self._anglerange = [start, end] def GetAngleRange(self): """ Gets The Range Of Existence For SpeedMeter. The Returned Values Are In RADIANS. @rtype: L{list} of L{int}s (radians) like [start, end] """ return self._anglerange def SetIntervalColours(self, colours=None): """ Sets The Colours For The Intervals. Every Intervals (Circle Sector) Should Have A Colour. Expects a list of L{wx.Colour}s of the same length as the number of intervals. @param colours: list of colours to use for intervals @type colours: L{list} of L{wx.Colour}s of same length as number of intervals """ if colours is None: if not hasattr(self, "_anglerange"): errstr = "\nERROR: Impossible To Set Interval Colours," errstr = errstr + " Please Define The Intervals Ranges Before." raise errstr return colours = [wx.WHITE]*len(self._intervals) else: if len(colours) != len(self._intervals) - 1: errstr = "\nERROR: Length Of Colour List Does Not Match Length" errstr = errstr + " Of Intervals Ranges List." print errstr raise errstr return self._intervalcolours = colours def GetIntervalColours(self): """ Gets The Colours For The Intervals. @rtype: L{list} of L{wx.Colour}s """ if hasattr(self, "_intervalcolours"): return self._intervalcolours else: raise "\nERROR: No Interval Colours Have Been Defined" def SetTicks(self, ticks=None): """ Sets The Ticks For SpeedMeter Intervals (Main Ticks String Values). Must be a list of strings, of the same length as the number of intervals. This should probably not be called from outside the class, unless you want to set the interval ticks to something weird (maybe a fuel meter using "1/4", "1/2", etc.). It is probably better to use the L{SetValueMultiplier}() function if you're dealing with linear integers. @param ticks: list of strings, of the same length as the number of intervals. @type ticks: L{list} of L{string}s """ if ticks is None: if not hasattr(self, "_anglerange"): errstr = "\nERROR: Impossible To Set Interval Ticks," errstr = errstr + " Please Define The Intervals Ranges Before." raise errstr return ticks = [] for values in self._intervals: ticks.append(str(values)) else: if len(ticks) != len(self._intervals): errstr = "\nERROR: Length Of Ticks List Does Not Match Length" errstr = errstr + " Of Intervals Ranges List." raise errstr return self._intervalticks = ticks def GetTicks(self): """ Gets The Ticks For SpeedMeter Intervals (Main Ticks String Values). @rtype: L{list} of L{string}s """ if hasattr(self, "_intervalticks"): return self._intervalticks else: raise "\nERROR: No Interval Ticks Have Been Defined" def SetTicksFont(self, font=None): """ Sets The Ticks Font. @param font: the font for the text (default 10pt, wx.Font(1, wx.SWISS, wx.NORMAL, wx.BOLD, False)) @type font: L{wx.Font} """ if font is None: self._originalfont = [wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD, False)] self._originalsize = 10 else: self._originalfont = [font] self._originalsize = font.GetPointSize() def GetTicksFont(self): """ Gets The Ticks Font. @rtype: L{tuple} of (L{wx.Font}, L{float} size) """ return self._originalfont[:], self._originalsize def SetTicksColour(self, colour=None): """ Sets The Ticks Colour. @param colour @type colour: L{wx.Colour} """ if colour is None: colour = wx.BLUE self._tickscolour = colour def GetTicksColour(self): """ Gets The Ticks Colour. @rtype: L{wx.Colour} """ return self._tickscolour def SetSpeedBackground(self, colour=None): """ Sets The Background Colour Outside The SpeedMeter Control. @param colour @type colour: L{wx.Colour} """ if colour is None: colour = wx.SystemSettings_GetColour(0) self._speedbackground = colour def GetSpeedBackground(self): """ Gets The Background Colour Outside The SpeedMeter Control. @rtype: L{wx.Colour} """ return self._speedbackground def SetHandColour(self, colour=None): """ Sets The Hand (Arrow Indicator) Colour. @param colour @type colour: L{wx.Colour} """ if colour is None: colour = wx.RED self._handcolour = colour def GetHandColour(self): """ Gets The Hand (Arrow Indicator) Colour. @rtype: L{wx.Colour} """ return self._handcolour def SetArcColour(self, colour=None): """ Sets The External Arc Colour (Thicker Line). @param colour @type colour: L{wx.Colour} """ if colour is None: colour = wx.BLACK self._arccolour = colour def GetArcColour(self): """ Gets The External Arc Colour. @rtype: L{wx.Colour} """ return self._arccolour def SetShadowColour(self, colour=None): """ Sets The Hand's Shadow Colour. @param colour @type colour: L{wx.Colour} """ if colour is None: colour = wx.Colour(150, 150, 150) self._shadowcolour = colour def GetShadowColour(self): """ Gets The Hand's Shadow Colour. @rtype: L{wx.Colour} """ return self._shadowcolour def SetFillerColour(self, colour=None): """ Sets The Partial Filler Colour. A Circle Corona Near The Ticks Will Be Filled With This Colour, From The Starting Value To The Current Value Of SpeedMeter. @param colour: the colour @type colour: L{wx.Colour} """ if colour is None: colour = wx.Colour(255, 150, 50) self._fillercolour = colour def GetFillerColour(self): """ Gets The Partial Filler Colour. @rtype: L{wx.Colour} """ return self._fillercolour def SetDirection(self, direction=None): """ Sets The Direction Of Advancing SpeedMeter Value. Specifying "Advance" Will Move The Hand In Clock-Wise Direction (Like Normal Car Speed Control), While Using "Reverse" Will Move It CounterClock-Wise Direction. @param direction: direction of needle movement @type direction: L{string} "Advance" (default) or "Reverse" """ if direction is None: direction = "Advance" if direction not in ["Advance", "Reverse"]: raise '\nERROR: Direction Parameter Should Be One Of "Advance" Or "Reverse".' return self._direction = direction def GetDirection(self): """ Gets The Direction Of Advancing SpeedMeter Value. @rtype: L{string} "Advance" or "Reverse" """ return self._direction def SetNumberOfSecondaryTicks(self, ticknum=None): """ Sets The Number Of Secondary (Intermediate) Ticks. @param ticknum: number of secondary ticks (MUST be >= 1, default is 3) @type ticknum: L{int} """ if ticknum is None: ticknum = 3 if ticknum < 1: raise "\nERROR: Number Of Ticks Must Be Greater Than 1." return self._secondaryticks = ticknum def GetNumberOfSecondaryTicks(self): """ Gets The Number Of Secondary (Intermediate) Ticks. @rtype: L{int} """ return self._secondaryticks def SetMiddleText(self, text=None): """ Sets The Text To Be Drawn Near The Center Of SpeedMeter. @param text: the text to draw @type text: L{string} """ if text is None: text = "" self._middletext = text def GetMiddleText(self): """ Gets The Text To Be Drawn Near The Center Of SpeedMeter. @rtype: L{string} """ return self._middletext def SetMiddleTextFont(self, font=None): """ Sets The Font For The Text In The Middle. @param font: the font for the text (default 10pt, wx.Font(1, wx.SWISS, wx.NORMAL, wx.BOLD, False)) @type font: L{wx.Font} """ if font is None: self._middletextfont = wx.Font(1, wx.SWISS, wx.NORMAL, wx.BOLD, False) self._middletextsize = 10.0 self._middletextfont.SetPointSize(self._middletextsize) else: self._middletextfont = font self._middletextsize = font.GetPointSize() self._middletextfont.SetPointSize(self._middletextsize) def GetMiddleTextFont(self): """ Gets The Font For The Text In The Middle. @rtype: L{tuple} of (L{wx.Font}, L{float} size) """ return self._middletextfont, self._middletextsize def SetMiddleTextColour(self, colour=None): """ Sets The Colour For The Text In The Middle. @param colour: the colour for the text @type colour: L{wx.Colour} """ if colour is None: colour = wx.BLUE self._middlecolour = colour def GetMiddleTextColour(self): """ Gets The Colour For The Text In The Middle. @rtype: L{wx.Colour} """ return self._middlecolour def SetBottomText(self, text=None): """ Sets The Text To Be Drawn Near The Bottom Of SpeedMeter. Can have up to one newline. This should be used for a label, such as the gauge type and scale (i.e. "RPM x1000) Newlines are understood. The text is drawn as two separate lines, and this is taken into account when positioning the LED digits if used. @param text: the text to draw @type text: L{string} """ if text is None: text = "" self._bottomtext = text def GetBottomText(self): """ Gets The Text To Be Drawn Near The Bottom Of SpeedMeter (label) @rtype: L{string} """ return self._bottomtext def SetBottomTextFont(self, font=None): """ Sets The Font For The Text In The Bottom. @param font: the font for the text (default 10pt, wx.Font(1, wx.SWISS, wx.NORMAL, wx.BOLD, False)) @type font: L{wx.Font} """ if font is None: self._bottomtextfont = wx.Font(1, wx.SWISS, wx.NORMAL, wx.BOLD, False) self._bottomtextsize = 10.0 self._bottomtextfont.SetPointSize(self._bottomtextsize) else: self._bottomtextfont = font self._bottomtextsize = font.GetPointSize() self._bottomtextfont.SetPointSize(self._bottomtextsize) def GetBottomTextFont(self): """ Gets The Font For The Text In The Bottom. @rtype: L{tuple} of (L{wx.Font}, L{float} size) """ return self._bottomtextfont, self._bottomtextsize def SetBottomTextColour(self, colour=None): """ Sets The Colour For The Text In The Bottom of the gauge (label). @param colour: the colour for the text @type colour: L{wx.Colour} """ if colour is None: colour = wx.BLUE self._bottomcolour = colour def SetLEDColour(self, colour=None): """ Sets The Colour For Bottom LED digits. @param colour: the colour for the digits @type colour: L{wx.Colour} """ if colour is None: colour = wx.GREEN self._ledcolour = colour def GetLEDColour(self): """ Gets The Colour For The LED Digits @rtype: L{wx.Colour} """ return self._ledcolour def GetBottomTextColour(self): """ Gets The Colour For The Text In The Bottom @rtype: L{wx.Colour} """ return self._bottomcolour def SetMiddleIcon(self, icon): """ Sets The Icon To Be Drawn Near The Center Of SpeedMeter. @param icon: The icon to be drawn @type icon: L{wx.Icon} """ if icon.Ok(): self._middleicon = icon else: # edited 2010-06-13 by jantman to get rid of error - was raising an error as a string print "\nERROR: Invalid Icon Passed To SpeedMeter." return False def GetMiddleIcon(self): """ Gets The Icon To Be Drawn Near The Center Of SpeedMeter. @rtype: L{wx.Icon} """ return self._middleicon def __GetMiddleIconDimens(self): """ USED INTERNALLY ONLY - Undocumented. Do NOT call from outside this class. """ return self._middleicon.GetWidth(), self._middleicon.GetHeight() def __CircleCoords(self, radius, angle, centerX, centerY): """ USED INTERNALLY ONLY - Undocumented. Do NOT call from outside this class. Method to get the coordinates of the circle. """ x = radius*cos(angle) + centerX y = radius*sin(angle) + centerY return x, y def __GetIntersection(self, current, intervals): """ USED INTERNALLY ONLY - Undocumented. Do NOT call from outside this class. """ if self.GetDirection() == "Reverse": interval = intervals[:] interval.reverse() else: interval = intervals indexes = range(len(intervals)) try: intersection = [ind for ind in indexes if interval[ind] <= current <= interval[ind+1]] except: if self.GetDirection() == "Reverse": intersection = [len(intervals) - 1] else: intersection = [0] return intersection[0] def SetFirstGradientColour(self, colour=None): """ Sets The First Gradient Colour (Near The Ticks). @param colour: Color for the second gradient @type colour: L{wx.Colour} """ if colour is None: colour = wx.Colour(145, 220, 200) self._firstgradientcolour = colour def GetFirstGradientColour(self): """ Gets The First Gradient Colour (Near The Ticks). @return: first gradient color @rtype: L{wx.Colour} """ return self._firstgradientcolour def SetSecondGradientColour(self, colour=None): """ Sets The Second Gradient Colour (Near The Center). @param colour: Color for the second gradient @type colour: L{wx.Colour} """ if colour is None: colour = wx.WHITE self._secondgradientcolour = colour def GetSecondGradientColour(self): """ Gets The First Gradient Colour (Near The Center). @return: second gradient color @rtype: L{wx.Colour} """ return self._secondgradientcolour def SetHandStyle(self, style=None): """ Sets The Style For The Hand (Arrow Indicator). By Specifying "Hand" SpeedMeter Will Draw A Polygon That Simulates The Car Speed Control Indicator. Using "Arrow" Will Force SpeedMeter To Draw A Simple Arrow. @param style: hand style, string, either "Arrow" or "Hand" @type style: L{string} """ if style is None: style = "Hand" if style not in ["Hand", "Arrow"]: raise '\nERROR: Hand Style Parameter Should Be One Of "Hand" Or "Arrow".' return self._handstyle = style def GetHandStyle(self): """ Gets The Style For The Hand (Arrow Indicator) @return: hand style, string either "Arrow" or "Hand" @rtype: L{string} """ return self._handstyle def DrawExternalArc(self, draw=True): """ Specify Wheter Or Not You Wish To Draw The External (Thicker) Arc. @param draw: Whether or not to draw the external arc.(default True) @type draw: L{boolean} """ self._drawarc = draw def DrawExternalCircle(self, draw=False): """ Specify Wheter Or Not You Wish To Draw The External (Thicker) Arc as a full circle. @param draw: boolean, whether or not to draw the full circle (default False) @type draw: L{boolean} """ self._drawfullarc = draw def OnMouseMotion(self, event): """ Handles The Mouse Events. Here Only Left Clicks/Drags Are Involved. Should SpeedMeter Have Something More? @todo: Do we even want this? What does it do? Seems like it would allow the user to change the value or something, which is BAD. """ mousex = event.GetX() mousey = event.GetY() if event.Leaving(): return pos = self.GetClientSize() size = self.GetPosition() centerX = self.CenterX centerY = self.CenterY direction = self.GetDirection() if event.LeftIsDown(): angle = atan2(float(mousey) - centerY, centerX - float(mousex)) + pi - self.EndAngle if angle >= 2*pi: angle = angle - 2*pi if direction == "Advance": currentvalue = (self.StartAngle - self.EndAngle - angle)*float(self.Span)/(self.StartAngle - self.EndAngle) + self.StartValue else: currentvalue = (angle)*float(self.Span)/(self.StartAngle - self.EndAngle) + self.StartValue if currentvalue >= self.StartValue and currentvalue <= self.EndValue: self.SetSpeedValue(currentvalue) event.Skip() def GetSpeedStyle(self): """ Returns A List Of Strings And A List Of Integers Containing The Styles. """ stringstyle = [] integerstyle = [] if self._extrastyle & SM_ROTATE_TEXT: stringstyle.append("SM_ROTATE_TEXT") integerstyle.append(SM_ROTATE_TEXT) if self._extrastyle & SM_DRAW_SECTORS: stringstyle.append("SM_DRAW_SECTORS") integerstyle.append(SM_DRAW_SECTORS) if self._extrastyle & SM_DRAW_PARTIAL_SECTORS: stringstyle.append("SM_DRAW_PARTIAL_SECTORS") integerstyle.append(SM_DRAW_PARTIAL_SECTORS) if self._extrastyle & SM_DRAW_HAND: stringstyle.append("SM_DRAW_HAND") integerstyle.append(SM_DRAW_HAND) if self._extrastyle & SM_DRAW_SHADOW: stringstyle.append("SM_DRAW_SHADOW") integerstyle.append(SM_DRAW_SHADOW) if self._extrastyle & SM_DRAW_PARTIAL_FILLER: stringstyle.append("SM_DRAW_PARTIAL_FILLER") integerstyle.append(SM_DRAW_PARTIAL_FILLER) if self._extrastyle & SM_DRAW_SECONDARY_TICKS: stringstyle.append("SM_DRAW_SECONDARY_TICKS") integerstyle.append(SM_DRAW_SECONDARY_TICKS) if self._extrastyle & SM_DRAW_MIDDLE_TEXT: stringstyle.append("SM_DRAW_MIDDLE_TEXT") integerstyle.append(SM_DRAW_MIDDLE_TEXT) if self._extrastyle & SM_DRAW_BOTTOM_TEXT: stringstyle.append("SM_DRAW_BOTTOM_TEXT") integerstyle.append(SM_DRAW_BOTTOM_TEXT) if self._extrastyle & SM_DRAW_BOTTOM_LED: stringstyle.append("SM_DRAW_BOTTOM_LED") integerstyle.append(SM_DRAW_BOTTOM_LED) if self._extrastyle & SM_DRAW_MIDDLE_ICON: stringstyle.append("SM_DRAW_MIDDLE_ICON") integerstyle.append(SM_DRAW_MIDDLE_ICON) if self._extrastyle & SM_DRAW_GRADIENT: stringstyle.append("SM_DRAW_GRADIENT") integerstyle.append(SM_DRAW_GRADIENT) if self._extrastyle & SM_DRAW_FANCY_TICKS: stringstyle.append("SM_DRAW_FANCY_TICKS") integerstyle.append(SM_DRAW_FANCY_TICKS) return stringstyle, integerstyle # below here is stuff added by jantman for the LED control def SetDrawFaded(self, DrawFaded=None, Redraw=False): """ Set the option to draw the faded (non-used) LED segments. @param DrawFaded: Whether or not to draw the unused segments. @type DrawFaded: L{boolean} @param Redraw: Whether or not to redraw NOW. @type Redraw: L{boolean} """ if DrawFaded is None: self._DrawFaded = DrawFaded if DrawFaded != self._DrawFaded: self._DrawFaded = DrawFaded if Redraw: Refresh(False) def _InitLEDInternals(self): """ Sets up the class variables for the LED control stuff. Should ONLY be called INTERNALLY. """ self._LineMargin = None self._LineLength = None self._LineWidth = None self._DigitMargin = None self._LeftStartPos = None def _DrawLED(self, dc, CenterX): """ Handles all of the drawing for the LED control, just an extension to the original SpeedMeter Draw() method. Should ONLY be called INTERNALLY. @todo: this is hard coded to ignore the background - doesn't draw it. If you want something different, you need to change it. @param dc: the DC @type dc: L{dc} @param CenterX: The X coordinate of the center of the gauge, as found in the original SpeedMeter code. @type CenterX: L{int} """ self._RecalcInternals() # Iterate each digit in the value, and draw. if self.DEBUG is True: print "===Drawing LED Value String: " + self._speedStr for i in range(len(self._speedStr)): c = self._speedStr[i] if self.DEBUG: print "Digit Number: " + str(i) print "Drawing Digit: " + c # Draw faded lines if wanted. if self._DrawFaded and (c != '.'): self._DrawDigit(dc, DIGITALL, i) # Draw the digits. if c == '0': self._DrawDigit(dc, DIGIT0, i) elif c == '1': self._DrawDigit(dc, DIGIT1, i) elif c == '2': self._DrawDigit(dc, DIGIT2, i) elif c == '3': self._DrawDigit(dc, DIGIT3, i) elif c == '4': self._DrawDigit(dc, DIGIT4, i) elif c == '5': self._DrawDigit(dc, DIGIT5, i) elif c == '6': self._DrawDigit(dc, DIGIT6, i) elif c == '7': self._DrawDigit(dc, DIGIT7, i) elif c == '8': self._DrawDigit(dc, DIGIT8, i) elif c == '9': self._DrawDigit(dc, DIGIT9, i) elif c == '-': self._DrawDigit(dc, DASH, i) elif c == '.': self._DrawDigit(dc, DECIMALSIGN, (i-1)) elif c == ' ': # skip this pass else: print "Error: Undefined Digit Value: " + c def _DrawDigit(self, dc, Digit, Column): """ Internal code to actually draw the lines that make up a single digit. Should be called INTERNALLY ONLY. @param dc: The DC. @type dc: L{dc} @param Digit: The constant (mask) defining the lines of the specified digit. @type Digit: L{int} @param Column: the number of the column that the digit should be in @type Column: L{int} """ LineColor = self.GetForegroundColour() if Digit == DIGITALL: R = LineColor.Red() / 16 G = LineColor.Green() / 16 B = LineColor.Blue() / 16 LineColor = wx.Colour(R, G, B) XPos = self._LeftStartPos + (Column * (self._LineLength + self._DigitMargin)) # Create a pen and draw the lines. Pen = wx.Pen(LineColor, self._LineWidth, wx.SOLID) dc.SetPen(Pen) if Digit & LINE1: dc.DrawLine(XPos + self._LineMargin*2, self._LineMargin + self.LEDyOffset, XPos + self._LineLength + self._LineMargin*2, self._LineMargin + self.LEDyOffset) if self.DEBUG: print "Line1" if Digit & LINE2: dc.DrawLine(XPos + self._LineLength + self._LineMargin*3, self._LineMargin*2 + self.LEDyOffset, XPos + self._LineLength + self._LineMargin*3, self._LineLength + (self._LineMargin*2) + self.LEDyOffset) if self.DEBUG: print "Line2" if Digit & LINE3: dc.DrawLine(XPos + self._LineLength + self._LineMargin*3, self._LineLength + (self._LineMargin*4) + self.LEDyOffset, XPos + self._LineLength + self._LineMargin*3, self._LineLength*2 + (self._LineMargin*4) + self.LEDyOffset) if self.DEBUG: print "Line3" if Digit & LINE4: dc.DrawLine(XPos + self._LineMargin*2, self._LineLength*2 + (self._LineMargin*5) + self.LEDyOffset, XPos + self._LineLength + self._LineMargin*2, self._LineLength*2 + (self._LineMargin*5) + self.LEDyOffset) if self.DEBUG: print "Line4" if Digit & LINE5: dc.DrawLine(XPos + self._LineMargin, self._LineLength + (self._LineMargin*4) + self.LEDyOffset, XPos + self._LineMargin, self._LineLength*2 + (self._LineMargin*4) + self.LEDyOffset) if self.DEBUG: print "Line5" if Digit & LINE6: dc.DrawLine(XPos + self._LineMargin, self._LineMargin*2 + self.LEDyOffset, XPos + self._LineMargin, self._LineLength + (self._LineMargin*2) + self.LEDyOffset) if self.DEBUG: print "Line6" if Digit & LINE7: dc.DrawLine(XPos + self._LineMargin*2, self._LineLength + (self._LineMargin*3) + self.LEDyOffset, XPos + self._LineMargin*2 + self._LineLength, self._LineLength + (self._LineMargin*3) + self.LEDyOffset) if self.DEBUG: print "Line7" if Digit & DECIMALSIGN: dc.DrawLine(XPos + self._LineLength + self._LineMargin*4, self._LineLength*2 + (self._LineMargin*5) + self.LEDyOffset, XPos + self._LineLength + self._LineMargin*4, self._LineLength*2 + (self._LineMargin*5) + self.LEDyOffset) if self.DEBUG: print "Line DecimalSign" #Dc.SetPen(wxNullPen); def _RecalcInternals(self): """ Recalculates all variables controlling the placement and gemoetry of the digits. Bases it off of the Frame size. This should calculate everything like the gauge center and work off of that. Should be called INTERNALLY ONLY. Dimensions of LED segments Size of character is based on the HEIGH of the widget, NOT the width. Segment height is calculated as follows: Each segment is m_LineLength pixels long. There is m_LineMargin pixels at the top and bottom of each line segment There is m_LineMargin pixels at the top and bottom of each digit Therefore, the heigth of each character is: m_LineMargin : Top digit boarder m_LineMargin+m_LineLength+m_LineMargin : Top half of segment m_LineMargin+m_LineLength+m_LineMargin : Bottom half of segment m_LineMargin : Bottom digit boarder ---------------------- m_LineMargin*6 + m_LineLength*2 == Total height of digit. Therefore, (m_LineMargin*6 + m_LineLength*2) must equal Height Spacing between characters can then be calculated as follows: m_LineMargin : before the digit, m_LineMargin+m_LineLength+m_LineMargin : for the digit width m_LineMargin : after the digit = m_LineMargin*4 + m_LineLength """ # the size params for just the LED area itself size = self.GetClientSize() LEDHeight = int(size.y / 7) # based off of height of 30 in a 214px high client Height = LEDHeight LEDWidth = int(size.x / 2.4) # based off of width of 120 in a 290px wide client ClientWidth = size.x self.LEDyOffset = self.bottomTextBottom if (Height * 0.075) < 1: self._LineMargin = 1 else: self._LineMargin = int(Height * 0.075) if (Height * 0.275) < 1: self._LineLength = 1 else: self._LineLength = int(Height * 0.275) self._LineWidth = self._LineMargin self._DigitMargin = self._LineMargin * 4 # Count the number of characters in the string; '.' characters are not # included because they do not take up space in the display count = 0; for char in self._speedStr: if char != '.': count = count + 1 ValueWidth = (self._LineLength + self._DigitMargin) * count if self._Alignment == gizmos.LED_ALIGN_LEFT: self._LeftStartPos = self._LineMargin + LeftEdge elif self._Alignment == gizmos.LED_ALIGN_RIGHT: self._LeftStartPos = ClientWidth - ValueWidth - self._LineMargin + LeftEdge else: # self._Alignment == gizmos.LED_ALIGN_CENTER: # centered is the default self._LeftStartPos = (ClientWidth /2 ) - (ValueWidth / 2) def SetLEDAlignment(self, Alignment=None, Redraw=False): """ Sets LED digit alignment. @param Alignment - the alignment of the LED digits - valid values are L{gizmos.LED_ALIGN_LEFT}, L{gizmos.LED_ALIGN_RIGHT}, L{gizmos.LED_ALIGN_CENTER} (center is default). @type Alignment: wxLEDValueAlign @param Redraw: Whether or not to redraw NOW. @type Redraw: L{boolean} """ if Alignment is None: self._Alignment = Alignment if Alignment != self._Alignment: self._Alignment = Alignment if Redraw: try: self.UpdateDrawing() except: pass def SetDrawFaded(self, DrawFaded=None, Redraw=False): """ Whether or not to draw the unused line segments. If true, draws them faded. @param DrawFaded: Whether or not to draw the faded segments. (Default False) @type DrawFaded: L{boolean} @param Redraw: Whether or not to redraw NOW. @type Redraw: L{boolean} """ if DrawFaded is None: self._DrawFaded = DrawFaded if DrawFaded != self._DrawFaded: self._DrawFaded = DrawFaded if Redraw: Refresh(False) def SetValueMultiplier(self, multiplier=1): """ Sets the value multiplier. Values set with SetValue() will be multiplied by this amount before being displayed on the LED control. @param multiplier: the value multiplier @type multiplier: L{int} or L{float} @todo: re-do all this by setting a ValueScale (maybe at create time) and using this scale to determine the gauge scale, also divide values by it before feeding into the meter code itself (i.e. LED will show value as passed with SetValue()). """ self._ValueMultiplier = multiplier
jantman/python-obd
SpeedMeter.py
Python
gpl-3.0
81,844
/* DA-NRW Software Suite | ContentBroker Copyright (C) 2015 LVRInfoKom Landschaftsverband Rheinland This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @author jens Peters * Factory for building events */ package de.uzk.hki.da.event; import java.util.List; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.uzk.hki.da.model.Node; import de.uzk.hki.da.model.SystemEvent; import de.uzk.hki.da.service.HibernateUtil; public class SystemEventFactory { protected Logger logger = LoggerFactory.getLogger( this.getClass().getName() ); private Node localNode; private String eventsPackage = "de.uzk.hki.da.event."; public void buildStoredEvents() { List<SystemEvent> ses = getEventsPerNode(); if (ses != null) { for (SystemEvent se : ses) { if (se.getType() == null) continue; AbstractSystemEvent ase = null; try { ase = (AbstractSystemEvent) Class.forName(eventsPackage + se.getType()).newInstance(); injectProperties(ase, se); ase.run(); } catch (Exception e) { logger.error("could not instantiate " + se.getType()); } } } else logger.debug("no events to perform"); } private void injectProperties(AbstractSystemEvent ase, SystemEvent se) { ase.setNode(localNode); ase.setOwner(se.getOwner()); ase.setStoredEvent(se); } @SuppressWarnings("unchecked") private List<SystemEvent>getEventsPerNode() { Session session = HibernateUtil.openSession(); List<SystemEvent> events=null; try{ events = session .createQuery("from SystemEvent e where e.node.id = ?1") .setParameter("1", localNode.getId()).setCacheable(false).list(); if ((events == null) || (events.isEmpty())){ logger.trace("no systemevents found for " + localNode.getName()); session.close(); return null; } session.close(); }catch(Exception e){ session.close(); logger.error("Caught error in getEventsPerNode id: " + localNode.getId() + " " + e.getMessage(),e); throw new RuntimeException(e.getMessage(), e); } return events; } public Node getLocalNode() { return localNode; } public void setLocalNode(Node localNode) { this.localNode = localNode; } }
da-nrw/DNSCore
ContentBroker/src/main/java/de/uzk/hki/da/event/SystemEventFactory.java
Java
gpl-3.0
2,827
/** * Copyright (C) 2005-2014 Rivet Logic Corporation. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; version 3 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.rivetlogic.portal.search.elasticsearch.indexer.document; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.search.Document; import com.liferay.portal.kernel.search.Field; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; import com.liferay.util.portlet.PortletProps; import com.rivetlogic.portal.search.elasticsearch.ElasticsearchIndexerConstants; /** * The Class ElasticsearchDocumentJSONBuilder. * */ public class ElasticsearchDocumentJSONBuilder { /** * Init method. */ public void loadExcludedTypes() { String cslExcludedType = PortletProps.get(ElasticsearchIndexerConstants.ES_KEY_EXCLUDED_INDEXTYPE); if(Validator.isNotNull(cslExcludedType)){ excludedTypes = new HashSet<String>(); for(String excludedType : cslExcludedType.split(StringPool.COMMA)){ excludedTypes.add(excludedType); } if(_log.isDebugEnabled()){ _log.debug("Loaded Excluded index types are:"+cslExcludedType); } _log.info("Loaded Excluded index types are:"+cslExcludedType); } else { if(_log.isDebugEnabled()){ _log.debug("Excluded index types are not defined"); } _log.info("Excluded index types are not defined"); } } /** * Convert to json. * * @param document * the document * @return the string */ public ElasticserachJSONDocument convertToJSON(final Document document) { Map<String, Field> fields = document.getFields(); ElasticserachJSONDocument elasticserachJSONDocument = new ElasticserachJSONDocument(); try { XContentBuilder contentBuilder = XContentFactory.jsonBuilder().startObject(); Field classnameField = document.getField(ElasticsearchIndexerConstants.ENTRY_CLASSNAME); String entryClassName = (classnameField == null)? "": classnameField.getValue(); /** * Handle all error scenarios prior to conversion */ if(isDocumentHidden(document)){ elasticserachJSONDocument.setError(true); elasticserachJSONDocument.setErrorMessage(ElasticserachJSONDocument.DocumentError.HIDDEN_DOCUMENT.toString()); return elasticserachJSONDocument; } if(entryClassName.isEmpty()){ elasticserachJSONDocument.setError(true); elasticserachJSONDocument.setErrorMessage(ElasticserachJSONDocument.DocumentError.MISSING_ENTRYCLASSNAME.toString()); return elasticserachJSONDocument; } if(isExcludedType(entryClassName)){ elasticserachJSONDocument.setError(true); elasticserachJSONDocument.setErrorMessage("Index Type:"+entryClassName+StringPool.COMMA+ElasticserachJSONDocument.DocumentError.EXCLUDED_TYPE.toString()); return elasticserachJSONDocument; } /** * To avoid multiple documents for versioned assets such as Journal articles, DL entry etc * the primary Id will be Indextype + Entry class PK. The primary Id is to maintain uniqueness * in ES server database and nothing to do with UID or is not used for any other purpose. */ Field classPKField = document.getField(ElasticsearchIndexerConstants.ENTRY_CLASSPK); String entryClassPK = (classPKField == null)? "": classPKField.getValue(); if(entryClassPK.isEmpty()){ elasticserachJSONDocument.setError(true); elasticserachJSONDocument.setErrorMessage(ElasticserachJSONDocument.DocumentError.MISSING_CLASSPK.toString()); return elasticserachJSONDocument; } /** Replace '.' by '_' in Entry class name,since '.' is not recommended by Elasticsearch in Index type */ String indexType = entryClassName.replace(StringPool.PERIOD, StringPool.UNDERLINE); elasticserachJSONDocument.setIndexType(indexType); elasticserachJSONDocument.setId(indexType+entryClassPK); /** Create a JSON string for remaining fields of document */ for (Iterator<Map.Entry<String, Field>> it = fields.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Field> entry = it.next(); Field field = entry.getValue(); contentBuilder.field(entry.getKey(), field.getValue()); } contentBuilder.endObject(); elasticserachJSONDocument.setJsonDocument(contentBuilder.string()); if(_log.isDebugEnabled()){ _log.debug("Liferay Document converted to ESJSON document successfully:"+contentBuilder.string()); } } catch (IOException e) { _log.error("IO Error during converstion of Liferay Document to JSON format"+e.getMessage()); } return elasticserachJSONDocument; } /** * Check if liferay Document is of type hidden. * * @param document the document * @return true, if is document hidden */ private boolean isDocumentHidden(Document document){ Field hiddenField = document.getField(ElasticsearchIndexerConstants.HIDDEN); String hiddenFlag = (hiddenField == null)? "" : hiddenField.getValue(); if(StringPool.TRUE.equalsIgnoreCase(hiddenFlag)){ return true; } return false; } /** * Check if EntryClassname is com.liferay.portal.kernel.plugin.PluginPackage/ExportImportHelper which need not be indexed * * @param indexType the index type * @return true, if is excluded type */ private boolean isExcludedType(String indexType) { if(indexType != null && excludedTypes != null) { for(String excludedType : excludedTypes){ if(indexType.toLowerCase().contains(excludedType.toLowerCase())){ return true; } } } return false; } /** The Constant _log. */ private final static Log _log = LogFactoryUtil.getLog(ElasticsearchDocumentJSONBuilder.class); /** The excluded types. */ private Set<String> excludedTypes; }
rivetlogic/liferay-elasticsearch-integration
webs/elasticsearch-web/docroot/WEB-INF/src/com/rivetlogic/portal/search/elasticsearch/indexer/document/ElasticsearchDocumentJSONBuilder.java
Java
gpl-3.0
7,524
#include <ui_animationControls.hh> #if QT_VERSION >= 0x050000 #include <QtWidgets> #else #include <QtGui> #endif class AnimationToolboxWidget : public QWidget, public Ui::AnimationControls { Q_OBJECT public: AnimationToolboxWidget(QWidget *parent = 0); };
heartvalve/OpenFlipper
Plugin-SkeletalAnimation/AnimationToolbox.hh
C++
gpl-3.0
274
require 'spec_helper' describe User do it { should have_db_column(:id) } it { should have_db_column(:name).of_type(:string) } it { should have_db_column(:login).of_type(:string) } it { should have_db_column(:persistence_token).of_type(:string) } it_should_behave_like "a timestamped model" it { should have_many(:role_associations) } it { should have_many(:roles) } it { should have_many(:schedules) } context "default order" do it "should order by login in a ascending way" do first_user = described_class.make!(:login => 'adam') second_user = described_class.make!(:login => 'zirbel') users = described_class.all users.index(first_user).should < users.index(second_user) end end end
fslab/lilith
spec/models/user_spec.rb
Ruby
gpl-3.0
743
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace MuMech { public class MechJebModuleThrustController : ComputerModule { public MechJebModuleThrustController(MechJebCore core) : base(core) { priority = 200; } public float trans_spd_act = 0; public float trans_prev_thrust = 0; public bool trans_kill_h = false; [Persistent(pass = (int)Pass.Global)] public bool limitToTerminalVelocity = false; [GeneralInfoItem("Limit to terminal velocity", InfoItem.Category.Thrust)] public void LimitToTerminalVelocityInfoItem() { GUIStyle s = new GUIStyle(GUI.skin.toggle); if (limiter == LimitMode.TerminalVelocity) s.onHover.textColor = s.onNormal.textColor = Color.green; limitToTerminalVelocity = GUILayout.Toggle(limitToTerminalVelocity, "Limit to terminal velocity", s); } [Persistent(pass = (int)Pass.Global)] public bool limitToPreventOverheats = false; [GeneralInfoItem("Prevent overheats", InfoItem.Category.Thrust)] public void LimitToPreventOverheatsInfoItem() { GUIStyle s = new GUIStyle(GUI.skin.toggle); if (limiter == LimitMode.Temperature) s.onHover.textColor = s.onNormal.textColor = Color.green; limitToPreventOverheats = GUILayout.Toggle(limitToPreventOverheats, "Prevent overheats", s); } [ToggleInfoItem("Smooth throttle", InfoItem.Category.Thrust)] [Persistent(pass = (int)Pass.Global)] public bool smoothThrottle = false; [Persistent(pass = (int)Pass.Global)] public double throttleSmoothingTime = 1.0; [Persistent(pass = (int)Pass.Global)] public bool limitToPreventFlameout = false; [GeneralInfoItem("Prevent jet flameout", InfoItem.Category.Thrust)] public void LimitToPreventFlameoutInfoItem() { GUIStyle s = new GUIStyle(GUI.skin.toggle); if (limiter == LimitMode.Flameout) s.onHover.textColor = s.onNormal.textColor = Color.green; limitToPreventFlameout = GUILayout.Toggle(limitToPreventFlameout, "Prevent jet flameout", s); } // 5% safety margin on flameouts [Persistent(pass = (int)Pass.Global)] public EditableDouble flameoutSafetyPct = 5; [ToggleInfoItem("Manage air intakes", InfoItem.Category.Thrust)] [Persistent(pass = (int)Pass.Global)] public bool manageIntakes = false; [Persistent(pass = (int)Pass.Global)] public bool limitAcceleration = false; [Persistent(pass = (int)Pass.Global)] public EditableDouble maxAcceleration = 40; [GeneralInfoItem("Limit acceleration", InfoItem.Category.Thrust)] public void LimitAccelerationInfoItem() { GUILayout.BeginHorizontal(); GUIStyle s = new GUIStyle(GUI.skin.toggle); if (limiter == LimitMode.Acceleration) s.onHover.textColor = s.onNormal.textColor = Color.green; limitAcceleration = GUILayout.Toggle(limitAcceleration, "Limit acceleration to", s, GUILayout.Width(140)); maxAcceleration.text = GUILayout.TextField(maxAcceleration.text, GUILayout.Width(30)); GUILayout.Label("m/s²", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } [Persistent(pass = (int)Pass.Local)] public bool limitThrottle = false; [Persistent(pass = (int)Pass.Local)] public EditableDoubleMult maxThrottle = new EditableDoubleMult(1, 0.01); [GeneralInfoItem("Limit throttle", InfoItem.Category.Thrust)] public void LimitThrottleInfoItem() { GUILayout.BeginHorizontal(); GUIStyle s = new GUIStyle(GUI.skin.toggle); if (limiter == LimitMode.Throttle) s.onHover.textColor = s.onNormal.textColor = Color.green; limitThrottle = GUILayout.Toggle(limitThrottle, "Limit throttle to", s, GUILayout.Width(110)); maxThrottle.text = GUILayout.TextField(maxThrottle.text, GUILayout.Width(30)); GUILayout.Label("%", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } [Persistent(pass = (int)Pass.Type)] public bool differentialThrottle = false; [GeneralInfoItem("Differential throttle", InfoItem.Category.Thrust)] public void DifferentialThrottle() { bool oldDifferentialThrottle = core.thrust.differentialThrottle; GUIStyle s = new GUIStyle(GUI.skin.toggle); if (differentialThrottle && vessel.LiftedOff()) { s.onHover.textColor = s.onNormal.textColor = core.thrust.differentialThrottleSuccess ? Color.green : Color.yellow; } differentialThrottle = GUILayout.Toggle(differentialThrottle, "Differential throttle", s); if (oldDifferentialThrottle && !core.thrust.differentialThrottle) core.thrust.DisableDifferentialThrottle(); } public Vector3d differentialThrottleDemandedTorque = new Vector3d(); // true if differential throttle is active and a solution has been found i.e. at least 3 engines are on and they are not aligned public bool differentialThrottleSuccess = false; public enum LimitMode { None, TerminalVelocity, Temperature, Flameout, Acceleration, Throttle } public LimitMode limiter = LimitMode.None; public float targetThrottle = 0; protected bool tmode_changed = false; public PIDController pid; float lastThrottle = 0; bool userCommandingRotation { get { return userCommandingRotationSmoothed > 0; } } int userCommandingRotationSmoothed = 0; bool lastDisableThrusters = false; public enum TMode { OFF, KEEP_ORBITAL, KEEP_SURFACE, KEEP_VERTICAL, KEEP_RELATIVE, DIRECT } private TMode prev_tmode = TMode.OFF; private TMode _tmode = TMode.OFF; public TMode tmode { get { return _tmode; } set { if (_tmode != value) { prev_tmode = _tmode; _tmode = value; tmode_changed = true; } } } public override void OnStart(PartModule.StartState state) { pid = new PIDController(0.05, 0.000001, 0.05); users.Add(this); base.OnStart(state); } public void ThrustOff() { targetThrottle = 0; vessel.ctrlState.mainThrottle = 0; tmode = TMode.OFF; if (vessel == FlightGlobals.ActiveVessel) { FlightInputHandler.state.mainThrottle = 0; //so that the on-screen throttle gauge reflects the autopilot throttle } } // Call this function to set the throttle for a burn with dV delta-V remaining. // timeConstant controls how quickly we throttle down toward the end of the burn. // This function is nice because it will correctly handle engine spool-up/down times. public void ThrustForDV(double dV, double timeConstant) { timeConstant += vesselState.maxEngineResponseTime; double spooldownDV = vesselState.currentThrustAccel * vesselState.maxEngineResponseTime; double desiredAcceleration = (dV - spooldownDV) / timeConstant; targetThrottle = Mathf.Clamp01((float)(desiredAcceleration / vesselState.maxThrustAccel)); } public override void Drive(FlightCtrlState s) { float threshold = 0.1F; bool _userCommandingRotation = !(Mathfx.Approx(s.pitch, s.pitchTrim, threshold) && Mathfx.Approx(s.yaw, s.yawTrim, threshold) && Mathfx.Approx(s.roll, s.rollTrim, threshold)); bool _userCommandingTranslation = !(Math.Abs(s.X) < threshold && Math.Abs(s.Y) < threshold && Math.Abs(s.Z) < threshold); if (_userCommandingRotation && !_userCommandingTranslation) { userCommandingRotationSmoothed = 2; } else if (userCommandingRotationSmoothed > 0) { userCommandingRotationSmoothed--; } if (core.GetComputerModule<MechJebModuleThrustWindow>().hidden && core.GetComputerModule<MechJebModuleAscentGuidance>().hidden) { return; } if ((tmode != TMode.OFF) && (vesselState.thrustAvailable > 0)) { double spd = 0; switch (tmode) { case TMode.KEEP_ORBITAL: spd = vesselState.speedOrbital; break; case TMode.KEEP_SURFACE: spd = vesselState.speedSurface; break; case TMode.KEEP_VERTICAL: spd = vesselState.speedVertical; Vector3d rot = Vector3d.up; if (trans_kill_h) { Vector3 hsdir = Vector3.ProjectOnPlane(vesselState.surfaceVelocity, vesselState.up); Vector3 dir = -hsdir + vesselState.up * Math.Max(Math.Abs(spd), 20 * mainBody.GeeASL); if ((Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) > 5000) && (hsdir.magnitude > Math.Max(Math.Abs(spd), 100 * mainBody.GeeASL) * 2)) { tmode = TMode.DIRECT; trans_spd_act = 100; rot = -hsdir; } else { rot = dir.normalized; } core.attitude.attitudeTo(rot, AttitudeReference.INERTIAL, null); } break; } double t_err = (trans_spd_act - spd) / vesselState.maxThrustAccel; if ((tmode == TMode.KEEP_ORBITAL && Vector3d.Dot(vesselState.forward, vesselState.orbitalVelocity) < 0) || (tmode == TMode.KEEP_SURFACE && Vector3d.Dot(vesselState.forward, vesselState.surfaceVelocity) < 0)) { //allow thrust to declerate t_err *= -1; } double t_act = pid.Compute(t_err); if ((tmode != TMode.KEEP_VERTICAL) || !trans_kill_h || (core.attitude.attitudeError < 2) || ((Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) < 1000) && (core.attitude.attitudeError < 90))) { if (tmode == TMode.DIRECT) { trans_prev_thrust = targetThrottle = trans_spd_act / 100.0F; } else { trans_prev_thrust = targetThrottle = Mathf.Clamp01(trans_prev_thrust + (float)t_act); } } else { bool useGimbal = (vesselState.torqueFromEngine.x > vesselState.torqueAvailable.x * 10) || (vesselState.torqueFromEngine.z > vesselState.torqueAvailable.z * 10); bool useDiffThrottle = (vesselState.torqueFromDiffThrottle.x > vesselState.torqueAvailable.x * 10) || (vesselState.torqueFromDiffThrottle.z > vesselState.torqueAvailable.z * 10); if ((core.attitude.attitudeError >= 2) && (useGimbal || (useDiffThrottle && core.thrust.differentialThrottle))) { trans_prev_thrust = targetThrottle = 0.1F; } else { trans_prev_thrust = targetThrottle = 0; } } } // Only set throttle if a module need it. Othewise let the user or other mods set it // There is always at least 1 user : the module itself (why ?) if (users.Count() > 1) s.mainThrottle = targetThrottle; float throttleLimit = 1; limiter = LimitMode.None; if (limitThrottle) { if (maxThrottle < throttleLimit) limiter = LimitMode.Throttle; throttleLimit = Mathf.Min(throttleLimit, (float)maxThrottle); } if (limitToTerminalVelocity) { float limit = TerminalVelocityThrottle(); if (limit < throttleLimit) limiter = LimitMode.TerminalVelocity; throttleLimit = Mathf.Min(throttleLimit, limit); } if (limitToPreventOverheats) { float limit = (float)TemperatureSafetyThrottle(); if(limit < throttleLimit) limiter = LimitMode.Temperature; throttleLimit = Mathf.Min(throttleLimit, limit); } if (limitAcceleration) { float limit = AccelerationLimitedThrottle(); if(limit < throttleLimit) limiter = LimitMode.Acceleration; throttleLimit = Mathf.Min(throttleLimit, limit); } if (limitToPreventFlameout) { // This clause benefits being last: if we don't need much air // due to prior limits, we can close some intakes. float limit = FlameoutSafetyThrottle(); if (limit < throttleLimit) limiter = LimitMode.Flameout; throttleLimit = Mathf.Min(throttleLimit, limit); } if (double.IsNaN(throttleLimit)) throttleLimit = 0; throttleLimit = Mathf.Clamp01(throttleLimit); vesselState.throttleLimit = throttleLimit; if (s.mainThrottle < throttleLimit) limiter = LimitMode.None; s.mainThrottle = Mathf.Min(s.mainThrottle, throttleLimit); if (smoothThrottle) { s.mainThrottle = SmoothThrottle(s.mainThrottle); } if (double.IsNaN(s.mainThrottle)) s.mainThrottle = 0; s.mainThrottle = Mathf.Clamp01(s.mainThrottle); if (s.Z == 0 && core.rcs.rcsThrottle && vesselState.rcsThrust) s.Z = -s.mainThrottle; lastThrottle = s.mainThrottle; if (!core.attitude.enabled) { Vector3d act = new Vector3d(s.pitch, s.yaw, s.roll); differentialThrottleDemandedTorque = -Vector3d.Scale(act.xzy, vesselState.torqueFromDiffThrottle * s.mainThrottle * 0.5f); } } public override void OnFixedUpdate() { if (differentialThrottle) { differentialThrottleSuccess = ComputeDifferentialThrottle(differentialThrottleDemandedTorque); } else { differentialThrottleSuccess = false; } } //A throttle setting that throttles down when the vertical velocity of the ship exceeds terminal velocity float TerminalVelocityThrottle() { if (vesselState.altitudeASL > mainBody.RealMaxAtmosphereAltitude()) return 1.0F; double velocityRatio = Vector3d.Dot(vesselState.surfaceVelocity, vesselState.up) / vesselState.TerminalVelocity(); if (velocityRatio < 1.0) return 1.0F; //full throttle if under terminal velocity //throttle down quickly as we exceed terminal velocity: const double falloff = 15.0; return Mathf.Clamp((float)(1.0 - falloff * (velocityRatio - 1.0)), 0.0F, 1.0F); } //a throttle setting that throttles down if something is close to overheating double TemperatureSafetyThrottle() { double maxTempRatio = vessel.parts.Max(p => p.temperature / p.maxTemp); //reduce throttle as the max temp. ratio approaches 1 within the safety margin const double tempSafetyMargin = 0.05f; if (maxTempRatio < 1 - tempSafetyMargin) return 1.0F; else return (1 - maxTempRatio) / tempSafetyMargin; } float SmoothThrottle(float mainThrottle) { return Mathf.Clamp(mainThrottle, (float)(lastThrottle - vesselState.deltaT / throttleSmoothingTime), (float)(lastThrottle + vesselState.deltaT / throttleSmoothingTime)); } float FlameoutSafetyThrottle() { float throttle = 1; // For every resource that is provided by intakes, find how // much we need at full throttle, add a safety margin, and // that's the max throttle for that resource. Take the min of // the max throttles. foreach (var resource in vesselState.resources.Values) { if (resource.intakes.Length == 0) { // No intakes provide this resource; not our problem. continue; } // Compute the amount of air we will need, plus a safety // margin. Make sure it's at least enough for last frame's // requirement, since it takes time for engines to spin down. // Note: this could be zero, e.g. if we have intakes but no // jets. double margin = (1 + 0.01 * flameoutSafetyPct); double safeRequirement = margin * resource.requiredAtMaxThrottle; safeRequirement = Math.Max(safeRequirement, resource.required); // Open the right number of intakes. if (manageIntakes) { OptimizeIntakes(resource, safeRequirement); } double provided = resource.intakeProvided; if (resource.required >= provided) { // We must cut throttle immediately, otherwise we are // flaming out immediately. Continue doing the rest of the // loop anyway, but we'll be at zero throttle. throttle = 0; } else { double maxthrottle = provided / safeRequirement; throttle = Mathf.Min(throttle, (float)maxthrottle); } } return throttle; } // Open and close intakes so that they provide the required flow but no // more. void OptimizeIntakes(VesselState.ResourceInfo info, double requiredFlow) { // The highly imperfect algorithm here is: // - group intakes by symmetry // - sort the groups by their size // - open a group at a time until we have enough airflow // - close the remaining groups // TODO: improve the algorithm: // 1. Take cost-benefit into account. We want to open ram intakes // before any others, and we probably never want to open // nacelles. We need more info to know how much thrust we lose // for losing airflow, versus how much drag we gain for opening // an intake. // 2. Take the center of drag into account. We don't need to open // symmetry groups all at once; we just need the center of drag // to be in a good place. Symmetry in the SPH also doesn't // guarantee anything; we could be opening all pairs that are // above the plane through the center of mass and none below, // which makes control harder. // Even just point (1) means we want to solve knapsack. // Group intakes by symmetry, and collect the information by intake. var groups = new List<List<ModuleResourceIntake>>(); var groupIds = new Dictionary<ModuleResourceIntake, int>(); var data = new Dictionary<ModuleResourceIntake, VesselState.ResourceInfo.IntakeData>(); foreach (var intakeData in info.intakes) { ModuleResourceIntake intake = intakeData.intake; data[intake] = intakeData; if (groupIds.ContainsKey(intake)) { continue; } // Create a group for this symmetry int grpId = groups.Count; var intakes = new List<ModuleResourceIntake>(); groups.Add(intakes); // In DFS order, get all the symmetric parts. // We can't rely on symmetryCounterparts; see bug #52 by tavert: // https://github.com/MuMech/MechJeb2/issues/52 var stack = new Stack<Part>(); stack.Push(intake.part); while(stack.Count > 0) { var part = stack.Pop(); var partIntake = part.Modules.OfType<ModuleResourceIntake>().FirstOrDefault(); if (partIntake == null || groupIds.ContainsKey(partIntake)) { continue; } groupIds[partIntake] = grpId; intakes.Add(partIntake); for (int i = 0; i < part.symmetryCounterparts.Count; i++) { var sympart = part.symmetryCounterparts[i]; stack.Push(sympart); } } } // For each group in sorted order, if we need more air, open any // closed intakes. If we have enough air, close any open intakes. // OrderBy is stable, so we'll always be opening the same intakes. double airFlowSoFar = 0; KSPActionParam param = new KSPActionParam(KSPActionGroup.None, KSPActionType.Activate); foreach (var grp in groups.OrderBy(grp => grp.Count)) { if (airFlowSoFar < requiredFlow) { for (int i = 0; i < grp.Count; i++) { var intake = grp[i]; double airFlowThisIntake = data[intake].predictedMassFlow; if (!intake.intakeEnabled) { intake.ToggleAction(param); } airFlowSoFar += airFlowThisIntake; } } else { for (int j = 0; j < grp.Count; j++) { var intake = grp[j]; if (intake.intakeEnabled) { intake.ToggleAction(param); } } } } } //The throttle setting that will give an acceleration of maxAcceleration float AccelerationLimitedThrottle() { double throttleForMaxAccel = (maxAcceleration - vesselState.minThrustAccel) / (vesselState.maxThrustAccel - vesselState.minThrustAccel); return Mathf.Clamp((float)throttleForMaxAccel, 0, 1); } public override void OnUpdate() { if (core.GetComputerModule<MechJebModuleThrustWindow>().hidden && core.GetComputerModule<MechJebModuleAscentGuidance>().hidden) { return; } if (tmode_changed) { if (trans_kill_h && (tmode == TMode.OFF)) { core.attitude.attitudeDeactivate(); } pid.Reset(); tmode_changed = false; FlightInputHandler.SetNeutralControls(); } bool disableThrusters = (userCommandingRotation && !core.rcs.rcsForRotation); if (disableThrusters != lastDisableThrusters) { lastDisableThrusters = disableThrusters; var rcsModules = vessel.FindPartModulesImplementing<ModuleRCS>(); foreach (var pm in rcsModules) { if (disableThrusters) { pm.Disable(); } else { pm.Enable(); } } } } #warning from here remove all the EngineWrapper stuff and move the useful stuff to VesselState.EngineInfo static void MaxThrust(double[] x, ref double func, double[] grad, object obj) { List<EngineWrapper> el = (List<EngineWrapper>)obj; func = 0; for (int i = 0, j = 0; j < el.Count; j++) { EngineWrapper e = el[j]; if (!e.engine.throttleLocked) { func -= el[j].maxVariableForce.y * x[i]; grad[i] = -el[j].maxVariableForce.y; i++; } } } public bool ComputeDifferentialThrottle(Vector3d torque) { List<EngineWrapper> engines = new List<EngineWrapper>(); for (int i = 0; i < vessel.parts.Count; i++) { Part p = vessel.parts[i]; for (int j = 0; j < p.Modules.Count; j++) { PartModule pm = p.Modules[j]; if (pm is ModuleEngines) { ModuleEngines e = (ModuleEngines)pm; EngineWrapper engine = new EngineWrapper(e); if (e.EngineIgnited && !e.flameout && e.enabled) { engine.UpdateForceAndTorque(vesselState.CoM); engines.Add(engine); } } } } int n = engines.Count(eng => !eng.engine.throttleLocked); if (n < 3) { for (int i = 0; i < engines.Count; i++) { EngineWrapper e = engines[i]; e.thrustRatio = 1; } return false; } double[,] C = new double[2+2*n,n+1]; int[] CT = new int[2+2*n]; float mainThrottle = vessel.ctrlState.mainThrottle; // FIXME: the solver will throw an exception if the commanded torque is not realisable, // clamp the commanded torque to half the possible torque for now if (double.IsNaN(vesselState.torqueFromDiffThrottle.x)) vesselState.torqueFromDiffThrottle.x = 0; if (double.IsNaN(vesselState.torqueFromDiffThrottle.z)) vesselState.torqueFromDiffThrottle.z = 0; C[0, n] = Mathf.Clamp((float)torque.x, -(float)vesselState.torqueFromDiffThrottle.x * mainThrottle / 2, (float)vesselState.torqueFromDiffThrottle.x * mainThrottle / 2); C[1, n] = Mathf.Clamp((float)torque.z, -(float)vesselState.torqueFromDiffThrottle.z * mainThrottle / 2, (float)vesselState.torqueFromDiffThrottle.z * mainThrottle / 2); for (int i = 0, j = 0; j < engines.Count; j++) { var e = engines[j]; C[0,n] -= e.constantTorque.x; C[1,n] -= e.constantTorque.z; if (!e.engine.throttleLocked) { C[0,i] = e.maxVariableTorque.x; //C[1,j] = e.maxVariableTorque.y; C[1,i] = e.maxVariableTorque.z; C[2+2*i,i] = 1; C[2+2*i,n] = 1; CT[2+2*i] = -1; C[3+2*i,i] = 1; C[3+2*i,n] = 0; CT[3+2*i] = 1; i++; } } double[] w = new double[0]; double[,] u = new double[0,0]; double[,] vt = new double[0,0]; alglib.svd.rmatrixsvd(C, 2, n, 0, 0, 2, ref w, ref u, ref vt); if (w[0] >= 10 * w[1]) { for (int i = 0; i < engines.Count; i++) { EngineWrapper e = engines[i]; e.thrustRatio = 1; } return false; } // Multiply by mainThrottle later to compute the singular value decomposition correctly for (int i = 0; i < n; i++) { C[0,i] *= mainThrottle; C[1,i] *= mainThrottle; } double[] x = new double[n]; alglib.minbleicstate state; alglib.minbleicreport rep; try { alglib.minbleiccreate(x, out state); alglib.minbleicsetlc(state, C, CT); alglib.minbleicoptimize(state, MaxThrust, null, engines); alglib.minbleicresults(state, out x, out rep); } catch { return false; } if (x.Any(val => double.IsNaN(val))) return false; for (int i = 0, j = 0; j < engines.Count; j++) { if (!engines[j].engine.throttleLocked) { engines[j].thrustRatio = (float)x[i]; i++; } } return true; } public void DisableDifferentialThrottle() { for (int i = 0; i < vessel.parts.Count; i++) { Part p = vessel.parts[i]; for (int j = 0; j < p.Modules.Count; j++) { PartModule pm = p.Modules[j]; if (pm is ModuleEngines) { ModuleEngines e = (ModuleEngines)pm; EngineWrapper engine = new EngineWrapper(e); engine.thrustRatio = 1; } } } } } }
r3g1str0s/MechJeb2-en-Castellano
MechJeb2/MechJebModuleThrustController.cs
C#
gpl-3.0
31,601
using HoloToolkit; using HoloToolkit.Unity; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Keeps track of the current state of the experience. /// </summary> public class AppStateManager : Singleton<AppStateManager> { /// <summary> /// Enum to track progress through the experience. /// </summary> public enum AppState { WaitingForAnchor = 0, WaitingForStageTransform, Ready } /// <summary> /// Tracks the current state in the experience. /// </summary> public AppState CurrentAppState { get; set; } void Start() { CurrentAppState = AppState.WaitingForAnchor; } void Update() { switch (CurrentAppState) { case AppState.WaitingForAnchor: if (ImportExportAnchorManager.Instance.AnchorEstablished) { CurrentAppState = AppState.WaitingForStageTransform; //GestureManager.Instance.OverrideFocusedObject = HologramPlacement.Instance.gameObject; } break; case AppState.WaitingForStageTransform: // Now if we have the stage transform we are ready to go. if (HologramPlacement.Instance.GotTransform) { CurrentAppState = AppState.Ready; GestureManager.Instance.OverrideFocusedObject = null; } break; } } }
cefoot/HoloDice
Assets/Scripts/AppStateManager.cs
C#
gpl-3.0
1,520
package org.otherobjects.cms.model; import java.io.Serializable; import java.util.List; import org.otherobjects.cms.types.TypeDef; @SuppressWarnings("serial") public abstract class Folder extends BaseNode implements Serializable { public abstract String getLabel(); public abstract void setLabel(String label); abstract List<?> getAllowedTypes(); abstract void setAllowedTypes(List<String> allowedTypes); abstract List<TypeDef> getAllAllowedTypes(); abstract String getCssClass(); abstract void setCssClass(String cssClass); }
0x006EA1E5/oo6
src/main/java/org/otherobjects/cms/model/Folder.java
Java
gpl-3.0
564
#include "Utility.hpp" std::string prefix; time_t rawtime ; std::string return_file_name(const std::string file_name) { std::string result_file_name; if(prefix.length()>0) result_file_name=prefix+"."+file_name; else result_file_name=file_name; return result_file_name; } void delete_created_file(const std::string file_name) { if( remove( file_name.c_str() ) != 0 ) std::cerr<<"--- error deleting the file. "<<file_name<<std::endl; }
SaraEl-Metwally/LightAssembler
Utility.cpp
C++
gpl-3.0
503
#!/usr/bin/env python # Copyright (C) 2014-2017 Shea G Craig # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """misc_endpoints.py Classes representing API endpoints that don't subclass JSSObject """ from __future__ import print_function from __future__ import absolute_import import mimetypes import os import sys from xml.etree import ElementTree from .exceptions import MethodNotAllowedError, PostError from .tools import error_handler __all__ = ('CommandFlush', 'FileUpload', 'LogFlush') # Map Python 2 basestring type for Python 3. if sys.version_info.major == 3: basestring = str # pylint: disable=missing-docstring # pylint: disable=too-few-public-methods class CommandFlush(object): _endpoint_path = "commandflush" can_get = False can_put = False can_post = False def __init__(self, jss): """Initialize a new CommandFlush Args: jss: JSS object. """ self.jss = jss @property def url(self): """Return the path subcomponent of the url to this object.""" return self._endpoint_path def command_flush_with_xml(self, data): """Flush commands for devices with a supplied xml string. From the Casper API docs: Status and devices specified in an XML file. Id lists may be specified for <computers>, <computer_groups>, <mobile_devices>, <mobile_device_groups>. Sample file: <commandflush> <status>Pending+Failed</status> <mobile_devices> <mobile_device> <id>1</id> </mobile_device> <mobile_device> <id>2</id> </mobile_device> </mobile_devices> </commandflush> Args: data (string): XML string following the above structure or an ElementTree/Element. Raises: DeleteError if provided url_path has a >= 400 response. """ if not isinstance(data, basestring): data = ElementTree.tostring(data, encoding='UTF-8') self.jss.delete(self.url, data) def command_flush_for(self, id_type, command_id, status): """Flush commands for an individual device. Args: id_type (str): One of 'computers', 'computergroups', 'mobiledevices', or 'mobiledevicegroups'. id_value (str, int, list): ID value(s) for the devices to flush. More than one device should be passed as IDs in a list or tuple. status (str): One of 'Pending', 'Failed', 'Pending+Failed'. Raises: DeleteError if provided url_path has a >= 400 response. """ id_types = ('computers', 'computergroups', 'mobiledevices', 'mobiledevicegroups') status_types = ('Pending', 'Failed', 'Pending+Failed') if id_type not in id_types or status not in status_types: raise ValueError("Invalid arguments.") if isinstance(command_id, list): command_id = ",".join(str(item) for item in command_id) flush_url = "{}/{}/id/{}/status/{}".format( self.url, id_type, command_id, status) self.jss.delete(flush_url) # pylint: disable=too-few-public-methods class FileUpload(object): """FileUploads are a special case in the API. They allow you to add file resources to a number of objects on the JSS. To use, instantiate a new FileUpload object, then use the save() method to upload. Once the upload has been posted you may only interact with it through the web interface. You cannot list/get it or delete it through the API. However, you can reuse the FileUpload object if you wish, by changing the parameters, and issuing another save(). """ _endpoint_path = "fileuploads" allowed_kwargs = ('subset',) def __init__(self, j, resource_type, id_type, _id, resource): """Prepare a new FileUpload. Args: j: A JSS object to POST the upload to. resource_type: String. Acceptable Values: Attachments: computers mobiledevices enrollmentprofiles peripherals mobiledeviceenrollmentprofiles Icons: policies ebooks mobiledeviceapplicationsicon Mobile Device Application: mobiledeviceapplicationsipa Disk Encryption diskencryptionconfigurations diskencryptions (synonymous) PPD printers id_type: String of desired ID type: id name _id: Int or String referencing the identity value of the resource to add the FileUpload to. resource: String path to the file to upload. """ resource_types = ["computers", "mobiledevices", "enrollmentprofiles", "peripherals", "mobiledeviceenrollmentprofiles", "policies", "ebooks", "mobiledeviceapplicationsicon", "mobiledeviceapplicationsipa", "diskencryptionconfigurations", "printers"] id_types = ["id", "name"] self.jss = j # Do some basic error checking on parameters. if resource_type in resource_types: self.resource_type = resource_type else: raise TypeError( "resource_type must be one of: %s" % ', '.join(resource_types)) if id_type in id_types: self.id_type = id_type else: raise TypeError("id_type must be one of: %s" % ', '.join(id_types)) self._id = str(_id) basename = os.path.basename(resource) content_type = mimetypes.guess_type(basename)[0] self.resource = {"name": (basename, open(resource, "rb"), content_type)} self._set_upload_url() def _set_upload_url(self): """Generate the full URL for a POST.""" # pylint: disable=protected-access self._upload_url = "/".join([ self.jss._url, self._endpoint_path, self.resource_type, self.id_type, str(self._id)]) # pylint: enable=protected-access def save(self): """POST the object to the JSS.""" try: response = self.jss.session.post( self._upload_url, files=self.resource) except PostError as error: if error.status_code == 409: raise PostError(error) else: raise MethodNotAllowedError(self.__class__.__name__) if response.status_code == 201: if self.jss.verbose: print("POST: Success") print(response.content) elif response.status_code >= 400: error_handler(PostError, response) class LogFlush(object): _endpoint_path = "logflush" def __init__(self, jss): """Initialize a new LogFlush Args: jss: JSS object. """ self.jss = jss @property def url(self): """Return the path subcomponent of the url to this object.""" return self._endpoint_path def log_flush_with_xml(self, data): """Flush logs for devices with a supplied xml string. From the Casper API docs: log, log_id, interval, and devices specified in an XML file. Sample file: <logflush> <log>policy</log> <log_id>2</log_id> <interval>THREE MONTHS</interval> <computers> <computer> <id>1</id> </computer> <computer> <id>2</id> </computer> </computers> </logflush> Args: data (string): XML string following the above structure or an ElementTree/Element. Elements: logflush (root) log (Unknown; "policy" is the only one listed in docs). log_id: Log ID value. interval: Combination of "Zero", "One", "Two", "Three", "Six", and "Day", "Week", "Month", "Year". e.g. ("Three+Months") Please note: The documentation for this specifies the singular form (e.g. "Month"), and plural ("Months") at different times, and further the construction is listed as "THREE MONTHS" elsewhere. Limited testing indicates that pluralization does not matter, nor does capitalization. The "+" seems optional as well. Please test! Device Arrays: Again, acceptable values are not listed in the docs, aside from the example ("computers"). Presumably "mobiledevices", and possibly "computergroups" and "mobiledevicegroups" work. Raises: DeleteError if provided url_path has a >= 400 response. """ if not isinstance(data, basestring): data = ElementTree.tostring(data, encoding='UTF-8') self.jss.delete(self.url, data) def log_flush_for_interval(self, log_type, interval): """Flush logs for an interval of time. Args: log_type (str): Only documented type is "policies". This will be applied by default if nothing is passed. interval (str): Combination of "Zero", "One", "Two", "Three", "Six", and "Day", "Week", "Month", "Year". e.g. ("Three+Months") Please note: The documentation for this specifies the singular form (e.g. "Month"), and plural ("Months") at different times, and further the construction is listed as "THREE MONTHS" elsewhere. Limited testing indicates that pluralization does not matter, nor does capitalization. Please test! No validation is performed on this prior to the request being made. Raises: DeleteError if provided url_path has a >= 400 response. """ if not log_type: log_type = "policies" # The XML for the /logflush basic endpoint allows spaces # instead of "+", so do a replace here just in case. interval = interval.replace(" ", "+") flush_url = "{}/{}/interval/{}".format( self.url, log_type, interval) self.jss.delete(flush_url) def log_flush_for_obj_for_interval(self, log_type, obj_id, interval): """Flush logs for an interval of time for a specific object. Please note, log_type is a variable according to the API docs, but acceptable values are not listed. Only "policies" is demonstrated as an acceptable value. Args: log_type (str): Only documented type is "policies". This will be applied by default if nothing is passed. obj_id (str or int): ID of the object to have logs flushed. interval (str): Combination of "Zero", "One", "Two", "Three", "Six", and "Day", "Week", "Month", "Year". e.g. ("Three+Months") Please note: The documentation for this specifies the singular form (e.g. "Month"), and plural ("Months") at different times, and further the construction is listed as "THREE MONTHS" elsewhere. Limited testing indicates that pluralization does not matter, nor does capitalization. Please test! No validation is performed on this prior to the request being made. Raises: DeleteError if provided url_path has a >= 400 response. """ if not log_type: log_type = "policies" # The XML for the /logflush basic endpoint allows spaces # instead of "+", so do a replace here just in case. interval = interval.replace(" ", "+") flush_url = "{}/{}/id/{}/interval/{}".format( self.url, log_type, obj_id, interval) self.jss.delete(flush_url) # pylint: enable=missing-docstring # pylint: enable=too-few-public-methods
sheagcraig/python-jss
jss/misc_endpoints.py
Python
gpl-3.0
13,525
<?php /* * This file is part of Phraseanet * * (c) 2005-2015 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Alchemy\Phrasea\Core\Event\Subscriber; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Controller\Api\Result; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; class ApiExceptionHandlerSubscriber implements EventSubscriberInterface { private $app; public function __construct(Application $app) { $this->app = $app; } public static function getSubscribedEvents() { return [ KernelEvents::EXCEPTION => ['onSilexError', 0], ]; } public function onSilexError(GetResponseForExceptionEvent $event) { $headers = []; $e = $event->getException(); if ($e instanceof MethodNotAllowedHttpException) { $code = 405; } elseif ($e instanceof BadRequestHttpException) { $code = 400; } elseif ($e instanceof AccessDeniedHttpException) { $code = 403; } elseif ($e instanceof UnauthorizedHttpException) { $code = 401; } elseif ($e instanceof NotFoundHttpException) { $code = 404; } elseif ($e instanceof HttpExceptionInterface) { if (in_array($e->getStatusCode(), [400, 401, 403, 404, 405, 406, 503])) { $code = $e->getStatusCode(); } else { $code = 500; } } else { $code = 500; } if ($e instanceof HttpExceptionInterface) { $headers = $e->getHeaders(); } $response = Result::createError($event->getRequest(), $code, $e->getMessage())->createResponse(); $response->headers->set('X-Status-Code', $response->getStatusCode()); foreach ($headers as $key => $value) { $response->headers->set($key, $value); } $event->setResponse($response); } }
kwemi/Phraseanet
lib/Alchemy/Phrasea/Core/Event/Subscriber/ApiExceptionHandlerSubscriber.php
PHP
gpl-3.0
2,574
package com.osrs.suite.cache; /** * Created by Allen Kinzalow on 3/16/2015. */ public interface TextureImage { int method21(int var1, int var2); boolean method23(int var1, int var2); boolean method24(int var1, int var2); int[] getTexturePixels(int var1, int var2); }
kinztechcom/OS-Cache-Suite
src/com/osrs/suite/cache/TextureImage.java
Java
gpl-3.0
289
#include "MemTable.h" using namespace std; json MemTable::Table; template <class type> LinkedList<type> ListAdapter<type>::SmartList; int MemTable::getSize(long ID) { int size = 0; std::string number; std::stringstream strstream; strstream << ID; strstream >> number; for (json::iterator it = Table.begin(); it != Table.end(); ++it){ std::string Key = it.key(); if(number == Key){ size = it.value().at(1); break; } } return size; } void *MemTable::getPosition(long ID) { void* ptr = nullptr; std::string number; std::stringstream strstream; strstream << ID; strstream >> number; for (json::iterator it = Table.begin(); it != Table.end(); ++it){ std::string Key = it.key(); if(number == Key){ intptr_t pointer = it.value().at(0); ptr = reinterpret_cast<void*>(pointer); break; } } return ptr; } void *MemTable::burp(void * destination, void * source, size_t objectSize, std::string ID) { memcpy(destination, source, objectSize); memset(source, 0, objectSize); BurpingTable.erase(ID); intptr_t newPointer = (intptr_t) destination; BurpingTable[ID] = {newPointer, objectSize}; void * finalPointer = destination + objectSize; return finalPointer; } void MemTable::deleteFromTable(long ID) { void * voidPointer= getPosition(ID); size_t pointerSize = (size_t) getSize(ID); Manager.FreeMem(voidPointer, pointerSize); std::string number; std::stringstream strstream; strstream << ID; strstream >> number; Table.erase(number); void * iterPointer = voidPointer; BurpingTable = Table; for (json::iterator it = Table.begin(); it != Table.end(); ++it) { std::string key = it.key(); size_t tempObjSize = (size_t) it.value().at(1); intptr_t tempPointer = it.value().at(0); void * burpPointer = reinterpret_cast<void*>(tempPointer); if (voidPointer < burpPointer == 1){ void * newObjectPointer = burp(iterPointer, burpPointer, tempObjSize, key); iterPointer = newObjectPointer; } } Manager.setCurrentMem(iterPointer); Table = BurpingTable; BurpingTable.clear(); std::cout << "ID: [pointer address, memory size]" << std::endl; std::cout << Table <<"\n"<< std::endl; }
BlindHouse/xMemory
xMemoryManager/MemTable.cpp
C++
gpl-3.0
2,423
#!/usr/bin/env python """ Copyright (C) 2015 Louis Dijkstra This file is part of error-model-aligner This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from __future__ import print_function, division from optparse import OptionParser import os import sys from scipy.stats import norm import numpy as np from scipy.optimize import minimize import math __author__ = "Louis Dijkstra" usage = """%prog [options] <.insert-sizes> <.insert-sizes> File containing the insert size observations when there is no indel Outputs the mean and standard deviation of the null model (i.e., a discrete approximation of a Normal distribution that does not allow for negative values) The file .insert-sizes must be orginazed in two columns (tab seperated): x_1 c_1 x_2 c_2 ... ... x_n c_n where x_1 is the minimal insert size observed x_n is the maximum value found. (Note: x_{i+1} = x_i + 1). c_i is the count for x_i. """ def normalizationFactor(mu, sigma): """Returns the normalization factor given mean mu and STD sigma""" return 1.0 / (1.0 - norm.cdf((-mu - 0.5)/sigma)) def f(isize, mu, sigma): p = norm.cdf((isize + 0.5 - mu)/sigma) - norm.cdf((isize - 0.5 - mu)/sigma) if p < sys.float_info.min: return sys.float_info.min return p def loglikelihood(mu, sigma, isizes, counts, n): """Returns the loglikelihood of mu and sigma given the data (isizes, counts and n)""" l = n * math.log(normalizationFactor(mu, sigma)) for isize, count in zip(isizes, counts): l += count * math.log(f(isize, mu, sigma)) return l def aux_loglikelihood(var, isizes, counts, n): mu = var[0] sigma = var[1] return -1.0 * loglikelihood(mu, sigma, isizes, counts, n) def main(): parser = OptionParser(usage=usage) parser.add_option("-f", action="store", dest="maxfun", default=1000, type=int, help="Maximum number of function evaluations (Default = 1000) ") parser.add_option("-i", action="store", dest="maxiter", default=100, type=int, help="Maximum number of iterations (Default = 100) ") parser.add_option("-m", action="store", dest="mu_init", default=100.0, type=float, help="Initial guess for the mean (mu). (Default is 100) ") parser.add_option("-s", action="store", dest="sigma_init", default=10.0, type=float, help="Initial guess for the standard deviation (sigma). (Default is 10) ") parser.add_option("-v", action="store_true", dest="verbose", default=False, help="Verbose. Output of the optimizer is printed. ") (options, args) = parser.parse_args() if (len(args)!=1): parser.print_help() return 1 isizes = [] # insert sizes that were observed counts = [] # number of times these insert sizes were observed for line in open(args[0], 'r'): values = map(int, line.split()) isizes.append(values[0]) counts.append(values[1]) isizes = np.array(isizes) counts = np.array(counts) n = np.sum(counts) res = minimize ( aux_loglikelihood, [options.mu_init, options.sigma_init], args=[isizes, counts, n], method="L-BFGS-B", bounds=[(0, None), (0, None)], options={'disp': options.verbose, 'maxfun': options.maxfun, 'maxiter': options.maxiter}) print("\n*** RESULTS ***\n") print("estimated mean: %lf\t estimated STD: %lf\n"%(res.x[0], res.x[1])) print(res.message) if __name__ == '__main__': sys.exit(main())
louisdijkstra/error-model-aligner
bin/estimate-null-insert-sizes.py
Python
gpl-3.0
3,976
/* Copyright(c) 2014 Hashmi1 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Utility; namespace TES5.NPC { class ACBS : Field { enum FLAGS : uint { Female = 0x01, Essential = 0x02, Is_CharGen_Face_Preset = 0x04, Respawn = 0x08, Auto_calc_stats = 0x10, Unique = 0x20, Doesnt_affect_stealth_meter = 0x40, PC_Level_Mult = 0x80, Audio_template = 0x100, Protected = 0x800, Summonable = 0x4000, Doesnt_Bleed = 0x10000, Owned = 0x40000, Opposite_Gender_Anims = 0x80000, Simple_Actor = 0x100000, looped_script = 0x200000, looped_audio = 0x10000000, Ghost = 0x20000000, Invulnerable = 0x80000000, } Field base_field; public bool isPreset { get { return BinaryFlag.isSet(flags, (uint)FLAGS.Is_CharGen_Face_Preset); } set { if (value == true) { flags = BinaryFlag.set(flags, (uint)FLAGS.Is_CharGen_Face_Preset); } else { flags = BinaryFlag.remove(flags, (uint)FLAGS.Is_CharGen_Face_Preset); } } } //////////////////////////////////////////////////////////// // Field Data /////////////////////////////////////////////////////////// public UInt32 flags; public UInt16 Magicka_Offset; public UInt16 Stamina_Offset; public UInt16 Level; public UInt16 Calc_min_level; public UInt16 Calc_max_level; public UInt16 Speed_Multiplier; public UInt16 Disposition_Base; public UInt16 Template_Data_Flag; public UInt16 Health_Offset; public UInt16 Bleedout_Override; /////////////////////////////////////////////////////////// public void flush() { MemoryStream mstream = new MemoryStream(); BinaryWriter bw = new BinaryWriter(mstream); bw.Write((UInt32)flags); bw.Write((UInt16)Magicka_Offset); bw.Write((UInt16)Stamina_Offset); bw.Write((UInt16)Level); bw.Write((UInt16)Calc_min_level); bw.Write((UInt16)Calc_max_level); bw.Write((UInt16)Speed_Multiplier); bw.Write((UInt16)Disposition_Base); bw.Write((UInt16)Template_Data_Flag); bw.Write((UInt16)Health_Offset); bw.Write((UInt16)Bleedout_Override); base_field.replaceData(mstream.ToArray()); } public ACBS(Field f) { base_field = f; BinaryReader br = f.getData(); flags = br.ReadUInt32(); Magicka_Offset = br.ReadUInt16(); Stamina_Offset = br.ReadUInt16(); Level = br.ReadUInt16(); Calc_min_level = br.ReadUInt16(); Calc_max_level = br.ReadUInt16(); Speed_Multiplier = br.ReadUInt16(); Disposition_Base = br.ReadUInt16(); Template_Data_Flag = br.ReadUInt16(); Health_Offset = br.ReadUInt16(); Bleedout_Override = br.ReadUInt16(); } } }
Hashmi1/IndorilConverter
converter/converter/TES5/NPC/ACBS.cs
C#
gpl-3.0
3,874
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' /* brave ledger integration for the brave browser module entry points: init() - called by app/index.js to start module quit() - .. .. .. .. prior to browser quitting boot() - .. .. .. .. to create wallet IPC entry point: LEDGER_PUBLISHER - called synchronously by app/extensions/brave/content/scripts/pageInformation.js CHANGE_SETTING - called asynchronously to record a settings change eventStore entry point: addChangeListener - called when tabs render or gain focus */ const fs = require('fs') const path = require('path') const url = require('url') const util = require('util') const electron = require('electron') const app = electron.app const ipc = electron.ipcMain const session = electron.session const acorn = require('acorn') const ledgerBalance = require('ledger-balance') const ledgerClient = require('ledger-client') const ledgerGeoIP = require('ledger-geoip') const ledgerPublisher = require('ledger-publisher') const qr = require('qr-image') const random = require('random-lib') const tldjs = require('tldjs') const underscore = require('underscore') const uuid = require('node-uuid') const appActions = require('../js/actions/appActions') const appConstants = require('../js/constants/appConstants') const appDispatcher = require('../js/dispatcher/appDispatcher') const messages = require('../js/constants/messages') const settings = require('../js/constants/settings') const request = require('../js/lib/request') const getSetting = require('../js/settings').getSetting const locale = require('./locale') const appStore = require('../js/stores/appStore') const eventStore = require('../js/stores/eventStore') const rulesolver = require('./extensions/brave/content/scripts/pageInformation.js') const ledgerUtil = require('./common/lib/ledgerUtil') // TBD: remove these post beta [MTR] const logPath = 'ledger-log.json' const publisherPath = 'ledger-publisher.json' const scoresPath = 'ledger-scores.json' // TBD: move these to secureState post beta [MTR] const statePath = 'ledger-state.json' const synopsisPath = 'ledger-synopsis.json' /* * ledger globals */ var bootP = false var client const clientOptions = { debugP: process.env.LEDGER_DEBUG, loggingP: process.env.LEDGER_LOGGING, verboseP: process.env.LEDGER_VERBOSE } /* * publisher globals */ var synopsis var locations = {} var publishers = {} /* * utility globals */ const msecs = { year: 365 * 24 * 60 * 60 * 1000, week: 7 * 24 * 60 * 60 * 1000, day: 24 * 60 * 60 * 1000, hour: 60 * 60 * 1000, minute: 60 * 1000, second: 1000 } /* * notification state globals */ let addFundsMessage let reconciliationMessage let suppressNotifications = false let reconciliationNotificationShown = false let notificationTimeout = null // TODO(bridiver) - create a better way to get setting changes const doAction = (action) => { switch (action.actionType) { case appConstants.APP_CHANGE_SETTING: if (action.key === settings.PAYMENTS_ENABLED) return initialize(action.value) if (action.key === settings.PAYMENTS_CONTRIBUTION_AMOUNT) return setPaymentInfo(action.value) break case appConstants.APP_NETWORK_CONNECTED: setTimeout(networkConnected, 1 * msecs.second) break default: break } } /* * module entry points */ var init = () => { try { ledgerInfo._internal.debugP = ledgerClient.prototype.boolion(process.env.LEDGER_CLIENT_DEBUG) publisherInfo._internal.debugP = ledgerClient.prototype.boolion(process.env.LEDGER_PUBLISHER_DEBUG) publisherInfo._internal.verboseP = ledgerClient.prototype.boolion(process.env.LEDGER_PUBLISHER_VERBOSE) appDispatcher.register(doAction) initialize(getSetting(settings.PAYMENTS_ENABLED)) } catch (ex) { console.log('ledger.js initialization failed: ' + ex.toString() + '\n' + ex.stack) } } var quit = () => { visit('NOOP', underscore.now(), null) } var boot = () => { if ((bootP) || (client)) return bootP = true fs.access(pathName(statePath), fs.FF_OK, (err) => { if (!err) return if (err.code !== 'ENOENT') console.log('statePath read error: ' + err.toString()) ledgerInfo.creating = true appActions.updateLedgerInfo({ creating: true }) try { client = ledgerClient(null, underscore.extend({ roundtrip: roundtrip }, clientOptions), null) } catch (ex) { appActions.updateLedgerInfo({}) bootP = false return console.log('ledger client boot error: ' + ex.toString() + '\n' + ex.stack) } if (client.sync(callback) === true) run(random.randomInt({ min: msecs.minute, max: 10 * msecs.minute })) getBalance() bootP = false }) } /* * IPC entry point */ if (ipc) { ipc.on(messages.CHECK_BITCOIN_HANDLER, (event, partition) => { const protocolHandler = session.fromPartition(partition).protocol // TODO: https://github.com/brave/browser-laptop/issues/3625 if (typeof protocolHandler.isNavigatorProtocolHandled === 'function') { ledgerInfo.hasBitcoinHandler = protocolHandler.isNavigatorProtocolHandled('bitcoin') appActions.updateLedgerInfo(underscore.omit(ledgerInfo, [ '_internal' ])) } }) ipc.on(messages.LEDGER_PUBLISHER, (event, location) => { var ctx if ((!synopsis) || (event.sender.session === session.fromPartition('default')) || (!tldjs.isValid(location))) { event.returnValue = {} return } ctx = url.parse(location, true) ctx.TLD = tldjs.getPublicSuffix(ctx.host) if (!ctx.TLD) { if (publisherInfo._internal.verboseP) console.log('\nno TLD for:' + ctx.host) event.returnValue = {} return } ctx = underscore.mapObject(ctx, function (value, key) { if (!underscore.isFunction(value)) return value }) ctx.URL = location ctx.SLD = tldjs.getDomain(ctx.host) ctx.RLD = tldjs.getSubdomain(ctx.host) ctx.QLD = ctx.RLD ? underscore.last(ctx.RLD.split('.')) : '' event.returnValue = { context: ctx, rules: publisherInfo._internal.ruleset.cooked } }) ipc.on(messages.NOTIFICATION_RESPONSE, (e, message, buttonIndex) => { const win = electron.BrowserWindow.getFocusedWindow() if (message === addFundsMessage) { appActions.hideMessageBox(message) if (buttonIndex === 0) { // Don't show notifications for the next 6 hours. suppressNotifications = true setTimeout(() => { suppressNotifications = false }, 6 * msecs.hour) } else { // Open payments panel if (win) { win.webContents.send(messages.SHORTCUT_NEW_FRAME, 'about:preferences#payments', { singleFrame: true }) } } } else if (message === reconciliationMessage) { appActions.hideMessageBox(message) if (win) { win.webContents.send(messages.SHORTCUT_NEW_FRAME, 'about:preferences#payments', { singleFrame: true }) } // If > 24 hours has passed, it might be time to show the reconciliation // message again setTimeout(() => { reconciliationNotificationShown = false }, 1 * msecs.day) } }) ipc.on(messages.ADD_FUNDS_CLOSED, () => { if (balanceTimeoutId) clearTimeout(balanceTimeoutId) balanceTimeoutId = setTimeout(getBalance, 5 * msecs.second) }) } /* * eventStore entry point */ var fileTypes = { bmp: new Buffer([ 0x42, 0x4d ]), gif: new Buffer([ 0x47, 0x49, 0x46, 0x38, [0x37, 0x39], 0x61 ]), ico: new Buffer([ 0x00, 0x00, 0x01, 0x00 ]), jpeg: new Buffer([ 0xff, 0xd8, 0xff ]), png: new Buffer([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ]) } var signatureMax = 0 underscore.keys(fileTypes).forEach((fileType) => { if (signatureMax < fileTypes[fileType].length) signatureMax = fileTypes[fileType].length }) signatureMax = Math.ceil(signatureMax * 1.5) eventStore.addChangeListener(() => { const eventState = eventStore.getState().toJS() var view = eventState.page_view var info = eventState.page_info var pageLoad = eventState.page_load if ((!synopsis) || (!util.isArray(info))) return info.forEach((page) => { var entry, faviconURL, publisher var location = page.url if ((location.match(/^about/)) || ((locations[location]) && (locations[location].publisher))) return if (!page.publisher) { try { publisher = ledgerPublisher.getPublisher(location) if (publisher) page.publisher = publisher } catch (ex) { console.log('getPublisher error for ' + location + ': ' + ex.toString()) } } locations[location] = underscore.omit(page, [ 'url' ]) if (!page.publisher) return publisher = page.publisher synopsis.initPublisher(publisher) entry = synopsis.publishers[publisher] if ((page.protocol) && (!entry.protocol)) entry.protocol = page.protocol if ((typeof entry.faviconURL === 'undefined') && ((page.faviconURL) || (entry.protocol))) { var fetch = (url, redirects) => { if (typeof redirects === 'undefined') redirects = 0 request.request({ url: url, responseType: 'blob' }, (err, response, blob) => { var matchP, prefix, tail if (publisherInfo._internal.debugP) { console.log('\nresponse: ' + url + ' errP=' + (!!err) + ' blob=' + (blob || '').substr(0, 80) + '\nresponse=' + JSON.stringify(response, null, 2)) } if (err) return console.log('response error: ' + err.toString() + '\n' + err.stack) if ((response.statusCode === 301) && (response.headers.location)) { if (redirects < 3) fetch(response.headers.location, redirects++) return } if ((response.statusCode !== 200) || (response.headers['content-length'] === '0')) return if (blob.indexOf('data:image/') !== 0) { // NB: for some reason, some sites return an image, but with the wrong content-type... tail = blob.indexOf(';base64,') if (tail <= 0) return prefix = new Buffer(blob.substr(tail + 8, signatureMax), 'base64') underscore.keys(fileTypes).forEach((fileType) => { if (matchP) return if ((prefix.length < fileTypes[fileType].length) && (fileTypes[fileType].compare(prefix, 0, fileTypes[fileType].length) !== 0)) return blob = 'data:image/' + fileType + blob.substr(tail) matchP = true }) } entry.faviconURL = blob updatePublisherInfo() if (publisherInfo._internal.debugP) { console.log('\n' + publisher + ' synopsis=' + JSON.stringify(underscore.extend(underscore.omit(entry, [ 'faviconURL', 'window' ]), { faviconURL: entry.faviconURL && '... ' }), null, 2)) } }) } faviconURL = page.faviconURL || entry.protocol + '//' + url.parse(location).host + '/favicon.ico' entry.faviconURL = null if (publisherInfo._internal.debugP) console.log('request: ' + faviconURL) fetch(faviconURL) } }) view = underscore.last(view) || {} if (ledgerUtil.shouldTrackView(view, pageLoad)) { visit(view.url || 'NOOP', view.timestamp || underscore.now(), view.tabId) } }) /* * module initialization */ var initialize = (onoff) => { enable(onoff) if (!onoff) { client = null return appActions.updateLedgerInfo({}) } if (client) return cacheRuleSet(ledgerPublisher.rules) fs.access(pathName(statePath), fs.FF_OK, (err) => { if (!err) { if (clientOptions.verboseP) console.log('\nfound ' + pathName(statePath)) fs.readFile(pathName(statePath), (err, data) => { var state if (err) return console.log('read error: ' + err.toString()) try { state = JSON.parse(data) if (clientOptions.verboseP) console.log('\nstarting up ledger client integration') } catch (ex) { return console.log('statePath parse error: ' + ex.toString()) } getStateInfo(state) try { client = ledgerClient(state.personaId, underscore.extend(state.options, { roundtrip: roundtrip }, clientOptions), state) } catch (ex) { return console.log('ledger client creation error: ' + ex.toString() + '\n' + ex.stack) } if (client.sync(callback) === true) run(random.randomInt({ min: msecs.minute, max: 10 * msecs.minute })) cacheRuleSet(state.ruleset) // Make sure bravery props are up-to-date with user settings setPaymentInfo(getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT)) getBalance() }) return } if (err.code !== 'ENOENT') console.log('statePath read error: ' + err.toString()) appActions.updateLedgerInfo({}) }) } var enable = (onoff) => { if (!onoff) { synopsis = null if (notificationTimeout) { clearInterval(notificationTimeout) notificationTimeout = null } return updatePublisherInfo() } synopsis = new (ledgerPublisher.Synopsis)() fs.readFile(pathName(synopsisPath), (err, data) => { if (publisherInfo._internal.verboseP) console.log('\nstarting up ledger publisher integration') if (err) { if (err.code !== 'ENOENT') console.log('synopsisPath read error: ' + err.toString()) return updatePublisherInfo() } if (publisherInfo._internal.verboseP) console.log('\nfound ' + pathName(synopsisPath)) try { synopsis = new (ledgerPublisher.Synopsis)(data) } catch (ex) { console.log('synopsisPath parse error: ' + ex.toString()) } // cf., the `Synopsis` constructor, https://github.com/brave/ledger-publisher/blob/master/index.js#L167 if (process.env.NODE_ENV === 'test') { synopsis.options.minDuration = 0 synopsis.options.minPublisherDuration = 0 synopsis.options.minPublisherVisits = 0 } else { if (process.env.LEDGER_PUBLISHER_VISIT_DURATION) { synopsis.options.minDuration = ledgerClient.prototype.numbion(process.env.LEDGER_PUBLISHER_VISIT_DURATION) } if (process.env.LEDGER_PUBLISHER_MIN_DURATION) { synopsis.options.minPublisherDuration = ledgerClient.prototype.numbion(process.env.LEDGER_PUBLISHER_MIN_DURATION) } if (process.env.LEDGER_PUBLISHER_MIN_VISITS) { synopsis.options.minPublisherVisits = ledgerClient.prototype.numbion(process.env.LEDGER_PUBLISHER_MIN_VISITS) } } underscore.keys(synopsis.publishers).forEach((publisher) => { if (synopsis.publishers[publisher].faviconURL === null) delete synopsis.publishers[publisher].faviconURL }) updatePublisherInfo() // Check if relevant browser notifications should be shown every 15 minutes notificationTimeout = setInterval(showNotifications, 15 * msecs.minute) fs.readFile(pathName(publisherPath), (err, data) => { if (err) { if (err.code !== 'ENOENT') console.log('publisherPath read error: ' + err.toString()) return } if (publisherInfo._internal.verboseP) console.log('\nfound ' + pathName(publisherPath)) try { data = JSON.parse(data) underscore.keys(data).sort().forEach((publisher) => { var entries = data[publisher] publishers[publisher] = {} entries.forEach((entry) => { locations[entry.location] = entry publishers[publisher][entry.location] = { timestamp: entry.when, tabIds: [] } }) }) } catch (ex) { console.log('publishersPath parse error: ' + ex.toString()) } }) }) } /* * update publisher information */ var publisherInfo = { synopsis: undefined, _internal: { ruleset: { raw: [], cooked: [] } } } var updatePublisherInfo = () => { var data = {} var then = underscore.now() - msecs.week if (!synopsis) return underscore.keys(publishers).sort().forEach((publisher) => { var entries = [] underscore.keys(publishers[publisher]).forEach((location) => { var when = publishers[publisher][location].timestamp if (when > then) entries.push({ location: location, when: when }) }) if (entries.length > 0) data[publisher] = entries }) syncWriter(pathName(publisherPath), data, () => {}) syncWriter(pathName(scoresPath), synopsis.allN(), () => {}) syncWriter(pathName(synopsisPath), synopsis, () => {}) publisherInfo.synopsis = synopsisNormalizer() if (publisherInfo._internal.debugP) { data = [] publisherInfo.synopsis.forEach((entry) => { data.push(underscore.extend(underscore.omit(entry, [ 'faviconURL' ]), { faviconURL: entry.faviconURL && '...' })) }) console.log('\nupdatePublisherInfo: ' + JSON.stringify(data, null, 2)) } appActions.updatePublisherInfo(underscore.omit(publisherInfo, [ '_internal' ])) } var synopsisNormalizer = () => { var i, duration, n, pct, publisher, results, total var data = [] var scorekeeper = synopsis.options.scorekeeper results = [] underscore.keys(synopsis.publishers).forEach((publisher) => { if (synopsis.publishers[publisher].scores[scorekeeper] <= 0) return if ((synopsis.options.minPublisherDuration > synopsis.publishers[publisher].duration) || (synopsis.options.minPublisherVisits > synopsis.publishers[publisher].visits)) return results.push(underscore.extend({ publisher: publisher }, underscore.omit(synopsis.publishers[publisher], 'window'))) }, synopsis) results = underscore.sortBy(results, (entry) => { return -entry.scores[scorekeeper] }) n = results.length total = 0 for (i = 0; i < n; i++) { total += results[i].scores[scorekeeper] } if (total === 0) return data pct = [] for (i = 0; i < n; i++) { publisher = synopsis.publishers[results[i].publisher] duration = results[i].duration data[i] = { rank: i + 1, // TBD: the `ledger-publisher` package does not currently report `verified` ... verified: publisher.verified || false, site: results[i].publisher, views: results[i].visits, duration: duration, daysSpent: 0, hoursSpent: 0, minutesSpent: 0, secondsSpent: 0, faviconURL: publisher.faviconURL, score: results[i].scores[scorekeeper] } // HACK: Protocol is sometimes blank here, so default to http:// so we can // still generate publisherURL. data[i].publisherURL = (results[i].protocol || 'http:') + '//' + results[i].publisher pct[i] = Math.round((results[i].scores[scorekeeper] * 100) / total) if (duration >= msecs.day) { data[i].daysSpent = Math.max(Math.round(duration / msecs.day), 1) } else if (duration >= msecs.hour) { data[i].hoursSpent = Math.max(Math.floor(duration / msecs.hour), 1) data[i].minutesSpent = Math.round((duration % msecs.hour) / msecs.minute) } else if (duration >= msecs.minute) { data[i].minutesSpent = Math.max(Math.round(duration / msecs.minute), 1) data[i].secondsSpent = Math.round((duration % msecs.minute) / msecs.second) } else { data[i].secondsSpent = Math.max(Math.round(duration / msecs.second), 1) } } // courtesy of https://stackoverflow.com/questions/13483430/how-to-make-rounded-percentages-add-up-to-100#13485888 var foo = (l, target) => { var off = target - underscore.reduce(l, (acc, x) => { return acc + Math.round(x) }, 0) return underscore.chain(l) .sortBy((x) => { return Math.round(x) - x }) .map((x, i) => { return Math.round(x) + (off > i) - (i >= (l.length + off)) }) .value() } pct = foo(pct, 100) total = 0 for (i = 0; i < n; i++) { /* if (pct[i] <= 0) { data = data.slice(0, i) break } */ if (pct[i] < 0) pct[i] = 0 data[i].percentage = pct[i] total += pct[i] } for (i = data.length - 1; (total > 100) && (i >= 0); i--) { if (data[i].percentage < 2) continue data[i].percentage-- total-- } return data } /* * publisher utilities */ var currentLocation = 'NOOP' var currentTimestamp = underscore.now() var visit = (location, timestamp, tabId) => { var setLocation = () => { var duration, publisher, revisitP if (!synopsis) return if (publisherInfo._internal.verboseP) { console.log('locations[' + currentLocation + ']=' + JSON.stringify(locations[currentLocation], null, 2) + ' duration=' + (timestamp - currentTimestamp) + ' msec' + ' tabId=' + tabId) } if ((location === currentLocation) || (!locations[currentLocation]) || (!tabId)) return publisher = locations[currentLocation].publisher if (!publisher) return if (!publishers[publisher]) publishers[publisher] = {} if (!publishers[publisher][currentLocation]) publishers[publisher][currentLocation] = { tabIds: [] } publishers[publisher][currentLocation].timestamp = timestamp revisitP = publishers[publisher][currentLocation].tabIds.indexOf(tabId) !== -1 if (!revisitP) publishers[publisher][currentLocation].tabIds.push(tabId) duration = timestamp - currentTimestamp if (publisherInfo._internal.verboseP) { console.log('\nadd publisher ' + publisher + ': ' + duration + ' msec' + ' revisitP=' + revisitP + ' state=' + JSON.stringify(underscore.extend({ location: currentLocation }, publishers[publisher][currentLocation]), null, 2)) } synopsis.addPublisher(publisher, { duration: duration, revisitP: revisitP }) updatePublisherInfo() } setLocation() if (location === currentLocation) return currentLocation = location.match(/^about/) ? 'NOOP' : location currentTimestamp = timestamp } var cacheRuleSet = (ruleset) => { var stewed, syncP if ((!ruleset) || (underscore.isEqual(publisherInfo._internal.ruleset.raw, ruleset))) return try { stewed = [] ruleset.forEach((rule) => { var entry = { condition: acorn.parse(rule.condition) } if (rule.dom) { if (rule.dom.publisher) { entry.publisher = { selector: rule.dom.publisher.nodeSelector, consequent: acorn.parse(rule.dom.publisher.consequent) } } if (rule.dom.faviconURL) { entry.faviconURL = { selector: rule.dom.faviconURL.nodeSelector, consequent: acorn.parse(rule.dom.faviconURL.consequent) } } } if (!entry.publisher) entry.consequent = rule.consequent ? acorn.parse(rule.consequent) : rule.consequent stewed.push(entry) }) publisherInfo._internal.ruleset.raw = ruleset publisherInfo._internal.ruleset.cooked = stewed if (!synopsis) return underscore.keys(synopsis.publishers).forEach((publisher) => { var location = (synopsis.publishers[publisher].protocol || 'http:') + '//' + publisher var ctx = url.parse(location, true) ctx.TLD = tldjs.getPublicSuffix(ctx.host) if (!ctx.TLD) return ctx = underscore.mapObject(ctx, function (value, key) { if (!underscore.isFunction(value)) return value }) ctx.URL = location ctx.SLD = tldjs.getDomain(ctx.host) ctx.RLD = tldjs.getSubdomain(ctx.host) ctx.QLD = ctx.RLD ? underscore.last(ctx.RLD.split('.')) : '' stewed.forEach((rule) => { if ((rule.consequent !== null) || (rule.dom)) return if (!rulesolver.resolve(rule.condition, ctx)) return if (publisherInfo._internal.verboseP) console.log('\npurging ' + publisher) delete synopsis.publishers[publisher] delete publishers[publisher] syncP = true }) }) if (!syncP) return updatePublisherInfo() } catch (ex) { console.log('ruleset error: ' + ex.toString() + '\n' + ex.stack) } } /* * update ledger information */ var ledgerInfo = { creating: false, created: false, delayStamp: undefined, reconcileStamp: undefined, reconcileDelay: undefined, transactions: [ /* { viewingId: undefined, surveyorId: undefined, contribution: { fiat: { amount: undefined, currency: undefined }, rates: { [currency]: undefined // bitcoin value in <currency> }, satoshis: undefined, fee: undefined }, submissionStamp: undefined, submissionId: undefined, count: undefined, satoshis: undefined, votes: undefined, ballots: { [publisher]: undefined } , ... */ ], // set from ledger client's state.paymentInfo OR client's getWalletProperties // Bitcoin wallet address address: undefined, // Bitcoin wallet balance (truncated BTC and satoshis) balance: undefined, unconfirmed: undefined, satoshis: undefined, // the desired contribution (the btc value approximates the amount/currency designation) btc: undefined, amount: undefined, currency: undefined, paymentURL: undefined, buyURL: undefined, bravery: undefined, hasBitcoinHandler: false, // geoIP/exchange information countryCode: undefined, exchangeInfo: undefined, _internal: { exchangeExpiry: 0, exchanges: {}, geoipExpiry: 0 }, error: null } var updateLedgerInfo = () => { var info = ledgerInfo._internal.paymentInfo var now = underscore.now() if (info) { underscore.extend(ledgerInfo, underscore.pick(info, [ 'address', 'balance', 'unconfirmed', 'satoshis', 'btc', 'amount', 'currency' ])) if ((!info.buyURLExpires) || (info.buyURLExpires > now)) ledgerInfo.buyURL = info.buyURL underscore.extend(ledgerInfo, ledgerInfo._internal.cache || {}) } if ((client) && (now > ledgerInfo._internal.geoipExpiry)) { ledgerInfo._internal.geoipExpiry = now + (5 * msecs.minute) return ledgerGeoIP.getGeoIP(client.options, (err, provider, result) => { if (err) console.log('ledger geoip warning: ' + JSON.stringify(err, null, 2)) if (result) ledgerInfo.countryCode = result ledgerInfo.exchangeInfo = ledgerInfo._internal.exchanges[ledgerInfo.countryCode] if (now <= ledgerInfo._internal.exchangeExpiry) return updateLedgerInfo() ledgerInfo._internal.exchangeExpiry = now + msecs.day roundtrip({ path: '/v1/exchange/providers' }, client.options, (err, response, body) => { if (err) console.log('ledger exchange error: ' + JSON.stringify(err, null, 2)) ledgerInfo._internal.exchanges = body || {} ledgerInfo.exchangeInfo = ledgerInfo._internal.exchanges[ledgerInfo.countryCode] updateLedgerInfo() }) }) } if (ledgerInfo._internal.debugP) { console.log('\nupdateLedgerInfo: ' + JSON.stringify(underscore.omit(ledgerInfo, [ '_internal' ]), null, 2)) } appActions.updateLedgerInfo(underscore.omit(ledgerInfo, [ '_internal' ])) } /* * ledger client callbacks */ var logs = [] var callback = (err, result, delayTime) => { var i, then var entries = client && client.report() var now = underscore.now() if (clientOptions.verboseP) { console.log('\nledger client callback: clientP=' + (!!client) + ' errP=' + (!!err) + ' resultP=' + (!!result) + ' delayTime=' + delayTime) } if (entries) { then = now - msecs.week logs = logs.concat(entries) for (i = 0; i < logs.length; i++) if (logs[i].when > then) break if ((i !== 0) && (i !== logs.length)) logs = logs.slice(i) if (result) entries.push({ who: 'callback', what: result, when: underscore.now() }) syncWriter(pathName(logPath), entries, { flag: 'a' }, () => {}) } if (err) { console.log('ledger client error(1): ' + JSON.stringify(err, null, 2) + (err.stack ? ('\n' + err.stack) : '')) if (!client) return if (typeof delayTime === 'undefined') delayTime = random.randomInt({ min: msecs.minute, max: 10 * msecs.minute }) } if (!result) return run(delayTime) if ((client) && (result.properties.wallet)) { if (!ledgerInfo.created) setPaymentInfo(getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT)) getStateInfo(result) getPaymentInfo() } cacheRuleSet(result.ruleset) syncWriter(pathName(statePath), result, () => {}) run(delayTime) } var roundtrip = (params, options, callback) => { var i var parts = typeof params.server === 'string' ? url.parse(params.server) : typeof params.server !== 'undefined' ? params.server : typeof options.server === 'string' ? url.parse(options.server) : options.server if (!params.method) params.method = 'GET' parts = underscore.extend(underscore.pick(parts, [ 'protocol', 'hostname', 'port' ]), underscore.omit(params, [ 'headers', 'payload', 'timeout' ])) // TBD: let the user configure this via preferences [MTR] if ((parts.hostname === 'ledger.brave.com') && (params.useProxy)) parts.hostname = 'ledger-proxy.privateinternetaccess.com' i = parts.path.indexOf('?') if (i !== -1) { parts.pathname = parts.path.substring(0, i) parts.search = parts.path.substring(i) } else { parts.pathname = parts.path } options = { url: url.format(parts), method: params.method, payload: params.payload, responseType: 'text', headers: underscore.defaults(params.headers || {}, { 'content-type': 'application/json; charset=utf-8' }), verboseP: options.verboseP } request.request(options, (err, response, body) => { var payload if ((response) && (options.verboseP)) { console.log('[ response for ' + params.method + ' ' + parts.protocol + '//' + parts.hostname + params.path + ' ]') console.log('>>> HTTP/' + response.httpVersionMajor + '.' + response.httpVersionMinor + ' ' + response.statusCode + ' ' + (response.statusMessage || '')) underscore.keys(response.headers).forEach((header) => { console.log('>>> ' + header + ': ' + response.headers[header]) }) console.log('>>>') console.log('>>> ' + (body || '').split('\n').join('\n>>> ')) } if (err) return callback(err) if (Math.floor(response.statusCode / 100) !== 2) { return callback(new Error('HTTP response ' + response.statusCode) + ' for ' + params.method + ' ' + params.path) } try { payload = (response.statusCode !== 204) ? JSON.parse(body) : null } catch (err) { return callback(err) } try { callback(null, response, payload) } catch (err0) { if (options.verboseP) console.log('\ncallback: ' + err0.toString() + '\n' + err0.stack) } }) if (!options.verboseP) return console.log('<<< ' + params.method + ' ' + parts.protocol + '//' + parts.hostname + params.path) underscore.keys(options.headers).forEach((header) => { console.log('<<< ' + header + ': ' + options.headers[header]) }) console.log('<<<') if (options.payload) console.log('<<< ' + JSON.stringify(params.payload, null, 2).split('\n').join('\n<<< ')) } var runTimeoutId = false var run = (delayTime) => { if (clientOptions.verboseP) console.log('\nledger client run: clientP=' + (!!client) + ' delayTime=' + delayTime) if ((typeof delayTime === 'undefined') || (!client)) return var active, state var ballots = client.ballots() var siteSettings = appStore.getState().get('siteSettings') var winners = ((synopsis) && (ballots > 0) && (synopsis.winners(ballots))) || [] try { winners.forEach((winner) => { var result var siteSetting = siteSettings.get(`https?://${winner}`) if ((siteSetting) && (siteSetting.get('ledgerPayments') === false)) return result = client.vote(winner) if (result) state = result }) if (state) syncWriter(pathName(statePath), state, () => {}) } catch (ex) { console.log('ledger client error(2): ' + ex.toString() + (ex.stack ? ('\n' + ex.stack) : '')) } if (delayTime === 0) { try { delayTime = client.timeUntilReconcile() } catch (ex) { delayTime = false } if (delayTime === false) delayTime = random.randomInt({ min: msecs.minute, max: 10 * msecs.minute }) } if (delayTime > 0) { if (runTimeoutId) return active = client if (delayTime > (1 * msecs.hour)) delayTime = random.randomInt({ min: 3 * msecs.minute, max: msecs.hour }) runTimeoutId = setTimeout(() => { runTimeoutId = false if (active !== client) return if (!client) return console.log('\n\n*** MTR says this can\'t happen(1)... please tell him that he\'s wrong!\n\n') if (client.sync(callback) === true) return run(0) }, delayTime) return } if (client.isReadyToReconcile()) return client.reconcile(uuid.v4().toLowerCase(), callback) console.log('what? wait, how can this happen?') } /* * ledger client utilities */ var getStateInfo = (state) => { var ballots, i, transaction var info = state.paymentInfo var then = underscore.now() - msecs.year ledgerInfo.created = !!state.properties.wallet ledgerInfo.creating = !ledgerInfo.created ledgerInfo.delayStamp = state.delayStamp ledgerInfo.reconcileStamp = state.reconcileStamp ledgerInfo.reconcileDelay = state.prepareTransaction && state.delayStamp if (info) { ledgerInfo._internal.paymentInfo = info cacheReturnValue() } ledgerInfo.transactions = [] if (!state.transactions) return updateLedgerInfo() for (i = state.transactions.length - 1; i >= 0; i--) { transaction = state.transactions[i] if (transaction.stamp < then) break ballots = underscore.clone(transaction.ballots || {}) state.ballots.forEach((ballot) => { if (ballot.viewingId !== transaction.viewingId) return if (!ballots[ballot.publisher]) ballots[ballot.publisher] = 0 ballots[ballot.publisher]++ }) ledgerInfo.transactions.push(underscore.extend(underscore.pick(transaction, [ 'viewingId', 'contribution', 'submissionStamp', 'count' ]), { ballots: ballots })) } updateLedgerInfo() } var balanceTimeoutId = false var getBalance = () => { if (!client) return balanceTimeoutId = setTimeout(getBalance, 1 * msecs.minute) if (!ledgerInfo.address) return ledgerBalance.getBalance(ledgerInfo.address, underscore.extend({ balancesP: true }, client.options), (err, provider, result) => { var unconfirmed var info = ledgerInfo._internal.paymentInfo if (err) return console.log('ledger balance warning: ' + JSON.stringify(err, null, 2)) if (typeof result.unconfirmed === 'undefined') return if (result.unconfirmed > 0) { unconfirmed = (result.unconfirmed / 1e8).toFixed(4) if ((info || ledgerInfo).unconfirmed === unconfirmed) return ledgerInfo.unconfirmed = unconfirmed if (info) info.unconfirmed = ledgerInfo.unconfirmed if (clientOptions.verboseP) console.log('\ngetBalance refreshes ledger info: ' + ledgerInfo.unconfirmed) return updateLedgerInfo() } if (ledgerInfo.unconfirmed === '0.0000') return if (clientOptions.verboseP) console.log('\ngetBalance refreshes payment info') getPaymentInfo() }) } var logError = (err, caller) => { if (err) { ledgerInfo.error = { caller: caller, error: err } console.log('Error in %j: %j', caller, err) return true } else { ledgerInfo.error = null return false } } var getPaymentInfo = () => { var amount, currency if (!client) return try { ledgerInfo.bravery = client.getBraveryProperties() if (ledgerInfo.bravery.fee) { amount = ledgerInfo.bravery.fee.amount currency = ledgerInfo.bravery.fee.currency } client.getWalletProperties(amount, currency, function (err, body) { var info = ledgerInfo._internal.paymentInfo || {} if (logError(err, 'getWalletProperties')) { return } info = underscore.extend(info, underscore.pick(body, [ 'buyURL', 'buyURLExpires', 'balance', 'unconfirmed', 'satoshis' ])) info.address = client.getWalletAddress() if ((amount) && (currency)) { info = underscore.extend(info, { amount: amount, currency: currency }) if ((body.rates) && (body.rates[currency])) { info.btc = (amount / body.rates[currency]).toFixed(8) } } ledgerInfo._internal.paymentInfo = info updateLedgerInfo() cacheReturnValue() }) } catch (ex) { console.log('properties error: ' + ex.toString()) } } var setPaymentInfo = (amount) => { if (!client) return var bravery = client.getBraveryProperties() amount = parseInt(amount, 10) if (isNaN(amount) || (amount <= 0)) return underscore.extend(bravery.fee, { amount: amount }) client.setBraveryProperties(bravery, (err, result) => { if (err) return console.log('ledger setBraveryProperties: ' + err.toString()) if (result) syncWriter(pathName(statePath), result, () => {}) }) if (ledgerInfo.created) getPaymentInfo() } var cacheReturnValue = () => { var chunks, cache, paymentURL var info = ledgerInfo._internal.paymentInfo if (!info) return if (!ledgerInfo._internal.cache) ledgerInfo._internal.cache = {} cache = ledgerInfo._internal.cache paymentURL = 'bitcoin:' + info.address + '?amount=' + info.btc + '&label=' + encodeURI('Brave Software') if (cache.paymentURL === paymentURL) return cache.paymentURL = paymentURL updateLedgerInfo() try { chunks = [] qr.image(paymentURL, { type: 'png' }).on('data', (chunk) => { chunks.push(chunk) }).on('end', () => { cache.paymentIMG = 'data:image/png;base64,' + Buffer.concat(chunks).toString('base64') updateLedgerInfo() }) } catch (ex) { console.log('qr.imageSync error: ' + ex.toString()) } } var networkConnected = underscore.debounce(() => { if (!client) return if (runTimeoutId) { clearTimeout(runTimeoutId) runTimeoutId = false } if (client.sync(callback) === true) run(random.randomInt({ min: msecs.minute, max: 10 * msecs.minute })) if (balanceTimeoutId) clearTimeout(balanceTimeoutId) balanceTimeoutId = setTimeout(getBalance, 5 * msecs.second) }, 1 * msecs.minute, true) /* * low-level utilities */ var syncingP = {} var syncWriter = (path, obj, options, cb) => { if (typeof options === 'function') { cb = options options = null } options = underscore.defaults(options || {}, { encoding: 'utf8', mode: parseInt('644', 8) }) if (syncingP[path]) { syncingP[path] = { obj: obj, options: options, cb: cb } if (ledgerInfo._internal.debugP) console.log('deferring ' + path) return } syncingP[path] = true if (ledgerInfo._internal.debugP) console.log('writing ' + path) fs.writeFile(path, JSON.stringify(obj, null, 2), options, (err) => { var deferred = syncingP[path] delete syncingP[path] if (typeof deferred === 'object') { if (ledgerInfo._internal.debugP) console.log('restarting ' + path) syncWriter(path, deferred.obj, deferred.options, deferred.cb) } if (err) console.log('write error: ' + err.toString()) cb(err) }) } const pathSuffix = { development: '-dev', test: '-test' }[process.env.NODE_ENV] || '' var pathName = (name) => { var parts = path.parse(name) var basePath = process.env.NODE_ENV === 'test' ? path.join(process.env.HOME, '.brave-test-ledger') : app.getPath('userData') return path.join(basePath, parts.name + pathSuffix + parts.ext) } /** * UI controller functionality */ /** * Show message that it's time to add funds if reconciliation is less than * a day in the future and balance is too low. * 24 hours prior to reconciliation, show message asking user to review * their votes. */ const showNotifications = () => { if (!getSetting(settings.PAYMENTS_ENABLED) || !getSetting(settings.PAYMENTS_NOTIFICATIONS) || suppressNotifications) { return } const reconcileStamp = ledgerInfo.reconcileStamp const balance = Number(ledgerInfo.balance || 0) const unconfirmed = Number(ledgerInfo.unconfirmed || 0) if (reconcileStamp && reconcileStamp - underscore.now() < msecs.day) { if (ledgerInfo.btc && balance + unconfirmed < 0.9 * Number(ledgerInfo.btc)) { addFundsMessage = addFundsMessage || locale.translation('addFundsNotification') appActions.showMessageBox({ greeting: locale.translation('updateHello'), message: addFundsMessage, buttons: [ {text: locale.translation('updateLater')}, {text: locale.translation('addFunds'), className: 'primary'} ], options: { style: 'greetingStyle', persist: false } }) } else if (!reconciliationNotificationShown) { reconciliationMessage = reconciliationMessage || locale.translation('reconciliationNotification') appActions.showMessageBox({ greeting: locale.translation('updateHello'), message: reconciliationMessage, buttons: [ {text: locale.translation('reviewSites'), className: 'primary'} ], options: { style: 'greetingStyle', persist: false } }) reconciliationNotificationShown = true } } } module.exports = { init: init, quit: quit, boot: boot }
MKuenzi/browser-laptop
app/ledger.js
JavaScript
mpl-2.0
41,776
/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved. ******************************* END LICENSE BLOCK ***************************/ package net.opengis.gml.v32; import net.opengis.OgcPropertyList; /** * POJO class for XML type AbstractTimePrimitiveType(@http://www.opengis.net/gml/3.2). * * This is a complex type. */ @SuppressWarnings("javadoc") public interface AbstractTimePrimitive extends AbstractGML { /** * Gets the list of relatedTime properties */ public OgcPropertyList<AbstractTimePrimitive> getRelatedTimeList(); /** * Returns number of relatedTime properties */ public int getNumRelatedTimes(); /** * Adds a new relatedTime property */ public void addRelatedTime(AbstractTimePrimitive relatedTime); }
sensiasoft/lib-swe-common
swe-common-om/src/main/java/net/opengis/gml/v32/AbstractTimePrimitive.java
Java
mpl-2.0
1,326
package iso import ( "context" "fmt" "log" "github.com/hashicorp/packer-plugin-sdk/multistep" packersdk "github.com/hashicorp/packer-plugin-sdk/packer" parallelscommon "github.com/hashicorp/packer/builder/parallels/common" ) // This step attaches the ISO to the virtual machine. // // Uses: // driver Driver // iso_path string // ui packersdk.Ui // vmName string // // Produces: // attachedIso bool type stepAttachISO struct{} func (s *stepAttachISO) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(parallelscommon.Driver) isoPath := state.Get("iso_path").(string) ui := state.Get("ui").(packersdk.Ui) vmName := state.Get("vmName").(string) // Attach the disk to the cdrom0 device. We couldn't use a separated device because it is failed to boot in PD9 [GH-1667] ui.Say("Attaching ISO to the default CD/DVD ROM device...") command := []string{ "set", vmName, "--device-set", "cdrom0", "--image", isoPath, "--enable", "--connect", } if err := driver.Prlctl(command...); err != nil { err := fmt.Errorf("Error attaching ISO: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Set some state so we know to remove state.Put("attachedIso", true) return multistep.ActionContinue } func (s *stepAttachISO) Cleanup(state multistep.StateBag) { if _, ok := state.GetOk("attachedIso"); !ok { return } driver := state.Get("driver").(parallelscommon.Driver) ui := state.Get("ui").(packersdk.Ui) vmName := state.Get("vmName").(string) // Detach ISO by setting an empty string image. log.Println("Detaching ISO from the default CD/DVD ROM device...") command := []string{ "set", vmName, "--device-set", "cdrom0", "--image", "", "--disconnect", "--enable", } if err := driver.Prlctl(command...); err != nil { ui.Error(fmt.Sprintf("Error detaching ISO: %s", err)) } }
ricardclau/packer
builder/parallels/iso/step_attach_iso.go
GO
mpl-2.0
1,921
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from selenium.webdriver.common.by import By from pages.base import BasePage class FirefoxWhatsNew73Page(BasePage): URL_TEMPLATE = '/{locale}/firefox/73.0/whatsnew/all/{params}' _set_default_button_locator = (By.ID, 'set-as-default-button') @property def is_default_browser_button_displayed(self): return self.is_element_displayed(*self._set_default_button_locator)
ericawright/bedrock
tests/pages/firefox/whatsnew/whatsnew_73.py
Python
mpl-2.0
595
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "TexUnpackBlob.h" #include "GLBlitHelper.h" #include "GLContext.h" #include "mozilla/dom/Element.h" #include "mozilla/dom/HTMLCanvasElement.h" #include "mozilla/RefPtr.h" #include "nsLayoutUtils.h" #include "WebGLBuffer.h" #include "WebGLContext.h" #include "WebGLTexelConversions.h" #include "WebGLTexture.h" namespace mozilla { namespace webgl { static bool IsPIValidForDOM(const webgl::PackingInfo& pi) { // https://www.khronos.org/registry/webgl/specs/latest/2.0/#TEXTURE_TYPES_FORMATS_FROM_DOM_ELEMENTS_TABLE // Just check for invalid individual formats and types, not combinations. switch (pi.format) { case LOCAL_GL_RGB: case LOCAL_GL_RGBA: case LOCAL_GL_LUMINANCE_ALPHA: case LOCAL_GL_LUMINANCE: case LOCAL_GL_ALPHA: case LOCAL_GL_RED: case LOCAL_GL_RED_INTEGER: case LOCAL_GL_RG: case LOCAL_GL_RG_INTEGER: case LOCAL_GL_RGB_INTEGER: case LOCAL_GL_RGBA_INTEGER: break; case LOCAL_GL_SRGB: case LOCAL_GL_SRGB_ALPHA: // Allowed in WebGL1+EXT_srgb break; default: return false; } switch (pi.type) { case LOCAL_GL_UNSIGNED_BYTE: case LOCAL_GL_UNSIGNED_SHORT_5_6_5: case LOCAL_GL_UNSIGNED_SHORT_4_4_4_4: case LOCAL_GL_UNSIGNED_SHORT_5_5_5_1: case LOCAL_GL_HALF_FLOAT: case LOCAL_GL_HALF_FLOAT_OES: case LOCAL_GL_FLOAT: case LOCAL_GL_UNSIGNED_INT_10F_11F_11F_REV: break; default: return false; } return true; } static bool ValidatePIForDOM(WebGLContext* webgl, const char* funcName, const webgl::PackingInfo& pi) { if (!IsPIValidForDOM(pi)) { webgl->ErrorInvalidOperation("%s: Format or type is invalid for DOM sources.", funcName); return false; } return true; } static WebGLTexelFormat FormatForPackingInfo(const PackingInfo& pi) { switch (pi.type) { case LOCAL_GL_UNSIGNED_BYTE: switch (pi.format) { case LOCAL_GL_RED: case LOCAL_GL_LUMINANCE: case LOCAL_GL_RED_INTEGER: return WebGLTexelFormat::R8; case LOCAL_GL_ALPHA: return WebGLTexelFormat::A8; case LOCAL_GL_LUMINANCE_ALPHA: return WebGLTexelFormat::RA8; case LOCAL_GL_RGB: case LOCAL_GL_RGB_INTEGER: return WebGLTexelFormat::RGB8; case LOCAL_GL_RGBA: case LOCAL_GL_RGBA_INTEGER: return WebGLTexelFormat::RGBA8; case LOCAL_GL_RG: case LOCAL_GL_RG_INTEGER: return WebGLTexelFormat::RG8; default: break; } break; case LOCAL_GL_UNSIGNED_SHORT_5_6_5: if (pi.format == LOCAL_GL_RGB) return WebGLTexelFormat::RGB565; break; case LOCAL_GL_UNSIGNED_SHORT_5_5_5_1: if (pi.format == LOCAL_GL_RGBA) return WebGLTexelFormat::RGBA5551; break; case LOCAL_GL_UNSIGNED_SHORT_4_4_4_4: if (pi.format == LOCAL_GL_RGBA) return WebGLTexelFormat::RGBA4444; break; case LOCAL_GL_HALF_FLOAT: case LOCAL_GL_HALF_FLOAT_OES: switch (pi.format) { case LOCAL_GL_RED: case LOCAL_GL_LUMINANCE: return WebGLTexelFormat::R16F; case LOCAL_GL_ALPHA: return WebGLTexelFormat::A16F; case LOCAL_GL_LUMINANCE_ALPHA: return WebGLTexelFormat::RA16F; case LOCAL_GL_RG: return WebGLTexelFormat::RG16F; case LOCAL_GL_RGB: return WebGLTexelFormat::RGB16F; case LOCAL_GL_RGBA: return WebGLTexelFormat::RGBA16F; default: break; } break; case LOCAL_GL_FLOAT: switch (pi.format) { case LOCAL_GL_RED: case LOCAL_GL_LUMINANCE: return WebGLTexelFormat::R32F; case LOCAL_GL_ALPHA: return WebGLTexelFormat::A32F; case LOCAL_GL_LUMINANCE_ALPHA: return WebGLTexelFormat::RA32F; case LOCAL_GL_RG: return WebGLTexelFormat::RG32F; case LOCAL_GL_RGB: return WebGLTexelFormat::RGB32F; case LOCAL_GL_RGBA: return WebGLTexelFormat::RGBA32F; default: break; } break; case LOCAL_GL_UNSIGNED_INT_10F_11F_11F_REV: if (pi.format == LOCAL_GL_RGB) return WebGLTexelFormat::RGB11F11F10F; break; default: break; } return WebGLTexelFormat::FormatNotSupportingAnyConversion; } //////////////////// static bool ValidateUnpackPixels(WebGLContext* webgl, const char* funcName, uint32_t fullRows, uint32_t tailPixels, webgl::TexUnpackBlob* blob) { if (!blob->mWidth || !blob->mHeight || !blob->mDepth) return true; const auto usedPixelsPerRow = CheckedUint32(blob->mSkipPixels) + blob->mWidth; if (!usedPixelsPerRow.isValid() || usedPixelsPerRow.value() > blob->mRowLength) { webgl->ErrorInvalidOperation("%s: UNPACK_SKIP_PIXELS + width >" " UNPACK_ROW_LENGTH.", funcName); return false; } if (blob->mHeight > blob->mImageHeight) { webgl->ErrorInvalidOperation("%s: height > UNPACK_IMAGE_HEIGHT.", funcName); return false; } ////// // The spec doesn't bound SKIP_ROWS + height <= IMAGE_HEIGHT, unfortunately. auto skipFullRows = CheckedUint32(blob->mSkipImages) * blob->mImageHeight; skipFullRows += blob->mSkipRows; MOZ_ASSERT(blob->mDepth >= 1); MOZ_ASSERT(blob->mHeight >= 1); auto usedFullRows = CheckedUint32(blob->mDepth - 1) * blob->mImageHeight; usedFullRows += blob->mHeight - 1; // Full rows in the final image, excluding the tail. const auto fullRowsNeeded = skipFullRows + usedFullRows; if (!fullRowsNeeded.isValid()) { webgl->ErrorOutOfMemory("%s: Invalid calculation for required row count.", funcName); return false; } if (fullRows > fullRowsNeeded.value()) return true; if (fullRows == fullRowsNeeded.value() && tailPixels >= usedPixelsPerRow.value()) { blob->mNeedsExactUpload = true; return true; } webgl->ErrorInvalidOperation("%s: Desired upload requires more data than is" " available: (%u rows plus %u pixels needed, %u rows" " plus %u pixels available)", funcName, fullRowsNeeded.value(), usedPixelsPerRow.value(), fullRows, tailPixels); return false; } static bool ValidateUnpackBytes(WebGLContext* webgl, const char* funcName, const webgl::PackingInfo& pi, size_t availByteCount, webgl::TexUnpackBlob* blob) { if (!blob->mWidth || !blob->mHeight || !blob->mDepth) return true; const auto bytesPerPixel = webgl::BytesPerPixel(pi); const auto bytesPerRow = CheckedUint32(blob->mRowLength) * bytesPerPixel; const auto rowStride = RoundUpToMultipleOf(bytesPerRow, blob->mAlignment); const auto fullRows = availByteCount / rowStride; if (!fullRows.isValid()) { webgl->ErrorOutOfMemory("%s: Unacceptable upload size calculated."); return false; } const auto bodyBytes = fullRows.value() * rowStride.value(); const auto tailPixels = (availByteCount - bodyBytes) / bytesPerPixel; return ValidateUnpackPixels(webgl, funcName, fullRows.value(), tailPixels, blob); } //////////////////// static uint32_t ZeroOn2D(TexImageTarget target, uint32_t val) { return (IsTarget3D(target) ? val : 0); } static uint32_t FallbackOnZero(uint32_t val, uint32_t fallback) { return (val ? val : fallback); } TexUnpackBlob::TexUnpackBlob(const WebGLContext* webgl, TexImageTarget target, uint32_t rowLength, uint32_t width, uint32_t height, uint32_t depth, bool srcIsPremult) : mAlignment(webgl->mPixelStore_UnpackAlignment) , mRowLength(rowLength) , mImageHeight(FallbackOnZero(ZeroOn2D(target, webgl->mPixelStore_UnpackImageHeight), height)) , mSkipPixels(webgl->mPixelStore_UnpackSkipPixels) , mSkipRows(webgl->mPixelStore_UnpackSkipRows) , mSkipImages(ZeroOn2D(target, webgl->mPixelStore_UnpackSkipImages)) , mWidth(width) , mHeight(height) , mDepth(depth) , mSrcIsPremult(srcIsPremult) , mNeedsExactUpload(false) { MOZ_ASSERT_IF(!IsTarget3D(target), mDepth == 1); } bool TexUnpackBlob::ConvertIfNeeded(WebGLContext* webgl, const char* funcName, const uint32_t rowLength, const uint32_t rowCount, WebGLTexelFormat srcFormat, const uint8_t* const srcBegin, const ptrdiff_t srcStride, WebGLTexelFormat dstFormat, const ptrdiff_t dstStride, const uint8_t** const out_begin, UniqueBuffer* const out_anchoredBuffer) const { MOZ_ASSERT(srcFormat != WebGLTexelFormat::FormatNotSupportingAnyConversion); MOZ_ASSERT(dstFormat != WebGLTexelFormat::FormatNotSupportingAnyConversion); *out_begin = srcBegin; if (!rowLength || !rowCount) return true; const auto& dstIsPremult = webgl->mPixelStore_PremultiplyAlpha; const auto srcOrigin = (webgl->mPixelStore_FlipY ? gl::OriginPos::TopLeft : gl::OriginPos::BottomLeft); const auto dstOrigin = gl::OriginPos::BottomLeft; if (srcFormat != dstFormat) { webgl->GenerateWarning("%s: Conversion requires pixel reformatting.", funcName); } else if (mSrcIsPremult != dstIsPremult) { webgl->GenerateWarning("%s: Conversion requires change in" "alpha-premultiplication.", funcName); } else if (srcOrigin != dstOrigin) { webgl->GenerateWarning("%s: Conversion requires y-flip.", funcName); } else if (srcStride != dstStride) { webgl->GenerateWarning("%s: Conversion requires change in stride.", funcName); } else { return true; } //// const auto dstTotalBytes = CheckedUint32(rowCount) * dstStride; if (!dstTotalBytes.isValid()) { webgl->ErrorOutOfMemory("%s: Calculation failed.", funcName); return false; } UniqueBuffer dstBuffer = calloc(1, dstTotalBytes.value()); if (!dstBuffer.get()) { webgl->ErrorOutOfMemory("%s: Failed to allocate dest buffer.", funcName); return false; } const auto dstBegin = static_cast<uint8_t*>(dstBuffer.get()); //// // And go!: bool wasTrivial; if (!ConvertImage(rowLength, rowCount, srcBegin, srcStride, srcOrigin, srcFormat, mSrcIsPremult, dstBegin, dstStride, dstOrigin, dstFormat, dstIsPremult, &wasTrivial)) { webgl->ErrorImplementationBug("%s: ConvertImage failed.", funcName); return false; } *out_begin = dstBegin; *out_anchoredBuffer = Move(dstBuffer); return true; } static GLenum DoTexOrSubImage(bool isSubImage, gl::GLContext* gl, TexImageTarget target, GLint level, const DriverUnpackInfo* dui, GLint xOffset, GLint yOffset, GLint zOffset, GLsizei width, GLsizei height, GLsizei depth, const void* data) { if (isSubImage) { return DoTexSubImage(gl, target, level, xOffset, yOffset, zOffset, width, height, depth, dui->ToPacking(), data); } else { return DoTexImage(gl, target, level, dui, width, height, depth, data); } } ////////////////////////////////////////////////////////////////////////////////////////// // TexUnpackBytes TexUnpackBytes::TexUnpackBytes(const WebGLContext* webgl, TexImageTarget target, uint32_t width, uint32_t height, uint32_t depth, bool isClientData, const uint8_t* ptr, size_t availBytes) : TexUnpackBlob(webgl, target, FallbackOnZero(webgl->mPixelStore_UnpackRowLength, width), width, height, depth, false) , mIsClientData(isClientData) , mPtr(ptr) , mAvailBytes(availBytes) { } bool TexUnpackBytes::Validate(WebGLContext* webgl, const char* funcName, const webgl::PackingInfo& pi) { if (mIsClientData && !mPtr) return true; return ValidateUnpackBytes(webgl, funcName, pi, mAvailBytes, this); } bool TexUnpackBytes::TexOrSubImage(bool isSubImage, bool needsRespec, const char* funcName, WebGLTexture* tex, TexImageTarget target, GLint level, const webgl::DriverUnpackInfo* dui, GLint xOffset, GLint yOffset, GLint zOffset, GLenum* const out_error) const { WebGLContext* webgl = tex->mContext; const auto pi = dui->ToPacking(); const auto format = FormatForPackingInfo(pi); const auto bytesPerPixel = webgl::BytesPerPixel(pi); const uint8_t* uploadPtr = mPtr; UniqueBuffer tempBuffer; do { if (!mIsClientData || !mPtr) break; if (!webgl->mPixelStore_FlipY && !webgl->mPixelStore_PremultiplyAlpha) { break; } if (webgl->mPixelStore_UnpackImageHeight || webgl->mPixelStore_UnpackSkipImages || webgl->mPixelStore_UnpackRowLength || webgl->mPixelStore_UnpackSkipRows || webgl->mPixelStore_UnpackSkipPixels) { webgl->ErrorInvalidOperation("%s: Non-DOM-Element uploads with alpha-premult" " or y-flip do not support subrect selection.", funcName); return false; } webgl->GenerateWarning("%s: Alpha-premult and y-flip are deprecated for" " non-DOM-Element uploads.", funcName); const uint32_t rowLength = mWidth; const uint32_t rowCount = mHeight * mDepth; const auto stride = RoundUpToMultipleOf(rowLength * bytesPerPixel, mAlignment); if (!ConvertIfNeeded(webgl, funcName, rowLength, rowCount, format, mPtr, stride, format, stride, &uploadPtr, &tempBuffer)) { return false; } } while (false); ////// const auto& gl = webgl->gl; bool useParanoidHandling = false; if (mNeedsExactUpload && webgl->mBoundPixelUnpackBuffer) { webgl->GenerateWarning("%s: Uploads from a buffer with a final row with a byte" " count smaller than the row stride can incur extra" " overhead.", funcName); if (gl->WorkAroundDriverBugs()) { useParanoidHandling |= (gl->Vendor() == gl::GLVendor::NVIDIA); } } if (!useParanoidHandling) { if (webgl->mBoundPixelUnpackBuffer) { gl->fBindBuffer(LOCAL_GL_PIXEL_UNPACK_BUFFER, webgl->mBoundPixelUnpackBuffer->mGLName); } *out_error = DoTexOrSubImage(isSubImage, gl, target, level, dui, xOffset, yOffset, zOffset, mWidth, mHeight, mDepth, uploadPtr); if (webgl->mBoundPixelUnpackBuffer) { gl->fBindBuffer(LOCAL_GL_PIXEL_UNPACK_BUFFER, 0); } return true; } ////// MOZ_ASSERT(webgl->mBoundPixelUnpackBuffer); if (!isSubImage) { // Alloc first to catch OOMs. AssertUintParamCorrect(gl, LOCAL_GL_PIXEL_UNPACK_BUFFER, 0); *out_error = DoTexOrSubImage(false, gl, target, level, dui, xOffset, yOffset, zOffset, mWidth, mHeight, mDepth, nullptr); if (*out_error) return true; } const ScopedLazyBind bindPBO(gl, LOCAL_GL_PIXEL_UNPACK_BUFFER, webgl->mBoundPixelUnpackBuffer); ////// // Make our sometimes-implicit values explicit. Also this keeps them constant when we // ask for height=mHeight-1 and such. gl->fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, mRowLength); gl->fPixelStorei(LOCAL_GL_UNPACK_IMAGE_HEIGHT, mImageHeight); if (mDepth > 1) { *out_error = DoTexOrSubImage(true, gl, target, level, dui, xOffset, yOffset, zOffset, mWidth, mHeight, mDepth-1, uploadPtr); } // Skip the images we uploaded. gl->fPixelStorei(LOCAL_GL_UNPACK_SKIP_IMAGES, mSkipImages + mDepth - 1); if (mHeight > 1) { *out_error = DoTexOrSubImage(true, gl, target, level, dui, xOffset, yOffset, zOffset+mDepth-1, mWidth, mHeight-1, 1, uploadPtr); } const auto totalSkipRows = CheckedUint32(mSkipImages) * mImageHeight + mSkipRows; const auto totalFullRows = CheckedUint32(mDepth - 1) * mImageHeight + mHeight - 1; const auto tailOffsetRows = totalSkipRows + totalFullRows; const auto bytesPerRow = CheckedUint32(mRowLength) * bytesPerPixel; const auto rowStride = RoundUpToMultipleOf(bytesPerRow, mAlignment); if (!rowStride.isValid()) { MOZ_CRASH("Should be checked earlier."); } const auto tailOffsetBytes = tailOffsetRows * rowStride; uploadPtr += tailOffsetBytes.value(); ////// gl->fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT, 1); // No stride padding. gl->fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, 0); // No padding in general. gl->fPixelStorei(LOCAL_GL_UNPACK_SKIP_IMAGES, 0); // Don't skip images, gl->fPixelStorei(LOCAL_GL_UNPACK_SKIP_ROWS, 0); // or rows. // Keep skipping pixels though! *out_error = DoTexOrSubImage(true, gl, target, level, dui, xOffset, yOffset+mHeight-1, zOffset+mDepth-1, mWidth, 1, 1, uploadPtr); // Reset all our modified state. gl->fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT, webgl->mPixelStore_UnpackAlignment); gl->fPixelStorei(LOCAL_GL_UNPACK_IMAGE_HEIGHT, webgl->mPixelStore_UnpackImageHeight); gl->fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, webgl->mPixelStore_UnpackRowLength); gl->fPixelStorei(LOCAL_GL_UNPACK_SKIP_IMAGES, webgl->mPixelStore_UnpackSkipImages); gl->fPixelStorei(LOCAL_GL_UNPACK_SKIP_ROWS, webgl->mPixelStore_UnpackSkipRows); return true; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // TexUnpackImage TexUnpackImage::TexUnpackImage(const WebGLContext* webgl, TexImageTarget target, uint32_t width, uint32_t height, uint32_t depth, layers::Image* image, bool isAlphaPremult) : TexUnpackBlob(webgl, target, image->GetSize().width, width, height, depth, isAlphaPremult) , mImage(image) { } TexUnpackImage::~TexUnpackImage() { } bool TexUnpackImage::Validate(WebGLContext* webgl, const char* funcName, const webgl::PackingInfo& pi) { if (!ValidatePIForDOM(webgl, funcName, pi)) return false; const auto fullRows = mImage->GetSize().height; return ValidateUnpackPixels(webgl, funcName, fullRows, 0, this); } bool TexUnpackImage::TexOrSubImage(bool isSubImage, bool needsRespec, const char* funcName, WebGLTexture* tex, TexImageTarget target, GLint level, const webgl::DriverUnpackInfo* dui, GLint xOffset, GLint yOffset, GLint zOffset, GLenum* const out_error) const { MOZ_ASSERT_IF(needsRespec, !isSubImage); WebGLContext* webgl = tex->mContext; gl::GLContext* gl = webgl->GL(); gl->MakeCurrent(); if (needsRespec) { *out_error = DoTexOrSubImage(isSubImage, gl, target.get(), level, dui, xOffset, yOffset, zOffset, mWidth, mHeight, mDepth, nullptr); if (*out_error) return true; } do { if (mDepth != 1) break; const auto& dstIsPremult = webgl->mPixelStore_PremultiplyAlpha; if (mSrcIsPremult != dstIsPremult) break; if (dui->unpackFormat != LOCAL_GL_RGB && dui->unpackFormat != LOCAL_GL_RGBA) break; if (dui->unpackType != LOCAL_GL_UNSIGNED_BYTE) break; gl::ScopedFramebuffer scopedFB(gl); gl::ScopedBindFramebuffer bindFB(gl, scopedFB.FB()); { gl::GLContext::LocalErrorScope errorScope(*gl); gl->fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0, target.get(), tex->mGLName, level); if (errorScope.GetError()) break; } const GLenum status = gl->fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER); if (status != LOCAL_GL_FRAMEBUFFER_COMPLETE) break; const gfx::IntSize destSize(mWidth, mHeight); const auto dstOrigin = (webgl->mPixelStore_FlipY ? gl::OriginPos::TopLeft : gl::OriginPos::BottomLeft); if (!gl->BlitHelper()->BlitImageToFramebuffer(mImage, destSize, scopedFB.FB(), dstOrigin)) { break; } // Blitting was successful, so we're done! *out_error = 0; return true; } while (false); webgl->GenerateWarning("%s: Failed to hit GPU-copy fast-path. Falling back to CPU" " upload.", funcName); const RefPtr<gfx::SourceSurface> surf = mImage->GetAsSourceSurface(); RefPtr<gfx::DataSourceSurface> dataSurf; if (surf) { // WARNING: OSX can lose our MakeCurrent here. dataSurf = surf->GetDataSurface(); } if (!dataSurf) { webgl->ErrorOutOfMemory("%s: GetAsSourceSurface or GetDataSurface failed after" " blit failed for TexUnpackImage.", funcName); return false; } const TexUnpackSurface surfBlob(webgl, target, mWidth, mHeight, mDepth, dataSurf, mSrcIsPremult); return surfBlob.TexOrSubImage(isSubImage, needsRespec, funcName, tex, target, level, dui, xOffset, yOffset, zOffset, out_error); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // TexUnpackSurface TexUnpackSurface::TexUnpackSurface(const WebGLContext* webgl, TexImageTarget target, uint32_t width, uint32_t height, uint32_t depth, gfx::DataSourceSurface* surf, bool isAlphaPremult) : TexUnpackBlob(webgl, target, surf->GetSize().width, width, height, depth, isAlphaPremult) , mSurf(surf) { } ////////// static bool GetFormatForSurf(gfx::SourceSurface* surf, WebGLTexelFormat* const out_texelFormat, uint8_t* const out_bpp) { const auto surfFormat = surf->GetFormat(); switch (surfFormat) { case gfx::SurfaceFormat::B8G8R8A8: *out_texelFormat = WebGLTexelFormat::BGRA8; *out_bpp = 4; return true; case gfx::SurfaceFormat::B8G8R8X8: *out_texelFormat = WebGLTexelFormat::BGRX8; *out_bpp = 4; return true; case gfx::SurfaceFormat::R8G8B8A8: *out_texelFormat = WebGLTexelFormat::RGBA8; *out_bpp = 4; return true; case gfx::SurfaceFormat::R8G8B8X8: *out_texelFormat = WebGLTexelFormat::RGBX8; *out_bpp = 4; return true; case gfx::SurfaceFormat::R5G6B5_UINT16: *out_texelFormat = WebGLTexelFormat::RGB565; *out_bpp = 2; return true; case gfx::SurfaceFormat::A8: *out_texelFormat = WebGLTexelFormat::A8; *out_bpp = 1; return true; case gfx::SurfaceFormat::YUV: // Ugh... NS_ERROR("We don't handle uploads from YUV sources yet."); // When we want to, check out gfx/ycbcr/YCbCrUtils.h. (specifically // GetYCbCrToRGBDestFormatAndSize and ConvertYCbCrToRGB) return false; default: return false; } } ////////// bool TexUnpackSurface::Validate(WebGLContext* webgl, const char* funcName, const webgl::PackingInfo& pi) { if (!ValidatePIForDOM(webgl, funcName, pi)) return false; const auto fullRows = mSurf->GetSize().height; return ValidateUnpackPixels(webgl, funcName, fullRows, 0, this); } bool TexUnpackSurface::TexOrSubImage(bool isSubImage, bool needsRespec, const char* funcName, WebGLTexture* tex, TexImageTarget target, GLint level, const webgl::DriverUnpackInfo* dstDUI, GLint xOffset, GLint yOffset, GLint zOffset, GLenum* const out_error) const { const auto& webgl = tex->mContext; //// const auto rowLength = mSurf->GetSize().width; const auto rowCount = mSurf->GetSize().height; const auto& dstPI = dstDUI->ToPacking(); const auto& dstBPP = webgl::BytesPerPixel(dstPI); const auto dstFormat = FormatForPackingInfo(dstPI); //// WebGLTexelFormat srcFormat; uint8_t srcBPP; if (!GetFormatForSurf(mSurf, &srcFormat, &srcBPP)) { webgl->ErrorImplementationBug("%s: GetFormatForSurf failed for" " WebGLTexelFormat::%u.", funcName, uint32_t(mSurf->GetFormat())); return false; } gfx::DataSourceSurface::ScopedMap map(mSurf, gfx::DataSourceSurface::MapType::READ); if (!map.IsMapped()) { webgl->ErrorOutOfMemory("%s: Failed to map source surface for upload.", funcName); return false; } const auto& srcBegin = map.GetData(); const auto& srcStride = map.GetStride(); //// const auto srcRowLengthBytes = rowLength * srcBPP; const uint8_t maxGLAlignment = 8; uint8_t srcAlignment = 1; for (; srcAlignment <= maxGLAlignment; srcAlignment *= 2) { const auto strideGuess = RoundUpToMultipleOf(srcRowLengthBytes, srcAlignment); if (strideGuess == srcStride) break; } const uint32_t dstAlignment = (srcAlignment > maxGLAlignment) ? 1 : srcAlignment; const auto dstRowLengthBytes = rowLength * dstBPP; const auto dstStride = RoundUpToMultipleOf(dstRowLengthBytes, dstAlignment); //// const uint8_t* dstBegin = srcBegin; UniqueBuffer tempBuffer; if (!ConvertIfNeeded(webgl, funcName, rowLength, rowCount, srcFormat, srcBegin, srcStride, dstFormat, dstStride, &dstBegin, &tempBuffer)) { return false; } //// const auto& gl = webgl->gl; MOZ_ALWAYS_TRUE( gl->MakeCurrent() ); gl->fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT, dstAlignment); if (webgl->IsWebGL2()) { gl->fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, rowLength); } *out_error = DoTexOrSubImage(isSubImage, gl, target.get(), level, dstDUI, xOffset, yOffset, zOffset, mWidth, mHeight, mDepth, dstBegin); gl->fPixelStorei(LOCAL_GL_UNPACK_ALIGNMENT, webgl->mPixelStore_UnpackAlignment); if (webgl->IsWebGL2()) { gl->fPixelStorei(LOCAL_GL_UNPACK_ROW_LENGTH, webgl->mPixelStore_UnpackRowLength); } return true; } } // namespace webgl } // namespace mozilla
Yukarumya/Yukarum-Redfoxes
dom/canvas/TexUnpackBlob.cpp
C++
mpl-2.0
28,368
// Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. package main import ( "time" "github.com/MustWin/baremetal-sdk-go" "github.com/hashicorp/terraform/helper/schema" "github.com/oracle/terraform-provider-baremetal/options" "github.com/oracle/terraform-provider-baremetal/client" "github.com/oracle/terraform-provider-baremetal/crud" ) func RouteTableDatasource() *schema.Resource { return &schema.Resource{ Read: readRouteTables, Schema: map[string]*schema.Schema{ "compartment_id": { Type: schema.TypeString, Required: true, }, "limit": { Type: schema.TypeInt, Optional: true, }, "page": { Type: schema.TypeString, Optional: true, }, "route_tables": { Type: schema.TypeList, Computed: true, Elem: RouteTableResource(), }, "vcn_id": { Type: schema.TypeString, Required: true, }, }, } } func readRouteTables(d *schema.ResourceData, m interface{}) (e error) { client := m.(client.BareMetalClient) reader := &RouteTableDatasourceCrud{} reader.D = d reader.Client = client return crud.ReadResource(reader) } type RouteTableDatasourceCrud struct { crud.BaseCrud Res *baremetal.ListRouteTables } func (s *RouteTableDatasourceCrud) Get() (e error) { compartmentID := s.D.Get("compartment_id").(string) vcnID := s.D.Get("vcn_id").(string) opts := &baremetal.ListOptions{} options.SetListOptions(s.D, opts) s.Res = &baremetal.ListRouteTables{RouteTables: []baremetal.RouteTable{}} for { var list *baremetal.ListRouteTables if list, e = s.Client.ListRouteTables(compartmentID, vcnID, opts); e != nil { break } s.Res.RouteTables = append(s.Res.RouteTables, list.RouteTables...) if hasNextPage := options.SetNextPageOption(list.NextPage, &opts.PageListOptions); !hasNextPage { break } } return } func (s *RouteTableDatasourceCrud) SetData() { if s.Res != nil { s.D.SetId(time.Now().UTC().String()) resources := []map[string]interface{}{} for _, v := range s.Res.RouteTables { rules := []map[string]interface{}{} for _, val := range v.RouteRules { rule := map[string]interface{}{ "cidr_block": val.CidrBlock, "network_entity_id": val.NetworkEntityID, } rules = append(rules, rule) } res := map[string]interface{}{ "compartment_id": v.CompartmentID, "display_name": v.DisplayName, "id": v.ID, "route_rules": rules, "time_modified": v.TimeModified.String(), "state": v.State, "time_created": v.TimeCreated.String(), } resources = append(resources, res) } s.D.Set("route_tables", resources) } return }
MustWin/terraform-provider-baremetal
data_source_obmcs_core_route_table.go
GO
mpl-2.0
2,688
<?php declare(strict_types=1); namespace Outplay\RiotApi; use GuzzleHttp\Client; use Psr\Http\Message\ResponseInterface; final class GuzzleHttpClient implements Interfaces\HttpClient { protected $client; public function __construct() { $this->setClient(new Client()); } public function setClient(Client $client) { $this->client = $client; } public function fetch(string $url) : ResponseInterface { return $this->client->get($url); } }
kcjpop/riot-api
src/GuzzleHttpClient.php
PHP
mpl-2.0
506
/* * Copyright ©1998-2022 by Richard A. Wilkes. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, version 2.0. If a copy of the MPL was not distributed with * this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This Source Code Form is "Incompatible With Secondary Licenses", as * defined by the Mozilla Public License, version 2.0. */ package com.trollworks.gcs.expression.function; import com.trollworks.gcs.expression.ArgumentTokenizer; import com.trollworks.gcs.expression.EvaluationException; import com.trollworks.gcs.expression.Evaluator; public class Log implements ExpressionFunction { @Override public final String getName() { return "log"; } @Override public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException { return Double.valueOf(Math.log(ArgumentTokenizer.getDoubleArgument(evaluator, arguments))); } }
richardwilkes/gcs
com.trollworks.gcs/src/com/trollworks/gcs/expression/function/Log.java
Java
mpl-2.0
977
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (C) 2010, 2011, 2012, Pyravlos Team * * http://www.strabon.di.uoa.gr/ */ package eu.earthobservatory.runtime.generaldb; public class InvalidDatasetFormatFault extends Exception { }
wx1988/strabon
runtime/src/main/java/eu/earthobservatory/runtime/generaldb/InvalidDatasetFormatFault.java
Java
mpl-2.0
410
import { Component, ViewChild } from '@angular/core'; import { Nav, Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { HomePage } from '../pages/home/home'; import { Userpage } from '../pages/userpage/userpage'; import { Projects } from '../pages/projects/projects'; import { Customers } from '../pages/customers/customers'; import { Statistics } from '../pages/statistics/statistics'; import { Sms } from '../pages/sms/sms'; //import { LoginPage } from '../pages/login/login'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = HomePage; pages: Array<{title: string, component: any}>; constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); // used for an example of ngFor and navigation this.pages = [ { title: 'Dashboard', component: Userpage }, { title: 'Müşteriler', component: Customers}, { title: 'Projeler', component: Projects }, { title: 'İstatistikler', component: Statistics }, { title: 'SMS', component: Sms }, ]; } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } }
wemrekurt/cariapp
src/app/app.component.ts
TypeScript
mpl-2.0
1,692
# flake8: noqa from bedrock.mozorg.templatetags import misc, social_widgets
sgarrity/bedrock
bedrock/mozorg/templatetags/__init__.py
Python
mpl-2.0
76
"use strict"; let Ci = Components.interfaces; let Cc = Components.classes; let Cu = Components.utils; let Cr = Components.results; var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader); loader.loadSubScript("resource://emic/sugar.js"); Cu.import("resource://emic/mailtodate.js"); var myStateListener = { init: function(e){ gMsgCompose.RegisterStateListener(myStateListener); emicComposeObj.init(); }, NotifyComposeFieldsReady: function() { }, NotifyComposeBodyReady: function() { }, ComposeProcessDone: function(aResult) { }, SaveInFolderDone: function(folderURI) { } }; var emicComposeObj = { consoleService: Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService), promptService: Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService), prefs: Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.emic."), global_strBundle: null, compose_strBundle: null, expdatestr: "", menu_insert_never: null, menu_insert_now: null, menu_insert_custom: null, menu_context_never: null, menu_context_now: null, menu_context_custom: null, menu_select_nothing: function(){ this.menu_insert_never .setAttribute("checked", "false"); this.menu_context_never .setAttribute("checked", "false"); this.menu_insert_now .setAttribute("checked", "false"); this.menu_context_now .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "false"); this.menu_context_custom .setAttribute("checked", "false"); }, menu_select_custom: function(){ this.menu_insert_never .setAttribute("checked", "false"); this.menu_context_never .setAttribute("checked", "false"); this.menu_insert_now .setAttribute("checked", "false"); this.menu_context_now .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "true"); this.menu_context_custom .setAttribute("checked", "true"); }, menu_select_never: function(){ this.menu_insert_now .setAttribute("checked", "false"); this.menu_context_now .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "false"); this.menu_context_custom .setAttribute("checked", "false"); this.menu_insert_never .setAttribute("checked", "true"); this.menu_context_never .setAttribute("checked", "true"); }, menu_select_now: function(){ this.menu_insert_never .setAttribute("checked", "false"); this.menu_context_never .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "false"); this.menu_context_custom .setAttribute("checked", "false"); this.menu_insert_now .setAttribute("checked", "true"); this.menu_context_now .setAttribute("checked", "true"); }, setExpirationDateCustom: function() { // this.consoleService.logStringMessage("emicComposeObj.setExpirationDateCustom() called"); // this.consoleService.logStringMessage("new Date(this.expdatestr): " + new Date(this.expdatestr).toString()); // this.consoleService.logStringMessage("subject: " + document.getElementById("msgSubject").value); // this.consoleService.logStringMessage("body: " + GetCurrentEditor().outputToString('text/plain',4)); var mailtodate = new MailToDate(document.getElementById("msgSubject").value, GetCurrentEditor().outputToString('text/plain',4)); //call Dialog: var params = {inn:{customdate:(new Date(this.expdatestr)), suggestions: mailtodate.extractDates(window.navigator.language)}, out:null}; window.openDialog("chrome://emic/content/dialogcustomdate.xul","","chrome, dialog, modal, resizable=no", params).focus(); if(params.out) { // User clicked ok. Process changed arguments; e.g. write them to disk or whatever if(params.out.datestr == this.global_strBundle.getString("global.identifier.never")) this.menu_select_never(); else if(params.out.date.isPast()) this.menu_select_now(); else this.menu_select_custom(); this.expdatestr = params.out.datestr; // this.consoleService.logStringMessage("this.expdatestr: " + this.expdatestr); } else { // User clicked cancel. Typically, nothing is done here. } }, setExpirationDateNever: function() { // this.consoleService.logStringMessage("emicComposeObj.setExpirationDateNever() called"); this.menu_select_never(); this.expdatestr = this.global_strBundle.getString("global.identifier.never"); }, setExpirationDateNow: function() { // this.consoleService.logStringMessage("emicComposeObj.setExpirationDateNow() called"); this.menu_select_now(); this.expdatestr = Date.create().toString(); }, send_event_listener: function(e) { // this.consoleService.logStringMessage("emicComposeObj.send_event_handler(e) called, e: " + e); // this.consoleService.logStringMessage("e.detail: " + e.detail); // this.consoleService.logStringMessage("e.view: " + e.view); if(this.expdatestr.length <= 0){ var result = this.promptService.confirmEx( window, this.compose_strBundle.getString("compose.noexpirationdateset.confirm.title"), this.compose_strBundle.getString("compose.noexpirationdateset.confirm.text"), Ci.nsIPromptService.STD_YES_NO_BUTTONS, null,null,null,null,{} ); if(result == 0) { // this.consoleService.logStringMessage("subject: " + gMsgCompose.compFields.subject); // this.consoleService.logStringMessage("body: " + GetCurrentEditor().outputToString('text/plain',4)); var mailtodate = new MailToDate(gMsgCompose.compFields.subject, GetCurrentEditor().outputToString('text/plain',4)); var params = {inn:{customdate:null, suggestions:mailtodate.extractDates(window.navigator.language)}, out:null}; window.openDialog("chrome://emic/content/dialogcustomdate.xul","","chrome, dialog, modal, resizable=no", params).focus(); if (params.out) { this.expdatestr = params.out.datestr; } else { this.expdatestr = this.global_strBundle.getString("global.identifier.never"); } } else { this.expdatestr = this.global_strBundle.getString("global.identifier.never"); } } if(this.expdatestr.length > 0 && this.expdatestr != this.global_strBundle.getString("global.identifier.never")) { var headeridentifieroutlook = this.global_strBundle.getString("global.identifier.expirationdate.mailheader.outlook"); if(this.prefs.getBoolPref("compose.compatiblewithoutlook") && !gMsgCompose.compFields.otherRandomHeaders.contains(headeridentifieroutlook)) gMsgCompose.compFields.otherRandomHeaders += headeridentifieroutlook + this.expdatestr + "\r\n"; var headeridentifier = this.global_strBundle.getString("global.identifier.expirationdate.mailheader"); if(!gMsgCompose.compFields.otherRandomHeaders.contains(headeridentifier)) gMsgCompose.compFields.otherRandomHeaders += headeridentifier + this.expdatestr + "\r\n"; } }, init: function() { // this.consoleService.logStringMessage("emicComposeObj.init() called"); // this.setExpirationDateNever(); //not optimal this.expdatestr = ""; // this.consoleService.logStringMessage("expdatestr: " + this.expdatestr); this.global_strBundle = document.getElementById("emic-strings-global"); this.compose_strBundle = document.getElementById("emic-strings-compose"); this.menu_insert_never = document.getElementById("emic-menu-compose-insert-never"); this.menu_insert_now = document.getElementById("emic-menu-compose-insert-now"); this.menu_insert_custom = document.getElementById("emic-menu-compose-insert-custom"); this.menu_context_never = document.getElementById("emic-menu-compose-context-never"); this.menu_context_now = document.getElementById("emic-menu-compose-context-now"); this.menu_context_custom = document.getElementById("emic-menu-compose-context-custom"); this.menu_select_nothing(); } } window.addEventListener( "compose-send-message", function(e){emicComposeObj.send_event_listener(e);}, true); window.addEventListener( "compose-window-init", myStateListener.init, true);
XxJo3yxX/emic
content/compose.js
JavaScript
mpl-2.0
8,930
const products = [{id : 'classic', name : 'Classic Ad', price : 269.99}, {id : 'standout', name : 'Standout Ad', price : 322.99}, {id : 'premium', name : 'Premium Ad', price : 394.99}] class ProductDao { constructor() { console.log('Instantiating ProductDao') } listAll(){ return products } findById(id){ } } module.exports = new ProductDao
marcos-goes/ads-checkout-nodejs
dao/ProductDao.js
JavaScript
mpl-2.0
408
package com.modelo; import java.nio.charset.StandardCharsets; import javax.print.Doc; import javax.print.DocFlavor; import javax.print.PrintException; import javax.print.PrintService; import javax.print.SimpleDoc; /** * * Etiqueta class * Clase donde se inicializa el tamaño de la letra y la posicion en la que van a * estar los valores extraidos de la lista, ademas esta clase se ecargar de mandar * estos valores a la impresora. * * * @author Jose Rene Palacios Ruiz * @version 1.0 * @since 19-06-2015 */ public class Etiqueta { /** * * Metodo encargada de imprimir la etiqueta; se le pasan * ciertos parametros al mandarlo llamar * * @param printService Servicio de impresora al que se le va a mandar la informacion * @param date Inicializador de la fecha * @param mA Amperaje del archivo .cvs * @return result */ public boolean impEtiqueta(PrintService printService, String date, String mA) { if (printService == null || date == null || mA == null) { return false; } String command = "^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR5,5~SD15^JUS^LRN^CI0^XZ^XA^MMT^PW203^LL0102^LS0^FT40,71^A0N,20,19^FH\\^FD"+date+"^FS^FT44,45^A0N,28,28^FH\\^FD"+mA+"^FS^PQ1,0,1,Y^XZ" ; byte[] data; data = command.getBytes(StandardCharsets.US_ASCII); Doc doc = new SimpleDoc(data, DocFlavor.BYTE_ARRAY.AUTOSENSE, null); boolean result = false; try { printService.createPrintJob().print(doc, null); result = true; } catch (PrintException e) { e.printStackTrace(); } return result; } }
jreneruiz/Impresor-de-etiquetas-zebra
src/com/modelo/Etiqueta.java
Java
mpl-2.0
1,643
import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ model() { const job = this.modelFor('jobs.job'); return RSVP.all([job.get('deployments'), job.get('versions')]).then(() => job); }, });
Ashald/nomad
ui/app/routes/jobs/job/deployments.js
JavaScript
mpl-2.0
238
public class Solution { public int findLUSlength(String[] strs) { Arrays.sort(strs, new Comparator<String>(){ public int compare(String a, String b) { if (a.length() != b.length()) { return b.length()-a.length(); } else { return a.compareTo(b); } } }); for (int i=0; i<strs.length; i++) { boolean flag = (i == strs.length-1 || !strs[i].equals(strs[i+1])); if (flag) { for (int j=i-1; j>=0; j--) { if (isSub(strs[i], strs[j])) { flag = false; break; } } } if (flag) { return strs[i].length(); } } return -1; } private boolean isSub(String a, String b) { if (a.length() <= b.length()) { for (int state=1, i=0; i<b.length(); i++) { int next = 1; for (int j=0; j<=i && j<a.length(); j++) { if (0 != (state&(1<<j)) && a.charAt(j) == b.charAt(i)) { if (j == a.length()-1) { return true; } next |= (1<<(j+1)); } } state |= next; } } return false; } }
DevinZ1993/LeetCode-Solutions
java/522.java
Java
mpl-2.0
1,490
package plugin import ( "context" "errors" "fmt" "math" "sync/atomic" "time" "github.com/hashicorp/vault/sdk/framework" "github.com/hashicorp/vault/sdk/logical" ) func (b *backend) pathRotateCredentials() *framework.Path { return &framework.Path{ Pattern: "rotate-root", Operations: map[logical.Operation]framework.OperationHandler{ logical.CreateOperation: &framework.PathOperation{ Callback: b.pathRotateCredentialsUpdate, ForwardPerformanceStandby: true, ForwardPerformanceSecondary: true, }, logical.ReadOperation: &framework.PathOperation{ Callback: b.pathRotateCredentialsUpdate, ForwardPerformanceStandby: true, ForwardPerformanceSecondary: true, }, logical.UpdateOperation: &framework.PathOperation{ Callback: b.pathRotateCredentialsUpdate, ForwardPerformanceStandby: true, ForwardPerformanceSecondary: true, }, }, HelpSynopsis: pathRotateCredentialsUpdateHelpSyn, HelpDescription: pathRotateCredentialsUpdateHelpDesc, } } func (b *backend) pathRotateCredentialsUpdate(ctx context.Context, req *logical.Request, _ *framework.FieldData) (*logical.Response, error) { engineConf, err := readConfig(ctx, req.Storage) if err != nil { return nil, err } if engineConf == nil { return nil, errors.New("the config is currently unset") } newPassword, err := GeneratePassword(ctx, engineConf.PasswordConf, b.System()) if err != nil { return nil, err } oldPassword := engineConf.ADConf.BindPassword if !atomic.CompareAndSwapInt32(b.rotateRootLock, 0, 1) { resp := &logical.Response{} resp.AddWarning("Root password rotation is already in progress.") return resp, nil } defer atomic.CompareAndSwapInt32(b.rotateRootLock, 1, 0) // Update the password remotely. if err := b.client.UpdateRootPassword(engineConf.ADConf, engineConf.ADConf.BindDN, newPassword); err != nil { return nil, err } engineConf.ADConf.BindPassword = newPassword // Update the password locally. if pwdStoringErr := writeConfig(ctx, req.Storage, engineConf); pwdStoringErr != nil { // We were unable to store the new password locally. We can't continue in this state because we won't be able // to roll any passwords, including our own to get back into a state of working. So, we need to roll back to // the last password we successfully got into storage. if rollbackErr := b.rollBackPassword(ctx, engineConf, oldPassword); rollbackErr != nil { return nil, fmt.Errorf("unable to store new password due to %s and unable to return to previous password due to %s, configure a new binddn and bindpass to restore active directory function", pwdStoringErr, rollbackErr) } return nil, fmt.Errorf("unable to update password due to storage err: %s", pwdStoringErr) } // Respond with a 204. return nil, nil } // rollBackPassword uses naive exponential backoff to retry updating to an old password, // because Active Directory may still be propagating the previous password change. func (b *backend) rollBackPassword(ctx context.Context, engineConf *configuration, oldPassword string) error { var err error for i := 0; i < 10; i++ { waitSeconds := math.Pow(float64(i), 2) timer := time.NewTimer(time.Duration(waitSeconds) * time.Second) select { case <-timer.C: case <-ctx.Done(): // Outer environment is closing. return fmt.Errorf("unable to roll back password because enclosing environment is shutting down") } if err = b.client.UpdateRootPassword(engineConf.ADConf, engineConf.ADConf.BindDN, oldPassword); err == nil { // Success. return nil } } // Failure after looping. return err } const pathRotateCredentialsUpdateHelpSyn = ` Request to rotate the root credentials. ` const pathRotateCredentialsUpdateHelpDesc = ` This path attempts to rotate the root credentials. `
hartsock/vault
vendor/github.com/hashicorp/vault-plugin-secrets-ad/plugin/path_rotate_root_creds.go
GO
mpl-2.0
3,863
import animate; import event.Emitter as Emitter; import device; import ui.View; import ui.ImageView; import ui.TextView; import src.Match3Core as Core; import src.Utils as Utils; //var Chance = require('chance'); //Some constants var CoreGame = new Core(); var level = new Core(); //var chance = new Chance(); /* The Game Screen code. * The child of the main application in * the game. Everything else is a child * of game so it is all visible. */ exports = Class(ui.View, function(supr) { this.init = function(opts) { opts = merge(opts, { x: 0, y: 0, width: 576, height: 1024, backgroundColor: '#37b34a' }); supr(this, 'init', [opts]); this.build(); }; this.build = function() { this.on('app:start', start_game_flow.bind(this)); }; // Main Menu Functions this.SetMenu = function(menu) { this._menu = menu; }; this.GetMenu = function() { return this._menu; }; this.OnLaunchMainMenu = function(){ this.emit('MainMenu'); }; }); /* function ReadyGame() { CoreGame.InitializeBoard(); CoreGame.CreateLevel(); //Find Initial Moves and Clusters CoreGame.FindMoves(); CoreGame.FindClusters(); } */ // Starts the game function start_game_flow() { CoreGame.ReadyGame(); play_game(this); } // Game play function play_game() { if(CoreGame.moves.length === 0) { end_game_flow.call(this); } } // function tick() {} // function update_countdown() {} // Game End function end_game_flow() { //slight delay before allowing a tap reset setTimeout(emit_endgame_event.bind(this), 2000); } function emit_endgame_event() { this.once('InputSelect', function() { this.emit('gamescreen:end'); reset_game.call(this); }); } function reset_game() {}
CoderBear/HoneyBear
src/GameScreen.js
JavaScript
mpl-2.0
1,811
// This file is part of UniLib <http://github.com/ufal/unilib/>. // // Copyright 2014 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // // UniLib version: $UNILIB_VERSION // Unicode version: $UNICODE_VERSION #include "version.h" namespace ufal { namespace unilib { // Returns current version. version version::current() { return {$UNILIB_MAJOR_VERSION, $UNILIB_MINOR_VERSION, $UNILIB_PATCH_VERSION, $UNILIB_PRERELEASE_VERSION}; } } // namespace unilib } // namespace ufal
ufal/unilib
gen/template/version.cpp
C++
mpl-2.0
766
/* * Copyright Aduna (http://www.aduna-software.com/) (c) 2008. * * Licensed under the Aduna BSD-style license. */ package org.openrdf.sail.postgis; import java.sql.SQLException; import org.openrdf.sail.generaldb.GeneralDBSqlTable; import eu.earthobservatory.constants.GeoConstants; /** * Converts table names to lower-case and include the analyse optimisation. * * @author James Leigh * */ public class PostGISSqlTable extends GeneralDBSqlTable { public PostGISSqlTable(String name) { super(name.toLowerCase()); } @Override protected String buildOptimize() throws SQLException { return "VACUUM ANALYZE " + getName(); } @Override protected String buildClear() { return "TRUNCATE " + getName(); } @Override public String buildGeometryCollumn() { return "SELECT AddGeometryColumn('','geo_values','strdfgeo',4326,'GEOMETRY',2)"; } @Override public String buildIndexOnGeometryCollumn() { return "CREATE INDEX geoindex ON geo_values USING GIST (strdfgeo)"; } @Override public String buildInsertGeometryValue() { Integer srid= GeoConstants.defaultSRID; return " (id, strdfgeo,srid) VALUES (?,ST_Transform(ST_GeomFromWKB(?,?),"+srid+"),?)"; } @Override public String buildInsertValue(String type) { return " (id, value) VALUES ( ?, ?) "; } @Override protected String buildCreateTemporaryTable(CharSequence columns) { StringBuilder sb = new StringBuilder(); sb.append("CREATE TEMPORARY TABLE ").append(getName()); sb.append(" (\n").append(columns).append(")"); return sb.toString(); } @Override public String buildDummyFromAndWhere(String fromDummy) { StringBuilder sb = new StringBuilder(256); sb.append(fromDummy); sb.append("\nWHERE 1=0"); return sb.toString(); } @Override public String buildDynamicParameterInteger() { return "?"; } @Override public String buildWhere() { return " WHERE (1=1) "; } }
wx1988/strabon
postgis/src/main/java/org/openrdf/sail/postgis/PostGISSqlTable.java
Java
mpl-2.0
1,904
var fs = require("fs"); var path = require("path"); var _ = require("underscore"); var chai = require("chai"); var expect = chai.expect; var profile = require("../../lib/profile"); var PREFS = require("../../data/preferences"); var simpleXpiPath = path.join(__dirname, '..', 'xpis', 'simple-addon.xpi'); describe("lib/profile", function () { it("creates a profile and returns the path", function (done) { profile().then(function (profilePath) { var contents = fs.readFileSync(path.join(profilePath, "user.js"), "utf8"); expect(contents).to.be.ok; }) .then(done, done); }); it("creates a profile with proper default preferences (Firefox)", function (done) { profile().then(function (profilePath) { var contents = fs.readFileSync(path.join(profilePath, "user.js"), "utf8"); var defaults = _.extend({}, PREFS.DEFAULT_COMMON_PREFS, PREFS.DEFAULT_FIREFOX_PREFS); comparePrefs(defaults, contents); }) .then(done, done); }); it("creates a profile with an addon installed when given a XPI", function (done) { profile({ xpi: simpleXpiPath }).then(function (profilePath) { var addonPath = path.join(profilePath, "extensions", "simple-addon"); var files = fs.readdirSync(addonPath, "utf8"); var index = fs.readFileSync(path.join(addonPath, "index.js")); var manifest = fs.readFileSync(path.join(addonPath, "package.json")); expect(index).to.be.ok; expect(manifest).to.be.ok; }) .then(done, done); }); }); function comparePrefs (defaults, prefs) { var count = Object.keys(defaults).length; prefs.split("\n").forEach(function (pref) { var parsed = pref.match(/user_pref\("(.*)", "?([^"]*)"?\)\;$/); if (!parsed || parsed.length < 2) return; var key = parsed[1]; var value = parsed[2]; // Cast booleans and numbers in string formative to primitives if (value === 'true') value = true; else if (value === 'false') value = false; else if (!isNaN(parseFloat(value)) && isFinite(value)) value = +value; // TODO need to override firefox-profile setting default prefs // but we still override them if we explicitly set them if (key in defaults) { expect(defaults[key]).to.be.equal(value); --count; } }); expect(count).to.be.equal(0); }
Gozala/jpm
test/unit/test.profile.js
JavaScript
mpl-2.0
2,323
package aws import ( "fmt" "strconv" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elb" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) func resourceAwsLoadBalancerBackendServerPolicies() *schema.Resource { return &schema.Resource{ Create: resourceAwsLoadBalancerBackendServerPoliciesCreate, Read: resourceAwsLoadBalancerBackendServerPoliciesRead, Update: resourceAwsLoadBalancerBackendServerPoliciesCreate, Delete: resourceAwsLoadBalancerBackendServerPoliciesDelete, Schema: map[string]*schema.Schema{ "load_balancer_name": { Type: schema.TypeString, Required: true, }, "policy_names": { Type: schema.TypeSet, Elem: &schema.Schema{Type: schema.TypeString}, Optional: true, Set: schema.HashString, }, "instance_port": { Type: schema.TypeInt, Required: true, }, }, } } func resourceAwsLoadBalancerBackendServerPoliciesCreate(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn loadBalancerName := d.Get("load_balancer_name") policyNames := []*string{} if v, ok := d.GetOk("policy_names"); ok { policyNames = expandStringList(v.(*schema.Set).List()) } setOpts := &elb.SetLoadBalancerPoliciesForBackendServerInput{ LoadBalancerName: aws.String(loadBalancerName.(string)), InstancePort: aws.Int64(int64(d.Get("instance_port").(int))), PolicyNames: policyNames, } if _, err := elbconn.SetLoadBalancerPoliciesForBackendServer(setOpts); err != nil { return fmt.Errorf("Error setting LoadBalancerPoliciesForBackendServer: %s", err) } d.SetId(fmt.Sprintf("%s:%s", *setOpts.LoadBalancerName, strconv.FormatInt(*setOpts.InstancePort, 10))) return resourceAwsLoadBalancerBackendServerPoliciesRead(d, meta) } func resourceAwsLoadBalancerBackendServerPoliciesRead(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn loadBalancerName, instancePort := resourceAwsLoadBalancerBackendServerPoliciesParseId(d.Id()) describeElbOpts := &elb.DescribeLoadBalancersInput{ LoadBalancerNames: []*string{aws.String(loadBalancerName)}, } describeResp, err := elbconn.DescribeLoadBalancers(describeElbOpts) if err != nil { if ec2err, ok := err.(awserr.Error); ok { if ec2err.Code() == "LoadBalancerNotFound" { d.SetId("") return fmt.Errorf("LoadBalancerNotFound: %s", err) } } return fmt.Errorf("Error retrieving ELB description: %s", err) } if len(describeResp.LoadBalancerDescriptions) != 1 { return fmt.Errorf("Unable to find ELB: %#v", describeResp.LoadBalancerDescriptions) } lb := describeResp.LoadBalancerDescriptions[0] policyNames := []*string{} for _, backendServer := range lb.BackendServerDescriptions { if instancePort != strconv.Itoa(int(*backendServer.InstancePort)) { continue } policyNames = append(policyNames, backendServer.PolicyNames...) } d.Set("load_balancer_name", loadBalancerName) instancePortVal, err := strconv.ParseInt(instancePort, 10, 64) if err != nil { return fmt.Errorf("error parsing instance port: %s", err) } d.Set("instance_port", instancePortVal) d.Set("policy_names", flattenStringList(policyNames)) return nil } func resourceAwsLoadBalancerBackendServerPoliciesDelete(d *schema.ResourceData, meta interface{}) error { elbconn := meta.(*AWSClient).elbconn loadBalancerName, instancePort := resourceAwsLoadBalancerBackendServerPoliciesParseId(d.Id()) instancePortInt, err := strconv.ParseInt(instancePort, 10, 64) if err != nil { return fmt.Errorf("Error parsing instancePort as integer: %s", err) } setOpts := &elb.SetLoadBalancerPoliciesForBackendServerInput{ LoadBalancerName: aws.String(loadBalancerName), InstancePort: aws.Int64(instancePortInt), PolicyNames: []*string{}, } if _, err := elbconn.SetLoadBalancerPoliciesForBackendServer(setOpts); err != nil { return fmt.Errorf("Error setting LoadBalancerPoliciesForBackendServer: %s", err) } return nil } func resourceAwsLoadBalancerBackendServerPoliciesParseId(id string) (string, string) { parts := strings.SplitN(id, ":", 2) return parts[0], parts[1] }
kjmkznr/terraform-provider-aws
aws/resource_aws_load_balancer_backend_server_policy.go
GO
mpl-2.0
4,213
using MiNET.Items; namespace MiNET.Blocks { public class EmeraldOre : Block { public EmeraldOre() : base(129) { BlastResistance = 15; Hardness = 3; } public override Item[] GetDrops() { return new[] {ItemFactory.GetItem(388, 0, 1)}; } } }
MiPE-JP/RaNET
src/MiNET/MiNET/Blocks/EmeraldOre.cs
C#
mpl-2.0
267
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package jscover.mozilla.javascript.ast; import jscover.mozilla.javascript.Token; /** * If-else statement. Node type is {@link Token#IF}.<p> * * <pre><i>IfStatement</i> : * <b>if</b> ( Expression ) Statement <b>else</b> Statement * <b>if</b> ( Expression ) Statement</pre> */ public class IfStatement extends AstNode { private AstNode condition; private AstNode thenPart; private int elsePosition = -1; private AstNode elsePart; private int lp = -1; private int rp = -1; { type = Token.IF; } public IfStatement() { } public IfStatement(int pos) { super(pos); } public IfStatement(int pos, int len) { super(pos, len); } /** * Returns if condition */ public AstNode getCondition() { return condition; } /** * Sets if condition. * @throws IllegalArgumentException if {@code condition} is {@code null}. */ public void setCondition(AstNode condition) { assertNotNull(condition); this.condition = condition; condition.setParent(this); } /** * Returns statement to execute if condition is true */ public AstNode getThenPart() { return thenPart; } /** * Sets statement to execute if condition is true * @throws IllegalArgumentException if thenPart is {@code null} */ public void setThenPart(AstNode thenPart) { assertNotNull(thenPart); this.thenPart = thenPart; thenPart.setParent(this); } /** * Returns statement to execute if condition is false */ public AstNode getElsePart() { return elsePart; } /** * Sets statement to execute if condition is false * @param elsePart statement to execute if condition is false. * Can be {@code null}. */ public void setElsePart(AstNode elsePart) { this.elsePart = elsePart; if (elsePart != null) elsePart.setParent(this); } /** * Returns position of "else" keyword, or -1 */ public int getElsePosition() { return elsePosition; } /** * Sets position of "else" keyword, -1 if not present */ public void setElsePosition(int elsePosition) { this.elsePosition = elsePosition; } /** * Returns left paren offset */ public int getLp() { return lp; } /** * Sets left paren offset */ public void setLp(int lp) { this.lp = lp; } /** * Returns right paren position, -1 if missing */ public int getRp() { return rp; } /** * Sets right paren position, -1 if missing */ public void setRp(int rp) { this.rp = rp; } /** * Sets both paren positions */ public void setParens(int lp, int rp) { this.lp = lp; this.rp = rp; } @Override public String toSource(int depth) { String pad = makeIndent(depth); StringBuilder sb = new StringBuilder(32); sb.append(pad); sb.append("if ("); sb.append(condition.toSource(0)); sb.append(") "); if (thenPart.getType() != Token.BLOCK) { sb.append("\n").append(makeIndent(depth + 1)); } sb.append(thenPart.toSource(depth).trim()); if (elsePart != null) { if (thenPart.getType() != Token.BLOCK) { sb.append("\n").append(pad).append("else "); } else { sb.append(" else "); } if (elsePart.getType() != Token.BLOCK && elsePart.getType() != Token.IF) { sb.append("\n").append(makeIndent(depth + 1)); } sb.append(elsePart.toSource(depth).trim()); } sb.append("\n"); return sb.toString(); } /** * Visits this node, the condition, the then-part, and * if supplied, the else-part. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { condition.visit(v); thenPart.visit(v); if (elsePart != null) { elsePart.visit(v); } } } }
tntim96/rhino-jscover-repackaged
src/jscover/mozilla/javascript/ast/IfStatement.java
Java
mpl-2.0
4,530
package com.hserv.coordinatedentry.housingmatching.external; import java.util.List; import com.hserv.coordinatedentry.housingmatching.model.EligibilityRequirementModel; import com.hserv.coordinatedentry.housingmatching.model.HousingInventory; import com.servinglynk.hmis.warehouse.core.model.Session; public interface HousingUnitService { List<HousingInventory> getHousingInventoryList(Session session, String trustedAppId); List<EligibilityRequirementModel> getEligibilityRequirements(Session session, String trustedAppId); }
hserv/coordinated-entry
housing-matching/src/main/java/com/hserv/coordinatedentry/housingmatching/external/HousingUnitService.java
Java
mpl-2.0
553
package aws import ( "fmt" "log" "regexp" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/glue" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func init() { resource.AddTestSweepers("aws_glue_job", &resource.Sweeper{ Name: "aws_glue_job", F: testSweepGlueJobs, }) } func testSweepGlueJobs(region string) error { client, err := sharedClientForRegion(region) if err != nil { return fmt.Errorf("error getting client: %s", err) } conn := client.(*AWSClient).glueconn input := &glue.GetJobsInput{} err = conn.GetJobsPages(input, func(page *glue.GetJobsOutput, lastPage bool) bool { if len(page.Jobs) == 0 { log.Printf("[INFO] No Glue Jobs to sweep") return false } for _, job := range page.Jobs { name := aws.StringValue(job.Name) log.Printf("[INFO] Deleting Glue Job: %s", name) err := deleteGlueJob(conn, name) if err != nil { log.Printf("[ERROR] Failed to delete Glue Job %s: %s", name, err) } } return !lastPage }) if err != nil { if testSweepSkipSweepError(err) { log.Printf("[WARN] Skipping Glue Job sweep for %s: %s", region, err) return nil } return fmt.Errorf("Error retrieving Glue Jobs: %s", err) } return nil } func TestAccAWSGlueJob_Basic(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_Required(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), resource.TestCheckResourceAttr(resourceName, "command.0.script_location", "testscriptlocation"), resource.TestCheckResourceAttr(resourceName, "default_arguments.%", "0"), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestMatchResourceAttr(resourceName, "role_arn", regexp.MustCompile(fmt.Sprintf("^arn:[^:]+:iam::[^:]+:role/%s", rName))), resource.TestCheckResourceAttr(resourceName, "timeout", "2880"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_AllocatedCapacity(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_AllocatedCapacity(rName, 1), ExpectError: regexp.MustCompile(`expected allocated_capacity to be at least`), }, { Config: testAccAWSGlueJobConfig_AllocatedCapacity(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "allocated_capacity", "2"), ), }, { Config: testAccAWSGlueJobConfig_AllocatedCapacity(rName, 3), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "allocated_capacity", "3"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_Command(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_Command(rName, "testscriptlocation1"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), resource.TestCheckResourceAttr(resourceName, "command.0.script_location", "testscriptlocation1"), ), }, { Config: testAccAWSGlueJobConfig_Command(rName, "testscriptlocation2"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), resource.TestCheckResourceAttr(resourceName, "command.0.script_location", "testscriptlocation2"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_DefaultArguments(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_DefaultArguments(rName, "job-bookmark-disable", "python"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "default_arguments.%", "2"), resource.TestCheckResourceAttr(resourceName, "default_arguments.--job-bookmark-option", "job-bookmark-disable"), resource.TestCheckResourceAttr(resourceName, "default_arguments.--job-language", "python"), ), }, { Config: testAccAWSGlueJobConfig_DefaultArguments(rName, "job-bookmark-enable", "scala"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "default_arguments.%", "2"), resource.TestCheckResourceAttr(resourceName, "default_arguments.--job-bookmark-option", "job-bookmark-enable"), resource.TestCheckResourceAttr(resourceName, "default_arguments.--job-language", "scala"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_Description(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_Description(rName, "First Description"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "description", "First Description"), ), }, { Config: testAccAWSGlueJobConfig_Description(rName, "Second Description"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "description", "Second Description"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_ExecutionProperty(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_ExecutionProperty(rName, 0), ExpectError: regexp.MustCompile(`expected execution_property.0.max_concurrent_runs to be at least`), }, { Config: testAccAWSGlueJobConfig_ExecutionProperty(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "execution_property.#", "1"), resource.TestCheckResourceAttr(resourceName, "execution_property.0.max_concurrent_runs", "1"), ), }, { Config: testAccAWSGlueJobConfig_ExecutionProperty(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "execution_property.#", "1"), resource.TestCheckResourceAttr(resourceName, "execution_property.0.max_concurrent_runs", "2"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_MaxRetries(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_MaxRetries(rName, 11), ExpectError: regexp.MustCompile(`expected max_retries to be in the range`), }, { Config: testAccAWSGlueJobConfig_MaxRetries(rName, 0), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_retries", "0"), ), }, { Config: testAccAWSGlueJobConfig_MaxRetries(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_retries", "10"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_Timeout(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_Timeout(rName, 1), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "timeout", "1"), ), }, { Config: testAccAWSGlueJobConfig_Timeout(rName, 2), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "timeout", "2"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_SecurityConfiguration(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_SecurityConfiguration(rName, "default_encryption"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "security_configuration", "default_encryption"), ), }, { Config: testAccAWSGlueJobConfig_SecurityConfiguration(rName, "custom_encryption2"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "security_configuration", "custom_encryption2"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_PythonShell(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_PythonShell(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_capacity", "0.0625"), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), resource.TestCheckResourceAttr(resourceName, "command.0.script_location", "testscriptlocation"), resource.TestCheckResourceAttr(resourceName, "command.0.name", "pythonshell"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSGlueJob_MaxCapacity(t *testing.T) { var job glue.Job rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5)) resourceName := "aws_glue_job.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSGlueJobDestroy, Steps: []resource.TestStep{ { Config: testAccAWSGlueJobConfig_MaxCapacity(rName, 10), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_capacity", "10"), resource.TestCheckResourceAttr(resourceName, "command.#", "1"), resource.TestCheckResourceAttr(resourceName, "command.0.script_location", "testscriptlocation"), resource.TestCheckResourceAttr(resourceName, "command.0.name", "glueetl"), ), }, { Config: testAccAWSGlueJobConfig_MaxCapacity(rName, 15), Check: resource.ComposeTestCheckFunc( testAccCheckAWSGlueJobExists(resourceName, &job), resource.TestCheckResourceAttr(resourceName, "max_capacity", "15"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func testAccCheckAWSGlueJobExists(resourceName string, job *glue.Job) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("Not found: %s", resourceName) } if rs.Primary.ID == "" { return fmt.Errorf("No Glue Job ID is set") } conn := testAccProvider.Meta().(*AWSClient).glueconn output, err := conn.GetJob(&glue.GetJobInput{ JobName: aws.String(rs.Primary.ID), }) if err != nil { return err } if output.Job == nil { return fmt.Errorf("Glue Job (%s) not found", rs.Primary.ID) } if aws.StringValue(output.Job.Name) == rs.Primary.ID { *job = *output.Job return nil } return fmt.Errorf("Glue Job (%s) not found", rs.Primary.ID) } } func testAccCheckAWSGlueJobDestroy(s *terraform.State) error { for _, rs := range s.RootModule().Resources { if rs.Type != "aws_glue_job" { continue } conn := testAccProvider.Meta().(*AWSClient).glueconn output, err := conn.GetJob(&glue.GetJobInput{ JobName: aws.String(rs.Primary.ID), }) if err != nil { if isAWSErr(err, glue.ErrCodeEntityNotFoundException, "") { return nil } } job := output.Job if job != nil && aws.StringValue(job.Name) == rs.Primary.ID { return fmt.Errorf("Glue Job %s still exists", rs.Primary.ID) } return err } return nil } func testAccAWSGlueJobConfig_Base(rName string) string { return fmt.Sprintf(` data "aws_iam_policy" "AWSGlueServiceRole" { arn = "arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole" } resource "aws_iam_role" "test" { name = "%s" assume_role_policy = <<POLICY { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "glue.amazonaws.com" }, "Effect": "Allow", "Sid": "" } ] } POLICY } resource "aws_iam_role_policy_attachment" "test" { policy_arn = "${data.aws_iam_policy.AWSGlueServiceRole.arn}" role = "${aws_iam_role.test.name}" } `, rName) } func testAccAWSGlueJobConfig_AllocatedCapacity(rName string, allocatedCapacity int) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { allocated_capacity = %d name = "%s" role_arn = "${aws_iam_role.test.arn}" command { script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), allocatedCapacity, rName) } func testAccAWSGlueJobConfig_Command(rName, scriptLocation string) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" allocated_capacity = 10 command { script_location = "%s" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName, scriptLocation) } func testAccAWSGlueJobConfig_DefaultArguments(rName, jobBookmarkOption, jobLanguage string) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" allocated_capacity = 10 command { script_location = "testscriptlocation" } default_arguments = { "--job-bookmark-option" = "%s" "--job-language" = "%s" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName, jobBookmarkOption, jobLanguage) } func testAccAWSGlueJobConfig_Description(rName, description string) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { description = "%s" name = "%s" role_arn = "${aws_iam_role.test.arn}" allocated_capacity = 10 command { script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), description, rName) } func testAccAWSGlueJobConfig_ExecutionProperty(rName string, maxConcurrentRuns int) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" allocated_capacity = 10 command { script_location = "testscriptlocation" } execution_property { max_concurrent_runs = %d } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName, maxConcurrentRuns) } func testAccAWSGlueJobConfig_MaxRetries(rName string, maxRetries int) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { max_retries = %d name = "%s" role_arn = "${aws_iam_role.test.arn}" allocated_capacity = 10 command { script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), maxRetries, rName) } func testAccAWSGlueJobConfig_Required(rName string) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" allocated_capacity = 10 command { script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName) } func testAccAWSGlueJobConfig_Timeout(rName string, timeout int) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" timeout = %d allocated_capacity = 10 command { script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName, timeout) } func testAccAWSGlueJobConfig_SecurityConfiguration(rName string, securityConfiguration string) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" security_configuration = "%s" allocated_capacity = 10 command { script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName, securityConfiguration) } func testAccAWSGlueJobConfig_PythonShell(rName string) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" max_capacity = 0.0625 command { name = "pythonshell" script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName) } func testAccAWSGlueJobConfig_MaxCapacity(rName string, maxCapacity float64) string { return fmt.Sprintf(` %s resource "aws_glue_job" "test" { name = "%s" role_arn = "${aws_iam_role.test.arn}" max_capacity = %g command { script_location = "testscriptlocation" } depends_on = ["aws_iam_role_policy_attachment.test"] } `, testAccAWSGlueJobConfig_Base(rName), rName, maxCapacity) }
Ninir/terraform-provider-aws
aws/resource_aws_glue_job_test.go
GO
mpl-2.0
21,289
package org.gene.modules.textFile; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.Scanner; public class Test { public static void fileRead1() { try{ FileInputStream fis = new FileInputStream(new File("resource/bible/Korean/개역개정/01창세기.txt")); InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); BufferedReader br = new BufferedReader(isr); while(true){ String str = br.readLine(); if(str==null) break; System.out.println(str); } br.close(); }catch(Exception e){ e.printStackTrace(); } } public static void fileRead2() { Scanner s = null; try{ s = new Scanner(new File("sample2.txt"),"UTF-8"); while(true){ String str = s.nextLine(); System.out.println(str); } }catch(Exception e){ s.close(); } } public static void fileRead3() throws IOException { RandomAccessFile file = new RandomAccessFile("sample2.txt", "rwd"); String line = file.readLine(); file.close(); // line = new String(line.getBytes("ISO-8859-1"), "UTF-8"); line = new String(line.getBytes("8859_1"), "UTF-8"); System.out.println(line); } public static void fileWrite() { try { String srcText = new String("UTF-8 파일을 생성합니다."); File targetFile = new File("D:\\output.txt"); targetFile.createNewFile(); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile.getPath()), "UTF8")); output.write(srcText); output.close(); } catch(UnsupportedEncodingException uee) { uee.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } } public static void fileWrite2(){ try { File fileDir = new File("sample"); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(fileDir), "UTF8")); out.append("으하하").append("\r\n"); out.flush(); out.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws IOException { // fileRead3(); } }
llggkk1117/TextFile
src/org/gene/modules/textFile/Test.java
Java
mpl-2.0
2,697
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is Neil Deakin * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsXULTemplateQueryProcessorXML.h" #include "nsXULTemplateResultXML.h" #include "nsXMLBinding.h" NS_IMPL_ADDREF(nsXMLBindingSet) NS_IMPL_RELEASE(nsXMLBindingSet) nsresult nsXMLBindingSet::AddBinding(nsIAtom* aVar, nsIDOMXPathExpression* aExpr) { nsAutoPtr<nsXMLBinding> newbinding(new nsXMLBinding(aVar, aExpr)); NS_ENSURE_TRUE(newbinding, NS_ERROR_OUT_OF_MEMORY); if (mFirst) { nsXMLBinding* binding = mFirst; while (binding) { // if the target variable is already used in a binding, ignore it // since it won't be useful for anything if (binding->mVar == aVar) return NS_OK; // add the binding at the end of the list if (!binding->mNext) { binding->mNext = newbinding; break; } binding = binding->mNext; } } else { mFirst = newbinding; } return NS_OK; } PRInt32 nsXMLBindingSet::LookupTargetIndex(nsIAtom* aTargetVariable, nsXMLBinding** aBinding) { PRInt32 idx = 0; nsXMLBinding* binding = mFirst; while (binding) { if (binding->mVar == aTargetVariable) { *aBinding = binding; return idx; } idx++; binding = binding->mNext; } *aBinding = nsnull; return -1; } void nsXMLBindingValues::GetAssignmentFor(nsXULTemplateResultXML* aResult, nsXMLBinding* aBinding, PRInt32 aIndex, PRUint16 aType, nsIDOMXPathResult** aValue) { *aValue = mValues.SafeObjectAt(aIndex); if (!*aValue) { nsCOMPtr<nsIDOMNode> contextNode; aResult->GetNode(getter_AddRefs(contextNode)); if (contextNode) { nsCOMPtr<nsISupports> resultsupports; aBinding->mExpr->Evaluate(contextNode, aType, nsnull, getter_AddRefs(resultsupports)); nsCOMPtr<nsIDOMXPathResult> result = do_QueryInterface(resultsupports); if (result && mValues.ReplaceObjectAt(result, aIndex)) *aValue = result; } } NS_IF_ADDREF(*aValue); } void nsXMLBindingValues::GetNodeAssignmentFor(nsXULTemplateResultXML* aResult, nsXMLBinding* aBinding, PRInt32 aIndex, nsIDOMNode** aNode) { nsCOMPtr<nsIDOMXPathResult> result; GetAssignmentFor(aResult, aBinding, aIndex, nsIDOMXPathResult::FIRST_ORDERED_NODE_TYPE, getter_AddRefs(result)); if (result) result->GetSingleNodeValue(aNode); else *aNode = nsnull; } void nsXMLBindingValues::GetStringAssignmentFor(nsXULTemplateResultXML* aResult, nsXMLBinding* aBinding, PRInt32 aIndex, nsAString& aValue) { nsCOMPtr<nsIDOMXPathResult> result; GetAssignmentFor(aResult, aBinding, aIndex, nsIDOMXPathResult::STRING_TYPE, getter_AddRefs(result)); if (result) result->GetStringValue(aValue); else aValue.Truncate(); }
tmhorne/celtx
content/xul/templates/src/nsXMLBinding.cpp
C++
mpl-2.0
4,918
/* @flow */ import * as React from 'react'; import Link from 'amo/components/Link'; import { addParamsToHeroURL, checkInternalURL } from 'amo/utils'; import tracking from 'core/tracking'; import LoadingText from 'ui/components/LoadingText'; import type { HeroCallToActionType, SecondaryHeroShelfType, } from 'amo/reducers/home'; import './styles.scss'; export const SECONDARY_HERO_CLICK_CATEGORY = 'AMO Secondary Hero Clicks'; export const SECONDARY_HERO_SRC = 'homepage-secondary-hero'; type Props = {| shelfData?: SecondaryHeroShelfType |}; type InternalProps = {| ...Props, _checkInternalURL: typeof checkInternalURL, _tracking: typeof tracking, |}; const makeCallToActionURL = (urlString: string) => { return addParamsToHeroURL({ heroSrcCode: SECONDARY_HERO_SRC, urlString }); }; export const SecondaryHeroBase = ({ _checkInternalURL = checkInternalURL, _tracking = tracking, shelfData, }: InternalProps) => { const { headline, description, cta } = shelfData || {}; const modules = (shelfData && shelfData.modules) || Array(3).fill({}); const onHeroClick = (event: SyntheticEvent<HTMLAnchorElement>) => { _tracking.sendEvent({ action: event.currentTarget.href, category: SECONDARY_HERO_CLICK_CATEGORY, }); }; const getLinkProps = (link: HeroCallToActionType | null) => { const props = { onClick: onHeroClick }; if (link) { const urlInfo = _checkInternalURL({ urlString: link.url }); if (urlInfo.isInternal) { return { ...props, to: makeCallToActionURL(urlInfo.relativeURL) }; } return { ...props, href: makeCallToActionURL(link.url), prependClientApp: false, prependLang: false, target: '_blank', }; } return {}; }; const renderedModules = []; modules.forEach((module) => { renderedModules.push( <div className="SecondaryHero-module" key={module.description}> {module.icon ? ( <img alt={module.description} className="SecondaryHero-module-icon" src={module.icon} /> ) : ( <div className="SecondaryHero-module-icon" /> )} <div className="SecondaryHero-module-description"> {module.description || <LoadingText width={60} />} </div> {module.cta && ( <Link className="SecondaryHero-module-link" {...getLinkProps(module.cta)} > <span className="SecondaryHero-module-linkText"> {module.cta.text} </span> </Link> )} {!module.description && ( <div className="SecondaryHero-module-link"> <LoadingText width={50} /> </div> )} </div>, ); }); return ( <section className="SecondaryHero"> <div className="SecondaryHero-message"> <h2 className="SecondaryHero-message-headline"> {headline || ( <> <LoadingText width={70} /> <br /> <LoadingText width={50} /> </> )} </h2> <div className="SecondaryHero-message-description"> {description || ( <> <LoadingText width={80} /> <br /> <LoadingText width={60} /> </> )} </div> {cta && ( <Link className="SecondaryHero-message-link" {...getLinkProps(cta)}> <span className="SecondaryHero-message-linkText">{cta.text}</span> </Link> )} {!headline && ( <div className="SecondaryHero-message-link"> <LoadingText width={50} /> </div> )} </div> {renderedModules} </section> ); }; export default SecondaryHeroBase;
kumar303/addons-frontend
src/amo/components/SecondaryHero/index.js
JavaScript
mpl-2.0
3,823
# -*- coding: utf-8 -*- import scrapy class QuotesSpider(scrapy.Spider): name = 'quotes' allowed_domains = ['quotes.topscrape.com/tag/humor/'] start_urls = ['http://quotes.topscrape.com/tag/humor/'] def parse(self, response): for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').extract_first(), 'author': quote.xpath('span/small/text()').extract_first(), } next_page = response.css('li.next a::attr("href")').extract_first() if next_page is not None: yield response.follow(next_page, self.parse)
MegaWale/python-playb0x
scrapy/scrapyPlay/properties/properties/spiders/quotes.py
Python
mpl-2.0
641
#!/usr/bin/env node const fs = require('fs'); const Gcp = require('../static/app/js/classes/Gcp'); const argv = process.argv.slice(2); function die(s){ console.log(s); process.exit(1); } if (argv.length != 2){ die(`Usage: ./resize_gcp.js <path/to/gcp_file.txt> <JSON encoded image-->ratio map>`); } const [inputFile, jsonMap] = argv; if (!fs.existsSync(inputFile)){ die('File does not exist: ' + inputFile); } const originalGcp = new Gcp(fs.readFileSync(inputFile, 'utf8')); try{ const map = JSON.parse(jsonMap); const newGcp = originalGcp.resize(map, true); console.log(newGcp.toString()); }catch(e){ die("Not a valid JSON string: " + jsonMap); }
pierotofy/WebODM
app/scripts/resize_gcp.js
JavaScript
mpl-2.0
658
package aws import ( "fmt" "log" "strings" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/terraform" ) func init() { resource.AddTestSweepers("aws_nat_gateway", &resource.Sweeper{ Name: "aws_nat_gateway", F: testSweepNatGateways, }) } func testSweepNatGateways(region string) error { client, err := sharedClientForRegion(region) if err != nil { return fmt.Errorf("error getting client: %s", err) } conn := client.(*AWSClient).ec2conn req := &ec2.DescribeNatGatewaysInput{} resp, err := conn.DescribeNatGateways(req) if err != nil { if testSweepSkipSweepError(err) { log.Printf("[WARN] Skipping EC2 NAT Gateway sweep for %s: %s", region, err) return nil } return fmt.Errorf("Error describing NAT Gateways: %s", err) } if len(resp.NatGateways) == 0 { log.Print("[DEBUG] No AWS NAT Gateways to sweep") return nil } for _, natGateway := range resp.NatGateways { _, err := conn.DeleteNatGateway(&ec2.DeleteNatGatewayInput{ NatGatewayId: natGateway.NatGatewayId, }) if err != nil { return fmt.Errorf( "Error deleting NAT Gateway (%s): %s", *natGateway.NatGatewayId, err) } } return nil } func TestAccAWSNatGateway_basic(t *testing.T) { var natGateway ec2.NatGateway resourceName := "aws_nat_gateway.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, IDRefreshName: resourceName, Providers: testAccProviders, CheckDestroy: testAccCheckNatGatewayDestroy, Steps: []resource.TestStep{ { Config: testAccNatGatewayConfig, Check: resource.ComposeTestCheckFunc( testAccCheckNatGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "tags.#", "0"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSNatGateway_tags(t *testing.T) { var natGateway ec2.NatGateway resourceName := "aws_nat_gateway.test" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckNatGatewayDestroy, Steps: []resource.TestStep{ { Config: testAccNatGatewayConfigTags1("key1", "value1"), Check: resource.ComposeTestCheckFunc( testAccCheckNatGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, { Config: testAccNatGatewayConfigTags2("key1", "value1updated", "key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNatGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "2"), resource.TestCheckResourceAttr(resourceName, "tags.key1", "value1updated"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, { Config: testAccNatGatewayConfigTags1("key2", "value2"), Check: resource.ComposeTestCheckFunc( testAccCheckNatGatewayExists(resourceName, &natGateway), resource.TestCheckResourceAttr(resourceName, "tags.%", "1"), resource.TestCheckResourceAttr(resourceName, "tags.key2", "value2"), ), }, }, }) } func testAccCheckNatGatewayDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).ec2conn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_nat_gateway" { continue } // Try to find the resource resp, err := conn.DescribeNatGateways(&ec2.DescribeNatGatewaysInput{ NatGatewayIds: []*string{aws.String(rs.Primary.ID)}, }) if err == nil { status := map[string]bool{ ec2.NatGatewayStateDeleted: true, ec2.NatGatewayStateDeleting: true, ec2.NatGatewayStateFailed: true, } if _, ok := status[strings.ToLower(*resp.NatGateways[0].State)]; len(resp.NatGateways) > 0 && !ok { return fmt.Errorf("still exists") } return nil } // Verify the error is what we want ec2err, ok := err.(awserr.Error) if !ok { return err } if ec2err.Code() != "NatGatewayNotFound" { return err } } return nil } func testAccCheckNatGatewayExists(n string, ng *ec2.NatGateway) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } conn := testAccProvider.Meta().(*AWSClient).ec2conn resp, err := conn.DescribeNatGateways(&ec2.DescribeNatGatewaysInput{ NatGatewayIds: []*string{aws.String(rs.Primary.ID)}, }) if err != nil { return err } if len(resp.NatGateways) == 0 { return fmt.Errorf("NatGateway not found") } *ng = *resp.NatGateways[0] return nil } } const testAccNatGatewayConfigBase = ` resource "aws_vpc" "test" { cidr_block = "10.0.0.0/16" tags = { Name = "terraform-testacc-nat-gw-basic" } } resource "aws_subnet" "private" { vpc_id = "${aws_vpc.test.id}" cidr_block = "10.0.1.0/24" map_public_ip_on_launch = false tags = { Name = "tf-acc-nat-gw-basic-private" } } resource "aws_subnet" "public" { vpc_id = "${aws_vpc.test.id}" cidr_block = "10.0.2.0/24" map_public_ip_on_launch = true tags = { Name = "tf-acc-nat-gw-basic-public" } } resource "aws_internet_gateway" "test" { vpc_id = "${aws_vpc.test.id}" } resource "aws_eip" "test" { vpc = true } ` const testAccNatGatewayConfig = testAccNatGatewayConfigBase + ` // Actual SUT resource "aws_nat_gateway" "test" { allocation_id = "${aws_eip.test.id}" subnet_id = "${aws_subnet.public.id}" depends_on = ["aws_internet_gateway.test"] } ` func testAccNatGatewayConfigTags1(tagKey1, tagValue1 string) string { return testAccNatGatewayConfigBase + fmt.Sprintf(` resource "aws_nat_gateway" "test" { allocation_id = "${aws_eip.test.id}" subnet_id = "${aws_subnet.public.id}" tags = { %[1]q = %[2]q } depends_on = ["aws_internet_gateway.test"] } `, tagKey1, tagValue1) } func testAccNatGatewayConfigTags2(tagKey1, tagValue1, tagKey2, tagValue2 string) string { return testAccNatGatewayConfigBase + fmt.Sprintf(` resource "aws_nat_gateway" "test" { allocation_id = "${aws_eip.test.id}" subnet_id = "${aws_subnet.public.id}" tags = { %[1]q = %[2]q %[3]q = %[4]q } depends_on = ["aws_internet_gateway.test"] } `, tagKey1, tagValue1, tagKey2, tagValue2) }
kjmkznr/terraform-provider-aws
aws/resource_aws_nat_gateway_test.go
GO
mpl-2.0
6,816
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.skelril.skree.content.registry.item.tool.axe; import com.skelril.nitro.registry.ItemTier; import com.skelril.nitro.registry.item.ItemTiers; import com.skelril.nitro.registry.item.ItemToolTypes; import com.skelril.nitro.registry.item.axe.CustomAxe; import net.minecraft.item.ItemStack; import static com.skelril.nitro.item.ItemStackFactory.newItemStack; public class CrystalAxe extends CustomAxe { @Override public String __getType() { return "crystal"; } @Override public ItemStack __getRepairItemStack() { return (ItemStack) (Object) newItemStack("skree:sea_crystal"); } @Override public double __getHitPower() { return ItemTiers.CRYSTAL.getDamage() + ItemToolTypes.AXE.getBaseDamage(); } @Override public int __getEnchantability() { return ItemTiers.CRYSTAL.getEnchantability(); } @Override public ItemTier __getHarvestTier() { return ItemTiers.CRYSTAL; } @Override public float __getSpecializedSpeed() { return ItemTiers.CRYSTAL.getEfficienyOnProperMaterial(); } @Override public int __getMaxUses() { return ItemTiers.CRYSTAL.getDurability(); } }
Skelril/Skree
src/main/java/com/skelril/skree/content/registry/item/tool/axe/CrystalAxe.java
Java
mpl-2.0
1,351
/** * Copyright (C), 2012 Adaptinet.org (Todd Fearn, Anthony Graffeo) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * */ package org.adaptinet.peer; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.adaptinet.peer.PeerRoot; public class PeerFile { private static final String DEFAULT = "DefaultPeers.xml"; private boolean bOpen = false; private File file; private boolean bDefault = false; private boolean bDirty = false; public boolean isOpen() { return bOpen; } public void setOpen(boolean bOpen) { this.bOpen = bOpen; } public boolean isDefault() { return bDefault; } public void setDefault(boolean bDefault) { this.bDefault = bDefault; } public boolean isDirty() { return bDirty; } public void setDirty(boolean bDirty) { this.bDirty = bDirty; } public void openFile(final String name) throws Exception { } public PeerRoot open() throws Exception { this.bDefault = true; return open(DEFAULT); } public PeerRoot open(String name) throws Exception { if (name == null || name.length() == 0) { return open(); } PeerRoot tmpRoot = new PeerRoot(); FileInputStream fis = null; try { if (name.equalsIgnoreCase(DEFAULT)) { File defaultfile = new File(name); bDefault = true; if (!file.exists()) { throw new IOException( "error Default peer file does not exist."); } fis = new FileInputStream(defaultfile); } else { file = new File(name); if (!file.exists()) { new File(name.substring(0, name .lastIndexOf(File.separatorChar))).mkdirs(); file.createNewFile(); } fis = new FileInputStream(file); bOpen = true; } byte[] bytes = new byte[fis.available()]; fis.read(bytes); tmpRoot.parsePeers(bytes); // Check to see if there are any peers if not go to the default // peer file that should have been included in the installation if (tmpRoot.count() < 1 && !bDefault) { return open(); } return tmpRoot; } catch (IOException x) { x.printStackTrace(); throw x; } finally { if (fis != null) { fis.close(); } } } public void close() { bOpen = false; } public void save(String data) throws IOException { FileOutputStream fos = null; try { file.renameTo(new File(file.getName() + "~")); fos = new FileOutputStream(file); fos.write(data.getBytes()); bDirty = false; } catch (Exception e) { e.printStackTrace(); } finally { fos.close(); } } }
tfearn/AdaptinetSDK
src/org/adaptinet/peer/PeerFile.java
Java
mpl-2.0
2,831
package edu.asu.qstore4s.search.elements.factory.impl; import org.springframework.stereotype.Service; import edu.asu.qstore4s.search.elements.ISearchConcept; import edu.asu.qstore4s.search.elements.factory.ISearchConceptFactory; import edu.asu.qstore4s.search.elements.impl.SearchConcept; @Service public class SearchConceptFactory implements ISearchConceptFactory { @Override public ISearchConcept createSearchConcept() { ISearchConcept conceptObject = new SearchConcept(); return conceptObject; } @Override public ISearchConcept createSearchConcept(String sourceUri) { ISearchConcept conceptObject = new SearchConcept(); conceptObject.setSourceURI(sourceUri == null ? "" : sourceUri); return conceptObject; } }
diging/qstore4s
QStore4S/src/main/java/edu/asu/qstore4s/search/elements/factory/impl/SearchConceptFactory.java
Java
mpl-2.0
737
package com.mifos.mifosxdroid.injection.component; import com.mifos.mifosxdroid.activity.pathtracking.PathTrackingActivity; import com.mifos.mifosxdroid.activity.pinpointclient.PinpointClientActivity; import com.mifos.mifosxdroid.dialogfragments.chargedialog.ChargeDialogFragment; import com.mifos.mifosxdroid.dialogfragments.datatablerowdialog.DataTableRowDialogFragment; import com.mifos.mifosxdroid.dialogfragments.documentdialog.DocumentDialogFragment; import com.mifos.mifosxdroid.dialogfragments.identifierdialog.IdentifierDialogFragment; import com.mifos.mifosxdroid.dialogfragments.loanaccountapproval.LoanAccountApproval; import com.mifos.mifosxdroid.dialogfragments.loanaccountdisbursement.LoanAccountDisbursement; import com.mifos.mifosxdroid.dialogfragments.loanchargedialog.LoanChargeDialogFragment; import com.mifos.mifosxdroid.dialogfragments.savingsaccountapproval.SavingsAccountApproval; import com.mifos.mifosxdroid.dialogfragments.syncclientsdialog.SyncClientsDialogFragment; import com.mifos.mifosxdroid.dialogfragments.syncgroupsdialog.SyncGroupsDialogFragment; import com.mifos.mifosxdroid.injection.PerActivity; import com.mifos.mifosxdroid.injection.module.ActivityModule; import com.mifos.mifosxdroid.login.LoginActivity; import com.mifos.mifosxdroid.offline.offlinedashbarod.OfflineDashboardFragment; import com.mifos.mifosxdroid.offline.syncclientpayloads.SyncClientPayloadsFragment; import com.mifos.mifosxdroid.offline.syncgrouppayloads.SyncGroupPayloadsFragment; import com.mifos.mifosxdroid.offline.syncloanrepaymenttransacition.SyncLoanRepaymentTransactionFragment; import com.mifos.mifosxdroid.offline.syncsavingsaccounttransaction.SyncSavingsAccountTransactionFragment; import com.mifos.mifosxdroid.online.centerlist.CenterListFragment; import com.mifos.mifosxdroid.online.clientcharge.ClientChargeFragment; import com.mifos.mifosxdroid.online.clientdetails.ClientDetailsFragment; import com.mifos.mifosxdroid.online.clientidentifiers.ClientIdentifiersFragment; import com.mifos.mifosxdroid.online.clientlist.ClientListFragment; import com.mifos.mifosxdroid.online.datatablelistfragment.DataTableListFragment; import com.mifos.mifosxdroid.online.search.SearchFragment; import com.mifos.mifosxdroid.online.collectionsheet.CollectionSheetFragment; import com.mifos.mifosxdroid.online.createnewcenter.CreateNewCenterFragment; import com.mifos.mifosxdroid.online.createnewclient.CreateNewClientFragment; import com.mifos.mifosxdroid.online.createnewgroup.CreateNewGroupFragment; import com.mifos.mifosxdroid.online.datatabledata.DataTableDataFragment; import com.mifos.mifosxdroid.online.documentlist.DocumentListFragment; import com.mifos.mifosxdroid.online.generatecollectionsheet.GenerateCollectionSheetFragment; import com.mifos.mifosxdroid.online.groupdetails.GroupDetailsFragment; import com.mifos.mifosxdroid.online.grouplist.GroupListFragment; import com.mifos.mifosxdroid.online.grouploanaccount.GroupLoanAccountFragment; import com.mifos.mifosxdroid.online.groupslist.GroupsListFragment; import com.mifos.mifosxdroid.online.loanaccount.LoanAccountFragment; import com.mifos.mifosxdroid.online.loanaccountsummary.LoanAccountSummaryFragment; import com.mifos.mifosxdroid.online.loancharge.LoanChargeFragment; import com.mifos.mifosxdroid.online.loanrepayment.LoanRepaymentFragment; import com.mifos.mifosxdroid.online.loanrepaymentschedule.LoanRepaymentScheduleFragment; import com.mifos.mifosxdroid.online.loantransactions.LoanTransactionsFragment; import com.mifos.mifosxdroid.online.savingaccountsummary.SavingsAccountSummaryFragment; import com.mifos.mifosxdroid.online.savingaccounttransaction.SavingsAccountTransactionFragment; import com.mifos.mifosxdroid.online.savingsaccount.SavingsAccountFragment; import com.mifos.mifosxdroid.online.surveylist.SurveyListFragment; import com.mifos.mifosxdroid.online.surveysubmit.SurveySubmitFragment; import dagger.Component; /** * @author Rajan Maurya * This component inject dependencies to all Activities across the application */ @PerActivity @Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class) public interface ActivityComponent { void inject(LoginActivity loginActivity); void inject(CenterListFragment centerListFragment); void inject(ClientChargeFragment clientChargeFragment); void inject(ClientListFragment clientListFragment); void inject(ClientIdentifiersFragment clientIdentifiersFragment); void inject(SearchFragment clientSearchFragment); void inject(DocumentListFragment documentListFragment); void inject(GroupListFragment groupListFragment); void inject(GenerateCollectionSheetFragment generateCollectionSheetFragment); void inject(CreateNewCenterFragment createNewCenterFragment); void inject(CreateNewGroupFragment createNewGroupFragment); void inject(CreateNewClientFragment createNewClientFragment); void inject(DataTableDataFragment dataTableDataFragment); void inject(GroupDetailsFragment groupDetailsFragment); void inject(ClientDetailsFragment clientDetailsFragment); void inject(LoanAccountSummaryFragment loanAccountSummaryFragment); void inject(SavingsAccountSummaryFragment savingsAccountSummaryFragment); void inject(LoanChargeFragment loanChargeFragment); void inject(SavingsAccountTransactionFragment savingsAccountTransactionFragment); void inject(CollectionSheetFragment collectionSheetFragment); void inject(GroupsListFragment groupsListFragment); void inject(LoanTransactionsFragment loanTransactionsFragment); void inject(SavingsAccountFragment savingsAccountFragment); void inject(LoanRepaymentFragment loanRepaymentFragment); void inject(GroupLoanAccountFragment groupLoanAccountFragment); void inject(LoanAccountFragment loanAccountFragment); void inject(LoanRepaymentScheduleFragment loanRepaymentScheduleFragment); void inject(SurveyListFragment surveyListFragment); void inject(SurveySubmitFragment surveySubmitFragment); void inject(PinpointClientActivity pinpointClientActivity); void inject(ChargeDialogFragment chargeDialogFragment); void inject(DataTableRowDialogFragment dataTableRowDialogFragment); void inject(DataTableListFragment dataTableListFragment); void inject(DocumentDialogFragment documentDialogFragment); void inject(LoanAccountApproval loanAccountApproval); void inject(LoanAccountDisbursement loanAccountDisbursement); void inject(LoanChargeDialogFragment loanChargeDialogFragment); void inject(SavingsAccountApproval savingsAccountApproval); void inject(SyncClientPayloadsFragment syncPayloadsFragment); void inject(SyncGroupPayloadsFragment syncGroupPayloadsFragment); void inject(OfflineDashboardFragment offlineDashboardFragment); void inject(SyncLoanRepaymentTransactionFragment syncLoanRepaymentTransactionFragment); void inject(SyncClientsDialogFragment syncClientsDialogFragment); void inject(SyncSavingsAccountTransactionFragment syncSavingsAccountTransactionFragment); void inject(SyncGroupsDialogFragment syncGroupsDialogFragment); void inject(IdentifierDialogFragment identifierDialogFragment); void inject(PathTrackingActivity pathTrackingActivity); }
CloudyPadmal/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/injection/component/ActivityComponent.java
Java
mpl-2.0
7,297
// listen and handle messages from the content script // via the background script import { addStackingContext } from "./actions/stacking-context"; function connectToInspectedWindow({ dispatch }) { browser.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.tabId !== browser.devtools.inspectedWindow.tabId) { return; } switch (request.action) { case "SET_STACKING_CONTEXT_TREE": const { tree, selector } = request.data; dispatch(addStackingContext(tree, selector)); } }); } export { connectToInspectedWindow };
gregtatum/z-index-devtool
extension/src/bootstrap.js
JavaScript
mpl-2.0
588
package com.codejockey.canvas.com.codejockey.canvas.helperfiles; /* Canvas Drawing class Accepts touch events and draws curves on a canvas. Solves these major problems: * Smooths jagged lines by drawing b-spline curves between sample points. * Snaps curve start and end points to the border to make it easier to draw closed areas. * Snaps curve end to curve start, if user drew a shape, to make it easier to draw closed shapes. * Adjusts curve thickness based on drawing velocity, so that slow drawing creates thinner lines. * Smooths curve thickness by removing outliers (some devices have peaky sample rates). * Allows perfect shape filling by using 100% pixel colors (no anti- aliasing). * Draws on larger bitmap, scales down to view size, to allow zooming and give better image quality. Algorithm by Pieter Hintjens and Darrin Smith. */ import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.os.AsyncTask; import android.os.Vibrator; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.widget.ImageView; import android.content.Context; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; // Import Magnet API // import com.samsung.magnet.wrapper.MagnetAgent; // import com.samsung.magnet.wrapper.MagnetAgentImpl; // import com.samsung.magnet.wrapper.MagnetAgent.ChannelListener; // import com.samsung.magnet.wrapper.MagnetAgent.MagnetListener; // import com.samsung.magnet.wrapper.MagnetAgent.MagnetServiceListener; // import com.samsung.allshare.canvas.QueueLinearFloodFiller; public class Drawing { private static final String TAG = "CanvasDrawing"; private Context context; private ImageView imageview; private Bitmap bitmap; private Canvas canvas = new Canvas (); private Paint paint = new Paint (); // Magnet interface // private MagnetAgent magnet = new MagnetAgentImpl (); private String device_id = ""; // Drawing state private int width; private int height; private int ink; private int paper; // Ratio of height or width for snaps private static final float SNAP_MARGIN = 0.04f; // Snap methods private static final int SNAP_NONE = 0; private static final int SNAP_TO_EDGE = 1; private static final int SNAP_TO_START = 2; // Snap margins private int snapmin_x, snapmin_y; private int snapmax_x, snapmax_y; // Current drawn curve private Point curve_start; // Requested starting point private Point curve_start_snap; // Snapped starting point private Point curve_end; // Requested ending point private Point curve_end_snap; // Snapped ending point private float curve_width; // Current (median) width private float curve_extent; // Maximum distance from start // Curve drawing constants // We vary paintbrush width by at most this much each stroke // to reduce the effects of event time spikes (affects some devices) private static final float OUTLIER_TOLERANCE = 0.1f; // Number of steps we draw between points private static final int CURVE_STEPS = 30; // Weight of curve between points private static final float CURVE_DENSITY = 5.0f; // Starting point for event sample rate guess private static final int DIFF_BASELINE = 40; // Points in curve; we store last four knots private Point [] knots = new Point [4]; private long last_knot_time = 0; // Smart invalidation after drawing curve private float minx, maxx, miny, maxy; // Median event sample rate, using the baseline as initial guess private long median_diff = DIFF_BASELINE; // Replaying to UI, don't process input events private boolean ui_locked; // Did we snap the start of the line to the edge? private boolean start_snapped; // Each command represents one instruction // We can replay these from first to last class command { // These are the command types we know public static final int RESET = 1; // Reset drawing public static final int PAPER = 2; // Set paper color public static final int INK = 3; // Set ink color public static final int ERASE = 4; // Erase canvas public static final int DOWN = 5; // Start a line public static final int MOVE = 6; // Draw the line public static final int UP = 7; // Draw the line public static final int FILL = 8; // Fill an area private int type; private int x; private int y; private int color; public command (int type, Point point) { this.type = type; this.x = point.x; this.y = point.y; } public command (int type, int x, int y) { this.type = type; this.x = x; this.y = y; } public command (int type, int color) { this.type = type; this.color = color; } } // List of commands since we started private List commands = new ArrayList <command> (1000); public Drawing (Context _context, ImageView _imageview) { // Store parent context context = _context; imageview = _imageview; // Create our bitmap drawing area reset (1200, 1600); // Set-up paint brush paint.setStyle (Paint.Style.STROKE); paint.setStrokeJoin (Paint.Join.ROUND); paint.setStrokeCap (Paint.Cap.SQUARE); // Connect to the Magnet network // magnet.initServiceWithCustomAction ("com.samsung.magnet.service.Canvas", // context, service_listener); // magnet.registerPublicChannelListener (channel_listener); } public void onTouchEvent (MotionEvent event) { if (!gesture_detector.onTouchEvent (event)) { Point point = get_point (event); switch (event.getAction ()) { case MotionEvent.ACTION_DOWN: commands.add (new command (command.DOWN, point)); down_headless (point); break; case MotionEvent.ACTION_MOVE: commands.add (new command (command.MOVE, point)); move_headless (point); rect_invalidate (); break; case MotionEvent.ACTION_UP: commands.add (new command (command.UP, point)); up_headless (point); rect_invalidate (); break; } } } // Set the canvas size public void reset (int _width, int _height) { commands.add (new command (command.RESET, _width, _height)); width = _width; height = _height; paper = Color.WHITE; ink = Color.BLACK; bitmap = Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888); // Calculate snap knots, each time the width/height changes snapmin_x = (int) (width * SNAP_MARGIN); snapmin_y = (int) (height * SNAP_MARGIN); snapmax_x = width - snapmin_x; snapmax_y = height - snapmin_y; // Draw the bitmap on the image canvas.setBitmap (bitmap); canvas.drawColor (paper); imageview.setImageBitmap (bitmap); imageview.setScaleType (ImageView.ScaleType.FIT_XY); imageview.invalidate (); } // Set the drawing ink color public void setInk (int _ink) { commands.add (new command (command.INK, _ink)); ink = _ink; } // Set the drawing paper color public void setPaper (int _paper) { commands.add (new command (command.PAPER, _paper)); paper = _paper; } // Reset the canvas to the current paper color public void erase () { commands.add (new command (command.ERASE, paper)); erase_headless (); } // Event handlers // --------------------------------------------------------------------- /* private MagnetServiceListener service_listener = new MagnetServiceListener () { @Override public void onWifiConnectivity () { device_id = magnet.getLocalName (); Log.i (TAG, "Magnet onWifiConnectivity received for device ID: " + device_id); } @Override public void onServiceTerminated () { Log.i (TAG, "Magnet onServiceTerminated received"); } @Override public void onServiceNotFound () { Log.i (TAG, "Magnet onServiceNotFound received"); } @Override public void onNoWifiConnectivity () { Log.i (TAG, "Magnet onNoWifiConnectivity received"); } @Override public void onMagnetPeers () { Log.i (TAG, "Magnet onMagnetPeers received"); } @Override public void onMagnetNoPeers () { Log.i (TAG, "Magnet onMagnetNoPeers received"); } @Override public void onInvalidSdk () { Log.i (TAG, "Magnet onInvalidSdk received"); } }; private ChannelListener channel_listener = new ChannelListener () { @Override public void onFailure (int reason) { Log.i (TAG, "Magnet onFailure received"); } @Override public void onFileReceived ( String fromNode, String fromChannel, String originalName, String hash, String exchangeId, String type, long fileSize, String tmp_path) { Log.i (TAG, "Magnet onFileReceived received"); } @Override public void onFileFailed ( String fromNode, String fromChannel, String originalName, String hash, String exchangeId, int reason) { Log.i (TAG, "Magnet onFileFailed received"); } @Override public void onDataReceived ( String fromNode, String fromChannel, String type, List<byte[]> payload) { Log.i (TAG, "Magnet onDataReceived received"); } @Override public void onChunkReceived ( String fromNode, String fromChannel, String originalName, String hash, String exchangeId, String type, long fileSize, long offset) { Log.i (TAG, "Magnet onChunkReceived received"); } @Override public void onFileNotified ( String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, long arg6, String arg7) { Log.i (TAG, "Magnet onFileNotified received"); } @Override public void onJoinEvent (String fromNode, String fromChannel) { Log.i (TAG, "Magnet onJoinEvent received, node:" + fromNode + " channel:" + fromChannel); if (device_id == null) { Log.i (TAG, "onJoinEvent: E: NULL device ID"); device_id = magnet.getLocalName (); } } @Override public void onLeaveEvent (String fromNode, String fromChannel) { Log.i (TAG, "Magnet onLeaveEvent received, node: " + fromNode + " channel: " + fromChannel); } }; */ // Private methods // --------------------------------------------------------------------- private GestureDetector gesture_detector = new GestureDetector ( new GestureDetector.SimpleOnGestureListener () { public boolean onSingleTapUp (MotionEvent event) { Point point = get_point (event); commands.add (new command (command.FILL, point)); fill_headless (point); imageview.invalidate (); vibrate (); return true; } public void onLongPress (MotionEvent event) { new replay_commands ().execute ("nothing"); } } ); // Headless methods do not create any command history // Thus they can safely be called to replay commands private void erase_headless () { canvas.drawColor (paper); } // Start a new line private void down_headless (Point point) { curve_start = point; curve_start_snap = snap (point, SNAP_TO_EDGE); curve_extent = 0; if (curve_start.equals (curve_start_snap)) curve_open (curve_start); else { curve_open (curve_start_snap); curve_move (curve_start); } } // Continue the line private void move_headless (Point point) { curve_move (point); // Track the extent of the curve to help us decide whether to // close the shape automatically. float extent = distance (point, curve_start); if (curve_extent < extent) curve_extent = extent; } // End the line private void up_headless (Point point) { // Snap the end of the curve back to the start if close enough // but only if the start wasn't itself snapped to the edge. curve_end = point; if (curve_start.equals (curve_start_snap)) curve_end_snap = snap (point, SNAP_TO_START); else curve_end_snap = snap (point, SNAP_TO_EDGE); if (curve_end.equals (curve_end_snap)) curve_close (curve_end); else { curve_move (curve_end); curve_close (curve_end_snap); } } // Fill the selected area with the current ink color public void fill_headless (Point point) { int targetColor = bitmap.getPixel (point.x, point.y); QueueLinearFloodFiller filler = new QueueLinearFloodFiller (bitmap, targetColor, ink); filler.setTolerance (25); filler.floodFill (point.x, point.y); } // Convert motion event coordinates into point in our drawing private Point get_point (MotionEvent event) { Point point = new Point (); point.x = (int) (event.getX () * width / imageview.getWidth ()); point.y = (int) (event.getY () * height / imageview.getHeight ()); return point; } // Return point with snap if requested private Point snap (Point point, int mode) { if (mode == SNAP_TO_EDGE) { if (point.x < snapmin_x) point.x = 0; else if (point.x > snapmax_x) point.x = width; if (point.y < snapmin_y) point.y = 0; else if (point.y > snapmax_y) point.y = height; } else if (mode == SNAP_TO_START) { // Snap back to start if start didn't move to edge. // We snap back if we're less than 50% of the curve // extent away from the starting point, i.e. we made // some kind of shape. Ending point must also be // reasonably close to starting point. float extent = distance (curve_start, point); if (curve_start.equals (curve_start_snap) && extent < curve_extent / 2.0f && extent < snapmin_x + snapmin_y) point = curve_start; else point = snap (point, SNAP_TO_EDGE); } return point; } // Calculate distance in pixels between two knots private float distance (Point p1, Point p2) { float distance = (float) Math.sqrt ( (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)); return distance; } // Plots a b-spline curve through the last four knots of the curve // Based on Section 4.2 of Ammeraal, L. (1998) Computer Graphics for // Java Programmers, Chichester: John Wiley. // private void curve_open (Point knot) { // Load up our knots with our start position. // This solves two problems; one that we need at least 4 // knots to draw a curve and two, that we lose the first // point unless we repeat it three times. knots [1] = knot; knots [2] = knot; knots [3] = knot; last_knot_time = System.currentTimeMillis (); curve_width = 2.0f; } private void curve_move (Point knot) { // Adds a knot and draws the curve. Since we've preloaded // the knots in curve_open this will draw between two or // more points (aka knot in b-spline jargon). knots [0] = knots [1]; knots [1] = knots [2]; knots [2] = knots [3]; knots [3] = knot; // Sample rates range from 60-100 msecs depending on the device // We estimate a rolling median using the simple technique of // taking each new value; if it's larger than sample rate, add // 1 to sample rate and if it's smaller, subtract 1. long this_knot_time = System.currentTimeMillis (); long time_diff = this_knot_time - last_knot_time; if (time_diff > 10) median_diff += median_diff > time_diff? -1: 1; last_knot_time = this_knot_time; curve_plot (); } private void curve_close (Point knot) { // Close the curve, drawing the end three times to ensure // the curve is fully connected; otherwise the actual end // point won't be drawn (the curve will stop just short). curve_move (knot); curve_move (knot); curve_move (knot); } // We always draw the last 4 knots private void curve_plot () { // We take DIFF_BASELINE msec as being our "normal" sample // rate. On slower screens the lines will otherwise be too fat. float compensation = (float) median_diff / DIFF_BASELINE / CURVE_STEPS * CURVE_DENSITY; float x1 = -1; float y1 = -1; float a0 = (knots [0].x + 4 * knots [1].x + knots [2].x) / 6; float b0 = (knots [0].y + 4 * knots [1].y + knots [2].y) / 6; float a1 = (knots [2].x - knots [0].x) / 2; float b1 = (knots [2].y - knots [0].y) / 2; float a2 = (knots [0].x - 2 * knots [1].x + knots [2].x) / 2; float b2 = (knots [0].y - 2 * knots [1].y + knots [2].y) / 2; float a3 = (knots [3].x - knots [0].x + 3 * (knots [1].x - knots [2].x)) / 6; float b3 = (knots [3].y - knots [0].y + 3 * (knots [1].y - knots [2].y)) / 6; rect_reset (); for (int step = 0; step <= CURVE_STEPS; step++) { float x0 = x1; float y0 = y1; float t = (float) step / (float) CURVE_STEPS; x1 = ((a3 * t + a2) * t + a1) * t + a0; y1 = ((b3 * t + b2) * t + b1) * t + b0; if (x0 != -1) { float distance = (float) Math.sqrt ((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)); if (distance > 0) { float target_width = (float) distance / compensation + 1.0f; if (target_width > curve_width) curve_width += OUTLIER_TOLERANCE; else curve_width -= OUTLIER_TOLERANCE; paint.setStrokeWidth (curve_width); paint.setColor (ink); canvas.drawLine (x0, y0, x1, y1, paint); rect_stretch (x0, y0, x1, y1); } } } } // Reset invalidation rectangle private void rect_reset () { minx = width; maxx = -1; miny = height; maxy = -1; } private void rect_stretch (float x0, float y0, float x1, float y1) { if (minx > x0 - curve_width) minx = x0 - curve_width; if (miny > y0 - curve_width) miny = y0 - curve_width; if (maxx < x1 + curve_width) maxx = x1 + curve_width; if (maxy < y1 + curve_width) maxy = y1 + curve_width; } private void rect_invalidate () { // Adjust rectangle for imageview only the affected rectangle minx = minx / width * imageview.getWidth (); maxx = maxx / width * imageview.getWidth (); miny = miny / height * imageview.getHeight (); maxy = maxy / height * imageview.getHeight (); if (maxx > minx && maxy > miny) imageview.invalidate ((int) minx, (int) miny, (int) maxx, (int) maxy); } private void vibrate () { Vibrator mVibrator; mVibrator = (Vibrator) context.getSystemService (Context.VIBRATOR_SERVICE); mVibrator.vibrate (10); } private class replay_commands extends AsyncTask <String, Bitmap, String> { protected void onPreExecute () { ui_locked = true; } protected String doInBackground (String... params) { Bitmap offscreen = Bitmap.createBitmap (width, height, Bitmap.Config.ARGB_8888); canvas.setBitmap (offscreen); ListIterator iterator = commands.listIterator (); while (iterator.hasNext ()) { command cmd = (command) iterator.next (); switch (cmd.type) { case command.RESET: erase_headless (); break; case command.PAPER: paper = cmd.color; break; case command.INK: ink = cmd.color; break; case command.ERASE: erase_headless (); break; case command.DOWN: down_headless (new Point (cmd.x, cmd.y)); break; case command.MOVE: move_headless (new Point (cmd.x, cmd.y)); break; case command.UP: up_headless (new Point (cmd.x, cmd.y)); break; case command.FILL: fill_headless (new Point (cmd.x, cmd.y)); break; } Bitmap onscreen = Bitmap.createBitmap (offscreen); publishProgress (onscreen); } return null; } protected void onProgressUpdate (Bitmap... onscreen) { imageview.setImageBitmap (onscreen [0]); imageview.invalidate (); } protected void onPostExecute (String result) { ui_locked = false; } } private void trace (String s, Point p) { Log.d (TAG, s + " " + p.x + "/" + p.y); } }
hintjens/Canvas
app/src/main/java/com/codejockey/canvas/helperfiles/Drawing.java
Java
mpl-2.0
23,382
package main.origo.core.utils; import main.origo.core.InitializationException; import main.origo.core.ModuleException; import play.Logger; import play.Play; public class ExceptionUtil { /** * Transforms a nested exception into a simple runtime exception and throws it if in DEV mode. * Only logs the exception if in PROD mode. * @param e * @return */ public static void assertExceptionHandling(Exception e) { if (Play.isDev()) { Throwable thrown = e; while(thrown instanceof RuntimeException && thrown.getCause() != null) { thrown = thrown.getCause(); } if (thrown instanceof RuntimeException) { throw (RuntimeException)thrown; } throw new RuntimeException(thrown); } Logger.error("An exception occurred while loading: " + e.getMessage(), e); } public static RuntimeException getCause(Throwable e) { Throwable thrown = e; while(thrown.getCause() != null && (thrown instanceof InitializationException || thrown instanceof ModuleException || thrown instanceof RuntimeException)) { thrown = thrown.getCause(); } if (thrown instanceof RuntimeException) { throw (RuntimeException)thrown; } else { throw new RuntimeException(thrown); } } }
origocms/origo
modules/core/app/main/origo/core/utils/ExceptionUtil.java
Java
mpl-2.0
1,459
<?php namespace TwelveCode\MShell; abstract class ACommand { /** * Call argument count * @var int */ protected $_argc; /** * Call argument list * @var string[] */ protected $_argv; /** * Holds the command's result * @var null|mixed */ protected $_result = null; /** * Executes the command * * Internally the protected process() method is called, together with * beforeProcess() and afterProcess() * * The commend's result can be obtained using getResult() * * @return ACommand The execution results */ public function execute() { $this->beforeProcess(); $this->process(); $this->afterProcess(); return $this; } /** * Logic to be executed before the main processing takes place * * @return mixed */ protected function beforeProcess() { return; } /** * The main command working unit * * This method contains all the main command's logic * As a result the internal $_result property should be set, so the * product can be obtained using getResult() method. * * @return mixed */ protected function process() { return; } /** * The logic that should be executed after the main processing takes * place * * @return mixed */ protected function afterProcess() { return; } /** * Returns help information for the command * * This method should contain all the help information that the end user * would require. It's extreamly powerful in conjunction with the `help` * command. * * @return string */ protected function getHelp() { return 'No help contents for this command.'; } public function setArgc($argc) { $this->_argc = $argc; } public function getArgc() { return $this->_argc; } public function setArgv($argv) { $this->_argv = $argv; } public function getArgv() { return $this->_argv; } /** * Returns the command's result (product) * * @return mixed|null */ public function getResult() { return $this->_result; } }
twelvecode/mshell
lib/TwelveCode/MShell/ACommand.php
PHP
mpl-2.0
2,344
/** * Image Processing * * In imaging science, image processing is any form of signal processing for * which the input is an image, such as a photograph or video frame; the output * of image processing may be either an image or a set of characteristics or * parameters related to the image. Most image-processing techniques involve * treating the image as a two-dimensional signal and applying standard * signal-processing techniques to it. * * -->Image Processing (image in -> image out) * Image Analysis (image in -> measurements out) * Image Understanding (image in -> high-level description out) * * - http://en.wikipedia.org/wiki/Image_processing */ var util = require('util'); var stream = require('stream'); var Transform = stream.Transform; var cv = require('opencv'); function Processing(settings, options) { if (!(this instanceof Processing)) return new Processing(options); if (options === undefined) options = {}; options.objectMode = true; Transform.call(this, options); this.settings = settings; this.decodeSettings(); } util.inherits(Processing, Transform); Processing.prototype.decodeSettings = function() { var profile = this.settings.profile; this.profile = this.settings[profile]; this.lowerbound = this.profile.lowerb.reverse(); this.upperbound = this.profile.upperb.reverse(); }; /** * Expects a full image */ Processing.prototype._transform = function(chunk, encoding, callback) { var self = this; cv.readImage(chunk, function(err, image) { // Color filter image.inRange(self.lowerbound, self.upperbound); // Do canny operations on a copy var im_canny = image.copy(); // Feature detection with canny algorithm im_canny.canny(self.settings.lowThresh, self.settings.highThresh); im_canny.dilate(self.settings.nIters); // All done self.push({ 'original': chunk, 'image': image }); callback(); }); }; module.exports = Processing;
team178/oculus.js
lib/processing.js
JavaScript
mpl-2.0
1,968
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileOverview WebAudio layout test utility library. Built around W3C's * testharness.js. Includes asynchronous test task manager, * assertion utilities. * @dependency testharness.js */ (function() { 'use strict'; // Selected methods from testharness.js. let testharnessProperties = [ 'test', 'async_test', 'promise_test', 'promise_rejects', 'generate_tests', 'setup', 'done', 'assert_true', 'assert_false' ]; // Check if testharness.js is properly loaded. Throw otherwise. for (let name in testharnessProperties) { if (!self.hasOwnProperty(testharnessProperties[name])) throw new Error('Cannot proceed. testharness.js is not loaded.'); } })(); window.Audit = (function() { 'use strict'; // NOTE: Moving this method (or any other code above) will change the location // of 'CONSOLE ERROR...' message in the expected text files. function _logError(message) { console.error('[audit.js] ' + message); } function _logPassed(message) { test(function(arg) { assert_true(true); }, message); } function _logFailed(message, detail) { test(function() { assert_true(false, detail); }, message); } function _throwException(message) { throw new Error(message); } // TODO(hongchan): remove this hack after confirming all the tests are // finished correctly. (crbug.com/708817) const _testharnessDone = window.done; window.done = () => { _throwException('Do NOT call done() method from the test code.'); }; // Generate a descriptive string from a target value in various types. function _generateDescription(target, options) { let targetString; switch (typeof target) { case 'object': // Handle Arrays. if (target instanceof Array || target instanceof Float32Array || target instanceof Float64Array || target instanceof Uint8Array) { let arrayElements = target.length < options.numberOfArrayElements ? String(target) : String(target.slice(0, options.numberOfArrayElements)) + '...'; targetString = '[' + arrayElements + ']'; } else if (target === null) { targetString = String(target); } else { targetString = '' + String(target).split(/[\s\]]/)[1]; } break; case 'function': if (Error.isPrototypeOf(target)) { targetString = "EcmaScript error " + target.name; } else { targetString = String(target); } break; default: targetString = String(target); break; } return targetString; } // Return a string suitable for printing one failed element in // |beCloseToArray|. function _formatFailureEntry(index, actual, expected, abserr, threshold) { return '\t[' + index + ']\t' + actual.toExponential(16) + '\t' + expected.toExponential(16) + '\t' + abserr.toExponential(16) + '\t' + (abserr / Math.abs(expected)).toExponential(16) + '\t' + threshold.toExponential(16); } // Compute the error threshold criterion for |beCloseToArray| function _closeToThreshold(abserr, relerr, expected) { return Math.max(abserr, relerr * Math.abs(expected)); } /** * @class Should * @description Assertion subtask for the Audit task. * @param {Task} parentTask Associated Task object. * @param {Any} actual Target value to be tested. * @param {String} actualDescription String description of the test target. */ class Should { constructor(parentTask, actual, actualDescription) { this._task = parentTask; this._actual = actual; this._actualDescription = (actualDescription || null); this._expected = null; this._expectedDescription = null; this._detail = ''; // If true and the test failed, print the actual value at the // end of the message. this._printActualForFailure = true; this._result = null; /** * @param {Number} numberOfErrors Number of errors to be printed. * @param {Number} numberOfArrayElements Number of array elements to be * printed in the test log. * @param {Boolean} verbose Verbose output from the assertion. */ this._options = { numberOfErrors: 4, numberOfArrayElements: 16, verbose: false }; } _processArguments(args) { if (args.length === 0) return; if (args.length > 0) this._expected = args[0]; if (typeof args[1] === 'string') { // case 1: (expected, description, options) this._expectedDescription = args[1]; Object.assign(this._options, args[2]); } else if (typeof args[1] === 'object') { // case 2: (expected, options) Object.assign(this._options, args[1]); } } _buildResultText() { if (this._result === null) _throwException('Illegal invocation: the assertion is not finished.'); let actualString = _generateDescription(this._actual, this._options); // Use generated text when the description is not provided. if (!this._actualDescription) this._actualDescription = actualString; if (!this._expectedDescription) { this._expectedDescription = _generateDescription(this._expected, this._options); } // For the assertion with a single operand. this._detail = this._detail.replace(/\$\{actual\}/g, this._actualDescription); // If there is a second operand (i.e. expected value), we have to build // the string for it as well. this._detail = this._detail.replace(/\$\{expected\}/g, this._expectedDescription); // If there is any property in |_options|, replace the property name // with the value. for (let name in this._options) { if (name === 'numberOfErrors' || name === 'numberOfArrayElements' || name === 'verbose') { continue; } // The RegExp key string contains special character. Take care of it. let re = '\$\{' + name + '\}'; re = re.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); this._detail = this._detail.replace( new RegExp(re, 'g'), _generateDescription(this._options[name])); } // If the test failed, add the actual value at the end. if (this._result === false && this._printActualForFailure === true) { this._detail += ' Got ' + actualString + '.'; } } _finalize() { if (this._result) { _logPassed(' ' + this._detail); } else { _logFailed('X ' + this._detail); } // This assertion is finished, so update the parent task accordingly. this._task.update(this); // TODO(hongchan): configurable 'detail' message. } _assert(condition, passDetail, failDetail) { this._result = Boolean(condition); this._detail = this._result ? passDetail : failDetail; this._buildResultText(); this._finalize(); return this._result; } get result() { return this._result; } get detail() { return this._detail; } /** * should() assertions. * * @example All the assertions can have 1, 2 or 3 arguments: * should().doAssert(expected); * should().doAssert(expected, options); * should().doAssert(expected, expectedDescription, options); * * @param {Any} expected Expected value of the assertion. * @param {String} expectedDescription Description of expected value. * @param {Object} options Options for assertion. * @param {Number} options.numberOfErrors Number of errors to be printed. * (if applicable) * @param {Number} options.numberOfArrayElements Number of array elements * to be printed. (if * applicable) * @notes Some assertions can have additional options for their specific * testing. */ /** * Check if |actual| exists. * * @example * should({}, 'An empty object').exist(); * @result * "PASS An empty object does exist." */ exist() { return this._assert( this._actual !== null && this._actual !== undefined, '${actual} does exist.', '${actual} does not exist.'); } /** * Check if |actual| operation wrapped in a function throws an exception * with a expected error type correctly. |expected| is optional. If it is an * instance of DOMException, then the description (second argument) can be * provided to be more strict about the expected exception type. |expected| * also can be other generic error types such as TypeError, RangeError or * etc. * * @example * should(() => { let a = b; }, 'A bad code').throw(); * should(() => { new SomeConstructor(); }, 'A bad construction') * .throw(DOMException, 'NotSupportedError'); * should(() => { let c = d; }, 'Assigning d to c') * .throw(ReferenceError); * should(() => { let e = f; }, 'Assigning e to f') * .throw(ReferenceError, { omitErrorMessage: true }); * * @result * "PASS A bad code threw an exception of ReferenceError: b is not * defined." * "PASS A bad construction threw DOMException:NotSupportedError." * "PASS Assigning d to c threw ReferenceError: d is not defined." * "PASS Assigning e to f threw ReferenceError: [error message * omitted]." */ throw() { this._processArguments(arguments); this._printActualForFailure = false; let didThrowCorrectly = false; let passDetail, failDetail; try { // This should throw. this._actual(); // Catch did not happen, so the test is failed. failDetail = '${actual} did not throw an exception.'; } catch (error) { let errorMessage = this._options.omitErrorMessage ? ': [error message omitted]' : ': "' + error.message + '"'; if (this._expected === null || this._expected === undefined) { // The expected error type was not given. didThrowCorrectly = true; passDetail = '${actual} threw ' + error.name + errorMessage + '.'; } else if (this._expected === DOMException && (this._expectedDescription === undefined || this._expectedDescription === error.name)) { // Handles DOMException with the associated name. didThrowCorrectly = true; passDetail = '${actual} threw ${expected}' + errorMessage + '.'; } else if (this._expected == error.constructor) { // Handler other error types. didThrowCorrectly = true; passDetail = '${actual} threw ' + error.name + errorMessage + '.'; } else { didThrowCorrectly = false; failDetail = '${actual} threw "' + error.name + '" instead of ${expected}.'; } } return this._assert(didThrowCorrectly, passDetail, failDetail); } /** * Check if |actual| operation wrapped in a function does not throws an * exception correctly. * * @example * should(() => { let foo = 'bar'; }, 'let foo = "bar"').notThrow(); * * @result * "PASS let foo = "bar" did not throw an exception." */ notThrow() { this._printActualForFailure = false; let didThrowCorrectly = false; let passDetail, failDetail; try { this._actual(); passDetail = '${actual} did not throw an exception.'; } catch (error) { didThrowCorrectly = true; failDetail = '${actual} incorrectly threw ' + error.name + ': "' + error.message + '".'; } return this._assert(!didThrowCorrectly, passDetail, failDetail); } /** * Check if |actual| promise is resolved correctly. Note that the returned * result from promise object will be passed to the following then() * function. * * @example * should('My promise', promise).beResolve().then((result) => { * log(result); * }); * * @result * "PASS My promise resolved correctly." * "FAIL X My promise rejected *INCORRECTLY* with _ERROR_." */ beResolved() { return this._actual.then( function(result) { this._assert(true, '${actual} resolved correctly.', null); return result; }.bind(this), function(error) { this._assert( false, null, '${actual} rejected incorrectly with ' + error + '.'); }.bind(this)); } /** * Check if |actual| promise is rejected correctly. * * @example * should('My promise', promise).beRejected().then(nextStuff); * * @result * "PASS My promise rejected correctly (with _ERROR_)." * "FAIL X My promise resolved *INCORRECTLY*." */ beRejected() { return this._actual.then( function() { this._assert(false, null, '${actual} resolved incorrectly.'); }.bind(this), function(error) { this._assert( true, '${actual} rejected correctly with ' + error + '.', null); }.bind(this)); } /** * Check if |actual| promise is rejected correctly. * * @example * should(promise, 'My promise').beRejectedWith('_ERROR_').then(); * * @result * "PASS My promise rejected correctly with _ERROR_." * "FAIL X My promise rejected correctly but got _ACTUAL_ERROR instead of * _EXPECTED_ERROR_." * "FAIL X My promise resolved incorrectly." */ beRejectedWith() { this._processArguments(arguments); return this._actual.then( function() { this._assert(false, null, '${actual} resolved incorrectly.'); }.bind(this), function(error) { if (this._expected !== error.name) { this._assert( false, null, '${actual} rejected correctly but got ' + error.name + ' instead of ' + this._expected + '.'); } else { this._assert( true, '${actual} rejected correctly with ' + this._expected + '.', null); } }.bind(this)); } /** * Check if |actual| is a boolean true. * * @example * should(3 < 5, '3 < 5').beTrue(); * * @result * "PASS 3 < 5 is true." */ beTrue() { return this._assert( this._actual === true, '${actual} is true.', '${actual} is not true.'); } /** * Check if |actual| is a boolean false. * * @example * should(3 > 5, '3 > 5').beFalse(); * * @result * "PASS 3 > 5 is false." */ beFalse() { return this._assert( this._actual === false, '${actual} is false.', '${actual} is not false.'); } /** * Check if |actual| is strictly equal to |expected|. (no type coercion) * * @example * should(1).beEqualTo(1); * * @result * "PASS 1 is equal to 1." */ beEqualTo() { this._processArguments(arguments); return this._assert( this._actual === this._expected, '${actual} is equal to ${expected}.', '${actual} is not equal to ${expected}.'); } /** * Check if |actual| is not equal to |expected|. * * @example * should(1).notBeEqualTo(2); * * @result * "PASS 1 is not equal to 2." */ notBeEqualTo() { this._processArguments(arguments); return this._assert( this._actual !== this._expected, '${actual} is not equal to ${expected}.', '${actual} should not be equal to ${expected}.'); } /** * check if |actual| is NaN * * @example * should(NaN).beNaN(); * * @result * "PASS NaN is NaN" * */ beNaN() { this._processArguments(arguments); return this._assert( isNaN(this._actual), '${actual} is NaN.', '${actual} is not NaN but should be.'); } /** * check if |actual| is NOT NaN * * @example * should(42).notBeNaN(); * * @result * "PASS 42 is not NaN" * */ notBeNaN() { this._processArguments(arguments); return this._assert( !isNaN(this._actual), '${actual} is not NaN.', '${actual} is NaN but should not be.'); } /** * Check if |actual| is greater than |expected|. * * @example * should(2).beGreaterThanOrEqualTo(2); * * @result * "PASS 2 is greater than or equal to 2." */ beGreaterThan() { this._processArguments(arguments); return this._assert( this._actual > this._expected, '${actual} is greater than ${expected}.', '${actual} is not greater than ${expected}.'); } /** * Check if |actual| is greater than or equal to |expected|. * * @example * should(2).beGreaterThan(1); * * @result * "PASS 2 is greater than 1." */ beGreaterThanOrEqualTo() { this._processArguments(arguments); return this._assert( this._actual >= this._expected, '${actual} is greater than or equal to ${expected}.', '${actual} is not greater than or equal to ${expected}.'); } /** * Check if |actual| is less than |expected|. * * @example * should(1).beLessThan(2); * * @result * "PASS 1 is less than 2." */ beLessThan() { this._processArguments(arguments); return this._assert( this._actual < this._expected, '${actual} is less than ${expected}.', '${actual} is not less than ${expected}.'); } /** * Check if |actual| is less than or equal to |expected|. * * @example * should(1).beLessThanOrEqualTo(1); * * @result * "PASS 1 is less than or equal to 1." */ beLessThanOrEqualTo() { this._processArguments(arguments); return this._assert( this._actual <= this._expected, '${actual} is less than or equal to ${expected}.', '${actual} is not less than or equal to ${expected}.'); } /** * Check if |actual| array is filled with a constant |expected| value. * * @example * should([1, 1, 1]).beConstantValueOf(1); * * @result * "PASS [1,1,1] contains only the constant 1." */ beConstantValueOf() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; let errors = {}; let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { if (actual[index] !== expected) errors[index] = actual[index]; } let numberOfErrors = Object.keys(errors).length; passed = numberOfErrors === 0; if (passed) { passDetail = '${actual} contains only the constant ${expected}.'; } else { let counter = 0; failDetail = '${actual}: Expected ${expected} for all values but found ' + numberOfErrors + ' unexpected values: '; failDetail += '\n\tIndex\tActual'; for (let errorIndex in errors) { failDetail += '\n\t[' + errorIndex + ']' + '\t' + errors[errorIndex]; if (++counter >= this._options.numberOfErrors) { failDetail += '\n\t...and ' + (numberOfErrors - counter) + ' more errors.'; break; } } } return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| array is not filled with a constant |expected| value. * * @example * should([1, 0, 1]).notBeConstantValueOf(1); * should([0, 0, 0]).notBeConstantValueOf(0); * * @result * "PASS [1,0,1] is not constantly 1 (contains 1 different value)." * "FAIL X [0,0,0] should have contain at least one value different * from 0." */ notBeConstantValueOf() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail; let failDetail; let differences = {}; let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { if (actual[index] !== expected) differences[index] = actual[index]; } let numberOfDifferences = Object.keys(differences).length; passed = numberOfDifferences > 0; if (passed) { let valueString = numberOfDifferences > 1 ? 'values' : 'value'; passDetail = '${actual} is not constantly ${expected} (contains ' + numberOfDifferences + ' different ' + valueString + ').'; } else { failDetail = '${actual} should have contain at least one value ' + 'different from ${expected}.'; } return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| array is identical to |expected| array element-wise. * * @example * should([1, 2, 3]).beEqualToArray([1, 2, 3]); * * @result * "[1,2,3] is identical to the array [1,2,3]." */ beEqualToArray() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; let errorIndices = []; if (this._actual.length !== this._expected.length) { passed = false; failDetail = 'The array length does not match.'; return this._assert(passed, passDetail, failDetail); } let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { if (actual[index] !== expected[index]) errorIndices.push(index); } passed = errorIndices.length === 0; if (passed) { passDetail = '${actual} is identical to the array ${expected}.'; } else { let counter = 0; failDetail = '${actual} expected to be equal to the array ${expected} ' + 'but differs in ' + errorIndices.length + ' places:' + '\n\tIndex\tActual\t\t\tExpected'; for (let index of errorIndices) { failDetail += '\n\t[' + index + ']' + '\t' + this._actual[index].toExponential(16) + '\t' + this._expected[index].toExponential(16); if (++counter >= this._options.numberOfErrors) { failDetail += '\n\t...and ' + (errorIndices.length - counter) + ' more errors.'; break; } } } return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| array contains only the values in |expected| in the * order of values in |expected|. * * @example * Should([1, 1, 3, 3, 2], 'My random array').containValues([1, 3, 2]); * * @result * "PASS [1,1,3,3,2] contains all the expected values in the correct * order: [1,3,2]. */ containValues() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let indexedActual = []; let firstErrorIndex = null; // Collect the unique value sequence from the actual. for (let i = 0, prev = null; i < this._actual.length; i++) { if (this._actual[i] !== prev) { indexedActual.push({index: i, value: this._actual[i]}); prev = this._actual[i]; } } // Compare against the expected sequence. let failMessage = '${actual} expected to have the value sequence of ${expected} but ' + 'got '; if (this._expected.length === indexedActual.length) { for (let j = 0; j < this._expected.length; j++) { if (this._expected[j] !== indexedActual[j].value) { firstErrorIndex = indexedActual[j].index; passed = false; failMessage += this._actual[firstErrorIndex] + ' at index ' + firstErrorIndex + '.'; break; } } } else { passed = false; let indexedValues = indexedActual.map(x => x.value); failMessage += `${indexedActual.length} values, [${ indexedValues}], instead of ${this._expected.length}.`; } return this._assert( passed, '${actual} contains all the expected values in the correct order: ' + '${expected}.', failMessage); } /** * Check if |actual| array does not have any glitches. Note that |threshold| * is not optional and is to define the desired threshold value. * * @example * should([0.5, 0.5, 0.55, 0.5, 0.45, 0.5]).notGlitch(0.06); * * @result * "PASS [0.5,0.5,0.55,0.5,0.45,0.5] has no glitch above the threshold * of 0.06." * */ notGlitch() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { let diff = Math.abs(actual[index - 1] - actual[index]); if (diff >= expected) { passed = false; failDetail = '${actual} has a glitch at index ' + index + ' of size ' + diff + '.'; } } passDetail = '${actual} has no glitch above the threshold of ${expected}.'; return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| is close to |expected| using the given relative error * |threshold|. * * @example * should(2.3).beCloseTo(2, { threshold: 0.3 }); * * @result * "PASS 2.3 is 2 within an error of 0.3." * @param {Object} options Options for assertion. * @param {Number} options.threshold Threshold value for the comparison. */ beCloseTo() { this._processArguments(arguments); // The threshold is relative except when |expected| is zero, in which case // it is absolute. let absExpected = this._expected ? Math.abs(this._expected) : 1; let error = Math.abs(this._actual - this._expected) / absExpected; // debugger; return this._assert( error <= this._options.threshold, '${actual} is ${expected} within an error of ${threshold}.', '${actual} is not close to ${expected} within a relative error of ' + '${threshold} (RelErr=' + error + ').'); } /** * Check if |target| array is close to |expected| array element-wise within * a certain error bound given by the |options|. * * The error criterion is: * abs(actual[k] - expected[k]) < max(absErr, relErr * abs(expected)) * * If nothing is given for |options|, then absErr = relErr = 0. If * absErr = 0, then the error criterion is a relative error. A non-zero * absErr value produces a mix intended to handle the case where the * expected value is 0, allowing the target value to differ by absErr from * the expected. * * @param {Number} options.absoluteThreshold Absolute threshold. * @param {Number} options.relativeThreshold Relative threshold. */ beCloseToArray() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; // Parsing options. let absErrorThreshold = (this._options.absoluteThreshold || 0); let relErrorThreshold = (this._options.relativeThreshold || 0); // A collection of all of the values that satisfy the error criterion. // This holds the absolute difference between the target element and the // expected element. let errors = {}; // Keep track of the max absolute error found. let maxAbsError = -Infinity, maxAbsErrorIndex = -1; // Keep track of the max relative error found, ignoring cases where the // relative error is Infinity because the expected value is 0. let maxRelError = -Infinity, maxRelErrorIndex = -1; let actual = this._actual; let expected = this._expected; for (let index = 0; index < expected.length; ++index) { let diff = Math.abs(actual[index] - expected[index]); let absExpected = Math.abs(expected[index]); let relError = diff / absExpected; if (diff > Math.max(absErrorThreshold, relErrorThreshold * absExpected)) { if (diff > maxAbsError) { maxAbsErrorIndex = index; maxAbsError = diff; } if (!isNaN(relError) && relError > maxRelError) { maxRelErrorIndex = index; maxRelError = relError; } errors[index] = diff; } } let numberOfErrors = Object.keys(errors).length; let maxAllowedErrorDetail = JSON.stringify({ absoluteThreshold: absErrorThreshold, relativeThreshold: relErrorThreshold }); if (numberOfErrors === 0) { // The assertion was successful. passDetail = '${actual} equals ${expected} with an element-wise ' + 'tolerance of ' + maxAllowedErrorDetail + '.'; } else { // Failed. Prepare the detailed failure log. passed = false; failDetail = '${actual} does not equal ${expected} with an ' + 'element-wise tolerance of ' + maxAllowedErrorDetail + '.\n'; // Print out actual, expected, absolute error, and relative error. let counter = 0; failDetail += '\tIndex\tActual\t\t\tExpected\t\tAbsError' + '\t\tRelError\t\tTest threshold'; let printedIndices = []; for (let index in errors) { failDetail += '\n' + _formatFailureEntry( index, actual[index], expected[index], errors[index], _closeToThreshold( absErrorThreshold, relErrorThreshold, expected[index])); printedIndices.push(index); if (++counter > this._options.numberOfErrors) { failDetail += '\n\t...and ' + (numberOfErrors - counter) + ' more errors.'; break; } } // Finalize the error log: print out the location of both the maxAbs // error and the maxRel error so we can adjust thresholds appropriately // in the test. failDetail += '\n' + '\tMax AbsError of ' + maxAbsError.toExponential(16) + ' at index of ' + maxAbsErrorIndex + '.\n'; if (printedIndices.find(element => { return element == maxAbsErrorIndex; }) === undefined) { // Print an entry for this index if we haven't already. failDetail += _formatFailureEntry( maxAbsErrorIndex, actual[maxAbsErrorIndex], expected[maxAbsErrorIndex], errors[maxAbsErrorIndex], _closeToThreshold( absErrorThreshold, relErrorThreshold, expected[maxAbsErrorIndex])) + '\n'; } failDetail += '\tMax RelError of ' + maxRelError.toExponential(16) + ' at index of ' + maxRelErrorIndex + '.\n'; if (printedIndices.find(element => { return element == maxRelErrorIndex; }) === undefined) { // Print an entry for this index if we haven't already. failDetail += _formatFailureEntry( maxRelErrorIndex, actual[maxRelErrorIndex], expected[maxRelErrorIndex], errors[maxRelErrorIndex], _closeToThreshold( absErrorThreshold, relErrorThreshold, expected[maxRelErrorIndex])) + '\n'; } } return this._assert(passed, passDetail, failDetail); } /** * A temporary escape hat for printing an in-task message. The description * for the |actual| is required to get the message printed properly. * * TODO(hongchan): remove this method when the transition from the old Audit * to the new Audit is completed. * @example * should(true, 'The message is').message('truthful!', 'false!'); * * @result * "PASS The message is truthful!" */ message(passDetail, failDetail) { return this._assert( this._actual, '${actual} ' + passDetail, '${actual} ' + failDetail); } /** * Check if |expected| property is truly owned by |actual| object. * * @example * should(BaseAudioContext.prototype, * 'BaseAudioContext.prototype').haveOwnProperty('createGain'); * * @result * "PASS BaseAudioContext.prototype has an own property of * 'createGain'." */ haveOwnProperty() { this._processArguments(arguments); return this._assert( this._actual.hasOwnProperty(this._expected), '${actual} has an own property of "${expected}".', '${actual} does not own the property of "${expected}".'); } /** * Check if |expected| property is not owned by |actual| object. * * @example * should(BaseAudioContext.prototype, * 'BaseAudioContext.prototype') * .notHaveOwnProperty('startRendering'); * * @result * "PASS BaseAudioContext.prototype does not have an own property of * 'startRendering'." */ notHaveOwnProperty() { this._processArguments(arguments); return this._assert( !this._actual.hasOwnProperty(this._expected), '${actual} does not have an own property of "${expected}".', '${actual} has an own the property of "${expected}".') } /** * Check if an object is inherited from a class. This looks up the entire * prototype chain of a given object and tries to find a match. * * @example * should(sourceNode, 'A buffer source node') * .inheritFrom('AudioScheduledSourceNode'); * * @result * "PASS A buffer source node inherits from 'AudioScheduledSourceNode'." */ inheritFrom() { this._processArguments(arguments); let prototypes = []; let currentPrototype = Object.getPrototypeOf(this._actual); while (currentPrototype) { prototypes.push(currentPrototype.constructor.name); currentPrototype = Object.getPrototypeOf(currentPrototype); } return this._assert( prototypes.includes(this._expected), '${actual} inherits from "${expected}".', '${actual} does not inherit from "${expected}".'); } } // Task Class state enum. const TaskState = {PENDING: 0, STARTED: 1, FINISHED: 2}; /** * @class Task * @description WebAudio testing task. Managed by TaskRunner. */ class Task { /** * Task constructor. * @param {Object} taskRunner Reference of associated task runner. * @param {String||Object} taskLabel Task label if a string is given. This * parameter can be a dictionary with the * following fields. * @param {String} taskLabel.label Task label. * @param {String} taskLabel.description Description of task. * @param {Function} taskFunction Task function to be performed. * @return {Object} Task object. */ constructor(taskRunner, taskLabel, taskFunction) { this._taskRunner = taskRunner; this._taskFunction = taskFunction; if (typeof taskLabel === 'string') { this._label = taskLabel; this._description = null; } else if (typeof taskLabel === 'object') { if (typeof taskLabel.label !== 'string') { _throwException('Task.constructor:: task label must be string.'); } this._label = taskLabel.label; this._description = (typeof taskLabel.description === 'string') ? taskLabel.description : null; } else { _throwException( 'Task.constructor:: task label must be a string or ' + 'a dictionary.'); } this._state = TaskState.PENDING; this._result = true; this._totalAssertions = 0; this._failedAssertions = 0; } get label() { return this._label; } get state() { return this._state; } get result() { return this._result; } // Start the assertion chain. should(actual, actualDescription) { // If no argument is given, we cannot proceed. Halt. if (arguments.length === 0) _throwException('Task.should:: requires at least 1 argument.'); return new Should(this, actual, actualDescription); } // Run this task. |this| task will be passed into the user-supplied test // task function. run(harnessTest) { this._state = TaskState.STARTED; this._harnessTest = harnessTest; // Print out the task entry with label and description. _logPassed( '> [' + this._label + '] ' + (this._description ? this._description : '')); return new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; let result = this._taskFunction(this, this.should.bind(this)); if (result && typeof result.then === "function") { result.then(() => this.done()).catch(reject); } }); } // Update the task success based on the individual assertion/test inside. update(subTask) { // After one of tests fails within a task, the result is irreversible. if (subTask.result === false) { this._result = false; this._failedAssertions++; } this._totalAssertions++; } // Finish the current task and start the next one if available. done() { assert_equals(this._state, TaskState.STARTED) this._state = TaskState.FINISHED; let message = '< [' + this._label + '] '; if (this._result) { message += 'All assertions passed. (total ' + this._totalAssertions + ' assertions)'; _logPassed(message); } else { message += this._failedAssertions + ' out of ' + this._totalAssertions + ' assertions were failed.' _logFailed(message); } this._resolve(); } // Runs |subTask| |time| milliseconds later. |setTimeout| is not allowed in // WPT linter, so a thin wrapper around the harness's |step_timeout| is // used here. Returns a Promise which is resolved after |subTask| runs. timeout(subTask, time) { return new Promise(resolve => { this._harnessTest.step_timeout(() => { let result = subTask(); if (result && typeof result.then === "function") { // Chain rejection directly to the harness test Promise, to report // the rejection against the subtest even when the caller of // timeout does not handle the rejection. result.then(resolve, this._reject()); } else { resolve(); } }, time); }); } isPassed() { return this._state === TaskState.FINISHED && this._result; } toString() { return '"' + this._label + '": ' + this._description; } } /** * @class TaskRunner * @description WebAudio testing task runner. Manages tasks. */ class TaskRunner { constructor() { this._tasks = {}; this._taskSequence = []; // Configure testharness.js for the async operation. setup(new Function(), {explicit_done: true}); } _finish() { let numberOfFailures = 0; for (let taskIndex in this._taskSequence) { let task = this._tasks[this._taskSequence[taskIndex]]; numberOfFailures += task.result ? 0 : 1; } let prefix = '# AUDIT TASK RUNNER FINISHED: '; if (numberOfFailures > 0) { _logFailed( prefix + numberOfFailures + ' out of ' + this._taskSequence.length + ' tasks were failed.'); } else { _logPassed( prefix + this._taskSequence.length + ' tasks ran successfully.'); } return Promise.resolve(); } // |taskLabel| can be either a string or a dictionary. See Task constructor // for the detail. If |taskFunction| returns a thenable, then the task // is considered complete when the thenable is fulfilled; otherwise the // task must be completed with an explicit call to |task.done()|. define(taskLabel, taskFunction) { let task = new Task(this, taskLabel, taskFunction); if (this._tasks.hasOwnProperty(task.label)) { _throwException('Audit.define:: Duplicate task definition.'); return; } this._tasks[task.label] = task; this._taskSequence.push(task.label); } // Start running all the tasks scheduled. Multiple task names can be passed // to execute them sequentially. Zero argument will perform all defined // tasks in the order of definition. run() { // Display the beginning of the test suite. _logPassed('# AUDIT TASK RUNNER STARTED.'); // If the argument is specified, override the default task sequence with // the specified one. if (arguments.length > 0) { this._taskSequence = []; for (let i = 0; i < arguments.length; i++) { let taskLabel = arguments[i]; if (!this._tasks.hasOwnProperty(taskLabel)) { _throwException('Audit.run:: undefined task.'); } else if (this._taskSequence.includes(taskLabel)) { _throwException('Audit.run:: duplicate task request.'); } else { this._taskSequence.push(taskLabel); } } } if (this._taskSequence.length === 0) { _throwException('Audit.run:: no task to run.'); return; } for (let taskIndex in this._taskSequence) { let task = this._tasks[this._taskSequence[taskIndex]]; // Some tests assume that tasks run in sequence, which is provided by // promise_test(). promise_test((t) => task.run(t), `Executing "${task.label}"`); } // Schedule a summary report on completion. promise_test(() => this._finish(), "Audit report"); // From testharness.js. The harness now need not wait for more subtests // to be added. _testharnessDone(); } } /** * Load file from a given URL and pass ArrayBuffer to the following promise. * @param {String} fileUrl file URL. * @return {Promise} * * @example * Audit.loadFileFromUrl('resources/my-sound.ogg').then((response) => { * audioContext.decodeAudioData(response).then((audioBuffer) => { * // Do something with AudioBuffer. * }); * }); */ function loadFileFromUrl(fileUrl) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open('GET', fileUrl, true); xhr.responseType = 'arraybuffer'; xhr.onload = () => { // |status = 0| is a workaround for the run_web_test.py server. We are // speculating the server quits the transaction prematurely without // completing the request. if (xhr.status === 200 || xhr.status === 0) { resolve(xhr.response); } else { let errorMessage = 'loadFile: Request failed when loading ' + fileUrl + '. ' + xhr.statusText + '. (status = ' + xhr.status + ')'; if (reject) { reject(errorMessage); } else { new Error(errorMessage); } } }; xhr.onerror = (event) => { let errorMessage = 'loadFile: Network failure when loading ' + fileUrl + '.'; if (reject) { reject(errorMessage); } else { new Error(errorMessage); } }; xhr.send(); }); } /** * @class Audit * @description A WebAudio layout test task manager. * @example * let audit = Audit.createTaskRunner(); * audit.define('first-task', function (task, should) { * should(someValue).beEqualTo(someValue); * task.done(); * }); * audit.run(); */ return { /** * Creates an instance of Audit task runner. * @param {Object} options Options for task runner. * @param {Boolean} options.requireResultFile True if the test suite * requires explicit text * comparison with the expected * result file. */ createTaskRunner: function(options) { if (options && options.requireResultFile == true) { _logError( 'this test requires the explicit comparison with the ' + 'expected result when it runs with run_web_tests.py.'); } return new TaskRunner(); }, /** * Load file from a given URL and pass ArrayBuffer to the following promise. * See |loadFileFromUrl| method for the detail. */ loadFileFromUrl: loadFileFromUrl }; })();
DominoTree/servo
tests/wpt/web-platform-tests/webaudio/resources/audit.js
JavaScript
mpl-2.0
46,546
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.orginal.ast; import org.mozilla.javascript.orginal.Token; /** * AST node for a single name:value entry in an Object literal. * For simple entries, the node type is {@link Token#COLON}, and * the name (left side expression) is either a {@link Name}, a * {@link StringLiteral} or a {@link NumberLiteral}.<p> * * This node type is also used for getter/setter properties in object * literals. In this case the node bounds include the "get" or "set" * keyword. The left-hand expression in this case is always a * {@link Name}, and the overall node type is {@link Token#GET} or * {@link Token#SET}, as appropriate.<p> * * The {@code operatorPosition} field is meaningless if the node is * a getter or setter.<p> * * <pre><i>ObjectProperty</i> : * PropertyName <b>:</b> AssignmentExpression * <i>PropertyName</i> : * Identifier * StringLiteral * NumberLiteral</pre> */ public class ObjectProperty extends InfixExpression { { type = Token.COLON; } /** * Sets the node type. Must be one of * {@link Token#COLON}, {@link Token#GET}, or {@link Token#SET}. * @throws IllegalArgumentException if {@code nodeType} is invalid */ public void setNodeType(int nodeType) { if (nodeType != Token.COLON && nodeType != Token.GET && nodeType != Token.SET) throw new IllegalArgumentException("invalid node type: " + nodeType); setType(nodeType); } public ObjectProperty() { } public ObjectProperty(int pos) { super(pos); } public ObjectProperty(int pos, int len) { super(pos, len); } /** * Marks this node as a "getter" property. */ public void setIsGetter() { type = Token.GET; } /** * Returns true if this is a getter function. */ public boolean isGetter() { return type == Token.GET; } /** * Marks this node as a "setter" property. */ public void setIsSetter() { type = Token.SET; } /** * Returns true if this is a setter function. */ public boolean isSetter() { return type == Token.SET; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); if (isGetter()) { sb.append("get "); } else if (isSetter()) { sb.append("set "); } sb.append(left.toSource(0)); if (type == Token.COLON) { sb.append(": "); } sb.append(right.toSource(0)); return sb.toString(); } }
WolframG/Rhino-Prov-Mod
src/org/mozilla/javascript/orginal/ast/ObjectProperty.java
Java
mpl-2.0
3,013
/* * taskapi. */ var input_taskname_text = '<input type="text" id="task_name_{0}" value="{1}" class="form-control">'; var input_taskdesc_text = '<input type="text" id="task_desc_{0}" value="{1}" class="form-control">'; var btn_update_task = '<a href="#" class="btn-update-task btn btn-sm btn-success" data-taskid="{0}" id="task_update_btn_{0}">Update</a>&nbsp;'; var btn_remove_task = '<a href="#" class="{2} btn btn-sm btn-danger" data-taskid="{0}" id="taskbtn_{0}">{1}</a>'; var taskilyTasks = (function (survey, table) { var tsk = {}; var tableID = table; var surveyID = survey; tsk.loadTasks = function() { $.ajax({ url: '/api/tasks/all/' + surveyID, type: 'GET', success: function(data) { for (var i = 0; i < data.length; i++) { var activeclass = ''; if (data[i].Active == false) { activeclass = 'task-row-inactive'; } var row = ['<tr id="taskrow_' + data[i].ID + '" class="task-row '+ activeclass + '">', '<td>' + input_taskname_text.format(data[i].ID, data[i].Name) + '</td>', '<td>' + input_taskdesc_text.format(data[i].ID, data[i].Description) + '</td>'] ; if (data[i].Active == true) { row.push('<td>' + btn_update_task.format(data[i].ID) + btn_remove_task.format(data[i].ID, 'Remove', 'btn-remove-task') + '</td>'); } else { row.push('<td>' + btn_remove_task.format(data[i].ID, 'Activate', 'btn-activate-task') + '</td>') ; } row.push('</tr>'); $( row.join() ).appendTo(tableID); } bindTaskButtons(); }, error: function(msg) { alert(msg); } }); } function bindTaskButtons() { $(".btn-remove-task").click(function (e) { e.stopPropagation(); e.preventDefault(); var taskID = $(this).data("taskid"); removeTask(taskID); }); $(".btn-update-task").click(function (e) { e.stopPropagation(); e.preventDefault(); var taskID = $(this).data("taskid"); updateTask(taskID); }); $("#addTask").click(function (e) { e.stopPropagation(); e.preventDefault(); var tName = $("#newTask").val(); var tDesc = $("#newDesc").val(); addTask(tName, tDesc); }); $(".btn-activate-task").click(function (e) { e.stopPropagation(); e.preventDefault(); var taskID = $(this).data("taskid"); activateTask(taskID); }); } function removeTask(taskId) { $.ajax({ url: '/api/tasks/delete/' + taskId, type: 'DELETE', success: function (data) { if (data.Active == false) { toggleButton(data.ID); btn.unbind('click'); btn.click(function (e) { e.stopPropagation(); var taskID = $(this).data("taskid"); activateTask(taskID); }); } else { $("#taskrow_" + data.ID).fadeOut(); } }, error: function (data) { alert("Error removing task"); } }); } function updateTask(taskId) { var taskName = $("#task_name_" + taskId).val(); var taskDesc = $("#task_desc_" + taskId).val(); var task = { 'ID': taskId, 'SurveyID': surveyID, 'Name': taskName, 'Description': taskDesc }; $.ajax({ url: '/api/tasks/update/' + surveyID, type: 'POST', contentType: 'application/json', data: JSON.stringify(task), success: function (data) { var row = $('#taskrow_' + data.ID).addClass('task-done') ; setTimeout(function () { row.toggleClass('task-done'); }, 1000); }, error: function (msg) { alert('failed to update task'); } }); } function activateTask(taskId) { $.ajax({ url: '/api/tasks/activate/' + taskId, type: 'PUT', success: function (data) { toggleButton(data.ID); btn.unbind('click'); btn.click(function (e) { e.stopPropagation(); var taskID = $(this).data("taskid"); removeTask(taskID); }); }, error: function (data) { alert("Error activating task"); } }); } function toggleButton(taskId) { var btn = $('#taskbtn_' + taskId); var row = $('#taskrow_' + taskId).addClass('task-done'); if (btn.html() == 'Activate') { btn.addClass("btn-remove-task"); btn.addClass("btn-danger"); btn.removeClass("btn-activate-task"); btn.removeClass("btn-warning"); row.removeClass("task-row-inactive"); btn.html("Remove"); } else { btn.removeClass("btn-remove-task"); btn.removeClass("btn-danger"); btn.addClass("btn-activate-task"); btn.addClass("btn-warning"); btn.html("Activate"); row.addClass("task-row-inactive"); } setTimeout(function () { row.toggleClass('task-done'); }, 1000); } function addTask(name, description) { var task = { 'SurveyID': surveyID, 'Active': true, 'Name': name, 'Description': description }; $.ajax({ url: '/api/tasks/add/' + surveyID, type: 'POST', contentType: 'application/json', data: JSON.stringify(task), success: function (data) { $( ['<tr id="taskrow_' + data.ID + '" class="task-row">', '<td>' + input_taskname_text.format(data.ID, data.Name) + '</td>', '<td>' + input_taskdesc_text.format(data.ID, data.Description) + '</td>', '<td>' + btn_update_task.format(data.ID) + btn_remove_task.format(data.ID, 'Remove', 'btn-remove-task') + '</td>', '</tr>' ].join()).appendTo(tableID); }, error: function (msg) { alert( "Failed to add " + msg) } }); } return tsk; });
Jumoo/Taskily
TaskilyWeb/Scripts/admin/tasks.js
JavaScript
mpl-2.0
7,154
package de.textmode.afpbox.ptoca; /* * Copyright 2019 Michael Knigge * * 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. */ /** * Unit-Tests for the class {@link SetTextColor}. */ public final class SetTextColorTest extends PtocaControlSequenceTest<SetTextColor> { /** * Checks if a faulty STC is determined. */ public void testFaulty() throws Exception { this.parseAndExpectFailure("2BD3067400000000", "PTOCA control sequence STC has invalid length of 6 bytes (expected 4 or 5 bytes)"); } /** * Checks some correct STCs. */ public void testHappyFlow() throws Exception { final SetTextColor stc1 = this.parse("2BD30474FF01"); assertEquals(0xFF01, stc1.getForegroundColor()); assertEquals(0x00, stc1.getPrecision()); final SetTextColor stc2 = this.parse("2BD30575010201"); assertEquals(0x0102, stc2.getForegroundColor()); assertEquals(0x01, stc2.getPrecision()); } }
michaelknigge/afpbox
afpbox/src/test/java/de/textmode/afpbox/ptoca/SetTextColorTest.java
Java
mpl-2.0
1,497