repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jgmanzanas/CMNT_004_15
project-addons/custom_account/report/account_invoice_contact_report.py
6114
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Pexego All Rights Reserved # # This program 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. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, tools class AccountInvoiceContactReport(models.Model): _name = 'account.invoice.contact.report' _description = "Contact Invoices Statistics" _auto = False _rec_name = 'date' _order = 'date desc' number = fields.Char('Number', readonly=True) date = fields.Date('Date', readonly=True) date_due = fields.Date('Due Date', readonly=True) period_id = fields.Many2one('account.period', 'Period', domain=[('state', '<>', 'done')], readonly=True) partner_id = fields.Many2one('res.partner', 'Partner Company', readonly=True) contact_id = fields.Many2one('res.partner', 'Partner Contact', readonly=True) section_id = fields.Many2one('crm.case.section', 'Sales Team') currency_id = fields.Many2one('res.currency', 'Currency', readonly=True) type = fields.Selection([ ('out_invoice', 'Customer Invoice'), ('in_invoice', 'Supplier Invoice'), ('out_refund', 'Customer Refund'), ('in_refund', 'Supplier Refund'), ], 'Type', readonly=True) state = fields.Selection([ ('draft', 'Draft'), ('proforma', 'Pro-forma'), ('proforma2', 'Pro-forma'), ('open', 'Open'), ('paid', 'Done'), ('cancel', 'Cancelled') ], 'Invoice Status', readonly=True) price_total = fields.Float('Total Without Tax', readonly=True) benefit = fields.Float('Benefit', readonly=True) brand_id = fields.Many2one('product.brand', 'Brand', readonly=True) product_id = fields.Many2one('product.product', 'Product', readonly=True) def _select(self): select_str = """ SELECT sub.id, sub.id_invoice, sub.number, sub.partner_id, sub.contact_id, sub.date, sub.date_due, sub.section_id, sub.period_id, sub.type, sub.state, sub.currency_id, sub.product_id, sub.brand_id, sub.price_total / cr.rate as price_total, CASE WHEN sub.type IN ('out_refund') THEN -sub.benefit WHEN sub.type IN ('out_invoice') THEN sub.benefit ELSE 0 END as benefit """ return select_str def _sub_select(self): select_str = """ SELECT ail.id, ai.id AS id_invoice, ai.number AS number, ai.partner_id, coalesce(rp_contact.id, ai.partner_id) AS contact_id, ai.date_invoice AS date, ai.date_due, ai.section_id, ai.period_id, ai.type, ai.state, ai.currency_id, ail.product_id, pt.product_brand_id AS brand_id, SUM(CASE WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text]) THEN - ail.price_subtotal ELSE ail.price_subtotal END) AS price_total, SUM(ail.quantity * ail.price_unit * (100.0-ail.discount) / 100.0) - sum(coalesce(ail.cost_unit, 0)*ail.quantity) as benefit """ return select_str def _from(self): from_str = """ FROM account_invoice_line ail JOIN account_invoice ai ON ai.id = ail.invoice_id LEFT JOIN sale_order_line_invoice_rel solir ON solir.invoice_id = ail.id LEFT JOIN sale_order_line sol ON sol.id = solir.order_line_id LEFT JOIN sale_order so ON so.id = sol.order_id LEFT JOIN res_partner rp_contact ON rp_contact.id = so.partner_shipping_id LEFT JOIN product_product pp ON pp.id = ail.product_id LEFT JOIN product_template pt ON pt.id = pp.product_tmpl_id """ return from_str def _group_by(self): group_by_str = """ GROUP BY ail.id, ail.product_id, pt.product_brand_id, ai.id, ai.partner_id, coalesce(rp_contact.id, ai.partner_id), ai.number, ai.date_invoice, ai.section_id, ai.period_id, ai.currency_id, ai.type, ai.state """ return group_by_str def init(self, cr): # self._table = account_invoice_contact_report tools.drop_view_if_exists(cr, self._table) cr.execute("""CREATE or REPLACE VIEW %s as ( WITH currency_rate (currency_id, rate, date_start, date_end) AS ( SELECT r.currency_id, r.rate, r.name AS date_start, (SELECT name FROM res_currency_rate r2 WHERE r2.name > r.name AND r2.currency_id = r.currency_id ORDER BY r2.name ASC LIMIT 1) AS date_end FROM res_currency_rate r ) %s FROM ( %s %s %s ) AS sub JOIN currency_rate cr ON (cr.currency_id = sub.currency_id AND cr.date_start <= COALESCE(sub.date, NOW()) AND (cr.date_end IS NULL OR cr.date_end > COALESCE(sub.date, NOW()))) )""" % ( self._table, self._select(), self._sub_select(), self._from(), self._group_by()))
agpl-3.0
opensourceBIM/bimql
BimQL/src/nl/wietmazairac/bimql/set/attribute/SetAttributeSubIfcServiceLifeFactor.java
2993
package nl.wietmazairac.bimql.set.attribute; /****************************************************************************** * Copyright (C) 2009-2017 BIMserver.org * * This program 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import org.bimserver.models.ifc2x3tc1.IfcServiceLifeFactor; public class SetAttributeSubIfcServiceLifeFactor { // fields private Object object; private String attributeName; private String attributeNewValue; // constructors public SetAttributeSubIfcServiceLifeFactor() { } public SetAttributeSubIfcServiceLifeFactor(Object object, String attributeName, String attributeNewValue) { this.object = object; this.attributeName = attributeName; this.attributeNewValue = attributeNewValue; } // methods public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public String getAttributeName() { return attributeName; } public void setAttributeName(String attributeName) { this.attributeName = attributeName; } public String getAttributeNewValue() { return attributeNewValue; } public void setAttributeNewValue(String attributeNewValue) { this.attributeNewValue = attributeNewValue; } public void setAttribute() { if (attributeName.equals("UpperValue")) { //1NoEList //1void //1IfcMeasureValue } else if (attributeName.equals("MostUsedValue")) { //1NoEList //1void //1IfcMeasureValue } else if (attributeName.equals("LowerValue")) { //1NoEList //1void //1IfcMeasureValue } else if (attributeName.equals("PredefinedType")) { //1NoEList //1void //1IfcServiceLifeFactorTypeEnum } else if (attributeName.equals("GlobalId")) { //5NoEList //5void //5IfcGloballyUniqueId } else if (attributeName.equals("OwnerHistory")) { //5NoEList //5void //5IfcOwnerHistory } else if (attributeName.equals("Name")) { //5NoEList ((IfcServiceLifeFactor) object).setName(attributeNewValue); //5void //5String } else if (attributeName.equals("Description")) { //5NoEList ((IfcServiceLifeFactor) object).setDescription(attributeNewValue); //5void //5String } else { } } }
agpl-3.0
yinhm/sugarcrm
include/SugarObjects/templates/person/metadata/detailviewdefs.php
4112
<?php /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $module_name = '<module_name>'; $viewdefs[$module_name]['DetailView'] = array( 'templateMeta' => array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', 'FIND_DUPLICATES', ), ), 'maxColumns' => '2', 'widths' => array( array('label' => '10', 'field' => '30'), array('label' => '10', 'field' => '30') ), ), 'panels' =>array ( array ( array ( 'name' => 'full_name', 'label' => 'LBL_NAME', ), //'full_name', array ( 'name' => 'phone_work', ), ), array ( 'title', array ( 'name' => 'phone_mobile', ), ), array ( 'department', array ( 'name' => 'phone_home', 'label' => 'LBL_HOME_PHONE', ), ), array ( NULL, array ( 'name' => 'phone_other', 'label' => 'LBL_OTHER_PHONE', ), ), array ( array ( 'name' => 'date_entered', 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', 'label' => 'LBL_DATE_ENTERED', ), array ( 'name' => 'phone_fax', 'label' => 'LBL_FAX_PHONE', ), ), array ( array ( 'name' => 'date_modified', 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', 'label' => 'LBL_DATE_MODIFIED', ), 'do_not_call', ), array('assigned_user_name', ''), array( 'email1'), array ( array ( 'name' => 'primary_address_street', 'label'=> 'LBL_PRIMARY_ADDRESS', 'type' => 'address', 'displayParams'=>array('key'=>'primary'), ), array ( 'name' => 'alt_address_street', 'label'=> 'LBL_ALT_ADDRESS', 'type' => 'address', 'displayParams'=>array('key'=>'alt'), ), ), array ( 'description', ), ) ); ?>
agpl-3.0
fnp/wolnelektury
src/club/migrations/0036_auto_20210730_1437.py
927
# Generated by Django 2.2.19 on 2021-07-30 12:37 from django.db import migrations import django_countries.fields class Migration(migrations.Migration): dependencies = [ ('club', '0035_schedule_postal_town'), ] operations = [ migrations.RenameField( model_name='schedule', old_name='postal_1', new_name='postal', ), migrations.RemoveField( model_name='schedule', name='postal_2', ), migrations.RemoveField( model_name='schedule', name='postal_3', ), migrations.RemoveField( model_name='schedule', name='postal_4', ), migrations.AlterField( model_name='schedule', name='postal_country', field=django_countries.fields.CountryField(blank=True, default='PL', max_length=2), ), ]
agpl-3.0
lpellegr/programming
programming-extensions/programming-extension-dataspaces/src/test/java/dataspaces/InputOutputSpaceConfigurationTest.java
8114
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library 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; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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 * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package dataspaces; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.objectweb.proactive.extensions.dataspaces.core.InputOutputSpaceConfiguration; import org.objectweb.proactive.extensions.dataspaces.core.SpaceType; import org.objectweb.proactive.extensions.dataspaces.exceptions.ConfigurationException; public class InputOutputSpaceConfigurationTest { private static final String URL = "http://host/"; private static final String[] URLS = { "/file.txt", "http://host/" }; private static final String PATH = "/file.txt"; private static final String HOSTNAME = "host"; private static final String NAME = "name"; private static final SpaceType TYPE = SpaceType.INPUT; private InputOutputSpaceConfiguration config; @Test public void testCreateInputWithURLName() throws ConfigurationException { config = InputOutputSpaceConfiguration.createInputSpaceConfiguration(URL, null, null, NAME); assertProperlyConfigured(URL, null, null, NAME, SpaceType.INPUT, true); } @Test public void testCreateInputWithURLsName() throws ConfigurationException { config = InputOutputSpaceConfiguration.createInputSpaceConfiguration(Arrays.asList(URLS), null, null, NAME); assertProperlyConfigured(Arrays.asList(URLS), null, null, NAME, SpaceType.INPUT, true); } @Test public void testCreateOutputWithURLName() throws ConfigurationException { config = InputOutputSpaceConfiguration.createOutputSpaceConfiguration(URL, null, null, NAME); assertProperlyConfigured(URL, null, null, NAME, SpaceType.OUTPUT, true); } @Test public void testCreateOutputWithURLsName() throws ConfigurationException { config = InputOutputSpaceConfiguration.createOutputSpaceConfiguration(Arrays.asList(URLS), null, null, NAME); assertProperlyConfigured(Arrays.asList(URLS), null, null, NAME, SpaceType.OUTPUT, true); } @Test public void testCreateWithURLPathHostnameNameType() throws ConfigurationException { config = InputOutputSpaceConfiguration.createConfiguration(URL, PATH, HOSTNAME, NAME, TYPE); assertProperlyConfigured(URL, PATH, HOSTNAME, NAME, TYPE, true); } @Test public void testCreateWithURLsPathHostnameNameType() throws ConfigurationException { config = InputOutputSpaceConfiguration.createConfiguration(Arrays.asList(URLS), PATH, HOSTNAME, NAME, TYPE); assertProperlyConfigured(Arrays.asList(URLS), PATH, HOSTNAME, NAME, TYPE, true); } @Test public void testCreateWithURLNameType() throws ConfigurationException { config = InputOutputSpaceConfiguration.createConfiguration(URL, null, null, NAME, TYPE); assertProperlyConfigured(URL, null, null, NAME, TYPE, true); } @Test public void testCreateWithURLsNameType() throws ConfigurationException { config = InputOutputSpaceConfiguration.createConfiguration(Arrays.asList(URLS), null, null, NAME, TYPE); assertProperlyConfigured(Arrays.asList(URLS), null, null, NAME, TYPE, true); } @Test public void testCreateWithURLHostnameNameType() throws ConfigurationException { // just check if it does not crash if there is no path config = InputOutputSpaceConfiguration.createConfiguration(URL, null, "hostname", NAME, TYPE); } @Test public void testCreateWithPathHostname() throws ConfigurationException { config = InputOutputSpaceConfiguration.createConfiguration((String) null, PATH, HOSTNAME, NAME, TYPE); assertProperlyConfigured((String) null, PATH, HOSTNAME, NAME, TYPE, false); } private void assertProperlyConfigured(String url, String path, String hostname, String name, SpaceType type, boolean complete) { if (url != null) { assertEquals(url, config.getUrls().get(0)); } else { assertEquals(url, config.getUrls()); } assertEquals(path, config.getPath()); assertEquals(hostname, config.getHostname()); assertEquals(name, config.getName()); assertSame(type, config.getType()); assertEquals(complete, config.isComplete()); } private void assertProperlyConfigured(List<String> urls, String path, String hostname, String name, SpaceType type, boolean complete) { assertEquals(urls, config.getUrls()); assertEquals(path, config.getPath()); assertEquals(hostname, config.getHostname()); assertEquals(name, config.getName()); assertSame(type, config.getType()); assertEquals(complete, config.isComplete()); } @Test public void testTryCreateWithNameType() throws ConfigurationException { testTryCreateWrongConfig(null, null, null, NAME, TYPE); } @Test public void testTryCreateWithPathNameTypeNoHostname() throws ConfigurationException { testTryCreateWrongConfig(null, PATH, null, NAME, TYPE); } @Test public void testTryCreateWithURLNameWrongType() throws ConfigurationException { testTryCreateWrongConfig(URL, null, null, NAME, SpaceType.SCRATCH); } @Test public void testTryCreateWithURLNameNoType() throws ConfigurationException { testTryCreateWrongConfig(URL, null, null, NAME, null); } @Test public void testTryCreateWithURLTypeNoName() throws ConfigurationException { testTryCreateWrongConfig(URL, null, null, null, TYPE); } private void testTryCreateWrongConfig(String url, String path, String hostname, String name, SpaceType type) { try { config = InputOutputSpaceConfiguration.createConfiguration(url, path, hostname, name, type); fail("exception expected"); } catch (ConfigurationException x) { } } @Test public void testEquals() throws ConfigurationException { config = InputOutputSpaceConfiguration.createConfiguration(URL, null, "hostname", NAME, TYPE); InputOutputSpaceConfiguration config2 = InputOutputSpaceConfiguration.createConfiguration(URL, null, "hostname", NAME, TYPE); InputOutputSpaceConfiguration config3 = InputOutputSpaceConfiguration.createConfiguration(URL, null, "hostname", NAME + "x", TYPE); assertEquals(config, config2); assertFalse(config.equals(config3)); assertFalse(config3.equals(config)); } }
agpl-3.0
CortexPE/TeaSpoon
src/CortexPE/level/particle/SpellParticle.php
880
<?php declare(strict_types = 1); namespace CortexPE\level\particle; use pocketmine\level\particle\GenericParticle; use pocketmine\math\Vector3; use pocketmine\network\mcpe\protocol\LevelEventPacket; class SpellParticle extends GenericParticle { /** * SpellParticle constructor. * * @param Vector3 $pos * @param int $r * @param int $g * @param int $b * @param int $a */ public function __construct(Vector3 $pos, $r = 0, $g = 0, $b = 0, $a = 255){ parent::__construct($pos, LevelEventPacket::EVENT_PARTICLE_SPLASH, (($a & 0xff) << 24) | (($r & 0xff) << 16) | (($g & 0xff) << 8) | ($b & 0xff)); } /** * @return LevelEventPacket */ public function encode(){ $pk = new LevelEventPacket(); $pk->evid = LevelEventPacket::EVENT_PARTICLE_SPLASH; $pk->position = new Vector3($this->x, $this->y, $this->z); $pk->data = $this->data; return $pk; } }
agpl-3.0
leowmjw/terraform-provider-fixazurerm
fixazurerm/resource_arm_route_table.go
5883
package fixazurerm import ( "bytes" "fmt" "log" "net/http" "strings" "github.com/Azure/azure-sdk-for-go/arm/network" "github.com/hashicorp/terraform/helper/hashcode" "github.com/hashicorp/terraform/helper/schema" ) func resourceArmRouteTable() *schema.Resource { return &schema.Resource{ Create: resourceArmRouteTableCreate, Read: resourceArmRouteTableRead, Update: resourceArmRouteTableCreate, Delete: resourceArmRouteTableDelete, Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: true, }, "location": { Type: schema.TypeString, Required: true, ForceNew: true, StateFunc: azureRMNormalizeLocation, }, "resource_group_name": { Type: schema.TypeString, Required: true, ForceNew: true, }, "route": { Type: schema.TypeSet, Optional: true, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, }, "address_prefix": { Type: schema.TypeString, Required: true, }, "next_hop_type": { Type: schema.TypeString, Required: true, ValidateFunc: validateRouteTableNextHopType, }, "next_hop_in_ip_address": { Type: schema.TypeString, Optional: true, Computed: true, }, }, }, Set: resourceArmRouteTableRouteHash, }, "subnets": { Type: schema.TypeSet, Optional: true, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, Set: schema.HashString, }, "tags": tagsSchema(), }, } } func resourceArmRouteTableCreate(d *schema.ResourceData, meta interface{}) error { client := meta.(*ArmClient) routeTablesClient := client.routeTablesClient log.Printf("[INFO] preparing arguments for Azure ARM Route Table creation.") name := d.Get("name").(string) location := d.Get("location").(string) resGroup := d.Get("resource_group_name").(string) tags := d.Get("tags").(map[string]interface{}) routeSet := network.RouteTable{ Name: &name, Location: &location, Tags: expandTags(tags), } if _, ok := d.GetOk("route"); ok { properties := network.RouteTablePropertiesFormat{} routes, routeErr := expandAzureRmRouteTableRoutes(d) if routeErr != nil { return fmt.Errorf("Error Building list of Route Table Routes: %s", routeErr) } if len(routes) > 0 { routeSet.Properties = &properties } } _, err := routeTablesClient.CreateOrUpdate(resGroup, name, routeSet, make(chan struct{})) if err != nil { return err } read, err := routeTablesClient.Get(resGroup, name, "") if err != nil { return err } if read.ID == nil { return fmt.Errorf("Cannot read Route Table %s (resource group %s) ID", name, resGroup) } d.SetId(*read.ID) return resourceArmRouteTableRead(d, meta) } func resourceArmRouteTableRead(d *schema.ResourceData, meta interface{}) error { routeTablesClient := meta.(*ArmClient).routeTablesClient id, err := parseAzureResourceID(d.Id()) if err != nil { return err } resGroup := id.ResourceGroup name := id.Path["routeTables"] resp, err := routeTablesClient.Get(resGroup, name, "") if err != nil { if resp.StatusCode == http.StatusNotFound { d.SetId("") return nil } return fmt.Errorf("Error making Read request on Azure Route Table %s: %s", name, err) } if resp.Properties.Subnets != nil { if len(*resp.Properties.Subnets) > 0 { subnets := make([]string, 0, len(*resp.Properties.Subnets)) for _, subnet := range *resp.Properties.Subnets { id := subnet.ID subnets = append(subnets, *id) } if err := d.Set("subnets", subnets); err != nil { return err } } } flattenAndSetTags(d, resp.Tags) return nil } func resourceArmRouteTableDelete(d *schema.ResourceData, meta interface{}) error { routeTablesClient := meta.(*ArmClient).routeTablesClient id, err := parseAzureResourceID(d.Id()) if err != nil { return err } resGroup := id.ResourceGroup name := id.Path["routeTables"] _, err = routeTablesClient.Delete(resGroup, name, make(chan struct{})) return err } func expandAzureRmRouteTableRoutes(d *schema.ResourceData) ([]network.Route, error) { configs := d.Get("route").(*schema.Set).List() routes := make([]network.Route, 0, len(configs)) for _, configRaw := range configs { data := configRaw.(map[string]interface{}) address_prefix := data["address_prefix"].(string) next_hop_type := data["next_hop_type"].(string) properties := network.RoutePropertiesFormat{ AddressPrefix: &address_prefix, NextHopType: network.RouteNextHopType(next_hop_type), } if v := data["next_hop_in_ip_address"].(string); v != "" { properties.NextHopIPAddress = &v } name := data["name"].(string) route := network.Route{ Name: &name, Properties: &properties, } routes = append(routes, route) } return routes, nil } func resourceArmRouteTableRouteHash(v interface{}) int { var buf bytes.Buffer m := v.(map[string]interface{}) buf.WriteString(fmt.Sprintf("%s-", m["name"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["address_prefix"].(string))) buf.WriteString(fmt.Sprintf("%s-", m["next_hop_type"].(string))) return hashcode.String(buf.String()) } func validateRouteTableNextHopType(v interface{}, k string) (ws []string, errors []error) { value := strings.ToLower(v.(string)) hopTypes := map[string]bool{ "virtualnetworkgateway": true, "vnetlocal": true, "internet": true, "virtualappliance": true, "none": true, } if !hopTypes[value] { errors = append(errors, fmt.Errorf("Route Table NextHopType Protocol can only be VirtualNetworkGateway, VnetLocal, Internet or VirtualAppliance")) } return }
agpl-3.0
eXtreme-Fusion/EF5-Online
locale/Czech/admin/urls.php
1273
<?php defined('EF5_SYSTEM') || exit; return array( 'URLs Generator' => 'Generátor odkazů', 'Current URL:' => 'Aktuální adresa:', 'New URL:' => 'Nová adresa:', 'Full URL' => 'Plná adresa', 'Short URL' => 'Krátká adresa', 'The URL has been added.' => 'Adresa URL byla přidána.', 'The URL has been edited.' => 'Adresa URL byla upravena.', 'The URL has been deleted.' => 'Adresa URL byla smazána.', 'Error! The URL has not been added.' => 'Došlo k chybě! Adresa URL nebyla přidána.', 'Error! The URL has not been edited.' => 'Došlo k chybě! Adresa URL nebyla upravena.', 'Error! The URL has not been deleted.' => 'Došlo k chybě! Adresa URL nebyla smazána.', 'Incorrect link' => 'Nesprávný odkaz', 'There is no such action' => 'Tato akce není dostupná', 'Every field must be filled' => 'Všechny pole musí být vyplněny', 'About URLs' => '<p>Generátor odkazů vám umožní vytvořit si vlastní cestu na stránky vašeho webu.</p> <p>Adresy, zveřejněny v níže uvedeném formuláři by neměly zahrnovat cesty k hlavní stránce.</p> <p>Příklad správného používání:</p> <br /> <ul><li><strong>Aktuálny adresa:</strong> profile/1/Admin</li><li><strong>Nová adresa:</strong> profil-admina</ul>' );
agpl-3.0
gburt/dmap-sharp
src/Dmap/Hasher.cs
8345
/* * daap-sharp * Copyright (C) 2005 James Willcox <snorp@snorp.net> * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Copyright (C) 2004 David Hammerton <david@crazney.net> * Copyright (C) 2005 Jon Lech Johansen <jon@nanocrew.net> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Text; namespace Dmap { internal class Hasher { private static byte [] _hasht42 = null; private static byte [] _hasht45 = null; private static byte [] _hexchars = Encoding.ASCII.GetBytes( "0123456789ABCDEF" ); private static byte [] _copyright = Convert.FromBase64String( "Q29weXJpZ2h0IDIwMDMgQXBwbGUgQ29tcHV0ZXIsIEluYy4=" ); private static void HashToString( byte [] hash, byte [] str, int offset ) { for( int i = 0; i < hash.Length; i++ ) { byte tmp = hash[ i ]; str[ i * 2 + 1 + offset ] = _hexchars[ tmp & 0xF ]; str[ i * 2 + 0 + offset ] = _hexchars[ (tmp >> 4) & 0xF ]; } } private static void TransformString( BrokenMD5 md5, string str, bool final ) { byte [] tmp = Encoding.ASCII.GetBytes( str ); if( final ) md5.TransformFinalBlock( tmp, 0, tmp.Length ); else md5.TransformBlock( tmp, 0, tmp.Length, tmp, 0 ); } private static void GenerateTable42() { int i; _hasht42 = new byte[ 256 * 32 ]; for( i = 0; i < 256; i++ ) { BrokenMD5 md5 = new BrokenMD5( 0 ); if( ( i & 0x80 ) != 0 ) TransformString( md5, "Accept-Language", false ); else TransformString( md5, "user-agent", false ); if( ( i & 0x40 ) != 0 ) TransformString( md5, "max-age", false ); else TransformString( md5, "Authorization", false ); if( ( i & 0x20 ) != 0 ) TransformString( md5, "Client-DAAP-Version", false ); else TransformString( md5, "Accept-Encoding", false ); if( ( i & 0x10 ) != 0 ) TransformString( md5, "daap.protocolversion", false ); else TransformString( md5, "daap.songartist", false ); if( ( i & 0x08 ) != 0 ) TransformString( md5, "daap.songcomposer", false ); else TransformString( md5, "daap.songdatemodified", false ); if( ( i & 0x04 ) != 0 ) TransformString( md5, "daap.songdiscnumber", false ); else TransformString( md5, "daap.songdisabled", false ); if( ( i & 0x02 ) != 0 ) TransformString( md5, "playlist-item-spec", false ); else TransformString( md5, "revision-number", false ); if( ( i & 0x01 ) != 0 ) TransformString( md5, "session-id", true ); else TransformString( md5, "content-codes", true ); HashToString( md5.Hash, _hasht42, i * 32 ); } } private static void GenerateTable45() { int i; _hasht45 = new byte[ 256 * 32 ]; for( i = 0; i < 256; i++ ) { BrokenMD5 md5 = new BrokenMD5( 1 ); if( ( i & 0x40 ) != 0 ) TransformString( md5, "eqwsdxcqwesdc", false ); else TransformString( md5, "op[;lm,piojkmn", false ); if( ( i & 0x20 ) != 0 ) TransformString( md5, "876trfvb 34rtgbvc", false ); else TransformString( md5, "=-0ol.,m3ewrdfv", false ); if( ( i & 0x10 ) != 0 ) TransformString( md5, "87654323e4rgbv ", false ); else TransformString( md5, "1535753690868867974342659792", false ); if( ( i & 0x08 ) != 0 ) TransformString( md5, "Song Name", false ); else TransformString( md5, "DAAP-CLIENT-ID:", false ); if( ( i & 0x04 ) != 0 ) TransformString( md5, "111222333444555", false ); else TransformString( md5, "4089961010", false ); if( ( i & 0x02 ) != 0 ) TransformString( md5, "playlist-item-spec", false ); else TransformString( md5, "revision-number", false ); if( ( i & 0x01 ) != 0 ) TransformString( md5, "session-id", false ); else TransformString( md5, "content-codes", false ); if( ( i & 0x80 ) != 0 ) TransformString( md5, "IUYHGFDCXWEDFGHN", true ); else TransformString( md5, "iuytgfdxwerfghjm", true ); HashToString( md5.Hash, _hasht45, i * 32 ); } } public static string GenerateHash(int version_major, string url, int hash_select, int request_id ) { if( _hasht42 == null ) GenerateTable42(); if( _hasht45 == null ) GenerateTable45(); byte [] hashtable = (version_major == 3) ? _hasht45 : _hasht42; BrokenMD5 md5 = new BrokenMD5( (version_major == 3) ? 1 : 0 ); byte [] hash = new byte[ 32 ]; byte [] tmp = Encoding.ASCII.GetBytes( url ); md5.TransformBlock( tmp, 0, tmp.Length, tmp, 0 ); md5.TransformBlock( _copyright, 0, _copyright.Length, _copyright, 0 ); if( request_id > 0 && version_major == 3 ) { md5.TransformBlock( hashtable, hash_select * 32, 32, hashtable, hash_select * 32 ); tmp = Encoding.ASCII.GetBytes( request_id.ToString() ); md5.TransformFinalBlock( tmp, 0, tmp.Length ); } else { md5.TransformFinalBlock( hashtable, hash_select * 32, 32 ); } HashToString( md5.Hash, hash, 0 ); return Encoding.ASCII.GetString( hash ); } } }
lgpl-2.1
hyyh619/OpenSceneGraph-3.4.0
src/osgWrappers/deprecated-dotosg/osgVolume/Property.cpp
1225
#include <osgVolume/Property> #include <iostream> #include <string> #include <osg/Vec3> #include <osg/Vec4> #include <osg/io_utils> #include <osgDB/ReadFile> #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/ParameterOutput> bool Property_readLocalData(osg::Object &obj, osgDB::Input &fr); bool Property_writeLocalData(const osg::Object &obj, osgDB::Output &fw); REGISTER_DOTOSGWRAPPER(Property_Proxy) ( new osgVolume::Property, "Property", "Object Property", Property_readLocalData, Property_writeLocalData ); REGISTER_DOTOSGWRAPPER(MaximumImageProjectionProperty_Proxy) ( new osgVolume::MaximumIntensityProjectionProperty, "MaximumIntensityProjectionProperty", "Object MaximumIntensityProjectionProperty", Property_readLocalData, Property_writeLocalData ); REGISTER_DOTOSGWRAPPER(LightingProperty_Proxy) ( new osgVolume::LightingProperty, "LightingProperty", "Object LightingProperty", Property_readLocalData, Property_writeLocalData ); bool Property_readLocalData(osg::Object &obj, osgDB::Input &fr) { return false; } bool Property_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { return true; }
lgpl-2.1
umjinsun12/dngshin
html/admin/modules/core/views/trunks/custom.php
695
<tr> <td colspan="2"> <h4><?php echo _("Outgoing Settings")?><hr></h4> </td> </tr> <tr> <td> <a href=# class="info"><?php echo _("Custom Dial String")?><span><?php echo _("Define the custom Dial String. Include the token")?> $OUTNUM$ <?php echo _("wherever the number to dial should go.<br><br><b>examples:</b><br>")?>CAPI/XXXXXXXX/$OUTNUM$<br>H323/$OUTNUM$@XX.XX.XX.XX<br>OH323/$OUTNUM$@XX.XX.XX.XX:XXXX<br>vpb/1-1/$OUTNUM$</span></a>: </td><td> <input type="text" size="35" maxlength="46" name="channelid" value="<?php echo htmlspecialchars($channelid) ?>" tabindex="<?php echo ++$tabindex;?>"/> <input type="hidden" size="14" name="usercontext" value="notneeded"/> </td> </tr>
lgpl-2.1
deegree/deegree3
deegree-core/deegree-core-metadata/src/main/java/org/deegree/protocol/csw/CSWConstants.java
13941
//$HeadURL: svn+ssh://sthomas@svn.wald.intevation.org/deegree/base/trunk/resources/eclipse/files_template.xml $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.protocol.csw; import java.net.URI; import java.net.URISyntaxException; import javax.xml.namespace.QName; import org.deegree.commons.tom.ows.Version; /** * * Container for, in the specification defined, static specified elements * * @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public final class CSWConstants { /** * Namespace for elements from the CSW 2.0.2 specification <br> * Namespace="http://www.opengis.net/cat/csw/2.0.2" * */ public static final String CSW_202_NS = "http://www.opengis.net/cat/csw/2.0.2"; public static final String CSW_202_PREFIX = "csw"; /** * ISO application profile <br> * "http://www.isotc211.org/2005/gmd" */ public static final String ISO_19115_NS = "http://www.isotc211.org/2005/gmd"; /** * DC application profile <br> * "http://purl.org/dc/elements/1.1/" */ public static final String DC_NS = "http://purl.org/dc/elements/1.1/"; /** * DCT application profile <br> * "http://purl.org/dc/terms/" */ public static final String DCT_NS = "http://purl.org/dc/terms/"; /** * LOCAL_PART = "dct" */ public static final String DCT_PREFIX = "dct"; /** * APISO application profile <br> * "http://www.opengis.net/cat/csw/apiso/1.0" */ public static final String APISO_NS = "http://www.opengis.net/cat/csw/apiso/1.0"; /** * Namespace for elements from the ISO AP 1.0 specification <br> * Namespace="http://www.isotc211.org/2005/gmd" * */ public static final String GMD_NS = "http://www.isotc211.org/2005/gmd"; /** * Namespace for elements from the ISO AP 1.0 specification <br> * Namespace="http://www.isotc211.org/2005/srv" * */ public static final String SRV_NS = "http://www.isotc211.org/2005/srv"; /** * Location of the schema <br> * "http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd" */ public static final String CSW_202_DISCOVERY_SCHEMA = "http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd"; /** * Location of the schema <br> * "http://schemas.opengis.net/csw/2.0.2/CSW-publication.xsd" */ public static final String CSW_202_PUBLICATION_SCHEMA = "http://schemas.opengis.net/csw/2.0.2/CSW-publication.xsd"; /** * Location of the schema <br> * "http://schemas.opengis.net/csw/2.0.2/record.xsd" */ public static final String CSW_202_RECORD = "http://schemas.opengis.net/csw/2.0.2/record.xsd"; /** Common namespace prefix for elements from the CSW specification */ public static final String CSW_PREFIX = "csw"; /** * Common namespace prefix for elements from the ISO AP specification for the types "Dataset", "DatasetCollection" * and "Application" */ public static final String GMD_PREFIX = "gmd"; /** * Common namespace prefix for elements from the ISO AP specification for the types "Service" */ public static final String SRV_PREFIX = "srv"; /** * Common namespace prefix for elements from the INSPIRE SDS specification. */ public static final String SDS_PREFIX = "sds"; /** * Namespace for elements from the NSPIRE SDS specification.<br> * Namespace="http://inspire.ec.europa.eu/schemas/inspire_sds/1.0" * */ public static final String SDS_NS = "http://inspire.ec.europa.eu/schemas/inspire_sds/1.0"; /** Common namespace prefix for elements from the ISO AP specification */ public static final String APISO_PREFIX = "apiso"; /** * Common local part of a qualified name for elements from the CSW specification <br> * LOCAL_PART = "Record" */ public static final String DC_LOCAL_PART = "Record"; /** * LOCAL_PART = "dc" */ public static final String DC_PREFIX = "dc"; /** * Common local part of a qualified name for elements from the ISO AP specification <br> * LOCAL_PART = "MD_Metadata" */ public static final String GMD_LOCAL_PART = "MD_Metadata"; /** * Common local part of a qualified name for elements from the ISO AP specification <br> * LOCAL_PART = "Service" */ public static final String SRV_LOCAL_PART = "Service"; /** CSW protocol version 2.0.2 */ public static final Version VERSION_202 = Version.parseVersion( "2.0.2" ); /** CSW protocol version 2.0.2 as String representation */ public static final String VERSION_202_STRING = "2.0.2"; /** CSW ebrim protocol version 1.0.0 */ public static final Version VERSION_100 = new Version( 1, 0, 0 ); /** * * Operations that is the webservice capable of <br> * <li>GetCapabilities</li> <li>DescribeRecord</li> <li>GetRecords</li> <li>GetRecordById</li><li>Transaction</li> <br> * * @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public enum CSWRequestType { /** Retrieve the capabilities of the service. */ GetCapabilities, /** Discover elements of the service */ DescribeRecord, /** Resource discovery combines the two operations - search and present */ GetRecords, /** Retrieve the default representation of the service */ GetRecordById, /** Creates, modifys and deletes catalogue records */ Transaction, GetRepositoryItem } /** * * Sections are informations about the service represented in the GetCapabilities operation <br> * <li>ServiceIdentification</li> <li>ServiceProvider</li> <li>OperationsMetadata</li> <li>Filter_Capabilities</li> <br> * * @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public enum Sections { /** Metadata about the CSW implementation */ ServiceIdentification, /** Metadata about the organisation that provides the CSW implementation */ ServiceProvider, /** Metadata about the operations provided by this CSW implementation */ OperationsMetadata, /** Metadata about the filter capabilities that are implemented at this server */ Filter_Capabilities } /** * Specifies the mode of the response that is requested. The modes are: <br> * <li>hits (default)</li> <li>results</li> <li>validate</li> <br> * * * @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public enum ResultType { /** returns an empty SearchResults element that include the size of the result set */ hits, /** returns one or more records from the result set up to the maximum number of records specified in the request */ results, /** validates the request message */ validate; ResultType() { } public static ResultType determineResultType( String typeString ) { ResultType resultType = null; typeString = typeString.toLowerCase(); if ( typeString.equalsIgnoreCase( ResultType.hits.name() ) ) { resultType = ResultType.hits; } else if ( typeString.equalsIgnoreCase( ResultType.results.name() ) ) { resultType = ResultType.results; } else if ( typeString.equalsIgnoreCase( ResultType.validate.name() ) ) { resultType = ResultType.validate; } return resultType; } } /** * * Specifies the elements that should be returned in the response <br> * <li>brief</li> <li>summary</li> <li>full</li> <br> * * @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public enum ReturnableElement { /** * Brief representation of a record. This is the shortest view of a record by a specific profile. */ brief, /** * Summary representation of a record. This view responses all the elements that should be queryable by a * record-profile. */ summary, /** * Full representation of a record. In that response there are all the elements represented that a record holds. * Thus, there are elements presented that are not queryable regarding to the CSW specification. */ full; private ReturnableElement() { // TODO Auto-generated constructor stub } public static ReturnableElement determineReturnableElement( String returnableElement ) { ReturnableElement elementSetName = null; returnableElement = returnableElement.toLowerCase(); if ( returnableElement.equalsIgnoreCase( ReturnableElement.brief.name() ) ) { elementSetName = ReturnableElement.brief; } else if ( returnableElement.equalsIgnoreCase( ReturnableElement.summary.name() ) ) { elementSetName = ReturnableElement.summary; } else if ( returnableElement.equalsIgnoreCase( ReturnableElement.full.name() ) ) { elementSetName = ReturnableElement.full; } else { elementSetName = ReturnableElement.summary; } return elementSetName; } } /** * * Specifies in which filter mode the query has to be processed. Either there is a OGC XML filter encoding after the * filterspecification document <a href="http://www.opengeospatial.org/standards/filter">OGC 04-095</a> or there is * a common query language string (CqlText) which can be seen as an explicit typed statement like an SQL statement. * * @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public enum ConstraintLanguage { /** Common Queryable Language Text filtering */ CQLTEXT, /** Filterexpression specified in OGC Spec document 04-095 */ FILTER } /** * * Defined in the CSW-publication.xsd. Specifies the data manipulation operations <br> * <li>insert</li> <li>delete</li> <li>update</li> <br> * * @author <a href="mailto:thomas@lat-lon.de">Steffen Thomas</a> * @author last edited by: $Author: thomas $ * * @version $Revision: $, $Date: $ */ public enum TransactionType { /** * With the INSERT action of the transaction operation there can be inserted one or more records into the * backend. */ INSERT, /** * With the DELETE action of the transaction operation there can be deleted specific records defined by a filter * expression. */ DELETE, /** * With the UPDATE action of the transaction operation there can be updated one complete record or just * properties of specific records defined by a filter expression. */ UPDATE } public enum OutputSchema { DC, ISO_19115; private OutputSchema() { } public static URI determineOutputSchema( OutputSchema outputSchema ) throws MetadataStoreException { URI schema = null; try { switch ( outputSchema ) { case DC: schema = new URI( CSWConstants.CSW_202_NS ); break; case ISO_19115: schema = new URI( CSWConstants.GMD_NS ); break; } } catch ( URISyntaxException e ) { throw new MetadataStoreException( e.getMessage() ); } return schema; } public static OutputSchema determineByTypeName( QName typeName ) { String uri = typeName.getNamespaceURI(); if ( uri.equals( CSW_202_NS ) ) { return DC; } else if ( uri.equals( GMD_NS ) ) { return ISO_19115; } return null; } } }
lgpl-2.1
skosukhin/spack
var/spack/repos/builtin/packages/mshadow/package.py
1833
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the LICENSE file for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of 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 program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Mshadow(Package): """MShadow is a lightweight CPU/GPU Matrix/Tensor C++ Template Library. in C++/CUDA.""" homepage = "https://github.com/dmlc/mshadow" url = "https://github.com/dmlc/mshadow/archive/v1.1.tar.gz" version('master', git='https://github.com/dmlc/mshadow.git', branch='master') version('20170721', git='https://github.com/dmlc/mshadow.git', commit='20b54f068c1035f0319fa5e5bbfb129c450a5256') def install(self, spec, prefix): install_tree('mshadow', prefix.include.mshadow) install_tree('make', prefix.make)
lgpl-2.1
Zongsoft/Zongsoft.Externals.Quartz
Commands/ServerCommandBase.cs
3010
/* * Authors: * 阳敏(Jason Yang) <jasonsoop@gmail.com> * * Copyright (C) 2014 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.Externals.Quartz. * * Zongsoft.Externals.Quartz 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. * * Zongsoft.Externals.Quartz 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. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.Externals.Quartz; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Common.Logging; using Zongsoft.Services; using Zongsoft.Terminals; using Zongsoft.Externals.Quartz.Communication; namespace Zongsoft.Externals.Quartz.Commands { /// <summary> /// 提供实现 <see cref="T:Zongsoft.Services.ICommand"/> 接口功能的调度服务器命令基类。 /// </summary> public abstract class ServerCommandBase : CommandBase<TerminalCommandContext> { #region 成员字段 private IQuartzServer _server; private ILog _logger; #endregion #region 公共属性 /// <summary> /// 获取或设置调度服务器实例。 /// </summary> public IQuartzServer Server { get { return _server; } set { if(value == null) throw new ArgumentNullException(); _server = value; } } /// <summary> /// 获取或设置日志记录器实例。 /// </summary> public ILog Logger { get { return _logger; } set { if(value == null) throw new ArgumentNullException(); _logger = value; } } #endregion #region 构造方法 /// <summary> /// 初始化 RemoteServerCommandBase 类的新实例。 /// </summary> /// <param name="name">命令名称。</param> protected ServerCommandBase(string name) : base(name) { this._logger = LogManager.GetLogger(this.GetType()); } /// <summary> /// 初始化 RemoteServerCommandBase 类的新实例。 /// </summary> /// <param name="name">命令名称。</param> /// <param name="server">调度服务器实例。</param> protected ServerCommandBase(string name, IQuartzServer server) : this(name) { _server = server; } #endregion #region 重写方法 public override bool CanExecute(TerminalCommandContext parameter) { return _server != null && base.CanExecute(parameter); } #endregion } }
lgpl-2.1
bakaiadam/collaborative_qt_creator
src/plugins/projectexplorer/buildsteplist.cpp
6402
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "buildsteplist.h" #include "buildconfiguration.h" #include "buildmanager.h" #include "buildstep.h" #include "deployconfiguration.h" #include "projectexplorer.h" #include "target.h" #include <extensionsystem/pluginmanager.h> using namespace ProjectExplorer; namespace { IBuildStepFactory *findCloneFactory(BuildStepList *parent, BuildStep *source) { QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IBuildStepFactory>(); foreach(IBuildStepFactory *factory, factories) if (factory->canClone(parent, source)) return factory; return 0; } IBuildStepFactory *findRestoreFactory(BuildStepList *parent, const QVariantMap &map) { QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IBuildStepFactory>(); foreach(IBuildStepFactory *factory, factories) if (factory->canRestore(parent, map)) return factory; return 0; } const char * const STEPS_COUNT_KEY("ProjectExplorer.BuildStepList.StepsCount"); const char * const STEPS_PREFIX("ProjectExplorer.BuildStepList.Step."); } // namespace BuildStepList::BuildStepList(QObject *parent, const QString &id) : ProjectConfiguration(parent, id), m_isNull(false) { Q_ASSERT(parent); } BuildStepList::BuildStepList(QObject *parent, BuildStepList *source) : ProjectConfiguration(parent, source), m_isNull(source->m_isNull) { Q_ASSERT(parent); // do not clone the steps here: // The BC is not fully set up yet and thus some of the buildstepfactories // will fail to clone the buildsteps! } BuildStepList::BuildStepList(QObject *parent, const QVariantMap &data) : ProjectConfiguration(parent, QLatin1String("UNKNOWN ID")) { Q_ASSERT(parent); m_isNull = !fromMap(data); } BuildStepList::~BuildStepList() { qDeleteAll(m_steps); } QVariantMap BuildStepList::toMap() const { QVariantMap map(ProjectConfiguration::toMap()); // Save build steps map.insert(QString::fromLatin1(STEPS_COUNT_KEY), m_steps.count()); for (int i = 0; i < m_steps.count(); ++i) map.insert(QString::fromLatin1(STEPS_PREFIX) + QString::number(i), m_steps.at(i)->toMap()); return map; } bool BuildStepList::isNull() const { return m_isNull; } int BuildStepList::count() const { return m_steps.count(); } bool BuildStepList::isEmpty() const { return m_steps.isEmpty(); } bool BuildStepList::contains(const QString &id) const { foreach (BuildStep *bs, steps()) { if (bs->id() == id) return true; } return false; } void BuildStepList::cloneSteps(BuildStepList *source) { Q_ASSERT(source); foreach (BuildStep *originalbs, source->steps()) { IBuildStepFactory *factory(findCloneFactory(this, originalbs)); if (!factory) continue; BuildStep *clonebs(factory->clone(this, originalbs)); if (clonebs) m_steps.append(clonebs); } } bool BuildStepList::fromMap(const QVariantMap &map) { // We need the ID set before trying to restore the steps! if (!ProjectConfiguration::fromMap(map)) return false; int maxSteps = map.value(QString::fromLatin1(STEPS_COUNT_KEY), 0).toInt(); for (int i = 0; i < maxSteps; ++i) { QVariantMap bsData(map.value(QString::fromLatin1(STEPS_PREFIX) + QString::number(i)).toMap()); if (bsData.isEmpty()) { qWarning() << "No step data found for" << i << "(continuing)."; continue; } IBuildStepFactory *factory(findRestoreFactory(this, bsData)); if (!factory) { qWarning() << "No factory for step" << i << "found (continuing)."; continue; } BuildStep *bs(factory->restore(this, bsData)); if (!bs) { qWarning() << "Restoration of step" << i << "failed (continuing)."; continue; } insertStep(m_steps.count(), bs); } return true; } QList<BuildStep *> BuildStepList::steps() const { return m_steps; } void BuildStepList::insertStep(int position, BuildStep *step) { m_steps.insert(position, step); emit stepInserted(position); } bool BuildStepList::removeStep(int position) { ProjectExplorer::BuildManager *bm = ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager(); BuildStep *bs = at(position); if (bm->isBuilding(bs)) return false; emit aboutToRemoveStep(position); m_steps.removeAt(position); delete bs; emit stepRemoved(position); return true; } void BuildStepList::moveStepUp(int position) { m_steps.swap(position - 1, position); emit stepMoved(position, position - 1); } BuildStep *BuildStepList::at(int position) { return m_steps.at(position); } Target *BuildStepList::target() const { Q_ASSERT(parent()); BuildConfiguration *bc = qobject_cast<BuildConfiguration *>(parent()); if (bc) return bc->target(); DeployConfiguration *dc = qobject_cast<DeployConfiguration *>(parent()); if (dc) return dc->target(); return 0; }
lgpl-2.1
JasonILTG/Minecraft-Modding
src/main/java/com/JasonILTG/ScienceMod/reference/Textures.java
13187
package com.JasonILTG.ScienceMod.reference; import com.JasonILTG.ScienceMod.util.ResourceHelper; import net.minecraft.util.ResourceLocation; /** * Reference class for textures. * * @author JasonILTG and syy1125 */ public class Textures { private static final String TEXTURE_LOCATION = "textures/"; // References for GUIs public static final class GUI { // Default private static final String GUI_TEXTURE_LOCATION = TEXTURE_LOCATION + "gui/"; public static final int DEFAULT_GUI_X_SIZE = 176; public static final int DEFAULT_GUI_Y_SIZE = 166; // Player Inventory public static final ResourceLocation PLAYER_INV = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "player_inventory.png"); public static final int PLAYER_INV_WIDTH = 176; public static final int PLAYER_INV_HEIGHT = 98; // Progress Direction public static final int TOP = 0; public static final int BOTTOM = 1; public static final int LEFT = 2; public static final int RIGHT = 3; // Tanks public static final ResourceLocation TANK = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "fluid_tank.png"); public static final int DEFAULT_TANK_WIDTH = 16; public static final int DEFAULT_TANK_HEIGHT = 56; public static final ResourceLocation WATER_TANK = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "water_tank.png"); public static final int DEFAULT_TANK_DIR = BOTTOM; // Progress Bars public static final ResourceLocation PROGRESS_BAR_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "progress_bar_empty.png"); public static final ResourceLocation PROGRESS_BAR_FULL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "progress_bar_full.png"); public static final int DEFAULT_PROGRESS_WIDTH = 16; public static final int DEFAULT_PROGRESS_HEIGHT = 5; public static final int DEFAULT_PROGRESS_DIR = LEFT; // Power public static final ResourceLocation POWER_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "power_empty.png"); public static final ResourceLocation POWER_FULL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "power_full.png"); public static final int POWER_WIDTH = 8; public static final int POWER_HEIGHT = 16; public static final int POWER_DIR = BOTTOM; // Temperature public static final ResourceLocation TEMP_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "thermometer_progress_empty.png"); public static final ResourceLocation TEMP_FULL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "thermometer_progress_full.png"); public static final int TEMP_WIDTH = 6; public static final int TEMP_HEIGHT = 34; public static final int TEMP_DIR = BOTTOM; public static final int TEMP_MAX = 100; public static final int TEMP_MIN = 0; // Fire public static final ResourceLocation FIRE_FULL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "fire_progress_full.png"); public static final ResourceLocation FIRE_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "fire_progress_empty.png"); public static final int FIRE_WIDTH = 13; public static final int FIRE_HEIGHT = 12; public static final int FIRE_DIR = TOP; // Upgrades public static final ResourceLocation UPGRADE = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "upgrade.png"); public static final int UPGRADE_WIDTH = 33; public static final int UPGRADE_HEIGHT = 50; public static final int UPGRADE_SLOT_X = 9; public static final int UPGRADE_SLOT_1_Y = 8; public static final int UPGRADE_SLOT_2_Y = 26; // Jar Launcher public static final ResourceLocation JAR_LAUNCHER = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "jar_launcher.png"); public static final int JAR_LAUNCHER_GUI_WIDTH = 108; public static final int JAR_LAUNCHER_GUI_HEIGHT = 82; public static final class Machine { // Electrolyzer public static final ResourceLocation ELECTROLYZER = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "electrolyzer.png"); public static final int ELECTROLYZER_GUI_WIDTH = 119; public static final int ELECTROLYZER_GUI_HEIGHT = 83; public static final ResourceLocation ELECTROLYZER_PROGRESS_FULL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "electrolyzer_progress_bar_full.png"); public static final ResourceLocation ELECTROLYZER_PROGRESS_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "electrolyzer_progress_bar_empty.png"); public static final int ELECTROLYZER_PROGRESS_WIDTH = 28; public static final int ELECTROLYZER_PROGRESS_HEIGHT = 22; public static final int ELECTROLYZER_PROGRESS_X = 67; public static final int ELECTROLYZER_PROGRESS_Y = 35; public static final int ELECTROLYZER_PROGRESS_DIR = TOP; public static final int ELECTROLYZER_TANK_X = 37; public static final int ELECTROLYZER_TANK_Y = 18; public static final int ELECTROLYZER_POWER_X = 119; public static final int ELECTROLYZER_POWER_Y = 40; public static final int ELECTROLYZER_TEMP_X = 133; public static final int ELECTROLYZER_TEMP_Y = 8; // Air Extractor public static final ResourceLocation AIR_EXTRACTOR = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "air_extractor.png"); public static final int AIR_EXTRACTOR_GUI_WIDTH = 233; public static final int AIR_EXTRACTOR_GUI_HEIGHT = 79; public static final int AIR_EXTRACTOR_PROGRESS_X = -19; public static final int AIR_EXTRACTOR_PROGRESS_Y = 21; public static final int AIR_EXTRACTOR_POWER_X = -15; public static final int AIR_EXTRACTOR_POWER_Y = 32; public static final int AIR_EXTRACTOR_TEMP_X = 191; public static final int AIR_EXTRACTOR_TEMP_Y = 8; // Condenser public static final ResourceLocation CONDENSER = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "condenser.png"); public static final int CONDENSER_GUI_WIDTH = 95; public static final int CONDENSER_GUI_HEIGHT = 83; public static final ResourceLocation CONDENSER_PROGRESS_FULL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "condenser_progress_bar_full.png"); public static final ResourceLocation CONDENSER_PROGRESS_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "condenser_progress_bar_empty.png"); public static final int CONDENSER_PROGRESS_WIDTH = 16; public static final int CONDENSER_PROGRESS_HEIGHT = 16; public static final int CONDENSER_PROGRESS_X = 74; public static final int CONDENSER_PROGRESS_Y = 27; public static final int CONDENSER_PROGRESS_DIR = BOTTOM; public static final int CONDENSER_TANK_X = 48; public static final int CONDENSER_TANK_Y = 18; public static final int CONDENSER_POWER_X = 103; public static final int CONDENSER_POWER_Y = 29; public static final int CONDENSER_TEMP_X = 121; public static final int CONDENSER_TEMP_Y = 8; // Mixer public static final ResourceLocation MIXER = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "mixer.png"); public static final int MIXER_GUI_WIDTH = 94; public static final int MIXER_GUI_HEIGHT = 83; public static final ResourceLocation MIXER_PROGRESS_FULL_SOLUTION = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "mixer_progress_bar_full_solution.png"); public static final ResourceLocation MIXER_PROGRESS_FULL_MIXTURE = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "mixer_progress_bar_full_mixture.png"); public static final ResourceLocation MIXER_PROGRESS_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "mixer_progress_bar_empty.png"); public static final int MIXER_PROGRESS_WIDTH = 16; public static final int MIXER_PROGRESS_HEIGHT = 16; public static final int MIXER_PROGRESS_X = 73; public static final int MIXER_PROGRESS_Y = 58; public static final int MIXER_PROGRESS_DIR = BOTTOM; public static final int MIXER_TANK_X = 50; public static final int MIXER_TANK_Y = 18; public static final int MIXER_TEMP_X = 121; public static final int MIXER_TEMP_Y = 8; // Centrifuge public static final ResourceLocation CENTRIFUGE = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "centrifuge.png"); public static final int CENTRIFUGE_GUI_WIDTH = 108; public static final int CENTRIFUGE_GUI_HEIGHT = 82; // Distiller public static final ResourceLocation DISTILLER = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "distiller.png"); public static final int DISTILLER_GUI_WIDTH = 108; public static final int DISTILLER_GUI_HEIGHT = 82; // Chemical Reactor public static final ResourceLocation CHEM_REACTOR = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "chemical_reactor.png"); public static final int CHEM_REACTOR_GUI_WIDTH = 121; public static final int CHEM_REACTOR_GUI_HEIGHT = 86; public static final ResourceLocation CHEM_REACTOR_PROGRESS_FULL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "chemical_reactor_progress_bar_full.png"); public static final ResourceLocation CHEM_REACTOR_PROGRESS_EMPTY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "chemical_reactor_progress_bar_empty.png"); public static final int CHEM_REACTOR_PROGRESS_WIDTH = 32; public static final int CHEM_REACTOR_PROGRESS_HEIGHT = 46; public static final int CHEM_REACTOR_PROGRESS_X = 53; public static final int CHEM_REACTOR_PROGRESS_Y = 25; public static final int CHEM_REACTOR_PROGRESS_DIR = LEFT; public static final int CHEM_REACTOR_POWER_X = 116; public static final int CHEM_REACTOR_POWER_Y = 44; public static final int CHEM_REACTOR_TEMP_X = 134; public static final int CHEM_REACTOR_TEMP_Y = 8; } public static final class Generator { // Combuster public static final ResourceLocation COMBUSTER = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "combuster.png"); public static final int COMBUSTER_GUI_WIDTH = 111; public static final int COMBUSTER_GUI_HEIGHT = 83; public static final int COMBUSTER_PROGRESS_X = 85; public static final int COMBUSTER_PROGRESS_Y = 40; public static final int COMBUSTER_FUEL_TANK_X = 63; public static final int COMBUSTER_FUEL_TANK_Y = 18; public static final int COMBUSTER_COOLANT_TANK_X = 41; public static final int COMBUSTER_COOLANT_TANK_Y = 18; public static final int COMBUSTER_POWER_X = 111; public static final int COMBUSTER_POWER_Y = 18; public static final int COMBUSTER_TEMP_X = 129; public static final int COMBUSTER_TEMP_Y = 8; // Solar Panel public static final ResourceLocation SOLAR_PANEL = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "solar_panel.png"); public static final int SOLAR_PANEL_GUI_WIDTH = 72; public static final int SOLAR_PANEL_GUI_HEIGHT = 80; public static final int SOLAR_PANEL_POWER_X = 84; public static final int SOLAR_PANEL_POWER_Y = 37; public static final int SOLAR_PANEL_TEMP_X = 110; public static final int SOLAR_PANEL_TEMP_Y = 8; public static final ResourceLocation SOLAR_PANEL_DAY = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "solar_panel_day.png"); public static final ResourceLocation SOLAR_PANEL_NIGHT = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "solar_panel_night.png"); public static final ResourceLocation SOLAR_PANEL_OFF = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "solar_panel_off.png"); public static final int SOLAR_PANEL_ICON_WIDTH = 10; public static final int SOLAR_PANEL_ICON_HEIGHT = 10; public static final int SOLAR_PANEL_ICON_X = 83; public static final int SOLAR_PANEL_ICON_Y = 21; } public static final class Component { public static final ResourceLocation ASSEMBLER = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "assembler.png"); public static final int ASSEMBLER_GUI_WIDTH = 109; public static final int ASSEMBLER_GUI_HEIGHT = 79; } public static final class Misc { public static final ResourceLocation DRAIN = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "drain.png"); public static final int DRAIN_GUI_WIDTH = 144; public static final int DRAIN_GUI_HEIGHT = 79; public static final ResourceLocation CHEM_PROPERTIES = ResourceHelper.getResourceLocation(GUI_TEXTURE_LOCATION + "chem_properties.png"); public static final int CHEM_PROPERTIES_WIDTH = 42; public static final int CHEM_PROPERTIES_HEIGHT = 42; } } public static final class JEI { public static final String JEI_TEXTURE_LOCATION = GUI.GUI_TEXTURE_LOCATION + "jei/"; public static final ResourceLocation ELECTROLYZER = ResourceHelper.getResourceLocation(JEI_TEXTURE_LOCATION + "electrolyzer.png"); public static final int ELECTROLYZER_WIDTH = 42; public static final int ELECTROLYZER_HEIGHT = 42; } public static final class Entity { public static final String PROJECTILE_TEXTURE_LOCATION = TEXTURE_LOCATION + "items/"; } }
lgpl-2.1
luminwin/beast-mcmc
src/dr/inference/operators/GibbsIndependentGammaOperator.java
5212
/* * GibbsIndependentGammaOperator.java * * Copyright (c) 2002-2014 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.inference.operators; import dr.inference.model.Bounds; import dr.inference.model.Parameter; import dr.inference.model.Variable; import dr.math.distributions.GammaDistribution; import dr.xml.AttributeRule; import dr.xml.ElementRule; import dr.xml.XMLObject; import dr.xml.XMLParseException; import dr.xml.XMLSyntaxRule; /** * An independent gamma sampler to propose new (independent) values from a provided gamma prior (distribution). * * @author Guy Baele * */ public class GibbsIndependentGammaOperator extends SimpleMCMCOperator implements GibbsOperator { public static final String OPERATOR_NAME = "GibbsIndependentGammaOperator"; public static final String SHAPE = "shape"; public static final String SCALE = "scale"; private Variable<Double> variable = null; private GammaDistribution gamma = null; private boolean updateAllIndependently = true; public GibbsIndependentGammaOperator(Variable variable, GammaDistribution gamma) { this(variable, gamma, 1.0); } public GibbsIndependentGammaOperator(Variable variable, GammaDistribution gamma, double weight) { this(variable, gamma, weight, true); } public GibbsIndependentGammaOperator(Variable variable, GammaDistribution gamma, double weight, boolean updateAllIndependently) { this.variable = variable; this.gamma = gamma; this.updateAllIndependently = updateAllIndependently; setWeight(weight); } public String getPerformanceSuggestion() { return ""; } public String getOperatorName() { return "GibbsIndependentGamma(" + variable.getVariableName() + ")"; } public int getStepCount() { return 1; } /** * change the parameter and return the hastings ratio. */ public double doOperation() throws OperatorFailedException { //double logq = 0; //double currentValue; double newValue; final Bounds<Double> bounds = variable.getBounds(); final int dim = variable.getSize(); if (updateAllIndependently) { for (int i = 0; i < dim; i++) { //both current and new value of the variable needed for the hastings ratio //currentValue = variable.getValue(i); newValue = gamma.nextGamma(); while (newValue == 0.0) { newValue = gamma.nextGamma(); } //System.err.println("newValue: " + newValue + " - logPdf: " + gamma.logPdf(newValue)); //logq += (gamma.logPdf(currentValue) - gamma.logPdf(newValue)); if (newValue < bounds.getLowerLimit(i) || newValue > bounds.getUpperLimit(i)) { throw new OperatorFailedException("proposed value outside boundaries"); } variable.setValue(i, newValue); } } //return logq; return 0; } public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { public String getParserName() { return OPERATOR_NAME; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { double weight = xo.getDoubleAttribute(WEIGHT); double shape = xo.getDoubleAttribute(SHAPE); double scale = xo.getDoubleAttribute(SCALE); if (! (shape > 0 && scale > 0)) { throw new XMLParseException("Shape and scale must be positive values."); } Parameter parameter = (Parameter) xo.getChild(Parameter.class); return new GibbsIndependentGammaOperator(parameter, new GammaDistribution(shape, scale), weight); } //************************************************************************ // AbstractXMLObjectParser implementation //************************************************************************ public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule(WEIGHT), AttributeRule.newDoubleRule(SHAPE), AttributeRule.newDoubleRule(SCALE), new ElementRule(Parameter.class) }; public String getParserDescription() { return "This element returns an independence sampler, disguised as a Gibss operator, from a provided gamma prior."; } public Class getReturnType() { return MCMCOperator.class; } }; }
lgpl-2.1
YYChildren/jspider
src/net/javacoding/jspider/core/storage/bloommem/InMemoryStorageImpl.java
1484
package net.javacoding.jspider.core.storage.bloommem; import net.javacoding.jspider.core.storage.spi.*; /** * * $Id: InMemoryStorageImpl.java,v 1.24 2003/04/11 16:37:07 vanrogu Exp $ * * @author G�nther Van Roey */ class InMemoryStorageImpl implements StorageSPI { protected SiteDAOSPI siteDAO; protected ResourceDAOSPI resourceDAO; protected ContentDAOSPI contentDAO; protected DecisionDAOSPI decisionDAO; protected CookieDAOSPI cookieDAO; protected EMailAddressDAOSPI emailAddressDAO; protected FolderDAOSPI folderDAO; public InMemoryStorageImpl() { siteDAO = new SiteDAOImpl(this); resourceDAO = new ResourceDAOImpl(this); contentDAO = new ContentDAOImpl(this); decisionDAO = new DecisionDAOImpl(this); cookieDAO = new CookieDAOImpl(this); emailAddressDAO = new EMailAddressDAOImpl(this); folderDAO = new FolderDAOImpl(this); } public FolderDAOSPI getFolderDAO() { return folderDAO; } public SiteDAOSPI getSiteDAO() { return siteDAO; } public ResourceDAOSPI getResourceDAO() { return resourceDAO; } public ContentDAOSPI getContentDAO() { return contentDAO; } public DecisionDAOSPI getDecisionDAO() { return decisionDAO; } public CookieDAOSPI getCookieDAO() { return cookieDAO; } public EMailAddressDAOSPI getEMailAddressDAO() { return emailAddressDAO; } }
lgpl-2.1
ManolitoOctaviano/Language-Identification
src/test/de/danielnaber/languagetool/tagging/de/GermanTaggerTest.java
7123
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package de.danielnaber.languagetool.tagging.de; import java.io.IOException; import java.util.List; import de.danielnaber.languagetool.JLanguageTool; import junit.framework.TestCase; import morfologik.stemming.Dictionary; import morfologik.stemming.DictionaryLookup; import morfologik.stemming.WordData; /** * @author Daniel Naber */ public class GermanTaggerTest extends TestCase { public void testTagger() throws IOException { GermanTagger tagger = new GermanTagger(); AnalyzedGermanTokenReadings aToken = tagger.lookup("Haus"); assertEquals("Haus[SUB:AKK:SIN:NEU, SUB:DAT:SIN:NEU, SUB:NOM:SIN:NEU]", aToken.toSortedString()); assertEquals("Haus", aToken.getReadings().get(0).getLemma()); assertEquals("Haus", aToken.getReadings().get(1).getLemma()); assertEquals("Haus", aToken.getReadings().get(2).getLemma()); aToken = tagger.lookup("Hauses"); assertEquals("Hauses[SUB:GEN:SIN:NEU]", aToken.toSortedString()); assertEquals("Haus", aToken.getReadings().get(0).getLemma()); aToken = tagger.lookup("hauses"); assertNull(aToken); aToken = tagger.lookup("Groß"); assertNull(aToken); aToken = tagger.lookup("großer"); assertEquals("großer[ADJ:DAT:SIN:FEM:GRU:SOL, ADJ:GEN:PLU:FEM:GRU:SOL, " + "ADJ:GEN:PLU:MAS:GRU:SOL, ADJ:GEN:PLU:NEU:GRU:SOL, " + "ADJ:GEN:SIN:FEM:GRU:SOL, ADJ:NOM:SIN:MAS:GRU:IND, ADJ:NOM:SIN:MAS:GRU:SOL]", aToken.toSortedString()); assertEquals("groß", aToken.getReadings().get(0).getLemma()); // from both german.dict and added.txt: aToken = tagger.lookup("Interessen"); assertEquals("Interessen[SUB:AKK:PLU:NEU, SUB:DAT:PLU:NEU, SUB:GEN:PLU:NEU, SUB:NOM:PLU:NEU]", aToken.toSortedString()); assertEquals("Interesse", aToken.getReadings().get(0).getLemma()); assertEquals("Interesse", aToken.getReadings().get(1).getLemma()); assertEquals("Interesse", aToken.getReadings().get(2).getLemma()); assertEquals("Interesse", aToken.getReadings().get(3).getLemma()); // words that are not in the dictionary but that are recognized thanks to noun splitting: aToken = tagger.lookup("Donaudampfschiff"); assertEquals("Donaudampfschiff[SUB:AKK:SIN:NEU, SUB:DAT:SIN:NEU, SUB:NOM:SIN:NEU]", aToken.toSortedString()); assertEquals("Donaudampfschiff", aToken.getReadings().get(0).getLemma()); assertEquals("Donaudampfschiff", aToken.getReadings().get(1).getLemma()); aToken = tagger.lookup("Häuserkämpfe"); assertEquals("Häuserkämpfe[SUB:AKK:PLU:MAS, SUB:GEN:PLU:MAS, SUB:NOM:PLU:MAS]", aToken.toSortedString()); assertEquals("Häuserkampf", aToken.getReadings().get(0).getLemma()); assertEquals("Häuserkampf", aToken.getReadings().get(1).getLemma()); assertEquals("Häuserkampf", aToken.getReadings().get(2).getLemma()); aToken = tagger.lookup("Häuserkampfes"); assertEquals("Häuserkampfes[SUB:GEN:SIN:MAS]", aToken.toSortedString()); assertEquals("Häuserkampf", aToken.getReadings().get(0).getLemma()); aToken = tagger.lookup("Häuserkampfs"); assertEquals("Häuserkampfs[SUB:GEN:SIN:MAS]", aToken.toSortedString()); assertEquals("Häuserkampf", aToken.getReadings().get(0).getLemma()); aToken = tagger.lookup("Lieblingsfarben"); assertEquals("Lieblingsfarben[SUB:AKK:PLU:FEM, SUB:DAT:PLU:FEM, SUB:GEN:PLU:FEM, " + "SUB:NOM:PLU:FEM]", aToken.toSortedString()); assertEquals("Lieblingsfarbe", aToken.getReadings().get(0).getLemma()); aToken = tagger.lookup("Autolieblingsfarben"); assertEquals("Autolieblingsfarben[SUB:AKK:PLU:FEM, SUB:DAT:PLU:FEM, SUB:GEN:PLU:FEM, " + "SUB:NOM:PLU:FEM]", aToken.toSortedString()); assertEquals("Autolieblingsfarbe", aToken.getReadings().get(0).getLemma()); aToken = tagger.lookup("übrigbleibst"); assertEquals("übrigbleibst[VER:2:SIN:PRÄ:NON:NEB]", aToken.toSortedString()); assertEquals("übrigbleiben", aToken.getReadings().get(0).getLemma()); } // make sure we use the version of the POS data that was extended with post spelling reform data public void testExtendedTagger() throws IOException { GermanTagger tagger = new GermanTagger(); assertEquals("Kuß[SUB:AKK:SIN:MAS, SUB:DAT:SIN:MAS, SUB:NOM:SIN:MAS]", tagger.lookup("Kuß").toSortedString()); assertEquals("Kuss[SUB:AKK:SIN:MAS, SUB:DAT:SIN:MAS, SUB:NOM:SIN:MAS]", tagger.lookup("Kuss").toSortedString()); assertEquals("Haß[SUB:AKK:SIN:MAS, SUB:DAT:SIN:MAS, SUB:NOM:SIN:MAS]", tagger.lookup("Haß").toSortedString()); assertEquals("Hass[SUB:AKK:SIN:MAS, SUB:DAT:SIN:MAS, SUB:NOM:SIN:MAS]", tagger.lookup("Hass").toSortedString()); assertEquals("muß[VER:MOD:1:SIN:PRÄ, VER:MOD:3:SIN:PRÄ]", tagger.lookup("muß").toSortedString()); assertEquals("muss[VER:MOD:1:SIN:PRÄ, VER:MOD:3:SIN:PRÄ]", tagger.lookup("muss").toSortedString()); } public void testTaggerBaseforms() throws IOException { GermanTagger tagger = new GermanTagger(); List<AnalyzedGermanToken> readings = tagger.lookup("übrigbleibst").getGermanReadings(); assertEquals(1, readings.size()); assertEquals("übrigbleiben", readings.get(0).getLemma()); readings = tagger.lookup("Haus").getGermanReadings(); assertEquals(3, readings.size()); assertEquals("Haus", readings.get(0).getLemma()); assertEquals("Haus", readings.get(1).getLemma()); assertEquals("Haus", readings.get(2).getLemma()); readings = tagger.lookup("Häuser").getGermanReadings(); assertEquals(3, readings.size()); assertEquals("Haus", readings.get(0).getLemma()); assertEquals("Haus", readings.get(1).getLemma()); assertEquals("Haus", readings.get(2).getLemma()); } public void testDictionary() throws IOException { final Dictionary dictionary = Dictionary.read( JLanguageTool.getDataBroker().getFromResourceDirAsUrl("/de/german.dict")); final DictionaryLookup dl = new DictionaryLookup(dictionary); for (WordData wd : dl) { if (wd.getTag() == null || wd.getTag().length() == 0) { System.err.println("**** Warning: the word " + wd.getWord() + "/" + wd.getStem() + " lacks a POS tag in the dictionary."); } } } }
lgpl-2.1
mbatchelor/pentaho-reporting
engine/core/src/test/java/org/pentaho/reporting/engine/classic/core/modules/gui/base/actions/GoToLastPageActionPluginTest.java
3712
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2000 - 2017 Hitachi Vantara, Simba Management Limited and Contributors... All rights reserved. */ package org.pentaho.reporting.engine.classic.core.modules.gui.base.actions; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import org.pentaho.reporting.engine.classic.core.modules.gui.base.PreviewPane; public class GoToLastPageActionPluginTest extends GoToActionPluginTest { private GoToLastPageActionPlugin plugin; @Before public void setUp() { super.setUp(); plugin = new GoToLastPageActionPlugin(); } @Override protected String getSmallIconKey() { return "action.lastpage.small-icon"; } @Override protected String getNameValue() { return "test lastpage name"; } @Override protected String getDescriptionValue() { return "test lastpage description"; } @Override protected String getLargeIconKey() { return "action.lastpage.icon"; } @Override protected String getExpectedPrefix() { return "org.pentaho.reporting.engine.classic.core.modules.gui.base.go-to-last."; } @Override protected String getPrefix() { return getPlugin().getConfigurationPrefix(); } @Override protected GoToLastPageActionPlugin getPlugin() { return plugin; } @Test public void testRevalidate() { doReturn( false ).when( source ).isPaginated(); boolean result = plugin.initialize( context ); assertThat( result, is( equalTo( true ) ) ); assertThat( plugin.isEnabled(), is( equalTo( false ) ) ); doReturn( true ).when( source ).isPaginated(); doReturn( 0 ).when( source ).getPageNumber(); result = plugin.initialize( context ); assertThat( result, is( equalTo( true ) ) ); assertThat( plugin.isEnabled(), is( equalTo( false ) ) ); doReturn( true ).when( source ).isPaginated(); doReturn( 5 ).when( source ).getPageNumber(); doReturn( 5 ).when( source ).getNumberOfPages(); result = plugin.initialize( context ); assertThat( result, is( equalTo( true ) ) ); assertThat( plugin.isEnabled(), is( equalTo( false ) ) ); doReturn( true ).when( source ).isPaginated(); doReturn( 5 ).when( source ).getPageNumber(); doReturn( 15 ).when( source ).getNumberOfPages(); result = plugin.initialize( context ); assertThat( result, is( equalTo( true ) ) ); assertThat( plugin.isEnabled(), is( equalTo( true ) ) ); } @Test public void testConfigure() { PreviewPane reportPane = mock( PreviewPane.class ); doReturn( 2 ).when( reportPane ).getNumberOfPages(); boolean result = plugin.configure( reportPane ); verify( reportPane ).setPageNumber( 2 ); assertThat( result, is( equalTo( true ) ) ); } }
lgpl-2.1
Copix/Copix3
project/modules/public/devel/cms/cms/actiongroup/cmspageworkflow.actiongroup.php
26274
<?php /** * @package cms * @author Croes Gérald * @copyright 2001-2006 CopixTeam * @link http://copix.org * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file */ /** * @ignore */ CopixClassesFactory::fileInclude ('cms|ServicesCMSPage'); /** * ActionGroupCMSPageWorkflow * @package cms */ class ActionGroupCMSPageWorkflow extends CopixActionGroup { /** * Sends the given page to the trash. * we can only sends item in the trash if it's our document and we still have * the write right on the given heading, or if we're a moderator of the heading * @param $this->vars['id'] the id of the page we wants to sends in the trash. */ function doTrash () { CopixClassesFactory::fileInclude ('cms|CMSAuth'); $draft = ServicesCMSPage::getDraft ($this->vars['id']); //cannot find the given draft if ($draft === null){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } //check if we *can* do it if (CopixUserProfile::getLogin () == $draft->author_cmsp){ //our document, we just have to still have write enabled here. if (! CMSAuth::canWrite($draft->id_head)){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotSendToTrash'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } }else{ //not our document, we have to be a moderator. if (! CMSAuth::canModerate ($draft->id_head)){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotSendToTrash'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setTrash ($this->vars['id'], $statuscomment); if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * Definitely deletes the document. * We can only deletes documents that are in the trash. * We can only deletes document we wrote, in a heading we still have write rights. * If we're not the author of the document, we have to be a moderator. * @param int $this->vars['id'] */ function doDelete () { $draft = ServicesCMSPage::getDraft ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); //cannot find the given draft if ($draft === null) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin'))); } if ($draft->status_cmsp != $workflow->getTrash ()){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotDeleteNonTrash'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } //check if we *can* do it if (CopixUserProfile::getLogin () == $draft->author_cmsp){ //our document, we just have to still have write enabled here. if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_WRITE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotDelete'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } }else{ //not our document, we have to be a moderator. if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_MODERATE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotDelete'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setDelete ($this->vars['id'],$statuscomment); if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * We can only restore documents that are in the trash. * We can only restores documents we're the author of, in heading we still have write permissions on * If we're not the author of the document, we have to be a moderator of the heading. * @param int $this->vars['id'] the page id */ function doRestore () { $draft = ServicesCMSPage::getDraft ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); //cannot find the given draft if ($draft === null) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } if (($draft->status_cmsp != $workflow->getTrash ()) && ($draft->status_cmsp != $workflow->getRefuse())){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotRestoreNonTrash'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } //check if we *can* do it if (CopixUserProfile::getLogin () == $draft->author_cmsp) { //our document, we just have to still have write enabled here. if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_WRITE) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotRestore'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } }else{ //not our document, we have to be a moderator. if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_MODERATE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotRestore'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setCreate ($this->vars['id'],$statuscomment); return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } /** * We can propose a document only if we have write permissions on the given heading, and if we are the author of it. * We can propose documents only if they are in the created status (not in the trash) */ function doPropose () { $draft = ServicesCMSPage::getDraft ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); //cannot find the given draft if ($draft === null) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } //if ($draft->status_cmsp != $workflow->getCreate ()){ if ($draft->status_cmsp != $workflow->getDraft ()){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotProposeNonDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } //check if we *can* do it if (CopixUserProfile::getLogin () == $draft->author_cmsp) { //our document, we just have to still have write enabled here. if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_WRITE) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotPropose'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } } else { //not our document, we have to be a moderator. if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_MODERATE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotPropose'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } } if (CopixConfig::get ('cms|easyWorkflow') == 1){ $this->doBest (); return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setPropose ($this->vars['id'],$statuscomment); return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } /** * we can only validate documents that are proposed. * we can only validate if we have valid rights on the headings. */ function doValid (){ $draft = ServicesCMSPage::getDraft ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); //cannot find the given draft if ($draft === null) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } if ($draft->status_cmsp != $workflow->getPropose ()){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotValidNonPropose'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } //check if we *can* do it if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_VALID) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotValid'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } if (CopixConfig::get ('cms|easyWorkflow') == 1){ return $this->doBest (); } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setValid ($this->vars['id'],$statuscomment); if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * Publish the given document. */ function doPublish (){ $draft = ServicesCMSPage::getDraft ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); //cannot find the given draft if ($draft === null) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } if ($draft->status_cmsp != $workflow->getValid ()){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotPublishNonValid'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } //check if we *can* do it if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_PUBLISH) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotPublish'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setPublish ($this->vars['id'], $statuscomment); if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * Refuse a given document. */ function doRefuse (){ $draft = ServicesCMSPage::getDraft ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); //cannot find the given draft if ($draft === null) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } if ($draft->status_cmsp != $workflow->getPropose () && $draft->status_cmsp != $workflow->getValid ()){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotValidNonPropose'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } //check if we *can* do it if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_VALID) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotValid'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setRefuse ($this->vars['id'],$statuscomment); if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * gets a refused document back in the drafts. * we can only restore drafts we're the author of, or if we are a moderator of the given heading. */ function doDraft () { $draft = ServicesCMSPage::getDraft ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); //cannot find the given draft if ($draft === null) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } if ($draft->status_cmsp != $workflow->getRefuse ()){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotValidNonPropose'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } //check if we *can* do it if (CopixUserProfile::getLogin() == $draft->author_cmsp){ //we're the author, we can do it if we still have the rights to write in the headings if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_WRITE) { return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotDraftBack'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } }else{ //we're not the author, we then have to be a moderator. if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)) < PROFILE_CCV_MODERATE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotDraftBack'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$draft->id_head)))); } } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$this->vars['id']]) ? $this->vars['statuscomment_cmsp_'.$this->vars['id']] : null; ServicesCMSPage::setRefuse ($this->vars['id'],$statuscomment); if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * Best status, depends on profile. * we'll check if we can at least write here. */ function doBest ($params=array()){ $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $id = isset($params['id']) ? $params['id'] : $this->vars['id']; $draft = ServicesCMSPage::getDraft ($id); if ($draft === null){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } $value = CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)); if ($value < PROFILE_CCV_WRITE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.notAnAuthorizedHead'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$id]) ? $this->vars['statuscomment_cmsp_'.$id] : null; $method = 'setPropose'; if ($value >= PROFILE_CCV_VALID){ $method = 'setValid'; } if ($value >= PROFILE_CCV_PUBLISH){ $method = 'setPublish'; } ServicesCMSPage::$method ($id,$statuscomment); if (isset($params->urlRedirect)) { return new CopixActionReturn (CopixActionReturn::REDIRECT, $params->urlRedirect); } if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * doNext * nextStatus */ function doNext ($params=array()) { $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); $id = isset($params['id']) ? $params['id'] : $this->vars['id']; $draft = ServicesCMSPage::getDraft ($id); if ($draft === null){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } $value = CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($draft->id_head)); if ($value < PROFILE_CCV_WRITE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.notAnAuthorizedHead'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } $statuscomment = isset($this->vars['statuscomment_cmsp_'.$id]) ? $this->vars['statuscomment_cmsp_'.$id] : null; $workflow = CopixClassesFactory::getInstanceOf ('copixheadings|workflow'); $nextid_head = $workflow->getNext($draft->id_head,'cms',$draft->status_cmsp); //print_r($draft);exit; //echo $draft->status_cmsp; //echo $nextid_head;exit; $method=null; switch ($nextid_head) { case $workflow->getPropose() : $method = 'setPropose'; break; case $workflow->getValid() : $method = 'setValid'; break; case $workflow->getPublish() : $method = 'setPublish'; break; } if ($method) { ServicesCMSPage::$method ($id,$statuscomment); } if (isset($params->urlRedirect)) { return new CopixActionReturn (CopixActionReturn::REDIRECT, $params->urlRedirect); } if (isset($this->vars['back']) && strlen($this->vars['back']) > 0) {//Redirect with a special url return new CopixActionReturn (CopixActionReturn::REDIRECT, $this->vars['back']); }else{ return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$draft->id_head))); } } /** * Asks for deletion of an online page */ function doDeleteOnline () { $page = ServicesCMSPage::getOnline ($this->vars['id']); $servicesHeading = CopixClassesFactory::getInstanceOf ('copixheadings|CopixProfileForHeadingServices'); //cannot find the given draft if ($page === null){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotFindDraft'), 'back'=>CopixUrl::get ('copixheadings|admin|'))); } //Confirmation screen ? if (!isset ($this->vars['confirm'])){ return CopixActionGroup::process ('genericTools|Messages::getConfirm', array ('title'=>CopixI18N::get ('admin.titlePage.confirmDelete'), 'message'=>CopixI18N::get ('admin.message.confirmDelete'), 'confirm'=>CopixUrl::get ('cms|workflow|deleteOnline', array ('confirm'=>1, 'id'=>$this->vars['id'])), 'cancel'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$page->id_head,'browse'=>'cms')))); } if (CopixUserProfile::valueOf ('cms', $servicesHeading->getPath ($page->id_head)) < PROFILE_CCV_MODERATE){ return CopixActionGroup::process ('genericTools|Messages::getError', array ('message'=>CopixI18N::get ('admin.error.cannotDelete'), 'back'=>CopixUrl::get ('copixheadings|admin|', array ('id_head'=>$page->id_head)))); } ServicesCMSPage::deleteOnline ($this->vars['id']); return new CopixActionReturn (CopixActionReturn::REDIRECT, CopixUrl::get ('copixheadings|admin|', array ('browse'=>'cms', 'id_head'=>$page->id_head))); } } ?>
lgpl-2.1
Pondidum/Conifer
Conifer/Extensions.cs
248
using System.Collections.Generic; namespace Conifer { public static class Extensions { public static void AddRange<T>(this ICollection<T> self, IEnumerable<T> items) { foreach (var item in items) { self.Add(item); } } } }
lgpl-2.1
zimbatm/nix
src/libstore/s3-binary-cache-store.cc
15005
#if ENABLE_S3 #include "s3.hh" #include "s3-binary-cache-store.hh" #include "nar-info.hh" #include "nar-info-disk-cache.hh" #include "globals.hh" #include "compression.hh" #include "download.hh" #include "istringstream_nocopy.hh" #include <aws/core/Aws.h> #include <aws/core/VersionConfig.h> #include <aws/core/auth/AWSCredentialsProvider.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/client/DefaultRetryStrategy.h> #include <aws/core/utils/logging/FormattedLogSystem.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/core/utils/threading/Executor.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/GetObjectRequest.h> #include <aws/s3/model/HeadObjectRequest.h> #include <aws/s3/model/ListObjectsRequest.h> #include <aws/s3/model/PutObjectRequest.h> #include <aws/transfer/TransferManager.h> using namespace Aws::Transfer; namespace nix { struct S3Error : public Error { Aws::S3::S3Errors err; S3Error(Aws::S3::S3Errors err, const FormatOrString & fs) : Error(fs), err(err) { }; }; /* Helper: given an Outcome<R, E>, return R in case of success, or throw an exception in case of an error. */ template<typename R, typename E> R && checkAws(const FormatOrString & fs, Aws::Utils::Outcome<R, E> && outcome) { if (!outcome.IsSuccess()) throw S3Error( outcome.GetError().GetErrorType(), fs.s + ": " + outcome.GetError().GetMessage()); return outcome.GetResultWithOwnership(); } class AwsLogger : public Aws::Utils::Logging::FormattedLogSystem { using Aws::Utils::Logging::FormattedLogSystem::FormattedLogSystem; void ProcessFormattedStatement(Aws::String && statement) override { debug("AWS: %s", chomp(statement)); } }; static void initAWS() { static std::once_flag flag; std::call_once(flag, []() { Aws::SDKOptions options; /* We install our own OpenSSL locking function (see shared.cc), so don't let aws-sdk-cpp override it. */ options.cryptoOptions.initAndCleanupOpenSSL = false; if (verbosity >= lvlDebug) { options.loggingOptions.logLevel = verbosity == lvlDebug ? Aws::Utils::Logging::LogLevel::Debug : Aws::Utils::Logging::LogLevel::Trace; options.loggingOptions.logger_create_fn = [options]() { return std::make_shared<AwsLogger>(options.loggingOptions.logLevel); }; } Aws::InitAPI(options); }); } S3Helper::S3Helper(const string & profile, const string & region, const string & scheme, const string & endpoint) : config(makeConfig(region, scheme, endpoint)) , client(make_ref<Aws::S3::S3Client>( profile == "" ? std::dynamic_pointer_cast<Aws::Auth::AWSCredentialsProvider>( std::make_shared<Aws::Auth::DefaultAWSCredentialsProviderChain>()) : std::dynamic_pointer_cast<Aws::Auth::AWSCredentialsProvider>( std::make_shared<Aws::Auth::ProfileConfigFileAWSCredentialsProvider>(profile.c_str())), *config, // FIXME: https://github.com/aws/aws-sdk-cpp/issues/759 #if AWS_VERSION_MAJOR == 1 && AWS_VERSION_MINOR < 3 false, #else Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, #endif endpoint.empty())) { } /* Log AWS retries. */ class RetryStrategy : public Aws::Client::DefaultRetryStrategy { bool ShouldRetry(const Aws::Client::AWSError<Aws::Client::CoreErrors>& error, long attemptedRetries) const override { auto retry = Aws::Client::DefaultRetryStrategy::ShouldRetry(error, attemptedRetries); if (retry) printError("AWS error '%s' (%s), will retry in %d ms", error.GetExceptionName(), error.GetMessage(), CalculateDelayBeforeNextRetry(error, attemptedRetries)); return retry; } }; ref<Aws::Client::ClientConfiguration> S3Helper::makeConfig(const string & region, const string & scheme, const string & endpoint) { initAWS(); auto res = make_ref<Aws::Client::ClientConfiguration>(); res->region = region; if (!scheme.empty()) { res->scheme = Aws::Http::SchemeMapper::FromString(scheme.c_str()); } if (!endpoint.empty()) { res->endpointOverride = endpoint; } res->requestTimeoutMs = 600 * 1000; res->retryStrategy = std::make_shared<RetryStrategy>(); res->caFile = settings.caFile; return res; } S3Helper::DownloadResult S3Helper::getObject( const std::string & bucketName, const std::string & key) { debug("fetching 's3://%s/%s'...", bucketName, key); auto request = Aws::S3::Model::GetObjectRequest() .WithBucket(bucketName) .WithKey(key); request.SetResponseStreamFactory([&]() { return Aws::New<std::stringstream>("STRINGSTREAM"); }); DownloadResult res; auto now1 = std::chrono::steady_clock::now(); try { auto result = checkAws(fmt("AWS error fetching '%s'", key), client->GetObject(request)); res.data = decompress(result.GetContentEncoding(), dynamic_cast<std::stringstream &>(result.GetBody()).str()); } catch (S3Error & e) { if (e.err != Aws::S3::S3Errors::NO_SUCH_KEY) throw; } auto now2 = std::chrono::steady_clock::now(); res.durationMs = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count(); return res; } struct S3BinaryCacheStoreImpl : public S3BinaryCacheStore { const Setting<std::string> profile{this, "", "profile", "The name of the AWS configuration profile to use."}; const Setting<std::string> region{this, Aws::Region::US_EAST_1, "region", {"aws-region"}}; const Setting<std::string> scheme{this, "", "scheme", "The scheme to use for S3 requests, https by default."}; const Setting<std::string> endpoint{this, "", "endpoint", "An optional override of the endpoint to use when talking to S3."}; const Setting<std::string> narinfoCompression{this, "", "narinfo-compression", "compression method for .narinfo files"}; const Setting<std::string> lsCompression{this, "", "ls-compression", "compression method for .ls files"}; const Setting<std::string> logCompression{this, "", "log-compression", "compression method for log/* files"}; const Setting<bool> multipartUpload{ this, false, "multipart-upload", "whether to use multi-part uploads"}; const Setting<uint64_t> bufferSize{ this, 5 * 1024 * 1024, "buffer-size", "size (in bytes) of each part in multi-part uploads"}; std::string bucketName; Stats stats; S3Helper s3Helper; S3BinaryCacheStoreImpl( const Params & params, const std::string & bucketName) : S3BinaryCacheStore(params) , bucketName(bucketName) , s3Helper(profile, region, scheme, endpoint) { diskCache = getNarInfoDiskCache(); } std::string getUri() override { return "s3://" + bucketName; } void init() override { if (!diskCache->cacheExists(getUri(), wantMassQuery_, priority)) { BinaryCacheStore::init(); diskCache->createCache(getUri(), storeDir, wantMassQuery_, priority); } } const Stats & getS3Stats() override { return stats; } /* This is a specialisation of isValidPath() that optimistically fetches the .narinfo file, rather than first checking for its existence via a HEAD request. Since .narinfos are small, doing a GET is unlikely to be slower than HEAD. */ bool isValidPathUncached(const Path & storePath) override { try { queryPathInfo(storePath); return true; } catch (InvalidPath & e) { return false; } } bool fileExists(const std::string & path) override { stats.head++; auto res = s3Helper.client->HeadObject( Aws::S3::Model::HeadObjectRequest() .WithBucket(bucketName) .WithKey(path)); if (!res.IsSuccess()) { auto & error = res.GetError(); if (error.GetErrorType() == Aws::S3::S3Errors::RESOURCE_NOT_FOUND || error.GetErrorType() == Aws::S3::S3Errors::NO_SUCH_KEY // If bucket listing is disabled, 404s turn into 403s || error.GetErrorType() == Aws::S3::S3Errors::ACCESS_DENIED) return false; throw Error(format("AWS error fetching '%s': %s") % path % error.GetMessage()); } return true; } std::shared_ptr<TransferManager> transferManager; std::once_flag transferManagerCreated; void uploadFile(const std::string & path, const std::string & data, const std::string & mimeType, const std::string & contentEncoding) { auto stream = std::make_shared<istringstream_nocopy>(data); auto maxThreads = std::thread::hardware_concurrency(); static std::shared_ptr<Aws::Utils::Threading::PooledThreadExecutor> executor = std::make_shared<Aws::Utils::Threading::PooledThreadExecutor>(maxThreads); std::call_once(transferManagerCreated, [&]() { if (multipartUpload) { TransferManagerConfiguration transferConfig(executor.get()); transferConfig.s3Client = s3Helper.client; transferConfig.bufferSize = bufferSize; transferConfig.uploadProgressCallback = [](const TransferManager *transferManager, const std::shared_ptr<const TransferHandle> &transferHandle) { //FIXME: find a way to properly abort the multipart upload. //checkInterrupt(); debug("upload progress ('%s'): '%d' of '%d' bytes", transferHandle->GetKey(), transferHandle->GetBytesTransferred(), transferHandle->GetBytesTotalSize()); }; transferManager = TransferManager::Create(transferConfig); } }); auto now1 = std::chrono::steady_clock::now(); if (transferManager) { if (contentEncoding != "") throw Error("setting a content encoding is not supported with S3 multi-part uploads"); std::shared_ptr<TransferHandle> transferHandle = transferManager->UploadFile( stream, bucketName, path, mimeType, Aws::Map<Aws::String, Aws::String>(), nullptr /*, contentEncoding */); transferHandle->WaitUntilFinished(); if (transferHandle->GetStatus() == TransferStatus::FAILED) throw Error("AWS error: failed to upload 's3://%s/%s': %s", bucketName, path, transferHandle->GetLastError().GetMessage()); if (transferHandle->GetStatus() != TransferStatus::COMPLETED) throw Error("AWS error: transfer status of 's3://%s/%s' in unexpected state", bucketName, path); } else { auto request = Aws::S3::Model::PutObjectRequest() .WithBucket(bucketName) .WithKey(path); request.SetContentType(mimeType); if (contentEncoding != "") request.SetContentEncoding(contentEncoding); auto stream = std::make_shared<istringstream_nocopy>(data); request.SetBody(stream); auto result = checkAws(fmt("AWS error uploading '%s'", path), s3Helper.client->PutObject(request)); } auto now2 = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1) .count(); printInfo(format("uploaded 's3://%1%/%2%' (%3% bytes) in %4% ms") % bucketName % path % data.size() % duration); stats.putTimeMs += duration; stats.putBytes += data.size(); stats.put++; } void upsertFile(const std::string & path, const std::string & data, const std::string & mimeType) override { if (narinfoCompression != "" && hasSuffix(path, ".narinfo")) uploadFile(path, *compress(narinfoCompression, data), mimeType, narinfoCompression); else if (lsCompression != "" && hasSuffix(path, ".ls")) uploadFile(path, *compress(lsCompression, data), mimeType, lsCompression); else if (logCompression != "" && hasPrefix(path, "log/")) uploadFile(path, *compress(logCompression, data), mimeType, logCompression); else uploadFile(path, data, mimeType, ""); } void getFile(const std::string & path, Sink & sink) override { stats.get++; // FIXME: stream output to sink. auto res = s3Helper.getObject(bucketName, path); stats.getBytes += res.data ? res.data->size() : 0; stats.getTimeMs += res.durationMs; if (res.data) { printTalkative("downloaded 's3://%s/%s' (%d bytes) in %d ms", bucketName, path, res.data->size(), res.durationMs); sink((unsigned char *) res.data->data(), res.data->size()); } else throw NoSuchBinaryCacheFile("file '%s' does not exist in binary cache '%s'", path, getUri()); } PathSet queryAllValidPaths() override { PathSet paths; std::string marker; do { debug(format("listing bucket 's3://%s' from key '%s'...") % bucketName % marker); auto res = checkAws(format("AWS error listing bucket '%s'") % bucketName, s3Helper.client->ListObjects( Aws::S3::Model::ListObjectsRequest() .WithBucket(bucketName) .WithDelimiter("/") .WithMarker(marker))); auto & contents = res.GetContents(); debug(format("got %d keys, next marker '%s'") % contents.size() % res.GetNextMarker()); for (auto object : contents) { auto & key = object.GetKey(); if (key.size() != 40 || !hasSuffix(key, ".narinfo")) continue; paths.insert(storeDir + "/" + key.substr(0, key.size() - 8)); } marker = res.GetNextMarker(); } while (!marker.empty()); return paths; } }; static RegisterStoreImplementation regStore([]( const std::string & uri, const Store::Params & params) -> std::shared_ptr<Store> { if (std::string(uri, 0, 5) != "s3://") return 0; auto store = std::make_shared<S3BinaryCacheStoreImpl>(params, std::string(uri, 5)); store->init(); return store; }); } #endif
lgpl-2.1
oregional/tiki
lib/wizard/pages/upgrade_novice_admin_assistance.php
925
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ require_once('lib/wizard/wizard.php'); /** * The Wizard's language handler */ class UpgradeWizardNoviceAdminAssistance extends Wizard { function pageTitle () { return tra('Novice Admin Assistance'); } function isEditable () { return true; } function onSetupPage ($homepageUrl) { // Run the parent first parent::onSetupPage($homepageUrl); $showPage = true; return $showPage; } function getTemplate() { $wizardTemplate = 'wizard/upgrade_novice_admin_assistance.tpl'; return $wizardTemplate; } function onContinue ($homepageUrl) { // Run the parent first parent::onContinue($homepageUrl); } }
lgpl-2.1
KarimLUCCIN/Cudafy
Cudafy.Translator/ICSharpCode.NRefactory/TypeSystem/IConversions.cs
513
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under MIT X11 license (for details please see \doc\license.txt) using System; namespace ICSharpCode.NRefactory.TypeSystem { /// <summary> /// Interface used to check whether types are convertible. /// </summary> public interface IConversions { bool ImplicitConversion(IType fromType, IType toType); bool ImplicitReferenceConversion(IType fromType, IType toType); } }
lgpl-2.1
akquinet/needle
src/main/java/de/akquinet/jbosscc/needle/db/configuration/PersistenceConfigurationFactory.java
3681
package de.akquinet.jbosscc.needle.db.configuration; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * Factory to create and access the configured persistence context. */ public final class PersistenceConfigurationFactory implements PersistenceConfiguration { private static final Map<PersistenceConfigurationFactory, PersistenceConfiguration> PERSISTENCE_MAP = new HashMap<PersistenceConfigurationFactory, PersistenceConfiguration>(); private String persistenceUnit; private Class<?>[] cfgClazzes; public PersistenceConfigurationFactory(final String persistenceUnit) { super(); this.persistenceUnit = persistenceUnit; } public PersistenceConfigurationFactory(final Class<?>[] cfgClazzes) { super(); this.cfgClazzes = Arrays.copyOf(cfgClazzes, cfgClazzes.length); } private PersistenceConfiguration getPersistenceConfiguration() { return getPersistenceConfiguration(this); } String getPersistenceUnit() { return persistenceUnit; } Class<?>[] getCfgClazzes() { return cfgClazzes; } /** * Returns the {@link EntityManager} instance which is associated with the * configured persistence context. * * @return {@link EntityManager} */ @Override public EntityManager getEntityManager() { return getPersistenceConfiguration().getEntityManager(); } /** * Returns the {@link EntityManagerFactory}. * * @return {@link EntityManagerFactory} */ @Override public EntityManagerFactory getEntityManagerFactory() { return getPersistenceConfiguration().getEntityManagerFactory(); } private static PersistenceConfiguration getPersistenceConfiguration( final PersistenceConfigurationFactory configuration) { PersistenceConfiguration result = PERSISTENCE_MAP.get(configuration); if (result == null) { result = createPersistenceConfiguration(configuration); PERSISTENCE_MAP.put(configuration, result); } return result; } private static PersistenceConfiguration createPersistenceConfiguration( final PersistenceConfigurationFactory configuration) { if (configuration.getPersistenceUnit() != null) { return new PersistenceUnitConfiguration(configuration.getPersistenceUnit()); } else if (configuration.getCfgClazzes() != null) { return new EJB3Configuration(configuration.getCfgClazzes()); } return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(cfgClazzes); result = prime * result + ((persistenceUnit == null) ? 0 : persistenceUnit.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PersistenceConfigurationFactory other = (PersistenceConfigurationFactory) obj; if (!Arrays.equals(cfgClazzes, other.cfgClazzes)) { return false; } if (persistenceUnit == null) { if (other.persistenceUnit != null) { return false; } } else if (!persistenceUnit.equals(other.persistenceUnit)) { return false; } return true; } }
lgpl-2.1
EgorZhuk/pentaho-reporting
libraries/libcss/src/main/java/org/pentaho/reporting/libraries/css/keys/color/ColorStyleKeys.java
2077
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.reporting.libraries.css.keys.color; import org.pentaho.reporting.libraries.css.model.StyleKey; import org.pentaho.reporting.libraries.css.model.StyleKeyRegistry; /** * Creation-Date: 30.10.2005, 18:47:30 * * @author Thomas Morgner */ public final class ColorStyleKeys { public static final StyleKey COLOR = StyleKeyRegistry.getRegistry().createKey ( "color", false, true, StyleKey.ALWAYS ); /** * Not sure whether we can implement this one. It is a post-processing operation, and may or may not be supported by * the output target. */ public static final StyleKey OPACITY = StyleKeyRegistry.getRegistry().createKey ( "opacity", false, false, StyleKey.ALWAYS ); /** * For now, we do not care about color profiles. This might have to do with me being clueless about the topic, but * also with the cost vs. usefullness calculation involved. */ public static final StyleKey COLOR_PROFILE = StyleKeyRegistry.getRegistry().createKey ( "color-profile", false, true, StyleKey.ALWAYS ); public static final StyleKey RENDERING_INTENT = StyleKeyRegistry.getRegistry().createKey ( "rendering-intent", false, true, StyleKey.ALWAYS ); private ColorStyleKeys() { } }
lgpl-2.1
insuusvenerati/Smash-Mod
src/main/java/com/stiforr/smashmod/items/SmashSpawner.java
4028
package com.stiforr.smashmod.items; import com.stiforr.smashmod.creativetab.CreativeTabSmash; import com.stiforr.smashmod.entity.EntitySmash; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import java.util.List; public class SmashSpawner extends Item { public SmashSpawner(){ setUnlocalizedName("smashSpawner"); setCreativeTab(CreativeTabSmash.Smash_Tab); } @Override public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { float f = 1.0F; float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; double d0 = player.prevPosX + (player.posX - player.prevPosX) * f; double d1 = player.prevPosY + (player.posY - player.prevPosY) * f + 1.62D - player.yOffset; double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * f; Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float)Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float)Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = 5.0D; Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); MovingObjectPosition movingobjectposition = world.rayTraceBlocks(vec3, vec31, true); if (movingobjectposition == null) { return itemStack; } else { Vec3 vec32 = player.getLook(f); boolean flag = false; float f9 = 1.0F; List list = world.getEntitiesWithinAABBExcludingEntity(player, player.boundingBox.addCoord(vec32.xCoord * d3, vec32.yCoord * d3, vec32.zCoord * d3).expand(f9, f9, f9)); int i; for (i = 0; i < list.size(); ++i) { Entity entity = (Entity)list.get(i); if (entity.canBeCollidedWith()) { float f10 = entity.getCollisionBorderSize(); AxisAlignedBB axisalignedbb = entity.boundingBox.expand(f10, f10, f10); if (axisalignedbb.isVecInside(vec3)) { flag = true; } } } if (flag) { return itemStack; } else { if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { i = movingobjectposition.blockX; int j = movingobjectposition.blockY; int k = movingobjectposition.blockZ; if (world.getBlock(i, j, k) == Blocks.snow_layer) { --j; } EntitySmash jeep = new EntitySmash(world, i + 0.5, j + 1.0F,k + 0.5); if (!world.getCollidingBoundingBoxes(jeep, jeep.boundingBox.expand(-0.1D, -0.1D, -0.1D)).isEmpty()) { return itemStack; } if (!world.isRemote) { world.spawnEntityInWorld(jeep); } if (!player.capabilities.isCreativeMode) { --itemStack.stackSize; } } return itemStack; } } } }
lgpl-2.1
carlos22/SmartSoftCorba
src/components/SmartXsensIMUMTiServer/src/gen/SmartXsensIMUMTiServer.cc
3998
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain Version 0.10.4 // The SmartSoft Toolchain has been developed by: // // ZAFH Servicerobotic Ulm // Christian Schlegel (schlegel@hs-ulm.de) // University of Applied Sciences // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // smart-robotics.sourceforge.net // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #include "SmartXsensIMUMTiServer.hh" // constructor SmartXsensIMUMTiServer::SmartXsensIMUMTiServer() { std::cout << "constructor of SmartXsensIMUMTiServer\n"; ini.component.name = "SmartXsensIMUMTiServer"; ini.pushTimedDataServer.serviceName = "imuData"; ini.pushTimedDataServer.cycle = 0.008333; ini.xsens.port = "/dev/ttyUSB0"; ini.xsens.verbose = true; } void SmartXsensIMUMTiServer::init(int argc, char *argv[]) { try { loadParameter(argc, argv); component = new CHS::SmartComponent(ini.component.name, argc, argv); std::cout << "Component SmartXsensIMUMTiServer is named " << ini.component.name << "." << std::endl; // create ports pushTimedDataServer = new CHS::PushTimedServer< CommBasicObjects::CommIMUData>(component, ini.pushTimedDataServer.serviceName, pushTimedDataHandler, ini.pushTimedDataServer.cycle); // add client port to wiring slave } catch (const CORBA::Exception &) { std::cerr << "Uncaught CORBA exception" << std::endl; } catch (...) { std::cerr << "Uncaught exception" << std::endl; } } // run the component void SmartXsensIMUMTiServer::run() { compHandler.onStartup(); component->run(); delete component; } void SmartXsensIMUMTiServer::loadParameter(int argc, char *argv[]) { /* Parameters can be specified via command line -filename=<filename> With this parameter present: - The component will look for the file in the current working directory, a path relative to the current directory or any absolute path - The component will use the default values if the file cannot be found With this parameter absent: - <Name of Component>.ini will be read from current working directory, if found there - $SMART_ROOT/etc/<Name of Component>.ini will be read otherwise - Default values will be used if neither found in working directory or /etc */ CHS::SmartParameter parameter; // load parameters try { // check if paramfile is given as argument bool paramFile = false; std::string str; for (int i = 0; i < argc; i++) { str = argv[i]; if (str.find("filename") != std::string::npos) paramFile = true; } // if paramfile is given as argument if (paramFile == true) { std::cout << "load parameter file from argv \n"; parameter.addFile(argc, argv, "filename", false); } // else load standard paramfile else { std::cout << "load SmartXsensIMUMTiServer.ini parameter file\n"; parameter.addFile("SmartXsensIMUMTiServer.ini"); } // than add command line arguments to allow overwriting of parameters // from file parameter.addCommandLine("", argc, argv); // print all known parameters parameter.print(); // TODO remove this // load parameter parameter.getString("component", "name", ini.component.name); parameter.getString("pushTimedDataServer", "serviceName", ini.pushTimedDataServer.serviceName); parameter.getDouble("pushTimedDataServer", "cycle", ini.pushTimedDataServer.cycle); parameter.getString("xsens", "port", ini.xsens.port); parameter.getTruthValue("xsens", "verbose", ini.xsens.verbose); } catch (const CORBA::Exception &) { std::cerr << "Uncaught CORBA exception" << std::endl; } catch (const CHS::ParameterError & e) { std::cerr << "Exception from parameter handling: " << e << std::endl; } catch (...) { std::cerr << "Uncaught exception" << std::endl; } }
lgpl-2.1
peastman/cbang
src/cbang/http/ScriptedWebHandler.cpp
3620
/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2015, Cauldron Development LLC Copyright (c) 2003-2015, Stanford University All rights reserved. The C! 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. The C! 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 C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "ScriptedWebHandler.h" #include "Context.h" #include "Connection.h" #include "Response.h" #include "Request.h" #include "FileWebPageHandler.h" #include "ScriptWebPageHandler.h" #include "ScriptedWebContext.h" #include <cbang/Info.h> #include <cbang/SStream.h> #include <cbang/config/Options.h> #include <cbang/log/Logger.h> #include <cbang/xml/XMLWriter.h> #include <cbang/script/MemberFunctor.h> using namespace std; using namespace cb; using namespace cb::HTTP; using namespace cb::Script; ScriptedWebHandler::ScriptedWebHandler(Options &options, const string &match, Script::Handler *parent, hasFeature_t hasFeature) : WebHandler(options, match, hasFeature), Environment("Web Handler", parent), options(options) { options.pushCategory("Web Server"); if (hasFeature(FEATURE_FS_DYNAMIC)) options.add("web-dynamic", "Path to dynamic web pages. Empty to disable " "filesystem access for dynamic pages."); options.popCategory(); // Dynamic page functions #define MF_ADD(name, func, min, max) \ add(new Script::MemberFunctor<ScriptedWebHandler> \ (name, this, &ScriptedWebHandler::func, min, max)) if (hasFeature(FEATURE_INFO)) MF_ADD("info", evalInfo, 0, 2); } void ScriptedWebHandler::init() { WebHandler::init(); if (hasFeature(FEATURE_FS_DYNAMIC) && options["web-dynamic"].hasValue()) addHandler(new ScriptWebPageHandler (new FileWebPageHandler(options["web-dynamic"]))); } void ScriptedWebHandler::evalInfo(const Script::Context &ctx) { Info &info = Info::instance(); switch (ctx.args.size()) { case 1: { XMLWriter writer(ctx.stream); info.write(writer); break; } case 2: ctx.args.invalidNum(); break; case 3: ctx.stream << info.get(ctx.args[1], ctx.args[2]); break; } } void ScriptedWebHandler::evalOption(const Script::Context &ctx) { ctx.stream << options[ctx.args[1]]; } HTTP::Context *ScriptedWebHandler::createContext(Connection *con) { return new ScriptedWebContext(*this, *con); }
lgpl-2.1
jbossws/jbossws-cxf
modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/jbws2257/jaxws/SayHelloResponse.java
1835
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.ws.jaxws.jbws2257.jaxws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "sayHelloResponse", namespace = "http://www.jboss.org/jbossws/ws-extensions/wsaddressing") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "sayHelloResponse", namespace = "http://www.jboss.org/jbossws/ws-extensions/wsaddressing") public class SayHelloResponse { @XmlElement(name = "return", namespace = "") private String _return; public String getReturn() { return this._return; } public void setReturn(String _return) { this._return = _return; } }
lgpl-2.1
holmesian/xinhu-project
config/version.php
69
<?php //信呼OA系统,信呼OA云平台,平台 return '1.8.1';
lgpl-2.1
opensagres/xdocreport.eclipse
rap/org.eclipse.gef/src/org/eclipse/gef/commands/Command.java
3825
/******************************************************************************* * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.gef.commands; /** * An Abstract implementation of {@link Command}. * * @author hudsonr * @since 2.0 */ public abstract class Command { private String label; private String debugLabel; /** * Constructs a Command with no label. */ public Command() { } /** * Constructs a Command with the specified label. * * @param label * the Command's label */ public Command(String label) { setLabel(label); } /** * @return <code>true</code> if the command can be executed */ public boolean canExecute() { return true; } /** * @return <code>true</code> if the command can be undone. This method * should only be called after <code>execute()</code> or * <code>redo()</code> has been called. */ public boolean canUndo() { return true; } /** * Returns a Command that represents the chaining of a specified Command to * this Command. The Command being chained will <code>execute()</code> after * this command has executed, and it will <code>undo()</code> before this * Command is undone. * * @param command * <code>null</code> or the Command being chained * @return a Command representing the union */ public Command chain(Command command) { if (command == null) return this; class ChainedCompoundCommand extends CompoundCommand { public Command chain(Command c) { add(c); return this; } } CompoundCommand result = new ChainedCompoundCommand(); result.setDebugLabel("Chained Commands"); //$NON-NLS-1$ result.add(this); result.add(command); return result; } /** * This is called to indicate that the <code>Command</code> will not be used * again. The Command may be in any state (executed, undone or redone) when * dispose is called. The Command should not be referenced in any way after * it has been disposed. */ public void dispose() { } /** * executes the Command. This method should not be called if the Command is * not executable. */ public void execute() { } /** * @return an untranslated String used for debug purposes only */ public String getDebugLabel() { return debugLabel + ' ' + getLabel(); } /** * @return a String used to describe this command to the User */ public String getLabel() { return label; } /** * Re-executes the Command. This method should only be called after * <code>undo()</code> has been called. */ public void redo() { execute(); } /** * Sets the debug label for this command * * @param label * a description used for debugging only */ public void setDebugLabel(String label) { debugLabel = label; } /** * Sets the label used to describe this command to the User. * * @param label * the label */ public void setLabel(String label) { this.label = label; } /** * Undoes the changes performed during <code>execute()</code>. This method * should only be called after <code>execute</code> has been called, and * only when <code>canUndo()</code> returns <code>true</code>. * * @see #canUndo() */ public void undo() { } }
lgpl-2.1
johnscancella/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/AbstractDominatorsAnalysis.java
5682
/* * Bytecode Analysis Framework * Copyright (C) 2003,2004 University of Maryland * * 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 */ package edu.umd.cs.findbugs.ba; import java.util.BitSet; import java.util.Iterator; import javax.annotation.CheckForNull; import org.apache.bcel.generic.InstructionHandle; /** * <p>A dataflow analysis to compute dominator relationships between basic blocks. * Use the {@link #getResultFact} method to get the dominator set for a given * basic block. The dominator sets are represented using the * {@link java.util.BitSet} class, with the individual bits corresponding to the * IDs of basic blocks.</p> * <p> * Subclasses extend this class to compute either dominators or postdominators. * </p> * <p> * An EdgeChooser may be specified to select which edges to take into account. * For example, exception edges could be ignored. * </p> * * @author David Hovemeyer * @see DataflowAnalysis * @see CFG * @see BasicBlock */ public abstract class AbstractDominatorsAnalysis extends BasicAbstractDataflowAnalysis<BitSet> { private final CFG cfg; private final EdgeChooser edgeChooser; /** * Constructor. * * @param cfg * the CFG to compute dominator relationships for * @param ignoreExceptionEdges * true if exception edges should be ignored */ public AbstractDominatorsAnalysis(CFG cfg, final boolean ignoreExceptionEdges) { this(cfg, new EdgeChooser() { @Override public boolean choose(Edge edge) { if (ignoreExceptionEdges && edge.isExceptionEdge()) { return false; } else { return true; } } }); } /** * Constructor. * * @param cfg * the CFG to compute dominator relationships for * @param edgeChooser * EdgeChooser to choose which Edges to consider significant */ public AbstractDominatorsAnalysis(CFG cfg, EdgeChooser edgeChooser) { this.cfg = cfg; this.edgeChooser = edgeChooser; } @Override public BitSet createFact() { return new BitSet(); } @Override public void copy(BitSet source, BitSet dest) { dest.clear(); dest.or(source); } @Override public void initEntryFact(BitSet result) { // No blocks dominate the entry block result.clear(); } @Override public boolean isTop(BitSet fact) { // We represent TOP as a bitset with an illegal bit set return fact.get(cfg.getNumBasicBlocks()); } @Override public void makeFactTop(BitSet fact) { // We represent TOP as a bitset with an illegal bit set fact.set(cfg.getNumBasicBlocks()); } @Override public boolean same(BitSet fact1, BitSet fact2) { return fact1.equals(fact2); } @Override public void transfer(BasicBlock basicBlock, @CheckForNull InstructionHandle end, BitSet start, BitSet result) throws DataflowAnalysisException { // Start with intersection of dominators of predecessors copy(start, result); if (!isTop(result)) { // Every block dominates itself result.set(basicBlock.getLabel()); } } @Override public void meetInto(BitSet fact, Edge edge, BitSet result) throws DataflowAnalysisException { if (!edgeChooser.choose(edge)) { return; } if (isTop(fact)) { return; } else if (isTop(result)) { copy(fact, result); } else { // Meet is intersection result.and(fact); } } /** * Get a bitset containing the unique IDs of all blocks which dominate (or * postdominate) the given block. * * @param block * a BasicBlock * @return BitSet of the unique IDs of all blocks that dominate (or * postdominate) the BasicBlock */ public BitSet getAllDominatorsOf(BasicBlock block) { return getResultFact(block); } /** * Get a bitset containing the unique IDs of all blocks in CFG dominated (or * postdominated, depending on how the analysis was done) by given block. * * @param dominator * we want to get all blocks dominated (or postdominated) by this * block * @return BitSet of the ids of all blocks dominated by the given block */ public BitSet getAllDominatedBy(BasicBlock dominator) { BitSet allDominated = new BitSet(); for (Iterator<BasicBlock> i = cfg.blockIterator(); i.hasNext();) { BasicBlock block = i.next(); BitSet dominators = getResultFact(block); if (dominators.get(dominator.getLabel())) { allDominated.set(block.getLabel()); } } return allDominated; } }
lgpl-2.1
markcmiller86/libmesh_silo
src/geom/face_tri.C
4586
// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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 // C++ includes // Local includes #include "libmesh/face_tri.h" #include "libmesh/edge_edge2.h" namespace libMesh { // ------------------------------------------------------------ // Tri class member functions dof_id_type Tri::key (const unsigned int s) const { libmesh_assert_less (s, this->n_sides()); switch (s) { case 0: return this->compute_key (this->node(0), this->node(1)); case 1: return this->compute_key (this->node(1), this->node(2)); case 2: return this->compute_key (this->node(2), this->node(0)); } // We will never get here... Look at the code above. libmesh_error(); return 0; } AutoPtr<Elem> Tri::side (const unsigned int i) const { libmesh_assert_less (i, this->n_sides()); Elem* edge = new Edge2; switch (i) { case 0: { edge->set_node(0) = this->get_node(0); edge->set_node(1) = this->get_node(1); AutoPtr<Elem> ap_edge(edge); return ap_edge; } case 1: { edge->set_node(0) = this->get_node(1); edge->set_node(1) = this->get_node(2); AutoPtr<Elem> ap_edge(edge); return ap_edge; } case 2: { edge->set_node(0) = this->get_node(2); edge->set_node(1) = this->get_node(0); AutoPtr<Elem> ap_edge(edge); return ap_edge; } default: { libmesh_error(); } } // We will never get here... Look at the code above. libmesh_error(); AutoPtr<Elem> ap_edge(edge); return ap_edge; } bool Tri::is_child_on_side(const unsigned int c, const unsigned int s) const { libmesh_assert_less (c, this->n_children()); libmesh_assert_less (s, this->n_sides()); return (c == s || c == (s+1)%3); } Real Tri::quality (const ElemQuality q) const { switch (q) { /** * Source: Netgen, meshtool.cpp, TriangleQualityInst */ case DISTORTION: case STRETCH: { const Node* p1 = this->get_node(0); const Node* p2 = this->get_node(1); const Node* p3 = this->get_node(2); Point v1 = (*p2) - (*p1); Point v2 = (*p3) - (*p1); Point v3 = (*p3) - (*p2); const Real l1 = v1.size(); const Real l2 = v2.size(); const Real l3 = v3.size(); // if one length is 0, quality is quite bad! if ((l1 <=0.) || (l2 <= 0.) || (l3 <= 0.)) return 0.; const Real s1 = std::sin(std::acos(v1*v2/l1/l2)/2.); v1 *= -1; const Real s2 = std::sin(std::acos(v1*v3/l1/l3)/2.); const Real s3 = std::sin(std::acos(v2*v3/l2/l3)/2.); return 8. * s1 * s2 * s3; } default: return Elem::quality(q); } /** * I don't know what to do for this metric. * Maybe the base class knows. We won't get * here because of the defualt case above. */ return Elem::quality(q); } std::pair<Real, Real> Tri::qual_bounds (const ElemQuality q) const { std::pair<Real, Real> bounds; switch (q) { case MAX_ANGLE: bounds.first = 60.; bounds.second = 90.; break; case MIN_ANGLE: bounds.first = 30.; bounds.second = 60.; break; case CONDITION: bounds.first = 1.; bounds.second = 1.3; break; case JACOBIAN: bounds.first = 0.5; bounds.second = 1.155; break; case SIZE: case SHAPE: bounds.first = 0.25; bounds.second = 1.; break; case DISTORTION: bounds.first = 0.6; bounds.second = 1.; break; default: libMesh::out << "Warning: Invalid quality measure chosen." << std::endl; bounds.first = -1; bounds.second = -1; } return bounds; } } // namespace libMesh
lgpl-2.1
jriwanek/PaintedPlanks
src/main/java/paintedplanks/init/Items.java
354
package paintedplanks.init; import net.minecraftforge.fml.common.event.FMLInitializationEvent; public class Items { private static boolean initDone = false; public static void init(){ if(initDone)return; initDone = true; } public static void registerItemRenders(FMLInitializationEvent event) { // TODO Auto-generated method stub } }
lgpl-2.1
ExRam/DotSpatial-PCL
SupportFiles/NTS 1.7.3 Build 416/NetTopologySuite.Samples.Console/Operation/Distance/ClosestPointExample.cs
2954
using System; using GeoAPI.Geometries; using GisSharpBlog.NetTopologySuite.Geometries; using GisSharpBlog.NetTopologySuite.IO; using GisSharpBlog.NetTopologySuite.Operation.Distance; namespace GisSharpBlog.NetTopologySuite.Samples.Operation.Distance { /// <summary> /// Example of computing distance and closest points between geometries /// using the DistanceOp class. /// </summary> public class ClosestPointExample { internal static GeometryFactory fact; internal static WKTReader wktRdr; /// <summary> /// /// </summary> /// <param name="args"></param> [STAThread] public static void main(string[] args) { ClosestPointExample example = new ClosestPointExample(); example.Run(); } /// <summary> /// /// </summary> public ClosestPointExample() { } /// <summary> /// /// </summary> public virtual void Run() { FindClosestPoint("POLYGON ((200 180, 60 140, 60 260, 200 180))", "POINT (140 280)"); FindClosestPoint("POLYGON ((200 180, 60 140, 60 260, 200 180))", "MULTIPOINT (140 280, 140 320)"); FindClosestPoint("LINESTRING (100 100, 200 100, 200 200, 100 200, 100 100)", "POINT (10 10)"); FindClosestPoint("LINESTRING (100 100, 200 200)", "LINESTRING (100 200, 200 100)"); FindClosestPoint("LINESTRING (100 100, 200 200)", "LINESTRING (150 121, 200 0)"); FindClosestPoint("POLYGON (( 76 185, 125 283, 331 276, 324 122, 177 70, 184 155, 69 123, 76 185 ), ( 267 237, 148 248, 135 185, 223 189, 251 151, 286 183, 267 237 ))", "LINESTRING ( 153 204, 185 224, 209 207, 238 222, 254 186 )"); FindClosestPoint("POLYGON (( 76 185, 125 283, 331 276, 324 122, 177 70, 184 155, 69 123, 76 185 ), ( 267 237, 148 248, 135 185, 223 189, 251 151, 286 183, 267 237 ))", "LINESTRING ( 120 215, 185 224, 209 207, 238 222, 254 186 )"); } /// <summary> /// /// </summary> /// <param name="wktA"></param> /// <param name="wktB"></param> public virtual void FindClosestPoint(string wktA, string wktB) { Console.WriteLine("-------------------------------------"); try { IGeometry A = wktRdr.Read(wktA); IGeometry B = wktRdr.Read(wktB); Console.WriteLine("Geometry A: " + A); Console.WriteLine("Geometry B: " + B); DistanceOp distOp = new DistanceOp(A, B); double distance = distOp.Distance(); Console.WriteLine("Distance = " + distance); ICoordinate[] closestPt = distOp.ClosestPoints(); ILineString closestPtLine = fact.CreateLineString(closestPt); Console.WriteLine("Closest points: " + closestPtLine + " (distance = " + closestPtLine.Length + ")"); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } /// <summary> /// /// </summary> static ClosestPointExample() { fact = new GeometryFactory(); wktRdr = new WKTReader(fact); } } }
lgpl-2.1
n8han/Databinder-for-Wicket
databinder-models-jpa1/src/main/java/net/databinder/models/jpa/ModelPropertyQueryBinder.java
883
package net.databinder.models.jpa; import javax.persistence.Query; import org.apache.wicket.model.IDetachable; import org.apache.wicket.model.IModel; /** * A query binder that sets query parameters to corresponding properties taken * from the given Wicket model object. * * @param <T> Object type for the model * * @author rhansen@kindleit.net */ public class ModelPropertyQueryBinder<T> extends AbstractPropertyQueryBinder implements IDetachable { private static final long serialVersionUID = -6544558086991812867L; protected final IModel<T> model; protected final String[] properties; public ModelPropertyQueryBinder(final IModel<T> model, final String[] properties) { this.model = model; this.properties = properties; } public void detach() { model.detach(); } public void bind(final Query query) { bind(query, model.getObject(), properties); } }
lgpl-2.1
jozilla/Cassowary.net
Cassowary/ExClNotEnoughStays.cs
1174
/* Cassowary.net: an incremental constraint solver for .NET (http://lumumba.uhasselt.be/jo/projects/cassowary.net/) Copyright (C) 2005-2006 Jo Vermeulen (jo.vermeulen@uhasselt.be) This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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. */ using System; namespace Cassowary { public class ExClNotEnoughStays : ExClError { public override string Description() { return "(ExCLNotEnoughStays) There are not enough stays to give specific values to every variable"; } } }
lgpl-2.1
certator/tuxguitar_mod
TuxGuitar/src/org/herac/tuxguitar/app/tools/template/TGTemplateManager.java
1886
package org.herac.tuxguitar.app.tools.template; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.herac.tuxguitar.app.TuxGuitar; import org.herac.tuxguitar.app.util.TGFileUtils; import org.herac.tuxguitar.io.base.TGFileFormatManager; import org.herac.tuxguitar.song.models.TGSong; public class TGTemplateManager { private static final String TEMPLATE_DEFAULT_RESOURCE = "template-default.tg"; private static final String TEMPLATES_PREFIX = "templates/"; private static final String TEMPLATES_CONFIG_PATH = (TEMPLATES_PREFIX + "templates.xml"); private List templates; public TGTemplateManager(){ this.templates = new ArrayList(); this.loadTemplates(); } public int countTemplates(){ return this.templates.size(); } public Iterator getTemplates(){ return this.templates.iterator(); } public void loadTemplates(){ try{ InputStream templateInputStream = TGFileUtils.getResourceAsStream(TEMPLATES_CONFIG_PATH); if( templateInputStream != null ){ TGTemplateReader tgTemplateReader = new TGTemplateReader(); tgTemplateReader.loadTemplates(this.templates, templateInputStream); } } catch (Throwable e) { e.printStackTrace(); } } public TGTemplate getDefaultTemplate(){ TGTemplate tgTemplate = new TGTemplate(); tgTemplate.setName(new String()); tgTemplate.setResource(TEMPLATE_DEFAULT_RESOURCE); return tgTemplate; } public TGSong getTemplateAsSong(TGTemplate tgTemplate){ try{ if( tgTemplate != null && tgTemplate.getResource() != null ){ InputStream stream = TGFileUtils.getResourceAsStream(TEMPLATES_PREFIX + tgTemplate.getResource()); return TGFileFormatManager.instance().getLoader().load(TuxGuitar.instance().getSongManager().getFactory(),stream); } } catch (Throwable e) { e.printStackTrace(); } return null; } }
lgpl-2.1
mvarie/ILNumerics
ILNumerics/Misc/ILDimension.cs
21930
#region LGPL License /* This file is part of ILNumerics.Net Core Module. ILNumerics.Net Core Module 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. ILNumerics.Net Core Module 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 ILNumerics.Net Core Module. If not, see <http://www.gnu.org/licenses/>. */ #endregion using System; using ILNumerics.Storage; using ILNumerics.Exceptions; using System.Collections.Generic; namespace ILNumerics.Misc { /// <summary> /// ILDimension - dimensions for ILArray objects (immutable) /// </summary> /// <remarks>The class internally manages the dimensions of ILArray. /// The class is immutable. Therefore, once created, it informs the user /// about all dimension related properties, but cannot get altered.</remarks> [Serializable] [System.Diagnostics.DebuggerDisplay("{ToString(),nq}")] public class ILDimension { #region attributes int [] m_dims; int m_nrDims = 0; int m_numberOfElements = 0; int m_length = 0; int [] m_seqDistancesCache; #endregion #region constructors /// <summary> /// create new ILDimension /// </summary> /// <param name="dims">variable length dimensions specifier</param> /// <remarks>trailing singleton dimensions of dims will be kept.</remarks> public ILDimension (params int[] dims) : this(false,dims) {} /// <summary> /// create new ILDimension, without trimming trailing singleton dimensions /// </summary> /// <param name="trimSingletons">true: trailing singleton /// dimensions will be trimmed, false: those singleton dimensions will be kept.</param> /// <param name="dims">dimension lenght specifiers</param> public ILDimension (bool trimSingletons, params int[] dims) { List<int> tmp = new List<int>(dims); while(tmp.Count < 2) tmp.Add(1); if (trimSingletons) for (int i = tmp.Count; i-->2;) { if (tmp[i] == 1) tmp.RemoveAt(i); else break; } m_dims = tmp.ToArray(); m_numberOfElements = 1; m_nrDims = m_dims.Length; int t = 0, d; for(; t < m_dims.Length; t++){ d = m_dims[t]; if (d > m_length) m_length = d; m_numberOfElements *= d; } } /// <summary> /// [obsolete] copy constructor /// </summary> /// <param name="newDim">ILDimension object to copy this object from</param> /// <remarks>This function is obsolete and will be removed in a future version. Resona: /// ILDimension objects are immutable and can therefore savely be reused for /// multiple arrays.</remarks> private ILDimension (ILDimension newDim) { m_nrDims = newDim.m_nrDims; m_numberOfElements = newDim.m_numberOfElements; m_dims = new int[m_nrDims]; m_length = newDim.m_length; for (int i = 0; i < m_nrDims; i++) { m_dims[i] = newDim[i]; if (m_length < m_dims[i]) m_length = m_dims[i]; } } #endregion #region properties /// <summary>Get number of dimensions.</summary> public int NumberOfDimensions { get { return m_nrDims; } } /// <summary> /// Number of non singleton dimensions this ILDimension is referencing /// </summary> /// <remarks>non singleton dimensions are dimensions which length is larger than 1. /// Empty dimensions (length = 0) will not be take into account.</remarks> public int NonSingletonDimensions { get { int ret = 0; for (int i = 0; i < m_nrDims; i++) { if (m_dims[i] > 1) ret++; } return ret; } } /// <summary> /// The number of elements the dimensions reference in an array of that size /// </summary> public int NumberOfElements { get { return m_numberOfElements; } } /// <summary> /// return longest dimension length /// </summary> public int Longest { get { return m_length; } } /// <summary> /// find first non singleton dimension - if exist /// </summary> /// <returns>index of first non singleton dimension or -1, if this is a scalar.</returns> public int FirstNonSingleton() { if (m_numberOfElements <= 1) return -1; for (int i = 0; i < m_nrDims; i++) { if (m_dims[i] > 1) return i; } return -1; // this should not happen! Test on scalar above } #endregion #region public member /// <summary> /// Marks the number of elements between adjacent elementes of /// each dimension as if the underlying storage was a dense storage. /// </summary> /// <param name="dim">dimension number to query the element distance for. The /// first dimension has index 0 ('zero')!</param> /// <returns>number of elements between adjacent elements of dimension dim. /// </returns> /// <remarks>if dimension index dim is larger than the number of /// dimensions inside this ILDimension, the number of elements will /// be returned (assuming the trailing dimensions to be 1).</remarks> public int SequentialIndexDistance(int dim) { if (dim == m_nrDims) return m_numberOfElements; dim %= m_nrDims; int ret = 1; for (int i = 0; i < dim && i < m_nrDims; i++) { ret *= m_dims[i]; } return ret; } /// <summary> /// distances between adjacent elements for all dimensions /// </summary> /// <param name="minLength">minimum length of array to be /// returned. If this is larger than the number of dimensions /// in this ILDimension, the array will have minLength elements, /// with elements outside this dimensions repeating the value /// of the last dimension. The length of the array returned will /// be equal or greater than max(minLength,NumberOfDimensions).</param> /// <remarks>This is provided for performance reasons and should be /// used internally only. It enables developer of index access routines /// to cache the elements distances directly inside their functions /// without having to query the info on every index access. /// <para>Keep in mind, only the distances for the number of my /// dimensions are returned. Higher dimensions must be set to /// NumberOfElements if needed. This is different than querying /// the distances by SequentialIndexDistance(int), which will assume /// and return trailing dimensions to be 1.</para></remarks> internal int[] GetSequentialIndexDistances(int minLength) { minLength = Math.Max(m_nrDims,minLength); if (m_seqDistancesCache == null || m_seqDistancesCache.Length < minLength){ m_seqDistancesCache = new int[minLength]; int tmp = 1, i = 0; for (; i < m_nrDims; i++) { m_seqDistancesCache[i] = tmp; tmp *= m_dims[i]; } for (; i < m_seqDistancesCache.Length; i++) { m_seqDistancesCache[i] = tmp; } } return m_seqDistancesCache; } /// <summary> /// transfer my dimensions to integer array /// </summary> /// <returns>integer array containing a copy of dimensions length</returns> public int[] ToIntArray(){ return (int[])m_dims.Clone(); } /// <summary> /// transfer my dimensions to integer array /// </summary> /// <param name="length">minimum length of output array. If length /// is larger than my dimensions, trailing ones will be added.</param> /// <returns>integer array containing a copy of dimensions length. /// Trailing elements outside my dims will be one.</returns> internal int[] ToIntArray (int length) { int[] ret; ret = new int[length > m_nrDims ? length : m_nrDims]; Array.Copy(m_dims,0,ret,0,m_nrDims); for (int i = m_nrDims; i < length; i++) { ret[i] = 1; } return ret; } /// <summary> /// Translate indices from int[] Array to sequential storage access /// in my dimensions /// </summary> /// <param name="idx">int array of nrDims length</param> /// <returns>Index number pointing to the value's position in /// sequential storage.</returns> public int IndexFromArray(int[] idx) { try { int faktor = m_dims[0]; int ret = idx[0]; if (ret > faktor || ret < 0) throw new Exception("check value at dimension 0!"); int d = 1,tmp; if (idx.Length < 2) { if (idx.Length == 0) return 0; return ret; } for (; d<idx.Length-1; d++) { tmp = idx[d]; if (tmp > m_dims[d] || tmp < 0) throw new Exception("check value at dimension "+d+"!"); ret += tmp * faktor; faktor *= m_dims[d]; } ret += idx[d] * faktor; return ret; } catch (Exception e) { throw new ArgumentException ("Indices must match array dimension!",e); } } /// <summary> /// Transform dimension position into sequential index, gather expand /// information /// </summary> /// <param name="idx">int array of arbitrary length</param> /// <param name="MustExpand">[output] true, if the indices /// given address an element outside of /// this dimensions size. In this case, the output parameter /// 'Dimensions' carry the sizes /// of new dimensions needed. False otherwise</param> /// <param name="Dimensions">sizes of dimension if expansion is needed</param> /// <returns>Index number pointing to the value's position in /// sequential storage.</returns> /// <remarks>no checks are made for idx to fit inside dimensions! /// This functions is used for left side assignments. Therefore it /// computes the destination index also if it lays outside /// the array bounds.</remarks> internal int IndexFromArray(ref bool MustExpand, ref int[] Dimensions, int[] idx) { if (idx.Length < m_nrDims) { // expanding is allowed for all but the last specified dimension int d = 0, tmp = idx[0], faktor = 1; int ret = 0; while (d < idx.Length-1) { if (tmp < 0) throw new ILArgumentException("check index at dimension " + d.ToString() + "!"); if (tmp >= m_dims[d]) { Dimensions[d] = tmp+1; MustExpand = true; ret += (faktor * tmp); faktor *= tmp+1; } else { ret += (faktor * tmp); faktor *= m_dims[d]; } tmp = idx[++d]; } while (d < m_nrDims) { ret += faktor * ((tmp % m_dims[d])); tmp /= m_dims[d]; faktor *= m_dims[d++]; } if (tmp > 0) throw new ILArgumentException("expanding is allowed for explicitly bounded dimensions only! You must specify indices into all existing dimensions."); return ret; } else if (idx.Length == m_nrDims) { // expanding is allowed for all dimensions int d = 0, tmp, faktor = 1; int ret = 0; while (d < idx.Length) { tmp = idx[d]; if (tmp < 0) throw new ILArgumentException("check index at dimension " + d.ToString() + "!"); if (tmp >= m_dims[d]) { Dimensions[d] = tmp+1; MustExpand = true; ret += (faktor * tmp); faktor *= tmp+1; } else { ret += (faktor * tmp); faktor *= m_dims[d]; } d++; } return ret; } else { // idx dimensions are larger than my dimensions int d = 0, tmp = idx[0], faktor = 1; int ret = 0; while (d < m_nrDims) { tmp = idx[d]; if (tmp < 0) throw new ILArgumentException("check index at dimension " + d.ToString() + "!"); if (tmp >= m_dims[d]) { Dimensions[d] = tmp+1; MustExpand = true; ret += (faktor * tmp); faktor *= tmp+1; } else { ret += (faktor * tmp); faktor *= m_dims[d]; } d++; } while (d < idx.Length) { tmp = idx[d]; if (tmp > 0) { Dimensions[d] = tmp +1; MustExpand = true; } d++; faktor *= tmp; ret += faktor; } return ret; } } /// <summary> /// Unshift dimensions of indices from int[] Array /// and translate to index for sequential storage access /// in my dimensions </summary> /// <param name="idx">int array of the same length as /// the number of dimensions of this storage. Indices must /// lay within my dimensions.</param> /// <param name="unshift">number of dimensions to unshift /// idx before computing index</param> /// <returns>Index number pointing to the value's position /// in sequential storage.</returns> /// <remarks> If idx contains elements (indices) larger than /// my dimension bounds, an exception will be thrown. If unshift /// is 0, the length of idx may be smaller than the length of /// my dimensions. However, with unshift &gt; 0 the result /// is undefined.</remarks> public int IndexFromArray(int[] idx, int unshift) { unshift %= m_nrDims; int faktor = m_dims[0]; int ret = idx[(-unshift) % m_nrDims]; int d = 1; for (; d<idx.Length; d++) { ret += idx[(-unshift + d) % m_nrDims] * faktor; faktor *= m_dims[d]; } return ret; } /// <summary> /// Clone ILDimension object. /// </summary> /// <return> /// New ILDimension object as exact copy of this object. /// </return> private ILDimension Clone() { ILDimension ret = new ILDimension(this); return ret; } /// <summary> /// [deprecated] Shift this ILDimension /// </summary> /// <param name="shift">number of dimensions to shift.</param> /// <remarks>this will not alter this object anymore but return the shifted version! /// The function will be removed in a future release! Use /// ILDimension.GetShiftedVersion() instead!</remarks> private ILDimension Shift (int shift) { return GetShifted(shift); } /// <summary> /// return shifted version /// </summary> /// <param name="shift">number of dimensions to shift. The value /// will be considered modules the number of dimensions of /// this ILDimension.</param> /// <returns>shifted version of this ILDimension object.</returns> public ILDimension GetShifted(int shift){ shift %= m_nrDims; int [] tmp = new int [m_nrDims]; int id; for (int d = 0; d < m_nrDims; d++) { id = (d + shift) % m_nrDims; tmp[d] = m_dims[id]; } return new ILDimension(tmp); } /// <summary> /// Get length for dimension specified (Readonly) /// </summary> /// <param name="idx">index of dimension</param> /// <returns>length of dimension specified by idx</returns> /// <exception cref="ILNumerics.Exceptions.ILArgumentException">if idx is negative</exception> /// <remarks><para>for idx corresponds to an existing dimension, /// the length of that dimension is returned. If idx is larger than /// the number of dimensions 1 is returned. </para> /// </remarks> public int this [int idx] { get { if (idx < 0) throw new ArgumentOutOfRangeException("index","Index out of Range!"); else if (idx >= m_nrDims) { return 1; } return m_dims[idx]; } } /// <summary> /// Compares the size of this dimension to another dimension object. /// </summary> /// <param name="dim2">ILDimension object to compare this to.</param> /// <returns>Returns true if the sizes are the same, else returns false. /// The comparison is made by recognizing singleton dimensions. Therefore /// only non singleton dimensions are compared in the order of their /// appearance. </returns> /// <remarks>The function reutrns true, if the squeezed dimensions of /// both ILDimensions match.</remarks> public bool IsSameSize(ILDimension dim2) { if (dim2.NumberOfElements != m_numberOfElements) return false; for (int d2 = dim2.NumberOfDimensions,d1 = m_nrDims;d1 >= 0;) { d1--; d2--; while (d1 >= 0 && m_dims[d1]== 1) d1--; while (d2 >= 0 && dim2[d2] == 1) d2--; if (d1 >= 0 && d2 >= 0) { if (m_dims[d1] != dim2[d2]) return false; } } return true; } /// <summary> /// Compares the shape of this dimension to another dimension object /// </summary> /// <param name="dim2">ILDimension object to compare this to.</param> /// <returns>Returns true if the shapes are the same, else returns false. </returns> /// <remarks>This function is more strict than IsSameSize. In order /// for two dimensions to have the same shape, ALL dimensions must match - /// even singleton dimensions.</remarks> public bool IsSameShape(ILDimension dim2) { if (dim2.NumberOfElements != m_numberOfElements) return false; if (dim2.NumberOfDimensions != m_nrDims) return false; for (int d1 = m_nrDims;d1-->0;) { if (m_dims[d1] != dim2.m_dims[d1]) return false; } return true; } /// <summary> /// [deprecated] Create copy of this ILDimension having all singleton /// dimensions removed. /// </summary> /// <returns>a squeezed copy</returns> /// <remarks>This function is deprecated. Use the ILDimension.Squeeze() /// memeber instead. </remarks> public ILDimension GetSqueezed() { return Squeeze(); } /// <summary> /// Create and return copy without singleton dimensions /// </summary> /// <returns>Copy of this ILDimension having all singleton dimensions removed.</returns> /// <remarks> This function does not alter this object (since ILDimension is /// immutable). /// <para>All arrays in ILNumerics.Net have at least 2 dimensions. /// Therefore all but the first two singleton dimensions can be removed.</para> /// </remarks> public ILDimension Squeeze() { List<int> tmp = new List<int>(); foreach (int d in m_dims) { if (d != 1) tmp.Add(d); } while (tmp.Count < 2) { tmp.Add(1); } return new ILDimension(tmp.ToArray()); } /// <summary> /// Return ILDimension having trailing singleton dimensions removed /// </summary> /// <returns>Copy without trailing singleton dimensions</returns> /// <remarks> this object will NOT be altered. As usual for all ILArrays, /// the result wil have at least 2 dimensions.</remarks> public ILDimension Trim() { if (m_nrDims == 2 || m_dims[m_nrDims-1] != 1) { return this; } int i = m_nrDims; for (; i-->2; ) if (m_dims[i] != 1) break; int[] newdims = new int[++i]; System.Array.Copy(m_dims,0,newdims,0,i); return new ILDimension(newdims); } /// toString: prints out dimensions public override String ToString (){ String s = "["; for (int t = 0; t < m_nrDims; t++) { s = s + m_dims[t]; if (t < m_nrDims -1 ) s = s + ","; } s = s + "]"; return s; } #endregion } }
lgpl-2.1
xcthulhu/periphondemand
src/bin/pod.py
3821
#!/usr/bin/python # -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Name: pod.py # Purpose: # Author: Fabien Marteau <fabien.marteau@armadeus.com> # Created: 02/06/2008 #----------------------------------------------------------------------------- # Copyright (2008) Armadeus Systems # # 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. # #----------------------------------------------------------------------------- # Revision list : # # Date By Changes # #----------------------------------------------------------------------------- """ Starting point of POD """ #__versionTime__ = "02/06/2008" __author__ = "Fabien Marteau <fabien.marteau@armadeus.com>" from periphondemand.bin.commandline import Cli from periphondemand.bin.utils import Settings from periphondemand.bin.utils import wrappersystem as sy from periphondemand.bin.define import POD_PATH from periphondemand.bin import version as ver import sys,os,getopt __version__ = ver.getVersion() TMPFILENAME = "podtmp" def usage(): """ print POD arg usage """ print """\ Usage: pod [OPTION...] -h, --help give this help list -s, --source=filename load a script -l, --load=projectname load a project -v, --version print program version Report bugs to http://periphondemand.sourceforge.net/ """ def main(argv): try: opts, args = getopt.getopt(argv[1:], "hvs:l:", ["help", "version","source=","load="] ) except getopt.GetoptError,e: print str(e) usage() sys.exit(2) options = [arg[0] for arg in opts] if "help" in options or "-h" in options: usage() sys.exit(2) if "version" in options or "-v" in options: print "Peripherals On Demand version "+ ver.getVersion() sys.exit(2) CLI = Cli() SETTINGS = Settings() SETTINGS.path = POD_PATH SETTINGS.projectpath = sy.pwd() SETTINGS.version = ver.getVersion() # load command file if in command params if "--source" in options or "-s" in options: for opt,arg in opts: if opt=="--source" or opt=="-s": argument = arg break if not os.path.exists(argument): print "[ERROR] script "+str(argument)+\ " doesn't exist" usage() return CLI.do_source(argument) elif "--load" in options or "-l" in options: for opt,arg in opts: if opt=="--load" or opt=="-l": argument = arg break if not os.path.exists(argument): print "[ERROR] project "+str(argument)+\ " doesn't exist" usage() return tmpfile = open(TMPFILENAME,"w") tmpfile.write("project.load "+argument) tmpfile.close() print "Loading project "+str(argument)+" :\n" CLI.do_source(TMPFILENAME) # infinite command loop CLI.cmdloop() if __name__ == "__main__": main()
lgpl-2.1
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/job/history/internal/CompositeReader.java
2151
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.job.history.internal; import java.io.IOException; import java.io.Reader; /** * A composite {@link Reader} (because there is {@code SequenceInputStream} but not {@code SequenceReader}). * * @version $Id$ * @since 7.1RC1 */ public class CompositeReader extends Reader { private final Reader[] readers; private int index; /** * Creates a new composite reader that includes the given readers. * * @param readers the readers to include */ public CompositeReader(Reader... readers) { this.readers = readers; } @Override public void close() throws IOException { for (Reader reader : this.readers) { reader.close(); } } @Override public int read(char[] buffer, int offset, int length) throws IOException { if (this.index >= this.readers.length) { // No more readers. return -1; } int readCount = this.readers[this.index].read(buffer, offset, length); if (readCount < 0) { // End of the current reader. Move to the next reader. this.index++; return read(buffer, offset, length); } return readCount; } }
lgpl-2.1
huasanyelao/lucene1.0
com/lucene/analysis/standard/ParseException.java
6374
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 0.7pre6 */ package com.lucene.analysis.standard; /** * This exception is thrown when parse errors are encountered. * You can explicitly create objects of this exception type by * calling the method generateParseException in the generated * parser. * * You can modify this class to customize your error reporting * mechanisms so long as you retain the public fields. */ public class ParseException extends java.io.IOException { /** * This constructor is used by the method "generateParseException" * in the generated parser. Calling this constructor generates * a new object of this type with the fields "currentToken", * "expectedTokenSequences", and "tokenImage" set. The boolean * flag "specialConstructor" is also set to true to indicate that * this constructor was used to create this object. * This constructor calls its super class with the empty string * to force the "toString" method of parent class "Throwable" to * print the error message in the form: * ParseException: <result of getMessage> */ public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal ) { super(""); specialConstructor = true; currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; tokenImage = tokenImageVal; } /** * The following constructors are for use by you for whatever * purpose you can think of. Constructing the exception in this * manner makes the exception behave in the normal way - i.e., as * documented in the class "Throwable". The fields "errorToken", * "expectedTokenSequences", and "tokenImage" do not contain * relevant information. The JavaCC generated code does not use * these constructors. */ public ParseException() { super(); specialConstructor = false; } public ParseException(String message) { super(message); specialConstructor = false; } /** * This variable determines which constructor was used to create * this object and thereby affects the semantics of the * "getMessage" method (see below). */ protected boolean specialConstructor; /** * This is the last token that has been consumed successfully. If * this object has been created due to a parse error, the token * followng this token will (therefore) be the first error token. */ public Token currentToken; /** * Each entry in this array is an array of integers. Each array * of integers represents a sequence of tokens (by their ordinal * values) that is expected at this point of the parse. */ public int[][] expectedTokenSequences; /** * This is a reference to the "tokenImage" array of the generated * parser within which the parse error occurred. This array is * defined in the generated ...Constants interface. */ public String[] tokenImage; /** * This method has the standard behavior when this object has been * created using the standard constructors. Otherwise, it uses * "currentToken" and "expectedTokenSequences" to generate a parse * error message and returns it. If this object has been created * due to a parse error, and you do not catch it (it gets thrown * from the parser), then this method is called during the printing * of the final stack trace, and hence the correct error message * gets displayed. */ public String getMessage() { if (!specialConstructor) { return super.getMessage(); } String expected = ""; int maxSize = 0; for (int i = 0; i < expectedTokenSequences.length; i++) { if (maxSize < expectedTokenSequences[i].length) { maxSize = expectedTokenSequences[i].length; } for (int j = 0; j < expectedTokenSequences[i].length; j++) { expected += tokenImage[expectedTokenSequences[i][j]] + " "; } if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) { expected += "..."; } expected += eol + " "; } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += add_escapes(tok.image); tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn + "." + eol; if (expectedTokenSequences.length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected; return retval; } /** * The end of line string for this machine. */ protected String eol = System.getProperty("line.separator", "\n"); /** * Used to convert raw characters to their escaped version * when these raw version cannot be used as part of an ASCII * string literal. */ protected String add_escapes(String str) { StringBuffer retval = new StringBuffer(); char ch; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case 0 : continue; case '\b': retval.append("\\b"); continue; case '\t': retval.append("\\t"); continue; case '\n': retval.append("\\n"); continue; case '\f': retval.append("\\f"); continue; case '\r': retval.append("\\r"); continue; case '\"': retval.append("\\\""); continue; case '\'': retval.append("\\\'"); continue; case '\\': retval.append("\\\\"); continue; default: if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { String s = "0000" + Integer.toString(ch, 16); retval.append("\\u" + s.substring(s.length() - 4, s.length())); } else { retval.append(ch); } continue; } } return retval.toString(); } }
lgpl-2.1
melqkiades/yelp
source/python/netflix/__init__.py
22
__author__ = 'monica'
lgpl-2.1
duythanhphan/qt-creator
src/plugins/qbsprojectmanager/qbsnodes.cpp
21457
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qbsnodes.h" #include "qbsproject.h" #include "qbsrunconfiguration.h" #include <coreplugin/fileiconprovider.h> #include <coreplugin/idocument.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/target.h> #include <qtsupport/qtsupportconstants.h> #include <utils/hostosinfo.h> #include <utils/qtcassert.h> #include <qbs.h> #include <QDir> #include <QStyle> // ---------------------------------------------------------------------- // Helpers: // ---------------------------------------------------------------------- static QString displayNameFromPath(const QString &path, const QString &base) { QString dir = base; if (!base.endsWith(QLatin1Char('/'))) dir.append(QLatin1Char('/')); QString name = path; if (name.startsWith(dir)) { name = name.mid(dir.count()); } else { QFileInfo fi = QFileInfo(path); name = QCoreApplication::translate("Qbs::QbsProjectNode", "%1 in %2") .arg(fi.fileName(), fi.absolutePath()); } return name; } static QIcon generateIcon() { const QSize desiredSize = QSize(16, 16); const QIcon projectBaseIcon(QString::fromLatin1(QtSupport::Constants::ICON_QT_PROJECT)); const QPixmap projectPixmap = Core::FileIconProvider::overlayIcon(QStyle::SP_DirIcon, projectBaseIcon, desiredSize); QIcon result; result.addPixmap(projectPixmap); return result; } namespace QbsProjectManager { namespace Internal { QIcon QbsProjectNode::m_projectIcon = generateIcon(); QIcon QbsProductNode::m_productIcon = QIcon(QString::fromLatin1(ProjectExplorer::Constants::ICON_REBUILD_SMALL)); QIcon QbsGroupNode::m_groupIcon = QIcon(QString::fromLatin1(ProjectExplorer::Constants::ICON_BUILD_SMALL)); class FileTreeNode { public: explicit FileTreeNode(const QString &n = QString(), FileTreeNode *p = 0, bool f = false) : parent(p), name(n), m_isFile(f) { if (p) p->children.append(this); } ~FileTreeNode() { qDeleteAll(children); } FileTreeNode *addPart(const QString &n, bool isFile) { foreach (FileTreeNode *c, children) { if (c->name == n) return c; } return new FileTreeNode(n, this, isFile); } bool isFile() { return m_isFile; } static FileTreeNode *moveChildrenUp(FileTreeNode *node) { QTC_ASSERT(node, return 0); FileTreeNode *newParent = node->parent; if (!newParent) return 0; // disconnect node and parent: node->parent = 0; newParent->children.removeOne(node); foreach (FileTreeNode *c, node->children) { // update path, make sure there will be no / before "C:" on windows: if (Utils::HostOsInfo::isWindowsHost() && node->name.isEmpty()) c->name = node->name; else c->name = node->name + QLatin1Char('/') + c->name; newParent->children.append(c); c->parent = newParent; } // Delete node node->children.clear(); delete node; return newParent; } // Moves the children of the node pointing to basedir to the root of the tree. static void reorder(FileTreeNode *node, const QString &basedir) { QTC_CHECK(!basedir.isEmpty()); QString prefix = basedir; if (basedir.startsWith(QLatin1Char('/'))) prefix = basedir.mid(1); prefix.append(QLatin1Char('/')); if (node->path() == basedir) { // Find root node: FileTreeNode *root = node; while (root->parent) root = root->parent; foreach (FileTreeNode *c, node->children) { // Update children names by prepending basedir c->name = prefix + c->name; // Update parent information: c->parent = root; root->children.append(c); } // Clean up node: node->children.clear(); node->parent->children.removeOne(node); node->parent = 0; delete node; return; } foreach (FileTreeNode *n, node->children) reorder(n, basedir); } static void simplify(FileTreeNode *node) { foreach (FileTreeNode *c, node->children) simplify(c); if (!node->parent) return; if (node->children.isEmpty() && !node->isFile()) { // Clean up empty folder nodes: node->parent->children.removeOne(node); node->parent = 0; delete node; } else if (node->children.count() == 1 && !node->children.at(0)->isFile()) { // Compact folder nodes with one child only: moveChildrenUp(node); } } QString path() { QString p = name; FileTreeNode *node = parent; while (node) { if (!Utils::HostOsInfo::isWindowsHost() || !node->name.isEmpty()) p = node->name + QLatin1Char('/') + p; node = node->parent; } return p; } QList<FileTreeNode *> children; FileTreeNode *parent; QString name; bool m_isFile; }; // ---------------------------------------------------------------------- // QbsFileNode: // ---------------------------------------------------------------------- QbsFileNode::QbsFileNode(const QString &filePath, const ProjectExplorer::FileType fileType, bool generated, int line) : ProjectExplorer::FileNode(filePath, fileType, generated), m_line(line) { } void QbsFileNode::setLine(int l) { m_line = l; } QString QbsFileNode::displayName() const { return ProjectExplorer::FileNode::displayName() + QLatin1Char(':') + QString::number(m_line); } bool QbsFileNode::update(const qbs::CodeLocation &loc) { const QString oldPath = path(); const int oldLine = line(); setPath(loc.fileName()); setLine(loc.line()); return (line() != oldLine || path() != oldPath); } // --------------------------------------------------------------------------- // QbsBaseProjectNode: // --------------------------------------------------------------------------- QbsBaseProjectNode::QbsBaseProjectNode(const QString &path) : ProjectExplorer::ProjectNode(path) { } bool QbsBaseProjectNode::hasBuildTargets() const { foreach (ProjectNode *n, subProjectNodes()) if (n->hasBuildTargets()) return true; return false; } QList<ProjectExplorer::ProjectNode::ProjectAction> QbsBaseProjectNode::supportedActions(ProjectExplorer::Node *node) const { Q_UNUSED(node); return QList<ProjectExplorer::ProjectNode::ProjectAction>(); } bool QbsBaseProjectNode::canAddSubProject(const QString &proFilePath) const { Q_UNUSED(proFilePath); return false; } bool QbsBaseProjectNode::addSubProjects(const QStringList &proFilePaths) { Q_UNUSED(proFilePaths); return false; } bool QbsBaseProjectNode::removeSubProjects(const QStringList &proFilePaths) { Q_UNUSED(proFilePaths); return false; } bool QbsBaseProjectNode::addFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths, QStringList *notAdded) { Q_UNUSED(fileType); Q_UNUSED(filePaths); Q_UNUSED(notAdded); return false; } bool QbsBaseProjectNode::removeFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths, QStringList *notRemoved) { Q_UNUSED(fileType); Q_UNUSED(filePaths); Q_UNUSED(notRemoved); return false; } bool QbsBaseProjectNode::deleteFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths) { Q_UNUSED(fileType); Q_UNUSED(filePaths); return false; } bool QbsBaseProjectNode::renameFile(const ProjectExplorer::FileType fileType, const QString &filePath, const QString &newFilePath) { Q_UNUSED(fileType); Q_UNUSED(filePath); Q_UNUSED(newFilePath); return false; } QList<ProjectExplorer::RunConfiguration *> QbsBaseProjectNode::runConfigurationsFor(ProjectExplorer::Node *node) { Q_UNUSED(node); return QList<ProjectExplorer::RunConfiguration *>(); } // -------------------------------------------------------------------- // QbsGroupNode: // -------------------------------------------------------------------- QbsGroupNode::QbsGroupNode(const qbs::GroupData *grp, const QString &productPath) : QbsBaseProjectNode(QString()), m_qbsGroupData(0) { setIcon(m_groupIcon); QbsFileNode *idx = new QbsFileNode(grp->location().fileName(), ProjectExplorer::ProjectFileType, false, grp->location().line()); addFileNodes(QList<ProjectExplorer::FileNode *>() << idx, this); updateQbsGroupData(grp, productPath, true, true); } bool QbsGroupNode::isEnabled() const { if (!parentFolderNode() || !m_qbsGroupData) return false; return static_cast<QbsProductNode *>(parentFolderNode())->isEnabled() && m_qbsGroupData->isEnabled(); } void QbsGroupNode::updateQbsGroupData(const qbs::GroupData *grp, const QString &productPath, bool productWasEnabled, bool productIsEnabled) { Q_ASSERT(grp); if (grp == m_qbsGroupData && productPath == m_productPath) return; bool groupWasEnabled = productWasEnabled && m_qbsGroupData && m_qbsGroupData->isEnabled(); bool groupIsEnabled = productIsEnabled && grp->isEnabled(); bool updateExisting = groupWasEnabled != groupIsEnabled; m_productPath = productPath; m_qbsGroupData = grp; setPath(grp->location().fileName()); setDisplayName(grp->name()); QbsFileNode *idx = 0; foreach (ProjectExplorer::FileNode *fn, fileNodes()) { idx = qobject_cast<QbsFileNode *>(fn); if (idx) break; } if (idx->update(grp->location()) || updateExisting) idx->emitNodeUpdated(); setupFiles(this, grp->allFilePaths(), productPath, updateExisting); if (updateExisting) emitNodeUpdated(); } void QbsGroupNode::setupFiles(QbsBaseProjectNode *root, const QStringList &files, const QString &productPath, bool updateExisting) { // Build up a tree of nodes: FileTreeNode tree; foreach (const QString &path, files) { QStringList pathSegments = path.split(QLatin1Char('/'), QString::SkipEmptyParts); FileTreeNode *root = &tree; while (!pathSegments.isEmpty()) { bool isFile = pathSegments.count() == 1; root = root->addPart(pathSegments.takeFirst(), isFile); } } FileTreeNode::reorder(&tree, productPath); FileTreeNode::simplify(&tree); setupFolder(root, &tree, productPath, updateExisting); } void QbsGroupNode::setupFolder(ProjectExplorer::FolderNode *root, const FileTreeNode *fileTree, const QString &baseDir, bool updateExisting) { // We only need to care about FileNodes and FolderNodes here. Everything else is // handled elsewhere. // QbsGroupNodes are managed by the QbsProductNode. // The buildsystem file is either managed by QbsProductNode or by updateQbsGroupData(...). QList<ProjectExplorer::FileNode *> filesToRemove; foreach (ProjectExplorer::FileNode *fn, root->fileNodes()) { if (!qobject_cast<QbsFileNode *>(fn)) filesToRemove << fn; } QList<ProjectExplorer::FileNode *> filesToAdd; QList<ProjectExplorer::FolderNode *> foldersToRemove; foreach (ProjectExplorer::FolderNode *fn, root->subFolderNodes()) { if (fn->nodeType() == ProjectExplorer::ProjectNodeType) continue; // Skip ProjectNodes mixed into the folders... foldersToRemove.append(fn); } foreach (FileTreeNode *c, fileTree->children) { QString path = c->path(); // Handle files: if (c->isFile()) { ProjectExplorer::FileNode *fn = root->findFile(path); if (fn) { filesToRemove.removeOne(fn); if (updateExisting) fn->emitNodeUpdated(); } else { fn = new ProjectExplorer::FileNode(path, ProjectExplorer::UnknownFileType, false); filesToAdd.append(fn); } continue; } else { FolderNode *fn = root->findSubFolder(c->path()); if (!fn) { fn = new FolderNode(c->path()); root->projectNode()->addFolderNodes(QList<FolderNode *>() << fn, root); } else { foldersToRemove.removeOne(fn); if (updateExisting) fn->emitNodeUpdated(); } fn->setDisplayName(displayNameFromPath(c->path(), baseDir)); setupFolder(fn, c, c->path(), updateExisting); } } root->projectNode()->removeFileNodes(filesToRemove, root); root->projectNode()->removeFolderNodes(foldersToRemove, root); root->projectNode()->addFileNodes(filesToAdd, root); } // -------------------------------------------------------------------- // QbsProductNode: // -------------------------------------------------------------------- QbsProductNode::QbsProductNode(const qbs::ProductData &prd) : QbsBaseProjectNode(prd.location().fileName()) { setIcon(m_productIcon); ProjectExplorer::FileNode *idx = new QbsFileNode(prd.location().fileName(), ProjectExplorer::ProjectFileType, false, prd.location().line()); addFileNodes(QList<ProjectExplorer::FileNode *>() << idx, this); setQbsProductData(prd); } bool QbsProductNode::isEnabled() const { return m_qbsProductData.isEnabled(); } void QbsProductNode::setQbsProductData(const qbs::ProductData prd) { if (m_qbsProductData == prd) return; bool productWasEnabled = m_qbsProductData.isEnabled(); bool productIsEnabled = prd.isEnabled(); bool updateExisting = productWasEnabled != productIsEnabled; setDisplayName(prd.name()); setPath(prd.location().fileName()); const QString &productPath = QFileInfo(prd.location().fileName()).absolutePath(); // Find the QbsFileNode we added earlier: QbsFileNode *idx = 0; foreach (ProjectExplorer::FileNode *fn, fileNodes()) { idx = qobject_cast<QbsFileNode *>(fn); if (idx) break; } if (idx->update(prd.location()) || updateExisting) idx->emitNodeUpdated(); QList<ProjectExplorer::ProjectNode *> toAdd; QList<ProjectExplorer::ProjectNode *> toRemove = subProjectNodes(); foreach (const qbs::GroupData &grp, prd.groups()) { if (grp.name() == prd.name() && grp.location() == prd.location()) { // Set implicit product group right onto this node: QbsGroupNode::setupFiles(this, grp.allFilePaths(), productPath, updateExisting); continue; } QbsGroupNode *gn = findGroupNode(grp.name()); if (gn) { toRemove.removeOne(gn); gn->updateQbsGroupData(&grp, productPath, productWasEnabled, productIsEnabled); } else { gn = new QbsGroupNode(&grp, productPath); toAdd.append(gn); } } addProjectNodes(toAdd); removeProjectNodes(toRemove); m_qbsProductData = prd; if (updateExisting) emitNodeUpdated(); } QList<ProjectExplorer::RunConfiguration *> QbsProductNode::runConfigurationsFor(ProjectExplorer::Node *node) { Q_UNUSED(node); QList<ProjectExplorer::RunConfiguration *> result; QbsProjectNode *pn = qobject_cast<QbsProjectNode *>(projectNode()); if (!isEnabled() || !pn || pn->qbsProject()->targetExecutable(m_qbsProductData, qbs::InstallOptions()).isEmpty()) { return result; } foreach (ProjectExplorer::RunConfiguration *rc, pn->project()->activeTarget()->runConfigurations()) { QbsRunConfiguration *qbsRc = qobject_cast<QbsRunConfiguration *>(rc); if (!qbsRc) continue; if (qbsRc->qbsProduct() == qbsProductData().name()) result << qbsRc; } return result; } QbsGroupNode *QbsProductNode::findGroupNode(const QString &name) { foreach (ProjectExplorer::ProjectNode *n, subProjectNodes()) { QbsGroupNode *qn = static_cast<QbsGroupNode *>(n); if (qn->qbsGroupData()->name() == name) return qn; } return 0; } // -------------------------------------------------------------------- // QbsProjectNode: // -------------------------------------------------------------------- QbsProjectNode::QbsProjectNode(QbsProject *project) : QbsBaseProjectNode(project->document()->fileName()), m_project(project), m_qbsProject(0) { ctor(); } QbsProjectNode::QbsProjectNode(const QString &path) : QbsBaseProjectNode(path), m_project(0), m_qbsProject(0) { ctor(); } QbsProjectNode::~QbsProjectNode() { // do not delete m_project delete m_qbsProject; } void QbsProjectNode::update(const qbs::Project *prj) { update(prj ? prj->projectData() : qbs::ProjectData()); delete m_qbsProject; m_qbsProject = prj; } void QbsProjectNode::update(const qbs::ProjectData &prjData) { QList<ProjectExplorer::ProjectNode *> toAdd; QList<ProjectExplorer::ProjectNode *> toRemove = subProjectNodes(); foreach (const qbs::ProjectData &subData, prjData.subProjects()) { QbsProjectNode *qn = findProjectNode(subData.name()); if (!qn) { QbsProjectNode *subProject = new QbsProjectNode(prjData.location().fileName()); subProject->update(subData); toAdd << subProject; } else { qn->update(subData); toRemove.removeOne(qn); } } foreach (const qbs::ProductData &prd, prjData.products()) { QbsProductNode *qn = findProductNode(prd.name()); if (!qn) { toAdd << new QbsProductNode(prd); } else { qn->setQbsProductData(prd); toRemove.removeOne(qn); } } setDisplayName(prjData.name()); removeProjectNodes(toRemove); addProjectNodes(toAdd); m_qbsProjectData = prjData; } QbsProject *QbsProjectNode::project() const { if (!m_project && projectNode()) return static_cast<QbsProjectNode *>(projectNode())->project(); return m_project; } const qbs::Project *QbsProjectNode::qbsProject() const { QbsProjectNode *parent = qobject_cast<QbsProjectNode *>(projectNode()); if (!m_qbsProject && parent != this) return parent->qbsProject(); return m_qbsProject; } const qbs::ProjectData QbsProjectNode::qbsProjectData() const { return m_qbsProjectData; } void QbsProjectNode::ctor() { setIcon(m_projectIcon); addFileNodes(QList<ProjectExplorer::FileNode *>() << new ProjectExplorer::FileNode(path(), ProjectExplorer::ProjectFileType, false), this); } QbsProductNode *QbsProjectNode::findProductNode(const QString &name) { foreach (ProjectExplorer::ProjectNode *n, subProjectNodes()) { QbsProductNode *qn = qobject_cast<QbsProductNode *>(n); if (qn && qn->qbsProductData().name() == name) return qn; } return 0; } QbsProjectNode *QbsProjectNode::findProjectNode(const QString &name) { foreach (ProjectExplorer::ProjectNode *n, subProjectNodes()) { QbsProjectNode *qn = qobject_cast<QbsProjectNode *>(n); if (qn && qn->qbsProjectData().name() == name) return qn; } return 0; } } // namespace Internal } // namespace QbsProjectManager
lgpl-2.1
gambess/ERP-Arica
htdocs/fichinter/index.php
6933
<?php /* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2009 Regis Houssin <regis@dolibarr.fr> * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es> * * 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/>. */ /** * \file htdocs/fichinter/index.php * \brief List of all interventions * \ingroup ficheinter * \version $Id: index.php,v 1.66 2011/07/31 23:50:54 eldy Exp $ */ require("../main.inc.php"); require_once(DOL_DOCUMENT_ROOT."/contact/class/contact.class.php"); require_once(DOL_DOCUMENT_ROOT."/fichinter/class/fichinter.class.php"); require_once(DOL_DOCUMENT_ROOT."/lib/date.lib.php"); $langs->load("companies"); $langs->load("interventions"); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); if ($page == -1) { $page = 0; } $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; $socid=GETPOST("socid"); $page=GETPOST("page"); // Security check $fichinterid = GETPOST("id"); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'ficheinter', $fichinterid,'fichinter'); if (! $sortorder) $sortorder="DESC"; if (! $sortfield) $sortfield="fd.date"; if ($page == -1) { $page = 0 ; } $limit = $conf->liste_limit; $offset = $limit * $page ; $pageprev = $page - 1; $pagenext = $page + 1; $search_ref=GETPOST("search_ref"); $search_company=GETPOST("search_company"); $search_desc=GETPOST("search_desc"); /* * View */ llxHeader(); $sql = "SELECT"; $sql.= " f.ref, f.rowid as fichid, f.fk_statut, f.description,"; $sql.= " fd.description as descriptiondetail, fd.date as dp, fd.duree,"; $sql.= " s.nom, s.rowid as socid"; $sql.= " FROM (".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= ", ".MAIN_DB_PREFIX."fichinter as f)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid"; $sql.= " WHERE f.fk_soc = s.rowid "; $sql.= " AND f.entity = ".$conf->entity; if ($search_ref) $sql .= " AND f.ref like '%".$db->escape($search_ref)."%'"; if ($search_company) $sql .= " AND s.nom like '%".$db->escape($search_company)."%'"; if ($search_desc) $sql .= " AND (f.description like '%".$db->escape($search_desc)."%' OR fd.description like '%".$db->escape($search_desc)."%')"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid) $sql.= " AND s.rowid = " . $socid; $sql.= " ORDER BY ".$sortfield." ".$sortorder; $sql.= $db->plimit( $limit + 1 ,$offset); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); $interventionstatic=new Fichinter($db); $urlparam="&amp;socid=$socid"; print_barre_liste($langs->trans("ListOfInterventions"), $page, "index.php",$urlparam,$sortfield,$sortorder,'',$num); print '<form method="get" action="'.$_SERVER["PHP_SELF"].'">'."\n"; print '<table class="noborder" width="100%">'; print "<tr class=\"liste_titre\">"; print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"f.ref","",$urlparam,'width="15%"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"],"s.nom","",$urlparam,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Description"),$_SERVER["PHP_SELF"],"f.description","",$urlparam,'',$sortfield,$sortorder); print_liste_field_titre('',$_SERVER["PHP_SELF"],''); print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"fd.date","",$urlparam,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Duration"),$_SERVER["PHP_SELF"],"fd.duree","",$urlparam,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"f.fk_statut","",$urlparam,'align="right"',$sortfield,$sortorder); print "</tr>\n"; print '<tr class="liste_titre">'; print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_ref" value="'.$search_ref.'" size="8">'; print '</td><td class="liste_titre">'; print '<input type="text" class="flat" name="search_company" value="'.$search_company.'" size="10">'; print '</td><td class="liste_titre">'; print '<input type="text" class="flat" name="search_desc" value="'.$search_desc.'" size="12">'; print '</td>'; print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre">&nbsp;</td>'; print '<td class="liste_titre" align="right"><input class="liste_titre" type="image" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/search.png" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'"></td>'; print "</tr>\n"; $companystatic=new Societe($db); $var=True; $total = 0; $i = 0; while ($i < min($num, $limit)) { $objp = $db->fetch_object($result); $var=!$var; print "<tr $bc[$var]>"; print "<td>"; $interventionstatic->id=$objp->fichid; $interventionstatic->ref=$objp->ref; print $interventionstatic->getNomUrl(1); print "</td>\n"; print '<td>'; $companystatic->nom=$objp->nom; $companystatic->id=$objp->socid; $companystatic->client=$objp->client; print $companystatic->getNomUrl(1,'',44); print '</td>'; print '<td>'.dol_htmlentitiesbr(dol_trunc($objp->description,20)).'</td>'; print '<td>'.dol_htmlentitiesbr(dol_trunc($objp->descriptiondetail,20)).'</td>'; print '<td align="center">'.dol_print_date($db->jdate($objp->dp),'dayhour')."</td>\n"; print '<td align="right">'.ConvertSecondToTime($objp->duree).'</td>'; print '<td align="right">'.$interventionstatic->LibStatut($objp->fk_statut,5).'</td>'; print "</tr>\n"; $total += $objp->duree; $i++; } print '<tr class="liste_total"><td colspan="5" class="liste_total">'.$langs->trans("Total").'</td>'; print '<td align="right" nowrap="nowrap" class="liste_total">'.ConvertSecondToTime($total).'</td><td>&nbsp;</td>'; print '</tr>'; print '</table>'; print "</form>\n"; $db->free($result); } else { dol_print_error($db); } $db->close(); llxFooter('$Date: 2011/07/31 23:50:54 $ - $Revision: 1.66 $'); ?>
lgpl-2.1
Metaswitch/jitsi
src/net/java/sip/communicator/impl/ldap/LdapContactSourceService.java
5700
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.ldap; import java.util.*; import java.util.regex.*; import net.java.sip.communicator.service.contactsource.*; import net.java.sip.communicator.service.ldap.*; /** * Implements <tt>ContactSourceService</tt> for LDAP. * <p> * In contrast to other contact source implementations like AddressBook and * Outlook the LDAP contact source implementation is explicitly moved to the * "impl.ldap" package in order to allow us to create LDAP contact sources * for ldap directories through the LdapService. * </p> * * @author Sebastien Vincent */ public class LdapContactSourceService implements ExtendedContactSourceService { /** * The <tt>List</tt> of <tt>LdapContactQuery</tt> instances * which have been started and haven't stopped yet. */ private final List<LdapContactQuery> queries = new LinkedList<LdapContactQuery>(); /** * LDAP name. */ private final LdapDirectory ldapDirectory; /** * Constructor. * * @param ldapDirectory LDAP directory */ public LdapContactSourceService(LdapDirectory ldapDirectory) { this.ldapDirectory = ldapDirectory; } /** * Queries this search source for the given <tt>searchPattern</tt>. * * @param queryPattern the pattern to search for * @return the created query */ public ContactQuery queryContactSource(Pattern queryPattern) { return queryContactSource(queryPattern, LdapContactQuery.LDAP_MAX_RESULTS); } /** * Queries this search source for the given <tt>searchPattern</tt>. * * @param queryPattern the pattern to search for * @param count maximum number of contact returned * @return the created query */ public ContactQuery queryContactSource(Pattern queryPattern, int count) { LdapContactQuery query = new LdapContactQuery(this, queryPattern, count); synchronized (queries) { queries.add(query); } boolean hasStarted = false; try { query.start(); hasStarted = true; } finally { if (!hasStarted) { synchronized (queries) { if (queries.remove(query)) queries.notify(); } } } return query; } /** * Returns a user-friendly string that identifies this contact source. * @return the display name of this contact source */ public String getDisplayName() { return ldapDirectory.getSettings().getName(); } /** * Returns the identifier of this contact source. Some of the common * identifiers are defined here (For example the CALL_HISTORY identifier * should be returned by all call history implementations of this interface) * @return the identifier of this contact source */ public int getType() { return SEARCH_TYPE; } /** * Queries this search source for the given <tt>queryString</tt>. * @param query the string to search for * @return the created query */ public ContactQuery queryContactSource(String query) { return queryContactSource( Pattern.compile(query), LdapContactQuery.LDAP_MAX_RESULTS); } /** * Queries this search source for the given <tt>queryString</tt>. * * @param query the string to search for * @param contactCount the maximum count of result contacts * @return the created query */ public ContactQuery queryContactSource(String query, int contactCount) { return queryContactSource(Pattern.compile(query), contactCount); } /** * Stops this <tt>ContactSourceService</tt> implementation and prepares it * for garbage collection. * * @see AsyncContactSourceService#stop() */ public void stop() { boolean interrupted = false; synchronized (queries) { while (!queries.isEmpty()) { queries.get(0).cancel(); try { queries.wait(); } catch (InterruptedException iex) { interrupted = true; } } } if (interrupted) Thread.currentThread().interrupt(); } /** * Get LDAP directory. * * @return LDAP directory */ public LdapDirectory getLdapDirectory() { return ldapDirectory; } /** * Returns the phoneNumber prefix for all phone numbers. * * @return the phoneNumber prefix for all phone numbers */ public String getPhoneNumberPrefix() { return ldapDirectory.getSettings().getGlobalPhonePrefix(); } /** * Notifies this <tt>LdapContactSourceService</tt> that a specific * <tt>LdapContactQuery</tt> has stopped. * * @param query the <tt>LdapContactQuery</tt> which has stopped */ void stopped(LdapContactQuery query) { synchronized (queries) { if (queries.remove(query)) queries.notify(); } } /** * Returns the index of the contact source in the result list. * * @return the index of the contact source in the result list */ public int getIndex() { return -1; } }
lgpl-2.1
netarchivesuite/netarchivesuite-svngit-migration
tests/SendIndexReadyMessage.java
2188
/* File: $Id$ * Version: $Revision$ * Date: $Date$ * Author: $Author$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ import dk.netarkivet.common.distribute.ChannelID; import dk.netarkivet.common.distribute.Channels; import dk.netarkivet.common.distribute.JMSConnection; import dk.netarkivet.common.distribute.JMSConnectionFactory; import dk.netarkivet.harvester.distribute.IndexReadyMessage; /** * Send a {@link IndexReadyMessage} to the HarvestJobManager to * inform, that an deduplication index is ready for at certain harvest ID. * */ public class SendIndexReadyMessage { /** * @param args The harvestID */ public static void main(String[] args) { if (args.length < 1) { System.err.println( "arguments missing. Expected <harvestid>"); System.exit(1); } Long harvestId = Long.parseLong(args[0]); JMSConnection con = JMSConnectionFactory.getInstance(); ChannelID to = Channels.getTheSched(); ChannelID replyTo = Channels.getError(); boolean indexisready = true; IndexReadyMessage msg = new IndexReadyMessage(harvestId, indexisready, to, replyTo); con.send(msg); con.cleanup(); } }
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/layout/build/RepeatedFooterLayoutModelBuilder.java
4776
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.layout.build; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.engine.classic.core.ReportElement; import org.pentaho.reporting.engine.classic.core.SubReport; import org.pentaho.reporting.engine.classic.core.function.ProcessingContext; import org.pentaho.reporting.engine.classic.core.layout.InlineSubreportMarker; import org.pentaho.reporting.engine.classic.core.layout.model.RenderBox; import org.pentaho.reporting.engine.classic.core.layout.output.OutputProcessorFeature; import org.pentaho.reporting.engine.classic.core.layout.output.OutputProcessorMetaData; import org.pentaho.reporting.engine.classic.core.util.InstanceID; public class RepeatedFooterLayoutModelBuilder extends LayoutModelBuilderWrapper { private static final Log logger = LogFactory.getLog( RepeatedFooterLayoutModelBuilder.class ); private RenderBox parentBox; private int inBoxDepth; private OutputProcessorMetaData metaData; public RepeatedFooterLayoutModelBuilder( final LayoutModelBuilder backend ) { super( backend ); backend.setLimitedSubReports( true ); } public void initialize( final ProcessingContext metaData, final RenderBox parentBox, final RenderNodeFactory renderNodeFactory ) { this.parentBox = parentBox; getParent().initialize( metaData, parentBox, renderNodeFactory ); this.metaData = metaData.getOutputProcessorMetaData(); } public void setLimitedSubReports( final boolean limitedSubReports ) { } public InstanceID startBox( final ReportElement element ) { InstanceID instanceID = getParent().startBox( element ); inBoxDepth += 1; return instanceID; } public void startSection( final ReportElement element, final int sectionSize ) { throw new UnsupportedOperationException( "Global sections cannot be started for page headers" ); } public InlineSubreportMarker processSubReport( final SubReport element ) { return null; } public boolean finishBox() { inBoxDepth -= 1; return super.finishBox(); } public void endSubFlow() { throw new UnsupportedOperationException( "SubReport sections cannot be started for page headers" ); } public void addProgressMarkerBox() { if ( inBoxDepth != 0 ) { throw new IllegalStateException(); } super.addProgressMarkerBox(); } public void addManualPageBreakBox( final long range ) { throw new UnsupportedOperationException( "PageBreak sections cannot be started for page headers" ); } public LayoutModelBuilder deriveForStorage( final RenderBox clonedContent ) { final RepeatedFooterLayoutModelBuilder clone = (RepeatedFooterLayoutModelBuilder) super.deriveForStorage( clonedContent ); clone.parentBox = clonedContent; return clone; } public void startSection() { if ( inBoxDepth != 0 ) { throw new IllegalStateException(); } parentBox.clear(); super.startSection(); } public void endSection() { if ( inBoxDepth != 0 ) { throw new IllegalStateException(); } if ( metaData.isFeatureSupported( OutputProcessorFeature.STRICT_COMPATIBILITY ) ) { super.legacyFlagNotEmpty(); } super.endSection(); } public InstanceID createSubflowPlaceholder( final ReportElement element ) { throw new UnsupportedOperationException( "SubReport sections cannot be started for page headers" ); } public void startSubFlow( final InstanceID insertationPoint ) { throw new UnsupportedOperationException( "SubReport sections cannot be started for page headers" ); } public void startSubFlow( final ReportElement element ) { throw new UnsupportedOperationException( "SubReport sections cannot be started for page headers" ); } public void suspendSubFlow() { throw new UnsupportedOperationException( "SubReport sections cannot be started for page headers" ); } }
lgpl-2.1
julie-sullivan/phytomine
intermine/api/test/src/org/intermine/api/xml/TagBindingTest.java
4782
package org.intermine.api.xml; /* * Copyright (C) 2002-2014 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.io.IOUtils; import org.custommonkey.xmlunit.XMLUnit; import org.intermine.api.InterMineAPITestCase; import org.intermine.api.profile.ProfileManager; import org.intermine.metadata.FieldDescriptor; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.SingletonResults; public class TagBindingTest extends InterMineAPITestCase { private ProfileManager pm; private Map<String, List<FieldDescriptor>> classKeys; public TagBindingTest(String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); pm = im.getProfileManager(); } public void testUnMarshal() throws Exception { Reader reader = new InputStreamReader(getClass().getClassLoader() .getResourceAsStream("TagBindingTest.xml")); int count = new TagBinding().unmarshal(pm, pm.getSuperuser(), reader); assertEquals(3, count); Query q = new Query(); QueryClass qc = new QueryClass(Tag.class); q.addFrom(qc); q.addToSelect(qc); SingletonResults res = uosw.getObjectStore().executeSingleton(q); Iterator resIter = res.iterator(); while (resIter.hasNext()) { Tag t = (Tag) resIter.next(); assertEquals("class", t.getType()); String id = t.getObjectIdentifier(); if ("org.intermine.model.testmodel.Employee".equals(id) || "org.intermine.model.testmodel.Manager".equals(id)) { assertEquals("im:aspect:People", t.getTagName()); } else if ("org.intermine.model.testmodel.Bank".equals(id)) { assertEquals("im:aspect:Entities", t.getTagName()); } else { fail("Wrong objectIdentifier for tag encountered"); } } } public void testMarshal() throws Exception { XMLUnit.setIgnoreWhitespace(true); StringWriter sw = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(sw); writer.writeStartElement("tags"); List<Tag> tags = getTags(); for (Tag tag : tags) { TagBinding.marshal(tag, writer); } writer.writeEndElement(); writer.close(); } catch (XMLStreamException e) { throw new RuntimeException(e); } InputStream is = getClass().getClassLoader().getResourceAsStream("TagBindingTest.xml"); String expectedXml = IOUtils.toString(is); String actualXml = sw.toString().trim(); System.out.println(normalise(actualXml)); assertEquals("actual and expected XML should be the same", normalise(expectedXml), normalise(actualXml)); } private static String normalise(String x) { return x.replaceAll(">\\s*<", "><") // Ignore whitespace between elements .replaceAll("\n", "") // Remove all new-lines .replaceAll("\\s*/>", "/>") // Remove whitespace before /> .replaceAll("\\s{2,}", " ") // Collapse white space to single space .replaceAll("date-created=\"\\d+\"", "date-created=\"XXXX\""); // Ignore all dates } private List<Tag> getTags() { List<Tag> tags = new ArrayList<Tag>(); Tag tag = new Tag(); tag.setTagName("im:aspect:People"); tag.setType("class"); tag.setObjectIdentifier("org.intermine.model.testmodel.Employee"); tags.add(tag); tag = new Tag(); tag.setTagName("im:aspect:People"); tag.setType("class"); tag.setObjectIdentifier("org.intermine.model.testmodel.Manager"); tags.add(tag); tag = new Tag(); tag.setTagName("im:aspect:Entities"); tag.setType("class"); tag.setObjectIdentifier("org.intermine.model.testmodel.Bank"); tags.add(tag); return tags; } }
lgpl-2.1
interval1066/XFC
ui/xfc/gtk/image.cc
5958
/* XFC: Xfce Foundation Classes (User Interface Library) * Copyright (C) 2004-2005 The XFC Development Team. * * image.cc - GtkImage C++ wrapper implementation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "image.hh" #include "iconfactory.hh" #include "stockid.hh" #include "private/imageclass.hh" #include "../gdk/pixmap.hh" #include "../gdk/bitmap.hh" #include "../gdk/image.hh" #include "../gdk-pixbuf/pixbuf.hh" #include "../gdk-pixbuf/pixbuf-animation.hh" using namespace Xfc; /* Gtk::Image */ Gtk::Image::Image(GtkImage *image, bool owns_reference) : Misc((GtkMisc*)image, owns_reference) { } Gtk::Image::Image() : Misc((GtkMisc*)ImageClass::create()) { } Gtk::Image::Image(Gdk::Pixmap& pixmap, Gdk::Bitmap& mask) : Misc((GtkMisc*)ImageClass::create()) { set(&pixmap, &mask); } Gtk::Image::Image(Gdk::Image& image, Gdk::Bitmap& mask) : Misc((GtkMisc*)ImageClass::create()) { set(&image, &mask); } Gtk::Image::Image(const char *filename) : Misc((GtkMisc*)ImageClass::create()) { set(filename); } Gtk::Image::Image(const String& filename) : Misc((GtkMisc*)ImageClass::create()) { set(filename); } Gtk::Image::Image(Gdk::Pixbuf& pixbuf) : Misc((GtkMisc*)ImageClass::create()) { set(&pixbuf); } Gtk::Image::Image(const char **xpm_data) : Misc((GtkMisc*)ImageClass::create()) { GdkPixbuf *pixbuf = gdk_pixbuf_new_from_xpm_data(xpm_data); gtk_image_set_from_pixbuf(gtk_image(), pixbuf); g_object_unref(pixbuf); } Gtk::Image::Image(const StockId& stock_id, IconSize size) : Misc((GtkMisc*)ImageClass::create()) { set(stock_id, size); } Gtk::Image::Image(IconSet& icon_set, IconSize size) : Misc((GtkMisc*)ImageClass::create()) { set(&icon_set, size); } Gtk::Image::Image(Gdk::PixbufAnimation& animation) : Misc((GtkMisc*)ImageClass::create()) { set(animation); } Gtk::Image::Image(const char *icon_name, IconSize size) : Misc((GtkMisc*)ImageClass::create()) { set(icon_name, size); } Gtk::Image::Image(const String& icon_name, IconSize size) : Misc((GtkMisc*)ImageClass::create()) { set(icon_name, size); } Gtk::Image::~Image() { } void Gtk::Image::get_pixmap(Gdk::Pixmap **pixmap, Gdk::Bitmap **mask) const { GdkPixmap *tmp_pixmap = 0; GdkBitmap *tmp_mask = 0; gtk_image_get_pixmap(gtk_image(), &tmp_pixmap, &tmp_mask); if (pixmap && tmp_pixmap) *pixmap = G::Object::wrap<Gdk::Pixmap>(tmp_pixmap); if (mask && tmp_mask) *mask = G::Object::wrap<Gdk::Bitmap>(tmp_mask); } void Gtk::Image::get_image(Gdk::Image **gdk_image, Gdk::Bitmap **mask) const { GdkImage *tmp_image = 0; GdkBitmap *tmp_mask = 0; gtk_image_get_image(gtk_image(), &tmp_image, &tmp_mask); if (gdk_image && tmp_image) *gdk_image = G::Object::wrap<Gdk::Image>(tmp_image); if (mask && tmp_mask) *mask = G::Object::wrap<Gdk::Bitmap>(tmp_mask); } Gdk::Pixbuf* Gtk::Image::get_pixbuf() const { return G::Object::wrap<Gdk::Pixbuf>(gtk_image_get_pixbuf(gtk_image())); } void Gtk::Image::get_stock(StockId *stock_id, IconSize *size) const { char *tmp_stock_id = 0; gtk_image_get_stock(gtk_image(), &tmp_stock_id, (GtkIconSize*)size); if (stock_id) *stock_id = tmp_stock_id; } void Gtk::Image::get_icon_set(Pointer<IconSet> *icon_set, IconSize *size) const { GtkIconSet *tmp_icon_set = 0; gtk_image_get_icon_set(gtk_image(), &tmp_icon_set, (GtkIconSize*)size); if (icon_set && tmp_icon_set) *icon_set = G::Boxed::wrap<IconSet>(GTK_TYPE_ICON_SET, tmp_icon_set, true); } Gdk::PixbufAnimation* Gtk::Image::get_animation() const { return G::Object::wrap<Gdk::PixbufAnimation>(gtk_image_get_animation(gtk_image())); } void Gtk::Image::get_icon_name(String& icon_name, IconSize *size) const { const char *tmp_icon_name = 0; gtk_image_get_icon_name(gtk_image(), &tmp_icon_name, (GtkIconSize*)size); icon_name.assign(tmp_icon_name); } void Gtk::Image::set(Gdk::Pixmap *pixmap, Gdk::Bitmap *mask) { gtk_image_set_from_pixmap(gtk_image(), *pixmap, *mask); } void Gtk::Image::set(Gdk::Image *image, Gdk::Bitmap *mask) { gtk_image_set_from_image(gtk_image(), *image, *mask); } void Gtk::Image::set(const String& filename) { gtk_image_set_from_file(gtk_image(), filename.c_str()); } void Gtk::Image::set(Gdk::Pixbuf *pixbuf) { gtk_image_set_from_pixbuf(gtk_image(), *pixbuf); } void Gtk::Image::set(const StockId& stock_id, IconSize size) { gtk_image_set_from_stock(gtk_image(), stock_id, (GtkIconSize)size); } void Gtk::Image::set(Gtk::IconSet *icon_set, IconSize size) { gtk_image_set_from_icon_set(gtk_image(), *icon_set, (GtkIconSize)size); } void Gtk::Image::set(Gdk::PixbufAnimation& animation) { gtk_image_set_from_animation(gtk_image(), animation.gdk_pixbuf_animation()); } void Gtk::Image::set(const char *icon_name, IconSize size) { gtk_image_set_from_icon_name(gtk_image(), icon_name, (GtkIconSize)size); } void Gtk::Image::set(const String& icon_name, IconSize size) { set(icon_name.c_str(), size); } /* Gtk::ImageClass */ void Gtk::ImageClass::init(GtkImageClass *g_class) { MiscClass::init((GtkMiscClass*)g_class); } GType Gtk::ImageClass::get_type() { static GType type = 0; if (!type) { type = G::TypeInstance::register_type(GTK_TYPE_IMAGE, (GClassInitFunc)&init); } return type; } void* Gtk::ImageClass::create() { return g_object_new(get_type(), 0); }
lgpl-2.1
mono/linux-packaging-monodevelop
src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads/ErrorListPad.cs
37437
// ErrorListPad.cs // // Author: // Todd Berman <tberman@sevenl.net> // David Makovský <yakeen@sannyas-on.net> // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2004 Todd Berman // Copyright (c) 2006 David Makovský // Copyright (c) 2009 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Drawing; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.IO; using System.Diagnostics; using MonoDevelop.Core; using MonoDevelop.Projects; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Tasks; using MonoDevelop.Ide.Gui.Content; using Gtk; using System.Text; using MonoDevelop.Components.Docking; using MonoDevelop.Ide.Gui.Components; using MonoDevelop.Components.Commands; using MonoDevelop.Ide.Commands; using MonoDevelop.Components; using MonoDevelop.Components.AtkCocoaHelper; using System.Linq; using MonoDevelop.Components.AutoTest; using System.ComponentModel; using MonoDevelop.Ide.BuildOutputView; using System.Threading.Tasks; using MonoDevelop.Core.ProgressMonitoring; using MonoDevelop.Core.Instrumentation; namespace MonoDevelop.Ide.Gui.Pads { class ErrorListPad : PadContent { HPaned control; ScrolledWindow sw; PadTreeView view; BuildOutputViewContent buildOutputViewContent; BuildOutput buildOutput; LogView logView; TreeStore store; TreeModelFilter filter; TreeModelSort sort; ToggleButton errorBtn, warnBtn, msgBtn; Button buildLogBtn; ToggleButton logBtn; Label errorBtnLbl, warnBtnLbl, msgBtnLbl, logBtnLbl; SearchEntry searchEntry; string currentSearchPattern = null; Hashtable tasks = new Hashtable (); int errorCount; int warningCount; int infoCount; bool initialLogShow = true; Clipboard clipboard; Xwt.Drawing.Image iconWarning; Xwt.Drawing.Image iconError; Xwt.Drawing.Image iconInfo; Xwt.Drawing.Image iconEmpty; static readonly string restoreID = "Monodevelop.ErrorListColumns"; public readonly ConfigurationProperty<bool> ShowErrors = ConfigurationProperty.Create ("SharpDevelop.TaskList.ShowErrors", true); public readonly ConfigurationProperty<bool> ShowWarnings = ConfigurationProperty.Create ("SharpDevelop.TaskList.ShowWarnings", true); public readonly ConfigurationProperty<bool> ShowMessages = ConfigurationProperty.Create ("SharpDevelop.TaskList.ShowMessages", true); public readonly ConfigurationProperty<double> LogSeparatorPosition = ConfigurationProperty.Create ("SharpDevelop.TaskList.LogSeparatorPosition", 0.5d); public readonly ConfigurationProperty<bool> OutputViewVisible = ConfigurationProperty.Create ("SharpDevelop.TaskList.OutputViewVisible", false); static class DataColumns { internal const int Type = 0; internal const int Read = 1; internal const int Task = 2; internal const int Description = 3; } static class VisibleColumns { internal const int Type = 0; internal const int Marked = 1; internal const int Line = 2; internal const int Description = 3; internal const int File = 4; internal const int Project = 5; internal const int Path = 6; internal const int Category = 7; } static class Counters { public static Counter BuildLogShown = InstrumentationService.CreateCounter ("Build log opened", "Build Output", id: "ErrorListPad.BuildLogShown"); } public override Control Control { get { if (control == null) CreateControl (); return control; } } public override string Id { get { return "MonoDevelop.Ide.Gui.Pads.ErrorListPad"; } } ToggleButton MakeButton (string image, string name, bool active, out Label label) { var btnBox = MakeHBox (image, out label); var btn = new ToggleButton { Name = name, Active = active }; btn.Child = btnBox; return btn; } Button MakeButton (string image, string name, out Label label) { var btnBox = MakeHBox (image, out label); var btn = new Button { Name = name }; btn.Child = btnBox; return btn; } HBox MakeHBox (string image, out Label label) { var btnBox = new HBox (false, 2); btnBox.Accessible.SetShouldIgnore (true); var imageView = new ImageView (image, Gtk.IconSize.Menu); imageView.Accessible.SetShouldIgnore (true); btnBox.PackStart (imageView); label = new Label (); label.Accessible.SetShouldIgnore (true); btnBox.PackStart (label); return btnBox; } protected override void Initialize (IPadWindow window) { window.Title = GettextCatalog.GetString ("Errors"); DockItemToolbar toolbar = window.GetToolbar (DockPositionType.Top); toolbar.Accessible.Name = "ErrorPad.Toolbar"; toolbar.Accessible.SetLabel ("Error Pad Toolbar"); toolbar.Accessible.SetRole ("AXToolbar", "Pad toolbar"); toolbar.Accessible.Description = GettextCatalog.GetString ("The Error pad toolbar"); errorBtn = MakeButton (Stock.Error, "toggleErrors", ShowErrors, out errorBtnLbl); errorBtn.Accessible.Name = "ErrorPad.ErrorButton"; errorBtn.Toggled += FilterChanged; errorBtn.TooltipText = GettextCatalog.GetString ("Show Errors"); errorBtn.Accessible.Description = GettextCatalog.GetString ("Show Errors"); UpdateErrorsNum (); toolbar.Add (errorBtn); warnBtn = MakeButton (Stock.Warning, "toggleWarnings", ShowWarnings, out warnBtnLbl); warnBtn.Accessible.Name = "ErrorPad.WarningButton"; warnBtn.Toggled += FilterChanged; warnBtn.TooltipText = GettextCatalog.GetString ("Show Warnings"); warnBtn.Accessible.Description = GettextCatalog.GetString ("Show Warnings"); UpdateWarningsNum (); toolbar.Add (warnBtn); msgBtn = MakeButton (Stock.Information, "toggleMessages", ShowMessages, out msgBtnLbl); msgBtn.Accessible.Name = "ErrorPad.MessageButton"; msgBtn.Toggled += FilterChanged; msgBtn.TooltipText = GettextCatalog.GetString ("Show Messages"); msgBtn.Accessible.Description = GettextCatalog.GetString ("Show Messages"); UpdateMessagesNum (); toolbar.Add (msgBtn); var sep = new SeparatorToolItem (); sep.Accessible.SetShouldIgnore (true); toolbar.Add (sep); logBtn = MakeButton ("md-message-log", "toggleBuildOutput", false, out logBtnLbl); logBtn.Accessible.Name = "ErrorPad.LogButton"; logBtn.TooltipText = GettextCatalog.GetString ("Build Output"); logBtn.Accessible.Description = GettextCatalog.GetString ("Build Output"); logBtnLbl.Text = GettextCatalog.GetString ("Build Output"); logBtn.Accessible.SetTitle (logBtnLbl.Text); logBtn.Toggled += HandleTextLogToggled; toolbar.Add (logBtn); if (BuildOutput.IsFeatureEnabled) { buildLogBtn = MakeButton ("md-message-log", "toggleBuildOutput", out logBtnLbl); buildLogBtn.Accessible.Name = "ErrorPad.BuildLogButton"; buildLogBtn.TooltipText = GettextCatalog.GetString ("Structured Build Output"); buildLogBtn.Accessible.Description = GettextCatalog.GetString ("Structured Build Output"); logBtnLbl.Text = GettextCatalog.GetString ("Structured Build Output"); buildLogBtn.Accessible.SetTitle (logBtnLbl.Text); buildLogBtn.Clicked += HandleBinLogClicked; toolbar.Add (buildLogBtn); } buildOutput = new BuildOutput (); //Dummy widget to take all space between "Build Output" button and SearchEntry var spacer = new HBox (); spacer.Accessible.SetShouldIgnore (true); toolbar.Add (spacer, true); searchEntry = new SearchEntry (); searchEntry.Accessible.SetLabel (GettextCatalog.GetString ("Search")); searchEntry.Accessible.Name = "ErrorPad.Search"; searchEntry.Accessible.Description = GettextCatalog.GetString ("Search the error data"); searchEntry.Entry.Changed += searchPatternChanged; searchEntry.WidthRequest = 200; searchEntry.Visible = true; toolbar.Add (searchEntry); toolbar.ShowAll (); UpdatePadIcon (); IdeApp.ProjectOperations.StartBuild += OnBuildStarted; IdeApp.ProjectOperations.StartClean += OnBuildStarted; } void searchPatternChanged (object sender, EventArgs e) { currentSearchPattern = searchEntry.Entry.Text; filter.Refilter (); } void CreateControl () { control = new HPaned (); store = new Gtk.TreeStore (typeof (Xwt.Drawing.Image), // image - type typeof (bool), // read? typeof (TaskListEntry), // read? -- use Pango weight typeof (string)); SemanticModelAttribute modelAttr = new SemanticModelAttribute ("store__Type", "store__Read", "store__Task", "store__Description"); TypeDescriptor.AddAttributes (store, modelAttr); TreeModelFilterVisibleFunc filterFunct = new TreeModelFilterVisibleFunc (FilterTasks); filter = new TreeModelFilter (store, null); filter.VisibleFunc = filterFunct; sort = new TreeModelSort (filter); sort.SetSortFunc (VisibleColumns.Type, SeverityIterSort); sort.SetSortFunc (VisibleColumns.Project, ProjectIterSort); sort.SetSortFunc (VisibleColumns.File, FileIterSort); sort.SetSortFunc (VisibleColumns.Category, CategoryIterSort); view = new PadTreeView (sort); view.Selection.Mode = SelectionMode.Multiple; view.ShowExpanders = true; view.RulesHint = true; view.DoPopupMenu += ShowPopup; AddColumns (); LoadColumnsVisibility (); view.Columns [VisibleColumns.Type].SortColumnId = VisibleColumns.Type; view.Columns [VisibleColumns.Project].SortColumnId = VisibleColumns.Project; view.Columns [VisibleColumns.File].SortColumnId = VisibleColumns.File; view.Columns [VisibleColumns.Category].SortColumnId = VisibleColumns.Category; sw = new MonoDevelop.Components.CompactScrolledWindow (); sw.ShadowType = ShadowType.None; sw.Add (view); TaskService.Errors.TasksRemoved += ShowResults; TaskService.Errors.TasksAdded += TaskAdded; TaskService.Errors.TasksChanged += TaskChanged; TaskService.Errors.CurrentLocationTaskChanged += HandleTaskServiceErrorsCurrentLocationTaskChanged; IdeApp.Workspace.FirstWorkspaceItemOpened += OnCombineOpen; IdeApp.Workspace.LastWorkspaceItemClosed += OnCombineClosed; view.RowActivated += OnRowActivated; iconWarning = ImageService.GetIcon (Ide.Gui.Stock.Warning, Gtk.IconSize.Menu); iconError = ImageService.GetIcon (Ide.Gui.Stock.Error, Gtk.IconSize.Menu); iconInfo = ImageService.GetIcon (Ide.Gui.Stock.Information, Gtk.IconSize.Menu); iconEmpty = ImageService.GetIcon (Ide.Gui.Stock.Empty, Gtk.IconSize.Menu); control.Add1 (sw); logView = new LogView { Name = "buildOutput" }; control.Add2 (logView); control.ShowAll (); control.SizeAllocated += HandleControlSizeAllocated; sw.SizeAllocated += HandleSwSizeAllocated; logView.Visible = OutputViewVisible; logBtn.Active = OutputViewVisible; // Load existing tasks foreach (TaskListEntry t in TaskService.Errors) { AddTask (t); } } public override void Dispose () { errorBtn.Toggled -= FilterChanged; warnBtn.Toggled -= FilterChanged; msgBtn.Toggled -= FilterChanged; logBtn.Toggled -= HandleTextLogToggled; if (BuildOutput.IsFeatureEnabled) buildLogBtn.Clicked -= HandleBinLogClicked; searchEntry.Entry.Changed -= searchPatternChanged; IdeApp.Workspace.FirstWorkspaceItemOpened -= OnCombineOpen; IdeApp.Workspace.LastWorkspaceItemClosed -= OnCombineClosed; IdeApp.ProjectOperations.StartBuild -= OnBuildStarted; IdeApp.ProjectOperations.StartClean -= OnBuildStarted; TaskService.Errors.TasksRemoved -= ShowResults; TaskService.Errors.TasksAdded -= TaskAdded; TaskService.Errors.TasksChanged -= TaskChanged; TaskService.Errors.CurrentLocationTaskChanged -= HandleTaskServiceErrorsCurrentLocationTaskChanged; buildOutput?.Dispose (); buildOutputViewContent?.Dispose (); buildOutputDoc?.Close (); // Set the model to null as it makes Gtk clean up faster if (view != null) { view.RowActivated -= OnRowActivated; view.Model = null; } if (control != null) { control.SizeAllocated -= HandleControlSizeAllocated; } if (sw != null) { sw.SizeAllocated -= HandleSwSizeAllocated; } base.Dispose (); } void HandleSwSizeAllocated (object o, SizeAllocatedArgs args) { if (!initialLogShow && OutputViewVisible) { var val = (double)((double)control.Position / (double)control.Allocation.Width); LogSeparatorPosition.Value = val; } } [GLib.ConnectBefore] void HandleControlSizeAllocated (object o, SizeAllocatedArgs args) { if (initialLogShow && OutputViewVisible) { SetInitialOutputViewSize (args.Allocation.Width); initialLogShow = false; } } public ProgressMonitor GetBuildProgressMonitor () { if (control == null) CreateControl (); var monitor = new AggregatedProgressMonitor (); monitor.AddFollowerMonitor (buildOutput.GetProgressMonitor ()); monitor.AddFollowerMonitor (logView.GetProgressMonitor ()); return monitor; } void HandleTaskServiceErrorsCurrentLocationTaskChanged (object sender, EventArgs e) { if (TaskService.Errors.CurrentLocationTask == null) { view.Selection.UnselectAll (); return; } TreeIter it; if (!view.Model.GetIterFirst (out it)) return; do { TaskListEntry t = (TaskListEntry)view.Model.GetValue (it, DataColumns.Task); if (t == TaskService.Errors.CurrentLocationTask) { view.Selection.SelectIter (it); view.ScrollToCell (view.Model.GetPath (it), view.Columns [0], false, 0, 0); it = filter.ConvertIterToChildIter (sort.ConvertIterToChildIter (it)); store.SetValue (it, DataColumns.Read, true); return; } } while (view.Model.IterNext (ref it)); } internal void SelectTaskListEntry (TaskListEntry taskListEntry) { TreeIter iter; if (!view.Model.GetIterFirst (out iter)) return; do { var t = (TaskListEntry)view.Model.GetValue (iter, DataColumns.Task); if (t == taskListEntry) { view.Selection.SelectIter (iter); view.ScrollToCell (view.Model.GetPath (iter), view.Columns [0], false, 0, 0); return; } } while (view.Model.IterNext (ref iter)); } void LoadColumnsVisibility () { var columns = PropertyService.Get (restoreID, string.Join (";", Enumerable.Repeat ("TRUE", view.Columns.Length))); var tokens = columns.Split (new [] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (view.Columns.Length == tokens.Length) { for (int i = 0; i < tokens.Length; i++) { bool visible; if (bool.TryParse (tokens [i], out visible)) view.Columns [i].Visible = visible; } } } void ShowPopup (Gdk.EventButton evt) { var menu = new ContextMenu (); var help = new ContextMenuItem (GettextCatalog.GetString ("Go to _Reference")); help.Clicked += OnShowReference; menu.Add (help); if (BuildOutput.IsFeatureEnabled) { var goBuild = new ContextMenuItem (GettextCatalog.GetString ("Go to _Log")); goBuild.Clicked += async (s, e) => await OnGoToLog (s, e); menu.Add (goBuild); } var jump = new ContextMenuItem (GettextCatalog.GetString ("_Go to Task")); jump.Clicked += OnTaskJumpto; menu.Add (jump); var columnsMenu = new ColumnSelectorMenu (view, restoreID, GettextCatalog.GetString ("Type"), GettextCatalog.GetString ("Validity")); menu.Add (new SeparatorContextMenuItem ()); var copy = new ContextMenuItem (GettextCatalog.GetString ("_Copy")); copy.Clicked += OnTaskCopied; menu.Add (copy); menu.Add (new SeparatorContextMenuItem ()); var columns = new ContextMenuItem (GettextCatalog.GetString ("Columns")); columns.SubMenu = columnsMenu; menu.Add (columns); help.Sensitive = copy.Sensitive = jump.Sensitive = view.Selection != null && view.Selection.CountSelectedRows () > 0 && view.IsAColumnVisible (); // Disable Help and Go To if multiple rows selected. if (help.Sensitive && view.Selection.CountSelectedRows () > 1) { help.Sensitive = false; jump.Sensitive = false; } string dummyString; help.Sensitive &= GetSelectedErrorReference (out dummyString); menu.Show (view, evt); } async Task OnGoToLog (object o, EventArgs args) { var rows = view.Selection.GetSelectedRows (); if (!rows.Any ()) return; TreeIter iter, sortedIter; if (view.Model.GetIter (out sortedIter, rows [0])) { iter = filter.ConvertIterToChildIter (sort.ConvertIterToChildIter (sortedIter)); store.SetValue (iter, DataColumns.Read, true); TaskListEntry task = store.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task != null) { OpenBuildOutputViewDocument (); if (task.Severity == TaskSeverity.Error) { await buildOutputViewContent.GoToError (task.Message, task.GetProjectWithExtension ()); } else if (task.Severity == TaskSeverity.Warning) { await buildOutputViewContent.GoToWarning (task.Message, task.GetProjectWithExtension ()); } else if (task.Severity == TaskSeverity.Information) { await buildOutputViewContent.GoToMessage (task.Message, task.GetProjectWithExtension ()); } } } } TaskListEntry SelectedTask { get { TreeIter iter; var rows = view.Selection.GetSelectedRows (); if (rows.Any () && view.Model.GetIter (out iter, rows[0])) return view.Model.GetValue (iter, DataColumns.Task) as TaskListEntry; return null; // no one selected } } IEnumerable<TaskListEntry> GetSelectedTasks () { TreeIter iter; foreach (var row in view.Selection.GetSelectedRows ()) { if (view.Model.GetIter (out iter, row)) { var task = view.Model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task != null) yield return task; } } } [CommandHandler (EditCommands.Copy)] protected void OnCopy () { OnTaskCopied (null, null); } void OnTaskCopied (object o, EventArgs args) { var selectedTasks = GetSelectedTasks ().ToArray (); if (!selectedTasks.Any ()) return; var text = new StringBuilder (); for (int i = 0; i < selectedTasks.Length; i++) { if (i > 0) text.Append (Environment.NewLine); TaskListEntry task = selectedTasks [i]; if (!string.IsNullOrEmpty (task.FileName)) { text.Append (task.FileName); if (task.Line >= 1) { text.Append ("(").Append (task.Column); if (task.Column >= 0) text.Append (",").Append (task.Column); text.Append (")"); } text.Append (": "); } text.Append (task.Severity.ToString ()); if (!string.IsNullOrEmpty (task.Code)) { text.Append (" ").Append (task.Code); } text.Append (": "); text.Append (task.Description); if (task.WorkspaceObject != null) text.Append (" (").Append (task.WorkspaceObject.Name).Append (")"); if (!string.IsNullOrEmpty (task.Category)) { text.Append (" ").Append (task.Category); } } clipboard = Clipboard.Get (Gdk.Atom.Intern ("CLIPBOARD", false)); clipboard.Text = text.ToString (); clipboard = Clipboard.Get (Gdk.Atom.Intern ("PRIMARY", false)); clipboard.Text = text.ToString (); } void OnShowReference (object o, EventArgs args) { string reference = null; if (GetSelectedErrorReference (out reference) && reference != null) DesktopService.ShowUrl (reference); } bool GetSelectedErrorReference (out string reference) { string webRequest = "http://google.com/search?q="; TaskListEntry task = SelectedTask; if (task != null && task.HasDocumentationLink ()) { reference = task.DocumentationLink; return true; } if (task != null && !string.IsNullOrEmpty (task.HelpKeyword)) { reference = webRequest + System.Web.HttpUtility.UrlEncode (task.HelpKeyword); return true; } if (task != null && !string.IsNullOrEmpty (task.Code)) { reference = webRequest + System.Web.HttpUtility.UrlEncode (task.Code); return true; } reference = null; return false; } void OnTaskJumpto (object o, EventArgs args) { var rows = view.Selection.GetSelectedRows (); if (!rows.Any ()) return; TreeIter iter, sortedIter; if (view.Model.GetIter (out sortedIter, rows [0])) { iter = filter.ConvertIterToChildIter (sort.ConvertIterToChildIter (sortedIter)); store.SetValue (iter, DataColumns.Read, true); TaskListEntry task = store.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task != null) { TaskService.ShowStatus (task); task.JumpToPosition (); TaskService.Errors.CurrentLocationTask = task; IdeApp.Workbench.ActiveLocationList = TaskService.Errors; } } } void AddColumns () { CellRendererImage iconRender = new CellRendererImage (); Gtk.CellRendererToggle toggleRender = new Gtk.CellRendererToggle (); toggleRender.Toggled += new ToggledHandler (ItemToggled); TreeViewColumn col; col = view.AppendColumn ("!", iconRender, "image", DataColumns.Type); col = view.AppendColumn ("", toggleRender); col.SetCellDataFunc (toggleRender, new Gtk.TreeCellDataFunc (ToggleDataFunc)); col = view.AppendColumn (GettextCatalog.GetString ("Line"), view.TextRenderer); col.SetCellDataFunc (view.TextRenderer, new Gtk.TreeCellDataFunc (LineDataFunc)); var descriptionCellRenderer = new DescriptionCellRendererText (); view.RegisterRenderForFontChanges (descriptionCellRenderer); var descriptionCol = view.AppendColumn (GettextCatalog.GetString ("Description"), descriptionCellRenderer); descriptionCol.SetCellDataFunc (descriptionCellRenderer, new Gtk.TreeCellDataFunc (DescriptionDataFunc)); descriptionCol.Resizable = true; descriptionCellRenderer.PreferedMaxWidth = IdeApp.Workbench.RootWindow.Allocation.Width / 3; descriptionCellRenderer.WrapWidth = descriptionCellRenderer.PreferedMaxWidth; descriptionCellRenderer.WrapMode = Pango.WrapMode.Word; col = view.AppendColumn (GettextCatalog.GetString ("File"), view.TextRenderer); col.SetCellDataFunc (view.TextRenderer, new Gtk.TreeCellDataFunc (FileDataFunc)); col.Resizable = true; col = view.AppendColumn (GettextCatalog.GetString ("Project"), view.TextRenderer); col.SetCellDataFunc (view.TextRenderer, new Gtk.TreeCellDataFunc (ProjectDataFunc)); col.Resizable = true; col = view.AppendColumn (GettextCatalog.GetString ("Path"), view.TextRenderer); col.SetCellDataFunc (view.TextRenderer, new Gtk.TreeCellDataFunc (PathDataFunc)); col.Resizable = true; col = view.AppendColumn (GettextCatalog.GetString ("Category"), view.TextRenderer); col.SetCellDataFunc (view.TextRenderer, new Gtk.TreeCellDataFunc (CategoryDataFunc)); col.Resizable = true; } static void ToggleDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererToggle toggleRenderer = (Gtk.CellRendererToggle)cell; TaskListEntry task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) { toggleRenderer.Visible = false; return; } toggleRenderer.Active = task.Completed; } static void LineDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererText textRenderer = (Gtk.CellRendererText)cell; TaskListEntry task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) { textRenderer.Text = ""; return; } SetText (textRenderer, model, iter, task, task.Line != 0 ? task.Line.ToString () : ""); } static void DescriptionDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { var textRenderer = (CellRendererText)cell; TaskListEntry task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; var text = model.GetValue (iter, DataColumns.Description) as string; if (task == null) { if (model.IterParent (out iter, iter)) { task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) { textRenderer.Text = ""; return; } } else { textRenderer.Text = ""; return; } } SetText (textRenderer, model, iter, task, text); } static void FileDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererText textRenderer = (Gtk.CellRendererText)cell; TaskListEntry task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) { textRenderer.Text = ""; return; } SetText (textRenderer, model, iter, task, task.GetFile ()); } static void ProjectDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererText textRenderer = (Gtk.CellRendererText)cell; TaskListEntry task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) { textRenderer.Text = ""; return; } SetText (textRenderer, model, iter, task, task.GetProject ()); } static void PathDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererText textRenderer = (Gtk.CellRendererText)cell; TaskListEntry task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) { textRenderer.Text = ""; return; } SetText (textRenderer, model, iter, task, task.GetPath ()); } static void CategoryDataFunc (Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { Gtk.CellRendererText textRenderer = (Gtk.CellRendererText)cell; var task = model.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) { textRenderer.Text = ""; return; } SetText (textRenderer, model, iter, task, task.Category ?? ""); } static void SetText (CellRendererText textRenderer, TreeModel model, TreeIter iter, TaskListEntry task, string text) { textRenderer.Text = text; textRenderer.Weight = (int)((bool)model.GetValue (iter, DataColumns.Read) ? Pango.Weight.Normal : Pango.Weight.Bold); textRenderer.Strikethrough = task.Completed; } void OnCombineOpen(object sender, EventArgs e) { Clear(); } void OnCombineClosed(object sender, EventArgs e) { Clear(); buildOutput.Dispose (); if (buildOutputViewContent != null) { buildOutputViewContent.Dispose (); buildOutputViewContent = null; } buildOutputDoc?.Close (); buildOutput = new BuildOutput (); } void OnBuildStarted (object sender, EventArgs e) { buildOutput.Clear (); } void OnRowActivated (object o, RowActivatedArgs args) { OnTaskJumpto (null, null); } public CompilerResults CompilerResults = null; void FilterChanged (object sender, EventArgs e) { ShowErrors.Value = errorBtn.Active; ShowWarnings.Value = warnBtn.Active; ShowMessages.Value = msgBtn.Active; filter.Refilter (); } internal void SetFilter (bool showErrors, bool showWarnings, bool showMessages) { errorBtn.Active = showErrors; warnBtn.Active = showWarnings; msgBtn.Active = showMessages; } bool FilterTasks (TreeModel model, TreeIter iter) { bool canShow = false; try { TaskListEntry task = store.GetValue (iter, DataColumns.Task) as TaskListEntry; if (task == null) return true; if (task.Severity == TaskSeverity.Error && errorBtn.Active) canShow = true; else if (task.Severity == TaskSeverity.Warning && warnBtn.Active) canShow = true; else if (task.Severity == TaskSeverity.Information && msgBtn.Active) canShow = true; if (canShow && !string.IsNullOrWhiteSpace (currentSearchPattern)) { canShow = (task.Description != null && task.Description.IndexOf (currentSearchPattern, StringComparison.OrdinalIgnoreCase) != -1) || (task.Code != null && task.Code.IndexOf (currentSearchPattern, StringComparison.OrdinalIgnoreCase) != -1) || (task.FileName != null && task.FileName.FileName.IndexOf (currentSearchPattern, StringComparison.OrdinalIgnoreCase) != -1) || (task.WorkspaceObject != null && task.WorkspaceObject.Name != null && task.WorkspaceObject.Name.IndexOf (currentSearchPattern, StringComparison.OrdinalIgnoreCase) != -1) || (task.Category != null && task.Category.IndexOf (currentSearchPattern, StringComparison.OrdinalIgnoreCase) != -1); } } catch { //Not yet fully added return false; } return canShow; } public void ShowResults (object sender, EventArgs e) { Clear(); AddTasks (TaskService.Errors); } private void Clear() { errorCount = warningCount = infoCount = 0; if (view.IsRealized) view.ScrollToPoint (0, 0); store.Clear (); tasks.Clear (); UpdateErrorsNum (); UpdateWarningsNum (); UpdateMessagesNum (); UpdatePadIcon (); } void TaskChanged (object sender, TaskEventArgs e) { this.view.QueueDraw (); } void TaskAdded (object sender, TaskEventArgs e) { AddTasks (e.Tasks); } public void AddTasks (IEnumerable<TaskListEntry> tasks) { int n = 1; foreach (TaskListEntry t in tasks) { AddTaskInternal (t); if ((n++ % 100) == 0) { // Adding many tasks is a bit slow, so refresh the // ui at every block of 100. DispatchService.RunPendingEvents (); } } filter.Refilter (); } public void AddTask (TaskListEntry t) { AddTaskInternal (t); filter.Refilter (); } void AddTaskInternal (TaskListEntry t) { if (tasks.Contains (t)) return; Xwt.Drawing.Image stock; switch (t.Severity) { case TaskSeverity.Error: stock = iconError; errorCount++; UpdateErrorsNum (); break; case TaskSeverity.Warning: stock = iconWarning; warningCount++; UpdateWarningsNum (); break; default: stock = iconInfo; infoCount++; UpdateMessagesNum (); break; } tasks [t] = t; var indexOfNewLine = t.Description.IndexOfAny (new [] { '\n', '\r' }); if (indexOfNewLine != -1) { var iter = store.AppendValues (stock, false, t, t.Description.Remove (indexOfNewLine)); store.AppendValues (iter, iconEmpty, false, null, t.Description); } else { store.AppendValues (stock, false, t, t.Description); } UpdatePadIcon (); } void UpdateErrorsNum () { errorBtnLbl.Text = " " + string.Format(GettextCatalog.GetPluralString("{0} Error", "{0} Errors", errorCount), errorCount); errorBtn.Accessible.SetTitle (errorBtnLbl.Text); } void UpdateWarningsNum () { warnBtnLbl.Text = " " + string.Format(GettextCatalog.GetPluralString("{0} Warning", "{0} Warnings", warningCount), warningCount); warnBtn.Accessible.SetTitle (warnBtnLbl.Text); } void UpdateMessagesNum () { msgBtnLbl.Text = " " + string.Format(GettextCatalog.GetPluralString("{0} Message", "{0} Messages", infoCount), infoCount); msgBtn.Accessible.SetTitle (msgBtnLbl.Text); } void UpdatePadIcon () { if (errorCount > 0) Window.Icon = "md-errors-list-has-errors"; else if (warningCount > 0) Window.Icon = "md-errors-list-has-warnings"; else Window.Icon = "md-errors-list"; } private void ItemToggled (object o, ToggledArgs args) { Gtk.TreeIter iter; if (view.Model.GetIterFromString (out iter, args.Path)) { TaskListEntry task = (TaskListEntry)view.Model.GetValue (iter, DataColumns.Task); task.Completed = !task.Completed; TaskService.FireTaskToggleEvent (this, new TaskEventArgs (task)); } } static int SeverityIterSort(TreeModel model, TreeIter a, TreeIter z) { TaskListEntry aTask = model.GetValue(a, DataColumns.Task) as TaskListEntry, zTask = model.GetValue(z, DataColumns.Task) as TaskListEntry; return (aTask != null && zTask != null) ? aTask.Severity.CompareTo(zTask.Severity) : 0; } static int ProjectIterSort (TreeModel model, TreeIter a, TreeIter z) { TaskListEntry aTask = model.GetValue (a, DataColumns.Task) as TaskListEntry, zTask = model.GetValue (z, DataColumns.Task) as TaskListEntry; return (aTask != null && zTask != null) ? string.Compare (aTask.GetProject (), zTask.GetProject (), StringComparison.Ordinal) : 0; } static int FileIterSort (TreeModel model, TreeIter a, TreeIter z) { TaskListEntry aTask = model.GetValue (a, DataColumns.Task) as TaskListEntry, zTask = model.GetValue (z, DataColumns.Task) as TaskListEntry; return (aTask != null && zTask != null) ? aTask.FileName.CompareTo (zTask.FileName) : 0; } static int CategoryIterSort (TreeModel model, TreeIter a, TreeIter z) { TaskListEntry aTask = model.GetValue (a, DataColumns.Task) as TaskListEntry, zTask = model.GetValue (z, DataColumns.Task) as TaskListEntry; return (aTask?.Category != null && zTask?.Category != null) ? string.Compare (aTask.Category, zTask.Category, StringComparison.Ordinal) : 0; } internal void FocusOutputView () { HandleBinLogClicked (this, EventArgs.Empty); } void HandleTextLogToggled (object sender, EventArgs e) { var visible = logBtn.Active; OutputViewVisible.Value = visible; logView.Visible = visible; SetInitialOutputViewSize (control.Allocation.Width); if (visible) { Counters.BuildLogShown++; } } void SetInitialOutputViewSize (int controlWidth) { double relPos = LogSeparatorPosition; int pos = (int)(controlWidth * relPos); pos = Math.Max(30, Math.Min(pos, controlWidth - 30)); control.Position = pos; } Document buildOutputDoc; void HandleBinLogClicked (object sender, EventArgs e) { if (BuildOutput.IsFeatureEnabled) { OpenBuildOutputViewDocument (); } } void OpenBuildOutputViewDocument () { if (buildOutputViewContent == null) { buildOutputViewContent = new BuildOutputViewContent (buildOutput); buildOutputDoc = IdeApp.Workbench.OpenDocument (buildOutputViewContent, true); buildOutputDoc.Closed += BuildOutputDocClosed; } else if (buildOutputDoc != null) { buildOutputDoc.Select (); } } void BuildOutputDocClosed (object sender, EventArgs e) { buildOutputViewContent?.Dispose (); buildOutputDoc.Closed -= BuildOutputDocClosed; buildOutputViewContent = null; buildOutputDoc = null; } class DescriptionCellRendererText : CellRendererText { public int PreferedMaxWidth { get; set; } public override void GetSize (Widget widget, ref Gdk.Rectangle cell_area, out int x_offset, out int y_offset, out int width, out int height) { int originalWrapWidth = WrapWidth; WrapWidth = -1; // First calculate Width with WrapWidth=-1 which will give us // Width of text in one line(without wrapping) base.GetSize (widget, ref cell_area, out x_offset, out y_offset, out width, out height); int oneLineWidth = width; WrapWidth = originalWrapWidth; // originalWrapWidth(aka WrapWidth) equals to actual width of Column if oneLineWidth is bigger // then column width/height we must recalculate, because Height is atm for one line // and not multipline that WrapWidth creates... if (oneLineWidth > originalWrapWidth) { base.GetSize (widget, ref cell_area, out x_offset, out y_offset, out width, out height); } width = Math.Min (oneLineWidth, PreferedMaxWidth); } } } internal static class TaskListEntryExtensions { public static string GetPath (this TaskListEntry task) { if (task.WorkspaceObject != null) return FileService.AbsoluteToRelativePath (task.WorkspaceObject.BaseDirectory, task.FileName); return task.FileName; } public static string GetProject (this TaskListEntry task) { return (task != null && task.WorkspaceObject is SolutionFolderItem) ? task.WorkspaceObject.Name : string.Empty; } public static string GetProjectWithExtension (this TaskListEntry task) { return (task != null && task.WorkspaceObject is SolutionItem) ? Path.GetFileName (((SolutionItem)task.WorkspaceObject).FileName) : string.Empty; } public static string GetFile (this TaskListEntry task) { string tmpPath = ""; string fileName = ""; try { tmpPath = GetPath (task); fileName = Path.GetFileName (tmpPath); } catch (Exception) { fileName = tmpPath; } return fileName; } } }
lgpl-2.1
actsasflinn/ruby-tokyotyrant
spec/tokyo_tyrant_balancer_table_spec.rb
5567
require 'pathname' require Pathname(__FILE__).dirname.join('spec_base') unless $root describe TokyoTyrant::Balancer::Table, "with an open database" do before do @db = TokyoTyrant::Balancer::Table.new(['127.0.0.1:45001']) @db.clear end it "should not be nil" do @db.should.not.be.nil end it "should close" do @db.close.should.be.true begin @db.close rescue => e e.message.should == 'close error: invalid operation' end end it "should optimize" do @db.optimize.should.be.true end it "should save a value" do value = { 'lettuce' => 'Red Leaf', 'dressing' => 'ranch', 'extra' => 'bacon bits' } @db['salad'] = value @db['salad'].should == value end it "should return a value" do value = { 'lettuce' => 'Red Leaf', 'dressing' => 'ranch', 'extra' => 'bacon bits' } @db['salad'] = value @db['salad'].should == value end it "should accept binary data" do s = "mango#{0.chr}salsa" h = { s => s } @db.put(s, h).should.be.true @db[s].should.equal(h) end it "should out a value" do k = 'tomato' @db[k] = { 'color' => 'red', 'variety' => 'beefy' } @db.out(k).should.be.true @db[k].should.be.nil @db.out(k).should.be.false end it "should check a key" do k = 'fruit' @db[k] = { 'name' => 'banana', 'code' => '4011' } @db.check(k).should.be.true @db.out(k) @db.check(k).should.be.false end it "should get forward matching keys" do @db['apples/royalgala'] = { 'code' => '4173', 'color' => 'red-yellow' } @db['apples/grannysmith'] = { 'code' => '4139', 'color' => 'green' } @db['bananas/yellow'] = { 'code' => '4011', 'color' => 'yellow' } @db['oranges/shamouti'] = { 'code' => '3027', 'color' => 'orange' } @db['grapefruit/deepred'] = { 'code' => '4288', 'color' => 'yellow/pink' } @db.fwmkeys('apples').sort.should == ["apples/grannysmith", "apples/royalgala"] end it "should delete forward matching keys" do @db['apples/royalgala'] = { 'code' => '4173', 'color' => 'red-yellow' } @db['apples/grannysmith'] = { 'code' => '4139', 'color' => 'green' } @db['bananas/yellow'] = { 'code' => '4011', 'color' => 'yellow' } @db['oranges/shamouti'] = { 'code' => '3027', 'color' => 'orange' } @db['grapefruit/deepred'] = { 'code' => '4288', 'color' => 'yellow/pink' } @db.delete_keys_with_prefix('apples').should == nil @db.fwmkeys('apples').should.be.empty @db.keys.sort.should == ['bananas/yellow', 'grapefruit/deepred', 'oranges/shamouti'] end it "should get all keys" do keys = %w[appetizers entree dessert] values = [{ 'cheap' => 'chips', 'expensive' => 'sample everything platter' }, { 'cheap' => 'hoagie', 'expensive' => 'steak' }, { 'cheap' => 'water ice', 'expensive' => 'cheesecake' }] keys.each_with_index do |k,i| @db[k] = values[i] end @db.keys.should == keys end it "should get all values" do keys = %w[appetizers entree dessert] values = [{ 'cheap' => 'chips', 'expensive' => 'sample everything platter' }, { 'cheap' => 'hoagie', 'expensive' => 'steak' }, { 'cheap' => 'water ice', 'expensive' => 'cheesecake' }] keys.each_with_index do |k,i| @db[k] = values[i] end @db.values.should == values end it "should vanish all records" do @db['chocolate'] = { 'type' => 'dark' } @db['tea'] = { 'type' => 'earl grey' } @db.empty?.should.be.false @db.vanish.should.be.true @db.empty?.should.be.true end it "should count records" do @db['hummus'] = { 'ingredients' => 'chickpeas,garlic' } @db['falafel'] = { 'ingredients' => 'chickpeas,herbs' } @db.rnum.should == 2 end it "should fetch a record" do @db.out('beer') @db.fetch('beer'){{ 'import' => 'heineken' }}.should == { 'import' => 'heineken' } @db['beer'].should == { 'import' => 'heineken' } @db.fetch('beer'){{ 'import' => 'becks' }}.should == { 'import' => 'heineken' } end it "should add serialized integer values" do key = 'counter' @db.out(key) @db[key] = { 'title' => 'Bean Counter' } @db.add_int(key, 1).should == 1 @db.add_int(key, 1).should == 2 @db.get_int(key).should == 2 @db[key].should == { 'title' => 'Bean Counter', '_num' => "2" } end it "should increment integer values" do key = 'counter' @db.out(key) @db[key] = { 'title' => 'Bean Counter' } @db.increment(key).should == 1 @db.increment(key, 2).should == 3 @db.get_int(key).should == 3 @db[key].should == { 'title' => 'Bean Counter', '_num' => "3" } end it "should add serialized double values" do key = 'counter' @db.out(key) @db[key] = { 'title' => 'Bean Counter' } @db.add_double(key, 1.0).should.be.close?(1.0, 0.005) @db.add_double(key, 1.0).should.be.close?(2.0, 0.005) @db.get_double(key).should.be.close?(2.0, 0.005) @db[key].should == { 'title' => 'Bean Counter', '_num' => "2" } end it "should set an index" do key = 'counter' 50.times do |i| @db["key#{i}"] = { 'title' => %w{rice beans corn}.sort_by{rand}.first, 'description' => 'a whole protein' } end @db.set_index('title', :lexical).should.be.true end it "should serialize objects that respond to to_tokyo_tyrant" do class Thing def to_tokyo_tyrant "success" end end @db["to_tokyo_tyrant"] = { "thing" => Thing.new } @db["to_tokyo_tyrant"].should == { "thing" => "success" } end end
lgpl-2.1
herculeshssj/unirio-ppgi-goalservice
GoalService/serviceDiscovery/src/main/ch/epfl/qosdisc/repmgnt/datastructures/QoSReportedParameter.java
1182
package ch.epfl.qosdisc.repmgnt.datastructures; /** * A reported value for a certain QoS parameter. * This class is designed such that we can further stored different tpyes of reported values in it * @author lhvu * */ public class QoSReportedParameter { private int qosConceptID; private double reportedConformanceValue; private double observedValue; /** * @param qosConceptID * @param reportedConformanceValue */ public QoSReportedParameter(int qosConceptID, double reportedValue, double advertisedValue) { this.qosConceptID=qosConceptID; this.reportedConformanceValue=reportedValue; this.observedValue=advertisedValue; } public int getQosConceptID() { return qosConceptID; } public void setQosConceptID(int qosConceptID) { this.qosConceptID = qosConceptID; } public double getReportedConfValue() { return reportedConformanceValue; } public void setReportedConfValue(double reportedConformanceValue) { this.reportedConformanceValue = reportedConformanceValue; } public double getObservedValue() { return observedValue; } public void setAdvertisedValue(double observedValue) { this.observedValue = observedValue; } }
lgpl-2.1
tiger-young/ecallaShop
temp/compiled/recommend_new.lbi.php
1988
<?php if ($this->_var['new_goods']): ?> <?php if ($this->_var['cat_rec_sign'] != 1): ?> <div class="box "> <div class="tit_2"><span><a href="search.php?intro=new" class="f6">New Arrivals</a></span> <a href="search.php?intro=new" class="clear more right">See More »</a> </div> <div class="blank"></div> <div id="show_new_area" class="clearfix"> <?php endif; ?> <?php $_from = $this->_var['new_goods']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); }; $this->push_vars('', 'goods_0_73185200_1409215598');if (count($_from)): foreach ($_from AS $this->_var['goods_0_73185200_1409215598']): ?> <div class="goodsItem"> <a href="<?php echo $this->_var['goods_0_73185200_1409215598']['url']; ?>"><img src="<?php echo $this->_var['goods_0_73185200_1409215598']['thumb']; ?>" alt="<?php echo htmlspecialchars($this->_var['goods_0_73185200_1409215598']['name']); ?>" class="goodsimg" /></a><br /> <p class="f1"><a href="<?php echo $this->_var['goods_0_73185200_1409215598']['url']; ?>" title="<?php echo htmlspecialchars($this->_var['goods_0_73185200_1409215598']['name']); ?>"><?php echo $this->_var['goods_0_73185200_1409215598']['short_style_name']; ?></a></p> <font class="market"><?php echo $this->_var['goods_0_73185200_1409215598']['market_price']; ?></font><br /> <font class="f1"> <?php if ($this->_var['goods_0_73185200_1409215598']['promote_price'] != ""): ?> <?php echo $this->_var['goods_0_73185200_1409215598']['promote_price']; ?> <?php else: ?> <?php echo $this->_var['goods_0_73185200_1409215598']['shop_price']; ?> <?php endif; ?> </font> </div> <?php endforeach; endif; unset($_from); ?><?php $this->pop_vars();; ?> <?php if ($this->_var['cat_rec_sign'] != 1): ?> </div> </div> <div class="blank"></div> <?php endif; ?> <?php endif; ?>
lgpl-2.1
TheHunter/PersistentLayer.Raven
PersistentLayer.Raven/CustomExtensions.cs
571
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using Raven.Abstractions.Data; namespace PersistentLayer.Raven { /// <summary> /// /// </summary> public static class CustomExtensions { /// <summary> /// /// </summary> /// <param name="etag"></param> /// <returns></returns> public static RavenEtag ToRavenEtag(this Etag etag) { return new RavenEtag(etag); } } }
lgpl-2.1
plast-lab/soot
src/main/java/soot/tagkit/AbstractAnnotationElemTypeSwitch.java
2163
package soot.tagkit; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program 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 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public abstract class AbstractAnnotationElemTypeSwitch implements IAnnotationElemTypeSwitch { Object result; @Override public void caseAnnotationAnnotationElem(AnnotationAnnotationElem v) { defaultCase(v); } @Override public void caseAnnotationArrayElem(AnnotationArrayElem v) { defaultCase(v); } @Override public void caseAnnotationBooleanElem(AnnotationBooleanElem v) { defaultCase(v); } @Override public void caseAnnotationClassElem(AnnotationClassElem v) { defaultCase(v); } @Override public void caseAnnotationDoubleElem(AnnotationDoubleElem v) { defaultCase(v); } @Override public void caseAnnotationEnumElem(AnnotationEnumElem v) { defaultCase(v); } @Override public void caseAnnotationFloatElem(AnnotationFloatElem v) { defaultCase(v); } @Override public void caseAnnotationIntElem(AnnotationIntElem v) { defaultCase(v); } @Override public void caseAnnotationLongElem(AnnotationLongElem v) { defaultCase(v); } @Override public void caseAnnotationStringElem(AnnotationStringElem v) { defaultCase(v); } @Override public void defaultCase(Object object) { } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } }
lgpl-2.1
danielpunkass/tinymce
src/core/test/ts/browser/InlineEditorRemoveTest.ts
1205
import { Pipeline, Logger, Chain, UiFinder } from '@ephox/agar'; import Theme from 'tinymce/themes/modern/Theme'; import { UnitTest } from '@ephox/bedrock'; import { Editor as McEditor, ApiChains } from '@ephox/mcagar'; import { Body } from '@ephox/sugar'; UnitTest.asynctest('browser.tinymce.core.InlineEditorRemoveTest', (success, failure) => { Theme(); const settings = { inline: true, skin_url: '/project/js/tinymce/skins/lightgray' }; const cAssertBogusNotExist = Chain.async((val, next, die) => { UiFinder.findIn(Body.body(), '[data-mce-bogus]').fold( () => { next(val); }, () => { die('Should not be any data-mce-bogus tags present'); } ); }); const cRemoveEditor = Chain.op((editor: any) => editor.remove()); Pipeline.async({}, [ Logger.t('Removing inline editor should remove all data-mce-bogus tags', Chain.asStep({}, [ McEditor.cFromHtml('<div></div>', settings), ApiChains.cSetRawContent('<p data-mce-bogus="all">b</p><p data-mce-bogus="1">b</p>'), cRemoveEditor, cAssertBogusNotExist, McEditor.cRemove, ]), ) ], function () { success(); }, failure); });
lgpl-2.1
infchem/RealRobots
src/main/java/infchem/realrobots/leonardo/LeonardoVPLMessage.java
2148
package infchem.realrobots.leonardo; import java.io.IOException; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTSizeTracker; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import io.netty.buffer.ByteBuf; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.relauncher.Side; public class LeonardoVPLMessage implements IMessage { public int callbackID; private ItemStack[] is = new ItemStack[10]; private String playername; private int x; private int y; private int z; public LeonardoVPLMessage() {} public LeonardoVPLMessage(ItemStack[] itemStacks,String playername,int x,int y,int z) { this.is = itemStacks; this.playername = playername; this.x=x; this.y=y; this.z=z; } @Override public void fromBytes(ByteBuf buf) { for(int i=0;i<10;i++) { this.is[i] = ByteBufUtils.readItemStack(buf); } this.playername=ByteBufUtils.readUTF8String(buf); this.x=buf.readInt(); this.y=buf.readInt(); this.z=buf.readInt(); } @Override public void toBytes(ByteBuf buf) { for(int i=0;i<10;i++) { ByteBufUtils.writeItemStack(buf, this.is[i]); } ByteBufUtils.writeUTF8String(buf, playername); buf.writeInt(x); buf.writeInt(y); buf.writeInt(z); } public static class Handler implements IMessageHandler<LeonardoVPLMessage, IMessage> { @Override public IMessage onMessage(LeonardoVPLMessage message, MessageContext ctx) { Runnable r = new RunnableLeonardo(message.is,message.playername,message.x,message.y,message.z); new Thread(r).start(); return null; // no response in this case } } }
lgpl-2.1
bakaiadam/collaborative_qt_creator
src/libs/cplusplus/PreprocessorEnvironment.cpp
7231
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ /* Copyright 2005 Roberto Raggi <roberto@kdevelop.org> Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE KDEVELOP TEAM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "PreprocessorEnvironment.h" #include "Macro.h" #include <cstring> using namespace CPlusPlus; Environment::Environment() : currentLine(0), hideNext(false), _macros(0), _allocated_macros(0), _macro_count(-1), _hash(0), _hash_count(401) { } Environment::~Environment() { if (_macros) { qDeleteAll(firstMacro(), lastMacro()); free(_macros); } if (_hash) free(_hash); } unsigned Environment::macroCount() const { return _macro_count + 1; } Macro *Environment::macroAt(unsigned index) const { return _macros[index]; } Macro *Environment::bind(const Macro &__macro) { Q_ASSERT(! __macro.name().isEmpty()); Macro *m = new Macro (__macro); m->_hashcode = hashCode(m->name()); if (++_macro_count == _allocated_macros) { if (! _allocated_macros) _allocated_macros = 401; else _allocated_macros <<= 1; _macros = reinterpret_cast<Macro **>(realloc(_macros, sizeof(Macro *) * _allocated_macros)); } _macros[_macro_count] = m; if (! _hash || _macro_count > (_hash_count >> 1)) { rehash(); } else { const unsigned h = m->_hashcode % _hash_count; m->_next = _hash[h]; _hash[h] = m; } return m; } void Environment::addMacros(const QList<Macro> &macros) { foreach (const Macro &macro, macros) { bind(macro); } } Macro *Environment::remove(const QByteArray &name) { Macro macro; macro.setName(name); macro.setHidden(true); macro.setFileName(currentFile); macro.setLine(currentLine); return bind(macro); } void Environment::reset() { if (_macros) { qDeleteAll(firstMacro(), lastMacro()); free(_macros); } if (_hash) free(_hash); _macros = 0; _allocated_macros = 0; _macro_count = -1; _hash = 0; _hash_count = 401; } bool Environment::isBuiltinMacro(const QByteArray &s) { if (s.length() != 8) return false; if (s[0] == '_') { if (s[1] == '_') { if (s[2] == 'D') { if (s[3] == 'A') { if (s[4] == 'T') { if (s[5] == 'E') { if (s[6] == '_') { if (s[7] == '_') { return true; } } } } } } else if (s[2] == 'F') { if (s[3] == 'I') { if (s[4] == 'L') { if (s[5] == 'E') { if (s[6] == '_') { if (s[7] == '_') { return true; } } } } } } else if (s[2] == 'L') { if (s[3] == 'I') { if (s[4] == 'N') { if (s[5] == 'E') { if (s[6] == '_') { if (s[7] == '_') { return true; } } } } } } else if (s[2] == 'T') { if (s[3] == 'I') { if (s[4] == 'M') { if (s[5] == 'E') { if (s[6] == '_') { if (s[7] == '_') { return true; } } } } } } } } return false; } Environment::iterator Environment::firstMacro() const { return _macros; } Environment::iterator Environment::lastMacro() const { return _macros + _macro_count + 1; } Macro *Environment::resolve(const QByteArray &name) const { if (! _macros) return 0; Macro *it = _hash[hashCode(name) % _hash_count]; for (; it; it = it->_next) { if (it->name() != name) continue; else if (it->isHidden()) return 0; else break; } return it; } unsigned Environment::hashCode(const QByteArray &s) { unsigned hash_value = 0; for (int i = 0; i < s.size (); ++i) hash_value = (hash_value << 5) - hash_value + s.at (i); return hash_value; } void Environment::rehash() { if (_hash) { free(_hash); _hash_count <<= 1; } _hash = reinterpret_cast<Macro **>(calloc(_hash_count, sizeof(Macro *))); for (iterator it = firstMacro(); it != lastMacro(); ++it) { Macro *m = *it; const unsigned h = m->_hashcode % _hash_count; m->_next = _hash[h]; _hash[h] = m; } }
lgpl-2.1
mivianmf/ocr-ia
src/ocr/controllers/DimensionReducer.java
29227
/* * NumberRecognition.java * * Created on Dec 7, 2011, 1:27:25 PM * * Description: Recognizes numbers. * * Copyright (C) Dec 7, 2011, Stephen L. Reed, Texai.org. * * This file is a translation from the OpenCV example http://www.shervinemami.info/numberRecognition.html, ported * to Java using the JavaCV library. Notable changes are the addition of the Apache Log4J framework and the * installation of image files in a data directory child of the working directory. Some of the code has * been expanded to make debugging easier. Expected results are 100% recognition of the lower3.txt test * image index set against the all10.txt training image index set. See http://en.wikipedia.org/wiki/Eigennumber * for a technical explanation of the algorithm. * * stephenreed@yahoo.com * * NumberRecognition 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 (subject to the "Classpath" exception * as provided in the LICENSE.txt file that accompanied this code). * * NumberRecognition 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 JavaCV. If not, see . * */ package ocr.controllers; import com.googlecode.javacpp.FloatPointer; import com.googlecode.javacpp.PointerPointer; import static com.googlecode.javacv.cpp.opencv_core.*; import com.googlecode.javacv.cpp.opencv_core.CvMat; import com.googlecode.javacv.cpp.opencv_core.CvSize; import com.googlecode.javacv.cpp.opencv_core.CvTermCriteria; import com.googlecode.javacv.cpp.opencv_core.IplImage; import static com.googlecode.javacv.cpp.opencv_legacy.*; /** * Recognizes numbers. * * @author Bruno, Mívian e Washington */ public class DimensionReducer { /** * the number of training numbers */ private int nTrainNumbers = 0; /** * the training number image array */ IplImage[] trainingNumberImgArr; /** * the test number image array */ //IplImage[] testNumberImgArr; /** * the number number array */ CvMat numberNumTruthMat; /** * the number of numbers */ int nNumbers; /** * the number of eigenvalues */ int nEigens = 0; /** * eigenvectors */ IplImage[] eigenVectArr; /** * eigenvalues */ CvMat eigenValMat; /** * the average image */ IplImage pAvgTrainImg; /** * the projected training numbers */ public CvMat projectedTrainNumberMat; /** * Constructs a new NumberRecognition instance. */ public DimensionReducer() { } /** * Trains from the data in the given training text index file, and store the * trained data into the file 'data/numberdata.xml'. * * @param trainingFileName the given training text index file */ public void reduce(IplImage[] trainingNumberImgArr, int nNumbers) { int i; this.nNumbers = nNumbers; this.trainingNumberImgArr = trainingNumberImgArr; nTrainNumbers = this.trainingNumberImgArr.length; // do Principal Component Analysis on the training numbers doPCA(); System.out.println("projecting the training numbers onto the PCA subspace"); // project the training numbers onto the PCA subspace projectedTrainNumberMat = cvCreateMat( nTrainNumbers, // rows nEigens, // cols CV_32FC1); // type, 32-bit float, 1 channel // initialize the training number matrix - for ease of debugging for (int i1 = 0; i1 < nTrainNumbers; i1++) { for (int j1 = 0; j1 < nEigens; j1++) { projectedTrainNumberMat.put(i1, j1, 0.0); } } System.out.println("created projectedTrainNumberMat with " + nTrainNumbers + " (nTrainNumbers) rows and " + nEigens + " (nEigens) columns"); if (nTrainNumbers < 5) { System.out.println("projectedTrainNumberMat contents:\n FAIL");// + oneChannelCvMatToString(projectedTrainNumberMat)); } final FloatPointer floatPointer = new FloatPointer(nEigens); for (i = 0; i < nTrainNumbers; i++) { cvEigenDecomposite( this.trainingNumberImgArr[i], // obj nEigens, // nEigObjs new PointerPointer(eigenVectArr), // eigInput (Pointer) 0, // ioFlags null, // userData (Pointer) pAvgTrainImg, // avg floatPointer); // coeffs (FloatPointer) if (nTrainNumbers < 5) { System.out.println("floatPointer: " + floatPointer.toString()); } for (int j1 = 0; j1 < nEigens; j1++) { projectedTrainNumberMat.put(i, j1, floatPointer.get(j1)); } } if (nTrainNumbers < 5) { System.out.println("projectedTrainNumberMat after cvEigenDecomposite:\n" + projectedTrainNumberMat); } // store the recognition data as an xml file //storeTrainingData(); // Save all the eigenvectors as numbers, so that they can be checked. //storeEigennumberImages(); } /** * Does the Principal Component Analysis, finding the average image and the * eigennumbers that represent any image in the given dataset. */ private void doPCA() { int i; CvTermCriteria calcLimit; CvSize numberImgSize = new CvSize(); // set the number of eigenvalues to use nEigens = nTrainNumbers - 1; System.out.println("allocating numbers for principal component analysis, using " + nEigens + (nEigens == 1 ? " eigenvalue" : " eigenvalues")); // allocate the eigenvector numbers numberImgSize.width(trainingNumberImgArr[0].width()); numberImgSize.height(trainingNumberImgArr[0].height()); eigenVectArr = new IplImage[nEigens]; for (i = 0; i < nEigens; i++) { eigenVectArr[i] = cvCreateImage( numberImgSize, // size IPL_DEPTH_32F, // depth 1); // channels } // allocate the eigenvalue array eigenValMat = cvCreateMat( 1, // rows nEigens, // cols CV_32FC1); // type, 32-bit float, 1 channel // allocate the averaged image pAvgTrainImg = cvCreateImage( numberImgSize, // size IPL_DEPTH_32F, // depth 1); // channels // set the PCA termination criterion calcLimit = cvTermCriteria( CV_TERMCRIT_ITER, // type nEigens, // max_iter 1); // epsilon System.out.println("computing average image, eigenvalues and eigenvectors"); // compute average image, eigenvalues, and eigenvectors cvCalcEigenObjects( nTrainNumbers, // nObjects new PointerPointer(trainingNumberImgArr), // input new PointerPointer(eigenVectArr), // output CV_EIGOBJ_NO_CALLBACK, // ioFlags 0, // ioBufSize null, // userData calcLimit, pAvgTrainImg, // avg eigenValMat.data_fl()); // eigVals System.out.println("normalizing the eigenvectors"); cvNormalize( eigenValMat, // src (CvArr) eigenValMat, // dst (CvArr) 1, // a 0, // b CV_L1, // norm_type null); // mask } /** * Recognizes the number in each of the test numbers given, and compares the * results with the truth. * * @param szFileTest the index file of test numbers */ public float[] recognize(IplImage imagem) { float[] projectedTestNumber; // project the test image onto the PCA subspace projectedTestNumber = new float[nEigens]; cvEigenDecomposite( imagem, // obj nEigens, // nEigObjs new PointerPointer(eigenVectArr), // eigInput (Pointer) 0, // ioFlags null, // userData pAvgTrainImg, // avg projectedTestNumber); // coeffs return projectedTestNumber; } /*public void recognizeFileList(final String szFileTest) { System.out.println("==========================================="); System.out.println("recognizing numbers indexed from " + szFileTest); int i = 0; int nTestNumbers = 0; // the number of test numbers CvMat trainNumberNumMat; // the number numbers during training float[] projectedTestNumber; String answer; int nCorrect = 0; int nWrong = 0; double timeNumberRecognizeStart; double tallyNumberRecognizeTime; float confidence = 0.0f; // load test numbers and ground truth for number number testNumberImgArr = loadNumberImgArray(szFileTest); nTestNumbers = testNumberImgArr.length; System.out.println(nTestNumbers + " test numbers loaded"); // load the saved training data trainNumberNumMat = loadTrainingData(); if (trainNumberNumMat == null) { return; } // project the test numbers onto the PCA subspace projectedTestNumber = new float[nEigens]; timeNumberRecognizeStart = (double) cvGetTickCount(); // Record the timing. for (i = 0; i < nTestNumbers; i++) { int iNearest; int nearest; int truth; // project the test image onto the PCA subspace cvEigenDecomposite( testNumberImgArr[i], // obj nEigens, // nEigObjs new PointerPointer(eigenVectArr), // eigInput (Pointer) 0, // ioFlags null, // userData pAvgTrainImg, // avg projectedTestNumber); // coeffs //System.out.println("projectedTestNumber\n" + floatArrayToString(projectedTestNumber)); final FloatPointer pConfidence = new FloatPointer(confidence); iNearest = findNearestNeighbor(projectedTestNumber, new FloatPointer(pConfidence)); confidence = pConfidence.get(); truth = numberNumTruthMat.data_i().get(i); nearest = trainNumberNumMat.data_i().get(iNearest); if (nearest == truth) { answer = "Correct"; nCorrect++; } else { answer = "WRONG!"; nWrong++; } System.out.println("nearest = " + nearest + ", Truth = " + truth + " (" + answer + "). Confidence = " + confidence); } tallyNumberRecognizeTime = (double) cvGetTickCount() - timeNumberRecognizeStart; if (nCorrect + nWrong > 0) { System.out.println("TOTAL ACCURACY: " + (nCorrect * 100 / (nCorrect + nWrong)) + "% out of " + (nCorrect + nWrong) + " tests."); System.out.println("TOTAL TIME: " + (tallyNumberRecognizeTime / (cvGetTickFrequency() * 1000.0 * (nCorrect + nWrong))) + " ms average."); } } /** * Reads the names & image filenames of people from a text file, and loads * all those numbers listed. * * @param filename the training file name * @return the number image array */ /*private IplImage[] loadNumberImgArray(final String filename) { IplImage[] numberImgArr; BufferedReader imgListFile; String imgFilename; int iNumber = 0; int nNumbers = 0; int i; try { // open the input file imgListFile = new BufferedReader(new FileReader(filename)); // count the number of numbers while (true) { final String line = imgListFile.readLine(); if (line == null || line.isEmpty()) { break; } nNumbers++; } System.out.println("nNumbers: " + nNumbers); imgListFile = new BufferedReader(new FileReader(filename)); // allocate the number-image array and number number matrix numberImgArr = new IplImage[nNumbers]; numberNumTruthMat = cvCreateMat( 1, // rows nNumbers, // cols CV_32SC1); // type, 32-bit unsigned, one channel // initialize the number number matrix - for ease of debugging for (int j1 = 0; j1 < nNumbers; j1++) { numberNumTruthMat.put(0, j1, 0); } numberNames.clear(); // Make sure it starts as empty. nNumbers = 0; // store the number numbers in an array for (iNumber = 0; iNumber < nNumbers; iNumber++) { String numberName; String sNumberName; int numberNumber; // read number number (beginning with 1), their name and the image filename. final String line = imgListFile.readLine(); if (line.isEmpty()) { break; } final String[] tokens = line.split(" "); numberNumber = Integer.parseInt(tokens[0]); numberName = tokens[1]; imgFilename = tokens[2]; sNumberName = numberName; System.out.println("Got " + iNumber + " " + numberNumber + " " + numberName + " " + imgFilename); // Check if a new number is being loaded. if (numberNumber > nNumbers) { // Allocate memory for the extra number (or possibly multiple), using this new number's name. numberNames.add(sNumberName); nNumbers = numberNumber; System.out.println("Got new number " + sNumberName + " -> nNumbers = " + nNumbers + " [" + numberNames.size() + "]"); } // Keep the data numberNumTruthMat.put( 0, // i iNumber, // j numberNumber); // v // load the number image numberImgArr[iNumber] = cvLoadImage( imgFilename, // filename CV_LOAD_IMAGE_GRAYSCALE); // isColor if (numberImgArr[iNumber] == null) { throw new RuntimeException("Can't load image from " + imgFilename); } } imgListFile.close(); } catch (IOException ex) { throw new RuntimeException(ex); } System.out.println("Data loaded from '" + filename + "': (" + nNumbers + " numbers of " + nNumbers + " people)."); final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("People: "); if (nNumbers > 0) { stringBuilder.append("<").append(numberNames.get(0)).append(">"); } for (i = 1; i < nNumbers && i < numberNames.size(); i++) { stringBuilder.append(", <").append(numberNames.get(i)).append(">"); } System.out.println(stringBuilder.toString()); return numberImgArr; } /** * Stores the training data to the file 'data/numberdata.xml'. */ /*private void storeTrainingData() { CvFileStorage fileStorage; int i; System.out.println("writing data/numberdata.xml"); // create a file-storage internumber fileStorage = cvOpenFileStorage( "data/numberdata.xml", // filename null, // memstorage CV_STORAGE_WRITE, // flags null); // encoding // Store the number names. Added by Shervin. cvWriteInt( fileStorage, // fs "nNumbers", // name nNumbers); // value for (i = 0; i < nNumbers; i++) { String varname = "numberName_" + (i + 1); cvWriteString( fileStorage, // fs varname, // name numberNames.get(i), // string 0); // quote } // store all the data cvWriteInt( fileStorage, // fs "nEigens", // name nEigens); // value cvWriteInt( fileStorage, // fs "nTrainNumbers", // name nTrainNumbers); // value cvWrite( fileStorage, // fs "trainNumberNumMat", // name numberNumTruthMat, // value cvAttrList()); // attributes cvWrite( fileStorage, // fs "eigenValMat", // name eigenValMat, // value cvAttrList()); // attributes cvWrite( fileStorage, // fs "projectedTrainNumberMat", // name projectedTrainNumberMat, cvAttrList()); // value cvWrite(fileStorage, // fs "avgTrainImg", // name pAvgTrainImg, // value cvAttrList()); // attributes for (i = 0; i < nEigens; i++) { String varname = "eigenVect_" + i; cvWrite( fileStorage, // fs varname, // name eigenVectArr[i], // value cvAttrList()); // attributes } // release the file-storage internumber cvReleaseFileStorage(fileStorage); } /** * Opens the training data from the file 'data/numberdata.xml'. * * @param pTrainNumberNumMat * @return the number numbers during training, or null if not successful */ /* private CvMat loadTrainingData() { System.out.println("loading training data"); CvMat pTrainNumberNumMat = null; // the number numbers during training CvFileStorage fileStorage; int i; // create a file-storage internumber fileStorage = cvOpenFileStorage( "data/numberdata.xml", // filename null, // memstorage CV_STORAGE_READ, // flags null); // encoding if (fileStorage == null) { System.out.println("Can't open training database file 'data/numberdata.xml'."); return null; } // Load the number names. numberNames.clear(); // Make sure it starts as empty. nNumbers = cvReadIntByName( fileStorage, // fs null, // map "nNumbers", // name 0); // default_value if (nNumbers == 0) { System.out.println("No people found in the training database 'data/numberdata.xml'."); return null; } else { System.out.println(nNumbers + " numbers read from the training database"); } // Load each number's name. for (i = 0; i < nNumbers; i++) { String sNumberName; String varname = "numberName_" + (i + 1); sNumberName = cvReadStringByName( fileStorage, // fs null, // map varname, ""); numberNames.add(sNumberName); } System.out.println("number names: " + numberNames); // Load the data nEigens = cvReadIntByName( fileStorage, // fs null, // map "nEigens", 0); // default_value nTrainNumbers = cvReadIntByName( fileStorage, null, // map "nTrainNumbers", 0); // default_value Pointer pointer = cvReadByName( fileStorage, // fs null, // map "trainNumberNumMat", // name cvAttrList()); // attributes pTrainNumberNumMat = new CvMat(pointer); pointer = cvReadByName( fileStorage, // fs null, // map "eigenValMat", // nmae cvAttrList()); // attributes eigenValMat = new CvMat(pointer); pointer = cvReadByName( fileStorage, // fs null, // map "projectedTrainNumberMat", // name cvAttrList()); // attributes projectedTrainNumberMat = new CvMat(pointer); pointer = cvReadByName( fileStorage, null, // map "avgTrainImg", cvAttrList()); // attributes pAvgTrainImg = new IplImage(pointer); eigenVectArr = new IplImage[nTrainNumbers]; for (i = 0; i < nEigens; i++) { String varname = "eigenVect_" + i; pointer = cvReadByName( fileStorage, null, // map varname, cvAttrList()); // attributes eigenVectArr[i] = new IplImage(pointer); } // release the file-storage internumber cvReleaseFileStorage(fileStorage); System.out.println("Training data loaded (" + nTrainNumbers + " training numbers of " + nNumbers + " people)"); final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("People: "); if (nNumbers > 0) { stringBuilder.append("<").append(numberNames.get(0)).append(">"); } for (i = 1; i < nNumbers; i++) { stringBuilder.append(", <").append(numberNames.get(i)).append(">"); } System.out.println(stringBuilder.toString()); return pTrainNumberNumMat; } /** * Saves all the eigenvectors as numbers, so that they can be checked. */ /*private void storeEigennumberImages() { // Store the average image to a file System.out.println("Saving the image of the average number as 'data/out_averageImage.bmp'"); cvSaveImage("data/out_averageImage.bmp", pAvgTrainImg); // Create a large image made of many eigennumber numbers. // Must also convert each eigennumber image to a normal 8-bit UCHAR image instead of a 32-bit float image. System.out.println("Saving the " + nEigens + " eigenvector numbers as 'data/out_eigennumbers.bmp'"); if (nEigens > 0) { // Put all the eigennumbers next to each other. int COLUMNS = 8; // Put upto 8 numbers on a row. int nCols = Math.min(nEigens, COLUMNS); int nRows = 1 + (nEigens / COLUMNS); // Put the rest on new rows. int w = eigenVectArr[0].width(); int h = eigenVectArr[0].height(); CvSize size = cvSize(nCols * w, nRows * h); final IplImage bigImg = cvCreateImage( size, IPL_DEPTH_8U, // depth, 8-bit Greyscale UCHAR image 1); // channels for (int i = 0; i < nEigens; i++) { // Get the eigennumber image. IplImage byteImg = convertFloatImageToUcharImage(eigenVectArr[i]); // Paste it into the correct position. int x = w * (i % COLUMNS); int y = h * (i / COLUMNS); CvRect ROI = cvRect(x, y, w, h); cvSetImageROI( bigImg, // image ROI); // rect cvCopy( byteImg, // src bigImg, // dst null); // mask cvResetImageROI(bigImg); cvReleaseImage(byteImg); } cvSaveImage( "data/out_eigennumbers.bmp", // filename bigImg); // image cvReleaseImage(bigImg); } } /** * Converts the given float image to an unsigned character image. * * @param srcImg the given float image * @return the unsigned character image */ /*private IplImage convertFloatImageToUcharImage(IplImage srcImg) { IplImage dstImg; if ((srcImg != null) && (srcImg.width() > 0 && srcImg.height() > 0)) { // Spread the 32bit floating point pixels to fit within 8bit pixel range. CvPoint minloc = new CvPoint(); CvPoint maxloc = new CvPoint(); double[] minVal = new double[1]; double[] maxVal = new double[1]; cvMinMaxLoc(srcImg, minVal, maxVal, minloc, maxloc, null); // Deal with NaN and extreme values, since the DFT seems to give some NaN results. if (minVal[0] < -1e30) { minVal[0] = -1e30; } if (maxVal[0] > 1e30) { maxVal[0] = 1e30; } if (maxVal[0] - minVal[0] == 0.0f) { maxVal[0] = minVal[0] + 0.001; // remove potential divide by zero errors. } // Convert the format dstImg = cvCreateImage(cvSize(srcImg.width(), srcImg.height()), 8, 1); cvConvertScale(srcImg, dstImg, 255.0 / (maxVal[0] - minVal[0]), -minVal[0] * 255.0 / (maxVal[0] - minVal[0])); return dstImg; } return null; } /** * Find the most likely number based on a detection. Returns the index, and * stores the confidence value into pConfidence. * * @param projectedTestNumber the projected test number * @param pConfidencePointer a pointer containing the confidence value * @param iTestNumber the test number index * @return the index */ /* private int findNearestNeighbor(float projectedTestNumber[], FloatPointer pConfidencePointer) { double leastDistSq = Double.MAX_VALUE; int i = 0; int iTrain = 0; int iNearest = 0; System.out.println("................"); System.out.println("find nearest neighbor from " + nTrainNumbers + " training numbers"); for (iTrain = 0; iTrain < nTrainNumbers; iTrain++) { //System.out.println("considering training number " + (iTrain + 1)); double distSq = 0; for (i = 0; i < nEigens; i++) { //LOGGER.debug(" projected test number distance from eigennumber " + (i + 1) + " is " + projectedTestNumber[i]); float projectedTrainNumberDistance = (float) projectedTrainNumberMat.get(iTrain, i); float d_i = projectedTestNumber[i] - projectedTrainNumberDistance; distSq += d_i * d_i; // / eigenValMat.data_fl().get(i); // Mahalanobis distance (might give better results than Eucalidean distance) // if (iTrain < 5) { // System.out.println(" ** projected training number " + (iTrain + 1) + " distance from eigennumber " + (i + 1) + " is " + projectedTrainNumberDistance); // System.out.println(" distance between them " + d_i); // System.out.println(" distance squared " + distSq); // } } if (distSq < leastDistSq) { leastDistSq = distSq; iNearest = iTrain; System.out.println(" training number " + (iTrain + 1) + " is the new best match, least squared distance: " + leastDistSq); } } // Return the confidence level based on the Euclidean distance, // so that similar numbers should give a confidence between 0.5 to 1.0, // and very different numbers should give a confidence between 0.0 to 0.5. float pConfidence = (float) (1.0f - Math.sqrt(leastDistSq / (float) (nTrainNumbers * nEigens)) / 255.0f); pConfidencePointer.put(pConfidence); System.out.println("training number " + (iNearest + 1) + " is the final best match, confidence " + pConfidence); return iNearest; } /** * Returns a string representation of the given float array. * * @param floatArray the given float array * @return a string representation of the given float array */ /* private String floatArrayToString(final float[] floatArray) { final StringBuilder stringBuilder = new StringBuilder(); boolean isFirst = true; stringBuilder.append('['); for (int i = 0; i < floatArray.length; i++) { if (isFirst) { isFirst = false; } else { stringBuilder.append(", "); } stringBuilder.append(floatArray[i]); } stringBuilder.append(']'); return stringBuilder.toString(); } /** * Returns a string representation of the given float pointer. * * @param floatPointer the given float pointer * @return a string representation of the given float pointer */ /*private String floatPointerToString(final FloatPointer floatPointer) { final StringBuilder stringBuilder = new StringBuilder(); boolean isFirst = true; stringBuilder.append('['); for (int i = 0; i < floatPointer.capacity(); i++) { if (isFirst) { isFirst = false; } else { stringBuilder.append(", "); } stringBuilder.append(floatPointer.get(i)); } stringBuilder.append(']'); return stringBuilder.toString(); } /** * Returns a string representation of the given one-channel CvMat object. * * @param cvMat the given CvMat object * @return a string representation of the given CvMat object */ /*public String oneChannelCvMatToString(final CvMat cvMat) { //Preconditions if (cvMat.channels() != 1) { throw new RuntimeException("illegal argument - CvMat must have one channel"); } final int type = cvMat.maskedType(); StringBuilder s = new StringBuilder("[ "); for (int i = 0; i < cvMat.rows(); i++) { for (int j = 0; j < cvMat.cols(); j++) { if (type == CV_32FC1 || type == CV_32SC1) { s.append(cvMat.get(i, j)); } else { throw new RuntimeException("illegal argument - CvMat must have one channel and type of float or signed integer"); } if (j < cvMat.cols() - 1) { s.append(", "); } } if (i < cvMat.rows() - 1) { s.append("\n "); } } s.append(" ]"); return s.toString(); } /** * Executes this application. * * @param args the command line arguments */ /*public static void main(final String[] args) { final NumberRecognition numberRecognition = new NumberRecognition(); //numberRecognition.learn("data/some-training-numbers.txt"); numberRecognition.learn("data/all10.txt"); //numberRecognition.recognizeFileList("data/some-test-numbers.txt"); numberRecognition.recognizeFileList("data/lower3.txt"); }*/ }
lgpl-2.1
Morik/WCF
wcfsetup/install/files/lib/acp/page/PackagePage.class.php
2385
<?php namespace wcf\acp\page; use wcf\data\package\Package; use wcf\page\AbstractPage; use wcf\system\exception\IllegalLinkException; use wcf\system\WCF; /** * Shows all information about an installed package. * * @author Marcel Werk * @copyright 2001-2018 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Page */ class PackagePage extends AbstractPage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.package'; /** * list of compatible API versions * @var integer[] */ public $compatibleVersions = []; /** * @inheritDoc */ public $neededPermissions = ['admin.configuration.package.canUpdatePackage', 'admin.configuration.package.canUninstallPackage']; /** * id of the package * @var integer */ public $packageID = 0; /** * package object * @var Package */ public $package; /** * Plugin-Store fileID * @var integer */ public $pluginStoreFileID = 0; /** * @inheritDoc */ public function readParameters() { parent::readParameters(); if (isset($_REQUEST['id'])) $this->packageID = intval($_REQUEST['id']); $this->package = new Package($this->packageID); if (!$this->package->packageID) { throw new IllegalLinkException(); } } /** * @inheritDoc */ public function readData() { parent::readData(); $sql = "SELECT pluginStoreFileID FROM wcf".WCF_N."_package_update WHERE package = ? AND pluginStoreFileID <> 0"; $statement = WCF::getDB()->prepareStatement($sql); $statement->execute([$this->package->package]); $this->pluginStoreFileID = intval($statement->fetchSingleColumn()); $sql = "SELECT version FROM wcf".WCF_N."_package_compatibility WHERE packageID = ? AND version >= ? ORDER BY version"; $statement = WCF::getDB()->prepareStatement($sql); $statement->execute([ $this->package->packageID, WSC_API_VERSION ]); while ($version = $statement->fetchColumn()) { $this->compatibleVersions[] = $version; } } /** * @inheritDoc */ public function assignVariables() { parent::assignVariables(); WCF::getTPL()->assign([ 'compatibleVersions' => $this->compatibleVersions, 'package' => $this->package, 'pluginStoreFileID' => $this->pluginStoreFileID ]); } }
lgpl-2.1
arthurdejong/python-stdnum
stdnum/fi/alv.py
2177
# vat.py - functions for handling Finnish VAT numbers # coding: utf-8 # # Copyright (C) 2012-2015 Arthur de Jong # # 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., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """ALV nro (Arvonlisäveronumero, Finnish VAT number). The number is an 8-digit code with a weighted checksum. >>> validate('FI 20774740') '20774740' >>> validate('FI 20774741') # invalid check digit Traceback (most recent call last): ... InvalidChecksum: ... """ from stdnum.exceptions import * from stdnum.util import clean, isdigits def compact(number): """Convert the number to the minimal representation. This strips the number of any valid separators and removes surrounding whitespace.""" number = clean(number, ' -').upper().strip() if number.startswith('FI'): number = number[2:] return number def checksum(number): """Calculate the checksum.""" weights = (7, 9, 10, 5, 8, 4, 2, 1) return sum(w * int(n) for w, n in zip(weights, number)) % 11 def validate(number): """Check if the number is a valid VAT number. This checks the length, formatting and check digit.""" number = compact(number) if not isdigits(number): raise InvalidFormat() if len(number) != 8: raise InvalidLength() if checksum(number) != 0: raise InvalidChecksum() return number def is_valid(number): """Check if the number is a valid VAT number.""" try: return bool(validate(number)) except ValidationError: return False
lgpl-2.1
plays2009/rentacaro-triz
include/modifyMailAddress.php
1721
<?php $cntQuery = "SELECT count(address) FROM admin_mail"; // 카운트 얻기 위한 쿼리 $cntResult = $mysqli->query($cntQuery); $cntData = mysqli_fetch_array($cntResult); ?> <div class="w3-modal-content w3-card-4" style="padding-left: 12px"> <header class="w3-container"> <span onclick="document.getElementById('modifyAdminEmail').style.display='none'" class="w3-button w3-display-topright">&times;</span> <h3>사용자가 입력한 상담 내용이 전송되는 메일 주소를 수정합니다.</h3> <h5>현재 <b><?=$cntData[0]?></b>개의 주소가 등록되어 있습니다.</h5> </header> <div class="w3-container w3-center" style="margin-bottom: 30px; max-height: 480px; padding: 16px; overflow: auto"> <?php $getMailQuery = "SELECT * FROM admin_mail"; $getMailResult = $mysqli->query($getMailQuery); while ($getMailData = mysqli_fetch_array($getMailResult)) { ?> <div> <h6><b><?=$getMailData[address]?><b>&nbsp;&nbsp;&nbsp;&nbsp; 이 메일 주소를 &nbsp;&nbsp;<button onclick="window.open('editMailAddress.php?idx=<?=$getMailData[idx]?>', '_blank', 'width=600 height=200 left=500 top=400')" class="w3-button w3-blue w3-round-large">수정</button> &nbsp;<button onclick="location.href='deleteMailAddress.php?idx=<?=$getMailData[idx]?>'" class="w3-button w3-blue w3-round-large">삭제</button></h6> </div> <?php } ?> </div> <footer class="w3-container"> <h5>상담 내용을 받아 볼 메일 주소를 추가하려면 <a onclick="window.open('addMailAddress.php', '_blank', 'width=600 height=500 left=500 top=400')" style="color: blue; cursor: pointer"><i>여기</i></a>를 눌러주세요</h5> </footer> </div>
lgpl-2.1
Matt3164/sill
src/sill/graph/directed_edge.hpp
2624
#ifndef SILL_DIRECTED_EDGE_HPP #define SILL_DIRECTED_EDGE_HPP #include <boost/functional/hash.hpp> #include <sill/global.hpp> namespace sill { template<typename V, typename VP, typename EP> class directed_graph; template<typename V, typename VP, typename EP> class directed_multigraph; /** * A class that represents a directed edge. * \ingroup graph_types */ template <typename Vertex> class directed_edge { private: //! Vertex from which the edge originates Vertex m_source; //! Vertex to which the edge emenates Vertex m_target; /** * The property associated with this edge. Edges maintain a private * pointer to the associated property. However, this pointer can only * be accessed through the associated graph. This permits graphs to * return iterators over edges and permits constant time lookup for * the corresponding edge properties. The property is stored as a void*, * to simplify the type of the edges. */ void* m_property; /** * directed_graphs are made friends here to have access to the internal * edge property. */ template <typename V, typename VP, typename EP> friend class directed_graph; template <typename V, typename VP, typename EP> friend class directed_multigraph; public: //! Default constructor directed_edge() : m_source(), m_target(), m_property() {} //! Constructor which permits setting the edge_property directed_edge(Vertex source, Vertex target, void* property = NULL) : m_source(source), m_target(target), m_property(property) { } bool operator<(const directed_edge& other) const { return (m_source < other.m_source) || (m_source == other.m_source && m_target < other.m_target); } bool operator==(const directed_edge& other) const { return m_source == other.m_source && m_target == other.m_target; } bool operator!=(const directed_edge& other) const { return !operator==(other); } const Vertex& source() const { return m_source; } const Vertex& target() const { return m_target; } }; // class directed_edge //! \relates directed_edge template <typename Vertex> std::ostream& operator<<(std::ostream& out, const directed_edge<Vertex>& e) { out << e.source() << " --> " << e.target(); return out; } //! \relates directed_edge template <typename Vertex> inline size_t hash_value(const directed_edge<Vertex>& e) { return boost::hash_value(std::make_pair(e.source(), e.target())); } } // namespace sill #endif
lgpl-2.1
wood-galaxy/FreeCAD
src/Mod/TechDraw/App/AppTechDrawPy.cpp
8602
/*************************************************************************** * Copyright (c) Jürgen Riegel (juergen.riegel@web.de) 2002 * * Copyright (c) WandererFan (wandererfan@gmail.com) 2016 * * * * This file is part of the FreeCAD CAx development system. * * * * 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., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Python.h> # include <TopoDS.hxx> # include <TopoDS_Edge.hxx> # include <TopoDS_Face.hxx> # include <TopoDS_Wire.hxx> #endif #include <CXX/Extensions.hxx> #include <CXX/Objects.hxx> #include <Base/Console.h> #include <Base/PyObjectBase.h> #include <Base/Exception.h> #include <Base/GeometryPyCXX.h> #include <Mod/Part/App/TopoShape.h> #include <Mod/Part/App/TopoShapePy.h> #include <Mod/Part/App/TopoShapeEdgePy.h> #include <Mod/Part/App/TopoShapeWirePy.h> #include <Mod/Part/App/OCCError.h> #include "EdgeWalker.h" namespace TechDraw { //module level static C++ functions go here } using Part::TopoShape; using Part::TopoShapePy; using Part::TopoShapeEdgePy; using Part::TopoShapeWirePy; namespace TechDraw { class Module : public Py::ExtensionModule<Module> { public: Module() : Py::ExtensionModule<Module>("TechDraw") { add_varargs_method("edgeWalker",&Module::edgeWalker, "[wires] = edgeWalker(edgePile,inclBiggest) -- Planar graph traversal finds wires in edge pile." ); add_varargs_method("findOuterWire",&Module::findOuterWire, "wire = findOuterWire(edgeList) -- Planar graph traversal finds OuterWire in edge pile." ); initialize("This is a module for making drawings"); // register with Python } virtual ~Module() {} private: virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) { try { return Py::ExtensionModule<Module>::invoke_method_varargs(method_def, args); } catch (const Standard_Failure &e) { std::string str; Standard_CString msg = e.GetMessageString(); str += typeid(e).name(); str += " "; if (msg) {str += msg;} else {str += "No OCCT Exception Message";} Base::Console().Error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } catch (const Base::Exception &e) { std::string str; str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; e.ReportException(); throw Py::RuntimeError(str); } catch (const std::exception &e) { std::string str; str += "C++ exception thrown ("; str += e.what(); str += ")"; Base::Console().Error("%s\n", str.c_str()); throw Py::RuntimeError(str); } } Py::Object edgeWalker(const Py::Tuple& args) { PyObject *pcObj; PyObject *inclBig = Py_True; if (!PyArg_ParseTuple(args.ptr(), "O|O", &pcObj,&inclBig)) { throw Py::Exception(); } std::vector<TopoDS_Edge> edgeList; try { Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapeEdgePy::Type))) { const TopoDS_Shape& sh = static_cast<TopoShapePy*>((*it).ptr())-> getTopoShapePtr()->getShape(); const TopoDS_Edge e = TopoDS::Edge(sh); edgeList.push_back(e); } } } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); throw Py::Exception(Part::PartExceptionOCCError, e->GetMessageString()); } if (edgeList.empty()) { Base::Console().Log("LOG - edgeWalker: input is empty\n"); return Py::None(); } bool biggie; if (inclBig == Py_True) { biggie = true; } else { biggie = false; } PyObject* result = PyList_New(0); try { EdgeWalker ew; ew.loadEdges(edgeList); bool success = ew.perform(); if (success) { std::vector<TopoDS_Wire> rw = ew.getResultNoDups(); std::vector<TopoDS_Wire> sortedWires = ew.sortStrip(rw,biggie); //false==>do not include biggest wires for (auto& w:sortedWires) { PyList_Append(result,new TopoShapeWirePy(new TopoShape(w))); } } else { Base::Console().Warning("edgeWalker: input is not planar graph. Wire detection not done\n"); } } catch (Base::Exception &e) { throw Py::Exception(Base::BaseExceptionFreeCADError, e.what()); } return Py::asObject(result); } Py::Object findOuterWire(const Py::Tuple& args) { PyObject *pcObj; if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj)) { throw Py::Exception(); } std::vector<TopoDS_Edge> edgeList; try { Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapeEdgePy::Type))) { const TopoDS_Shape& sh = static_cast<TopoShapePy*>((*it).ptr())-> getTopoShapePtr()->getShape(); const TopoDS_Edge e = TopoDS::Edge(sh); edgeList.push_back(e); } } } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); throw Py::Exception(Part::PartExceptionOCCError, e->GetMessageString()); } if (edgeList.empty()) { Base::Console().Log("LOG - findOuterWire: input is empty\n"); return Py::None(); } PyObject* outerWire = nullptr; bool success = false; try { EdgeWalker ew; ew.loadEdges(edgeList); success = ew.perform(); if (success) { std::vector<TopoDS_Wire> rw = ew.getResultNoDups(); std::vector<TopoDS_Wire> sortedWires = ew.sortStrip(rw,true); outerWire = new TopoShapeWirePy(new TopoShape(*sortedWires.begin())); } else { Base::Console().Warning("findOuterWire: input is not planar graph. Wire detection not done\n"); } } catch (Base::Exception &e) { throw Py::Exception(Base::BaseExceptionFreeCADError, e.what()); } if (!success) { return Py::None(); } return Py::asObject(outerWire); } }; PyObject* initModule() { return (new Module)->module().ptr(); } } // namespace TechDraw
lgpl-2.1
maekitalo/tntdb
src/oracle/string.cpp
2221
/* * Copyright (C) 2018 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tntdb/oracle/string.h> #include <cxxtools/log.h> log_define("tntdb.oracle.string") namespace tntdb { namespace oracle { void String::assign(Connection* conn, const std::string& s) { sword ret = OCIStringAssignText(conn->getEnvHandle(), conn->getErrorHandle(), reinterpret_cast<const OraText*>(s.data()), s.size(), &handle); conn->checkError(ret, "OCIStringAssignText"); } const char* String::data() const { if (handle == 0) return 0; return reinterpret_cast<const char*>(OCIStringPtr(conn->getEnvHandle(), handle)); } ub4 String::size() const { if (handle == 0) return 0; return OCIStringSize(conn->getEnvHandle(), handle); } } }
lgpl-2.1
Mag-nus/Mag-Plugins
Mag-Tools/ItemInfo/ItemInfo.cs
17064
using System; using System.Collections.Generic; using Mag.Shared; using Mag.Shared.Constants; using Decal.Adapter; using Decal.Adapter.Wrappers; using Decal.Filters; using DoubleValueKey = Decal.Adapter.Wrappers.DoubleValueKey; namespace MagTools.ItemInfo { /// <summary> /// Instantiate this object with the item you want info for. /// ToString() this object for the info. /// </summary> public class ItemInfo { private readonly WorldObject wo; private readonly MyWorldObject mwo; public ItemInfo(WorldObject worldObject) { wo = worldObject; mwo = MyWorldObjectCreator.Create(worldObject); } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (wo.Values(LongValueKey.Material) > 0) { if (Dictionaries.MaterialInfo.ContainsKey(wo.Values(LongValueKey.Material))) sb.Append(Dictionaries.MaterialInfo[wo.Values(LongValueKey.Material)] + " "); else sb.Append("unknown material " + wo.Values(LongValueKey.Material) + " "); } sb.Append(wo.Name); if (wo.Values((LongValueKey)353) > 0) { if (Dictionaries.MasteryInfo.ContainsKey(wo.Values((LongValueKey)353))) sb.Append(" (" + Dictionaries.MasteryInfo[wo.Values((LongValueKey)353)] + ")"); else sb.Append(" (Unknown mastery " + wo.Values((LongValueKey)353) + ")"); } int set = wo.Values((LongValueKey)265, 0); if (set != 0) { sb.Append(", "); if (Dictionaries.AttributeSetInfo.ContainsKey(set)) sb.Append(Dictionaries.AttributeSetInfo[set]); else sb.Append("Unknown set " + set); } if (wo.Values(LongValueKey.ArmorLevel) > 0) sb.Append(", AL " + wo.Values(LongValueKey.ArmorLevel)); if (wo.Values(LongValueKey.Imbued) > 0) { sb.Append(","); if ((wo.Values(LongValueKey.Imbued) & 1) == 1) sb.Append(" CS"); if ((wo.Values(LongValueKey.Imbued) & 2) == 2) sb.Append(" CB"); if ((wo.Values(LongValueKey.Imbued) & 4) == 4) sb.Append(" AR"); if ((wo.Values(LongValueKey.Imbued) & 8) == 8) sb.Append(" SlashRend"); if ((wo.Values(LongValueKey.Imbued) & 16) == 16) sb.Append(" PierceRend"); if ((wo.Values(LongValueKey.Imbued) & 32) == 32) sb.Append(" BludgeRend"); if ((wo.Values(LongValueKey.Imbued) & 64) == 64) sb.Append(" AcidRend"); if ((wo.Values(LongValueKey.Imbued) & 128) == 128) sb.Append(" FrostRend"); if ((wo.Values(LongValueKey.Imbued) & 256) == 256) sb.Append(" LightRend"); if ((wo.Values(LongValueKey.Imbued) & 512) == 512) sb.Append(" FireRend"); if ((wo.Values(LongValueKey.Imbued) & 1024) == 1024) sb.Append(" MeleeImbue"); if ((wo.Values(LongValueKey.Imbued) & 4096) == 4096) sb.Append(" MagicImbue"); if ((wo.Values(LongValueKey.Imbued) & 8192) == 8192) sb.Append(" Hematited"); if ((wo.Values(LongValueKey.Imbued) & 536870912) == 536870912) sb.Append(" MagicAbsorb"); } if (wo.Values(LongValueKey.NumberTimesTinkered) > 0) sb.Append(", Tinks " + wo.Values(LongValueKey.NumberTimesTinkered)); if (wo.Values(LongValueKey.MaxDamage) != 0 && wo.Values(DoubleValueKey.Variance) != 0) sb.Append(", " + (wo.Values(LongValueKey.MaxDamage) - (wo.Values(LongValueKey.MaxDamage) * wo.Values(DoubleValueKey.Variance))).ToString("N2") + "-" + wo.Values(LongValueKey.MaxDamage)); else if (wo.Values(LongValueKey.MaxDamage) != 0 && wo.Values(DoubleValueKey.Variance) == 0) sb.Append(", " + wo.Values(LongValueKey.MaxDamage)); if (wo.Values(LongValueKey.ElementalDmgBonus, 0) != 0) sb.Append(", +" + wo.Values(LongValueKey.ElementalDmgBonus)); if (wo.Values(DoubleValueKey.DamageBonus, 1) != 1) sb.Append(", +" + Math.Round(((wo.Values(DoubleValueKey.DamageBonus) - 1) * 100)) + "%"); if (wo.Values(DoubleValueKey.ElementalDamageVersusMonsters, 1) != 1) sb.Append(", +" + Math.Round(((wo.Values(DoubleValueKey.ElementalDamageVersusMonsters) - 1) * 100)) + "%vs. Monsters"); if (wo.Values(DoubleValueKey.AttackBonus, 1) != 1) sb.Append(", +" + Math.Round(((wo.Values(DoubleValueKey.AttackBonus) - 1) * 100)) + "%a"); if (wo.Values(DoubleValueKey.MeleeDefenseBonus, 1) != 1) sb.Append(", " + Math.Round(((wo.Values(DoubleValueKey.MeleeDefenseBonus) - 1) * 100)) + "%md"); if (wo.Values(DoubleValueKey.MagicDBonus, 1) != 1) sb.Append(", " + Math.Round(((wo.Values(DoubleValueKey.MagicDBonus) - 1) * 100), 1) + "%mgc.d"); if (wo.Values(DoubleValueKey.MissileDBonus, 1) != 1) sb.Append(", " + Math.Round(((wo.Values(DoubleValueKey.MissileDBonus) - 1) * 100), 1) + "%msl.d"); if (wo.Values(DoubleValueKey.ManaCBonus) != 0) sb.Append(", " + Math.Round((wo.Values(DoubleValueKey.ManaCBonus) * 100)) + "%mc"); if (Settings.SettingsManager.ItemInfoOnIdent.ShowBuffedValues.Value && (wo.ObjectClass == ObjectClass.MeleeWeapon || wo.ObjectClass == ObjectClass.MissileWeapon || wo.ObjectClass == ObjectClass.WandStaffOrb)) { sb.Append(", ("); // (Damage) if (wo.ObjectClass == ObjectClass.MeleeWeapon) sb.Append(mwo.CalcedBuffedTinkedDoT.ToString("N1") + "/" + mwo.GetBuffedIntValueKey((int)LongValueKey.MaxDamage)); if (wo.ObjectClass == ObjectClass.MissileWeapon) sb.Append(mwo.CalcedBuffedMissileDamage.ToString("N1")); if (wo.ObjectClass == ObjectClass.WandStaffOrb) sb.Append(((mwo.GetBuffedDoubleValueKey((int)DoubleValueKey.ElementalDamageVersusMonsters) - 1) * 100).ToString("N1")); // (AttackBonus/MeleeDefenseBonus/ManaCBonus) sb.Append(" "); if (wo.Values(DoubleValueKey.AttackBonus, 1) != 1) sb.Append(Math.Round(((mwo.GetBuffedDoubleValueKey((int)DoubleValueKey.AttackBonus) - 1) * 100)).ToString("N1") + "/"); if (wo.Values(DoubleValueKey.MeleeDefenseBonus, 1) != 1) sb.Append(Math.Round(((mwo.GetBuffedDoubleValueKey((int)DoubleValueKey.MeleeDefenseBonus) - 1) * 100)).ToString("N1")); if (wo.Values(DoubleValueKey.ManaCBonus) != 0) sb.Append("/" + Math.Round(mwo.GetBuffedDoubleValueKey((int)DoubleValueKey.ManaCBonus) * 100)); sb.Append(")"); } if (wo.SpellCount > 0) { FileService service = CoreManager.Current.Filter<FileService>(); List<int> itemActiveSpells = new List<int>(); for (int i = 0 ; i < wo.SpellCount ; i++) itemActiveSpells.Add(wo.Spell(i)); itemActiveSpells.Sort(); itemActiveSpells.Reverse(); foreach (int spell in itemActiveSpells) { Spell spellById = service.SpellTable.GetById(spell); // If the item is not loot generated, show all spells if (!wo.LongKeys.Contains((int)LongValueKey.Material)) goto ShowSpell; // Always show Minor/Major/Epic Impen if (spellById.Name.Contains("Minor Impenetrability") || spellById.Name.Contains("Major Impenetrability") || spellById.Name.Contains("Epic Impenetrability") || spellById.Name.Contains("Legendary Impenetrability")) goto ShowSpell; // Always show trinket spells if (spellById.Name.Contains("Augmented")) goto ShowSpell; if (wo.Values(LongValueKey.Unenchantable, 0) != 0) { // Show banes and impen on unenchantable equipment if (spellById.Name.Contains(" Bane") || spellById.Name.Contains("Impen") || spellById.Name.StartsWith("Brogard")) goto ShowSpell; } else { // Hide banes and impen on enchantable equipment if (spellById.Name.Contains(" Bane") || spellById.Name.Contains("Impen") || spellById.Name.StartsWith("Brogard")) continue; } //Debug.WriteToChat(spellById.Name + ", Difficulty: " + spellById.Difficulty + ", Family: " + spellById.Family + ", Generation: " + spellById.Generation + ", Type: " + spellById.Type + ", " + spellById.Unknown1 + " " + spellById.Unknown2 + " " + spellById.Unknown3 + " " + spellById.Unknown4 + " " + spellById.Unknown5 + " " + spellById.Unknown6 + " " + spellById.Unknown7 + " " + spellById.Unknown8 + " " + spellById.Unknown9 + " " + spellById.Unknown10); // <{Mag-Tools}>: Major Coordination, Difficulty: 15, Family: 267, Generation: 1, Type: 1, 0 1 1 2572 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Epic Magic Resistance, Difficulty: 20, Family: 299, Generation: 1, Type: 1, 0 1 1 4704 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Epic Life Magic Aptitude, Difficulty: 20, Family: 357, Generation: 1, Type: 1, 0 1 1 4700 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Epic Endurance, Difficulty: 20, Family: 263, Generation: 1, Type: 1, 0 1 1 4226 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Essence Glutton, Difficulty: 30, Family: 279, Generation: 1, Type: 1, 0 0 1 2666 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Might of the Lugians, Difficulty: 300, Family: 1, Generation: 1, Type: 1, 0 0 1 2087 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Executor's Blessing, Difficulty: 300, Family: 115, Generation: 1, Type: 1, 0 0 1 2053 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Regeneration Other Incantation, Difficulty: 400, Family: 93, Generation: 1, Type: 1, 5 0.25 1 3982 -2.07525870829232E+20 0 0 0 0 0 // Focusing stone // <{Mag-Tools}>: Brilliance, Difficulty: 250, Family: 15, Generation: 1, Type: 1, 5 0.25 1 2348 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Concentration, Difficulty: 100, Family: 13, Generation: 1, Type: 1, 0 0 1 2347 -2.07525870829232E+20 0 0 0 0 0 // <{Mag-Tools}>: Malediction, Difficulty: 50, Family: 284, Generation: 1, Type: 1, 0 0 1 2346 -2.07525870829232E+20 0 0 0 0 0 // Weapon buffs // <{Mag-Tools}>: Elysa's Sight, Difficulty: 300, Family: 152, Generation: 1, Type: 1, 25 0 1 2106 -2.07525870829232E+20 0 0 0 0 0 (Attack Skill) // <{Mag-Tools}>: Infected Caress, Difficulty: 300, Family: 154, Generation: 1, Type: 1, 25 0 1 2096 -2.07525870829232E+20 0 0 0 0 0 (Damage) // <{Mag-Tools}>: Infected Spirit Caress, Difficulty: 300, Family: 154, Generation: 1, Type: 1, 25 0 1 3259 -2.07525870829232E+20 0 0 0 0 0 (Damage) // <{Mag-Tools}>: Cragstone's Will, Difficulty: 300, Family: 156, Generation: 1, Type: 1, 25 0 1 2101 -2.07525870829232E+20 0 0 0 0 0 (Defense) // <{Mag-Tools}>: Atlan's Alacrity, Difficulty: 300, Family: 158, Generation: 1, Type: 1, 25 0 1 2116 -2.07525870829232E+20 0 0 0 0 0 (Speed) // <{Mag-Tools}>: Mystic's Blessing, Difficulty: 300, Family: 195, Generation: 1, Type: 1, 25 0 1 2117 -2.07525870829232E+20 0 0 0 0 0 (Mana C) // <{Mag-Tools}>: Vision of the Hunter, Difficulty: 500, Family: 325, Generation: 1, Type: 1, 25 0 1 2968 -2.07525870829232E+20 0 0 0 0 0 (Damage Mod) if ((spellById.Family >= 152 && spellById.Family <= 158) || spellById.Family == 195 || spellById.Family == 325) { // This is a weapon buff // Lvl 6 if (spellById.Difficulty == 250) continue; // Lvl 7 if (spellById.Difficulty == 300) goto ShowSpell; // Lvl 8+ if (spellById.Difficulty >= 400) goto ShowSpell; continue; } // This is not a weapon buff. // Filter all 1-5 spells if (spellById.Name.EndsWith(" I") || spellById.Name.EndsWith(" II") || spellById.Name.EndsWith(" III") || spellById.Name.EndsWith(" IV") || spellById.Name.EndsWith(" V")) continue; // Filter 6's if (spellById.Name.EndsWith(" VI")) continue; // Filter 7's if (spellById.Difficulty == 300) continue; // Filter 8's if (spellById.Name.Contains("Incantation")) continue; ShowSpell: sb.Append(", " + spellById.Name); } } // Wield Lvl 180 if (wo.Values(LongValueKey.WieldReqValue) > 0) { // I don't quite understand this. if (wo.Values(LongValueKey.WieldReqType) == 7 && wo.Values(LongValueKey.WieldReqAttribute) == 1) sb.Append(", Wield Lvl " + wo.Values(LongValueKey.WieldReqValue)); else { if (Dictionaries.SkillInfo.ContainsKey(wo.Values(LongValueKey.WieldReqAttribute))) sb.Append(", " + Dictionaries.SkillInfo[wo.Values(LongValueKey.WieldReqAttribute)] + " " + wo.Values(LongValueKey.WieldReqValue)); else sb.Append(", Unknown skill: " +wo.Values(LongValueKey.WieldReqAttribute) + " " + wo.Values(LongValueKey.WieldReqValue)); } } // Summoning Gem if (wo.Values((LongValueKey)369) > 0) sb.Append(", Lvl " + wo.Values((LongValueKey)369)); // Melee Defense 300 to Activate // If the activation is lower than the wield requirement, don't show it. if (wo.Values(LongValueKey.SkillLevelReq) > 0 && (wo.Values(LongValueKey.WieldReqAttribute) != wo.Values(LongValueKey.ActivationReqSkillId) || wo.Values(LongValueKey.WieldReqValue) < wo.Values(LongValueKey.SkillLevelReq))) { if (Dictionaries.SkillInfo.ContainsKey(wo.Values(LongValueKey.ActivationReqSkillId))) sb.Append(", " + Dictionaries.SkillInfo[wo.Values(LongValueKey.ActivationReqSkillId)] + " " + wo.Values(LongValueKey.SkillLevelReq) + " to Activate"); else sb.Append(", Unknown skill: " + wo.Values(LongValueKey.ActivationReqSkillId) + " " + wo.Values(LongValueKey.SkillLevelReq) + " to Activate"); } // Summoning Gem if (wo.Values((LongValueKey)366) > 0 && wo.Values((LongValueKey)367) > 0) { if (Dictionaries.SkillInfo.ContainsKey(wo.Values((LongValueKey)366))) sb.Append(", " + Dictionaries.SkillInfo[wo.Values((LongValueKey)366)] + " " + wo.Values((LongValueKey)367)); else sb.Append(", Unknown skill: " + wo.Values((LongValueKey)366) + " " + wo.Values((LongValueKey)367)); } // Summoning Gem if (wo.Values((LongValueKey)368) > 0 && wo.Values((LongValueKey)367) > 0) { if (Dictionaries.SkillInfo.ContainsKey(wo.Values((LongValueKey)368))) sb.Append(", Spec " + Dictionaries.SkillInfo[wo.Values((LongValueKey)368)] + " " + wo.Values((LongValueKey)367)); else sb.Append(", Unknown skill spec: " + wo.Values((LongValueKey)368) + " " + wo.Values((LongValueKey)367)); } if (wo.Values(LongValueKey.LoreRequirement) > 0) sb.Append(", Diff " + wo.Values(LongValueKey.LoreRequirement)); if (wo.ObjectClass == ObjectClass.Salvage) { if (wo.Values(DoubleValueKey.SalvageWorkmanship) > 0) sb.Append(", Work " + wo.Values(DoubleValueKey.SalvageWorkmanship).ToString("N2")); } else { if (wo.Values(LongValueKey.Workmanship) > 0 && wo.Values(LongValueKey.NumberTimesTinkered) != 10) // Don't show the work if its already 10 tinked. sb.Append(", Craft " + wo.Values(LongValueKey.Workmanship)); } if (wo.ObjectClass == ObjectClass.Armor && wo.Values(LongValueKey.Unenchantable, 0) != 0) { sb.Append(", [" + wo.Values(DoubleValueKey.SlashProt).ToString("N1") + "/" + wo.Values(DoubleValueKey.PierceProt).ToString("N1") + "/" + wo.Values(DoubleValueKey.BludgeonProt).ToString("N1") + "/" + wo.Values(DoubleValueKey.ColdProt).ToString("N1") + "/" + wo.Values(DoubleValueKey.FireProt).ToString("N1") + "/" + wo.Values(DoubleValueKey.AcidProt).ToString("N1") + "/" + wo.Values(DoubleValueKey.LightningProt).ToString("N1") + "]"); } if (Settings.SettingsManager.ItemInfoOnIdent.ShowValueAndBurden.Value) { if (wo.Values(LongValueKey.Value) > 0) sb.Append(", Value " + String.Format("{0:n0}", wo.Values(LongValueKey.Value))); if (wo.Values(LongValueKey.Burden) > 0) sb.Append(", BU " + wo.Values(LongValueKey.Burden)); } if (mwo.TotalRating > 0) { sb.Append(", ["); bool first = true; if (mwo.DamRating > 0) { sb.Append("D " + mwo.DamRating); first = false; } if (mwo.DamResistRating > 0) { if (!first) sb.Append(", "); sb.Append("DR " + mwo.DamResistRating); first = false; } if (mwo.CritRating > 0) { if (!first) sb.Append(", "); sb.Append("C " + mwo.CritRating); first = false; } if (mwo.CritDamRating > 0) { if (!first) sb.Append(", "); sb.Append("CD " + mwo.CritDamRating); first = false; } if (mwo.CritResistRating > 0) { if (!first) sb.Append(", "); sb.Append("CR " + mwo.CritResistRating); first = false; } if (mwo.CritDamResistRating > 0) { if (!first) sb.Append(", "); sb.Append("CDR " + mwo.CritDamResistRating); first = false; } if (mwo.HealBoostRating > 0) { if (!first) sb.Append(", "); sb.Append("HB " + mwo.HealBoostRating); first = false; } if (mwo.VitalityRating > 0) { if (!first) sb.Append(", "); sb.Append("V " + mwo.VitalityRating); first = false; } sb.Append("]"); } if (wo.ObjectClass == ObjectClass.Misc && wo.Name.Contains("Keyring")) sb.Append(", Keys: " + wo.Values(LongValueKey.KeysHeld) + ", Uses: " + wo.Values(LongValueKey.UsesRemaining)); return sb.ToString(); } } }
lgpl-2.1
stormvlad/qframework
class/validation/qdaterule.class.php
4137
<?php include_once(QFRAMEWORK_CLASS_PATH . "qframework/class/validation/qrule.class.php"); define("ERROR_RULE_WRONG_FORMAT_VALUE", "error_rule_wrong_format_value"); define("ERROR_RULE_WRONG_DATE", "error_rule_wrong_date"); define("ERROR_RULE_UNKNOWN_FORMAT", "error_rule_unknown_format"); /** * @brief Valida el formato y valor de una fecha * * This is an implementation of the 'Strategy' pattern as it can be seen * http://www.phppatterns.com/index.php/article/articleview/13/1/1/. Here we use * this pattern to validate data received from forms. Its is useful since for example * we check in many places if a 'postId' is valid or not. We can put the * checkings inside the class and simply reuse this class wherever we want. If we ever *`change the format of the postId parameter, we only have to change the code of the * class that validates it and it will be automatically used everywhere. * * @author qDevel - info@qdevel.com * @date 05/03/2005 19:22 * @version 1.0 * @ingroup validation rule */ class qDateRule extends qRule { var $_format; /** * The constructor does nothing. */ function qDateRule($format) { $this->qRule(); $this->_format = $format; } /** * Add function info here */ function getFormat() { return $this->_format; } /** * Add function info here */ function setFormat($format) { $this->_format = $format; } /** * Validates the data. Does nothing here and it must be reimplemented by * every child class. */ function validate($value, $field = null) { switch ($this->_format) { case "dd/mm/yyyy": $regExp = "/([0-9]{1,2}).([0-9]{1,2}).([0-9]{4})/"; if (!preg_match($regExp, $value, $regs)) { $this->setError(ERROR_RULE_WRONG_FORMAT_VALUE); return false; } if (checkDate($regs[2], $regs[1], $regs[3])) { return true; } else { $this->setError(ERROR_RULE_WRONG_DATE); return false; } break; case "mm/dd/yyyy": $regExp = "/([0-9]{1,2}).([0-9]{1,2}).([0-9]{4})/"; if (!preg_match($regExp, $value, $regs)) { $this->setError(ERROR_RULE_WRONG_FORMAT_VALUE); return false; } if (checkDate($regs[1], $regs[2], $regs[3])) { return true; } else { $this->setError(ERROR_RULE_WRONG_DATE); return false; } break; case "yyyy/mm/dd": $regExp = "/([0-9]{4}).([0-9]{1,2}).([0-9]{1,2})/"; if (!preg_match($regExp, $value, $regs)) { $this->setError(ERROR_RULE_WRONG_FORMAT_VALUE); return false; } if (checkDate($regs[2], $regs[3], $regs[1])) { return true; } else { $this->setError(ERROR_RULE_WRONG_DATE); return false; } break; default: trigger_error("Unknown format '" . $this->_format . "'.", E_USER_ERROR); } $this->setError(ERROR_RULE_UNKNOWN_FORMAT); return false; } } ?>
lgpl-2.1
jetreports/EPPlus
EPPlusTest/FormulaParsing/Excel/Functions/Math/LargeTests.cs
11342
/******************************************************************************* * You may amend and distribute as you like, but don't remove this header! * * EPPlus provides server-side generation of Excel 2007/2010 spreadsheets. * See http://www.codeplex.com/EPPlus for details. * * Copyright (C) 2011-2017 Jan Källman, Matt Delaney, and others as noted in the source history. * * 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. * * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html * * All code and executables are provided "as is" with no warranty either express or implied. * The author accepts no liability for any damage or loss of business that this product may cause. * * For code change notes, see the source control history. *******************************************************************************/ using System; using EPPlusTest.FormulaParsing.TestHelpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using OfficeOpenXml.FormulaParsing.Excel.Functions.Math; using OfficeOpenXml; namespace EPPlusTest.FormulaParsing.Excel.Functions.Math { [TestClass] public class LargeTests : MathFunctionsTestBase { #region Large Function (Execute) Tests [TestMethod] public void LargeWithCorrectInputsReturnsCorrectValue() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = 45; worksheet.Cells["A3"].Value = 2; worksheet.Cells["A4"].Value = 789; worksheet.Cells["A5"].Value = 3; worksheet.Cells["B1"].Formula = "LARGE(A2:A5, 2)"; worksheet.Calculate(); Assert.AreEqual(45, worksheet.Cells["B1"].Value); } } [TestMethod] public void LargeWithNullFirstParameterReturnsPoundNum() { var function = new Large(); var result = function.Execute(FunctionsHelper.CreateArgs(null, 4), this.ParsingContext); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)result.Result).Type); using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["B1"].Formula = "LARGE(, 4)"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithNullSecondParameterReturnsPoundNum() { var function = new Large(); var result = function.Execute(FunctionsHelper.CreateArgs(4, null), this.ParsingContext); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)result.Result).Type); using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["B1"].Formula = "LARGE(4, )"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithNegativeSecondInputReturnsPoundNum() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = 45; worksheet.Cells["A3"].Value = 2; worksheet.Cells["A4"].Value = 789; worksheet.Cells["A5"].Value = 3; worksheet.Cells["B1"].Formula = "LARGE(A2:A5, -56)"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithSecondInputOutOfArrayIndexRangeReturnsPoundNum() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = 45; worksheet.Cells["A3"].Value = 2; worksheet.Cells["A4"].Value = 789; worksheet.Cells["A5"].Value = 3; worksheet.Cells["B1"].Formula = "LARGE(A2:A5, 67)"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithSecondInputAsNumericStringReturnsCorrectValue() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = 45; worksheet.Cells["A3"].Value = 2; worksheet.Cells["A4"].Value = 789; worksheet.Cells["A5"].Value = 3; worksheet.Cells["B1"].Formula = "LARGE(A2:A5, \"3\")"; worksheet.Calculate(); Assert.AreEqual(3, worksheet.Cells["B1"].Value); } } [TestMethod] public void LargeWithSecondInputAsStringReturnsPoundValue() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = 6; worksheet.Cells["A3"].Value = 67; worksheet.Cells["A4"].Value = 44; worksheet.Cells["B1"].Formula = "LARGE(A2:A4,\"string\")"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Value, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithArrayOfStringsReturnsPoundNum() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = "string"; worksheet.Cells["A3"].Value = "string"; worksheet.Cells["A4"].Value = "String"; worksheet.Cells["B1"].Formula = "LARGE(A2:A4, 2)"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithArrayOfNumericStringsReturnsPoundNum() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = "2"; worksheet.Cells["A3"].Value = "34"; worksheet.Cells["A4"].Value = "77"; worksheet.Cells["B1"].Formula = "LARGE(A2:A4, 3)"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithGeneralStringInputsReturnsPoundValue() { var function = new Large(); var result = function.Execute(FunctionsHelper.CreateArgs("string", "string"), this.ParsingContext); Assert.AreEqual(eErrorType.Value, ((ExcelErrorValue)result.Result).Type); } [TestMethod] public void LargeWithDatesFromDateFunctionInputsReturnsPoundNum() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["B1"].Formula = "LARGE(DATE(2017,6,15), DATE(2017,6,20))"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithSecondInputAsDateFromDateFunctionReturnsPoundNum() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["A2"].Value = 56; worksheet.Cells["A3"].Value = 34; worksheet.Cells["A4"].Value = 3; worksheet.Cells["B1"].Formula = "LARGE(A2:A4, DATE(2017,6,15))"; worksheet.Calculate(); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B1"].Value).Type); } } [TestMethod] public void LargeWithNoInputsReturnsPoundValue() { var function = new Large(); var result = function.Execute(FunctionsHelper.CreateArgs(), this.ParsingContext); Assert.AreEqual(eErrorType.Value, ((ExcelErrorValue)result.Result).Type); } [TestMethod] public void LargeWithDatesAsStringsInputsReturnsPoundNum() { var function = new Large(); var result = function.Execute(FunctionsHelper.CreateArgs("5/15/2017", 6), this.ParsingContext); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)result.Result).Type); } [TestMethod] public void LargeWithNumericStringInputReturnsPoundNum() { var function = new Large(); var result = function.Execute(FunctionsHelper.CreateArgs("3", "56"), this.ParsingContext); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)result.Result).Type); } [TestMethod] public void LargeShouldReturnTheLargestNumberIf1() { var func = new Large(); var args = FunctionsHelper.CreateArgs(FunctionsHelper.CreateArgs(1, 2, 3), 1); var result = func.Execute(args, this.ParsingContext); Assert.AreEqual(3, result.Result); } [TestMethod] public void LargeShouldReturnTheSecondLargestNumberIf2() { var func = new Large(); var args = FunctionsHelper.CreateArgs(FunctionsHelper.CreateArgs(4, 1, 2, 3), 2); var result = func.Execute(args, this.ParsingContext); Assert.AreEqual(3, result.Result); } [TestMethod] public void LargeShouldPoundNumIfIndexOutOfBounds() { var func = new Large(); var args = FunctionsHelper.CreateArgs(FunctionsHelper.CreateArgs(4, 1, 2, 3), 6); var result = func.Execute(args, this.ParsingContext); Assert.AreEqual(OfficeOpenXml.FormulaParsing.ExpressionGraph.DataType.ExcelError, result.DataType); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)(result.Result)).Type); } [TestMethod] public void LargeWithInvalidArgumentReturnsPoundValue() { var func = new Large(); var args = FunctionsHelper.CreateArgs(); var result = func.Execute(args, this.ParsingContext); Assert.AreEqual(eErrorType.Value, ((ExcelErrorValue)result.Result).Type); } [TestMethod] public void LargeWithSomeValidSomeInvalidInputsReturnsCorrectValue() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["B1"].Formula = "LARGE({1,2,3,\"Cats\"}, 1)"; worksheet.Calculate(); Assert.AreEqual(3d, worksheet.Cells["B1"].Value); } } [TestMethod] public void LargeWithMixedNumbersAndLogicReturnsCorrectValue() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["B1"].Formula = "LARGE({TRUE, 67, \"1000\"}, 1)"; worksheet.Cells["B2"].Formula = "LARGE({TRUE, 99, \"345\"}, 2)"; worksheet.Calculate(); Assert.AreEqual(67d, worksheet.Cells["B1"].Value); Assert.AreEqual(eErrorType.Num, ((ExcelErrorValue)worksheet.Cells["B2"].Value).Type); } } [TestMethod] public void LargeWithDoubleInputsReturnsCorrectValue() { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("Sheet1"); worksheet.Cells["B1"].Value = 45.6; worksheet.Cells["B2"].Value = 12.2; worksheet.Cells["B3"].Value = 13.5; worksheet.Cells["B4"].Value = 158.2; worksheet.Cells["B10"].Formula = "LARGE(B1:B4, 2)"; worksheet.Cells["B11"].Formula = "LARGE(B1:B4, \"2\")"; worksheet.Calculate(); Assert.AreEqual(45.6d, worksheet.Cells["B10"].Value); Assert.AreEqual(45.6d, worksheet.Cells["B11"].Value); } } #endregion } }
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/layout/richtext/RichTextConverterRegistry.java
1691
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.layout.richtext; import java.util.HashMap; public class RichTextConverterRegistry { private static RichTextConverterRegistry registry; public static synchronized RichTextConverterRegistry getRegistry() { if ( registry == null ) { registry = new RichTextConverterRegistry(); } return registry; } private HashMap<String, RichTextConverter> richTextConverters; private RichTextConverterRegistry() { richTextConverters = new HashMap<String, RichTextConverter>(); richTextConverters.put( "text/html", new HtmlRichTextConverter() ); richTextConverters.put( "text/rtf", new RtfRichTextConverter() ); } public RichTextConverter getConverter( final String key ) { if ( key == null ) { return null; } return richTextConverters.get( key ); } }
lgpl-2.1
comundus/opencms-comundus
src/main/java/org/opencms/widgets/CmsSelectWidget.java
6121
/* * File : $Source: /usr/local/cvs/opencms/src/org/opencms/widgets/CmsSelectWidget.java,v $ * Date : $Date: 2008-02-27 12:05:44 $ * Version: $Revision: 1.15 $ * * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software GmbH, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 */ package org.opencms.widgets; import org.opencms.file.CmsObject; import org.opencms.util.CmsMacroResolver; import java.util.Iterator; import java.util.List; /** * Provides a widget for a standard HTML form select box.<p> * * Please see the documentation of <code>{@link org.opencms.widgets.CmsSelectWidgetOption}</code> for a description * about the configuration String syntax for the select options.<p> * * The select widget does use the following select options:<ul> * <li><code>{@link org.opencms.widgets.CmsSelectWidgetOption#getValue()}</code> for the <code>value</code> of the HTML select box * <li><code>{@link org.opencms.widgets.CmsSelectWidgetOption#isDefault()}</code> for pre-selecting a specific value * <li><code>{@link org.opencms.widgets.CmsSelectWidgetOption#getOption()}</code> for the <code>option</code> of the HTML select box * </ul> * <p> * * @author Andreas Zahner * * @version $Revision: 1.15 $ * * @since 6.0.0 */ public class CmsSelectWidget extends A_CmsSelectWidget { /** * Creates a new select widget.<p> */ public CmsSelectWidget() { // empty constructor is required for class registration super(); } /** * Creates a select widget with the select options specified in the given configuration List.<p> * * The list elements must be of type <code>{@link CmsSelectWidgetOption}</code>.<p> * * @param configuration the configuration (possible options) for the select widget * * @see CmsSelectWidgetOption */ public CmsSelectWidget(List configuration) { super(configuration); } /** * Creates a select widget with the specified select options.<p> * * @param configuration the configuration (possible options) for the select box */ public CmsSelectWidget(String configuration) { super(configuration); } /** * @see org.opencms.widgets.I_CmsWidget#getDialogWidget(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) */ public String getDialogWidget(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { String id = param.getId(); StringBuffer result = new StringBuffer(16); result.append("<td class=\"xmlTd\" style=\"height: 25px;\"><select class=\"xmlInput"); if (param.hasError()) { result.append(" xmlInputError"); } result.append("\" name=\""); result.append(id); result.append("\" id=\""); result.append(id); result.append("\">"); // get select box options from default value String List options = parseSelectOptions(cms, widgetDialog, param); String selected = getSelectedValue(cms, param); Iterator i = options.iterator(); while (i.hasNext()) { CmsSelectWidgetOption option = (CmsSelectWidgetOption)i.next(); // create the option result.append("<option value=\""); result.append(option.getValue()); result.append("\""); if ((selected != null) && selected.equals(option.getValue())) { result.append(" selected=\"selected\""); } result.append(">"); result.append(option.getOption()); result.append("</option>"); } result.append("</select>"); result.append("</td>"); return result.toString(); } /** * @see org.opencms.widgets.A_CmsWidget#getWidgetStringValue(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) */ public String getWidgetStringValue(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { String result = super.getWidgetStringValue(cms, widgetDialog, param); String configuration = CmsMacroResolver.resolveMacros(getConfiguration(), cms, widgetDialog.getMessages()); if (configuration == null) { configuration = param.getDefault(cms); } List options = CmsSelectWidgetOption.parseOptions(configuration); for (int m = 0; m < options.size(); m++) { CmsSelectWidgetOption option = (CmsSelectWidgetOption)options.get(m); if (result.equals(option.getValue())) { result = option.getOption(); break; } } return result; } /** * @see org.opencms.widgets.I_CmsWidget#newInstance() */ public I_CmsWidget newInstance() { return new CmsSelectWidget(getConfiguration()); } }
lgpl-2.1
TeamupCom/tinymce
modules/tinymce/src/core/test/ts/browser/dom/NodePathTest.ts
1322
import { describe, it } from '@ephox/bedrock-client'; import { LegacyUnit } from '@ephox/mcagar'; import { assert } from 'chai'; import * as NodePath from 'tinymce/core/dom/NodePath'; import * as ViewBlock from '../../module/test/ViewBlock'; describe('browser.tinymce.core.dom.NodePathTest', () => { const viewBlock = ViewBlock.bddSetup(); const getRoot = viewBlock.get; const setupHtml = viewBlock.update; it('create', () => { setupHtml('<p>a<b>12<input></b></p>'); assert.deepEqual(NodePath.create(getRoot(), getRoot().firstChild), [ 0 ]); assert.deepEqual(NodePath.create(getRoot(), getRoot().firstChild.firstChild), [ 0, 0 ]); assert.deepEqual(NodePath.create(getRoot(), getRoot().firstChild.lastChild.lastChild), [ 1, 1, 0 ]); }); it('resolve', () => { setupHtml('<p>a<b>12<input></b></p>'); LegacyUnit.equalDom(NodePath.resolve(getRoot(), NodePath.create(getRoot(), getRoot().firstChild)), getRoot().firstChild); LegacyUnit.equalDom( NodePath.resolve(getRoot(), NodePath.create(getRoot(), getRoot().firstChild.firstChild)), getRoot().firstChild.firstChild ); LegacyUnit.equalDom( NodePath.resolve(getRoot(), NodePath.create(getRoot(), getRoot().firstChild.lastChild.lastChild)), getRoot().firstChild.lastChild.lastChild ); }); });
lgpl-2.1
youfoh/webkit-efl
Source/WebCore/rendering/RenderTheme.cpp
43916
/** * This file is part of the theme implementation for form controls in WebCore. * * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Computer, Inc. * * 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 "config.h" #include "RenderTheme.h" #include "CSSValueKeywords.h" #include "Document.h" #include "FileList.h" #include "FileSystem.h" #include "FloatConversion.h" #include "FocusController.h" #include "FontSelector.h" #include "Frame.h" #include "FrameSelection.h" #include "GraphicsContext.h" #include "HTMLInputElement.h" #include "HTMLNames.h" #include "LocalizedStrings.h" #include "MediaControlElements.h" #include "Page.h" #include "PaintInfo.h" #include "RenderStyle.h" #include "RenderView.h" #include "Settings.h" #include "StringTruncator.h" #include "TextControlInnerElements.h" #if ENABLE(METER_ELEMENT) #include "HTMLMeterElement.h" #include "RenderMeter.h" #endif #if ENABLE(INPUT_SPEECH) #include "RenderInputSpeech.h" #endif #if ENABLE(DATALIST_ELEMENT) #include "ElementShadow.h" #include "HTMLCollection.h" #include "HTMLDataListElement.h" #include "HTMLOptionElement.h" #include "HTMLParserIdioms.h" #endif // The methods in this file are shared by all themes on every platform. namespace WebCore { using namespace HTMLNames; static Color& customFocusRingColor() { DEFINE_STATIC_LOCAL(Color, color, ()); return color; } RenderTheme::RenderTheme() #if USE(NEW_THEME) : m_theme(platformTheme()) #endif { } void RenderTheme::adjustStyle(StyleResolver* styleResolver, RenderStyle* style, Element* e, bool UAHasAppearance, const BorderData& border, const FillLayer& background, const Color& backgroundColor) { // Force inline and table display styles to be inline-block (except for table- which is block) ControlPart part = style->appearance(); if (style->display() == INLINE || style->display() == INLINE_TABLE || style->display() == TABLE_ROW_GROUP || style->display() == TABLE_HEADER_GROUP || style->display() == TABLE_FOOTER_GROUP || style->display() == TABLE_ROW || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_COLUMN || style->display() == TABLE_CELL || style->display() == TABLE_CAPTION) style->setDisplay(INLINE_BLOCK); else if (style->display() == COMPACT || style->display() == RUN_IN || style->display() == LIST_ITEM || style->display() == TABLE) style->setDisplay(BLOCK); if (UAHasAppearance && isControlStyled(style, border, background, backgroundColor)) { if (part == MenulistPart) { style->setAppearance(MenulistButtonPart); part = MenulistButtonPart; } else style->setAppearance(NoControlPart); } if (!style->hasAppearance()) return; // Never support box-shadow on native controls. style->setBoxShadow(nullptr); #if USE(NEW_THEME) switch (part) { case CheckboxPart: case InnerSpinButtonPart: case RadioPart: case PushButtonPart: case SquareButtonPart: case DefaultButtonPart: case ButtonPart: { // Border LengthBox borderBox(style->borderTopWidth(), style->borderRightWidth(), style->borderBottomWidth(), style->borderLeftWidth()); borderBox = m_theme->controlBorder(part, style->font(), borderBox, style->effectiveZoom()); if (borderBox.top().value() != static_cast<int>(style->borderTopWidth())) { if (borderBox.top().value()) style->setBorderTopWidth(borderBox.top().value()); else style->resetBorderTop(); } if (borderBox.right().value() != static_cast<int>(style->borderRightWidth())) { if (borderBox.right().value()) style->setBorderRightWidth(borderBox.right().value()); else style->resetBorderRight(); } if (borderBox.bottom().value() != static_cast<int>(style->borderBottomWidth())) { style->setBorderBottomWidth(borderBox.bottom().value()); if (borderBox.bottom().value()) style->setBorderBottomWidth(borderBox.bottom().value()); else style->resetBorderBottom(); } if (borderBox.left().value() != static_cast<int>(style->borderLeftWidth())) { style->setBorderLeftWidth(borderBox.left().value()); if (borderBox.left().value()) style->setBorderLeftWidth(borderBox.left().value()); else style->resetBorderLeft(); } // Padding LengthBox paddingBox = m_theme->controlPadding(part, style->font(), style->paddingBox(), style->effectiveZoom()); if (paddingBox != style->paddingBox()) style->setPaddingBox(paddingBox); // Whitespace if (m_theme->controlRequiresPreWhiteSpace(part)) style->setWhiteSpace(PRE); // Width / Height // The width and height here are affected by the zoom. // FIXME: Check is flawed, since it doesn't take min-width/max-width into account. LengthSize controlSize = m_theme->controlSize(part, style->font(), LengthSize(style->width(), style->height()), style->effectiveZoom()); if (controlSize.width() != style->width()) style->setWidth(controlSize.width()); if (controlSize.height() != style->height()) style->setHeight(controlSize.height()); // Min-Width / Min-Height LengthSize minControlSize = m_theme->minimumControlSize(part, style->font(), style->effectiveZoom()); if (minControlSize.width() != style->minWidth()) style->setMinWidth(minControlSize.width()); if (minControlSize.height() != style->minHeight()) style->setMinHeight(minControlSize.height()); // Font FontDescription controlFont = m_theme->controlFont(part, style->font(), style->effectiveZoom()); if (controlFont != style->font().fontDescription()) { // Reset our line-height style->setLineHeight(RenderStyle::initialLineHeight()); // Now update our font. if (style->setFontDescription(controlFont)) style->font().update(0); } } default: break; } #endif // Call the appropriate style adjustment method based off the appearance value. switch (style->appearance()) { #if !USE(NEW_THEME) case CheckboxPart: return adjustCheckboxStyle(styleResolver, style, e); case RadioPart: return adjustRadioStyle(styleResolver, style, e); case PushButtonPart: case SquareButtonPart: case DefaultButtonPart: case ButtonPart: return adjustButtonStyle(styleResolver, style, e); case InnerSpinButtonPart: return adjustInnerSpinButtonStyle(styleResolver, style, e); #endif case TextFieldPart: return adjustTextFieldStyle(styleResolver, style, e); case TextAreaPart: return adjustTextAreaStyle(styleResolver, style, e); case MenulistPart: return adjustMenuListStyle(styleResolver, style, e); case MenulistButtonPart: return adjustMenuListButtonStyle(styleResolver, style, e); case MediaPlayButtonPart: case MediaCurrentTimePart: case MediaTimeRemainingPart: case MediaEnterFullscreenButtonPart: case MediaExitFullscreenButtonPart: case MediaMuteButtonPart: case MediaVolumeSliderContainerPart: return adjustMediaControlStyle(styleResolver, style, e); case MediaSliderPart: case MediaVolumeSliderPart: case MediaFullScreenVolumeSliderPart: case SliderHorizontalPart: case SliderVerticalPart: return adjustSliderTrackStyle(styleResolver, style, e); case SliderThumbHorizontalPart: case SliderThumbVerticalPart: return adjustSliderThumbStyle(styleResolver, style, e); case SearchFieldPart: return adjustSearchFieldStyle(styleResolver, style, e); case SearchFieldCancelButtonPart: return adjustSearchFieldCancelButtonStyle(styleResolver, style, e); case SearchFieldDecorationPart: return adjustSearchFieldDecorationStyle(styleResolver, style, e); case SearchFieldResultsDecorationPart: return adjustSearchFieldResultsDecorationStyle(styleResolver, style, e); case SearchFieldResultsButtonPart: return adjustSearchFieldResultsButtonStyle(styleResolver, style, e); #if ENABLE(PROGRESS_ELEMENT) case ProgressBarPart: return adjustProgressBarStyle(styleResolver, style, e); #endif #if ENABLE(METER_ELEMENT) case MeterPart: case RelevancyLevelIndicatorPart: case ContinuousCapacityLevelIndicatorPart: case DiscreteCapacityLevelIndicatorPart: case RatingLevelIndicatorPart: return adjustMeterStyle(styleResolver, style, e); #endif #if ENABLE(INPUT_SPEECH) case InputSpeechButtonPart: return adjustInputFieldSpeechButtonStyle(styleResolver, style, e); #endif default: break; } } bool RenderTheme::paint(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r) { // If painting is disabled, but we aren't updating control tints, then just bail. // If we are updating control tints, just schedule a repaint if the theme supports tinting // for that control. if (paintInfo.context->updatingControlTints()) { if (controlSupportsTints(o)) o->repaint(); return false; } if (paintInfo.context->paintingDisabled()) return false; ControlPart part = o->style()->appearance(); #if USE(NEW_THEME) switch (part) { case CheckboxPart: case RadioPart: case PushButtonPart: case SquareButtonPart: case DefaultButtonPart: case ButtonPart: case InnerSpinButtonPart: m_theme->paint(part, controlStatesForRenderer(o), const_cast<GraphicsContext*>(paintInfo.context), r, o->style()->effectiveZoom(), o->view()->frameView()); return false; default: break; } #endif // Call the appropriate paint method based off the appearance value. switch (part) { #if !USE(NEW_THEME) case CheckboxPart: return paintCheckbox(o, paintInfo, r); case RadioPart: return paintRadio(o, paintInfo, r); case PushButtonPart: case SquareButtonPart: case DefaultButtonPart: case ButtonPart: return paintButton(o, paintInfo, r); case InnerSpinButtonPart: return paintInnerSpinButton(o, paintInfo, r); #endif case MenulistPart: return paintMenuList(o, paintInfo, r); #if ENABLE(METER_ELEMENT) case MeterPart: case RelevancyLevelIndicatorPart: case ContinuousCapacityLevelIndicatorPart: case DiscreteCapacityLevelIndicatorPart: case RatingLevelIndicatorPart: return paintMeter(o, paintInfo, r); #endif #if ENABLE(PROGRESS_ELEMENT) case ProgressBarPart: return paintProgressBar(o, paintInfo, r); #endif case SliderHorizontalPart: case SliderVerticalPart: return paintSliderTrack(o, paintInfo, r); case SliderThumbHorizontalPart: case SliderThumbVerticalPart: return paintSliderThumb(o, paintInfo, r); case MediaEnterFullscreenButtonPart: case MediaExitFullscreenButtonPart: return paintMediaFullscreenButton(o, paintInfo, r); case MediaPlayButtonPart: return paintMediaPlayButton(o, paintInfo, r); case MediaOverlayPlayButtonPart: return paintMediaOverlayPlayButton(o, paintInfo, r); case MediaMuteButtonPart: return paintMediaMuteButton(o, paintInfo, r); case MediaSeekBackButtonPart: return paintMediaSeekBackButton(o, paintInfo, r); case MediaSeekForwardButtonPart: return paintMediaSeekForwardButton(o, paintInfo, r); case MediaRewindButtonPart: return paintMediaRewindButton(o, paintInfo, r); case MediaReturnToRealtimeButtonPart: return paintMediaReturnToRealtimeButton(o, paintInfo, r); case MediaToggleClosedCaptionsButtonPart: return paintMediaToggleClosedCaptionsButton(o, paintInfo, r); case MediaSliderPart: return paintMediaSliderTrack(o, paintInfo, r); case MediaSliderThumbPart: return paintMediaSliderThumb(o, paintInfo, r); case MediaVolumeSliderMuteButtonPart: return paintMediaMuteButton(o, paintInfo, r); case MediaVolumeSliderContainerPart: return paintMediaVolumeSliderContainer(o, paintInfo, r); case MediaVolumeSliderPart: return paintMediaVolumeSliderTrack(o, paintInfo, r); case MediaVolumeSliderThumbPart: return paintMediaVolumeSliderThumb(o, paintInfo, r); case MediaFullScreenVolumeSliderPart: return paintMediaFullScreenVolumeSliderTrack(o, paintInfo, r); case MediaFullScreenVolumeSliderThumbPart: return paintMediaFullScreenVolumeSliderThumb(o, paintInfo, r); case MediaTimeRemainingPart: return paintMediaTimeRemaining(o, paintInfo, r); case MediaCurrentTimePart: return paintMediaCurrentTime(o, paintInfo, r); case MediaControlsBackgroundPart: return paintMediaControlsBackground(o, paintInfo, r); case MenulistButtonPart: case TextFieldPart: case TextAreaPart: case ListboxPart: return true; case SearchFieldPart: return paintSearchField(o, paintInfo, r); case SearchFieldCancelButtonPart: return paintSearchFieldCancelButton(o, paintInfo, r); case SearchFieldDecorationPart: return paintSearchFieldDecoration(o, paintInfo, r); case SearchFieldResultsDecorationPart: return paintSearchFieldResultsDecoration(o, paintInfo, r); case SearchFieldResultsButtonPart: return paintSearchFieldResultsButton(o, paintInfo, r); #if ENABLE(INPUT_SPEECH) case InputSpeechButtonPart: return paintInputFieldSpeechButton(o, paintInfo, r); #endif default: break; } return true; // We don't support the appearance, so let the normal background/border paint. } bool RenderTheme::paintBorderOnly(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r) { if (paintInfo.context->paintingDisabled()) return false; // Call the appropriate paint method based off the appearance value. switch (o->style()->appearance()) { case TextFieldPart: return paintTextField(o, paintInfo, r); case ListboxPart: case TextAreaPart: return paintTextArea(o, paintInfo, r); case MenulistButtonPart: case SearchFieldPart: return true; case CheckboxPart: case RadioPart: case PushButtonPart: case SquareButtonPart: case DefaultButtonPart: case ButtonPart: case MenulistPart: #if ENABLE(METER_ELEMENT) case MeterPart: case RelevancyLevelIndicatorPart: case ContinuousCapacityLevelIndicatorPart: case DiscreteCapacityLevelIndicatorPart: case RatingLevelIndicatorPart: #endif #if ENABLE(PROGRESS_ELEMENT) case ProgressBarPart: #endif case SliderHorizontalPart: case SliderVerticalPart: case SliderThumbHorizontalPart: case SliderThumbVerticalPart: case SearchFieldCancelButtonPart: case SearchFieldDecorationPart: case SearchFieldResultsDecorationPart: case SearchFieldResultsButtonPart: #if ENABLE(INPUT_SPEECH) case InputSpeechButtonPart: #endif default: break; } return false; } bool RenderTheme::paintDecorations(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r) { if (paintInfo.context->paintingDisabled()) return false; // Call the appropriate paint method based off the appearance value. switch (o->style()->appearance()) { case MenulistButtonPart: return paintMenuListButton(o, paintInfo, r); case TextFieldPart: case TextAreaPart: case ListboxPart: case CheckboxPart: case RadioPart: case PushButtonPart: case SquareButtonPart: case DefaultButtonPart: case ButtonPart: case MenulistPart: #if ENABLE(METER_ELEMENT) case MeterPart: case RelevancyLevelIndicatorPart: case ContinuousCapacityLevelIndicatorPart: case DiscreteCapacityLevelIndicatorPart: case RatingLevelIndicatorPart: #endif #if ENABLE(PROGRESS_ELEMENT) case ProgressBarPart: #endif case SliderHorizontalPart: case SliderVerticalPart: case SliderThumbHorizontalPart: case SliderThumbVerticalPart: case SearchFieldPart: case SearchFieldCancelButtonPart: case SearchFieldDecorationPart: case SearchFieldResultsDecorationPart: case SearchFieldResultsButtonPart: #if ENABLE(INPUT_SPEECH) case InputSpeechButtonPart: #endif default: break; } return false; } #if ENABLE(VIDEO) String RenderTheme::formatMediaControlsTime(float time) const { if (!isfinite(time)) time = 0; int seconds = (int)fabsf(time); int hours = seconds / (60 * 60); int minutes = (seconds / 60) % 60; seconds %= 60; if (hours) { if (hours > 9) return String::format("%s%02d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds); return String::format("%s%01d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds); } return String::format("%s%02d:%02d", (time < 0 ? "-" : ""), minutes, seconds); } String RenderTheme::formatMediaControlsCurrentTime(float currentTime, float /*duration*/) const { return formatMediaControlsTime(currentTime); } String RenderTheme::formatMediaControlsRemainingTime(float currentTime, float duration) const { return formatMediaControlsTime(currentTime - duration); } IntPoint RenderTheme::volumeSliderOffsetFromMuteButton(RenderBox* muteButtonBox, const IntSize& size) const { int y = -size.height(); FloatPoint absPoint = muteButtonBox->localToAbsolute(FloatPoint(muteButtonBox->pixelSnappedOffsetLeft(), y), true, true); if (absPoint.y() < 0) y = muteButtonBox->height(); return IntPoint(0, y); } #endif Color RenderTheme::activeSelectionBackgroundColor() const { if (!m_activeSelectionBackgroundColor.isValid()) m_activeSelectionBackgroundColor = platformActiveSelectionBackgroundColor().blendWithWhite(); return m_activeSelectionBackgroundColor; } Color RenderTheme::inactiveSelectionBackgroundColor() const { if (!m_inactiveSelectionBackgroundColor.isValid()) m_inactiveSelectionBackgroundColor = platformInactiveSelectionBackgroundColor().blendWithWhite(); return m_inactiveSelectionBackgroundColor; } Color RenderTheme::activeSelectionForegroundColor() const { if (!m_activeSelectionForegroundColor.isValid() && supportsSelectionForegroundColors()) m_activeSelectionForegroundColor = platformActiveSelectionForegroundColor(); return m_activeSelectionForegroundColor; } Color RenderTheme::inactiveSelectionForegroundColor() const { if (!m_inactiveSelectionForegroundColor.isValid() && supportsSelectionForegroundColors()) m_inactiveSelectionForegroundColor = platformInactiveSelectionForegroundColor(); return m_inactiveSelectionForegroundColor; } Color RenderTheme::activeListBoxSelectionBackgroundColor() const { if (!m_activeListBoxSelectionBackgroundColor.isValid()) m_activeListBoxSelectionBackgroundColor = platformActiveListBoxSelectionBackgroundColor(); return m_activeListBoxSelectionBackgroundColor; } Color RenderTheme::inactiveListBoxSelectionBackgroundColor() const { if (!m_inactiveListBoxSelectionBackgroundColor.isValid()) m_inactiveListBoxSelectionBackgroundColor = platformInactiveListBoxSelectionBackgroundColor(); return m_inactiveListBoxSelectionBackgroundColor; } Color RenderTheme::activeListBoxSelectionForegroundColor() const { if (!m_activeListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors()) m_activeListBoxSelectionForegroundColor = platformActiveListBoxSelectionForegroundColor(); return m_activeListBoxSelectionForegroundColor; } Color RenderTheme::inactiveListBoxSelectionForegroundColor() const { if (!m_inactiveListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors()) m_inactiveListBoxSelectionForegroundColor = platformInactiveListBoxSelectionForegroundColor(); return m_inactiveListBoxSelectionForegroundColor; } Color RenderTheme::platformActiveSelectionBackgroundColor() const { // Use a blue color by default if the platform theme doesn't define anything. return Color(0, 0, 255); } Color RenderTheme::platformActiveSelectionForegroundColor() const { // Use a white color by default if the platform theme doesn't define anything. return Color::white; } Color RenderTheme::platformInactiveSelectionBackgroundColor() const { // Use a grey color by default if the platform theme doesn't define anything. // This color matches Firefox's inactive color. return Color(176, 176, 176); } Color RenderTheme::platformInactiveSelectionForegroundColor() const { // Use a black color by default. return Color::black; } Color RenderTheme::platformActiveListBoxSelectionBackgroundColor() const { return platformActiveSelectionBackgroundColor(); } Color RenderTheme::platformActiveListBoxSelectionForegroundColor() const { return platformActiveSelectionForegroundColor(); } Color RenderTheme::platformInactiveListBoxSelectionBackgroundColor() const { return platformInactiveSelectionBackgroundColor(); } Color RenderTheme::platformInactiveListBoxSelectionForegroundColor() const { return platformInactiveSelectionForegroundColor(); } #if ENABLE(CALENDAR_PICKER) CString RenderTheme::extraCalendarPickerStyleSheet() { return CString(); } #endif LayoutUnit RenderTheme::baselinePosition(const RenderObject* o) const { if (!o->isBox()) return 0; const RenderBox* box = toRenderBox(o); #if USE(NEW_THEME) return box->height() + box->marginTop() + m_theme->baselinePositionAdjustment(o->style()->appearance()) * o->style()->effectiveZoom(); #else return box->height() + box->marginTop(); #endif } bool RenderTheme::isControlContainer(ControlPart appearance) const { // There are more leaves than this, but we'll patch this function as we add support for // more controls. return appearance != CheckboxPart && appearance != RadioPart; } bool RenderTheme::isControlStyled(const RenderStyle* style, const BorderData& border, const FillLayer& background, const Color& backgroundColor) const { switch (style->appearance()) { case PushButtonPart: case SquareButtonPart: case DefaultButtonPart: case ButtonPart: case ListboxPart: case MenulistPart: case ProgressBarPart: case MeterPart: case RelevancyLevelIndicatorPart: case ContinuousCapacityLevelIndicatorPart: case DiscreteCapacityLevelIndicatorPart: case RatingLevelIndicatorPart: #if ENABLE(TIZEN_SEARCH_FIELD_STYLE) case SearchFieldPart: #else // FIXME: Uncomment this when making search fields style-able. // case SearchFieldPart: #endif case TextFieldPart: case TextAreaPart: // Test the style to see if the UA border and background match. return (style->border() != border || *style->backgroundLayers() != background || style->visitedDependentColor(CSSPropertyBackgroundColor) != backgroundColor); default: return false; } } void RenderTheme::adjustRepaintRect(const RenderObject* o, IntRect& r) { #if USE(NEW_THEME) m_theme->inflateControlPaintRect(o->style()->appearance(), controlStatesForRenderer(o), r, o->style()->effectiveZoom()); #endif } bool RenderTheme::supportsFocusRing(const RenderStyle* style) const { return (style->hasAppearance() && style->appearance() != TextFieldPart && style->appearance() != TextAreaPart && style->appearance() != MenulistButtonPart && style->appearance() != ListboxPart); } bool RenderTheme::stateChanged(RenderObject* o, ControlState state) const { // Default implementation assumes the controls don't respond to changes in :hover state if (state == HoverState && !supportsHover(o->style())) return false; // Assume pressed state is only responded to if the control is enabled. if (state == PressedState && !isEnabled(o)) return false; // Repaint the control. o->repaint(); return true; } ControlStates RenderTheme::controlStatesForRenderer(const RenderObject* o) const { ControlStates result = 0; if (isHovered(o)) { result |= HoverState; if (isSpinUpButtonPartHovered(o)) result |= SpinUpState; } if (isPressed(o)) { result |= PressedState; if (isSpinUpButtonPartPressed(o)) result |= SpinUpState; } if (isFocused(o) && o->style()->outlineStyleIsAuto()) result |= FocusState; if (isEnabled(o)) result |= EnabledState; if (isChecked(o)) result |= CheckedState; if (isReadOnlyControl(o)) result |= ReadOnlyState; if (isDefault(o)) result |= DefaultState; if (!isActive(o)) result |= WindowInactiveState; if (isIndeterminate(o)) result |= IndeterminateState; return result; } bool RenderTheme::isActive(const RenderObject* o) const { Node* node = o->node(); if (!node) return false; Frame* frame = node->document()->frame(); if (!frame) return false; Page* page = frame->page(); if (!page) return false; return page->focusController()->isActive(); } bool RenderTheme::isChecked(const RenderObject* o) const { if (!o->node()) return false; HTMLInputElement* inputElement = o->node()->toInputElement(); if (!inputElement) return false; return inputElement->shouldAppearChecked(); } bool RenderTheme::isIndeterminate(const RenderObject* o) const { if (!o->node()) return false; HTMLInputElement* inputElement = o->node()->toInputElement(); if (!inputElement) return false; return inputElement->isIndeterminate(); } bool RenderTheme::isEnabled(const RenderObject* o) const { Node* node = o->node(); if (!node || !node->isElementNode()) return true; return static_cast<Element*>(node)->isEnabledFormControl(); } bool RenderTheme::isFocused(const RenderObject* o) const { Node* node = o->node(); if (!node) return false; node = node->focusDelegate(); Document* document = node->document(); Frame* frame = document->frame(); return node == document->focusedNode() && frame && frame->selection()->isFocusedAndActive(); } bool RenderTheme::isPressed(const RenderObject* o) const { if (!o->node()) return false; return o->node()->active(); } bool RenderTheme::isSpinUpButtonPartPressed(const RenderObject* o) const { Node* node = o->node(); if (!node || !node->active() || !node->isElementNode() || !static_cast<Element*>(node)->isSpinButtonElement()) return false; SpinButtonElement* element = static_cast<SpinButtonElement*>(node); return element->upDownState() == SpinButtonElement::Up; } bool RenderTheme::isReadOnlyControl(const RenderObject* o) const { Node* node = o->node(); if (!node || !node->isElementNode()) return false; return static_cast<Element*>(node)->isReadOnlyFormControl(); } bool RenderTheme::isHovered(const RenderObject* o) const { Node* node = o->node(); if (!node) return false; if (!node->isElementNode() || !static_cast<Element*>(node)->isSpinButtonElement()) return node->hovered(); SpinButtonElement* element = static_cast<SpinButtonElement*>(node); return element->hovered() && element->upDownState() != SpinButtonElement::Indeterminate; } bool RenderTheme::isSpinUpButtonPartHovered(const RenderObject* o) const { Node* node = o->node(); if (!node || !node->isElementNode() || !static_cast<Element*>(node)->isSpinButtonElement()) return false; SpinButtonElement* element = static_cast<SpinButtonElement*>(node); return element->upDownState() == SpinButtonElement::Up; } bool RenderTheme::isDefault(const RenderObject* o) const { // A button should only have the default appearance if the page is active if (!isActive(o)) return false; if (!o->document()) return false; Settings* settings = o->document()->settings(); if (!settings || !settings->inApplicationChromeMode()) return false; return o->style()->appearance() == DefaultButtonPart; } #if !USE(NEW_THEME) void RenderTheme::adjustCheckboxStyle(StyleResolver*, RenderStyle* style, Element*) const { // A summary of the rules for checkbox designed to match WinIE: // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.) // font-size - not honored (control has no text), but we use it to decide which control size to use. setCheckboxSize(style); // padding - not honored by WinIE, needs to be removed. style->resetPadding(); // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme) // for now, we will not honor it. style->resetBorder(); style->setBoxShadow(nullptr); } void RenderTheme::adjustRadioStyle(StyleResolver*, RenderStyle* style, Element*) const { // A summary of the rules for checkbox designed to match WinIE: // width/height - honored (WinIE actually scales its control for small widths, but lets it overflow for small heights.) // font-size - not honored (control has no text), but we use it to decide which control size to use. setRadioSize(style); // padding - not honored by WinIE, needs to be removed. style->resetPadding(); // border - honored by WinIE, but looks terrible (just paints in the control box and turns off the Windows XP theme) // for now, we will not honor it. style->resetBorder(); style->setBoxShadow(nullptr); } void RenderTheme::adjustButtonStyle(StyleResolver*, RenderStyle* style, Element*) const { // Most platforms will completely honor all CSS, and so we have no need to adjust the style // at all by default. We will still allow the theme a crack at setting up a desired vertical size. setButtonSize(style); } void RenderTheme::adjustInnerSpinButtonStyle(StyleResolver*, RenderStyle*, Element*) const { } #endif void RenderTheme::adjustTextFieldStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustTextAreaStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustMenuListStyle(StyleResolver*, RenderStyle*, Element*) const { } #if ENABLE(INPUT_SPEECH) void RenderTheme::adjustInputFieldSpeechButtonStyle(StyleResolver* styleResolver, RenderStyle* style, Element* element) const { RenderInputSpeech::adjustInputFieldSpeechButtonStyle(styleResolver, style, element); } bool RenderTheme::paintInputFieldSpeechButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect) { return RenderInputSpeech::paintInputFieldSpeechButton(object, paintInfo, rect); } #endif #if ENABLE(METER_ELEMENT) void RenderTheme::adjustMeterStyle(StyleResolver*, RenderStyle* style, Element*) const { style->setBoxShadow(nullptr); } IntSize RenderTheme::meterSizeForBounds(const RenderMeter*, const IntRect& bounds) const { return bounds.size(); } bool RenderTheme::supportsMeter(ControlPart) const { return false; } bool RenderTheme::paintMeter(RenderObject*, const PaintInfo&, const IntRect&) { return true; } #endif #if ENABLE(DATALIST_ELEMENT) void RenderTheme::paintSliderTicks(RenderObject* o, const PaintInfo& paintInfo, const IntRect& rect) { Node* node = o->node(); if (!node) return; HTMLInputElement* input = node->toInputElement(); if (!input) return; HTMLDataListElement* dataList = static_cast<HTMLDataListElement*>(input->list()); if (!dataList) return; double min = input->minimum(); double max = input->maximum(); ControlPart part = o->style()->appearance(); // We don't support ticks on alternate sliders like MediaVolumeSliders. if (part != SliderHorizontalPart && part != SliderVerticalPart) return; bool isHorizontal = part == SliderHorizontalPart; IntSize thumbSize; RenderObject* thumbRenderer = input->sliderThumbElement()->renderer(); if (thumbRenderer) { RenderStyle* thumbStyle = thumbRenderer->style(); int thumbWidth = thumbStyle->width().intValue(); int thumbHeight = thumbStyle->height().intValue(); thumbSize.setWidth(isHorizontal ? thumbWidth : thumbHeight); thumbSize.setHeight(isHorizontal ? thumbHeight : thumbWidth); } IntSize tickSize = sliderTickSize(); float zoomFactor = o->style()->effectiveZoom(); FloatRect tickRect; int tickRegionMargin = (thumbSize.width() - tickSize.width()) / 2.0; int tickRegionSideMargin = 0; int tickRegionWidth = 0; if (isHorizontal) { tickRect.setWidth(floor(tickSize.width() * zoomFactor)); tickRect.setHeight(floor(tickSize.height() * zoomFactor)); tickRect.setY(floor(rect.y() + rect.height() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor)); tickRegionSideMargin = rect.x() + tickRegionMargin; tickRegionWidth = rect.width() - tickRegionMargin * 2 - tickSize.width() * zoomFactor; } else { tickRect.setWidth(floor(tickSize.height() * zoomFactor)); tickRect.setHeight(floor(tickSize.width() * zoomFactor)); tickRect.setX(floor(rect.x() + rect.width() / 2.0 + sliderTickOffsetFromTrackCenter() * zoomFactor)); tickRegionSideMargin = rect.y() + tickRegionMargin; tickRegionWidth = rect.height() - tickRegionMargin * 2 - tickSize.width() * zoomFactor; } RefPtr<HTMLCollection> options = dataList->options(); GraphicsContextStateSaver stateSaver(*paintInfo.context); paintInfo.context->setFillColor(o->style()->visitedDependentColor(CSSPropertyColor), ColorSpaceDeviceRGB); for (unsigned i = 0; Node* node = options->item(i); i++) { ASSERT(node->hasTagName(optionTag)); HTMLOptionElement* optionElement = static_cast<HTMLOptionElement*>(node); String value = optionElement->value(); if (!input->isValidValue(value)) continue; double parsedValue = parseToDoubleForNumberType(input->sanitizeValue(value)); double tickPosition = (parsedValue - min) / (max - min); if (!o->style()->isLeftToRightDirection()) tickPosition = 1.0 - tickPosition; if (isHorizontal) tickRect.setX(floor(tickRegionSideMargin + tickRegionWidth * tickPosition)); else tickRect.setY(floor(tickRegionSideMargin + tickRegionWidth * tickPosition)); paintInfo.context->fillRect(tickRect); } } #endif #if ENABLE(PROGRESS_ELEMENT) double RenderTheme::animationRepeatIntervalForProgressBar(RenderProgress*) const { return 0; } double RenderTheme::animationDurationForProgressBar(RenderProgress*) const { return 0; } void RenderTheme::adjustProgressBarStyle(StyleResolver*, RenderStyle*, Element*) const { } #endif bool RenderTheme::shouldHaveSpinButton(HTMLInputElement* inputElement) const { return inputElement->isSteppable() && !inputElement->isRangeControl(); } void RenderTheme::adjustMenuListButtonStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustMediaControlStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustSliderTrackStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustSliderThumbStyle(StyleResolver*, RenderStyle* style, Element* element) const { adjustSliderThumbSize(style, element); } void RenderTheme::adjustSliderThumbSize(RenderStyle*, Element*) const { } void RenderTheme::adjustSearchFieldStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustSearchFieldCancelButtonStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustSearchFieldDecorationStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustSearchFieldResultsDecorationStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::adjustSearchFieldResultsButtonStyle(StyleResolver*, RenderStyle*, Element*) const { } void RenderTheme::platformColorsDidChange() { m_activeSelectionForegroundColor = Color(); m_inactiveSelectionForegroundColor = Color(); m_activeSelectionBackgroundColor = Color(); m_inactiveSelectionBackgroundColor = Color(); m_activeListBoxSelectionForegroundColor = Color(); m_inactiveListBoxSelectionForegroundColor = Color(); m_activeListBoxSelectionBackgroundColor = Color(); m_inactiveListBoxSelectionForegroundColor = Color(); Page::scheduleForcedStyleRecalcForAllPages(); } Color RenderTheme::systemColor(int cssValueId) const { switch (cssValueId) { case CSSValueActiveborder: return 0xFFFFFFFF; case CSSValueActivecaption: return 0xFFCCCCCC; case CSSValueAppworkspace: return 0xFFFFFFFF; case CSSValueBackground: return 0xFF6363CE; case CSSValueButtonface: return 0xFFC0C0C0; case CSSValueButtonhighlight: return 0xFFDDDDDD; case CSSValueButtonshadow: return 0xFF888888; case CSSValueButtontext: return 0xFF000000; case CSSValueCaptiontext: return 0xFF000000; case CSSValueGraytext: return 0xFF808080; case CSSValueHighlight: return 0xFFB5D5FF; case CSSValueHighlighttext: return 0xFF000000; case CSSValueInactiveborder: return 0xFFFFFFFF; case CSSValueInactivecaption: return 0xFFFFFFFF; case CSSValueInactivecaptiontext: return 0xFF7F7F7F; case CSSValueInfobackground: return 0xFFFBFCC5; case CSSValueInfotext: return 0xFF000000; case CSSValueMenu: return 0xFFC0C0C0; case CSSValueMenutext: return 0xFF000000; case CSSValueScrollbar: return 0xFFFFFFFF; case CSSValueText: return 0xFF000000; case CSSValueThreeddarkshadow: return 0xFF666666; case CSSValueThreedface: return 0xFFC0C0C0; case CSSValueThreedhighlight: return 0xFFDDDDDD; case CSSValueThreedlightshadow: return 0xFFC0C0C0; case CSSValueThreedshadow: return 0xFF888888; case CSSValueWindow: return 0xFFFFFFFF; case CSSValueWindowframe: return 0xFFCCCCCC; case CSSValueWindowtext: return 0xFF000000; } return Color(); } Color RenderTheme::platformActiveTextSearchHighlightColor() const { return Color(255, 150, 50); // Orange. } Color RenderTheme::platformInactiveTextSearchHighlightColor() const { return Color(255, 255, 0); // Yellow. } #if ENABLE(TOUCH_EVENTS) Color RenderTheme::tapHighlightColor() { return defaultTheme()->platformTapHighlightColor(); } #endif // Value chosen by observation. This can be tweaked. static const int minColorContrastValue = 1300; // For transparent or translucent background color, use lightening. static const int minDisabledColorAlphaValue = 128; Color RenderTheme::disabledTextColor(const Color& textColor, const Color& backgroundColor) const { // The explicit check for black is an optimization for the 99% case (black on white). // This also means that black on black will turn into grey on black when disabled. Color disabledColor; if (textColor.rgb() == Color::black || backgroundColor.alpha() < minDisabledColorAlphaValue || differenceSquared(textColor, Color::white) > differenceSquared(backgroundColor, Color::white)) disabledColor = textColor.light(); else disabledColor = textColor.dark(); // If there's not very much contrast between the disabled color and the background color, // just leave the text color alone. We don't want to change a good contrast color scheme so that it has really bad contrast. // If the the contrast was already poor, then it doesn't do any good to change it to a different poor contrast color scheme. if (differenceSquared(disabledColor, backgroundColor) < minColorContrastValue) return textColor; return disabledColor; } void RenderTheme::setCustomFocusRingColor(const Color& c) { customFocusRingColor() = c; } Color RenderTheme::focusRingColor() { return customFocusRingColor().isValid() ? customFocusRingColor() : defaultTheme()->platformFocusRingColor(); } String RenderTheme::fileListDefaultLabel(bool multipleFilesAllowed) const { #if OS(TIZEN) return fileButtonNoFileSelectedLabel(); #else if (multipleFilesAllowed) return fileButtonNoFilesSelectedLabel(); return fileButtonNoFileSelectedLabel(); #endif } String RenderTheme::fileListNameForWidth(const FileList* fileList, const Font& font, int width, bool multipleFilesAllowed) const { if (width <= 0) return String(); String string; if (fileList->isEmpty()) string = fileListDefaultLabel(multipleFilesAllowed); else if (fileList->length() == 1) string = fileList->item(0)->name(); else return StringTruncator::rightTruncate(multipleFileUploadText(fileList->length()), width, font, StringTruncator::EnableRoundingHacks); return StringTruncator::centerTruncate(string, width, font, StringTruncator::EnableRoundingHacks); } } // namespace WebCore
lgpl-2.1
Maximo384/Deuterium
imgenc.py
459
from Crypto.Cipher import AES file_img = open ("Link_spin.gif","rb") file_enc = open ("Link_spin.enc","wb") blocs=8192 clau = b"mecagoentojoven1" iv = b"mecmecmecmecmec1" obj=AES.new (clau, AES.MODE_CBC, iv) while True: bloc = file_img.read(blocs) if not bloc : break num = len(bloc) mod = num % 16 if mod > 0: padding = 16 - mod bloc += b"0" * padding codificat = obj.encrypt(bloc) file_enc.write(codificat) file_enc.close() file_img.close()
lgpl-2.1
rianquinn/hyperkernel
src/thread/src/thread.cpp
1619
// // Bareflank Hyperkernel // // Copyright (C) 2015 Assured Information Security, Inc. // Author: Rian Quinn <quinnr@ainfosec.com> // Author: Brendan Kerrigan <kerriganb@ainfosec.com> // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <debug.h> #include <thread/thread.h> thread::thread(threadid::type id, gsl::not_null<process *> proc) : m_id(id), m_proc(proc), m_is_running(false), m_is_initialized(false) { if ((id & threadid::reserved) != 0) throw std::invalid_argument("invalid threadid"); } void thread::init(user_data *data) { (void) data; m_is_initialized = true; } void thread::fini(user_data *data) { (void) data; if (m_is_running) this->hlt(); m_is_initialized = false; } void thread::run(user_data *data) { (void) data; m_is_running = true; } void thread::hlt(user_data *data) { (void) data; m_is_running = false; }
lgpl-2.1
marcel-bariou/zcarto
application/models/ZDBtUser.php
917
<?php /* * Created on May 3, 2009 * PAPWEB * * LICENSE * * This source file is subject to the lpgl.txt license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.brasnah.com/lgpl.txt * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to papweb@brasnah.com so we can send you a copy immediately. * * @category Papweb * @package WebServices * @author Marcel Bariou * @copyright Copyright (c) 2005-2009 Brasnah sarl (http://www.brasnah.com) * @license http://www.brasnah.com/lpgl.txt * * To change the template for this generated file go to * Window - Preferences - PHPeclipse - PHP - Code Templates */ class Model_ZDBtUser extends Zend_Db_Table { /** * Table name */ protected $_name = 'tUser'; } ?>
lgpl-2.1
BhallaLab/moose-thalamocortical
pymoose/gui/moosegui.py
1947
#!/usr/bin/env python # moosegui.py --- # # Filename: moosegui.py # Description: # Author: subhasis ray # Maintainer: # Created: Tue Jun 16 11:12:18 2009 (+0530) # Version: # Last-Updated: Sat Jul 4 01:06:27 2009 (+0530) # By: subhasis ray # Update #: 60 # URL: # Keywords: # Compatibility: # # # Commentary: # # Simple GUI for loading models in MOOSE # # # Change log: # # # # # 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, 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; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth # Floor, Boston, MA 02110-1301, USA. # # # Code: import sys from PyQt4.Qt import Qt from PyQt4 import QtCore, QtGui from mainwin import MainWindow if __name__ == '__main__': app = QtGui.QApplication(sys.argv) QtCore.QObject.connect(app, QtCore.SIGNAL('lastWindowClosed()'), app, QtCore.SLOT('quit()')) fileName = None fileType = None if len(sys.argv) == 3: fileName = sys.argv[1] fileType = sys.argv[2] elif len(sys.argv) == 2: errorDialog = QtGui.QErrorMessage() errorDialog.setWindowFlags(Qt.WindowStaysOnTopHint) errorDialog.showMessage('<p>If specifying a file to load, you must specify a model type as the final argument to this program</p>') app.exec_() mainwin = MainWindow(fileName, fileType) mainwin.show() app.exec_() # # moosegui.py ends here
lgpl-2.1
lolodo/algorithm
android_app/CameraPreview/app/src/main/java/alex/com/camerapreview/CameraPreview.java
2751
package alex.com.camerapreview; import android.content.Context; //import android.graphics.Camera; //import android.hardware.Camera; import android.hardware.Camera; import android.util.Log; import android.view.Display; import android.view.Surface; import android.view.SurfaceView; import android.view.SurfaceHolder; import android.view.WindowManager; import java.io.IOException; /** * Created by liufangyuan on 2018/5/9. */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; private static final String TAG = "CameraPreview"; private Camera mCamera; public CameraPreview(Context context) { super(context); mHolder = getHolder(); mHolder.addCallback(this); } private static Camera getCameraInstance() { Camera c = null; try { c = Camera.open(); } catch (Exception e) { Log.d(TAG, "getCameraInstance: camera is not available"); } return c; } @Override public void surfaceCreated(SurfaceHolder holder) { mCamera = getCameraInstance(); try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d(TAG, "surfaceCreated: error setting camera preview:" + e.getMessage()); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { mHolder.removeCallback(this); mCamera.setPreviewCallback(null); mCamera.stopPreview(); mCamera.release(); mCamera = null; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { int rotation = getDisplayOrientation(); mCamera.setDisplayOrientation(rotation); } public int getDisplayOrientation() { Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int rotation = display.getRotation(); int degress = 0; switch (rotation) { case Surface.ROTATION_0: degress = 0; break; case Surface.ROTATION_90: degress = 90; break; case Surface.ROTATION_180: degress = 180; break; case Surface.ROTATION_270: degress = 270; break; } android.hardware.Camera.CameraInfo camInfo = new android.hardware.Camera.CameraInfo(); android.hardware.Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_FRONT, camInfo); int result = (360 + 180 + camInfo.orientation - degress) % 360; return result; } }
lgpl-2.1
shabanovd/exist
src/org/exist/repo/RepoBackup.java
5196
package org.exist.repo; import org.exist.dom.DocumentImpl; import org.exist.security.PermissionDeniedException; import org.exist.storage.DBBroker; import org.exist.storage.NativeBroker; import org.exist.storage.lock.Lock; import org.exist.xmldb.XmldbURI; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * Utility methods for backing up and restoring the expath file system repository. */ public class RepoBackup { public final static String REPO_ARCHIVE = "expathrepo.zip"; public static File backup(DBBroker broker) throws IOException { ZipOutputStream os = null; File tempFile = null; try { final File directory = ExistRepository.getRepositoryDir(broker.getConfiguration()); tempFile = File.createTempFile("expathrepo", "zip"); os = new ZipOutputStream(new FileOutputStream(tempFile)); zipDir(directory.getAbsolutePath(), os, ""); } finally { if (os != null) {os.close();} } return tempFile; } public static void restore(DBBroker broker) throws IOException, PermissionDeniedException { final XmldbURI docPath = XmldbURI.createInternal(XmldbURI.ROOT_COLLECTION + "/" + REPO_ARCHIVE); DocumentImpl doc = null; try { doc = broker.getXMLResource(docPath, Lock.READ_LOCK); if (doc == null) {return;} if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {throw new IOException(docPath + " is not a binary resource");} final File file = ((NativeBroker)broker).getCollectionBinaryFileFsPath(doc.getURI()); final File directory = ExistRepository.getRepositoryDir(broker.getConfiguration()); unzip(file, directory); } finally { if (doc != null) {doc.getUpdateLock().release(Lock.READ_LOCK);} } } /** * Zip up a directory path * * @param directory * @param zos * @param path * @throws IOException */ public static void zipDir(String directory, ZipOutputStream zos, String path) throws IOException { final File zipDir = new File(directory); // get a listing of the directory content final String[] dirList = zipDir.list(); final byte[] readBuffer = new byte[2156]; int bytesIn = 0; // loop through dirList, and zip the files for (int i = 0; i < dirList.length; i++) { final File f = new File(zipDir, dirList[i]); if (f.isDirectory()) { final String filePath = f.getPath(); zipDir(filePath, zos, path + f.getName() + "/"); continue; } final FileInputStream fis = new FileInputStream(f); try { final ZipEntry anEntry = new ZipEntry(path + f.getName()); zos.putNextEntry(anEntry); bytesIn = fis.read(readBuffer); while (bytesIn != -1) { zos.write(readBuffer, 0, bytesIn); bytesIn = fis.read(readBuffer); } } finally { fis.close(); } } } /*** * Extract zipfile to outdir with complete directory structure. * * @param zipfile Input .zip file * @param outdir Output directory */ public static void unzip(File zipfile, File outdir) throws IOException { ZipInputStream zin = null; try { zin = new ZipInputStream(new FileInputStream(zipfile)); ZipEntry entry; String name, dir; while ((entry = zin.getNextEntry()) != null) { name = entry.getName(); if( entry.isDirectory() ) { mkdirs(outdir, name); continue; } dir = dirpart(name); if( dir != null ) {mkdirs(outdir, dir);} extractFile(zin, outdir, name); } } finally { if (zin != null) try { zin.close(); } catch (final IOException e) { // ignore } } } private static void extractFile(ZipInputStream in, File directory, String name) throws IOException { final byte[] buf = new byte[4096]; final OutputStream out = new FileOutputStream(new File(directory, name)); int count; try { while ((count = in.read(buf)) != -1) { out.write(buf, 0, count); } } finally { out.close(); } } private static void mkdirs(File directory,String path) { final File d = new File(directory, path); if( !d.exists() ) {d.mkdirs();} } private static String dirpart(String name) { final int s = name.lastIndexOf( File.separatorChar ); return s == -1 ? null : name.substring( 0, s ); } }
lgpl-2.1
cran/Boom
inst/include/Models/StateSpace/PosteriorSamplers/StateSpacePoissonPosteriorSampler.hpp
3065
// Copyright 2018 Google LLC. All Rights Reserved. /* Copyright (C) 2005-2015 Steven L. Scott 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef BOOM_STATE_SPACE_POISSON_POSTERIOR_SAMPLER_HPP_ #define BOOM_STATE_SPACE_POISSON_POSTERIOR_SAMPLER_HPP_ #include "Models/Glm/PosteriorSamplers/PoissonDataImputer.hpp" #include "Models/Glm/PosteriorSamplers/PoissonRegressionSpikeSlabSampler.hpp" #include "Models/StateSpace/PosteriorSamplers/StateSpacePosteriorSampler.hpp" #include "Models/StateSpace/StateSpacePoissonModel.hpp" namespace BOOM { class StateSpacePoissonPosteriorSampler : public StateSpacePosteriorSampler { public: // Args: // model: The model for which posterior samples are desired. // All state components should have posterior samplers // assigned to them before 'model' is passed to this // constructor. Likewise, the observation model should have // observation_model_sampler assigned to it before being // passed here. // observation_model_sampler: The posterior sampler for the // Poisson regression observation model. We need a separate // handle to this sampler because we need to control the // latent data imputation and parameter draw steps separately. StateSpacePoissonPosteriorSampler( StateSpacePoissonModel *model, const Ptr<PoissonRegressionSpikeSlabSampler> &observation_model_sampler, RNG &seeding_rng = GlobalRng::rng); // Impute the latent Gaussian observations and variances at each // data point. void impute_nonstate_latent_data() override; // Clear the complete_data_sufficient_statistics for the Poisson // regression model. void clear_complete_data_sufficient_statistics(); // Increment the complete_data_sufficient_statistics for the // Poisson regression model by adding the latent data from // observation t. This update is conditional on the contribution // of the state space portion of the model, which is stored in the // "offset" component of observation t. void update_complete_data_sufficient_statistics(int t); private: StateSpacePoissonModel *model_; Ptr<PoissonRegressionSpikeSlabSampler> observation_model_sampler_; PoissonDataImputer data_imputer_; }; } // namespace BOOM #endif // BOOM_STATE_SPACE_POISSON_POSTERIOR_SAMPLER_HPP_
lgpl-2.1
ess-dmsc/h5cpp
src/h5cpp/property/link_creation.cpp
2744
// // (c) Copyright 2017 DESY,ESS // // This file is part of h5cpp. // // 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 ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Authors: // Eugen Wintersberger <eugen.wintersberger@desy.de> // Martin Shetty <martin.shetty@esss.se> // Created on: Aug 21, 2017 // #include <h5cpp/property/link_creation.hpp> #include <h5cpp/error/error.hpp> #include <sstream> namespace hdf5 { namespace property { LinkCreationList::LinkCreationList() : StringCreationList(kLinkCreate) {} LinkCreationList::~LinkCreationList() {} LinkCreationList::LinkCreationList(ObjectHandle &&handle) : StringCreationList(std::move(handle)) { if (get_class() != kLinkCreate) { std::stringstream ss; ss << "Cannot create property::LinkCreationList from " << get_class(); throw std::runtime_error(ss.str()); } } void LinkCreationList::enable_intermediate_group_creation() const { if (H5Pset_create_intermediate_group(static_cast<hid_t>(*this), 1) < 0) { error::Singleton::instance().throw_with_stack("Failure setting intermediate group creation " "flag to link creation property list!"); } } void LinkCreationList::disable_intermediate_group_creation() const { if (H5Pset_create_intermediate_group(static_cast<hid_t>(*this), 0) < 0) { error::Singleton::instance().throw_with_stack("Failure deleting intermediate group creation " "flag on link creation property list!"); } } bool LinkCreationList::intermediate_group_creation() const { unsigned buffer = 0; if (H5Pget_create_intermediate_group(static_cast<hid_t>(*this), &buffer) < 0) { error::Singleton::instance().throw_with_stack("Failure retrieving intermediate group creation flag " "from link creation property list!"); } if (buffer != 0) return true; else return false; } } // namespace property } // namespace hdf5
lgpl-2.1
SQLBulkQueryTool/SQLBulkQueryTool
core/src/main/java/org/jboss/bqt/core/xml/SAXBuilderHelper.java
2566
/* * JBoss, Home of Professional Open Source. * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. Some portions may be licensed * to Red Hat, Inc. under one or more contributor license agreements. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. */ package org.jboss.bqt.core.xml; import org.jdom.input.SAXBuilder; /** * Utility class used to create a SAXBuilder */ public class SAXBuilderHelper { /** System property name used to get parser class */ public static final String PARSER_PROPERTY_NAME = "bqt.xmlparser.class"; //$NON-NLS-1$ private static String PARSER_NAME; public static String getParserClassName() { if (PARSER_NAME == null) { PARSER_NAME = System.getProperty(PARSER_PROPERTY_NAME); } return PARSER_NAME; } /** * Returns a SAXBuilder using the Parser class defined by the * metamatrix.xmlparser.class System property. If the System property does * not exist, returns a SAXBuilder using the * org.apache.xerces.parsers.SAXParser. * * @return org.jdom.input.SAXBuilder */ public static SAXBuilder createSAXBuilder() { return createSAXBuilder(false); } /** * Returns a SAXBuilder using the Parser class defined by the * metamatrix.xmlparser.class System property. If the System property does * not exist, returns a SAXBuilder using the * org.apache.xerces.parsers.SAXParser. * @param validate * * @return org.jdom.input.SAXBuilder */ public static SAXBuilder createSAXBuilder(boolean validate) { return new SAXBuilder(getParserClassName(), validate); } /** * Returns a SAXBuilder * @param saxDriverClass * * @param validate * @return org.jdom.input.SAXBuilder */ public static SAXBuilder createSAXBuilder(String saxDriverClass, boolean validate) { return new SAXBuilder(saxDriverClass, validate); } }
lgpl-2.1
evlist/orbeon-forms
src/main/scala/org/orbeon/oxf/xforms/processor/handlers/xhtml/XFormsOutputHandler.scala
9850
/** * Copyright (C) 2010 Orbeon, Inc. * * This program 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 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xforms.processor.handlers.xhtml import org.orbeon.oxf.xforms.control.{XFormsControl, XFormsSingleNodeControl} import org.orbeon.oxf.xml.{XMLUtils, ContentHandlerHelper} import org.xml.sax.Attributes import org.orbeon.oxf.xforms.control.controls.XFormsOutputControl import org.orbeon.oxf.xforms.processor.handlers.XFormsBaseHandler import org.orbeon.oxf.xforms.{XFormsConstants, XFormsUtils} import org.orbeon.oxf.xforms.processor.handlers.HandlerHelper._ import org.orbeon.oxf.xml.XMLConstants.{XHTML_NAMESPACE_URI,FORMATTING_URL_TYPE_QNAME} import org.apache.commons.lang3.StringUtils import org.orbeon.oxf.xml.ContentHandlerHelper._ import org.orbeon.oxf.xforms.XFormsConstants._ trait XFormsOutputHandler extends XFormsControlLifecyleHandler { protected def getContainerAttributes(uri: String, localname: String, attributes: Attributes, effectiveId: String, outputControl: XFormsSingleNodeControl) = { // Add custom class val containerAttributes = super.getContainerAttributes(uri, localname, attributes, effectiveId, outputControl, true) containerAttributes.addAttribute("", "class", "class", ContentHandlerHelper.CDATA, "xforms-output-output") containerAttributes } // Don't use @for as we ae not pointing to an HTML control override def getForEffectiveId(effectiveId: String) = null } // Default xf:output handler class XFormsOutputDefaultHandler extends XFormsControlLifecyleHandler(false) with XFormsOutputHandler { protected def handleControlStart(uri: String, localname: String, qName: String, attributes: Attributes, effectiveId: String, control: XFormsControl): Unit = { implicit val xmlReceiver = handlerContext.getController.getOutput val outputControl = control.asInstanceOf[XFormsOutputControl] val isConcreteControl = outputControl ne null val contentHandler = handlerContext.getController.getOutput val containerAttributes = getContainerAttributes(uri, localname, attributes, effectiveId, outputControl) // Handle accessibility attributes on <span> XFormsBaseHandler.handleAccessibilityAttributes(attributes, containerAttributes) withElement(handlerContext.findXHTMLPrefix, XHTML_NAMESPACE_URI, getContainingElementName, containerAttributes) { if (isConcreteControl) { val mediatypeValue = attributes.getValue("mediatype") val textValue = XFormsOutputControl.getExternalValueOrDefault(outputControl, mediatypeValue) if ((textValue ne null) && textValue.nonEmpty) contentHandler.characters(textValue.toCharArray, 0, textValue.length) } } } } // xf:output[@mediatype = 'text/html'] class XFormsOutputHTMLHandler extends XFormsControlLifecyleHandler(false) with XFormsOutputHandler { protected def handleControlStart(uri: String, localname: String, qName: String, attributes: Attributes, effectiveId: String, control: XFormsControl): Unit = { implicit val xmlReceiver = handlerContext.getController.getOutput val outputControl = control.asInstanceOf[XFormsOutputControl] val isConcreteControl = outputControl ne null val xhtmlPrefix = handlerContext.findXHTMLPrefix val containerAttributes = getContainerAttributes(uri, localname, attributes, effectiveId, outputControl) // Handle accessibility attributes on <div> XFormsBaseHandler.handleAccessibilityAttributes(attributes, containerAttributes) withElement(xhtmlPrefix, XHTML_NAMESPACE_URI, getContainingElementName, containerAttributes) { if (isConcreteControl) { val mediatypeValue = attributes.getValue("mediatype") val htmlValue = XFormsOutputControl.getExternalValueOrDefault(outputControl, mediatypeValue) XFormsUtils.streamHTMLFragment(xmlReceiver, htmlValue, outputControl.getLocationData, xhtmlPrefix) } } } protected override def getContainingElementName: String = "div" } // xf:output[starts-with(@appearance, 'image/')] class XFormsOutputImageHandler extends XFormsControlLifecyleHandler(false) with XFormsOutputHandler { protected def handleControlStart(uri: String, localname: String, qName: String, attributes: Attributes, effectiveId: String, control: XFormsControl): Unit = { implicit val xmlReceiver = handlerContext.getController.getOutput val outputControl = control.asInstanceOf[XFormsOutputControl] val xhtmlPrefix = handlerContext.findXHTMLPrefix val mediatypeValue = attributes.getValue("mediatype") val containerAttributes = getContainerAttributes(uri, localname, attributes, effectiveId, outputControl) // @src="..." // NOTE: If producing a template, or if the image URL is blank, we point to an existing dummy image val srcValue = XFormsOutputControl.getExternalValueOrDefault(outputControl, mediatypeValue) containerAttributes.addAttribute("", "src", "src", ContentHandlerHelper.CDATA, if (srcValue ne null) srcValue else XFormsConstants.DUMMY_IMAGE_URI) XFormsBaseHandler.handleAccessibilityAttributes(attributes, containerAttributes) element(xhtmlPrefix, XHTML_NAMESPACE_URI, "img", containerAttributes) } } // xf:output[@appearance = 'xxf:text'] class XFormsOutputTextHandler extends XFormsControlLifecyleHandler(false) with XFormsOutputHandler { protected def handleControlStart(uri: String, localname: String, qName: String, attributes: Attributes, effectiveId: String, control: XFormsControl): Unit = { val outputControl = control.asInstanceOf[XFormsOutputControl] val isConcreteControl = outputControl ne null val contentHandler = handlerContext.getController.getOutput if (isConcreteControl) { val externalValue = outputControl.getExternalValue if ((externalValue ne null) && externalValue.nonEmpty) contentHandler.characters(externalValue.toCharArray, 0, externalValue.length) } } } // xf:output[@appearance = 'xxf:download'] class XFormsOutputDownloadHandler extends XFormsControlLifecyleHandler(false) with XFormsOutputHandler { // NOP because the label is output as the text within <a> protected override def handleLabel() = () protected def handleControlStart(uri: String, localname: String, qName: String, attributes: Attributes, effectiveId: String, control: XFormsControl) { implicit val context = handlerContext implicit val xmlReceiver = context.getController.getOutput val outputControl = control.asInstanceOf[XFormsOutputControl] val containerAttributes = getContainerAttributes(uri, localname, attributes, effectiveId, outputControl) val xhtmlPrefix = context.findXHTMLPrefix // For f:url-type="resource" withFormattingPrefix { formattingPrefix ⇒ def anchorAttributes = { val hrefValue = XFormsOutputControl.getExternalValueOrDefault(outputControl, null) if (StringUtils.isBlank(hrefValue)) { // No URL so make sure a click doesn't cause navigation, and add class containerAttributes.addAttribute("", "href", "href", CDATA, "#") XMLUtils.addOrAppendToAttribute(containerAttributes, "class", "xforms-readonly") } else { // URL value containerAttributes.addAttribute("", "href", "href", CDATA, hrefValue) } // Specify resource URL type for proxy portlet containerAttributes.addAttribute( FORMATTING_URL_TYPE_QNAME.getNamespaceURI, FORMATTING_URL_TYPE_QNAME.getName, XMLUtils.buildQName(formattingPrefix, FORMATTING_URL_TYPE_QNAME.getName), CDATA, "resource") // Add _blank target in order to prevent: // 1. The browser replacing the current page, and // 2. The browser displaying the "Are you sure you want to navigate away from this page?" warning dialog // This, as of 2009-05, seems to be how most sites handle this containerAttributes.addAttribute("", "target", "target", CDATA, "_blank") // Output xxf:* extension attributes if (outputControl ne null) outputControl.addExtensionAttributesExceptClassAndAcceptForHandler(containerAttributes, XXFORMS_NAMESPACE_URI) containerAttributes } val aAttributes = anchorAttributes XFormsBaseHandler.handleAccessibilityAttributes(attributes, aAttributes) withElement(xhtmlPrefix, XHTML_NAMESPACE_URI, "a", aAttributes) { val labelValue = Option(control) map (_.getLabel) orNull val mustOutputHTMLFragment = Option(control) exists (_.isHTMLLabel) XFormsBaseHandlerXHTML.outputLabelText(xmlReceiver, control, labelValue, xhtmlPrefix, mustOutputHTMLFragment) } } } }
lgpl-2.1
radekp/qt
src/xmlpatterns/api/qabstracturiresolver.cpp
3731
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QUrl> #include "qabstracturiresolver.h" QT_BEGIN_NAMESPACE /*! \class QAbstractUriResolver \brief The QAbstractUriResolver class is a callback interface for resolving Uniform Resource Identifiers. \since 4.4 \reentrant \ingroup xml-tools A Uniform Resource Identifier (URI) is a string that uniquely identifies a resource. URIs are versatile global identifiers. It is often useful to transform a URI that identifies something logical into a URI that locates something physical (a URL), or to simply map a URI to a different URI. QAbstractUriResolver::resolve() provides this functionality. For example, one could write a QAbstractUriResolver subclass that rewrites library ISBN number URIs as book title URLs, e.g., \e{urn:isbn:0-345-33973-8} would be rewritten as \e{file:///books/returnOfTheKing.doc}. Or a QAbstractUriResolver subclass could be written for a web browser to let the web browser protect the user's private files by mapping incoming requests for them to null URIs. \sa {http://en.wikipedia.org/wiki/Uniform_Resource_Identifier} */ /*! Constructs a QAbstractUriResolver with the specified \a parent. */ QAbstractUriResolver::QAbstractUriResolver(QObject *parent) : QObject(parent) { } /*! Destructor. */ QAbstractUriResolver::~QAbstractUriResolver() { } /*! \fn QUrl QAbstractUriResolver::resolve(const QUrl &relative, const QUrl &baseURI) const Returns the \a relative URI resolved using the \a baseURI. The caller guarantees that both \a relative and \a baseURI are valid, and that \a baseURI is absolute. \a relative can be relative, absolute, or empty. The returned QUrl can be a default constructed QUrl. If it is not a default constructed QUrl, it will be absolute and valid. If a default constructed QUrl is returned, it means the \a relative URI was not accepted to be resolved. If the reimplemented resolve() function decides it has nothing to do about resolving the \a relative URI, it should simply return the \a relative URI resolved against the \a baseURI, i.e.: \snippet doc/src/snippets/code/src_xmlpatterns_api_qabstracturiresolver.cpp 0 \sa QUrl::isRelative(), QUrl::isValid() */ QT_END_NAMESPACE
lgpl-2.1
Hiroyuki-Nagata/JaneClone
src/virtualboardlistctrl.cpp
27309
/* JaneClone - a text board site viewer for 2ch * Copyright (C) 2012-2014 Hiroyuki Nagata * * 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. * * Contributor: * Hiroyuki Nagata <newserver002@gmail.com> */ #include "virtualboardlistctrl.hpp" #include "janeclone.hpp" IMPLEMENT_DYNAMIC_CLASS(VirtualBoardListCtrl, wxListCtrl) /** * コンストラクタ:配置するwindowと板名を指定 * @param wxWindow* parent 親ウィンドウ * @param wxWindowID id ウィンドウID * @param wxString boardName 板名 * @param wxString outputPath datファイルのパス * @param map<wxString,ThreadList>& oldThreadMap 古いスレッドの情報を保持するコンテナ * @rapam bool targetIsShingetsu 読み込み対象は新月のCSVか */ VirtualBoardListCtrl::VirtualBoardListCtrl(wxWindow* parent, const wxWindowID id, const wxString& boardName, const wxString& outputPath, const std::map<wxString,ThreadList>& oldThreadMap, bool targetIsShingetsu): wxListCtrl(parent, id, wxDefaultPosition, wxDefaultSize, wxLC_REPORT | wxLC_VIRTUAL) { this->Hide(); f_nowSearching = false; // クラス自体の目印を設置する SetLabel(boardName); #ifdef __WXMSW__ // ウィンドウ内に入った際のイベント通知 this->Connect(id, wxEVT_ENTER_WINDOW, wxMouseEventHandler(JaneClone::OnEnterWindow), NULL, this); #endif // リストに使用する画像を設定する wxImageList* threadImage = new wxImageList(16, 16); wxBitmap idx1(threadCheckImg, wxBITMAP_TYPE_PNG); threadImage->Add(idx1); wxBitmap idx2(threadAddImg, wxBITMAP_TYPE_PNG); threadImage->Add(idx2); wxBitmap idx3(threadDropImg, wxBITMAP_TYPE_PNG); threadImage->Add(idx3); wxBitmap idx4(threadNewImg, wxBITMAP_TYPE_PNG); threadImage->Add(idx4); this->AssignImageList(threadImage, wxIMAGE_LIST_SMALL); // プロパティファイルにフォント設定/背景色があれば使用する wxString widgetsName = wxT("ID_ThreadListFontButton"); wxString widgetsInfo = wxEmptyString; JaneCloneUtil::GetJaneCloneProperties(widgetsName, &widgetsInfo); if (widgetsInfo != wxEmptyString) { wxFont font; bool ret = font.SetNativeFontInfoUserDesc(widgetsInfo); if(ret) m_attr.SetFont(font); } widgetsName = wxT("ID_ExtractFontButton"); widgetsInfo.Clear(); JaneCloneUtil::GetJaneCloneProperties(widgetsName, &widgetsInfo); if (widgetsInfo != wxEmptyString) { wxFont font; bool ret = font.SetNativeFontInfoUserDesc(widgetsInfo); if(ret) m_attr_search.SetFont(font); } widgetsName = wxT("ID_ThreadListBGColorButton"); widgetsInfo.Clear(); JaneCloneUtil::GetJaneCloneProperties(widgetsName, &widgetsInfo); if (widgetsInfo != wxEmptyString) { wxColour bgColor; bool ret = bgColor.Set(widgetsInfo); if(ret) m_attr.SetBackgroundColour(bgColor); if(ret) m_attr_search.SetBackgroundColour(bgColor); } else { // デフォルト設定 m_attr.SetBackgroundColour(*wxLIGHT_GREY); m_attr_search.SetBackgroundColour(wxColour(wxT("YELLOW"))); } // ファイル読み出しメソッドの変更 #ifdef USE_SHINGETSU targetIsShingetsu ? FileLoadMethodShingetsu(boardName, outputPath, oldThreadMap) : FileLoadMethod2ch(boardName, outputPath, oldThreadMap); #else FileLoadMethod2ch(boardName, outputPath, oldThreadMap); #endif /** USE_SHINGETSU */ InsertColumn(COL_CHK, wxT("!"), wxLIST_FORMAT_CENTRE); InsertColumn(COL_NUM, wxT("番号"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_TITLE, wxT("タイトル")); InsertColumn(COL_RESP, wxT("レス"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_CACHEDRES, wxT("取得"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_NEWRESP, wxT("新着"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_INCRESP, wxT("増レス"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_MOMENTUM, wxT("勢い"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_LASTUP, wxT("最終取得")); InsertColumn(COL_SINCE, wxT("SINCE")); InsertColumn(COL_OID, wxT("固有番号")); InsertColumn(COL_BOARDNAME, wxT("板")); // フラグを全てtrueに設定する f_check = true; f_number = true; f_title = true; f_response = true; f_cachedResponseNumber = true; f_newResponseNumber = true; f_increaseResponseNumber = true; f_momentum = true; f_lastUpdate = true; f_since = true; f_oid = true; f_boardName = true; this->Show(); } /** * 2chのdatファイルを読み出す処理 */ void VirtualBoardListCtrl::FileLoadMethod2ch(const wxString& boardName, const wxString& outputPath, const std::map<wxString,ThreadList>& oldThreadMap) { // 過去のデータがあるかどうかのフラグを立てる bool hasOldData, noNeedToChkThreadState = false; wxString stub = wxT("NO_NEED_TO_CHK_THREAD_STATE"); if (!oldThreadMap.empty()) hasOldData = true; if (!(oldThreadMap.find(stub) == oldThreadMap.end())) noNeedToChkThreadState = true; f_nowSearching = false; // テキストファイルの読み込み wxTextFile datfile(outputPath); datfile.Open(); // スレッド一覧読み込み用正規表現を準備する wxRegEx reThreadLine(_T("([[:digit:]]+).dat<>(.+)\\(([[:digit:]]{1,4})\\)"), wxRE_ADVANCED + wxRE_ICASE); // スレッドに番号をつける int loopNumber = 1; // テキストファイルの終端まで読み込む for (wxString line = datfile.GetFirstLine(); !datfile.Eof(); line = datfile.GetNextLine()) { if (line.Contains(_("&"))) { // 実態参照文字の変換 line = JaneCloneUtil::ConvCharacterReference(line); } // アイテム用の文字列を先に宣言する wxString itemNumber, itemBoardName, itemOid, itemSince, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate; // 番号 itemNumber = wxString::Format(wxT("%i"), loopNumber); // 板名 itemBoardName = boardName; // 正規表現で情報を取得する if (reThreadLine.Matches(line)) { // キー値を取得する itemOid = reThreadLine.GetMatch(line, 1); // since itemSince = JaneCloneUtil::CalcThreadCreatedTime(itemOid); // スレタイを取得する itemTitle = reThreadLine.GetMatch(line, 2); // レス数を取得する itemResponse = reThreadLine.GetMatch(line, 3); } /** * 新規ダウンロードの場合多くは空白となる */ if (hasOldData) { // 過去のデータがある } else { // 過去のデータがない // 取得 itemCachedResponseNumber = itemResponse; // 新着 itemNewResponseNumber = itemResponse; // 増レス itemIncreaseResponseNumber = itemResponse; } // 最終取得 itemLastUpdate = wxEmptyString; // 勢い itemMomentum = JaneCloneUtil::CalcThreadMomentum(itemResponse, itemOid); // リストにアイテムを挿入する VirtualBoardListItem listItem = VirtualBoardListItem(itemNumber, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate, itemSince, itemOid, itemBoardName); // この項目の状態を設定する if (hasOldData) { if (oldThreadMap.find(itemOid) == oldThreadMap.end()) { // 要素がない場合の処理 listItem.setCheck(THREAD_STATE_NEW); } else { // 要素がある場合の処理 std::map<wxString, ThreadList>::const_iterator it; it = oldThreadMap.find(itemOid); const ThreadList oldThread = it->second; int newResInt = wxAtoi(itemResponse) - oldThread.response; // 取得した情報をリストの項目に設定する wxString oldRes = wxString::Format(wxT("%d"), oldThread.response); wxString newRes = wxString::Format(wxT("%d"), newResInt); listItem.setCachedResponseNumber(oldRes); listItem.setNewResponseNumber(newRes); listItem.setIncreaseResponseNumber(newRes); if (newResInt == 0) { // 新着なし listItem.setCheck(THREAD_STATE_NORMAL); } else { // 新着あり listItem.setCheck(THREAD_STATE_ADD); } } } // 特殊処理・レス数が1000ならばDAT落ち扱い if (itemResponse == wxT("1000")) listItem.setCheck(THREAD_STATE_DROP); // 新着チェックする必要のないJaneClone起動時であればすべて普通に if (noNeedToChkThreadState) listItem.setCheck(THREAD_STATE_NORMAL); // Listctrlに項目を追加する m_vBoardList.push_back(listItem); // ループ変数をインクリメント ++loopNumber; } datfile.Close(); /** * データ挿入 */ // データを挿入 SetItemCount(m_vBoardList.size()); } #ifdef USE_SHINGETSU /** * 新月ののcsvファイルを読み出す処理 */ void VirtualBoardListCtrl::FileLoadMethodShingetsu(const wxString& boardName, const wxString& outputPath, const std::map<wxString,ThreadList>& oldThreadMap) { // テキストファイルの読み込み wxTextFile csvfile(outputPath); csvfile.Open(); f_nowSearching = false; // スレッドに番号をつける int loopNumber = 1; // テキストファイルの終端まで読み込む for (wxString line = csvfile.GetFirstLine(); !csvfile.Eof(); line = csvfile.GetNextLine()) { // アイテム用の文字列を先に宣言する wxString itemNumber, itemBoardName, itemOid, itemSince, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate, itemFilename, itemPath, itemUri, itemSize; // lineをコンマで分割する wxStringTokenizer tkz(line, wxT(",")); while (tkz.HasMoreTokens()) { itemFilename = tkz.GetNextToken(); itemOid = tkz.GetNextToken(); itemLastUpdate = tkz.GetNextToken(); itemPath = tkz.GetNextToken(); itemUri = tkz.GetNextToken(); itemBoardName = tkz.GetNextToken(); // type itemTitle = tkz.GetNextToken(); itemResponse = tkz.GetNextToken(); itemSize = tkz.GetNextToken(); break; } // 番号 itemNumber = wxString::Format(wxT("%i"), loopNumber); // since itemSince = JaneCloneUtil::CalcThreadCreatedTime(itemOid); // 勢い itemMomentum = JaneCloneUtil::CalcThreadMomentum(itemResponse, itemOid); // リストにアイテムを挿入する VirtualBoardListItem listItem = VirtualBoardListItem(itemNumber, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate, itemSince, itemOid, itemBoardName); listItem.setFilename(itemFilename); // Listctrlに項目を追加する m_vBoardList.push_back(listItem); // ループ変数をインクリメント ++loopNumber; } csvfile.Close(); /** * データ挿入 */ // データを挿入 SetItemCount(m_vBoardList.size()); } #endif /** USE_SHINGETSU */ /** * 内部リストの更新処理 * @param wxString boardName 板名 * @pram wxString outputPath datファイルのパス * @param VirtualBoardList 更新したリストのコンテナ */ VirtualBoardList VirtualBoardListCtrl::ThreadListUpdate(const wxString& boardName, const wxString& outputPath) { this->Hide(); f_nowSearching = false; // 内部にデータがあればリストをクリアする if ( ! m_vBoardList.empty()) { m_vBoardList.clear(); } // テキストファイルの読み込み wxTextFile datfile(outputPath); datfile.Open(); // スレッド一覧読み込み用正規表現を準備する wxRegEx reThreadLine(_T("([[:digit:]]+).dat<>(.+)\\(([[:digit:]]{1,4})\\)"), wxRE_ADVANCED + wxRE_ICASE); // スレッドに番号をつける int loopNumber = 1; // テキストファイルの終端まで読み込む for (wxString line = datfile.GetFirstLine(); !datfile.Eof(); line = datfile.GetNextLine()) { if (line.Contains(_("&"))) { line = JaneCloneUtil::ConvCharacterReference(line); } // アイテム用の文字列を先に宣言する wxString itemNumber, itemBoardName, itemOid, itemSince, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate; // 番号 itemNumber = wxString::Format(wxT("%i"), loopNumber); // 板名 itemBoardName = boardName; // 正規表現で情報を取得する if (reThreadLine.Matches(line)) { // キー値を取得する itemOid = reThreadLine.GetMatch(line, 1); // since itemSince = JaneCloneUtil::CalcThreadCreatedTime(itemOid); // スレタイを取得する itemTitle = reThreadLine.GetMatch(line, 2); // レス数を取得する itemResponse = reThreadLine.GetMatch(line, 3); } /** * 更新処理 */ // 取得 itemCachedResponseNumber = wxEmptyString; // 新着 itemNewResponseNumber = wxEmptyString; // 増レス itemIncreaseResponseNumber = wxEmptyString; // 勢い itemMomentum = JaneCloneUtil::CalcThreadMomentum(itemResponse, itemOid); // 最終取得 itemLastUpdate = wxEmptyString; // リストにアイテムを挿入する VirtualBoardListItem listItem = VirtualBoardListItem(itemNumber, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate, itemSince, itemOid, itemBoardName); // この項目の状態を設定する listItem.setCheck(THREAD_STATE_ADD); // Listctrlに項目を追加する m_vBoardList.push_back(listItem); // ループ変数をインクリメント ++loopNumber; } datfile.Close(); /** * データ挿入 */ // データを挿入 SetItemCount(m_vBoardList.size()); InsertColumn(COL_CHK, wxT("!"), wxLIST_FORMAT_CENTRE); InsertColumn(COL_NUM, wxT("番号"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_TITLE, wxT("タイトル")); InsertColumn(COL_RESP, wxT("レス"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_CACHEDRES, wxT("取得"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_NEWRESP, wxT("新着"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_INCRESP, wxT("増レス"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_MOMENTUM, wxT("勢い"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_LASTUP, wxT("最終取得")); InsertColumn(COL_SINCE, wxT("SINCE")); InsertColumn(COL_OID, wxT("固有番号")); InsertColumn(COL_BOARDNAME, wxT("板")); this->Show(); return m_vBoardList; } /** * wxListCtrl備え付きの仮想関数 : wxListCtrlを継承したクラスで仮想関数を実装することで使えるようになる * 指定されたアイテムとカラムに存在するテキストを返すことができる */ wxString VirtualBoardListCtrl::OnGetItemText(long item, long column) const { wxString result = wxEmptyString; switch (column) { case COL_CHK: // アイコン部分には文字列を入れない result = wxEmptyString; break; case COL_NUM: result = m_vBoardList[item].getNumber(); break; case COL_TITLE: result = m_vBoardList[item].getTitle(); break; case COL_RESP: result = m_vBoardList[item].getResponse(); break; case COL_CACHEDRES: result = m_vBoardList[item].getCachedResponseNumber(); break; case COL_NEWRESP: result = m_vBoardList[item].getNewResponseNumber(); break; case COL_INCRESP: result = m_vBoardList[item].getIncreaseResponseNumber(); break; case COL_MOMENTUM: result = m_vBoardList[item].getMomentum(); break; case COL_LASTUP: result = m_vBoardList[item].getLastUpdate(); break; case COL_SINCE: result = m_vBoardList[item].getSince(); break; case COL_OID: result = m_vBoardList[item].getOid(); break; case COL_BOARDNAME: result = m_vBoardList[item].getBoardName(); break; default: wxFAIL_MSG("板一覧リストからデータを取り出す処理に失敗しました"); break; } return result; } /** * 仮想リスト内のアイコンを表示させる */ int VirtualBoardListCtrl::OnGetItemColumnImage(long item, long column) const { if (column != COL_CHK) { return -1; } return m_vBoardList[item].getCheck(); } /** * 仮想リスト内の色情報等の設定 */ wxListItemAttr* VirtualBoardListCtrl::OnGetItemAttr(long item) const { if (f_nowSearching) { if (item <= searchItemNum) { return (wxListItemAttr*)&m_attr_search; } } return item % 2 ? NULL : (wxListItemAttr*)&m_attr; } /** * コンストラクタ:ログ一覧リスト作成用 * @param wxWindow* parent 親ウィンドウ> * @param wxString boardName 板名(ログ一覧で固定) * @param wxString outputPath datファイルのパス */ VirtualBoardListCtrl::VirtualBoardListCtrl(wxWindow* parent,const wxString& boardName, const wxArrayString& datFileList) : wxListCtrl(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize,wxLC_REPORT | wxLC_VIRTUAL) { this->Hide(); f_nowSearching = false; /** * datファイルの数だけ処理を繰り返す */ for (unsigned int i = 0; i < datFileList.GetCount(); i++) { // テキストファイルの読み込み wxTextFile datfile(datFileList[i]); datfile.Open(); // アイテム用の文字列を先に宣言する wxString itemNumber, itemBoardName, itemOid, itemSince, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate; // スレッドに番号をつける int loopNumber = i + 1; // datファイルの1行目だけ読み込む wxString line = datfile.GetFirstLine(); if (line.Contains(_("&"))) { line = JaneCloneUtil::ConvCharacterReference(line); } /** * リストに値を設定する */ // 番号 itemNumber = wxString::Format(wxT("%i"), loopNumber); // 板名 //item.boardName = boardName; // キー値を取得する wxFileName* filename = new wxFileName(datFileList[i], wxPATH_NATIVE); itemOid = filename->GetName(); delete filename; // since itemSince = JaneCloneUtil::CalcThreadCreatedTime(itemOid); // スレタイを取得する if (regexThreadFst.Matches(line)) { itemTitle = regexThreadFst.GetMatch(line, 5); } // レス数を取得する itemResponse = wxString::Format(wxT("%i"), datfile.GetLineCount()); /** * ログ一覧なのでこの辺は空白でいいんじゃないだろうか */ // 取得 itemCachedResponseNumber = wxEmptyString; // 新着 itemNewResponseNumber = wxEmptyString; // 増レス itemIncreaseResponseNumber = wxEmptyString; // 勢い itemMomentum = JaneCloneUtil::CalcThreadMomentum(itemResponse, itemOid); // 最終取得 itemLastUpdate = wxEmptyString; // リストにアイテムを挿入する VirtualBoardListItem listItem = VirtualBoardListItem(itemNumber, itemTitle, itemResponse, itemCachedResponseNumber, itemNewResponseNumber, itemIncreaseResponseNumber, itemMomentum, itemLastUpdate, itemSince, itemOid, itemBoardName); // この項目の状態を設定する listItem.setCheck(THREAD_STATE_ADD); // Listctrlに項目を追加する m_vBoardList.push_back(listItem); // ループ変数をインクリメント ++loopNumber; // ファイルをクローズ datfile.Close(); } /** * データ挿入 */ // データを挿入 SetItemCount(m_vBoardList.size()); InsertColumn(COL_CHK, wxT("!"), wxLIST_FORMAT_CENTRE); InsertColumn(COL_NUM, wxT("番号"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_TITLE, wxT("タイトル")); InsertColumn(COL_RESP, wxT("レス"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_CACHEDRES, wxT("取得"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_NEWRESP, wxT("新着"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_INCRESP, wxT("増レス"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_MOMENTUM, wxT("勢い"), wxLIST_FORMAT_RIGHT); InsertColumn(COL_LASTUP, wxT("最終取得")); InsertColumn(COL_SINCE, wxT("SINCE")); InsertColumn(COL_OID, wxT("固有番号")); InsertColumn(COL_BOARDNAME, wxT("板")); this->Show(); } /** * 内部のリストをソートする */ void VirtualBoardListCtrl::SortVectorItems(int col) { this->Hide(); f_nowSearching = false; // 要素を一度全て削除する DeleteAllItems(); // カラムの位置によって分岐させる switch (col) { case COL_CHK: f_check ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseCheck) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardCheck); f_check ? f_check = false : f_check = true; break; case COL_NUM: f_number ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseNumber) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardNumber); f_number ? f_number = false : f_number = true; break; case COL_TITLE: f_title ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseTitle) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardTitle); f_title ? f_title = false : f_title = true; break; case COL_RESP: f_response ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseResponse) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardResponse); f_response ? f_response = false : f_response = true; break; case COL_CACHEDRES: f_cachedResponseNumber ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseCachedResponseNumber) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardCachedResponseNumber); f_cachedResponseNumber ? f_cachedResponseNumber = false : f_cachedResponseNumber = true; break; case COL_NEWRESP: f_newResponseNumber ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseNewResponseNumber) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardNewResponseNumber); f_newResponseNumber ? f_newResponseNumber = false : f_newResponseNumber = true; break; case COL_INCRESP: f_increaseResponseNumber ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseIncreaseResNum) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardIncreaseResNum); f_increaseResponseNumber ? f_increaseResponseNumber = false : f_increaseResponseNumber = true; break; case COL_MOMENTUM: f_momentum ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseMomentum) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardMomentum); f_momentum ? f_momentum = false : f_momentum = true; break; case COL_LASTUP: f_lastUpdate ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseLastUpdate) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardLastUpdate); f_lastUpdate ? f_lastUpdate = false : f_lastUpdate = true; break; case COL_SINCE: f_since ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseSince) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardSince); f_since ? f_since = false : f_since = true; break; case COL_OID: f_since ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseOid) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardOid); f_since ? f_since = false : f_since = true; break; case COL_BOARDNAME: f_boardName ? std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateReverseSince) : std::sort(m_vBoardList.begin(), m_vBoardList.end(), VirtualBoardListItem::PredicateForwardSince); f_since ? f_since = false : f_since = true; break; default: wxFAIL_MSG("板一覧リストのソートに失敗しました"); break; } SetItemCount(m_vBoardList.size()); this->Show(); } /** * スレッドタイトル検索を実施する */ void VirtualBoardListCtrl::SearchAndSortItems(const wxString& keyword) { this->Hide(); // 要素を一度全て削除する DeleteAllItems(); f_nowSearching = true; VirtualBoardList work; // 文字列に一致するものをコピーして再構築 std::copy_if(m_vBoardList.begin(), m_vBoardList.end(), back_inserter(work), [&keyword] (const VirtualBoardListItem& item) -> bool { return item.getTitle().Contains(keyword); }); // 当てはまった数を記録 searchItemNum = work.size(); // 文字列に一致しないものをコピーして再構築 std::copy_if(m_vBoardList.begin(), m_vBoardList.end(), back_inserter(work), [&keyword] (const VirtualBoardListItem& item) -> bool { return ! item.getTitle().Contains(keyword); }); // リストを削除して構築し直す m_vBoardList.clear(); m_vBoardList = std::move(work); SetItemCount(m_vBoardList.size()); this->Show(); }
lgpl-2.1
geotools/geotools
modules/library/metadata/src/main/java/org/geotools/measure/Longitude.java
2094
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 1999-2008, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * 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. */ package org.geotools.measure; /** * A longitude angle. Positive longitudes are East, while negative longitudes are West. * * @since 2.0 * @version $Id$ * @author Martin Desruisseaux (PMO, IRD) * @see Latitude * @see AngleFormat */ public final class Longitude extends Angle { /** Serial number for interoperability with different versions. */ private static final long serialVersionUID = -8614900608052762636L; /** Minimum legal value for longitude (-180°). */ public static final double MIN_VALUE = -180; /** Maximum legal value for longitude (+180°). */ public static final double MAX_VALUE = +180; /** * Contruct a new longitude with the specified value. * * @param theta Angle in degrees. */ public Longitude(final double theta) { super(theta); } /** * Constructs a newly allocated {@code Longitude} object that represents the longitude value * represented by the string. The string should represents an angle in either fractional degrees * (e.g. 45.5°) or degrees with minutes and seconds (e.g. 45°30'). The hemisphere (E or W) is * optional (default to East). * * @param theta A string to be converted to a {@code Longitude}. * @throws NumberFormatException if the string does not contain a parsable longitude. */ public Longitude(final String theta) throws NumberFormatException { super(theta); } }
lgpl-2.1
einon/affymetrix-power-tools
sdk/util/LogStream.cpp
10378
//////////////////////////////////////////////////////////////// // // Copyright (C) 2005 Affymetrix, Inc. // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License // (version 2.1) as published by the Free Software Foundation. // // 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 // //////////////////////////////////////////////////////////////// /** * @file LogStream.cpp * @author Chuck Sugnet * @date Tue Mar 21 10:35:22 PST 2006 * * @brief Output verbose messages to log file as we go along. */ #include "util/LogStream.h" // #include "util/AffxTime.h" #include "util/Util.h" // #ifdef __APPLE__ #include <mach/mach_init.h> #include <mach/task.h> #endif // #ifdef __linux__ #include "stdlib.h" #include "stdio.h" #include "string.h" #endif // #ifdef WIN32 #include "windows.h" #include "psapi.h" #endif void printHeader(std::ostream *out, bool profile) { if(out != NULL && out->good()) { (*out) << "Timestamp\t"; if(profile) { (*out) << "Total RAM\t"; (*out) << "Free RAM\t"; (*out) << "Swap Available\t"; (*out) << "Memory Available\t"; (*out) << "Memory Available at Start\t"; (*out) << "Memory Available at Block Start\t"; (*out) << "Memory Used Since Start\t"; (*out) << "Memory Used Since Block Start\t"; #ifdef __APPLE__ (*out) << "Memory Resident Size\t"; (*out) << "Memory Virtual Size\t"; #endif #ifdef __linux__ (*out) << "Memory Resident Size\t"; (*out) << "Memory Virtual Size\t"; #endif #ifdef WIN32 (*out) << "Memory Resident Size\t"; (*out) << "Memory Virtual Size\t"; #endif } (*out) << "Message\n"; } } /** Constructor. */ LogStream::LogStream(int verbosity, std::ostream *out, bool profile) : m_Verbosity(verbosity), m_Out(out), m_Profile(profile) { printHeader(m_Out, m_Profile); } LogStream::~LogStream() { m_ProgressTimeStart.clear(); m_ProgressTotal.clear(); } void LogStream::setStream(std::ostream *out) { m_Out = out; printHeader(m_Out, m_Profile); } void LogStream::unsetStream(std::ostream *out) { m_Out = NULL; } /** * A message to be processed by the stream. * * @param verbosity - What level of verbosity is associated with this message, higher number == more verbosity. * @param log - Message that is to be processed. * @param delimiter - Should a delimiter be emitted as well? */ void LogStream::message(int verbosity, const std::string &log, bool delimiter) { if(verbosity <= m_Verbosity && m_Out != NULL && m_Out->good()) { std::string timeStr = AffxTime::getCurrentTime().getTimeStampString(); (*m_Out) << timeStr << "\t"; if(m_Profile) (*m_Out) << profileString(); (*m_Out) << log; // For the log file we always dump a newline (*m_Out) << std::endl; m_Out->flush(); } } /** * Begin a progress reporting. After this initial call the * progressStep call will be called N times where N = the parameter * total passed in below. * * @param verbosity - What level of verbosity is the progress * associated with. Higher levels of verbosity produce more * messages. * @param msg - String message associated with the beginning of this task. * @param total - Expected number of times that the progressStep() * will be called after this. */ void LogStream::progressBegin(int verbosity, const std::string &msg, int total) { m_ProgressTimeStart.push_back(time(NULL)); m_ProgressTotal.push_back(total); if(verbosity <= m_Verbosity && m_Out != NULL && m_Out->good()) { // flush any C io before doing our IO fflush(NULL); std::string timeStr = AffxTime::getCurrentTime().getTimeStampString(); (*m_Out) << timeStr << "\t"; if(m_Profile) (*m_Out) << profileString(); (*m_Out) << msg; // For the log file we always dump a newline (*m_Out) << std::endl; m_Out->flush(); } } /** * This function is called when one unit of work has been done. In * general it is expected that the units of work should be roughly * equal in size. * * @param verbosity - At what verbosity levell should this step be * displayed. */ void LogStream::progressStep(int verbosity) { if(verbosity <= m_Verbosity && m_Out != NULL && m_Out->good()) { // flush any C io before doing our IO fflush(NULL); std::string timeStr = AffxTime::getCurrentTime().getTimeStampString(); (*m_Out) << timeStr << "\t"; if(m_Profile) (*m_Out) << profileString(); (*m_Out) << "Progress Step"; // For the log file we always dump a newline (*m_Out) << std::endl; m_Out->flush(); } } /** * Signals the end of progress report. * * @param verbosity - Level of verbosity associated with this progress report. * @param msg - Closing message from calling function. */ void LogStream::progressEnd(int verbosity, const std::string &msg) { time_t timeStart = m_ProgressTimeStart[m_ProgressTimeStart.size()-1]; m_ProgressTimeStart.pop_back(); m_ProgressTotal.pop_back(); if(verbosity <= m_Verbosity && m_Out != NULL && m_Out->good()) { time_t timeEnd = time(NULL); double dRunTime = (timeEnd - timeStart); // time span in seconds. std::string str; if (dRunTime < 60) { str = msg + "\t"; str += ::getDouble(dRunTime, 2, true); str += " second run time"; } else if (dRunTime < (60 * 60)) { str = msg + "\t"; str += ::getDouble((dRunTime) / 60, 2, true); str += " minute run time"; } else { str = msg + "\t"; str += ::getDouble((dRunTime) / (60 * 60), 2, true); str += " hour run time"; } // flush any C io before doing our IO fflush(NULL); std::string timeStr = AffxTime::getCurrentTime().getTimeStampString(); (*m_Out) << timeStr << "\t"; if(m_Profile) (*m_Out) << profileString(); (*m_Out) << str ; // For the log file we always dump a newline (*m_Out) << std::endl; m_Out->flush(); } } /** * What level of verbosity is requested. We force lots of output here. * * @param verbosity - Level below which progress messages are printed. */ void LogStream::setBaseVerbosity(int verbosity) { // do notthing } std::string toMB(int64_t mem) { return ToStr(mem/MEGABYTE); } #ifdef __APPLE__ void _getProcessMemOSX(uint64_t &rss, uint64_t &vs) { struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count)) { rss = 0; vs = 0; } else { rss = t_info.resident_size; vs = t_info.virtual_size; /* Looks like the os-x docs are wrong. The return values are in bytes, not pages vm_size_t page_size; if(KERN_SUCCESS != host_page_size(mach_task_self(), &page_size)) { rss = 0; vs = 0; } else { rss *= page_size; vs *= page_size; } */ } } #endif #ifdef __linux__ int parseProcLine(char* line){ int i = strlen(line); while (*line < '0' || *line > '9') line++; line[i-3] = '\0'; i = atoi(line); return i; } void _getProcessMemLinux(uint64_t &rss, uint64_t &vs) { FILE* file = fopen("/proc/self/status", "r"); char line[128]; rss = 0; vs = 0; // VmPeak: 3764 kB // VmSize: 3764 kB // VmLck: 0 kB // VmHWM: 376 kB // VmRSS: 376 kB // VmData: 164 kB // VmStk: 88 kB // VmExe: 20 kB // VmLib: 1408 kB // VmPTE: 32 kB while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmSize:", 7) == 0) vs = parseProcLine(line); if (strncmp(line, "VmRSS:", 6) == 0) rss = parseProcLine(line); } fclose(file); vs *= 1024; rss *= 1024; } #endif #ifdef WIN32 void _getProcessMemWin32(uint64_t &rss, uint64_t &vs) { PROCESS_MEMORY_COUNTERS_EX pmc; if(GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS)&pmc, sizeof(pmc))==0) { vs = 0; rss = 0; } else { vs = pmc.WorkingSetSize; rss = pmc.PrivateUsage; } } #endif std::string LogStream::profileString() { uint64_t freeRam = 0, totalRam = 0, swapAvail = 0, memAvail = 0; Util::memInfo(freeRam, totalRam, swapAvail, memAvail, false); uint64_t memFreeAtStart = Util::getMemFreeAtStart(); uint64_t memFreeAtBlock = Util::getMemFreeAtBlock(); int64_t memUsedSinceStart = memFreeAtStart; memUsedSinceStart -= memAvail; int64_t memUsedSinceBlock = memFreeAtBlock; memUsedSinceBlock -= memAvail; std::string profile = toMB(totalRam) + "\t" + toMB(freeRam) + "\t" + toMB(swapAvail) + "\t" + toMB(memAvail) + "\t" + toMB(memFreeAtStart) + "\t" + toMB(memFreeAtBlock) + "\t" + toMB(memUsedSinceStart) + "\t" + toMB(memUsedSinceBlock) + "\t"; #ifdef __APPLE__ uint64_t rss=0, vs=0; _getProcessMemOSX(rss, vs); profile += toMB(rss) + "\t" + toMB(vs) + "\t"; #endif #ifdef __linux__ uint64_t rss=0, vs=0; _getProcessMemLinux(rss, vs); profile += toMB(rss) + "\t" + toMB(vs) + "\t"; #endif #ifdef WIN32 uint64_t rss=0, vs=0; _getProcessMemWin32(rss, vs); profile += toMB(rss) + "\t" + toMB(vs) + "\t"; #endif return profile; }
lgpl-2.1
mtommila/apfloat
apfloat-calc/src/main/java/org/apfloat/calc/package-info.java
1261
/* * MIT License * * Copyright (c) 2002-2021 Mikko Tommila * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** Arbitrary precision calculator interactive application. */ package org.apfloat.calc;
lgpl-2.1
richardmg/qtcreator
src/plugins/projectexplorer/environmentaspect.cpp
3641
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "environmentaspect.h" #include "environmentaspectwidget.h" #include "target.h" #include <utils/qtcassert.h> static const char BASE_KEY[] = "PE.EnvironmentAspect.Base"; static const char CHANGES_KEY[] = "PE.EnvironmentAspect.Changes"; namespace ProjectExplorer { // -------------------------------------------------------------------- // EnvironmentAspect: // -------------------------------------------------------------------- EnvironmentAspect::EnvironmentAspect(RunConfiguration *runConfig) : IRunConfigurationAspect(runConfig), m_base(-1) { setDisplayName(tr("Run Environment")); setId("EnvironmentAspect"); } RunConfigWidget *EnvironmentAspect::createConfigurationWidget() { return new EnvironmentAspectWidget(this); } int EnvironmentAspect::baseEnvironmentBase() const { if (m_base == -1) { QList<int> bases = possibleBaseEnvironments(); QTC_ASSERT(!bases.isEmpty(), return -1); foreach (int i, bases) QTC_CHECK(i >= 0); m_base = bases.at(0); } return m_base; } void EnvironmentAspect::setBaseEnvironmentBase(int base) { QTC_ASSERT(base >= 0, return); QTC_ASSERT(possibleBaseEnvironments().contains(base), return); if (m_base != base) { m_base = base; emit baseEnvironmentChanged(); } } void EnvironmentAspect::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff) { if (m_changes != diff) { m_changes = diff; emit userEnvironmentChangesChanged(m_changes); emit environmentChanged(); } } Utils::Environment EnvironmentAspect::environment() const { Utils::Environment env = baseEnvironment(); env.modify(m_changes); return env; } void EnvironmentAspect::fromMap(const QVariantMap &map) { m_base = map.value(QLatin1String(BASE_KEY), -1).toInt(); m_changes = Utils::EnvironmentItem::fromStringList(map.value(QLatin1String(CHANGES_KEY)).toStringList()); } void EnvironmentAspect::toMap(QVariantMap &data) const { data.insert(QLatin1String(BASE_KEY), m_base); data.insert(QLatin1String(CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_changes)); } } // namespace ProjectExplorer
lgpl-2.1
joevandyk/osg
examples/osgmanipulator/osgmanipulator.cpp
16684
/* OpenSceneGraph example, osgmanipulator. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <osgDB/ReadFile> #include <osgUtil/Optimizer> #include <osgViewer/Viewer> #include <osg/CoordinateSystemNode> #include <osgText/Text> #include <osgManipulator/CommandManager> #include <osgManipulator/TabBoxDragger> #include <osgManipulator/TabPlaneDragger> #include <osgManipulator/TabPlaneTrackballDragger> #include <osgManipulator/TrackballDragger> #include <osgManipulator/Translate1DDragger> #include <osgManipulator/Translate2DDragger> #include <osgManipulator/TranslateAxisDragger> #include <osg/ShapeDrawable> #include <osg/MatrixTransform> #include <osg/Geometry> #include <osg/Material> #include <iostream> osgManipulator::Dragger* createDragger(const std::string& name) { osgManipulator::Dragger* dragger = 0; if ("TabPlaneDragger" == name) { osgManipulator::TabPlaneDragger* d = new osgManipulator::TabPlaneDragger(); d->setupDefaultGeometry(); dragger = d; } else if ("TabPlaneTrackballDragger" == name) { osgManipulator::TabPlaneTrackballDragger* d = new osgManipulator::TabPlaneTrackballDragger(); d->setupDefaultGeometry(); dragger = d; } else if ("TrackballDragger" == name) { osgManipulator::TrackballDragger* d = new osgManipulator::TrackballDragger(); d->setupDefaultGeometry(); dragger = d; } else if ("Translate1DDragger" == name) { osgManipulator::Translate1DDragger* d = new osgManipulator::Translate1DDragger(); d->setupDefaultGeometry(); dragger = d; } else if ("Translate2DDragger" == name) { osgManipulator::Translate2DDragger* d = new osgManipulator::Translate2DDragger(); d->setupDefaultGeometry(); dragger = d; } else if ("TranslateAxisDragger" == name) { osgManipulator::TranslateAxisDragger* d = new osgManipulator::TranslateAxisDragger(); d->setupDefaultGeometry(); dragger = d; } else { osgManipulator::TabBoxDragger* d = new osgManipulator::TabBoxDragger(); d->setupDefaultGeometry(); dragger = d; } return dragger; } osg::Node* createHUD() { osg::Geode* geode = new osg::Geode(); std::string timesFont("fonts/arial.ttf"); osg::StateSet* stateset = geode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); osgText::Text* text = new osgText::Text; geode->addDrawable( text ); osg::Vec3 position(50.0f,50.0f,0.0f); text->setPosition(position); text->setText("Use the Tab key to switch between the trackball and pick modes."); text->setFont(timesFont); osg::Camera* camera = new osg::Camera; // set the projection matrix camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1280,0,1024)); // set the view matrix camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); camera->setViewMatrix(osg::Matrix::identity()); // only clear the depth buffer camera->setClearMask(GL_DEPTH_BUFFER_BIT); // draw subgraph after main camera view. camera->setRenderOrder(osg::Camera::POST_RENDER); camera->addChild(geode); return camera; } osg::Node* addDraggerToScene(osg::Node* scene, osgManipulator::CommandManager* cmdMgr, const std::string& name) { scene->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON); osgManipulator::Selection* selection = new osgManipulator::Selection; selection->addChild(scene); osgManipulator::Dragger* dragger = createDragger(name); osg::Group* root = new osg::Group; root->addChild(dragger); root->addChild(selection); root->addChild(createHUD()); float scale = scene->getBound().radius() * 1.6; dragger->setMatrix(osg::Matrix::scale(scale, scale, scale) * osg::Matrix::translate(scene->getBound().center())); cmdMgr->connect(*dragger, *selection); return root; } osg::Node* createDemoScene(osgManipulator::CommandManager* cmdMgr) { osg::Group* root = new osg::Group; osg::ref_ptr<osg::Geode> geode_1 = new osg::Geode; osg::ref_ptr<osg::MatrixTransform> transform_1 = new osg::MatrixTransform; osg::ref_ptr<osg::Geode> geode_2 = new osg::Geode; osg::ref_ptr<osg::MatrixTransform> transform_2 = new osg::MatrixTransform; osg::ref_ptr<osg::Geode> geode_3 = new osg::Geode; osg::ref_ptr<osg::MatrixTransform> transform_3 = new osg::MatrixTransform; osg::ref_ptr<osg::Geode> geode_4 = new osg::Geode; osg::ref_ptr<osg::MatrixTransform> transform_4 = new osg::MatrixTransform; osg::ref_ptr<osg::Geode> geode_5 = new osg::Geode; osg::ref_ptr<osg::MatrixTransform> transform_5 = new osg::MatrixTransform; osg::ref_ptr<osg::Geode> geode_6 = new osg::Geode; osg::ref_ptr<osg::MatrixTransform> transform_6 = new osg::MatrixTransform; osg::ref_ptr<osg::Geode> geode_7 = new osg::Geode; osg::ref_ptr<osg::MatrixTransform> transform_7 = new osg::MatrixTransform; const float radius = 0.8f; const float height = 1.0f; osg::ref_ptr<osg::TessellationHints> hints = new osg::TessellationHints; hints->setDetailRatio(2.0f); osg::ref_ptr<osg::ShapeDrawable> shape; shape = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0.0f, 0.0f, -2.0f), 10, 10.0f, 0.1f), hints.get()); shape->setColor(osg::Vec4(0.5f, 0.5f, 0.7f, 1.0f)); geode_1->addDrawable(shape.get()); shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 0.0f, 0.0f), radius * 2,radius), hints.get()); shape->setColor(osg::Vec4(0.8f, 0.8f, 0.8f, 1.0f)); geode_2->addDrawable(shape.get()); shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(-3.0f, 0.0f, 0.0f), radius,radius), hints.get()); shape->setColor(osg::Vec4(0.6f, 0.8f, 0.8f, 1.0f)); geode_3->addDrawable(shape.get()); shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(3.0f, 0.0f, 0.0f), 2 * radius,radius), hints.get()); shape->setColor(osg::Vec4(0.4f, 0.9f, 0.3f, 1.0f)); geode_4->addDrawable(shape.get()); shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, -3.0f, 0.0f), radius, height), hints.get()); shape->setColor(osg::Vec4(0.2f, 0.5f, 0.7f, 1.0f)); geode_5->addDrawable(shape.get()); shape = new osg::ShapeDrawable(new osg::Cylinder(osg::Vec3(0.0f, 3.0f, 0.0f), radius, height), hints.get()); shape->setColor(osg::Vec4(1.0f, 0.3f, 0.3f, 1.0f)); geode_6->addDrawable(shape.get()); shape = new osg::ShapeDrawable(new osg::Cone(osg::Vec3(0.0f, 0.0f, 3.0f), 2.0f, 2.0f), hints.get()); shape->setColor(osg::Vec4(0.8f, 0.8f, 0.4f, 1.0f)); geode_7->addDrawable(shape.get()); // material osg::ref_ptr<osg::Material> matirial = new osg::Material; matirial->setColorMode(osg::Material::DIFFUSE); matirial->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1)); matirial->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1)); matirial->setShininess(osg::Material::FRONT_AND_BACK, 64.0f); root->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), osg::StateAttribute::ON); transform_1.get()->addChild(addDraggerToScene(geode_1.get(),cmdMgr,"TabBoxDragger")); transform_2.get()->addChild(addDraggerToScene(geode_2.get(),cmdMgr,"TabPlaneDragger")); transform_3.get()->addChild(addDraggerToScene(geode_3.get(),cmdMgr,"TabPlaneTrackballDragger")); transform_4.get()->addChild(addDraggerToScene(geode_4.get(),cmdMgr,"TrackballDragger")); transform_5.get()->addChild(addDraggerToScene(geode_5.get(),cmdMgr,"Translate1DDragger")); transform_6.get()->addChild(addDraggerToScene(geode_6.get(),cmdMgr,"Translate2DDragger")); transform_7.get()->addChild(addDraggerToScene(geode_7.get(),cmdMgr,"TranslateAxisDragger")); root->addChild(transform_1.get()); root->addChild(transform_2.get()); root->addChild(transform_3.get()); root->addChild(transform_4.get()); root->addChild(transform_5.get()); root->addChild(transform_6.get()); root->addChild(transform_7.get()); return root; } class PickModeHandler : public osgGA::GUIEventHandler { public: enum Modes { VIEW = 0, PICK }; PickModeHandler(): _mode(VIEW), _activeDragger(0) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*) { osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa); if (!view) return false; if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Tab && ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN && _activeDragger == 0) { _mode = ! _mode; } if (VIEW == _mode) return false; switch (ea.getEventType()) { case osgGA::GUIEventAdapter::PUSH: { osgUtil::LineSegmentIntersector::Intersections intersections; _pointer.reset(); if (view->computeIntersections(ea.getX(),ea.getY(),intersections)) { _pointer.setCamera(view->getCamera()); _pointer.setMousePosition(ea.getX(), ea.getY()); for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin(); hitr != intersections.end(); ++hitr) { _pointer.addIntersection(hitr->nodePath, hitr->getLocalIntersectPoint()); } for (osg::NodePath::iterator itr = _pointer._hitList.front().first.begin(); itr != _pointer._hitList.front().first.end(); ++itr) { osgManipulator::Dragger* dragger = dynamic_cast<osgManipulator::Dragger*>(*itr); if (dragger) { dragger->handle(_pointer, ea, aa); _activeDragger = dragger; break; } } } } case osgGA::GUIEventAdapter::DRAG: case osgGA::GUIEventAdapter::RELEASE: { if (_activeDragger) { _pointer._hitIter = _pointer._hitList.begin(); _pointer.setCamera(view->getCamera()); _pointer.setMousePosition(ea.getX(), ea.getY()); _activeDragger->handle(_pointer, ea, aa); } break; } default: break; } if (ea.getEventType() == osgGA::GUIEventAdapter::RELEASE) { _activeDragger = 0; _pointer.reset(); } return true; } private: unsigned int _mode; osgManipulator::Dragger* _activeDragger; osgManipulator::PointerInfo _pointer; }; int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the standard OpenSceneGraph example which loads and visualises 3d models."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available"); arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings."); arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation [TabPlaneDragger,TabPlaneTrackballDragger,TrackballDragger,Translate1DDragger,Translate2DDragger,TranslateAxisDragger,TabBoxDragger]"); // construct the viewer. osgViewer::Viewer viewer; // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); // if user request help write it out to cout. bool helpAll = arguments.read("--help-all"); unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) | ((helpAll || arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) | ((helpAll || arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 ); if (helpType) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } std::string dragger_name = "TabBoxDragger"; arguments.read("--dragger", dragger_name); osg::Timer_t start_tick = osg::Timer::instance()->tick(); // read the scene from the list of file specified command line args. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); // create a command manager osg::ref_ptr<osgManipulator::CommandManager> cmdMgr = new osgManipulator::CommandManager; // if no model has been successfully loaded report failure. bool tragger2Scene(true); if (!loadedModel) { //std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; //return 1; loadedModel = createDemoScene(cmdMgr.get()); tragger2Scene=false; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } osg::Timer_t end_tick = osg::Timer::instance()->tick(); std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl; // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); // pass the loaded scene graph to the viewer. if ( tragger2Scene ) { viewer.setSceneData(addDraggerToScene(loadedModel.get(), cmdMgr.get(), dragger_name)); } else { viewer.setSceneData(loadedModel.get()); } viewer.addEventHandler(new PickModeHandler()); return viewer.run(); }
lgpl-2.1
Luxoft/SDLP
SDL_Core/src/components/JSONHandler/src/SDLRPCObjectsImpl/V2/GPSData.cpp
5902
// // Copyright (c) 2013, Ford Motor Company // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following // disclaimer in the documentation and/or other materials provided with the // distribution. // // Neither the name of the Ford Motor Company nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. // #include "../include/JSONHandler/SDLRPCObjects/V2/GPSData.h" #include "GPSDataMarshaller.h" #include "CompassDirectionMarshaller.h" #include "DimensionMarshaller.h" /* interface Ford Sync RAPI version 2.0O date 2012-11-02 generated at Thu Jan 24 06:36:23 2013 source stamp Thu Jan 24 06:35:41 2013 author RC */ using namespace NsSmartDeviceLinkRPCV2; GPSData::GPSData(const GPSData& c) { *this=c; } bool GPSData::checkIntegrity(void) { return GPSDataMarshaller::checkIntegrity(*this); } GPSData::GPSData(void) { } bool GPSData::set_actual(bool actual_) { actual=actual_; return true; } bool GPSData::set_altitude(int altitude_) { if(altitude_>10000) return false; altitude=altitude_; return true; } bool GPSData::set_compassDirection(const CompassDirection& compassDirection_) { if(!CompassDirectionMarshaller::checkIntegrityConst(compassDirection_)) return false; compassDirection=compassDirection_; return true; } bool GPSData::set_dimension(const Dimension& dimension_) { if(!DimensionMarshaller::checkIntegrityConst(dimension_)) return false; dimension=dimension_; return true; } bool GPSData::set_hdop(unsigned int hdop_) { if(hdop_>31) return false; hdop=hdop_; return true; } bool GPSData::set_heading(unsigned int heading_) { if(heading_>360) return false; heading=heading_; return true; } bool GPSData::set_latitudeDegrees(int latitudeDegrees_) { if(latitudeDegrees_>1000000000) return false; latitudeDegrees=latitudeDegrees_; return true; } bool GPSData::set_longitudeDegrees(int longitudeDegrees_) { if(longitudeDegrees_>1000000000) return false; longitudeDegrees=longitudeDegrees_; return true; } bool GPSData::set_pdop(unsigned int pdop_) { if(pdop_>31) return false; pdop=pdop_; return true; } bool GPSData::set_satellites(unsigned int satellites_) { if(satellites_>31) return false; satellites=satellites_; return true; } bool GPSData::set_speed(unsigned int speed_) { if(speed_>400) return false; speed=speed_; return true; } bool GPSData::set_utcDay(unsigned int utcDay_) { if(utcDay_>31) return false; if(utcDay_<1) return false; utcDay=utcDay_; return true; } bool GPSData::set_utcHours(unsigned int utcHours_) { if(utcHours_>23) return false; utcHours=utcHours_; return true; } bool GPSData::set_utcMinutes(unsigned int utcMinutes_) { if(utcMinutes_>59) return false; utcMinutes=utcMinutes_; return true; } bool GPSData::set_utcMonth(unsigned int utcMonth_) { if(utcMonth_>12) return false; if(utcMonth_<1) return false; utcMonth=utcMonth_; return true; } bool GPSData::set_utcSeconds(unsigned int utcSeconds_) { if(utcSeconds_>59) return false; utcSeconds=utcSeconds_; return true; } bool GPSData::set_utcYear(unsigned int utcYear_) { if(utcYear_>2100) return false; if(utcYear_<2010) return false; utcYear=utcYear_; return true; } bool GPSData::set_vdop(unsigned int vdop_) { if(vdop_>31) return false; vdop=vdop_; return true; } bool GPSData::get_actual(void) const { return actual; } int GPSData::get_altitude(void) const { return altitude; } const CompassDirection& GPSData::get_compassDirection(void) const { return compassDirection; } const Dimension& GPSData::get_dimension(void) const { return dimension; } unsigned int GPSData::get_hdop(void) const { return hdop; } unsigned int GPSData::get_heading(void) const { return heading; } int GPSData::get_latitudeDegrees(void) const { return latitudeDegrees; } int GPSData::get_longitudeDegrees(void) const { return longitudeDegrees; } unsigned int GPSData::get_pdop(void) const { return pdop; } unsigned int GPSData::get_satellites(void) const { return satellites; } unsigned int GPSData::get_speed(void) const { return speed; } unsigned int GPSData::get_utcDay(void) const { return utcDay; } unsigned int GPSData::get_utcHours(void) const { return utcHours; } unsigned int GPSData::get_utcMinutes(void) const { return utcMinutes; } unsigned int GPSData::get_utcMonth(void) const { return utcMonth; } unsigned int GPSData::get_utcSeconds(void) const { return utcSeconds; } unsigned int GPSData::get_utcYear(void) const { return utcYear; } unsigned int GPSData::get_vdop(void) const { return vdop; }
lgpl-2.1
hovo1990/deviser
generator/tests/test_cpp_code/test-code/Transition.cpp
33004
/** * @file Transition.cpp * @brief Implementation of the Transition class. * @author SBMLTeam * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2013-2016 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright (C) 2006-2008 by the California Institute of Technology, * Pasadena, CA, USA * * Copyright (C) 2002-2005 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. Japan Science and Technology Agency, Japan * * 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. A copy of the license agreement is provided in the * file named "LICENSE.txt" included with this software distribution and also * available online as http://sbml.org/software/libsbml/license.html * ------------------------------------------------------------------------ --> */ #include <sbml/packages/qual/sbml/Transition.h> #include <sbml/packages/qual/sbml/ListOfTransitions.h> #include <sbml/packages/qual/validator/QualSBMLError.h> #include <sbml/util/ElementFilter.h> using namespace std; LIBSBML_CPP_NAMESPACE_BEGIN #ifdef __cplusplus /* * Creates a new Transition using the given SBML Level, Version and * &ldquo;qual&rdquo; package version. */ Transition::Transition(unsigned int level, unsigned int version, unsigned int pkgVersion) : SBase(level, version) , mId ("") , mName ("") , mInputs (level, version, pkgVersion) , mOutputs (level, version, pkgVersion) , mFunctionTerms (level, version, pkgVersion) { setSBMLNamespacesAndOwn(new QualPkgNamespaces(level, version, pkgVersion)); connectToChild(); } /* * Creates a new Transition using the given QualPkgNamespaces object. */ Transition::Transition(QualPkgNamespaces *qualns) : SBase(qualns) , mId ("") , mName ("") , mInputs (qualns) , mOutputs (qualns) , mFunctionTerms (qualns) { setElementNamespace(qualns->getURI()); connectToChild(); loadPlugins(qualns); } /* * Copy constructor for Transition. */ Transition::Transition(const Transition& orig) : SBase( orig ) , mId ( orig.mId ) , mName ( orig.mName ) , mInputs ( orig.mInputs ) , mOutputs ( orig.mOutputs ) , mFunctionTerms ( orig.mFunctionTerms ) { connectToChild(); } /* * Assignment operator for Transition. */ Transition& Transition::operator=(const Transition& rhs) { if (&rhs != this) { SBase::operator=(rhs); mId = rhs.mId; mName = rhs.mName; mInputs = rhs.mInputs; mOutputs = rhs.mOutputs; mFunctionTerms = rhs.mFunctionTerms; connectToChild(); } return *this; } /* * Creates and returns a deep copy of this Transition object. */ Transition* Transition::clone() const { return new Transition(*this); } /* * Destructor for Transition. */ Transition::~Transition() { } /* * Returns the value of the "id" attribute of this Transition. */ const std::string& Transition::getId() const { return mId; } /* * Returns the value of the "name" attribute of this Transition. */ const std::string& Transition::getName() const { return mName; } /* * Predicate returning @c true if this Transition's "id" attribute is set. */ bool Transition::isSetId() const { return (mId.empty() == false); } /* * Predicate returning @c true if this Transition's "name" attribute is set. */ bool Transition::isSetName() const { return (mName.empty() == false); } /* * Sets the value of the "id" attribute of this Transition. */ int Transition::setId(const std::string& id) { return SyntaxChecker::checkAndSetSId(id, mId); } /* * Sets the value of the "name" attribute of this Transition. */ int Transition::setName(const std::string& name) { mName = name; return LIBSBML_OPERATION_SUCCESS; } /* * Unsets the value of the "id" attribute of this Transition. */ int Transition::unsetId() { mId.erase(); if (mId.empty() == true) { return LIBSBML_OPERATION_SUCCESS; } else { return LIBSBML_OPERATION_FAILED; } } /* * Unsets the value of the "name" attribute of this Transition. */ int Transition::unsetName() { mName.erase(); if (mName.empty() == true) { return LIBSBML_OPERATION_SUCCESS; } else { return LIBSBML_OPERATION_FAILED; } } /* * Returns the ListOfInputs from this Transition. */ const ListOfInputs* Transition::getListOfInputs() const { return &mInputs; } /* * Returns the ListOfInputs from this Transition. */ ListOfInputs* Transition::getListOfInputs() { return &mInputs; } /* * Get an Input from the Transition. */ Input* Transition::getInput(unsigned int n) { return mInputs.get(n); } /* * Get an Input from the Transition. */ const Input* Transition::getInput(unsigned int n) const { return mInputs.get(n); } /* * Get an Input from the Transition based on its identifier. */ Input* Transition::getInput(const std::string& sid) { return mInputs.get(sid); } /* * Get an Input from the Transition based on its identifier. */ const Input* Transition::getInput(const std::string& sid) const { return mInputs.get(sid); } /* * Get an Input from the Transition based on the QualitativeSpecies to which it * refers. */ const Input* Transition::getInputByQualitativeSpecies(const std::string& sid) const { return mInputs.getByQualitativeSpecies(sid); } /* * Get an Input from the Transition based on the QualitativeSpecies to which it * refers. */ Input* Transition::getInputByQualitativeSpecies(const std::string& sid) { return mInputs.getByQualitativeSpecies(sid); } /* * Adds a copy of the given Input to this Transition. */ int Transition::addInput(const Input* i) { if (i == NULL) { return LIBSBML_OPERATION_FAILED; } else if (i->hasRequiredAttributes() == false) { return LIBSBML_INVALID_OBJECT; } else if (getLevel() != i->getLevel()) { return LIBSBML_LEVEL_MISMATCH; } else if (getVersion() != i->getVersion()) { return LIBSBML_VERSION_MISMATCH; } else if (matchesRequiredSBMLNamespacesForAddition(static_cast<const SBase*>(i)) == false) { return LIBSBML_NAMESPACES_MISMATCH; } else if (i->isSetId() && (mInputs.get(i->getId())) != NULL) { return LIBSBML_DUPLICATE_OBJECT_ID; } else { return mInputs.append(i); } } /* * Get the number of Input objects in this Transition. */ unsigned int Transition::getNumInputs() const { return mInputs.size(); } /* * Creates a new Input object, adds it to this Transition object and returns * the Input object created. */ Input* Transition::createInput() { Input* i = NULL; try { QUAL_CREATE_NS(qualns, getSBMLNamespaces()); i = new Input(qualns); delete qualns; } catch (...) { } if (i != NULL) { mInputs.appendAndOwn(i); } return i; } /* * Removes the nth Input from this Transition and returns a pointer to it. */ Input* Transition::removeInput(unsigned int n) { return mInputs.remove(n); } /* * Removes the Input from this Transition based on its identifier and returns a * pointer to it. */ Input* Transition::removeInput(const std::string& sid) { return mInputs.remove(sid); } /* * Returns the ListOfOutputs from this Transition. */ const ListOfOutputs* Transition::getListOfOutputs() const { return &mOutputs; } /* * Returns the ListOfOutputs from this Transition. */ ListOfOutputs* Transition::getListOfOutputs() { return &mOutputs; } /* * Get an Output from the Transition. */ Output* Transition::getOutput(unsigned int n) { return mOutputs.get(n); } /* * Get an Output from the Transition. */ const Output* Transition::getOutput(unsigned int n) const { return mOutputs.get(n); } /* * Get an Output from the Transition based on its identifier. */ Output* Transition::getOutput(const std::string& sid) { return mOutputs.get(sid); } /* * Get an Output from the Transition based on its identifier. */ const Output* Transition::getOutput(const std::string& sid) const { return mOutputs.get(sid); } /* * Get an Output from the Transition based on the QualitativeSpecies to which * it refers. */ const Output* Transition::getOutputByQualitativeSpecies(const std::string& sid) const { return mOutputs.getByQualitativeSpecies(sid); } /* * Get an Output from the Transition based on the QualitativeSpecies to which * it refers. */ Output* Transition::getOutputByQualitativeSpecies(const std::string& sid) { return mOutputs.getByQualitativeSpecies(sid); } /* * Adds a copy of the given Output to this Transition. */ int Transition::addOutput(const Output* o) { if (o == NULL) { return LIBSBML_OPERATION_FAILED; } else if (o->hasRequiredAttributes() == false) { return LIBSBML_INVALID_OBJECT; } else if (getLevel() != o->getLevel()) { return LIBSBML_LEVEL_MISMATCH; } else if (getVersion() != o->getVersion()) { return LIBSBML_VERSION_MISMATCH; } else if (matchesRequiredSBMLNamespacesForAddition(static_cast<const SBase*>(o)) == false) { return LIBSBML_NAMESPACES_MISMATCH; } else if (o->isSetId() && (mOutputs.get(o->getId())) != NULL) { return LIBSBML_DUPLICATE_OBJECT_ID; } else { return mOutputs.append(o); } } /* * Get the number of Output objects in this Transition. */ unsigned int Transition::getNumOutputs() const { return mOutputs.size(); } /* * Creates a new Output object, adds it to this Transition object and returns * the Output object created. */ Output* Transition::createOutput() { Output* o = NULL; try { QUAL_CREATE_NS(qualns, getSBMLNamespaces()); o = new Output(qualns); delete qualns; } catch (...) { } if (o != NULL) { mOutputs.appendAndOwn(o); } return o; } /* * Removes the nth Output from this Transition and returns a pointer to it. */ Output* Transition::removeOutput(unsigned int n) { return mOutputs.remove(n); } /* * Removes the Output from this Transition based on its identifier and returns * a pointer to it. */ Output* Transition::removeOutput(const std::string& sid) { return mOutputs.remove(sid); } /* * Returns the ListOfFunctionTerms from this Transition. */ const ListOfFunctionTerms* Transition::getListOfFunctionTerms() const { return &mFunctionTerms; } /* * Returns the ListOfFunctionTerms from this Transition. */ ListOfFunctionTerms* Transition::getListOfFunctionTerms() { return &mFunctionTerms; } /* * Get a FunctionTerm from the Transition. */ FunctionTerm* Transition::getFunctionTerm(unsigned int n) { return mFunctionTerms.get(n); } /* * Get a FunctionTerm from the Transition. */ const FunctionTerm* Transition::getFunctionTerm(unsigned int n) const { return mFunctionTerms.get(n); } /* * Adds a copy of the given FunctionTerm to this Transition. */ int Transition::addFunctionTerm(const FunctionTerm* ft) { if (ft == NULL) { return LIBSBML_OPERATION_FAILED; } else if (ft->hasRequiredAttributes() == false) { return LIBSBML_INVALID_OBJECT; } else if (ft->hasRequiredElements() == false) { return LIBSBML_INVALID_OBJECT; } else if (getLevel() != ft->getLevel()) { return LIBSBML_LEVEL_MISMATCH; } else if (getVersion() != ft->getVersion()) { return LIBSBML_VERSION_MISMATCH; } else if (matchesRequiredSBMLNamespacesForAddition(static_cast<const SBase*>(ft)) == false) { return LIBSBML_NAMESPACES_MISMATCH; } else { return mFunctionTerms.append(ft); } } /* * Get the number of FunctionTerm objects in this Transition. */ unsigned int Transition::getNumFunctionTerms() const { return mFunctionTerms.size(); } /* * Creates a new FunctionTerm object, adds it to this Transition object and * returns the FunctionTerm object created. */ FunctionTerm* Transition::createFunctionTerm() { FunctionTerm* ft = NULL; try { QUAL_CREATE_NS(qualns, getSBMLNamespaces()); ft = new FunctionTerm(qualns); delete qualns; } catch (...) { } if (ft != NULL) { mFunctionTerms.appendAndOwn(ft); } return ft; } /* * Removes the nth FunctionTerm from this Transition and returns a pointer to * it. */ FunctionTerm* Transition::removeFunctionTerm(unsigned int n) { return mFunctionTerms.remove(n); } /* * Returns the value of the "defaultTerm" element of this Transition. */ const DefaultTerm* Transition::getDefaultTerm() const { return mDefaultTerm; } /* * Returns the value of the "defaultTerm" element of this Transition. */ DefaultTerm* Transition::getDefaultTerm() { return mDefaultTerm; } /* * Predicate returning @c true if this Transition's "defaultTerm" element is * set. */ bool Transition::isSetDefaultTerm() const { return (mDefaultTerm != NULL); } /* * Sets the value of the "defaultTerm" element of this Transition. */ int Transition::setDefaultTerm(const DefaultTerm* defaultTerm) { if (mDefaultTerm == defaultTerm) { return LIBSBML_OPERATION_SUCCESS; } else if (defaultTerm == NULL) { delete mDefaultTerm; mDefaultTerm = NULL; return LIBSBML_OPERATION_SUCCESS; } else { delete mDefaultTerm; mDefaultTerm = (defaultTerm != NULL) ? defaultTerm->clone() : NULL; if (mDefaultTerm != NULL) { mDefaultTerm->connectToParent(this); } return LIBSBML_OPERATION_SUCCESS; } } /* * Creates a new DefaultTerm object, adds it to this Transition object and * returns the DefaultTerm object created. */ DefaultTerm* Transition::createDefaultTerm() { } /* * Unsets the value of the "defaultTerm" element of this Transition. */ int Transition::unsetDefaultTerm() { delete mDefaultTerm; mDefaultTerm = NULL; return LIBSBML_OPERATION_SUCCESS; } /* * Returns the XML element name of this Transition object. */ const std::string& Transition::getElementName() const { static const string name = "transition"; return name; } /* * Returns the libSBML type code for this Transition object. */ int Transition::getTypeCode() const { return SBML_QUAL_TRANSITION; } /* * Predicate returning @c true if all the required attributes for this * Transition object have been set. */ bool Transition::hasRequiredAttributes() const { bool allPresent = true; return allPresent; } /* * Predicate returning @c true if all the required elements for this Transition * object have been set. */ bool Transition::hasRequiredElements() const { bool allPresent = true; if (getNumFunctionTerms() == 0) { allPresent = false; } return allPresent; } /** @cond doxygenLibsbmlInternal */ /* * Write any contained elements */ void Transition::writeElements(XMLOutputStream& stream) const { SBase::writeElements(stream); if (getNumInputs() > 0) { mInputs.write(stream); } if (getNumOutputs() > 0) { mOutputs.write(stream); } if (getNumFunctionTerms() > 0) { mFunctionTerms.write(stream); } SBase::writeExtensionElements(stream); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Accepts the given SBMLVisitor */ bool Transition::accept(SBMLVisitor& v) const { v.visit(*this); mInputs.accept(v); mOutputs.accept(v); mFunctionTerms.accept(v); v.leave(*this); return true; } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Sets the parent SBMLDocument */ void Transition::setSBMLDocument(SBMLDocument* d) { SBase::setSBMLDocument(d); mInputs.setSBMLDocument(d); mOutputs.setSBMLDocument(d); mFunctionTerms.setSBMLDocument(d); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Connects to child elements */ void Transition::connectToChild() { SBase::connectToChild(); mInputs.connectToParent(this); mOutputs.connectToParent(this); mFunctionTerms.connectToParent(this); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Enables/disables the given package with this element */ void Transition::enablePackageInternal(const std::string& pkgURI, const std::string& pkgPrefix, bool flag) { SBase::enablePackageInternal(pkgURI, pkgPrefix, flag); mInputs.enablePackageInternal(pkgURI, pkgPrefix, flag); mOutputs.enablePackageInternal(pkgURI, pkgPrefix, flag); mFunctionTerms.enablePackageInternal(pkgURI, pkgPrefix, flag); } /** @endcond */ /* * Returns the first child element that has the given @p id in the model-wide * SId namespace, or @c NULL if no such object is found. */ SBase* Transition::getElementBySId(const std::string& id) { if (id.empty()) { return NULL; } SBase* obj = NULL; obj = mInputs.getElementBySId(id); if (obj != NULL) { return obj; } obj = mOutputs.getElementBySId(id); if (obj != NULL) { return obj; } obj = mFunctionTerms.getElementBySId(id); if (obj != NULL) { return obj; } return obj; } /* * Returns the first child element that has the given @p metaid, or @c NULL if * no such object is found. */ SBase* Transition::getElementByMetaId(const std::string& metaid) { if (metaid.empty()) { return NULL; } SBase* obj = NULL; if (mInputs.getMetaId() == metaid) { return &mInputs; } if (mOutputs.getMetaId() == metaid) { return &mOutputs; } if (mFunctionTerms.getMetaId() == metaid) { return &mFunctionTerms; } obj = mInputs.getElementByMetaId(metaid); if (obj != NULL) { return obj; } obj = mOutputs.getElementByMetaId(metaid); if (obj != NULL) { return obj; } obj = mFunctionTerms.getElementByMetaId(metaid); if (obj != NULL) { return obj; } return obj; } /* * Returns a List of all child SBase objects, including those nested to an * arbitrary depth. */ List* Transition::getAllElements(ElementFilter* filter) { List* ret = new List(); List* sublist = NULL; ADD_FILTERED_LIST(ret, sublist, mInputs, filter); ADD_FILTERED_LIST(ret, sublist, mOutputs, filter); ADD_FILTERED_LIST(ret, sublist, mFunctionTerms, filter); ADD_FILTERED_FROM_PLUGIN(ret, sublist, filter); return ret; } /** @cond doxygenLibsbmlInternal */ /* * Creates a new object from the next XMLToken on the XMLInputStream */ SBase* Transition::createObject(XMLInputStream& stream) { SBase* obj = NULL; const std::string& name = stream.peek().getName(); if (name == "listOfInputs") { if (mInputs.size() != 0) { getErrorLog()->logPackageError("qual", QualTransitionAllowedElements, getPackageVersion(), getLevel(), getVersion()); } obj = &mInputs; } else if (name == "listOfOutputs") { if (mOutputs.size() != 0) { getErrorLog()->logPackageError("qual", QualTransitionAllowedElements, getPackageVersion(), getLevel(), getVersion()); } obj = &mOutputs; } else if (name == "listOfFunctionTerms") { if (mFunctionTerms.size() != 0) { getErrorLog()->logPackageError("qual", QualTransitionAllowedElements, getPackageVersion(), getLevel(), getVersion()); } obj = &mFunctionTerms; } connectToChild(); return obj; } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Adds the expected attributes for this element */ void Transition::addExpectedAttributes(ExpectedAttributes& attributes) { SBase::addExpectedAttributes(attributes); attributes.add("id"); attributes.add("name"); } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Reads the expected attributes into the member data variables */ void Transition::readAttributes(const XMLAttributes& attributes, const ExpectedAttributes& expectedAttributes) { unsigned int level = getLevel(); unsigned int version = getVersion(); unsigned int pkgVersion = getPackageVersion(); unsigned int numErrs; bool assigned = false; SBMLErrorLog* log = getErrorLog(); if (static_cast<ListOfTransitions*>(getParentSBMLObject())->size() < 2) { numErrs = log->getNumErrors(); for (int n = numErrs-1; n >= 0; n--) { if (log->getError(n)->getErrorId() == UnknownPackageAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownPackageAttribute); log->logPackageError("qual", QualModelLOTransitionsAllowedAttributes, pkgVersion, level, version, details); } else if (log->getError(n)->getErrorId() == UnknownCoreAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownCoreAttribute); log->logPackageError("qual", QualModelLOTransitionsAllowedCoreAttributes, pkgVersion, level, version, details); } } } SBase::readAttributes(attributes, expectedAttributes); numErrs = log->getNumErrors(); for (int n = numErrs-1; n >= 0; n--) { if (log->getError(n)->getErrorId() == UnknownPackageAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownPackageAttribute); log->logPackageError("qual", QualTransitionAllowedAttributes, pkgVersion, level, version, details); } else if (log->getError(n)->getErrorId() == UnknownCoreAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(UnknownCoreAttribute); log->logPackageError("qual", QualTransitionAllowedCoreAttributes, pkgVersion, level, version, details); } } // // id SId (use = "optional" ) // assigned = attributes.readInto("id", mId); if (assigned == true) { if (mId.empty() == true) { logEmptyString(mId, level, version, "<Transition>"); } else if (SyntaxChecker::isValidSBMLSId(mId) == false) { logError(QualIdSyntaxRule, level, version, "The id '" + mId + "' does not " "conform to the syntax."); } } // // name string (use = "optional" ) // assigned = attributes.readInto("name", mName); if (assigned == true) { if (mName.empty() == true) { logEmptyString(mName, level, version, "<Transition>"); } } } /** @endcond */ /** @cond doxygenLibsbmlInternal */ /* * Writes the attributes to the stream */ void Transition::writeAttributes(XMLOutputStream& stream) const { SBase::writeAttributes(stream); if (isSetId() == true) { stream.writeAttribute("id", getPrefix(), mId); } if (isSetName() == true) { stream.writeAttribute("name", getPrefix(), mName); } SBase::writeExtensionAttributes(stream); } /** @endcond */ #endif /* __cplusplus */ /* * Creates a new Transition_t using the given SBML Level, Version and * &ldquo;qual&rdquo; package version. */ LIBSBML_EXTERN Transition_t * Transition_create(unsigned int level, unsigned int version, unsigned int pkgVersion) { return new Transition(level, version, pkgVersion); } /* * Creates and returns a deep copy of this Transition_t object. */ LIBSBML_EXTERN Transition_t* Transition_clone(const Transition_t* t) { if (t != NULL) { return static_cast<Transition_t*>(t->clone()); } else { return NULL; } } /* * Frees this Transition_t object. */ LIBSBML_EXTERN void Transition_free(Transition_t* t) { if (t != NULL) { delete t; } } /* * Returns the value of the "id" attribute of this Transition_t. */ LIBSBML_EXTERN const char * Transition_getId(const Transition_t * t) { if (t == NULL) { return NULL; } return t->getId().empty() ? NULL : safe_strdup(t->getId().c_str()); } /* * Returns the value of the "name" attribute of this Transition_t. */ LIBSBML_EXTERN const char * Transition_getName(const Transition_t * t) { if (t == NULL) { return NULL; } return t->getName().empty() ? NULL : safe_strdup(t->getName().c_str()); } /* * Predicate returning @c 1 if this Transition_t's "id" attribute is set. */ LIBSBML_EXTERN int Transition_isSetId(const Transition_t * t) { return (t != NULL) ? static_cast<int>(t->isSetId()) : 0; } /* * Predicate returning @c 1 if this Transition_t's "name" attribute is set. */ LIBSBML_EXTERN int Transition_isSetName(const Transition_t * t) { return (t != NULL) ? static_cast<int>(t->isSetName()) : 0; } /* * Sets the value of the "id" attribute of this Transition_t. */ LIBSBML_EXTERN int Transition_setId(Transition_t * t, const char * id) { return (t != NULL) ? t->setId(id) : LIBSBML_INVALID_OBJECT; } /* * Sets the value of the "name" attribute of this Transition_t. */ LIBSBML_EXTERN int Transition_setName(Transition_t * t, const char * name) { return (t != NULL) ? t->setName(name) : LIBSBML_INVALID_OBJECT; } /* * Unsets the value of the "id" attribute of this Transition_t. */ LIBSBML_EXTERN int Transition_unsetId(Transition_t * t) { return (t != NULL) ? t->unsetId() : LIBSBML_INVALID_OBJECT; } /* * Unsets the value of the "name" attribute of this Transition_t. */ LIBSBML_EXTERN int Transition_unsetName(Transition_t * t) { return (t != NULL) ? t->unsetName() : LIBSBML_INVALID_OBJECT; } /* * Returns a ListOf_t* containing Input_t objects from this Transition_t. */ LIBSBML_EXTERN ListOf_t* Transition_getListOfInputs(Transition_t* t) { return (t != NULL) ? t->getListOfInputs() : NULL; } /* * Get an Input_t from the Transition_t. */ LIBSBML_EXTERN const Input_t* Transition_getInput(Transition_t* t, unsigned int n) { return (t != NULL) ? t->getInput(n) : NULL; } /* * Get an Input_t from the Transition_t based on its identifier. */ LIBSBML_EXTERN const Input_t* Transition_getInputById(Transition_t* t, const char *sid) { return (t != NULL && sid != NULL) ? t->getInput(sid) : NULL; } /* * Get an Input_t from the Transition_t based on the QualitativeSpecies to * which it refers. */ LIBSBML_EXTERN const Input_t* Transition_getInputByQualitativeSpecies(Transition_t* t, const char *sid) { return (t != NULL && sid != NULL) ? t->getInputByQualitativeSpecies(sid) : NULL; } /* * Adds a copy of the given Input_t to this Transition_t. */ LIBSBML_EXTERN int Transition_addInput(Transition_t* t, const Input_t* i) { return (t != NULL) ? t->addInput(i) : LIBSBML_INVALID_OBJECT; } /* * Get the number of Input_t objects in this Transition_t. */ LIBSBML_EXTERN unsigned int Transition_getNumInputs(Transition_t* t) { return (t != NULL) ? t->getNumInputs() : SBML_INT_MAX; } /* * Creates a new Input_t object, adds it to this Transition_t object and * returns the Input_t object created. */ LIBSBML_EXTERN Input_t* Transition_createInput(Transition_t* t) { return (t != NULL) ? t->createInput() : NULL; } /* * Removes the nth Input_t from this Transition_t and returns a pointer to it. */ LIBSBML_EXTERN Input_t* Transition_removeInput(Transition_t* t, unsigned int n) { return (t != NULL) ? t->removeInput(n) : NULL; } /* * Removes the Input_t from this Transition_t based on its identifier and * returns a pointer to it. */ LIBSBML_EXTERN Input_t* Transition_removeInputById(Transition_t* t, const char* sid) { return (t != NULL && sid != NULL) ? t->removeInput(sid) : NULL; } /* * Returns a ListOf_t* containing Output_t objects from this Transition_t. */ LIBSBML_EXTERN ListOf_t* Transition_getListOfOutputs(Transition_t* t) { return (t != NULL) ? t->getListOfOutputs() : NULL; } /* * Get an Output_t from the Transition_t. */ LIBSBML_EXTERN const Output_t* Transition_getOutput(Transition_t* t, unsigned int n) { return (t != NULL) ? t->getOutput(n) : NULL; } /* * Get an Output_t from the Transition_t based on its identifier. */ LIBSBML_EXTERN const Output_t* Transition_getOutputById(Transition_t* t, const char *sid) { return (t != NULL && sid != NULL) ? t->getOutput(sid) : NULL; } /* * Get an Output_t from the Transition_t based on the QualitativeSpecies to * which it refers. */ LIBSBML_EXTERN const Output_t* Transition_getOutputByQualitativeSpecies(Transition_t* t, const char *sid) { return (t != NULL && sid != NULL) ? t->getOutputByQualitativeSpecies(sid) : NULL; } /* * Adds a copy of the given Output_t to this Transition_t. */ LIBSBML_EXTERN int Transition_addOutput(Transition_t* t, const Output_t* o) { return (t != NULL) ? t->addOutput(o) : LIBSBML_INVALID_OBJECT; } /* * Get the number of Output_t objects in this Transition_t. */ LIBSBML_EXTERN unsigned int Transition_getNumOutputs(Transition_t* t) { return (t != NULL) ? t->getNumOutputs() : SBML_INT_MAX; } /* * Creates a new Output_t object, adds it to this Transition_t object and * returns the Output_t object created. */ LIBSBML_EXTERN Output_t* Transition_createOutput(Transition_t* t) { return (t != NULL) ? t->createOutput() : NULL; } /* * Removes the nth Output_t from this Transition_t and returns a pointer to it. */ LIBSBML_EXTERN Output_t* Transition_removeOutput(Transition_t* t, unsigned int n) { return (t != NULL) ? t->removeOutput(n) : NULL; } /* * Removes the Output_t from this Transition_t based on its identifier and * returns a pointer to it. */ LIBSBML_EXTERN Output_t* Transition_removeOutputById(Transition_t* t, const char* sid) { return (t != NULL && sid != NULL) ? t->removeOutput(sid) : NULL; } /* * Returns a ListOf_t* containing FunctionTerm_t objects from this * Transition_t. */ LIBSBML_EXTERN ListOf_t* Transition_getListOfFunctionTerms(Transition_t* t) { return (t != NULL) ? t->getListOfFunctionTerms() : NULL; } /* * Get a FunctionTerm_t from the Transition_t. */ LIBSBML_EXTERN const FunctionTerm_t* Transition_getFunctionTerm(Transition_t* t, unsigned int n) { return (t != NULL) ? t->getFunctionTerm(n) : NULL; } /* * Adds a copy of the given FunctionTerm_t to this Transition_t. */ LIBSBML_EXTERN int Transition_addFunctionTerm(Transition_t* t, const FunctionTerm_t* ft) { return (t != NULL) ? t->addFunctionTerm(ft) : LIBSBML_INVALID_OBJECT; } /* * Get the number of FunctionTerm_t objects in this Transition_t. */ LIBSBML_EXTERN unsigned int Transition_getNumFunctionTerms(Transition_t* t) { return (t != NULL) ? t->getNumFunctionTerms() : SBML_INT_MAX; } /* * Creates a new FunctionTerm_t object, adds it to this Transition_t object and * returns the FunctionTerm_t object created. */ LIBSBML_EXTERN FunctionTerm_t* Transition_createFunctionTerm(Transition_t* t) { return (t != NULL) ? t->createFunctionTerm() : NULL; } /* * Removes the nth FunctionTerm_t from this Transition_t and returns a pointer * to it. */ LIBSBML_EXTERN FunctionTerm_t* Transition_removeFunctionTerm(Transition_t* t, unsigned int n) { return (t != NULL) ? t->removeFunctionTerm(n) : NULL; } /* * Returns the value of the "defaultTerm" element of this Transition_t. */ LIBSBML_EXTERN const DefaultTerm_t * Transition_getDefaultTerm(const Transition_t * t) { if (t == NULL) { return NULL; } return (DefaultTerm_t *)(t->getDefaultTerm()); } /* * Predicate returning @c 1 if this Transition_t's "defaultTerm" element is * set. */ LIBSBML_EXTERN int Transition_isSetDefaultTerm(const Transition_t * t) { return (t != NULL) ? static_cast<int>(t->isSetDefaultTerm()) : 0; } /* * Sets the value of the "defaultTerm" element of this Transition_t. */ LIBSBML_EXTERN int Transition_setDefaultTerm(Transition_t * t, const DefaultTerm_t * defaultTerm) { return (t != NULL) ? t->setDefaultTerm(defaultTerm) : LIBSBML_INVALID_OBJECT; } /* * Creates a new DefaultTerm_t object, adds it to this Transition_t object and * returns the DefaultTerm_t object created. */ LIBSBML_EXTERN DefaultTerm_t * Transition_createDefaultTerm(Transition_t* t) { } /* * Unsets the value of the "defaultTerm" element of this Transition_t. */ LIBSBML_EXTERN int Transition_unsetDefaultTerm(Transition_t * t) { return (t != NULL) ? t->unsetDefaultTerm() : LIBSBML_INVALID_OBJECT; } /* * Predicate returning @c 1 if all the required attributes for this * Transition_t object have been set. */ LIBSBML_EXTERN int Transition_hasRequiredAttributes(const Transition_t * t) { return (t != NULL) ? static_cast<int>(t->hasRequiredAttributes()) : 0; } /* * Predicate returning @c 1 if all the required elements for this Transition_t * object have been set. */ LIBSBML_EXTERN int Transition_hasRequiredElements(const Transition_t * t) { return (t != NULL) ? static_cast<int>(t->hasRequiredElements()) : 0; } LIBSBML_CPP_NAMESPACE_END
lgpl-2.1
lucee/extension-pdf
source/java/src/org/lucee/extension/pdf/img/PDF2ImageICEpdf.java
3356
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * 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, see <http://www.gnu.org/licenses/>. * **/ package org.lucee.extension.pdf.img; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import org.icepdf.core.pobjects.Catalog; import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.PDimension; import org.icepdf.core.pobjects.PRectangle; import org.icepdf.core.pobjects.Page; import org.icepdf.core.util.GraphicsRenderingHints; import lucee.loader.engine.CFMLEngineFactory; import lucee.runtime.exp.PageException; public class PDF2ImageICEpdf extends PDF2Image { public PDF2ImageICEpdf() { Document.class.getName();// this is needed, that the class throws a error when the PDFRenderer.jar is not in the enviroment } @Override public BufferedImage toImage(byte[] input, int pageNumber) throws PageException { return toImage(input, pageNumber, 100, false); } public BufferedImage toImage(byte[] input, int pageNumber, int scale, boolean transparent) throws PageException { Document document = toDocument(input); BufferedImage bi = toBufferedImage(document, pageNumber, scale / 100f, transparent); document.dispose(); return bi; } private Document toDocument(byte[] input) throws PageException { Document document = new Document(); try { document.setByteArray(input, 0, input.length, null); } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(t); } return document; } private static BufferedImage toBufferedImage(Document document, int pageNumber, float scale, boolean transparent) { System.getProperties().put("org.icepdf.core.screen.background", "VALUE_DRAW_NO_BACKGROUND"); Catalog cat = document.getCatalog(); Page page = cat.getPageTree().getPage(pageNumber - 1, document); PDimension sz = page.getSize(Page.BOUNDARY_CROPBOX, 0f, scale); int pageWidth = (int) sz.getWidth(); int pageHeight = (int) sz.getHeight(); BufferedImage image = new BufferedImage(pageWidth, pageHeight, transparent ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); if (!transparent) { PRectangle pageBoundary = page.getPageBoundary(Page.BOUNDARY_CROPBOX); float x = 0 - pageBoundary.x; float y = 0 - (pageBoundary.y - pageBoundary.height); g.setColor(Color.WHITE); g.fillRect((int) (0 - x), (int) (0 - y), (int) pageBoundary.width, (int) pageBoundary.height); } page.paint(g, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, 0f, scale); g.dispose(); cat.getPageTree().releasePage(page, document); return image; } }
lgpl-2.1
alphabetsoup/gpstk
src/ENUUtil.hpp
3051
#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2007, The University of Texas at Austin // //============================================================================ // // #ifndef GPSTK_ENUUTIL_HPP #define GPSTK_ENUUTIL_HPP // gpstk #include "Triple.hpp" #include "Matrix.hpp" #include "Vector.hpp" #include "Xvt.hpp" namespace gpstk { /** @addtogroup geodeticgroup */ //@{ /// A utility for converting from Cartesian in XZY to East-North-Up (ENU) class ENUUtil { public: // Constructors /** * Given a location as a (geodetic) latitude and longitude * the constructor creates the appropriate rotation matrix * from XYZ to ENU and retains it for later use. * @param refGeodeticLatRad geodetic latitude of point of interest (radians) * @param refLonRad longitude of point of interest (radians). */ ENUUtil( const double refGeodeticLatRad, const double refLonRad); // Methods /** * Convert from a vector in ECEF XYZ to ECEF ENU using the * current rotation matrix. * @param inV,inVec,in vector of interest in ECEF XYZ. * @return Same type as input but with the vector in ECEF ENU */ gpstk::Vector<double> convertToENU( const gpstk::Vector<double>& inV ) const; gpstk::Triple convertToENU( const gpstk::Triple& inVec ) const; gpstk::Xvt convertToENU( const gpstk::Xvt& in ) const; /** * Update the rotation matrix to the new location without creating * a new object * @param refGdLatRad geodetic latitude of point of interest (radians) * @param refLonRad longitude of point of interest (radians). */ void updatePosition( const double refGDLatRad, const double refLonRad ); // Utilities protected: void compute( const double refLat, const double refLon); Matrix<double> rotMat; }; //@} } #endif
lgpl-2.1
MenesesEvandro/WCF
wcfsetup/install/files/lib/system/payment/method/IPaymentMethod.class.php
1211
<?php namespace wcf\system\payment\method; /** * Default interface for payment methods. * * @author Marcel Werk * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Payment\Method */ interface IPaymentMethod { /** * Returns true, if this payment method supports recurring payments. * * @return boolean */ public function supportsRecurringPayments(); /** * Returns a list of supported currencies. * * @return string[] */ public function getSupportedCurrencies(); /** * Returns the HTML code of the purchase button. * * @param float $cost * @param string $currency ISO 4217 code * @param string $name product/item name * @param string $token custom token * @param string $returnURL * @param string $cancelReturnURL * @param boolean $isRecurring * @param integer $subscriptionLength * @param string $subscriptionLengthUnit * * @return string */ public function getPurchaseButton($cost, $currency, $name, $token, $returnURL, $cancelReturnURL, $isRecurring = false, $subscriptionLength = 0, $subscriptionLengthUnit = ''); }
lgpl-2.1
falko0000/moduleEProc
ZajavkiOtPostavwikov/ZajavkiOtPostavwikov-service/src/main/java/tj/zajavki/ot/postavwikov/service/impl/ZajavkiOtPostavwikovTempLocalServiceImpl.java
3564
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * 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. */ package tj.zajavki.ot.postavwikov.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import aQute.bnd.annotation.ProviderType; import tj.zajavki.ot.postavwikov.model.ZajavkiOtPostavwikov; import tj.zajavki.ot.postavwikov.model.ZajavkiOtPostavwikovTemp; import tj.zajavki.ot.postavwikov.service.base.ZajavkiOtPostavwikovTempLocalServiceBaseImpl; /** * The implementation of the zajavki ot postavwikov temp local service. * * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link tj.zajavki.ot.postavwikov.service.ZajavkiOtPostavwikovTempLocalService} interface. * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author Brian Wing Shun Chan * @see ZajavkiOtPostavwikovTempLocalServiceBaseImpl * @see tj.zajavki.ot.postavwikov.service.ZajavkiOtPostavwikovTempLocalServiceUtil */ @ProviderType public class ZajavkiOtPostavwikovTempLocalServiceImpl extends ZajavkiOtPostavwikovTempLocalServiceBaseImpl { public List<ZajavkiOtPostavwikovTemp> getZajavkiOtPostavwikovs(long tovar_id) { return zajavkiOtPostavwikovTempPersistence.findByTovarId(tovar_id); } public List<ZajavkiOtPostavwikovTemp> getZajavkiOtPostavwikovs(long lot_id, long postavwik_id) { return zajavkiOtPostavwikovTempPersistence.findByLotIdPostavwikId(lot_id, postavwik_id); } public Map<Long, ZajavkiOtPostavwikovTemp> getMapZajavkiOtPostavwikovs(long lot_id, long postavwik_id) { Map<Long, ZajavkiOtPostavwikovTemp> zajavka = new HashMap<Long, ZajavkiOtPostavwikovTemp>(); List<ZajavkiOtPostavwikovTemp> zajavkiOtPostavwikovs = getZajavkiOtPostavwikovs(lot_id,postavwik_id ); for(ZajavkiOtPostavwikovTemp otPostavwikov : zajavkiOtPostavwikovs) zajavka.put(otPostavwikov.getTovar_id(), otPostavwikov); return zajavka; } public int getCountZajavkiOtPostavwikovs(long lot_id, long postavwik_id) { return zajavkiOtPostavwikovTempPersistence.countByLotIdPostavwikId(lot_id, postavwik_id); } public int getCountLotId(long lot_id) { return zajavkiOtPostavwikovTempPersistence.countByLotId(lot_id); } public boolean compareTo(ZajavkiOtPostavwikovTemp otPostavwikovTemp, String predlozhenie_postavwika, String opisanie_tovara, long kod_strany_proizvoditelja, double summa_za_edinicu_tovara) { boolean result = true; if(!otPostavwikovTemp.getPredlozhenie_postavwika().equals(predlozhenie_postavwika) || !otPostavwikovTemp.getOpisanie_tovara().equals(opisanie_tovara) || otPostavwikovTemp.getKod_strany_proizvoditelja()!=kod_strany_proizvoditelja || otPostavwikovTemp.getSumma_za_edinicu_tovara()!= summa_za_edinicu_tovara) result = false; return result; } }
lgpl-2.1
kazuyaujihara/NCDK
NCDK/Layout/AtomPlacer.cs
40416
/* Copyright (C) 2003-2007 The Chemistry Development Kit (CDK) project * * Contact: cdk-devel@lists.sourceforge.net * * This program 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. * All we ask is that proper credit is given for our work, which includes * - but is not limited to - adding the above copyright notice to the beginning * of your source code files, and to any copyright notice that you may distribute * with programs based on this work. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using NCDK.Common.Mathematics; using NCDK.Geometries; using NCDK.Graphs; using NCDK.Graphs.Matrix; using NCDK.Numerics; using NCDK.Tools; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace NCDK.Layout { /// <summary> /// Methods for generating coordinates for atoms in various situations. They can /// be used for Automated Structure Diagram Generation or in the interactive /// buildup of molecules by the user. /// </summary> // @author steinbeck // @cdk.created 2003-08-29 // @cdk.module sdg public class AtomPlacer { private static readonly double ANGLE_120 = Vectors.DegreeToRadian(120); public const string Priority = "Weight"; /// <summary> /// Constructor for the AtomPlacer object /// </summary> public AtomPlacer() { } /// <summary> /// The molecule the AtomPlacer currently works with /// </summary> public IAtomContainer Molecule { get; set; } = null; /// <summary> /// Distribute the bonded atoms (neighbours) of an atom such that they fill the /// remaining space around an atom in a geometrically nice way. /// IMPORTANT: This method is not supposed to handle the /// case of one or no place neighbor. In the case of /// one placed neighbor, the chain placement methods /// should be used. /// </summary> /// <param name="atom">The atom whose partners are to be placed</param> /// <param name="placedNeighbours">The atoms which are already placed</param> /// <param name="unplacedNeighbours">The partners to be placed</param> /// <param name="bondLength">The standard bond length for the newly placed atoms</param> /// <param name="sharedAtomsCenter">The 2D centre of the placed atoms</param> public void DistributePartners(IAtom atom, IAtomContainer placedNeighbours, Vector2 sharedAtomsCenter, IAtomContainer unplacedNeighbours, double bondLength) { // calculate the direction away from the already placed partners of atom var sharedAtomsCenterVector = sharedAtomsCenter; var newDirection = atom.Point2D.Value; var occupiedDirection = sharedAtomsCenter; occupiedDirection = Vector2.Subtract(occupiedDirection, newDirection); // if the placing on the centre atom we get NaNs just give a arbitrary direction the // rest works it's self out if (Math.Abs(occupiedDirection.Length()) < 0.001) occupiedDirection = new Vector2(0, 1); Debug.WriteLine("distributePartners->occupiedDirection.Lenght(): " + occupiedDirection.Length()); var atomsToDraw = new List<IAtom>(); Debug.WriteLine($"Number of shared atoms: {placedNeighbours.Atoms.Count}"); // IMPORTANT: This method is not supposed to handle the case of one or // no place neighbor. In the case of one placed neighbor, the chain // placement methods should be used. if (placedNeighbours.Atoms.Count == 1) { Debug.WriteLine("Only one neighbour..."); for (int f = 0; f < unplacedNeighbours.Atoms.Count; f++) { atomsToDraw.Add(unplacedNeighbours.Atoms[f]); } var addAngle = Math.PI * 2 / (unplacedNeighbours.Atoms.Count + placedNeighbours.Atoms.Count); // IMPORTANT: At this point we need a calculation of the start // angle. Not done yet. IAtom placedAtom = placedNeighbours.Atoms[0]; double xDiff = placedAtom.Point2D.Value.X - atom.Point2D.Value.X; double yDiff = placedAtom.Point2D.Value.Y - atom.Point2D.Value.Y; Debug.WriteLine("distributePartners->xdiff: " + Vectors.RadianToDegree(xDiff)); Debug.WriteLine("distributePartners->ydiff: " + Vectors.RadianToDegree(yDiff)); var startAngle = GeometryUtil.GetAngle(xDiff, yDiff); Debug.WriteLine("distributePartners->angle: " + Vectors.RadianToDegree(startAngle)); PopulatePolygonCorners(atomsToDraw, atom.Point2D.Value, startAngle, addAngle, bondLength); return; } else if (placedNeighbours.Atoms.Count == 0) { Debug.WriteLine("First atom..."); for (int f = 0; f < unplacedNeighbours.Atoms.Count; f++) { atomsToDraw.Add(unplacedNeighbours.Atoms[f]); } var addAngle = Math.PI * 2.0 / unplacedNeighbours.Atoms.Count; // IMPORTANT: At this point we need a calculation of the start // angle. Not done yet. var startAngle = 0.0; PopulatePolygonCorners(atomsToDraw, atom.Point2D.Value, startAngle, addAngle, bondLength); return; } if (DoAngleSnap(atom, placedNeighbours)) { int numTerminal = 0; foreach (var unplaced in unplacedNeighbours.Atoms) if (Molecule.GetConnectedBonds(unplaced).Count() == 1) numTerminal++; if (numTerminal == unplacedNeighbours.Atoms.Count) { var a = NewVector(placedNeighbours.Atoms[0].Point2D.Value, atom.Point2D.Value); var b = NewVector(placedNeighbours.Atoms[1].Point2D.Value, atom.Point2D.Value); var d1 = GeometryUtil.GetAngle(a.X, a.Y); var d2 = GeometryUtil.GetAngle(b.X, b.Y); var sweep = Vectors.Angle(a, b); if (sweep < Math.PI) { sweep = 2 * Math.PI - sweep; } var startAngle = d2; if (d1 > d2 && d1 - d2 < Math.PI || d2 - d1 >= Math.PI) { startAngle = d1; } sweep /= (1 + unplacedNeighbours.Atoms.Count); PopulatePolygonCorners(unplacedNeighbours.Atoms, atom.Point2D.Value, startAngle, sweep, bondLength); MarkPlaced(unplacedNeighbours); return; } else { atom.RemoveProperty(MacroCycleLayout.MACROCYCLE_ATOM_HINT); } } // if the least hindered side of the atom is clearly defined (bondLength / 10 is an arbitrary value that seemed reasonable) //newDirection.Sub(sharedAtomsCenterVector); sharedAtomsCenterVector -= newDirection; newDirection = sharedAtomsCenterVector; newDirection = Vector2.Normalize(newDirection); newDirection *= bondLength; newDirection = -newDirection; Debug.WriteLine($"distributePartners->newDirection.Lenght(): {newDirection.Length()}"); var distanceMeasure = atom.Point2D.Value; distanceMeasure += newDirection; // get the two sharedAtom partners with the smallest distance to the new center var sortedAtoms = placedNeighbours.Atoms.ToArray(); GeometryUtil.SortBy2DDistance(sortedAtoms, distanceMeasure); var closestPoint1 = sortedAtoms[0].Point2D.Value; var closestPoint2 = sortedAtoms[1].Point2D.Value; closestPoint1 -= atom.Point2D.Value; closestPoint2 -= atom.Point2D.Value; var occupiedAngle = Vectors.Angle(closestPoint1, occupiedDirection); occupiedAngle += Vectors.Angle(closestPoint2, occupiedDirection); var angle1 = GeometryUtil.GetAngle( sortedAtoms[0].Point2D.Value.X - atom.Point2D.Value.X, sortedAtoms[0].Point2D.Value.Y - atom.Point2D.Value.Y); var angle3 = GeometryUtil.GetAngle( distanceMeasure.X - atom.Point2D.Value.X, distanceMeasure.Y - atom.Point2D.Value.Y); IAtom startAtom; if (angle1 > angle3) { if (angle1 - angle3 < Math.PI) { startAtom = sortedAtoms[1]; } else { // 12 o'clock is between the two vectors startAtom = sortedAtoms[0]; } } else { if (angle3 - angle1 < Math.PI) { startAtom = sortedAtoms[0]; } else { // 12 o'clock is between the two vectors startAtom = sortedAtoms[1]; } } { var remainingAngle = (2 * Math.PI) - occupiedAngle; var addAngle = remainingAngle / (unplacedNeighbours.Atoms.Count + 1); for (int f = 0; f < unplacedNeighbours.Atoms.Count; f++) { atomsToDraw.Add(unplacedNeighbours.Atoms[f]); } var radius = bondLength; var startAngle = GeometryUtil.GetAngle(startAtom.Point2D.Value.X - atom.Point2D.Value.X, startAtom.Point2D.Value.Y - atom.Point2D.Value.Y); Debug.WriteLine($"Before check: distributePartners->startAngle: {startAngle}"); Debug.WriteLine($"After check: distributePartners->startAngle: {startAngle}"); PopulatePolygonCorners(atomsToDraw, atom.Point2D.Value, startAngle, addAngle, radius); } } private bool DoAngleSnap(IAtom atom, IAtomContainer placedNeighbours) { if (placedNeighbours.Atoms.Count != 2) return false; var b1 = Molecule.GetBond(atom, placedNeighbours.Atoms[0]); if (!b1.IsInRing) return false; var b2 = Molecule.GetBond(atom, placedNeighbours.Atoms[1]); if (!b2.IsInRing) return false; var p1 = atom.Point2D.Value; var p2 = placedNeighbours.Atoms[0].Point2D.Value; var p3 = placedNeighbours.Atoms[1].Point2D.Value; var v1 = NewVector(p2, p1); var v2 = NewVector(p3, p1); return Math.Abs(Vectors.Angle(v2, v1) - ANGLE_120) < 0.01; } /// <summary> /// Places the atoms in a linear chain. /// </summary> /// <remarks> /// Expects the first atom to be placed and /// places the next atom according to initialBondVector. The rest of the chain /// is placed such that it is as linear as possible (in the overall result, the /// angles in the chain are set to 120 Deg.) /// </remarks> /// <param name="atomContainer">The IAtomContainer containing the chain atom to be placed</param> /// <param name="initialBondVector">The Vector indicating the direction of the first bond</param> /// <param name="bondLength">The factor used to scale the initialBondVector</param> public void PlaceLinearChain(IAtomContainer atomContainer, ref Vector2 initialBondVector, double bondLength) { var withh = atomContainer.Builder.NewAtomContainer(atomContainer); // BUGFIX - withh does not have cloned cloned atoms, so changes are // reflected in our atom container. If we're using implicit hydrogens // the correct counts need saving and restoring var numh = new int[atomContainer.Atoms.Count]; for (int i = 0, n = atomContainer.Atoms.Count; i < n; i++) { numh[i] = atomContainer.Atoms[i].ImplicitHydrogenCount ?? 0; } Debug.WriteLine($"Placing linear chain of length {atomContainer.Atoms.Count}"); var bondVector = initialBondVector; IBond prevBond = null; for (int f = 0; f < atomContainer.Atoms.Count - 1; f++) { var atom = atomContainer.Atoms[f]; var nextAtom = atomContainer.Atoms[f + 1]; var currBond = atomContainer.GetBond(atom, nextAtom); var atomPoint = atom.Point2D.Value; bondVector = Vector2.Normalize(bondVector); bondVector *= bondLength; if (f == 0) initialBondVector = bondVector; atomPoint += bondVector; nextAtom.Point2D = atomPoint; nextAtom.IsPlaced = true; bool trans = false; if (prevBond != null && IsColinear(atom, Molecule.GetConnectedBonds(atom))) { // double length of the last bond to determining next placement var p = prevBond.GetOther(atom).Point2D.Value; p = Vector2.Lerp(p, atom.Point2D.Value, 2); nextAtom.Point2D = p; } if (GeometryUtil.Has2DCoordinates(atomContainer)) { try { if (f > 2 && BondTools.IsValidDoubleBondConfiguration(withh, withh.GetBond(withh.Atoms[f - 2], withh.Atoms[f - 1]))) { trans = BondTools.IsCisTrans(withh.Atoms[f - 3], withh.Atoms[f - 2], withh.Atoms[f - 1], withh.Atoms[f - 0], withh); } } catch (Exception) { Debug.WriteLine("Exception in detecting E/Z. This could mean that cleanup does not respect E/Z"); } bondVector = GetNextBondVector(nextAtom, atom, GeometryUtil.Get2DCenter(Molecule), trans); } else { bondVector = GetNextBondVector(nextAtom, atom, GeometryUtil.Get2DCenter(Molecule), true); } prevBond = currBond; } // BUGFIX part 2 - restore hydrogen counts for (int i = 0, n = atomContainer.Atoms.Count; i < n; i++) { atomContainer.Atoms[i].ImplicitHydrogenCount = numh[i]; } } private bool IsTerminalD4(IAtom atom) { var bonds = Molecule.GetConnectedBonds(atom).ToReadOnlyList(); if (bonds.Count != 4) return false; int nonD1 = 0; foreach (var bond in bonds) { if (Molecule.GetConnectedBonds(bond.GetOther(atom)).Count() != 1) { if (++nonD1 > 1) return false; } } return true; } /// <summary> /// Returns the next bond vector needed for drawing an extended linear chain of /// atoms. It assumes an angle of 120 deg for a nice chain layout and /// calculates the two possible placments for the next atom. It returns the /// vector pointing farmost away from a given start atom. /// </summary> /// <param name="atom">An atom for which the vector to the next atom to draw is calculated</param> /// <param name="previousAtom">The preceding atom for angle calculation</param> /// <param name="distanceMeasure">A point from which the next atom is to be farmost away</param> /// <param name="trans">if true E (trans) configurations are built, false makes Z (cis) configurations</param> /// <returns>A vector pointing to the location of the next atom to draw</returns> public Vector2 GetNextBondVector(IAtom atom, IAtom previousAtom, Vector2 distanceMeasure, bool trans) { Debug.WriteLine("Entering AtomPlacer.GetNextBondVector()"); Debug.WriteLine($"Arguments are atom: {atom}, previousAtom: {previousAtom}, distanceMeasure: {distanceMeasure}"); var a = previousAtom.Point2D; var b = atom.Point2D; var bonds = Molecule.GetConnectedBonds(atom).ToReadOnlyList(); if (IsColinear(atom, bonds)) { return b.Value - a.Value; } var angle = GeometryUtil.GetAngle(previousAtom.Point2D.Value.X - atom.Point2D.Value.X, previousAtom.Point2D.Value.Y - atom.Point2D.Value.Y); double addAngle; if (IsTerminalD4(atom)) addAngle = Vectors.DegreeToRadian(45); else if (IsColinear(atom, bonds)) addAngle = Vectors.DegreeToRadian(180); else if (PeriodicTable.IsMetal(atom.AtomicNumber)) addAngle = (2 * Math.PI) / bonds.Count; else { addAngle = Vectors.DegreeToRadian(120); if (!trans) addAngle = Vectors.DegreeToRadian(60); } angle += addAngle; var vec1 = new Vector2(Math.Cos(angle), Math.Sin(angle)); var point1 = atom.Point2D.Value; point1 += vec1; var distance1 = Vector2.Distance(point1, distanceMeasure); angle += addAngle; var vec2 = new Vector2(Math.Cos(angle), Math.Sin(angle)); var point2 = atom.Point2D.Value; point2 += vec2; var distance2 = Vector2.Distance(point2, distanceMeasure); if (distance2 > distance1) { Debug.WriteLine("Exiting AtomPlacer.GetNextBondVector()"); return vec2; } Debug.WriteLine("Exiting AtomPlacer.GetNextBondVector()"); return vec1; } /// <summary> /// Populates the corners of a polygon with atoms. Used to place atoms in a /// geometrically regular way around a ring center or another atom. If this is /// used to place the bonding partner of an atom (and not to draw a ring) we /// want to place the atoms such that those with highest "weight" are placed /// far-most away from the rest of the molecules. The "weight" mentioned here is /// calculated by a modified Morgan number algorithm. /// </summary> /// <param name="atoms">All the atoms to draw</param> /// <param name="thetaBeg">A start angle (in radians), giving the angle of the most clockwise atom which has already been placed</param> /// <param name="thetaStep">An angle (in radians) to be added for each atom from atomsToDraw</param> /// <param name="center">The center of a ring, or an atom for which the partners are to be placed</param> /// <param name="radius">The radius of the polygon to be populated: bond length or ring radius</param> public static void PopulatePolygonCorners(IEnumerable<IAtom> atoms, Vector2 center, double thetaBeg, double thetaStep, double radius) { double theta = thetaBeg; Debug.WriteLine($"populatePolygonCorners(numAtoms={atoms.Count()}, center={center}, thetaBeg={Common.Mathematics.Vectors.RadianToDegree(thetaBeg)}, r={radius}"); foreach (var atom in atoms) { theta += thetaStep; var x = Math.Cos(theta) * radius; var y = Math.Sin(theta) * radius; var newX = x + center.X; var newY = y + center.Y; atom.Point2D = new Vector2(newX, newY); atom.IsPlaced = true; Debug.WriteLine($"populatePolygonCorners - angle={Vectors.RadianToDegree(theta)}, newX={newX}, newY={newY}"); } } /// <summary> /// Partition the bonding partners of a given atom into placed (coordinates assigned) and not placed. /// </summary> /// <param name="atom">The atom whose bonding partners are to be partitioned</param> /// <param name="unplacedPartners">A vector for the unplaced bonding partners to go in</param> /// <param name="placedPartners">A vector for the placed bonding partners to go in</param> public void PartitionPartners(IAtom atom, IAtomContainer unplacedPartners, IAtomContainer placedPartners) { var atoms = Molecule.GetConnectedAtoms(atom); foreach (var curatom in atoms) { if (curatom.IsPlaced) { placedPartners.Atoms.Add(curatom); } else { unplacedPartners.Atoms.Add(curatom); } } } /// <summary> /// Search an aliphatic molecule for the longest chain. This is the method to /// be used if there are no rings in the molecule and you want to layout the /// longest chain in the molecule as a starting point of the structure diagram /// generation. /// </summary> /// <param name="molecule">The molecule to be search for the longest unplaced chain</param> /// <returns>An AtomContainer holding the longest chain.</returns> /// <exception cref="NoSuchAtomException">Description of the Exception</exception> public static IAtomContainer GetInitialLongestChain(IAtomContainer molecule) { Debug.WriteLine("Start of GetInitialLongestChain()"); var conMat = ConnectionMatrix.GetMatrix(molecule); Debug.WriteLine("Computing all-pairs-shortest-paths"); var apsp = PathTools.ComputeFloydAPSP(conMat); int maxPathLength = 0; int bestStartAtom = -1; int bestEndAtom = -1; for (int f = 0; f < apsp.Length; f++) { var atom = molecule.Atoms[f]; if (molecule.GetConnectedBonds(atom).Count() == 1) { for (int g = 0; g < apsp.Length; g++) { if (apsp[f][g] > maxPathLength) { maxPathLength = apsp[f][g]; bestStartAtom = f; bestEndAtom = g; } } } } Debug.WriteLine($"Longest chain in molecule is of length {maxPathLength} between atoms {bestStartAtom + 1} and {bestEndAtom + 1}"); var startAtom = molecule.Atoms[bestStartAtom]; var path = molecule.Builder.NewAtomContainer(); path.Atoms.Add(startAtom); path = GetLongestUnplacedChain(molecule, startAtom); Debug.WriteLine("End of GetInitialLongestChain()"); return path; } /// <summary> /// Search a molecule for the longest unplaced, aliphatic chain in it. If an /// aliphatic chain encounters an unplaced ring atom, the ring atom is also /// appended to allow for it to be laid out. This gives us a vector for /// attaching the unplaced ring later. /// </summary> /// <param name="molecule">The molecule to be search for the longest unplaced chain</param> /// <param name="startAtom">A start atom from which the chain search starts</param> /// <returns>An AtomContainer holding the longest unplaced chain.</returns> /// <exception cref="CDKException">Description of the Exception</exception> public static IAtomContainer GetLongestUnplacedChain(IAtomContainer molecule, IAtom startAtom) { Debug.WriteLine("Start of getLongestUnplacedChain."); var pathes = new IAtomContainer[molecule.Atoms.Count]; for (int f = 0; f < molecule.Atoms.Count; f++) { molecule.Atoms[f].IsVisited = false; pathes[f] = molecule.Builder.NewAtomContainer(); pathes[f].Atoms.Add(startAtom); } var startSphere = new List<IAtom> { startAtom }; BreadthFirstSearch(molecule, startSphere, pathes); int longest = 0; int longestPathLength = 0; int maxDegreeSum = 0; for (int f = 0; f < molecule.Atoms.Count; f++) { if (pathes[f].Atoms.Count >= longestPathLength) { var degreeSum = GetDegreeSum(pathes[f], molecule); if (degreeSum > maxDegreeSum) { maxDegreeSum = degreeSum; longest = f; longestPathLength = pathes[f].Atoms.Count; } } } Debug.WriteLine("End of getLongestUnplacedChain."); return pathes[longest]; } /// <summary> /// Performs a breadthFirstSearch in an AtomContainer starting with a /// particular sphere, which usually consists of one start atom, and searches /// for the longest aliphatic chain which is yet unplaced. If the search /// encounters an unplaced ring atom, it is also appended to the chain so that /// this last bond of the chain can also be laid out. This gives us the /// orientation for the attachment of the ring system. /// </summary> /// <param name="ac">The AtomContainer to be searched</param> /// <param name="sphere">A sphere of atoms to start the search with</param> /// <param name="pathes">A vector of N paths (N = no of heavy atoms).</param> /// <exception cref="CDKException"> Description of the Exception</exception> public static void BreadthFirstSearch(IAtomContainer ac, IList<IAtom> sphere, IAtomContainer[] pathes) { var newSphere = new List<IAtom>(); Debug.WriteLine("Start of breadthFirstSearch"); foreach (var atom in sphere) { if (!atom.IsInRing) { var atomNr = ac.Atoms.IndexOf(atom); Debug.WriteLine($"{nameof(BreadthFirstSearch)} around atom {atomNr + 1}"); var bonds = ac.GetConnectedBonds(atom); foreach (var curBond in bonds) { var nextAtom = curBond.GetOther(atom); if (!nextAtom.IsVisited && !nextAtom.IsPlaced) { var nextAtomNr = ac.Atoms.IndexOf(nextAtom); Debug.WriteLine("BreadthFirstSearch is meeting new atom " + (nextAtomNr + 1)); pathes[nextAtomNr] = ac.Builder.NewAtomContainer(pathes[atomNr]); Debug.WriteLine("Making copy of path " + (atomNr + 1) + " to form new path " + (nextAtomNr + 1)); pathes[nextAtomNr].Atoms.Add(nextAtom); Debug.WriteLine("Adding atom " + (nextAtomNr + 1) + " to path " + (nextAtomNr + 1)); pathes[nextAtomNr].Bonds.Add(curBond); if (ac.GetConnectedBonds(nextAtom).Count() > 1) { newSphere.Add(nextAtom); } } } } } if (newSphere.Count > 0) { for (int f = 0; f < newSphere.Count; f++) { newSphere[f].IsVisited = true; } BreadthFirstSearch(ac, newSphere, pathes); } Debug.WriteLine("End of breadthFirstSearch"); } #if DEBUG /// <summary> /// Returns a string with the numbers of all placed atoms in an AtomContainer /// </summary> /// <param name="ac">The AtomContainer for which the placed atoms are to be listed</param> /// <returns>A string with the numbers of all placed atoms in an AtomContainer</returns> public static string ListPlaced(IAtomContainer ac) { string s = "Placed: "; for (int f = 0; f < ac.Atoms.Count; f++) { if (ac.Atoms[f].IsPlaced) { s += (f + 1) + "+ "; } else { s += (f + 1) + "- "; } } return s; } /// <summary> /// Returns a string with the numbers of all atoms in an <see cref="IAtomContainer"/> relative /// to a given Molecule, i.e. the number is listed is the position of each /// atom in the Molecule. /// </summary> /// <param name="mol">Description of Parameter</param> /// <param name="ac">The <see cref="IAtomContainer"/> for which the placed atoms are to be listed</param> /// <returns>A string with the numbers of all placed atoms in an AtomContainer</returns> /// <exception cref="CDKException"></exception> public static string ListNumbers(IAtomContainer mol, IAtomContainer ac) { string s = "Numbers: "; for (int f = 0; f < ac.Atoms.Count; f++) { s += (mol.Atoms.IndexOf(ac.Atoms[f]) + 1) + " "; } return s; } /// <summary> /// Returns a string with the numbers of all atoms in a Vector relative to a /// given Molecule. I.e. the number the is listesd is the position of each atom /// in the Molecule. /// </summary> /// <param name="ac">The Vector for which the placed atoms are to be listed</param> /// <param name="mol">Description of the Parameter</param> /// <returns>A string with the numbers of all placed atoms in an AtomContainer</returns> public static string ListNumbers(IAtomContainer mol, List<IAtom> ac) { string s = "Numbers: "; for (int f = 0; f < ac.Count; f++) { s += (mol.Atoms.IndexOf((IAtom)ac[f]) + 1) + " "; } return s; } #endif /// <summary> /// True is all the atoms in the given AtomContainer have been placed /// </summary> /// <param name="ac">The AtomContainer to be searched</param> /// <returns>True is all the atoms in the given AtomContainer have been placed</returns> public static bool AllPlaced(IAtomContainer ac) { for (int f = 0; f < ac.Atoms.Count; f++) { if (!ac.Atoms[f].IsPlaced) { return false; } } return true; } /// <summary> /// Marks all the atoms in the given AtomContainer as not placed /// </summary> /// <param name="ac">The AtomContainer whose atoms are to be marked</param> public static void MarkNotPlaced(IAtomContainer ac) => MarkPlaced(ac, false); /// <summary> /// Marks all the atoms in the given AtomContainer as placed /// </summary> /// <param name="ac">The <see cref="IAtomContainer"/> whose atoms are to be marked</param> public static void MarkPlaced(IAtomContainer ac) => MarkPlaced(ac, true); public static void MarkPlaced(IAtomContainer ac, bool isPlaced) { for (int f = 0; f < ac.Atoms.Count; f++) { ac.Atoms[f].IsPlaced = isPlaced; } } /// <summary> /// Get all the placed atoms in an <see cref="IAtomContainer"/> /// </summary> /// <param name="ac">The <see cref="IAtomContainer"/> to be searched for placed atoms</param> /// <returns>An AtomContainer containing all the placed atoms</returns> public static IAtomContainer GetPlacedAtoms(IAtomContainer ac) { var ret = ac.Builder.NewAtomContainer(); for (int f = 0; f < ac.Atoms.Count; f++) { if (ac.Atoms[f].IsPlaced) { ret.Atoms.Add(ac.Atoms[f]); } } return ret; } /// <summary> /// Copy placed atoms/bonds from one container to another. /// </summary> /// <param name="dest">destination container</param> /// <param name="src">source container</param> internal static void CopyPlaced(IRing dest, IAtomContainer src) { foreach (IBond bond in src.Bonds) { var beg = bond.Begin; var end = bond.End; if (beg.IsPlaced) { dest.Atoms.Add(beg); if (end.IsPlaced) { dest.Atoms.Add(end); dest.Bonds.Add(bond); } } else if (end.IsPlaced) { dest.Atoms.Add(end); } } } /// <summary> /// Sums up the degrees of atoms in an atomcontainer /// </summary> /// <param name="ac">The atomcontainer to be processed</param> /// <param name="superAC">The superAtomContainer from which the former has been derived</param> /// <returns>sum of degrees</returns> static int GetDegreeSum(IAtomContainer ac, IAtomContainer superAC) { int degreeSum = 0; for (int f = 0; f < ac.Atoms.Count; f++) { degreeSum += superAC.GetConnectedBonds(ac.Atoms[f]).Count(); degreeSum += ac.Atoms[f].ImplicitHydrogenCount ?? 0; } return degreeSum; } /// <summary> /// Calculates priority for atoms in a Molecule. /// </summary> /// <param name="mol">connected molecule</param> /// <seealso cref="Priority"/> internal static void Prioritise(IAtomContainer mol) { Prioritise(mol, GraphUtil.ToAdjList(mol)); } /// <summary> /// Calculates priority for atoms in a Molecule. /// </summary> /// <param name="mol">connected molecule</param> /// <param name="adjList">fast adjacency lookup</param> /// <seealso cref="Priority"/> static void Prioritise(IAtomContainer mol, int[][] adjList) { var weights = GetPriority(mol, adjList); for (int i = 0; i < mol.Atoms.Count; i++) { mol.Atoms[i].SetProperty(Priority, weights[i]); } } /// <summary> /// Prioritise atoms of a molecule base on how 'buried' they are. The priority /// is cacheted with a morgan-like relaxation O(n^2 lg n). Priorities are assign /// from 1..|V| (usually less than |V| due to symmetry) where the lowest numbers /// have priority. /// </summary> /// <param name="mol">molecule</param> /// <param name="adjList">fast adjacency lookup</param> /// <returns>the priority</returns> static int[] GetPriority(IAtomContainer mol, int[][] adjList) { var n = mol.Atoms.Count; var order = new int[n]; var rank = new int[n]; var prev = new int[n]; // init priorities, Helson 99 favours cyclic (init=2) for (int f = 0; f < n; f++) { rank[f] = 1; prev[f] = 1; order[f] = f; } int nDistinct = 1; for (int rep = 0; rep < n; rep++) { for (int i = 0; i < n; i++) { rank[i] = 3 * prev[i]; foreach (var w in adjList[i]) rank[i] += prev[w]; } // assign new ranks Array.Sort(order, (a, b) => rank[a].CompareTo(rank[b])); int clsNum = 1; prev[order[0]] = clsNum; for (int i = 1; i < n; i++) { if (rank[order[i]] != rank[order[i - 1]]) clsNum++; prev[order[i]] = clsNum; } // no refinement over previous if (clsNum == nDistinct) break; nDistinct = clsNum; } // we want values 1 ≤ x < |V| for (int i = 0; i < n; i++) prev[i] = 1 + nDistinct - prev[i]; return prev; } /// <summary> /// <pre> /// -C#N /// -[N+]#[C-] /// -C=[N+]=N /// -N=[N+]=N /// </pre> /// </summary> internal static bool IsColinear(IAtom atom, IEnumerable<IBond> bonds) { if (PeriodicTable.IsMetal(atom.AtomicNumber)) return bonds.Count() == 2; int numSgl = atom.ImplicitHydrogenCount ?? 0; int numDbl = 0; int numTpl = 0; int count = 0; foreach (var bond in bonds) { ++count; switch (bond.Order.Numeric()) { case 1: numSgl++; break; case 2: numDbl++; break; case 3: numTpl++; break; case 4: return true; default: return false; } } if (count != 2) return false; switch (atom.AtomicNumber) { case 6: case 7: case 14: case 32: if (numTpl == 1 && numSgl == 1) return true; if (numDbl == 2 && numSgl == 0) return true; break; } return false; } [Obsolete] public static bool ShouldBeLinear(IAtom atom, IAtomContainer molecule) { int sum = 0; var bonds = molecule.GetConnectedBonds(atom); foreach (var bond in bonds) { if (bond.Order == BondOrder.Triple) sum += 10; else if (bond.Order == BondOrder.Single) sum += 1; // else if (bond.Order == BondOrder.Double) sum += 5; } if (sum >= 10) return true; return false; } static Vector2 NewVector(Vector2 to, Vector2 from) { return new Vector2(to.X - from.X, to.Y - from.Y); } } }
lgpl-2.1
societo/societo
web/doctor.php
287
<?php /** * Societo - Provides social site platform * Copyright (C) 2011 Kousuke Ebihara * * This program is licensed under the EPL/GPL/LGPL triple license. * Please see the LICENSE file that was distributed with this file. */ $doctor = true; require_once __DIR__.'/index.php';
lgpl-2.1