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
/* * Copyright (C) 2020 Emweb bv, Herent, Belgium. * * See the LICENSE file for terms of use. */ package eu.webtoolkit.jwt.auth; import eu.webtoolkit.jwt.*; import eu.webtoolkit.jwt.chart.*; import eu.webtoolkit.jwt.servlet.*; import eu.webtoolkit.jwt.utils.*; import java.io.*; import java.lang.ref.*; import java.time.*; import java.util.*; import java.util.regex.*; import javax.servlet.*; import javax.servlet.http.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A widget which allows a user to choose a new password. * * <p>This widget lets a user choose a new password. * * <p>The widget renders the <code>&quot;Wt.Auth.template.update-password&quot;</code> template. * Optionally, it asks for the current password, as well as a new password. * * <p> * * @see AuthWidget#createUpdatePasswordView(User user, boolean promptPassword) */ public class UpdatePasswordWidget extends WTemplateFormView { private static Logger logger = LoggerFactory.getLogger(UpdatePasswordWidget.class); /** * Constructor. * * <p>If <code>authModel</code> is not <code>null</code>, the user also has to authenticate first * using his current password. */ public UpdatePasswordWidget( final User user, RegistrationModel registrationModel, final AuthModel authModel, WContainerWidget parentContainer) { super(tr("Wt.Auth.template.update-password"), (WContainerWidget) null); this.user_ = user; this.registrationModel_ = registrationModel; this.authModel_ = authModel; this.updated_ = new Signal(); this.canceled_ = new Signal(); this.registrationModel_.setValue( RegistrationModel.LoginNameField, user.getIdentity(Identity.LoginName)); this.registrationModel_.setReadOnly(RegistrationModel.LoginNameField, true); if (user.getPassword().isEmpty()) { this.authModel_ = null; } else { if (this.authModel_ != null) { this.authModel_.reset(); } } if (this.authModel_ != null && this.authModel_.getBaseAuth().isEmailVerificationEnabled()) { this.registrationModel_.setValue( RegistrationModel.EmailField, user.getEmail() + " " + user.getUnverifiedEmail()); } this.registrationModel_.setVisible(RegistrationModel.EmailField, false); WPushButton okButton = new WPushButton(tr("Wt.WMessageBox.Ok")); this.bindWidget("ok-button", okButton); WPushButton cancelButton = new WPushButton(tr("Wt.WMessageBox.Cancel")); this.bindWidget("cancel-button", cancelButton); if (this.authModel_ != null) { this.authModel_.setValue(AuthModel.LoginNameField, user.getIdentity(Identity.LoginName)); this.updateViewField(this.authModel_, AuthModel.PasswordField); this.authModel_.configureThrottling(okButton); WLineEdit password = (WLineEdit) this.resolveWidget(AuthModel.PasswordField); password.setFocus(true); } this.updateView(this.registrationModel_); WLineEdit password = (WLineEdit) this.resolveWidget(RegistrationModel.ChoosePasswordField); WLineEdit password2 = (WLineEdit) this.resolveWidget(RegistrationModel.RepeatPasswordField); WText password2Info = (WText) this.resolveWidget(RegistrationModel.RepeatPasswordField + "-info"); this.registrationModel_.validatePasswordsMatchJS(password, password2, password2Info); if (!(this.authModel_ != null)) { password.setFocus(true); } okButton .clicked() .addListener( this, (WMouseEvent e1) -> { UpdatePasswordWidget.this.doUpdate(); }); cancelButton .clicked() .addListener( this, (WMouseEvent e1) -> { UpdatePasswordWidget.this.cancel(); }); if (parentContainer != null) parentContainer.addWidget(this); } /** * Constructor. * * <p>Calls {@link #UpdatePasswordWidget(User user, RegistrationModel registrationModel, AuthModel * authModel, WContainerWidget parentContainer) this(user, registrationModel, authModel, * (WContainerWidget)null)} */ public UpdatePasswordWidget( final User user, RegistrationModel registrationModel, final AuthModel authModel) { this(user, registrationModel, authModel, (WContainerWidget) null); } /** {@link Signal} emitted when the password was updated. */ public Signal updated() { return this.updated_; } /** {@link Signal} emitted when cancel clicked. */ public Signal canceled() { return this.canceled_; } protected WWidget createFormWidget(String field) { WFormWidget result = null; if (field == RegistrationModel.LoginNameField) { result = new WLineEdit(); } else { if (field == AuthModel.PasswordField) { WLineEdit p = new WLineEdit(); p.setEchoMode(EchoMode.Password); result = p; } else { if (field == RegistrationModel.ChoosePasswordField) { WLineEdit p = new WLineEdit(); p.setEchoMode(EchoMode.Password); p.keyWentUp() .addListener( this, (WKeyEvent e1) -> { UpdatePasswordWidget.this.checkPassword(); }); p.changed() .addListener( this, () -> { UpdatePasswordWidget.this.checkPassword(); }); result = p; } else { if (field == RegistrationModel.RepeatPasswordField) { WLineEdit p = new WLineEdit(); p.setEchoMode(EchoMode.Password); p.changed() .addListener( this, () -> { UpdatePasswordWidget.this.checkPassword2(); }); result = p; } } } } return result; } private User user_; private RegistrationModel registrationModel_; private AuthModel authModel_; private Signal updated_; private Signal canceled_; private void checkPassword() { this.updateModelField(this.registrationModel_, RegistrationModel.ChoosePasswordField); this.registrationModel_.validateField(RegistrationModel.ChoosePasswordField); this.updateViewField(this.registrationModel_, RegistrationModel.ChoosePasswordField); } private void checkPassword2() { this.updateModelField(this.registrationModel_, RegistrationModel.RepeatPasswordField); this.registrationModel_.validateField(RegistrationModel.RepeatPasswordField); this.updateViewField(this.registrationModel_, RegistrationModel.RepeatPasswordField); } private boolean validate() { boolean valid = true; if (this.authModel_ != null) { this.updateModelField(this.authModel_, AuthModel.PasswordField); if (!this.authModel_.validate()) { this.updateViewField(this.authModel_, AuthModel.PasswordField); valid = false; } } this.registrationModel_.validateField(RegistrationModel.LoginNameField); this.checkPassword(); this.checkPassword2(); this.registrationModel_.validateField(RegistrationModel.EmailField); if (!this.registrationModel_.isValid()) { valid = false; } return valid; } private void doUpdate() { if (this.validate()) { String password = this.registrationModel_.valueText(RegistrationModel.ChoosePasswordField); this.registrationModel_.getPasswordAuth().updatePassword(this.user_, password); this.registrationModel_.getLogin().login(this.user_); this.updated_.trigger(); } } private void cancel() { this.canceled_.trigger(); } }
kdeforche/jwt
src/eu/webtoolkit/jwt/auth/UpdatePasswordWidget.java
Java
gpl-2.0
7,657
<?php /** * @file * Returns the HTML for a single Drupal page. * * Complete documentation for this file is available online. * @see https://drupal.org/node/1728148 */ ?> <div id="page"> <div class="top"> <?php print render($page['top']); ?> </div> <header class="header" id="header" role="banner"> <?php if ($logo): ?> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" class="header__logo" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" class="header__logo-image" /></a> <?php endif; ?> <?php if ($site_name || $site_slogan): ?> <div class="header__name-and-slogan" id="name-and-slogan"> <?php if ($site_name): ?> <h1 class="header__site-name" id="site-name"> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" class="header__site-link" rel="home"><span><?php print $site_name; ?></span></a> </h1> <?php endif; ?> <?php if ($site_slogan): ?> <div class="header__site-slogan" id="site-slogan"><?php print $site_slogan; ?></div> <?php endif; ?> </div> <?php endif; ?> <?php if ($secondary_menu): ?> <nav class="header__secondary-menu" id="secondary-menu" role="navigation"> <?php print theme('links__system_secondary_menu', array( 'links' => $secondary_menu, 'attributes' => array( 'class' => array('links', 'inline', 'clearfix'), ), 'heading' => array( 'text' => $secondary_menu_heading, 'level' => 'h2', 'class' => array('element-invisible'), ), )); ?> </nav> <?php endif; ?> <?php print render($page['header']); ?> </header> <div id="main"> <div id="content" class="column" role="main"> <?php print render($page['highlighted']); ?> <?php print $breadcrumb; ?> <a id="main-content"></a> <?php print render($title_prefix); ?> <?php if ($title): ?> <h1 class="page__title title" id="page-title"><?php print $title; ?></h1> <?php endif; ?> <?php print render($title_suffix); ?> <?php print $messages; ?> <?php print render($tabs); ?> <?php print render($page['help']); ?> <?php if ($action_links): ?> <ul class="action-links"><?php print render($action_links); ?></ul> <?php endif; ?> <?php print render($page['content']); ?> <?php print $feed_icons; ?> </div> <div id="navigation"> <?php print render($page['navigation']); ?> </div> <?php // Render the sidebars to see if there's anything in them. $sidebar_first = render($page['sidebar_first']); $sidebar_second = render($page['sidebar_second']); ?> <?php if ($sidebar_first || $sidebar_second): ?> <aside class="sidebars"> <?php print $sidebar_first; ?> <?php print $sidebar_second; ?> </aside> <?php endif; ?> </div> <?php print render($page['footer']); ?> </div> <?php print render($page['bottom']); ?>
tarasdj/intetrane
sites/all/themes/mythemes/templates/page.tpl.php
PHP
gpl-2.0
3,104
#include "MeshRenderer.h" #include "Data/ShapeMesh.h" #include "Data/Utility.h" #include <GLBlaat/GLFramebuffer.h> #include <GLBlaat/GLProgram.h> #include <GLBlaat/GLTextureManager.h> #include <GLBlaat/GLUtility.h> #include <NQVTK/Rendering/Camera.h> #include <cassert> #include <sstream> namespace Diverse { // ------------------------------------------------------------------------ MeshRenderer::MeshRenderer() : mesh(0), meshShader(0), meshBuffer(0) { useColorMap = true; threshold = -1.0; // disabled } // ------------------------------------------------------------------------ MeshRenderer::~MeshRenderer() { SetShader(0); delete meshShader; delete meshBuffer; } // ------------------------------------------------------------------------ void MeshRenderer::SetViewport(int x, int y, int w, int h) { Superclass::SetViewport(x, y, w, h); if (meshBuffer) { if (!meshBuffer->Resize(w, h)) { delete meshBuffer; meshBuffer = 0; } } if (!meshBuffer) { // Create G-buffer FBO meshBuffer = GLFramebuffer::New(w, h); bool ok = meshBuffer != 0; if (ok) { meshBuffer->CreateDepthBuffer(); int nBufs = 2; GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; for (int i = 0; i < nBufs; ++i) { meshBuffer->CreateColorTextureRectangle( bufs[i], GL_RGBA16F_ARB, GL_RGBA, GL_FLOAT); GLTexture *buf = meshBuffer->GetTexture2D(bufs[i]); GLUtility::SetDefaultColorTextureParameters(buf); } glDrawBuffers(nBufs, bufs); ok = meshBuffer->IsOk(); meshBuffer->Unbind(); } if (!ok) { std::cerr << "Error creating mesh G-buffer" << std::endl; delete meshBuffer; meshBuffer = 0; } } // Re-register the textures as they might have moved if (meshBuffer) { tm->AddTexture("gbuffer0", meshBuffer->GetTexture2D( GL_COLOR_ATTACHMENT0), false); tm->AddTexture("gbuffer1", meshBuffer->GetTexture2D( GL_COLOR_ATTACHMENT1), false); } else { tm->RemoveTexture("gbuffer0"); tm->RemoveTexture("gbuffer1"); } } // ------------------------------------------------------------------------ void MeshRenderer::Draw() { if (mesh) { mesh->SetShape(shape); mesh->SetReference(reference); } // TODO: add a standard deferred shading renderer to NQVTK // Fallback in case something went wrong in initialization if (!meshBuffer) { Clear(); return; } // G-buffer creation pass GLFramebuffer *oldTarget = SetTarget(meshBuffer); bool oldDrawBackground = drawBackground; SetDrawBackground(false); glDisable(GL_BLEND); Superclass::Draw(); // Prepare for the shading pass SetTarget(oldTarget); SetDrawBackground(oldDrawBackground); DrawShadingPass(); } // ------------------------------------------------------------------------ void MeshRenderer::SetMesh(ShapeMesh *mesh) { this->mesh = mesh; if (mesh) { shape.set_size(mesh->GetShapeSpaceDimension()); shape.zeros(); reference.set_size(mesh->GetShapeSpaceDimension()); reference.zeros(); } } // ------------------------------------------------------------------------ void MeshRenderer::SetShape(itpp::vec shape) { assert(mesh != 0); assert(shape.size() == mesh->GetShapeSpaceDimension()); this->shape = shape; } // ------------------------------------------------------------------------ void MeshRenderer::SetReference(itpp::vec shape) { assert(mesh != 0); assert(shape.size() == mesh->GetShapeSpaceDimension()); this->reference = shape; } // ------------------------------------------------------------------------ void MeshRenderer::SetUseColorMap(bool use) { this->useColorMap = use; } // ------------------------------------------------------------------------ void MeshRenderer::SetThreshold(float threshold) { this->threshold = threshold; } // ------------------------------------------------------------------------ bool MeshRenderer::Initialize() { if (!Superclass::Initialize()) return false; bool ok; // Initialize shader for G-buffer creation GLProgram *meshScribe = GLProgram::New(); ok = meshScribe != 0; if (ok) ok = meshScribe->AddVertexShader( Utility::LoadShader("MeshScribeVS.txt")); if (ok) ok = meshScribe->AddFragmentShader( Utility::LoadShader("MeshScribeFS.txt")); if (ok) ok = meshScribe->Link(); if (!ok) { std::cerr << "Error creating mesh scribe" << std::endl; delete meshScribe; meshScribe = 0; } GLProgram *oldShader = SetShader(meshScribe); delete oldShader; // Initialize shader for deferred shading delete meshShader; meshShader = GLProgram::New(); ok = meshShader != 0; if (ok) ok = meshShader->AddVertexShader( Utility::LoadShader("MeshShaderVS.txt")); if (ok) ok = meshShader->AddFragmentShader( Utility::LoadShader("MeshShaderFS.txt")); if (ok) ok = meshShader->Link(); if (!ok) { std::cerr << "Error creating mesh shader" << std::endl; delete meshShader; meshShader = 0; } // The G-buffer FBO is created when the viewport is resized tm->RemoveTexture("gbuffer0"); tm->RemoveTexture("gbuffer1"); delete meshBuffer; meshBuffer = 0; return ok; } // ------------------------------------------------------------------------ void MeshRenderer::DrawShadingPass() { glPushAttrib(GL_ALL_ATTRIB_BITS); if (fboTarget) fboTarget->Bind(); Clear(); DrawCamera(); meshShader->Start(); meshShader->SetUniform1f("viewportX", viewportX); meshShader->SetUniform1f("viewportY", viewportY); meshShader->SetUniform3f("cameraPos", static_cast<float>(camera->position.x), static_cast<float>(camera->position.y), static_cast<float>(camera->position.z)); meshShader->SetUniform1i("useColorMap", useColorMap ? 1 : 0); meshShader->SetUniform1f("threshold", threshold); tm->SetupProgram(meshShader); tm->Bind(); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); glDisable(GL_CULL_FACE); // Draw full-screen quad glBegin(GL_QUADS); glVertex3d(-1.0, 1.0, 0.0); glVertex3d(1.0, 1.0, 0.0); glVertex3d(1.0, -1.0, 0.0); glVertex3d(-1.0, -1.0, 0.0); glEnd(); tm->Unbind(); meshShader->Stop(); if (fboTarget) fboTarget->Unbind(); glPopAttrib(); } }
bwrrp/shapespaceexplorer
Rendering/MeshRenderer.cpp
C++
gpl-2.0
6,514
<?php if (isset($_GET['disable'])) $nonce = ''; else { @session_start(); require_once(dirname(dirname(__FILE__)).'/classes/SemisecureLoginReimagined.php'); $nonce_session_key = SemisecureLoginReimagined::nonce_session_key(); $nonce = $_SESSION[$nonce_session_key]; } // load the nonce into a JavaScript variable if "js" is set on the query-string if (isset($_GET['js'])) : ?> var SemisecureLoginReimagined_nonce = '<?php echo addslashes($nonce); ?>'; <?php else : // otherwise just return the nonce directly echo $nonce; endif; ?>
Yeremenko-Roman/Geekhub-Roman-E
wp-content/plugins/semisecure-login-reimagined/js/nonce.php
PHP
gpl-2.0
539
// third-party deps import { reduce, sortBy, isNil, isEmpty, mapValues, each, Dictionary } from 'lodash'; import { IHttpService, ILogService, IPromise } from 'angular'; import * as moment from 'moment'; type ILocalStorageService = angular.local.storage.ILocalStorageService; // internal deps import { ILineItem } from './line-item'; import { SHORT_DATE_FORMAT } from '../config'; import { IState as IAppConfig, ConfigService } from '../../app/config'; export interface IPriceGroupItem { productId: number; size: string; } export interface IPriceGroup { date: string; price: number; items: IPriceGroupItem[]; } // response format from API // { // '2016-07-12': [{ // date: 'xxx', // price: 'xxx', // items: 'xxx' // }] // } export type PriceGroupsByDate = Dictionary<IPriceGroup[]>; // {'2016-07-12': GroupKeyToPriceMap, ...} export type PricesByDate = Dictionary<GroupKeyToPriceMap>; // consumer price format // { // '24-big|3-big|': 75, // '34-big|76-big|': 80, // '5-medium|82-medium|': 55, // ... // } export type GroupKeyToPriceMap = Dictionary<number>; export type PriceList = Dictionary<number>; /* tslint:disable */ // export const priceList: PriceList = { // // big ----------------------------------------------------------------------- // // full // 'meat-big|garnish-big|salad-big': 70, // 'fish-big|garnish-big|salad-big': 90, // // no meat/fish // 'garnish-big|salad-big': 45, // // no salad (meat included) // 'meat-big|garnish-big': 55, // // no salad (fish included) // 'fish-big|garnish-big': 75, // // no garnish (meat included) // 'meat-big|salad-big': 55, // // no garnish (fish included) // 'fish-big|salad-big': 75, // 'salad-big': 25, // 'meat-big': 35, // 'fish-big': 55, // 'garnish-big': 30, // // medium -------------------------------------------------------------------- // // full // 'meat-medium|garnish-medium|salad-medium': 45, // 'fish-medium|garnish-medium|salad-medium': 55, // // no meat/fish // 'garnish-medium|salad-medium': 35, // // no salad (meat included) // 'meat-medium|garnish-medium': 40, // // no salad (fish included) // 'fish-medium|garnish-medium': 50, // // no garnish (meat included) // 'meat-medium|salad-medium': 40, // // no garnish (fish included) // 'fish-medium|salad-medium': 50, // 'salad-medium': 20, // 'meat-medium': 30, // 'fish-medium': 45, // 'garnish-medium': 20 // }; /* tslint:enable */ // todo: a lot of performance issues export class PriceService { private lConfig: IAppConfig; constructor( private $http: IHttpService, private $log: ILogService, // private $timeout: ITimeoutService, private localStorageService: ILocalStorageService, private configService: ConfigService ) { 'ngInject'; this.configService.get().first().subscribe(config => this.lConfig = config); } fetchPriceGroupsForActualDays(): IPromise<PricesByDate> { const startDate = moment().format(SHORT_DATE_FORMAT); const endDate = moment().add(1, 'weeks').endOf('week').format(SHORT_DATE_FORMAT); const url = this.lConfig.apiUrl + '/prices?startDate=' + startDate + '&endDate=' + endDate; return this.$http.get<PriceGroupsByDate>(url, {cache: true}) .then(res => res.data) .then(priceGroupsByData => { const pricesByDate = this.priceGroupsByDateToPricesByDate(priceGroupsByData); this.storeToLocalStorage(pricesByDate); return pricesByDate; }); } priceGroupsByDateToPricesByDate(priceGroupsByDate: PriceGroupsByDate): PricesByDate { return mapValues(priceGroupsByDate, priceGroups => { return this.convertPriceGroupsToKeyPrice(priceGroups); }); } calcPriceForAll(orderLineItems: ILineItem[], date: string): number { if (orderLineItems.length === 0) { return 0; } let prices = this.getPricesFromLocalStorage(date); if (isEmpty(prices)) { return 0; } const orderGroupKey = this.groupKeyForLineItems(orderLineItems); let price = prices[orderGroupKey]; if (isNil(price)) { price = this.calcFallbackPriceFor(orderLineItems, prices); this.$log.warn('Price: Price not found! Calculate sum of product prices.', price, orderLineItems, prices); } return price; } // todo: find out more clean solution // createPriceGroupsForAllMenus(menus: IMenu[]): IPriceGroup[] { // let priceGroups = []; // each(menus, menu => { // priceGroups = union(priceGroups, this.createPriceGroupsForDayMenu(menu)); // }); // return priceGroups; // } // // todo: generalize for any amount of menu products and sizes // createPriceGroupsForDayMenu(menu: IMenu): IPriceGroup[] { // let meat, // garnish, // salad, // meatGarnishPriceGroupBig, // meatGarnishPriceGroupMedium, // garnishSaladPriceGroupBig, // garnishSaladPriceGroupMedium; // if (menu.products.length === 3) { // meat = menu.products[0]; // garnish = menu.products[1]; // salad = menu.products[2]; // } else { // meat = menu.products[0]; // salad = menu.products[1]; // } // const perProductPriceGroupsBig = this.createPerProductPriceGroups(menu, 'big'); // const perProductPriceGroupsMedium = this.createPerProductPriceGroups(menu, 'medium'); // const allProductsPriceGroupBig = this.createPriceGroupForProductsCombination(menu.products, menu.date, 'big'); // const allProductsPriceGroupMedium = this.createPriceGroupForProductsCombination(menu.products, menu.date, 'medium'); // const meatSaladPriceGroupBig = this.createPriceGroupForProductsCombination([meat, salad], menu.date, 'big'); // const meatSaladPriceGroupMedium = this.createPriceGroupForProductsCombination([meat, salad], menu.date, 'medium'); // if (garnish) { // meatGarnishPriceGroupBig = this.createPriceGroupForProductsCombination([meat, garnish], menu.date, 'big'); // meatGarnishPriceGroupMedium = this.createPriceGroupForProductsCombination([meat, garnish], menu.date, 'medium'); // garnishSaladPriceGroupBig = this.createPriceGroupForProductsCombination([garnish, salad], menu.date, 'big'); // garnishSaladPriceGroupMedium = this.createPriceGroupForProductsCombination([garnish, salad], menu.date, 'medium'); // } // let groups = union( // perProductPriceGroupsBig, // perProductPriceGroupsMedium, // [ // allProductsPriceGroupBig, // allProductsPriceGroupMedium, // meatSaladPriceGroupBig, // meatSaladPriceGroupMedium, // ] // ); // if (garnish) { // groups = union( // groups, // [ // meatGarnishPriceGroupBig, // meatGarnishPriceGroupMedium, // garnishSaladPriceGroupBig, // garnishSaladPriceGroupMedium // ] // ); // } // return groups; // } // createPriceGroupForProductsCombination(products: IProduct[], date: string, size: string): IPriceGroup { // const price = this.calcPriceForProductCombination(products, size); // const items = this.createPriceGroupItemsForAll(products, size); // return {date, price, items}; // } // pushPriceGroups(groups: IPriceGroup[]): void { // each(groups, group => { // const url = this.lConfig.apiUrl + '/prices/' + group.date; // this.$timeout(() => { // this.$http.put(url, group); // }, 1000); // }); // } // private calcPriceForProductCombination(products: IProduct[], size: string): number { // const key = map(products, product => product.type + '-' + size).join('|'); // return priceList[key]; // } // private createPerProductPriceGroups(menu: IMenu, size: string): IPriceGroup[] { // return map(menu.products, product => { // return this.createPriceGroupForProductsCombination([product], menu.date, size); // }); // } // private createPriceGroupItemsForAll(products: IProduct[], size: string): IPriceGroupItem[] { // return map(products, product => { // return { // size, // productId: product.id // }; // }); // } private groupKeyForLineItems(lineItems: ILineItem[]): string { const sortedLineItems = sortBy(lineItems, 'product.id'); return reduce(sortedLineItems, (key, lineItem) => { return key + this.groupKeyForLineItem(lineItem); }, ''); } private groupKeyForLineItem(lineItem: ILineItem): string { return lineItem.product.id + '-' + lineItem.size + '|'; } private groupKeyForPriceGroup(priceGroup: IPriceGroup): string { const sortedPriceGroupItems = sortBy(priceGroup.items, 'productId'); return reduce(sortedPriceGroupItems, (key, priceItem) => { return key + priceItem.productId + '-' + priceItem.size + '|'; }, ''); } private convertPriceGroupsToKeyPrice(priceGroups: IPriceGroup[]): GroupKeyToPriceMap { const keyPriceHash = {}; each(priceGroups, priceGroup => { const groupKey = this.groupKeyForPriceGroup(priceGroup); keyPriceHash[groupKey] = priceGroup.price; }); return keyPriceHash; } private calcFallbackPriceFor(lineItems: ILineItem[], prices: GroupKeyToPriceMap): number { return reduce(lineItems, (_, lineItem) => { return prices[this.groupKeyForLineItem(lineItem)]; }, 0); } private storeToLocalStorage(prices: PricesByDate): boolean { if (!prices) { return false; } return this.localStorageService.set('pricesByDate', prices); } private getPricesFromLocalStorage(date: string): GroupKeyToPriceMap { const prices = this.localStorageService.get('pricesByDate'); if (!prices) { return {}; } return prices[date] || {}; } }
lunches-platform/fe
src/app.ng1/models/price.ts
TypeScript
gpl-2.0
9,779
using System; using Server; using Server.Gumps; using Server.Network; using Server.Mobiles; using System.Collections; using Server.Targeting; using Server.Engines.XmlSpawner2; /* ** LastManStandingGauntlet ** ArteGordon ** updated 12/05/04 ** ** used to set up a last man standing pvp challenge game through the XmlPoints system. */ namespace Server.Items { public class LastManStandingGauntlet : BaseChallengeGame { public class ChallengeEntry : BaseChallengeEntry { public ChallengeEntry(Mobile m) : base (m) { } public ChallengeEntry() : base () { } } private static TimeSpan MaximumOutOfBoundsDuration = TimeSpan.FromSeconds(15); // maximum time allowed out of bounds before disqualification private static TimeSpan MaximumOfflineDuration = TimeSpan.FromSeconds(60); // maximum time allowed offline before disqualification private static TimeSpan MaximumHiddenDuration = TimeSpan.FromSeconds(10); // maximum time allowed hidden before disqualification private static TimeSpan RespawnTime = TimeSpan.FromSeconds(6); // delay until autores if autores is enabled public static bool OnlyInChallengeGameRegion = false; // if this is true, then the game can only be set up in a challenge game region private Mobile m_Challenger; private ArrayList m_Organizers = new ArrayList(); private ArrayList m_Participants = new ArrayList(); private bool m_GameLocked; private bool m_GameInProgress; private int m_TotalPurse; private int m_EntryFee; private int m_ArenaSize = 0; // maximum distance from the challenge gauntlet allowed before disqualification. Zero is unlimited range private Mobile m_Winner; // how long before the gauntlet decays if a gauntlet is dropped but never started public override TimeSpan DecayTime { get{ return TimeSpan.FromMinutes( 15 ); } } // this will apply to the setup public override ArrayList Organizers { get { return m_Organizers; } } public override bool AllowPoints { get{ return false; } } // determines whether kills during the game will award points. If this is false, UseKillDelay is ignored public override bool UseKillDelay { get{ return true; } } // determines whether the normal delay between kills of the same player for points is enforced public bool AutoRes { get { return true; } } // determines whether players auto res after being killed [CommandProperty( AccessLevel.GameMaster )] public override Mobile Challenger { get{ return m_Challenger; } set { m_Challenger = value; } } public override bool GameInProgress { get{ return m_GameInProgress; } set {m_GameInProgress = value; } } [CommandProperty( AccessLevel.GameMaster )] public override bool GameCompleted { get{ return !m_GameInProgress && m_GameLocked; } } public override bool GameLocked { get{ return m_GameLocked; } set {m_GameLocked = value; } } [CommandProperty( AccessLevel.GameMaster )] public Mobile Winner { get{ return m_Winner; } set { m_Winner = value; } } public override ArrayList Participants { get{ return m_Participants; } set { m_Participants = value; } } public override int TotalPurse { get { return m_TotalPurse; } set { m_TotalPurse = value; } } public override int EntryFee { get { return m_EntryFee; } set { m_EntryFee = value; } } [CommandProperty( AccessLevel.GameMaster )] public override int ArenaSize { get { return m_ArenaSize; } set { m_ArenaSize = value; } } public override bool InsuranceIsFree(Mobile from, Mobile awardto) { return true; } public override void OnTick() { CheckForDisqualification(); } public void CheckForDisqualification() { if(Participants == null || !GameInProgress) return; bool statuschange = false; foreach(ChallengeEntry entry in Participants) { if(entry.Participant == null || entry.Status == ChallengeStatus.Forfeit || entry.Status == ChallengeStatus.Disqualified) continue; bool hadcaution = (entry.Caution != ChallengeStatus.None); // and a map check if(entry.Participant.Map != Map) { // check to see if they are offline if(entry.Participant.Map == Map.Internal) { // then give them a little time to return before disqualification if(entry.Caution == ChallengeStatus.Offline) { // were previously out of bounds so check for disqualification // check to see how long they have been out of bounds if(DateTime.Now - entry.LastCaution > MaximumOfflineDuration) { entry.Status = ChallengeStatus.Disqualified; GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified" RefreshSymmetricNoto(entry.Participant); statuschange = true; } } else { entry.LastCaution = DateTime.Now; statuschange = true; } entry.Caution = ChallengeStatus.Offline; } else { // changing to any other map is instant disqualification entry.Status = ChallengeStatus.Disqualified; GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified" RefreshSymmetricNoto(entry.Participant); statuschange = true; } } else // make a range check if(m_ArenaSize > 0 && !Utility.InRange(entry.Participant.Location, Location, m_ArenaSize) || (IsInChallengeGameRegion && !(Region.Find(entry.Participant.Location, entry.Participant.Map) is ChallengeGameRegion))) { if(entry.Caution == ChallengeStatus.OutOfBounds) { // were previously out of bounds so check for disqualification // check to see how long they have been out of bounds if(DateTime.Now - entry.LastCaution > MaximumOutOfBoundsDuration) { entry.Status = ChallengeStatus.Disqualified; GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified" RefreshSymmetricNoto(entry.Participant); statuschange = true; } } else { entry.LastCaution = DateTime.Now; // inform the player XmlPoints.SendText(entry.Participant, 100309, MaximumOutOfBoundsDuration.TotalSeconds); // "You are out of bounds! You have {0} seconds to return" statuschange = true; } entry.Caution = ChallengeStatus.OutOfBounds; } else // make a hiding check if(entry.Participant.Hidden) { if(entry.Caution == ChallengeStatus.Hidden) { // were previously hidden so check for disqualification // check to see how long they have hidden if(DateTime.Now - entry.LastCaution > MaximumHiddenDuration) { entry.Status = ChallengeStatus.Disqualified; GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified" RefreshSymmetricNoto(entry.Participant); statuschange = true; } } else { entry.LastCaution = DateTime.Now; // inform the player XmlPoints.SendText(entry.Participant, 100310, MaximumHiddenDuration.TotalSeconds); // "You have {0} seconds become unhidden" statuschange = true; } entry.Caution = ChallengeStatus.Hidden; } else { entry.Caution = ChallengeStatus.None; } if(hadcaution && entry.Caution == ChallengeStatus.None) statuschange = true; } if(statuschange) { // update gumps with the new status LastManStandingGump.RefreshAllGumps(this, false); } // it is possible that the game could end like this so check CheckForGameEnd(); } public override void CheckForGameEnd() { if(Participants == null || !GameInProgress) return; int leftstanding = 0; Mobile winner = null; foreach(ChallengeEntry entry in Participants) { if(entry.Status == ChallengeStatus.Active) { leftstanding++; winner = entry.Participant; } } // and then check to see if this is the last man standing if(leftstanding == 1 && winner != null) { // declare the winner and end the game XmlPoints.SendText(winner, 100311, ChallengeName); // "You have won {0}" Winner = winner; RefreshSymmetricNoto(winner); GameBroadcast( 100312, winner.Name); // "The winner is {0}" AwardWinnings(winner, TotalPurse); EndGame(); LastManStandingGump.RefreshAllGumps(this, true); } if(leftstanding < 1) { // declare a tie and keep the fees GameBroadcast(100313); // "The match is a draw" EndGame(); LastManStandingGump.RefreshAllGumps(this, true); } } public override void OnPlayerKilled(Mobile killer, Mobile killed) { if (killed == null) return; /* // move the killed player and their corpse to a location // you have to replace x,y,z with some valid coordinates int x = this.Location.X + 30; int y = this.Location.Y + 30; int z = this.Location.Z; Point3D killedloc = new Point3D(x, y, z); ArrayList petlist = new ArrayList(); foreach (Mobile m in killed.GetMobilesInRange(16)) { if (m is BaseCreature && ((BaseCreature)m).ControlMaster == killed) { petlist.Add(m); } } // port the pets foreach (Mobile m in petlist) { m.MoveToWorld(killedloc, killed.Map); } // do the actual moving killed.MoveToWorld(killedloc, killed.Map); if (killed.Corpse != null) killed.Corpse.MoveToWorld(killedloc, killed.Map); */ if (AutoRes) { // prepare the autores callback Timer.DelayCall( RespawnTime, new TimerStateCallback( XmlPoints.AutoRes_Callback ), new object[]{ killed, false } ); } // find the player in the participants list and set their status to Dead if(m_Participants != null) { foreach(ChallengeEntry entry in m_Participants) { if(entry.Participant == killed && entry.Status != ChallengeStatus.Forfeit) { entry.Status = ChallengeStatus.Dead; // clear up their noto RefreshSymmetricNoto(killed); GameBroadcast(100314, killed.Name); // "{0} has been killed" } } } LastManStandingGump.RefreshAllGumps(this, true); // see if the game is over CheckForGameEnd(); } public override bool AreTeamMembers(Mobile from, Mobile target) { // there are no teams, its every man for himself if(from == target) return true; return false; } public override bool AreChallengers(Mobile from, Mobile target) { // everyone participant is a challenger to everyone other participant, so just being a participant // makes you a challenger return(AreInGame(from) && AreInGame(target)); } public LastManStandingGauntlet(Mobile challenger) : base( 0x1414 ) { m_Challenger = challenger; m_Organizers.Add(challenger); // check for points attachments XmlPoints afrom = (XmlPoints)XmlAttach.FindAttachment(challenger, typeof(XmlPoints)); Movable = false; Hue = 33; if(challenger == null || afrom == null || afrom.Deleted) { Delete(); } else { Name = XmlPoints.SystemText(100302) + " " + String.Format(XmlPoints.SystemText(100315), challenger.Name); // "Challenge by {0}" } } public LastManStandingGauntlet( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version writer.Write(m_Challenger); writer.Write(m_GameLocked); writer.Write(m_GameInProgress); writer.Write(m_TotalPurse); writer.Write(m_EntryFee); writer.Write(m_ArenaSize); writer.Write(m_Winner); if(Participants != null) { writer.Write(Participants.Count); foreach(ChallengeEntry entry in Participants) { writer.Write(entry.Participant); writer.Write(entry.Status.ToString()); writer.Write(entry.Accepted); writer.Write(entry.PageBeingViewed); } } else { writer.Write((int)0); } } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch(version) { case 0: m_Challenger = reader.ReadMobile(); m_Organizers.Add(m_Challenger); m_GameLocked = reader.ReadBool(); m_GameInProgress = reader.ReadBool(); m_TotalPurse = reader.ReadInt(); m_EntryFee = reader.ReadInt(); m_ArenaSize = reader.ReadInt(); m_Winner = reader.ReadMobile(); int count = reader.ReadInt(); for(int i = 0;i<count;i++) { ChallengeEntry entry = new ChallengeEntry(); entry.Participant = reader.ReadMobile(); string sname = reader.ReadString(); // look up the enum by name ChallengeStatus status = ChallengeStatus.None; try{ status = (ChallengeStatus)Enum.Parse(typeof(ChallengeStatus), sname); } catch{} entry.Status = status; entry.Accepted = reader.ReadBool(); entry.PageBeingViewed = reader.ReadInt(); Participants.Add(entry); } break; } if(GameCompleted) Timer.DelayCall( PostGameDecayTime, new TimerCallback( Delete ) ); StartChallengeTimer(); } public override void OnDoubleClick( Mobile from ) { from.SendGump( new LastManStandingGump( this, from ) ); } } }
jackuoll/Pre-AOS-RunUO
Scripts/Engines/XmlSpawner/XMLSpawner Extras/XmlPoints/ChallengeGames/LastManStandingGauntlet.cs
C#
gpl-2.0
16,786
<?php /** * Jobs for XOOPS * * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * 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. * * @copyright {@link https://xoops.org/ XOOPS Project} * @license {@link http://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2 or later} * @package jobs * @author John Mordo * @author XOOPS Development Team */ //require_once __DIR__ . '/admin_header.php'; require_once __DIR__ . '/../../../include/cp_header.php'; $moduleDirName = basename(dirname(__DIR__)); require_once XOOPS_ROOT_PATH . "/modules/$moduleDirName/include/functions.php"; require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php'; $myts = \MyTextSanitizer::getInstance(); xoops_cp_header(); if (!empty($_POST['comp_id'])) { $comp_id = \Xmf\Request::getInt('comp_id', 0, 'POST'); } elseif (!empty($_GET['comp_id'])) { $comp_id = \Xmf\Request::getInt('comp_id', 0, 'GET'); } else { $comp_id = ''; } if (!empty($_POST['comp_name'])) { $comp_name = $_POST['comp_name']; } else { $comp_name = ''; } $result = $xoopsDB->query('SELECT comp_name, comp_usid, comp_img FROM ' . $xoopsDB->prefix('jobs_companies') . ' WHERE comp_id=' . $xoopsDB->escape($comp_id) . ''); list($comp_name, $comp_usid, $photo) = $xoopsDB->fetchRow($result); $result1 = $xoopsDB->query('SELECT company, usid FROM ' . $xoopsDB->prefix('jobs_listing') . ' WHERE usid=' . $xoopsDB->escape($comp_usid) . ''); list($their_company, $usid) = $xoopsDB->fetchRow($result1); $ok = !isset($_REQUEST['ok']) ? null : $_REQUEST['ok']; if (1 == $ok) { // Delete Company $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('jobs_companies') . ' WHERE comp_id=' . $xoopsDB->escape($comp_id) . ''); // Delete all listing by Company if ($comp_name == $their_company) { $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('jobs_listing') . ' WHERE usid=' . $xoopsDB->escape($comp_usid) . ''); } // Delete Company logo if ($photo) { $destination = XOOPS_ROOT_PATH . "/modules/$moduleDirName/logo_images"; if (file_exists("$destination/$photo")) { unlink("$destination/$photo"); } } redirect_header('company.php', 13, _AM_JOBS_COMPANY_DEL); } else { echo "<table width='100%' border='0' cellspacing='1' cellpadding='8'><tr class='bg4'><td valign='top'>\n"; echo '<br><center>'; echo '<b>' . _AM_JOBS_SURECOMP . '' . $comp_name . '' . _AM_JOBS_SURECOMPEND . '</b><br><br>'; // } echo "[ <a href=\"delcomp.php?comp_id=$comp_id&amp;ok=1\">" . _AM_JOBS_YES . '</a> | <a href="index.php">' . _AM_JOBS_NO . '</a> ]<br><br>'; echo '</td></tr></table>'; } xoops_cp_footer();
mambax7/jobs
admin/delcomp.php
PHP
gpl-2.0
3,003
/* Malaysian initialisation for the jQuery UI date picker plugin. */ /* Written by Mohd Nawawi Mohamad Jamili (nawawi@ronggeng.net). */ jQuery(function ($) { $.datepicker.regional['ms'] = { closeText: 'Tutup', prevText: '&#x3c;Sebelum', nextText: 'Selepas&#x3e;', currentText: 'hari ini', monthNames: ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'], monthNamesShort: ['Jan', 'Feb', 'Mac', 'Apr', 'Mei', 'Jun', 'Jul', 'Ogo', 'Sep', 'Okt', 'Nov', 'Dis'], dayNames: ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'], dayNamesShort: ['Aha', 'Isn', 'Sel', 'Rab', 'kha', 'Jum', 'Sab'], dayNamesMin: ['Ah', 'Is', 'Se', 'Ra', 'Kh', 'Ju', 'Sa'], weekHeader: 'Mg', dateFormat: 'dd/mm/yy', firstDay: 0, isRTL: false, showMonthAfterYear: false, yearSuffix: ''}; $.datepicker.setDefaults($.datepicker.regional['ms']); });
parksandwildlife/parkstay
jomres/javascript/jquery-ui-cal-localisation/jquery.ui.datepicker-ms.js
JavaScript
gpl-2.0
932
<?php namespace AweBooking\Calendar\Resource; use AweBooking\Support\Collection; class Resources extends Collection {}
awethemes/awebooking
inc/Calendar/Resource/Resources.php
PHP
gpl-2.0
122
#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug)
tech-server/gondul
templating/templating.py
Python
gpl-2.0
3,215
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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 2 of the License, or * (at your option) any later version. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.env; import java.io.IOException; import java.io.PrintWriter; /** * Represents a PHP default value. */ @SuppressWarnings("serial") public class DefaultValue extends NullValue { public static final DefaultValue DEFAULT = new DefaultValue(); private DefaultValue() { } /** * Returns the null value singleton. */ public static DefaultValue create() { return DEFAULT; } /** * Returns true for a DefaultValue */ @Override public boolean isDefault() { return true; } /** * Converts to a boolean. */ @Override public boolean toBoolean() { return false; } /** * Converts to a long. */ @Override public long toLong() { return 0; } /** * Converts to a double. */ @Override public double toDouble() { return 0; } /** * Converts to an object. */ public Object toObject() { return ""; } /** * Converts to a callable */ @Override public Callable toCallable(Env env) { return null; } /** * Prints the value. * @param env */ @Override public void print(Env env) { } /** * Converts to a string. * @param env */ @Override public String toString() { return ""; } /** * Generates code to recreate the expression. * * @param out the writer to the Java source code. */ @Override public void generate(PrintWriter out) throws IOException { out.print("DefaultValue.DEFAULT"); } /** * Generates code to recreate the expression. * * @param out the writer to the Java source code. */ public void generateLong(PrintWriter out) throws IOException { out.print("0"); } /** * Generates code to recreate the expression. * * @param out the writer to the Java source code. */ public void generateString(PrintWriter out) throws IOException { out.print("\"\""); } // // Java Serialization // private Object readResolve() { return DEFAULT; } }
CleverCloud/Quercus
quercus/src/main/java/com/caucho/quercus/env/DefaultValue.java
Java
gpl-2.0
3,172
/* * Copyright (C) 2013 Leszek Mzyk * * 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 com.convenientbanner; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; /** * A ViewPager subclass enabling infinte scrolling of the viewPager elements * * When used for paginating views (in opposite to fragments), no code changes * should be needed only change xml's from <android.support.v4.view.ViewPager> * to <com.imbryk.viewPager.LoopViewPager> * * If "blinking" can be seen when paginating to first or last view, simply call * seBoundaryCaching( true ), or change DEFAULT_BOUNDARY_CASHING to true * * When using a FragmentPagerAdapter or FragmentStatePagerAdapter, * additional changes in the adapter must be done. * The adapter must be prepared to create 2 extra items e.g.: * * The original adapter creates 4 items: [0,1,2,3] * The modified adapter will have to create 6 items [0,1,2,3,4,5] * with mapping realPosition=(position-1)%count * [0->3, 1->0, 2->1, 3->2, 4->3, 5->0] */ public class CBLoopViewPager extends ViewPager { private static final boolean DEFAULT_BOUNDARY_CASHING = false; OnPageChangeListener mOuterPageChangeListener; private CBLoopPagerAdapterWrapper mAdapter; private boolean mBoundaryCaching = DEFAULT_BOUNDARY_CASHING; /** * helper function which may be used when implementing FragmentPagerAdapter * * @param position * @param count * @return (position-1)%count */ public static int toRealPosition( int position, int count ){ position = position-1; if( position < 0 ){ position += count; }else{ position = position%count; } return position; } /** * If set to true, the boundary views (i.e. first and last) will never be destroyed * This may help to prevent "blinking" of some views * * @param flag */ public void setBoundaryCaching(boolean flag) { mBoundaryCaching = flag; if (mAdapter != null) { mAdapter.setBoundaryCaching(flag); } } @Override public void setAdapter(PagerAdapter adapter) { mAdapter = new CBLoopPagerAdapterWrapper(adapter); mAdapter.setBoundaryCaching(mBoundaryCaching); super.setAdapter(mAdapter); setCurrentItem(0, false); } @Override public PagerAdapter getAdapter() { return mAdapter != null ? mAdapter.getRealAdapter() : mAdapter; } @Override public int getCurrentItem() { return mAdapter != null ? mAdapter.toRealPosition(super.getCurrentItem()) : 0; } public void setCurrentItem(int item, boolean smoothScroll) { int realItem = mAdapter.toInnerPosition(item); super.setCurrentItem(realItem, smoothScroll); } @Override public void setCurrentItem(int item) { if (getCurrentItem() != item) { setCurrentItem(item, true); } } @Override public void setOnPageChangeListener(OnPageChangeListener listener) { mOuterPageChangeListener = listener; }; public CBLoopViewPager(Context context) { super(context); init(); } public CBLoopViewPager(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { super.setOnPageChangeListener(onPageChangeListener); } private OnPageChangeListener onPageChangeListener = new OnPageChangeListener() { private float mPreviousOffset = -1; private float mPreviousPosition = -1; @Override public void onPageSelected(int position) { int realPosition = mAdapter.toRealPosition(position); if (mPreviousPosition != realPosition) { mPreviousPosition = realPosition; if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageSelected(realPosition); } } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { int realPosition = position; if (mAdapter != null) { realPosition = mAdapter.toRealPosition(position); if (positionOffset == 0 && mPreviousOffset == 0 && (position == 0 || position == mAdapter.getCount() - 1)) { setCurrentItem(realPosition, false); } } mPreviousOffset = positionOffset; if (mOuterPageChangeListener != null) { if (realPosition != mAdapter.getRealCount() - 1) { mOuterPageChangeListener.onPageScrolled(realPosition, positionOffset, positionOffsetPixels); } else { if (positionOffset > .5) { mOuterPageChangeListener.onPageScrolled(0, 0, 0); } else { mOuterPageChangeListener.onPageScrolled(realPosition, 0, 0); } } } } @Override public void onPageScrollStateChanged(int state) { if (mAdapter != null) { int position = CBLoopViewPager.super.getCurrentItem(); int realPosition = mAdapter.toRealPosition(position); if (state == ViewPager.SCROLL_STATE_IDLE && (position == 0 || position == mAdapter.getCount() - 1)) { setCurrentItem(realPosition, false); } } if (mOuterPageChangeListener != null) { mOuterPageChangeListener.onPageScrollStateChanged(state); } } }; }
bairutai/SinaWeibo
src/com/convenientbanner/CBLoopViewPager.java
Java
gpl-2.0
6,473
<?php if ( ! defined( 'ABSPATH' ) ) exit; // Exit when accessed directly /** * @since 1.0 */ class CPAC_WC_Column_Post_Price extends CPAC_Column_Default { /** * @see CPAC_Column::init() * @since 1.0 */ public function init() { parent::init(); // define properties $this->properties['type'] = 'price'; $this->properties['label'] = __( 'Price', 'cpac' ); $this->properties['group'] = 'woocommerce-default'; $this->properties['handle'] = 'price'; } /** * @see CPAC_Column::get_raw_value() * @since 1.0 */ public function get_raw_value( $post_id ) { $product = get_product( $post_id ); if ( $product->is_type( 'variable', 'grouped' ) ) { return; } $sale_from = $product->sale_price_dates_from; $sale_to = $product->sale_price_dates_to; return array( 'regular_price' => $product->get_regular_price(), 'sale_price' => $product->get_sale_price(), 'sale_price_dates_from' => $sale_from ? date( 'Y-m-d', $sale_from ) : '', 'sale_price_dates_to' => $sale_to ? date( 'Y-m-d', $sale_to ) : '' ); } }
kappuccino/wp-fast-start
data/plugins/cac-addon-woocommerce/classes/column/product/price.php
PHP
gpl-2.0
1,058
using iTextSharp.text; using iTextSharp.text.pdf; namespace Discovery.iTextSharp.infrastructure.helper { internal static class Layout { internal static Font GetBaseFont() { return FontFactory.GetFont("Segoe UI", 12.0f, BaseColor.BLACK); } internal static Font GetSmallestFont() { return FontFactory.GetFont("Segoe UI", 6.0f, BaseColor.BLACK); } internal static PdfPCell GetSmallesCell(string phrase) { var cell = GetCell(3, BaseColor.WHITE); cell.Phrase = new Phrase(phrase) { Font = GetSmallestFont() }; cell.Phrase.Font.Size = 6f; return cell; } internal static PdfPCell GetCell(int colspan, BaseColor borderColor) { return new PdfPCell { Colspan = colspan, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, BorderColor = borderColor }; } internal static PdfPHeaderCell GetHeaderCell(string content) { return new PdfPHeaderCell { Colspan = 1, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, BorderColor = BaseColor.WHITE, BorderColorBottom = BaseColor.GRAY, Phrase = new Phrase(content) { Font = GetBaseFont() } }; } } }
corycoffee/discovery
src/Discovery.iTextSharp/infrastructure/helper/Layout.cs
C#
gpl-2.0
1,538
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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 2 * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common.model; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.apache.commons.lang.StringUtils; @Entity @Table(name = "consultationRequests") public class ConsultationRequest extends AbstractModel<Integer> implements Serializable { private static final String ACTIVE_MARKER = "1"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "requestId") private Integer id; @Column(name = "referalDate") @Temporal(TemporalType.DATE) private Date referralDate; private Integer serviceId; @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="specId") private ProfessionalSpecialist professionalSpecialist; @Temporal(TemporalType.DATE) private Date appointmentDate; @Temporal(TemporalType.TIME) private Date appointmentTime; @Column(name = "reason") private String reasonForReferral; private String clinicalInfo; private String currentMeds; private String allergies; private String providerNo; @Column(name = "demographicNo") private Integer demographicId; private String status = ACTIVE_MARKER; private String statusText; private String sendTo; private String concurrentProblems; private String urgency; private String appointmentInstructions; private boolean patientWillBook; @Column(name = "site_name") private String siteName; @Temporal(TemporalType.DATE) private Date followUpDate; @Column(name = "signature_img") private String signatureImg; private String letterheadName; private String letterheadAddress; private String letterheadPhone; private String letterheadFax; @Temporal(TemporalType.TIMESTAMP) private Date lastUpdateDate; private Integer fdid = null; private String source; @ManyToOne(fetch=FetchType.EAGER, targetEntity=LookupListItem.class) @JoinColumn(name="appointmentInstructions", referencedColumnName="value", insertable = false, updatable = false) private LookupListItem lookupListItem; @Override public Integer getId() { return(id); } public Date getReferralDate() { return referralDate; } public void setReferralDate(Date referralDate) { this.referralDate = referralDate; } public Integer getServiceId() { return serviceId; } public void setServiceId(Integer serviceId) { this.serviceId = serviceId; } public Date getAppointmentDate() { return appointmentDate; } public void setAppointmentDate(Date appointmentDate) { this.appointmentDate = appointmentDate; } public Date getAppointmentTime() { return appointmentTime; } public void setAppointmentTime(Date appointmentTime) { this.appointmentTime = appointmentTime; } public String getReasonForReferral() { return reasonForReferral; } public void setReasonForReferral(String reasonForReferral) { this.reasonForReferral = StringUtils.trimToNull(reasonForReferral); } public String getClinicalInfo() { return clinicalInfo; } public void setClinicalInfo(String clinicalInfo) { this.clinicalInfo = StringUtils.trimToNull(clinicalInfo); } public String getCurrentMeds() { return currentMeds; } public void setCurrentMeds(String currentMeds) { this.currentMeds = StringUtils.trimToNull(currentMeds); } public String getAllergies() { return allergies; } public void setAllergies(String allergies) { this.allergies = StringUtils.trimToNull(allergies); } public String getProviderNo() { return providerNo; } public void setProviderNo(String providerNo) { this.providerNo = StringUtils.trimToNull(providerNo); } public Integer getDemographicId() { return demographicId; } public void setDemographicId(Integer demographicId) { this.demographicId = demographicId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = StringUtils.trimToNull(status); } public String getStatusText() { return statusText; } public void setStatusText(String statusText) { this.statusText = StringUtils.trimToNull(statusText); } public String getSendTo() { return sendTo; } public void setSendTo(String sendTo) { this.sendTo = StringUtils.trimToNull(sendTo); } public String getConcurrentProblems() { return concurrentProblems; } public void setConcurrentProblems(String concurrentProblems) { this.concurrentProblems = StringUtils.trimToNull(concurrentProblems); } public String getUrgency() { return urgency; } public void setUrgency(String urgency) { this.urgency = StringUtils.trimToNull(urgency); } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public boolean isPatientWillBook() { return patientWillBook; } public void setPatientWillBook(boolean patientWillBook) { this.patientWillBook = patientWillBook; } /** * @return the followUpDate */ public Date getFollowUpDate() { return followUpDate; } /** * @param followUpDate the followUpDate to set */ public void setFollowUpDate(Date followUpDate) { this.followUpDate = followUpDate; } /** * @return the professionalSpecialist */ public ProfessionalSpecialist getProfessionalSpecialist() { return professionalSpecialist; } /** * @param professionalSpecialist the professionalSpecialist to set */ public void setProfessionalSpecialist(ProfessionalSpecialist professionalSpecialist) { this.professionalSpecialist = professionalSpecialist; } public Integer getSpecialistId() { if(professionalSpecialist != null) return this.professionalSpecialist.getId(); else return null; } public String getSignatureImg() { return signatureImg; } public void setSignatureImg(String signatureImg) { this.signatureImg = signatureImg; } public String getLetterheadName() { return letterheadName; } public void setLetterheadName(String letterheadName) { this.letterheadName = letterheadName; } public String getLetterheadAddress() { return letterheadAddress; } public void setLetterheadAddress(String letterheadAddress) { this.letterheadAddress = letterheadAddress; } public String getLetterheadPhone() { return letterheadPhone; } public void setLetterheadPhone(String letterheadPhone) { this.letterheadPhone = letterheadPhone; } public String getLetterheadFax() { return letterheadFax; } public void setLetterheadFax(String letterheadFax) { this.letterheadFax = letterheadFax; } public Integer getFdid() { return fdid; } public void setFdid(Integer fdid) { this.fdid = fdid; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } @PrePersist @PreUpdate protected void jpa_updateLastDateUpdated() { lastUpdateDate = new Date(); } /** * returns the appointment instructions value. * This can be a display value or select list value * if the Lookup List interface is used. * If the table contains a hash key it most likely is a * primary key association in the LookupListItem table. */ public String getAppointmentInstructions() { return appointmentInstructions; } public void setAppointmentInstructions(String appointmentInstructions) { this.appointmentInstructions = appointmentInstructions; } /** * Returns the display label of the Appointment Instruction if * the Lookup List interface is being used. * Empty string otherwise. */ @Transient public String getAppointmentInstructionsLabel() { if( lookupListItem != null ) { return lookupListItem.getLabel(); } return ""; } /** * This will be bound if the Appointment Instructions * value is found as a unique match in the LookupListItem * table. */ public LookupListItem getLookupListItem() { return lookupListItem; } public void setLookupListItem(LookupListItem lookupListItem) { this.lookupListItem = lookupListItem; } public Date getLastUpdateDate() { return lastUpdateDate; } public void setLastUpdateDate(Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } }
scoophealth/oscar
src/main/java/org/oscarehr/common/model/ConsultationRequest.java
Java
gpl-2.0
10,011
/* * linksync commander -- Command line interface to LinkSync * Copyright (C) 2016 Andrew Duncan * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file LICENSE that should have accompanied this file. * * 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/>. */ 'use strict'; const crawler = require('simplecrawler').Crawler, fs = require('node-fs'), path = require('path'), q = require('q'), request = require('request'), url = require('url'), linklib = require('./links'), settings = require('./settings'); var self = module.exports = { crawler: new crawler(), init_crawler: function() { self.crawler.cache = new crawler.cache(settings.get('syncroot')); self.crawler.interval = 250; self.crawler.maxConcurrency = 5; self.crawler.userAgent = "LinkSync version " + settings.get('version'); self.crawler.maxDepth = 1; self.crawler.ignoreInvalidSSL = true; }, download_url: function(id, weburl, callback) { var mask = parseInt('0755', 8); var parsed_url = url.parse(weburl); var root_id = id; self.crawler = new crawler(parsed_url.hostname); self.init_crawler(); self.crawler.queueURL(weburl); self.crawler.on("fetchcomplete", function(queue_item, response_buffer, response) { console.log("Fetched: %s", queue_item.url); var parsed_url = url.parse(queue_item.url); if (parsed_url.pathname === "/") { parsed_url.pathname = "/index.html"; } var output_directory = path.join(settings.get('syncroot') + root_id + '/', parsed_url.hostname); var dirname = output_directory + parsed_url.pathname.replace(/\/[^\/]+$/, ""); var filepath = output_directory + parsed_url.pathname; console.log('%s : %s : %s', output_directory, dirname, filepath); fs.exists(dirname, function(exists) { if (exists) { fs.writeFile(filepath, response_buffer, function() {}); } else { fs.mkdir(dirname, mask, true, function() { fs.writeFile(filepath, response_buffer, function() {}); }); } }); console.log("%s (%d bytes) / %s", queue_item.url, response_buffer.length, response.headers["content-type"]); }); self.crawler.on("fetcherror", function(error) { console.log("Error syncing url (%s): %s", weburl, error); }); self.crawler.on("complete", function() { callback(); }); self.crawler.start(); }, sync: function(id) { linklib.get_link(id).then(function(link) { console.log('Syncing %s ...', link.url); self.download_url(id, link.url, function() { console.log("Finished syncing %s", link.url); }); }); } }
lakesite/linksync-commander
lib/sync.js
JavaScript
gpl-2.0
3,119
namespace Clinica.Listados_Estadisticos { partial class Pantalla2 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Text = "Pantalla2"; } #endregion } }
eldie1984/GESTIONAR
src/Clinica/Listados Estadisticos/Pantalla2.Designer.cs
C#
gpl-2.0
1,197
//============================================================================ //ZedGraph Class Library - A Flexible Line Graph/Bar Graph Library in C# //Copyright © 2004 John Champion // //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.1 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //============================================================================= using System; using System.Drawing; using System.Collections.Generic; namespace ZedGraph { /// <summary> /// A collection class containing a list of <see cref="CurveItem"/> objects /// that define the set of curves to be displayed on the graph. /// </summary> /// /// <author> John Champion /// modified by Jerry Vos</author> /// <version> $Revision: 3.43 $ $Date: 2007/11/03 04:41:28 $ </version> [Serializable] public class CurveList : List<CurveItem>, ICloneable { #region Properties // internal temporary value that keeps // the max number of points for any curve // associated with this curveList private int maxPts; /// <summary> /// Read only value for the maximum number of points in any of the curves /// in the list. /// </summary> public int MaxPts { get { return maxPts; } } /// <summary> /// Read only property that returns the number of curves in the list that are of /// type <see cref="BarItem"/>. This does not include <see cref="HiLowBarItem" /> or /// <see cref="ErrorBarItem" /> types. /// </summary> public int NumBars { get { int count = 0; foreach ( CurveItem curve in this ) { if ( curve.IsBar ) count++; } return count; } } /// <summary> /// Read only property that returns the number of curves in the list that are /// potentially "clusterable", which includes <see cref="BarItem"/> and /// <see cref="HiLowBarItem" /> types. This does not include <see cref="ErrorBarItem" />, /// <see cref="OHLCBarItem" />, <see cref="JapaneseCandleStickItem" />, etc. types. /// </summary> /// <remarks>Note that this property is only the number of bars that COULD BE clustered. The /// actual cluster settings are not considered.</remarks> public int NumClusterableBars { get { int count = 0; foreach ( CurveItem curve in this ) { if ( curve.IsBar || curve is HiLowBarItem ) count++; } return count; } } /// <summary> /// Read only property that returns the number of pie slices in the list (class type is /// <see cref="PieItem"/> ). /// </summary> public int NumPies { get { int count = 0; foreach ( CurveItem curve in this ) { if ( curve.IsPie ) count++; } return count; } } /// <summary> /// Read only property that determines if all items in the <see cref="CurveList"/> are /// Pies. /// </summary> public bool IsPieOnly { get { bool hasPie = false; foreach ( CurveItem curve in this ) { if ( !curve.IsPie ) return false; else hasPie = true; } return hasPie; } } /// <summary> /// Determine if there is any data in any of the <see cref="CurveItem"/> /// objects for this graph. This method does not verify valid data, it /// only checks to see if <see cref="CurveItem.NPts"/> > 0. /// </summary> /// <returns>true if there is any data, false otherwise</returns> public bool HasData() { foreach( CurveItem curve in this ) { if ( curve.Points.Count > 0 ) return true; } return false; } #endregion #region Constructors /// <summary> /// Default constructor for the collection class /// </summary> public CurveList() { maxPts = 1; } /// <summary> /// The Copy Constructor /// </summary> /// <param name="rhs">The XAxis object from which to copy</param> public CurveList( CurveList rhs ) { this.maxPts = rhs.maxPts; foreach ( CurveItem item in rhs ) { this.Add( (CurveItem) ((ICloneable)item).Clone() ); } } /// <summary> /// Implement the <see cref="ICloneable" /> interface in a typesafe manner by just /// calling the typed version of <see cref="Clone" /> /// </summary> /// <returns>A deep copy of this object</returns> object ICloneable.Clone() { return this.Clone(); } /// <summary> /// Typesafe, deep-copy clone method. /// </summary> /// <returns>A new, independent copy of this class</returns> public CurveList Clone() { return new CurveList( this ); } #endregion #region IEnumerable Methods //CJBL /// <summary> /// Iterate backwards through the <see cref="CurveList" /> items. /// </summary> public IEnumerable<CurveItem> Backward { get { for ( int i = this.Count - 1; i >= 0; i-- ) yield return this[i]; } } /// <summary> /// Iterate forward through the <see cref="CurveList" /> items. /// </summary> public IEnumerable<CurveItem> Forward { get { for ( int i = 0; i < this.Count; i++ ) yield return this[i]; } } #endregion #region List Methods /* /// <summary> /// Indexer to access the specified <see cref="CurveItem"/> object by /// its ordinal position in the list. /// </summary> /// <param name="index">The ordinal position (zero-based) of the /// <see cref="CurveItem"/> object to be accessed.</param> /// <value>A <see cref="CurveItem"/> object reference.</value> public CurveItem this[ int index ] { get { return( (CurveItem) List[index] ); } set { List[index] = value; } } */ /// <summary> /// Indexer to access the specified <see cref="CurveItem"/> object by /// its <see cref="CurveItem.Label"/> string. /// </summary> /// <param name="label">The string label of the /// <see cref="CurveItem"/> object to be accessed.</param> /// <value>A <see cref="CurveItem"/> object reference.</value> public CurveItem this[ string label ] { get { int index = IndexOf( label ); if ( index >= 0 ) return( this[index] ); else return null; } } /* /// <summary> /// Add a <see cref="CurveItem"/> object to the collection at the end of the list. /// </summary> /// <param name="curve">A reference to the <see cref="CurveItem"/> object to /// be added</param> /// <seealso cref="IList.Add"/> public void Add( CurveItem curve ) { List.Add( curve ); } */ /* /// <summary> /// Remove a <see cref="CurveItem"/> object from the collection based on an object reference. /// </summary> /// <param name="curve">A reference to the <see cref="CurveItem"/> object that is to be /// removed.</param> /// <seealso cref="IList.Remove"/> public void Remove( CurveItem curve ) { List.Remove( curve ); } */ /* /// <summary> /// Insert a <see cref="CurveItem"/> object into the collection at the specified /// zero-based index location. /// </summary> /// <param name="index">The zero-based index location for insertion.</param> /// <param name="curve">A reference to the <see cref="CurveItem"/> object that is to be /// inserted.</param> /// <seealso cref="IList.Insert"/> public void Insert( int index, CurveItem curve ) { List.Insert( index, curve ); } */ /// <summary> /// Return the zero-based position index of the /// <see cref="CurveItem"/> with the specified <see cref="CurveItem.Label"/>. /// </summary> /// <param name="label">The <see cref="String"/> label that is in the /// <see cref="CurveItem.Label"/> attribute of the item to be found. /// </param> /// <returns>The zero-based index of the specified <see cref="CurveItem"/>, /// or -1 if the <see cref="CurveItem"/> is not in the list</returns> /// <seealso cref="IndexOfTag"/> public int IndexOf( string label ) { int index = 0; foreach ( CurveItem p in this ) { if ( String.Compare( p._label._text, label, true ) == 0 ) return index; index++; } return -1; } /// <summary> /// Return the zero-based position index of the /// <see cref="CurveItem"/> with the specified <see cref="CurveItem.Tag"/>. /// </summary> /// <remarks>In order for this method to work, the <see cref="CurveItem.Tag"/> /// property must be of type <see cref="String"/>.</remarks> /// <param name="tag">The <see cref="String"/> tag that is in the /// <see cref="CurveItem.Tag"/> attribute of the item to be found. /// </param> /// <returns>The zero-based index of the specified <see cref="CurveItem"/>, /// or -1 if the <see cref="CurveItem"/> is not in the list</returns> public int IndexOfTag( string tag ) { int index = 0; foreach ( CurveItem p in this ) { if ( p.Tag is string && String.Compare( (string) p.Tag, tag, true ) == 0 ) return index; index++; } return -1; } /// <summary> /// Sorts the list according to the point values at the specified index and /// for the specified axis. /// </summary> public void Sort( SortType type, int index ) { this.Sort( new CurveItem.Comparer( type, index ) ); } /// <summary> /// Move the position of the object at the specified index /// to the new relative position in the list.</summary> /// <remarks>For Graphic type objects, this method controls the /// Z-Order of the items. Objects at the beginning of the list /// appear in front of objects at the end of the list.</remarks> /// <param name="index">The zero-based index of the object /// to be moved.</param> /// <param name="relativePos">The relative number of positions to move /// the object. A value of -1 will move the /// object one position earlier in the list, a value /// of 1 will move it one position later. To move an item to the /// beginning of the list, use a large negative value (such as -999). /// To move it to the end of the list, use a large positive value. /// </param> /// <returns>The new position for the object, or -1 if the object /// was not found.</returns> public int Move( int index, int relativePos ) { if ( index < 0 || index >= Count ) return -1; CurveItem curve = this[index]; this.RemoveAt( index ); index += relativePos; if ( index < 0 ) index = 0; if ( index > Count ) index = Count; Insert( index, curve ); return index; } #endregion #region Rendering Methods /// <summary> /// Go through each <see cref="CurveItem"/> object in the collection, /// calling the <see cref="CurveItem.GetRange"/> member to /// determine the minimum and maximum values in the /// <see cref="CurveItem.Points"/> list of data value pairs. If the curves include /// a stack bar, handle within the current GetRange method. In the event that no /// data are available, a default range of min=0.0 and max=1.0 are returned. /// If the Y axis has a valid data range and the Y2 axis not, then the Y2 /// range will be a duplicate of the Y range. Vice-versa for the Y2 axis /// having valid data when the Y axis does not. /// If any <see cref="CurveItem"/> in the list has a missing /// <see cref="PointPairList"/>, a new empty one will be generated. /// </summary> /// <param name="bIgnoreInitial">ignoreInitial is a boolean value that /// affects the data range that is considered for the automatic scale /// ranging (see <see cref="GraphPane.IsIgnoreInitial"/>). If true, then initial /// data points where the Y value is zero are not included when /// automatically determining the scale <see cref="Scale.Min"/>, /// <see cref="Scale.Max"/>, and <see cref="Scale.MajorStep"/> size. All data after /// the first non-zero Y value are included. /// </param> /// <param name="isBoundedRanges"> /// Determines if the auto-scaled axis ranges will subset the /// data points based on any manually set scale range values. /// </param> /// <param name="pane"> /// A reference to the <see cref="GraphPane"/> object that is the parent or /// owner of this object. /// </param> /// <seealso cref="GraphPane.IsBoundedRanges"/> public void GetRange( bool bIgnoreInitial, bool isBoundedRanges, GraphPane pane ) { double tXMinVal, tXMaxVal, tYMinVal, tYMaxVal; InitScale( pane.XAxis.Scale, isBoundedRanges ); InitScale( pane.X2Axis.Scale, isBoundedRanges ); foreach ( YAxis axis in pane.YAxisList ) InitScale( axis.Scale, isBoundedRanges ); foreach ( Y2Axis axis in pane.Y2AxisList ) InitScale( axis.Scale, isBoundedRanges ); maxPts = 1; // Loop over each curve in the collection and examine the data ranges foreach ( CurveItem curve in this ) { if ( curve.IsVisible ) { // For stacked types, use the GetStackRange() method which accounts for accumulated values // rather than simple curve values. if ( ( ( curve is BarItem ) && ( pane._barSettings.Type == BarType.Stack || pane._barSettings.Type == BarType.PercentStack ) ) || ( ( curve is LineItem ) && pane.LineType == LineType.Stack ) ) { GetStackRange( pane, curve, out tXMinVal, out tYMinVal, out tXMaxVal, out tYMaxVal ); } else { // Call the GetRange() member function for the current // curve to get the min and max values curve.GetRange( out tXMinVal, out tXMaxVal, out tYMinVal, out tYMaxVal, bIgnoreInitial, true, pane ); } // isYOrd is true if the Y axis is an ordinal type Scale yScale = curve.GetYAxis( pane ).Scale; Scale xScale = curve.GetXAxis( pane ).Scale; bool isYOrd = yScale.IsAnyOrdinal; // isXOrd is true if the X axis is an ordinal type bool isXOrd = xScale.IsAnyOrdinal; // For ordinal Axes, the data range is just 1 to Npts if ( isYOrd && !curve.IsOverrideOrdinal ) { tYMinVal = 1.0; tYMaxVal = curve.NPts; } if ( isXOrd && !curve.IsOverrideOrdinal ) { tXMinVal = 1.0; tXMaxVal = curve.NPts; } // Bar types always include the Y=0 value if ( curve.IsBar ) { if ( pane._barSettings.Base == BarBase.X || pane._barSettings.Base == BarBase.X2 ) { // Only force z=0 for BarItems, not HiLowBarItems if ( ! (curve is HiLowBarItem) ) { if ( tYMinVal > 0 ) tYMinVal = 0; else if ( tYMaxVal < 0 ) tYMaxVal = 0; } // for non-ordinal axes, expand the data range slightly for bar charts to // account for the fact that the bar clusters have a width if ( !isXOrd ) { tXMinVal -= pane._barSettings._clusterScaleWidth / 2.0; tXMaxVal += pane._barSettings._clusterScaleWidth / 2.0; } } else { // Only force z=0 for BarItems, not HiLowBarItems if ( !( curve is HiLowBarItem ) ) { if ( tXMinVal > 0 ) tXMinVal = 0; else if ( tXMaxVal < 0 ) tXMaxVal = 0; } // for non-ordinal axes, expand the data range slightly for bar charts to // account for the fact that the bar clusters have a width if ( !isYOrd ) { tYMinVal -= pane._barSettings._clusterScaleWidth / 2.0; tYMaxVal += pane._barSettings._clusterScaleWidth / 2.0; } } } // determine which curve has the maximum number of points if ( curve.NPts > maxPts ) maxPts = curve.NPts; // If the min and/or max values from the current curve // are the absolute min and/or max, then save the values // Also, differentiate between Y and Y2 values if ( tYMinVal < yScale._rangeMin ) yScale._rangeMin = tYMinVal; if ( tYMaxVal > yScale._rangeMax ) yScale._rangeMax = tYMaxVal; if ( tXMinVal < xScale._rangeMin ) xScale._rangeMin = tXMinVal; if ( tXMaxVal > xScale._rangeMax ) xScale._rangeMax = tXMaxVal; } } pane.XAxis.Scale.SetRange( pane, pane.XAxis ); pane.X2Axis.Scale.SetRange( pane, pane.X2Axis ); foreach ( YAxis axis in pane.YAxisList ) axis.Scale.SetRange( pane, axis ); foreach ( Y2Axis axis in pane.Y2AxisList ) axis.Scale.SetRange( pane, axis ); } private void InitScale( Scale scale, bool isBoundedRanges ) { scale._rangeMin = double.MaxValue; scale._rangeMax = double.MinValue; scale._lBound = ( isBoundedRanges && !scale._minAuto ) ? scale._min : double.MinValue; scale._uBound = ( isBoundedRanges && !scale._maxAuto ) ? scale._max : double.MaxValue; } /// <summary> /// Calculate the range for stacked bars and lines. /// </summary> /// <remarks>This method is required for the stacked /// types because (for bars), the negative values are a separate stack than the positive /// values. If you just sum up the bars, you will get the sum of the positive plus negative, /// which is less than the maximum positive value and greater than the maximum negative value. /// </remarks> /// <param name="pane"> /// A reference to the <see cref="GraphPane"/> object that is the parent or /// owner of this object. /// </param> /// <param name="curve">The <see cref="CurveItem"/> for which to calculate the range</param> /// <param name="tXMinVal">The minimum X value so far</param> /// <param name="tYMinVal">The minimum Y value so far</param> /// <param name="tXMaxVal">The maximum X value so far</param> /// <param name="tYMaxVal">The maximum Y value so far</param> /// <seealso cref="GraphPane.IsBoundedRanges"/> private void GetStackRange( GraphPane pane, CurveItem curve, out double tXMinVal, out double tYMinVal, out double tXMaxVal, out double tYMaxVal ) { // initialize the values to outrageous ones to start tXMinVal = tYMinVal = Double.MaxValue; tXMaxVal = tYMaxVal = Double.MinValue; ValueHandler valueHandler = new ValueHandler( pane, false ); Axis baseAxis = curve.BaseAxis( pane ); bool isXBase = baseAxis is XAxis || baseAxis is X2Axis; double lowVal, baseVal, hiVal; for ( int i=0; i<curve.Points.Count; i++ ) { valueHandler.GetValues( curve, i, out baseVal, out lowVal, out hiVal ); double x = isXBase ? baseVal : hiVal; double y = isXBase ? hiVal : baseVal; if ( x != PointPair.Missing && y != PointPair.Missing && lowVal != PointPair.Missing ) { if ( x < tXMinVal ) tXMinVal = x; if ( x > tXMaxVal ) tXMaxVal = x; if ( y < tYMinVal ) tYMinVal = y; if ( y > tYMaxVal ) tYMaxVal = y; if ( !isXBase ) { if ( lowVal < tXMinVal ) tXMinVal = lowVal; if ( lowVal > tXMaxVal ) tXMaxVal = lowVal; } else { if ( lowVal < tYMinVal ) tYMinVal = lowVal; if ( lowVal > tYMaxVal ) tYMaxVal = lowVal; } } } } /// <summary> /// Render all the <see cref="CurveItem"/> objects in the list to the /// specified <see cref="Graphics"/> /// device by calling the <see cref="CurveItem.Draw"/> member function of /// each <see cref="CurveItem"/> object. /// </summary> /// <param name="g"> /// A graphic device object to be drawn into. This is normally e.Graphics from the /// PaintEventArgs argument to the Paint() method. /// </param> /// <param name="pane"> /// A reference to the <see cref="GraphPane"/> object that is the parent or /// owner of this object. /// </param> /// <param name="scaleFactor"> /// The scaling factor to be used for rendering objects. This is calculated and /// passed down by the parent <see cref="GraphPane"/> object using the /// <see cref="PaneBase.CalcScaleFactor"/> method, and is used to proportionally adjust /// font sizes, etc. according to the actual size of the graph. /// </param> public void Draw( Graphics g, GraphPane pane, float scaleFactor ) { // Configure the accumulator for stacked bars //Bar.ResetBarStack(); // Count the number of BarItems in the curvelist int pos = this.NumBars; // sorted overlay bars are a special case, since they are sorted independently at each // ordinal position. if ( pane._barSettings.Type == BarType.SortedOverlay ) { // First, create a new curveList with references (not clones) of the curves CurveList tempList = new CurveList(); foreach ( CurveItem curve in this ) if ( curve.IsBar ) tempList.Add( (CurveItem) curve ); // Loop through the bars, graphing each ordinal position separately for ( int i=0; i<this.maxPts; i++ ) { // At each ordinal position, sort the curves according to the value axis value tempList.Sort( pane._barSettings.Base == BarBase.X ? SortType.YValues : SortType.XValues, i ); // plot the bars for the current ordinal position, in sorted order foreach ( BarItem barItem in tempList ) barItem.Bar.DrawSingleBar( g, pane, barItem, ((BarItem)barItem).BaseAxis( pane ), ((BarItem)barItem).ValueAxis( pane ), 0, i, ( (BarItem)barItem ).GetBarWidth( pane ), scaleFactor ); } } // Loop for each curve in reverse order to pick up the remaining curves // The reverse order is done so that curves that are later in the list are plotted behind // curves that are earlier in the list for ( int i = this.Count - 1; i >= 0; i-- ) { CurveItem curve = this[i]; if ( curve.IsBar) pos--; // Render the curve // if it's a sorted overlay bar type, it's already been done above if ( !( curve.IsBar && pane._barSettings.Type == BarType.SortedOverlay ) ) { curve.Draw( g, pane, pos, scaleFactor ); } } } /// <summary> /// Find the ordinal position of the specified <see cref="BarItem" /> within /// the <see cref="CurveList" />. This position only counts <see cef="BarItem" /> /// types, ignoring all other types. /// </summary> /// <param name="pane">The <see cref="GraphPane" /> of interest</param> /// <param name="barItem">The <see cref="BarItem" /> for which to search.</param> /// <returns>The ordinal position of the specified bar, or -1 if the bar /// was not found.</returns> public int GetBarItemPos( GraphPane pane, BarItem barItem ) { if ( pane._barSettings.Type == BarType.Overlay || pane._barSettings.Type == BarType.Stack || pane._barSettings.Type == BarType.PercentStack) return 0; int i = 0; foreach ( CurveItem curve in this ) { if ( curve == barItem ) return i; else if ( curve is BarItem ) i++; } return -1; } #endregion } }
McoreD/TDMaker
TDMaker/Lib/BDInfo/ZedGraph/CurveList.cs
C#
gpl-2.0
23,063
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Signrider")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Signrider")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
swkrueger/signrider
SignRider/Signrider/Properties/AssemblyInfo.cs
C#
gpl-2.0
2,245
from datetime import datetime from grazyna.utils import register @register(cmd='weekend') def weekend(bot): """ Answer to timeless question - are we at .weekend, yet? """ current_date = datetime.now() day = current_date.weekday() nick = bot.user.nick if day in (5, 6): answer = "Oczywiście %s - jest weekend. Omawiamy tylko lajtowe tematy, ok?" % nick else: str_day = datetime.strftime(current_date, "%A") answer = "%s - dopiero %s, musisz jeszcze poczekać..." % (nick, str_day) bot.reply(answer)
firemark/grazyna
grazyna/plugins/weekend.py
Python
gpl-2.0
562
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * * 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 2 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/>. */ /* ScriptData Name: ban_commandscript %Complete: 100 Comment: All ban related commands Category: commandscripts EndScriptData */ #include "AccountMgr.h" #include "Chat.h" #include "Language.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptMgr.h" class ban_commandscript : public CommandScript { public: ban_commandscript() : CommandScript("ban_commandscript") { } ChatCommand* GetCommands() const override { static ChatCommand unbanCommandTable[] = { { "account", rbac::RBAC_PERM_COMMAND_UNBAN_ACCOUNT, true, &HandleUnBanAccountCommand, "", NULL }, { "character", rbac::RBAC_PERM_COMMAND_UNBAN_CHARACTER, true, &HandleUnBanCharacterCommand, "", NULL }, { "playeraccount", rbac::RBAC_PERM_COMMAND_UNBAN_PLAYERACCOUNT, true, &HandleUnBanAccountByCharCommand, "", NULL }, { "ip", rbac::RBAC_PERM_COMMAND_UNBAN_IP, true, &HandleUnBanIPCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; static ChatCommand banlistCommandTable[] = { { "account", rbac::RBAC_PERM_COMMAND_BANLIST_ACCOUNT, true, &HandleBanListAccountCommand, "", NULL }, { "character", rbac::RBAC_PERM_COMMAND_BANLIST_CHARACTER, true, &HandleBanListCharacterCommand, "", NULL }, { "ip", rbac::RBAC_PERM_COMMAND_BANLIST_IP, true, &HandleBanListIPCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; static ChatCommand baninfoCommandTable[] = { { "account", rbac::RBAC_PERM_COMMAND_BANINFO_ACCOUNT, true, &HandleBanInfoAccountCommand, "", NULL }, { "character", rbac::RBAC_PERM_COMMAND_BANINFO_CHARACTER, true, &HandleBanInfoCharacterCommand, "", NULL }, { "ip", rbac::RBAC_PERM_COMMAND_BANINFO_IP, true, &HandleBanInfoIPCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; static ChatCommand banCommandTable[] = { { "account", rbac::RBAC_PERM_COMMAND_BAN_ACCOUNT, true, &HandleBanAccountCommand, "", NULL }, { "character", rbac::RBAC_PERM_COMMAND_BAN_CHARACTER, true, &HandleBanCharacterCommand, "", NULL }, { "playeraccount", rbac::RBAC_PERM_COMMAND_BAN_PLAYERACCOUNT, true, &HandleBanAccountByCharCommand, "", NULL }, { "ip", rbac::RBAC_PERM_COMMAND_BAN_IP, true, &HandleBanIPCommand, "", NULL }, { NULL, 0, false, NULL, "", NULL } }; static ChatCommand commandTable[] = { { "ban", rbac::RBAC_PERM_COMMAND_BAN, true, NULL, "", banCommandTable }, { "baninfo", rbac::RBAC_PERM_COMMAND_BANINFO, true, NULL, "", baninfoCommandTable }, { "banlist", rbac::RBAC_PERM_COMMAND_BANLIST, true, NULL, "", banlistCommandTable }, { "unban", rbac::RBAC_PERM_COMMAND_UNBAN, true, NULL, "", unbanCommandTable }, { NULL, 0, false, NULL, "", NULL } }; return commandTable; } static bool HandleBanAccountCommand(ChatHandler* handler, char const* args) { return HandleBanHelper(BAN_ACCOUNT, args, handler); } static bool HandleBanCharacterCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* nameStr = strtok((char*)args, " "); if (!nameStr) return false; std::string name = nameStr; char* durationStr = strtok(NULL, " "); if (!durationStr || !atoi(durationStr)) return false; char* reasonStr = strtok(NULL, ""); if (!reasonStr) return false; if (!normalizePlayerName(name)) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } std::string author = handler->GetSession() ? handler->GetSession()->GetPlayerName() : "Server"; switch (sWorld->BanCharacter(name, durationStr, reasonStr, author)) { case BAN_SUCCESS: { if (atoi(durationStr) > 0) { if (sWorld->getBoolConfig(CONFIG_SHOW_BAN_IN_WORLD)) sWorld->SendWorldText(LANG_BAN_CHARACTER_YOUBANNEDMESSAGE_WORLD, author.c_str(), name.c_str(), secsToTimeString(TimeStringToSecs(durationStr), true).c_str(), reasonStr); else handler->PSendSysMessage(LANG_BAN_YOUBANNED, name.c_str(), secsToTimeString(TimeStringToSecs(durationStr), true).c_str(), reasonStr); } else { if (sWorld->getBoolConfig(CONFIG_SHOW_BAN_IN_WORLD)) sWorld->SendWorldText(LANG_BAN_CHARACTER_YOUPERMBANNEDMESSAGE_WORLD, author.c_str(), name.c_str(), reasonStr); else handler->PSendSysMessage(LANG_BAN_YOUPERMBANNED, name.c_str(), reasonStr); } break; } case BAN_NOTFOUND: { handler->PSendSysMessage(LANG_BAN_NOTFOUND, "character", name.c_str()); handler->SetSentErrorMessage(true); return false; } default: break; } return true; } static bool HandleBanAccountByCharCommand(ChatHandler* handler, char const* args) { return HandleBanHelper(BAN_CHARACTER, args, handler); } static bool HandleBanIPCommand(ChatHandler* handler, char const* args) { return HandleBanHelper(BAN_IP, args, handler); } static bool HandleBanHelper(BanMode mode, char const* args, ChatHandler* handler) { if (!*args) return false; char* cnameOrIP = strtok((char*)args, " "); if (!cnameOrIP) return false; std::string nameOrIP = cnameOrIP; char* durationStr = strtok(NULL, " "); if (!durationStr || !atoi(durationStr)) return false; char* reasonStr = strtok(NULL, ""); if (!reasonStr) return false; switch (mode) { case BAN_ACCOUNT: if (!AccountMgr::normalizeString(nameOrIP)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); handler->SetSentErrorMessage(true); return false; } break; case BAN_CHARACTER: if (!normalizePlayerName(nameOrIP)) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } break; case BAN_IP: if (!IsIPAddress(nameOrIP.c_str())) return false; break; } std::string author = handler->GetSession() ? handler->GetSession()->GetPlayerName() : "Server"; switch (sWorld->BanAccount(mode, nameOrIP, durationStr, reasonStr, author)) { case BAN_SUCCESS: if (atoi(durationStr) > 0) { if (sWorld->getBoolConfig(CONFIG_SHOW_BAN_IN_WORLD)) sWorld->SendWorldText(LANG_BAN_ACCOUNT_YOUBANNEDMESSAGE_WORLD, author.c_str(), nameOrIP.c_str(), secsToTimeString(TimeStringToSecs(durationStr), true).c_str(), reasonStr); else handler->PSendSysMessage(LANG_BAN_YOUBANNED, nameOrIP.c_str(), secsToTimeString(TimeStringToSecs(durationStr), true).c_str(), reasonStr); } else { if (sWorld->getBoolConfig(CONFIG_SHOW_BAN_IN_WORLD)) sWorld->SendWorldText(LANG_BAN_ACCOUNT_YOUPERMBANNEDMESSAGE_WORLD, author.c_str(), nameOrIP.c_str(), reasonStr); else handler->PSendSysMessage(LANG_BAN_YOUPERMBANNED, nameOrIP.c_str(), reasonStr); } break; case BAN_SYNTAX_ERROR: return false; case BAN_NOTFOUND: switch (mode) { default: handler->PSendSysMessage(LANG_BAN_NOTFOUND, "account", nameOrIP.c_str()); break; case BAN_CHARACTER: handler->PSendSysMessage(LANG_BAN_NOTFOUND, "character", nameOrIP.c_str()); break; case BAN_IP: handler->PSendSysMessage(LANG_BAN_NOTFOUND, "ip", nameOrIP.c_str()); break; } handler->SetSentErrorMessage(true); return false; } return true; } static bool HandleBanInfoAccountCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* nameStr = strtok((char*)args, ""); if (!nameStr) return false; std::string accountName = nameStr; if (!AccountMgr::normalizeString(accountName)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); return false; } uint32 accountId = AccountMgr::GetId(accountName); if (!accountId) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); return true; } return HandleBanInfoHelper(accountId, accountName.c_str(), handler); } static bool HandleBanInfoHelper(uint32 accountId, char const* accountName, ChatHandler* handler) { QueryResult result = LoginDatabase.PQuery("SELECT FROM_UNIXTIME(bandate), unbandate-bandate, active, unbandate, banreason, bannedby FROM account_banned WHERE id = '%u' ORDER BY bandate ASC", accountId); if (!result) { handler->PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountName); return true; } handler->PSendSysMessage(LANG_BANINFO_BANHISTORY, accountName); do { Field* fields = result->Fetch(); time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; if (fields[2].GetBool() && (fields[1].GetUInt64() == uint64(0) || unbanDate >= time(NULL))) active = true; bool permanent = (fields[1].GetUInt64() == uint64(0)); std::string banTime = permanent ? handler->GetTrinityString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt64(), true); handler->PSendSysMessage(LANG_BANINFO_HISTORYENTRY, fields[0].GetCString(), banTime.c_str(), active ? handler->GetTrinityString(LANG_YES) : handler->GetTrinityString(LANG_NO), fields[4].GetCString(), fields[5].GetCString()); } while (result->NextRow()); return true; } static bool HandleBanInfoCharacterCommand(ChatHandler* handler, char const* args) { if (!*args) return false; Player* target = ObjectAccessor::FindPlayerByName(args); uint32 targetGuid = 0; std::string name(args); if (!target) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUID_BY_NAME); stmt->setString(0, name); PreparedQueryResult resultCharacter = CharacterDatabase.Query(stmt); if (!resultCharacter) { handler->PSendSysMessage(LANG_BANINFO_NOCHARACTER); return false; } targetGuid = (*resultCharacter)[0].GetUInt32(); } else targetGuid = target->GetGUIDLow(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANINFO); stmt->setUInt32(0, targetGuid); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) { handler->PSendSysMessage(LANG_CHAR_NOT_BANNED, name.c_str()); return true; } handler->PSendSysMessage(LANG_BANINFO_BANHISTORY, name.c_str()); do { Field* fields = result->Fetch(); time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; if (fields[2].GetUInt8() && (!fields[1].GetUInt32() || unbanDate >= time(NULL))) active = true; bool permanent = (fields[1].GetUInt32() == uint32(0)); std::string banTime = permanent ? handler->GetTrinityString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt32(), true); handler->PSendSysMessage(LANG_BANINFO_HISTORYENTRY, TimeToTimestampStr(fields[0].GetUInt32()).c_str(), banTime.c_str(), active ? handler->GetTrinityString(LANG_YES) : handler->GetTrinityString(LANG_NO), fields[4].GetCString(), fields[5].GetCString()); } while (result->NextRow()); return true; } static bool HandleBanInfoIPCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* ipStr = strtok((char*)args, ""); if (!ipStr) return false; if (!IsIPAddress(ipStr)) return false; std::string IP = ipStr; LoginDatabase.EscapeString(IP); QueryResult result = LoginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(bandate), FROM_UNIXTIME(unbandate), unbandate-UNIX_TIMESTAMP(), banreason, bannedby, unbandate-bandate FROM ip_banned WHERE ip = '%s'", IP.c_str()); if (!result) { handler->PSendSysMessage(LANG_BANINFO_NOIP); return true; } Field* fields = result->Fetch(); bool permanent = !fields[6].GetUInt64(); handler->PSendSysMessage(LANG_BANINFO_IPENTRY, fields[0].GetCString(), fields[1].GetCString(), permanent ? handler->GetTrinityString(LANG_BANINFO_NEVER) : fields[2].GetCString(), permanent ? handler->GetTrinityString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[3].GetUInt64(), true).c_str(), fields[4].GetCString(), fields[5].GetCString()); return true; } static bool HandleBanListAccountCommand(ChatHandler* handler, char const* args) { PreparedStatement* stmt = NULL; stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); LoginDatabase.Execute(stmt); char* filterStr = strtok((char*)args, " "); std::string filter = filterStr ? filterStr : ""; PreparedQueryResult result; if (filter.empty()) { stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED_ALL); result = LoginDatabase.Query(stmt); } else { stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME); stmt->setString(0, filter); result = LoginDatabase.Query(stmt); } if (!result) { handler->PSendSysMessage(LANG_BANLIST_NOACCOUNT); return true; } return HandleBanListHelper(result, handler); } static bool HandleBanListHelper(PreparedQueryResult result, ChatHandler* handler) { handler->PSendSysMessage(LANG_BANLIST_MATCHINGACCOUNT); // Chat short output if (handler->GetSession()) { do { Field* fields = result->Fetch(); uint32 accountid = fields[0].GetUInt32(); QueryResult banResult = LoginDatabase.PQuery("SELECT account.username FROM account, account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id", accountid); if (banResult) { Field* fields2 = banResult->Fetch(); handler->PSendSysMessage("%s", fields2[0].GetCString()); } } while (result->NextRow()); } // Console wide output else { handler->SendSysMessage(LANG_BANLIST_ACCOUNTS); handler->SendSysMessage(" ==============================================================================="); handler->SendSysMessage(LANG_BANLIST_ACCOUNTS_HEADER); do { handler->SendSysMessage("-------------------------------------------------------------------------------"); Field* fields = result->Fetch(); uint32 accountId = fields[0].GetUInt32(); std::string accountName; // "account" case, name can be get in same query if (result->GetFieldCount() > 1) accountName = fields[1].GetString(); // "character" case, name need extract from another DB else AccountMgr::GetName(accountId, accountName); // No SQL injection. id is uint32. QueryResult banInfo = LoginDatabase.PQuery("SELECT bandate, unbandate, bannedby, banreason FROM account_banned WHERE id = %u ORDER BY unbandate", accountId); if (banInfo) { Field* fields2 = banInfo->Fetch(); do { time_t timeBan = time_t(fields2[0].GetUInt32()); tm tmBan; localtime_r(&timeBan, &tmBan); if (fields2[0].GetUInt32() == fields2[1].GetUInt32()) { handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d| permanent |%-15.15s|%-15.15s|", accountName.c_str(), tmBan.tm_year%100, tmBan.tm_mon+1, tmBan.tm_mday, tmBan.tm_hour, tmBan.tm_min, fields2[2].GetCString(), fields2[3].GetCString()); } else { time_t timeUnban = time_t(fields2[1].GetUInt32()); tm tmUnban; localtime_r(&timeUnban, &tmUnban); handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|", accountName.c_str(), tmBan.tm_year%100, tmBan.tm_mon+1, tmBan.tm_mday, tmBan.tm_hour, tmBan.tm_min, tmUnban.tm_year%100, tmUnban.tm_mon+1, tmUnban.tm_mday, tmUnban.tm_hour, tmUnban.tm_min, fields2[2].GetCString(), fields2[3].GetCString()); } } while (banInfo->NextRow()); } } while (result->NextRow()); handler->SendSysMessage(" ==============================================================================="); } return true; } static bool HandleBanListCharacterCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* filterStr = strtok((char*)args, " "); if (!filterStr) return false; std::string filter(filterStr); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUID_BY_NAME_FILTER); stmt->setString(0, filter); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) { handler->PSendSysMessage(LANG_BANLIST_NOCHARACTER); return true; } handler->PSendSysMessage(LANG_BANLIST_MATCHINGCHARACTER); // Chat short output if (handler->GetSession()) { do { Field* fields = result->Fetch(); PreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANNED_NAME); stmt2->setUInt32(0, fields[0].GetUInt32()); PreparedQueryResult banResult = CharacterDatabase.Query(stmt2); if (banResult) handler->PSendSysMessage("%s", (*banResult)[0].GetCString()); } while (result->NextRow()); } // Console wide output else { handler->SendSysMessage(LANG_BANLIST_CHARACTERS); handler->SendSysMessage(" =============================================================================== "); handler->SendSysMessage(LANG_BANLIST_CHARACTERS_HEADER); do { handler->SendSysMessage("-------------------------------------------------------------------------------"); Field* fields = result->Fetch(); std::string char_name = fields[1].GetString(); PreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANINFO_LIST); stmt2->setUInt32(0, fields[0].GetUInt32()); PreparedQueryResult banInfo = CharacterDatabase.Query(stmt2); if (banInfo) { Field* banFields = banInfo->Fetch(); do { time_t timeBan = time_t(banFields[0].GetUInt32()); tm tmBan; localtime_r(&timeBan, &tmBan); if (banFields[0].GetUInt32() == banFields[1].GetUInt32()) { handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d| permanent |%-15.15s|%-15.15s|", char_name.c_str(), tmBan.tm_year%100, tmBan.tm_mon+1, tmBan.tm_mday, tmBan.tm_hour, tmBan.tm_min, banFields[2].GetCString(), banFields[3].GetCString()); } else { time_t timeUnban = time_t(banFields[1].GetUInt32()); tm tmUnban; localtime_r(&timeUnban, &tmUnban); handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|", char_name.c_str(), tmBan.tm_year%100, tmBan.tm_mon+1, tmBan.tm_mday, tmBan.tm_hour, tmBan.tm_min, tmUnban.tm_year%100, tmUnban.tm_mon+1, tmUnban.tm_mday, tmUnban.tm_hour, tmUnban.tm_min, banFields[2].GetCString(), banFields[3].GetCString()); } } while (banInfo->NextRow()); } } while (result->NextRow()); handler->SendSysMessage(" =============================================================================== "); } return true; } static bool HandleBanListIPCommand(ChatHandler* handler, char const* args) { PreparedStatement* stmt = NULL; stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); LoginDatabase.Execute(stmt); char* filterStr = strtok((char*)args, " "); std::string filter = filterStr ? filterStr : ""; LoginDatabase.EscapeString(filter); PreparedQueryResult result; if (filter.empty()) { stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED_ALL); result = LoginDatabase.Query(stmt); } else { stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED_BY_IP); stmt->setString(0, filter); result = LoginDatabase.Query(stmt); } if (!result) { handler->PSendSysMessage(LANG_BANLIST_NOIP); return true; } handler->PSendSysMessage(LANG_BANLIST_MATCHINGIP); // Chat short output if (handler->GetSession()) { do { Field* fields = result->Fetch(); handler->PSendSysMessage("%s", fields[0].GetCString()); } while (result->NextRow()); } // Console wide output else { handler->SendSysMessage(LANG_BANLIST_IPS); handler->SendSysMessage(" ==============================================================================="); handler->SendSysMessage(LANG_BANLIST_IPS_HEADER); do { handler->SendSysMessage("-------------------------------------------------------------------------------"); Field* fields = result->Fetch(); time_t timeBan = time_t(fields[1].GetUInt32()); tm tmBan; localtime_r(&timeBan, &tmBan); if (fields[1].GetUInt32() == fields[2].GetUInt32()) { handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d| permanent |%-15.15s|%-15.15s|", fields[0].GetCString(), tmBan.tm_year%100, tmBan.tm_mon+1, tmBan.tm_mday, tmBan.tm_hour, tmBan.tm_min, fields[3].GetCString(), fields[4].GetCString()); } else { time_t timeUnban = time_t(fields[2].GetUInt32()); tm tmUnban; localtime_r(&timeUnban, &tmUnban); handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|", fields[0].GetCString(), tmBan.tm_year%100, tmBan.tm_mon+1, tmBan.tm_mday, tmBan.tm_hour, tmBan.tm_min, tmUnban.tm_year%100, tmUnban.tm_mon+1, tmUnban.tm_mday, tmUnban.tm_hour, tmUnban.tm_min, fields[3].GetCString(), fields[4].GetCString()); } } while (result->NextRow()); handler->SendSysMessage(" ==============================================================================="); } return true; } static bool HandleUnBanAccountCommand(ChatHandler* handler, char const* args) { return HandleUnBanHelper(BAN_ACCOUNT, args, handler); } static bool HandleUnBanCharacterCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* nameStr = strtok((char*)args, " "); if (!nameStr) return false; std::string name = nameStr; if (!normalizePlayerName(name)) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } if (!sWorld->RemoveBanCharacter(name)) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } return true; } static bool HandleUnBanAccountByCharCommand(ChatHandler* handler, char const* args) { return HandleUnBanHelper(BAN_CHARACTER, args, handler); } static bool HandleUnBanIPCommand(ChatHandler* handler, char const* args) { return HandleUnBanHelper(BAN_IP, args, handler); } static bool HandleUnBanHelper(BanMode mode, char const* args, ChatHandler* handler) { if (!*args) return false; char* nameOrIPStr = strtok((char*)args, " "); if (!nameOrIPStr) return false; std::string nameOrIP = nameOrIPStr; switch (mode) { case BAN_ACCOUNT: if (!AccountMgr::normalizeString(nameOrIP)) { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, nameOrIP.c_str()); handler->SetSentErrorMessage(true); return false; } break; case BAN_CHARACTER: if (!normalizePlayerName(nameOrIP)) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } break; case BAN_IP: if (!IsIPAddress(nameOrIP.c_str())) return false; break; } if (sWorld->RemoveBanAccount(mode, nameOrIP)) handler->PSendSysMessage(LANG_UNBAN_UNBANNED, nameOrIP.c_str()); else handler->PSendSysMessage(LANG_UNBAN_ERROR, nameOrIP.c_str()); return true; } }; void AddSC_ban_commandscript() { new ban_commandscript(); }
madisodr/legacy-core
src/server/scripts/Commands/cs_ban.cpp
C++
gpl-2.0
30,765
package model.device; /** * Title : The Mobile Robot Explorer Simulation Environment v2.0 * Copyright: GNU General Public License as published by the Free Software Foundation * Company : Hanze University of Applied Sciences * * @author Dustin Meijer (2012) * @author Alexander Jeurissen (2012) * @author Davide Brugali (2002) * @version 2.0 */ import model.environment.Environment; import model.environment.Position; import model.robot.MobileRobot; import java.awt.Polygon; import java.awt.Color; import java.io.PrintWriter; import java.util.ArrayList; public abstract class Device implements Runnable { // A final object to make sure the lock cannot be overwritten with another Object private final Object lock = new Object(); private final String name; // the name of this device private final Polygon shape; // the device's shape in local coords // a reference to the environment protected final Environment environment; // a reference to the robot protected final MobileRobot robot; // origin of the device reference frame with regards to the robot frame protected final Position localPosition; // the robot current position protected Position robotPosition; // the arrayList with all the commands protected final ArrayList<String> commands; // the colors of the devices protected Color backgroundColor = Color.red; protected Color foregroundColor = Color.blue; // Is the device running? protected boolean running; // Is the device executingCommand a command? protected boolean executingCommand; private PrintWriter output; // the constructor protected Device(String name, MobileRobot robot, Position local, Environment environment) { this.name = name; this.robot = robot; this.localPosition = local; this.environment = environment; this.shape = new Polygon(); this.robotPosition = new Position(); this.running = true; this.executingCommand = false; this.commands = new ArrayList<String>(); this.output = null; robot.readPosition(this.robotPosition); } // this method is invoked when the geometric shape of the device is defined protected void addPoint(int x, int y) { shape.addPoint(x, y); } public boolean sendCommand(String command) { commands.add(command); synchronized (lock) { // Notify the tread that is waiting for commands. lock.notify(); } return true; } protected synchronized void writeOut(String data) { if (output != null) { output.println(data); } else { System.out.println(this.name + " output not initialized"); } } public void setOutput(PrintWriter output) { this.output = output; } public void run() { System.out.println("Device " + this.name + " running"); do { try { if (executingCommand) { // pause before the next step synchronized (this) { Thread.sleep(MobileRobot.delay); } } else if (commands.size() > 0) { // extracts the the next command and executes it String command = commands.remove(0); executeCommand(command); } else { // waits for a new command synchronized (lock) { // Wait to be notified about a new command (in sendCommand()). lock.wait(); } } // processes a new step nextStep(); } catch (InterruptedException ie) { System.err.println("Device : Run was interrupted."); } } while (this.running); } public Position getRobotPosition() { return robotPosition; } public Position getLocalPosition() { return localPosition; } public Polygon getShape() { return shape; } public Color getBackgroundColor() { return backgroundColor; } public Color getForegroundColor() { return foregroundColor; } public String getName() { return name; } protected abstract void executeCommand(String command); protected abstract void nextStep(); }
TranceCake/SoftwareEngineering
leertaak3DynamicProgramming/leertaak4MobileRobot/src/model/device/Device.java
Java
gpl-2.0
3,923
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列特性集 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Web")] [assembly: AssemblyCopyright("版权所有(C) Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的某个类型, // 请针对该类型将 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("c041effd-97b4-4bad-8d51-badbb5d742c5")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“修订号”和“内部版本号”的默认值, // 方法是按如下所示使用“*”: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
lsyuan/yzxzgl
Web/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,326
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DateFormatSymbols; import java.text.Format; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** * <p>Abstract class for Date/Time/Calendar validation.</p> * * <p>This is a <i>base</i> class for building Date / Time * Validators using format parsing.</p> * * @version $Revision: 1739356 $ * @since Validator 1.3.0 */ public abstract class AbstractCalendarValidator extends AbstractFormatValidator { private static final long serialVersionUID = -1410008585975827379L; private final int dateStyle; private final int timeStyle; /** * Construct an instance with the specified <i>strict</i>, * <i>time</i> and <i>date</i> style parameters. * * @param strict <code>true</code> if strict * <code>Format</code> parsing should be used. * @param dateStyle the date style to use for Locale validation. * @param timeStyle the time style to use for Locale validation. */ public AbstractCalendarValidator(boolean strict, int dateStyle, int timeStyle) { super(strict); this.dateStyle = dateStyle; this.timeStyle = timeStyle; } /** * <p>Validate using the specified <code>Locale</code>. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format, defaults to the default * @return <code>true</code> if the value is valid. */ @Override public boolean isValid(String value, String pattern, Locale locale) { Object parsedValue = parse(value, pattern, locale, (TimeZone)null); return (parsedValue == null ? false : true); } /** * <p>Format an object into a <code>String</code> using * the default Locale.</p> * * @param value The value validation is being performed on. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, TimeZone timeZone) { return format(value, (String)null, (Locale)null, timeZone); } /** * <p>Format an object into a <code>String</code> using * the specified pattern.</p> * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, String pattern, TimeZone timeZone) { return format(value, pattern, (Locale)null, timeZone); } /** * <p>Format an object into a <code>String</code> using * the specified Locale.</p> * * @param value The value validation is being performed on. * @param locale The locale to use for the Format. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, Locale locale, TimeZone timeZone) { return format(value, (String)null, locale, timeZone); } /** * <p>Format an object using the specified pattern and/or * <code>Locale</code>. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format. * @return The value formatted as a <code>String</code>. */ @Override public String format(Object value, String pattern, Locale locale) { return format(value, pattern, locale, (TimeZone)null); } /** * <p>Format an object using the specified pattern and/or * <code>Locale</code>. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a <code>Calendar</code>. * @return The value formatted as a <code>String</code>. */ public String format(Object value, String pattern, Locale locale, TimeZone timeZone) { DateFormat formatter = (DateFormat)getFormat(pattern, locale); if (timeZone != null) { formatter.setTimeZone(timeZone); } else if (value instanceof Calendar) { formatter.setTimeZone(((Calendar)value).getTimeZone()); } return format(value, formatter); } /** * <p>Format a value with the specified <code>DateFormat</code>.</p> * * @param value The value to be formatted. * @param formatter The Format to use. * @return The formatted value. */ @Override protected String format(Object value, Format formatter) { if (value == null) { return null; } else if (value instanceof Calendar) { value = ((Calendar)value).getTime(); } return formatter.format(value); } /** * <p>Checks if the value is valid against a specified pattern.</p> * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the <code>Locale</code> if <code>null</code>. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed value if valid or <code>null</code> if invalid. */ protected Object parse(String value, String pattern, Locale locale, TimeZone timeZone) { value = (value == null ? null : value.trim()); if (value == null || value.length() == 0) { return null; } DateFormat formatter = (DateFormat)getFormat(pattern, locale); if (timeZone != null) { formatter.setTimeZone(timeZone); } return parse(value, formatter); } /** * <p>Process the parsed value, performing any further validation * and type conversion required.</p> * * @param value The parsed object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to the appropriate type * if valid or <code>null</code> if invalid. */ @Override protected abstract Object processParsedValue(Object value, Format formatter); /** * <p>Returns a <code>DateFormat</code> for the specified <i>pattern</i> * and/or <code>Locale</code>.</p> * * @param pattern The pattern used to validate the value against or * <code>null</code> to use the default for the <code>Locale</code>. * @param locale The locale to use for the currency format, system default if null. * @return The <code>DateFormat</code> to created. */ @Override protected Format getFormat(String pattern, Locale locale) { DateFormat formatter = null; boolean usePattern = (pattern != null && pattern.length() > 0); if (!usePattern) { formatter = (DateFormat)getFormat(locale); } else if (locale == null) { formatter = new SimpleDateFormat(pattern); } else { DateFormatSymbols symbols = new DateFormatSymbols(locale); formatter = new SimpleDateFormat(pattern, symbols); } formatter.setLenient(false); return formatter; } /** * <p>Returns a <code>DateFormat</code> for the specified Locale.</p> * * @param locale The locale a <code>DateFormat</code> is required for, * system default if null. * @return The <code>DateFormat</code> to created. */ protected Format getFormat(Locale locale) { DateFormat formatter = null; if (dateStyle >= 0 && timeStyle >= 0) { if (locale == null) { formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle); } else { formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); } } else if (timeStyle >= 0) { if (locale == null) { formatter = DateFormat.getTimeInstance(timeStyle); } else { formatter = DateFormat.getTimeInstance(timeStyle, locale); } } else { int useDateStyle = dateStyle >= 0 ? dateStyle : DateFormat.SHORT; if (locale == null) { formatter = DateFormat.getDateInstance(useDateStyle); } else { formatter = DateFormat.getDateInstance(useDateStyle, locale); } } formatter.setLenient(false); return formatter; } /** * <p>Compares a calendar value to another, indicating whether it is * equal, less then or more than at a specified level.</p> * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param field The field <i>level</i> to compare to - e.g. specifying * <code>Calendar.MONTH</code> will compare the year and month * portions of the calendar. * @return Zero if the first value is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compare(Calendar value, Calendar compare, int field) { int result = 0; // Compare Year result = calculateCompareResult(value, compare, Calendar.YEAR); if (result != 0 || field == Calendar.YEAR) { return result; } // Compare Week of Year if (field == Calendar.WEEK_OF_YEAR) { return calculateCompareResult(value, compare, Calendar.WEEK_OF_YEAR); } // Compare Day of the Year if (field == Calendar.DAY_OF_YEAR) { return calculateCompareResult(value, compare, Calendar.DAY_OF_YEAR); } // Compare Month result = calculateCompareResult(value, compare, Calendar.MONTH); if (result != 0 || field == Calendar.MONTH) { return result; } // Compare Week of Month if (field == Calendar.WEEK_OF_MONTH) { return calculateCompareResult(value, compare, Calendar.WEEK_OF_MONTH); } // Compare Date result = calculateCompareResult(value, compare, Calendar.DATE); if (result != 0 || (field == Calendar.DATE || field == Calendar.DAY_OF_WEEK || field == Calendar.DAY_OF_WEEK_IN_MONTH)) { return result; } // Compare Time fields return compareTime(value, compare, field); } /** * <p>Compares a calendar time value to another, indicating whether it is * equal, less then or more than at a specified level.</p> * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param field The field <i>level</i> to compare to - e.g. specifying * <code>Calendar.MINUTE</code> will compare the hours and minutes * portions of the calendar. * @return Zero if the first value is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compareTime(Calendar value, Calendar compare, int field) { int result = 0; // Compare Hour result = calculateCompareResult(value, compare, Calendar.HOUR_OF_DAY); if (result != 0 || (field == Calendar.HOUR || field == Calendar.HOUR_OF_DAY)) { return result; } // Compare Minute result = calculateCompareResult(value, compare, Calendar.MINUTE); if (result != 0 || field == Calendar.MINUTE) { return result; } // Compare Second result = calculateCompareResult(value, compare, Calendar.SECOND); if (result != 0 || field == Calendar.SECOND) { return result; } // Compare Milliseconds if (field == Calendar.MILLISECOND) { return calculateCompareResult(value, compare, Calendar.MILLISECOND); } throw new IllegalArgumentException("Invalid field: " + field); } /** * <p>Compares a calendar's quarter value to another, indicating whether it is * equal, less then or more than the specified quarter.</p> * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param monthOfFirstQuarter The month that the first quarter starts. * @return Zero if the first quarter is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compareQuarters(Calendar value, Calendar compare, int monthOfFirstQuarter) { int valueQuarter = calculateQuarter(value, monthOfFirstQuarter); int compareQuarter = calculateQuarter(compare, monthOfFirstQuarter); if (valueQuarter < compareQuarter) { return -1; } else if (valueQuarter > compareQuarter) { return 1; } else { return 0; } } /** * <p>Calculate the quarter for the specified Calendar.</p> * * @param calendar The Calendar value. * @param monthOfFirstQuarter The month that the first quarter starts. * @return The calculated quarter. */ private int calculateQuarter(Calendar calendar, int monthOfFirstQuarter) { // Add Year int year = calendar.get(Calendar.YEAR); int month = (calendar.get(Calendar.MONTH) + 1); int relativeMonth = (month >= monthOfFirstQuarter) ? (month - monthOfFirstQuarter) : (month + (12 - monthOfFirstQuarter)); // CHECKSTYLE IGNORE MagicNumber int quarter = ((relativeMonth / 3) + 1); // CHECKSTYLE IGNORE MagicNumber // adjust the year if the quarter doesn't start in January if (month < monthOfFirstQuarter) { --year; } return (year * 10) + quarter; // CHECKSTYLE IGNORE MagicNumber } /** * <p>Compares the field from two calendars indicating whether the field for the * first calendar is equal to, less than or greater than the field from the * second calendar. * * @param value The Calendar value. * @param compare The <code>Calendar</code> to check the value against. * @param field The field to compare for the calendars. * @return Zero if the first calendar's field is equal to the seconds, -1 * if it is less than the seconds or +1 if it is greater than the seconds. */ private int calculateCompareResult(Calendar value, Calendar compare, int field) { int difference = value.get(field) - compare.get(field); if (difference < 0) { return -1; } else if (difference > 0) { return 1; } else { return 0; } } }
lamsfoundation/lams
3rdParty_sources/commons-validator/org/apache/commons/validator/routines/AbstractCalendarValidator.java
Java
gpl-2.0
16,430
/** @file Host-key wrapper. @if license Copyright (C) 2010, 2013 Alexander Lamaison <awl03@doc.ic.ac.uk> 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. In addition, as a special exception, the the copyright holders give you permission to combine this program with free software programs or the OpenSSL project's "OpenSSL" library (or with modified versions of it, with unchanged license). You may copy and distribute such a system following the terms of the GNU GPL for this program and the licenses of the other code concerned. The GNU General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. @endif */ #ifndef SSH_HOST_KEY_HPP #define SSH_HOST_KEY_HPP #include <ssh/detail/session_state.hpp> #include <boost/foreach.hpp> // BOOST_FOREACH #include <boost/shared_ptr.hpp> // shared_ptr #include <boost/throw_exception.hpp> // BOOST_THROW_EXCEPTION #include <sstream> // ostringstream #include <stdexcept> // invalid_argument #include <string> #include <utility> // pair #include <vector> #include <libssh2.h> namespace ssh { namespace detail { /** * Thin wrapper around libssh2_session_hostkey. */ inline std::pair<std::string, int> hostkey(session_state& session) { // Session owns the string. // Lock until we finish copying the key string from the session. I // don't know if other calls to the session are currently able to // change it, but they might one day. // Locking it for the duration makes it thread-safe either way. detail::session_state::scoped_lock lock = session.aquire_lock(); size_t len = 0; int type = LIBSSH2_HOSTKEY_TYPE_UNKNOWN; const char* key = libssh2_session_hostkey(session.session_ptr(), &len, &type); if (key) return std::make_pair(std::string(key, len), type); else return std::make_pair(std::string(), type); } /** * Thin wrapper around libssh2_hostkey_hash. * * @param T Type of collection to return. Sensible examples * include std::string or std::vector<unsigned char>. * @param session libssh2 session pointer * @param hash_type Hash method being requested. */ template <typename T> inline T hostkey_hash(session_state& session, int hash_type) { // Session owns the data. // Lock until we finish copying the key hash bytes from the session. I // don't know if other calls to the session are currently able to // change it, but they might one day. // Locking it for the duration makes it thread-safe either way. detail::session_state::scoped_lock lock = session.aquire_lock(); const T::value_type* hash_bytes = reinterpret_cast<const T::value_type*>( ::libssh2_hostkey_hash(session.session_ptr(), hash_type)); size_t len = 0; if (hash_type == LIBSSH2_HOSTKEY_HASH_MD5) len = 16; else if (hash_type == LIBSSH2_HOSTKEY_HASH_SHA1) len = 20; else BOOST_THROW_EXCEPTION(std::invalid_argument("Unknown hash type")); if (hash_bytes) return T(hash_bytes, hash_bytes + len); else return T(); } /** * Thin wrapper around libssh2_session_methods. */ inline std::string method(session_state& session, int method_type) { // Session owns the string. // Lock until we finish copying the string from the session. I // don't know if other calls to the session are currently able to // change it, but they might one day. // Locking it for the duration makes it thread-safe either way. detail::session_state::scoped_lock lock = session.aquire_lock(); const char* key_type = libssh2_session_methods(session.session_ptr(), method_type); if (key_type) return std::string(key_type); else return std::string(); } } /** * Possible types of host-key algorithm. */ struct hostkey_type { enum enum_t { unknown, rsa1, ssh_rsa, ssh_dss }; }; namespace detail { /** * Convert the returned key-type from libssh2_session_hostkey into a value from * the hostkey_type enum. */ inline hostkey_type::enum_t type_to_hostkey_type(int type) { switch (type) { case LIBSSH2_HOSTKEY_TYPE_RSA: return hostkey_type::ssh_rsa; case LIBSSH2_HOSTKEY_TYPE_DSS: return hostkey_type::ssh_dss; default: return hostkey_type::unknown; } } } /** * Class representing the session's current negotiated host-key. * * As well as the raw key itself, this class provides MD5 and SHA1 hashes and * key metadata. */ class host_key { public: explicit host_key(detail::session_state& session) : // We pull everything out of the session here and store it to avoid // instances of this class depending on the lifetime of the session m_key(detail::hostkey(session)), m_algorithm_name(detail::method(session, LIBSSH2_METHOD_HOSTKEY)), m_md5_hash(detail::hostkey_hash<std::vector<unsigned char>>( session, LIBSSH2_HOSTKEY_HASH_MD5)), m_sha1_hash(detail::hostkey_hash<std::vector<unsigned char>>( session, LIBSSH2_HOSTKEY_HASH_SHA1)) { } /** * Host-key either raw or base-64 encoded. * * @see is_base64() */ std::string key() const { return m_key.first; } /** * Is the key returned by key() base64-encoded (printable)? */ bool is_base64() const { return false; } /** * Type of the key algorithm e.g., ssh-dss. */ hostkey_type::enum_t algorithm() const { return detail::type_to_hostkey_type(m_key.second); } /** * Printable name of the method negotiated for the key algorithm. */ std::string algorithm_name() const { return m_algorithm_name; } /** * Hostkey sent by the server to identify itself, hashed with the MD5 * algorithm. * * @returns Hash as binary data; it is not directly printable * (@see hexify()). */ std::vector<unsigned char> md5_hash() const { return m_md5_hash; } /** * Hostkey sent by the server to identify itself, hashed with the SHA1 * algorithm. * * @returns Hash as binary data; it is not directly printable * (@see hexify()). */ std::vector<unsigned char> sha1_hash() const { return m_sha1_hash; } private: std::pair<std::string, int> m_key; std::string m_algorithm_name; std::vector<unsigned char> m_md5_hash; std::vector<unsigned char> m_sha1_hash; }; /** * Turn a collection of bytes into a printable hexidecimal string. * * @param bytes Collection of bytes. * @param nibble_sep String to place between each pair of hexidecimal * characters. * @param uppercase Whether to use uppercase or lowercase hexidecimal. */ template <typename T> std::string hexify(const T& bytes, const std::string& nibble_sep = ":", bool uppercase = false) { std::ostringstream hex_hash; if (uppercase) hex_hash << std::uppercase; else hex_hash << std::nouppercase; hex_hash << std::hex << std::setfill('0'); BOOST_FOREACH (unsigned char b, bytes) { if (!hex_hash.str().empty()) hex_hash << nibble_sep; unsigned int i = b; hex_hash << std::setw(2) << i; } return hex_hash.str(); } } // namespace ssh #endif
alamaison/swish
ssh/host_key.hpp
C++
gpl-2.0
8,313
<?php if (!defined('THINK_PATH')) exit();?><!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" /> <title>Makerway</title> <script type="text/javascript" src="/passon/Public/js/jquery-1.11.1.min.js"></script> <link rel="stylesheet" type="text/css" href="/passon/Public/css/phonelogin.css"> </head> <body> <div class="content"> <!--<div class="title">--> <!--<div>--> <!--<span>Pass On</span>--> <!--</div>--> <!--</div>--> <div class="main"> <div class="book-message"> <div class="main-img"> <img src="<?php echo ($bookin['image']); ?>"/> </div> <!--<span class="book-title"><?php echo $s = iconv("UTF-8","GB2312",$bookin['title'])?></span>--> <span class="book-title">《<?php echo ($bookin['title']); ?>》</span> <?php if ($book['con_name'] != null): ?> <span class="book-info">分享者:<?php echo ($book['con_name']); ?></span> <?php endif ?> <?php if ($book['con_name'] == null): ?> <span class="book-info">分享者:<?php echo ($book['owner_name']); ?></span> <?php endif ?> <?php if ($book['status']==1 || $book['status']==3) : ?> <span class="book-info">状态:可借阅,现在在<?php echo ($book['keeper_name']); ?>那儿</span> <?php endif ?> <?php if ($book['status']==2 || $book['status']==5) : ?> <span class="book-info">状态:已借出,现在在<?php echo ($book['keeper_name']); ?>那儿</span> <?php endif ?> </div> <div class="book-login"> <!--action待定--> <form action="<?php echo U(pLogin);?>" method="post" onsubmit="return check()"> <div class="book-input"><label>用户名:</label><input type="text" name="username"/></div> <div class="book-input"><label>密&nbsp;&nbsp;&nbsp;&nbsp;码:</label><input type="password" name="password"/></div> <span class="span1"><a href="<?php echo U(phoneRegister);?>">立即注册>></a></span> <span class="span2"><a href="<?php echo U(phoneForget);?>">&lt;&lt;忘记密码?</a></span> <div class="book-input2"><input type="submit" name="submit" value="登录"/></div> </form> </div> </div> </div> </body> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-68503572-4', 'auto'); ga('send', 'pageview'); </script> <script type="text/javascript" src="/passon/Public/js/phonelogin.js"></script> </html>
huran2014/huran.github.io
makerway/Application/Runtime/Cache/Home/15d459605ca1272097c790b0a93a119a.php
PHP
gpl-2.0
2,727
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.cgc.bean; import java.sql.Timestamp; /** * * @author com02 */ public class MessageBean { private int runno; private String message_id; private String message_detail; private String status; private Timestamp create_date; private String create_by; private Timestamp update_date; private String update_by; private String delete_flag; private Timestamp delete_date; private String delete_by; private String company_id; /** * @return the runno */ public int getRunno() { return runno; } /** * @param runno the runno to set */ public void setRunno(int runno) { this.runno = runno; } /** * @return the message_id */ public String getMessage_id() { return message_id; } /** * @param message_id the message_id to set */ public void setMessage_id(String message_id) { this.message_id = message_id; } /** * @return the message_detail */ public String getMessage_detail() { return message_detail; } /** * @param message_detail the message_detail to set */ public void setMessage_detail(String message_detail) { this.message_detail = message_detail; } /** * @return the status */ public String getStatus() { return status; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the create_date */ public Timestamp getCreate_date() { return create_date; } /** * @param create_date the create_date to set */ public void setCreate_date(Timestamp create_date) { this.create_date = create_date; } /** * @return the create_by */ public String getCreate_by() { return create_by; } /** * @param create_by the create_by to set */ public void setCreate_by(String create_by) { this.create_by = create_by; } /** * @return the update_date */ public Timestamp getUpdate_date() { return update_date; } /** * @param update_date the update_date to set */ public void setUpdate_date(Timestamp update_date) { this.update_date = update_date; } /** * @return the update_by */ public String getUpdate_by() { return update_by; } /** * @param update_by the update_by to set */ public void setUpdate_by(String update_by) { this.update_by = update_by; } /** * @return the delete_flag */ public String getDelete_flag() { return delete_flag; } /** * @param delete_flag the delete_flag to set */ public void setDelete_flag(String delete_flag) { this.delete_flag = delete_flag; } /** * @return the delete_date */ public Timestamp getDelete_date() { return delete_date; } /** * @param delete_date the delete_date to set */ public void setDelete_date(Timestamp delete_date) { this.delete_date = delete_date; } /** * @return the delete_by */ public String getDelete_by() { return delete_by; } /** * @param delete_by the delete_by to set */ public void setDelete_by(String delete_by) { this.delete_by = delete_by; } /** * @return the company_id */ public String getCompany_id() { return company_id; } /** * @param company_id the company_id to set */ public void setCompany_id(String company_id) { this.company_id = company_id; } }
beckpalmx/ImportTask
src/com/cgc/bean/MessageBean.java
Java
gpl-2.0
3,859
package org.openstreetmap.osmaxil; import org.apache.log4j.Logger; import org.openstreetmap.osmaxil.flow.__AbstractImportFlow; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; @Component("OsmaxilApp") public class Application { @Value("${osmaxil.flow}") public String flow; public static final String NAME = "Osmaxil"; private static ClassPathXmlApplicationContext applicationContext; static private final Logger LOGGER = Logger.getLogger(Application.class); static protected final Logger LOGGER_FOR_STATS = Logger.getLogger("LoggerForStats"); public static void main(String[] args) { applicationContext = new ClassPathXmlApplicationContext("spring.xml"); Application app = (Application) applicationContext.getBean("OsmaxilApp"); LOGGER.info("=== Starting Osmaxil ==="); long startTime = System.currentTimeMillis(); try { app.run(); } catch (Exception e) { LOGGER.error(e); } LOGGER_FOR_STATS.info("Job has been executed in " + (System.currentTimeMillis() - startTime) / 1000 + " seconds"); LOGGER.info("=== Osmaxil has finished its job ==="); applicationContext.close(); } public void run() throws Exception { __AbstractImportFlow<?, ?> flow = (__AbstractImportFlow<?, ?>) applicationContext.getBean(this.flow); flow.load(); flow.process(); flow.synchronize(); flow.displayLoadingStatistics(); flow.displayProcessingStatistics(); } }
vince-from-nice/osmaxil
src/main/java/org/openstreetmap/osmaxil/Application.java
Java
gpl-2.0
1,528
<?php /** * Do authentication of users and session management * * @category DMS * @package SeedDMS * @license GPL 2 * @version @version@ * @author Markus Westphal, Malcolm Cowe, Uwe Steinmann <uwe@steinmann.cx> * @copyright Copyright (C) 2002-2005 Markus Westphal, * 2006-2008 Malcolm Cowe, 2010 Uwe Steinmann * @version Release: @package_version@ */ $refer = $_SERVER["REQUEST_URI"]; if (!strncmp("/op", $refer, 3)) { $refer=""; } else { $refer = urlencode($refer); } if (!isset($_COOKIE["mydms_session"])) { header("Location: " . $settings->_httpRoot . "out/out.Login.php?referuri=".$refer); exit; } require_once("inc.Utils.php"); require_once("inc.ClassEmail.php"); require_once("inc.ClassSession.php"); /* Load session */ $dms_session = $_COOKIE["mydms_session"]; $session = new SeedDMS_Session($db); if(!$resArr = $session->load($dms_session)) { setcookie("mydms_session", $dms_session, time()-3600, $settings->_httpRoot); //delete cookie header("Location: " . $settings->_httpRoot . "out/out.Login.php?referuri=".$refer); exit; } /* Update last access time */ $session->updateAccess($dms_session); /* Load user data */ $user = $dms->getUser($resArr["userID"]); if($user->isAdmin()) { if($resArr["su"]) { $user = $dms->getUser($resArr["su"]); } } if (!is_object($user)) { setcookie("mydms_session", $dms_session, time()-3600, $settings->_httpRoot); //delete cookie header("Location: " . $settings->_httpRoot . "out/out.Login.php?referuri=".$refer); exit; } $dms->setUser($user); if($settings->_enableEmail) { $notifier = new SeedDMS_Email(); $notifier->setSender($user); } else { $notifier = null; } /* Include the language file as specified in the session. If that is not * available use the language from the settings */ /* if(file_exists($settings->_rootDir . "languages/" . $resArr["language"] . "/lang.inc")) { include $settings->_rootDir . "languages/" . $resArr["language"] . "/lang.inc"; $session->setLanguage($resArr["language"]); } else { include $settings->_rootDir . "languages/" . $settings->_language . "/lang.inc"; $session->setLanguage($settings->_language); } */ $theme = $resArr["theme"]; if(file_exists($settings->_rootDir . "view/".$theme."/languages/" . $resArr["language"] . "/lang.inc")) { include $settings->_rootDir . "view/".$theme."/languages/" . $resArr["language"] . "/lang.inc"; } /* Check if password needs to be changed because it expired. If it needs * to be changed redirect to out/out.ForcePasswordChange.php. Do this * check only if password expiration is turned on, we are not on the * page to change the password or the page that changes the password, and * it is not admin */ if (!$user->isAdmin()) { if($settings->_passwordExpiration > 0) { if(basename($_SERVER['SCRIPT_NAME']) != 'out.ForcePasswordChange.php' && basename($_SERVER['SCRIPT_NAME']) != 'op.EditUserData.php') { $pwdexp = $user->getPwdExpiration(); if(substr($pwdexp, 0, 10) != '0000-00-00') { $pwdexpts = strtotime($pwdexp); // + $pwdexp*86400; if($pwdexpts > 0 && $pwdexpts < time()) { header("Location: ../out/out.ForcePasswordChange.php"); exit; } } } } } /* Update cookie lifetime */ if($settings->_cookieLifetime) { $lifetime = time() + intval($settings->_cookieLifetime); /* Turn off http only cookies if jumploader is enabled */ setcookie("mydms_session", $dms_session, $lifetime, $settings->_httpRoot, null, null, !$settings->_enableLargeFileUpload); } ?>
FavioGalvis/DIDOC
inc/inc.Authentication.php
PHP
gpl-2.0
3,495
/** * Created by kliu on 10/10/2015. */ var jsonschema = require("jsonschema"); var utils = {}; utils.validateJSON = function(schema, json){ var result = jsonschema.validate(json, schema); if(result.errors.length == 0){ return json; }else{ throw new Error("message not valid, " + result.errors.join()); } }; utils.validateRawString = function(schema, message){ var self = this; var json = JSON.parse(message); return self.validateJSON(json, schema); }; /** * load and initial an object from specified path, and check the function exists in this object * @param filePath * @param checkFuncs * @constructor */ utils.loadAndCheck = function(filePath, checkFuncs){ var loadCls = require(filePath); var loadObj = new loadCls(); checkFuncs.forEach(function(checkFunc){ if (typeof(loadObj[checkFunc]) != "function") { throw new Error(filePath + " doesn't have " + checkFunc + "()") } }); return loadObj; }; module.exports = utils;
adleida/adx-nodejs
utils.js
JavaScript
gpl-2.0
1,027
package com.aw.swing.mvp.action; import com.aw.swing.mvp.Presenter; import com.aw.swing.mvp.navigation.Flow; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import java.util.Iterator; import java.util.Map; /** * User: gmc * Date: 16/05/2009 */ public class BackBeanProvider { protected Log logger = LogFactory.getLog(getClass()); public BackBeanProvider() { } /** * Return the back bean that must be used. * * @return */ public Object getBackBean(Presenter targetPst,Flow flow) { Object backBean = null; backBean = flow.getTargetBackBeanAttr(); if (backBean == null) { backBean = targetPst.createBackBean(); } decorateBackBeanWithFlowAttributes(backBean, flow); return backBean; } /** * Decorate the back bean with the attributes sent in the flow * * @param backBean * @param flow */ private void decorateBackBeanWithFlowAttributes(Object backBean, Flow flow) { Map flowAttributes = flow.getAttributes(); BeanWrapper bwBackBean = new BeanWrapperImpl(backBean); for (Iterator iterator = flowAttributes.keySet().iterator(); iterator.hasNext();) { String flowAttributeName = (String) iterator.next(); if (bwBackBean.isWritableProperty(flowAttributeName)) { bwBackBean.setPropertyValue(flowAttributeName, flowAttributes.get(flowAttributeName)); } } } }
AlanGuerraQuispe/SisAtuxPerfumeria
atux-jrcp/src/main/java/com/aw/swing/mvp/action/BackBeanProvider.java
Java
gpl-2.0
1,684
# -*- encoding : utf-8 -*- class User < ActiveRecord::Base include Invitable::Base include Humanizer include UserSearchable include EnrollmentService::BaseModelAdditions include EnrollmentService::UserAdditions::ModelAdditions include StatusService::BaseModelAdditions include StatusService::UserAdditions::ModelAdditions include DestroySoon::ModelAdditions # Valida a resposta ao captcha attr_writer :enable_humanizer require_human_on :create, if: :enable_humanizer require 'community_engine_sha1_crypto_method' require 'paperclip' # Constants MALE = 'M' FEMALE = 'F' MIN_LOGIN_LENGTH = 5 MAX_LOGIN_LENGTH = 20 # CALLBACKS before_create :make_activation_code after_create :update_last_login before_validation :strip_whitespace after_commit on: :create do environment = Environment.find_by_path('ava-redu') environment.courses.each { |c| c.join(self) } if environment UserNotifier.delay(queue: 'email', priority: 1).user_signedup(self.id) end # ASSOCIATIONS has_many :chat_messages has_many :chats, dependent: :destroy # Space has_many :spaces, through: :user_space_associations, conditions: ["spaces.destroy_soon = ?", false] has_many :user_space_associations, dependent: :destroy has_many :spaces_owned, class_name: "Space" , foreign_key: "user_id" # Environment has_many :user_environment_associations, dependent: :destroy has_many :environments, through: :user_environment_associations, conditions: ["environments.destroy_soon = ?", false] has_many :user_course_associations, dependent: :destroy has_many :course_enrollments, dependent: :destroy has_many :environments_owned, class_name: "Environment", foreign_key: "user_id" # Course has_many :courses, through: :user_course_associations, conditions: ["courses.destroy_soon = ? AND course_enrollments.state = ?", false, 'approved'] # Authentication has_many :authentications, dependent: :destroy has_many :chats, dependent: :destroy #COURSES has_many :lectures, foreign_key: "user_id", conditions: {is_clone: false} has_many :courses_owned, class_name: "Course", foreign_key: "user_id" classy_enum_attr :role, default: 'member' has_many :enrollments has_many :asset_reports, through: :enrollments #subject has_many :subjects, order: 'name ASC', conditions: { finalized: true } has_many :plans has_many :course_invitations, class_name: "UserCourseAssociation", conditions: ["state LIKE 'invited'"] has_many :experiences, dependent: :destroy has_many :educations, dependent: :destroy has_one :settings, class_name: "TourSetting", dependent: :destroy has_many :partners, through: :partner_user_associations has_many :partner_user_associations, dependent: :destroy has_many :social_networks, dependent: :destroy has_many :logs, as: :logeable, order: "created_at DESC", dependent: :destroy has_many :statuses, as: :statusable, order: "updated_at DESC" has_many :overview, through: :status_user_associations, source: :status, include: [:user, :answers], order: "updated_at DESC" has_many :status_user_associations has_many :client_applications has_many :tokens, class_name: "OauthToken", order: "authorized_at desc", include: [:client_application] has_many :results, dependent: :destroy has_many :choices, dependent: :delete_all # Named scopes scope :recent, order('users.created_at DESC') scope :active, where("users.activated_at IS NOT NULL") scope :with_ids, lambda { |ids| where(id: ids) } scope :without_ids, lambda {|ids| where("users.id NOT IN (?)", ids) } scope :with_keyword, lambda { |keyword| where("LOWER(login) LIKE :keyword OR " + \ "LOWER(first_name) LIKE :keyword OR " + \ "LOWER(last_name) LIKE :keyword OR " + \ "CONCAT(TRIM(LOWER(first_name)), ' ', TRIM(LOWER(last_name))) LIKE :keyword OR " + \ "LOWER(email) LIKE :keyword", { keyword: "%#{keyword.to_s.downcase}%" }). limit(10).select("users.id, users.first_name, users.last_name, users.login, users.email, users.avatar_file_name, users.avatar_updated_at") } scope :popular, lambda { |quantity| order('friends_count desc').limit(quantity) } scope :popular_teachers, lambda { |quantity| includes(:user_course_associations). where("course_enrollments.role" => Role[:teacher]).popular(quantity) } scope :with_email_domain_like, lambda { |email| where("email LIKE ?", "%#{email.to_s.split("@")[1]}%") } scope :contacts_and_pending_contacts_ids , select("users.id"). joins("LEFT OUTER JOIN `friendships`" \ " ON `friendships`.`friend_id` = `users`.`id`"). where("friendships.status = 'accepted'" \ " OR friendships.status = 'pending'" \ " OR friendships.status = 'requested'") scope :message_recipients, lambda { |recipients_ids| where("users.id IN (?)", recipients_ids) } attr_accessor :email_confirmation # Accessors attr_protected :admin, :role, :activation_code, :friends_count, :score, :removed accepts_nested_attributes_for :settings accepts_nested_attributes_for :social_networks, reject_if: proc { |attributes| attributes['url'].blank? or attributes['name'].blank? }, allow_destroy: true # PLUGINS acts_as_authentic do |c| c.crypto_provider = CommunityEngineSha1CryptoMethod c.validate_login_field = false c.validate_password_field = false c.validate_email_field = false end has_attached_file :avatar, Redu::Application.config.paperclip_user has_friends ajaxful_rater acts_as_taggable has_private_messages # VALIDATIONS validates_presence_of :first_name, :last_name validates :birthday, allow_nil: true, date: { before: Proc.new { 13.years.ago } } validates_acceptance_of :tos validates_format_of :mobile, with: /^\+\d{2}\s\(\d{2}\)\s\d{4}-\d{4}$/, allow_blank: true validates_format_of :first_name, with: /^\S(\S|\s)*\S$/ validates_format_of :last_name, with: /^\S(\S|\s)*\S$/ validates_length_of :first_name, maximum: 25 validates_length_of :last_name, maximum: 25 validates :password, length: { minimum: 6, maximum: 20 }, confirmation: true, if: :password_required? validates :login, exclusion: { in: Redu::Application.config.extras["reserved_logins"] }, format: { with: /^[A-Za-z0-9_-]*[A-Za-z]+[A-Za-z0-9_-]*$/ }, length: { minimum: MIN_LOGIN_LENGTH, maximum: MAX_LOGIN_LENGTH } validates_uniqueness_of :login, case_sensitive: false validates :email, format: { with: /^([^@\s]+)@((?:[-a-z0-9A-Z]+\.)+[a-zA-Z]{2,})$/ }, length: { minimum: 3, maximum: 100 }, confirmation: true validates_uniqueness_of :email, case_sensitive: false delegate :can?, :cannot?, to: :ability class << self # override activerecord's find to allow us to find by name or id transparently def find(*args) if args.is_a?(Array) and args.first.is_a?(String) and (args.first.index(/[a-zA-Z\-_]+/) or args.first.to_i.eql?(0) ) find_by_login(args) else super end end def find_by_login_or_email(login) User.find_by_login(login) || User.find_by_email(login) end def encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end end def process_invitation!(invitee, invitation) self.be_friends_with(invitee) invitation.delete end def profile_complete? (self.first_name and self.last_name and self.gender and self.description and self.tags) ? true : false end def can_manage?(entity) entity.nil? and return false self.admin? and return true self.environment_admin? entity and return true case entity.class.to_s when 'Course' (self.environment_admin? entity.environment) when 'Space' self.teacher?(entity) || self.can_manage?(entity.course) || self.teacher?(entity.course) when 'Subject' self.teacher?(entity.space) || self.can_manage?(entity.space) when 'Lecture' teacher?(entity.subject.space) || can_manage?(entity.subject) when 'Exam' self.teacher?(entity.subject.space) || self.can_manage?(entity.space) when 'Folder' self.teacher?(entity.space) || self.tutor?(entity.space) || self.can_manage?(entity.space) when 'Topic' self.member?(entity.space) when 'SbPost' self.member?(entity.space) when 'Status', 'Activity', 'Answer', 'Help' if self == entity.user true else case entity.statusable.class.to_s when 'Space' self.teacher?(entity.statusable) || self.can_manage?(entity.statusable) when 'Subject' self.teacher?(entity.statusable.space) || self.can_manage?(entity.statusable.space) when 'Lecture' self.can_manage?(entity.statusable.subject) when 'Answer', 'Activity', 'Help' self.can_manage?(entity.statusable) end end when 'User' entity == self when 'Plan', 'PackagePlan', 'LicensedPlan' entity.user == self || self.can_manage?(entity.billable) || # Caso em que billable foi destruído self.can_manage?( # Não levanta RecordNotFound Partner.where( id: entity.billable_audit. try(:[], :partner_environment_association). try(:[],"partner_id")).first ) when 'Invoice', 'LicensedInvoice', 'PackageInvoice' self.can_manage?(entity.plan) when 'Myfile' self.can_manage?(entity.folder) when 'Friendship' # user_id necessário devido ao bug do create_time_zone self.id == entity.user_id when 'PartnerEnvironmentAssociation' entity.partner.users.exists?(self.id) when 'Partner' entity.users.exists?(self.id) when 'Experience' self.can_manage?(entity.user) when 'SocialNetwork' self.can_manage?(entity.user) when 'Education' self.can_manage?(entity.user) when 'Result' self.can_manage?(entity.exercise) when 'Exercise' self.can_manage?(entity.lecture) && !entity.has_results? when 'Invitation' self.can_manage?(entity.hostable) end end def has_access_to?(entity) self.admin? and return true if self.get_association_with(entity) # Apenas Course tem state if entity.class.to_s == 'Course' && !self.get_association_with(entity).approved? return false else return true end else case entity when Folder self.get_association_with(entity.space).nil? ? false : true when Status if entity.statusable.is_a? User self.friends?(entity.statusable) || self == entity.statusable else self.has_access_to? entity.statusable end when Help has_access_to?(entity.statusable) when Lecture self.has_access_to? entity.subject when PartnerEnvironmentAssociation self.has_access_to? entity.partner when Partner entity.users.exists?(self) when Result entity.user == self when Question has_access_to? entity.exercise.lecture else return false end end end def enrolled?(subject) self.get_association_with(subject).nil? ? false : true end # Método de alto nível, verifica se o object está publicado (caso se aplique) # e se o usuário possui acesso (i.e. relacionamento) com o mesmo def can_read?(object) if (object.is_a? Folder) || (object.is_a? Status) || (object.is_a? Help) || (object.is_a? User) || (object.is_a? Friendship) || (object.is_a? Plan) || (object.is_a? PackagePlan) || (object.is_a? Invoice) || (object.is_a? PartnerEnvironmentAssociation) || (object.is_a? Partner) || (object.is_a? Result) || (object.is_a? Question) || (object.is_a? Lecture) self.has_access_to?(object) else if (object.is_a? Subject) object.visible? && self.has_access_to?(object) else object.published? && self.has_access_to?(object) end end end def to_param login end def deactivate return if admin? #don't allow admin deactivation @activated = false update_attributes(activated_at: nil, activation_code: make_activation_code) end def activate @activated = true update_attributes(activated_at: Time.now.utc, activation_code: nil) end # Indica se o usuário ainda pode utilizar o Redu sem ter ativado a conta def can_activate? activated_at.nil? and created_at > 30.days.ago end def active? #FIXME Workaround para quando o active? é chamado e o usuário não exite # (authlogic) return false unless created_at ( activated_at.nil? and (created_at < (Time.now - 30.days))) ? false : true end def encrypt(password) self.class.encrypt(password, self.password_salt) end def authenticated?(password) crypted_password == encrypt(password) end def reset_password new_password = newpass(8) self.password = new_password self.password_confirmation = new_password return self.valid? end def owner self end def update_last_login self.save #FIXME necessário para que o last_login_at seja atualizado, #419 self.update_attribute(:last_login_at, Time.now) end def display_name if self.removed? return '(usuário removido)' end if self.first_name and self.last_name self.first_name + " " + self.last_name else login end end # Cria associação do agrupamento de amizade do usuário para seus amigos # e para o pŕoprio usuário (home_activity) def notify(compound_log) self.status_user_associations.create(status: compound_log) Status.associate_with(compound_log, self.friends.select('users.id')) end # Pega associação com Entity (aplica-se a Environment, Course, Space e Subject) def get_association_with(entity) return false unless entity case entity.class.to_s when 'Space' self.user_space_associations. find(:first, conditions: { space_id: entity.id }) when 'Course' self.user_course_associations. find(:first, conditions: { course_id: entity.id }) when 'Environment' self.user_environment_associations. find(:first, conditions: { environment_id: entity.id }) when 'Subject' self.enrollments. find(:first, conditions: { subject_id: entity.id }) when 'Lecture' self.enrollments. find(:first, conditions: { subject_id: entity.subject.id }) when 'Activity', 'Help', 'Status', 'Log' self.status_user_associations. find(:first, conditions: { status_id: entity.id }) end end def environment_admin?(entity) return false if entity.is_a? Status association = get_association_with entity association && association.role && association.role.environment_admin? end def admin? @is_admin ||= role.admin? end def teacher?(entity) association = get_association_with entity return false if association.nil? association && association.role && association.role.teacher? end def tutor?(entity) association = get_association_with entity return false if association.nil? association && association.role && association.role.tutor? end def member?(entity) association = get_association_with entity return false if association.nil? association && association.role && association.role.member? end def male? gender && gender.eql?(MALE) end def female? gender && gender.eql?(FEMALE) end def home_activity(page = 1) associateds = [:status_resources, { answers: [:user, :status_resources] }, :user, :logeable, :statusable] overview.where(compound: false).includes(associateds). page(page).per(Redu::Application.config.items_per_page) end def profile_for(subject) self.enrollments.where(subject_id: subject) end def completeness total = 16.0 undone = 0.0 undone += 1 if self.description.to_s.empty? undone += 1 if self.avatar_file_name.nil? undone += 1 if self.gender.nil? undone += 1 if self.localization.to_s.empty? undone += 1 if self.birth_localization.to_s.empty? undone += 1 if self.languages.to_s.empty? undone += 1 if self.tags.empty? undone += 1 if self.mobile.to_s.empty? undone += 1 if self.social_networks.empty? undone += 1 if self.experiences.empty? undone += 1 if self.educations.empty? done = total - undone (done/total*100).round end def email_confirmation @email_confirmation || self.email end def create_settings! self.settings = TourSetting.create(view_mural: Privacy[:friends]) end def presence_channel "presence-user-#{self.id}" end def private_channel_with(user) if self.id < user.id "private-#{self.id}-#{user.id}" else "private-#{user.id}-#{self.id}" end end #FIXME falta testar alguns casos def age dob = self.birthday now = Time.now.utc.to_date now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1) end # Retrieves five contacts recommendations def recommended_contacts(quantity) if self.friends_count == 0 contacts_and_pending_ids = User.contacts_and_pending_contacts_ids. where("friendships.user_id = ?", self.id) # Populares da rede exceto o próprio usuário e os usuários que ele, # requisitou/foi requisitada a amizade. users = User.select('users.id, users.login, users.avatar_file_name,' \ ' users.first_name, users.last_name, users.avatar_updated_at'). without_ids(contacts_and_pending_ids << self). popular(20) | # Professores populares da rede exceto o próprio usuário e os usuários, # que ele requisitou/foi requisitada a amizade. User.select('users.id, users.login, users.avatar_file_name,'\ ' users.first_name, users.last_name, users.avatar_updated_at'). without_ids(contacts_and_pending_ids << self). popular_teachers(20) | # Usuários com o mesmo domínio de email exceto o próprio usuário e os, # usuários que ele requisitou/foi requisitada a amizade. User.select('users.id, users.login, users.avatar_file_name,' \ ' users.first_name, users.last_name, users.avatar_updated_at'). without_ids(contacts_and_pending_ids << self). with_email_domain_like(self.email).limit(20) else # Colegas de curso e amigos de amigos users = colleagues(20) | self.friends_of_friends end # Choosing randomly if quantity >= (users.length - 1) quantity = (users.length - 1) end (1..quantity).collect do users.delete_at(SecureRandom.random_number(users.length - 1)) end end # Participam do mesmo curso, mas não são contatos nem possuem requisição # de contato pendente. def colleagues(quantity) contacts_ids = User.contacts_and_pending_contacts_ids. where("friendships.user_id = ?", self.id) User.select("DISTINCT users.id, users.login, users.avatar_file_name," \ " users.first_name, users.last_name, users.avatar_updated_at"). joins("LEFT OUTER JOIN course_enrollments ON" \ " course_enrollments.user_id = users.id AND" \ " course_enrollments.type = 'UserCourseAssociation'"). where("course_enrollments.state = 'approved' AND" \ " course_enrollments.user_id NOT IN (?, ?)", contacts_ids, self.id). limit(quantity) end def friends_of_friends contacts_ids = self.friends.select("users.id") contacts_and_pending_ids = User.contacts_and_pending_contacts_ids. where("friendships.user_id = ?", self.id) User.select("DISTINCT users.id, users.login, users.avatar_file_name," \ " users.first_name, users.last_name, users.avatar_updated_at"). joins("LEFT OUTER JOIN `friendships`" \ " ON `friendships`.`friend_id` = `users`.`id`"). where("friendships.status = 'accepted' AND friendships.user_id IN (?)" \ " AND friendships.friend_id NOT IN (?, ?)", contacts_ids, contacts_and_pending_ids, self.id) end def most_important_education educations = [] edu = self.educations educations << edu.select { |e| e.educationable_type == 'HigherEducation' }.first educations << edu.select { |e| e.educationable_type == 'ComplementaryCourse' }.first educations << edu.select { |e| e.educationable_type == 'HighSchool' }.first educations.compact! educations end def subjects_id self.lectures.collect{ |lecture| lecture.subject_id } end def has_no_visible_profile_information self.experiences.actual_jobs.empty? && self.educations.empty? && self.birthday.nil? && self.languages.blank? && self.birth_localization.blank? && self.localization.blank? end protected # Retorna true ou false baseado se o humanizer está ou não habilitado. # Por padrão do ambiente de desenvolvimento, ele é desabilitado. E em produção # habilitado. # # É possível desabilitar para uma determinada instância da seguinte forma: # user = User.new # user.enable_humanizer = false # # Esta configuração é restrita a uma única instância e independente de ambiente. def enable_humanizer return @enable_humanizer if defined? @enable_humanizer Rails.env.production? end def activate_before_save self.activated_at = Time.now.utc self.activation_code = nil end def make_activation_code self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end # before filters def encrypt_password return if password.blank? self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? self.crypted_password = encrypt(password) end def password_required? crypted_password.blank? || !password.blank? end def newpass( len ) chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a new_password = "" 1.upto(len) { |i| new_password << chars[rand(chars.size-1)] } return new_password end #Metodo que remove os espaços em branco no incio e no fim desses campos def strip_whitespace %w(login first_name last_name email).each do |var| self.send("#{var}=", (self.send(var).strip if attribute_present? var)) end end end
tuliolages/OpenRedu
app/models/user.rb
Ruby
gpl-2.0
22,732
/* This file is part of the KDE project Copyright 2007 Stefan Nikolaus <stefan.nikolaus@kdemail.net> Copyright (C) 2008 Thomas Zander <zander@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Binding.h" #include "BindingModel.h" #include <QRect> #include <kdebug.h> #include "CellStorage.h" #include "Map.h" #include "Sheet.h" #include "Value.h" using namespace Calligra::Sheets; class Q_DECL_HIDDEN Binding::Private : public QSharedData { public: BindingModel* model; Private(Binding *q) : model(new BindingModel(q)) {} ~Private() { delete model; } }; Binding::Binding() : d(new Private(this)) { } Binding::Binding(const Region& region) : d(new Private(this)) { Q_ASSERT(region.isValid()); d->model->setRegion(region); } Binding::Binding(const Binding& other) : d(other.d) { } Binding::~Binding() { } bool Binding::isEmpty() const { return d->model->region().isEmpty(); } QAbstractItemModel* Binding::model() const { return d->model; } const Calligra::Sheets::Region& Binding::region() const { return d->model->region(); } void Binding::setRegion(const Region& region) { d->model->setRegion(region); } void Binding::update(const Region& region) { QRect rect; Region changedRegion; const QPoint offset = d->model->region().firstRange().topLeft(); const QRect range = d->model->region().firstRange(); const Sheet* sheet = d->model->region().firstSheet(); Region::ConstIterator end(region.constEnd()); for (Region::ConstIterator it = region.constBegin(); it != end; ++it) { if (sheet != (*it)->sheet()) continue; rect = range & (*it)->rect(); rect.translate(-offset.x(), -offset.y()); if (rect.isValid()) { d->model->emitDataChanged(rect); changedRegion.add(rect, (*it)->sheet()); } } d->model->emitChanged(changedRegion); } void Binding::operator=(const Binding & other) { d = other.d; } bool Binding::operator==(const Binding& other) const { return d == other.d; } bool Binding::operator<(const Binding& other) const { return d < other.d; } QHash<QString, QVector<QRect> > BindingModel::cellRegion() const { QHash<QString, QVector<QRect> > answer; Region::ConstIterator end = m_region.constEnd(); for (Region::ConstIterator it = m_region.constBegin(); it != end; ++it) { if (!(*it)->isValid()) { continue; } answer[(*it)->name()].append((*it)->rect()); } return answer; } bool BindingModel::setCellRegion(const QString& regionName) { Q_ASSERT(m_region.isValid()); Q_ASSERT(m_region.firstSheet()); const Map* const map = m_region.firstSheet()->map(); const Region region = Region(regionName, map); if (!region.isValid()) { kDebug() << qPrintable(regionName) << "is not a valid region."; return false; } // Clear the old binding. Region::ConstIterator end = m_region.constEnd(); for (Region::ConstIterator it = m_region.constBegin(); it != end; ++it) { if (!(*it)->isValid()) { continue; } // FIXME Stefan: This may also clear other bindings! (*it)->sheet()->cellStorage()->setBinding(Region((*it)->rect(), (*it)->sheet()), Binding()); } // Set the new region m_region = region; end = m_region.constEnd(); for (Region::ConstIterator it = m_region.constBegin(); it != end; ++it) { if (!(*it)->isValid()) { continue; } (*it)->sheet()->cellStorage()->setBinding(Region((*it)->rect(), (*it)->sheet()), *m_binding); } return true; } /////// BindingModel BindingModel::BindingModel(Binding* binding, QObject *parent) : QAbstractTableModel(parent) , m_binding(binding) { } bool BindingModel::isCellRegionValid(const QString& regionName) const { Q_CHECK_PTR(m_region.firstSheet()); Q_CHECK_PTR(m_region.firstSheet()->map()); return Region(regionName, m_region.firstSheet()->map()).isValid(); } void BindingModel::emitChanged(const Region& region) { emit changed(region); } void BindingModel::emitDataChanged(const QRect& rect) { const QPoint tl = rect.topLeft(); const QPoint br = rect.bottomRight(); //kDebug(36005) << "emit QAbstractItemModel::dataChanged" << QString("%1:%2").arg(tl).arg(br); emit dataChanged(index(tl.y(), tl.x()), index(br.y(), br.x())); } QVariant BindingModel::data(const QModelIndex& index, int role) const { if ((m_region.isEmpty()) || (role != Qt::EditRole && role != Qt::DisplayRole)) return QVariant(); const QPoint offset = m_region.firstRange().topLeft(); const Sheet* sheet = m_region.firstSheet(); int row = offset.y() + index.row(); int column = offset.x() + index.column(); Value value = sheet->cellStorage()->value(column, row); switch (role) { case Qt::DisplayRole: { // return the in the cell displayed test Cell c(sheet, column, row); bool showFormula = false; return c.displayText(Style(), &value, &showFormula); } case Qt::EditRole: { // return the actual cell value // KoChart::Value is either: // - a double (interpreted as a value) // - a QString (interpreted as a label) // - a QDateTime (interpreted as a date/time value) // - Invalid (interpreted as empty) QVariant variant; switch (value.type()) { case Value::Float: case Value::Integer: if (value.format() == Value::fmt_DateTime || value.format() == Value::fmt_Date || value.format() == Value::fmt_Time) { variant.setValue<QDateTime>(value.asDateTime(sheet->map()->calculationSettings())); break; } // fall through case Value::Boolean: case Value::Complex: case Value::Array: variant.setValue<double>(numToDouble(value.asFloat())); break; case Value::String: case Value::Error: variant.setValue<QString>(value.asString()); break; case Value::Empty: case Value::CellRange: default: break; } return variant; } } //kDebug() << index.column() <<"," << index.row() <<"," << variant; return QVariant(); } const Calligra::Sheets::Region& BindingModel::region() const { return m_region; } QVariant BindingModel::headerData(int section, Qt::Orientation orientation, int role) const { if ((m_region.isEmpty()) || (role != Qt::EditRole && role != Qt::DisplayRole)) return QVariant(); const QPoint offset = m_region.firstRange().topLeft(); const int col = (orientation == Qt::Vertical) ? offset.x() : offset.x() + section; const int row = (orientation == Qt::Vertical) ? offset.y() + section : offset.y(); const Sheet* sheet = m_region.firstSheet(); const Value value = sheet->cellStorage()->value(col, row); return value.asVariant(); } int BindingModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return m_region.isEmpty() ? 0 : m_region.firstRange().height(); } int BindingModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return m_region.isEmpty() ? 0 : m_region.firstRange().width(); } void BindingModel::setRegion(const Region& region) { m_region = region; }
TheTypoMaster/calligra
sheets/Binding.cpp
C++
gpl-2.0
8,416
from kvmap.code.projections import * from urllib2 import urlopen from httplib import HTTPConnection from threading import Thread from kivy.logger import Logger from kivy.loader import Loader from os.path import join, dirname import time, os import hashlib try: from pyproj import Proj from xml.etree import ElementTree as ET except: pass class WMSOverlayServer(object): cache = {} available_maptype = dict(roadmap='Roadmap') # default type = "wms" '''Generic WMS server''' def __init__(self, progress_callback=None): self.progress_callback = progress_callback def setProgressCallback(self, progress_callback): self.progress_callback = progress_callback def getInfo(self, lat, lon, epsilon): return None def get(self, parent, width, height): self.bl = parent.bottom_left self.tr = parent.top_right self.zoom = parent.zoom url = self.geturl(self.bl[0], self.bl[1], self.tr[0], self.tr[1], self.zoom, width, height) if not url: return None key = hashlib.md5(url).hexdigest() if key in self.cache: return self.cache[key] try: image = Loader.image('http://' + self.provider_host + url, progress_callback=self.progress_callback) self.cache[key] = image except Exception, e: Logger.error('OverlayServer could not find (or read) image %s [%s]' % (url, e)) image = None def getLegendGraphic(self): if self.legend is None and not self.triedlegend: self.triedlegend = True layer = self.layer if "," in layer: layer = layer[layer.rindex(",") + 1:] if self.legendlayer: layer = self.legendlayer url = self.baseurl + "?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&LAYER=%s&ext=.png" % (layer) try: print 'http://' + self.provider_host + url image = Loader.image('http://' + self.provider_host + url) self.legend = image except Exception, e: Logger.error('OverlayServer could not find LEGENDGRAPHICS for %s %s' % (self.baseurl, layer)) return self.legend def xy_to_co(self, lat, lon): if self.customBounds: x, y = latlon_to_custom(lat, lon, self.bounds) elif self.isPLatLon: # patch for android - does not require pyproj library x, y = lon, lat elif self.isPGoogle: # patch for android - does not require pyproj library x, y = latlon_to_google (lat, lon) else: x, y = transform(pLatlon, self.projection, lon, lat) return x, y def co_to_ll(self, x, y): if self.customBounds: u, v = custom_to_unit(lat, lon, self.bounds) l, m = unit_to_latlon(u, v) elif self.isPLatLon: # patch for android - does not require pyproj library l, m = y, x elif self.isPGoogle: # patch for android - does not require pyproj library l, m = google_to_latlon (y, x) else: l, m = transform(self.projection, pLatlon, y, x) return l, m def geturl(self, lat1, lon1, lat2, lon2, zoom, w, h): try: x1, y1 = self.xy_to_co(lat1, lon1) x2, y2 = self.xy_to_co(lat2, lon2) return self.url + "&BBOX=%f,%f,%f,%f&WIDTH=%i&HEIGHT=%i&ext=.png" % (x1, y1, x2, y2, w, h) except RuntimeError, e: return None def parseLayer(self, layer, data): try: name = layer.find("Name").text except: name = None srss = layer.findall("SRS") if name: # and srss: data[name] = map(lambda x:x.text, srss) if self.debug: print "Provider %s provides layer %s in projections %s" % (self.provider_host, name, data[name]) subs = layer.findall("Layer") for sub in subs: self.parseLayer(sub, data) def initFromGetCapabilities(self, host, baseurl, layer=None, index=0, srs=None): self.debug = (layer == None) and (index == 0) # GetCapabilities (Layers + SRS) if layer is None or srs is None: capabilities = urlopen(host + baseurl + "?SERVICE=WMS&VERSION=1.1.1&Request=GetCapabilities").read().strip() try: tree = ET.fromstring(capabilities) if self.debug: ET.dump(tree) layers = tree.findall("Capability/Layer") # TODO: proper parsing of cascading layers and their SRS data = {} for l in layers: self.parseLayer(l, data) # Choose Layer and SRS by (alphabetical) index if layer is None: layer = sorted(data.keys())[index] if srs is None: srs = sorted(data[layer])[0] except: pass print "Displaying from %s/%s: layer %s in SRS %s." % (host, baseurl, layer, srs) # generate tile URL and init projection by EPSG code self.layer = layer self.baseurl = baseurl self.url = baseurl + "?LAYERS=%s&SRS=%s&FORMAT=image/png&TRANSPARENT=TRUE&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=" % (layer, srs) self.isPGoogle = False self.isPLatLon = False self.legend = None self.legendlayer = None self.triedlegend = False if srs == "EPSG:4326": self.isPLatLon = True elif srs == "EPSG:900913" or srs == "EPSG:3857": self.isPGoogle = True try: self.projection = pGoogle except: pass else: try: self.projection = Proj(init=srs) except: pass
jchome/LocalGuide-Mobile
kvmap/overlays/WMSOverlayServer.py
Python
gpl-2.0
5,614
#include "../vidhrdw/cbuster.cpp" /*************************************************************************** Crude Buster (World version FX) (c) 1990 Data East Corporation Crude Buster (World version FU) (c) 1990 Data East Corporation Crude Buster (Japanese version) (c) 1990 Data East Corporation Two Crude (USA version) (c) 1990 Data East USA The 'FX' board is filled with 'FU' roms except for the 4 program roms, both boards have 'export' stickers which usually indicates a World version. Maybe one is a UK or European version. Emulation by Bryan McPhail, mish@tendril.co.uk ***************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "cpu/h6280/h6280.h" int twocrude_vh_start(void); void twocrude_vh_stop(void); void twocrude_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); WRITE_HANDLER( twocrude_pf1_data_w ); WRITE_HANDLER( twocrude_pf2_data_w ); WRITE_HANDLER( twocrude_pf3_data_w ); WRITE_HANDLER( twocrude_pf4_data_w ); WRITE_HANDLER( twocrude_control_0_w ); WRITE_HANDLER( twocrude_control_1_w ); WRITE_HANDLER( twocrude_palette_24bit_rg_w ); WRITE_HANDLER( twocrude_palette_24bit_b_w ); READ_HANDLER( twocrude_palette_24bit_rg_r ); READ_HANDLER( twocrude_palette_24bit_b_r ); WRITE_HANDLER( twocrude_pf1_rowscroll_w ); WRITE_HANDLER( twocrude_pf2_rowscroll_w ); WRITE_HANDLER( twocrude_pf3_rowscroll_w ); WRITE_HANDLER( twocrude_pf4_rowscroll_w ); extern unsigned char *twocrude_pf1_rowscroll,*twocrude_pf2_rowscroll; extern unsigned char *twocrude_pf3_rowscroll,*twocrude_pf4_rowscroll; extern unsigned char *twocrude_pf1_data, *twocrude_pf2_data, *twocrude_pf3_data, *twocrude_pf4_data; static unsigned char *twocrude_ram; extern void twocrude_pri_w(int pri); WRITE_HANDLER( twocrude_update_sprites_w ); static int prot; /******************************************************************************/ static WRITE_HANDLER( twocrude_control_w ) { switch (offset) { case 0: /* DMA flag */ twocrude_update_sprites_w(0,0); return; case 6: /* IRQ ack */ return; case 2: /* Sound CPU write */ soundlatch_w(0,data & 0xff); cpu_cause_interrupt(1,H6280_INT_IRQ1); return; case 4: /* Protection, maybe this is a PAL on the board? 80046 is level number stop at stage and enter. see also 8216.. 9a 00 = pf4 over pf3 (normal) (level 0) 9a f1 = (level 1 - water), pf3 over ALL sprites + pf4 9a 80 = pf3 over pf4 (Level 2 - copter) 9a 40 = pf3 over ALL sprites + pf4 (snow) level 3 9a c0 = doesn't matter? 9a ff = pf 3 over pf4 I can't find a priority register, I assume it's tied to the protection?! */ if ((data&0xffff)==0x9a00) prot=0; if ((data&0xffff)==0xaa) prot=0x74; if ((data&0xffff)==0x0200) prot=0x63<<8; if ((data&0xffff)==0x9a) prot=0xe; if ((data&0xffff)==0x55) prot=0x1e; if ((data&0xffff)==0x0e) {prot=0x0e;twocrude_pri_w(0);} /* start */ if ((data&0xffff)==0x00) {prot=0x0e;twocrude_pri_w(0);} /* level 0 */ if ((data&0xffff)==0xf1) {prot=0x36;twocrude_pri_w(1);} /* level 1 */ if ((data&0xffff)==0x80) {prot=0x2e;twocrude_pri_w(1);} /* level 2 */ if ((data&0xffff)==0x40) {prot=0x1e;twocrude_pri_w(1);} /* level 3 */ if ((data&0xffff)==0xc0) {prot=0x3e;twocrude_pri_w(0);} /* level 4 */ if ((data&0xffff)==0xff) {prot=0x76;twocrude_pri_w(1);} /* level 5 */ break; } //logerror("Warning %04x- %02x written to control %02x\n",cpu_get_pc(),data,offset); } READ_HANDLER( twocrude_control_r ) { switch (offset) { case 0: /* Player 1 & Player 2 joysticks & fire buttons */ return (readinputport(0) + (readinputport(1) << 8)); case 2: /* Dip Switches */ return (readinputport(3) + (readinputport(4) << 8)); case 4: /* Protection */ //logerror("%04x : protection control read at 30c000 %d\n",cpu_get_pc(),offset); return prot; case 6: /* Credits, VBL in byte 7 */ return readinputport(2); } return 0xffff; } static READ_HANDLER( twocrude_pf1_data_r ) { return READ_WORD(&twocrude_pf1_data[offset]);} static READ_HANDLER( twocrude_pf2_data_r ) { return READ_WORD(&twocrude_pf2_data[offset]);} static READ_HANDLER( twocrude_pf3_data_r ) { return READ_WORD(&twocrude_pf3_data[offset]);} static READ_HANDLER( twocrude_pf4_data_r ) { return READ_WORD(&twocrude_pf4_data[offset]);} static READ_HANDLER( twocrude_pf1_rowscroll_r ) { return READ_WORD(&twocrude_pf1_rowscroll[offset]);} static READ_HANDLER( twocrude_pf2_rowscroll_r ) { return READ_WORD(&twocrude_pf2_rowscroll[offset]);} static READ_HANDLER( twocrude_pf3_rowscroll_r ) { return READ_WORD(&twocrude_pf3_rowscroll[offset]);} static READ_HANDLER( twocrude_pf4_rowscroll_r ) { return READ_WORD(&twocrude_pf4_rowscroll[offset]);} /******************************************************************************/ static struct MemoryReadAddress twocrude_readmem[] = { { 0x000000, 0x07ffff, MRA_ROM }, { 0x080000, 0x083fff, MRA_BANK1 }, { 0x0a0000, 0x0a1fff, twocrude_pf1_data_r }, { 0x0a2000, 0x0a2fff, twocrude_pf4_data_r }, { 0x0a4000, 0x0a47ff, twocrude_pf1_rowscroll_r }, { 0x0a6000, 0x0a67ff, twocrude_pf4_rowscroll_r }, { 0x0a8000, 0x0a8fff, twocrude_pf3_data_r }, { 0x0aa000, 0x0aafff, twocrude_pf2_data_r }, { 0x0ac000, 0x0ac7ff, twocrude_pf3_rowscroll_r }, { 0x0ae000, 0x0ae7ff, twocrude_pf2_rowscroll_r }, { 0x0b0000, 0x0b07ff, MRA_BANK2 }, { 0x0b8000, 0x0b8fff, twocrude_palette_24bit_rg_r }, { 0x0b9000, 0x0b9fff, twocrude_palette_24bit_b_r }, { 0x0bc000, 0x0bc00f, twocrude_control_r }, { -1 } /* end of table */ }; static struct MemoryWriteAddress twocrude_writemem[] = { { 0x000000, 0x07ffff, MWA_ROM }, { 0x080000, 0x083fff, MWA_BANK1, &twocrude_ram }, { 0x0a0000, 0x0a1fff, twocrude_pf1_data_w, &twocrude_pf1_data }, { 0x0a2000, 0x0a2fff, twocrude_pf4_data_w, &twocrude_pf4_data }, { 0x0a4000, 0x0a47ff, twocrude_pf1_rowscroll_w, &twocrude_pf1_rowscroll }, { 0x0a6000, 0x0a67ff, twocrude_pf4_rowscroll_w, &twocrude_pf4_rowscroll }, { 0x0a8000, 0x0a8fff, twocrude_pf3_data_w, &twocrude_pf3_data }, { 0x0aa000, 0x0aafff, twocrude_pf2_data_w, &twocrude_pf2_data }, { 0x0ac000, 0x0ac7ff, twocrude_pf3_rowscroll_w, &twocrude_pf3_rowscroll }, { 0x0ae000, 0x0ae7ff, twocrude_pf2_rowscroll_w, &twocrude_pf2_rowscroll }, { 0x0b0000, 0x0b07ff, MWA_BANK2, &spriteram }, { 0x0b4000, 0x0b4001, MWA_NOP }, { 0x0b5000, 0x0b500f, twocrude_control_1_w }, { 0x0b6000, 0x0b600f, twocrude_control_0_w }, { 0x0b8000, 0x0b8fff, twocrude_palette_24bit_rg_w, &paletteram }, { 0x0b9000, 0x0b9fff, twocrude_palette_24bit_b_w, &paletteram_2 }, { 0x0bc000, 0x0bc00f, twocrude_control_w }, { -1 } /* end of table */ }; /******************************************************************************/ static WRITE_HANDLER( YM2151_w ) { switch (offset) { case 0: YM2151_register_port_0_w(0,data); break; case 1: YM2151_data_port_0_w(0,data); break; } } static WRITE_HANDLER( YM2203_w ) { switch (offset) { case 0: YM2203_control_port_0_w(0,data); break; case 1: YM2203_write_port_0_w(0,data); break; } } static struct MemoryReadAddress sound_readmem[] = { { 0x000000, 0x00ffff, MRA_ROM }, { 0x100000, 0x100001, YM2203_status_port_0_r }, { 0x110000, 0x110001, YM2151_status_port_0_r }, { 0x120000, 0x120001, OKIM6295_status_0_r }, { 0x130000, 0x130001, OKIM6295_status_1_r }, { 0x140000, 0x140001, soundlatch_r }, { 0x1f0000, 0x1f1fff, MRA_BANK8 }, { -1 } /* end of table */ }; static struct MemoryWriteAddress sound_writemem[] = { { 0x000000, 0x00ffff, MWA_ROM }, { 0x100000, 0x100001, YM2203_w }, { 0x110000, 0x110001, YM2151_w }, { 0x120000, 0x120001, OKIM6295_data_0_w }, { 0x130000, 0x130001, OKIM6295_data_1_w }, { 0x1f0000, 0x1f1fff, MWA_BANK8 }, { 0x1fec00, 0x1fec01, H6280_timer_w }, { 0x1ff402, 0x1ff403, H6280_irq_status_w }, { -1 } /* end of table */ }; /******************************************************************************/ INPUT_PORTS_START( twocrude ) PORT_START /* Player 1 controls */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_START /* Player 2 controls */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 ) PORT_START /* Credits */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_VBLANK ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START /* Dip switch bank 1 */ PORT_DIPNAME( 0x07, 0x07, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x00, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x03, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x38, 0x38, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x00, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x38, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x30, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x28, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x20, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x18, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Flip_Screen ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START /* Dip switch bank 2 */ PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "1" ) PORT_DIPSETTING( 0x01, "2" ) PORT_DIPSETTING( 0x03, "3" ) PORT_DIPSETTING( 0x02, "4" ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x0c, "Normal" ) PORT_DIPSETTING( 0x08, "Easy" ) PORT_DIPSETTING( 0x04, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "Allow Continue" ) PORT_DIPSETTING( 0x00, DEF_STR( No ) ) PORT_DIPSETTING( 0x40, DEF_STR( Yes ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END /******************************************************************************/ static struct GfxLayout charlayout = { 8,8, 4096, 4, { 0x10000*8+8, 8, 0x10000*8, 0 }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, }, 16*8 }; static struct GfxLayout tilelayout = { 16,16, 4096, 4, { 24, 16, 8, 0 }, { 64*8+0, 64*8+1, 64*8+2, 64*8+3, 64*8+4, 64*8+5, 64*8+6, 64*8+7, 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32 }, 128*8 }; static struct GfxLayout spritelayout = { 16,16, (4096*2)+2048, /* Main bank + 4 extra roms */ 4, { 0xa0000*8+8, 0xa0000*8, 8, 0 }, { 32*8+0, 32*8+1, 32*8+2, 32*8+3, 32*8+4, 32*8+5, 32*8+6, 32*8+7, 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16 }, 64*8 }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { REGION_GFX1, 0, &charlayout, 0, 16 }, /* Characters 8x8 */ { REGION_GFX2, 0, &tilelayout, 1024, 16 }, /* Tiles 16x16 */ { REGION_GFX2, 0, &tilelayout, 768, 16 }, /* Tiles 16x16 */ { REGION_GFX3, 0, &tilelayout, 512, 16 }, /* Tiles 16x16 */ { REGION_GFX4, 0, &spritelayout, 256, 80 }, /* Sprites 16x16 */ { -1 } /* end of array */ }; /******************************************************************************/ static struct OKIM6295interface okim6295_interface = { 2, /* 2 chips */ { 7757, 15514 },/* Frequency */ { REGION_SOUND1, REGION_SOUND2 }, /* memory regions 3 & 4 */ { 50, 25 } /* Note! Keep chip 1 (voices) louder than chip 2 */ }; static struct YM2203interface ym2203_interface = { 1, 32220000/8, /* Accurate, audio section crystal is 32.220 MHz */ { YM2203_VOL(40,40) }, { 0 }, { 0 }, { 0 }, { 0 } }; static void sound_irq(int state) { cpu_set_irq_line(1,1,state); /* IRQ 2 */ } static struct YM2151interface ym2151_interface = { 1, 32220000/9, /* Accurate, audio section crystal is 32.220 MHz */ { YM3012_VOL(45,MIXER_PAN_LEFT,45,MIXER_PAN_RIGHT) }, { sound_irq } }; static struct MachineDriver machine_driver_twocrude = { /* basic machine hardware */ { { CPU_M68000, 12000000, /* Accurate */ twocrude_readmem,twocrude_writemem,0,0, m68_level4_irq,1 /* VBL */ }, { CPU_H6280 | CPU_AUDIO_CPU, 32220000/8, /* Accurate */ sound_readmem,sound_writemem,0,0, ignore_interrupt,0 } }, 58, 529, /* frames per second, vblank duration */ 1, /* 1 CPU slice per frame - interleaving is forced when a sound command is written */ 0, /* video hardware */ 32*8, 32*8, { 0*8, 32*8-1, 1*8, 31*8-1 }, gfxdecodeinfo, 2048, 2048, 0, VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE | VIDEO_UPDATE_BEFORE_VBLANK, 0, twocrude_vh_start, twocrude_vh_stop, twocrude_vh_screenrefresh, /* sound hardware */ 0,0,0,0, { { SOUND_YM2203, &ym2203_interface }, { SOUND_YM2151, &ym2151_interface }, { SOUND_OKIM6295, &okim6295_interface } } }; /******************************************************************************/ ROM_START( cbuster ) ROM_REGION( 0x80000, REGION_CPU1 ) /* 68000 code */ ROM_LOAD_EVEN( "fx01.rom", 0x00000, 0x20000, 0xddae6d83 ) ROM_LOAD_ODD ( "fx00.rom", 0x00000, 0x20000, 0x5bc2c0de ) ROM_LOAD_EVEN( "fx03.rom", 0x40000, 0x20000, 0xc3d65bf9 ) ROM_LOAD_ODD ( "fx02.rom", 0x40000, 0x20000, 0xb875266b ) ROM_REGION( 0x10000, REGION_CPU2 ) /* Sound CPU */ ROM_LOAD( "fu11-.rom", 0x00000, 0x10000, 0x65f20f10 ) ROM_REGION( 0x20000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "fu05-.rom", 0x00000, 0x10000, 0x8134d412 ) /* Chars */ ROM_LOAD( "fu06-.rom", 0x10000, 0x10000, 0x2f914a45 ) ROM_REGION( 0x80000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-01", 0x00000, 0x80000, 0x1080d619 ) /* Tiles */ ROM_REGION( 0x80000, REGION_GFX3 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-00", 0x00000, 0x80000, 0x660eaabd ) /* Tiles */ ROM_REGION( 0x180000,REGION_GFX4 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-02", 0x000000, 0x80000, 0x58b7231d ) /* Sprites */ /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "mab-03", 0x0a0000, 0x80000, 0x76053b9d ) /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "fu07-.rom", 0x140000, 0x10000, 0xca8d0bb3 ) /* Extra sprites */ ROM_LOAD( "fu08-.rom", 0x150000, 0x10000, 0xc6afc5c8 ) ROM_LOAD( "fu09-.rom", 0x160000, 0x10000, 0x526809ca ) ROM_LOAD( "fu10-.rom", 0x170000, 0x10000, 0x6be6d50e ) ROM_REGION( 0x20000, REGION_SOUND1 ) /* ADPCM samples */ ROM_LOAD( "fu12-.rom", 0x00000, 0x20000, 0x2d1d65f2 ) ROM_REGION( 0x20000, REGION_SOUND2 ) /* ADPCM samples */ ROM_LOAD( "fu13-.rom", 0x00000, 0x20000, 0xb8525622 ) ROM_END ROM_START( cbusterw ) ROM_REGION( 0x80000, REGION_CPU1 ) /* 68000 code */ ROM_LOAD_EVEN( "fu01-.rom", 0x00000, 0x20000, 0x0203e0f8 ) ROM_LOAD_ODD ( "fu00-.rom", 0x00000, 0x20000, 0x9c58626d ) ROM_LOAD_EVEN( "fu03-.rom", 0x40000, 0x20000, 0xdef46956 ) ROM_LOAD_ODD ( "fu02-.rom", 0x40000, 0x20000, 0x649c3338 ) ROM_REGION( 0x10000, REGION_CPU2 ) /* Sound CPU */ ROM_LOAD( "fu11-.rom", 0x00000, 0x10000, 0x65f20f10 ) ROM_REGION( 0x20000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "fu05-.rom", 0x00000, 0x10000, 0x8134d412 ) /* Chars */ ROM_LOAD( "fu06-.rom", 0x10000, 0x10000, 0x2f914a45 ) ROM_REGION( 0x80000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-01", 0x00000, 0x80000, 0x1080d619 ) /* Tiles */ ROM_REGION( 0x80000, REGION_GFX3 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-00", 0x00000, 0x80000, 0x660eaabd ) /* Tiles */ ROM_REGION( 0x180000,REGION_GFX4 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-02", 0x000000, 0x80000, 0x58b7231d ) /* Sprites */ /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "mab-03", 0x0a0000, 0x80000, 0x76053b9d ) /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "fu07-.rom", 0x140000, 0x10000, 0xca8d0bb3 ) /* Extra sprites */ ROM_LOAD( "fu08-.rom", 0x150000, 0x10000, 0xc6afc5c8 ) ROM_LOAD( "fu09-.rom", 0x160000, 0x10000, 0x526809ca ) ROM_LOAD( "fu10-.rom", 0x170000, 0x10000, 0x6be6d50e ) ROM_REGION( 0x20000, REGION_SOUND1 ) /* ADPCM samples */ ROM_LOAD( "fu12-.rom", 0x00000, 0x20000, 0x2d1d65f2 ) ROM_REGION( 0x20000, REGION_SOUND2 ) /* ADPCM samples */ ROM_LOAD( "fu13-.rom", 0x00000, 0x20000, 0xb8525622 ) ROM_END ROM_START( cbusterj ) ROM_REGION( 0x80000, REGION_CPU1 ) /* 68000 code */ ROM_LOAD_EVEN( "fr01-1", 0x00000, 0x20000, 0xaf3c014f ) ROM_LOAD_ODD ( "fr00-1", 0x00000, 0x20000, 0xf666ad52 ) ROM_LOAD_EVEN( "fr03", 0x40000, 0x20000, 0x02c06118 ) ROM_LOAD_ODD ( "fr02", 0x40000, 0x20000, 0xb6c34332 ) ROM_REGION( 0x10000, REGION_CPU2 ) /* Sound CPU */ ROM_LOAD( "fu11-.rom", 0x00000, 0x10000, 0x65f20f10 ) ROM_REGION( 0x20000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "fu05-.rom", 0x00000, 0x10000, 0x8134d412 ) /* Chars */ ROM_LOAD( "fu06-.rom", 0x10000, 0x10000, 0x2f914a45 ) ROM_REGION( 0x80000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-01", 0x00000, 0x80000, 0x1080d619 ) /* Tiles */ ROM_REGION( 0x80000, REGION_GFX3 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-00", 0x00000, 0x80000, 0x660eaabd ) /* Tiles */ ROM_REGION( 0x180000,REGION_GFX4 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-02", 0x000000, 0x80000, 0x58b7231d ) /* Sprites */ /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "mab-03", 0x0a0000, 0x80000, 0x76053b9d ) /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "fr07", 0x140000, 0x10000, 0x52c85318 ) /* Extra sprites */ ROM_LOAD( "fr08", 0x150000, 0x10000, 0xea25fbac ) ROM_LOAD( "fr09", 0x160000, 0x10000, 0xf8363424 ) ROM_LOAD( "fr10", 0x170000, 0x10000, 0x241d5760 ) ROM_REGION( 0x20000, REGION_SOUND1 ) /* ADPCM samples */ ROM_LOAD( "fu12-.rom", 0x00000, 0x20000, 0x2d1d65f2 ) ROM_REGION( 0x20000, REGION_SOUND2 ) /* ADPCM samples */ ROM_LOAD( "fu13-.rom", 0x00000, 0x20000, 0xb8525622 ) ROM_END ROM_START( twocrude ) ROM_REGION( 0x80000, REGION_CPU1 ) /* 68000 code */ ROM_LOAD_EVEN( "ft01", 0x00000, 0x20000, 0x08e96489 ) ROM_LOAD_ODD ( "ft00", 0x00000, 0x20000, 0x6765c445 ) ROM_LOAD_EVEN( "ft03", 0x40000, 0x20000, 0x28002c99 ) ROM_LOAD_ODD ( "ft02", 0x40000, 0x20000, 0x37ea0626 ) ROM_REGION( 0x10000, REGION_CPU2 ) /* Sound CPU */ ROM_LOAD( "fu11-.rom", 0x00000, 0x10000, 0x65f20f10 ) ROM_REGION( 0x20000, REGION_GFX1 | REGIONFLAG_DISPOSE ) ROM_LOAD( "fu05-.rom", 0x00000, 0x10000, 0x8134d412 ) /* Chars */ ROM_LOAD( "fu06-.rom", 0x10000, 0x10000, 0x2f914a45 ) ROM_REGION( 0x80000, REGION_GFX2 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-01", 0x00000, 0x80000, 0x1080d619 ) /* Tiles */ ROM_REGION( 0x80000, REGION_GFX3 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-00", 0x00000, 0x80000, 0x660eaabd ) /* Tiles */ ROM_REGION( 0x180000,REGION_GFX4 | REGIONFLAG_DISPOSE ) ROM_LOAD( "mab-02", 0x000000, 0x80000, 0x58b7231d ) /* Sprites */ /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "mab-03", 0x0a0000, 0x80000, 0x76053b9d ) /* Space for extra sprites to be copied to (0x20000) */ ROM_LOAD( "ft07", 0x140000, 0x10000, 0xe3465c25 ) ROM_LOAD( "ft08", 0x150000, 0x10000, 0xc7f1d565 ) ROM_LOAD( "ft09", 0x160000, 0x10000, 0x6e3657b9 ) ROM_LOAD( "ft10", 0x170000, 0x10000, 0xcdb83560 ) ROM_REGION( 0x20000, REGION_SOUND1 ) /* ADPCM samples */ ROM_LOAD( "fu12-.rom", 0x00000, 0x20000, 0x2d1d65f2 ) ROM_REGION( 0x20000, REGION_SOUND2 ) /* ADPCM samples */ ROM_LOAD( "fu13-.rom", 0x00000, 0x20000, 0xb8525622 ) ROM_END /******************************************************************************/ static void init_twocrude(void) { unsigned char *RAM = memory_region(REGION_CPU1); unsigned char *PTR; int i,j; /* Main cpu decrypt */ for (i=0x00000; i<0x80000; i+=2) { #ifdef LSB_FIRST RAM[i+1]=(RAM[i+1] & 0xcf) | ((RAM[i+1] & 0x10) << 1) | ((RAM[i+1] & 0x20) >> 1); RAM[i+1]=(RAM[i+1] & 0x5f) | ((RAM[i+1] & 0x20) << 2) | ((RAM[i+1] & 0x80) >> 2); RAM[i]=(RAM[i] & 0xbd) | ((RAM[i] & 0x2) << 5) | ((RAM[i] & 0x40) >> 5); RAM[i]=(RAM[i] & 0xf5) | ((RAM[i] & 0x2) << 2) | ((RAM[i] & 0x8) >> 2); #else RAM[i]=(RAM[i] & 0xcf) | ((RAM[i] & 0x10) << 1) | ((RAM[i] & 0x20) >> 1); RAM[i]=(RAM[i] & 0x5f) | ((RAM[i] & 0x20) << 2) | ((RAM[i] & 0x80) >> 2); RAM[i+1]=(RAM[i+1] & 0xbd) | ((RAM[i+1] & 0x2) << 5) | ((RAM[i+1] & 0x40) >> 5); RAM[i+1]=(RAM[i+1] & 0xf5) | ((RAM[i+1] & 0x2) << 2) | ((RAM[i+1] & 0x8) >> 2); #endif } /* Rearrange the 'extra' sprite bank to be in the same format as main sprites */ RAM = memory_region(REGION_GFX4) + 0x080000; PTR = memory_region(REGION_GFX4) + 0x140000; for (i=0; i<0x20000; i+=64) { for (j=0; j<16; j+=1) { /* Copy 16 lines down */ RAM[i+ 0+j*2]=PTR[i/2+ 0+j]; /* Pixels 0-7 for each plane */ RAM[i+ 1+j*2]=PTR[i/2+0x10000+j]; RAM[i+0xa0000+j*2]=PTR[i/2+0x20000+j]; RAM[i+0xa0001+j*2]=PTR[i/2+0x30000+j]; } for (j=0; j<16; j+=1) { /* Copy 16 lines down */ RAM[i+ 0x20+j*2]=PTR[i/2+ 0x10+j]; /* Pixels 8-15 for each plane */ RAM[i+ 0x21+j*2]=PTR[i/2+0x10010+j]; RAM[i+0xa0020+j*2]=PTR[i/2+0x20010+j]; RAM[i+0xa0021+j*2]=PTR[i/2+0x30010+j]; } } } /******************************************************************************/ GAME( 1990, cbuster, 0, twocrude, twocrude, twocrude, ROT0, "Data East Corporation", "Crude Buster (World FX version)" ) GAME( 1990, cbusterw, cbuster, twocrude, twocrude, twocrude, ROT0, "Data East Corporation", "Crude Buster (World FU version)" ) GAME( 1990, cbusterj, cbuster, twocrude, twocrude, twocrude, ROT0, "Data East Corporation", "Crude Buster (Japan)" ) GAME( 1990, twocrude, cbuster, twocrude, twocrude, twocrude, ROT0, "Data East USA", "Two Crude (US)" )
Neo2003/mame4all-pi-adv
src/drivers/cbuster.cpp
C++
gpl-2.0
23,569
<?php class FaqController extends Controller { protected $logAction = false; public function accessRules() { return array( array( 'allow', 'users'=>array('*'), ), ); } public function actionIndex() { $categoryId = $this->iGet('category_id', 1); $model = new Faq(); $model->unsetAttributes(); $model->category_id = $categoryId; $model->status = Faq::STATUS_SHOW; $categories = FaqCategory::getCategoryMenu(); $this->title = Yii::t('common', 'Frequently Asked Questions'); $this->pageTitle = array($this->title); if ($model->category) { $this->pageTitle = array($this->title, $model->category->getAttributeValue('name')); } $this->breadcrumbs = array( 'FAQ', ); $this->render('index', array( 'model'=>$model, 'categories'=>$categories, )); } }
CubingChina/cubingchina
protected/controllers/FaqController.php
PHP
gpl-2.0
841
<?php namespace Drupal\simple_columns\Plugin\CKEditorPlugin; use Drupal\ckeditor\CKEditorPluginBase; use Drupal\editor\Entity\Editor; /** * Defines the "simplecolumns" plugin. * * @CKEditorPlugin( * id = "simplecolumns", * label = @Translation("Simple Columns"), * module = "cke_columns" * ) */ class SimpleColumns extends CKEditorPluginBase { /** * {@inheritdoc} */ public function getFile() { return drupal_get_path('module', 'simple_columns') . '/js/plugins/simplecolumns/plugin.js'; } /** * {@inheritdoc} */ public function getButtons() { return [ 'SimpleColumns' => [ 'label' => $this->t('Simple Columns'), 'image' => drupal_get_path('module', 'simple_columns') . '/js/plugins/simplecolumns/icons/simplecolumns.png', ], 'SimpleColumnBreak' => [ 'label' => $this->t('Simple Column Break'), 'image' => drupal_get_path('module', 'simple_columns') . '/js/plugins/simplecolumns/icons/simplecolumnbreak.png', ], ]; } /** * {@inheritdoc} */ public function getConfig(Editor $editor) { return []; } }
ilrWebServices/ilr
web/modules/custom/simple_columns/src/Plugin/CKEditorPlugin/SimpleColumns.php
PHP
gpl-2.0
1,127
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2022 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI 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 2 of the License, or * (at your option) any later version. * * GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ /** * @since 9.5 */ include('../inc/includes.php'); $translation = new ReminderTranslation(); if (isset($_POST['add'])) { $translation->add($_POST); Html::back(); } else if (isset($_POST['update'])) { $translation->update($_POST); Html::back(); } else if (isset($_POST["purge"])) { $translation->delete($_POST, true); Html::redirect(Reminder::getFormURLWithID($_POST['reminders_id'])); } else if (isset($_GET["id"])) { $translation->check($_GET["id"], READ); Html::header(Reminder::getTypeName(1), $_SERVER['PHP_SELF'], "tools", "remindertranslation"); $translation->display(['id' => $_GET['id']]); Html::footer(); }
stweil/glpi
front/remindertranslation.form.php
PHP
gpl-2.0
1,827
/* global Ext, ViewStateManager, App */ Ext.define( 'App.ux.StatefulTabPanel', { extend: 'Ext.tab.Panel', alias: 'widget.statefultabpanel', initComponent: function() { this.iconCls = this.iconCls || this.itemId; this.on( 'afterrender', this.onAfterRender, this); this.callParent( arguments); }, setActiveTab: function( tab, dontUpdateHistory) { this.callParent( arguments); if (!dontUpdateHistory) { ViewStateManager.change( tab.itemId); } }, addViewState: function( tab, path) { var i, item, newPath; for (i = 0; i < tab.items.length; i++) { item = tab.items.get( i); newPath = Ext.Array.clone( path); newPath.push( item); ViewStateManager.add( item.itemId, newPath); if (item instanceof App.ux.StatefulTabPanel) { this.addViewState( item, newPath); } } tab.viewStateDone = true; }, onAfterRender: function( tab) { if (!tab.viewStateDone) { if (tab.ownerCt instanceof App.ux.StatefulTabPanel) { tab = tab.ownerCt; } this.addViewState( tab, []); } } });
liancastellon/cellstore-admin
web/app/ux/StatefulTabPanel.js
JavaScript
gpl-2.0
1,141
<?php /** * @package Joomla.Administrator * @subpackage com_joomlaupdate * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; use Joomla\CMS\Language\Text; /** @var JoomlaupdateViewDefault $this */ ?> <fieldset> <legend> <?php echo Text::_('COM_JOOMLAUPDATE_VIEW_DEFAULT_NOUPDATES'); ?> </legend> <p> <?php echo Text::sprintf($this->langKey, $this->updateSourceKey); ?> </p> <div class="alert alert-success"> <?php echo Text::sprintf('COM_JOOMLAUPDATE_VIEW_DEFAULT_NOUPDATESNOTICE', JVERSION); ?> </div> </fieldset>
astridx/joomla-cms
administrator/components/com_joomlaupdate/tmpl/joomlaupdate/default_noupdate.php
PHP
gpl-2.0
686
<?php /** * Copyright (c) by the ACP3 Developers. * See the LICENSE file at the top-level module directory for licensing details. */ namespace ACP3\Modules\ACP3\Newsletter\Controller\Frontend\Index; use ACP3\Core; use ACP3\Modules\ACP3\Newsletter; class Activate extends Core\Controller\AbstractFrontendAction { /** * @var \ACP3\Modules\ACP3\Newsletter\Helper\AccountStatus */ protected $accountStatusHelper; /** * @var \ACP3\Modules\ACP3\Newsletter\Validation\ActivateAccountFormValidation */ protected $activateAccountFormValidation; /** * @var \ACP3\Core\Helpers\Alerts */ private $alertsHelper; /** * Activate constructor. * * @param \ACP3\Core\Controller\Context\FrontendContext $context * @param \ACP3\Core\Helpers\Alerts $alertsHelper * @param \ACP3\Modules\ACP3\Newsletter\Helper\AccountStatus $accountStatusHelper * @param \ACP3\Modules\ACP3\Newsletter\Validation\ActivateAccountFormValidation $activateAccountFormValidation */ public function __construct( Core\Controller\Context\FrontendContext $context, Core\Helpers\Alerts $alertsHelper, Newsletter\Helper\AccountStatus $accountStatusHelper, Newsletter\Validation\ActivateAccountFormValidation $activateAccountFormValidation ) { parent::__construct($context); $this->accountStatusHelper = $accountStatusHelper; $this->activateAccountFormValidation = $activateAccountFormValidation; $this->alertsHelper = $alertsHelper; } /** * @param string $hash */ public function execute($hash) { try { $this->activateAccountFormValidation->validate(['hash' => $hash]); $bool = $this->accountStatusHelper->changeAccountStatus( Newsletter\Helper\AccountStatus::ACCOUNT_STATUS_CONFIRMED, ['hash' => $hash] ); $this->setTemplate($this->alertsHelper->confirmBox($this->translator->t( 'newsletter', $bool !== false ? 'activate_success' : 'activate_error' ), $this->appPath->getWebRoot())); } catch (Core\Validation\Exceptions\ValidationFailedException $e) { $this->setContent($this->alertsHelper->errorBox($e->getMessage())); } } }
ACP3/module-newsletter
Controller/Frontend/Index/Activate.php
PHP
gpl-2.0
2,433
<?php /** * Proxies AJAX calls to the Bambuser public API, * and retrieves broadcast data. */ require __DIR__.'/../../vendor/autoload.php'; use GuzzleHttp\Client; header('Content-Type: application/json'); $client = new Client(); $params = [ 'query' => [ 'api_key'=> BAMBUSER_API_KEY, 'tag'=> 'NuitDeboutLive,NuitDebout' ] ]; $response = $client->get('http://api.bambuser.com/broadcast.json', $params); $body = $response->getBody(); // Implicitly cast the body to a string and echo it echo $body;
nuitdebout/wordpress
theme/lib/api/bambuser.php
PHP
gpl-2.0
521
<?php /** * @file * Toyota Yaris class. */ namespace Drupal\oop_example_11\BusinessLogic\Vehicle\Car\Toyota; /** * Toyota Yaris class. */ class ToyotaYaris extends Toyota { /** * The doors count. * * @var int */ public $doors = 5; /** * Returns class type description. */ public function getClassTypeDescription() { $s = t('Toyota Yaris'); return $s; } }
nfouka/poo_d8
oop_examples/oop_example_11/src/BusinessLogic/Vehicle/Car/Toyota/ToyotaYaris.php
PHP
gpl-2.0
402
package eu.geekhome.asymptote.model; public abstract class SyncUpdateBase<T> implements SyncUpdate<T> { private T _value; @Override public T getValue() { return _value; } public void setValue(T value) { _value = value; } public SyncUpdateBase(T value) { _value = value; } }
tomaszbabiuk/geekhome-asymptote
asymptote/src/main/java/eu/geekhome/asymptote/model/SyncUpdateBase.java
Java
gpl-2.0
335
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bugman.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
aliasav/Bugman
bugman/manage.py
Python
gpl-2.0
249
<?php // +-------------------------------------------------+ // © 2002-2012 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net) // +-------------------------------------------------+ // $Id: cms_module_carousel_datasource_notices.class.php,v 1.5 2012-11-15 09:47:40 arenou Exp $ if (stristr($_SERVER['REQUEST_URI'], ".class.php")) die("no access"); class cms_module_carousel_datasource_notices extends cms_module_common_datasource_records{ public function __construct($id=0){ parent::__construct($id); } /* * Récupération des données de la source... */ public function get_datas(){ global $opac_url_base; global $opac_show_book_pics; global $opac_book_pics_url; $datas = parent::get_datas(); $notices = $datas['records']; $query = "select notice_id,tit1,thumbnail_url,code from notices where notice_id in(".implode(",",$notices).")"; $result = mysql_query($query); $notices = array(); if(mysql_num_rows($result)){ while($row = mysql_fetch_object($result)){ if ($opac_show_book_pics=='1' && ($opac_book_pics_url || $row->thumbnail_url)) { $code_chiffre = pmb_preg_replace('/-|\.| /', '', $row->code); $url_image = $opac_book_pics_url ; $url_image = $opac_url_base."getimage.php?url_image=".urlencode($url_image)."&noticecode=!!noticecode!!&vigurl=".urlencode($row->thumbnail_url) ; if ($row->thumbnail_url){ $url_vign=$row->thumbnail_url; }else if($code_chiffre){ $url_vign = str_replace("!!noticecode!!", $code_chiffre, $url_image) ; }else { $url_vign = $opac_url_base."images/vide.png"; } } $notices[] = array( 'title' => $row->tit1, 'link' => $opac_url_base."?lvl=notice_display&id=".$row->notice_id, 'vign' => $url_vign ); } } return array('records' => $notices); } public function get_format_data_structure(){ return array( array( 'var' => "records", 'desc' => $this->msg['cms_module_carousel_datasource_notices_records_desc'], 'children' => array( array( 'var' => "records[i].title", 'desc'=> $this->msg['cms_module_carousel_datasource_notices_record_title_desc'] ), array( 'var' => "records[i].vign", 'desc'=> $this->msg['cms_module_carousel_datasource_notices_record_vign_desc'] ), array( 'var' => "records[i].link", 'desc'=> $this->msg['cms_module_carousel_datasource_notices_record_link_desc'] ) ) ) ); } }
Gambiit/pmb-on-docker
web_appli/pmb/cms/modules/carousel/datasources/cms_module_carousel_datasource_notices.class.php
PHP
gpl-2.0
2,475
/* Greeter module for xdm Copyright (C) 1997, 1998 Steffen Hansen <hansen@kde.org> Copyright (C) 2000-2003 Oswald Buddenhagen <ossi@kde.org> 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kdm_greet.h" #include "kdmshutdown.h" #include "kdmconfig.h" #include "kgapp.h" #include "kgreeter.h" #ifdef XDMCP # include "kchooser.h" #endif #include <kprocess.h> #include <kcmdlineargs.h> #include <kcrash.h> #include <kstandarddirs.h> #include <ksimpleconfig.h> #include <qtimer.h> #include <qcursor.h> #include <qpalette.h> #include <stdlib.h> // free(), exit() #include <unistd.h> // alarm() #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <X11/cursorfont.h> extern "C" { static void sigAlarm( int ) { exit( EX_RESERVER_DPY ); } } GreeterApp::GreeterApp() { pingInterval = _isLocal ? 0 : _pingInterval; if (pingInterval) { struct sigaction sa; sigemptyset( &sa.sa_mask ); sa.sa_flags = 0; sa.sa_handler = sigAlarm; sigaction( SIGALRM, &sa, 0 ); alarm( pingInterval * 70 ); // sic! give the "proper" pinger enough time startTimer( pingInterval * 60000 ); } } void GreeterApp::timerEvent( QTimerEvent * ) { alarm( 0 ); if (!PingServer( qt_xdisplay() )) ::exit( EX_RESERVER_DPY ); alarm( pingInterval * 70 ); // sic! give the "proper" pinger enough time } bool GreeterApp::x11EventFilter( XEvent * ev ) { KeySym sym; switch (ev->type) { case FocusIn: case FocusOut: // Hack to tell dialogs to take focus when the keyboard is grabbed ev->xfocus.mode = NotifyNormal; break; case KeyPress: sym = XLookupKeysym( &ev->xkey, 0 ); if (sym != XK_Return && !IsModifierKey( sym )) emit activity(); break; case ButtonPress: emit activity(); /* fall through */ case ButtonRelease: // Hack to let the RMB work as LMB if (ev->xbutton.button == 3) ev->xbutton.button = 1; /* fall through */ case MotionNotify: if (ev->xbutton.state & Button3Mask) ev->xbutton.state = (ev->xbutton.state & ~Button3Mask) | Button1Mask; break; } return false; } extern bool kde_have_kipc; extern "C" { static int xIOErr( Display * ) { exit( EX_RESERVER_DPY ); } void kg_main( const char *argv0 ) { static char *argv[] = { (char *)"kdmgreet", 0 }; KCmdLineArgs::init( 1, argv, *argv, 0, 0, 0, true ); kde_have_kipc = false; KApplication::disableAutoDcopRegistration(); KCrash::setSafer( true ); GreeterApp app; XSetIOErrorHandler( xIOErr ); Display *dpy = qt_xdisplay(); if (!_GUIStyle.isEmpty()) app.setStyle( _GUIStyle ); _colorScheme = locate( "data", "kdisplay/color-schemes/" + _colorScheme + ".kcsrc" ); if (!_colorScheme.isEmpty()) { KSimpleConfig config( _colorScheme, true ); config.setGroup( "Color Scheme" ); app.setPalette( app.createApplicationPalette( &config, 7 ) ); } app.setFont( _normalFont ); setup_modifiers( dpy, _numLockStatus ); SecureDisplay( dpy ); KProcess *proc = 0; if (!_grabServer) { if (_useBackground) { proc = new KProcess; *proc << QCString( argv0, strrchr( argv0, '/' ) - argv0 + 2 ) + "krootimage"; *proc << _backgroundCfg; proc->start(); } GSendInt( G_SetupDpy ); GRecvInt(); } GSendInt( G_Ready ); setCursor( dpy, app.desktop()->winId(), XC_left_ptr ); for (;;) { int rslt, cmd = GRecvInt(); if (cmd == G_ConfShutdown) { int how = GRecvInt(), uid = GRecvInt(); char *os = GRecvStr(); KDMSlimShutdown::externShutdown( how, os, uid ); if (os) free( os ); GSendInt( G_Ready ); _autoLoginDelay = 0; continue; } if (cmd == G_ErrorGreet) { if (KGVerify::handleFailVerify( qApp->desktop()->screen( _greeterScreen ) )) break; _autoLoginDelay = 0; cmd = G_Greet; } KProcess *proc2 = 0; app.setOverrideCursor( Qt::WaitCursor ); FDialog *dialog; #ifdef XDMCP if (cmd == G_Choose) { dialog = new ChooserDlg; GSendInt( G_Ready ); /* tell chooser to go into async mode */ GRecvInt(); /* ack */ } else #endif { if ((cmd != G_GreetTimed && !_autoLoginAgain) || _autoLoginUser.isEmpty()) _autoLoginDelay = 0; if (_useTheme && !_theme.isEmpty()) { KThemedGreeter *tgrt; dialog = tgrt = new KThemedGreeter; if (!tgrt->isOK()) { delete tgrt; dialog = new KStdGreeter; } } else dialog = new KStdGreeter; if (*_preloader) { proc2 = new KProcess; *proc2 << _preloader; proc2->start(); } } app.restoreOverrideCursor(); Debug( "entering event loop\n" ); rslt = dialog->exec(); Debug( "left event loop\n" ); delete dialog; delete proc2; #ifdef XDMCP switch (rslt) { case ex_greet: GSendInt( G_DGreet ); continue; case ex_choose: GSendInt( G_DChoose ); continue; default: break; } #endif break; } KGVerify::done(); delete proc; UnsecureDisplay( dpy ); restore_modifiers(); XSetInputFocus( qt_xdisplay(), PointerRoot, PointerRoot, CurrentTime ); } } // extern "C" #include "kgapp.moc"
iegor/kdebase
kdm/kfrontend/kgapp.cpp
C++
gpl-2.0
5,569
<?php class Bbpress_Meta_Commands extends WP_CLI_Command { /** * This will install bbPress metas plugin required table and migrate data over. * * ## EXAMPLES * * wp bbpress_metas install */ public function install() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; // Notify the user we are putting the site into maintenance mode WP_CLI::log( 'Putting the site into maintenance mode and installing the new schema' ); // This puts WordPress in maintenance mode $maintenance_file = ABSPATH . '.maintenance'; // 1. Put the website into maintenance mode for a short period if ( ! file_put_contents( $maintenance_file, '<?php $upgrading = time(); ?>' ) ) { // If we are unable to write the maintenance file, we return right away to keep data integrity WP_CLI::error( 'Unable to put the website into maintenance mode. Please check file permissions in the root.' ); } // 2. Install the new table $table = Bbpress_Meta::$table_name; $sql = "CREATE TABLE {$table} ( meta_id bigint(20) unsigned NOT NULL, post_id bigint(20) unsigned NOT NULL, meta_key varchar(255) NULL, meta_value varchar(255) NULL, PRIMARY KEY (meta_id), KEY post_id_meta_value (post_id, meta_value), KEY meta_value (meta_value), KEY post_id (post_id) ) ENGINE = MyISAM"; if ( ! empty( $wpdb->charset ) ) { $sql .= " CHARACTER SET $wpdb->charset"; } if ( ! empty( $wpdb->collate ) ) { $sql .= " COLLATE $wpdb->collate"; } $sql .= ';'; dbDelta( $sql ); // MySQL to migrate data over the new table WP_CLI::log( 'Starting data migration...' ); // 3. Query old data over from the postmeta table $results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s", Bbpress_Meta::$meta_key ), ARRAY_A ); // Populate the new table... this might take a while so we keep the user posted foreach ( $results as $key => $row ) { // Inform the user every 5 000 entries if ( ( $key % 5000 ) === 0 && $key !== 0 ) { WP_CLI::log( sprintf( 'We have just processed %s entries', number_format( $key ) ) ); } $wpdb->insert( $table, $row ); } // Notify the user we are done WP_CLI::success( 'Done migrating content. We will now remove maintenance mode and update db option' ); // Database table created, update option to reflect plugin version update_option( Bbpress_Meta::OPTION_KEY, Bbpress_Meta::VERSION ); // Remove maintenance mode if ( ! unlink( $maintenance_file ) ) { // If we are unable to unlink the file we need to warn the user right now. WP_CLI::error( 'The script was unable to delete the .maintenance file required for the site to run properly. Please delete it manually.' ); } } public function update() { // No update for now. } } WP_CLI::add_command( 'bbpress-meta', 'Bbpress_Meta_Commands' );
mainsocial/bbpress-meta
inc/wp-cli-commands.php
PHP
gpl-2.0
2,895
$(function(){ $('.home .bxslider').bxSlider({ auto: true, mode: 'fade' }); /** * QUICK REFERENCE */ // check if the window bindings should be applied (only if the element is present) var $reference = $('.reference-wrap'); if($reference.length > 0){ // toggle the menu $('.reference-wrap h3').click(function() { $('.reference-content').slideToggle(300); }); // scroll to the elements $('.reference-content a').click(function(){ $('.reference-content').slideToggle(300); var id = $(this).html(); $('html, body').animate({ scrollTop: $('#' + id).offset().top - 20 }, 300); return false; }); $(window).bind('scroll resize', positionQuickReference); } // check if .reference-wrap should be sticky function positionQuickReference(){ var windowTop = $(window).scrollTop(); if(windowTop >= 112){ $reference.css({ position: 'fixed', top: 20, right: $(window).width() > 700 ? $(window).width() - ($('#primary h1').offset().left + $('#primary').width()) : 20 }); }else{ $reference.css({ position: 'absolute', top: 0, right: $(window).width() > 1040 ? 0 : 20 }); } } /** * SIDEBAR */ $('.btn-donate').click(function() { $('#frm-paypal').submit(); return false; }); $('.block-signup form').submit(function() { var email = $('#mce-EMAIL').val(); if(!isValidEmailAddress(email)){ $('.block-signup .error').show(); return false; } }); }); function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; // (function(){ // var bsa = document.createElement('script'); // bsa.type = 'text/javascript'; // bsa.async = true; // bsa.src = '//s3.buysellads.com/ac/bsa.js'; // (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(bsa); // })(); /** * Create a cookie */ function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; }; /** * Get a cookie */ function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ""; };
naka211/tellusavokater
html/js/scripts.js
JavaScript
gpl-2.0
3,481
package com.meetup.agileim.web.rest.errors; import java.util.List; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.*; /** * Controller advice to translate the server side exceptions to client-friendly json structures. */ @ControllerAdvice public class ExceptionTranslator { @ExceptionHandler(ConcurrencyFailureException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public ErrorDTO processConcurencyError(ConcurrencyFailureException ex) { return new ErrorDTO(ErrorConstants.ERR_CONCURRENCY_FAILURE); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorDTO processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); return processFieldErrors(fieldErrors); } @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ParameterizedErrorDTO processParameterizedValidationError(CustomParameterizedException ex) { return ex.getErrorDTO(); } @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public ErrorDTO processAccessDeniedExcpetion(AccessDeniedException e) { return new ErrorDTO(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage()); } private ErrorDTO processFieldErrors(List<FieldError> fieldErrors) { ErrorDTO dto = new ErrorDTO(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public ErrorDTO processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) { return new ErrorDTO(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage()); } }
lazcatluc/agileim
src/main/java/com/meetup/agileim/web/rest/errors/ExceptionTranslator.java
Java
gpl-2.0
2,547
/* * File: TestLogAppender.cpp * Author: HoelscJ * * Created on 7. Oktober 2011, 15:06 */ #include "TestLogAppender.h" namespace org { namespace esb { namespace hive { TestLogAppender::TestLogAppender(const log4cplus::helpers::Properties properties) { } TestLogAppender::~TestLogAppender() { } } } }
psychobob666/MediaEncodingCluster
src/org/esb/hive/TestLogAppender.cpp
C++
gpl-2.0
348
import ctypes.wintypes as ctypes import braille import brailleInput import globalPluginHandler import scriptHandler import inputCore import api INPUT_MOUSE = 0 INPUT_KEYBOARD = 1 INPUT_HARDWARE = 2 MAPVK_VK_TO_VSC = 0 KEYEVENTF_EXTENDEDKEY = 0x0001 KEYEVENTF_KEYUP = 0x0002 KEYEVENT_SCANCODE = 0x0008 KEYEVENTF_UNICODE = 0x0004 class MOUSEINPUT(ctypes.Structure): _fields_ = ( ('dx', ctypes.c_long), ('dy', ctypes.c_long), ('mouseData', ctypes.DWORD), ('dwFlags', ctypes.DWORD), ('time', ctypes.DWORD), ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong)), ) class KEYBDINPUT(ctypes.Structure): _fields_ = ( ('wVk', ctypes.WORD), ('wScan', ctypes.WORD), ('dwFlags', ctypes.DWORD), ('time', ctypes.DWORD), ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong)), ) class HARDWAREINPUT(ctypes.Structure): _fields_ = ( ('uMsg', ctypes.DWORD), ('wParamL', ctypes.WORD), ('wParamH', ctypes.WORD), ) class INPUTUnion(ctypes.Union): _fields_ = ( ('mi', MOUSEINPUT), ('ki', KEYBDINPUT), ('hi', HARDWAREINPUT), ) class INPUT(ctypes.Structure): _fields_ = ( ('type', ctypes.DWORD), ('union', INPUTUnion)) class BrailleInputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGesture): def __init__(self, **kwargs): super(BrailleInputGesture, self).__init__() for key, value in kwargs.iteritems(): setattr(self, key, value) self.source="remote{}{}".format(self.source[0].upper(),self.source[1:]) self.scriptPath=getattr(self,"scriptPath",None) self.script=self.findScript() if self.scriptPath else None def findScript(self): if not (isinstance(self.scriptPath,list) and len(self.scriptPath)==3): return None module,cls,scriptName=self.scriptPath focus = api.getFocusObject() if not focus: return None if scriptName.startswith("kb:"): # Emulate a key press. return scriptHandler._makeKbEmulateScript(scriptName) import globalCommands # Global plugin level. if cls=='GlobalPlugin': for plugin in globalPluginHandler.runningPlugins: if module==plugin.__module__: func = getattr(plugin, "script_%s" % scriptName, None) if func: return func # App module level. app = focus.appModule if app and cls=='AppModule' and module==app.__module__: func = getattr(app, "script_%s" % scriptName, None) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = getattr(treeInterceptor , "script_%s" % scriptName, None) # We are no keyboard input return func # NVDAObject level. func = getattr(focus, "script_%s" % scriptName, None) if func: return func for obj in reversed(api.getFocusAncestors()): func = getattr(obj, "script_%s" % scriptName, None) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = getattr(globalCommands.commands, "script_%s" % scriptName, None) if func: return func return None def send_key(vk=None, scan=None, extended=False, pressed=True): i = INPUT() i.union.ki.wVk = vk if scan: i.union.ki.wScan = scan else: #No scancode provided, try to get one i.union.ki.wScan = ctypes.windll.user32.MapVirtualKeyW(vk, MAPVK_VK_TO_VSC) if not pressed: i.union.ki.dwFlags |= KEYEVENTF_KEYUP if extended: i.union.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY i.type = INPUT_KEYBOARD ctypes.windll.user32.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT))
nishimotz/NVDARemote
addon/globalPlugins/remoteClient/input.py
Python
gpl-2.0
3,588
<?php /** * @covers ClassCollector */ class ClassCollectorTest extends MediaWikiUnitTestCase { public static function provideCases() { return [ [ "class Foo {}", [ 'Foo' ], ], [ "namespace Example;\nclass Foo {}\nclass Bar {}", [ 'Example\Foo', 'Example\Bar' ], ], [ "class_alias( 'Foo', 'Bar' );", [ 'Bar' ], ], [ "namespace Example;\nclass Foo {}\nclass_alias( 'Example\Foo', 'Foo' );", [ 'Example\Foo', 'Foo' ], ], [ "namespace Example;\nclass Foo {}\nclass_alias( 'Example\Foo', 'Bar' );", [ 'Example\Foo', 'Bar' ], ], [ // Support a multiline 'class' statement "namespace Example;\nclass Foo extends\n\tFooBase {\n\t" . "public function x() {}\n}\nclass_alias( 'Example\Foo', 'Bar' );", [ 'Example\Foo', 'Bar' ], ], [ "class_alias( Foo::class, 'Bar' );", [ 'Bar' ], ], [ // Support nested class_alias() calls "if ( false ) {\n\tclass_alias( Foo::class, 'Bar' );\n}", [ 'Bar' ], ], [ // Namespaced class is not currently supported. Must use namespace declaration // earlier in the file. "class_alias( Example\Foo::class, 'Bar' );", [], ], [ "namespace Example;\nclass Foo {}\nclass_alias( Foo::class, 'Bar' );", [ 'Example\Foo', 'Bar' ], ], [ "new class() extends Foo {}", [] ] ]; } /** * @dataProvider provideCases */ public function testGetClasses( $code, array $classes, $message = null ) { $cc = new ClassCollector(); $this->assertEquals( $classes, $cc->getClasses( "<?php\n$code" ), $message ); } }
pierres/archlinux-mediawiki
tests/phpunit/unit/includes/utils/ClassCollectorTest.php
PHP
gpl-2.0
1,608
/** @file project_euler_problem_15.cpp @author Terence Henriod Project Euler Problem 15 @brief Solves the following problem for the general case of any power of 2 (within system limitations): "2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000?" @version Original Code 1.00 (1/4/2014) - T. Henriod */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HEADER FILES / NAMESPACES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #include <cassert> #include <cmath> #include <cstdio> #include <iostream> #include <iomanip> #include <fstream> #include <mpirxx.h> using namespace std; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GLOBAL CONSTANTS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FUNCTION PROTOTYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /** FunctionName A short description @param @return @pre -# @post -# @detail @bAlgorithm -# @exception @code @endcode */ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN FUNCTION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ int main(int argc, char** argv) { // variables // DID IT IN JAVA - a good method is with a string though // unsigned int power = 1000; // unsigned int digit_sum = 0; // mpz_class large_number = 0; // char file_name [] = "project_euler_problem_16.txt"; // ofstream fout; // FILE* file; // // // get the power of 2 to use // printf("The number whose digits to be summed is: 2^"); // scanf("%u", &power); // // // compute the power // large_number = 4; //pow(2, power); // //cout << large_number << endl; // // // write it to the file // file = fopen(file_name, "w"); // fprintf(file, "%lf", large_number); // fclose(file); // // // compute the sum of the digits // //digit_sum = sumDigits(file_name); // // // report the result to the user // printf("\nThe sum of %lf's \ndigits is: %u\n", large_number, digit_sum); // scanf("%s", file_name); // return 0 on successful completion return 0; } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FUNCTION IMPLEMENTATIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
T-R0D/JustForFun
Project-Euler/project_euler_problem_16.cpp
C++
gpl-2.0
2,633
// Copyright 2013 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include <algorithm> #include <mbedtls/error.h> #ifndef _WIN32 #include <arpa/inet.h> #include <unistd.h> #endif #include "Common/FileUtil.h" #include "Core/ConfigManager.h" #include "Core/Core.h" #include "Core/IPC_HLE/WII_IPC_HLE.h" #include "Core/IPC_HLE/WII_IPC_HLE_Device.h" #include "Core/IPC_HLE/WII_Socket.h" // No Wii socket support while using NetPlay or TAS #ifdef _WIN32 #define ERRORCODE(name) WSA##name #define EITHER(win32, posix) win32 #else #define ERRORCODE(name) name #define EITHER(win32, posix) posix #endif char* WiiSockMan::DecodeError(s32 ErrorCode) { #ifdef _WIN32 // NOT THREAD SAFE static char Message[1024]; FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, nullptr, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), Message, sizeof(Message), nullptr); return Message; #else return strerror(ErrorCode); #endif } static s32 TranslateErrorCode(s32 native_error, bool isRW) { switch (native_error) { case ERRORCODE(EMSGSIZE): ERROR_LOG(WII_IPC_NET, "Find out why this happened, looks like PEEK failure?"); return -1; // Should be -SO_EMSGSIZE case EITHER(WSAENOTSOCK, EBADF): return -SO_EBADF; case ERRORCODE(EADDRINUSE): return -SO_EADDRINUSE; case ERRORCODE(ECONNRESET): return -SO_ECONNRESET; case ERRORCODE(EISCONN): return -SO_EISCONN; case ERRORCODE(ENOTCONN): return -SO_EAGAIN; // After proper blocking SO_EAGAIN shouldn't be needed... case ERRORCODE(EINPROGRESS): return -SO_EINPROGRESS; case ERRORCODE(EALREADY): return -SO_EALREADY; case ERRORCODE(EACCES): return -SO_EACCES; case ERRORCODE(ECONNREFUSED): return -SO_ECONNREFUSED; case ERRORCODE(ENETUNREACH): return -SO_ENETUNREACH; case ERRORCODE(EHOSTUNREACH): return -SO_EHOSTUNREACH; case EITHER(WSAEWOULDBLOCK, EAGAIN): if (isRW) { return -SO_EAGAIN; // EAGAIN } else { return -SO_EINPROGRESS; // EINPROGRESS } default: return -1; } } // Don't use string! (see https://github.com/dolphin-emu/dolphin/pull/3143) s32 WiiSockMan::GetNetErrorCode(s32 ret, const char* caller, bool isRW) { #ifdef _WIN32 s32 errorCode = WSAGetLastError(); #else s32 errorCode = errno; #endif if (ret >= 0) { WiiSockMan::GetInstance().SetLastNetError(ret); return ret; } ERROR_LOG(WII_IPC_NET, "%s failed with error %d: %s, ret= %d", caller, errorCode, DecodeError(errorCode), ret); s32 ReturnValue = TranslateErrorCode(errorCode, isRW); WiiSockMan::GetInstance().SetLastNetError(ReturnValue); return ReturnValue; } WiiSocket::~WiiSocket() { if (fd >= 0) { (void)CloseFd(); } } void WiiSocket::SetFd(s32 s) { if (fd >= 0) (void)CloseFd(); nonBlock = false; fd = s; // Set socket to NON-BLOCK #ifdef _WIN32 u_long iMode = 1; ioctlsocket(fd, FIONBIO, &iMode); #else int flags; if (-1 == (flags = fcntl(fd, F_GETFL, 0))) flags = 0; fcntl(fd, F_SETFL, flags | O_NONBLOCK); #endif } s32 WiiSocket::CloseFd() { s32 ReturnValue = 0; if (fd >= 0) { #ifdef _WIN32 s32 ret = closesocket(fd); #else s32 ret = close(fd); #endif ReturnValue = WiiSockMan::GetNetErrorCode(ret, "CloseFd", false); } else { ReturnValue = WiiSockMan::GetNetErrorCode(EITHER(WSAENOTSOCK, EBADF), "CloseFd", false); } fd = -1; return ReturnValue; } s32 WiiSocket::FCntl(u32 cmd, u32 arg) { #define F_GETFL 3 #define F_SETFL 4 #define F_NONBLOCK 4 s32 ret = 0; if (cmd == F_GETFL) { ret = nonBlock ? F_NONBLOCK : 0; } else if (cmd == F_SETFL) { nonBlock = (arg & F_NONBLOCK) == F_NONBLOCK; } else { ERROR_LOG(WII_IPC_NET, "SO_FCNTL unknown command"); } INFO_LOG(WII_IPC_NET, "IOCTL_SO_FCNTL(%08x, %08X, %08X)", fd, cmd, arg); return ret; } void WiiSocket::Update(bool read, bool write, bool except) { auto it = pending_sockops.begin(); while (it != pending_sockops.end()) { s32 ReturnValue = 0; bool forceNonBlock = false; IPCCommandType ct = static_cast<IPCCommandType>(Memory::Read_U32(it->_CommandAddress)); if (!it->is_ssl && ct == IPC_CMD_IOCTL) { u32 BufferIn = Memory::Read_U32(it->_CommandAddress + 0x10); u32 BufferInSize = Memory::Read_U32(it->_CommandAddress + 0x14); u32 BufferOut = Memory::Read_U32(it->_CommandAddress + 0x18); u32 BufferOutSize = Memory::Read_U32(it->_CommandAddress + 0x1C); switch (it->net_type) { case IOCTL_SO_FCNTL: { u32 cmd = Memory::Read_U32(BufferIn + 4); u32 arg = Memory::Read_U32(BufferIn + 8); ReturnValue = FCntl(cmd, arg); break; } case IOCTL_SO_BIND: { // u32 has_addr = Memory::Read_U32(BufferIn + 0x04); sockaddr_in local_name; WiiSockAddrIn* wii_name = (WiiSockAddrIn*)Memory::GetPointer(BufferIn + 0x08); WiiSockMan::Convert(*wii_name, local_name); int ret = bind(fd, (sockaddr*)&local_name, sizeof(local_name)); ReturnValue = WiiSockMan::GetNetErrorCode(ret, "SO_BIND", false); INFO_LOG(WII_IPC_NET, "IOCTL_SO_BIND (%08X %s:%d) = %d ", fd, inet_ntoa(local_name.sin_addr), Common::swap16(local_name.sin_port), ret); break; } case IOCTL_SO_CONNECT: { // u32 has_addr = Memory::Read_U32(BufferIn + 0x04); sockaddr_in local_name; WiiSockAddrIn* wii_name = (WiiSockAddrIn*)Memory::GetPointer(BufferIn + 0x08); WiiSockMan::Convert(*wii_name, local_name); int ret = connect(fd, (sockaddr*)&local_name, sizeof(local_name)); ReturnValue = WiiSockMan::GetNetErrorCode(ret, "SO_CONNECT", false); INFO_LOG(WII_IPC_NET, "IOCTL_SO_CONNECT (%08x, %s:%d)", fd, inet_ntoa(local_name.sin_addr), Common::swap16(local_name.sin_port)); break; } case IOCTL_SO_ACCEPT: { if (BufferOutSize > 0) { sockaddr_in local_name; WiiSockAddrIn* wii_name = (WiiSockAddrIn*)Memory::GetPointer(BufferOut); WiiSockMan::Convert(*wii_name, local_name); socklen_t addrlen = sizeof(sockaddr_in); int ret = (s32)accept(fd, (sockaddr*)&local_name, &addrlen); ReturnValue = WiiSockMan::GetNetErrorCode(ret, "SO_ACCEPT", true); WiiSockMan::Convert(local_name, *wii_name, addrlen); } else { int ret = (s32)accept(fd, nullptr, nullptr); ReturnValue = WiiSockMan::GetNetErrorCode(ret, "SO_ACCEPT", true); } WiiSockMan::GetInstance().AddSocket(ReturnValue); INFO_LOG(WII_IPC_NET, "IOCTL_SO_ACCEPT " "BufferIn: (%08x, %i), BufferOut: (%08x, %i)", BufferIn, BufferInSize, BufferOut, BufferOutSize); break; } default: break; } // Fix blocking error codes if (!nonBlock) { if (it->net_type == IOCTL_SO_CONNECT && ReturnValue == -SO_EISCONN) { ReturnValue = SO_SUCCESS; } } } else if (ct == IPC_CMD_IOCTLV) { SIOCtlVBuffer CommandBuffer(it->_CommandAddress); u32 BufferIn = 0, BufferIn2 = 0; u32 BufferInSize = 0, BufferInSize2 = 0; u32 BufferOut = 0, BufferOut2 = 0; u32 BufferOutSize = 0, BufferOutSize2 = 0; if (CommandBuffer.InBuffer.size() > 0) { BufferIn = CommandBuffer.InBuffer.at(0).m_Address; BufferInSize = CommandBuffer.InBuffer.at(0).m_Size; } if (CommandBuffer.PayloadBuffer.size() > 0) { BufferOut = CommandBuffer.PayloadBuffer.at(0).m_Address; BufferOutSize = CommandBuffer.PayloadBuffer.at(0).m_Size; } if (CommandBuffer.PayloadBuffer.size() > 1) { BufferOut2 = CommandBuffer.PayloadBuffer.at(1).m_Address; BufferOutSize2 = CommandBuffer.PayloadBuffer.at(1).m_Size; } if (CommandBuffer.InBuffer.size() > 1) { BufferIn2 = CommandBuffer.InBuffer.at(1).m_Address; BufferInSize2 = CommandBuffer.InBuffer.at(1).m_Size; } if (it->is_ssl) { int sslID = Memory::Read_U32(BufferOut) - 1; if (SSLID_VALID(sslID)) { switch (it->ssl_type) { case IOCTLV_NET_SSL_DOHANDSHAKE: { mbedtls_ssl_context* ctx = &CWII_IPC_HLE_Device_net_ssl::_SSL[sslID].ctx; int ret = mbedtls_ssl_handshake(ctx); if (ret) { char error_buffer[256] = ""; mbedtls_strerror(ret, error_buffer, sizeof(error_buffer)); ERROR_LOG(WII_IPC_SSL, "IOCTLV_NET_SSL_DOHANDSHAKE: %s", error_buffer); } switch (ret) { case 0: Memory::Write_U32(SSL_OK, BufferIn); break; case MBEDTLS_ERR_SSL_WANT_READ: Memory::Write_U32(SSL_ERR_RAGAIN, BufferIn); if (!nonBlock) ReturnValue = SSL_ERR_RAGAIN; break; case MBEDTLS_ERR_SSL_WANT_WRITE: Memory::Write_U32(SSL_ERR_WAGAIN, BufferIn); if (!nonBlock) ReturnValue = SSL_ERR_WAGAIN; break; case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED: { char error_buffer[256] = ""; int res = mbedtls_ssl_get_verify_result(ctx); mbedtls_x509_crt_verify_info(error_buffer, sizeof(error_buffer), "", res); ERROR_LOG(WII_IPC_SSL, "MBEDTLS_ERR_X509_CERT_VERIFY_FAILED (verify_result = %d): %s", res, error_buffer); if (res & MBEDTLS_X509_BADCERT_CN_MISMATCH) res = SSL_ERR_VCOMMONNAME; else if (res & MBEDTLS_X509_BADCERT_NOT_TRUSTED) res = SSL_ERR_VROOTCA; else if (res & MBEDTLS_X509_BADCERT_REVOKED) res = SSL_ERR_VCHAIN; else if (res & MBEDTLS_X509_BADCERT_EXPIRED || res & MBEDTLS_X509_BADCERT_FUTURE) res = SSL_ERR_VDATE; else res = SSL_ERR_FAILED; Memory::Write_U32(res, BufferIn); if (!nonBlock) ReturnValue = res; break; } default: Memory::Write_U32(SSL_ERR_FAILED, BufferIn); break; } // mbedtls_ssl_get_peer_cert(ctx) seems not to work if handshake failed // Below is an alternative to dump the peer certificate if (SConfig::GetInstance().m_SSLDumpPeerCert && ctx->session_negotiate != nullptr) { const mbedtls_x509_crt* cert = ctx->session_negotiate->peer_cert; if (cert != nullptr) { std::string filename = File::GetUserPath(D_DUMPSSL_IDX) + ((ctx->hostname != nullptr) ? ctx->hostname : "") + "_peercert.der"; File::IOFile(filename, "wb").WriteBytes(cert->raw.p, cert->raw.len); } } INFO_LOG(WII_IPC_SSL, "IOCTLV_NET_SSL_DOHANDSHAKE = (%d) " "BufferIn: (%08x, %i), BufferIn2: (%08x, %i), " "BufferOut: (%08x, %i), BufferOut2: (%08x, %i)", ret, BufferIn, BufferInSize, BufferIn2, BufferInSize2, BufferOut, BufferOutSize, BufferOut2, BufferOutSize2); break; } case IOCTLV_NET_SSL_WRITE: { int ret = mbedtls_ssl_write(&CWII_IPC_HLE_Device_net_ssl::_SSL[sslID].ctx, Memory::GetPointer(BufferOut2), BufferOutSize2); if (SConfig::GetInstance().m_SSLDumpWrite && ret > 0) { std::string filename = File::GetUserPath(D_DUMPSSL_IDX) + SConfig::GetInstance().GetUniqueID() + "_write.bin"; File::IOFile(filename, "ab").WriteBytes(Memory::GetPointer(BufferOut2), ret); } if (ret >= 0) { // Return bytes written or SSL_ERR_ZERO if none Memory::Write_U32((ret == 0) ? SSL_ERR_ZERO : ret, BufferIn); } else { switch (ret) { case MBEDTLS_ERR_SSL_WANT_READ: Memory::Write_U32(SSL_ERR_RAGAIN, BufferIn); if (!nonBlock) ReturnValue = SSL_ERR_RAGAIN; break; case MBEDTLS_ERR_SSL_WANT_WRITE: Memory::Write_U32(SSL_ERR_WAGAIN, BufferIn); if (!nonBlock) ReturnValue = SSL_ERR_WAGAIN; break; default: Memory::Write_U32(SSL_ERR_FAILED, BufferIn); break; } } break; } case IOCTLV_NET_SSL_READ: { int ret = mbedtls_ssl_read(&CWII_IPC_HLE_Device_net_ssl::_SSL[sslID].ctx, Memory::GetPointer(BufferIn2), BufferInSize2); if (SConfig::GetInstance().m_SSLDumpRead && ret > 0) { std::string filename = File::GetUserPath(D_DUMPSSL_IDX) + SConfig::GetInstance().GetUniqueID() + "_read.bin"; File::IOFile(filename, "ab").WriteBytes(Memory::GetPointer(BufferIn2), ret); } if (ret >= 0) { // Return bytes read or SSL_ERR_ZERO if none Memory::Write_U32((ret == 0) ? SSL_ERR_ZERO : ret, BufferIn); } else { switch (ret) { case MBEDTLS_ERR_SSL_WANT_READ: Memory::Write_U32(SSL_ERR_RAGAIN, BufferIn); if (!nonBlock) ReturnValue = SSL_ERR_RAGAIN; break; case MBEDTLS_ERR_SSL_WANT_WRITE: Memory::Write_U32(SSL_ERR_WAGAIN, BufferIn); if (!nonBlock) ReturnValue = SSL_ERR_WAGAIN; break; default: Memory::Write_U32(SSL_ERR_FAILED, BufferIn); break; } } break; } default: break; } } else { Memory::Write_U32(SSL_ERR_ID, BufferIn); } } else { switch (it->net_type) { case IOCTLV_SO_SENDTO: { u32 flags = Memory::Read_U32(BufferIn2 + 0x04); u32 has_destaddr = Memory::Read_U32(BufferIn2 + 0x08); // Not a string, Windows requires a const char* for sendto const char* data = (const char*)Memory::GetPointer(BufferIn); // Act as non blocking when SO_MSG_NONBLOCK is specified forceNonBlock = ((flags & SO_MSG_NONBLOCK) == SO_MSG_NONBLOCK); // send/sendto only handles MSG_OOB flags &= SO_MSG_OOB; sockaddr_in local_name = {0}; if (has_destaddr) { WiiSockAddrIn* wii_name = (WiiSockAddrIn*)Memory::GetPointer(BufferIn2 + 0x0C); WiiSockMan::Convert(*wii_name, local_name); } int ret = sendto(fd, data, BufferInSize, flags, has_destaddr ? (struct sockaddr*)&local_name : nullptr, has_destaddr ? sizeof(sockaddr) : 0); ReturnValue = WiiSockMan::GetNetErrorCode(ret, "SO_SENDTO", true); DEBUG_LOG( WII_IPC_NET, "%s = %d Socket: %08x, BufferIn: (%08x, %i), BufferIn2: (%08x, %i), %u.%u.%u.%u", has_destaddr ? "IOCTLV_SO_SENDTO " : "IOCTLV_SO_SEND ", ReturnValue, fd, BufferIn, BufferInSize, BufferIn2, BufferInSize2, local_name.sin_addr.s_addr & 0xFF, (local_name.sin_addr.s_addr >> 8) & 0xFF, (local_name.sin_addr.s_addr >> 16) & 0xFF, (local_name.sin_addr.s_addr >> 24) & 0xFF); break; } case IOCTLV_SO_RECVFROM: { u32 flags = Memory::Read_U32(BufferIn + 0x04); // Not a string, Windows requires a char* for recvfrom char* data = (char*)Memory::GetPointer(BufferOut); int data_len = BufferOutSize; sockaddr_in local_name; memset(&local_name, 0, sizeof(sockaddr_in)); if (BufferOutSize2 != 0) { WiiSockAddrIn* wii_name = (WiiSockAddrIn*)Memory::GetPointer(BufferOut2); WiiSockMan::Convert(*wii_name, local_name); } // Act as non blocking when SO_MSG_NONBLOCK is specified forceNonBlock = ((flags & SO_MSG_NONBLOCK) == SO_MSG_NONBLOCK); // recv/recvfrom only handles PEEK/OOB flags &= SO_MSG_PEEK | SO_MSG_OOB; #ifdef _WIN32 if (flags & SO_MSG_PEEK) { unsigned long totallen = 0; ioctlsocket(fd, FIONREAD, &totallen); ReturnValue = totallen; break; } #endif socklen_t addrlen = sizeof(sockaddr_in); int ret = recvfrom(fd, data, data_len, flags, BufferOutSize2 ? (struct sockaddr*)&local_name : nullptr, BufferOutSize2 ? &addrlen : nullptr); ReturnValue = WiiSockMan::GetNetErrorCode(ret, BufferOutSize2 ? "SO_RECVFROM" : "SO_RECV", true); INFO_LOG(WII_IPC_NET, "%s(%d, %p) Socket: %08X, Flags: %08X, " "BufferIn: (%08x, %i), BufferIn2: (%08x, %i), " "BufferOut: (%08x, %i), BufferOut2: (%08x, %i)", BufferOutSize2 ? "IOCTLV_SO_RECVFROM " : "IOCTLV_SO_RECV ", ReturnValue, data, fd, flags, BufferIn, BufferInSize, BufferIn2, BufferInSize2, BufferOut, BufferOutSize, BufferOut2, BufferOutSize2); if (BufferOutSize2 != 0) { WiiSockAddrIn* wii_name = (WiiSockAddrIn*)Memory::GetPointer(BufferOut2); WiiSockMan::Convert(local_name, *wii_name, addrlen); } break; } default: break; } } } if (nonBlock || forceNonBlock || (!it->is_ssl && ReturnValue != -SO_EAGAIN && ReturnValue != -SO_EINPROGRESS && ReturnValue != -SO_EALREADY) || (it->is_ssl && ReturnValue != SSL_ERR_WAGAIN && ReturnValue != SSL_ERR_RAGAIN)) { DEBUG_LOG(WII_IPC_NET, "IOCTL(V) Sock: %08x ioctl/v: %d returned: %d nonBlock: %d forceNonBlock: %d", fd, it->is_ssl ? (int)it->ssl_type : (int)it->net_type, ReturnValue, nonBlock, forceNonBlock); WiiSockMan::EnqueueReply(it->_CommandAddress, ReturnValue, ct); it = pending_sockops.erase(it); } else { ++it; } } } void WiiSocket::DoSock(u32 _CommandAddress, NET_IOCTL type) { sockop so = {_CommandAddress, false}; so.net_type = type; pending_sockops.push_back(so); } void WiiSocket::DoSock(u32 _CommandAddress, SSL_IOCTL type) { sockop so = {_CommandAddress, true}; so.ssl_type = type; pending_sockops.push_back(so); } void WiiSockMan::AddSocket(s32 fd) { if (fd >= 0) { WiiSocket& sock = WiiSockets[fd]; sock.SetFd(fd); } } s32 WiiSockMan::NewSocket(s32 af, s32 type, s32 protocol) { s32 fd = (s32)socket(af, type, protocol); s32 ret = GetNetErrorCode(fd, "NewSocket", false); AddSocket(ret); return ret; } s32 WiiSockMan::DeleteSocket(s32 s) { auto socket_entry = WiiSockets.find(s); s32 ReturnValue = socket_entry->second.CloseFd(); WiiSockets.erase(socket_entry); return ReturnValue; } void WiiSockMan::Update() { s32 nfds = 0; fd_set read_fds, write_fds, except_fds; struct timeval t = {0, 0}; FD_ZERO(&read_fds); FD_ZERO(&write_fds); FD_ZERO(&except_fds); auto socket_iter = WiiSockets.begin(); auto end_socks = WiiSockets.end(); while (socket_iter != end_socks) { WiiSocket& sock = socket_iter->second; if (sock.IsValid()) { FD_SET(sock.fd, &read_fds); FD_SET(sock.fd, &write_fds); FD_SET(sock.fd, &except_fds); nfds = std::max(nfds, sock.fd + 1); ++socket_iter; } else { // Good time to clean up invalid sockets. socket_iter = WiiSockets.erase(socket_iter); } } s32 ret = select(nfds, &read_fds, &write_fds, &except_fds, &t); if (ret >= 0) { for (auto& pair : WiiSockets) { WiiSocket& sock = pair.second; sock.Update(FD_ISSET(sock.fd, &read_fds) != 0, FD_ISSET(sock.fd, &write_fds) != 0, FD_ISSET(sock.fd, &except_fds) != 0); } } else { for (auto& elem : WiiSockets) { elem.second.Update(false, false, false); } } } void WiiSockMan::EnqueueReply(u32 CommandAddress, s32 ReturnValue, IPCCommandType CommandType) { // The original hardware overwrites the command type with the async reply type. Memory::Write_U32(IPC_REP_ASYNC, CommandAddress); // IOS also seems to write back the command that was responded to in the FD field. Memory::Write_U32(CommandType, CommandAddress + 8); // Return value Memory::Write_U32(ReturnValue, CommandAddress + 4); WII_IPC_HLE_Interface::EnqueueReply(CommandAddress); } void WiiSockMan::Convert(WiiSockAddrIn const& from, sockaddr_in& to) { to.sin_addr.s_addr = from.addr.addr; to.sin_family = from.family; to.sin_port = from.port; } void WiiSockMan::Convert(sockaddr_in const& from, WiiSockAddrIn& to, s32 addrlen) { to.addr.addr = from.sin_addr.s_addr; to.family = from.sin_family & 0xFF; to.port = from.sin_port; if (addrlen < 0 || addrlen > (s32)sizeof(WiiSockAddrIn)) to.len = sizeof(WiiSockAddrIn); else to.len = addrlen; } void WiiSockMan::UpdateWantDeterminism(bool want) { // If we switched into movie recording, kill existing sockets. if (want) Clean(); } #undef ERRORCODE #undef EITHER
sigmabeta/dolphin
Source/Core/Core/IPC_HLE/WII_Socket.cpp
C++
gpl-2.0
22,315
<?php global $wpdb, $byt_multi_language_count; function bookyourtravel_register_location_post_type() { $locations_permalink_slug = of_get_option('locations_permalink_slug', 'locations'); $labels = array( 'name' => _x( 'Locations', 'Post Type General Name', 'bookyourtravel' ), 'singular_name' => _x( 'Location', 'Post Type Singular Name', 'bookyourtravel' ), 'menu_name' => __( 'Locations', 'bookyourtravel' ), 'all_items' => __( 'All Locations', 'bookyourtravel' ), 'view_item' => __( 'View Location', 'bookyourtravel' ), 'add_new_item' => __( 'Add New Location', 'bookyourtravel' ), 'add_new' => __( 'New Location', 'bookyourtravel' ), 'edit_item' => __( 'Edit Location', 'bookyourtravel' ), 'update_item' => __( 'Update Location', 'bookyourtravel' ), 'search_items' => __( 'Search locations', 'bookyourtravel' ), 'not_found' => __( 'No locations found', 'bookyourtravel' ), 'not_found_in_trash' => __( 'No locations found in Trash', 'bookyourtravel' ), ); $args = array( 'label' => __( 'location', 'bookyourtravel' ), 'description' => __( 'Location information pages', 'bookyourtravel' ), 'labels' => $labels, 'supports' => array( 'title', 'editor', 'thumbnail', 'author', 'page-attributes' ), 'taxonomies' => array( ), 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'show_in_admin_bar' => true, 'can_export' => true, 'has_archive' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'page', 'rewrite' => array('slug' => $locations_permalink_slug) ); register_post_type( 'location', $args ); } function list_locations($location_id = 0, $paged = 0, $per_page = -1, $orderby = '', $order = '', $featured_only = false) { $location_ids = array(); if ($location_id > 0) { $location_ids[] = $location_id; $location_descendants = byt_get_post_descendants($location_id, 'location'); foreach ($location_descendants as $location) { $location_ids[] = $location->ID; } } $args = array( 'post_type' => 'location', 'post_status' => array('publish'), 'posts_per_page' => $per_page, 'paged' => $paged, 'orderby' => $orderby, 'suppress_filters' => false, 'order' => $order, 'meta_query' => array('relation' => 'AND') ); if (count($location_ids) > 0) { $args['meta_query'][] = array( 'key' => 'location_location_post_id', 'value' => $location_ids, 'compare' => 'IN' ); } if (isset($featured_only) && $featured_only) { $args['meta_query'][] = array( 'key' => 'location_is_featured', 'value' => 1, 'compare' => '=', 'type' => 'numeric' ); } $posts_query = new WP_Query($args); $locations = array(); if ($posts_query->have_posts() ) { while ( $posts_query->have_posts() ) { global $post; $posts_query->the_post(); $locations[] = $post; } } $results = array( 'total' => $posts_query->found_posts, 'results' => $locations ); wp_reset_postdata(); return $results; }
stanleyr15/samter
wp-content/themes/BookYourTravel/includes/post_types/locations.php
PHP
gpl-2.0
3,435
from django import template from django.template.loader_tags import BaseIncludeNode from django.template import Template from django.conf import settings from pages.plugins import html_to_template_text, SearchBoxNode from pages.plugins import LinkNode, EmbedCodeNode from pages import models from django.utils.text import unescape_string_literal from pages.models import Page, slugify from django.core.urlresolvers import reverse register = template.Library() @register.filter def name_to_url(value): return models.name_to_url(value) name_to_url.is_safe = True class PageContentNode(BaseIncludeNode): def __init__(self, html_var, render_plugins=True, *args, **kwargs): super(PageContentNode, self).__init__(*args, **kwargs) self.html_var = template.Variable(html_var) self.render_plugins = render_plugins def render(self, context): try: html = unicode(self.html_var.resolve(context)) t = Template(html_to_template_text(html, context, self.render_plugins)) return self.render_template(t, context) except: if settings.TEMPLATE_DEBUG: raise return '' class IncludeContentNode(BaseIncludeNode): """ Base class for including some named content inside a other content. Subclass and override get_content() and get_title() to return HTML or None. The name of the content to include is stored in self.name All other parameters are stored in self.args, without quotes (if any). """ def __init__(self, parser, token, *args, **kwargs): super(IncludeContentNode, self).__init__(*args, **kwargs) bits = token.split_contents() if len(bits) < 2: raise template.TemplateSyntaxError, ('%r tag requires at least one' ' argument' % token.contents.split()[0]) self.args = [] for b in bits[1:]: if is_quoted(b): b = unescape_string_literal(b) self.args.append(b) self.name = self.args.pop(0) def get_content(self, context): """ Override this to return content to be included. """ return None def get_title(self, context): """ Override this to return a title or None to omit it. """ return self.name def render(self, context): try: template_text = '' if 'showtitle' in self.args: title = self.get_title(context) if title: template_text += '<h2>%s</h2>' % title template_text += self.get_content(context) template = Template(template_text) return self.render_template(template, context) except: if settings.TEMPLATE_DEBUG: raise return '' class IncludePageNode(IncludeContentNode): def __init__(self, *args, **kwargs): super(IncludePageNode, self).__init__(*args, **kwargs) try: self.page = Page.objects.get(slug__exact=slugify(self.name)) except Page.DoesNotExist: self.page = None def get_title(self, context): if not self.page: return None return ('<a href="%s">%s</a>' % (self.get_page_url(), self.page.name)) def get_page_url(self): if self.page: slug = self.page.pretty_slug else: slug = name_to_url(self.name) return reverse('pages:show', args=[slug]) def get_content(self, context): if not self.page: return ('<p class="plugin includepage">Unable to include ' '<a href="%s" class="missing_link">%s</a></p>' % (self.get_page_url(), self.name)) # prevent endless loops context_page = context['page'] include_stack = context.get('_include_stack', []) include_stack.append(context_page.name) if self.page.name in include_stack: return ('<p class="plugin includepage">Unable to' ' include <a href="%s">%s</a>: endless include' ' loop.</p>' % (self.get_page_url(), self.page.name)) context['_include_stack'] = include_stack context['page'] = self.page template_text = html_to_template_text(self.page.content, context) # restore context context['_include_stack'].pop() context['page'] = context_page return template_text @register.tag(name='render_plugins') def do_render_plugins(parser, token, render_plugins=True): """ Render tags and plugins """ try: tag, html_var = token.split_contents() except ValueError: raise template.TemplateSyntaxError, ("%r tag requires one argument" % token.contents.split()[0]) return PageContentNode(html_var, render_plugins) @register.tag(name='render_tags') def do_render_tags(parser, token): """ Render tags only, does not render plugins """ return do_render_plugins(parser, token, render_plugins=False) @register.tag(name='include_page') def do_include_page(parser, token): return IncludePageNode(parser, token) def is_quoted(text): return text[0] == text[-1] and text[0] in ('"', "'") @register.tag(name='embed_code') def do_embed_code(parser, token): nodelist = parser.parse(('endembed_code',)) parser.delete_first_token() return EmbedCodeNode(nodelist) @register.tag(name='searchbox') def do_searchbox(parser, token): try: tag, query = token.split_contents() except ValueError: raise template.TemplateSyntaxError('%r tag requires one argument' % token.contents.split()[0]) if not is_quoted(query): raise template.TemplateSyntaxError( "%r tag's argument should be in quotes" % token.contents.split()[0]) return SearchBoxNode(query=unescape_string_literal(query)) @register.tag(name='link') def do_link(parser, token): try: tag, href = token.split_contents() except ValueError: raise template.TemplateSyntaxError("%r tag requires one argument" % token.contents.split()[0]) if not is_quoted(href): raise template.TemplateSyntaxError( "%r tag's argument should be in quotes" % token.contents.split()[0]) nodelist = parser.parse(('endlink',)) parser.delete_first_token() return LinkNode(unescape_string_literal(href), nodelist)
mivanov/editkit
editkit/pages/templatetags/pages_tags.py
Python
gpl-2.0
6,764
from opencvBuilder import exists,generate
bverhagen/openCV-sconsbuilder
opencvBuilder/__init__.py
Python
gpl-2.0
42
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "umiss_project.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
CadeiraCuidadora/UMISS-backend
umiss_project/manage.py
Python
gpl-3.0
811
package ru.ncedu.ecomm.servlets.services.passwordRecovery; import ru.ncedu.ecomm.data.models.dao.UserDAOObject; import java.util.ArrayList; import java.util.List; import java.util.Random; import static ru.ncedu.ecomm.data.DAOFactory.getDAOFactory; public class PasswordRecoveryService { private final static String ERROR_FOUND_EMAIL = "ErrorEmailNotFound"; private final static String SUCCESS_SEND = "SuccessSend"; private final static String ERROR_SEND = "ErrorSend"; private final static int MAX_HASH = 10; private final static int MAX_NUMBER = 9; private PasswordRecoveryService() { } private static PasswordRecoveryService instance; public static synchronized PasswordRecoveryService getInstance() { if (instance == null) { instance = new PasswordRecoveryService(); } return instance; } public String sendMailToUser(String toEmail, String contextPath) { UserDAOObject userByEmail = getDAOFactory().getUserDAO().getUserByEmail(toEmail); if (userByEmail == null) return ERROR_FOUND_EMAIL; userByEmail.setRecoveryHash(getRecoveryHash()); return sendMailToUser(userByEmail, contextPath); } private String getRecoveryHash() { String recoveryHash; UserDAOObject userByHash; do { recoveryHash = generateRecoveryHash(); userByHash = getDAOFactory().getUserDAO().getUserByRecoveryHash(recoveryHash); } while (userByHash != null); return recoveryHash; } private String generateRecoveryHash() { List<Integer> uniqueHashCollection = new ArrayList<>(); addHashToCollection(uniqueHashCollection); return getHashFromCollection(uniqueHashCollection); } private void addHashToCollection(List<Integer> uniqueHash) { Random random = new Random(); while (uniqueHash.size() < MAX_HASH) { uniqueHash.add(random.nextInt(MAX_NUMBER)); } } private String getHashFromCollection(List<Integer> uniqueHashCollection) { StringBuilder recoveryHash = new StringBuilder(MAX_HASH); for (int hash : uniqueHashCollection) { recoveryHash.append(hash); } return recoveryHash.toString(); } private String sendMailToUser(UserDAOObject user, String contextPath) { String textHTML = getTextHtml(user.getEmail(), user.getRecoveryHash(), contextPath); getDAOFactory().getUserDAO().updateUser(user); return SendMailService.getInstance().isSentLetterToEmail(user.getEmail(), textHTML) ? SUCCESS_SEND : ERROR_SEND; } private String getTextHtml(String toEmail, String recoveryHash, String contextPath) { return "<p>Please change your password in here:</p>" + "<a href='" + contextPath + "/passwordChange?email=" + toEmail + "&recoveryHash=" + recoveryHash + "'>Change Password</a>"; } }
ncedu-tlt/ecomm
src/main/java/ru/ncedu/ecomm/servlets/services/passwordRecovery/PasswordRecoveryService.java
Java
gpl-3.0
2,999
using System; using System.Globalization; #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP using Windows.UI; using Windows.UI.Xaml.Media; #endif #if WINDOWS_DESKTOP using System.Windows.Data; using System.Windows.Media; #endif namespace SmokSmog.Extensions { public static class ColorExtensions { public static Color ToColor(this string color) { if (string.IsNullOrWhiteSpace(color) || color[0] != '#') throw new ArgumentException(nameof(color)); color = color.Replace("#", ""); switch (color.Length) { case 6: return Color.FromArgb(255, byte.Parse(color.Substring(0, 2), NumberStyles.HexNumber), byte.Parse(color.Substring(2, 2), NumberStyles.HexNumber), byte.Parse(color.Substring(4, 2), NumberStyles.HexNumber)); case 8: return Color.FromArgb( byte.Parse(color.Substring(0, 2), NumberStyles.HexNumber), byte.Parse(color.Substring(2, 2), NumberStyles.HexNumber), byte.Parse(color.Substring(4, 2), NumberStyles.HexNumber), byte.Parse(color.Substring(6, 2), NumberStyles.HexNumber)); } throw new ArgumentException(nameof(color)); } public static Brush ToBrush(this string color) { return new SolidColorBrush(color.ToColor()); } } }
SmokSmog/smoksmog-windows
Core/SmokSmog.Core.Shared/Extensions/ColorExtensions.cs
C#
gpl-3.0
1,547
// just-install - The simple package installer for Windows // Copyright (C) 2020 just-install authors. // // 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, see <http://www.gnu.org/licenses/>. // Package fetch provides functions to reference and download local and remote resources addressed // by URLs. It provides functionality similar in spirit to wget and curl. package fetch
just-install/just-install
pkg/fetch/doc.go
GO
gpl-3.0
891
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file DownloadView.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "DownloadView.h" #include <QtWidgets> #include <QtCore> #include <libethereum/DownloadMan.h> #include "Grapher.h" using namespace std; using namespace dev; using namespace dev::eth; DownloadView::DownloadView(QWidget* _p): QWidget(_p) { } void DownloadView::paintEvent(QPaintEvent*) { QPainter p(this); p.fillRect(rect(), Qt::white); if (!m_man || m_man->chain().empty() || !m_man->subCount()) return; double ratio = (double)rect().width() / rect().height(); if (ratio < 1) ratio = 1 / ratio; double n = min(rect().width(), rect().height()) / ceil(sqrt(m_man->chain().size() / ratio)); // QSizeF area(rect().width() / floor(rect().width() / n), rect().height() / floor(rect().height() / n)); QSizeF area(n, n); QPointF pos(0, 0); auto const& bg = m_man->blocksGot(); for (unsigned i = bg.all().first, ei = bg.all().second; i < ei; ++i) { int s = -2; if (bg.contains(i)) s = -1; else { unsigned h = 0; m_man->foreachSub([&](DownloadSub const& sub) { if (sub.asked().contains(i)) s = h; h++; }); } unsigned dh = 360 / m_man->subCount(); if (s == -2) p.fillRect(QRectF(QPointF(pos) + QPointF(3 * area.width() / 8, 3 * area.height() / 8), area / 4), Qt::black); else if (s == -1) p.fillRect(QRectF(QPointF(pos) + QPointF(1 * area.width() / 8, 1 * area.height() / 8), area * 3 / 4), Qt::black); else p.fillRect(QRectF(QPointF(pos) + QPointF(1 * area.width() / 8, 1 * area.height() / 8), area * 3 / 4), QColor::fromHsv(s * dh, 64, 128)); pos.setX(pos.x() + n); if (pos.x() >= rect().width() - n) pos = QPoint(0, pos.y() + n); } }
arkpar/cpp-ethereum
alethzero/DownloadView.cpp
C++
gpl-3.0
2,368
<?php /** * Properties * * @package Cherry_Framework * @subpackage Model * @author Cherry Team <cherryframework@gmail.com> * @copyright Copyright (c) 2012 - 2016, Cherry Team * @link http://www.cherryframework.com/ * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html */ /** * Model properties */ class Model_Properties { /** * Get all properties * * @param [type] $atts atriibutes. * @return array properties */ public static function get_properties( $atts = array() ) { $args = array( 'posts_per_page' => 20, 'offset' => 0, 'tax_query' => array(), 'orderby' => 'date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'property', 'post_mime_type' => '', 'post_parent' => '', 'author' => '', 'post_status' => 'publish', 'suppress_filters' => true, ); $args = array_merge( $args, $atts ); if ( $args['offset'] <= 0 ) { $args['offset'] = max( 0, get_query_var( 'paged' ) ); } $single_page = Model_Settings::get_search_single_page(); $properties = (array) get_posts( $args ); if ( count( $properties ) ) { foreach ( $properties as &$property ) { $property->meta = get_metadata( 'post', $property->ID, '', true ); $property->images = self::get_all_post_images( $property->ID ); $property->image = self::get_image( $property->ID ); $property->gallery = self::get_gallery( $property->ID ); $property->status = self::get_property_status( $property->ID ); $property->price = self::get_price( $property->ID ); $property->type = self::get_type( $property->ID ); $property->bathrooms = self::get_bathrooms( $property->ID ); $property->bedrooms = self::get_bedrooms( $property->ID ); $property->area = self::get_area( $property->ID ); $property->tags = self::get_property_tags( $property->ID ); $property->types = self::get_property_types( $property->ID ); $property->url = $single_page . '?id=' . $property->ID; $property->address = self::get_address( $property->ID ); $property->lat = self::get_lat( $property->ID ); $property->lng = self::get_lng( $property->ID ); } } return $properties; } /** * Get total properties count * * @return total properties count. */ public static function get_total_count( $atts = array() ) { unset( $atts['posts_per_page'], $atts['offset'] ); $args = array( 'posts_per_page' => -1, 'offset' => 0, 'fields' => 'ids', 'orderby' => 'date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'property', 'post_mime_type' => '', 'post_parent' => '', 'author' => '', 'post_status' => 'publish', 'suppress_filters' => true, ); $args = array_merge( $args, $atts ); return count( get_posts( $args ) ); } /** * Shortcode properties * * @param [type] $atts attributes. * @return html code. */ public static function prepare_param_properties( $atts ) { if ( is_array( $atts ) ) { if ( ! empty( $atts['orderby'] ) ) { $atts['orderby'] = $atts['orderby']; } else { $atts['orderby'] = 'date'; } if ( ! empty( $atts['order'] ) ) { $atts['order'] = $atts['order']; } else { $atts['order'] = 'desc'; } if ( ! empty( $atts['limit'] ) ) { $atts['posts_per_page'] = $atts['limit']; unset( $atts['limit'] ); } else { $atts['posts_per_page'] = 5; } if ( ! empty( $atts['id'] ) ) { $atts['include'] = explode( ',', $atts['id'] ); unset( $atts['id'] ); } if ( ! empty( $atts['keyword'] ) ) { $atts['s'] = $atts['keyword']; unset( $atts['keyword'] ); } if ( ! empty( $atts['type'] ) ) { $atts['tax_query'][] = array( 'taxonomy' => 'property-type', 'field' => 'term_id', 'terms' => (int) $atts['type'], ); unset( $atts['property_type'] ); } if ( ! empty( $atts['location'] ) ) { $atts['tax_query'][] = array( 'taxonomy' => 'location', 'field' => 'term_id', 'terms' => (int) $atts['location'], ); unset( $atts['location'] ); } if ( ! empty( $atts['tag'] ) ) { $atts['tax_query'][] = array( 'taxonomy' => 'property-tag', 'field' => 'term_id', 'terms' => (int) $atts['tag'], ); unset( $atts['tag'] ); } $atts['meta_query']['relation'] = 'AND'; if ( ! empty( $atts['property_status'] ) ) { $atts['meta_query'][] = array( 'key' => 'status', 'value' => (string) $atts['property_status'], 'compare' => '=', ); unset( $atts['property_status'] ); } if ( ! empty( $atts['min_price'] ) ) { $atts['meta_query'][] = array( 'key' => 'price', 'value' => (int) $atts['min_price'], 'type' => 'numeric', 'compare' => '>=', ); unset( $atts['min_price'] ); } if ( ! empty( $atts['max_price'] ) ) { $atts['meta_query'][] = array( 'key' => 'price', 'value' => (int) $atts['max_price'], 'type' => 'numeric', 'compare' => '<=', ); unset( $atts['min_price'] ); } if ( ! empty( $atts['min_bathrooms'] ) ) { $atts['meta_query'][] = array( 'key' => 'bathrooms', 'value' => (int) $atts['min_bathrooms'], 'type' => 'numeric', 'compare' => '>=', ); unset( $atts['min_bathrooms'] ); } if ( ! empty( $atts['status'] ) ) { $atts['meta_query'][] = array( 'key' => 'status', 'value' => esc_attr( $atts['status'] ), 'compare' => '=', ); unset( $atts['status'] ); } if ( ! empty( $atts['max_bathrooms'] ) ) { $atts['meta_query'][] = array( 'key' => 'bathrooms', 'value' => (int) $atts['max_bathrooms'], 'type' => 'numeric', 'compare' => ' <=', ); unset( $atts['max_bathrooms'] ); } if ( ! empty( $atts['min_bedrooms'] ) ) { $atts['meta_query'][] = array( 'key' => 'bedrooms', 'value' => (int) $atts['min_bedrooms'], 'type' => 'numeric', 'compare' => '>=', ); unset( $atts['min_bedrooms'] ); } if ( ! empty( $atts['max_bedrooms'] ) ) { $atts['meta_query'][] = array( 'key' => 'bedrooms', 'value' => (int) $atts['max_bedrooms'], 'type' => 'numeric', 'compare' => '<=', ); unset( $atts['max_bedrooms'] ); } if ( ! empty( $atts['min_area'] ) ) { $atts['meta_query'][] = array( 'key' => 'area', 'value' => (int) $atts['min_area'], 'type' => 'numeric', 'compare' => '>=', ); unset( $atts['min_area'] ); } if ( ! empty( $atts['max_area'] ) ) { $atts['meta_query'][] = array( 'key' => 'area', 'value' => (int) $atts['max_area'], 'type' => 'numeric', 'compare' => '<=', ); unset( $atts['max_area'] ); } if ( ! empty( $atts['agent'] ) ) { $atts['meta_query'][] = array( 'key' => 'agent', 'value' => (int) $atts['agent'], 'compare' => '=', ); unset( $atts['agent'] ); } } else { $atts = array( 'posts_per_page' => 5, ); } return $atts; } /** * Shortcode properties * * @return html code. */ public static function shortcode_search_result( $atts ) { $atts = shortcode_atts( array( 'show_sorting' => 'no', 'order' => 'desc', ), $atts ); $atts = array_merge( $atts, $_GET ); $form = self::shortcode_search_form( $atts ); $properties = self::shortcode_properties( $atts ); return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/search-result.php', array( 'form' => $form, 'properties' => $properties, 'area_unit' => Model_Settings::get_area_unit_title(), ) ); } /** * Shortcode properties * * @param [type] $atts attributes. * @return html code. */ public static function shortcode_properties( $atts ) { $atts = shortcode_atts( array( 'show_sorting' => 'no', 'orderby' => 'date', 'order' => 'desc', ), $atts ); $atts = array_merge( $atts, $_GET ); $atts = self::prepare_param_properties( $atts ); $properties = (array) self::get_properties( $atts ); $show_sorting = 'no'; $order_html = ''; if ( ! empty( $atts['show_sorting'] ) ) { $show_sorting = $atts['show_sorting']; if ( 'yes' == $atts['show_sorting'] ) { $order_html = self::properties_order(); } } return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/properties.php', array( 'properties' => $properties, 'show_sorting' => $show_sorting, 'order_html' => $order_html, 'pagination' => self::get_pagination( $atts, $atts['posts_per_page'] ), 'area_unit' => Model_Settings::get_area_unit_title(), 'currency_symbol' => Model_Settings::get_currency_symbol(), ) ); } /** * Get html of order links * * @return string html */ private static function properties_order() { $orderby = ! empty( $_GET['orderby'] ) ? $_GET['orderby'] : 'date'; $order = ! empty( $_GET['order'] ) ? $_GET['order'] : 'desc'; unset( $_GET['orderby'], $_GET['order'] ); $query_string = '?' . build_query( $_GET ); $reverse = 'desc'; if ( 'desc' == $order ) { $reverse = 'asc'; } return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/order.php', array( 'query_string' => $query_string, 'orderby' => $orderby, 'order' => $order, 'reverse' => $reverse, ) ); } /** * Get all addresses * * @return [array] properties address. */ public static function get_addresses() { $result = array(); $properties = (array) self::get_properties( array( 'meta_query' => array( array( 'key' => 'address', 'value' => '', 'compare' => '!=', ), ), ) ); if ( count( $properties ) ) { foreach ( $properties as &$p ) { array_push( $result, array( 'id' => $p->ID, 'address' => $p->address, 'lat' => $p->lat, 'lng' => $p->lng, ) ); } } return $result; } /** * Shortcode google map * with all property items. * * @return [string] map view. */ public static function shortcode_map() { return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/map.php', array( 'addresses' => self::get_addresses(), 'addresses_json' => json_encode( self::get_addresses() ), 'property_settings' => json_encode( array( 'base_url' => sprintf( '%s?id=', Model_Settings::get_search_single_page() ), ) ), ) ); } /** * Publish hidden * * @param [int] $id post. */ public static function publish_hidden( $id ) { $id = (int) $id; $post = get_post( $id ); if ( $post ) { $post->post_status = 'publish'; wp_update_post( $post ); } } /** * Add new properties * * @param [type] $attr attributes. * @return html code. */ public static function add_property( $attr ) { if ( current_user_can( 'administrator' ) || current_user_can( 're_agent' ) ) { $property_status = 'publish'; } else { $property_status = 'draft'; } $property = array( 'post_title' => $attr['title'], 'post_author' => get_current_user_id(), 'post_content' => $attr['description'], 'post_status' => $property_status, 'post_type' => 'property', ); $property = sanitize_post( $property, 'db' ); return wp_insert_post( $property ); } /** * Contact form assets */ public static function property_single_assets() { wp_enqueue_script( 'swipe', plugins_url( 'tm-real-estate' ) . '/assets/js/swiper.min.js', array( 'jquery' ), '1.0.0', true ); wp_enqueue_script( 'tm-re-property-gallery', plugins_url( 'tm-real-estate' ) . '/assets/js/property-gallery.min.js', array( 'jquery' ), '1.0.0', true ); wp_enqueue_style( 'swiper', plugins_url( 'tm-real-estate' ) . '/assets/css/swiper.min.css', array(), '3.3.0', 'all' ); wp_enqueue_style( 'tm-re-property-gallery', plugins_url( 'tm-real-estate' ) . '/assets/css/property-gallery.min.css', array(), '1.0.0', 'all' ); } /** * Shortcode property item * * @return html code. */ public static function shortcode_property_single() { if ( ! empty( $_GET['id'] ) && is_numeric( $_GET['id'] ) ) { self::property_single_assets(); $id = $_GET['id']; $properties = (array) self::get_properties( array( 'include' => $id, 'limit' => 1 ) ); $property = $properties[0]; $contact_form = self::agent_contact_form( null, $id ); return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/property.php', array( 'property' => $property, 'contact_form' => $contact_form, 'area_unit' => Model_Settings::get_area_unit_title(), 'currency_symbol' => Model_Settings::get_currency_symbol(), ) ); } } /** * Shortcode tm-re-search-form * * @return html code. */ public static function shortcode_search_form( $atts ) { $default_value = array( 'keyword' => '', 'min_price' => '', 'max_price' => '', 'min_bedrooms' => '', 'max_bedrooms' => '', 'min_bathrooms' => '', 'max_bathrooms' => '', 'min_area' => '', 'max_area' => '', 'property_status' => '', 'property_type' => '', 'show_sorting' => 'no', 'orderby' => 'date', ); $values = array_merge( $default_value, $_GET, $atts ); $action_url = Model_Settings::get_search_result_page(); return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/search-form.php', array( 'property_statuses' => self::get_allowed_property_statuses(), 'property_types' => self::get_all_property_types(), 'action_url' => $action_url, 'values' => $values, 'locations' => Model_Submit_Form::get_locations(), ) ); } /** * Agent contact form shortcode * * @return html code. */ public static function shortcode_contact_form( $atts ) { if ( empty( $atts['agent_id'] ) && empty( $atts['property_id'] ) ) { return; } $property_id = null; if ( ! empty( $atts['property_id'] ) ) { $property_id = $atts['property_id']; } $agent_id = null; if ( ! empty( $atts['agent_id'] ) ) { $agent_id = $atts['agent_id']; } else { $agent_id = get_post_meta( $property_id, 'agent', true ); } return self::agent_contact_form( $agent_id, $property_id ); } /** * Agent contact form shortcode * * @return html code. */ public static function shortcode_agent_properties( $atts ) { if ( ! is_array( $atts ) ) { $atts = array(); } if ( empty( $atts['agent_id'] ) && empty( $atts['property_id'] ) && empty( $_GET['agent_id'] ) && empty( $_GET['property_id'] ) ) { return; } $atts = array_merge( $atts, $_GET ); $property_id = null; if ( ! empty( $atts['property_id'] ) ) { $property_id = $atts['property_id']; } $agent_id = null; if ( ! empty( $atts['agent_id'] ) ) { $agent_id = $atts['agent_id']; } else { $agent_id = get_post_meta( $property_id, 'agent', true ); } $args = array( 'agent' => $agent_id ); $args = array_merge( $atts, $args ); $contact_form_html = self::agent_contact_form( $agent_id, $property_id ); $properties_html = self::shortcode_properties( $args ); return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/agent-properties.php', array( 'contact_form_html' => $contact_form_html, 'properties_html' => $properties_html, ) ); } /** * Contact form assets */ public static function contact_form_assets() { $contact_form_settings = Model_Settings::get_contact_form_settings(); wp_enqueue_script( 'google-captcha', 'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit', null, '1.0.0', false ); wp_enqueue_script( 'tm-real-state-contact-form', plugins_url( 'tm-real-estate' ) . '/assets/js/contact-form.min.js', array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'tm-real-state-contact-form', 'TMREContactForm', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'successMessage' => $contact_form_settings['success-message'], 'failedMessage' => $contact_form_settings['failed-message'], 'captchaKey' => ! empty( $contact_form_settings['google-captcha-key'] ) ? $contact_form_settings['google-captcha-key'] : '', ) ); wp_enqueue_style( 'tm-real-contact-form', plugins_url( 'tm-real-estate' ) . '/assets/css/contact-form.min.css', array(), '1.0.0', 'all' ); } /** * Agent contact form * * @return html code. */ public static function agent_contact_form( $agent_id, $property_id ) { self::contact_form_assets(); if ( empty( $agent_id ) ) { if ( empty( $property_id ) ) { return; } $agent_id = get_post_meta( $property_id, 'agent', true ); } $agent_id = max( (int) $agent_id, 1 ); $user_data = get_userdata( $agent_id ); $agent_page = Model_Settings::get_agent_properties_page() . '?agent_id=' . $agent_id; return Cherry_Core::render_view( TM_REAL_ESTATE_DIR . 'views/contact-form.php', array( 'agent' => $user_data->data, 'property_id' => $property_id, 'agent_page' => $agent_page, ) ); } /** * Get property price * * @param [type] $post_id id. * @return string property price. */ public static function get_price( $post_id ) { return (float) get_post_meta( $post_id, 'price', true ); } /** * Get property type * * @param [type] $post_id id. * @return string property type. */ public static function get_type( $post_id ) { return (string) get_post_meta( $post_id, 'type', true ); } /** * Get property address * * @param [integer] $post_id id. * @return string property address. */ public static function get_address( $post_id ) { return (string) get_post_meta( $post_id, 'address', true ); } /** * Get property lat * * @param [integer] $post_id id. * @return string property lat. */ public static function get_lat( $post_id ) { return (float) get_post_meta( $post_id, 'lat', true ); } /** * Get property lng * * @param [integer] $post_id id. * @return string property lng. */ public static function get_lng( $post_id ) { return (float) get_post_meta( $post_id, 'lng', true ); } /** * Get property bathrooms * * @param [type] $post_id id. * @return string property bathrooms. */ public static function get_bathrooms( $post_id ) { return (float) get_post_meta( $post_id, 'bathrooms', true ); } /** * Get property bedrooms * * @param [type] $post_id id. * @return string property bedrooms. */ public static function get_bedrooms( $post_id ) { return (float) get_post_meta( $post_id, 'bedrooms', true ); } /** * Get property area * * @param [type] $post_id id. * @return string property area. */ public static function get_area( $post_id ) { return (float) get_post_meta( $post_id, 'area', true ); } /** * Get property status * * @param [type] $post_id id. * @return string property status. */ public static function get_property_status( $post_id ) { $allowed = self::get_allowed_property_statuses(); $type = (string) get_post_meta( $post_id, 'status', true ); if ( array_key_exists( $type, $allowed ) ) { return $type; } return end( $allowed ); } /** * Get allowed property statuses * * @return array property statuses. */ public static function get_allowed_property_statuses() { return array( 'rent' => __( 'Rent', 'tm-real-estate' ), 'sale' => __( 'Sale', 'tm-real-estate' ), ); } /** * Get all property types * * @return array */ public static function get_all_property_types() { return get_terms( array( 'property-type' ), array( 'hide_empty' => false, 'orderby' => 'term_group', ) ); } /** * Get gallery * * @param [type] $post_id id. * @return property gallery. */ public static function get_gallery( $post_id ) { $gallery = get_post_meta( $post_id, 'gallery', true ); if ( array_key_exists( 'image', (array) $gallery ) ) { foreach ( $gallery['image'] as &$image ) { $image = self::get_all_images( $image ); } } return $gallery; } /** * Get property image * * @param [type] $post_id property id. * @return string image. */ public static function get_image( $post_id ) { $images = self::get_all_post_images( $post_id ); if ( array_key_exists( 'medium', $images ) ) { return $images['medium'][0]; } return TM_REAL_ESTATE_URI.'assets/images/placehold.png'; } /** * Get type list of property * * @param [type] $post_id property id. * @return array list */ public static function get_property_types( $post_id ) { $types = wp_get_post_terms( $post_id, 'property-type' ); $list = array(); if ( ! empty( $types ) && is_array( $types ) ) { foreach ( $types as $type ) { $list[] = $type->name; } } return $list; } /** * Get tags list of property * * @param [type] $post_id property id. * @return array list */ public static function get_property_tags( $post_id ) { $tags = wp_get_post_terms( $post_id, 'property-tag' ); $list = array(); if ( ! empty( $tags ) && is_array( $tags ) ) { foreach ( $tags as $tag ) { $list[] = $tag->name; } } return $list; } /** * Get all post images * * @param [type] $post_id post id. * @return array all post images. */ public static function get_all_post_images( $post_id ) { if ( has_post_thumbnail( $post_id ) ) { $attachment_id = get_post_thumbnail_id( $post_id ); return self::get_all_images( $attachment_id ); } return array(); } /** * Get all images by attachmen id * * @param [type] $attachment_id id. * @return array size => image */ public static function get_all_images( $attachment_id ) { $result = array(); $sizes = get_intermediate_image_sizes(); if ( is_array( $sizes ) && count( $sizes ) ) { foreach ( $sizes as $size ) { $result[ $size ] = wp_get_attachment_image_src( $attachment_id, $size ); } } return $result; } /** * Get propeties pagination array * * @param [type] array $atts parameters. * @param [type] integer $posts_per_page properties per page. * @return array pagination. */ public static function get_pagination( $atts = array(), $posts_per_page = 5 ) { $big = 99999; $args = array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?page=%#%', 'total' => self::get_total_pages( $atts, $posts_per_page ), 'current' => max( 1, get_query_var( 'paged' ) ), 'show_all' => false, 'end_size' => 0, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => __( '« Previous' ), 'next_text' => __( 'Next »' ), 'type' => 'array', 'add_args' => false, 'add_fragment' => '', 'before_page_number' => '', 'after_page_number' => '', ); return paginate_links( $args ); } /** * Get total pages count * * @param [type] array $atts parameters. * @param [type] integer $posts_per_page properties per page. * @return total pages. */ public static function get_total_pages( $atts = array(), $posts_per_page = 5 ) { return ceil( self::get_total_count( $atts ) / $posts_per_page ); } /** * Get Types of properties * * @param type integer $parent ID of parent types. * @return total pages. */ public static function get_types( $parent = 0 ) { $terms = get_terms( 'property-type', array( 'parent' => $parent, 'hide_empty' => false ) ); if ( count( $terms ) > 0 ) { foreach ( $terms as $term ) { $child = Model_Properties::get_types( $term->term_id ); $types[] = array( 'term_id' => $term->term_id, 'name' => $term->name, 'child' => $child, ); } return $types; } return false; } /** * Get latitude and longitude from address. * * @param [string] $address item. * @return [array] array( $lat, $lng ) */ public static function get_lat_lng( $address ) { $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode( $address ); $body = false; $lat = 0; $lng = 0; $response = wp_remote_request( $url ); if ( array_key_exists( 'body', $response ) ) { $body = json_decode( $response['body'], true ); $lat = $body['results'][0]['geometry']['location']['lat']; $lng = $body['results'][0]['geometry']['location']['lng']; } return array( $lat, $lng ); } }
gcofficial/tm-real-estate
models/model-properties.php
PHP
gpl-3.0
24,916
class PublicDisclosureScope < Scope # Disclosed to the public def is_in_scope(user) # Will allow anyone to see true end def is_in_pitch_card_scope(user, pitch_card) is_in_scope(user) end def is_in_comment_scope(user, comment) is_in_scope(user) end end
mrwinton/pitchhub
app/models/disclosure_scopes/public_disclosure_scope.rb
Ruby
gpl-3.0
286
#include "logger/Stack.hpp" using namespace logger; /////////////////////////////////////// std::ostream& operator<<(std::ostream& ioOut, const Stack& stack) { if (stack.empty()) return ioOut; std::deque<std::string>::const_iterator dequeIt; for(dequeIt = stack.begin(); dequeIt != stack.end(); ++dequeIt) { if (dequeIt != stack.begin()) ioOut << "_"; ioOut << *dequeIt; } return ioOut; }
belzano/MDW
logger/src/Stack.cpp
C++
gpl-3.0
415
/* * Copyright 2015 @author Unai Alegre * * This file is part of R-CASE (Requirements for Context-Aware Systems Engineering), a module * of Modelio that aids the requirements elicitation phase of a Context-Aware System (C-AS). * * R-CASE 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. * * R-CASE 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 Modelio. If not, see <http://www.gnu.org/licenses/>. * */ package edu.casetools.rcase.modelio.diagrams.requirements.tools.relations; import org.modelio.api.modelio.diagram.IDiagramGraphic; import org.modelio.api.modelio.diagram.IDiagramHandle; import org.modelio.metamodel.uml.infrastructure.Dependency; import org.modelio.metamodel.uml.infrastructure.ModelElement; import edu.casetools.rcase.modelio.diagrams.RelationTool; import edu.casetools.rcase.module.api.RCaseStereotypes; import edu.casetools.rcase.module.impl.RCaseModule; import edu.casetools.rcase.module.impl.RCasePeerModule; import edu.casetools.rcase.utils.ElementUtils; /** * The Class SatisfyTool is the tool for creating a Satisfy relation. */ public class SatisfyTool extends RelationTool { /* * (non-Javadoc) * * @see * org.modelio.api.diagram.tools.DefaultLinkTool#acceptFirstElement(org. * modelio.api.diagram.IDiagramHandle, * org.modelio.api.diagram.IDiagramGraphic) */ @Override public boolean acceptFirstElement(IDiagramHandle representation, IDiagramGraphic target) { return acceptAnyElement(target); } /* * (non-Javadoc) * * @see * org.modelio.api.diagram.tools.DefaultLinkTool#acceptSecondElement(org * .modelio.api.diagram.IDiagramHandle, * org.modelio.api.diagram.IDiagramGraphic, * org.modelio.api.diagram.IDiagramGraphic) */ @Override public boolean acceptSecondElement(IDiagramHandle representation, IDiagramGraphic source, IDiagramGraphic target) { return acceptElement(RCasePeerModule.MODULE_NAME, target, RCaseStereotypes.STEREOTYPE_REQUIREMENT); } /* * (non-Javadoc) * * @see edu.casesuite.modelio.diagrams.RelationTool# * createDependency(org.modelio.metamodel.uml.infrastructure.ModelElement, * org.modelio.metamodel.uml.infrastructure.ModelElement) */ @Override public Dependency createDependency(ModelElement originElement, ModelElement targetElement) { return ElementUtils.getInstance().createDependency(RCaseModule.getInstance(), RCasePeerModule.MODULE_NAME, originElement, targetElement, RCaseStereotypes.STEREOTYPE_SATISFY); } }
casetools/rcase
rcase/src/main/java/edu/casetools/rcase/modelio/diagrams/requirements/tools/relations/SatisfyTool.java
Java
gpl-3.0
3,013
<?php /* * Copyright 2014 REI Systems, Inc. * * This file is part of GovDashboard. * * GovDashboard 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. * * GovDashboard 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 GovDashboard. If not, see <http://www.gnu.org/licenses/>. */ /** * Informs gd_sync about available entities with export/import functionality */ function hook_gd_sync_entities () { $items['entity'] = array(); return $items; }
REI-Systems/GovDashboard-Community
webapp/sites/all/modules/custom/sync/gd_sync.api.php
PHP
gpl-3.0
919
import { AlloyTriggers, Attachment, Debugging, Swapping } from '@ephox/alloy'; import { Cell, Fun } from '@ephox/katamari'; import { PlatformDetection } from '@ephox/sand'; import { Element, Focus, Insert, Node } from '@ephox/sugar'; import DOMUtils from 'tinymce/core/api/dom/DOMUtils'; import ThemeManager from 'tinymce/core/api/ThemeManager'; import TinyCodeDupe from './alien/TinyCodeDupe'; import Settings from './api/Settings'; import TinyChannels from './channels/TinyChannels'; import Features from './features/Features'; import Styles from './style/Styles'; import Orientation from './touch/view/Orientation'; import AndroidRealm from './ui/AndroidRealm'; import Buttons from './ui/Buttons'; import IosRealm from './ui/IosRealm'; import CssUrls from './util/CssUrls'; import FormatChangers from './util/FormatChangers'; import SkinLoaded from './util/SkinLoaded'; /// not to be confused with editor mode const READING = Fun.constant('toReading'); /// 'hide the keyboard' const EDITING = Fun.constant('toEditing'); /// 'show the keyboard' ThemeManager.add('mobile', function (editor) { const renderUI = function (args) { const cssUrls = CssUrls.derive(editor); if (Settings.isSkinDisabled(editor) === false) { editor.contentCSS.push(cssUrls.content); DOMUtils.DOM.styleSheetLoader.load(cssUrls.ui, SkinLoaded.fireSkinLoaded(editor)); } else { SkinLoaded.fireSkinLoaded(editor)(); } const doScrollIntoView = function () { editor.fire('scrollIntoView'); }; const wrapper = Element.fromTag('div'); const realm = PlatformDetection.detect().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView); const original = Element.fromDom(args.targetNode); Insert.after(original, wrapper); Attachment.attachSystem(wrapper, realm.system()); const findFocusIn = function (elem) { return Focus.search(elem).bind(function (focused) { return realm.system().getByDom(focused).toOption(); }); }; const outerWindow = args.targetNode.ownerDocument.defaultView; const orientation = Orientation.onChange(outerWindow, { onChange () { const alloy = realm.system(); alloy.broadcastOn([ TinyChannels.orientationChanged() ], { width: Orientation.getActualWidth(outerWindow) }); }, onReady: Fun.noop }); const setReadOnly = function (readOnlyGroups, mainGroups, ro) { if (ro === false) { editor.selection.collapse(); } realm.setToolbarGroups(ro ? readOnlyGroups.get() : mainGroups.get()); editor.setMode(ro === true ? 'readonly' : 'design'); editor.fire(ro === true ? READING() : EDITING()); realm.updateMode(ro); }; const bindHandler = function (label, handler) { editor.on(label, handler); return { unbind () { editor.off(label); } }; }; editor.on('init', function () { realm.init({ editor: { getFrame () { return Element.fromDom(editor.contentAreaContainer.querySelector('iframe')); }, onDomChanged () { return { unbind: Fun.noop }; }, onToReading (handler) { return bindHandler(READING(), handler); }, onToEditing (handler) { return bindHandler(EDITING(), handler); }, onScrollToCursor (handler) { editor.on('scrollIntoView', function (tinyEvent) { handler(tinyEvent); }); const unbind = function () { editor.off('scrollIntoView'); orientation.destroy(); }; return { unbind }; }, onTouchToolstrip () { hideDropup(); }, onTouchContent () { const toolbar = Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar'))); // If something in the toolbar had focus, fire an execute on it (execute on tap away) // Perhaps it will be clearer later what is a better way of doing this. findFocusIn(toolbar).each(AlloyTriggers.emitExecute); realm.restoreToolbar(); hideDropup(); }, onTapContent (evt) { const target = evt.target(); // If the user has tapped (touchstart, touchend without movement) on an image, select it. if (Node.name(target) === 'img') { editor.selection.select(target.dom()); // Prevent the default behaviour from firing so that the image stays selected evt.kill(); } else if (Node.name(target) === 'a') { const component = realm.system().getByDom(Element.fromDom(editor.editorContainer)); component.each(function (container) { /// view mode if (Swapping.isAlpha(container)) { TinyCodeDupe.openLink(target.dom()); } }); } } }, container: Element.fromDom(editor.editorContainer), socket: Element.fromDom(editor.contentAreaContainer), toolstrip: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolstrip'))), toolbar: Element.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar'))), dropup: realm.dropup(), alloy: realm.system(), translate: Fun.noop, setReadOnly (ro) { setReadOnly(readOnlyGroups, mainGroups, ro); } }); const hideDropup = function () { realm.dropup().disappear(function () { realm.system().broadcastOn([ TinyChannels.dropupDismissed() ], { }); }); }; Debugging.registerInspector('remove this', realm.system()); const backToMaskGroup = { label: 'The first group', scrollable: false, items: [ Buttons.forToolbar('back', function (/* btn */) { editor.selection.collapse(); realm.exit(); }, { }) ] }; const backToReadOnlyGroup = { label: 'Back to read only', scrollable: false, items: [ Buttons.forToolbar('readonly-back', function (/* btn */) { setReadOnly(readOnlyGroups, mainGroups, true); }, {}) ] }; const readOnlyGroup = { label: 'The read only mode group', scrollable: true, items: [] }; const features = Features.setup(realm, editor); const items = Features.detect(editor.settings, features); const actionGroup = { label: 'the action group', scrollable: true, items }; const extraGroup = { label: 'The extra group', scrollable: false, items: [ // This is where the "add button" button goes. ] }; const mainGroups = Cell([ backToReadOnlyGroup, actionGroup, extraGroup ]); const readOnlyGroups = Cell([ backToMaskGroup, readOnlyGroup, extraGroup ]); // Investigate ways to keep in sync with the ui FormatChangers.init(realm, editor); }); return { iframeContainer: realm.socket().element().dom(), editorContainer: realm.element().dom() }; }; return { getNotificationManagerImpl () { return { open: Fun.identity, close: Fun.noop, reposition: Fun.noop, getArgs: Fun.identity }; }, renderUI }; }); export default function () { }
jabber-at/hp
hp/core/static/lib/tinymce/src/themes/mobile/main/ts/Theme.ts
TypeScript
gpl-3.0
7,637
#include "ObjetoCompuesto.h" ObjetoCompuesto:: ObjetoCompuesto() { hijos = new Objeto3D*[100000]; numHijos = 0; m1 = new GLfloat[16]; } ObjetoCompuesto:: ~ObjetoCompuesto() { for(int i =0; i < numHijos; i++) { delete hijos[i]; } } void ObjetoCompuesto:: dibuja() { glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(dameMatrizAfin()); // Copiar en m1 la matriz actual de modelado-vista glGetFloatv(GL_MODELVIEW_MATRIX, m1); for(int i =0; i < numHijos; i++) { glColor4f(hijos[i]->getR(), hijos[i]->getG(), hijos[i]->getB(), hijos[i]->getA()); glMultMatrixf(hijos[i]->dameMatrizAfin()); hijos[i]->dibuja(); glLoadMatrixf(m1); } glPopMatrix(); } void ObjetoCompuesto:: introduceObjeto(Objeto3D* objeto) { hijos[numHijos++] = objeto; }
RotaruDan/hierarchicalModelling
Practica2/ObjetoCompuesto.cpp
C++
gpl-3.0
788
''' ******************************************************************************* * ButtonEvent.py 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. * * ButtonEvent.py 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 ButtonEvent.py. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************** Created on Jan 5, 2010 @author: iocanto ''' BUTTON_SELECT = 257 BUTTON_HOTKEY_1 = 258; BUTTON_HOTKEY_2 = 259; BUTTON_HOTKEY_3 = 260; BUTTON_HOTKEY_4 = 261; BUTTON_RIGHT = 262; BUTTON_LEFT = 263; BUTTON_UP = 264; BUTTON_DOWN = 265; KEY_UP = 0 KEY_DOWN = 1 class ButtonEvent(): # Constructor def __init__(self, button = BUTTON_HOTKEY_1, action = KEY_UP ): self.__button = button self.__action = action def __str__ (self): return "ButtonEvent [__button %i]" % self.__button def getAction(self): return self.__action def getButton(self): return self.__button def getButtonName(self): return { 257 : "BUTTON_SELECT" , 258 : "BUTTON_HOTKEY_1", 259 : "BUTTON_HOTKEY_2", 260 : "BUTTON_HOTKEY_3", 261 : "BUTTON_HOTKEY_4", 262 : "BUTTON_RIGHT" , 263 : "BUTTON_LEFT" , 264 : "BUTTON_UP" , 265 : "BUTTON_DOWN" , }[self.__button] def setAction(self, action): self.__action = action def setButton(self, button): self.__button = button
iocanto/bug-python-libraries
ButtonEvent.py
Python
gpl-3.0
2,246
#!/usr/bin/env python # coding=utf-8 """ Distinct powers Problem 29 Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 2^2=4, 2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? """ from __future__ import print_function def power_combinations(a, b): for i in range(2, a): for j in range(2, b): yield i ** j if __name__ == '__main__': print(len(set(power_combinations(101, 101)))) # 9183
openqt/algorithms
projecteuler/ac/old/pe029_distinct_powers.py
Python
gpl-3.0
823
/* * This file is part of Radio Downloader. * Copyright © 2007-2018 by the authors - see the AUTHORS file for details. * * 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/>. */ namespace RadioDld { using System; using System.Drawing; using System.IO; using System.Windows.Forms; using Microsoft.VisualBasic; internal partial class Preferences : Form { private bool cancelClose; private bool folderChanged; public Preferences() { this.InitializeComponent(); } private void ButtonChangeFolder_Click(object eventSender, EventArgs eventArgs) { FolderBrowserDialog browse = new FolderBrowserDialog(); browse.SelectedPath = this.TextSaveIn.Text; browse.Description = "Choose the folder to save downloaded programmes in:"; if (browse.ShowDialog() == DialogResult.OK) { this.TextSaveIn.Text = browse.SelectedPath; this.folderChanged = true; } } private void ButtonOk_Click(object eventSender, EventArgs eventArgs) { if (string.IsNullOrEmpty(this.TextFileNameFormat.Text)) { Interaction.MsgBox("Please enter a value for the downloaded programme file name format.", MsgBoxStyle.Exclamation); this.TextFileNameFormat.Focus(); this.cancelClose = true; return; } bool formatChanged = Settings.FileNameFormat != this.TextFileNameFormat.Text; if (this.folderChanged || formatChanged) { string message = "Move existing downloads to \"" + this.TextSaveIn.Text + "\" and rename to new naming format?"; if (!formatChanged) { message = "Move existing downloads to \"" + this.TextSaveIn.Text + "\"?"; } else if (!this.folderChanged) { message = "Rename existing downloads to new naming format?"; } if (MessageBox.Show(message, Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { using (Status status = new Status()) { status.ShowDialog( this, () => { Model.Download.UpdatePaths(status, this.TextSaveIn.Text, this.TextFileNameFormat.Text); }); } } Settings.SaveFolder = this.TextSaveIn.Text; Settings.FileNameFormat = this.TextFileNameFormat.Text; } Settings.RunOnStartup = this.CheckRunOnStartup.Checked; Settings.RunAfterCommand = this.TextRunAfter.Text; Settings.ParallelDownloads = (int)this.NumberParallel.Value; Settings.RssServer = this.CheckRssServer.Checked; if (this.CheckRssServer.Checked) { Settings.RssServerPort = (int)this.NumberServerPort.Value; Settings.RssServerNumRecentEps = (int)this.NumberEpisodes.Value; } if (new TaskbarNotify().Supported) { Settings.CloseToSystray = this.CheckCloseToSystray.Checked; } OsUtils.ApplyRunOnStartup(); } private void Preferences_FormClosing(object sender, FormClosingEventArgs e) { if (this.cancelClose) { // Prevent the form from being automatically closed if it failed validation e.Cancel = true; this.cancelClose = false; } } private void Preferences_Load(object eventSender, EventArgs eventArgs) { this.Font = SystemFonts.MessageBoxFont; this.CheckRunOnStartup.Checked = Settings.RunOnStartup; if (new TaskbarNotify().Supported) { this.CheckCloseToSystray.Checked = Settings.CloseToSystray; } else { this.CheckCloseToSystray.Checked = true; this.CheckCloseToSystray.Enabled = false; } this.CheckRssServer.Checked = Settings.RssServer; this.NumberServerPort.Enabled = this.CheckRssServer.Checked; this.NumberServerPort.Value = Settings.RssServerPort; this.NumberEpisodes.Enabled = this.CheckRssServer.Checked; this.NumberEpisodes.Value = Settings.RssServerNumRecentEps; this.NumberParallel.Value = Settings.ParallelDownloads; this.NumberParallel.Maximum = Math.Max(this.NumberParallel.Value, Environment.ProcessorCount * 2); try { this.TextSaveIn.Text = FileUtils.GetSaveFolder(); } catch (DirectoryNotFoundException) { this.TextSaveIn.Text = Settings.SaveFolder; } this.TextFileNameFormat.Text = Settings.FileNameFormat; this.TextRunAfter.Text = Settings.RunAfterCommand; } private void Preferences_HelpButtonClicked(object sender, System.ComponentModel.CancelEventArgs e) { this.ShowHelp(); e.Cancel = true; } private void Preferences_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F1) { e.Handled = true; this.ShowHelp(); } } private void ShowHelp() { OsUtils.LaunchUrl(new Uri("https://nerdoftheherd.com/tools/radiodld/help/dialogs.options/"), "Context Help"); } private void TextFileNameFormat_TextChanged(object sender, EventArgs e) { Model.Programme dummyProg = new Model.Programme(); dummyProg.Name = "Programme Name"; Model.Episode dummyEp = new Model.Episode(); dummyEp.Name = "Episode Name"; dummyEp.Date = DateTime.Now; this.LabelFilenameFormatResult.Text = "Result: " + Model.Download.CreateSaveFileName(this.TextFileNameFormat.Text, dummyProg, dummyEp) + ".mp3"; } private void ButtonReset_Click(object sender, EventArgs e) { if (Interaction.MsgBox("Are you sure that you would like to reset all of your settings?", MsgBoxStyle.YesNo | MsgBoxStyle.Question) == MsgBoxResult.Yes) { Settings.ResetUserSettings(); OsUtils.ApplyRunOnStartup(); this.Close(); } } private void CheckRssServer_CheckedChanged(object sender, EventArgs e) { this.NumberServerPort.Enabled = this.CheckRssServer.Checked; this.NumberEpisodes.Enabled = this.CheckRssServer.Checked; } } }
nbl1268/RadioDownloader
Forms/Preferences.cs
C#
gpl-3.0
7,638
/* * 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/>. */ /* * MavenArtifactExclusion.java * Copyright (C) 2021 University of Waikato, Hamilton, NZ */ package adams.core.base; /** * Encapsulates Maven artifact exclusions. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public class MavenArtifactExclusion extends AbstractBaseString { private static final long serialVersionUID = 1516586362049381050L; public final static String SEPARATOR = ":"; /** * Initializes the string with length 0. */ public MavenArtifactExclusion() { this(""); } /** * Initializes the object with the string to parse. * * @param s the string to parse */ public MavenArtifactExclusion(String s) { super(s); } /** * Initializes the object with the artifact coordinates. * * @param groupId the group ID * @param artifactId the artifact ID */ public MavenArtifactExclusion(String groupId, String artifactId) { super(groupId + SEPARATOR + artifactId); } /** * Checks whether the string value is a valid presentation for this class. * * @param value the string value to check * @return true if non-null */ @Override public boolean isValid(String value) { return (value != null) && (value.split(SEPARATOR).length == 2); } /** * Returns the specified part of the coordinate triplet. * * @param index the index from the triplet to return * @return the value or empty string if invalid string or index */ protected String getPart(int index) { String[] parts; if (isEmpty()) return ""; parts = getValue().split(SEPARATOR); if (parts.length != 2) return ""; return parts[index]; } /** * Returns the group ID part, if possible. * * @return the group ID */ public String groupIdValue() { return getPart(0); } /** * Returns the artifact ID part, if possible. * * @return the artifact ID */ public String artifactIdValue() { return getPart(1); } /** * Returns a tool tip for the GUI editor (ignored if null is returned). * * @return the tool tip */ @Override public String getTipText() { return "The two coordinates of a Maven artifact exclusion: groupId:artifactId"; } }
waikato-datamining/adams-base
adams-core/src/main/java/adams/core/base/MavenArtifactExclusion.java
Java
gpl-3.0
2,905
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # 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/>. import os import numpy as np from copy import deepcopy import h5py from .util import Signal from .util.ImgCorrection import CbnCorrection, ObliqueAngleDetectorAbsorptionCorrection from .util import Pattern from .util.calc import convert_units from . import ImgModel, CalibrationModel, MaskModel, PatternModel, BatchModel from .CalibrationModel import DetectorModes class Configuration(object): """ The configuration class contains a working combination of an ImgModel, PatternModel, MaskModel and CalibrationModel. It does handles the core data manipulation of Dioptas. The management of multiple Configurations is done by the DioptasModel. """ def __init__(self, working_directories=None): super(Configuration, self).__init__() self.img_model = ImgModel() self.mask_model = MaskModel() self.calibration_model = CalibrationModel(self.img_model) self.batch_model = BatchModel(self.calibration_model, self.mask_model) self.pattern_model = PatternModel() if working_directories is None: self.working_directories = {'calibration': '', 'mask': '', 'image': os.path.expanduser("~"), 'pattern': '', 'overlay': '', 'phase': '', 'batch': os.path.expanduser("~")} else: self.working_directories = working_directories self.use_mask = False self.transparent_mask = False self._integration_rad_points = None self._integration_unit = '2th_deg' self._oned_azimuth_range = None self._cake_azimuth_points = 360 self._cake_azimuth_range = None self._auto_integrate_pattern = True self._auto_integrate_cake = False self.auto_save_integrated_pattern = False self.integrated_patterns_file_formats = ['.xy'] self.cake_changed = Signal() self._connect_signals() def _connect_signals(self): """ Connects the img_changed signal to responding functions. """ self.img_model.img_changed.connect(self.update_mask_dimension) self.img_model.img_changed.connect(self.integrate_image_1d) def integrate_image_1d(self): """ Integrates the image in the ImageModel to a Pattern. Will also automatically save the integrated pattern, if auto_save_integrated is True. """ if self.calibration_model.is_calibrated: if self.use_mask: mask = self.mask_model.get_mask() elif self.mask_model.roi is not None: mask = self.mask_model.roi_mask else: mask = None x, y = self.calibration_model.integrate_1d(azi_range=self.oned_azimuth_range, mask=mask, unit=self.integration_unit, num_points=self.integration_rad_points) self.pattern_model.set_pattern(x, y, self.img_model.filename, unit=self.integration_unit) # if self.auto_save_integrated_pattern: self._auto_save_patterns() def integrate_image_2d(self): """ Integrates the image in the ImageModel to a Cake. """ if self.use_mask: mask = self.mask_model.get_mask() elif self.mask_model.roi is not None: mask = self.mask_model.roi_mask else: mask = None self.calibration_model.integrate_2d(mask=mask, rad_points=self._integration_rad_points, azimuth_points=self._cake_azimuth_points, azimuth_range=self._cake_azimuth_range) self.cake_changed.emit() def save_pattern(self, filename=None, subtract_background=False): """ Saves the current integrated pattern. The format depends on the file ending. Possible file formats: [*.xy, *.chi, *.dat, *.fxye] :param filename: where to save the file :param subtract_background: flat whether the pattern should be saved with or without subtracted background """ if filename is None: filename = self.img_model.filename if filename.endswith('.xy'): self.pattern_model.save_pattern(filename, header=self._create_xy_header(), subtract_background=subtract_background) elif filename.endswith('.fxye'): self.pattern_model.save_pattern(filename, header=self._create_fxye_header(filename), subtract_background=subtract_background) else: self.pattern_model.save_pattern(filename, subtract_background=subtract_background) def save_background_pattern(self, filename=None): """ Saves the current fit background as a pattern. The format depends on the file ending. Possible file formats: [*.xy, *.chi, *.dat, *.fxye] """ if filename is None: filename = self.img_model.filename if filename.endswith('.xy'): self.pattern_model.save_auto_background_as_pattern(filename, header=self._create_xy_header()) elif filename.endswith('.fxye'): self.pattern_model.save_auto_background_as_pattern(filename, header=self._create_fxye_header(filename)) else: self.pattern_model.save_pattern(filename) def _create_xy_header(self): """ Creates the header for the xy file format (contains information about calibration parameters). :return: header string """ header = self.calibration_model.create_file_header() header = header.replace('\r\n', '\n') header = header + '\n#\n# ' + self._integration_unit + '\t I' return header def _create_fxye_header(self, filename): """ Creates the header for the fxye file format (used by GSAS and GSAS-II) containing the calibration information :return: header string """ header = 'Generated file ' + filename + ' using DIOPTAS\n' header = header + self.calibration_model.create_file_header() unit = self._integration_unit lam = self.calibration_model.wavelength if unit == 'q_A^-1': con = 'CONQ' else: con = 'CONS' header = header + '\nBANK\t1\tNUM_POINTS\tNUM_POINTS ' + con + '\tMIN_X_VAL\tSTEP_X_VAL ' + \ '{0:.5g}'.format(lam * 1e10) + ' 0.0 FXYE' return header def _auto_save_patterns(self): """ Saves the current pattern in the pattern working directory (specified in self.working_directories['pattern']. When background subtraction is enabled in the pattern model the pattern will be saved with background subtraction and without in another sub-folder. ('bkg_subtracted') """ for file_ending in self.integrated_patterns_file_formats: filename = os.path.join( self.working_directories['pattern'], os.path.basename(str(self.img_model.filename)).split('.')[:-1][0] + file_ending) filename = filename.replace('\\', '/') self.save_pattern(filename) if self.pattern_model.pattern.has_background(): for file_ending in self.integrated_patterns_file_formats: directory = os.path.join(self.working_directories['pattern'], 'bkg_subtracted') if not os.path.exists(directory): os.mkdir(directory) filename = os.path.join(directory, self.pattern_model.pattern.name + file_ending) filename = filename.replace('\\', '/') self.save_pattern(filename, subtract_background=True) def update_mask_dimension(self): """ Updates the shape of the mask in the MaskModel to the shape of the image in the ImageModel. """ self.mask_model.set_dimension(self.img_model._img_data.shape) @property def integration_rad_points(self): return self._integration_rad_points @integration_rad_points.setter def integration_rad_points(self, new_value): self._integration_rad_points = new_value self.integrate_image_1d() if self.auto_integrate_cake: self.integrate_image_2d() @property def cake_azimuth_points(self): return self._cake_azimuth_points @cake_azimuth_points.setter def cake_azimuth_points(self, new_value): self._cake_azimuth_points = new_value if self.auto_integrate_cake: self.integrate_image_2d() @property def cake_azimuth_range(self): return self._cake_azimuth_range @cake_azimuth_range.setter def cake_azimuth_range(self, new_value): self._cake_azimuth_range = new_value if self.auto_integrate_cake: self.integrate_image_2d() @property def oned_azimuth_range(self): return self._oned_azimuth_range @oned_azimuth_range.setter def oned_azimuth_range(self, new_value): self._oned_azimuth_range = new_value if self.auto_integrate_pattern: self.integrate_image_1d() @property def integration_unit(self): return self._integration_unit @integration_unit.setter def integration_unit(self, new_unit): old_unit = self.integration_unit self._integration_unit = new_unit auto_bg_subtraction = self.pattern_model.pattern.auto_background_subtraction if auto_bg_subtraction: self.pattern_model.pattern.auto_background_subtraction = False self.integrate_image_1d() self.update_auto_background_parameters_unit(old_unit, new_unit) if auto_bg_subtraction: self.pattern_model.pattern.auto_background_subtraction = True self.pattern_model.pattern.recalculate_pattern() self.pattern_model.pattern_changed.emit() @property def correct_solid_angle(self): return self.calibration_model.correct_solid_angle @correct_solid_angle.setter def correct_solid_angle(self, new_val): self.calibration_model.correct_solid_angle = new_val if self.auto_integrate_pattern: self.integrate_image_1d() if self._auto_integrate_cake: self.integrate_image_2d() def update_auto_background_parameters_unit(self, old_unit, new_unit): """ This handles the changes for the auto background subtraction parameters in the PatternModel when the integration unit is changed. :param old_unit: possible values are '2th_deg', 'q_A^-1', 'd_A' :param new_unit: possible values are '2th_deg', 'q_A^-1', 'd_A' """ par_0 = convert_units(self.pattern_model.pattern.auto_background_subtraction_parameters[0], self.calibration_model.wavelength, old_unit, new_unit) # Value of 0.1 let background subtraction algorithm work without crash. if np.isnan(par_0): par_0 = 0.1 self.pattern_model.pattern.auto_background_subtraction_parameters = \ par_0, \ self.pattern_model.pattern.auto_background_subtraction_parameters[1], \ self.pattern_model.pattern.auto_background_subtraction_parameters[2] if self.pattern_model.pattern.auto_background_subtraction_roi is not None: self.pattern_model.pattern.auto_background_subtraction_roi = \ convert_units(self.pattern_model.pattern.auto_background_subtraction_roi[0], self.calibration_model.wavelength, old_unit, new_unit), \ convert_units(self.pattern_model.pattern.auto_background_subtraction_roi[1], self.calibration_model.wavelength, old_unit, new_unit) @property def auto_integrate_cake(self): return self._auto_integrate_cake @auto_integrate_cake.setter def auto_integrate_cake(self, new_value): if self._auto_integrate_cake == new_value: return self._auto_integrate_cake = new_value if new_value: self.img_model.img_changed.connect(self.integrate_image_2d) else: self.img_model.img_changed.disconnect(self.integrate_image_2d) @property def auto_integrate_pattern(self): return self._auto_integrate_pattern @auto_integrate_pattern.setter def auto_integrate_pattern(self, new_value): if self._auto_integrate_pattern == new_value: return self._auto_integrate_pattern = new_value if new_value: self.img_model.img_changed.connect(self.integrate_image_1d) else: self.img_model.img_changed.disconnect(self.integrate_image_1d) @property def cake_img(self): return self.calibration_model.cake_img @property def roi(self): return self.mask_model.roi @roi.setter def roi(self, new_val): self.mask_model.roi = new_val self.integrate_image_1d() def copy(self): """ Creates a copy of the current working directory :return: copied configuration :rtype: Configuration """ new_configuration = Configuration(self.working_directories) new_configuration.img_model._img_data = self.img_model._img_data new_configuration.img_model.img_transformations = deepcopy(self.img_model.img_transformations) new_configuration.calibration_model.set_pyFAI(self.calibration_model.get_calibration_parameter()[0]) new_configuration.integrate_image_1d() return new_configuration def save_in_hdf5(self, hdf5_group): """ Saves the configuration group in the given hdf5_group. :type hdf5_group: h5py.Group """ f = hdf5_group # save general information general_information = f.create_group('general_information') # integration parameters: general_information.attrs['integration_unit'] = self.integration_unit if self.integration_rad_points: general_information.attrs['integration_num_points'] = self.integration_rad_points else: general_information.attrs['integration_num_points'] = 0 # cake parameters: general_information.attrs['auto_integrate_cake'] = self.auto_integrate_cake general_information.attrs['cake_azimuth_points'] = self.cake_azimuth_points if self.cake_azimuth_range is None: general_information.attrs['cake_azimuth_range'] = "None" else: general_information.attrs['cake_azimuth_range'] = self.cake_azimuth_range # mask parameters general_information.attrs['use_mask'] = self.use_mask general_information.attrs['transparent_mask'] = self.transparent_mask # auto save parameters general_information.attrs['auto_save_integrated_pattern'] = self.auto_save_integrated_pattern formats = [n.encode('ascii', 'ignore') for n in self.integrated_patterns_file_formats] general_information.create_dataset('integrated_patterns_file_formats', (len(formats), 1), 'S10', formats) # save working directories working_directories_gp = f.create_group('working_directories') try: for key in self.working_directories: working_directories_gp.attrs[key] = self.working_directories[key] except TypeError: self.working_directories = {'calibration': '', 'mask': '', 'image': '', 'pattern': '', 'overlay': '', 'phase': '', 'batch': ''} for key in self.working_directories: working_directories_gp.attrs[key] = self.working_directories[key] # save image model image_group = f.create_group('image_model') image_group.attrs['auto_process'] = self.img_model.autoprocess image_group.attrs['factor'] = self.img_model.factor image_group.attrs['has_background'] = self.img_model.has_background() image_group.attrs['background_filename'] = self.img_model.background_filename image_group.attrs['background_offset'] = self.img_model.background_offset image_group.attrs['background_scaling'] = self.img_model.background_scaling if self.img_model.has_background(): background_data = self.img_model.untransformed_background_data image_group.create_dataset('background_data', background_data.shape, 'f', background_data) image_group.attrs['series_max'] = self.img_model.series_max image_group.attrs['series_pos'] = self.img_model.series_pos # image corrections corrections_group = image_group.create_group('corrections') corrections_group.attrs['has_corrections'] = self.img_model.has_corrections() for correction, correction_object in self.img_model.img_corrections.corrections.items(): if correction in ['cbn', 'oiadac']: correction_data = correction_object.get_data() imcd = corrections_group.create_dataset(correction, correction_data.shape, 'f', correction_data) for param, value in correction_object.get_params().items(): imcd.attrs[param] = value elif correction == 'transfer': params = correction_object.get_params() transfer_group = corrections_group.create_group('transfer') original_data = params['original_data'] response_data = params['response_data'] original_ds = transfer_group.create_dataset('original_data', original_data.shape, 'f', original_data) original_ds.attrs['filename'] = params['original_filename'] response_ds = transfer_group.create_dataset('response_data', response_data.shape, 'f', response_data) response_ds.attrs['filename'] = params['response_filename'] # the actual image image_group.attrs['filename'] = self.img_model.filename current_raw_image = self.img_model.untransformed_raw_img_data raw_image_data = image_group.create_dataset('raw_image_data', current_raw_image.shape, dtype='f') raw_image_data[...] = current_raw_image # image transformations transformations_group = image_group.create_group('image_transformations') for ind, transformation in enumerate(self.img_model.get_transformations_string_list()): transformations_group.attrs[str(ind)] = transformation # save roi data if self.roi is not None: image_group.attrs['has_roi'] = True image_group.create_dataset('roi', (4,), 'i8', tuple(self.roi)) else: image_group.attrs['has_roi'] = False # save mask model mask_group = f.create_group('mask') current_mask = self.mask_model.get_mask() mask_data = mask_group.create_dataset('data', current_mask.shape, dtype=bool) mask_data[...] = current_mask # save detector information detector_group = f.create_group('detector') detector_mode = self.calibration_model.detector_mode detector_group.attrs['detector_mode'] = detector_mode.value if detector_mode == DetectorModes.PREDEFINED: detector_group.attrs['detector_name'] = self.calibration_model.detector.name elif detector_mode == DetectorModes.NEXUS: detector_group.attrs['nexus_filename'] =self.calibration_model.detector.filename # save calibration model calibration_group = f.create_group('calibration_model') calibration_filename = self.calibration_model.filename if calibration_filename.endswith('.poni'): base_filename, ext = self.calibration_model.filename.rsplit('.', 1) else: base_filename = self.calibration_model.filename ext = 'poni' calibration_group.attrs['calibration_filename'] = base_filename + '.' + ext pyfai_param, fit2d_param = self.calibration_model.get_calibration_parameter() pfp = calibration_group.create_group('pyfai_parameters') for key in pyfai_param: try: pfp.attrs[key] = pyfai_param[key] except TypeError: pfp.attrs[key] = '' calibration_group.attrs['correct_solid_angle'] = self.correct_solid_angle if self.calibration_model.distortion_spline_filename is not None: calibration_group.attrs['distortion_spline_filename'] = self.calibration_model.distortion_spline_filename # save background pattern and pattern model background_pattern_group = f.create_group('background_pattern') try: background_pattern_x = self.pattern_model.background_pattern.original_x background_pattern_y = self.pattern_model.background_pattern.original_y except (TypeError, AttributeError): background_pattern_x = None background_pattern_y = None if background_pattern_x is not None and background_pattern_y is not None: background_pattern_group.attrs['has_background_pattern'] = True bgx = background_pattern_group.create_dataset('x', background_pattern_x.shape, dtype='f') bgy = background_pattern_group.create_dataset('y', background_pattern_y.shape, dtype='f') bgx[...] = background_pattern_x bgy[...] = background_pattern_y else: background_pattern_group.attrs['has_background_pattern'] = False pattern_group = f.create_group('pattern') try: pattern_x = self.pattern_model.pattern.original_x pattern_y = self.pattern_model.pattern.original_y except (TypeError, AttributeError): pattern_x = None pattern_y = None if pattern_x is not None and pattern_y is not None: px = pattern_group.create_dataset('x', pattern_x.shape, dtype='f') py = pattern_group.create_dataset('y', pattern_y.shape, dtype='f') px[...] = pattern_x py[...] = pattern_y pattern_group.attrs['pattern_filename'] = self.pattern_model.pattern_filename pattern_group.attrs['unit'] = self.pattern_model.unit pattern_group.attrs['file_iteration_mode'] = self.pattern_model.file_iteration_mode if self.pattern_model.pattern.auto_background_subtraction: pattern_group.attrs['auto_background_subtraction'] = True auto_background_group = pattern_group.create_group('auto_background_settings') auto_background_group.attrs['smoothing'] = \ self.pattern_model.pattern.auto_background_subtraction_parameters[0] auto_background_group.attrs['iterations'] = \ self.pattern_model.pattern.auto_background_subtraction_parameters[1] auto_background_group.attrs['poly_order'] = \ self.pattern_model.pattern.auto_background_subtraction_parameters[2] auto_background_group.attrs['x_start'] = self.pattern_model.pattern.auto_background_subtraction_roi[0] auto_background_group.attrs['x_end'] = self.pattern_model.pattern.auto_background_subtraction_roi[1] else: pattern_group.attrs['auto_background_subtraction'] = False def load_from_hdf5(self, hdf5_group): """ Loads a configuration from the specified hdf5_group. :type hdf5_group: h5py.Group """ f = hdf5_group # disable all automatic functions self.auto_integrate_pattern = False self.auto_integrate_cake = False self.auto_save_integrated_pattern = False # get working directories working_directories = {} for key, value in f.get('working_directories').attrs.items(): if os.path.isdir(value): working_directories[key] = value else: working_directories[key] = '' self.working_directories = working_directories # load pyFAI parameters pyfai_parameters = {} for key, value in f.get('calibration_model').get('pyfai_parameters').attrs.items(): pyfai_parameters[key] = value try: self.calibration_model.set_pyFAI(pyfai_parameters) filename = f.get('calibration_model').attrs['calibration_filename'] (file_path, base_name) = os.path.split(filename) self.calibration_model.filename = filename self.calibration_model.calibration_name = base_name except (KeyError, ValueError): print('Problem with saved pyFAI calibration parameters') pass try: self.correct_solid_angle = f.get('calibration_model').attrs['correct_solid_angle'] except KeyError: pass try: distortion_spline_filename = f.get('calibration_model').attrs['distortion_spline_filename'] self.calibration_model.load_distortion(distortion_spline_filename) except KeyError: pass # load detector definition try: detector_mode = f.get('detector').attrs['detector_mode'] if detector_mode == DetectorModes.PREDEFINED.value: detector_name = f.get('detector').attrs['detector_name'] self.calibration_model.load_detector(detector_name) elif detector_mode == DetectorModes.NEXUS.value: nexus_filename = f.get('detector').attrs['nexus_filename'] self.calibration_model.load_detector_from_file(nexus_filename) except AttributeError: # to ensure backwards compatibility pass # load img_model self.img_model._img_data = np.copy(f.get('image_model').get('raw_image_data')[...]) filename = f.get('image_model').attrs['filename'] self.img_model.filename = filename try: self.img_model.file_name_iterator.update_filename(filename) self.img_model._directory_watcher.path = os.path.dirname(filename) except EnvironmentError: pass self.img_model.autoprocess = f.get('image_model').attrs['auto_process'] self.img_model.autoprocess_changed.emit() self.img_model.factor = f.get('image_model').attrs['factor'] try: self.img_model.series_max = f.get('image_model').attrs['series_max'] self.img_model.series_pos = f.get('image_model').attrs['series_pos'] except KeyError: pass if f.get('image_model').attrs['has_background']: self.img_model.background_data = np.copy(f.get('image_model').get('background_data')[...]) self.img_model.background_filename = f.get('image_model').attrs['background_filename'] self.img_model.background_scaling = f.get('image_model').attrs['background_scaling'] self.img_model.background_offset = f.get('image_model').attrs['background_offset'] # load image transformations transformation_group = f.get('image_model').get('image_transformations') transformation_list = [] for key, transformation in transformation_group.attrs.items(): transformation_list.append(transformation) self.calibration_model.load_transformations_string_list(transformation_list) self.img_model.load_transformations_string_list(transformation_list) # load roi data if f.get('image_model').attrs['has_roi']: self.roi = tuple(f.get('image_model').get('roi')[...]) # load mask model self.mask_model.set_mask(np.copy(f.get('mask').get('data')[...])) # load pattern model if f.get('pattern').get('x') and f.get('pattern').get('y'): self.pattern_model.set_pattern(f.get('pattern').get('x')[...], f.get('pattern').get('y')[...], f.get('pattern').attrs['pattern_filename'], f.get('pattern').attrs['unit']) self.pattern_model.file_iteration_mode = f.get('pattern').attrs['file_iteration_mode'] self.integration_unit = f.get('general_information').attrs['integration_unit'] if f.get('background_pattern').attrs['has_background_pattern']: self.pattern_model.background_pattern = Pattern(f.get('background_pattern').get('x')[...], f.get('background_pattern').get('y')[...], 'background_pattern') if f.get('pattern').attrs['auto_background_subtraction']: bg_params = [] bg_roi = [] bg_params.append(f.get('pattern').get('auto_background_settings').attrs['smoothing']) bg_params.append(f.get('pattern').get('auto_background_settings').attrs['iterations']) bg_params.append(f.get('pattern').get('auto_background_settings').attrs['poly_order']) bg_roi.append(f.get('pattern').get('auto_background_settings').attrs['x_start']) bg_roi.append(f.get('pattern').get('auto_background_settings').attrs['x_end']) self.pattern_model.pattern.set_auto_background_subtraction(bg_params, bg_roi, recalc_pattern=False) # load general configuration if f.get('general_information').attrs['integration_num_points']: self.integration_rad_points = f.get('general_information').attrs['integration_num_points'] # cake parameters: self.auto_integrate_cake = f.get('general_information').attrs['auto_integrate_cake'] try: self.cake_azimuth_points = f.get('general_information').attrs['cake_azimuth_points'] except KeyError as e: pass try: if f.get('general_information').attrs['cake_azimuth_range'] == "None": self.cake_azimuth_range = None else: self.cake_azimuth_range = f.get('general_information').attrs['cake_azimuth_range'] except KeyError as e: pass # mask parameters self.use_mask = f.get('general_information').attrs['use_mask'] self.transparent_mask = f.get('general_information').attrs['transparent_mask'] # corrections if f.get('image_model').get('corrections').attrs['has_corrections']: for name, correction_group in f.get('image_model').get('corrections').items(): params = {} for param, val in correction_group.attrs.items(): params[param] = val if name == 'cbn': tth_array = 180.0 / np.pi * self.calibration_model.pattern_geometry.ttha azi_array = 180.0 / np.pi * self.calibration_model.pattern_geometry.chia cbn_correction = CbnCorrection(tth_array=tth_array, azi_array=azi_array) cbn_correction.set_params(params) cbn_correction.update() self.img_model.add_img_correction(cbn_correction, name) elif name == 'oiadac': tth_array = 180.0 / np.pi * self.calibration_model.pattern_geometry.ttha azi_array = 180.0 / np.pi * self.calibration_model.pattern_geometry.chia oiadac = ObliqueAngleDetectorAbsorptionCorrection(tth_array=tth_array, azi_array=azi_array) oiadac.set_params(params) oiadac.update() self.img_model.add_img_correction(oiadac, name) elif name == 'transfer': params = { 'original_data': correction_group.get('original_data')[...], 'original_filename': correction_group.get('original_data').attrs['filename'], 'response_data': correction_group.get('response_data')[...], 'response_filename': correction_group.get('response_data').attrs['filename'] } self.img_model.transfer_correction.set_params(params) self.img_model.enable_transfer_function() # autosave parameters self.auto_save_integrated_pattern = f.get('general_information').attrs['auto_save_integrated_pattern'] self.integrated_patterns_file_formats = [] for file_format in f.get('general_information').get('integrated_patterns_file_formats'): self.integrated_patterns_file_formats.append(file_format[0].decode('utf-8')) if self.calibration_model.is_calibrated: self.integrate_image_1d() else: self.pattern_model.pattern.recalculate_pattern()
Dioptas/Dioptas
dioptas/model/Configuration.py
Python
gpl-3.0
34,175
<?php /** * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link https://github.com/bderidder/ldm-guild-website */ namespace LaDanse\ServicesBundle\Service\DTO\Callback; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\Type; use Symfony\Component\Validator\Constraints as Assert; /** * @ExclusionPolicy("none") */ class LogCallback { /** * @var string * @Type("string") * @SerializedName("source") * @Assert\NotBlank() */ protected $source; /** * @var string * @Type("string") * @SerializedName("message") * @Assert\NotBlank() */ protected $message; /** * @return string */ public function getSource() { return $this->source; } /** * @param string $source * @return LogCallback */ public function setSource(string $source): LogCallback { $this->source = $source; return $this; } /** * @return string */ public function getMessage() { return $this->message; } /** * @param string $message * @return LogCallback */ public function setMessage(string $message): LogCallback { $this->message = $message; return $this; } }
bderidder/ldm-guild-website
src/LaDanse/ServicesBundle/Service/DTO/Callback/LogCallback.php
PHP
gpl-3.0
1,366
var express = require('express'); var reload = require('reload'); var fs = require('fs'); var wss = new require('ws').Server({port: 3030}); var app = express(); var Chopper = require('./lib/Chopper'); app.set('port', process.env.PORT || 3000); app.set('view engine', 'ejs'); app.use(require('./routes/index')); app.use(require('./routes/visual')); app.use(require('./routes/d3')); app.use(require('./routes/control')); app.use(require('./routes/config')); app.use(require('./routes/api')); app.use('/jquery', express.static('./node_modules/jquery/dist')); app.use(express.static('./public')); // global vars for the EJS (Embedded JavaScript) framework app.locals.siteTitle = 'CS'; // Control Systems title var server = app.listen(app.get('port'), function () { console.log('Example app listening on port: ' + app.get('port') + '!'); }); reload(server, app); wss.on('connection', function (ws) { ws.send('Welcome to cyber chat'); ws.on('message', function (msg) { if (msg == 'exit') { ws.close(); } }) }); var chop = new Chopper(); chop.on('ready', function() { console.log('Chopper ready'); app.set('chopper', chop); }); chop.on('change', function(value) { wss.clients.forEach(function (ws, index, list) { ws.send(JSON.stringify(value)); }) }); chop.on('data', function(type, data) { fs.writeFile(type + Date.now() + '.csv', data, function (err) { console.log(`${type} data saved`); }); });
gjgjwmertens/LedBlinkJohhny5
exp_app.js
JavaScript
gpl-3.0
1,517
package org.trrusst.software.recommender; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by lahiru.gallege */ public class TrustBasedServiceRecommender extends HttpServlet implements Servlet { // Logger for the servlet private static final Logger log = Logger.getLogger(TrustBasedServiceRecommender.class.getName()); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the form parameters //String spList = (String)request.getParameter("spList"); String query = (String)request.getParameter("TrustBased"); String qos = (String)request.getParameter("QoS"); //System.out.println("Inside A : " + query); String sqlQuery = "select id,title,score from App.AzSoftware where title like '%" + query + "%' and text like '%" + qos +"%'"; String[] resultSet = DerbyDBUtil.getResults(sqlQuery); List<ServiceDAO> spList = new ArrayList<ServiceDAO>(); for (int i = 0 ; i < resultSet.length ; i++){ String[] resultArray = resultSet[i].split(","); ServiceDAO serviceDAO = new ServiceDAO(); serviceDAO.setId(resultArray[0]); serviceDAO.setName(resultArray[1]); serviceDAO.setRating(resultArray[2]); spList.add(serviceDAO); } // Set Request Attributes request.setAttribute("recommendedTrustList", spList); request.setAttribute("selection", "TrustBased"); // Log the request status log.log(Level.INFO, "Tagging Automatic Recommendations : " + "| Description : " + "None"); // Forward the request back request.getRequestDispatcher("/recommendServiceProviders.jsp").forward(request, response); } }
sandakith/TRRuSST
TrWebApp/src/main/java/org/trrusst/software/recommender/TrustBasedServiceRecommender.java
Java
gpl-3.0
2,115
import time import json import pytz from datetime import datetime, timedelta from django.utils import timezone from django.conf import settings from rest_framework import status from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import IsAdminUser from ..models.security import ( SecurityLoginAttemptIncorrect, SecurityLoginAttemptCorrect ) @api_view(['GET']) @permission_classes((IsAdminUser, )) def correctlogins_data(request): date_start_raw = request.GET.get('date_start') date_end_raw = request.GET.get('date_end') date_start_tz = None date_end_tz = None if not date_start_raw or not date_end_raw: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now else: date_start = datetime.fromtimestamp(int(date_start_raw)) date_start_tz = pytz.timezone(settings.TIME_ZONE).localize(date_start, is_dst=None) date_end = datetime.fromtimestamp(int(date_end_raw)) date_end_tz = pytz.timezone(settings.TIME_ZONE).localize(date_end, is_dst=None) if date_start_tz == date_end_tz: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now count_hosts = [] temp_hosts = {} temp_users = {} dates = [] values = SecurityLoginAttemptCorrect.objects.filter(time__range=[date_start_tz, date_end_tz]) count_correct_attempt = 0 for p in values: value = json.loads(p.value) attempt_count = 0 for host, v in value.get("hosts", {}).items(): attempt_count += v.get("count", 0) count_correct_attempt += attempt_count raw_date = v.get("last_date") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if host in temp_hosts: temp_hosts[host]["count"] = temp_hosts[host]["count"] + v.get("count", 0) temp_hosts[host]["last_date"] = date_tz.strftime("%b %d %H:%M") else: temp_hosts[host] = { "host": host, "count": v.get("count", 0), "last_date": date_tz.strftime("%b %d %H:%M") } for username, v in value.get("users", {}).items(): attempt_count += v.get("count", 0) raw_date = v.get("last_date") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if username in temp_users: temp_users[username]["count"] = temp_users[username]["count"] + v.get("count", 0) temp_users[username]["last_date"] = date_tz.strftime("%b %d %H:%M") else: temp_users[username] = { "username": username, "count": v.get("count", 0), "last_date": date_tz.strftime("%b %d %H:%M") } count_hosts.append(attempt_count) dates.append(timezone.localtime(p.time).strftime("%b %d %H:%M")) hosts = [] for i in temp_hosts: hosts.append(temp_hosts[i]) if hosts: hosts.sort(key=lambda x: x["count"], reverse=True) hosts = hosts[:100] users = [] for i in temp_users: users.append(temp_users[i]) if users: users.sort(key=lambda x: x["count"], reverse=True) users = users[:100] date_range = { "start": time.mktime(timezone.localtime(date_start_tz).timetuple()), # time.mktime(timezone.localtime(timezone.now()).timetuple()), "start_date": time.mktime(timezone.localtime(date_start_tz).timetuple()) + 10, # time.mktime(timezone.localtime(timezone.now()).timetuple()), "end_date": time.mktime(timezone.localtime(date_end_tz).timetuple()), } if values: date_range["start"] = time.mktime(timezone.localtime(values[0].time).timetuple()) start_obj = SecurityLoginAttemptCorrect.objects.all().first() if start_obj: date_range["start_date"] = time.mktime(timezone.localtime(start_obj.time).timetuple()) if date_range["start_date"] == date_range["end_date"]: date_range["end_date"] += 10 return Response({ "values": [{ "data": count_hosts, "label": 'Number of login' }], "dates": dates, "date_range": date_range, "count_correct_attempt": count_correct_attempt, "hosts": hosts, "users": users }, status=status.HTTP_200_OK) @api_view(['GET']) @permission_classes((IsAdminUser, )) def incorrectlogins_data(request): date_start_raw = request.GET.get('date_start') date_end_raw = request.GET.get('date_end') date_start_tz = None date_end_tz = None if not date_start_raw or not date_end_raw: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now else: date_start = datetime.fromtimestamp(int(date_start_raw)) date_start_tz = pytz.timezone(settings.TIME_ZONE).localize(date_start, is_dst=None) date_end = datetime.fromtimestamp(int(date_end_raw)) date_end_tz = pytz.timezone(settings.TIME_ZONE).localize(date_end, is_dst=None) if date_start_tz == date_end_tz: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now count_incorrect_attepmt = 0 count_hosts = [] temp_hosts = {} temp_users = {} dates = [] values = SecurityLoginAttemptIncorrect.objects.filter(time__range=[date_start_tz, date_end_tz]) for p in values: value = json.loads(p.value) attempt_count = 0 for host, v in value.get("hosts", {}).items(): attempt_count += v.get("count", 0) raw_date = v.get("last_date") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if host in temp_hosts: temp_hosts[host]["count"] = temp_hosts[host]["count"] + v.get("count", 0) temp_hosts[host]["last_date"] = date_tz.strftime("%b %d %H:%M") else: temp_hosts[host] = { "host": host, "count": v.get("count", 0), "last_date": date_tz.strftime("%b %d %H:%M") } for user, v in value.get("users", {}).items(): attempt_count += v.get("count") raw_date = v.get("last_date") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if user in temp_users: temp_users[user]["count"] = temp_users[user]["count"] + v.get("count") temp_users[user]["last_date"] = date_tz.strftime("%b %d %H:%M") else: temp_users[user] = { "username": user, "count": v.get("count"), "last_date": date_tz.strftime("%b %d %H:%M") } count_incorrect_attepmt += attempt_count count_hosts.append(attempt_count) dates.append(timezone.localtime(p.time).strftime("%b %d %H:%M")) hosts = [] for i in temp_hosts: hosts.append(temp_hosts[i]) if hosts: hosts.sort(key=lambda x: x["count"], reverse=True) hosts = hosts[:100] users = [] for i in temp_users: users.append(temp_users[i]) if users: users.sort(key=lambda x: x["count"], reverse=True) users = users[:100] date_range = { "start": time.mktime(timezone.localtime(date_start_tz).timetuple()), # time.mktime(timezone.localtime(timezone.now()).timetuple()), "start_date": time.mktime(timezone.localtime(date_start_tz).timetuple()) + 10, # time.mktime(timezone.localtime(timezone.now()).timetuple()), "end_date": time.mktime(timezone.localtime(date_end_tz).timetuple()), } if values: date_range["start"] = time.mktime(timezone.localtime(values[0].time).timetuple()) start_obj = SecurityLoginAttemptIncorrect.objects.all().first() if start_obj: date_range["start_date"] = time.mktime(timezone.localtime(start_obj.time).timetuple()) if date_range["start_date"] == date_range["end_date"]: date_range["end_date"] += 10 return Response({ "values": [{ "data": count_hosts, "label": 'Number of attempt incorrect login' }], "dates": dates, "date_range": date_range, "count_incorrect_attepmt": count_incorrect_attepmt, "hosts": hosts, "users": users }, status=status.HTTP_200_OK)
dspichkin/djangodashpanel
djangodashpanel/security/views.py
Python
gpl-3.0
9,113
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace Plasmosis { public partial class frmClassical : Form { private String cipher = ""; private string oldLongKey = ""; private string oldshortKey1 = ""; private string oldshortKey2 = ""; private String inputCipherForFile = ""; private String statusForfile = ""; private String inputForFile = ""; private String inputLongKeyForFile = ""; private String inputShortKey1ForFile = ""; private String inputShortKey2ForFile = ""; public frmClassical() { InitializeComponent(); //Initialy set the visible for key text boxes to false; longKey.Visible = false; shortKey1.Visible = false; shortKey2.Visible = false; } private void howToToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show(caesarShiftDecrypt(caesarShiftEncrypt("abc yo", 3), 3), "Hello I am How to"); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show(affineEncrypt("abc", 5, 3), "About the Crew"); } private String affineEncrypt(String str, int multiplier, int shift) { char[] charset = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=<>,.?/;:'\"[{]}|\\".ToCharArray(); int len = charset.Length; String result = ""; foreach (char c in str.ToCharArray()) { int j = 0; for (int i = 0; i < len; i++) { if (c.Equals(charset[i])) { j = i; i = len; } } j++; j = (j * multiplier + shift) % len; j--; for (int i = 0; i < len; i++) { if (i == j) { result += charset[i]; i = len; } } } return result; } // ###################### DOES NOT WORK ######################### // private String affineDecrypt(String str, int multiplier, int shift) { // Affine Decryption algorithm goes here. // Multiplier, Shift is garenteed to be an Integers. char[] charset = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=<>,.?/;:'\"[{]}|\\".ToCharArray(); int len = charset.Length; String result = ""; foreach (char c in str.ToCharArray()) { int j = 0; for (int i = 0; i < len; i++) { if (c.Equals(charset[i])) { j = i; i = len; } } j++; j = (j * multiplier - shift) % len; j--; for (int i = 0; i < len; i++) { if (i == j) { result += charset[i]; i = len; } } } return result; } private String caesarShiftEncrypt(String str, int shift) { char[] charset = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=<>,.?/;:'\"[{]}|\\".ToCharArray(); int len = charset.Length; String result = ""; foreach(char c in str.ToCharArray()) { int j = 0; for(int i = 0; i < len; i++) { if(c.Equals(charset[i])) { j = i; i = len; } } j = (j + shift) % len; for (int i = 0; i < len; i++) { if(i == j) { result += charset[i]; i = len; } } } return result; } private String caesarShiftDecrypt(String str, int shift) { char[] charset = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=<>,.?/;:'\"[{]}|\\".ToCharArray(); int len = charset.Length; String result = ""; foreach (char c in str.ToCharArray()) { int j = 0; for (int i = 0; i < len; i++) { if (c.Equals(charset[i])) { j = i; i = len; } } if (j - shift < 0) { j = len + ((j - shift) % len); } else { j = (j - shift) % len; } if(j == len) { j = j % len; } for (int i = 0; i < len; i++) { if (i == j) { result += charset[i]; i = len; } } } return result; } // Either Affine or Caesar decryption does not work properly. private void btnEncrypt_Click(object sender, EventArgs e) { switch (this.cipher) { case "Affine": if(!isInteger(shortKey1.Text) || !isInteger(shortKey2.Text)) { MessageBox.Show("Affine requires a multiplier in addition to a shift. For your key, please enter an integer for your multiplier and an integer for your shift separated by a comma (,). For example: 5,3 would be a multiplier of 5 and a shift of 3.", "Affine Alert!"); } else { int multiplier = int.Parse(shortKey1.Text); if(multiplier <= 0) { MessageBox.Show("The multiplier must be a positive integer!"); } else { txtOutput.Text = affineEncrypt(txtInput.Text, int.Parse(shortKey1.Text), int.Parse(shortKey2.Text)); statusForfile = "Encrypted"; } } break; case "Caesar": if(!isInteger(longKey.Text)) { MessageBox.Show("The shift must be an integer."); } else { txtOutput.Text = caesarShiftEncrypt(txtInput.Text, int.Parse(longKey.Text)); statusForfile = "Encrypted"; } break; } } //Decrypt button clicked. // ###################### DOES NOT WORK ######################### // private void btnDecrypt_Click(object sender, EventArgs e) { if(this.cipher.Equals("Affine")) { try { txtOutput.Text = affineDecrypt(txtInput.Text, int.Parse(shortKey1.Text), int.Parse(shortKey2.Text)); statusForfile = "Decrypted"; } catch (Exception error) { MessageBox.Show(error.Message + "\nPerhaps put Correct Input in [Key] section", "Error"); } } else if(this.cipher.Equals("Caesar")) { try { txtOutput.Text = caesarShiftDecrypt(txtInput.Text, int.Parse(longKey.Text)); statusForfile = "Decrypted"; } catch(Exception error) { MessageBox.Show(error.Message +"\nPerhaps put Correct Input in [Key] section", "Error"); } } } private void radAffine_CheckedChanged(object sender, EventArgs e) { this.cipher = "Affine"; //Swap text box visiblity. ex) show two text box shortKey1 for multiplier, shortkey2 for shift longKey.Visible = false; shortKey1.Visible = true; shortKey2.Visible = true; //Set the info label's text to explain the example input key value infoLabel.Text = " ↑ Multiplier ↑ Shift"; } private void radCaesar_CheckedChanged(object sender, EventArgs e) { this.cipher = "Caesar"; //Swap text box visiblity. ex) longkey for shift of shortKey1.Visible = false; shortKey2.Visible = false; longKey.Visible = true; //Set the info label's text to explain the example input key value infoLabel.Text = " ↑ Shift"; } //check to see if input is an integer https://msdn.microsoft.com/en-us/library/bb384043.aspx private Boolean isInteger(String str) { int result = 0; return int.TryParse(str, out result); } //Limit the text in the text box to be integer only. private void longKey_TextChanged(object sender, EventArgs e) { //check to see if new text is still integer. if(isInteger(longKey.Text) || longKey.Text.Equals("")) { oldLongKey = longKey.Text; } else { //oldLongKey is "" empty initially. MessageBox.Show("Please Type Numbers ONLY\nex) 0 - 9", "Error"); longKey.Text = oldLongKey; } } private void shortKey1_TextChanged(object sender, EventArgs e) { //check to see if new text is still integer. if (isInteger(shortKey1.Text) || shortKey1.Text.Equals("")) { oldshortKey1 = shortKey1.Text; } else { //shortKey1 is "" empty initially. MessageBox.Show("Please Type Integers ONLY\nex) 0 - 9", "Error"); shortKey1.Text = oldshortKey1; } } private void shortKey2_TextChanged(object sender, EventArgs e) { //check to see if new text is still integer. if (isInteger(shortKey2.Text) || shortKey2.Text.Equals("")) { oldshortKey2 = shortKey2.Text; } else { //shortKey2 is "" empty initially. MessageBox.Show("Please Type Integers ONLY\nex) 0 - 9", "Error"); shortKey2.Text = oldshortKey2; } } // Save to a file method. private void btnSave_Click(object sender, EventArgs e) { if (!this.txtOutput.Text.Equals("")) // works only if program has been used. { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "Save Result to a File"; if (saveFileDialog.ShowDialog() == DialogResult.OK) // if destination choosen { using (Stream destination = File.Open(saveFileDialog.FileName, FileMode.CreateNew)) using (StreamWriter kb = new StreamWriter(destination)) { // Output File Format. kb.WriteLine("# Thank you for using our Program Plasmosis."); kb.WriteLine("# Here are some Important information about the output"); kb.WriteLine(); kb.WriteLine(); kb.WriteLine("$ Saved Time : " + DateTime.Now); kb.WriteLine(); kb.WriteLine("$ Algorithm Used : " + inputCipherForFile); kb.WriteLine(); kb.WriteLine("$ Status : " + statusForfile); kb.WriteLine(); kb.WriteLine("$ Input Passed in : "); kb.WriteLine(); kb.WriteLine(inputForFile); kb.WriteLine(); if (inputCipherForFile.Equals("Affine")) { kb.WriteLine("$ The Key used : Mutiplier -> " + inputShortKey1ForFile + " , Shift -> " + inputShortKey2ForFile); } else if(inputCipherForFile.Equals("Caesar")) { kb.WriteLine("$ The Key used : Shift -> " + inputLongKeyForFile); } kb.WriteLine(); kb.WriteLine("$ Corresponding Output : "); kb.WriteLine(); kb.WriteLine(txtOutput.Text); } } } else { MessageBox.Show("Sorry, The output is empty.", "Error"); } } // When the output textbox field has been modified. private void txtOutput_TextChanged(object sender, EventArgs e) { // Save the state or the result of that output for Saving to a file later. inputCipherForFile = this.cipher; inputForFile = txtInput.Text; inputLongKeyForFile = longKey.Text; inputShortKey1ForFile = shortKey1.Text; inputShortKey2ForFile = shortKey2.Text; } } }
shawnkoon/Plasmosis
Plasmosis/Form1.cs
C#
gpl-3.0
14,513
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package solomonserver; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import runnables.ConnectClientsRunnable; import runnables.ConnectToUnityDemoRunnable; import runnables.ProcessDatabaseDataRunnable; /** * * @author beia */ public class SolomonServer { //solomon server variables public static ServerSocket serverSocket; public static Thread connectClients; public static Thread processDatabaseData; //unity demo server variables public static ServerSocket unityDemoServerSocket; public static Socket unityDemoSocket; public static Thread connectToUnityDemoThread; //sql server variables public static String error; public static Connection con; //data processing variables public static volatile int lastLocationEntryId = 1; public static void main(String[] args) throws IOException, SQLException, Exception { //connect to a mySql database connectToDatabase(); //create a tcp serverSocket and wait for client connections serverSocket = new ServerSocket(8000); connectClients = new Thread(new ConnectClientsRunnable(serverSocket)); connectClients.start(); unityDemoServerSocket = new ServerSocket(7000); connectToUnityDemoThread = new Thread(new ConnectToUnityDemoRunnable(unityDemoServerSocket)); connectToUnityDemoThread.start(); //extract user location data from the database and process it at a fixed amount of time processDatabaseData = new Thread(new ProcessDatabaseDataRunnable()); processDatabaseData.start(); } public static void connectToDatabase() throws ClassNotFoundException, SQLException, Exception { try { Class.forName("com.mysql.cj.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/solomondb?autoReconnect=true&useJDBCCompliantTimezoneShift=true&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC&useSSL=false", "root", "Puihoward_1423"); // nu uitati sa puneti parola corecta de root pe care o aveti setata pe serverul vostru de MySql. System.out.println("Successfully connected to the database!"); } catch (ClassNotFoundException cnfe) { error = "ClassNotFoundException: Can't find the driver for the database."; throw new ClassNotFoundException(error); } catch (SQLException cnfe) { cnfe.printStackTrace(); error = "SQLException: Can't connect to the database."; throw new SQLException(error); } catch (Exception e) { error = "Exception: Unexpected exception occured while we tried to connect to the database."; throw new Exception(error); } } public static void addUser(String username, String password, String lastName, String firstName, int age) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement String userInsertionStatement = "insert into users(username, password, lastName, firstName, age) values(?,?,?,?,?)"; PreparedStatement updateUsers = con.prepareStatement(userInsertionStatement); updateUsers.setString(1, username); updateUsers.setString(2, password); updateUsers.setString(3, lastName); updateUsers.setString(4, firstName); updateUsers.setInt(5, age); updateUsers.executeUpdate(); System.out.println("Inserted user '" + username + "'\n password: " + password + "\nlast name: " + lastName + "\nfirst name: " + firstName + "\nage: " + age + " into the database\n\n"); } catch (SQLException sqle) { error = "SqlException: Update failed; duplicates may exist."; throw new SQLException(error); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static void addLocationData(int idUser, int idStore, String zoneName, boolean zoneEntered, String time) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement String userLocationInsertionStatement = "insert into userlocations(idUser, idStore, zoneName, zoneEntered, time) values(?,?,?,?,?)"; PreparedStatement updateUserLocation = con.prepareStatement(userLocationInsertionStatement); updateUserLocation.setInt(1, idUser); updateUserLocation.setInt(2, idStore); updateUserLocation.setString(3, zoneName); updateUserLocation.setBoolean(4, zoneEntered); updateUserLocation.setString(5, time); updateUserLocation.executeUpdate(); System.out.println("Inserted userLocation into the database\nuser id: " + idUser + "\nstore id: " + idStore + "\nzone name: " + zoneName + "\nzone entered: " + zoneEntered + "\ntime: " + time + "\n\n"); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static void addZoneTimeData(int idUser, int idStore, String[] zonesTime) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement String userRoomTimeInsertionStatementFirstPart = "insert into userroomtime(idUser, idStore"; String userRoomTimeInsertionStatementLastPart = "values(" + idUser + ", " + idStore; String outputFeedBackString; Statement updateRoomTimeData = con.createStatement(); outputFeedBackString = "Inserted user room time data "; for(int i = 0; i < zonesTime.length; i++) { userRoomTimeInsertionStatementFirstPart += ", room" + (i + 1) + "Time"; userRoomTimeInsertionStatementLastPart += ", '" + zonesTime[i] + "'"; outputFeedBackString += "room" + (i + 1) + " time = " + zonesTime[i]; } userRoomTimeInsertionStatementFirstPart += ") "; userRoomTimeInsertionStatementLastPart += ")"; String statementString = userRoomTimeInsertionStatementFirstPart + userRoomTimeInsertionStatementLastPart; updateRoomTimeData.executeUpdate(statementString); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static void updateZoneTimeData(int idUser, int idStore, String zoneName, String zoneTime) throws SQLException, Exception { if (con != null) { try { // create a prepared SQL statement Statement updateStatement = con.createStatement(); String userRoomTimeUpdateStatement = "update userroomtime set " + zoneName + "='" + zoneTime + "' where idUser=" + idUser + " and idStore=" + idStore; updateStatement.executeUpdate(userRoomTimeUpdateStatement); } catch (SQLException sqle) { sqle.printStackTrace(); } } else { error = "Exception : Database connection was lost."; throw new Exception(error); } } public static ResultSet getUserDataFromDatabase(String tabelName, String username) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from " + tabelName + " where username = '" + username + "';"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } public static ResultSet getRoomTimeDataFromDatabase(String tableName, int idUser, int idStore) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from " + tableName + " where idUser=" + idUser + " and idStore=" + idStore); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } public static ResultSet getTableData(String tabelName) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from " + tabelName + ";"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } public static ResultSet getNewTableData(String tabelName, String idName, int lastId) throws SQLException, Exception { ResultSet rs = null; try { // Execute query String queryString = ("select * from "+ tabelName + " where " + idName + " > " + lastId); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(queryString); //sql exception } catch (SQLException sqle) { error = "SQLException: Query was not possible."; sqle.printStackTrace(); throw new SQLException(error); } catch (Exception e) { error = "Exception occured when we extracted the data."; throw new Exception(error); } return rs; } }
beia/beialand
projects/solomon/Server/SolomonServer/src/solomonserver/SolomonServer.java
Java
gpl-3.0
11,938
#include "BioXASCarbonFilterFarm.h" BioXASCarbonFilterFarm::BioXASCarbonFilterFarm(const QString &deviceName, QObject *parent) : BioXASBeamlineComponent(deviceName, parent) { // Create upstream actuator. upstreamActuator_ = new BioXASCarbonFilterFarmActuator(QString("%1%2").arg(deviceName).arg("UpstreamActuator"), this); addChildControl(upstreamActuator_); connect( upstreamActuator_, SIGNAL(motorChanged(CLSMAXvMotor*)), this, SIGNAL(upstreamActuatorMotorChanged(CLSMAXvMotor*)) ); connect( upstreamActuator_, SIGNAL(positionStatusChanged(AMControl*)), this, SIGNAL(upstreamActuatorPositionStatusChanged(AMControl*)) ); connect( upstreamActuator_, SIGNAL(windowsChanged()), this, SIGNAL(upstreamActuatorWindowsChanged()) ); connect( upstreamActuator_, SIGNAL(windowPreferencesChanged()), this, SIGNAL(upstreamActuatorWindowPreferencesChanged()) ); // Create downstream actuator. downstreamActuator_ = new BioXASCarbonFilterFarmActuator(QString("%1%2").arg(deviceName).arg("DownstreamActuator"), this); addChildControl(downstreamActuator_); connect( downstreamActuator_, SIGNAL(motorChanged(CLSMAXvMotor*)), this, SIGNAL(downstreamActuatorMotorChanged(CLSMAXvMotor*)) ); connect( downstreamActuator_, SIGNAL(positionStatusChanged(AMControl*)), this, SIGNAL(downstreamActuatorPositionStatusChanged(AMControl*)) ); connect( downstreamActuator_, SIGNAL(windowsChanged()), this, SIGNAL(downstreamActuatorWindowsChanged()) ); connect( downstreamActuator_, SIGNAL(windowPreferencesChanged()), this, SIGNAL(downstreamActuatorWindowPreferencesChanged()) ); // Create filter control. filter_ = new BioXASCarbonFilterFarmFilterControl(QString("%1%2").arg(name()).arg("Filter"), "um", this); addChildControl(filter_); filter_->setUpstreamFilter(upstreamActuator_->filter()); filter_->setDownstreamFilter(downstreamActuator_->filter()); connect( filter_, SIGNAL(valueChanged(double)), this, SIGNAL(filterValueChanged(double)) ); } BioXASCarbonFilterFarm::~BioXASCarbonFilterFarm() { } bool BioXASCarbonFilterFarm::isConnected() const { bool connected = ( upstreamActuator_ && upstreamActuator_->isConnected() && downstreamActuator_ && downstreamActuator_->isConnected() && filter_ && filter_->isConnected() ); return connected; } double BioXASCarbonFilterFarm::filterValue() const { double result = -1; if (filter_ && filter_->canMeasure()) result = filter_->value(); return result; } CLSMAXvMotor* BioXASCarbonFilterFarm::upstreamActuatorMotor() const { CLSMAXvMotor *motor = 0; if (upstreamActuator_) motor = upstreamActuator_->motor(); return motor; } AMControl* BioXASCarbonFilterFarm::upstreamActuatorPositionStatus() const { AMControl *positionStatus = 0; if (upstreamActuator_) positionStatus = upstreamActuator_->positionStatus(); return positionStatus; } CLSMAXvMotor* BioXASCarbonFilterFarm::downstreamActuatorMotor() const { CLSMAXvMotor *motor = 0; if (downstreamActuator_) motor = downstreamActuator_->motor(); return motor; } AMControl* BioXASCarbonFilterFarm::downstreamActuatorPositionStatus() const { AMControl *positionStatus = 0; if (downstreamActuator_) positionStatus = downstreamActuator_->positionStatus(); return positionStatus; } QString BioXASCarbonFilterFarm::windowToString(double window) const { QString result; switch (int(window)) { case Window::None: result = "None"; break; case Window::Bottom: result = "Bottom"; break; case Window::Top: result = "Top"; break; default: break; } return result; } void BioXASCarbonFilterFarm::setUpstreamActuatorMotor(CLSMAXvMotor *newControl) { if (upstreamActuator_) upstreamActuator_->setMotor(newControl); } void BioXASCarbonFilterFarm::setUpstreamActuatorPositionStatus(AMControl *newControl) { if (upstreamActuator_) upstreamActuator_->setPositionStatus(newControl); } void BioXASCarbonFilterFarm::addUpstreamActuatorWindow(int windowIndex, double positionSetpoint, double positionMin, double positionMax, double filter) { if (upstreamActuator_) upstreamActuator_->addWindow(windowIndex, windowToString(windowIndex), positionSetpoint, positionMin, positionMax, filter); } void BioXASCarbonFilterFarm::removeUpstreamActuatorWindow(int windowIndex) { if (upstreamActuator_) upstreamActuator_->removeWindow(windowIndex); } void BioXASCarbonFilterFarm::clearUpstreamActuatorWindows() { if (upstreamActuator_) upstreamActuator_->clearWindows(); } void BioXASCarbonFilterFarm::setUpstreamActuatorWindowPreference(double filter, int windowIndex) { if (upstreamActuator_) upstreamActuator_->setWindowPreference(filter, windowIndex); } void BioXASCarbonFilterFarm::removeUpstreamActuatorWindowPreference(double filter) { if (upstreamActuator_) upstreamActuator_->removeWindowPreference(filter); } void BioXASCarbonFilterFarm::clearUpstreamActuatorWindowPreferences() { if (upstreamActuator_) upstreamActuator_->clearWindowPreferences(); } void BioXASCarbonFilterFarm::setDownstreamActuatorMotor(CLSMAXvMotor *newControl) { if (downstreamActuator_) downstreamActuator_->setMotor(newControl); } void BioXASCarbonFilterFarm::setDownstreamActuatorPositionStatus(AMControl *newControl) { if (downstreamActuator_) downstreamActuator_->setPositionStatus(newControl); } void BioXASCarbonFilterFarm::addDownstreamActuatorWindow(int windowIndex, double positionSetpoint, double positionMin, double positionMax, double filter) { if (downstreamActuator_) downstreamActuator_->addWindow(windowIndex, windowToString(windowIndex), positionSetpoint, positionMin, positionMax, filter); } void BioXASCarbonFilterFarm::removeDownstreamActuatorWindow(int windowIndex) { if (downstreamActuator_) downstreamActuator_->removeWindow(windowIndex); } void BioXASCarbonFilterFarm::clearDownstreamActuatorWindows() { if (downstreamActuator_) downstreamActuator_->clearWindows(); } void BioXASCarbonFilterFarm::setDownstreamActuatorWindowPreference(double filter, int windowIndex) { if (downstreamActuator_) downstreamActuator_->setWindowPreference(filter, windowIndex); } void BioXASCarbonFilterFarm::removeDownstreamActuatorWindowPreference(double filter) { if (downstreamActuator_) downstreamActuator_->removeWindowPreference(filter); } void BioXASCarbonFilterFarm::clearDownstreamActuatorWindowPreferences() { if (downstreamActuator_) downstreamActuator_->clearWindowPreferences(); } void BioXASCarbonFilterFarm::clearWindows() { clearUpstreamActuatorWindows(); clearDownstreamActuatorWindows(); } void BioXASCarbonFilterFarm::clearWindowPreferences() { clearUpstreamActuatorWindowPreferences(); clearDownstreamActuatorWindowPreferences(); }
acquaman/acquaman
source/beamline/BioXAS/BioXASCarbonFilterFarm.cpp
C++
gpl-3.0
6,658
package org.optimizationBenchmarking.evaluator.attributes.clusters.propertyValueGroups; import org.optimizationBenchmarking.utils.math.NumericalTypes; import org.optimizationBenchmarking.utils.math.functions.arithmetic.Div; import org.optimizationBenchmarking.utils.math.functions.arithmetic.Mul; import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingAdd; import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingSub; import org.optimizationBenchmarking.utils.math.functions.power.Log; import org.optimizationBenchmarking.utils.math.functions.power.Pow; import org.optimizationBenchmarking.utils.text.TextUtils; /** * A set of different modi for grouping elements. */ public enum EGroupingMode { /** Group distinct values, i.e., each value becomes an own group */ DISTINCT { /** {@inheritDoc} */ @Override _Groups _groupObjects(final Number param, final Object[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { int count; count = 0; for (final _Group group : buffer) { group.m_size = 1; group.m_isUpperExclusive = false; group.m_lower = group.m_upper = data[count++]; } return new _Groups(buffer, minGroups, maxGroups, this, null); } /** {@inheritDoc} */ @Override _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { return this._groupObjects(param, data, minGroups, maxGroups, buffer); } /** {@inheritDoc} */ @Override _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { return this._groupObjects(param, data, minGroups, maxGroups, buffer); } }, /** * Group elements in terms of reasonable powers, including powers of * {@code 2}, {@code 10}, etc. */ POWERS { /** {@inheritDoc} */ @Override final _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final long pl; _Groups best, current; if (param != null) { pl = param.longValue(); best = EGroupingMode._groupLongsByPowerRange(pl, data, minGroups, maxGroups, buffer); if ((param instanceof Float) || (param instanceof Double)) { if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { current = EGroupingMode._groupLongsByPowerRange((pl + 1L), data, minGroups, maxGroups, buffer); if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best != null) { return best; } } else { best = null; } for (final long power : EGroupingMode.POWER_CHOICES) { current = EGroupingMode._groupLongsByPowerRange(power, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupLongs(param, data, minGroups, maxGroups, buffer); } return best; } /** {@inheritDoc} */ @Override final _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final double dl; _Groups best, current; if (param != null) { dl = param.doubleValue(); best = EGroupingMode._groupDoublesByPowerRange(dl, data, minGroups, maxGroups, buffer); if (best != null) { return best; } } else { best = null; } for (final long power : EGroupingMode.POWER_CHOICES) { current = EGroupingMode._groupDoublesByPowerRange(power, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, buffer); } return best; } }, /** * Group elements in terms of reasonable multiples, including multipes of * {@code 1}, {@code 2}, {@code 10}, etc. */ MULTIPLES { /** {@inheritDoc} */ @Override final _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final long pl; _Groups best, current; if (param != null) { pl = param.longValue(); best = EGroupingMode._groupLongsByMultipleRange(pl, data, minGroups, maxGroups, buffer); if ((param instanceof Float) || (param instanceof Double)) { if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { current = EGroupingMode._groupLongsByMultipleRange((pl + 1L), data, minGroups, maxGroups, buffer); if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best != null) { return best; } } else { best = null; } for (final long range : EGroupingMode.MULTIPLE_CHOICES_L) { current = EGroupingMode._groupLongsByMultipleRange(range, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupLongs(param, data, minGroups, maxGroups, buffer); } return best; } /** {@inheritDoc} */ @Override final _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { final double dl; _Groups best, current; if (param != null) { dl = param.doubleValue(); best = EGroupingMode._groupDoublesByMultipleRange(dl, data, minGroups, maxGroups, buffer); if (best != null) { return best; } } else { best = null; } for (final double range : EGroupingMode.MULTIPLE_CHOICES_D) { current = EGroupingMode._groupDoublesByMultipleRange(range, data, minGroups, maxGroups, buffer); if (current != null) { if ((best == null) || (current.compareTo(best) < 0)) { best = current; } } } if (best == null) { return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, buffer); } return best; } }, /** Group according to any possible choice */ ANY { /** {@inheritDoc} */ @Override final _Groups _groupObjects(final Number param, final Object[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { return DISTINCT._groupObjects(param, data, minGroups, maxGroups, buffer); } /** {@inheritDoc} */ @Override _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { _Groups best, current; best = DISTINCT._groupLongs(param, data, minGroups, maxGroups, buffer); current = POWERS._groupLongs(param, data, minGroups, maxGroups, buffer); if (current.compareTo(best) < 0) { best = current; } current = MULTIPLES._groupLongs(param, data, minGroups, maxGroups, buffer); if ((current != null) && (current.compareTo(best) < 0)) { best = current; } return best; } /** {@inheritDoc} */ @Override _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { _Groups best, current; best = DISTINCT._groupDoubles(param, data, minGroups, maxGroups, buffer); current = POWERS._groupDoubles(param, data, minGroups, maxGroups, buffer); if (current.compareTo(best) < 0) { best = current; } current = MULTIPLES._groupDoubles(param, data, minGroups, maxGroups, buffer); if ((current != null) && (current.compareTo(best) < 0)) { best = current; } return best; } } ; /** the power choices */ static final long[] POWER_CHOICES = { 10L, 2L, 100L, 4L, 1000L, 8L, 16L, 10000L, 1024L, 32L, 64L, 256L, 512L, }; /** the choices for the {@code long} multiples */ static final long[] MULTIPLE_CHOICES_L = { 2L, 3L, 4L, 5L, 10L, 15L, 20L, 25L, 30L, 40L, 50L, 75L, 100L, 200L, 250L, 500L, 750L, 1_000L, 1_500L, 2_000L, 2_500L, 5_000L, 10_000L, 100_000L, 1_000_000L, 10_000_000L, 100_000_000L, 1_000_000_000L, 10_000_000_000L, 100_000_000_000L, 1_000_000_000_000L }; /** the choices for the {@code double} multiples */ static final double[] MULTIPLE_CHOICES_D = { 1e-30d, 1e-24d, 1e-21d, 1e-18d, 1e-15d, 1e-12d, 1e-9d, 1e-6, 1e-5, 1e-4d, 1E-3d, 1E-2d, 1E-1d, 0.125d, 0.2d, 0.25d, 0.3d, (1d / 3d), 0.4d, 0.5d, 0.75d, 1d, 1.5d, 2d, 2.5d, 3d, 4d, 5d, 7.5d, 10d, 15d, 20d, 25d, 30d, 40d, 50d, 75d, 100d, 200d, 250d, 500d, 750d, 1_000d, 1_500d, 2_000d, 2_500d, 5_000d, 1e4d, 1e5d, 1e6d, 1e7d, 1e8d, 1e9d, 1e10d, 1e12d, 1e15d, 1e18d, 1e20d, 1e21d, 1e24d, 1e27d, 1e30d, 1e35d, 1e40d, 1e50d, 1e60d, 1e70d, 1e100d, 1e200d, 1e300d }; /** the name */ private final String m_name; /** * Create a grouping * * @param param * the parameter * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ _Groups _groupObjects(final Number param, final Object[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { throw new UnsupportedOperationException("Mode " + this + //$NON-NLS-1$ " can only apply to numbers."); //$NON-NLS-1$ } /** * Create a grouping * * @param param * the parameter * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ abstract _Groups _groupLongs(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer); /** * Create a grouping * * @param param * the parameter * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ abstract _Groups _groupDoubles(final Number param, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer); /** * @param power * the power to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupLongsByPowerRange(final long power, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { long prev, next, cur; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; boolean exclusive; if (power <= 1L) { return null; } next = power; do { prev = next; next *= power; } while (next > prev); next = (-prev); prev = Long.MIN_VALUE; exclusiveMaxIndex = 0; groupIndex = 0; exclusive = true; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].longValue(); if (cur < prev) { break inner; } if (exclusive) { if (cur >= next) { break inner; } } else { if (cur > next) { break inner; } } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = NumericalTypes.valueOf(prev); group.m_upper = NumericalTypes.valueOf(next); group.m_isUpperExclusive = exclusive; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (prev > 0L) { if (next >= Long.MAX_VALUE) { throw new IllegalStateException(// "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ } next *= power; if (next <= prev) { next = Long.MAX_VALUE; exclusive = false; } } else { if (prev == 0L) { next = power; } else { next /= power; } } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, POWERS, // NumericalTypes.valueOf(power)); } /** * @param power * the power to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupDoublesByPowerRange(final double power, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { double prev, next, cur; long pwr; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; boolean exclusive; if ((power <= 1d) || (power != power) || (power >= Double.POSITIVE_INFINITY)) { return null; } pwr = (((long) (Log.INSTANCE.computeAsDouble(power, Double.MAX_VALUE))) + 1L); prev = Double.NEGATIVE_INFINITY; while ((next = (-Pow.INSTANCE.computeAsDouble(power, pwr))) <= prev) { pwr--; } if ((prev != prev) || (next != next)) { return null; // not possible. } exclusiveMaxIndex = 0; groupIndex = 0; exclusive = true; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].doubleValue(); if (cur < prev) { break inner; } if (exclusive) { if (cur >= next) { break inner; } } else { if (cur > next) { break inner; } } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = NumericalTypes.valueOf(prev); group.m_upper = NumericalTypes.valueOf(next); group.m_isUpperExclusive = exclusive; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (next > 0d) { if (next >= Double.POSITIVE_INFINITY) { throw new IllegalStateException(// "There are double values bigger than POSITIVE_INFINITY??"); //$NON-NLS-1$ } next = Pow.INSTANCE.computeAsDouble(power, (++pwr)); if (next >= Double.POSITIVE_INFINITY) { exclusive = false; } else { if (next != next) { return null; } } } else { if (prev == 0d) { pwr = (((long) (Log.INSTANCE.computeAsDouble(power, Double.MIN_VALUE))) - 1L); while ((next = Pow.INSTANCE.computeAsDouble(power, pwr)) <= 0d) { pwr++; } } else { next = (-(Pow.INSTANCE.computeAsDouble(power, (--pwr)))); if (next == 0d) { next = 0d; // deal with -0d -> 0d } else { if (next != next) { return null; } } } } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, POWERS, // NumericalTypes.valueOf(pwr)); } /** * Group longs by range * * @param range * the range to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupLongsByMultipleRange(final long range, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { long prev, next, cur; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; boolean exclusive; if (range <= 0L) { return null; } cur = data[0].longValue(); next = (cur / range); prev = (data[data.length - 1].longValue() / range); if (SaturatingAdd.INSTANCE.computeAsLong(// ((next > Long.MIN_VALUE) ? Math.abs(next) : Long.MAX_VALUE), // ((prev > Long.MIN_VALUE) ? Math.abs(prev) : Long.MAX_VALUE)) >= 1000L) { return null; // too many steps! } if (next >= prev) { return null;// range to big } next *= range; prev = next; if (prev <= 0L) { while (prev > cur) { prev = SaturatingSub.INSTANCE.computeAsLong(prev, range); } } next = SaturatingAdd.INSTANCE.computeAsLong(prev, range); exclusiveMaxIndex = 0; groupIndex = 0; exclusive = true; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].longValue(); if (cur < prev) { break inner; } if (exclusive) { if (cur >= next) { break inner; } } else { if (cur > next) { break inner; } } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = Long.valueOf(prev); group.m_upper = Long.valueOf(next); group.m_isUpperExclusive = exclusive; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (next >= Long.MAX_VALUE) { throw new IllegalStateException(// "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ } next = SaturatingAdd.INSTANCE.computeAsLong(next, range); if (next >= Long.MAX_VALUE) { exclusive = false; } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, NumericalTypes.valueOf(range)); } /** * Group longs by range * * @param range * the range to group by * @param data * the data * @param minGroups * the anticipated minimum number of groups * @param maxGroups * the anticipated maximum number of groups * @param buffer * a multi-purpose buffer * @return the objects to group */ static _Groups _groupDoublesByMultipleRange(final double range, final Number[] data, final int minGroups, final int maxGroups, final _Group[] buffer) { double prev, next, cur, span; long prevMul; int minIndex, exclusiveMaxIndex, groupIndex; _Group group; if ((range <= 0d) || (range != range) || (range >= Double.POSITIVE_INFINITY)) { return null; } cur = data[0].doubleValue(); prev = Div.INSTANCE.computeAsDouble(cur, range); next = Div.INSTANCE .computeAsDouble(data[data.length - 1].doubleValue(), range); if ((prev != prev) || // (next != next) || // ((span = (Math.abs(next) + Math.abs(prev))) >= 1000d) || // (span != span) || // (Math.ceil(prev) >= Math.floor(next))) { return null; // too many steps! } prevMul = ((long) (prev)); if (prevMul != prev) { return null; // cannot use the range due to imprecision } next = prev = Mul.INSTANCE.computeAsDouble(prevMul, range); if ((prev + range) <= prev) { return null; } if (prev <= 0d) { while (prev > cur) { if (prevMul <= Long.MIN_VALUE) { return null; } prevMul--; prev = Mul.INSTANCE.computeAsDouble(prevMul, range); if ((prev + range) <= prev) { return null; } } } if (prevMul >= Long.MAX_VALUE) { return null; } next = Mul.INSTANCE.computeAsDouble((++prevMul), range); if (next <= prev) { return null; } exclusiveMaxIndex = 0; groupIndex = 0; // First, we want to find all the negative powers, then the positive // ones. outer: for (;;) { if (exclusiveMaxIndex >= data.length) { break outer; } minIndex = exclusiveMaxIndex; inner: for (;;) { cur = data[exclusiveMaxIndex].longValue(); if ((cur < prev) || (cur >= next)) { break inner; } exclusiveMaxIndex++; if (exclusiveMaxIndex >= data.length) { break inner; } } if (exclusiveMaxIndex > minIndex) { group = buffer[groupIndex++]; group.m_lower = Double.valueOf(prev); group.m_upper = Double.valueOf(next); group.m_isUpperExclusive = true; group.m_size = (exclusiveMaxIndex - minIndex); if ((exclusiveMaxIndex >= data.length) || // (groupIndex >= buffer.length)) { break outer; } } prev = next; if (prevMul >= Long.MAX_VALUE) { return null; } prevMul++; next = Mul.INSTANCE.computeAsDouble(prevMul, range); if (next <= prev) { return null; } } if (groupIndex < buffer.length) { buffer[groupIndex].m_size = (-1); } return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, NumericalTypes.valueOf(range)); } /** create the grouping mode */ EGroupingMode() { this.m_name = TextUtils.toLowerCase(super.toString()); } /** {@inheritDoc} */ @Override public final String toString() { return this.m_name; } }
optimizationBenchmarking/evaluator-attributes
src/main/java/org/optimizationBenchmarking/evaluator/attributes/clusters/propertyValueGroups/EGroupingMode.java
Java
gpl-3.0
24,903
// Copyright 2014 The go-krypton Authors // This file is part of the go-krypton library. // // The go-krypton 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 3 of the License, or // (at your option) any later version. // // The go-krypton 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 the go-krypton library. If not, see <http://www.gnu.org/licenses/>. package types import ( "fmt" "io" "math/big" "github.com/krypton/go-krypton/common" "github.com/krypton/go-krypton/core/vm" "github.com/krypton/go-krypton/rlp" ) // Receipt represents the results of a transaction. type Receipt struct { // Consensus fields PostState []byte CumulativeGasUsed *big.Int Bloom Bloom Logs vm.Logs // Implementation fields TxHash common.Hash ContractAddress common.Address GasUsed *big.Int } // NewReceipt creates a barebone transaction receipt, copying the init fields. func NewReceipt(root []byte, cumulativeGasUsed *big.Int) *Receipt { return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)} } // EncodeRLP implements rlp.Encoder, and flattens the consensus fields of a receipt // into an RLP stream. func (r *Receipt) EncodeRLP(w io.Writer) error { return rlp.Encode(w, []interface{}{r.PostState, r.CumulativeGasUsed, r.Bloom, r.Logs}) } // DecodeRLP implements rlp.Decoder, and loads the consensus fields of a receipt // from an RLP stream. func (r *Receipt) DecodeRLP(s *rlp.Stream) error { var receipt struct { PostState []byte CumulativeGasUsed *big.Int Bloom Bloom Logs vm.Logs } if err := s.Decode(&receipt); err != nil { return err } r.PostState, r.CumulativeGasUsed, r.Bloom, r.Logs = receipt.PostState, receipt.CumulativeGasUsed, receipt.Bloom, receipt.Logs return nil } // RlpEncode implements common.RlpEncode required for SHA3 derivation. func (r *Receipt) RlpEncode() []byte { bytes, err := rlp.EncodeToBytes(r) if err != nil { panic(err) } return bytes } // String implements the Stringer interface. func (r *Receipt) String() string { return fmt.Sprintf("receipt{med=%x cgas=%v bloom=%x logs=%v}", r.PostState, r.CumulativeGasUsed, r.Bloom, r.Logs) } // ReceiptForStorage is a wrapper around a Receipt that flattens and parses the // entire content of a receipt, as opposed to only the consensus fields originally. type ReceiptForStorage Receipt // EncodeRLP implements rlp.Encoder, and flattens all content fields of a receipt // into an RLP stream. func (r *ReceiptForStorage) EncodeRLP(w io.Writer) error { logs := make([]*vm.LogForStorage, len(r.Logs)) for i, log := range r.Logs { logs[i] = (*vm.LogForStorage)(log) } return rlp.Encode(w, []interface{}{r.PostState, r.CumulativeGasUsed, r.Bloom, r.TxHash, r.ContractAddress, logs, r.GasUsed}) } // DecodeRLP implements rlp.Decoder, and loads both consensus and implementation // fields of a receipt from an RLP stream. func (r *ReceiptForStorage) DecodeRLP(s *rlp.Stream) error { var receipt struct { PostState []byte CumulativeGasUsed *big.Int Bloom Bloom TxHash common.Hash ContractAddress common.Address Logs []*vm.LogForStorage GasUsed *big.Int } if err := s.Decode(&receipt); err != nil { return err } // Assign the consensus fields r.PostState, r.CumulativeGasUsed, r.Bloom = receipt.PostState, receipt.CumulativeGasUsed, receipt.Bloom r.Logs = make(vm.Logs, len(receipt.Logs)) for i, log := range receipt.Logs { r.Logs[i] = (*vm.Log)(log) } // Assign the implementation fields r.TxHash, r.ContractAddress, r.GasUsed = receipt.TxHash, receipt.ContractAddress, receipt.GasUsed return nil } // Receipts is a wrapper around a Receipt array to implement types.DerivableList. type Receipts []*Receipt // RlpEncode implements common.RlpEncode required for SHA3 derivation. func (r Receipts) RlpEncode() []byte { bytes, err := rlp.EncodeToBytes(r) if err != nil { panic(err) } return bytes } // Len returns the number of receipts in this list. func (r Receipts) Len() int { return len(r) } // GetRlp returns the RLP encoding of one receipt from the list. func (r Receipts) GetRlp(i int) []byte { return common.Rlp(r[i]) }
covertress/go-krypton
core/types/receipt.go
GO
gpl-3.0
4,699
#!/usr/bin/env ruby #--------------------------------------------------------------- ## ## GridEngine plugin for Collectd ## ## This 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: Victor Penso ## Copyright 2012 ## Version: 0.0.1 ##---------------------------------------------------------------- hostname = ENV.has_key?('COLLECTD_HOSTNAME') ? ENV['COLLECTD_HOSTNAME'] : 'localhost' interval = ENV.has_key?('COLLECTD_INTERVAL') ? ENV['COLLECTD_INTERVAL'].to_i : 60 command = %q[qstat -ext -u '*'] while true time=`date +%s`.chop jobs = { :running => 0, :queued => 0, :suspended => 0 } qstat = `#{command}` unless qstat.nil? qstat.split("\n")[2..-1].each do |job| # get the job state job.split[7].each_char do |flag| case flag when 'r' jobs[:running] += 1 when 'q' jobs[:queued] += 1 when 's','S' jobs[:suspended] += 1 end end end end puts %Q[PUTVAL #{hostname}/gridengine/gridengine_jobs interval=#{interval} #{time}:#{jobs[:running]}:#{jobs[:queued]}:#{jobs[:suspended]} ] $stdout.flush # make sure to always write the output buffer before sleep sleep interval end
vpenso/collectd-exec-plugins
gridengine-jobs.rb
Ruby
gpl-3.0
1,860
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-10 04:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('article', '0002_auto_20160810_0134'), ] operations = [ migrations.RemoveField( model_name='article', name='content_1', ), migrations.AddField( model_name='article', name='content', field=models.CharField(default=0, max_length=10000, verbose_name='内容'), preserve_default=False, ), migrations.AlterField( model_name='article', name='title', field=models.CharField(max_length=100, verbose_name='标题'), ), ]
zhangvs1988/zhangyl-Djangodemo
article/migrations/0003_auto_20160810_1219.py
Python
gpl-3.0
806
export { AbilityScoresViewModel } from './ability_scores'; export { ActionsToolbarViewModel } from './actions_toolbar'; export { ArmorViewModel } from './armor'; export { CharacterNameViewModel } from './character_name'; export { CharacterPortraitModel } from './character_portrait'; export { CharacterStatusLineViewModel } from './character_status_line'; export { BackgroundViewModel } from './background'; export { FeatsViewModel } from './feats'; export { FeaturesViewModel } from './features'; export { ItemsViewModel } from './items'; export { MagicItemsViewModel } from './magic_items'; export { ProficienciesViewModel } from './proficiencies'; export { ProfileViewModel } from './profile'; export { CharacterRootViewModel } from './root'; export { SkillsViewModel } from './skills'; export { SpellSlotsViewModel } from './spell_slots'; export { SpellStatsViewModel } from './spell_stats'; export { SpellbookViewModel } from './spells'; export { StatsViewModel } from './stats'; export { TrackerViewModel } from './tracker'; export { TraitsViewModel } from './traits'; export { WealthViewModel } from './wealth'; export { WeaponsViewModel } from './weapons'; export { OtherStatsViewModel } from './other_stats';
adventurerscodex/adventurerscodex
src/charactersheet/viewmodels/character/index.js
JavaScript
gpl-3.0
1,218
#include "mssmUtils.h" #include "softsusy.h" #include <iostream> namespace softsusy { double sw2 = 1.0 - sqr(MW / MZ), gnuL = 0.5, guL = 0.5 - 2.0 * sw2 / 3.0, gdL = -0.5 + sw2 / 3.0, geL = -0.5 + sw2, guR = 2.0 * sw2 / 3.0, gdR = -sw2 / 3.0, geR = -sw2, yuL = 1.0 / 3.0, yuR = -4.0 / 3.0, ydL = 1.0 / 3.0, ydR = 2.0 / 3.0, yeL = -1.0, yeR = 2.0, ynuL = -1.0; void generalBcs(MssmSoftsusy & m, const DoubleVector & inputParameters) { MssmSusy s; SoftParsMssm r; double m3sq = m.displayM3Squared(); s = m.displaySusy(); r.set(inputParameters); r.setM3Squared(m3sq); m.setSoftPars(r); m.setSusy(s); return; } /// This one doesn't overwrite mh1sq or mh2sq at the high scale void generalBcs2(MssmSoftsusy & m, const DoubleVector & inputParameters) { MssmSusy s; SoftParsMssm r; double mh1sq = m.displayMh1Squared(); double mh2sq = m.displayMh2Squared(); double m3sq = m.displayM3Squared(); s = m.displaySusy(); r.set(inputParameters); r.setMh1Squared(mh1sq); r.setMh2Squared(mh2sq); r.setM3Squared(m3sq); m.setSoftPars(r); m.setSusy(s); return; } void extendedSugraBcs(MssmSoftsusy & m, const DoubleVector & inputParameters) { int i; for (i=1; i<=3; i++) m.setGauginoMass(i, inputParameters.display(i)); if (inputParameters.display(25) > 1. && m.displaySetTbAtMX()) m.setTanb(inputParameters.display(25)); m.setTrilinearElement(UA, 1, 1, m.displayYukawaElement(YU, 1, 1) * inputParameters.display(11)); m.setTrilinearElement(UA, 2, 2, m.displayYukawaElement(YU, 2, 2) * inputParameters.display(11)); m.setTrilinearElement(UA, 3, 3, m.displayYukawaElement(YU, 3, 3) * inputParameters.display(11)); m.setTrilinearElement(DA, 1, 1, m.displayYukawaElement(YD, 1, 1) * inputParameters.display(12)); m.setTrilinearElement(DA, 2, 2, m.displayYukawaElement(YD, 2, 2) * inputParameters.display(12)); m.setTrilinearElement(DA, 3, 3, m.displayYukawaElement(YD, 3, 3) * inputParameters.display(12)); m.setTrilinearElement(EA, 1, 1, m.displayYukawaElement(YE, 1, 1) * inputParameters.display(13)); m.setTrilinearElement(EA, 2, 2, m.displayYukawaElement(YE, 2, 2) * inputParameters.display(13)); m.setTrilinearElement(EA, 3, 3, m.displayYukawaElement(YE, 3, 3) * inputParameters.display(13)); m.setSoftMassElement(mLl, 1, 1, signedSqr(inputParameters.display(31))); m.setSoftMassElement(mLl, 2, 2, signedSqr(inputParameters.display(32))); m.setSoftMassElement(mLl, 3, 3, signedSqr(inputParameters.display(33))); m.setSoftMassElement(mEr, 1, 1, signedSqr(inputParameters.display(34))); m.setSoftMassElement(mEr, 2, 2, signedSqr(inputParameters.display(35))); m.setSoftMassElement(mEr, 3, 3, signedSqr(inputParameters.display(36))); m.setSoftMassElement(mQl, 1, 1, signedSqr(inputParameters.display(41))); m.setSoftMassElement(mQl, 2, 2, signedSqr(inputParameters.display(42))); m.setSoftMassElement(mQl, 3, 3, signedSqr(inputParameters.display(43))); m.setSoftMassElement(mUr, 1, 1, signedSqr(inputParameters.display(44))); m.setSoftMassElement(mUr, 2, 2, signedSqr(inputParameters.display(45))); m.setSoftMassElement(mUr, 3, 3, signedSqr(inputParameters.display(46))); m.setSoftMassElement(mDr, 1, 1, signedSqr(inputParameters.display(47))); m.setSoftMassElement(mDr, 2, 2, signedSqr(inputParameters.display(48))); m.setSoftMassElement(mDr, 3, 3, signedSqr(inputParameters.display(49))); if (!m.displayAltEwsb()) { m.setMh1Squared(inputParameters.display(21)); m.setMh2Squared(inputParameters.display(22)); } } /// universal mSUGRA boundary conditions void sugraBcs(MssmSoftsusy & m, const DoubleVector & inputParameters) { double m0 = inputParameters.display(1); double m12 = inputParameters.display(2); double a0 = inputParameters.display(3); /// Sets scalar soft masses equal to m0, fermion ones to m12 and sets the /// trilinear scalar coupling to be a0 /// if (m0 < 0.0) m.flagTachyon(true); Deleted on request from A Pukhov m.standardSugra(m0, m12, a0); return; } void nuhmI(MssmSoftsusy & m, const DoubleVector & inputParameters) { double m0 = inputParameters.display(1); double m12 = inputParameters.display(2); double mH = inputParameters.display(3); double a0 = inputParameters.display(4); /// Sets scalar soft masses equal to m0, fermion ones to m12 and sets the /// trilinear scalar coupling to be a0 /// if (m0 < 0.0) m.flagTachyon(true); Deleted on request from A Pukhov m.standardSugra(m0, m12, a0); m.setMh1Squared(mH * mH); m.setMh2Squared(mH * mH); return; } void nuhmII(MssmSoftsusy & m, const DoubleVector & inputParameters) { double m0 = inputParameters.display(1); double m12 = inputParameters.display(2); double mH1 = inputParameters.display(3); double mH2 = inputParameters.display(4); double a0 = inputParameters.display(5); /// Sets scalar soft masses equal to m0, fermion ones to m12 and sets the /// trilinear scalar coupling to be a0 /// if (m0 < 0.0) m.flagTachyon(true); Deleted on request from A Pukhov m.standardSugra(m0, m12, a0); m.setMh1Squared(mH1 * mH1); m.setMh2Squared(mH2 * mH2); return; } /// Other types of boundary condition void amsbBcs(MssmSoftsusy & m, const DoubleVector & inputParameters) { double m32 = inputParameters.display(1); double m0 = inputParameters.display(2); m.standardSugra(m0, 0., 0.); m.addAmsb(m32); return; } void lvsBcs(MssmSoftsusy & m, const DoubleVector & inputParameters) { double m0 = inputParameters.display(1); double m12 = inputParameters.display(1) * sqrt(3.); double a0 = -inputParameters.display(1) * sqrt(3.); m.standardSugra(m0, m12, a0); return; } void gmsbBcs(MssmSoftsusy & m, const DoubleVector & inputParameters) { int n5 = int(inputParameters.display(1)); double mMess = inputParameters.display(2); double lambda = inputParameters.display(3); double cgrav = inputParameters.display(4); m.minimalGmsb(n5, lambda, mMess, cgrav); return; } void userDefinedBcs(MssmSoftsusy & m, const DoubleVector & inputParameters) { m.methodBoundaryCondition(inputParameters); sugraBcs(m, inputParameters); } void nonUniGauginos(MssmSoftsusy & m, const DoubleVector & inputParameters) { double m0 = inputParameters.display(1); double m12 = inputParameters.display(2); double a0 = inputParameters.display(3); /// Sets scalar soft masses equal to m0, fermion ones to m12 and sets the /// trilinear scalar coupling to be a0 /// if (m0 < 0.0) m.flagTachyon(true); Deleted on request from A Pukhov m.standardSugra(m0, m12, a0); m.setGauginoMass(2, inputParameters.display(4)); m.setGauginoMass(3, inputParameters.display(5)); return; } // Boundary conditions of split gauge mediated SUSY breaking (see // http://www.physics.rutgers.edu/~somalwar/conlsp/slepton-coNLSP.pdf // for example). Note that here, mu is set at mMess instead of at the // electroweak scale. void splitGmsb(MssmSoftsusy & m, const DoubleVector & inputParameters) { double n5 = inputParameters(1); double lambdaL = inputParameters(2); double lambdaD = inputParameters(3); double mMess = inputParameters(4); double muOm2 = inputParameters(5); double mAOm2 = inputParameters(6); double cgrav = inputParameters(7); double lambda1 = n5 * (0.6 * lambdaL + 0.4 * lambdaD); double lambda2 = n5 * lambdaL; double lambda3 = n5 * lambdaD; double m1, m2, m3; m1 = sqr(m.displayGaugeCoupling(1)) / (16.0 * sqr(PI)) * lambda1; m2 = sqr(m.displayGaugeCoupling(2)) / (16.0 * sqr(PI)) * lambda2; m3 = sqr(m.displayGaugeCoupling(3)) / (16.0 * sqr(PI)) * lambda3; m.setGauginoMass(1, m1); m.setGauginoMass(2, m2); m.setGauginoMass(3, m3); m.setM32(2.37e-19 * sqrt((sqr(lambdaL) + sqr(lambdaD)) * 0.5) * mMess * cgrav); m.setM32(2.37e-19 * sqrt((sqr(lambdaL) + sqr(lambdaD)) * 0.5) * mMess * cgrav); double g1f = sqr(sqr(m.displayGaugeCoupling(1))); double g2f = sqr(sqr(m.displayGaugeCoupling(2))); double g3f = sqr(sqr(m.displayGaugeCoupling(3))); double lambdaP1sq = n5 * (0.6 * sqr(lambdaL) + 0.4 * sqr(lambdaD)); double lambdaP2sq = n5 * sqr(lambdaL); double lambdaP3sq = n5 * sqr(lambdaD); double mursq, mdrsq, mersq, mqlsq, mllsq; mursq = 2.0 * (4.0 / 3.0 * g3f * lambdaP3sq + 0.6 * 4.0 / 9.0 * g1f * lambdaP1sq) / sqr(16.0 * sqr(PI)); mdrsq = 2.0 * (4.0 / 3.0 * g3f * lambdaP3sq + 0.6 * 1.0 / 9.0 * g1f * lambdaP1sq) / sqr(16.0 * sqr(PI)); mersq = 2.0 * (0.6 * g1f * lambdaP1sq) / sqr(16.0 * sqr(PI)); mqlsq = 2.0 * (4.0 / 3.0 * g3f * lambdaP3sq + 0.75 * g2f * lambdaP2sq + 0.6 * g1f / 36.0 * lambdaP1sq) / sqr(16.0 * sqr(PI)); mllsq = 2.0 * (0.75 * g2f * lambdaP2sq + 0.6 * 0.25 * g1f * lambdaP1sq) / sqr(16.0 * sqr(PI)); // You need Higgs masses too! DoubleMatrix id(3, 3); id(1, 1) = 1.0; id(2, 2) = 1.0; id(3, 3) = 1.0; m.setSoftMassMatrix(mQl, mqlsq * id); m.setSoftMassMatrix(mUr, mursq * id); m.setSoftMassMatrix(mDr, mdrsq * id); m.setSoftMassMatrix(mLl, mllsq * id); m.setSoftMassMatrix(mEr, mersq * id); m.universalTrilinears(0.0); DoubleVector pars(2); ///< encodes EWSB BC pars(1) = muOm2 * m2; pars(2) = mAOm2 * m2; /// Save the two parameters m.setEwsbConditions(pars); } /// Returns true if a point passes the Higgs constraint from LEP2, false /// otherwise. Error is the amount of uncertainty on SOFTSUSY's mh prediction bool testLEPHiggs(const MssmSoftsusy & r, double error) { double Mh = r.displayPhys().mh0(1); Mh = Mh + error; double sinba2 = sqr(sin(atan(r.displayTanb()) - r.displayPhys().thetaH)); /// cout << "sinba2=" << sinba2 << endl; if (Mh < 90.0) return false; else if (90.0 <= Mh && Mh < 99.0) { if (sinba2 < -6.1979 + 0.12313 * Mh - 0.00058411 * sqr(Mh)) return true; else return false; } else if (99.0 <= Mh && Mh < 104.0) { if (sinba2 < 35.73 - 0.69747 * Mh + 0.0034266 * sqr(Mh)) return true; else return false; } else if (104.0 <= Mh && Mh < 109.5) { if (sinba2 < 21.379 - 0.403 * Mh + 0.0019211 * sqr(Mh)) return true; else return false; } else if (109.5 <= Mh && Mh < 114.4) { if (sinba2 < 1/(60.081 - 0.51624 * Mh)) return true; else return false; } return true; } /// from hep-ph/9507294 -- debugged 19/11/04 double ufb3fn(double mu, double htau, double h2, int family, const MssmSoftsusy & temp) { double vufb3 = 0.0; /// potential value for these VEVs if (fabs(h2) > sqrt(sqr(mu) / (4.0 * sqr(htau)) + 4.0 * temp.displaySoftMassSquared(mLl, family, family) / (0.6 * sqr(temp.displayGaugeCoupling(1)) + sqr(temp.displayGaugeCoupling(2)))) - fabs(mu) / temp.displayYukawaElement(YE, 3, 3) * 0.5) vufb3 = sqr(h2) * (temp.displayMh2Squared() + temp.displaySoftMassSquared(mLl, family, family)) + fabs(mu * h2) / htau * (temp.displaySoftMassSquared(mLl, 3, 3) + temp.displaySoftMassSquared(mEr, 3, 3) + temp.displaySoftMassSquared(mLl, family, family)) - 2.0 * sqr(temp.displaySoftMassSquared(mLl, family, family)) / (0.6 * sqr(temp.displayGaugeCoupling(1)) + sqr(temp.displayGaugeCoupling(2))); else vufb3 = sqr(h2) * temp.displayMh2Squared() + fabs(mu * h2) / htau * (temp.displaySoftMassSquared(mLl, 3, 3) + temp.displaySoftMassSquared(mEr, 3, 3)) + 1.0 / 8.0 * (0.6 * sqr(temp.displayGaugeCoupling(1)) + sqr(temp.displayGaugeCoupling(2))) * sqr(sqr(h2) + fabs(mu * h2) / htau); if (PRINTOUT > 1) cout << vufb3 << endl; return vufb3; } /// For ufb3direction, returns scale at which one-loop corrections are smallest double getQhat(double inminTol,double eR, double h2, double Lisq, double mx, MssmSoftsusy & temp) { double oldQhat = -1.0e16; int maxNum = 40; int d; for (d = 1; d <= maxNum; d++) { double qhat = maximum(maximum(maximum(temp.displayGaugeCoupling(2) * eR, temp.displayGaugeCoupling(2) * fabs(h2)), temp.displayGaugeCoupling(2) * sqrt(fabs(Lisq))), temp.displayYukawaElement(YU, 3, 3) * fabs(h2)); /// Run all paramaters to that scale if (qhat < mx) temp.runto(qhat); else temp.runto(mx); if (PRINTOUT > 1) cout << qhat << " "; if (fabs((qhat - oldQhat) / qhat) < inminTol) return qhat; oldQhat = qhat; } /// Return NOB if no convergence on qhat return -numberOfTheBeast; } /// Difference between two SOFTSUSY objects in and out: EWSB terms only double sumTol(const MssmSoftsusy & in, const MssmSoftsusy & out, int numTries) { drBarPars inforLoops(in.displayDrBarPars()), outforLoops(out.displayDrBarPars()); DoubleVector sT(34); int k = 1; double sTin = fabs(inforLoops.mh0(1)); double sTout = fabs(outforLoops.mh0(1)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; sTin = fabs(inforLoops.mA0(1)); sTout = fabs(outforLoops.mA0(1)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; sTin = fabs(inforLoops.mh0(2)); sTout = fabs(outforLoops.mh0(2)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; sTin = fabs(inforLoops.mHpm); sTout = fabs(outforLoops.mHpm); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; int i; for (i=1; i<=3; i++) { sTin = fabs(inforLoops.msnu(i)); sTout = fabs(outforLoops.msnu(i)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; } for (i=1; i<=2; i++) { sTin = fabs(inforLoops.mch(i)); sTout = fabs(outforLoops.mch(i)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; } for (i=1; i<=4; i++) { sTin = fabs(inforLoops.mneut(i)); sTout = fabs(outforLoops.mneut(i)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; } sTin = fabs(inforLoops.mGluino); sTout = fabs(outforLoops.mGluino); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; int j; for (j=1; j<=3; j++) for(i=1; i<=2; i++) { sTin = fabs(inforLoops.mu(i, j)); sTout = fabs(outforLoops.mu(i, j)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; sTin = fabs(inforLoops.md(i, j)); sTout = fabs(outforLoops.md(i, j)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; sTin = fabs(inforLoops.me(i, j)); sTout = fabs(outforLoops.me(i, j)); sT(k) = fabs(1.0 - minimum(sTin, sTout) / maximum(sTin, sTout)); k++; } /// The predicted value of MZ^2 is an absolute measure of how close to a /// true solution we are: // double tbPred = 0.; double predictedMzSq = in.displayPredMzSq(); /// We allow an extra factor of 10 for the precision in the predicted value /// of MZ compared to TOLERANCE if the program is struggling and gone beyond /// 10 tries - an extra 2 comes from MZ v MZ^2 if (!in.displayProblem().testSeriousProblem()) { sT(k) = 0.5 * fabs(1. - minimum(predictedMzSq, sqr(MZ)) / maximum(sqr(MZ), predictedMzSq)); if (numTries > 10) sT(k) *= 0.1; } return sT.max(); } /// Prints out what the lsp is string recogLsp(int temp, int posj) { string out; switch(temp) { case -1: out = "gravitino"; break; case 0: out = "neutralino"; break; case 1: switch(posj) { case 3: out = "stop"; break; case 2: out = "scharm"; break; case 1: out = "sup"; break; } break; case 2: switch(posj) { case 3: out = "sbottom"; break; case 2: out = "sstange"; break; case 1: out = "sdown"; break; } break; case 3: switch(posj) { case 3: out = "stau"; break; case 2: out = "smu"; break; case 1: out = "selectron"; break; } break; case 4: out = "chargino"; break; case 5: out = "sneutrino"; break; case 6: out = "gluino"; break; default: ostringstream ii; ii << "Wrong input to lsp printing routine\n"; throw ii.str(); break; } return out; } ostream & operator <<(ostream &left, const MssmSoftsusy &s) { left << HR << endl; left << "Gravitino mass M3/2: " << s.displayGravitino() << endl; left << "Msusy: " << s.displayMsusy() << " MW: " << s.displayMw() << " Predicted MZ: " << sqrt(s.displayPredMzSq()) << endl; left << "Data set:\n" << s.displayDataSet(); left << HR << endl; left << s.displaySoftPars(); left << "t1/v1(MS)=" << s.displayTadpole1Ms() << " t2/v2(MS)=" << s.displayTadpole2Ms() << endl; left << HR << "\nPhysical MSSM parameters:\n"; left << s.displayPhys(); double mass; int posi, posj, id; id = s.lsp(mass, posi, posj); /// If the gravitino mass is non-zero, and if it is smaller than the visible /// sector LSP mass, make it clear that the particle is the NLSP left << "lsp is " << recogLsp(id, posj); left << " of mass " << mass << " GeV\n"; if (s.displayProblem().test()) left << "***** PROBLEM *****" << s.displayProblem() << " *****" << endl; left << HR << endl; if (s.displaySetTbAtMX()) left << "Tan beta is set at user defined scale\n"; if (s.displayAltEwsb()) left << "Alternative EWSB conditions: mu=" << s.displayMuCond() << " mA=" << s.displayMaCond() << endl; return left; } } // namespace softsusy
McLenin/gm2
models/smssm/mssmUtils.cpp
C++
gpl-3.0
17,306
// Copyright (c) 2009 Frank Laub // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; namespace OpenSSL.Core { class Asn1Integer : Base { internal Asn1Integer(IntPtr ptr, bool takeOwnership) : base(ptr, takeOwnership) { } public Asn1Integer() : base(Native.ASN1_INTEGER_new(), true) { } public Asn1Integer(int value) : this() { Value = value; } protected override void OnDispose() { Native.ASN1_INTEGER_free(ptr); } public int Value { get { return Native.ASN1_INTEGER_get(ptr); } set { Native.ExpectSuccess(Native.ASN1_INTEGER_set(ptr, value)); } } public static int ToInt32(IntPtr ptr) { return Native.ASN1_INTEGER_get(ptr); } } }
dantmnf/YASS
openssl-net/ManagedOpenSsl/Core/Asn1Integer.cs
C#
gpl-3.0
2,086
<?php /** * LinkGpolGroupUserTable * * This class has been auto-generated by the Doctrine ORM Framework */ class LinkGpolGroupUserTable extends Doctrine_Table { /** * Returns an instance of this class. * * @return object LinkGpolGroupUserTable */ public static function getInstance() { return Doctrine_Core::getTable('LinkGpolGroupUser'); } }
bewiwi/gpol
lib/model/doctrine/LinkGpolGroupUserTable.class.php
PHP
gpl-3.0
392
# -*- coding: utf-8 -*- # # Copyright © 2011 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """IPython v0.11+ Plugin""" from spyderlib.qt.QtGui import QHBoxLayout # Local imports from spyderlib.widgets.ipython import create_widget from spyderlib.plugins import SpyderPluginWidget class IPythonPlugin(SpyderPluginWidget): """Find in files DockWidget""" CONF_SECTION = 'ipython' def __init__(self, parent, args, kernel_widget, kernel_name): super(IPythonPlugin, self).__init__(parent) self.kernel_widget = kernel_widget self.kernel_name = kernel_name self.ipython_widget = create_widget(argv=args.split()) layout = QHBoxLayout() layout.addWidget(self.ipython_widget) self.setLayout(layout) # Initialize plugin self.initialize_plugin() def toggle(self, state): """Toggle widget visibility""" if self.dockwidget: self.dockwidget.setVisible(state) #------ SpyderPluginWidget API --------------------------------------------- def get_plugin_title(self): """Return widget title""" return "IPython (%s) - Experimental!" % self.kernel_name def get_focus_widget(self): """ Return the widget to give focus to when this plugin's dockwidget is raised on top-level """ return self.ipython_widget._control def get_plugin_actions(self): """Return a list of actions related to plugin""" return [] def register_plugin(self): """Register plugin in Spyder's main window""" self.main.add_dockwidget(self) def refresh_plugin(self): """Refresh widget""" pass def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" return True
jromang/retina-old
distinclude/spyderlib/plugins/ipython.py
Python
gpl-3.0
2,012
package com.jmbsystems.fjbatresv.mascotassociales.photoList.ui; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable; import com.jmbsystems.fjbatresv.mascotassociales.MascotasSocialesApp; import com.jmbsystems.fjbatresv.mascotassociales.R; import com.jmbsystems.fjbatresv.mascotassociales.enitites.Photo; import com.jmbsystems.fjbatresv.mascotassociales.enitites.Session; import com.jmbsystems.fjbatresv.mascotassociales.libs.base.ImageLoader; import com.jmbsystems.fjbatresv.mascotassociales.main.ui.MainActivity; import com.jmbsystems.fjbatresv.mascotassociales.photo.ui.PhotoActivity; import com.jmbsystems.fjbatresv.mascotassociales.photoList.PhotoListPresenter; import com.jmbsystems.fjbatresv.mascotassociales.photoList.ui.adapters.OnItemClickListener; import com.jmbsystems.fjbatresv.mascotassociales.photoList.ui.adapters.PhotoListAdapter; import java.io.ByteArrayOutputStream; import java.util.List; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import de.hdodenhof.circleimageview.CircleImageView; public class PhotoListActivity extends AppCompatActivity implements PhotoListView, OnItemClickListener { @Bind(R.id.container) RelativeLayout container; @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.loggedAvatar) CircleImageView loggedAvatar; @Bind(R.id.loggedName) TextView loggedName; @Bind(R.id.progressBar) ProgressBar progressBar; @Bind(R.id.reclyclerView) RecyclerView recyclerView; @Bind(R.id.fab) FloatingActionButton fab; @Inject PhotoListPresenter presenter; @Inject ImageLoader imageLoader; @Inject PhotoListAdapter adapter; private MascotasSocialesApp app; public final static String NOMBRE_ORIGEN = "photoList"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo_list); ButterKnife.bind(this); app = (MascotasSocialesApp) getApplication(); app.validSessionInit(); setupInjection(); setupToolbar(); setUpRecyclerView(); presenter.onCreate(); } @Override protected void onDestroy() { presenter.onDestroy(); super.onDestroy(); } @Override public void onBackPressed() { startActivity(new Intent(this, MainActivity.class)); } @OnClick(R.id.fab) public void takePhoto(){ startActivity( new Intent(this, PhotoActivity.class) .putExtra(PhotoActivity.ORIGEN, NOMBRE_ORIGEN) ); } private void setupInjection() { app.getPhotoListComponent(this, this).inject(this); } private void setUpRecyclerView() { recyclerView.setLayoutManager(new GridLayoutManager(this, 1)); recyclerView.setAdapter(adapter); } private void setupToolbar() { loggedName.setText(Session.getInstancia().getNombre()); imageLoader.load(loggedAvatar, Session.getInstancia().getImage()); setSupportActionBar(toolbar); } @Override public void onError(String error) { loggedName.setText(Session.getInstancia().getNombre()); imageLoader.load(loggedAvatar, Session.getInstancia().getImage()); Snackbar.make(container, error, Snackbar.LENGTH_LONG).show(); } @Override public void toggleContent(boolean mostrar) { int visible = View.VISIBLE; if (!mostrar){ visible = View.GONE; } fab.setVisibility(visible); recyclerView.setVisibility(visible); } @Override public void toggleProgress(boolean mostrar) { int visible = View.VISIBLE; if (!mostrar){ visible = View.GONE; } progressBar.setVisibility(visible); } @Override public void addPhoto(Photo foto) { adapter.addPhoto(foto); } @Override public void removePhoto(Photo foto) { adapter.removePhoto(foto); } @Override public void onShareClick(Photo foto, ImageView img) { Bitmap bitmap = ((GlideBitmapDrawable)img.getDrawable()).getBitmap(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); String path = MediaStore.Images.Media.insertImage(this.getContentResolver(), bitmap, null, null); Uri uri = Uri.parse(path); Intent share = new Intent(Intent.ACTION_SEND) .setType("image/jpeg") .putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(share, getString(R.string.photolist_message_share))); } @Override public void onDeleteClick(Photo foto) { presenter.removePhoto(foto); } }
fjbatresv/MascotasSociales
app/src/main/java/com/jmbsystems/fjbatresv/mascotassociales/photoList/ui/PhotoListActivity.java
Java
gpl-3.0
5,594
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Abc-Map 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General * Public License along with Abc-Map. If not, see <https://www.gnu.org/licenses/>. */ import { Task } from '../../Task'; import { MapWrapper } from '../../../geo/map/MapWrapper'; import { LayerWrapper } from '../../../geo/layers/LayerWrapper'; export class RemoveLayerTask extends Task { constructor(private map: MapWrapper, private layer: LayerWrapper) { super(); } public async undo(): Promise<void> { this.map.addLayer(this.layer); this.map.setActiveLayer(this.layer); } public async redo(): Promise<void> { this.map.removeLayer(this.layer); // We activate the last layer const layers = this.map.getLayers(); if (layers.length) { this.map.setActiveLayer(layers[layers.length - 1]); } } }
remipassmoilesel/abcmap
packages/frontend/src/core/history/tasks/layers/RemoveLayerTask.ts
TypeScript
gpl-3.0
1,389
# coding: utf-8 import os import urllib import numpy as np import pickle from Experiment import Experiment ROOT_PATH = './full_dataset/article_4_data/grouped_ephys' ZIPFILE_PATH = './full_dataset/article_4_data' EXPM_PATH = './results/experiments/' URL = 'http://microcircuits.epfl.ch/data/released_data/' if not os.path.exists(EXPM_PATH): os.makedirs(EXPM_PATH) if not os.path.exists(ROOT_PATH): print('It seems that the directory of the raw data does not exist. It is expected to be at: ' + ROOT_PATH) if not os.path.exists(ROOT_PATH): print('It seems that the directory with the zip files does not exist. It is expected to be at: ' + ZIPFILE_PATH) # ============================================================================== # General io function # ============================================================================== def download_info_from_url(url): """ Download content from url and return it. """ r = urllib.request.urlopen(url) data = r.read() data = data.decode(encoding='UTF-8') return data def get_genetic_cell_infos(filepath): """ Downloads genetic information from cells in the directory at filepath. """ filelist = os.listdir(filepath) raw_names = [name[0:-4] for name in filelist] cell_names = [] for name in raw_names: # if name.rfind('ET') == -1: cell_names.append(name) infos = {} for cell in cell_names: url_complete = URL + cell + '.txt' try: infos[cell] = download_info_from_url(url_complete) except Exception: next return infos def save_filtered_cell_infos(filtername, criterion1='SOM:1', criterion2='PV:0', criterion3='VIP:0'): """ Gets genetic information from all cells in ZIPFILE_PATH directory, filters them by the given criterions and saves the filtered list with pickle. """ infos = get_genetic_cell_infos(ZIPFILE_PATH) desired_cells = {} for cell in infos.keys(): if criterion1 in infos[cell] and criterion2 in infos[cell] and criterion3 in infos[cell]: desired_cells[cell] = infos[cell] with open(filtername + '_infos.pkl', 'wb') as f: pickle.dump(desired_cells, f) def save_all_cell_infos(filepath): """ Saves genetic information from all cells in ZIPFILE_PATH directory in one list with pickle. """ infos = get_genetic_cell_infos(filepath) with open('cell_infos_full.pkl', 'wb') as f: pickle.dump(infos, f) def open_filtered_cell_info_list(filtername): """ Opens the list that was saved with save_filtered_cell_infos with the given filtername. """ with open(filtername + '_infos.pkl', 'rb') as f: filtered_list = pickle.load(f) return filtered_list def create_experiments_from_list(cells, cell_type, verbose=True): """ Creates Experiment objects for cells in cells, adds all existing traces and saves them. Params: - cells: List with cell names or dictionairy where the keys are the cell names. """ if type(cells) is dict: cell_names = list(cells.keys()) else: cell_names = cells ncells = len(cell_names) for i in range(ncells): PATH = os.path.join(ROOT_PATH, cell_names[i]) animal_files = sorted(os.listdir(PATH)) ntraces = int(len(animal_files) / 2) current_exp = Experiment('Cell_' + cell_names[i] + '_single_traces', cell_type=cell_type) exp_merged_traces = Experiment('Cell_' + cell_names[i] + '_merged_idrest_traces', cell_type=cell_type) nincluded_idrest_traces = 0 for j in np.arange(ntraces): # files end with 'recordingType_recordingNumber.ibw' file_split = str.split(animal_files[j][0:-4], '_') file_identifier = file_split[-2] + '_' + file_split[-1] + '.ibw' current_recording_type = file_split[-2] # find indeces of matching files in folder (current file always comes first because it's always Ch0) file_idc = [i for i, elem in enumerate(animal_files) if file_identifier in elem] current_file = animal_files[file_idc[0]] voltage_file = animal_files[file_idc[1]] current_exp.add_trainingset_trace(os.path.join(PATH, voltage_file), 10 ** -3, os.path.join(PATH, current_file), 10 ** -12, FILETYPE='Igor', verbose=verbose) tr = current_exp.trainingset_traces[j] tr.recording_type = current_recording_type tr.estimate_input_amp() if current_recording_type == 'IDRest': exp_merged_traces.add_trainingset_trace(os.path.join(PATH, voltage_file), 10 ** -3, os.path.join(PATH, current_file), 10 ** -12, FILETYPE='Igor', verbose=verbose) tr = current_exp.trainingset_traces[nincluded_idrest_traces] tr.recording_type = current_recording_type tr.estimate_input_amp() nincluded_idrest_traces += 1 if not len(exp_merged_traces.trainingset_traces) < 3: exp_merged_traces.mergeTrainingTraces() exp_merged_traces.save(os.path.join(EXPM_PATH), verbose=verbose) current_exp.save(os.path.join(EXPM_PATH), verbose=verbose) def load_merged_traces_experiments_from_list(cells, verbose=True): """ Load experiments where IDRest traces have been merged. This function will try to load an experiment with merged IDRest traces for all cells in the list and just skip the ones for which it is not found. If no experiments were found, None is returned. Params: - cells: List with cell names or dictionairy where the keys are the cell names. See also: load_single_traces_experiments_from_list() """ if type(cells) is dict: cell_names = list(cells.keys()) else: cell_names = cells expms = [] for i in range(len(cell_names)): current_expm_name = 'Experiment_Cell_' + cell_names[i] + '_merged_idrest_traces.pkl' current_expm_path = os.path.join(EXPM_PATH, current_expm_name) try: current_expm = Experiment.load(current_expm_path, verbose=verbose) expms.append(current_expm) except: pass if not len(expms) == 0: return expms else: return None def load_single_traces_experiments_from_list(cells, verbose=True): """ Load experiments where traces have been added separately. Params: - cells: List with cell names or dictionairy where the keys are the cell names. See also: load_merged_traces_experiments_from_list() """ if type(cells) is dict: cell_names = list(cells.keys()) else: cell_names = cells expms = [] for i in range(len(cell_names)): current_expm_name = 'Experiment_Cell_' + cell_names[i] + '_single_traces.pkl' current_expm_path = os.path.join(EXPM_PATH, current_expm_name) try: current_expm = Experiment.load(current_expm_path, verbose=verbose) expms.append(current_expm) except: pass if not len(expms) == 0: return expms else: return None # ============================================================================== # From here on it's interneuron-specific functions # ============================================================================== def create_interneuron_specific_experiments(verbose=True): """ Filters cell infos for SOM, PV and VIP neurons, loads them and creates Experiment objects. """ # create and save filtered info lists for SOM, PV and VIP neurons save_filtered_cell_infos('som_cells', criterion1='SOM:1', criterion2='PV:0', criterion3='VIP:0') save_filtered_cell_infos('pv_cells', criterion1='SOM:0', criterion2='PV:1', criterion3='VIP:0') save_filtered_cell_infos('vip_cells', criterion1='SOM:0', criterion2='PV:0', criterion3='VIP:1') # get saved lists som_dict = open_filtered_cell_info_list('som_cells') vip_dict = open_filtered_cell_info_list('vip_cells') pv_dict = open_filtered_cell_info_list('pv_cells') # create experiment objects create_experiments_from_list(vip_dict, cell_type='vip', verbose=verbose) create_experiments_from_list(som_dict, cell_type='som', verbose=verbose) create_experiments_from_list(pv_dict, cell_type='pv', verbose=verbose) def get_som_expms(merged=False, verbose=True): som_dict = open_filtered_cell_info_list('som_cells') if merged: return load_merged_traces_experiments_from_list(som_dict, verbose=verbose) else: return load_single_traces_experiments_from_list(som_dict, verbose=verbose) def get_pv_expms(merged=False, verbose=True): pv_dict = open_filtered_cell_info_list('pv_cells') if merged: return load_merged_traces_experiments_from_list(pv_dict, verbose=verbose) else: return load_single_traces_experiments_from_list(pv_dict, verbose=verbose) def get_vip_expms(merged=False, verbose=True): vip_dict = open_filtered_cell_info_list('vip_cells') if merged: return load_merged_traces_experiments_from_list(vip_dict, verbose=verbose) else: return load_single_traces_experiments_from_list(vip_dict, verbose=verbose)
awakenting/gif_fitting
bbp_analysis/bluebrain_data_io.py
Python
gpl-3.0
9,533
package org.safehaus.penrose.ldap; import java.util.Map; import java.util.TreeMap; /** * @author Endi S. Dewata */ public class RDNBuilder { public Map<String,Object> values = new TreeMap<String,Object>(); public RDNBuilder() { } public boolean isEmpty() { return values.isEmpty(); } public void clear() { values.clear(); } public void add(RDN rdn) { values.putAll(rdn.getValues()); } public void set(RDN rdn) { values.clear(); values.putAll(rdn.getValues()); } public void add(String prefix, RDN rdn) { for (String name : rdn.getNames()) { Object value = rdn.get(name); values.put(prefix == null ? name : prefix + "." + name, value); } } public void set(String prefix, RDN rdn) { values.clear(); for (String name : rdn.getNames()) { Object value = rdn.get(name); values.put(prefix == null ? name : prefix + "." + name, value); } } public void set(String name, Object value) { this.values.put(name, value); } public Object remove(String name) { return values.remove(name); } public void normalize() { for (String name : values.keySet()) { Object value = values.get(name); if (value == null) continue; if (value instanceof String) { value = ((String) value).toLowerCase(); } values.put(name, value); } } public RDN toRdn() { return new RDN(values); } }
rgorosito/penrose
common/src/main/java/org/safehaus/penrose/ldap/RDNBuilder.java
Java
gpl-3.0
1,607
<?php declare(strict_types = 1); namespace EssentialsPE\Tasks\AFK; use EssentialsPE\BaseFiles\BaseTask; use EssentialsPE\BaseFiles\BaseAPI; use pocketmine\utils\TextFormat; class AFKSetterTask extends BaseTask{ /** * @param BaseAPI $api */ public function __construct(BaseAPI $api){ parent::__construct($api); } /* * This task is executed every 30 seconds, * with the purpose of checking all players' last movement * time, stored in their 'Session', * and check if it is pretty near, * or it's over, the default Idling limit. * * If so, they will be set in AFK mode */ /** * @param int $currentTick */ public function onRun(int $currentTick): void{ $this->getAPI()->getServer()->getLogger()->debug(TextFormat::YELLOW . "Running EssentialsPE's AFKSetterTask"); foreach($this->getAPI()->getServer()->getOnlinePlayers() as $p){ if(!$this->getAPI()->isAFK($p) && ($last = $this->getAPI()->getLastPlayerMovement($p)) !== null && !$p->hasPermission("essentials.afk.preventauto")){ if(time() - $last >= $this->getAPI()->getEssentialsPEPlugin()->getConfig()->getNested("afk.auto-set")){ $this->getAPI()->setAFKMode($p, true, $this->getAPI()->getEssentialsPEPlugin()->getConfig()->getNested("afk.auto-broadcast")); } } } // Re-Schedule the task xD $this->getAPI()->scheduleAutoAFKSetter(); } }
LegendOfMCPE/EssentialsPE
src/EssentialsPE/Tasks/AFK/AFKSetterTask.php
PHP
gpl-3.0
1,503
// Copyright 2017 voidALPHA, Inc. // This file is part of the Haxxis video generation system and is provided // by voidALPHA in support of the Cyber Grand Challenge. // Haxxis 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. // Haxxis 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 // Haxxis. If not, see <http://www.gnu.org/licenses/>. using UnityEngine; using UnityEngine.EventSystems; namespace Utility.DevCommand { public class DevCommandConsoleResizeBehaviour : MonoBehaviour, IPointerDownHandler, IDragHandler { [SerializeField] private Vector2 m_MinSize = new Vector2(80.0f, 40.0f); private Vector2 MinSize { get { return m_MinSize; } set { m_MinSize = value; } } private Vector2 m_MaxSize = new Vector2(500.0f, 500.0f); private Vector2 MaxSize { get { return m_MaxSize; } set { m_MaxSize = value; } } private RectTransform rectTransform; private Vector2 currentPointerPosition; private Vector2 previousPointerPosition; private void Awake() { rectTransform = transform.parent.GetComponent<RectTransform>(); } public void OnPointerDown(PointerEventData data) { rectTransform.SetAsLastSibling(); // Ensure this is in front of everything RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out previousPointerPosition); } public void OnDrag(PointerEventData data) { MaxSize = SetMaxSize( ); Vector2 sizeDelta = rectTransform.sizeDelta; RectTransformUtility.ScreenPointToLocalPointInRectangle( rectTransform, data.position, data.pressEventCamera, out currentPointerPosition ); Vector2 resizeValue = currentPointerPosition - previousPointerPosition; sizeDelta += new Vector2(resizeValue.x, -resizeValue.y); sizeDelta = new Vector2( Mathf.Clamp( sizeDelta.x, MinSize.x, MaxSize.x ), Mathf.Clamp( sizeDelta.y, MinSize.y, MaxSize.y ) ); rectTransform.sizeDelta = sizeDelta; previousPointerPosition = currentPointerPosition; var panelBehaviour = transform.parent.parent.GetComponent< DevCommandConsoleBehaviour >(); var rt = panelBehaviour.TextInputField.GetComponent<RectTransform>(); var newWidth = rt.rect.width + resizeValue.x; if ( newWidth < 28.0f ) // Cheesy I know newWidth = 28.0f; rt.sizeDelta = new Vector2(newWidth, rt.rect.height); } // Set max size to the current canvas size private Vector2 SetMaxSize() { Vector3[] canvasCorners = new Vector3[4]; RectTransform canvasRectTransform = rectTransform.parent.GetComponent<RectTransform>( ); canvasRectTransform.GetWorldCorners(canvasCorners); return new Vector2(canvasCorners[2].x, canvasCorners[2].y); } } }
voidALPHA/cgc_viz
Assets/Scripts/Utility/DevCommand/DevCommandConsoleResizeBehaviour.cs
C#
gpl-3.0
3,345
var index = require('express').Router(); var Member = require('../models/Member'); var sitemap = require('../middlewares/sitemap'); var utils = require('../middlewares/utils'); index.get('/', function (req, res) { res.redirect('/article'); }); index.get('/lang', function (req, res) { var setLang; if (req.cookies.lang == undefined || req.cookies.lang == 'zh-cn') { setLang = 'en-us'; } else { setLang = 'zh-cn'; } res.cookie('lang', setLang); res.redirect('/'); }); index.get('/lib/contact-us', function (req, res) { res.render('contactUs', { description: '身为工大学子的你,如果对软件开发或是产品设计有兴趣,欢迎向我们投递简历。' }); }); index.get('/lib/sitemap.xml', function (req, res) { sitemap.createXml(function (xml) { res.contentType('text/xml'); res.send(xml); res.end(); }); }); module.exports = index;
hfut-xcsoft/xcsoft.hfut.edu.cn
routes/default.js
JavaScript
gpl-3.0
901
# # controller.py # # Copyright (C) 2013-2014 Ashwin Menon <ashwin.menon@gmail.com> # Copyright (C) 2015-2018 Track Master Steve <trackmastersteve@gmail.com> # # Alienfx is free software. # # You may 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. # # Alienfx 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 alienfx. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # """ Base classes for AlienFX controller chips. These must be subclassed for specific controllers. This module provides the following classes: AlienFXController: base class for AlienFX controller chips """ from builtins import hex from builtins import object import logging import alienfx.core.usbdriver as alienfx_usbdriver import alienfx.core.cmdpacket as alienfx_cmdpacket from alienfx.core.themefile import AlienFXThemeFile from functools import reduce class AlienFXController(object): """ Provides facilities to communicate with an AlienFX controller. This class provides methods to send commands to an AlienFX controller, and receive status from the controller. It must be overridden to provide behaviour specific to a particular AlienFX controller. """ # List of all subclasses of this class. Subclasses must add instances of # themselves to this list. See README for details. supported_controllers = [] # Zone names ZONE_LEFT_KEYBOARD = "Left Keyboard" ZONE_MIDDLE_LEFT_KEYBOARD = "Middle-left Keyboard" ZONE_MIDDLE_RIGHT_KEYBOARD = "Middle-right Keyboard" ZONE_RIGHT_KEYBOARD = "Right Keyboard" ZONE_RIGHT_SPEAKER = "Right Speaker" ZONE_LEFT_SPEAKER = "Left Speaker" ZONE_ALIEN_HEAD = "Alien Head" ZONE_LOGO = "Logo" ZONE_TOUCH_PAD = "Touchpad" ZONE_MEDIA_BAR = "Media Bar" ZONE_STATUS_LEDS = "Status LEDs" ZONE_POWER_BUTTON = "Power Button" ZONE_HDD_LEDS = "HDD LEDs" ZONE_RIGHT_DISPLAY = "Right Display" # LED-bar display right side, as built in the AW17R4 ZONE_LEFT_DISPLAY = "Left Display" # LED-bar display left side, as built in the AW17R4 # State names STATE_BOOT = "Boot" STATE_AC_SLEEP = "AC Sleep" STATE_AC_CHARGED = "AC Charged" STATE_AC_CHARGING = "AC Charging" STATE_BATTERY_SLEEP = "Battery Sleep" STATE_BATTERY_ON = "Battery On" STATE_BATTERY_CRITICAL = "Battery Critical" ALIENFX_CONTROLLER_TYPE = "old" # Default controllertype=old. Note that modern controllers are using 8 bits per color. older ones just 4 def __init__(self, conrev=1): # conrev defaulting to 1 to maintain compatibility with old definitions # conrev=1 -> old controllers (DEFAULT) # conrev=2 -> newer controllers (17R4 ...) self.zone_map = {} self.power_zones = [] self.reset_types = {} self.state_map = {} self.vendor_id = 0 self.product_id = 0 self.cmd_packet = alienfx_cmdpacket.AlienFXCmdPacket(conrev) # Loads the cmdpacket. self._driver = alienfx_usbdriver.AlienFXUSBDriver(self) def get_zone_name(self, pkt): """ Given 3 bytes of a command packet, return a string zone name corresponding to it """ zone_mask = (pkt[0] << 16) + (pkt[1] << 8) + pkt[2] zone_name = "" for zone in self.zone_map: bit_mask = self.zone_map[zone] if zone_mask & bit_mask: if zone_name != "": zone_name += "," zone_name += zone zone_mask &= ~bit_mask if zone_mask != 0: if zone_name != "": zone_name += "," zone_name += "UNKNOWN({})".format(hex(zone_mask)) return zone_name def get_state_name(self, state): """ Given a state number, return a string state name """ for state_name in self.state_map: if self.state_map[state_name] == state: return state_name return "UNKNOWN" def get_reset_type_name(self, num): """ Given a reset number, return a string reset name """ if num in list(self.reset_types.keys()): return self.reset_types[num] else: return "UNKNOWN" def _ping(self): """ Send a get-status command to the controller.""" pkt = self.cmd_packet.make_cmd_get_status() logging.debug("SENDING: {}".format(self.pkt_to_string(pkt))) self._driver.write_packet(pkt) self._driver.read_packet() def _reset(self, reset_type): """ Send a "reset" packet to the AlienFX controller.""" reset_code = self._get_reset_code(reset_type) pkt = self.cmd_packet.make_cmd_reset(reset_code) logging.debug("SENDING: {}".format(self.pkt_to_string(pkt))) self._driver.write_packet(pkt) def _wait_controller_ready(self): """ Keep sending a "get status" packet to the AlienFX controller and return only when the controller is ready """ ready = False errcount=0 while not ready: pkt = self.cmd_packet.make_cmd_get_status() logging.debug("SENDING: {}".format(self.pkt_to_string(pkt))) self._driver.write_packet(pkt) try: resp = self._driver.read_packet() ready = (resp[0] == self.cmd_packet.STATUS_READY) except TypeError: errcount += 1 logging.debug("No Status received yet... Failed tries=" + str(errcount)) if errcount > 50: logging.error("Controller status could not be retrieved. Is the device already in use?") quit(-99) def pkt_to_string(self, pkt_bytes): """ Return a human readable string representation of an AlienFX command packet. """ return self.cmd_packet.pkt_to_string(pkt_bytes, self) def _get_no_zone_code(self): """ Return a zone code corresponding to all non-visible zones.""" zone_codes = [self.zone_map[x] for x in self.zone_map] return ~reduce(lambda x,y: x|y, zone_codes, 0) def _get_zone_codes(self, zone_names): """ Given zone names, return the zone codes they refer to. """ zones = 0 for zone in zone_names: if zone in self.zone_map: zones |= self.zone_map[zone] return zones def _get_reset_code(self, reset_name): """ Given the name of a reset action, return its code. """ for reset in self.reset_types: if reset_name == self.reset_types[reset]: return reset logging.warning("Unknown reset type: {}".format(reset_name)) return 0 def _make_loop_cmds(self, themefile, zones, block, loop_items): """ Given loop-items from the theme file, return a list of loop commands. """ loop_cmds = [] pkt = self.cmd_packet for item in loop_items: item_type = themefile.get_action_type(item) item_colours = themefile.get_action_colours(item) if item_type == AlienFXThemeFile.KW_ACTION_TYPE_FIXED: if len(item_colours) != 1: logging.warning("fixed must have exactly one colour value") continue loop_cmds.append( pkt.make_cmd_set_colour(block, zones, item_colours[0])) elif item_type == AlienFXThemeFile.KW_ACTION_TYPE_BLINK: if len(item_colours) != 1: logging.warning("blink must have exactly one colour value") continue loop_cmds.append( pkt.make_cmd_set_blink_colour(block, zones, item_colours[0])) elif item_type == AlienFXThemeFile.KW_ACTION_TYPE_MORPH: if len(item_colours) != 2: logging.warning("morph must have exactly two colour values") continue loop_cmds.append( pkt.make_cmd_set_morph_colour( block, zones, item_colours[0], item_colours[1])) else: logging.warning("unknown loop item type: {}".format(item_type)) return loop_cmds def _make_zone_cmds(self, themefile, state_name, boot=False): """ Given a theme file, return a list of zone commands. If 'boot' is True, then the colour commands created are not saved with SAVE_NEXT commands. Also, the final command is one to set the colour of all non-visible zones to black. """ zone_cmds = [] block = 1 pkt = self.cmd_packet state = self.state_map[state_name] state_items = themefile.get_state_items(state_name) for item in state_items: zone_codes = self._get_zone_codes(themefile.get_zone_names(item)) loop_items = themefile.get_loop_items(item) loop_cmds = self._make_loop_cmds( themefile, zone_codes, block, loop_items) if (loop_cmds): block += 1 for loop_cmd in loop_cmds: if not boot: zone_cmds.append(pkt.make_cmd_save_next(state)) zone_cmds.append(loop_cmd) if not boot: zone_cmds.append(pkt.make_cmd_save_next(state)) zone_cmds.append(pkt.make_cmd_loop_block_end()) if zone_cmds: if not boot: zone_cmds.append(pkt.make_cmd_save()) if boot: zone_cmds.append( pkt.make_cmd_set_colour( block, self._get_no_zone_code(), (0,0,0))) zone_cmds.append(pkt.make_cmd_loop_block_end()) return zone_cmds def _send_cmds(self, cmds): """ Send the given commands to the controller. """ for cmd in cmds: logging.debug("SENDING: {}".format(self.pkt_to_string(cmd))) self._driver.write_packet(cmd) def set_theme(self, themefile): """ Send the given theme settings to the controller. This should result in the lights changing to the theme settings immediately. """ try: self._driver.acquire() cmds_boot = [] pkt = self.cmd_packet # prepare the controller self._ping() self._reset("all-lights-on") self._wait_controller_ready() for state_name in self.state_map: cmds = [] cmds = self._make_zone_cmds(themefile, state_name) # Boot block commands are saved for sending again later. # The second time, they are sent without SAVE_NEXT commands. if (state_name == self.STATE_BOOT): cmds_boot = self._make_zone_cmds( themefile, state_name, boot=True) self._send_cmds(cmds) cmd = pkt.make_cmd_set_speed(themefile.get_speed()) self._send_cmds([cmd]) # send the boot block commands again self._send_cmds(cmds_boot) cmd = pkt.make_cmd_transmit_execute() self._send_cmds([cmd]) finally: self._driver.release()
ashwinm76/alienfx
alienfx/core/controller.py
Python
gpl-3.0
11,875
// // SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2004-2015 Steve Baker <sjbaker1@airmail.net> // Copyright (C) 2010-2015 Steve Baker, Joerg Henrichs // // 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_MATERIAL_HPP #define HEADER_MATERIAL_HPP #include "utils/no_copy.hpp" #include "utils/random_generator.hpp" #include <assert.h> #include <map> #include <string> #include <vector> namespace irr { namespace video { class ITexture; class SMaterial; } namespace scene { class ISceneNode; class IMeshBuffer; } } using namespace irr; class XMLNode; class SFXBase; class ParticleKind; /** * \ingroup graphics */ class Material : public NoCopy { public: enum ShaderType { SHADERTYPE_SOLID = 0, SHADERTYPE_SOLID_SKINNED_MESH, SHADERTYPE_ALPHA_TEST, SHADERTYPE_ALPHA_TEST_SKINNED_MESH, SHADERTYPE_ALPHA_BLEND, SHADERTYPE_ADDITIVE, SHADERTYPE_SOLID_UNLIT, SHADERTYPE_SOLID_UNLIT_SKINNED_MESH, /** Effect that makes grass wave as in the wind */ SHADERTYPE_VEGETATION, SHADERTYPE_WATER, SHADERTYPE_SPHERE_MAP, SHADERTYPE_NORMAL_MAP, SHADERTYPE_NORMAL_MAP_SKINNED_MESH, SHADERTYPE_DETAIL_MAP, SHADERTYPE_SPLATTING, SHADERTYPE_COUNT, }; enum ParticleConditions { EMIT_ON_DRIVE = 0, EMIT_ON_SKID, EMIT_KINDS_COUNT }; enum CollisionReaction { NORMAL, RESCUE, PUSH_BACK, PUSH_SOCCER_BALL }; private: /** Pointer to the texture. */ video::ITexture *m_texture; /** Name of the texture. */ std::string m_texname; std::string m_full_path; std::string m_original_full_path; /** Name of a special sfx to play when a kart is on this terrain, or * "" if no special sfx exists. */ std::string m_sfx_name; ShaderType m_shader_type; /** Set if being on this surface means being under some other mesh. * This is used to simulate that a kart is in water: the ground under * the water is marked as 'm_below_surface', which will then trigger a raycast * up to find the position of the actual water surface. */ bool m_below_surface; bool m_water_splash; /** If a kart is falling over a material with this flag set, it * will trigger the special camera fall effect. */ bool m_falling_effect; /** A material that is a surface only, i.e. the karts can fall through * but the information is still needed (for GFX mostly). An example is * a water surface: karts can drive while partly in water (so the water * surface is not a physical object), but the location of the water * effect is on the surface. */ bool m_surface; /** If the material is a zipper, i.e. gives a speed boost. */ bool m_zipper; /** If a kart is rescued when driving on this surface. */ bool m_drive_reset; /** True if this is a texture that will start the jump animation when * leaving it and being in the air. */ bool m_is_jump_texture; /** True if driving on this texture should adjust the gravity of the kart * to be along the normal of the triangle. This allows karts to drive e.g * upside down. */ bool m_has_gravity; /** Speed of the 'main' wave in the water shader. Only used if m_shader_type == SHDERTYPE_WATER */ float m_water_shader_speed_1; /** Speed of the 'secondary' waves in the water shader. Only used if m_shader_type == SHADERTYPE_WATER */ float m_water_shader_speed_2; /** If a kart is rescued when crashing into this surface. */ CollisionReaction m_collision_reaction; /** Particles to show on touch */ std::string m_collision_particles; /** If m_shader_type == SHADERTYPE_VEGETATION */ float m_grass_speed; float m_grass_amplitude; /** If the property should be ignored in the physics. Example would be * plants that a kart can just drive through. */ bool m_ignore; bool m_fog; /** Either ' ' (no mirroring), 'U' or 'V' if a texture needs to be * mirrored when driving in reverse. Typically used for arrows indicating * the direction. */ char m_mirror_axis_when_reverse; /** * Associated with m_mirror_axis_when_reverse, to avoid mirroring the same material twice * (setAllMaterialFlags can be called multiple times on the same mesh buffer) */ std::map<void*, bool> m_mirrorred_mesh_buffers; ParticleKind* m_particles_effects[EMIT_KINDS_COUNT]; /** For normal maps */ std::string m_normal_map_tex; /** Texture clamp bitmask */ unsigned int m_clamp_tex; /** True if backface culliing should be enabled. */ bool m_backface_culling; /** Set to true to disable writing to the Z buffer. Usually to be used with alpha blending */ bool m_disable_z_write; /** True if this material can be colorized (like red/blue in team game). */ bool m_colorizable; /** Minimum resulting saturation when colorized (from 0 to 1) */ float m_colorization_factor; /** List of hue pre-defined for colorization (from 0 to 1) */ std::vector<float> m_hue_settings; /** Random generator for getting pre-defined hue */ RandomGenerator m_random_hue; /** Some textures need to be pre-multiplied, some divided to give * the intended effect. */ //enum {ADJ_NONE, ADJ_PREMUL, ADJ_DIV} // m_adjust_image; /** True if lightmapping is enabled for this material. */ //bool m_lightmap; /** True if the material shouldn't be "slippy" at an angle */ bool m_high_tire_adhesion; /** How much the top speed is reduced per second. */ float m_slowdown_time; /** Maximum speed at which no more slow down occurs. */ float m_max_speed_fraction; /** Minimum speed on this terrain. This is used for zippers on a ramp to * guarantee the right jump distance. A negative value indicates no * minimum speed. */ float m_zipper_min_speed; /** The minimum speed at which a special sfx is started to be played. */ float m_sfx_min_speed; /** The speed at which the maximum pitch is used. */ float m_sfx_max_speed; /** The minimum pitch to be used (at minimum speed). */ float m_sfx_min_pitch; /** The maximum pitch to be used (at maximum speed). */ float m_sfx_max_pitch; /** (max_pitch-min_pitch) / (max_speed - min_speed). Used to adjust * the pitch of a sfx depending on speed of the kart. */ float m_sfx_pitch_per_speed; /** Additional speed allowed on top of the kart-specific maximum kart speed * if a zipper is used. If this value is <0 the kart specific value will * be used. */ float m_zipper_max_speed_increase; /** Time a zipper stays activated. If this value is <0 the kart specific * value will be used. */ float m_zipper_duration; /** A one time additional speed gain - the kart will instantly add this * amount of speed to its current speed. If this value is <0 the kart * specific value will be used. */ float m_zipper_speed_gain; /** Time it takes for the zipper advantage to fade out. If this value * is <0 the kart specific value will be used. */ float m_zipper_fade_out_time; /** Additional engine force. */ float m_zipper_engine_force; std::string m_mask; std::string m_colorization_mask; /** If m_splatting is true, indicates the first splatting texture */ std::string m_splatting_texture_1; /** If m_splatting is true, indicates the second splatting texture */ std::string m_splatting_texture_2; /** If m_splatting is true, indicates the third splatting texture */ std::string m_splatting_texture_3; /** If m_splatting is true, indicates the fourth splatting texture */ std::string m_splatting_texture_4; std::string m_gloss_map; bool m_complain_if_not_found; bool m_deprecated; bool m_installed; void init (); void install (bool srgb = false, bool premul_alpha = false); void initCustomSFX(const XMLNode *sfx); void initParticlesEffect(const XMLNode *node); public: Material(const XMLNode *node, bool deprecated); Material(const std::string& fname, bool is_full_path=false, bool complain_if_not_found=true, bool load_texture = true); ~Material (); void unloadTexture(); void setSFXSpeed(SFXBase *sfx, float speed, bool should_be_paused) const; void setMaterialProperties(video::SMaterial *m, scene::IMeshBuffer* mb); void adjustForFog(scene::ISceneNode* parent, video::SMaterial *m, bool use_fog) const; void onMadeVisible(scene::IMeshBuffer* who); void onHidden(scene::IMeshBuffer* who); void isInitiallyHidden(scene::IMeshBuffer* who); /** Returns the ITexture associated with this material. */ video::ITexture *getTexture(bool srgb = true, bool premul_alpha = false); // ------------------------------------------------------------------------ bool isIgnore () const { return m_ignore; } // ------------------------------------------------------------------------ /** Returns true if this material is a zipper. */ bool isZipper () const { return m_zipper; } // ------------------------------------------------------------------------ /** Returns if this material should trigger a rescue if a kart * is driving on it. */ bool isDriveReset () const { return m_drive_reset; } // ------------------------------------------------------------------------ /** Returns if this material can be colorized. */ bool isColorizable () const { return m_colorizable; } // ------------------------------------------------------------------------ /** Returns the minimum resulting saturation when colorized. */ float getColorizationFactor () const { return m_colorization_factor; } // ------------------------------------------------------------------------ /** Returns a random hue when colorized. */ float getRandomHue() { if (m_hue_settings.empty()) return 0.0f; const unsigned int hue = m_random_hue.get(m_hue_settings.size()); assert(hue < m_hue_settings.size()); return m_hue_settings[hue]; } // ------------------------------------------------------------------------ /** Returns if this material should trigger a rescue if a kart * crashes against it. */ CollisionReaction getCollisionReaction() const { return m_collision_reaction; } // ------------------------------------------------------------------------ std::string getCrashResetParticles() const { return m_collision_particles; } // ------------------------------------------------------------------------ bool highTireAdhesion () const { return m_high_tire_adhesion; } // ------------------------------------------------------------------------ const std::string& getTexFname () const { return m_texname; } // ------------------------------------------------------------------------ const std::string& getTexFullPath () const { return m_full_path; } // ------------------------------------------------------------------------ bool isTransparent () const { return m_shader_type == SHADERTYPE_ADDITIVE || m_shader_type == SHADERTYPE_ALPHA_BLEND || m_shader_type == SHADERTYPE_ALPHA_TEST; } // ------------------------------------------------------------------------ /** Returns the fraction of maximum speed on this material. */ float getMaxSpeedFraction() const { return m_max_speed_fraction; } // ------------------------------------------------------------------------ /** Returns how long it will take for a slowdown to take effect. * It is the time it takes till the full slowdown applies to * karts. So a short time will slowdown a kart much faster. */ float getSlowDownTime() const { return m_slowdown_time; } // ------------------------------------------------------------------------ /** Returns true if this material is under some other mesh and therefore * requires another raycast to find the surface it is under (used for * gfx, e.g. driving under water to find where the water splash should * be shown at. */ bool isBelowSurface () const { return m_below_surface; } // ------------------------------------------------------------------------ /** Returns true if this material is a surface, i.e. it is going to be * ignored for the physics, but the information is needed e.g. for * gfx. See m_below_surface for more details. */ bool isSurface () const { return m_surface; } // ------------------------------------------------------------------------ /** Returns the name of a special sfx to play while a kart is on this * terrain. The string will be "" if no special sfx exists. */ const std::string &getSFXName() const { return m_sfx_name; } // ------------------------------------------------------------------------ /** Returns if fog is enabled. */ bool isFogEnabled() const { return m_fog; } // ------------------------------------------------------------------------ /** \brief Get the kind of particles that are to be used on this material, * in the given conditions. * \return The particles to use, or NULL if none. */ const ParticleKind* getParticlesWhen(ParticleConditions cond) const { return m_particles_effects[cond]; } // getParticlesWhen // ------------------------------------------------------------------------ /** Returns true if a kart falling over this kind of material triggers * the special falling camera. */ bool hasFallingEffect() const {return m_falling_effect; } // ------------------------------------------------------------------------ /** Returns if being in the air after this texture should start the * jump animation. */ bool isJumpTexture() const { return m_is_jump_texture; } // ------------------------------------------------------------------------ /** Returns true if this texture adjusts the gravity vector of the kart * to be parallel to the normal of the triangle - which allows karts to * e.g. drive upside down. */ bool hasGravity() const { return m_has_gravity; } // ------------------------------------------------------------------------ /** Returns the zipper parametersfor the current material. */ void getZipperParameter(float *zipper_max_speed_increase, float *zipper_duration, float *zipper_speed_gain, float *zipper_fade_out_time, float *zipper_engine_force) const { *zipper_max_speed_increase = m_zipper_max_speed_increase; *zipper_duration = m_zipper_duration; *zipper_speed_gain = m_zipper_speed_gain; *zipper_fade_out_time = m_zipper_fade_out_time; *zipper_engine_force = m_zipper_engine_force; } // getZipperParameter // ------------------------------------------------------------------------ /** Returns the minimum speed of a kart on this material. This is used * for zippers on a ramp to guarantee the right jump distance even * on lower speeds. A negative value indicates no minimum speed. */ float getZipperMinSpeed() const { return m_zipper_min_speed; } // ------------------------------------------------------------------------ ShaderType getShaderType() const { return m_shader_type; } void setShaderType(ShaderType st) { m_shader_type = st; } // ------------------------------------------------------------------------ /** True if this texture should have the U coordinates mirrored. */ char getMirrorAxisInReverse() const { return m_mirror_axis_when_reverse; } // ------------------------------------------------------------------------ const std::string getAlphaMask() const { return m_mask; } }; #endif /* EOF */
nado/stk-code
src/graphics/material.hpp
C++
gpl-3.0
17,686