code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
BlueImp File Upload Widget for Yii2 ActiveRecord attributes =========================================================== Widget to render the jQuery File Upload UI plugin similar to [its demo](http://blueimp.github.io/jQuery-File-Upload/index.html) for ActiveRecord attributes. Allows multiple widgets for one ActiveRecord and allows multiple files per attribute. Relies on custom controller actions to generate the expected responses, and some custom file validation. The files paths are not stored in the database but derived based on model name and primary key. Validation can force there to be 1 file, 0 files, or 1+ files per attribute, and maintains this thru model updates. Files can be private or public on s3 via requesting an expiring (signed) url, hence safe for sensitive information. The POST request generated when sending files, sends all files in a single request along with other form data, allowing for files to act the same as any other input in the form i.e. the files shouldn't be saved until all inputs are validated, and the database has been successfully updated. Supports validation across all files for an attribute e.g. maxFiles, and also supports per file validation e.g. matching mime types etc. This is currently untested in applications other than the one I am currently working on. In this project the files are arranged hierachically as per navigation within the system i.e. Client > 1 > Project > 3 > Task > 5 forms the directory path (actually a key in Amazon s3) Client/1/Project/3/Task/5 and attributes are added where necassary e.g. Client/1/logo-image/logoimage1.jpg. This allows for simple cleanup of obsolete files when a model is deleted i.e. in a unix file system rm -rf Client/1 when ClientActiveRecord::findOne(1)->delete() or on s3 remove all objects fromt the bucket where prefix is Client/1/ and then remove Client/1 (don't want to remove Client/10 etc) Usage ----- Attach the controller trait to your controller, and the ActiveRecordTrait to your ActiveRecord and alter as necassary. ``` class AccountController extends \backend\components\Controller { use \common\components\FileControllerTrait; ... ``` Within your form set ``` enctype='multipart/form-data' ``` Set the submit button as follows (an ordinary submit button in the form will not work) ``` <?= $this->context->renderPartial('@vendor/2amigos/yii2-file-upload-widget/views/saveButtonBar.php'); ?> ``` Add the widget for each attribute file attribute ``` <?= dosamigos\fileupload\FileUploadUIAR::widget([ 'model' => $model, 'attribute' => 'image', 'options' => ['accept' => 'image/*'], 'clientOptions' => [ 'maxFileSize' => 2000000 ] ]);?> Copy, alter and use as needed the example traits for active record and controller. These won't work out of the box in a new project but are noted in comments where they will likely need changing, mainly todo with the hierachical navigation within the application this currently written for. Add 'getexistingfiles' to the allowed actions within your controllers rules In your ActiveRecord, add file properties, getFileAttributes() method and add rules that apply to the attribute as a whole (per file validation is explained below) ``` class Account extends \common\components\ActiveRecord { use \common\components\FileActiveRecordTrait; /** * @var string $logo_image is a file attribute */ public $logo_image; /** * Get the attribute names for files * * @return array or strings - file attribute names */ public function getFileAttributes() { return [ 'logo_image', ]; } /** * @inheritdoc */ public function rules() { return [ [['logo_image'], '\dosamigos\fileupload\FileValidator', 'skipOnEmpty' => false, 'maxFiles' => 2], .... ]; } ... ``` Copy and alter for each file attribute example file dosamigos\fileupload\AccountLogoImageFile.php which contains the validation rule applicable per file This widget is configured to use dosamigos resource mananger - currently configured for amazon s3 hence alter your local config similarly to ``` 'components' => [ 'resourceManager' => [ 'class' => 'dosamigos\resourcemanager\AmazonS3ResourceManager', 'key' => 'your key', 'secret' => 'your secret', 'bucket' => 'your bucket' ], ... ``` Further Information ------------------- Please, check the [jQuery File Upload documentation](https://github.com/blueimp/jQuery-File-Upload/wiki) for further information about its configuration options.
andrewblake1/yii2-file-upload-widget
README.md
Markdown
bsd-3-clause
4,693
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\Family */ $this->title = 'Crear Familia'; $this->params['breadcrumbs'][] = ['label' => 'Families', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="family-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
frankpaul142/conti-sercop
views/family/create.php
PHP
bsd-3-clause
413
/** * @file DebyeHuckel.h * Headers for the DebyeHuckel ThermoPhase object, which models dilute * electrolyte solutions * (see \ref thermoprops and \link Cantera::DebyeHuckel DebyeHuckel \endlink) . * * Class DebyeHuckel represents a dilute liquid electrolyte phase which * obeys the Debye Huckel formulation for nonideality. */ /* * Copyright (2006) Sandia Corporation. Under the terms of * Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. */ #ifndef CT_DEBYEHUCKEL_H #define CT_DEBYEHUCKEL_H #include "MolalityVPSSTP.h" #include "cantera/base/Array.h" namespace Cantera { /*! * @name Formats for the Activity Coefficients * * These are possible formats for the molality-based activity coefficients. */ //@{ #define DHFORM_DILUTE_LIMIT 0 #define DHFORM_BDOT_AK 1 #define DHFORM_BDOT_ACOMMON 2 #define DHFORM_BETAIJ 3 #define DHFORM_PITZER_BETAIJ 4 //@} /* * @name Acceptable ways to calculate the value of A_Debye */ //@{ #define A_DEBYE_CONST 0 #define A_DEBYE_WATER 1 //@} class WaterProps; class PDSS_Water; /** * @ingroup thermoprops * * Class DebyeHuckel represents a dilute liquid electrolyte phase which * obeys the Debye Huckel formulation for nonideality. * * The concentrations of the ionic species are assumed to obey the electroneutrality * condition. * * <HR> * <H2> Specification of Species Standard State Properties </H2> * <HR> * * The standard states are on the unit molality basis. Therefore, in the * documentation below, the normal \f$ o \f$ superscript is replaced with * the \f$ \triangle \f$ symbol. The reference state symbol is now * \f$ \triangle, ref \f$. * * * It is assumed that the reference state thermodynamics may be * obtained by a pointer to a populated species thermodynamic property * manager class (see ThermoPhase::m_spthermo). How to relate pressure * changes to the reference state thermodynamics is resolved at this level. * * For an incompressible, * stoichiometric substance, the molar internal energy is * independent of pressure. Since the thermodynamic properties * are specified by giving the standard-state enthalpy, the * term \f$ P_0 \hat v\f$ is subtracted from the specified molar * enthalpy to compute the molar internal energy. The entropy is * assumed to be independent of the pressure. * * The enthalpy function is given by the following relation. * * \f[ * h^\triangle_k(T,P) = h^{\triangle,ref}_k(T) * + \tilde v \left( P - P_{ref} \right) * \f] * * For an incompressible, * stoichiometric substance, the molar internal energy is * independent of pressure. Since the thermodynamic properties * are specified by giving the standard-state enthalpy, the * term \f$ P_{ref} \tilde v\f$ is subtracted from the specified reference molar * enthalpy to compute the molar internal energy. * * \f[ * u^\triangle_k(T,P) = h^{\triangle,ref}_k(T) - P_{ref} \tilde v * \f] * * The standard state heat capacity and entropy are independent * of pressure. The standard state gibbs free energy is obtained * from the enthalpy and entropy functions. * * The vector Phase::m_speciesSize[] is used to hold the * base values of species sizes. These are defined as the * molar volumes of species at infinite dilution at 300 K and 1 atm * of water. m_speciesSize are calculated during the initialization of the * DebyeHuckel object and are then not touched. * * The current model assumes that an incompressible molar volume for * all solutes. The molar volume for the water solvent, however, * is obtained from a pure water equation of state, waterSS. * Therefore, the water standard state varies with both T and P. * It is an error to request standard state water properties at a T and P * where the water phase is not a stable phase, i.e., beyond its * spinodal curve. * * <HR> * <H2> Specification of Solution Thermodynamic Properties </H2> * <HR> * * Chemical potentials * of the solutes, \f$ \mu_k \f$, and the solvent, \f$ \mu_o \f$, which are based * on the molality form, have the following general format: * * \f[ * \mu_k = \mu^{\triangle}_k(T,P) + R T ln(\gamma_k^{\triangle} \frac{m_k}{m^\triangle}) * \f] * \f[ * \mu_o = \mu^o_o(T,P) + RT ln(a_o) * \f] * * where \f$ \gamma_k^{\triangle} \f$ is the molality based activity coefficient for species * \f$k\f$. * * Individual activity coefficients of ions can not be independently measured. Instead, * only binary pairs forming electroneutral solutions can be measured. * * <H3> Ionic Strength </H3> * * Most of the parameterizations within the model use the ionic strength * as a key variable. The ionic strength, \f$ I\f$ is defined as follows * * \f[ * I = \frac{1}{2} \sum_k{m_k z_k^2} * \f] * * \f$ m_k \f$ is the molality of the kth species. \f$ z_k \f$ is the charge * of the kth species. Note, the ionic strength is a defined units quantity. * The molality has defined units of gmol kg-1, and therefore the ionic * strength has units of sqrt( gmol kg-1). * * In some instances, from some authors, a different * formulation is used for the ionic strength in the equations below. The different * formulation is due to the possibility of the existence of weak acids and how * association wrt to the weak acid equilibrium relation affects the calculation * of the activity coefficients via the assumed value of the ionic strength. * * If we are to assume that the association reaction doesn't have an effect * on the ionic strength, then we will want to consider the associated weak * acid as in effect being fully dissociated, when we calculate an effective * value for the ionic strength. We will call this calculated value, the * stoichiometric ionic strength, \f$ I_s \f$, putting a subscript s to denote * it from the more straightforward calculation of \f$ I \f$. * * \f[ * I_s = \frac{1}{2} \sum_k{m_k^s z_k^2} * \f] * * Here, \f$ m_k^s \f$ is the value of the molalities calculated assuming that * all weak acid-base pairs are in their fully dissociated states. This calculation may * be simplified by considering that the weakly associated acid may be made up of two * charged species, k1 and k2, each with their own charges, obeying the following relationship: * * \f[ * z_k = z_{k1} + z_{k2} * \f] * Then, we may only need to specify one charge value, say, \f$ z_{k1}\f$, * the cation charge number, * in order to get both numbers, since we have already specified \f$ z_k \f$ * in the definition of original species. * Then, the stoichiometric ionic strength may be calculated via the following formula. * * \f[ * I_s = \frac{1}{2} \left(\sum_{k,ions}{m_k z_k^2}+ * \sum_{k,weak_assoc}(m_k z_{k1}^2 + m_k z_{k2}^2) \right) * \f] * * The specification of which species are weakly associated acids is made in the input * file via the * <TT> stoichIsMods </TT> XML block, where the charge for k1 is also specified. * An example is given below: * * @code * <stoichIsMods> * NaCl(aq):-1.0 * </stoichIsMods> * @endcode * * Because we need the concept of a weakly associated acid in order to calculated * \f$ I_s \f$ we need to * catalog all species in the phase. This is done using the following categories: * * - <B>cEST_solvent</B> Solvent species (neutral) * - <B>cEST_chargedSpecies</B> Charged species (charged) * - <B>cEST_weakAcidAssociated</B> Species which can break apart into charged species. * It may or may not be charged. These may or * may not be be included in the * species solution vector. * - <B>cEST_strongAcidAssociated</B> Species which always breaks apart into charged species. * It may or may not be charged. Normally, these aren't included * in the speciation vector. * - <B>cEST_polarNeutral </B> Polar neutral species * - <B>cEST_nonpolarNeutral</B> Non polar neutral species * * Polar and non-polar neutral species are differentiated, because some additions * to the activity * coefficient expressions distinguish between these two types of solutes. This is the so-called * salt-out effect. * * The type of species is specified in the <TT>electrolyteSpeciesType</TT> XML block. * Note, this is not * considered a part of the specification of the standard state for the species, * at this time. Therefore, * this information is put under the <TT>activityCoefficient</TT> XML block. An example * is given below * * @code * <electrolyteSpeciesType> * H2L(L):solvent * H+:chargedSpecies * NaOH(aq):weakAcidAssociated * NaCl(aq):strongAcidAssociated * NH3(aq):polarNeutral * O2(aq):nonpolarNeutral * </electrolyteSpeciesType> * @endcode * * Much of the species electrolyte type information is inferred from other information in the * input file. For example, as species which is charged is given the "chargedSpecies" default * category. A neutral solute species is put into the "nonpolarNeutral" category by default. * * The specification of solute activity coefficients depends on the model * assumed for the Debye-Huckel term. The model is set by the * internal parameter #m_formDH. We will now describe each category in its own section. * * * <H3> Debye-Huckel Dilute Limit </H3> * * DHFORM_DILUTE_LIMIT = 0 * * This form assumes a dilute limit to DH, and is mainly for informational purposes: * \f[ * \ln(\gamma_k^\triangle) = - z_k^2 A_{Debye} \sqrt{I} * \f] * where \f$ I\f$ is the ionic strength * \f[ * I = \frac{1}{2} \sum_k{m_k z_k^2} * \f] * * The activity for the solvent water,\f$ a_o \f$, is not independent and must be * determined from the Gibbs-Duhem relation. * * \f[ * \ln(a_o) = \frac{X_o - 1.0}{X_o} + \frac{ 2 A_{Debye} \tilde{M}_o}{3} (I)^{3/2} * \f] * * * <H3> Bdot Formulation </H3> * * DHFORM_BDOT_AK = 1 * * This form assumes Bethke's format for the Debye Huckel activity coefficient: * * \f[ * \ln(\gamma_k^\triangle) = -z_k^2 \frac{A_{Debye} \sqrt{I}}{ 1 + B_{Debye} a_k \sqrt{I}} * + \log(10) B^{dot}_k I * \f] * * Note, this particular form where \f$ a_k \f$ can differ in multielectrolyte * solutions has problems with respect to a Gibbs-Duhem analysis. However, * we include it here because there is a lot of data fit to it. * * The activity for the solvent water,\f$ a_o \f$, is not independent and must be * determined from the Gibbs-Duhem relation. Here, we use: * * \f[ * \ln(a_o) = \frac{X_o - 1.0}{X_o} * + \frac{ 2 A_{Debye} \tilde{M}_o}{3} (I)^{1/2} * \left[ \sum_k{\frac{1}{2} m_k z_k^2 \sigma( B_{Debye} a_k \sqrt{I} ) } \right] * - \frac{\log(10)}{2} \tilde{M}_o I \sum_k{ B^{dot}_k m_k} * \f] * where * \f[ * \sigma (y) = \frac{3}{y^3} \left[ (1+y) - 2 \ln(1 + y) - \frac{1}{1+y} \right] * \f] * * Additionally, Helgeson's formulation for the water activity is offered as an * alternative. * * * <H3> Bdot Formulation with Uniform Size Parameter in the Denominator </H3> * * DHFORM_BDOT_AUNIFORM = 2 * * This form assumes Bethke's format for the Debye-Huckel activity coefficient * * \f[ * \ln(\gamma_k^\triangle) = -z_k^2 \frac{A_{Debye} \sqrt{I}}{ 1 + B_{Debye} a \sqrt{I}} * + \log(10) B^{dot}_k I * \f] * * The value of a is determined at the beginning of the calculation, and not changed. * * \f[ * \ln(a_o) = \frac{X_o - 1.0}{X_o} * + \frac{ 2 A_{Debye} \tilde{M}_o}{3} (I)^{3/2} \sigma( B_{Debye} a \sqrt{I} ) * - \frac{\log(10)}{2} \tilde{M}_o I \sum_k{ B^{dot}_k m_k} * \f] * * * <H3> Beta_IJ formulation </H3> * * DHFORM_BETAIJ = 3 * * This form assumes a linear expansion in a virial coefficient form. * It is used extensively in the book by Newmann, "Electrochemistry Systems", * and is the beginning of more complex treatments for stronger electrolytes, * fom Pitzer and from Harvey, Moller, and Weire. * * \f[ * \ln(\gamma_k^\triangle) = -z_k^2 \frac{A_{Debye} \sqrt{I}}{ 1 + B_{Debye} a \sqrt{I}} * + 2 \sum_j \beta_{j,k} m_j * \f] * * In the current treatment the binary interaction coefficients, \f$ \beta_{j,k}\f$, are * independent of temperature and pressure. * * \f[ * \ln(a_o) = \frac{X_o - 1.0}{X_o} * + \frac{ 2 A_{Debye} \tilde{M}_o}{3} (I)^{3/2} \sigma( B_{Debye} a \sqrt{I} ) * - \tilde{M}_o \sum_j \sum_k \beta_{j,k} m_j m_k * \f] * * In this formulation the ionic radius, \f$ a \f$, is a constant. This must be supplied to the * model, in an <DFN> ionicRadius </DFN> XML block. * * The \f$ \beta_{j,k} \f$ parameters are binary interaction parameters. They are supplied to * the object in an <TT> DHBetaMatrix </TT> XML block. There are in principle \f$ N (N-1) /2 \f$ * different, symmetric interaction parameters, where \f$ N \f$ are the number of solute species in the * mechanism. * An example is given below. * * An example <TT> activityCoefficients </TT> XML block for this formulation is supplied below * * @code * <activityCoefficients model="Beta_ij"> * <!-- A_Debye units = sqrt(kg/gmol) --> * <A_Debye> 1.172576 </A_Debye> * <!-- B_Debye units = sqrt(kg/gmol)/m --> * <B_Debye> 3.28640E9 </B_Debye> * <ionicRadius default="3.042843" units="Angstroms"> * </ionicRadius> * <DHBetaMatrix> * H+:Cl-:0.27 * Na+:Cl-:0.15 * Na+:OH-:0.06 * </DHBetaMatrix> * <stoichIsMods> * NaCl(aq):-1.0 * </stoichIsMods> * <electrolyteSpeciesType> * H+:chargedSpecies * NaCl(aq):weakAcidAssociated * </electrolyteSpeciesType> * </activityCoefficients> * @endcode * * <H3> Pitzer Beta_IJ formulation </H3> * * DHFORM_PITZER_BETAIJ = 4 * * This form assumes an activity coefficient formulation consistent * with a truncated form of Pitzer's formulation. Pitzer's formulation is equivalent * to the formulations above in the dilute limit, where rigorous theory may be applied. * * \f[ * \ln(\gamma_k^\triangle) = -z_k^2 \frac{A_{Debye}}{3} \frac{\sqrt{I}}{ 1 + B_{Debye} a \sqrt{I}} * -2 z_k^2 \frac{A_{Debye}}{3} \frac{\ln(1 + B_{Debye} a \sqrt{I})}{ B_{Debye} a} * + 2 \sum_j \beta_{j,k} m_j * \f] * * * \f[ * \ln(a_o) = \frac{X_o - 1.0}{X_o} * + \frac{ 2 A_{Debye} \tilde{M}_o}{3} \frac{(I)^{3/2} }{1 + B_{Debye} a \sqrt{I} } * - \tilde{M}_o \sum_j \sum_k \beta_{j,k} m_j m_k * \f] * * <H3> Specification of the Debye Huckel Constants </H3> * * In the equations above, the formulas for \f$ A_{Debye} \f$ and \f$ B_{Debye} \f$ * are needed. The DebyeHuckel object uses two methods for specifying these quantities. * The default method is to assume that \f$ A_{Debye} \f$ is a constant, given * in the initialization process, and stored in the * member double, m_A_Debye. Optionally, a full water treatment may be employed that makes * \f$ A_{Debye} \f$ a full function of <I>T</I> and <I>P</I>. * * \f[ * A_{Debye} = \frac{F e B_{Debye}}{8 \pi \epsilon R T} {\left( C_o \tilde{M}_o \right)}^{1/2} * \f] * where * * \f[ * B_{Debye} = \frac{F} {{(\frac{\epsilon R T}{2})}^{1/2}} * \f] * Therefore: * \f[ * A_{Debye} = \frac{1}{8 \pi} * {\left(\frac{2 N_a \rho_o}{1000}\right)}^{1/2} * {\left(\frac{N_a e^2}{\epsilon R T }\right)}^{3/2} * \f] * * where * - \f$ N_a \f$ is Avogadro's number * - \f$ \rho_w \f$ is the density of water * - \f$ e \f$ is the electronic charge * - \f$ \epsilon = K \epsilon_o \f$ is the permittivity of water * - \f$ K \f$ is the dielectric constant of water * - \f$ \epsilon_o \f$ is the permittivity of free space * - \f$ \rho_o \f$ is the density of the solvent in its standard state. * * Nominal value at 298 K and 1 atm = 1.172576 (kg/gmol)<SUP>1/2</SUP> based on: * - \f$ \epsilon / \epsilon_0 \f$ = 78.54 (water at 25C) * - T = 298.15 K * - B_Debye = 3.28640E9 (kg/gmol)<SUP>1/2</SUP> m<SUP>-1</SUP> * * An example of a fixed value implementation is given below. * @code * <activityCoefficients model="Beta_ij"> * <!-- A_Debye units = sqrt(kg/gmol) --> * <A_Debye> 1.172576 </A_Debye> * <!-- B_Debye units = sqrt(kg/gmol)/m --> * <B_Debye> 3.28640E9 </B_Debye> * </activityCoefficients> * @endcode * * An example of a variable value implementation is given below. * * @code * <activityCoefficients model="Beta_ij"> * <A_Debye model="water" /> * <!-- B_Debye units = sqrt(kg/gmol)/m --> * <B_Debye> 3.28640E9 </B_Debye> * </activityCoefficients> * @endcode * * Currently, \f$ B_{Debye} \f$ is a constant in the model, specified either by a default * water value, or through the input file. This may have to be looked at, in the future. * * <HR> * <H2> %Application within Kinetics Managers </H2> * <HR> * * For the time being, we have set the standard concentration for all species in * this phase equal to the default concentration of the solvent at 298 K and 1 atm. * This means that the * kinetics operator essentially works on an activities basis, with units specified * as if it were on a concentration basis. * * For example, a bulk-phase binary reaction between liquid species j and k, producing * a new liquid species l would have the * following equation for its rate of progress variable, \f$ R^1 \f$, which has * units of kmol m-3 s-1. * * \f[ * R^1 = k^1 C_j^a C_k^a = k^1 (C_o a_j) (C_o a_k) * \f] * where * \f[ * C_j^a = C_o a_j \quad and \quad C_k^a = C_o a_k * \f] * * \f$ C_j^a \f$ is the activity concentration of species j, and * \f$ C_k^a \f$ is the activity concentration of species k. \f$ C_o \f$ * is the concentration of water at 298 K and 1 atm. \f$ a_j \f$ is * the activity of species j at the current temperature and pressure * and concentration of the liquid phase. \f$k^1 \f$ has units of m3 kmol-1 s-1. * * The reverse rate constant can then be obtained from the law of microscopic reversibility * and the equilibrium expression for the system. * * \f[ * \frac{a_j a_k}{ a_l} = K^{o,1} = \exp(\frac{\mu^o_l - \mu^o_j - \mu^o_k}{R T} ) * \f] * * \f$ K^{o,1} \f$ is the dimensionless form of the equilibrium constant. * * \f[ * R^{-1} = k^{-1} C_l^a = k^{-1} (C_o a_l) * \f] * * where * * \f[ * k^{-1} = k^1 K^{o,1} C_o * \f] * * \f$k^{-1} \f$ has units of s-1. * * Note, this treatment may be modified in the future, as events dictate. * * <HR> * <H2> Instantiation of the Class </H2> * <HR> * * The constructor for this phase is NOT located in the default ThermoFactory * for %Cantera. However, a new DebyeHuckel object may be created by * the following code snippets: * * @code * DebyeHuckel *DH = new DebyeHuckel("DH_NaCl.xml", "NaCl_electrolyte"); * @endcode * * or * * @code * XML_Node *xm = get_XML_NameID("phase", "DH_NaCl.xml#NaCl_electrolyte", 0); * DebyeHuckel *dh = new DebyeHuckel(*xm); * @endcode * * or by the following call to importPhase(): * * @code * XML_Node *xm = get_XML_NameID("phase", "DH_NaCl.xml#NaCl_electrolyte", 0); * DebyeHuckel dhphase; * importPhase(*xm, &dhphase); * @endcode * * <HR> * <H2> XML Example </H2> * <HR> * * The phase model name for this is called StoichSubstance. It must be supplied * as the model attribute of the thermo XML element entry. * Within the phase XML block, * the density of the phase must be specified. An example of an XML file * this phase is given below. * * @verbatim <phase id="NaCl_electrolyte" dim="3"> <speciesArray datasrc="#species_waterSolution"> H2O(L) Na+ Cl- H+ OH- NaCl(aq) NaOH(aq) </speciesArray> <state> <temperature units="K"> 300 </temperature> <pressure units="Pa">101325.0</pressure> <soluteMolalities> Na+:3.0 Cl-:3.0 H+:1.0499E-8 OH-:1.3765E-6 NaCl(aq):0.98492 NaOH(aq):3.8836E-6 </soluteMolalities> </state> <!-- thermo model identifies the inherited class from ThermoPhase that will handle the thermodynamics. --> <thermo model="DebyeHuckel"> <standardConc model="solvent_volume" /> <activityCoefficients model="Beta_ij"> <!-- A_Debye units = sqrt(kg/gmol) --> <A_Debye> 1.172576 </A_Debye> <!-- B_Debye units = sqrt(kg/gmol)/m --> <B_Debye> 3.28640E9 </B_Debye> <ionicRadius default="3.042843" units="Angstroms"> </ionicRadius> <DHBetaMatrix> H+:Cl-:0.27 Na+:Cl-:0.15 Na+:OH-:0.06 </DHBetaMatrix> <stoichIsMods> NaCl(aq):-1.0 </stoichIsMods> <electrolyteSpeciesType> H+:chargedSpecies NaCl(aq):weakAcidAssociated </electrolyteSpeciesType> </activityCoefficients> <solvent> H2O(L) </solvent> </thermo> <elementArray datasrc="elements.xml"> O H Na Cl </elementArray> </phase> @endverbatim * * */ class DebyeHuckel : public MolalityVPSSTP { public: //! Default Constructor DebyeHuckel(); //! Copy constructor DebyeHuckel(const DebyeHuckel&); //! Assignment operator DebyeHuckel& operator=(const DebyeHuckel&); //! Full constructor for creating the phase. /*! * @param inputFile File name containing the XML description of the phase * @param id id attribute containing the name of the phase. */ DebyeHuckel(const std::string& inputFile, const std::string& id = ""); //! Full constructor for creating the phase. /*! * @param phaseRef XML phase node containing the description of the phase * @param id id attribute containing the name of the phase. */ DebyeHuckel(XML_Node& phaseRef, const std::string& id = ""); /// Destructor. virtual ~DebyeHuckel(); //! Duplicator from the ThermoPhase parent class /*! * Given a pointer to a ThermoPhase object, this function will * duplicate the ThermoPhase object and all underlying structures. * This is basically a wrapper around the copy constructor. * * @return returns a pointer to a ThermoPhase */ ThermoPhase* duplMyselfAsThermoPhase() const; //! @name Utilities //! @{ /** * Equation of state type flag. The base class returns * zero. Subclasses should define this to return a unique * non-zero value. Constants defined for this purpose are * listed in mix_defs.h. */ virtual int eosType() const; //! @} //! @name Molar Thermodynamic Properties of the Solution //! @{ /// Molar enthalpy of the solution. Units: J/kmol. virtual doublereal enthalpy_mole() const; /// Molar entropy. Units: J/kmol/K. /** * For an ideal, constant partial molar volume solution mixture with * pure species phases which exhibit zero volume expansivity: * \f[ * \hat s(T, P, X_k) = \sum_k X_k \hat s^0_k(T) * - \hat R \sum_k X_k log(X_k) * \f] * The reference-state pure-species entropies * \f$ \hat s^0_k(T,p_{ref}) \f$ are computed by the * species thermodynamic * property manager. The pure species entropies are independent of * temperature since the volume expansivities are equal to zero. * @see SpeciesThermo */ virtual doublereal entropy_mole() const; /// Molar Gibbs function. Units: J/kmol. virtual doublereal gibbs_mole() const; /// Molar heat capacity at constant pressure. Units: J/kmol/K. virtual doublereal cp_mole() const; //! Molar heat capacity at constant volume. Units: J/kmol/K. /* * (HKM -> Bump up to Parent object) */ virtual doublereal cv_mole() const; //@} /** @name Mechanical Equation of State Properties //@{ * * In this equation of state implementation, the density is a * function only of the mole fractions. Therefore, it can't be * an independent variable. Instead, the pressure is used as the * independent variable. Functions which try to set the thermodynamic * state by calling setDensity() may cause an exception to be * thrown. */ //! Return the thermodynamic pressure (Pa). /*! * For this incompressible system, we return the internally stored * independent value of the pressure. */ virtual doublereal pressure() const; //! Set the internally stored pressure (Pa) at constant //! temperature and composition /*! * This method sets the pressure within the object. * The water model is a completely compressible model. * Also, the dielectric constant is pressure dependent. * * @param p input Pressure (Pa) * * @todo Implement a variable pressure capability */ virtual void setPressure(doublereal p); protected: //! Calculate the density of the mixture using the partial //! molar volumes and mole fractions as input /*! * The formula for this is * * \f[ * \rho = \frac{\sum_k{X_k W_k}}{\sum_k{X_k V_k}} * \f] * * where \f$X_k\f$ are the mole fractions, \f$W_k\f$ are * the molecular weights, and \f$V_k\f$ are the pure species * molar volumes. * * Note, the basis behind this formula is that in an ideal * solution the partial molar volumes are equal to the pure * species molar volumes. We have additionally specified * in this class that the pure species molar volumes are * independent of temperature and pressure. */ virtual void calcDensity(); public: //! Set the internally stored density (gm/m^3) of the phase. /*! * Overwritten setDensity() function is necessary because the * density is not an independent variable. * * This function will now throw an error condition * * @internal May have to adjust the strategy here to make * the eos for these materials slightly compressible, in order * to create a condition where the density is a function of * the pressure. * * This function will now throw an error condition if the * input isn't exactly equal to the current density. * * @todo Now have a compressible ss equation for liquid water. * Therefore, this phase is compressible. May still * want to change the independent variable however. * * @param rho Input density (kg/m^3). */ void setDensity(const doublereal rho); //! Set the internally stored molar density (kmol/m^3) of the phase. /** * Overwritten setMolarDensity() function is necessary because the * density is not an independent variable. * * This function will now throw an error condition if the input * isn't exactly equal to the current molar density. * * @param conc Input molar density (kmol/m^3). */ virtual void setMolarDensity(const doublereal conc); //! Set the temperature (K) /*! * This function sets the temperature, and makes sure that * the value propagates to underlying objects, such as * the water standard state model. * * @param temp Temperature in kelvin */ virtual void setTemperature(const doublereal temp); //! Set the temperature (K) and pressure (Pa) /*! * Set the temperature and pressure. * * @param t Temperature (K) * @param p Pressure (Pa) */ virtual void setState_TP(doublereal t, doublereal p); /** * @} * @name Activities, Standard States, and Activity Concentrations * * The activity \f$a_k\f$ of a species in solution is * related to the chemical potential by \f[ \mu_k = \mu_k^0(T) * + \hat R T \log a_k. \f] The quantity \f$\mu_k^0(T,P)\f$ is * the chemical potential at unit activity, which depends only * on temperature and the pressure. * Activity is assumed to be molality-based here. * @{ */ //! This method returns an array of generalized concentrations /*! * \f$ C_k\f$ that are defined such that * \f$ a_k = C_k / C^0_k, \f$ where \f$ C^0_k \f$ * is a standard concentration * defined below. These generalized concentrations are used * by kinetics manager classes to compute the forward and * reverse rates of elementary reactions. * * @param c Array of generalized concentrations. The * units depend upon the implementation of the * reaction rate expressions within the phase. */ virtual void getActivityConcentrations(doublereal* c) const; //! Return the standard concentration for the kth species /*! * The standard concentration \f$ C^0_k \f$ used to normalize * the activity (i.e., generalized) concentration in * kinetics calculations. * * For the time being, we will use the concentration of pure * solvent for the the standard concentration of all species. * This has the effect of making reaction rates * based on the molality of species proportional to the * molality of the species. * * @param k Optional parameter indicating the species. The default * is to assume this refers to species 0. * @return * Returns the standard Concentration in units of * m<SUP>3</SUP> kmol<SUP>-1</SUP>. */ virtual doublereal standardConcentration(size_t k=0) const; //! Returns the units of the standard and generalized concentrations. /*! * Note they have the same units, as their * ratio is defined to be equal to the activity of the kth * species in the solution, which is unitless. * * This routine is used in print out applications where the * units are needed. Usually, MKS units are assumed throughout * the program and in the XML input files. * * The base ThermoPhase class assigns the default quantities * of (kmol/m3) for all species. * Inherited classes are responsible for overriding the default * values if necessary. * * On return uA contains the powers of the units (MKS assumed) * of the standard concentrations and generalized concentrations * for the kth species. * * @param uA Output vector containing the units * uA[0] = kmol units - default = 1 * uA[1] = m units - default = -nDim(), the number of spatial * dimensions in the Phase class. * uA[2] = kg units - default = 0; * uA[3] = Pa(pressure) units - default = 0; * uA[4] = Temperature units - default = 0; * uA[5] = time units - default = 0 * @param k species index. Defaults to 0. * @param sizeUA output int containing the size of the vector. * Currently, this is equal to 6. */ virtual void getUnitsStandardConc(double* uA, int k = 0, int sizeUA = 6) const; //! Get the array of non-dimensional activities at //! the current solution temperature, pressure, and solution concentration. /*! * * We resolve this function at this level by calling * on the activityConcentration function. However, * derived classes may want to override this default * implementation. * * (note solvent activity coefficient is on molar scale). * * @param ac Output vector of activities. Length: m_kk. */ virtual void getActivities(doublereal* ac) const; //! Get the array of non-dimensional molality-based //! activity coefficients at //! the current solution temperature, pressure, and solution concentration. /*! * note solvent is on molar scale. The solvent molar * based activity coefficient is returned. * * Note, most of the work is done in an internal private routine * * @param acMolality Vector of Molality-based activity coefficients * Length: m_kk */ virtual void getMolalityActivityCoefficients(doublereal* acMolality) const; //@} /// @name Partial Molar Properties of the Solution //@{ //! Get the species chemical potentials. Units: J/kmol. /*! * * This function returns a vector of chemical potentials of the * species in solution. * * \f[ * \mu_k = \mu^{\triangle}_k(T,P) + R T ln(\gamma_k^{\triangle} m_k) * \f] * * @param mu Output vector of species chemical * potentials. Length: m_kk. Units: J/kmol */ virtual void getChemPotentials(doublereal* mu) const; //! Returns an array of partial molar enthalpies for the species //! in the mixture. Units (J/kmol) /*! * For this phase, the partial molar enthalpies are equal to the * standard state enthalpies modified by the derivative of the * molality-based activity coefficient wrt temperature * * \f[ * \bar h_k(T,P) = h^{\triangle}_k(T,P) - R T^2 \frac{d \ln(\gamma_k^\triangle)}{dT} * \f] * The solvent partial molar enthalpy is equal to * \f[ * \bar h_o(T,P) = h^{o}_o(T,P) - R T^2 \frac{d \ln(a_o}{dT} * \f] * * The temperature dependence of the activity coefficients currently * only occurs through the temperature dependence of the Debye constant. * * @param hbar Output vector of species partial molar enthalpies. * Length: m_kk. units are J/kmol. */ virtual void getPartialMolarEnthalpies(doublereal* hbar) const; //! Returns an array of partial molar entropies of the species in the //! solution. Units: J/kmol/K. /** * Maxwell's equations provide an insight in how to calculate this * (p.215 Smith and Van Ness) * \f[ * \frac{d\mu_i}{dT} = -\bar{s}_i * \f] * * For this phase, the partial molar entropies are equal to the * SS species entropies plus the ideal solution contribution.following * contribution: * \f[ * \bar s_k(T,P) = \hat s^0_k(T) - R log(M0 * molality[k]) * \f] * \f[ * \bar s_{solvent}(T,P) = \hat s^0_{solvent}(T) * - R ((xmolSolvent - 1.0) / xmolSolvent) * \f] * * The reference-state pure-species entropies,\f$ \hat s^0_k(T) \f$, * at the reference pressure, \f$ P_{ref} \f$, are computed by the * species thermodynamic * property manager. They are polynomial functions of temperature. * @see SpeciesThermo * * @param sbar Output vector of species partial molar entropies. * Length = m_kk. units are J/kmol/K. */ virtual void getPartialMolarEntropies(doublereal* sbar) const; //! Return an array of partial molar heat capacities for the //! species in the mixture. Units: J/kmol/K /*! * @param cpbar Output vector of species partial molar heat * capacities at constant pressure. * Length = m_kk. units are J/kmol/K. */ virtual void getPartialMolarCp(doublereal* cpbar) const; //! Return an array of partial molar volumes for the //! species in the mixture. Units: m^3/kmol. /*! * For this solution, the partial molar volumes are normally * equal to theconstant species molar volumes, except * when the activity coefficients depend on pressure. * * The general relation is * * vbar_i = d(chemPot_i)/dP at const T, n * = V0_i + d(Gex)/dP)_T,M * = V0_i + RT d(lnActCoeffi)dP _T,M * * @param vbar Output vector of species partial molar volumes. * Length = m_kk. units are m^3/kmol. */ virtual void getPartialMolarVolumes(doublereal* vbar) const; //@} /** * @name Chemical Equilibrium * @{ */ //!This method is used by the ChemEquil equilibrium solver. /*! * It sets the state such that the chemical potentials satisfy * \f[ \frac{\mu_k}{\hat R T} = \sum_m A_{k,m} * \left(\frac{\lambda_m} {\hat R T}\right) \f] where * \f$ \lambda_m \f$ is the element potential of element m. The * temperature is unchanged. Any phase (ideal or not) that * implements this method can be equilibrated by ChemEquil. * * @param lambda_RT Input vector of dimensionless element potentials * The length is equal to nElements(). */ virtual void setToEquilState(const doublereal* lambda_RT) { throw NotImplementedError("DebyeHuckel::setToEquilState"); } //@} /* * -------------- Utilities ------------------------------- */ //! Initialize the object's internal lengths after species are set /** * @internal Initialize. This method is provided to allow * subclasses to perform any initialization required after all * species have been added. For example, it might be used to * resize internal work arrays that must have an entry for * each species. The base class implementation does nothing, * and subclasses that do not require initialization do not * need to overload this method. When importing a CTML phase * description, this method is called just prior to returning * from function importPhase(). * * Cascading call sequence downwards starting with Parent. * * @internal */ virtual void initThermo(); //! Process the XML file after species are set up. /*! * This gets called from importPhase(). It processes the XML file * after the species are set up. This is the main routine for * reading in activity coefficient parameters. * * @param phaseNode This object must be the phase node of a * complete XML tree * description of the phase, including all of the * species data. In other words while "phase" must * point to an XML phase object, it must have * sibling nodes "speciesData" that describe * the species in the phase. * @param id ID of the phase. If nonnull, a check is done * to see if phaseNode is pointing to the phase * with the correct id. */ virtual void initThermoXML(XML_Node& phaseNode, const std::string& id); //! Return the Debye Huckel constant as a function of temperature //! and pressure (Units = sqrt(kg/gmol)) /*! * The default is to assume that it is constant, given * in the initialization process, and stored in the * member double, m_A_Debye. Optionally, a full water treatment may be employed that makes * \f$ A_{Debye} \f$ a full function of T and P. * * \f[ * A_{Debye} = \frac{F e B_{Debye}}{8 \pi \epsilon R T} {\left( C_o \tilde{M}_o \right)}^{1/2} * \f] * where * \f[ * B_{Debye} = \frac{F} {{(\frac{\epsilon R T}{2})}^{1/2}} * \f] * Therefore: * \f[ * A_{Debye} = \frac{1}{8 \pi} * {\left(\frac{2 N_a \rho_o}{1000}\right)}^{1/2} * {\left(\frac{N_a e^2}{\epsilon R T }\right)}^{3/2} * \f] * * where * - Units = sqrt(kg/gmol) * - \f$ N_a \f$ is Avogadro's number * - \f$ \rho_w \f$ is the density of water * - \f$ e \f$ is the electronic charge * - \f$ \epsilon = K \epsilon_o \f$ is the permittivity of water * - \f$ K \f$ is the dielectric constant of water, * - \f$ \epsilon_o \f$ is the permittivity of free space. * - \f$ \rho_o \f$ is the density of the solvent in its standard state. * * Nominal value at 298 K and 1 atm = 1.172576 (kg/gmol)<SUP>1/2</SUP> * based on: * - \f$ \epsilon / \epsilon_0 \f$ = 78.54 (water at 25C) * - T = 298.15 K * - B_Debye = 3.28640E9 (kg/gmol)<SUP>1/2</SUP> m<SUP>-1</SUP> * * @param temperature Temperature in kelvin. Defaults to -1, in which * case the temperature of the phase is assumed. * * @param pressure Pressure (Pa). Defaults to -1, in which * case the pressure of the phase is assumed. */ virtual double A_Debye_TP(double temperature = -1.0, double pressure = -1.0) const; //! Value of the derivative of the Debye Huckel constant with //! respect to temperature. /*! * This is a function of temperature and pressure. See A_Debye_TP() for * a definition of \f$ A_{Debye} \f$. * * Units = sqrt(kg/gmol) K-1 * * @param temperature Temperature in kelvin. Defaults to -1, in which * case the temperature of the phase is assumed. * * @param pressure Pressure (Pa). Defaults to -1, in which * case the pressure of the phase is assumed. */ virtual double dA_DebyedT_TP(double temperature = -1.0, double pressure = -1.0) const; //! Value of the 2nd derivative of the Debye Huckel constant with //! respect to temperature as a function of temperature and pressure. /*! * This is a function of temperature and pressure. See A_Debye_TP() for * a definition of \f$ A_{Debye} \f$. * * Units = sqrt(kg/gmol) K-2 * * @param temperature Temperature in kelvin. Defaults to -1, in which * case the temperature of the phase is assumed. * * @param pressure Pressure (Pa). Defaults to -1, in which * case the pressure of the phase is assumed. */ virtual double d2A_DebyedT2_TP(double temperature = -1.0, double pressure = -1.0) const; //! Value of the derivative of the Debye Huckel constant with //! respect to pressure, as a function of temperature and pressure. /*! * This is a function of temperature and pressure. See A_Debye_TP() for * a definition of \f$ A_{Debye} \f$. * * Units = sqrt(kg/gmol) Pa-1 * * @param temperature Temperature in kelvin. Defaults to -1, in which * case the temperature of the phase is assumed. * * @param pressure Pressure (Pa). Defaults to -1, in which * case the pressure of the phase is assumed. */ virtual double dA_DebyedP_TP(double temperature = -1.0, double pressure = -1.0) const; //!Reports the ionic radius of the kth species /*! * @param k species index. */ double AionicRadius(int k = 0) const; //! Returns the form of the Debye-Huckel parameterization used int formDH() const { return m_formDH; } //! Returns a reference to M_Beta_ij Array2D& get_Beta_ij() { return m_Beta_ij; } private: //! Static function that implements the non-polar species //! salt-out modifications. /*! * Returns the calculated activity coefficients. * * @param IionicMolality Value of the ionic molality (sqrt(gmol/kg)) */ double _nonpolarActCoeff(double IionicMolality) const; //! Formula for the osmotic coefficient that occurs in the GWB. /*! * It is originally from Helgeson for a variable * NaCl brine. It's to be used with extreme caution. */ double _osmoticCoeffHelgesonFixedForm() const; //! Formula for the log of the water activity that occurs in the GWB. /*! * It is originally from Helgeson for a variable * NaCl brine. It's to be used with extreme caution. */ double _lnactivityWaterHelgesonFixedForm() const; //@} protected: //! form of the Debye-Huckel parameterization used in the model. /*! * The options are described at the top of this document, * and in the general documentation. * The list is repeated here: * * DHFORM_DILUTE_LIMIT = 0 (default) * DHFORM_BDOT_AK = 1 * DHFORM_BDOT_AUNIFORM = 2 * DHFORM_BETAIJ = 3 * DHFORM_PITZER_BETAIJ = 4 */ int m_formDH; /** * Format for the generalized concentration: * * 0 = unity * 1 = molar_volume * 2 = solvent_volume (default) * * The generalized concentrations can have three different forms * depending on the value of the member attribute m_formGC, which * is supplied in the constructor. * <TABLE> * <TR><TD> m_formGC </TD><TD> GeneralizedConc </TD><TD> StandardConc </TD></TR> * <TR><TD> 0 </TD><TD> X_k </TD><TD> 1.0 </TD></TR> * <TR><TD> 1 </TD><TD> X_k / V_k </TD><TD> 1.0 / V_k </TD></TR> * <TR><TD> 2 </TD><TD> X_k / V_N </TD><TD> 1.0 / V_N </TD></TR> * </TABLE> * * The value and form of the generalized concentration will affect * reaction rate constants involving species in this phase. * * (HKM Note: Using option #1 may lead to spurious results and * has been included only with warnings. The reason is that it * molar volumes of electrolytes may often be negative. The * molar volume of H+ is defined to be zero too. Either options * 0 or 2 are the appropriate choice. Option 0 leads to * bulk reaction rate constants which have units of s-1. * Option 2 leads to bulk reaction rate constants for * bimolecular rxns which have units of m-3 kmol-1 s-1.) */ int m_formGC; //! Vector containing the electrolyte species type /*! * The possible types are: * - solvent * - Charged Species * - weakAcidAssociated * - strongAcidAssociated * - polarNeutral * - nonpolarNeutral * . */ vector_int m_electrolyteSpeciesType; /** * a_k = Size of the ionic species in the DH formulation * units = meters */ vector_fp m_Aionic; //! Current value of the ionic strength on the molality scale mutable double m_IionicMolality; /** * Maximum value of the ionic strength allowed in the * calculation of the activity coefficients. */ double m_maxIionicStrength; public: /** * If true, then the fixed for of Helgeson's activity * for water is used instead of the rigorous form * obtained from Gibbs-Duhem relation. This should be * used with caution, and is really only included as a * validation exercise. */ bool m_useHelgesonFixedForm; protected: //! Stoichiometric ionic strength on the molality scale mutable double m_IionicMolalityStoich; public: /** * Form of the constant outside the Debye-Huckel term * called A. It's normally a function of temperature * and pressure. However, it can be set from the * input file in order to aid in numerical comparisons. * Acceptable forms: * * A_DEBYE_CONST 0 * A_DEBYE_WATER 1 * * The A_DEBYE_WATER form may be used for water solvents * with needs to cover varying temperatures and pressures. * Note, the dielectric constant of water is a relatively * strong function of T, and its variability must be * accounted for, */ int m_form_A_Debye; protected: //! Current value of the Debye Constant, A_Debye /** * A_Debye -> this expression appears on the top of the * ln actCoeff term in the general Debye-Huckel * expression * It depends on temperature and pressure. * * A_Debye = (F e B_Debye) / (8 Pi epsilon R T) * * Units = sqrt(kg/gmol) * * Nominal value(298K, atm) = 1.172576 sqrt(kg/gmol) * based on: * epsilon/epsilon_0 = 78.54 * (water at 25C) * T = 298.15 K * B_Debye = 3.28640E9 sqrt(kg/gmol)/m * * note in Pitzer's nomenclature, A_phi = A_Debye/3.0 */ mutable double m_A_Debye; //! Current value of the constant that appears in the denominator /** * B_Debye -> this expression appears on the bottom of the * ln actCoeff term in the general Debye-Huckel * expression * It depends on temperature * * B_Bebye = F / sqrt( epsilon R T / 2 ) * * Units = sqrt(kg/gmol) / m * * Nominal value = 3.28640E9 sqrt(kg/gmol) / m * based on: * epsilon/epsilon_0 = 78.54 * (water at 25C) * T = 298.15 K */ double m_B_Debye; //! Array of B_Dot values /** * This expression is an extension of the Debye-Huckel expression used * in some formulations to extend DH to higher molalities. B_dot is * specific to the major ionic pair. */ vector_fp m_B_Dot; /** * These are coefficients to describe the increase in activity coeff for * non-polar molecules due to the electrolyte becoming stronger (the * so-called salt-out effect) */ vector_fp m_npActCoeff; //! Pointer to the Water standard state object /*! * derived from the equation of state for water. */ PDSS_Water* m_waterSS; //! Storage for the density of water's standard state /*! * Density depends on temperature and pressure. */ double m_densWaterSS; //! Pointer to the water property calculator WaterProps* m_waterProps; //! Temporary array used in equilibrium calculations mutable vector_fp m_pp; //! vector of size m_kk, used as a temporary holding area. mutable vector_fp m_tmpV; /** * Stoichiometric species charge -> This is for calculations * of the ionic strength which ignore ion-ion pairing into * neutral molecules. The Stoichiometric species charge is the * charge of one of the ion that would occur if the species broke * into two charged ion pairs. * NaCl -> m_speciesCharge_Stoich = -1; * HSO4- -> H+ + SO42- = -2 * -> The other charge is calculated. * For species that aren't ion pairs, it's equal to the * m_speciesCharge[] value. */ vector_fp m_speciesCharge_Stoich; /** * Array of 2D data used in the DHFORM_BETAIJ formulation * Beta_ij.value(i,j) is the coefficient of the jth species * for the specification of the chemical potential of the ith * species. */ Array2D m_Beta_ij; //! Logarithm of the activity coefficients on the molality scale. /*! * mutable because we change this if the composition * or temperature or pressure changes. */ mutable vector_fp m_lnActCoeffMolal; //! Derivative of log act coeff wrt T mutable vector_fp m_dlnActCoeffMolaldT; //! 2nd Derivative of log act coeff wrt T mutable vector_fp m_d2lnActCoeffMolaldT2; //! Derivative of log act coeff wrt P mutable vector_fp m_dlnActCoeffMolaldP; private: //! Initialize the internal lengths. /*! * This internal function adjusts the lengths of arrays based on * the number of species. */ void initLengths(); //! Calculate the log activity coefficients /*! * This function updates the internally stored natural logarithm of the * molality activity coefficients. This is the main routine for * implementing the activity coefficient formulation. */ void s_update_lnMolalityActCoeff() const; //! Calculation of temperature derivative of activity coefficient /*! * Using internally stored values, this function calculates * the temperature derivative of the logarithm of the * activity coefficient for all species in the mechanism. * * We assume that the activity coefficients are current in this routine * * The solvent activity coefficient is on the molality scale. Its derivative is too. */ void s_update_dlnMolalityActCoeff_dT() const; //! Calculate the temperature 2nd derivative of the activity coefficient /*! * Using internally stored values, this function calculates * the temperature 2nd derivative of the logarithm of the * activity coefficient for all species in the mechanism. * * We assume that the activity coefficients are current in this routine * * solvent activity coefficient is on the molality * scale. Its derivatives are too. */ void s_update_d2lnMolalityActCoeff_dT2() const; //! Calculate the pressure derivative of the activity coefficient /*! * Using internally stored values, this function calculates * the pressure derivative of the logarithm of the * activity coefficient for all species in the mechanism. * * We assume that the activity coefficients, molalities, * and A_Debye are current. * * solvent activity coefficient is on the molality * scale. Its derivatives are too. */ void s_update_dlnMolalityActCoeff_dP() const; }; } #endif
Cantera/cantera-svn
include/cantera/thermo/DebyeHuckel.h
C
bsd-3-clause
54,443
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BaseRenderingContext2D_h #define BaseRenderingContext2D_h #include "bindings/core/v8/UnionTypesCore.h" #include "bindings/modules/v8/UnionTypesModules.h" #include "modules/ModulesExport.h" #include "modules/canvas2d/CanvasGradient.h" #include "modules/canvas2d/CanvasPathMethods.h" #include "modules/canvas2d/CanvasRenderingContext2DState.h" #include "modules/canvas2d/CanvasStyle.h" #include "third_party/skia/include/core/SkCanvas.h" namespace blink { class CanvasImageSource; class Color; class Image; class ImageBuffer; class Path2D; class SVGMatrixTearOff; typedef HTMLImageElementOrHTMLVideoElementOrHTMLCanvasElementOrImageBitmap CanvasImageSourceUnion; class MODULES_EXPORT BaseRenderingContext2D : public GarbageCollectedMixin, public CanvasPathMethods { WTF_MAKE_NONCOPYABLE(BaseRenderingContext2D); public: ~BaseRenderingContext2D() override; void strokeStyle(StringOrCanvasGradientOrCanvasPattern&) const; void setStrokeStyle(const StringOrCanvasGradientOrCanvasPattern&); void fillStyle(StringOrCanvasGradientOrCanvasPattern&) const; void setFillStyle(const StringOrCanvasGradientOrCanvasPattern&); double lineWidth() const; void setLineWidth(double); String lineCap() const; void setLineCap(const String&); String lineJoin() const; void setLineJoin(const String&); double miterLimit() const; void setMiterLimit(double); const Vector<double>& getLineDash() const; void setLineDash(const Vector<double>&); double lineDashOffset() const; void setLineDashOffset(double); double shadowOffsetX() const; void setShadowOffsetX(double); double shadowOffsetY() const; void setShadowOffsetY(double); double shadowBlur() const; void setShadowBlur(double); String shadowColor() const; void setShadowColor(const String&); double globalAlpha() const; void setGlobalAlpha(double); String globalCompositeOperation() const; void setGlobalCompositeOperation(const String&); String filter() const; void setFilter(const String&); void save(); void restore(); SVGMatrixTearOff* currentTransform() const; void setCurrentTransform(SVGMatrixTearOff*); void scale(double sx, double sy); void rotate(double angleInRadians); void translate(double tx, double ty); void transform(double m11, double m12, double m21, double m22, double dx, double dy); void setTransform(double m11, double m12, double m21, double m22, double dx, double dy); void resetTransform(); void beginPath(); void fill(const String& winding = "nonzero"); void fill(Path2D*, const String& winding = "nonzero"); void stroke(); void stroke(Path2D*); void clip(const String& winding = "nonzero"); void clip(Path2D*, const String& winding = "nonzero"); bool isPointInPath(const double x, const double y, const String& winding = "nonzero"); bool isPointInPath(Path2D*, const double x, const double y, const String& winding = "nonzero"); bool isPointInStroke(const double x, const double y); bool isPointInStroke(Path2D*, const double x, const double y); void clearRect(double x, double y, double width, double height); void fillRect(double x, double y, double width, double height); void strokeRect(double x, double y, double width, double height); void drawImage(const CanvasImageSourceUnion&, double x, double y, ExceptionState&); void drawImage(const CanvasImageSourceUnion&, double x, double y, double width, double height, ExceptionState&); void drawImage(const CanvasImageSourceUnion&, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState&); void drawImage(CanvasImageSource*, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState&); CanvasGradient* createLinearGradient(double x0, double y0, double x1, double y1); CanvasGradient* createRadialGradient(double x0, double y0, double r0, double x1, double y1, double r1, ExceptionState&); CanvasPattern* createPattern(const CanvasImageSourceUnion&, const String& repetitionType, ExceptionState&); ImageData* createImageData(ImageData*, ExceptionState&) const; ImageData* createImageData(double width, double height, ExceptionState&) const; ImageData* getImageData(double sx, double sy, double sw, double sh, ExceptionState&) const; void putImageData(ImageData*, double dx, double dy, ExceptionState&); void putImageData(ImageData*, double dx, double dy, double dirtyX, double dirtyY, double dirtyWidth, double dirtyHeight, ExceptionState&); bool imageSmoothingEnabled() const; void setImageSmoothingEnabled(bool); String imageSmoothingQuality() const; void setImageSmoothingQuality(const String&); virtual bool originClean() const = 0; virtual void setOriginTainted() = 0; virtual bool wouldTaintOrigin(CanvasImageSource*) = 0; virtual int width() const = 0; virtual int height() const = 0; virtual bool hasImageBuffer() const = 0; virtual ImageBuffer* imageBuffer() const = 0; virtual bool parseColorOrCurrentColor(Color&, const String& colorString) const = 0; virtual SkCanvas* drawingCanvas() const = 0; virtual SkCanvas* existingDrawingCanvas() const = 0; virtual void disableDeferral(DisableDeferralReason) = 0; virtual AffineTransform baseTransform() const = 0; virtual void didDraw(const SkIRect& dirtyRect) = 0; virtual bool stateHasFilter() = 0; virtual SkImageFilter* stateGetFilter() = 0; virtual void validateStateStack() = 0; virtual bool hasAlpha() const = 0; virtual bool isContextLost() const = 0; DECLARE_VIRTUAL_TRACE(); protected: BaseRenderingContext2D(); CanvasRenderingContext2DState& modifiableState(); const CanvasRenderingContext2DState& state() const { return *m_stateStack.last(); } bool computeDirtyRect(const FloatRect& localBounds, SkIRect*); bool computeDirtyRect(const FloatRect& localBounds, const SkIRect& transformedClipBounds, SkIRect*); template<typename DrawFunc, typename ContainsFunc> bool draw(const DrawFunc&, const ContainsFunc&, const SkRect& bounds, CanvasRenderingContext2DState::PaintType, CanvasRenderingContext2DState::ImageType = CanvasRenderingContext2DState::NoImage); void inflateStrokeRect(FloatRect&) const; enum DrawType { ClipFill, // Fill that is already known to cover the current clip UntransformedUnclippedFill }; void checkOverdraw(const SkRect&, const SkPaint*, CanvasRenderingContext2DState::ImageType, DrawType); HeapVector<Member<CanvasRenderingContext2DState>> m_stateStack; AntiAliasingMode m_clipAntialiasing; private: void realizeSaves(); bool shouldDrawImageAntialiased(const FloatRect& destRect) const; void drawPathInternal(const Path&, CanvasRenderingContext2DState::PaintType, SkPath::FillType = SkPath::kWinding_FillType); void drawImageInternal(SkCanvas*, CanvasImageSource*, Image*, const FloatRect& srcRect, const FloatRect& dstRect, const SkPaint*); void clipInternal(const Path&, const String& windingRuleString); bool isPointInPathInternal(const Path&, const double x, const double y, const String& windingRuleString); bool isPointInStrokeInternal(const Path&, const double x, const double y); static bool isFullCanvasCompositeMode(SkXfermode::Mode); template<typename DrawFunc> void compositedDraw(const DrawFunc&, SkCanvas*, CanvasRenderingContext2DState::PaintType, CanvasRenderingContext2DState::ImageType); void clearCanvas(); bool rectContainsTransformedRect(const FloatRect&, const SkIRect&) const; }; template<typename DrawFunc, typename ContainsFunc> bool BaseRenderingContext2D::draw(const DrawFunc& drawFunc, const ContainsFunc& drawCoversClipBounds, const SkRect& bounds, CanvasRenderingContext2DState::PaintType paintType, CanvasRenderingContext2DState::ImageType imageType) { if (!state().isTransformInvertible()) return false; SkIRect clipBounds; if (!drawingCanvas() || !drawingCanvas()->getClipDeviceBounds(&clipBounds)) return false; // If gradient size is zero, then paint nothing. CanvasStyle* style = state().style(paintType); if (style) { CanvasGradient* gradient = style->getCanvasGradient(); if (gradient && gradient->getGradient()->isZeroSize()) return false; } if (isFullCanvasCompositeMode(state().globalComposite()) || stateHasFilter()) { compositedDraw(drawFunc, drawingCanvas(), paintType, imageType); didDraw(clipBounds); } else if (state().globalComposite() == SkXfermode::kSrc_Mode) { clearCanvas(); // takes care of checkOverdraw() const SkPaint* paint = state().getPaint(paintType, DrawForegroundOnly, imageType); drawFunc(drawingCanvas(), paint); didDraw(clipBounds); } else { SkIRect dirtyRect; if (computeDirtyRect(bounds, clipBounds, &dirtyRect)) { const SkPaint* paint = state().getPaint(paintType, DrawShadowAndForeground, imageType); if (paintType != CanvasRenderingContext2DState::StrokePaintType && drawCoversClipBounds(clipBounds)) checkOverdraw(bounds, paint, imageType, ClipFill); drawFunc(drawingCanvas(), paint); didDraw(dirtyRect); } } return true; } template<typename DrawFunc> void BaseRenderingContext2D::compositedDraw(const DrawFunc& drawFunc, SkCanvas* c, CanvasRenderingContext2DState::PaintType paintType, CanvasRenderingContext2DState::ImageType imageType) { SkImageFilter* filter = stateGetFilter(); ASSERT(isFullCanvasCompositeMode(state().globalComposite()) || filter); SkMatrix ctm = c->getTotalMatrix(); c->resetMatrix(); SkPaint compositePaint; compositePaint.setXfermodeMode(state().globalComposite()); if (state().shouldDrawShadows()) { // unroll into two independently composited passes if drawing shadows SkPaint shadowPaint = *state().getPaint(paintType, DrawShadowOnly, imageType); int saveCount = c->getSaveCount(); if (filter) { SkPaint filterPaint; filterPaint.setImageFilter(filter); // TODO(junov): crbug.com/502921 We could use primitive bounds if we knew that the filter // does not affect transparent black regions. c->saveLayer(nullptr, &shadowPaint); c->saveLayer(nullptr, &filterPaint); SkPaint foregroundPaint = *state().getPaint(paintType, DrawForegroundOnly, imageType); c->setMatrix(ctm); drawFunc(c, &foregroundPaint); } else { ASSERT(isFullCanvasCompositeMode(state().globalComposite())); c->saveLayer(nullptr, &compositePaint); shadowPaint.setXfermodeMode(SkXfermode::kSrcOver_Mode); c->setMatrix(ctm); drawFunc(c, &shadowPaint); } c->restoreToCount(saveCount); } compositePaint.setImageFilter(filter); // TODO(junov): crbug.com/502921 We could use primitive bounds if we knew that the filter // does not affect transparent black regions *and* !isFullCanvasCompositeMode c->saveLayer(nullptr, &compositePaint); SkPaint foregroundPaint = *state().getPaint(paintType, DrawForegroundOnly, imageType); foregroundPaint.setXfermodeMode(SkXfermode::kSrcOver_Mode); c->setMatrix(ctm); drawFunc(c, &foregroundPaint); c->restore(); c->setMatrix(ctm); } } // namespace blink #endif // BaseRenderingContext2D_h
was4444/chromium.src
third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.h
C
bsd-3-clause
11,817
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.genmod.cov_struct.Exchangeable &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix" href="statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix.html" /> <link rel="prev" title="statsmodels.genmod.cov_struct.Autoregressive.update" href="statsmodels.genmod.cov_struct.Autoregressive.update.html" /> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.genmod.cov_struct.Exchangeable" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.11.1</span> <span class="md-header-nav__topic"> statsmodels.genmod.cov_struct.Exchangeable </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../gee.html" class="md-tabs__link">Generalized Estimating Equations</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.11.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.genmod.cov_struct.Exchangeable.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-genmod-cov-struct-exchangeable--page-root">statsmodels.genmod.cov_struct.Exchangeable<a class="headerlink" href="#generated-statsmodels-genmod-cov-struct-exchangeable--page-root" title="Permalink to this headline">¶</a></h1> <dl class="class"> <dt id="statsmodels.genmod.cov_struct.Exchangeable"> <em class="property">class </em><code class="sig-prename descclassname">statsmodels.genmod.cov_struct.</code><code class="sig-name descname">Exchangeable</code><a class="reference internal" href="../_modules/statsmodels/genmod/cov_struct.html#Exchangeable"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.genmod.cov_struct.Exchangeable" title="Permalink to this definition">¶</a></dt> <dd><p>An exchangeable working dependence structure.</p> <p class="rubric">Methods</p> <table class="longtable docutils align-default"> <colgroup> <col style="width: 10%"/> <col style="width: 90%"/> </colgroup> <tbody> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix.html#statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix" title="statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix"><code class="xref py py-obj docutils literal notranslate"><span class="pre">covariance_matrix</span></code></a>(expval, index)</p></td> <td><p>Returns the working covariance or correlation matrix for a given cluster of data.</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix_solve.html#statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix_solve" title="statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix_solve"><code class="xref py py-obj docutils literal notranslate"><span class="pre">covariance_matrix_solve</span></code></a>(expval, index, …)</p></td> <td><p>Solves matrix equations of the form <cite>covmat * soln = rhs</cite> and returns the values of <cite>soln</cite>, where <cite>covmat</cite> is the covariance matrix represented by this class.</p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.genmod.cov_struct.Exchangeable.initialize.html#statsmodels.genmod.cov_struct.Exchangeable.initialize" title="statsmodels.genmod.cov_struct.Exchangeable.initialize"><code class="xref py py-obj docutils literal notranslate"><span class="pre">initialize</span></code></a>(model)</p></td> <td><p>Called by GEE, used by implementations that need additional setup prior to running <cite>fit</cite>.</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.genmod.cov_struct.Exchangeable.summary.html#statsmodels.genmod.cov_struct.Exchangeable.summary" title="statsmodels.genmod.cov_struct.Exchangeable.summary"><code class="xref py py-obj docutils literal notranslate"><span class="pre">summary</span></code></a>()</p></td> <td><p>Returns a text summary of the current estimate of the dependence structure.</p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.genmod.cov_struct.Exchangeable.update.html#statsmodels.genmod.cov_struct.Exchangeable.update" title="statsmodels.genmod.cov_struct.Exchangeable.update"><code class="xref py py-obj docutils literal notranslate"><span class="pre">update</span></code></a>(params)</p></td> <td><p>Update the association parameter values based on the current regression coefficients.</p></td> </tr> </tbody> </table> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.genmod.cov_struct.Autoregressive.update.html" title="Material" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.genmod.cov_struct.Autoregressive.update </span> </div> </a> <a href="statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix.html" title="Admonition" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.genmod.cov_struct.Exchangeable.covariance_matrix </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 21, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 2.4.2. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
v0.11.1/generated/statsmodels.genmod.cov_struct.Exchangeable.html
HTML
bsd-3-clause
20,421
/****************************************************************************** * PROJECT: New Millennium, DS1 * IPC (Interprocess Communication) Package * * (c) Copyright 1996 Reid Simmons. All rights reserved. * * FILE: module1.c * * ABSTRACT: Test program for IPC. * Publishes: MSG1, QUERY1 * Subscribes to: MSG2 * Behavior: Sends MSG1 whenever an "m" is typed at the terminal; * Sends a QUERY1 whenever an "r" is typed; * Quits the program when a 'q' is typed. * Should be run in conjunction with module2. * * $Revision: 2.5 $ * $Date: 2009/01/12 15:54:58 $ * $Author: reids $ * * Copyright (c) 2008, Carnegie Mellon University * This software is distributed under the terms of the * Simplified BSD License (see ipc/LICENSE.TXT) * * REVISION HISTORY * * $Log: module1.c,v $ * Revision 2.5 2009/01/12 15:54:58 reids * Added BSD Open Source license info * * Revision 2.4 2008/07/16 00:08:48 reids * Updates for newer (pickier) compiler gcc 4.x * * Revision 2.3 2007/01/07 20:31:00 reids * Removed memory leaks * * Revision 2.2 2001/01/31 17:53:26 reids * Subscribe/unsubscribe to connections/disconnections of modules. * Subscribe/unsubscribe to changes in handler registrations for a message. * * Revision 2.1.1.1 1999/11/23 19:07:37 reids * Putting IPC Version 2.9.0 under local (CMU) CVS control. * * Revision 1.2.2.1 1996/10/28 16:08:50 reids * Tests of the new IPC_unmarshallData function. * * Revision 1.2 1996/06/17 19:57:57 reids * Updated test programs to adhere to new Makefiles (mbuild) and directory * structure ("ipc/ipc.h"). * * Revision 1.1 1996/06/17 18:43:34 rouquett * ipc test files * * Revision 1.4 1996/05/09 01:07:52 reids * Added latency and throughput tests. * Modified to work on vxworks (m68k). * * Revision 1.3 1996/04/24 19:03:57 reids * Put test programs in architecture-specific obj and bin sub-directories. * Modify test programs for vxworks version (get rid of "main"). * * Revision 1.2 1996/03/12 03:06:07 reids * Test programs now illustrate use of "enum" format; * Handlers now free data. * * Revision 1.1 1996/03/06 20:19:24 reids * New test programs for passing data between C and LISP modules * ****************************************************************/ #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159 #endif #include "ipc.h" #include "module.h" static void msg2Handler (MSG_INSTANCE msgRef, BYTE_ARRAY callData, void *clientData) { MSG2_TYPE str1; IPC_unmarshallData(IPC_msgInstanceFormatter(msgRef), callData, &str1, sizeof(str1)); printf("msg2Handler: Receiving %s (%s) [%s]\n", IPC_msgInstanceName(msgRef), str1, (char *)clientData); free(str1); IPC_freeByteArray(callData); } #ifndef VXWORKS static void stdinHnd (int fd, void *clientData) { #ifdef UNUSED_PRAGMA #pragma unused(fd) #endif char inputLine[81]; fgets(inputLine, 80, stdin); switch (inputLine[0]) { case 'q': case 'Q': IPC_disconnect(); exit(0); case 'm': case 'M': { MSG1_TYPE i1 = 42; printf("\n IPC_publishData(%s, &i1) [%d]\n", MSG1, i1); IPC_publishData(MSG1, &i1); break; } case 'r': case 'R': { QUERY1_TYPE t1 = {666, SendVal, {{0.0, 1.0, 2.0}, {1.0, 2.0, 3.0}}, M_PI}; RESPONSE1_PTR r1Ptr; printf("\n IPC_queryResponseData(%s, &t1, &r1Ptr, IPC_WAIT_FOREVER)\n", QUERY1); IPC_queryResponseData(QUERY1, &t1, (void **)(void *)&r1Ptr, IPC_WAIT_FOREVER); printf("\n Received response:\n"); IPC_printData(IPC_msgFormatter(RESPONSE1), stdout, r1Ptr); IPC_freeData(IPC_msgFormatter(RESPONSE1), r1Ptr); break; } default: printf("stdinHnd [%s]: Received %s", (char *)clientData, inputLine); fflush(stdout); } } #endif static void handlerChangeHnd (const char *msgName, int num, void *clientData) { fprintf(stderr, "HANDLER CHANGE: %s: %d\n", msgName, num); } static void handlerChangeHnd2 (const char *msgName, int num, void *clientData) { fprintf(stderr, "HANDLER CHANGE2: %s: %d\n", msgName, num); } static void connect1Hnd (const char *moduleName, void *clientData) { fprintf(stderr, "CONNECT1: Connection from %s\n", moduleName); fprintf(stderr, " Confirming connection (%d)\n", IPC_isModuleConnected(moduleName)); } static void connect2Hnd (const char *moduleName, void *clientData) { fprintf(stderr, "CONNECT2: Connection from %s\n", moduleName); fprintf(stderr, " Number of handlers: %d\n", IPC_numHandlers(MSG1)); } static void disconnect1Hnd (const char *moduleName, void *clientData) { static int first = 1; fprintf(stderr, "DISCONNECT: %s\n", moduleName); if (first) IPC_unsubscribeConnect(connect1Hnd); else IPC_unsubscribeConnect(connect2Hnd); if (first) IPC_unsubscribeHandlerChange(MSG1, handlerChangeHnd2); else IPC_unsubscribeHandlerChange(MSG1, handlerChangeHnd); first = 0; } void x_ipcRegisterExitProc(void (*proc)(void)); static void safeExit (void) { printf("Don't really exit\n"); } #if defined(VXWORKS) #include <sys/times.h> void module1(void) #else int main (void) #endif { IPC_initialize(); x_ipcRegisterExitProc(safeExit); /* Connect to the central server */ printf("\nIPC_connect(%s)\n", MODULE1_NAME); IPC_connect(MODULE1_NAME); IPC_subscribeConnect(connect1Hnd, NULL); IPC_subscribeConnect(connect2Hnd, NULL); IPC_subscribeDisconnect(disconnect1Hnd, NULL); /* Define the named formats that the modules need */ printf("\nIPC_defineFormat(%s, %s)\n", T1_NAME, T1_FORMAT); IPC_defineFormat(T1_NAME, T1_FORMAT); printf("\nIPC_defineFormat(%s, %s)\n", T2_NAME, T2_FORMAT); IPC_defineFormat(T2_NAME, T2_FORMAT); /* Define the messages that this module publishes */ printf("\nIPC_defineMsg(%s, IPC_VARIABLE_LENGTH, %s)\n", MSG1, MSG1_FORMAT); IPC_defineMsg(MSG1, IPC_VARIABLE_LENGTH, MSG1_FORMAT); IPC_subscribeHandlerChange(MSG1, handlerChangeHnd, NULL); IPC_subscribeHandlerChange(MSG1, handlerChangeHnd2, NULL); printf("\nIPC_defineMsg(%s, IPC_VARIABLE_LENGTH, %s)\n", QUERY1, QUERY1_FORMAT); IPC_defineMsg(QUERY1, IPC_VARIABLE_LENGTH, QUERY1_FORMAT); IPC_subscribeHandlerChange(QUERY1, handlerChangeHnd, NULL); /* Subscribe to the messages that this module listens to. * NOTE: No need to subscribe to the RESPONSE1 message, since it is a * response to a query, not a regular subscription! */ printf("\nIPC_subscribe(%s, msg2Handler, %s)\n", MSG2, MODULE1_NAME); IPC_subscribe(MSG2, msg2Handler, MODULE1_NAME); #ifndef VXWORKS /* Since vxworks does not handle stdin from the terminal, this does not make sense. Instead, send off messages periodically */ /* Subscribe a handler for tty input. Typing "q" will quit the program; Typing "m" will send MSG1; Typing "r" will send QUERY1 ("r" for response) */ printf("\nIPC_subscribeFD(%d, stdinHnd, %s)\n", fileno(stdin), MODULE1_NAME); IPC_subscribeFD(fileno(stdin), stdinHnd, MODULE1_NAME); printf("\nType 'm' to send %s; Type 'r' to send %s; Type 'q' to quit\n", MSG1, QUERY1); IPC_dispatch(); #else #define NUM_MSGS (10) #define INTERVAL (5) { int i; printf("\nWill send a message every %d seconds for %d seconds\n", INTERVAL, NUM_MSGS); for (i=1; i<NUM_MSGS; i++) { /* Alternate */ if (i & 1) { MSG1_TYPE i1 = 42; printf("\n IPC_publishData(%s, &i1) [%d]\n", MSG1, i1); IPC_publishData(MSG1, &i1); } else { QUERY1_TYPE t1 = {666, SendVal, {{0.0, 1.0, 2.0}, {1.0, 2.0, 3.0}}, M_PI}; RESPONSE1_PTR r1Ptr; printf("\n IPC_queryResponseData(%s, &t1, &r1Ptr, IPC_WAIT_FOREVER)\n", QUERY1); IPC_queryResponseData(QUERY1, &t1, (void **)&r1Ptr, IPC_WAIT_FOREVER); printf("\n Received response:\n"); IPC_printData(IPC_msgFormatter(RESPONSE1), stdout, r1Ptr); IPC_freeData(IPC_msgFormatter(RESPONSE1), r1Ptr); } /* This works instead of sleep */ { struct timeval sleep = {INTERVAL, 0}; select(FD_SETSIZE, NULL, NULL, NULL, &sleep); } } } #endif IPC_disconnect(); printf("Made it safely to the end\n"); #if !defined(VXWORKS) return 0; #endif }
languitar/ipc
test/module1.c
C
bsd-3-clause
8,300
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>statsmodels.regression.linear_model.OLSResults.rsquared &#8212; statsmodels 0.8.0 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '0.8.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.regression.linear_model.OLSResults.rsquared_adj" href="statsmodels.regression.linear_model.OLSResults.rsquared_adj.html" /> <link rel="prev" title="statsmodels.regression.linear_model.OLSResults.resid_pearson" href="statsmodels.regression.linear_model.OLSResults.resid_pearson.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> </head> <body role="document"> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.regression.linear_model.OLSResults.rsquared_adj.html" title="statsmodels.regression.linear_model.OLSResults.rsquared_adj" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.regression.linear_model.OLSResults.resid_pearson.html" title="statsmodels.regression.linear_model.OLSResults.resid_pearson" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/group/pystatsmodels?hl=en">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../regression.html" >Linear Regression</a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.regression.linear_model.OLSResults.html" accesskey="U">statsmodels.regression.linear_model.OLSResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-regression-linear-model-olsresults-rsquared"> <h1>statsmodels.regression.linear_model.OLSResults.rsquared<a class="headerlink" href="#statsmodels-regression-linear-model-olsresults-rsquared" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="statsmodels.regression.linear_model.OLSResults.rsquared"> <code class="descclassname">OLSResults.</code><code class="descname">rsquared</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.regression.linear_model.OLSResults.rsquared" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.regression.linear_model.OLSResults.resid_pearson.html" title="previous chapter">statsmodels.regression.linear_model.OLSResults.resid_pearson</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.regression.linear_model.OLSResults.rsquared_adj.html" title="next chapter">statsmodels.regression.linear_model.OLSResults.rsquared_adj</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.regression.linear_model.OLSResults.rsquared.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.3. </div> </body> </html>
statsmodels/statsmodels.github.io
0.8.0/generated/statsmodels.regression.linear_model.OLSResults.rsquared.html
HTML
bsd-3-clause
6,299
""" ======================= Generate Surface Labels ======================= Define a label that is centered on a specific vertex in the surface mesh. Plot that label and the focus that defines its center. """ print __doc__ from surfer import Brain, utils subject_id = "fsaverage" """ Bring up the visualization. """ brain = Brain(subject_id, "lh", "inflated") """ First we'll identify a stereotaxic focus in the MNI coordinate system. This might be a peak activations from a volume based analysis. """ coord = [-43, 25, 24] """ Next we grow a label along the surface around the neareset vertex to this coordinate in the white surface mesh. The `n_steps` argument controls the size of the resulting label. """ utils.coord_to_label(subject_id, coord, label='example_data/coord', hemi='lh', n_steps=25, map_surface="white") brain.add_label('example_data/coord-lh.label', color="darkseagreen", alpha=.8) """ Now we plot the focus on the inflated surface at the vertex identified in the previous step. """ brain.add_foci([coord], map_surface="white", color="mediumseagreen") """ We can also do this using a vertex index, perhaps defined as the peak activation in a surface analysis. This will be more accurate than using a volume-based focus. """ coord = 0 utils.coord_to_label(subject_id, coord, label='example_data/coord', hemi='lh', n_steps=40, map_surface="white", coord_as_vert=True) brain.add_label('example_data/coord-lh.label', color='royalblue', alpha=.8) """ Now we plot the foci on the inflated surface. We will map the foci onto the surface by finding the vertex on the "white" mesh that is closest to the coordinate of the point we want to display. """ brain.add_foci([coord], map_surface="white", coords_as_verts=True, color="mediumblue") """ Set the camera position to show the extent of the labels. """ brain.show_view(dict(elevation=40, distance=430))
aestrivex/PySurfer
examples/plot_label_foci.py
Python
bsd-3-clause
1,955
<?php declare(strict_types=1); /** * This file is part of stubbles. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace stubbles\webapp\routing; use stubbles\ioc\Injector; use stubbles\peer\http\Http; use stubbles\webapp\Request; use stubbles\webapp\Response; /** * Denotes an answer to an OPTIONS request when no specific route for such * requests was configured. * * @since 2.2.0 */ class ResourceOptions extends AbstractResource { /** * list of actually allowed request methods * * @var \stubbles\webapp\routing\MatchingRoutes */ private $matchingRoutes; /** * constructor * * @param \stubbles\ioc\Injector $injector * @param \stubbles\webapp\routing\CalledUri $calledUri actual called uri * @param \stubbles\webapp\routing\Interceptors $interceptors * @param \stubbles\webapp\routing\SupportedMimeTypes $supportedMimeTypes * @param \stubbles\webapp\routing\MatchingRoutes $matchingRoutes */ public function __construct( Injector $injector, CalledUri $calledUri, Interceptors $interceptors, SupportedMimeTypes $supportedMimeTypes, MatchingRoutes $matchingRoutes) { parent::__construct($injector, $calledUri, $interceptors, $supportedMimeTypes); $this->matchingRoutes = $matchingRoutes; } /** * checks whether switch to https is required * * @return bool */ public function requiresHttps(): bool { return false; } /** * creates processor instance * * @param \stubbles\webapp\Request $request current request * @param \stubbles\webapp\Response $response response to send * @return void */ public function resolve(Request $request, Response $response) { $allowedMethods = $this->matchingRoutes->allowedMethods(); if (!in_array(Http::OPTIONS, $allowedMethods)) { $allowedMethods[] = Http::OPTIONS; } $response->addHeader('Allow', join(', ', $allowedMethods)) ->addHeader( 'Access-Control-Allow-Methods', join(', ', $allowedMethods) ); } }
stubbles/stubbles-webapp-core
src/main/php/routing/ResourceOptions.php
PHP
bsd-3-clause
2,389
<!doctype html> <html> <head> <title>walk-tour demo</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes"> <script src="../../webcomponentsjs/webcomponents-lite.js"></script> <link rel="import" href="../../iron-demo-helpers/demo-snippet.html"> <link rel="import" href="walk-tour-demo.html"> <style is="custom-style" include="demo-pages-shared-styles"> </style> </head> <body> <div class="vertical-section-container centered"> <h3>Basic walk-tour Demo</h3> <demo-snippet> <template> <walk-tour-demo></walk-tour-demo> </template> </demo-snippet> </div> </body> </html>
maxiplay/walk-tour
demo/index.html
HTML
bsd-3-clause
748
/******************************************************************************* * Copyright Duke Comprehensive Cancer Center and SemanticBits * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/c3pr/LICENSE.txt for details. ******************************************************************************/ package edu.duke.cabig.c3pr.web.selenium; import java.util.regex.Pattern; import org.springframework.beans.factory.config.PropertiesFactoryBean; import java.util.Properties; import com.thoughtworks.selenium.SeleneseTestCase; import org.springframework.core.io.*; public class CreateSubjectTest extends AbstractSeleniumTestCase { public void testCreateSubject() throws Exception { ajaxWidgets.login(); selenium .open("/c3pr/pages/personAndOrganization/participant/createParticipant"); c3prFixtures.populateSubjectDetails("John", "Smith", "132452461891GYAY"); ajaxWidgets.clickNext("flow-next"); ajaxWidgets.clickNext("flow-next"); // ajaxWidgets.clickNext("createSubject"); // assertTrue(selenium.isTextPresent("Subject successfully created.")); } }
NCIP/c3pr
codebase/projects/web/test/src/java/edu/duke/cabig/c3pr/web/selenium/CreateSubjectTest.java
Java
bsd-3-clause
1,162
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging from telemetry.page.actions import all_page_actions from telemetry.page.actions import page_action def _GetActionFromData(action_data): action_name = action_data['action'] action = all_page_actions.FindClassWithName(action_name) if not action: logging.critical('Could not find an action named %s.', action_name) logging.critical('Check the page set for a typo and check the error ' 'log for possible Python loading/compilation errors.') raise Exception('Action "%s" not found.' % action_name) return action(action_data) def GetCompoundActionFromPage(page, action_name): if not action_name: return [] action_data_list = getattr(page, action_name) if not isinstance(action_data_list, list): action_data_list = [action_data_list] action_list = [] for subaction_data in action_data_list: subaction_name = subaction_data['action'] if hasattr(page, subaction_name): subaction = GetCompoundActionFromPage(page, subaction_name) else: subaction = [_GetActionFromData(subaction_data)] action_list += subaction * subaction_data.get('repeat', 1) return action_list class Failure(Exception): """Exception that can be thrown from PageBenchmark to indicate an undesired but designed-for problem.""" pass class PageTestResults(object): def __init__(self): self.page_successes = [] self.page_failures = [] self.skipped_pages = [] def AddSuccess(self, page): self.page_successes.append({'page': page}) def AddFailure(self, page, message, details): self.page_failures.append({'page': page, 'message': message, 'details': details}) def AddSkippedPage(self, page, message, details): self.skipped_pages.append({'page': page, 'message': message, 'details': details}) class PageTest(object): """A class styled on unittest.TestCase for creating page-specific tests.""" def __init__(self, test_method_name, action_name_to_run='', needs_browser_restart_after_each_run=False, discard_first_result=False): self.options = None try: self._test_method = getattr(self, test_method_name) except AttributeError: raise ValueError, 'No such method %s.%s' % ( self.__class_, test_method_name) # pylint: disable=E1101 self._action_name_to_run = action_name_to_run self._needs_browser_restart_after_each_run = ( needs_browser_restart_after_each_run) self._discard_first_result = discard_first_result @property def needs_browser_restart_after_each_run(self): return self._needs_browser_restart_after_each_run @property def discard_first_result(self): """When set to True, the first run of the test is discarded. This is useful for cases where it's desirable to have some test resource cached so the first run of the test can warm things up. """ return self._discard_first_result def AddCommandLineOptions(self, parser): """Override to expose command-line options for this benchmark. The provided parser is an optparse.OptionParser instance and accepts all normal results. The parsed options are available in Run as self.options.""" pass def CustomizeBrowserOptions(self, options): """Override to add test-specific options to the BrowserOptions object""" pass def CustomizeBrowserOptionsForPage(self, page, options): """Add options specific to the test and the given page.""" if not self.CanRunForPage(page): return for action in GetCompoundActionFromPage(page, self._action_name_to_run): action.CustomizeBrowserOptions(options) def SetUpBrowser(self, browser): """Override to customize the browser right after it has launched.""" pass def CanRunForPage(self, page): #pylint: disable=W0613 """Override to customize if the test can be ran for the given page.""" return True def WillRunPageSet(self, tab, results): """Override to do operations before the page set is navigated.""" pass def DidRunPageSet(self, tab, results): """Override to do operations after page set is completed, but before browser is torn down.""" pass def WillNavigateToPage(self, page, tab): """Override to do operations before the page is navigated.""" pass def DidNavigateToPage(self, page, tab): """Override to do operations right after the page is navigated, but before any waiting for completion has occurred.""" pass def WillRunAction(self, page, tab, action): """Override to do operations before running the action on the page.""" pass def DidRunAction(self, page, tab, action): """Override to do operations after running the action on the page.""" pass def Run(self, options, page, tab, results): self.options = options compound_action = GetCompoundActionFromPage(page, self._action_name_to_run) self._RunCompoundAction(page, tab, compound_action) try: self._test_method(page, tab, results) finally: self.options = None def _RunCompoundAction(self, page, tab, actions): for i, action in enumerate(actions): prev_action = actions[i - 1] if i > 0 else None next_action = actions[i + 1] if i < len(actions) - 1 else None if (action.RunsPreviousAction() and next_action and next_action.RunsPreviousAction()): raise page_action.PageActionFailed('Consecutive actions cannot both ' 'have RunsPreviousAction() == True.') if not (next_action and next_action.RunsPreviousAction()): action.WillRunAction(page, tab) self.WillRunAction(page, tab, action) try: action.RunAction(page, tab, prev_action) finally: self.DidRunAction(page, tab, action) @property def action_name_to_run(self): return self._action_name_to_run
codenote/chromium-test
tools/telemetry/telemetry/page/page_test.py
Python
bsd-3-clause
6,182
namespace XSharp.Assembler.x86.SSE { [XSharp.Assembler.OpCode("mulss")] public class MulSS : InstructionWithDestinationAndSource { } }
CosmosOS/XSharp
source/XSharp/XSharp/Assembler/Gen1/x86/SSEAndMMX2/MulSS.cs
C#
bsd-3-clause
154
<?php namespace YATA; use YATA\YATA, YATA\Request\OAuth, YATA\Response; abstract class AuthorisedOperation { protected $_request; protected $_response; public function __construct(OAuth $request = null) { $this->_response = new Response(); if (!isset($request)) { $request = new OAuth(); } $this->setRequest($request); } public function getRequest() { return $this->_request; } public function setRequest(OAuth $request) { $this->_request = $request; } protected function _makeRequest(array $params) { $this->_request->setParameters($params); $rawResponse = $this->_request->send(); $this->_response->setRawBody($rawResponse); return $this->_response->getResponse(); } }
colindecarlo/Twitter-API
lib/YATA/AuthorisedOperation.php
PHP
bsd-3-clause
768
from django.conf.urls import url, patterns from data import views urlpatterns = patterns("data.views", url(r"^$", views.IndexView.as_view()), url(r"^a/(?P<application_external_id>[^/]{,255})\.json$", views.ApplicationInstanceListView.as_view()), url(r"^(?P<model_external_id>[^/]{,255})\.json$", views.InstanceListView.as_view()), url(r"^(?P<model_external_id>[^/]{,255})/(?P<instance_external_id>[^/]{,255})\.json", views.InstanceDetailView.as_view()), )
mohawkhq/mohawk-data-platform
data/urls.py
Python
bsd-3-clause
479
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.gam.generalized_additive_model.GLMGamResults.resid_pearson &#8212; statsmodels v0.10.0 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_response" href="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_response.html" /> <link rel="prev" title="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_deviance" href="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_deviance.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_response.html" title="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_response" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_deviance.html" title="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_deviance" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../gam.html" >Generalized Additive Models (GAM)</a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.gam.generalized_additive_model.GLMGamResults.html" accesskey="U">statsmodels.gam.generalized_additive_model.GLMGamResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-gam-generalized-additive-model-glmgamresults-resid-pearson"> <h1>statsmodels.gam.generalized_additive_model.GLMGamResults.resid_pearson<a class="headerlink" href="#statsmodels-gam-generalized-additive-model-glmgamresults-resid-pearson" title="Permalink to this headline">¶</a></h1> <p>method</p> <dl class="method"> <dt id="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_pearson"> <code class="sig-prename descclassname">GLMGamResults.</code><code class="sig-name descname">resid_pearson</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.gam.generalized_additive_model.GLMGamResults.resid_pearson" title="Permalink to this definition">¶</a></dt> <dd><p>Pearson residuals. The Pearson residuals are defined as (<cite>endog</cite> - <cite>mu</cite>)/sqrt(VAR(<cite>mu</cite>)) where VAR is the distribution specific variance function. See statsmodels.families.family and statsmodels.families.varfuncs for more information.</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_deviance.html" title="previous chapter">statsmodels.gam.generalized_additive_model.GLMGamResults.resid_deviance</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.gam.generalized_additive_model.GLMGamResults.resid_response.html" title="next chapter">statsmodels.gam.generalized_additive_model.GLMGamResults.resid_response</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.gam.generalized_additive_model.GLMGamResults.resid_pearson.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2. </div> </body> </html>
statsmodels/statsmodels.github.io
v0.10.0/generated/statsmodels.gam.generalized_additive_model.GLMGamResults.resid_pearson.html
HTML
bsd-3-clause
8,030
# minServant Simple Servant example web app
creswick/minServant
README.md
Markdown
bsd-3-clause
44
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/render_widget.h" #include "base/auto_reset.h" #include "base/bind.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/sys_info.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/trace_event_synthetic_delay.h" #include "build/build_config.h" #include "cc/base/switches.h" #include "cc/debug/benchmark_instrumentation.h" #include "cc/output/output_surface.h" #include "cc/trees/layer_tree_host.h" #include "components/scheduler/renderer/render_widget_scheduling_state.h" #include "components/scheduler/renderer/renderer_scheduler.h" #include "content/child/npapi/webplugin.h" #include "content/common/content_switches_internal.h" #include "content/common/gpu/client/context_provider_command_buffer.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/common/gpu/gpu_process_launch_causes.h" #include "content/common/input/synthetic_gesture_packet.h" #include "content/common/input/web_input_event_traits.h" #include "content/common/input_messages.h" #include "content/common/swapped_out_messages.h" #include "content/common/view_messages.h" #include "content/public/common/content_switches.h" #include "content/public/common/context_menu_params.h" #include "content/renderer/cursor_utils.h" #include "content/renderer/external_popup_menu.h" #include "content/renderer/gpu/compositor_output_surface.h" #include "content/renderer/gpu/delegated_compositor_output_surface.h" #include "content/renderer/gpu/frame_swap_message_queue.h" #include "content/renderer/gpu/mailbox_output_surface.h" #include "content/renderer/gpu/queue_message_swap_promise.h" #include "content/renderer/gpu/render_widget_compositor.h" #include "content/renderer/ime_event_guard.h" #include "content/renderer/input/input_handler_manager.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_frame_proxy.h" #include "content/renderer/render_process.h" #include "content/renderer/render_thread_impl.h" #include "content/renderer/render_view_impl.h" #include "content/renderer/renderer_blink_platform_impl.h" #include "content/renderer/resizing_mode_selector.h" #include "ipc/ipc_sync_message.h" #include "skia/ext/platform_canvas.h" #include "third_party/WebKit/public/platform/WebCursorInfo.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/WebKit/public/platform/WebPoint.h" #include "third_party/WebKit/public/platform/WebRect.h" #include "third_party/WebKit/public/platform/WebScreenInfo.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebDeviceEmulationParams.h" #include "third_party/WebKit/public/web/WebFrameWidget.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebPagePopup.h" #include "third_party/WebKit/public/web/WebPopupMenuInfo.h" #include "third_party/WebKit/public/web/WebRange.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #include "third_party/WebKit/public/web/WebView.h" #include "third_party/skia/include/core/SkShader.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/geometry/point_conversions.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gl_switches.h" #include "ui/surface/transport_dib.h" #if defined(OS_ANDROID) #include <android/keycodes.h> #include "content/renderer/android/synchronous_compositor_factory.h" #include "content/renderer/android/synchronous_compositor_filter.h" #include "content/renderer/android/synchronous_compositor_output_surface.h" #endif #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #include "third_party/skia/include/core/SkMallocPixelRef.h" #include "third_party/skia/include/core/SkPixelRef.h" #endif // defined(OS_POSIX) #if defined(MOJO_SHELL_CLIENT) #include "content/public/common/mojo_shell_connection.h" #include "content/renderer/render_widget_mus_connection.h" #endif #include "third_party/WebKit/public/web/WebWidget.h" using blink::WebCompositionUnderline; using blink::WebCursorInfo; using blink::WebDeviceEmulationParams; using blink::WebGestureEvent; using blink::WebInputEvent; using blink::WebKeyboardEvent; using blink::WebMouseEvent; using blink::WebMouseWheelEvent; using blink::WebNavigationPolicy; using blink::WebNode; using blink::WebPagePopup; using blink::WebPoint; using blink::WebPopupType; using blink::WebRange; using blink::WebRect; using blink::WebScreenInfo; using blink::WebSize; using blink::WebTextDirection; using blink::WebTouchEvent; using blink::WebTouchPoint; using blink::WebVector; using blink::WebWidget; namespace { typedef std::map<std::string, ui::TextInputMode> TextInputModeMap; class TextInputModeMapSingleton { public: static TextInputModeMapSingleton* GetInstance() { return base::Singleton<TextInputModeMapSingleton>::get(); } TextInputModeMapSingleton() { map_["verbatim"] = ui::TEXT_INPUT_MODE_VERBATIM; map_["latin"] = ui::TEXT_INPUT_MODE_LATIN; map_["latin-name"] = ui::TEXT_INPUT_MODE_LATIN_NAME; map_["latin-prose"] = ui::TEXT_INPUT_MODE_LATIN_PROSE; map_["full-width-latin"] = ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN; map_["kana"] = ui::TEXT_INPUT_MODE_KANA; map_["katakana"] = ui::TEXT_INPUT_MODE_KATAKANA; map_["numeric"] = ui::TEXT_INPUT_MODE_NUMERIC; map_["tel"] = ui::TEXT_INPUT_MODE_TEL; map_["email"] = ui::TEXT_INPUT_MODE_EMAIL; map_["url"] = ui::TEXT_INPUT_MODE_URL; } const TextInputModeMap& map() const { return map_; } private: TextInputModeMap map_; friend struct base::DefaultSingletonTraits<TextInputModeMapSingleton>; DISALLOW_COPY_AND_ASSIGN(TextInputModeMapSingleton); }; ui::TextInputMode ConvertInputMode(const blink::WebString& input_mode) { static TextInputModeMapSingleton* singleton = TextInputModeMapSingleton::GetInstance(); TextInputModeMap::const_iterator it = singleton->map().find(input_mode.utf8()); if (it == singleton->map().end()) return ui::TEXT_INPUT_MODE_DEFAULT; return it->second; } // TODO(brianderson): Replace the hard-coded threshold with a fraction of // the BeginMainFrame interval. // 4166us will allow 1/4 of a 60Hz interval or 1/2 of a 120Hz interval to // be spent in input hanlders before input starts getting throttled. const int kInputHandlingTimeThrottlingThresholdMicroseconds = 4166; int64 GetEventLatencyMicros(double event_timestamp, base::TimeTicks now) { return (now - base::TimeDelta::FromSecondsD(event_timestamp)) .ToInternalValue(); } void LogInputEventLatencyUmaImpl(WebInputEvent::Type event_type, double event_timestamp, base::TimeTicks now) { UMA_HISTOGRAM_CUSTOM_COUNTS("Event.AggregatedLatency.Renderer2", GetEventLatencyMicros(event_timestamp, now), 1, 10000000, 100); #define CASE_TYPE(t) \ case WebInputEvent::t: \ UMA_HISTOGRAM_CUSTOM_COUNTS("Event.Latency.Renderer2." #t, \ GetEventLatencyMicros(event_timestamp, now), \ 1, 10000000, 100); \ break; switch (event_type) { CASE_TYPE(Undefined); CASE_TYPE(MouseDown); CASE_TYPE(MouseUp); CASE_TYPE(MouseMove); CASE_TYPE(MouseEnter); CASE_TYPE(MouseLeave); CASE_TYPE(ContextMenu); CASE_TYPE(MouseWheel); CASE_TYPE(RawKeyDown); CASE_TYPE(KeyDown); CASE_TYPE(KeyUp); CASE_TYPE(Char); CASE_TYPE(GestureScrollBegin); CASE_TYPE(GestureScrollEnd); CASE_TYPE(GestureScrollUpdate); CASE_TYPE(GestureFlingStart); CASE_TYPE(GestureFlingCancel); CASE_TYPE(GestureShowPress); CASE_TYPE(GestureTap); CASE_TYPE(GestureTapUnconfirmed); CASE_TYPE(GestureTapDown); CASE_TYPE(GestureTapCancel); CASE_TYPE(GestureDoubleTap); CASE_TYPE(GestureTwoFingerTap); CASE_TYPE(GestureLongPress); CASE_TYPE(GestureLongTap); CASE_TYPE(GesturePinchBegin); CASE_TYPE(GesturePinchEnd); CASE_TYPE(GesturePinchUpdate); CASE_TYPE(TouchStart); CASE_TYPE(TouchMove); CASE_TYPE(TouchEnd); CASE_TYPE(TouchCancel); default: // Must include default to let blink::WebInputEvent add new event types // before they're added here. DLOG(WARNING) << "Unhandled WebInputEvent type: " << event_type; break; } #undef CASE_TYPE } void LogInputEventLatencyUma(const WebInputEvent& event, base::TimeTicks now, const ui::LatencyInfo& latency_info) { LogInputEventLatencyUmaImpl(event.type, event.timeStampSeconds, now); for (size_t i = 0; i < latency_info.coalesced_events_size(); i++) { LogInputEventLatencyUmaImpl( event.type, latency_info.timestamps_of_coalesced_events()[i], now); } } } // namespace namespace content { // RenderWidget::ScreenMetricsEmulator ---------------------------------------- class RenderWidget::ScreenMetricsEmulator { public: ScreenMetricsEmulator( RenderWidget* widget, const WebDeviceEmulationParams& params); virtual ~ScreenMetricsEmulator(); // Scale and offset used to convert between host coordinates // and webwidget coordinates. float scale() { return scale_; } gfx::PointF offset() { return offset_; } gfx::Rect applied_widget_rect() const { return applied_widget_rect_; } gfx::Rect original_screen_rect() const { return original_view_screen_rect_; } const WebScreenInfo& original_screen_info() { return original_screen_info_; } void ChangeEmulationParams( const WebDeviceEmulationParams& params); // The following methods alter handlers' behavior for messages related to // widget size and position. void OnResizeMessage(const ViewMsg_Resize_Params& params); void OnUpdateScreenRectsMessage(const gfx::Rect& view_screen_rect, const gfx::Rect& window_screen_rect); void OnShowContextMenu(ContextMenuParams* params); gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor); private: void Reapply(); void Apply(bool top_controls_shrink_blink_size, float top_controls_height, gfx::Rect resizer_rect, bool is_fullscreen_granted, blink::WebDisplayMode display_mode); RenderWidget* widget_; // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation. WebDeviceEmulationParams params_; // The computed scale and offset used to fit widget into browser window. float scale_; gfx::PointF offset_; // Widget rect as passed to webwidget. gfx::Rect applied_widget_rect_; // Original values to restore back after emulation ends. gfx::Size original_size_; gfx::Size original_physical_backing_size_; gfx::Size original_visible_viewport_size_; blink::WebScreenInfo original_screen_info_; gfx::Rect original_view_screen_rect_; gfx::Rect original_window_screen_rect_; }; RenderWidget::ScreenMetricsEmulator::ScreenMetricsEmulator( RenderWidget* widget, const WebDeviceEmulationParams& params) : widget_(widget), params_(params), scale_(1.f) { original_size_ = widget_->size_; original_physical_backing_size_ = widget_->physical_backing_size_; original_visible_viewport_size_ = widget_->visible_viewport_size_; original_screen_info_ = widget_->screen_info_; original_view_screen_rect_ = widget_->view_screen_rect_; original_window_screen_rect_ = widget_->window_screen_rect_; Apply(widget_->top_controls_shrink_blink_size_, widget_->top_controls_height_, widget_->resizer_rect_, widget_->is_fullscreen_granted_, widget_->display_mode_); } RenderWidget::ScreenMetricsEmulator::~ScreenMetricsEmulator() { widget_->screen_info_ = original_screen_info_; widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor); widget_->SetScreenMetricsEmulationParameters(false, params_); widget_->view_screen_rect_ = original_view_screen_rect_; widget_->window_screen_rect_ = original_window_screen_rect_; widget_->Resize(original_size_, original_physical_backing_size_, widget_->top_controls_shrink_blink_size_, widget_->top_controls_height_, original_visible_viewport_size_, widget_->resizer_rect_, widget_->is_fullscreen_granted_, widget_->display_mode_, NO_RESIZE_ACK); } void RenderWidget::ScreenMetricsEmulator::ChangeEmulationParams( const WebDeviceEmulationParams& params) { params_ = params; Reapply(); } void RenderWidget::ScreenMetricsEmulator::Reapply() { Apply(widget_->top_controls_shrink_blink_size_, widget_->top_controls_height_, widget_->resizer_rect_, widget_->is_fullscreen_granted_, widget_->display_mode_); } void RenderWidget::ScreenMetricsEmulator::Apply( bool top_controls_shrink_blink_size, float top_controls_height, gfx::Rect resizer_rect, bool is_fullscreen_granted, blink::WebDisplayMode display_mode) { applied_widget_rect_.set_size(gfx::Size(params_.viewSize)); if (!applied_widget_rect_.width()) applied_widget_rect_.set_width(original_size_.width()); if (!applied_widget_rect_.height()) applied_widget_rect_.set_height(original_size_.height()); if (params_.fitToView && !original_size_.IsEmpty()) { int original_width = std::max(original_size_.width(), 1); int original_height = std::max(original_size_.height(), 1); float width_ratio = static_cast<float>(applied_widget_rect_.width()) / original_width; float height_ratio = static_cast<float>(applied_widget_rect_.height()) / original_height; float ratio = std::max(1.0f, std::max(width_ratio, height_ratio)); scale_ = 1.f / ratio; // Center emulated view inside available view space. offset_.set_x( (original_size_.width() - scale_ * applied_widget_rect_.width()) / 2); offset_.set_y( (original_size_.height() - scale_ * applied_widget_rect_.height()) / 2); } else { scale_ = params_.scale; offset_.SetPoint(params_.offset.x, params_.offset.y); } if (params_.screenPosition == WebDeviceEmulationParams::Desktop) { applied_widget_rect_.set_origin(original_view_screen_rect_.origin()); widget_->screen_info_.rect = original_screen_info_.rect; widget_->screen_info_.availableRect = original_screen_info_.availableRect; widget_->window_screen_rect_ = original_window_screen_rect_; } else { applied_widget_rect_.set_origin(params_.viewPosition); gfx::Rect screen_rect = applied_widget_rect_; if (!params_.screenSize.isEmpty()) { screen_rect = gfx::Rect(0, 0, params_.screenSize.width, params_.screenSize.height); } widget_->screen_info_.rect = screen_rect; widget_->screen_info_.availableRect = screen_rect; widget_->window_screen_rect_ = applied_widget_rect_; } float applied_device_scale_factor = params_.deviceScaleFactor ? params_.deviceScaleFactor : original_screen_info_.deviceScaleFactor; widget_->screen_info_.deviceScaleFactor = applied_device_scale_factor; // Pass three emulation parameters to the blink side: // - we keep the real device scale factor in compositor to produce sharp image // even when emulating different scale factor; // - in order to fit into view, WebView applies offset and scale to the // root layer. blink::WebDeviceEmulationParams modified_params = params_; modified_params.deviceScaleFactor = original_screen_info_.deviceScaleFactor; modified_params.offset = blink::WebFloatPoint(offset_.x(), offset_.y()); modified_params.scale = scale_; widget_->SetScreenMetricsEmulationParameters(true, modified_params); widget_->SetDeviceScaleFactor(applied_device_scale_factor); widget_->view_screen_rect_ = applied_widget_rect_; gfx::Size physical_backing_size = gfx::ScaleToCeiledSize( original_size_, original_screen_info_.deviceScaleFactor); widget_->Resize(applied_widget_rect_.size(), physical_backing_size, top_controls_shrink_blink_size, top_controls_height, applied_widget_rect_.size(), resizer_rect, is_fullscreen_granted, display_mode, NO_RESIZE_ACK); } void RenderWidget::ScreenMetricsEmulator::OnResizeMessage( const ViewMsg_Resize_Params& params) { bool need_ack = params.new_size != original_size_ && !params.new_size.IsEmpty() && !params.physical_backing_size.IsEmpty(); original_size_ = params.new_size; original_physical_backing_size_ = params.physical_backing_size; original_screen_info_ = params.screen_info; original_visible_viewport_size_ = params.visible_viewport_size; Apply(params.top_controls_shrink_blink_size, params.top_controls_height, params.resizer_rect, params.is_fullscreen_granted, params.display_mode); if (need_ack) { widget_->set_next_paint_is_resize_ack(); if (widget_->compositor_) widget_->compositor_->SetNeedsRedrawRect(gfx::Rect(widget_->size_)); } } void RenderWidget::ScreenMetricsEmulator::OnUpdateScreenRectsMessage( const gfx::Rect& view_screen_rect, const gfx::Rect& window_screen_rect) { original_view_screen_rect_ = view_screen_rect; original_window_screen_rect_ = window_screen_rect; if (params_.screenPosition == WebDeviceEmulationParams::Desktop) Reapply(); } void RenderWidget::ScreenMetricsEmulator::OnShowContextMenu( ContextMenuParams* params) { params->x *= scale_; params->x += offset_.x(); params->y *= scale_; params->y += offset_.y(); } gfx::Rect RenderWidget::ScreenMetricsEmulator::AdjustValidationMessageAnchor( const gfx::Rect& anchor) { gfx::Rect scaled = gfx::ScaleToEnclosedRect(anchor, scale_); scaled.set_x(scaled.x() + offset_.x()); scaled.set_y(scaled.y() + offset_.y()); return scaled; } // RenderWidget --------------------------------------------------------------- RenderWidget::RenderWidget(CompositorDependencies* compositor_deps, blink::WebPopupType popup_type, const blink::WebScreenInfo& screen_info, bool swapped_out, bool hidden, bool never_visible) : routing_id_(MSG_ROUTING_NONE), compositor_deps_(compositor_deps), webwidget_(nullptr), opener_id_(MSG_ROUTING_NONE), top_controls_shrink_blink_size_(false), top_controls_height_(0.f), next_paint_flags_(0), auto_resize_mode_(false), need_update_rect_for_auto_resize_(false), did_show_(false), is_hidden_(hidden), compositor_never_visible_(never_visible), is_fullscreen_granted_(false), display_mode_(blink::WebDisplayModeUndefined), handling_input_event_(false), handling_event_overscroll_(nullptr), ime_event_guard_(nullptr), handling_event_type_(WebInputEvent::Undefined), ignore_ack_for_mouse_move_from_debugger_(false), closing_(false), host_closing_(false), is_swapped_out_(swapped_out), for_oopif_(false), text_input_type_(ui::TEXT_INPUT_TYPE_NONE), text_input_mode_(ui::TEXT_INPUT_MODE_DEFAULT), text_input_flags_(0), can_compose_inline_(true), popup_type_(popup_type), pending_window_rect_count_(0), suppress_next_char_events_(false), screen_info_(screen_info), device_scale_factor_(screen_info_.deviceScaleFactor), next_output_surface_id_(0), #if defined(OS_ANDROID) text_field_is_dirty_(false), #endif popup_origin_scale_for_emulation_(0.f), frame_swap_message_queue_(new FrameSwapMessageQueue()), resizing_mode_selector_(new ResizingModeSelector()), context_menu_source_type_(ui::MENU_SOURCE_MOUSE), has_host_context_menu_location_(false) { if (!swapped_out) RenderProcess::current()->AddRefProcess(); DCHECK(RenderThread::Get()); device_color_profile_.push_back('0'); #if defined(OS_ANDROID) text_input_info_history_.push_back(blink::WebTextInputInfo()); #endif // In tests there may not be a RenderThreadImpl. if (RenderThreadImpl::current()) { render_widget_scheduling_state_ = RenderThreadImpl::current() ->GetRendererScheduler() ->NewRenderWidgetSchedulingState() .Pass(); render_widget_scheduling_state_->SetHidden(is_hidden_); } } RenderWidget::~RenderWidget() { DCHECK(!webwidget_) << "Leaking our WebWidget!"; // If we are swapped out, we have released already. if (!is_swapped_out_ && RenderProcess::current()) RenderProcess::current()->ReleaseProcess(); } // static RenderWidget* RenderWidget::Create(int32 opener_id, CompositorDependencies* compositor_deps, blink::WebPopupType popup_type, const blink::WebScreenInfo& screen_info) { DCHECK(opener_id != MSG_ROUTING_NONE); scoped_refptr<RenderWidget> widget(new RenderWidget( compositor_deps, popup_type, screen_info, false, false, false)); if (widget->Init(opener_id)) { // adds reference on success. return widget.get(); } return NULL; } // static RenderWidget* RenderWidget::CreateForFrame( int routing_id, bool hidden, const blink::WebScreenInfo& screen_info, CompositorDependencies* compositor_deps, blink::WebLocalFrame* frame) { CHECK_NE(routing_id, MSG_ROUTING_NONE); // TODO(avi): Before RenderViewImpl has-a RenderWidget, the browser passes the // same routing ID for both the view routing ID and the main frame widget // routing ID. https://crbug.com/545684 RenderViewImpl* view = RenderViewImpl::FromRoutingID(routing_id); if (view) { view->AttachWebFrameWidget(RenderWidget::CreateWebFrameWidget(view, frame)); return view; } scoped_refptr<RenderWidget> widget( new RenderWidget(compositor_deps, blink::WebPopupTypeNone, screen_info, false, hidden, false)); widget->routing_id_ = routing_id; widget->for_oopif_ = true; // DoInit increments the reference count on |widget|, keeping it alive after // this function returns. if (widget->DoInit(MSG_ROUTING_NONE, RenderWidget::CreateWebFrameWidget(widget.get(), frame), nullptr)) { return widget.get(); } return nullptr; } // static blink::WebWidget* RenderWidget::CreateWebFrameWidget( RenderWidget* render_widget, blink::WebLocalFrame* frame) { if (!frame->parent()) { // TODO(dcheng): The main frame widget currently has a special case. // Eliminate this once WebView is no longer a WebWidget. return blink::WebFrameWidget::create(render_widget, frame->view(), frame); } return blink::WebFrameWidget::create(render_widget, frame); } // static blink::WebWidget* RenderWidget::CreateWebWidget(RenderWidget* render_widget) { switch (render_widget->popup_type_) { case blink::WebPopupTypeNone: // Nothing to create. break; case blink::WebPopupTypePage: return WebPagePopup::create(render_widget); default: NOTREACHED(); } return NULL; } void RenderWidget::CloseForFrame() { OnClose(); } bool RenderWidget::Init(int32 opener_id) { return DoInit( opener_id, RenderWidget::CreateWebWidget(this), new ViewHostMsg_CreateWidget(opener_id, popup_type_, &routing_id_)); } bool RenderWidget::DoInit(int32 opener_id, WebWidget* web_widget, IPC::SyncMessage* create_widget_message) { DCHECK(!webwidget_); if (opener_id != MSG_ROUTING_NONE) opener_id_ = opener_id; webwidget_ = web_widget; bool result = true; if (create_widget_message) result = RenderThread::Get()->Send(create_widget_message); if (result) { RenderThread::Get()->AddRoute(routing_id_, this); // Take a reference on behalf of the RenderThread. This will be balanced // when we receive ViewMsg_Close. AddRef(); if (RenderThreadImpl::current()) { RenderThreadImpl::current()->WidgetCreated(); if (is_hidden_) RenderThreadImpl::current()->WidgetHidden(); } return true; } else { // The above Send can fail when the tab is closing. return false; } } void RenderWidget::SetSwappedOut(bool is_swapped_out) { // We should only toggle between states. DCHECK(is_swapped_out_ != is_swapped_out); is_swapped_out_ = is_swapped_out; // If we are swapping out, we will call ReleaseProcess, allowing the process // to exit if all of its RenderViews are swapped out. We wait until the // WasSwappedOut call to do this, to allow the unload handler to finish. // If we are swapping in, we call AddRefProcess to prevent the process from // exiting. if (!is_swapped_out_) RenderProcess::current()->AddRefProcess(); } void RenderWidget::WasSwappedOut() { // If we have been swapped out and no one else is using this process, // it's safe to exit now. CHECK(is_swapped_out_); RenderProcess::current()->ReleaseProcess(); } void RenderWidget::SetPopupOriginAdjustmentsForEmulation( ScreenMetricsEmulator* emulator) { popup_origin_scale_for_emulation_ = emulator->scale(); popup_view_origin_for_emulation_ = emulator->applied_widget_rect().origin(); popup_screen_origin_for_emulation_ = gfx::Point( emulator->original_screen_rect().origin().x() + emulator->offset().x(), emulator->original_screen_rect().origin().y() + emulator->offset().y()); screen_info_ = emulator->original_screen_info(); device_scale_factor_ = screen_info_.deviceScaleFactor; } gfx::Rect RenderWidget::AdjustValidationMessageAnchor(const gfx::Rect& anchor) { if (screen_metrics_emulator_) return screen_metrics_emulator_->AdjustValidationMessageAnchor(anchor); return anchor; } void RenderWidget::SetScreenMetricsEmulationParameters( bool enabled, const blink::WebDeviceEmulationParams& params) { // This is only supported in RenderView. NOTREACHED(); } #if defined(OS_MACOSX) || defined(OS_ANDROID) void RenderWidget::SetExternalPopupOriginAdjustmentsForEmulation( ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator) { popup->SetOriginScaleAndOffsetForEmulation( emulator->scale(), emulator->offset()); } #endif void RenderWidget::OnShowHostContextMenu(ContextMenuParams* params) { if (screen_metrics_emulator_) screen_metrics_emulator_->OnShowContextMenu(params); } bool RenderWidget::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderWidget, message) IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnHandleInputEvent) IPC_MESSAGE_HANDLER(InputMsg_CursorVisibilityChange, OnCursorVisibilityChange) IPC_MESSAGE_HANDLER(InputMsg_ImeSetComposition, OnImeSetComposition) IPC_MESSAGE_HANDLER(InputMsg_ImeConfirmComposition, OnImeConfirmComposition) IPC_MESSAGE_HANDLER(InputMsg_MouseCaptureLost, OnMouseCaptureLost) IPC_MESSAGE_HANDLER(InputMsg_SetFocus, OnSetFocus) IPC_MESSAGE_HANDLER(InputMsg_SyntheticGestureCompleted, OnSyntheticGestureCompleted) IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose) IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize) IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation, OnEnableDeviceEmulation) IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation, OnDisableDeviceEmulation) IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile) IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect) IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden) IPC_MESSAGE_HANDLER(ViewMsg_WasShown, OnWasShown) IPC_MESSAGE_HANDLER(ViewMsg_Repaint, OnRepaint) IPC_MESSAGE_HANDLER(ViewMsg_SetTextDirection, OnSetTextDirection) IPC_MESSAGE_HANDLER(ViewMsg_Move_ACK, OnRequestMoveAck) IPC_MESSAGE_HANDLER(ViewMsg_UpdateScreenRects, OnUpdateScreenRects) IPC_MESSAGE_HANDLER(ViewMsg_SetSurfaceIdNamespace, OnSetSurfaceIdNamespace) #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(InputMsg_ImeEventAck, OnImeEventAck) IPC_MESSAGE_HANDLER(ViewMsg_ShowImeIfNeeded, OnShowImeIfNeeded) #endif IPC_MESSAGE_HANDLER(ViewMsg_HandleCompositorProto, OnHandleCompositorProto) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } bool RenderWidget::Send(IPC::Message* message) { // Don't send any messages after the browser has told us to close, and filter // most outgoing messages while swapped out. if ((is_swapped_out_ && !SwappedOutMessages::CanSendWhileSwappedOut(message)) || closing_) { delete message; return false; } // If given a messsage without a routing ID, then assign our routing ID. if (message->routing_id() == MSG_ROUTING_NONE) message->set_routing_id(routing_id_); return RenderThread::Get()->Send(message); } void RenderWidget::Resize(const gfx::Size& new_size, const gfx::Size& physical_backing_size, bool top_controls_shrink_blink_size, float top_controls_height, const gfx::Size& visible_viewport_size, const gfx::Rect& resizer_rect, bool is_fullscreen_granted, blink::WebDisplayMode display_mode, const ResizeAck resize_ack) { if (resizing_mode_selector_->NeverUsesSynchronousResize()) { // A resize ack shouldn't be requested if we have not ACK'd the previous // one. DCHECK(resize_ack != SEND_RESIZE_ACK || !next_paint_is_resize_ack()); DCHECK(resize_ack == SEND_RESIZE_ACK || resize_ack == NO_RESIZE_ACK); } // Ignore this during shutdown. if (!webwidget_) return; if (compositor_) compositor_->setViewportSize(physical_backing_size); bool resized = size_ != new_size || physical_backing_size_ != physical_backing_size; size_ = new_size; physical_backing_size_ = physical_backing_size; top_controls_shrink_blink_size_ = top_controls_shrink_blink_size; top_controls_height_ = top_controls_height; visible_viewport_size_ = visible_viewport_size; resizer_rect_ = resizer_rect; // NOTE: We may have entered fullscreen mode without changing our size. bool fullscreen_change = is_fullscreen_granted_ != is_fullscreen_granted; is_fullscreen_granted_ = is_fullscreen_granted; display_mode_ = display_mode; webwidget_->setTopControlsHeight(top_controls_height, top_controls_shrink_blink_size_); if (resized) { gfx::Size new_widget_size = IsUseZoomForDSFEnabled() ? physical_backing_size_ : size_; // When resizing, we want to wait to paint before ACK'ing the resize. This // ensures that we only resize as fast as we can paint. We only need to // send an ACK if we are resized to a non-empty rect. webwidget_->resize(new_widget_size); } WebSize visual_viewport_size; if (IsUseZoomForDSFEnabled()) { gfx::SizeF scaled_visible_viewport_size = gfx::ScaleSize(gfx::SizeF(visible_viewport_size), device_scale_factor_); visual_viewport_size = gfx::ToCeiledSize(scaled_visible_viewport_size); } else { visual_viewport_size = visible_viewport_size_; } webwidget()->resizeVisualViewport(visual_viewport_size); if (new_size.IsEmpty() || physical_backing_size.IsEmpty()) { // In this case there is no paint/composite and therefore no // ViewHostMsg_UpdateRect to send the resize ack with. We'd need to send the // ack through a fake ViewHostMsg_UpdateRect or a different message. DCHECK_EQ(resize_ack, NO_RESIZE_ACK); } // Send the Resize_ACK flag once we paint again if requested. if (resize_ack == SEND_RESIZE_ACK) set_next_paint_is_resize_ack(); if (fullscreen_change) DidToggleFullscreen(); // If a resize ack is requested and it isn't set-up, then no more resizes will // come in and in general things will go wrong. DCHECK(resize_ack != SEND_RESIZE_ACK || next_paint_is_resize_ack()); } void RenderWidget::SetWindowRectSynchronously( const gfx::Rect& new_window_rect) { Resize(new_window_rect.size(), new_window_rect.size(), top_controls_shrink_blink_size_, top_controls_height_, new_window_rect.size(), gfx::Rect(), is_fullscreen_granted_, display_mode_, NO_RESIZE_ACK); view_screen_rect_ = new_window_rect; window_screen_rect_ = new_window_rect; if (!did_show_) initial_rect_ = new_window_rect; } void RenderWidget::OnClose() { DCHECK(content::RenderThread::Get()); if (closing_) return; NotifyOnClose(); closing_ = true; // Browser correspondence is no longer needed at this point. if (routing_id_ != MSG_ROUTING_NONE) { RenderThread::Get()->RemoveRoute(routing_id_); SetHidden(false); if (RenderThreadImpl::current()) RenderThreadImpl::current()->WidgetDestroyed(); } if (for_oopif_) { // Widgets for frames may be created and closed at any time while the frame // is alive. However, the closing process must happen synchronously. Frame // widget and frames hold pointers to each other. If Close() is deferred to // the message loop like in the non-frame widget case, WebWidget::close() // can end up accessing members of an already-deleted frame. Close(); } else { // If there is a Send call on the stack, then it could be dangerous to close // now. Post a task that only gets invoked when there are no nested message // loops. base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask( FROM_HERE, base::Bind(&RenderWidget::Close, this)); } // Balances the AddRef taken when we called AddRoute. Release(); } void RenderWidget::OnResize(const ViewMsg_Resize_Params& params) { if (resizing_mode_selector_->ShouldAbortOnResize(this, params)) return; if (screen_metrics_emulator_) { screen_metrics_emulator_->OnResizeMessage(params); return; } bool orientation_changed = screen_info_.orientationAngle != params.screen_info.orientationAngle; screen_info_ = params.screen_info; SetDeviceScaleFactor(screen_info_.deviceScaleFactor); Resize(params.new_size, params.physical_backing_size, params.top_controls_shrink_blink_size, params.top_controls_height, params.visible_viewport_size, params.resizer_rect, params.is_fullscreen_granted, params.display_mode, params.needs_resize_ack ? SEND_RESIZE_ACK : NO_RESIZE_ACK); if (orientation_changed) OnOrientationChange(); } void RenderWidget::OnEnableDeviceEmulation( const blink::WebDeviceEmulationParams& params) { if (!screen_metrics_emulator_) screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params)); else screen_metrics_emulator_->ChangeEmulationParams(params); } void RenderWidget::OnDisableDeviceEmulation() { screen_metrics_emulator_.reset(); } void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) { SetDeviceColorProfile(color_profile); } void RenderWidget::OnChangeResizeRect(const gfx::Rect& resizer_rect) { if (resizer_rect_ == resizer_rect) return; resizer_rect_ = resizer_rect; if (webwidget_) webwidget_->didChangeWindowResizerRect(); } void RenderWidget::OnWasHidden() { TRACE_EVENT0("renderer", "RenderWidget::OnWasHidden"); // Go into a mode where we stop generating paint and scrolling events. SetHidden(true); FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WasHidden()); } void RenderWidget::OnWasShown(bool needs_repainting, const ui::LatencyInfo& latency_info) { TRACE_EVENT0("renderer", "RenderWidget::OnWasShown"); // During shutdown we can just ignore this message. if (!webwidget_) return; // See OnWasHidden SetHidden(false); FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WasShown()); if (!needs_repainting) return; // Generate a full repaint. if (compositor_) { ui::LatencyInfo swap_latency_info(latency_info); scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor( compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info)); compositor_->SetNeedsForcedRedraw(); } ScheduleComposite(); } void RenderWidget::OnRequestMoveAck() { DCHECK(pending_window_rect_count_); pending_window_rect_count_--; } GURL RenderWidget::GetURLForGraphicsContext3D() { return GURL(); } scoped_ptr<cc::OutputSurface> RenderWidget::CreateOutputSurface(bool fallback) { // For widgets that are never visible, we don't start the compositor, so we // never get a request for a cc::OutputSurface. DCHECK(!compositor_never_visible_); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); bool use_software = fallback; if (command_line.HasSwitch(switches::kDisableGpuCompositing)) use_software = true; #if defined(MOJO_SHELL_CLIENT) if (MojoShellConnection::Get() && !use_software) { RenderWidgetMusConnection* connection = RenderWidgetMusConnection::GetOrCreate(routing_id()); return connection->CreateOutputSurface(); } #endif scoped_refptr<ContextProviderCommandBuffer> context_provider; scoped_refptr<ContextProviderCommandBuffer> worker_context_provider; if (!use_software) { context_provider = ContextProviderCommandBuffer::Create( CreateGraphicsContext3D(true), RENDER_COMPOSITOR_CONTEXT); if (!context_provider.get()) { // Cause the compositor to wait and try again. return nullptr; } worker_context_provider = RenderThreadImpl::current()->SharedWorkerContextProvider(); if (!worker_context_provider) { // Cause the compositor to wait and try again. return nullptr; } #if defined(OS_ANDROID) if (SynchronousCompositorFactory* factory = SynchronousCompositorFactory::GetInstance()) { return factory->CreateOutputSurface( routing_id(), frame_swap_message_queue_, context_provider, worker_context_provider); } else if (RenderThreadImpl::current()->sync_compositor_message_filter()) { return make_scoped_ptr(new SynchronousCompositorOutputSurface( context_provider, worker_context_provider, routing_id(), content::RenderThreadImpl::current() ->sync_compositor_message_filter(), frame_swap_message_queue_)); } #endif } uint32 output_surface_id = next_output_surface_id_++; // Composite-to-mailbox is currently used for layout tests in order to cause // them to draw inside in the renderer to do the readback there. This should // no longer be the case when crbug.com/311404 is fixed. if (!RenderThreadImpl::current() || !RenderThreadImpl::current()->layout_test_mode()) { DCHECK(compositor_deps_->GetCompositorImplThreadTaskRunner()); return make_scoped_ptr(new DelegatedCompositorOutputSurface( routing_id(), output_surface_id, context_provider, worker_context_provider, frame_swap_message_queue_)); } if (!context_provider.get()) { scoped_ptr<cc::SoftwareOutputDevice> software_device( new cc::SoftwareOutputDevice()); return make_scoped_ptr(new CompositorOutputSurface( routing_id(), output_surface_id, nullptr, nullptr, software_device.Pass(), frame_swap_message_queue_, true)); } return make_scoped_ptr(new MailboxOutputSurface( routing_id(), output_surface_id, context_provider, worker_context_provider, frame_swap_message_queue_, cc::RGBA_8888)); } void RenderWidget::OnSwapBuffersAborted() { TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersAborted"); // Schedule another frame so the compositor learns about it. ScheduleComposite(); } void RenderWidget::OnSwapBuffersPosted() { TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersPosted"); } void RenderWidget::OnSwapBuffersComplete() { TRACE_EVENT0("renderer", "RenderWidget::OnSwapBuffersComplete"); // Notify subclasses that composited rendering was flushed to the screen. DidFlushPaint(); } void RenderWidget::OnHandleInputEvent(const blink::WebInputEvent* input_event, const ui::LatencyInfo& latency_info) { if (!input_event) return; base::AutoReset<bool> handling_input_event_resetter(&handling_input_event_, true); base::AutoReset<WebInputEvent::Type> handling_event_type_resetter( &handling_event_type_, input_event->type); // Calls into |didOverscroll()| while handling this event will populate // |event_overscroll|, which in turn will be bundled with the event ack. scoped_ptr<DidOverscrollParams> event_overscroll; base::AutoReset<scoped_ptr<DidOverscrollParams>*> handling_event_overscroll_resetter(&handling_event_overscroll_, &event_overscroll); #if defined(OS_ANDROID) const bool is_keyboard_event = WebInputEvent::isKeyboardEventType(input_event->type); // For non-keyboard events, we want the change source to be FROM_NON_IME. ImeEventGuard guard(this, false, is_keyboard_event); #endif base::TimeTicks start_time; if (base::TimeTicks::IsHighResolution()) start_time = base::TimeTicks::Now(); TRACE_EVENT1("renderer,benchmark", "RenderWidget::OnHandleInputEvent", "event", WebInputEventTraits::GetName(input_event->type)); TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("blink.HandleInputEvent"); TRACE_EVENT_WITH_FLOW1("input,benchmark", "LatencyInfo.Flow", TRACE_ID_DONT_MANGLE(latency_info.trace_id()), TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "step", "HandleInputEventMain"); // If we don't have a high res timer, these metrics won't be accurate enough // to be worth collecting. Note that this does introduce some sampling bias. if (!start_time.is_null()) LogInputEventLatencyUma(*input_event, start_time, latency_info); scoped_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor; ui::LatencyInfo swap_latency_info(latency_info); if (compositor_) { latency_info_swap_promise_monitor = compositor_->CreateLatencyInfoSwapPromiseMonitor(&swap_latency_info) .Pass(); } bool prevent_default = false; if (WebInputEvent::isMouseEventType(input_event->type)) { const WebMouseEvent& mouse_event = *static_cast<const WebMouseEvent*>(input_event); TRACE_EVENT2("renderer", "HandleMouseMove", "x", mouse_event.x, "y", mouse_event.y); context_menu_source_type_ = ui::MENU_SOURCE_MOUSE; prevent_default = WillHandleMouseEvent(mouse_event); } if (WebInputEvent::isKeyboardEventType(input_event->type)) { context_menu_source_type_ = ui::MENU_SOURCE_KEYBOARD; #if defined(OS_ANDROID) // The DPAD_CENTER key on Android has a dual semantic: (1) in the general // case it should behave like a select key (i.e. causing a click if a button // is focused). However, if a text field is focused (2), its intended // behavior is to just show the IME and don't propagate the key. // A typical use case is a web form: the DPAD_CENTER should bring up the IME // when clicked on an input text field and cause the form submit if clicked // when the submit button is focused, but not vice-versa. // The UI layer takes care of translating DPAD_CENTER into a RETURN key, // but at this point we have to swallow the event for the scenario (2). const WebKeyboardEvent& key_event = *static_cast<const WebKeyboardEvent*>(input_event); if (key_event.nativeKeyCode == AKEYCODE_DPAD_CENTER && GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) { OnShowImeIfNeeded(); prevent_default = true; } #endif } if (WebInputEvent::isGestureEventType(input_event->type)) { const WebGestureEvent& gesture_event = *static_cast<const WebGestureEvent*>(input_event); context_menu_source_type_ = ui::MENU_SOURCE_TOUCH; prevent_default = prevent_default || WillHandleGestureEvent(gesture_event); } bool processed = prevent_default; if (input_event->type != WebInputEvent::Char || !suppress_next_char_events_) { suppress_next_char_events_ = false; if (!processed && webwidget_) processed = webwidget_->handleInputEvent(*input_event); } // If this RawKeyDown event corresponds to a browser keyboard shortcut and // it's not processed by webkit, then we need to suppress the upcoming Char // events. bool is_keyboard_shortcut = input_event->type == WebInputEvent::RawKeyDown && static_cast<const WebKeyboardEvent*>(input_event)->isBrowserShortcut; if (!processed && is_keyboard_shortcut) suppress_next_char_events_ = true; InputEventAckState ack_result = processed ? INPUT_EVENT_ACK_STATE_CONSUMED : INPUT_EVENT_ACK_STATE_NOT_CONSUMED; if (!processed && input_event->type == WebInputEvent::TouchStart) { const WebTouchEvent& touch_event = *static_cast<const WebTouchEvent*>(input_event); // Hit-test for all the pressed touch points. If there is a touch-handler // for any of the touch points, then the renderer should continue to receive // touch events. ack_result = INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS; for (size_t i = 0; i < touch_event.touchesLength; ++i) { if (touch_event.touches[i].state == WebTouchPoint::StatePressed && HasTouchEventHandlersAt( gfx::ToFlooredPoint(touch_event.touches[i].position))) { ack_result = INPUT_EVENT_ACK_STATE_NOT_CONSUMED; break; } } } // Send mouse wheel events and their disposition to the compositor thread, so // that they can be used to produce the elastic overscroll effect on Mac. if (input_event->type == WebInputEvent::MouseWheel) { ObserveWheelEventAndResult( static_cast<const WebMouseWheelEvent&>(*input_event), event_overscroll ? event_overscroll->latest_overscroll_delta : gfx::Vector2dF(), processed); } bool frame_pending = compositor_ && compositor_->BeginMainFrameRequested(); // If we don't have a fast and accurate Now(), we assume the input handlers // are heavy and rate limit them. bool rate_limiting_wanted = input_event->type == WebInputEvent::MouseMove || input_event->type == WebInputEvent::MouseWheel; if (rate_limiting_wanted && !start_time.is_null()) { base::TimeTicks end_time = base::TimeTicks::Now(); total_input_handling_time_this_frame_ += (end_time - start_time); rate_limiting_wanted = total_input_handling_time_this_frame_.InMicroseconds() > kInputHandlingTimeThrottlingThresholdMicroseconds; } TRACE_EVENT_SYNTHETIC_DELAY_END("blink.HandleInputEvent"); // Note that we can't use handling_event_type_ here since it will be overriden // by reentrant calls for events after the paused one. bool no_ack = ignore_ack_for_mouse_move_from_debugger_ && input_event->type == WebInputEvent::MouseMove; if (WebInputEventTraits::WillReceiveAckFromRenderer(*input_event) && !no_ack) { InputEventAck ack(input_event->type, ack_result, swap_latency_info, event_overscroll.Pass(), WebInputEventTraits::GetUniqueTouchEventId(*input_event)); scoped_ptr<IPC::Message> response( new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack)); if (rate_limiting_wanted && frame_pending && !is_hidden_) { // We want to rate limit the input events in this case, so we'll wait for // painting to finish before ACKing this message. TRACE_EVENT_INSTANT0("renderer", "RenderWidget::OnHandleInputEvent ack throttled", TRACE_EVENT_SCOPE_THREAD); if (pending_input_event_ack_) { TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck", pending_input_event_ack_.get()); // As two different kinds of events could cause us to postpone an ack // we send it now, if we have one pending. The Browser should never // send us the same kind of event we are delaying the ack for. Send(pending_input_event_ack_.release()); } pending_input_event_ack_ = response.Pass(); TRACE_EVENT_ASYNC_BEGIN0("input", "RenderWidget::ThrottledInputEventAck", pending_input_event_ack_.get()); if (compositor_) compositor_->NotifyInputThrottledUntilCommit(); } else { Send(response.release()); } } else { DCHECK(!event_overscroll) << "Unexpected overscroll for un-acked event"; } if (!no_ack && RenderThreadImpl::current()) { RenderThreadImpl::current() ->GetRendererScheduler() ->DidHandleInputEventOnMainThread(*input_event); } if (input_event->type == WebInputEvent::MouseMove) ignore_ack_for_mouse_move_from_debugger_ = false; #if defined(OS_ANDROID) // Allow the IME to be shown when the focus changes as a consequence // of a processed touch end event. if (input_event->type == WebInputEvent::TouchEnd && processed) UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME); #elif defined(USE_AURA) // Show the virtual keyboard if enabled and a user gesture triggers a focus // change. if (processed && (input_event->type == WebInputEvent::TouchEnd || input_event->type == WebInputEvent::MouseUp)) { UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_IME); } #endif if (!prevent_default) { if (WebInputEvent::isKeyboardEventType(input_event->type)) DidHandleKeyEvent(); } // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with // virtual keyboard. #if !defined(OS_ANDROID) // Virtual keyboard is not supported, so react to focus change immediately. if (processed && (input_event->type == WebInputEvent::TouchEnd || input_event->type == WebInputEvent::MouseUp)) { FocusChangeComplete(); } #endif } void RenderWidget::OnCursorVisibilityChange(bool is_visible) { if (webwidget_) webwidget_->setCursorVisibilityState(is_visible); } void RenderWidget::OnMouseCaptureLost() { if (webwidget_) webwidget_->mouseCaptureLost(); } void RenderWidget::OnSetFocus(bool enable) { if (webwidget_) webwidget_->setFocus(enable); } void RenderWidget::FlushPendingInputEventAck() { if (pending_input_event_ack_) { TRACE_EVENT_ASYNC_END0("input", "RenderWidget::ThrottledInputEventAck", pending_input_event_ack_.get()); Send(pending_input_event_ack_.release()); } total_input_handling_time_this_frame_ = base::TimeDelta(); } /////////////////////////////////////////////////////////////////////////////// // WebWidgetClient void RenderWidget::didAutoResize(const WebSize& new_size) { // TODO(oshima): support UseZoomForDSFEnabled() if (size_.width() != new_size.width || size_.height() != new_size.height) { size_ = new_size; if (resizing_mode_selector_->is_synchronous_mode()) { WebRect new_pos(rootWindowRect().x, rootWindowRect().y, new_size.width, new_size.height); view_screen_rect_ = new_pos; window_screen_rect_ = new_pos; } AutoResizeCompositor(); if (!resizing_mode_selector_->is_synchronous_mode()) need_update_rect_for_auto_resize_ = true; } } void RenderWidget::AutoResizeCompositor() { physical_backing_size_ = gfx::ScaleToCeiledSize(size_, device_scale_factor_); if (compositor_) compositor_->setViewportSize(physical_backing_size_); } void RenderWidget::initializeLayerTreeView() { DCHECK(!host_closing_); compositor_ = RenderWidgetCompositor::Create(this, compositor_deps_); compositor_->setViewportSize(physical_backing_size_); // For background pages and certain tests, we don't want to trigger // OutputSurface creation. if (compositor_never_visible_ || !RenderThreadImpl::current()) compositor_->SetNeverVisible(); StartCompositor(); } void RenderWidget::WillCloseLayerTreeView() { if (host_closing_) return; // Prevent new compositors or output surfaces from being created. host_closing_ = true; // Always send this notification to prevent new layer tree views from // being created, even if one hasn't been created yet. if (webwidget_) webwidget_->willCloseLayerTreeView(); } blink::WebLayerTreeView* RenderWidget::layerTreeView() { return compositor_.get(); } void RenderWidget::didMeaningfulLayout(blink::WebMeaningfulLayout layout_type) { if (layout_type == blink::WebMeaningfulLayout::VisuallyNonEmpty) { QueueMessage(new ViewHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_), MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE); } FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, DidMeaningfulLayout(layout_type)); } void RenderWidget::WillBeginCompositorFrame() { TRACE_EVENT0("gpu", "RenderWidget::willBeginCompositorFrame"); // The UpdateTextInputState can result in further layout and possibly // enable GPU acceleration so they need to be called before any painting // is done. UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME); UpdateSelectionBounds(); } void RenderWidget::DidCommitCompositorFrame() { FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, DidCommitCompositorFrame()); FOR_EACH_OBSERVER(RenderFrameProxy, render_frame_proxies_, DidCommitCompositorFrame()); #if defined(VIDEO_HOLE) FOR_EACH_OBSERVER(RenderFrameImpl, video_hole_frames_, DidCommitCompositorFrame()); #endif // defined(VIDEO_HOLE) FlushPendingInputEventAck(); } void RenderWidget::DidCommitAndDrawCompositorFrame() { // NOTE: Tests may break if this event is renamed or moved. See // tab_capture_performancetest.cc. TRACE_EVENT0("gpu", "RenderWidget::DidCommitAndDrawCompositorFrame"); // Notify subclasses that we initiated the paint operation. DidInitiatePaint(); } void RenderWidget::DidCompleteSwapBuffers() { TRACE_EVENT0("renderer", "RenderWidget::DidCompleteSwapBuffers"); // Notify subclasses threaded composited rendering was flushed to the screen. DidFlushPaint(); if (!next_paint_flags_ && !need_update_rect_for_auto_resize_ && !plugin_window_moves_.size()) { return; } ViewHostMsg_UpdateRect_Params params; params.view_size = size_; params.plugin_window_moves.swap(plugin_window_moves_); params.flags = next_paint_flags_; Send(new ViewHostMsg_UpdateRect(routing_id_, params)); next_paint_flags_ = 0; need_update_rect_for_auto_resize_ = false; } void RenderWidget::ScheduleComposite() { if (compositor_ && compositor_deps_->GetCompositorImplThreadTaskRunner().get()) { compositor_->setNeedsAnimate(); } } void RenderWidget::ScheduleCompositeWithForcedRedraw() { if (compositor_) { // Regardless of whether threaded compositing is enabled, always // use this mechanism to force the compositor to redraw. However, // the invalidation code path below is still needed for the // non-threaded case. compositor_->SetNeedsForcedRedraw(); } ScheduleComposite(); } // static scoped_ptr<cc::SwapPromise> RenderWidget::QueueMessageImpl( IPC::Message* msg, MessageDeliveryPolicy policy, FrameSwapMessageQueue* frame_swap_message_queue, scoped_refptr<IPC::SyncMessageFilter> sync_message_filter, int source_frame_number) { bool first_message_for_frame = false; frame_swap_message_queue->QueueMessageForFrame(policy, source_frame_number, make_scoped_ptr(msg), &first_message_for_frame); if (first_message_for_frame) { scoped_ptr<cc::SwapPromise> promise(new QueueMessageSwapPromise( sync_message_filter, frame_swap_message_queue, source_frame_number)); return promise; } return nullptr; } void RenderWidget::QueueMessage(IPC::Message* msg, MessageDeliveryPolicy policy) { // RenderThreadImpl::current() is NULL in some tests. if (!compositor_ || !RenderThreadImpl::current()) { Send(msg); return; } scoped_ptr<cc::SwapPromise> swap_promise = QueueMessageImpl(msg, policy, frame_swap_message_queue_.get(), RenderThreadImpl::current()->sync_message_filter(), compositor_->GetSourceFrameNumber()); if (swap_promise) { compositor_->QueueSwapPromise(swap_promise.Pass()); // Request a commit. This might either A) request a commit ahead of time // or B) request a commit which is not needed because there are not // pending updates. If B) then the commit will be skipped and the swap // promises will be broken (see EarlyOut_NoUpdates). To achieve that we // call SetNeedsUpdateLayers instead of SetNeedsCommit so that // can_cancel_commit is not unset. compositor_->SetNeedsUpdateLayers(); } } void RenderWidget::didChangeCursor(const WebCursorInfo& cursor_info) { // TODO(darin): Eliminate this temporary. WebCursor cursor; InitializeCursorFromWebCursorInfo(&cursor, cursor_info); // Only send a SetCursor message if we need to make a change. if (!current_cursor_.IsEqual(cursor)) { current_cursor_ = cursor; Send(new ViewHostMsg_SetCursor(routing_id_, cursor)); } } // We are supposed to get a single call to Show for a newly created RenderWidget // that was created via RenderWidget::CreateWebView. So, we wait until this // point to dispatch the ShowWidget message. // // This method provides us with the information about how to display the newly // created RenderWidget (i.e., as a blocked popup or as a new tab). // void RenderWidget::show(WebNavigationPolicy) { DCHECK(!did_show_) << "received extraneous Show call"; DCHECK(routing_id_ != MSG_ROUTING_NONE); DCHECK(opener_id_ != MSG_ROUTING_NONE); if (did_show_) return; did_show_ = true; // NOTE: initial_rect_ may still have its default values at this point, but // that's okay. It'll be ignored if as_popup is false, or the browser // process will impose a default position otherwise. Send(new ViewHostMsg_ShowWidget(opener_id_, routing_id_, initial_rect_)); SetPendingWindowRect(initial_rect_); } void RenderWidget::didFocus() { } void RenderWidget::DoDeferredClose() { WillCloseLayerTreeView(); Send(new ViewHostMsg_Close(routing_id_)); } void RenderWidget::NotifyOnClose() { FOR_EACH_OBSERVER(RenderFrameImpl, render_frames_, WidgetWillClose()); } void RenderWidget::closeWidgetSoon() { DCHECK(content::RenderThread::Get()); if (is_swapped_out_) { // This widget is currently swapped out, and the active widget is in a // different process. Have the browser route the close request to the // active widget instead, so that the correct unload handlers are run. Send(new ViewHostMsg_RouteCloseEvent(routing_id_)); return; } // If a page calls window.close() twice, we'll end up here twice, but that's // OK. It is safe to send multiple Close messages. // Ask the RenderWidgetHost to initiate close. We could be called from deep // in Javascript. If we ask the RendwerWidgetHost to close now, the window // could be closed before the JS finishes executing. So instead, post a // message back to the message loop, which won't run until the JS is // complete, and then the Close message can be sent. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&RenderWidget::DoDeferredClose, this)); } void RenderWidget::QueueSyntheticGesture( scoped_ptr<SyntheticGestureParams> gesture_params, const SyntheticGestureCompletionCallback& callback) { DCHECK(!callback.is_null()); pending_synthetic_gesture_callbacks_.push(callback); SyntheticGesturePacket gesture_packet; gesture_packet.set_gesture_params(gesture_params.Pass()); Send(new InputHostMsg_QueueSyntheticGesture(routing_id_, gesture_packet)); } void RenderWidget::Close() { screen_metrics_emulator_.reset(); WillCloseLayerTreeView(); compositor_.reset(); if (webwidget_) { webwidget_->close(); webwidget_ = NULL; } } WebRect RenderWidget::windowRect() { if (pending_window_rect_count_) return pending_window_rect_; return view_screen_rect_; } void RenderWidget::setToolTipText(const blink::WebString& text, WebTextDirection hint) { Send(new ViewHostMsg_SetTooltipText(routing_id_, text, hint)); } void RenderWidget::setWindowRect(const WebRect& rect) { // TODO(oshima): Scale back to DIP coordinates. WebRect window_rect = rect; if (popup_origin_scale_for_emulation_) { float scale = popup_origin_scale_for_emulation_; window_rect.x = popup_screen_origin_for_emulation_.x() + (window_rect.x - popup_view_origin_for_emulation_.x()) * scale; window_rect.y = popup_screen_origin_for_emulation_.y() + (window_rect.y - popup_view_origin_for_emulation_.y()) * scale; } if (!resizing_mode_selector_->is_synchronous_mode()) { if (did_show_) { Send(new ViewHostMsg_RequestMove(routing_id_, window_rect)); SetPendingWindowRect(window_rect); } else { initial_rect_ = window_rect; } } else { SetWindowRectSynchronously(window_rect); } } void RenderWidget::SetPendingWindowRect(const WebRect& rect) { pending_window_rect_ = rect; pending_window_rect_count_++; } WebRect RenderWidget::rootWindowRect() { if (pending_window_rect_count_) { // NOTE(mbelshe): If there is a pending_window_rect_, then getting // the RootWindowRect is probably going to return wrong results since the // browser may not have processed the Move yet. There isn't really anything // good to do in this case, and it shouldn't happen - since this size is // only really needed for windowToScreen, which is only used for Popups. return pending_window_rect_; } return window_screen_rect_; } WebRect RenderWidget::windowResizerRect() { return resizer_rect_; } void RenderWidget::OnImeSetComposition( const base::string16& text, const std::vector<WebCompositionUnderline>& underlines, int selection_start, int selection_end) { if (!ShouldHandleImeEvent()) return; ImeEventGuard guard(this); if (!webwidget_->setComposition( text, WebVector<WebCompositionUnderline>(underlines), selection_start, selection_end)) { // If we failed to set the composition text, then we need to let the browser // process to cancel the input method's ongoing composition session, to make // sure we are in a consistent state. Send(new InputHostMsg_ImeCancelComposition(routing_id())); } UpdateCompositionInfo(true); } void RenderWidget::OnImeConfirmComposition(const base::string16& text, const gfx::Range& replacement_range, bool keep_selection) { if (!ShouldHandleImeEvent()) return; ImeEventGuard guard(this); handling_input_event_ = true; if (text.length()) webwidget_->confirmComposition(text); else if (keep_selection) webwidget_->confirmComposition(WebWidget::KeepSelection); else webwidget_->confirmComposition(WebWidget::DoNotKeepSelection); handling_input_event_ = false; UpdateCompositionInfo(true); } void RenderWidget::OnRepaint(gfx::Size size_to_paint) { // During shutdown we can just ignore this message. if (!webwidget_) return; // Even if the browser provides an empty damage rect, it's still expecting to // receive a repaint ack so just damage the entire widget bounds. if (size_to_paint.IsEmpty()) { size_to_paint = size_; } set_next_paint_is_repaint_ack(); if (compositor_) compositor_->SetNeedsRedrawRect(gfx::Rect(size_to_paint)); } void RenderWidget::OnSyntheticGestureCompleted() { DCHECK(!pending_synthetic_gesture_callbacks_.empty()); pending_synthetic_gesture_callbacks_.front().Run(); pending_synthetic_gesture_callbacks_.pop(); } void RenderWidget::OnSetTextDirection(WebTextDirection direction) { if (!webwidget_) return; webwidget_->setTextDirection(direction); } void RenderWidget::OnUpdateScreenRects(const gfx::Rect& view_screen_rect, const gfx::Rect& window_screen_rect) { if (screen_metrics_emulator_) { screen_metrics_emulator_->OnUpdateScreenRectsMessage( view_screen_rect, window_screen_rect); } else { view_screen_rect_ = view_screen_rect; window_screen_rect_ = window_screen_rect; } Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id())); } void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) { if (compositor_) compositor_->SetSurfaceIdNamespace(surface_id_namespace); } void RenderWidget::OnHandleCompositorProto(const std::vector<uint8_t>& proto) { if (compositor_) compositor_->OnHandleCompositorProto(proto); } void RenderWidget::showImeIfNeeded() { OnShowImeIfNeeded(); } void RenderWidget::OnShowImeIfNeeded() { #if defined(OS_ANDROID) || defined(USE_AURA) UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME); #endif // TODO(rouslan): Fix ChromeOS and Windows 8 behavior of autofill popup with // virtual keyboard. #if !defined(OS_ANDROID) FocusChangeComplete(); #endif } #if defined(OS_ANDROID) void RenderWidget::OnImeEventSentForAck(const blink::WebTextInputInfo& info) { text_input_info_history_.push_back(info); } void RenderWidget::OnImeEventAck() { DCHECK_GE(text_input_info_history_.size(), 1u); text_input_info_history_.pop_front(); } #endif bool RenderWidget::ShouldHandleImeEvent() { #if defined(OS_ANDROID) if (!webwidget_) return false; // We cannot handle IME events if there is any chance that the event we are // receiving here from the browser is based on the state that is different // from our current one as indicated by |text_input_info_|. // The states the browser might be in are: // text_input_info_history_[0] - current state ack'd by browser // text_input_info_history_[1...N] - pending state changes for (size_t i = 0u; i < text_input_info_history_.size() - 1u; ++i) { if (text_input_info_history_[i] != text_input_info_) return false; } return true; #else return !!webwidget_; #endif } bool RenderWidget::SendAckForMouseMoveFromDebugger() { if (handling_event_type_ == WebInputEvent::MouseMove) { // If we pause multiple times during a single mouse move event, we should // only send ACK once. if (!ignore_ack_for_mouse_move_from_debugger_) { InputEventAck ack(handling_event_type_, INPUT_EVENT_ACK_STATE_CONSUMED); Send(new InputHostMsg_HandleInputEvent_ACK(routing_id_, ack)); return true; } } return false; } void RenderWidget::IgnoreAckForMouseMoveFromDebugger() { ignore_ack_for_mouse_move_from_debugger_ = true; } void RenderWidget::SetDeviceScaleFactor(float device_scale_factor) { if (device_scale_factor_ == device_scale_factor) return; device_scale_factor_ = device_scale_factor; ScheduleComposite(); } bool RenderWidget::SetDeviceColorProfile( const std::vector<char>& color_profile) { if (device_color_profile_ == color_profile) return false; device_color_profile_ = color_profile; return true; } void RenderWidget::ResetDeviceColorProfileForTesting() { if (!device_color_profile_.empty()) device_color_profile_.clear(); device_color_profile_.push_back('0'); } void RenderWidget::OnOrientationChange() { } gfx::Vector2d RenderWidget::GetScrollOffset() { // Bare RenderWidgets don't support scroll offset. return gfx::Vector2d(); } void RenderWidget::SetHidden(bool hidden) { if (is_hidden_ == hidden) return; // The status has changed. Tell the RenderThread about it and ensure // throttled acks are released in case frame production ceases. is_hidden_ = hidden; FlushPendingInputEventAck(); if (is_hidden_) RenderThreadImpl::current()->WidgetHidden(); else RenderThreadImpl::current()->WidgetRestored(); if (render_widget_scheduling_state_) render_widget_scheduling_state_->SetHidden(hidden); } void RenderWidget::DidToggleFullscreen() { if (!webwidget_) return; if (is_fullscreen_granted_) { webwidget_->didEnterFullScreen(); } else { webwidget_->didExitFullScreen(); } } bool RenderWidget::next_paint_is_resize_ack() const { return ViewHostMsg_UpdateRect_Flags::is_resize_ack(next_paint_flags_); } void RenderWidget::set_next_paint_is_resize_ack() { next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK; } void RenderWidget::set_next_paint_is_repaint_ack() { next_paint_flags_ |= ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK; } static bool IsDateTimeInput(ui::TextInputType type) { return type == ui::TEXT_INPUT_TYPE_DATE || type == ui::TEXT_INPUT_TYPE_DATE_TIME || type == ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL || type == ui::TEXT_INPUT_TYPE_MONTH || type == ui::TEXT_INPUT_TYPE_TIME || type == ui::TEXT_INPUT_TYPE_WEEK; } void RenderWidget::OnImeEventGuardStart(ImeEventGuard* guard) { if (!ime_event_guard_) ime_event_guard_ = guard; } void RenderWidget::OnImeEventGuardFinish(ImeEventGuard* guard) { if (ime_event_guard_ != guard) { #if defined(OS_ANDROID) // In case a from-IME event (e.g. touch) ends up in not-from-IME event // (e.g. long press gesture), we want to treat it as not-from-IME event // so that AdapterInputConnection can make changes to its Editable model. // Therefore, we want to mark this text state update as 'from IME' only // when all the nested events are all originating from IME. ime_event_guard_->set_from_ime( ime_event_guard_->from_ime() && guard->from_ime()); #endif return; } ime_event_guard_ = nullptr; // While handling an ime event, text input state and selection bounds updates // are ignored. These must explicitly be updated once finished handling the // ime event. UpdateSelectionBounds(); #if defined(OS_ANDROID) UpdateTextInputState( guard->show_ime() ? SHOW_IME_IF_NEEDED : NO_SHOW_IME, guard->from_ime() ? FROM_IME : FROM_NON_IME); #endif } void RenderWidget::UpdateTextInputState(ShowIme show_ime, ChangeSource change_source) { TRACE_EVENT0("renderer", "RenderWidget::UpdateTextInputState"); if (ime_event_guard_) { // show_ime should still be effective even if it was set inside the IME // event guard. if (show_ime == SHOW_IME_IF_NEEDED) { ime_event_guard_->set_show_ime(true); } return; } ui::TextInputType new_type = GetTextInputType(); if (IsDateTimeInput(new_type)) return; // Not considered as a text input field in WebKit/Chromium. blink::WebTextInputInfo new_info; if (webwidget_) new_info = webwidget_->textInputInfo(); const ui::TextInputMode new_mode = ConvertInputMode(new_info.inputMode); bool new_can_compose_inline = CanComposeInline(); // Only sends text input params if they are changed or if the ime should be // shown. if (show_ime == SHOW_IME_IF_NEEDED || (text_input_type_ != new_type || text_input_mode_ != new_mode || text_input_info_ != new_info || can_compose_inline_ != new_can_compose_inline) #if defined(OS_ANDROID) || text_field_is_dirty_ #endif ) { ViewHostMsg_TextInputState_Params params; params.type = new_type; params.mode = new_mode; params.flags = new_info.flags; params.value = new_info.value.utf8(); params.selection_start = new_info.selectionStart; params.selection_end = new_info.selectionEnd; params.composition_start = new_info.compositionStart; params.composition_end = new_info.compositionEnd; params.can_compose_inline = new_can_compose_inline; params.show_ime_if_needed = (show_ime == SHOW_IME_IF_NEEDED); #if defined(USE_AURA) params.is_non_ime_change = true; #endif #if defined(OS_ANDROID) params.is_non_ime_change = (change_source == FROM_NON_IME) || text_field_is_dirty_; if (params.is_non_ime_change) OnImeEventSentForAck(new_info); text_field_is_dirty_ = false; #endif Send(new ViewHostMsg_TextInputStateChanged(routing_id(), params)); text_input_info_ = new_info; text_input_type_ = new_type; text_input_mode_ = new_mode; can_compose_inline_ = new_can_compose_inline; text_input_flags_ = new_info.flags; } } void RenderWidget::GetSelectionBounds(gfx::Rect* focus, gfx::Rect* anchor) { WebRect focus_webrect; WebRect anchor_webrect; webwidget_->selectionBounds(focus_webrect, anchor_webrect); if (IsUseZoomForDSFEnabled()) { float inverse_scale = 1.f / device_scale_factor_; gfx::RectF focus_rect(focus_webrect); *focus = gfx::ToEnclosingRect(gfx::ScaleRect(focus_rect, inverse_scale)); gfx::RectF anchor_rect(anchor_webrect); *anchor = gfx::ToEnclosingRect(gfx::ScaleRect(anchor_rect, inverse_scale)); } else { *focus = focus_webrect; *anchor = anchor_webrect; } } void RenderWidget::UpdateSelectionBounds() { TRACE_EVENT0("renderer", "RenderWidget::UpdateSelectionBounds"); if (!webwidget_) return; if (ime_event_guard_) return; #if defined(USE_AURA) // TODO(mohsen): For now, always send explicit selection IPC notifications for // Aura beucause composited selection updates are not working for webview tags // which regresses IME inside webview. Remove this when composited selection // updates are fixed for webviews. See, http://crbug.com/510568. bool send_ipc = true; #else // With composited selection updates, the selection bounds will be reported // directly by the compositor, in which case explicit IPC selection // notifications should be suppressed. bool send_ipc = !blink::WebRuntimeFeatures::isCompositedSelectionUpdateEnabled(); #endif if (send_ipc) { ViewHostMsg_SelectionBounds_Params params; GetSelectionBounds(&params.anchor_rect, &params.focus_rect); if (selection_anchor_rect_ != params.anchor_rect || selection_focus_rect_ != params.focus_rect) { selection_anchor_rect_ = params.anchor_rect; selection_focus_rect_ = params.focus_rect; webwidget_->selectionTextDirection(params.focus_dir, params.anchor_dir); params.is_anchor_first = webwidget_->isSelectionAnchorFirst(); Send(new ViewHostMsg_SelectionBoundsChanged(routing_id_, params)); } } UpdateCompositionInfo(false); } void RenderWidget::ForwardCompositorProto(const std::vector<uint8_t>& proto) { Send(new ViewHostMsg_ForwardCompositorProto(routing_id_, proto)); } // Check blink::WebTextInputType and ui::TextInputType is kept in sync. #define STATIC_ASSERT_WTIT_ENUM_MATCH(a, b) \ static_assert(int(blink::WebTextInputType##a) \ == int(ui::TEXT_INPUT_TYPE_##b), \ "mismatching enums: " #a) STATIC_ASSERT_WTIT_ENUM_MATCH(None, NONE); STATIC_ASSERT_WTIT_ENUM_MATCH(Text, TEXT); STATIC_ASSERT_WTIT_ENUM_MATCH(Password, PASSWORD); STATIC_ASSERT_WTIT_ENUM_MATCH(Search, SEARCH); STATIC_ASSERT_WTIT_ENUM_MATCH(Email, EMAIL); STATIC_ASSERT_WTIT_ENUM_MATCH(Number, NUMBER); STATIC_ASSERT_WTIT_ENUM_MATCH(Telephone, TELEPHONE); STATIC_ASSERT_WTIT_ENUM_MATCH(URL, URL); STATIC_ASSERT_WTIT_ENUM_MATCH(Date, DATE); STATIC_ASSERT_WTIT_ENUM_MATCH(DateTime, DATE_TIME); STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeLocal, DATE_TIME_LOCAL); STATIC_ASSERT_WTIT_ENUM_MATCH(Month, MONTH); STATIC_ASSERT_WTIT_ENUM_MATCH(Time, TIME); STATIC_ASSERT_WTIT_ENUM_MATCH(Week, WEEK); STATIC_ASSERT_WTIT_ENUM_MATCH(TextArea, TEXT_AREA); STATIC_ASSERT_WTIT_ENUM_MATCH(ContentEditable, CONTENT_EDITABLE); STATIC_ASSERT_WTIT_ENUM_MATCH(DateTimeField, DATE_TIME_FIELD); ui::TextInputType RenderWidget::WebKitToUiTextInputType( blink::WebTextInputType type) { // Check the type is in the range representable by ui::TextInputType. DCHECK_LE(type, static_cast<int>(ui::TEXT_INPUT_TYPE_MAX)) << "blink::WebTextInputType and ui::TextInputType not synchronized"; return static_cast<ui::TextInputType>(type); } ui::TextInputType RenderWidget::GetTextInputType() { if (webwidget_) return WebKitToUiTextInputType(webwidget_->textInputType()); return ui::TEXT_INPUT_TYPE_NONE; } void RenderWidget::UpdateCompositionInfo(bool should_update_range) { #if defined(OS_ANDROID) // TODO(yukawa): Start sending character bounds when the browser side // implementation becomes ready (crbug.com/424866). #else TRACE_EVENT0("renderer", "RenderWidget::UpdateCompositionInfo"); gfx::Range range = gfx::Range(); if (should_update_range) { GetCompositionRange(&range); } else { range = composition_range_; } std::vector<gfx::Rect> character_bounds; GetCompositionCharacterBounds(&character_bounds); if (!ShouldUpdateCompositionInfo(range, character_bounds)) return; composition_character_bounds_ = character_bounds; composition_range_ = range; Send(new InputHostMsg_ImeCompositionRangeChanged( routing_id(), composition_range_, composition_character_bounds_)); #endif } void RenderWidget::GetCompositionCharacterBounds( std::vector<gfx::Rect>* bounds) { DCHECK(bounds); bounds->clear(); } void RenderWidget::GetCompositionRange(gfx::Range* range) { size_t location, length; if (webwidget_->compositionRange(&location, &length)) { range->set_start(location); range->set_end(location + length); } else if (webwidget_->caretOrSelectionRange(&location, &length)) { range->set_start(location); range->set_end(location + length); } else { *range = gfx::Range::InvalidRange(); } } bool RenderWidget::ShouldUpdateCompositionInfo( const gfx::Range& range, const std::vector<gfx::Rect>& bounds) { if (composition_range_ != range) return true; if (bounds.size() != composition_character_bounds_.size()) return true; for (size_t i = 0; i < bounds.size(); ++i) { if (bounds[i] != composition_character_bounds_[i]) return true; } return false; } #if defined(OS_ANDROID) bool RenderWidget::DoesRecordFullLayer() const { return false; } #endif bool RenderWidget::CanComposeInline() { return true; } WebScreenInfo RenderWidget::screenInfo() { return screen_info_; } void RenderWidget::resetInputMethod() { ImeEventGuard guard(this); // If the last text input type is not None, then we should finish any // ongoing composition regardless of the new text input type. if (text_input_type_ != ui::TEXT_INPUT_TYPE_NONE) { // If a composition text exists, then we need to let the browser process // to cancel the input method's ongoing composition session. if (webwidget_->confirmComposition()) Send(new InputHostMsg_ImeCancelComposition(routing_id())); } UpdateCompositionInfo(true); } #if defined(OS_ANDROID) void RenderWidget::showUnhandledTapUIIfNeeded( const WebPoint& tapped_position, const WebNode& tapped_node, bool page_changed) { DCHECK(handling_input_event_); bool should_trigger = !page_changed && tapped_node.isTextNode() && !tapped_node.isContentEditable() && !tapped_node.isInsideFocusableElementOrARIAWidget(); if (should_trigger) { Send(new ViewHostMsg_ShowUnhandledTapUIIfNeeded(routing_id_, tapped_position.x, tapped_position.y)); } } #endif void RenderWidget::didHandleGestureEvent( const WebGestureEvent& event, bool event_cancelled) { #if defined(OS_ANDROID) || defined(USE_AURA) if (event_cancelled) return; if (event.type == WebInputEvent::GestureTap) { UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME); } else if (event.type == WebInputEvent::GestureLongPress) { DCHECK(webwidget_); if (webwidget_->textInputInfo().value.isEmpty()) UpdateTextInputState(NO_SHOW_IME, FROM_NON_IME); else UpdateTextInputState(SHOW_IME_IF_NEEDED, FROM_NON_IME); } #endif } void RenderWidget::didOverscroll( const blink::WebFloatSize& unusedDelta, const blink::WebFloatSize& accumulatedRootOverScroll, const blink::WebFloatPoint& position, const blink::WebFloatSize& velocity) { DidOverscrollParams params; params.accumulated_overscroll = gfx::Vector2dF( accumulatedRootOverScroll.width, accumulatedRootOverScroll.height); params.latest_overscroll_delta = gfx::Vector2dF(unusedDelta.width, unusedDelta.height); // TODO(sataya.m): don't negate velocity once http://crbug.com/499743 is // fixed. params.current_fling_velocity = gfx::Vector2dF(-velocity.width, -velocity.height); params.causal_event_viewport_point = gfx::PointF(position.x, position.y); // If we're currently handling an event, stash the overscroll data such that // it can be bundled in the event ack. if (handling_event_overscroll_) { handling_event_overscroll_->reset(new DidOverscrollParams(params)); return; } Send(new InputHostMsg_DidOverscroll(routing_id_, params)); } void RenderWidget::StartCompositor() { if (!is_hidden()) compositor_->setVisible(true); } void RenderWidget::SchedulePluginMove(const WebPluginGeometry& move) { size_t i = 0; for (; i < plugin_window_moves_.size(); ++i) { if (plugin_window_moves_[i].window == move.window) { if (move.rects_valid) { plugin_window_moves_[i] = move; } else { plugin_window_moves_[i].visible = move.visible; } break; } } if (i == plugin_window_moves_.size()) plugin_window_moves_.push_back(move); } void RenderWidget::CleanupWindowInPluginMoves(gfx::PluginWindowHandle window) { for (WebPluginGeometryVector::iterator i = plugin_window_moves_.begin(); i != plugin_window_moves_.end(); ++i) { if (i->window == window) { plugin_window_moves_.erase(i); break; } } } RenderWidgetCompositor* RenderWidget::compositor() const { return compositor_.get(); } bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) { return false; } bool RenderWidget::WillHandleGestureEvent( const blink::WebGestureEvent& event) { return false; } void RenderWidget::ObserveWheelEventAndResult( const blink::WebMouseWheelEvent& wheel_event, const gfx::Vector2dF& wheel_unused_delta, bool event_processed) { if (!compositor_deps_->IsElasticOverscrollEnabled()) return; cc::InputHandlerScrollResult scroll_result; scroll_result.did_scroll = event_processed; scroll_result.did_overscroll_root = !wheel_unused_delta.IsZero(); scroll_result.unused_scroll_delta = wheel_unused_delta; RenderThreadImpl* render_thread = RenderThreadImpl::current(); InputHandlerManager* input_handler_manager = render_thread ? render_thread->input_handler_manager() : NULL; if (input_handler_manager) { input_handler_manager->ObserveWheelEventAndResultOnMainThread( routing_id_, wheel_event, scroll_result); } } void RenderWidget::hasTouchEventHandlers(bool has_handlers) { if (render_widget_scheduling_state_) render_widget_scheduling_state_->SetHasTouchHandler(has_handlers); Send(new ViewHostMsg_HasTouchEventHandlers(routing_id_, has_handlers)); } // Check blink::WebTouchAction and blink::WebTouchActionAuto is kept in sync #define STATIC_ASSERT_WTI_ENUM_MATCH(a, b) \ static_assert(int(blink::WebTouchAction##a) == int(TOUCH_ACTION_##b), \ "mismatching enums: " #a) void RenderWidget::setTouchAction( blink::WebTouchAction web_touch_action) { // Ignore setTouchAction calls that result from synthetic touch events (eg. // when blink is emulating touch with mouse). if (handling_event_type_ != WebInputEvent::TouchStart) return; // Verify the same values are used by the types so we can cast between them. STATIC_ASSERT_WTI_ENUM_MATCH(None, NONE); STATIC_ASSERT_WTI_ENUM_MATCH(PanLeft, PAN_LEFT); STATIC_ASSERT_WTI_ENUM_MATCH(PanRight, PAN_RIGHT); STATIC_ASSERT_WTI_ENUM_MATCH(PanX, PAN_X); STATIC_ASSERT_WTI_ENUM_MATCH(PanUp, PAN_UP); STATIC_ASSERT_WTI_ENUM_MATCH(PanDown, PAN_DOWN); STATIC_ASSERT_WTI_ENUM_MATCH(PanY, PAN_Y); STATIC_ASSERT_WTI_ENUM_MATCH(Pan, PAN); STATIC_ASSERT_WTI_ENUM_MATCH(PinchZoom, PINCH_ZOOM); STATIC_ASSERT_WTI_ENUM_MATCH(Manipulation, MANIPULATION); STATIC_ASSERT_WTI_ENUM_MATCH(DoubleTapZoom, DOUBLE_TAP_ZOOM); STATIC_ASSERT_WTI_ENUM_MATCH(Auto, AUTO); content::TouchAction content_touch_action = static_cast<content::TouchAction>(web_touch_action); Send(new InputHostMsg_SetTouchAction(routing_id_, content_touch_action)); } void RenderWidget::didUpdateTextOfFocusedElementByNonUserInput() { #if defined(OS_ANDROID) text_field_is_dirty_ = true; #endif } bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const { return true; } scoped_ptr<WebGraphicsContext3DCommandBufferImpl> RenderWidget::CreateGraphicsContext3D(bool compositor) { if (!webwidget_) return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>(); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableGpuCompositing)) return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>(); if (!RenderThreadImpl::current()) return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>(); CauseForGpuLaunch cause = CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE; scoped_refptr<GpuChannelHost> gpu_channel_host( RenderThreadImpl::current()->EstablishGpuChannelSync(cause)); if (!gpu_channel_host.get()) return scoped_ptr<WebGraphicsContext3DCommandBufferImpl>(); // Explicitly disable antialiasing for the compositor. As of the time of // this writing, the only platform that supported antialiasing for the // compositor was Mac OS X, because the on-screen OpenGL context creation // code paths on Windows and Linux didn't yet have multisampling support. // Mac OS X essentially always behaves as though it's rendering offscreen. // Multisampling has a heavy cost especially on devices with relatively low // fill rate like most notebooks, and the Mac implementation would need to // be optimized to resolve directly into the IOSurface shared between the // GPU and browser processes. For these reasons and to avoid platform // disparities we explicitly disable antialiasing. blink::WebGraphicsContext3D::Attributes attributes; attributes.antialias = false; attributes.shareResources = true; attributes.noAutomaticFlushes = true; attributes.depth = false; attributes.stencil = false; bool lose_context_when_out_of_memory = true; WebGraphicsContext3DCommandBufferImpl::SharedMemoryLimits limits; #if defined(OS_ANDROID) bool using_synchronous_compositing = SynchronousCompositorFactory::GetInstance() || base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kIPCSyncCompositing); // If we raster too fast we become upload bound, and pending // uploads consume memory. For maximum upload throughput, we would // want to allow for upload_throughput * pipeline_time of pending // uploads, after which we are just wasting memory. Since we don't // know our upload throughput yet, this just caps our memory usage. // Synchronous compositor uses half because synchronous compositor // pipeline is only one frame deep. But twice of half for low end // because 16bit texture is not supported. size_t divider = using_synchronous_compositing ? 2 : 1; if (base::SysInfo::IsLowEndDevice()) divider = 6; // For reference Nexus10 can upload 1MB in about 2.5ms. const double max_mb_uploaded_per_ms = 2.0 / (5 * divider); // Deadline to draw a frame to achieve 60 frames per second. const size_t kMillisecondsPerFrame = 16; // Assuming a two frame deep pipeline between the CPU and the GPU. size_t max_transfer_buffer_usage_mb = static_cast<size_t>(2 * kMillisecondsPerFrame * max_mb_uploaded_per_ms); static const size_t kBytesPerMegabyte = 1024 * 1024; // We keep the MappedMemoryReclaimLimit the same as the upload limit // to avoid unnecessarily stalling the compositor thread. limits.mapped_memory_reclaim_limit = max_transfer_buffer_usage_mb * kBytesPerMegabyte; #endif if (compositor) { limits.command_buffer_size = 64 * 1024; limits.start_transfer_buffer_size = 64 * 1024; limits.min_transfer_buffer_size = 64 * 1024; } scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context( new WebGraphicsContext3DCommandBufferImpl( 0, GetURLForGraphicsContext3D(), gpu_channel_host.get(), attributes, lose_context_when_out_of_memory, limits, NULL)); return context.Pass(); } void RenderWidget::RegisterRenderFrameProxy(RenderFrameProxy* proxy) { render_frame_proxies_.AddObserver(proxy); } void RenderWidget::UnregisterRenderFrameProxy(RenderFrameProxy* proxy) { render_frame_proxies_.RemoveObserver(proxy); } void RenderWidget::RegisterRenderFrame(RenderFrameImpl* frame) { render_frames_.AddObserver(frame); } void RenderWidget::UnregisterRenderFrame(RenderFrameImpl* frame) { render_frames_.RemoveObserver(frame); } #if defined(VIDEO_HOLE) void RenderWidget::RegisterVideoHoleFrame(RenderFrameImpl* frame) { video_hole_frames_.AddObserver(frame); } void RenderWidget::UnregisterVideoHoleFrame(RenderFrameImpl* frame) { video_hole_frames_.RemoveObserver(frame); } #endif // defined(VIDEO_HOLE) } // namespace content
Workday/OpenFrame
content/renderer/render_widget.cc
C++
bsd-3-clause
91,088
from setuptools import setup, find_packages setup( name='django-facebook-comments', version=__import__('facebook_comments').__version__, description='Django implementation for Facebook Graph API Comments', long_description=open('README.md').read(), author='ramusus', author_email='ramusus@gmail.com', url='https://github.com/ramusus/django-facebook-comments', download_url='http://pypi.python.org/pypi/django-facebook-comments', license='BSD', packages=find_packages(), include_package_data=True, zip_safe=False, # because we're including media that Django needs install_requires=[ 'django-facebook-api>=0.5.0', 'django-facebook-users>=0.3.0', 'django-m2m-history>=0.1.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
ramusus/django-facebook-comments
setup.py
Python
bsd-3-clause
1,122
#include "z3dvolumesource.h" #include "zstack.hxx" #include "zstackdoc.h" #include "tz_stack_attribute.h" #include "z3dgpuinfo.h" #include "zsparseobject.h" #include "neutubeconfig.h" #include "zsparsestack.h" const size_t Z3DVolumeSource::m_nChannelSupport = 10; Z3DVolumeSource::Z3DVolumeSource(ZStackDoc *doc, size_t maxVoxelNumber) : Z3DProcessor() , m_stackOutputPort("Stack") , m_xScale("X Scale", 1.0f, 0.1f, 50.f) , m_yScale("Y Scale", 1.0f, 0.1f, 50.f) , m_zScale("Z Scale", 1.0f, 0.1f, 500.f) , m_isVolumeDownsampled("Volume Is Downsampled", false) , m_isSubVolume("Is Subvolume", false) , m_zoomInViewSize("Zoom In View Size", 256, 128, 512) , m_doc(doc) , m_widgetsGroup(NULL) { if (maxVoxelNumber == 0) { int currentAvailableTexMem = Z3DGpuInfoInstance.getAvailableTextureMemory(); if (currentAvailableTexMem != -1 && currentAvailableTexMem <= 256000) m_maxVoxelNumber = 256 * 256 * 256 * 2; else m_maxVoxelNumber = 512 * 512 * 512 * 1; } else { m_maxVoxelNumber = maxVoxelNumber; } for (size_t i=0; i<m_nChannelSupport; i++) { QString name = QString("Volume%1").arg(i+1); m_outputPorts.push_back(new Z3DOutputPort<Z3DVolume>(name)); addPort(m_outputPorts[i]); } addPort(m_stackOutputPort); loadData(); addParameter(m_xScale); addParameter(m_yScale); addParameter(m_zScale); m_isVolumeDownsampled.setEnabled(false); addParameter(m_isVolumeDownsampled); m_isSubVolume.setEnabled(false); addParameter(m_isSubVolume); m_zoomInViewSize.setTracking(false); m_zoomInViewSize.setSingleStep(32); addParameter(m_zoomInViewSize); connect(&m_xScale, SIGNAL(valueChanged()), this, SLOT(changeXScale())); connect(&m_yScale, SIGNAL(valueChanged()), this, SLOT(changeYScale())); connect(&m_zScale, SIGNAL(valueChanged()), this, SLOT(changeZScale())); connect(&m_zoomInViewSize, SIGNAL(valueChanged()), this, SLOT(changeZoomInViewSize())); } Z3DVolumeSource::~Z3DVolumeSource() { for (size_t i=0; i<m_outputPorts.size(); i++) delete m_outputPorts[i]; } void Z3DVolumeSource::loadData() { if (m_doc != NULL) { if (m_doc->hasStackData()) { if (m_doc->hasPlayer(ZStackObjectRole::ROLE_3DPAINT)) { readVolumesWithObject(); } else { readVolumes(); } } else if (m_doc->hasStack() && m_doc->hasSparseObject()) { if (m_doc->hasPlayer(ZStackObjectRole::ROLE_3DPAINT)) { readSparseVolumeWithObject(); } else { readSparseVolume(); } } else if (m_doc->hasStack()) { if (m_doc->hasSparseStack()) { readSparseStack(); } } } } void Z3DVolumeSource::process(Z3DEye) {} void Z3DVolumeSource::initialize() { Z3DProcessor::initialize(); sendData(); CHECK_GL_ERROR; } void Z3DVolumeSource::deinitialize() { clearVolume(); clearZoomInVolume(); CHECK_GL_ERROR; Z3DProcessor::deinitialize(); } void Z3DVolumeSource::readVolumes() { if (m_doc == NULL) { return; } clearVolume(); int nchannel = m_doc->hasStackData() ? m_doc->getStack()->channelNumber() : 0; if (nchannel > 0) { for (int i=0; i<nchannel; i++) { Stack *stack = m_doc->getStack()->c_stack(i); //Under deveopment ZPoint offset(m_doc->getStack()->getOffset().getX() * m_xScale.get(), m_doc->getStack()->getOffset().getY() * m_yScale.get(), m_doc->getStack()->getOffset().getZ() * m_zScale.get()); if (m_doc->getStack()->getVoxelNumber() * nchannel > m_maxVoxelNumber) { //Downsample big stack m_isVolumeDownsampled.set(true); double scale = std::sqrt((m_maxVoxelNumber*1.0) / (m_doc->getStack()->getVoxelNumber() * nchannel)); int height = (int)(stack->height * scale); int width = (int)(stack->width * scale); int depth = stack->depth; double widthScale = 1.0; double heightScale = 1.0; double depthScale = 1.0; int maxTextureSize = 100; if (stack->depth > 1) maxTextureSize = Z3DGpuInfoInstance.getMax3DTextureSize(); else maxTextureSize = Z3DGpuInfoInstance.getMaxTextureSize(); if (maxTextureSize > 1024) { maxTextureSize = 1024; } if (height > maxTextureSize) { heightScale = (double)maxTextureSize / height; height = std::floor(height * heightScale); } if (width > maxTextureSize) { widthScale = (double)maxTextureSize / width; width = std::floor(width * widthScale); } if (depth > maxTextureSize) { depthScale = (double)maxTextureSize / depth; depth = std::floor(depth * depthScale); } widthScale *= scale; heightScale *= scale; Stack *stack2 = Resize_Stack(stack, width, height, depth); Translate_Stack(stack2, GREY, 1); if (m_doc->getStack()->isBinary()) { size_t volume = Stack_Voxel_Number(stack2); for (size_t voxelIndex = 0; voxelIndex < volume; ++voxelIndex) { if (stack2->array[voxelIndex] == 1) { stack2->array[voxelIndex] = 255; } } } Z3DVolume *vh = new Z3DVolume( stack2, glm::vec3(1.f/widthScale, 1.f/heightScale, 1.f/depthScale), glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()), glm::vec3(offset.x(), offset.y(), offset.z()) /*glm::vec3(.0)*/); m_volumes.push_back(vh); } else { //small stack double widthScale = 1.0; double heightScale = 1.0; double depthScale = 1.0; int height = C_Stack::height(stack); int width = C_Stack::width(stack); int depth = C_Stack::depth(stack); int maxTextureSize = 100; if (stack->depth > 1) maxTextureSize = Z3DGpuInfoInstance.getMax3DTextureSize(); else maxTextureSize = Z3DGpuInfoInstance.getMaxTextureSize(); if (height > maxTextureSize) { heightScale = (double)maxTextureSize / height; height = std::floor(height * heightScale); } if (width > maxTextureSize) { widthScale = (double)maxTextureSize / width; width = std::floor(width * widthScale); } if (depth > maxTextureSize) { depthScale = (double)maxTextureSize / depth; depth = std::floor(depth * depthScale); } Stack *stack2; if (widthScale != 1.0 || heightScale != 1.0 || depthScale != 1.0) { stack2 = C_Stack::resize(stack, width, height, depth); } else { stack2 = Copy_Stack(stack); } if (stack->kind == GREY && m_doc->getStack()->isBinary()) { size_t volume = m_doc->getStack()->getVoxelNumber(); for (size_t voxelIndex = 0; voxelIndex < volume; ++voxelIndex) { if (stack2->array[voxelIndex] == 1) { stack2->array[voxelIndex] = 255; } } } Translate_Stack(stack2, GREY, 1); Z3DVolume *vh = new Z3DVolume(stack2, glm::vec3(1.f/widthScale, 1.f/heightScale, 1.f/depthScale), glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()), glm::vec3(offset.x(), offset.y(), offset.z())); m_volumes.push_back(vh); } } //for each cannel std::vector<ZVec3Parameter*>& chCols = m_doc->getStack()->channelColors(); for (int i=0; i<nchannel; i++) { m_volumes[i]->setVolColor(chCols[i]->get()); } } } void Z3DVolumeSource::readSparseStack() { if (m_doc == NULL) { return; } if (!m_doc->hasSparseStack()) { return; } ZSparseStack *spStack = m_doc->getSparseStack(); if (spStack->getBoundBox().isEmpty()) { return; } const ZStack *stackData = spStack->getStack(); if (stackData == NULL) { return; } clearVolume(); int nchannel = stackData->channelNumber(); const ZIntPoint dsIntv = spStack->getDownsampleInterval(); double widthScale = 1.0; double heightScale = 1.0; double depthScale = 1.0; if (dsIntv.getX() > 0 || dsIntv.getY() > 0 || dsIntv.getZ() > 0) { widthScale /= dsIntv.getX() + 1; heightScale /= dsIntv.getY() + 1; depthScale /= dsIntv.getZ() + 1; } int width = stackData->width(); int height = stackData->height(); int depth = stackData->depth(); std::vector<Stack*> stackArray; if (nchannel > 0) { int maxTextureSize = 100; if (stackData->depth() > 1) { maxTextureSize = Z3DGpuInfoInstance.getMax3DTextureSize(); } else { maxTextureSize = Z3DGpuInfoInstance.getMaxTextureSize(); } if (height > maxTextureSize) { double alpha = (double) maxTextureSize / height; heightScale *= alpha; height = (int) (height * alpha); } if (width > maxTextureSize) { double alpha = (double) maxTextureSize / width; widthScale *= alpha; width = (int) (width * alpha); } if (depth > maxTextureSize) { double alpha = (double) maxTextureSize / depth; depthScale *= alpha; depth = (int) (depth * alpha); } ZIntPoint dsIntv2 = misc::getDsIntvFor3DVolume( ZIntCuboid(0, 0, 0, width - 1, height - 1, depth - 1)); width /= dsIntv2.getX() + 1; height /= dsIntv2.getY() + 1; depth /= dsIntv2.getZ() + 1; /* ZIntPoint misc::getDsIntvFor3DVolume(const ZIntCuboid &box); size_t volume = (size_t) width * height *depth * nchannel; if (volume > m_maxVoxelNumber) { //Downsample big stack //m_isVolumeDownsampled.set(true); double scale = std::sqrt((double) (m_maxVoxelNumber) / volume); height = (int)(height * scale); width = (int)(width * scale); widthScale *= scale; heightScale *= scale; } */ for (int i=0; i<nchannel; i++) { const Stack *stack = stackData->c_stack(i); Stack *stack2 = NULL; if (C_Stack::width(stack) != width || C_Stack::height(stack) != height || C_Stack::depth(stack) != depth) { m_isVolumeDownsampled.set(true); int xIntv = C_Stack::width(stack) / width; int yIntv = C_Stack::height(stack) / height; int zIntv = C_Stack::depth(stack) / depth; stack2 = Downsample_Stack_Max(stack, xIntv, yIntv, zIntv, NULL); widthScale = 1.0 / ((xIntv + 1) * (dsIntv.getX() + 1)); heightScale = 1.0 / ((yIntv + 1) * (dsIntv.getY() + 1)); depthScale = 1.0 / ((zIntv + 1) * (dsIntv.getZ() + 1)); // stack2 = Resize_Stack(stack, width, height, depth); } else { stack2 = C_Stack::clone(stack); } Translate_Stack(stack2, GREY, 1); if (C_Stack::isBinary(stack2)) { size_t volume = C_Stack::voxelNumber(stack2); for (size_t voxelIndex = 0; voxelIndex < volume; ++voxelIndex) { if (stack2->array[voxelIndex] == 1) { stack2->array[voxelIndex] = 255; } } } stackArray.push_back(stack2); } //for each cannel /**********************/ int offset[3]; offset[0] = -stackData->getOffset().getX() * (dsIntv.getX() + 1); offset[1] = -stackData->getOffset().getY() * (dsIntv.getY() + 1); offset[2] = -stackData->getOffset().getZ() * (dsIntv.getZ() + 1); QList<ZDocPlayer*> playerList = m_doc->getPlayerList(ZStackObjectRole::ROLE_3DPAINT); foreach (const ZDocPlayer *player, playerList) { //player->paintStack(colorStack); if (player->getLabel() > 0 && player->getLabel() < 10) { if (player->getLabel() >= (int) stackArray.size()) { stackArray.push_back(C_Stack::make( GREY, stackData->width(), stackData->height(), stackData->depth())); C_Stack::setZero(stackArray.back()); //stackArray.resize(stackArray.size() + 1); } player->labelStack(stackArray[player->getLabel()], offset, 255, dsIntv.getX(), dsIntv.getY(), dsIntv.getZ()); } } for (size_t i = 0; i < stackArray.size(); ++i) { Z3DVolume *vh = new Z3DVolume( stackArray[i], glm::vec3(1.f/widthScale, 1.f/heightScale, 1.f/depthScale), glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()), glm::vec3(-offset[0] * m_xScale.get(), -offset[1] * m_yScale.get(), -offset[2] * m_zScale.get()) /*glm::vec3(.0)*/); m_volumes.push_back(vh); } m_volumes[0]->setVolColor(glm::vec3(1.f,1.f,1.f)); ZLabelColorTable colorTable; for (size_t i = 1; i < stackArray.size(); ++i) { QColor color = colorTable.getColor(i); m_volumes[i]->setVolColor( glm::vec3(color.redF(), color.greenF(), color.blueF())); } /**********************/ } } void Z3DVolumeSource::readVolumesWithObject() { if (m_doc == NULL) { return; } clearVolume(); std::vector<Stack*> stackArray; //int nchannel = 1; stackArray.push_back(C_Stack::clone(m_doc->getStack()->c_stack(0))); #if 0 ZStack *colorStack = new ZStack(GREY, m_doc->getStack()->width(), m_doc->getStack()->height(), m_doc->getStack()->depth(), 3); colorStack->setOffset(m_doc->getStackOffset()); colorStack->initChannelColors(); C_Stack::copyValue(m_doc->getStack()->c_stack(0), colorStack->c_stack(0)); colorStack->setChannelColor(0, 1, 1, 1); #endif int offset[3]; offset[0] = m_doc->getStackOffset().getX(); offset[1] = m_doc->getStackOffset().getY(); offset[2] = m_doc->getStackOffset().getZ(); ZLabelColorTable colorTable; std::vector<QColor> colorArray(m_nChannelSupport); colorArray[0] = QColor(255, 255, 255); for (size_t i = 1; i < m_nChannelSupport; ++i) { colorArray[i] = colorTable.getColor(i); } #if 0 C_Stack::setZero(colorStack->c_stack(1)); QColor color = colorTable.getColor(1); colorStack->setChannelColor(1, color.redF(), color.greenF(), color.blueF()); C_Stack::setZero(colorStack->c_stack(2)); color = colorTable.getColor(2); colorStack->setChannelColor(2, color.redF(), color.greenF(), color.blueF()); #endif //C_Stack::copyValue(m_doc->getStack()->c_stack(0), // colorStack->c_stack(1)); //C_Stack::copyValue(m_doc->getStack()->c_stack(0), // colorStack->c_stack(2)); QList<ZDocPlayer*> playerList = m_doc->getPlayerList(ZStackObjectRole::ROLE_3DPAINT); foreach (const ZDocPlayer *player, playerList) { //player->paintStack(colorStack); if (player->getLabel() > 0 && player->getLabel() < 10) { if (player->getLabel() >= (int) stackArray.size()) { stackArray.push_back(C_Stack::make( GREY, m_doc->getStack()->width(), m_doc->getStack()->height(), m_doc->getStack()->depth())); C_Stack::setZero(stackArray.back()); //stackArray.resize(stackArray.size() + 1); } player->labelStack(stackArray[player->getLabel()], offset, 255); //player->labelStack(colorStack->c_stack(player->getLabel()), offset, 255); } } /* QList<ZObject3d*> &objList = m_doc->getObj3dList(); foreach(ZObject3d *obj, objList) { obj->drawStack(colorStack); } */ int nchannel = stackArray.size(); if (nchannel > 0) { for (int i=0; i<nchannel; i++) { //Stack *stack = colorStack->c_stack(i); Stack *stack = stackArray[i]; //Under deveopment ZPoint offset = ZPoint( m_doc->getStack()->getOffset().getX() * m_xScale.get(), m_doc->getStack()->getOffset().getY() * m_yScale.get(), m_doc->getStack()->getOffset().getZ() * m_zScale.get()); if (m_doc->getStack()->getVoxelNumber() * nchannel > m_maxVoxelNumber) { //Downsample big stack m_isVolumeDownsampled.set(true); double scale = std::sqrt((m_maxVoxelNumber*1.0) / (m_doc->getStack()->getVoxelNumber() * nchannel)); int height = (int)(stack->height * scale); int width = (int)(stack->width * scale); int depth = stack->depth; double widthScale = 1.0; double heightScale = 1.0; double depthScale = 1.0; int maxTextureSize = 100; if (stack->depth > 1) maxTextureSize = Z3DGpuInfoInstance.getMax3DTextureSize(); else maxTextureSize = Z3DGpuInfoInstance.getMaxTextureSize(); if (height > maxTextureSize) { heightScale = (double)maxTextureSize / height; height = std::floor(height * heightScale); } if (width > maxTextureSize) { widthScale = (double)maxTextureSize / width; width = std::floor(width * widthScale); } if (depth > maxTextureSize) { depthScale = (double)maxTextureSize / depth; depth = std::floor(depth * depthScale); } widthScale *= scale; heightScale *= scale; Stack *stack2 = Resize_Stack(stack, width, height, depth); Translate_Stack(stack2, GREY, 1); if (m_doc->getStack()->isBinary()) { size_t volume = Stack_Voxel_Number(stack2); for (size_t voxelIndex = 0; voxelIndex < volume; ++voxelIndex) { if (stack2->array[voxelIndex] == 1) { stack2->array[voxelIndex] = 255; } } } Z3DVolume *vh = new Z3DVolume( stack2, glm::vec3(1.f/widthScale, 1.f/heightScale, 1.f/depthScale), glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()), glm::vec3(offset.x(), offset.y(), offset.z()) /*glm::vec3(.0)*/); m_volumes.push_back(vh); } else { //small stack double widthScale = 1.0; double heightScale = 1.0; double depthScale = 1.0; int height = C_Stack::height(stack); int width = C_Stack::width(stack); int depth = C_Stack::depth(stack); int maxTextureSize = 100; if (stack->depth > 1) maxTextureSize = Z3DGpuInfoInstance.getMax3DTextureSize(); else maxTextureSize = Z3DGpuInfoInstance.getMaxTextureSize(); if (height > maxTextureSize) { heightScale = (double)maxTextureSize / height; height = std::floor(height * heightScale); } if (width > maxTextureSize) { widthScale = (double)maxTextureSize / width; width = std::floor(width * widthScale); } if (depth > maxTextureSize) { depthScale = (double)maxTextureSize / depth; depth = std::floor(depth * depthScale); } Stack *stack2; if (widthScale != 1.0 || heightScale != 1.0) stack2 = C_Stack::resize(stack, width, height, depth); else stack2 = Copy_Stack(stack); if (stack->kind == GREY && m_doc->getStack()->isBinary()) { size_t volume = m_doc->getStack()->getVoxelNumber(); for (size_t voxelIndex = 0; voxelIndex < volume; ++voxelIndex) { if (stack2->array[voxelIndex] == 1) { stack2->array[voxelIndex] = 255; } } } Translate_Stack(stack2, GREY, 1); Z3DVolume *vh = new Z3DVolume(stack2, glm::vec3(1.f/widthScale, 1.f/heightScale, 1.f/depthScale), glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()), glm::vec3(offset.x(), offset.y(), offset.z())); m_volumes.push_back(vh); } } //for each cannel //std::vector<ZVec3Parameter*>& chCols = colorStack->channelColors(); for (int i=0; i<nchannel; i++) { QColor &color = colorArray[i]; m_volumes[i]->setVolColor(glm::vec3(color.redF(), color.greenF(), color.blueF())); //m_volumes[i]->setVolColor(chCols[i]->get()); } } for (std::vector<Stack*>::iterator iter = stackArray.begin(); iter != stackArray.end(); ++iter) { C_Stack::kill(*iter); } //delete colorStack; } void Z3DVolumeSource::readSparseVolume() { if (m_doc == NULL) { return; } if (!m_doc->hasStack() || m_doc->getSparseObjectList().isEmpty()) { return; } clearVolume(); //int nchannel = 1; ZSparseObject obj = *(m_doc->getSparseObjectList().front()); QColor color = obj.getColor(); int nchannel = 1; if (color.green() > 0) { nchannel = 2; } if (color.blue() > 0) { nchannel = 3; } ZIntPoint dsIntv = misc::getDsIntvFor3DVolume(m_doc->getStack()->getBoundBox()); int xIntv = dsIntv.getX(); int yIntv = dsIntv.getY(); int zIntv = dsIntv.getZ(); /* int xIntv = 0; int yIntv = 0; int zIntv = 0; if (m_doc->getStack()->getVoxelNumber() * nchannel > m_maxVoxelNumber) { //Downsample big stack //m_isVolumeDownsampled.set(true); xIntv = 1; yIntv = 1; zIntv = 1; } else if (m_doc->getStack()->getVoxelNumber() * nchannel > m_maxVoxelNumber * 3) { xIntv = 2; yIntv = 2; zIntv = 2; } */ int height = m_doc->getStack()->width(); int width = m_doc->getStack()->height(); int depth = m_doc->getStack()->depth(); int maxTextureSize = 100; if (depth > 1) { maxTextureSize = Z3DGpuInfoInstance.getMax3DTextureSize(); } else { maxTextureSize = Z3DGpuInfoInstance.getMaxTextureSize(); } if (height > maxTextureSize) { yIntv += height / maxTextureSize; } if (width > maxTextureSize) { xIntv += width / maxTextureSize; } if (depth > maxTextureSize) { zIntv += depth / maxTextureSize; } obj.downsampleMax(xIntv, yIntv, zIntv); int offset[3]; int rgb[3]; rgb[0] = color.red(); rgb[1] = color.green(); rgb[2] = color.blue(); for (int i = 0; i < nchannel; ++i) { Stack *stack2 = obj.toStack(offset, rgb[i]); ZPoint finalOffset; finalOffset.set(offset[0]* m_xScale.get() * (xIntv + 1), offset[1] * m_yScale.get() * (yIntv + 1), offset[2] * m_zScale.get() * (zIntv + 1)); #ifdef _DEBUG_2 C_Stack::write(GET_TEST_DATA_DIR + "/test.tif", stack2); #endif Z3DVolume *vh = new Z3DVolume( stack2, glm::vec3(xIntv + 1, yIntv + 1, zIntv + 1), glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()), glm::vec3(finalOffset.x(), finalOffset.y(), finalOffset.z())); m_volumes.push_back(vh); } m_volumes[0]->setVolColor(glm::vec3(1.f,0.f,0.f)); if (m_volumes.size() > 1) { m_volumes[1]->setVolColor(glm::vec3(0.f,1.f,0.f)); } if (m_volumes.size() > 2) { m_volumes[2]->setVolColor(glm::vec3(0.f,0.f,1.f)); } } void Z3DVolumeSource::readSparseVolumeWithObject() { if (m_doc == NULL) { return; } if (!m_doc->hasStack() || m_doc->getSparseObjectList().isEmpty()) { return; } clearVolume(); //int nchannel = 1; ZSparseObject obj = *(m_doc->getSparseObjectList().front()); QColor color = obj.getColor(); int nchannel = 3; ZIntPoint dsIntv = misc::getDsIntvFor3DVolume(m_doc->getStack()->getBoundBox()); int xIntv = dsIntv.getX(); int yIntv = dsIntv.getY(); int zIntv = dsIntv.getZ(); /* if (m_doc->getStack()->getVoxelNumber() * nchannel > m_maxVoxelNumber) { //Downsample big stack //m_isVolumeDownsampled.set(true); xIntv = 1; yIntv = 1; zIntv = 1; } */ int height = m_doc->getStack()->width(); int width = m_doc->getStack()->height(); int depth = m_doc->getStack()->depth(); int maxTextureSize = 100; if (depth > 1) { maxTextureSize = Z3DGpuInfoInstance.getMax3DTextureSize(); } else { maxTextureSize = Z3DGpuInfoInstance.getMaxTextureSize(); } if (height > maxTextureSize) { yIntv += height / maxTextureSize; } if (width > maxTextureSize) { xIntv += width / maxTextureSize; } if (depth > maxTextureSize) { zIntv += depth / maxTextureSize; } obj.downsampleMax(xIntv, yIntv, zIntv); int offset[3]; int rgb[3]; rgb[0] = color.red(); rgb[1] = color.green(); rgb[2] = color.blue(); std::vector<Stack*> stackArray(3); for (int i = 0; i < nchannel; ++i) { stackArray[i] = obj.toStack(offset, rgb[i]); ZPoint finalOffset; finalOffset.set(offset[0]* m_xScale.get() * (xIntv + 1), offset[1] * m_yScale.get() * (yIntv + 1), offset[2] * m_zScale.get() * (zIntv + 1)); #ifdef _DEBUG_2 C_Stack::write(GET_TEST_DATA_DIR + "/test.tif", stack2); #endif Z3DVolume *vh = new Z3DVolume( stackArray[i], glm::vec3(xIntv + 1, yIntv + 1, zIntv + 1), glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()), glm::vec3(finalOffset.x(), finalOffset.y(), finalOffset.z())); m_volumes.push_back(vh); } int originalOffset[3]; originalOffset[0] = offset[0] * (xIntv + 1); originalOffset[1] = offset[1] * (yIntv + 1); originalOffset[2] = offset[2] * (zIntv + 1); QList<ZObject3d*>objList = m_doc->getObj3dList(); foreach(ZObject3d *obj, objList) { obj->drawStack(stackArray, originalOffset, xIntv, yIntv, zIntv); } m_volumes[0]->setVolColor(glm::vec3(1.f,0.f,0.f)); if (m_volumes.size() > 1) { m_volumes[1]->setVolColor(glm::vec3(0.f,1.f,0.f)); } if (m_volumes.size() > 2) { m_volumes[2]->setVolColor(glm::vec3(0.f,0.f,1.f)); } } void Z3DVolumeSource::readSubVolumes(int left, int top, int front, int width, int height, int depth) { if (m_doc == NULL) { return; } clearZoomInVolume(); int nchannel = m_doc->hasStackData() ? m_doc->getStack()->channelNumber() : 0; if (nchannel > 0) { glm::vec3 scaleSpacing = glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get()); glm::vec3 downsampleSpacing = glm::vec3(1.f, 1.f, 1.f); glm::vec3 offset = glm::vec3(left, top, front) * scaleSpacing + getVolume(0)->getOffset(); for (int i=0; i<nchannel; i++) { Stack *stack = m_doc->getStack()->c_stack(i); Stack *subStack = Crop_Stack(stack, left, top, front, width, height, depth, NULL); if (subStack->kind == GREY) { Z3DVolume *vh = new Z3DVolume(subStack, downsampleSpacing, scaleSpacing, offset, getVolume(0)->getPhysicalToWorldMatrix()); vh->setParentVolumeDimensions(glm::uvec3(stack->width, stack->height, stack->depth)); vh->setParentVolumeOffset(getVolume(0)->getOffset()); m_zoomInVolumes.push_back(vh); } else { Translate_Stack(subStack, GREY, 1); Z3DVolume *vh = new Z3DVolume(subStack, downsampleSpacing, scaleSpacing, offset, getVolume(0)->getPhysicalToWorldMatrix()); vh->setParentVolumeDimensions(glm::uvec3(stack->width, stack->height, stack->depth)); vh->setParentVolumeOffset(getVolume(0)->getOffset()); m_zoomInVolumes.push_back(vh); } } std::vector<ZVec3Parameter*>& chCols = m_doc->getStack()->channelColors(); for (int i=0; i<nchannel; i++) { m_zoomInVolumes[i]->setVolColor(chCols[i]->get()); } } } void Z3DVolumeSource::sendData() { for (size_t i=0; i<m_volumes.size(); i++) { if (i < m_nChannelSupport) { m_outputPorts[i]->setData(m_volumes[i], false); } } for (size_t i=m_volumes.size(); i<m_outputPorts.size(); i++) { m_outputPorts[i]->setData(NULL); } if (m_volumes.size() > 0) { m_stackOutputPort.setData(m_doc->getStack()); } } void Z3DVolumeSource::sendZoomInVolumeData() { if (m_doc == NULL) { return; } for (size_t i=0; i<m_zoomInVolumes.size(); i++) { if (i < m_nChannelSupport) { m_outputPorts[i]->setData(m_zoomInVolumes[i], false); } } for (size_t i=m_zoomInVolumes.size(); i<m_outputPorts.size(); i++) { m_outputPorts[i]->setData(NULL); } if (m_volumes.size() > 0) { m_stackOutputPort.setData(m_doc->getStack()); } } void Z3DVolumeSource::changeXScale() { if (m_volumes.empty()) return; for (size_t i=0; i<m_volumes.size(); i++) { m_volumes[i]->setScaleSpacing(glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get())); } for (size_t i=0; i<m_zoomInVolumes.size(); i++) { m_zoomInVolumes[i]->setScaleSpacing(glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get())); } emit xScaleChanged(); } void Z3DVolumeSource::changeYScale() { if (m_volumes.empty()) return; for (size_t i=0; i<m_volumes.size(); i++) { m_volumes[i]->setScaleSpacing(glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get())); } for (size_t i=0; i<m_zoomInVolumes.size(); i++) { m_zoomInVolumes[i]->setScaleSpacing(glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get())); } emit yScaleChanged(); } void Z3DVolumeSource::changeZScale() { if (m_volumes.empty()) return; for (size_t i=0; i<m_volumes.size(); i++) { m_volumes[i]->setScaleSpacing(glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get())); } for (size_t i=0; i<m_zoomInVolumes.size(); i++) { m_zoomInVolumes[i]->setScaleSpacing(glm::vec3(m_xScale.get(), m_yScale.get(), m_zScale.get())); } emit zScaleChanged(); } void Z3DVolumeSource::changeZoomInViewSize() { if (m_zoomInVolumes.empty()) return; exitZoomInView(); openZoomInView(m_zoomInPos); } void Z3DVolumeSource::exitZoomInView() { if (m_zoomInVolumes.empty()) return; // copy transform matrix from sub volume, in case it is changed for (size_t i=0; i<m_volumes.size(); i++) { m_volumes[i]->setPhysicalToWorldMatrix(m_zoomInVolumes[i]->getPhysicalToWorldMatrix()); } clearZoomInVolume(); sendData(); m_isSubVolume.set(false); m_isVolumeDownsampled.set(true); } void Z3DVolumeSource::clearVolume() { for (size_t i=0; i<m_volumes.size(); i++) { delete m_volumes[i]; } m_volumes.clear(); } void Z3DVolumeSource::clearZoomInVolume() { for (size_t i=0; i<m_zoomInVolumes.size(); i++) { delete m_zoomInVolumes[i]; } m_zoomInVolumes.clear(); } void Z3DVolumeSource::reloadVolume() { if (!isInitialized()) return; clearVolume(); clearZoomInVolume(); loadData(); sendData(); } bool Z3DVolumeSource::openZoomInView(const glm::ivec3& volPos) { if (m_doc == NULL) { return false; } if (!m_isVolumeDownsampled.get()) return false; if (!m_doc->hasStackData()) return false; if (!volumeNeedDownsample()) return false; if (getVolume(0) == NULL) return false; glm::ivec3 voldim = glm::ivec3(getVolume(0)->getCubeSize()); if (!(volPos[0] >= 0 && volPos[0] < voldim.x && volPos[1] >= 0 && volPos[1] < voldim.y && volPos[2] >= 0 && volPos[2] < voldim.z)) { return false; } glm::vec3 offset = getVolume(0)->getOffset(); m_zoomInPos = volPos; if (m_zoomInViewSize.get() % 2 != 0) m_zoomInViewSize.set(m_zoomInViewSize.get()+1); int halfsize = m_zoomInViewSize.get() / 2; int left = std::max(volPos[0]-halfsize+1, 0); int right = std::min(volPos[0]+halfsize, m_doc->getStack()->width()-1); int width = right - left + 1; int up = std::max(volPos[1]-halfsize+1, 0); int down = std::min(volPos[1]+halfsize, m_doc->getStack()->height()-1); int height = down - up + 1; int front = 0; int depth = m_doc->getStack()->depth(); m_zoomInBound.clear(); m_zoomInBound.push_back(left*m_xScale.get() + offset.x); m_zoomInBound.push_back(right*m_xScale.get() + offset.x); m_zoomInBound.push_back(up*m_yScale.get() + offset.y); m_zoomInBound.push_back(down*m_yScale.get() + offset.y); m_zoomInBound.push_back(front*m_zScale.get() + offset.z); m_zoomInBound.push_back(depth*m_zScale.get() + offset.z); readSubVolumes(left, up, front, width, height, depth); sendZoomInVolumeData(); m_isSubVolume.set(true); m_isVolumeDownsampled.set(false); return true; } Z3DVolume *Z3DVolumeSource::getVolume(size_t index) { if (index < m_volumes.size()) return m_volumes[index]; else return NULL; } bool Z3DVolumeSource::isEmpty() { return m_volumes.empty(); } bool Z3DVolumeSource::volumeNeedDownsample() const { if (m_doc == NULL) { return false; } if (m_doc->getStack()->getVoxelNumber() * m_doc->getStack()->channelNumber() <= m_maxVoxelNumber) return false; else return true; } bool Z3DVolumeSource::isVolumeDownsampled() const { return m_isVolumeDownsampled.get(); } ZWidgetsGroup *Z3DVolumeSource::getWidgetsGroup() { if (!m_widgetsGroup) { m_widgetsGroup = new ZWidgetsGroup("Volume Source", NULL, 1); new ZWidgetsGroup(&m_zScale, m_widgetsGroup, 3); new ZWidgetsGroup(&m_xScale, m_widgetsGroup, 3); new ZWidgetsGroup(&m_yScale, m_widgetsGroup, 3); new ZWidgetsGroup(&m_isVolumeDownsampled, m_widgetsGroup, 3); new ZWidgetsGroup(&m_isSubVolume, m_widgetsGroup, 3); new ZWidgetsGroup(&m_zoomInViewSize, m_widgetsGroup, 3); m_widgetsGroup->setBasicAdvancedCutoff(4); } return m_widgetsGroup; }
stephenplaza/NeuTu
neurolabi/gui/z3dvolumesource.cpp
C++
bsd-3-clause
33,600
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.regression.mixed_linear_model.MixedLMResults.resid &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv" href="statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv.html" /> <link rel="prev" title="statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov" href="statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.regression.mixed_linear_model.MixedLMResults.resid" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.0</span> <span class="md-header-nav__topic"> statsmodels.regression.mixed_linear_model.MixedLMResults.resid </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../mixed_linear.html" class="md-tabs__link">Linear Mixed Effects Models</a></li> <li class="md-tabs__item"><a href="statsmodels.regression.mixed_linear_model.MixedLMResults.html" class="md-tabs__link">statsmodels.regression.mixed_linear_model.MixedLMResults</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.0</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.regression.mixed_linear_model.MixedLMResults.resid.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-regression-mixed-linear-model-mixedlmresults-resid--page-root">statsmodels.regression.mixed_linear_model.MixedLMResults.resid<a class="headerlink" href="#generated-statsmodels-regression-mixed-linear-model-mixedlmresults-resid--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py attribute"> <dt id="statsmodels.regression.mixed_linear_model.MixedLMResults.resid"> <code class="sig-prename descclassname">MixedLMResults.</code><code class="sig-name descname">resid</code><a class="headerlink" href="#statsmodels.regression.mixed_linear_model.MixedLMResults.resid" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the residuals for the model.</p> <p>The residuals reflect the mean structure specified by the fixed effects and the predicted random effects.</p> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov.html" title="statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.regression.mixed_linear_model.MixedLMResults.random_effects_cov </span> </div> </a> <a href="statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv.html" title="statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.regression.mixed_linear_model.MixedLMResults.score_obsv </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Aug 27, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
v0.12.0/generated/statsmodels.regression.mixed_linear_model.MixedLMResults.resid.html
HTML
bsd-3-clause
18,620
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('datasets', parent_package, top_path) config.add_subpackage('volumes') config.add_subpackage('transforms') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
yarikoptic/NiPy-OLD
nipy/neurospin/datasets/setup.py
Python
bsd-3-clause
390
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.discrete.discrete_model.LogitResults.use_t &#8212; statsmodels v0.10.2 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-discrete-discrete-model-logitresults-use-t"> <h1>statsmodels.discrete.discrete_model.LogitResults.use_t<a class="headerlink" href="#statsmodels-discrete-discrete-model-logitresults-use-t" title="Permalink to this headline">¶</a></h1> <p>attribute</p> <dl class="attribute"> <dt id="statsmodels.discrete.discrete_model.LogitResults.use_t"> <code class="sig-prename descclassname">LogitResults.</code><code class="sig-name descname">use_t</code><em class="property"> = False</em><a class="headerlink" href="#statsmodels.discrete.discrete_model.LogitResults.use_t" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.discrete.discrete_model.LogitResults.use_t.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.2.1. </div> </body> </html>
statsmodels/statsmodels.github.io
v0.10.2/generated/statsmodels.discrete.discrete_model.LogitResults.use_t.html
HTML
bsd-3-clause
5,908
module SpreeVariantOptionsSelect class Engine < Rails::Engine require 'spree/core' isolate_namespace Spree engine_name 'spree_variant_options_select' config.autoload_paths += %W(#{config.root}/lib) # use rspec for tests config.generators do |g| g.test_framework :rspec end def self.activate Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c| Rails.configuration.cache_classes ? require(c) : load(c) end end config.to_prepare &method(:activate).to_proc end end
chandananc/spree_variant_options_select
lib/spree_variant_options_select/engine.rb
Ruby
bsd-3-clause
571
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} import Db import Parser import Trains import Result import Data.List import System.IO import System.Directory import Control.Arrow import Control.Applicative import Control.Monad import Control.Monad.Writer import Data.Monoid import Data.Maybe import Debug.Trace todo = error "TODO" {- a action parsed from user input, - takes a Db, produces a new Db and some output to print - and a flag telling us if we are done -} type Command = (Db -> (Db, String)) commands = Commands { show_all_trains = todo, show_all_routes = todo, show_train = \id -> executeQuery (find_train_by_id id) (tell . show), show_traincar = \id -> executeQuery (find_traincar_by_id id) (tell . show), show_route = \id -> executeQuery (find_route_by_id id) (tell . show), show_city = todo, show_reservation = \id -> executeQuery (find_reservation_by_id id) (tell . show), cmd_query2 = \start stop -> executeQuery (query2_query start stop) query2_printer, cmd_query3 = \train car seat -> executeQuery (query3_query train car seat) query3_printer, cmd_query4 = \trains -> executeQuery (query4_query trains) query4_printer, unknown_command = \cmd db -> (db, "Unknown command: '" ++ cmd ++ "'") } -- | Get train car from train by index. -- | Start counting at 1. -- | So a train has cars [1 .. num-cars] get_nth_car_of_train :: Train -> Int -> Maybe TrainCar get_nth_car_of_train train n = do guard (n >= 1) guard (length (train_cars train) >= n) return (train_cars train !! (n - 1)) -- | Compute all trains that pass a given station transfers :: City -> Db -> [Train] transfers city = db_trains -- get all trains >>> filter (elem city . route_cities . train_route) -- filter out trains for city executeQuery :: (Db -> Result a) -> (a -> Writer String b) -> Db -> (Db, String) executeQuery query printer db = case query db of (Ok a) -> (db, snd (runWriter (printer a))) (Err msg) -> (db, "Error: " ++ msg) train_printer train = tell (show train) -- Mindestanzahl der freien und maximale Anzahl der durch Reservierung belegten Plätze pro Zug -- und Waggon zwischen je zwei Stationen (wobei sich Minimum und Maximum darauf beziehen, -- dass Reservierungen möglicherweise nur auf Teilen der abgefragten Strecke existieren); -- Input: Eine List von Stationen -- Output: Für jeden Wagon jeden Zuges, Anzahl der freien und reservierten Plätze zwischen den Stationen. query2_query :: City -> City -> Db -> Result [(TrainId, [(TrainCarId, Int, Int)])] query2_query start stop db = do route <- route_from_endpoints start stop db -- actual query runs in list monad return $ do train <- db_trains db let cars = do traincar <- train_cars train -- filter out reservations for this train, car and route let rs = do r <- db_reservations db guard (reservation_train r == train_id train) -- filter for this train guard (reservation_traincar r == traincar_id traincar) -- filter for this traincar guard (routes_overlap route (reservation_route r)) -- filter for this route return r let free = num_free_seats_for_car traincar (map reservation_slot rs) let reserved = num_reserved_seats_for_car traincar (map reservation_slot rs) return (traincar_id traincar, free, reserved) return (train_id train, cars) query2_printer :: [(TrainId, [(TrainCarId, Int, Int)])] -> Writer String () query2_printer trains = do tell ("QUERY 2 FOUND " ++ show (length trains) ++ " RECORD(S)") forM trains $ \(train, cars) -> do tell ("TRAIN: " ++ tId train ++ "\n") forM cars $ \(traincar, free_seats, reserved_seats) -> do tell ("\tTRAIN CAR: " ++ tcId traincar ++ "\n") tell ("\t\tFREE SEATS: " ++ show free_seats ++ "\n") tell ("\t\tRESERVED SEATS: " ++ show reserved_seats ++ "\n") return () -- Reservierungen für einen bestimmten Platz in einem Zug, wobei das Ergebnis die Stationen angibt, -- zwischen denen Reservierungen bestehen; -- Input: Ein Zug, ein Wagon, eine Sitznummer -- Output: Alle Routen für die diser Sitz reserviert wurde. --query3_query :: Train -> TrainCar -> Int -> Db -> Result [[City]] query3_query train_id traincar_id seat db = do train <- find_train_by_id train_id db -- validate train traincar <- find_traincar_by_id traincar_id db -- validate traincar return $ db_reservations -- get reservations from db >>> filter ((train_id ==) . reservation_train) -- filter for this train >>> filter ((traincar_id ==) . reservation_traincar) -- filter for this train >>> filter ((slot_contains_seat seat) . reservation_slot) -- filter for `seat' >>> map reservation_route -- get cities of reservation $ db query3_printer routes = do tell ("QUERY 3 FOUND " ++ show (length routes) ++ " RECORD(S)") forM routes $ \route -> do tell (concat (intersperse ", " (map city_name route))) tell "\n" return () -- Mindestanzahl der zwischen zwei Stationen freien und der noch reservierbaren Plätze sowie die maximale Gruppengröße -- (= maximale Zahl der Personen pro Reservierung) für einen Zug oder mehrere gegebene Züge (wenn Umsteigen nötig ist). -- Input: Eine Liste von (Zug, Startstation, Endstation) Tupeln -- Output: Für jeden Tupel, Anzahl der freien und reservierbaren Plätze, sowie Länge des größten freien Bereichs in einem Wagon, -- zwischen den Stationen. query4_query :: [(TrainId, City, City)] -> Db -> Result [(TrainId, Int, Int, Int)] query4_query trains db = do forM trains $ \(train_id, start, stop) -> do train <- find_train_by_id train_id db route <- route_from_endpoints start stop db let cars = do traincar <- train_cars train -- filter out reservations for this train, car and route let rs = do r <- db_reservations db guard (reservation_train r == train_id) -- filter for this train guard (reservation_traincar r == traincar_id traincar) -- filter for this traincar guard (routes_overlap route (reservation_route r)) -- filter for this route return r let free = num_free_seats_for_car traincar (map reservation_slot rs) let max_group_size = max_group_size_for_car traincar (map reservation_slot rs) return (free, max_group_size) let free = sum (map fst cars) -- add up free seats from all cars let reservable = free - (train_res_free_seats train) -- cannot reserve seats in free quota let max_group_size = maximum (map snd cars) -- get biggest free slot return (train_id, free, reservable, max_group_size) query4_printer trains = do tell ("QUERY 4 FOUND " ++ show (length trains) ++ " RECORD(S)") forM trains $ \(train, free, reservable, max_group_size) -> do tell ("\tTRAIN " ++ show (tId train) ++ "\n") tell ("\t\tFREE SEATS: " ++ show free ++ "\n") tell ("\t\tRESERVABLE SEATS: " ++ show reservable ++ "\n") tell ("\t\tMAXIMUM GROUP SIZE: " ++ show max_group_size ++ "\n") return () num_free_seats_for_train train db = do let rs = db_reservations db let free = do car <- train_cars train let rs' = filter (\r -> reservation_traincar r == traincar_id car) rs let slots = map reservation_slot rs' return (num_free_seats_for_car car slots) return (sum free) -- | Computes the number of free seats for a traincar num_free_seats_for_car :: TrainCar -> [Slot] -> Int num_free_seats_for_car traincar = traincar_status traincar -- compute free/reserved bitmap >>> filter (==Free) -- filter for `free' bits >>> length -- count `free' bits -- | Computes the number of reserved seats for a traincar num_reserved_seats_for_car :: TrainCar -> [Slot] -> Int num_reserved_seats_for_car traincar = traincar_status traincar -- compute free/reserved bitmap >>> filter (==Reserved) -- folter for `reserved' bits >>> length -- count `reserved' bits -- | Computes the size of the biggest free slot in a train car max_group_size_for_car :: TrainCar -> [Slot] -> Int max_group_size_for_car traincar = traincar_status traincar -- create free/reserved bitmap >>> run_length_encode -- run length encode >>> filter (\(a,_) -> a==Free) -- discard reserved slots >>> map snd -- discard Free tags >>> maximum -- get maximum where run_length_encode :: Eq a => [a] -> [(a, Int)] run_length_encode [] = [] run_length_encode (l:ls) = encode l 0 (l:ls) where encode a n [] = [(a,n)] encode a n (l:ls) | a == l = encode a (n+1) ls | otherwise = (a,n) : encode l 0 (l:ls) -- | A bitmap that shows which seats of a TrainCar are reserved or free type TrainCarStatus = [SeatStatus] data SeatStatus = Free | Reserved deriving (Show, Eq) -- | Computes a bitmap telling us which seats are free or reserved from a list of reservations -- | Works by computing a bitmap for each slot and just `or'ing together the bitmaps traincar_status :: TrainCar -> [Slot] -> TrainCarStatus traincar_status traincar reservations = foldl (zipWith or) initial_status (map slot_to_status reservations) where -- initially all seats are free initial_status = times Free (traincar_num_seats traincar) -- create bitmaps from reservation slot_to_status s = times Free (slot_first_seat s - 1) ++ times Reserved (slot_num_seats s) ++ repeat Free or Free Free = Free or _ _ = Reserved -- | Create a list that contains element `a' `n' times. times :: a -> Int -> [a] times a n = take n (repeat a) -- | Given a route try to get the subroute starting at station `start' and ending at station `stop' try_find_subroute :: City -> City -> [City] -> Maybe [City] try_find_subroute start stop cities = do a <- findIndex (start==) cities b <- findIndex (stop ==) cities guard (a < b) return (drop a (take b cities)) main :: IO () main = do let db_path = "zug.db" putStrLn ">> STARTING APP" db_exists <- doesFileExist db_path when (not db_exists) $ do putStrLn ">> CREATING DATABASE" writeDb db_path db putStrLn ">> READING DATABASE" db' <- readDb db_path putStrLn ">> READ DATABASE" db'' <- mainLoop db' putStrLn ">> WRITING DATABASE" writeDb db_path db'' -- process changes in DB putStrLn ">> WROTE DATABASE" putStrLn ">> DONE" _PROMPT = "$ " mainLoop :: Db -> IO Db mainLoop db = do eof <- isEOF if eof then return db else do input <- getLine cmd <- return (parse_command commands (id $! input)) (db', output) <- return (cmd db) putStrLn output mainLoop db' readDb :: FilePath -> IO Db readDb path = do text <- readFile path return $! read $! text -- $! makes sure file is fully read writeDb :: FilePath -> Db -> IO () writeDb file db = writeFile file (show db)
fadeopolis/prog-spr-ue3
ue3.hs
Haskell
bsd-3-clause
11,533
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.regression.linear_model.RegressionResults.load &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.regression.linear_model.RegressionResults.normalized_cov_params" href="statsmodels.regression.linear_model.RegressionResults.normalized_cov_params.html" /> <link rel="prev" title="statsmodels.regression.linear_model.RegressionResults.initialize" href="statsmodels.regression.linear_model.RegressionResults.initialize.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.regression.linear_model.RegressionResults.load" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.1</span> <span class="md-header-nav__topic"> statsmodels.regression.linear_model.RegressionResults.load </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../regression.html" class="md-tabs__link">Linear Regression</a></li> <li class="md-tabs__item"><a href="statsmodels.regression.linear_model.RegressionResults.html" class="md-tabs__link">statsmodels.regression.linear_model.RegressionResults</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.1</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.regression.linear_model.RegressionResults.load.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-regression-linear-model-regressionresults-load--page-root">statsmodels.regression.linear_model.RegressionResults.load<a class="headerlink" href="#generated-statsmodels-regression-linear-model-regressionresults-load--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt id="statsmodels.regression.linear_model.RegressionResults.load"> <em class="property">classmethod </em><code class="sig-prename descclassname">RegressionResults.</code><code class="sig-name descname">load</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">fname</span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.regression.linear_model.RegressionResults.load" title="Permalink to this definition">¶</a></dt> <dd><p>Load a pickled results instance</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Loading pickled models is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.</p> </div> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>fname</strong><span class="classifier">{<a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#str" title="(in Python v3.9)"><code class="docutils literal notranslate"><span class="pre">str</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">handle</span></code>}</span></dt><dd><p>A string filename or a file handle.</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl class="simple"> <dt><code class="xref py py-obj docutils literal notranslate"><span class="pre">Results</span></code></dt><dd><p>The unpickled results instance.</p> </dd> </dl> </dd> </dl> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.regression.linear_model.RegressionResults.initialize.html" title="statsmodels.regression.linear_model.RegressionResults.initialize" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.regression.linear_model.RegressionResults.initialize </span> </div> </a> <a href="statsmodels.regression.linear_model.RegressionResults.normalized_cov_params.html" title="statsmodels.regression.linear_model.RegressionResults.normalized_cov_params" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.regression.linear_model.RegressionResults.normalized_cov_params </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Oct 29, 2020. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
v0.12.1/generated/statsmodels.regression.linear_model.RegressionResults.load.html
HTML
bsd-3-clause
19,603
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/network/onc/onc_utils.h" #include "base/base64.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/values.h" #include "chromeos/network/network_event_log.h" #include "chromeos/network/onc/onc_mapper.h" #include "chromeos/network/onc/onc_signature.h" #include "chromeos/network/onc/onc_utils.h" #include "chromeos/network/onc/onc_validator.h" #include "components/device_event_log/device_event_log.h" #include "crypto/encryptor.h" #include "crypto/hmac.h" #include "crypto/symmetric_key.h" #include "net/cert/pem_tokenizer.h" #include "net/cert/x509_certificate.h" using namespace ::onc; namespace chromeos { namespace onc { namespace { const char kUnableToDecrypt[] = "Unable to decrypt encrypted ONC"; const char kUnableToDecode[] = "Unable to decode encrypted ONC"; } // namespace const char kEmptyUnencryptedConfiguration[] = "{\"Type\":\"UnencryptedConfiguration\",\"NetworkConfigurations\":[]," "\"Certificates\":[]}"; scoped_ptr<base::DictionaryValue> ReadDictionaryFromJson( const std::string& json) { std::string error; base::Value* root = base::JSONReader::DeprecatedReadAndReturnError( json, base::JSON_ALLOW_TRAILING_COMMAS, nullptr, &error); base::DictionaryValue* dict_ptr = nullptr; if (!root || !root->GetAsDictionary(&dict_ptr)) { NET_LOG(ERROR) << "Invalid JSON Dictionary: " << error; delete root; } return make_scoped_ptr(dict_ptr); } scoped_ptr<base::DictionaryValue> Decrypt(const std::string& passphrase, const base::DictionaryValue& root) { const int kKeySizeInBits = 256; const int kMaxIterationCount = 500000; std::string onc_type; std::string initial_vector; std::string salt; std::string cipher; std::string stretch_method; std::string hmac_method; std::string hmac; int iterations; std::string ciphertext; if (!root.GetString(encrypted::kCiphertext, &ciphertext) || !root.GetString(encrypted::kCipher, &cipher) || !root.GetString(encrypted::kHMAC, &hmac) || !root.GetString(encrypted::kHMACMethod, &hmac_method) || !root.GetString(encrypted::kIV, &initial_vector) || !root.GetInteger(encrypted::kIterations, &iterations) || !root.GetString(encrypted::kSalt, &salt) || !root.GetString(encrypted::kStretch, &stretch_method) || !root.GetString(toplevel_config::kType, &onc_type) || onc_type != toplevel_config::kEncryptedConfiguration) { NET_LOG(ERROR) << "Encrypted ONC malformed."; return nullptr; } if (hmac_method != encrypted::kSHA1 || cipher != encrypted::kAES256 || stretch_method != encrypted::kPBKDF2) { NET_LOG(ERROR) << "Encrypted ONC unsupported encryption scheme."; return nullptr; } // Make sure iterations != 0, since that's not valid. if (iterations == 0) { NET_LOG(ERROR) << kUnableToDecrypt; return nullptr; } // Simply a sanity check to make sure we can't lock up the machine // for too long with a huge number (or a negative number). if (iterations < 0 || iterations > kMaxIterationCount) { NET_LOG(ERROR) << "Too many iterations in encrypted ONC"; return nullptr; } if (!base::Base64Decode(salt, &salt)) { NET_LOG(ERROR) << kUnableToDecode; return nullptr; } scoped_ptr<crypto::SymmetricKey> key( crypto::SymmetricKey::DeriveKeyFromPassword(crypto::SymmetricKey::AES, passphrase, salt, iterations, kKeySizeInBits)); if (!base::Base64Decode(initial_vector, &initial_vector)) { NET_LOG(ERROR) << kUnableToDecode; return nullptr; } if (!base::Base64Decode(ciphertext, &ciphertext)) { NET_LOG(ERROR) << kUnableToDecode; return nullptr; } if (!base::Base64Decode(hmac, &hmac)) { NET_LOG(ERROR) << kUnableToDecode; return nullptr; } crypto::HMAC hmac_verifier(crypto::HMAC::SHA1); if (!hmac_verifier.Init(key.get()) || !hmac_verifier.Verify(ciphertext, hmac)) { NET_LOG(ERROR) << kUnableToDecrypt; return nullptr; } crypto::Encryptor decryptor; if (!decryptor.Init(key.get(), crypto::Encryptor::CBC, initial_vector)) { NET_LOG(ERROR) << kUnableToDecrypt; return nullptr; } std::string plaintext; if (!decryptor.Decrypt(ciphertext, &plaintext)) { NET_LOG(ERROR) << kUnableToDecrypt; return nullptr; } scoped_ptr<base::DictionaryValue> new_root = ReadDictionaryFromJson(plaintext); if (!new_root) { NET_LOG(ERROR) << "Property dictionary malformed."; return nullptr; } return new_root.Pass(); } std::string GetSourceAsString(ONCSource source) { switch (source) { case ONC_SOURCE_UNKNOWN: return "unknown"; case ONC_SOURCE_NONE: return "none"; case ONC_SOURCE_DEVICE_POLICY: return "device policy"; case ONC_SOURCE_USER_POLICY: return "user policy"; case ONC_SOURCE_USER_IMPORT: return "user import"; } NOTREACHED() << "unknown ONC source " << source; return "unknown"; } void ExpandField(const std::string& fieldname, const StringSubstitution& substitution, base::DictionaryValue* onc_object) { std::string user_string; if (!onc_object->GetStringWithoutPathExpansion(fieldname, &user_string)) return; std::string login_id; if (substitution.GetSubstitute(substitutes::kLoginIDField, &login_id)) { base::ReplaceSubstringsAfterOffset(&user_string, 0, substitutes::kLoginIDField, login_id); } std::string email; if (substitution.GetSubstitute(substitutes::kEmailField, &email)) { base::ReplaceSubstringsAfterOffset(&user_string, 0, substitutes::kEmailField, email); } onc_object->SetStringWithoutPathExpansion(fieldname, user_string); } void ExpandStringsInOncObject( const OncValueSignature& signature, const StringSubstitution& substitution, base::DictionaryValue* onc_object) { if (&signature == &kEAPSignature) { ExpandField(eap::kAnonymousIdentity, substitution, onc_object); ExpandField(eap::kIdentity, substitution, onc_object); } else if (&signature == &kL2TPSignature || &signature == &kOpenVPNSignature) { ExpandField(vpn::kUsername, substitution, onc_object); } // Recurse into nested objects. for (base::DictionaryValue::Iterator it(*onc_object); !it.IsAtEnd(); it.Advance()) { base::DictionaryValue* inner_object = nullptr; if (!onc_object->GetDictionaryWithoutPathExpansion(it.key(), &inner_object)) continue; const OncFieldSignature* field_signature = GetFieldSignature(signature, it.key()); if (!field_signature) continue; ExpandStringsInOncObject(*field_signature->value_signature, substitution, inner_object); } } void ExpandStringsInNetworks(const StringSubstitution& substitution, base::ListValue* network_configs) { for (base::Value* entry : *network_configs) { base::DictionaryValue* network = nullptr; entry->GetAsDictionary(&network); DCHECK(network); ExpandStringsInOncObject( kNetworkConfigurationSignature, substitution, network); } } void FillInHexSSIDFieldsInOncObject(const OncValueSignature& signature, base::DictionaryValue* onc_object) { if (&signature == &kWiFiSignature) FillInHexSSIDField(onc_object); // Recurse into nested objects. for (base::DictionaryValue::Iterator it(*onc_object); !it.IsAtEnd(); it.Advance()) { base::DictionaryValue* inner_object = nullptr; if (!onc_object->GetDictionaryWithoutPathExpansion(it.key(), &inner_object)) continue; const OncFieldSignature* field_signature = GetFieldSignature(signature, it.key()); if (!field_signature) continue; FillInHexSSIDFieldsInOncObject(*field_signature->value_signature, inner_object); } } void FillInHexSSIDField(base::DictionaryValue* wifi_fields) { std::string ssid_string; if (wifi_fields->HasKey(::onc::wifi::kHexSSID) || !wifi_fields->GetStringWithoutPathExpansion(::onc::wifi::kSSID, &ssid_string)) { return; } if (ssid_string.empty()) { NET_LOG(ERROR) << "Found empty SSID field."; return; } wifi_fields->SetStringWithoutPathExpansion( ::onc::wifi::kHexSSID, base::HexEncode(ssid_string.c_str(), ssid_string.size())); } namespace { class OncMaskValues : public Mapper { public: static scoped_ptr<base::DictionaryValue> Mask( const OncValueSignature& signature, const base::DictionaryValue& onc_object, const std::string& mask) { OncMaskValues masker(mask); bool unused_error; return masker.MapObject(signature, onc_object, &unused_error); } protected: explicit OncMaskValues(const std::string& mask) : mask_(mask) { } scoped_ptr<base::Value> MapField(const std::string& field_name, const OncValueSignature& object_signature, const base::Value& onc_value, bool* found_unknown_field, bool* error) override { if (FieldIsCredential(object_signature, field_name)) { return scoped_ptr<base::Value>(new base::StringValue(mask_)); } else { return Mapper::MapField(field_name, object_signature, onc_value, found_unknown_field, error); } } // Mask to insert in place of the sensitive values. std::string mask_; }; } // namespace scoped_ptr<base::DictionaryValue> MaskCredentialsInOncObject( const OncValueSignature& signature, const base::DictionaryValue& onc_object, const std::string& mask) { return OncMaskValues::Mask(signature, onc_object, mask); } namespace { std::string DecodePEM(const std::string& pem_encoded) { // The PEM block header used for DER certificates const char kCertificateHeader[] = "CERTIFICATE"; // This is an older PEM marker for DER certificates. const char kX509CertificateHeader[] = "X509 CERTIFICATE"; std::vector<std::string> pem_headers; pem_headers.push_back(kCertificateHeader); pem_headers.push_back(kX509CertificateHeader); net::PEMTokenizer pem_tokenizer(pem_encoded, pem_headers); std::string decoded; if (pem_tokenizer.GetNext()) { decoded = pem_tokenizer.data(); } else { // If we failed to read the data as a PEM file, then try plain base64 decode // in case the PEM marker strings are missing. For this to work, there has // to be no white space, and it has to only contain the base64-encoded data. if (!base::Base64Decode(pem_encoded, &decoded)) { LOG(ERROR) << "Unable to base64 decode X509 data: " << pem_encoded; return std::string(); } } return decoded; } CertPEMsByGUIDMap GetServerAndCACertsByGUID( const base::ListValue& certificates) { CertPEMsByGUIDMap certs_by_guid; for (const base::Value* entry : certificates) { const base::DictionaryValue* cert = nullptr; entry->GetAsDictionary(&cert); std::string guid; cert->GetStringWithoutPathExpansion(certificate::kGUID, &guid); std::string cert_type; cert->GetStringWithoutPathExpansion(certificate::kType, &cert_type); if (cert_type != certificate::kServer && cert_type != certificate::kAuthority) { continue; } std::string x509_data; cert->GetStringWithoutPathExpansion(certificate::kX509, &x509_data); std::string der = DecodePEM(x509_data); std::string pem; if (der.empty() || !net::X509Certificate::GetPEMEncodedFromDER(der, &pem)) { LOG(ERROR) << "Certificate with GUID " << guid << " is not in PEM encoding."; continue; } certs_by_guid[guid] = pem; } return certs_by_guid; } void FillInHexSSIDFieldsInNetworks(base::ListValue* network_configs) { for (base::Value* entry : *network_configs) { base::DictionaryValue* network = nullptr; entry->GetAsDictionary(&network); DCHECK(network); FillInHexSSIDFieldsInOncObject(kNetworkConfigurationSignature, network); } } } // namespace bool ParseAndValidateOncForImport(const std::string& onc_blob, ONCSource onc_source, const std::string& passphrase, base::ListValue* network_configs, base::DictionaryValue* global_network_config, base::ListValue* certificates) { network_configs->Clear(); global_network_config->Clear(); certificates->Clear(); if (onc_blob.empty()) return true; scoped_ptr<base::DictionaryValue> toplevel_onc = ReadDictionaryFromJson(onc_blob); if (!toplevel_onc) { LOG(ERROR) << "ONC loaded from " << GetSourceAsString(onc_source) << " is not a valid JSON dictionary."; return false; } // Check and see if this is an encrypted ONC file. If so, decrypt it. std::string onc_type; toplevel_onc->GetStringWithoutPathExpansion(toplevel_config::kType, &onc_type); if (onc_type == toplevel_config::kEncryptedConfiguration) { toplevel_onc = Decrypt(passphrase, *toplevel_onc); if (!toplevel_onc) { LOG(ERROR) << "Couldn't decrypt the ONC from " << GetSourceAsString(onc_source); return false; } } bool from_policy = (onc_source == ONC_SOURCE_USER_POLICY || onc_source == ONC_SOURCE_DEVICE_POLICY); // Validate the ONC dictionary. We are liberal and ignore unknown field // names and ignore invalid field names in kRecommended arrays. Validator validator(false, // Ignore unknown fields. false, // Ignore invalid recommended field names. true, // Fail on missing fields. from_policy); validator.SetOncSource(onc_source); Validator::Result validation_result; toplevel_onc = validator.ValidateAndRepairObject( &kToplevelConfigurationSignature, *toplevel_onc, &validation_result); if (from_policy) { UMA_HISTOGRAM_BOOLEAN("Enterprise.ONC.PolicyValidation", validation_result == Validator::VALID); } bool success = true; if (validation_result == Validator::VALID_WITH_WARNINGS) { LOG(WARNING) << "ONC from " << GetSourceAsString(onc_source) << " produced warnings."; success = false; } else if (validation_result == Validator::INVALID || !toplevel_onc) { LOG(ERROR) << "ONC from " << GetSourceAsString(onc_source) << " is invalid and couldn't be repaired."; return false; } base::ListValue* validated_certs = nullptr; if (toplevel_onc->GetListWithoutPathExpansion(toplevel_config::kCertificates, &validated_certs)) { certificates->Swap(validated_certs); } base::ListValue* validated_networks = nullptr; if (toplevel_onc->GetListWithoutPathExpansion( toplevel_config::kNetworkConfigurations, &validated_networks)) { FillInHexSSIDFieldsInNetworks(validated_networks); CertPEMsByGUIDMap server_and_ca_certs = GetServerAndCACertsByGUID(*certificates); if (!ResolveServerCertRefsInNetworks(server_and_ca_certs, validated_networks)) { LOG(ERROR) << "Some certificate references in the ONC policy for source " << GetSourceAsString(onc_source) << " could not be resolved."; success = false; } network_configs->Swap(validated_networks); } base::DictionaryValue* validated_global_config = nullptr; if (toplevel_onc->GetDictionaryWithoutPathExpansion( toplevel_config::kGlobalNetworkConfiguration, &validated_global_config)) { global_network_config->Swap(validated_global_config); } return success; } scoped_refptr<net::X509Certificate> DecodePEMCertificate( const std::string& pem_encoded) { std::string decoded = DecodePEM(pem_encoded); scoped_refptr<net::X509Certificate> cert = net::X509Certificate::CreateFromBytes(decoded.data(), decoded.size()); LOG_IF(ERROR, !cert.get()) << "Couldn't create certificate from X509 data: " << decoded; return cert; } namespace { bool GUIDRefToPEMEncoding(const CertPEMsByGUIDMap& certs_by_guid, const std::string& guid_ref, std::string* pem_encoded) { CertPEMsByGUIDMap::const_iterator it = certs_by_guid.find(guid_ref); if (it == certs_by_guid.end()) { LOG(ERROR) << "Couldn't resolve certificate reference " << guid_ref; return false; } *pem_encoded = it->second; if (pem_encoded->empty()) { LOG(ERROR) << "Couldn't PEM-encode certificate with GUID " << guid_ref; return false; } return true; } bool ResolveSingleCertRef(const CertPEMsByGUIDMap& certs_by_guid, const std::string& key_guid_ref, const std::string& key_pem, base::DictionaryValue* onc_object) { std::string guid_ref; if (!onc_object->GetStringWithoutPathExpansion(key_guid_ref, &guid_ref)) return true; std::string pem_encoded; if (!GUIDRefToPEMEncoding(certs_by_guid, guid_ref, &pem_encoded)) return false; onc_object->RemoveWithoutPathExpansion(key_guid_ref, nullptr); onc_object->SetStringWithoutPathExpansion(key_pem, pem_encoded); return true; } bool ResolveCertRefList(const CertPEMsByGUIDMap& certs_by_guid, const std::string& key_guid_ref_list, const std::string& key_pem_list, base::DictionaryValue* onc_object) { const base::ListValue* guid_ref_list = nullptr; if (!onc_object->GetListWithoutPathExpansion(key_guid_ref_list, &guid_ref_list)) { return true; } scoped_ptr<base::ListValue> pem_list(new base::ListValue); for (const base::Value* entry : *guid_ref_list) { std::string guid_ref; entry->GetAsString(&guid_ref); std::string pem_encoded; if (!GUIDRefToPEMEncoding(certs_by_guid, guid_ref, &pem_encoded)) return false; pem_list->AppendString(pem_encoded); } onc_object->RemoveWithoutPathExpansion(key_guid_ref_list, nullptr); onc_object->SetWithoutPathExpansion(key_pem_list, pem_list.release()); return true; } bool ResolveSingleCertRefToList(const CertPEMsByGUIDMap& certs_by_guid, const std::string& key_guid_ref, const std::string& key_pem_list, base::DictionaryValue* onc_object) { std::string guid_ref; if (!onc_object->GetStringWithoutPathExpansion(key_guid_ref, &guid_ref)) return true; std::string pem_encoded; if (!GUIDRefToPEMEncoding(certs_by_guid, guid_ref, &pem_encoded)) return false; scoped_ptr<base::ListValue> pem_list(new base::ListValue); pem_list->AppendString(pem_encoded); onc_object->RemoveWithoutPathExpansion(key_guid_ref, nullptr); onc_object->SetWithoutPathExpansion(key_pem_list, pem_list.release()); return true; } // Resolves the reference list at |key_guid_refs| if present and otherwise the // single reference at |key_guid_ref|. Returns whether the respective resolving // was successful. bool ResolveCertRefsOrRefToList(const CertPEMsByGUIDMap& certs_by_guid, const std::string& key_guid_refs, const std::string& key_guid_ref, const std::string& key_pem_list, base::DictionaryValue* onc_object) { if (onc_object->HasKey(key_guid_refs)) { if (onc_object->HasKey(key_guid_ref)) { LOG(ERROR) << "Found both " << key_guid_refs << " and " << key_guid_ref << ". Ignoring and removing the latter."; onc_object->RemoveWithoutPathExpansion(key_guid_ref, nullptr); } return ResolveCertRefList( certs_by_guid, key_guid_refs, key_pem_list, onc_object); } // Only resolve |key_guid_ref| if |key_guid_refs| isn't present. return ResolveSingleCertRefToList( certs_by_guid, key_guid_ref, key_pem_list, onc_object); } bool ResolveServerCertRefsInObject(const CertPEMsByGUIDMap& certs_by_guid, const OncValueSignature& signature, base::DictionaryValue* onc_object) { if (&signature == &kCertificatePatternSignature) { if (!ResolveCertRefList(certs_by_guid, client_cert::kIssuerCARef, client_cert::kIssuerCAPEMs, onc_object)) { return false; } } else if (&signature == &kEAPSignature) { if (!ResolveCertRefsOrRefToList(certs_by_guid, eap::kServerCARefs, eap::kServerCARef, eap::kServerCAPEMs, onc_object)) { return false; } } else if (&signature == &kIPsecSignature) { if (!ResolveCertRefsOrRefToList(certs_by_guid, ipsec::kServerCARefs, ipsec::kServerCARef, ipsec::kServerCAPEMs, onc_object)) { return false; } } else if (&signature == &kIPsecSignature || &signature == &kOpenVPNSignature) { if (!ResolveSingleCertRef(certs_by_guid, openvpn::kServerCertRef, openvpn::kServerCertPEM, onc_object) || !ResolveCertRefsOrRefToList(certs_by_guid, openvpn::kServerCARefs, openvpn::kServerCARef, openvpn::kServerCAPEMs, onc_object)) { return false; } } // Recurse into nested objects. for (base::DictionaryValue::Iterator it(*onc_object); !it.IsAtEnd(); it.Advance()) { base::DictionaryValue* inner_object = nullptr; if (!onc_object->GetDictionaryWithoutPathExpansion(it.key(), &inner_object)) continue; const OncFieldSignature* field_signature = GetFieldSignature(signature, it.key()); if (!field_signature) continue; if (!ResolveServerCertRefsInObject(certs_by_guid, *field_signature->value_signature, inner_object)) { return false; } } return true; } } // namespace bool ResolveServerCertRefsInNetworks(const CertPEMsByGUIDMap& certs_by_guid, base::ListValue* network_configs) { bool success = true; for (base::ListValue::iterator it = network_configs->begin(); it != network_configs->end(); ) { base::DictionaryValue* network = nullptr; (*it)->GetAsDictionary(&network); if (!ResolveServerCertRefsInNetwork(certs_by_guid, network)) { std::string guid; network->GetStringWithoutPathExpansion(network_config::kGUID, &guid); // This might happen even with correct validation, if the referenced // certificate couldn't be imported. LOG(ERROR) << "Couldn't resolve some certificate reference of network " << guid; it = network_configs->Erase(it, nullptr); success = false; continue; } ++it; } return success; } bool ResolveServerCertRefsInNetwork(const CertPEMsByGUIDMap& certs_by_guid, base::DictionaryValue* network_config) { return ResolveServerCertRefsInObject(certs_by_guid, kNetworkConfigurationSignature, network_config); } NetworkTypePattern NetworkTypePatternFromOncType(const std::string& type) { if (type == ::onc::network_type::kAllTypes) return NetworkTypePattern::Default(); if (type == ::onc::network_type::kCellular) return NetworkTypePattern::Cellular(); if (type == ::onc::network_type::kEthernet) return NetworkTypePattern::Ethernet(); if (type == ::onc::network_type::kVPN) return NetworkTypePattern::VPN(); if (type == ::onc::network_type::kWiFi) return NetworkTypePattern::WiFi(); if (type == ::onc::network_type::kWimax) return NetworkTypePattern::Wimax(); if (type == ::onc::network_type::kWireless) return NetworkTypePattern::Wireless(); NOTREACHED() << "Unrecognized ONC type: " << type; return NetworkTypePattern::Default(); } bool IsRecommendedValue(const base::DictionaryValue* onc, const std::string& property_key) { std::string property_basename, recommended_property_key; size_t pos = property_key.find_last_of('.'); if (pos != std::string::npos) { // 'WiFi.AutoConnect' -> 'AutoConnect', 'WiFi.Recommended' property_basename = property_key.substr(pos + 1); recommended_property_key = property_key.substr(0, pos + 1) + ::onc::kRecommended; } else { // 'Name' -> 'Name', 'Recommended' property_basename = property_key; recommended_property_key = ::onc::kRecommended; } const base::ListValue* recommended_keys = nullptr; return (onc->GetList(recommended_property_key, &recommended_keys) && recommended_keys->Find(base::StringValue(property_basename)) != recommended_keys->end()); } } // namespace onc } // namespace chromeos
SaschaMester/delicium
chromeos/network/onc/onc_utils.cc
C++
bsd-3-clause
26,331
<!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <!-- build:css styles/vendor.css --> <!-- bower:css --> <link rel="stylesheet" href="bower_components/sass-bootstrap/dist/css/bootstrap.css" /> <!-- endbower --> <!-- endbuild --> <!-- build:css({.tmp,app}) styles/main.css --> <link rel="stylesheet" href="styles/main.css"> <!-- endbuild --> </head> <body ng-app="sequencerApp"> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <!-- Add your site or application content here --> <div class="container" ng-view=""></div> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXX-X'); ga('send', 'pageview'); </script> <!--[if lt IE 9]> <script src="bower_components/es5-shim/es5-shim.js"></script> <script src="bower_components/json3/lib/json3.min.js"></script> <![endif]--> <!-- build:js scripts/vendor.js --> <!-- bower:js --> <script src="bower_components/jquery/jquery.js"></script> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/sass-bootstrap/dist/js/bootstrap.js"></script> <script src="bower_components/angular-resource/angular-resource.js"></script> <script src="bower_components/angular-cookies/angular-cookies.js"></script> <script src="bower_components/angular-route/angular-route.js"></script> <!-- endbower --> <!-- endbuild --> <!-- build:js({.tmp,app}) scripts/scripts.js --> <script src="scripts/app.js"></script> <script src="scripts/controllers/main.js"></script> <!-- endbuild --> </body> </html>
Micka33/sequencer
yeoman/app/index.html
HTML
bsd-3-clause
2,703
/** * Copyright (c) 2004-2021, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o 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. * * o Neither the name of Ben Fortuna nor the names of any other 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 OWNER 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. */ package net.fortuna.ical4j.filter.predicate; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyContainer; import java.util.Comparator; import java.util.function.Function; import java.util.function.Predicate; /** * Test for a property matching the supplied specification. */ public class PropertyExistsRule<T extends PropertyContainer> implements Predicate<T> { private final Property specification; public PropertyExistsRule(Property specification) { this.specification = specification; } @Override public boolean test(T t) { return new PropertyEqualToRule<>(new PropertyExists(specification)).test(t); } /** * Ignore the property value and just compare on the property name and parameters. */ public static class PropertyExists implements Comparable<Property> { private final Property specification; public PropertyExists(Property specification) { this.specification = specification; } @Override public int compareTo(Property o) { return Comparator.comparing(Property::getName) .thenComparing((Function<Property, ParameterList>) Property::getParameters) .compare(specification, o); } } }
ical4j/ical4j
src/main/java/net/fortuna/ical4j/filter/predicate/PropertyExistsRule.java
Java
bsd-3-clause
2,927
import React from 'react' import Reflux from 'reflux' const AssetStore = require('../stores/AssetStore'); import Tabs from './Tabs' export default React.createClass({ displayName: 'Asset', mixins: [Reflux.listenTo(AssetStore, 'update')], update: function () { if (!this.isMounted()) return; this.setState(this.getStateFromStore()); }, getStateFromStore: function(props) { props = props || this.props; return { asset: AssetStore.getAsset(props.params.id) || {} }; }, getInitialState: function () { return this.getStateFromStore(); }, componentWillReceiveProps: function (nextProps) { this.setState(this.getStateFromStore(nextProps)); }, render: function() { var url = this.state.asset.url || ''; var tabs = [ {title: 'Activity', content: 'Activity'}, {title: 'Task', content: 'Task'}, {title: 'Revisions', content: 'Revisions'}, {title: 'Comments', content: 'Comments'}, ]; return ( <div> <Row> <Column size={4}> <Preview url={url+'preview'} /> </Column> <Column size={8}> <Details asset={this.state.asset} /> </Column> </Row> <Row> <Column size={12}> <Tabs tabs={tabs}/> </Column> </Row> </div> ); } }); const Row = React.createClass({ render: function() { return ( <div className="row"> {this.props.children} </div> ); } }); export const Column = React.createClass({ render: function() { //col-sm-12 col-md-12 col-lg-6 return ( <div className={'col-lg-'+this.props.size}>{this.props.children}</div> ); } }); export const Preview = React.createClass({ render: function() { return ( <div><img src={this.props.url} alt="Preview" /></div> ); } }); export const Details = React.createClass({ render: function() { return ( <div>Details</div> ); } });
peragro/peragro-ui
src/components/Asset.js
JavaScript
bsd-3-clause
1,995
// // UIViewController+INNControllerContext.h // ControllerContextTest // // Created by Michael Raber on 5/14/14. // Copyright (c) 2014 Innoruptor. All rights reserved. // #import <UIKit/UIKit.h> #import "INNControllerContext.h" @interface UIViewController (INNControllerContext) -(id) INN_initWithContext:(INNControllerContext *)context; -(void) INN_setContext:(INNControllerContext *)context; -(INNControllerContext *)INN_context; #ifdef USE_NON_NAMESPACED_INNCONTROLLERCONTEXT_CATEGORY -(id) initWithContext:(INNControllerContext *)context; -(void) setContext:(INNControllerContext *)context; -(INNControllerContext *)context; #endif @end
Innoruptor/ControllerContext
Classes/UIViewController+INNControllerContext.h
C
bsd-3-clause
653
""" :Requirements: django-tagging This module contains some additional helper tags for the django-tagging project. Note that the functionality here might already be present in django-tagging but perhaps with some slightly different behaviour or usage. """ from django import template from django.core.urlresolvers import reverse as url_reverse from tagging.utils import parse_tag_input register = template.Library() class TagsForObjectNode(template.Node): def __init__(self, tags_string, urlname, junctor=None, last_junctor=None): self.tags_string = template.Variable(tags_string) self.junctor = junctor is None and ', ' or junctor.lstrip('"').rstrip('"') self.last_junctor = last_junctor is None and ' and ' or last_junctor.lstrip('"').rstrip('"') self.urlname = urlname def render(self, context): tags = parse_tag_input(self.tags_string.resolve(context)) tags = ['<a href="%s" rel="tag">%s</a>' % (url_reverse(self.urlname, kwargs={'tag':t}), t) for t in tags] if len(tags) > 2: first_part = self.junctor.join(tags[:-1]) return first_part + self.last_junctor + tags[-1] if len(tags) == 2: return self.last_junctor.join(tags) return self.junctor.join(tags) @register.tag('object_tags') def tags_for_object(parser, token): """ Simple tag for rendering tags of an object Usage:: {% object_tags object.tags blog-tag ", " " and " %} The last two arguments determine the junctor between the tag names with the last being the last junctor being used. """ variables = token.split_contents()[1:] return TagsForObjectNode(*variables)
zerok/django-zsutils
django_zsutils/templatetags/zsutils/taghelpers.py
Python
bsd-3-clause
1,704
package edu.ehu.galan.cvalue; /* * ProcessLinguisticFilters.java * Copyright (C) 2013 Angel Conde, neuw84 at gmail dot com * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ import com.google.common.base.CharMatcher; import edu.ehu.galan.cvalue.filters.ILinguisticFilter; import edu.ehu.galan.cvalue.model.Token; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class take the tokenized text, and process it through the desired filters * * @author Angel Conde Manjon */ public class ProcessLinguisticFilters { private List<LinkedList<Token>> text; private final List<ILinguisticFilter> filterList; private List<Candidate> candidates; private final Logger logger=LoggerFactory.getLogger(this.getClass()); /** * Main constructor */ public ProcessLinguisticFilters() { filterList = new ArrayList<>(); } /** * adds a linguistic filter to be processed * * @param filter */ public void addFilter(ILinguisticFilter filter) { filterList.add(filter); } /** * takes a tokenized text, and get a list of candidates processing all the linguistic filters * * @param text * @return */ public List<Candidate> processText(List<LinkedList<Token>> text) { candidates = new ArrayList<>(); for (LinkedList<Token> linkedList : text) { for (ILinguisticFilter filter : filterList) { List<String> tempCandidates = filter.getCandidates(linkedList); for (String string : tempCandidates) { // System.out.println(string); Candidate cand = new Candidate(string, string.split("\\s").length); candidates.add(cand); } } } List<Candidate> cleaned = cleanCandidates(candidates); Collections.sort(cleaned,(cand1,cand2) -> cand1.getLenght()> cand2.getLenght()? -1 : cand1.getLenght() == cand2.getLenght() ? 0 : 1); return cleaned; } private List<Candidate> cleanCandidates(List<Candidate> candidates) { List<Candidate> cand = new ArrayList<>(); for (Candidate candidate : candidates) { String printable = CharMatcher.INVISIBLE.removeFrom(candidate.getText()); int size = candidate.getText().length(); if (printable.length() > 0) { if (!cand.contains(candidate)) { candidate.incrementFreq(1); cand.add(candidate); } else { int idx = cand.indexOf(candidate); cand.get(idx).incrementFreq(1); } } } if(cand.size()>60000){ logger.warn("The candidates of CValue are > 5.000 .... an empty list will be returned"); List<Candidate> cands=new ArrayList<>(); return cands; } return cand; } public int getNumberOfFilters() { return filterList.size(); } }
Neuw84/CValue-TermExtraction
src/main/java/edu/ehu/galan/cvalue/ProcessLinguisticFilters.java
Java
bsd-3-clause
3,818
module SpreeFavorites class Engine < Rails::Engine require 'spree/core' isolate_namespace Spree engine_name 'spree_favorites' config.autoload_paths += %W(#{config.root}/lib) # use rspec for tests config.generators do |g| g.test_framework :rspec end def self.activate Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c| Rails.configuration.cache_classes ? require(c) : load(c) end end config.to_prepare &method(:activate).to_proc end end
spree-contrib/spree_favorites
lib/spree_favorites/engine.rb
Ruby
bsd-3-clause
542
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.imagepipeline.producers; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.Executor; import android.content.ContentResolver; import android.database.Cursor; import android.media.ExifInterface; import android.net.Uri; import android.provider.MediaStore; import android.util.Pair; import com.facebook.common.internal.ImmutableMap; import com.facebook.common.internal.VisibleForTesting; import com.facebook.common.references.CloseableReference; import com.facebook.common.util.UriUtil; import com.facebook.imageformat.ImageFormat; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.image.EncodedImage; import com.facebook.imagepipeline.memory.PooledByteBuffer; import com.facebook.imagepipeline.memory.PooledByteBufferFactory; import com.facebook.imagepipeline.memory.PooledByteBufferInputStream; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imageutils.BitmapUtil; import com.facebook.imageutils.JfifUtil; /** * A producer that retrieves exif thumbnails. * * <p>At present, these thumbnails are retrieved on the java heap before being put into native * memory. */ public class LocalExifThumbnailProducer implements ThumbnailProducer<EncodedImage> { private static final int COMMON_EXIF_THUMBNAIL_MAX_DIMENSION = 512; @VisibleForTesting static final String PRODUCER_NAME = "LocalExifThumbnailProducer"; @VisibleForTesting static final String CREATED_THUMBNAIL = "createdThumbnail"; private final Executor mExecutor; private final PooledByteBufferFactory mPooledByteBufferFactory; private final ContentResolver mContentResolver; public LocalExifThumbnailProducer( Executor executor, PooledByteBufferFactory pooledByteBufferFactory, ContentResolver contentResolver) { mExecutor = executor; mPooledByteBufferFactory = pooledByteBufferFactory; mContentResolver = contentResolver; } /** * Checks whether the producer may be able to produce images of the specified size. This makes no * promise about being able to produce images for a particular source, only generally being able * to produce output of the desired resolution. * * <p> In this case, assumptions are made about the common size of EXIF thumbnails which is that * they may be up to 512 pixels in each dimension. * * @param resizeOptions the resize options from the current request * @return true if the producer can meet these needs */ @Override public boolean canProvideImageForSize(ResizeOptions resizeOptions) { return ThumbnailSizeChecker.isImageBigEnough( COMMON_EXIF_THUMBNAIL_MAX_DIMENSION, COMMON_EXIF_THUMBNAIL_MAX_DIMENSION, resizeOptions); } @Override public void produceResults( final Consumer<EncodedImage> consumer, final ProducerContext producerContext) { final ProducerListener listener = producerContext.getListener(); final String requestId = producerContext.getId(); final ImageRequest imageRequest = producerContext.getImageRequest(); final StatefulProducerRunnable cancellableProducerRunnable = new StatefulProducerRunnable<EncodedImage>( consumer, listener, PRODUCER_NAME, requestId) { @Override protected EncodedImage getResult() throws Exception { final Uri sourceUri = imageRequest.getSourceUri(); final ExifInterface exifInterface = getExifInterface(sourceUri); if (exifInterface == null || !exifInterface.hasThumbnail()) { return null; } byte[] bytes = exifInterface.getThumbnail(); PooledByteBuffer pooledByteBuffer = mPooledByteBufferFactory.newByteBuffer(bytes); return buildEncodedImage(pooledByteBuffer, exifInterface); } @Override protected void disposeResult(EncodedImage result) { EncodedImage.closeSafely(result); } @Override protected Map<String, String> getExtraMapOnSuccess(final EncodedImage result) { return ImmutableMap.of(CREATED_THUMBNAIL, Boolean.toString(result != null)); } }; producerContext.addCallbacks( new BaseProducerContextCallbacks() { @Override public void onCancellationRequested() { cancellableProducerRunnable.cancel(); } }); mExecutor.execute(cancellableProducerRunnable); } @VisibleForTesting ExifInterface getExifInterface(Uri uri) throws IOException { final String realPath = getRealPathFromUri(uri); if (canReadAsFile(realPath)) { return new ExifInterface(realPath); } return null; } private EncodedImage buildEncodedImage( PooledByteBuffer imageBytes, ExifInterface exifInterface) { Pair<Integer, Integer> dimensions = BitmapUtil.decodeDimensions(new PooledByteBufferInputStream(imageBytes)); int rotationAngle = getRotationAngle(exifInterface); int width = dimensions != null ? dimensions.first : EncodedImage.UNKNOWN_WIDTH; int height = dimensions != null ? dimensions.second : EncodedImage.UNKNOWN_HEIGHT; EncodedImage encodedImage = new EncodedImage(CloseableReference.of(imageBytes)); encodedImage.setImageFormat(ImageFormat.JPEG); encodedImage.setRotationAngle(rotationAngle); encodedImage.setWidth(width); encodedImage.setHeight(height); return encodedImage; } // Gets the correction angle based on the image's orientation private int getRotationAngle(final ExifInterface exifInterface) { return JfifUtil.getAutoRotateAngleFromOrientation( Integer.parseInt(exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION))); } /** * Get the path of a file from the Uri * @param srcUri The source uri * @return The Path for the file or null if doesn't exists */ private String getRealPathFromUri(final Uri srcUri) { String result = null; if (UriUtil.isLocalContentUri(srcUri)) { Cursor cursor = null; try { cursor = mContentResolver.query(srcUri, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); result = cursor.getString(idx); } } finally { if (cursor != null) { cursor.close(); } } } else if (UriUtil.isLocalFileUri(srcUri)) { result = srcUri.getPath(); } return result; } @VisibleForTesting boolean canReadAsFile(String realPath) throws IOException { if (realPath == null) { return false; } final File file = new File(realPath); return file.exists() && file.canRead(); } }
mikandi/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/producers/LocalExifThumbnailProducer.java
Java
bsd-3-clause
7,144
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // test aligned operator delete replacement. // UNSUPPORTED: sanitizer-new-delete, c++98, c++03, c++11, c++14 // None of the current GCC compilers support this. // UNSUPPORTED: gcc-5, gcc-6 // Aligned allocation was not provided before macosx10.14 and as a result we // get availability errors when the deployment target is older than macosx10.14. // However, AppleClang 10 (and older) don't trigger availability errors, and // Clang < 8.0 doesn't warn for 10.13. // XFAIL: !(apple-clang-9 || apple-clang-10 || clang-7) && availability=macosx10.13 // XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.12 // XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.11 // XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.10 // XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.9 // On AppleClang 10 (and older), instead of getting an availability failure // like above, we get a link error when we link against a dylib that does // not export the aligned allocation functions. // XFAIL: (apple-clang-9 || apple-clang-10) && with_system_cxx_lib=macosx10.12 // XFAIL: (apple-clang-9 || apple-clang-10) && with_system_cxx_lib=macosx10.11 // XFAIL: (apple-clang-9 || apple-clang-10) && with_system_cxx_lib=macosx10.10 // XFAIL: (apple-clang-9 || apple-clang-10) && with_system_cxx_lib=macosx10.9 // On Windows libc++ doesn't provide its own definitions for new/delete // but instead depends on the ones in VCRuntime. However VCRuntime does not // yet provide aligned new/delete definitions so this test fails to compile/link. // XFAIL: LIBCXX-WINDOWS-FIXME #include <new> #include <cstddef> #include <cstdlib> #include <cassert> #include "test_macros.h" constexpr auto OverAligned = __STDCPP_DEFAULT_NEW_ALIGNMENT__ * 2; int unsized_delete_called = 0; int unsized_delete_nothrow_called = 0; int aligned_delete_called = 0; void reset() { unsized_delete_called = 0; unsized_delete_nothrow_called = 0; aligned_delete_called = 0; } void operator delete(void* p) TEST_NOEXCEPT { ++unsized_delete_called; std::free(p); } void operator delete(void* p, const std::nothrow_t&) TEST_NOEXCEPT { ++unsized_delete_nothrow_called; std::free(p); } void operator delete [] (void* p, std::align_val_t) TEST_NOEXCEPT { ++aligned_delete_called; std::free(p); } struct alignas(OverAligned) A {}; struct alignas(std::max_align_t) B {}; int main(int, char**) { reset(); { B *b = new B[2]; DoNotOptimize(b); assert(0 == unsized_delete_called); assert(0 == unsized_delete_nothrow_called); assert(0 == aligned_delete_called); delete [] b; DoNotOptimize(b); assert(1 == unsized_delete_called); assert(0 == unsized_delete_nothrow_called); assert(0 == aligned_delete_called); } reset(); { A *a = new A[2]; DoNotOptimize(a); assert(0 == unsized_delete_called); assert(0 == unsized_delete_nothrow_called); assert(0 == aligned_delete_called); delete [] a; DoNotOptimize(a); assert(0 == unsized_delete_called); assert(0 == unsized_delete_nothrow_called); assert(1 == aligned_delete_called); } return 0; }
endlessm/chromium-browser
third_party/llvm/libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/delete_align_val_t_replace.pass.cpp
C++
bsd-3-clause
3,639
<?php namespace TijsVerkoyen\Bpost; use TijsVerkoyen\Bpost\Exception; use TijsVerkoyen\Bpost\Geo6\Poi; /** * Geo6 class * * @author Tijs Verkoyen <php-bpost@verkoyen.eu> * @version 3.0.0 * @copyright Copyright (c), Tijs Verkoyen. All rights reserved. * @license BSD License */ class Geo6 { // URL for the api const API_URL = 'http://taxipost.geo6.be/Locator'; // current version const VERSION = '3'; /** * @var string */ private $appId; /** * @var string */ private $partner; /** * The timeout * * @var int */ private $timeOut = 10; /** * The user agent * * @var string */ private $userAgent; /** * Constructor * @param string $partner Static parameter used for protection/statistics * @param string $appId Static parameter used for protection/statistics */ public function __construct($partner, $appId) { $this->setPartner((string) $partner); $this->setAppId((string) $appId); } /** * Build the url to be called * * @param string $method * @param array|null $parameters * @return string */ private function buildUrl($method, $parameters = null) { // add credentials $parameters['Function'] = $method; $parameters['Partner'] = $this->getPartner(); $parameters['AppId'] = $this->getAppId(); $parameters['Format'] = 'xml'; return self::API_URL . '?' . http_build_query($parameters); } /** * Make the real call * * @param string $method * @param array|null $parameters * @return SimpleXMLElement */ private function doCall($method, $parameters = null) { $options[CURLOPT_URL] = $this->buildUrl($method, $parameters); $options[CURLOPT_USERAGENT] = $this->getUserAgent(); $options[CURLOPT_FOLLOWLOCATION] = true; $options[CURLOPT_SSL_VERIFYPEER] = false; $options[CURLOPT_SSL_VERIFYHOST] = false; $options[CURLOPT_RETURNTRANSFER] = true; $options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut(); $curl = curl_init(); // set options curl_setopt_array($curl, $options); // execute $response = curl_exec($curl); $errorNumber = curl_errno($curl); $errorMessage = curl_error($curl); // error? if ($errorNumber != '') { throw new Exception($errorMessage, $errorNumber); } // we expect XML so decode it $xml = @simplexml_load_string($response); // validate xml if ($xml === false || (isset($xml->head) && isset($xml->body))) { throw new Exception('Invalid XML-response.'); } // catch generic errors if (isset($xml['type']) && (string) $xml['type'] == 'TaxipostLocatorError') { throw new Exception((string) $xml->txt); } // return return $xml; } /** * @param string $appId */ public function setAppId($appId) { $this->appId = $appId; } /** * @return string */ public function getAppId() { return $this->appId; } /** * @param string $partner */ public function setPartner($partner) { $this->partner = $partner; } /** * @return string */ public function getPartner() { return $this->partner; } /** * Set the timeout * After this time the request will stop. You should handle any errors triggered by this. * * @param int $seconds The timeout in seconds. */ public function setTimeOut($seconds) { $this->timeOut = (int) $seconds; } /** * Get the timeout that will be used * * @return int */ public function getTimeOut() { return (int) $this->timeOut; } /** * Get the useragent that will be used. * Our version will be prepended to yours. * It will look like: "PHP Bpost/<version> <your-user-agent>" * * @return string */ public function getUserAgent() { return (string) 'PHP Bpost Geo6/' . self::VERSION . ' ' . $this->userAgent; } /** * Set the user-agent for you application * It will be appended to ours, the result will look like: "PHP Bpost/<version> <your-user-agent>" * * @param string $userAgent Your user-agent, it should look like <app-name>/<app-version>. */ public function setUserAgent($userAgent) { $this->userAgent = (string) $userAgent; } // webservice methods /** * The GetNearestServicePoints web service delivers the nearest bpost pick-up points to a location * * @param string $street Street name * @param string $number Street number * @param string $zone Postal code and/or city * @param string $language Language, possible values are: nl, fr * @param int $type Requested point type, possible values are: * 1: Post Office * 2: Post Point * 3: (1+2, Post Office + Post Point) * 4: bpack 24/7 * 7: (1+2+4, Post Office + Post Point + bpack 24/7) * @param int $limit * @return array */ public function getNearestServicePoint($street, $number, $zone, $language = 'nl', $type = 3, $limit = 10) { $parameters = array(); $parameters['Street'] = (string) $street; $parameters['Number'] = (string) $number; $parameters['Zone'] = (string) $zone; $parameters['Language'] = (string) $language; $parameters['Type'] = (int) $type; $parameters['Limit'] = (int) $limit; $xml = $this->doCall('search', $parameters); if (!isset($xml->PoiList->Poi)) { throw new Exception('Invalid XML-response'); } $pois = array(); foreach ($xml->PoiList->Poi as $poi) { $pois[] = array( 'poi' => Poi::createFromXML($poi->Record), 'distance' => (float) $poi->Distance, ); } return $pois; } /** * The GetServicePointDetails web service delivers the details for a bpost * pick up point referred to by its identifier. * * @param string $id Requested point identifier * @param string $language Language, possible values: nl, fr * @param int $type Requested point type, possible values are: * 1: Post Office * 2: Post Point * 4: bpack 24/7 * @return Poi */ public function getServicePointDetails($id, $language = 'nl', $type = 3) { $parameters = array(); $parameters['Id'] = (string) $id; $parameters['Language'] = (string) $language; $parameters['Type'] = (int) $type; $xml = $this->doCall('info', $parameters); if (!isset($xml->Poi->Record)) { throw new Exception('Invalid XML-response.'); } return Poi::createFromXML($xml->Poi->Record); } /** * @param $id * @param string $language * @param int $type * @return string */ public function getServicePointPage($id, $language = 'nl', $type = 3) { $parameters = array(); $parameters['Id'] = (string) $id; $parameters['Language'] = (string) $language; $parameters['Type'] = (int) $type; return $this->buildUrl('page', $parameters); } }
kouinkouin/bpost
src/Geo6.php
PHP
bsd-3-clause
7,785
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta http-equiv=Content-Type content="text/html; charset=GB2312"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 9"> <meta name=Originator content="Microsoft Word 9"> <link rel=File-List href="./»°ËµÃÀ¹úÅãÉóÍÅÖÆ¶ÈµÄ³¤¶Ì_files/filelist.xml"> <title>»°ËµÃÀ¹úÅãÉóÍÅÖÆ¶ÈµÄ³¤¶Ì</title> <!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Author>Zhengyi</o:Author> <o:Template>Normal</o:Template> <o:LastAuthor>windows user</o:LastAuthor> <o:Revision>2</o:Revision> <o:TotalTime>783</o:TotalTime> <o:LastPrinted>2003-12-12T23:12:00Z</o:LastPrinted> <o:Created>2003-12-16T14:32:00Z</o:Created> <o:LastSaved>2003-12-16T14:32:00Z</o:LastSaved> <o:Pages>7</o:Pages> <o:Words>918</o:Words> <o:Characters>5233</o:Characters> <o:Lines>43</o:Lines> <o:Paragraphs>10</o:Paragraphs> <o:CharactersWithSpaces>6426</o:CharactersWithSpaces> <o:Version>9.3821</o:Version> </o:DocumentProperties> </xml><![endif]--><!--[if gte mso 9]><xml> <w:WordDocument> <w:Compatibility> <w:UseFELayout/> </w:Compatibility> </w:WordDocument> </xml><![endif]--> <style> <!-- /* Font Definitions */ @font-face {font-family:ËÎÌå; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:»ªÎÄ¿¬Ìå; mso-font-alt:"Arial Unicode MS"; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:647 135200768 16 0 262303 0;} @font-face {font-family:"\@ËÎÌå"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"\@»ªÎÄ¿¬Ìå"; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:647 135200768 16 0 262303 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:ËÎÌå; mso-fareast-language:ZH-CN;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:274413664; mso-list-type:hybrid; mso-list-template-ids:1015200056 537419122 67698713 67698715 67698703 67698713 67698715 67698703 67698713 67698715;} @list l0:level1 {mso-level-number-format:japanese-counting; mso-level-text:µÚ%1£¬; mso-level-tab-stop:1.5in; mso-level-number-position:left; margin-left:1.5in; text-indent:-1.0in;} @list l1 {mso-list-id:1184593521; mso-list-type:hybrid; mso-list-template-ids:-1615570602 1917366520 67698713 67698715 67698703 67698713 67698715 67698703 67698713 67698715;} @list l1:level1 {mso-level-number-format:japanese-counting; mso-level-text:µÚ%1£¬; mso-level-tab-stop:1.5in; mso-level-number-position:left; margin-left:1.5in; text-indent:-1.0in;} ol {margin-bottom:0in;} ul {margin-bottom:0in;} --> </style> </head> <body lang=EN-US style='tab-interval:.5in'> <div class=Section1> <p class=MsoNormal align=center style='text-align:center'><span lang=ZH-CN style='font-size:14.0pt;mso-bidi-font-size:12.0pt;font-family:»ªÎÄ¿¬Ìå'>»°ËµÃÀ¹úÅãÉóÍÅÖÆ¶ÈµÄ³¤¶Ì</span><span style='font-size:14.0pt;mso-bidi-font-size:12.0pt;font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal align=center style='text-align:center'><span lang=ZH-CN style='font-size:14.0pt;mso-bidi-font-size:12.0pt;font-family:»ªÎÄ¿¬Ìå'>·½Ñæ</span><span style='font-size:14.0pt;mso-bidi-font-size:12.0pt;font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span style='font-family:»ªÎÄ¿¬Ìå'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p> <p class=MsoNormal align=center style='text-align:center'><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>£¨Ò»£©ÃÀ¹úÅãÉóÍÅÖÆ¶ÈÊÇÔõÑùµÄ£¿</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span style='font-family:»ªÎÄ¿¬Ìå'><span style='mso-tab-count: 1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span lang=ZH-CN>ÃÀ¹úµÄ·¨ÂÉÖÆ¶ÈÓëÖйúÓÐÈô¸ÉÏÔÖø²»Í¬¡£ÅãÉóÍÅÖÆ¶È£¬ÃÀ¹úÓУ¬ÖйúÎÞ£¬Õâ¾ÍÊÇÒ»¸öÖØ´óµÄÇø±ð¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ʲĩÊÇÅãÉóÍÅÖÆ¶È£¿¼´ÉèÁ¢ÅãÉóÍÅ£¬ºÍ·¨¹ÙÒ»Æð¹²Í¬½øÐÐÉóÅеÄÖÆ¶È¡£ÃÀ¹úÈ˰ÑÅãÉóÍÅÖÆ¶ÈÅõµÃºÜ¸ß£¬ÈÏΪÕâÊÇÃÀ¹ú·¨ÂÉÖÆ¶ÈµÄÒ»´óÓŵ㡣ÃÀ¹úµÚÈýÈÎ×Üͳ½Ü¸¥Ñ·Ôø¾­Ëµ£¬ÕâÖÖÉóÅÐÖÆ¶ÈÔÚά»¤ÃñÖ÷ÉÏ£¬±ÈÑ¡¾ÙȨ»¹ÖØÒª¡£Æäʵ£¬ÃÀ¹úµÄÅãÉóÍÅÖÆ¶È£¬ÓÐÓŵãÒ²ÓÐȱµã¡£¾ÍÏóÃÀ¹úµÄÃñÖ÷ÖÆ¶ÈÒ»Ñù£¬ÓÅȱµã¶¼ºÜÃ÷ÏÔÓëÍ»³ö¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÃÀ¹ú½øÐÐÉóÅУ¬²¢²»ÊǶ¼ÉèÅãÉóÍÅ¡£¾ü·¨ÉóÅв»ÉèÅãÉóÍÅ£»ÃñʺÍÐÌÊÂÉóÅÐÈç¹ûÔ­¸æ»ò±»¸æÒªÇóÉèÅãÉóÍŲÅÉèÁ¢£¬²»ÒªÇóÒ²²»ÉèÁ¢¡£ËùÒÔ£¬°Ù·ÖÖ®¾ÅÊ®µÄÃñÊÂÓëÐÌʰ¸¼þ¶¼ÊÇÓÉ·¨¹Ùµ¥¶ÀÉóÅУ¬²»¾­ÅãÉóÍÅ£»Ö»ÓдóÔ¼°Ù·Ö֮ʮµÄ°¸¼þ£¬¾­ÅãÉóÍÅÉóÅС£ÆäÄ¿µÄÊDZ£Ö¤ÉóÅеĹ«Õý¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÅãÉóÍÅÈËÊý¿É¶à¿ÉÉÙ£¬×îÉÙ</span><span style='font-family:»ªÎÄ¿¬Ìå'>3<span lang=ZH-CN>ÈË£¬×î¶à¿É´ï</span>23<span lang=ZH-CN>ÈË£¬Ò»°ãÊÇ</span>12<span lang=ZH-CN>ÈË¡£·²ÊÇÃÀ¹ú¹«Ãñ£¬ÄêÂú</span>18<span lang=ZH-CN>Ë꣬ÔÚ°¸·¢µÄ·¨ÔºÏ½ÇøÄڹ̶¨¾Óס£¬¶¼ÓÐȨÀûºÍÒåÎñµ£ÈÎÅãÉóÔ±¡£±ÊÕßÇ×ÓÑÖУ¬ÓÐÈËÈëÁËÃÀ¹ú¹ú¼®£¬²»¾Ã¾ÍÊÕµ½Ò»·Ý֪ͨ£¬ËµÃ÷ÃÀ¹ú¹«Ãñ°´ÕÕÏÜ·¨ºÍ·¨ÂÉÓе£ÈÎÅãÉóÔ±µÄÒåÎñ£¬²¢ÇÒÒªÇóÈçʵÌîдһ·ÝÏ൱ÏêϸµÄµÇ¼Ç±í¸ñ£¬ÒÔ¹©Ë¾·¨²¿ÃÅåàÑ¡¡£±í¸ñ¾­¹ýÉó²é£¬ÈÏΪºÏ¸ñ£¬Ôò°ÑÄãÁÐÈëºòÑ¡ÅãÉóÔ±Ãû²á¡£Ò»µ©Óа¸¼þ·¢Éú£¬ÐèÒªÄã×öÅãÉóԱʱ£¬¾Í»á֪ͨÄãÈ¥±¨µ½¡£·¨Âɹ涨£¬Ìá²»³öÕýµ±ÀíÓɶø²»±¨µ½£¬ÊÇÎ¥·¨µÄ¡£³äµ±ÅãÉóԱʱ£¨²ÎÓëÉóÅй¤×÷ÆÚ¼ä£¬²»ÊǵǼdzÉΪºòÑ¡ÉóÅÐÔ±ÆÚ¼ä£©£¬»á·¢¸øÒ»¶¨½òÌù£¨Ï൱ÖеÈÊÕÈëµÄƽ¾ùˮƽ£¬ËùÒÔÊÕÈë¸ßµÄÈ˲»Ô¸Òâµ±ÅãÉóÔ±£¬ÊÕÈëµÍµÄÈ˾õµÃµ±ÅãÉóÔ±Ò²²»´í£©£¬ÒÔ²¹³¥ÅãÉóÔ±Î󹤵ÄËðʧ£¬²¢ÇÒ¿É´úÏòËùÔÚµ¥Î»Ç빫¼Ù¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>åàÑ¡ÅãÉóÔ±ÊÇÒ»¼þºÜ¸´ÔÓµÄÊÂÇ飬ÓÐʱҪ·ÑºÜ³¤Ê±¼ä£¬ÓÐЩ±»¸æ»¹¹ÊÒâÏë·½Éè·¨Íϳ¤åàÑ¡ÅãÉóÔ±µÄʱ¼ä¡£¸ºÔð½øÐÐåàÑ¡µÄÊÇ·¨¹ÙºÍË«·½ÂÉʦ¡£åàÑ¡µÄÌõ¼þÊÇ£º·²Óë±»¸æºÍÔ­¸æÓÐÈκιØÁªµÄÈË£¬¶¼²»Äܳ䵱¸Ã°¸ÅãÉóÔ±£»ÓÐЩÐÐÒµ£¬Èçҽʦ</span><span style='font-family:»ªÎÄ¿¬Ìå'> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>ÂÉʦ</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>½ÌʦµÈ£¬ÒòΪÈÝÒ×ÓëÔ­¸æ±»¸æÓÐÖ±½Ó»ò¼ä½ÓÇ£Á¬£¬Ò²±»Åųý¡£ÓеÄÖÝ»¹¹æ¶¨éëÒǹݹ¤×÷ÈËÔ±²»µÃ×÷ÅãÉóÔ±£¬ÃâµÃËûÃÇÒòΪÏë¶àÀ­ÉúÒâ¶øÇáÒ×Å䦱»¸æËÀÐÌ¡£ÔÚÉϸöÊÀ¼ÍΪºä¶¯È«ÇòµÄéÏé­ÇòÐÇÐÁÆÖɭɱÈ˰¸£¨É±ËÀǰÆÞºÍËýµÄÇéÈË£©ÌôÑ¡ÅãÉóԱʱ£¬ÓÐÒ»Ãû¸¾Å®±»ÌÞ³ý£¬Ô­Òò½öÊÇÕâλ¸¾Å®ÊܹýÕÉ·òŰ´ý£¬µ£ÐÄËýÁªÏëÆð×Ô¼ºµÄ¾­Àú£¬¶ø¶ÔÐÁÆÖÉ­Óб¨¸´ÐÄÀí¡£ÌôÑ¡ÅãÉóԱʱ£¬ÐèÒª¾­¹ýÃæÌ¸£¬ÓÉ·¨¹Ù</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>±»¸æÂÉʦºÍÔ­¸æÂÉʦÏòºòÑ¡ÅãÉóÔ±ÌáÎÊ¡£ÀýÈ磬ÐÕÃû</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>סַ</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>Ö°Òµ</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>»éÒö×´¿ö</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>Åäż¼°³ÉÄê×ÓÅ®µÄÖ°Òµ£¬ÓÐÎÞ×÷ÅãÉó¹¤×÷µÄ¾­Ñ飿ÊÇ·ñÈÏʶԭ¸æ»ò±»¸æ£¿¶Ô±¾°¸ÊÇ·ñÖªÇ飿¶Ô±¾°¸ÓÐÎÞÆ«¼û£¿µÈµÈ¡£Èç¹û·¨¹Ù»òÈκÎÒ»·½µÄÂÉʦÈÏΪ²»Êʵ±£¬¶¼Óзñ¾öȨ£¬¿ÉÒÔÒªÇó¸ü»»ÅãÉóÔ±£¬Õâ¾ÍÓпÉÄܰÑåàѡʱ¼äÍϵúܳ¤¡£ÌôÑ¡ºÃÒԺ󣬱»Ñ¡ÖÐÕß¼¯ÌåÐûÊÄ£¬±¾°¸µÄÅãÉóÍż´Ðû¸æ³ÉÁ¢¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÅãÉóÔ±²ÎÓëÅãÉó¹¤×÷ÆÚ¼ä£¬ÓеÄÖݹ涨²»×¼»Ø¼Ò£¬±ØÐ뼯ÖÐסËÞÔÚ·¨ÔºÌرð°²ÅŵÄסËù£¬ÊµÐС°¸ôÀ롱£»ÓеÄÖÝÔÊÐíÅãÉóÔ±²ÎÓëÅãÉó¹¤×÷ÆÚ¼äÒ²¿ÉÒԻؼң¬µ«ÊDz»×¼ÓëÇׯÝÅóÓÑºÍÆäËûÈ˽»Ì¸ÌÖÂÛ±¾°¸¼þ£¬ÒÔÃâйÃܺÍÊÜÍâÈËÓ°Ïì¡£ÅãÉóÆÚ¼ä»¹²»×¼¿´ºÍÌýÓйر¾°¸¼þµÄµçÊÓ</span><span style='font-family:»ªÎÄ¿¬Ìå'> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>¹ã²¥</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>±¨Ö½ÔÓÖ¾µÄ±¨µÀ£¬ÒÔÃâÊÜÉç»áýÌåµÄÓ°Ïì¡£ÅãÉóÔ±²»ÊǾ¯²ì</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>Õì̽ºÍÂÉʦ£¬²»×¼Íâ³ö¶Ô°¸¼þ½øÐе÷²é</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>¿±²éÓëºËʵ¡£ÅãÉóÔ±ÔÚ·¨Í¥ÉÏûÓз¢ÑÔȨ£¬²»¿ÉÒÔÌáÎÊ£¬Ö»ÄÜ¿´ºÍÌý£¬ÉõÖÁ²»×¼ÔÚ·¨Í¥ÉÏ×÷±Ê¼Ç¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÅãÉóÍÅÔ±ÃǶ¼Òª²Î¼ÓÉóÅеÄÈ«¹ý³Ì¡£°üÀ¨Ìýȡԭ¸æ</span><span style='font-family:»ªÎÄ¿¬Ìå'> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>¼ì·½µÄ¿ØËߣ¬Ö¤È˵ÄÖ¤´Ê£¬Á½ÔìÂÉʦµÄ±çÂÛ£¬±»¸æµÄ³ÂÊöµÈµÈ¡£·¨Í¥µ÷²éºÍÉóѶ¸æÒ»¶ÎÂ䣬²Å¿ªÊ¼ÅãÉóÍÅÉóÒé¡£ÉóÒéʱ£¬Ê×ÏÈÓÉ·¨¹Ù¸øÅãÉóÔ±ÃÇ¡°ÉϿΡ±£¬Ïêϸ½²½âÓйر¾°¸µÄ·¨ÂÉÌõÎĺ͸÷Ïî¹æ¶¨£¬ÒÔ¼°ÈçºÎÕÆÎÕºÍʹÓÃÕâЩÌõÎĹ涨£»²¢ÇÒÐû²¼¼¸Ìõ×¢ÒâÊÂÏһÇÐÒÔ·¨ÂÉΪ׼Éþ£»²»¿É²ÎÓë¸öÈ˵ÄÏë·¨ºÍ¿´·¨£»²»¿ÉÓÐͬÇéÐÄ</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>Æ«¼û</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>ÆçÊÓºÍ˽È˸ÐÇéÇ£ÉæÔÚÄÚ£»ÒªÒÔÖ¤ÈËÖ¤ÎïΪÒÀ¾Ý£¬Ã»ÓÐÖ¤¾Ý¾Í²»ÄÜ×ö²Ã¾ö£»Ë«·½ÂÉʦµÄ»°¶¼²»¿ÉÇáÐŵȡ£È»ºóÓÉÅãÉóÍÅÔ±ÃÇ×ÔÐÐÌÖÂÛ¡£ÅãÉóÍÅÌÖÂÛʱ£¬×ÔÐÐÍÆ¾Ù³öÖ÷³ÖÈË£¬Õâ¸öÈ˼´×÷Ϊ´ú±í£¬ÔÚ×ö³ö²Ã¾öºó£¬¸ºÔðµ½·¨Í¥ÉÏÏò·¨¹ÙµÝ½»ÅãÉóÍŵÄÊéÃæÒâ¼û¡£ÔÚÌÖÂÛ¹ý³ÌÖУ¬ÅãÉóÍÅÈçÓÐÎÊÌ⣬¿ÉÏò·¨¹ÙÒªÇó´«Ñ¶Ö¤ÈË£¬µ÷ÔÄÖ¤ÎïºÍ·¨Í¥ÉóѶ¼Í¼¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÅãÉóÍÅÖ»¸ºÔð²Ã¾ö£¬ÊÇÓÐ×ﻹÊÇÎÞ×ÊÇʲĩ×²»¸ºÔðÁ¿ÐÌ¡£ÅãÉóÍÅ×ö³öµÄ²Ã¾ö¾ÍÊÇ¡°×îºóÅоö¡±£¬·¨¹ÙÎÞȨ¸ü¸Ä±ä¶¯¡£·¨¹Ù¸ù¾ÝÅãÉóÍŲþöµÄ×ïÃû£¬ÒÀ·¨Á¿ÐÌ£¬È»ºó¿ªÍ¥ÕýʽÐûÅС£·¨¹ÙÐûÅÐʱ£¬È«ÌåÅãÉóÍÅÔ±³öÍ¥Åãͬ¡££¨×¢£ºÃÀ¹úÊÇÁª°îÖÆ¹ú¼Ò£¬¸÷Öݵķ¨Âɲ»ÍêÈ«Ïàͬ£¬Ò²ÓеÄÖÝÅãÉóÍÅͬʱ¸ºÔðÁ¿ÐÌ£¬¾ö¶¨ÐÌÆÚ³¤¶ÌºÍ·£¿î¶àÉÙ£©¡£ÓÉÓÚÅãÉóÍŵIJþöÊÇ¡°×îºóÅоö¡±£¬Í¨³£ÊDz»×¼ÉÏËߵġ£²»¹ý£¬Ò²ÓÐÀýÍâ¡£ÄǾÍÊDZ»¸æÂÉʦ»ò¼ì²ì¹Ù´ÓÅãÉóÍŵÄÉ󰸼¼Êõ»ò³ÌÐòÉÏÕÒ³ö벡£¬Ò²¿ÉÒÔÌá³öÉÏËß¡£Èç¹ûÉÏËß±»Éϼ¶·¨ÔºÊÜÀí£¬ÄÇÄ©£¬ÅãÉóÍŵÄÅоö¾ÍÓпÉÄܱ»Ðû²¼ÎÞЧ¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÅãÉóÍÅʵÐС°Ò»ÖÂͨ¹ý¡±µÄÔ­Ôò£¬¶ø²»ÊÇ¡°ÉÙÊý·þ´Ó¶àÊý¡±Ô­Ôò¡£Ò»ÖÂͨ¹ý²¢²»×ÜÊǺÜÈÝÒ׵ģ¬ÓÐʱҪ»¨·Ñ¼¸Ììʱ¼ä£¬·´¸´ÔÍÄ𣬽»»»Òâ¼û¡£Èç¹ûÓÐÒ»¸öÈ˼á³Ö¼º¼û£¬²»Í¬Ò⣬¾Í×÷²»³öÅоö¡£×÷²»³öÅоö£¬½Ð×ö</span><span style='font-family:»ªÎÄ¿¬Ìå'>Hung<span style="mso-spacerun: yes">&nbsp; </span>Lury <span lang=ZH-CN>£¨ÒâÒëÊÇ£º±»ÅãÉóÍÅ¡°¹ÒÆðÀ´¡±£©¡£¾Ý˵´óÔ¼ÓаٷÖÖ®Îå×óÓҵݸ¼þ×ö²»³öÅоö£¬¡°¹ÒÆðÀ´¡±¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>¡°¹ÒÆðÀ´¡±µÄ°¸¼þ£¬Ö÷ÒªÓÐÈýÖÖ³ö·£ºÒ»ÊÇÖØÉó¡£ÖØÐÂåàÑ¡ÅãÉóÍÅ£¬Ò»ÇÐÉóÅй¤×÷ÖØÀ´Ò»±é£º¶þÊÇÑØÆäËû;¾¶½â¾ö£¬ÀýÈ磬Óеݸ¼þͨ¹ýÍ¥Íâµ÷½â¶øÁ˽ᡣÈýÊDz»ÁËÁËÖ®£¬Ö÷ÒªÊÇÉóÅÐÍÏÑÓ»ýÄêÀÛÔ£¬Ô­¸æºÍ¼ì·½¸ºµ£²»Æðʱ¼äºÍ½ðÇ®µÄ¾Þ¶îºÄ·Ñ¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span style='font-family:»ªÎÄ¿¬Ìå'><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span lang=ZH-CN>£¨¶þ£©ÃÀ¹úÅãÉóÍÅÖÆ¶ÈµÄºÃ´¦</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÃÀ¹úʵÐÐÅãÉóÍÅÖÆ¶È£¬È·ÊµÓкô¦£º</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l1 level1 lfo1; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚÒ»£¬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÈËÃñÖ±½Ó²ÎÓë˾·¨¹¤×÷£¬ÌåÏÖÁËÈËÃñµÄÃñÖ÷ȨÀû£¬¿ÉÒÔÔöÇ¿Ãñ</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÖÚ¶Ô¹ú¼ÒµÄÈÏͬ¸ÐºÍ°®¹úÐÄ¡£ÔÚÃÀ¹ú£¬ÐÂÒÆÃñÈëÁËÃÀ¹ú¹ú¼®£¬Óм¸·½ÃæºÃ´¦£ºÃÀ¹ú¶Ô¹«ÃñµÄ±£»¤ÏÔÖøÓÅÓڶԷǹ«Ãñ£¨°üÀ¨ºÏ·¨ÓÀ¾Ã¾ÓÃñ£©£»¹«Ãñ±È·Ç¹«Ãñ¸üÈÝÒ×¾ÍÒµ£»ÏíÊܹ«Ãñ²ÅÄÜÏíÊܵÄÉç»á¸£Àû´ýÓö£»ÏíÓÐÑ¡¾ÙȨ±»Ñ¡È¨ºÍ×÷ÅãÉóÔ±µÄȨÀûµÈ¡£ËùÒÔÐÂÒÆÃñ±»åàÑ¡×÷ÅãÉóÔ±£¬ÐÄÇéÉÏÊǸßÐ˺ÍÐ˷ܵģ¬ÈÏΪ×Ô¼ºÒ²±»ÃÀ¹úÐÅÈΣ¬ÓÐÁ˲ÎÓë˾·¨¹¤×÷µÄȨÀû¡£Ò»Î»²ÎÓë¹ýËÄ´ÎÅãÉó¹¤×÷µÄ»ªÈË£¬×«ÎĽéÉÜ×Ô¼ºµÄ¾­Àú£¬½áÂÛдµÀ£º¡°ÎÒÒÔ»ñÑ¡ÅãÉóԱΪÈÙ£¬ÔÚÅãÉóÖлñÒæ·Ëdz¡£Ï£Íû»ªÈËÃǶ¼ÄÜÁ˽âÕâÒ»ÖÆ¶È£¬²»Òª·ÅÆúµ±ÅãÉóÔ±µÄ»ú»á¡£¡±</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span style='font-family:»ªÎÄ¿¬Ìå'><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span lang=ZH-CN>²»¹ý»ªÈËÐÂÒÆÃñµ±ÅãÉóÔ±µÄÏ൱ÉÙ£¬Ô­ÒòÖ÷ÒªÓÐÁ½¸ö£ºÒ»ÊÇÓ¢Óïˮƽ²»¹ý¹Ø¡£²ÎÓëÅãÉó¹¤×÷£¬Ó¢Óï±ØÐëÍêÈ«¹ý¹Ø£¬ÒòΪÌÖÂÛ·ÖÎö°¸¼þÖ»»áÈÕ³£Éú»îÓÃÓïÊǺܲ»¹»µÄ¡£³ýÁËÓ¢Ó»¹ÐèÒª¶ÔÃÀ¹úµÄÉç»áÇé¿öºÍ·çË×ϰ¹ßµÈ¶¼±È½ÏÊìϤ£¬·ñÔòÒ²ÄÑʤÈÎÅãÉó¹¤×÷¡£¶þ£¬ÐÂÒÆÃñæÓÚΪıÉú¶ø±¼²¨£¬µ£Ðij䵱ÅãÉóÔ±Ó°Ïì×Ô¼ºµÄÉúÒâ»ò¹¤×÷£¬¾­³£Ïë·½Éè·¨ÕÒ³öÀíÓÉÍÆ´Çµô¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l1 level1 lfo1; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚ¶þ£¬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÆÕ¼°·¨ÂÉ֪ʶ£¬ÔöÇ¿ÃñÖڵķ¨ÖƹÛÄî¡£ÒòΪÊÇÔÚÃÀ¹ú¹«ÃñÖйã</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>·ºÕ÷¼¯ÅãÉóÔ±£¬¶ø²ÎÓëÅãÉó¹¤×÷µÄµÚÒ»²½¾ÍÊǽÓÊÜ·¨¹Ù¡°»îµÄ·¨ÂɽÌÓý¡±£¬ËùÒÔʵÐÐÅãÉóÍÅÖÆ¶È¶ÔÃÀ¹úµÄ·¨Öƽ¨É裬Óлý¼«µÄ×÷Óá£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l1 level1 lfo1; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚÈý£¬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>¿ÉÒÔ·ÀÖ¹·¨¹ÙÆ«ÌýÆ«ÐÅ£¬¶À¶ÏרÐУ¬³öÏÖÎóÅдíÅУ»Ò²¿ÉÒÔ¶Â</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÈûijЩÐлßÊܻߵÄ;¾¶£¬·ÀֹijЩ̰ÔßÍ÷·¨ÏÖÏó¡£ÅãÉóÍÅÊÇÁÙʱ×é³ÉµÄ£¬Ò»¸öÍÅÖ»¸ºÔðÉóÅÐÒ»¸ö°¸¼þ£¬ÉóÅÐÍê¾Í½âÉ¢£»ÅãÉóÍÅÈËÊý½Ï¶à£¬ÉóÅÐÆÚ¼äÓÖÓëÍâ½ç¸ô¾ø£»ÖîÈç´ËÀàµÄÖÆ¶È¹æ¶¨£¬Ê¹ÐлßÏ൱À§ÄÑ¡£ËùÒÔÔÚÏ൱³¤µÄʱ¼äÀÅãÉóÍÅÖÆ¶È¶ÔÃÀ¹ú˾·¨µÄ¹«ÕýÓëÁ®½à£¬È·ÊµÆð¹ýÖØÒª×÷Óá£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>µ«ÊÇ£¬ÈκÎÖÆ¶È¶¼ÊÇÈËÃÇÔÚÒ»¶¨µÄʱ¼äµØµãºÍÌõ¼þÏÂÖÆ¶¨µÄ£¬²»¿ÉÄÜʮȫʮÃÀ£¬¸ü²»¿ÉÄܾø¶ÔÕýÈ·ºÁÎÞ©¶´¡£Ë×»°Ëµ£¬¡°µÀ¸ßÒ»³ß£¬Ä§¸ßÒ»ÕÉ¡±¡£ÃÀ¹úµÄÅãÉóÍÅÖÆ¶È½¨Á¢ºÍʵÐÐÁ˶þ°Ù¶àÄ꣬ÆäÖеı׶ËÒ²ÈÕÒæ±äµÃÍ»³ö¶øÑÏÖØ¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span style='font-family:»ªÎÄ¿¬Ìå'><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span lang=ZH-CN>£¨Èý£©º§ÈËÌýÎŵĻÄÌÆÅоö</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÃÀ¹úÅãÉóÍÅÖÆ¶ÈµÄ×î´ó±×¶ËÊÇÓÐÀûÓÚ±»¸æ£¬²»ÀûÓÚÔ­¸æ</span><span style='font-family:»ªÎÄ¿¬Ìå'> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>¼ì·½£¬ÈÝÒ×Ôì³ÉÇáÅУ¬ÉõÖÁ°ü±ÓºÍ·Å¹ý×ï·¸¡£Í¬Ê±£¬ÃÀ¹úµÄÅãÉóÍÅÖÆ¶È£¬Êµ¼ÊÉÏÓÐÀûÓÚ¸»ÈË£¬²»ÀûÓÚÇîÈË¡£</span>9<span lang=ZH-CN>Äêǰ·¢ÉúµÄÃÀ¹úÖøÃûéÏé­ÇòÐÇÐÁÆÖɭɱÈ˰¸£¬ÔÚÐÌÊÂÉóÅÐÖУ¬Ã÷Ã÷Ö¤¾ÝÈ·Ô䣬¾­ÂÉʦ½Æ±ç£¬ÅãÉóÍŶ϶¨Èô¸ÉÖ¤¾ÝÎÞЧ£¬×îºóÅоöɱÈË·¸¡°ÎÞ×ÊÍ·Å¡£¼«¾ß·í´ÌÒâζµÄÊÇ£¬ÔÚÃñÊÂÉóÅÐÖУ¬ÓÖÅоöÐÁÆÖÉ­¡°ÓÐ×£¬·£¿îÊýǧÍòÃÀÔª¡£³ÉΪÃÀ¹ú˾·¨Ê·ÉÏÒ»¼þµäÐ͵ĻÄÌÆÅоö¡£¶øÐÁÆÖÉ­¾ÍÊÇÓµÓм¸Ç§ÍòÃÀÔªµÄ¸»ºÀ¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÎÞ¶ÀÓÐż¡£×î½üÃÀ¹úÓÖ·¢ÉúÒ»ÆðÅãÉóÍÅÖÆÔìµÄº§ÈËÌýÎŵĻÄÌÆÆæ°¸¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ŦԼ·¿µØ²úÒÚÍò´ó¸»ºÀÂÞ²®ÌØ </span><span style='font-family:»ªÎÄ¿¬Ìå'>¨C <span lang=ZH-CN>µÂË¹ÌØ£¨</span>Robert<span style="mso-spacerun: yes">&nbsp; </span>Durst <span lang=ZH-CN>£©µÄµÚÒ»ÈÎÆÞ×Ó¿­Ë¼ÁÖÓÚ</span>1982<span lang=ZH-CN>Äê</span>1<span lang=ZH-CN>Ôµ×ÉñÃØÊ§×Ù¡£µ±Ê±ËûÃÇ·ò¸¾ÕýÄÖÀë»é¾À·×¡£¿­Ë¼ÁÖʧ×ÙµÄǰһÌìÍíÉÏ£¬ÕýÔڲμÓÒ»¸öÎè»á£¬Í»È»½Óµ½µÂË¹ÌØµÄµç»°¡£Ëý½ÓÍêµç»°¶ÔºÃÓѼª¶û²®ÌØËµ£ºÎÒ±ØÐë¸Ï»Ø¼ÒÈ¥£¬¡°ÍòÒ»ÎÒ·¢ÉúÁËʲĩ²»²â£¬Ò»¶¨ÒªÎªÎÒ²éÃ÷ÕæÏ࣬ºÃÂð£¿ÎÒÕæµ£ÐĵÂË¹ÌØ»á×ö³öʲĩ·è¿ñ¾Ù¶¯¡±¡£ËÄÌìºó£¬µÂË¹ÌØ±¨¾¯£¬Ëµ¿­Ë¼ÁÖʧ×Ù¡£¿­µÄÅóÓÑÃÇÎÞ²»¶ÔµÂË¹ÌØÑÏÖØ»³ÒÉ£¬µ«ÊǾ¯·½Ê¼ÖÕûÓвé³öÏßË÷¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span style='font-family:»ªÎÄ¿¬Ìå'>2000<span lang=ZH-CN>Ä꣬¾¯·½ÁªÂçÉÏ¿­Ë¹ÁֵĺÃÓÑÅ®×÷¼ÒËÕɺ </span>¨C <span lang=ZH-CN>²®Âü£¬ÒªËÕɺЭÖúµ÷²é¡£ËÕÉºÔøÏòµÂË¹ÌØÑ¯ÎÊ¿­Ë¼ÁÖʧ×ÙµÄÎÊÌâ¡£Æäºó£¬µÂË¹ÌØ¸øËÕɺ¼Ä¹ýÁ½ÕÅ֧Ʊ£¬Ã¿ÕŽð¶î</span>2 .<span style="mso-spacerun: yes">&nbsp; </span>5<span lang=ZH-CN>ÍòÃÀÔª£¬µÂ½âÊÍ˵ÊÇ¡°ËÍÀñ¡±¡£</span>2000<span lang=ZH-CN>Äê</span>12<span lang=ZH-CN>ÔÂ</span>11<span lang=ZH-CN>ÈÕ£¬ËÕɺͻȻÔÚ¼ÒÖб»ÈËǹɱ¡£¾¯·½¿±²ì£¬Ã»ÓÐÆÆÃŶøÈëµÄºÛ¼££¬×Óµ¯ÓÖÊÇ´ÓÄÔºóÉäÈëËÕɺͷ­£¬ËùÒÔÅжÏÊDZ»ËÕɺÈÏʶµÄÊìÈËËùɱ£¬²¢ÈÏΪµÂË¹ÌØÓÐÖØ´óÏÓÒÉ¡£µÂË¹ÌØÃ»Óгä·ÖÀíÓɽâÊÍΪʲĩ¸øËÕɺ¼Ä֧Ʊ£¬Ò²±»»³ÒÉÊÇΪÁË¡°·â¡±ËÕɺµÄ¿Ú¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span style='font-family:»ªÎÄ¿¬Ìå'>2001<span lang=ZH-CN>Äê</span>9<span lang=ZH-CN>ÔÂ</span>30<span lang=ZH-CN>ÈÕ£¬µÂ¿ËÈøË¹ÖݼӶûά˹¶ÙÊеĺ£Ì²ÉÏ·¢ÏÖÒ»¾ßûÓÐÍ·ºÍËÄÖ«µÄÇû¸É¡£×ªÌ죬ͬһˮÓòÀÌÆðÁ½Ö»´ü×Ó£¬Ò»Ö»×°×ÅÒ»ÌõÈËÍÈ£¬Ò»Ö»×°×ÅÁ½Ö§¸ì±Û¡£Í¬Ê±£¬¾¯·½»¹´ÓË®µ×À̳öһֻװן־âµÄËÜÁÏÌ×£¬Ò»ÕÅ´Óµ±µØÎå½ðµê¹ºÂòËÜÁÏ´üµÄ¹ºÎïµ¥£¬Ò»¼þÒ·þ£¬Ò»Õű¨Ö½¡£¾¯·½ºÜ¿ì²é³ö£¬ËÀÕßÊÇʧ×ÙµÄ</span>71<span lang=ZH-CN>ËêÀÏÈËĪÀï˹</span>¨C<span lang=ZH-CN>²¼À³¿Ë¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>¾¯·½ÔÚËѲ鲼À³¿ËסËùʱ·¢ÏÖ£¬ÓÐÒ»µÀѪ¼£Ò»Ö±ÑÓÉìµ½²¼À³¿ËÁÚ¾Ó¡°µÂÂåÎ÷ </span><span style='font-family:»ªÎÄ¿¬Ìå'>¨C<span lang=ZH-CN>ÐÁÄÈ¡±µÄ·¿¼ä¡£ÔÚ¶Ô¡°ÐÁÄÈ¡±¼Ò½øÐÐËѲéʱ£¬Ëѳöһ˫ѪÁÜÁÖµÄÑ¥×ÓºÍÒ»°Ñµ¶¡£¾Ý´ËÉîÈë×·²é£¬²éÃ÷ÕæÕýµÄ¡°ÐÁÄÈ¡±£¬ÊǵÂË¹ÌØµÄͬѧ£¬²¢²»Ôڵ¿ËÈøË¹ÖݾÓס¡£¶ø¼Ù¡°ÐÁÄÈ¡±ÕýÊǵÂË¹ÌØÄаçŮװð³äµÄ¡£¾¯·½Á¢¼´´þÆËÁ˵ÂË¹ÌØ¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>¾¯·½ÉóѶ¹ý³ÌÖУ¬µÂË¹ÌØÔÚÌúÖ¤ÃæÇ°£¬³ÐÈÏÁËɱËÀºÍÖ«½â²¼À³¿ËµÄ×ïÐС£Ëû½»´ú£¬ÄаçŮװð³ä¡°ÐÁÄÈ¡±µ½µÂ¿ËÈøË¹ÖݾÓס£¬ÊÇÒòΪǰÆÞʧ×ÙºÍËÕɺ±»É±£¬Ëû±»»³ÒÉ£¬¶ø½øÐÐÌӱܡ£Ëû˵£¬²»ÊÇÓÐÒâɱËÀ²¼À³¿Ë¡£ÆðÒòÊÇ£¬²¼À³¿ËÐÔÇ鱩Ô꣬Á½È˾­³£Õù³³£¬ÓÐʱ»¹´ó´ò³öÊÖ£¨´ËÒ»Çé½ÚÓÐÈËÖ¤Ã÷£©¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'>2001<span lang=ZH-CN>Äê</span>9<span lang=ZH-CN>ÔÂ</span>28<span lang=ZH-CN>ÈÕ£¬Ëû·¢ÏÖ²¼À³¿Ë½øÈëËûµÄס·¿£¬ÊÖ³ÖËûµÄǹ¡£Á½ÈËŤ´ò¹ý³ÌÖУ¬Ç¹×ßÁË»ð£¬ÉäÖв¼À³¿ËÁ³²¿ÖÂËÀ¡£Ëû¡°ÏÅ»µÁË£¬º¦Å¾¯·½²»ÏàÐÅËûËù˵µÄ¾­¹ý¡±£¬ËùÒÔÖ«½âʬÌ壬Å×ʬÃ𼣡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>·¨ÔºÉóѶʱ£¬¼ì²ì¹Ù°´¡°Ä±É±×ÌáÆð¹«Ëߣ¬Èç¹û×ïÃû³ÉÁ¢£¬µÂË¹ÌØÃæÁÙ</span><span style='font-family:»ªÎÄ¿¬Ìå'>99<span lang=ZH-CN>ÄêͽÐÌ¡£ÅãÉóÍž­¹ýÎåÌìÉóÒ飬ÓÚ</span>2003<span lang=ZH-CN>Äê</span>11<span lang=ZH-CN>ÔÂ</span>11<span lang=ZH-CN>ÈÕ×ö³ö²Ã¾ö£¬ÍêÈ«³öºõËùÓÐÈ˵ÄÒâÁÏ£¬¾¹È»ÊÇ¡°ÎÞ×ïÊÍ·Å¡±¡£µ±·¨Í¥ÐûÅÐÕâÒ»Åоöʱ£¬Á¬µÂË¹ÌØ±¾È˶¼¡°ÏÅÁËÒ»Ìø¡±£¬×ì°Í΢΢ÕÅ¿ª£¬ÑÛ¾¦Á÷³öÀáË®¡£ËûÓµ±§ÂÉʦ˵£º¡°Ì«Ð»Ð»ÄãÁË¡±£¡¼ì²ì¹ÙÌýµ½ÕâÒ»Åоö¸Ðµ½¾ªãµ£¬Á¬Ëµ£º¡°ÁîÈËʧÍû£¬ÁîÈ˾ÚÉ¥£¡¡±ËûÈÏΪ£¬µÂË¹ÌØÒ»¹á˵»Ñ£¬ÊǸö¡°ÀäѪɱÊÖ¡±£»µÂË¹ÌØµÄÐÐΪÓÃËû×Ô¼ºµÄ˵·¨ÊÇÎÞ·¨½âÊ͵ġ£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>¿ÉϧµÄÊÇ£¬ÃÀ¹úýÌå¶Ô±¾°¸Ã»ÓкóÐøµÄ×·×Ù±¨µÀ¡£ÅãÉóÍŸù¾ÝʲĩÀíÓɲö¨µÂË¹ÌØ¡°ÎÞ×£¿×÷³öÈç´Ë»ÄÌÆÅоöµÄÔ­ÒòºÍ±³¾°ÊÇʲĩ£¿¶¼Ã»ÓÐÏÂÎÄ£¬Ò²Ã»ÈËÔÙ×·¾¿¡£ÕâÖÖ²»ÁËÁËÖ®µÄÏÖÏó£¬ÔÚÃÀ¹ú²¢²»ÉÙ¼û¡£³ýÁË·´Ó³ÃÀ¹ú˾·¨ÖƶȺÍ˾·¨¹¤×÷´æÔÚÑÏÖØ±×¶Ë£¬Ò²·´Ó³ÃÀ¹úµÄÐÂÎÅ×ÔÓɲ¢²»ÊÇÏñijЩÈË´µÐê»òÏëÏóµÄÄÇÑùÍêÃÀ¡£¡°¼Ò³ó²»¿ÉÍâÑºÍ¡°Îª¸»Õ߻䡱µÄÏÖÏóÔÚÃÀ¹ú²»ÊDz»´æÔÚ¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>ÔÚÃÀ¹ú£¬ÅãÉóÍÅ×ö³öµÄÅоö²»ºÏÀí£¬²»ÊǾøÎÞ½öÓеģ¬Ö»²»¹ýÐÁÆÖÉ­°¸ºÍµÂË¹ÌØ°¸Ì«»ÄÌÆÁË¡£ÀýÈ磬</span><span style='font-family:»ªÎÄ¿¬Ìå'>1994<span lang=ZH-CN>Äê</span>9<span lang=ZH-CN>Ô£¬°¢À­Ë¹¼ÓÖݵÄÓæÃñ¿Ø¸æ°¬¿ËɭʯÓ͹«Ë¾µÄÓæÂÖ´¥½¸Â©ÓÍ£¬¸øÓæÒµÔì³ÉËðʧ£¬ÅãÉóÍÅÅоöµÄÅâ³¥½ð¶î¾¹È»¸ß´ï</span>50<span lang=ZH-CN>ÒÚÃÀÔª¡£ÅãÉóÍÅ×ö³öÕâÑùµÄÅоö£¬¾ÍÊÇÒòΪ°¬¿ËɭʯÓ͹«Ë¾ÊǸöÀûÈó·áºñµÄ¿ç¹ú´óÆóÒµ£¬¶ÔÕâÑùµÄ´óÆóÒµ£¬ÓÉÆ½Ãñ×é³ÉµÄÅãÉóÍÅÍùÍù´æÓС°½Ù¸»¼Ãƶ¡±µÄÐÄÀí¡£ÓÖÈç¼ÓÀû¸£ÄáÑÇÖÝÓÐÁ½Ðֵܣ¬Ç¹É±ÁË×Ô¼ºµÄÇ×Éú¸¸Ä¸£¬ÅãÉóÍÅÌÖÂÛʱ¾¹È»ÈÏΪ¡°ÎÞ·¨¶¨×ï</span>¡±<span lang=ZH-CN>£¬³¤ÆÚ¡°¹ÒÆðÀ´¡±¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span style='font-family:»ªÎÄ¿¬Ìå'><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span lang=ZH-CN>£¨ËÄ£©ÃÀ¹úÅãÉçÍÅÖÆ¶ÈµÄ±×¶Ë</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>×îÔçʵÐÐÅãÉóÖÆ¶ÈµÄÊÇÓ¢¹ú£¬Èô¸ÉÎ÷·½¹ú¼ÒÒ²ÓÐÅãÉóÖÆ¶È¡£µ«ÊǸ÷¹úµÄÅãÉóÖÆ¶È¸÷²»Ïàͬ£¬ÓÅȱµãÒ²²»Ò»Ñù¡£ÃÀ¹úÅãÉóÍÅÖÆ¶ÈµÄ±×¶ËÖ÷ÒªÓÐÎåÌõ£º</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l0 level1 lfo2; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚÒ»£¬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>åàÑ¡ÅãÉóÔ±µÄÌõ¼þÎÊÌ⣺ÃÀ¹ú²»×¼Ò½Éú</span><span style='font-family:»ªÎÄ¿¬Ìå'> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>ÂÉʦ</span> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>½ÌʦµÈÖ°ÒµµÄ</span><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÈËÊ¿µ£ÈÎÅãÉóÔ±£¬Õâ¾ÍÅųýÁËÐí¶àÓÐ֪ʶÓвÅÄܵÄÈË¡£ÔÙÓУ¬Ç°Ãæ½²¹ý£¬ÓÉÓÚÅãÉó¹¤×÷½òÌù²»¸ß£¬Ðí¶à¸ßÊÕÈëµÄÈ˲»Ô¸Òâ×÷ÅãÉóÔ±£¬ÕâÑù£¬ÊÂʵÉϾÍÓÖʧȥһ´óÅúÓÐ֪ʶÓвÅÄܵÄÈË¡£Æä½á¹û£¬ÅãÉóÔ±Ö÷ÒªÀ´×ÔÒ»°ãƽÃñºÍÊÕÈë½ÏµÍµÄÈËȺ¡£ÕâЩÈË£¬·¨ÂÉ֪ʶˮƽºÍ·ÖÎöÅжÏÎÊÌâµÄÄÜÁ¦Ïà¶ÔÀ´ËµÊDz»¸ßµÄ£¬Ó°Ïì½øÐвþöµÄˮƽ¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l0 level1 lfo2; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚ¶þ£¬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÓÉË­åàÑ¡ºÍÈçºÎåàÑ¡ÅãÉóÔ±£¿ÓеÄÎ÷·½¹ú¼Ò£¨ÈçÓ¢¹ú£©£¬åàÑ¡</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÅãÉóÔ±ÊÇ´ÓºòÑ¡ÅãÉóÔ±Ãû²áÖÐËæ»ú³éÑùÑ¡³ö£¬±×¶Ë½ÏÉÙ¡£ÃÀ¹ú²»È»£¬ÊÇÓÉ·¨¹ÙºÍÁ½ÔìÂÉʦÌôÑ¡¡£ÓÐЩ¸»È˱㻨´óǮƸÇë¡°¸ßÃ÷¡±µÄ´óÂÉʦ£¨Êµ¼ÊÉÏÊÇÀϼé¾Þ»«£¬¾­Ñé·á¸»µÄ¡°ËϹ÷¡±£¬ÕâÖÖÂÉʦ×î»á×ê·¨ÂÉ©¶´£¬¾­ËûÃDZ绤£¬¿ÉÒÔ°ÑÖØ×ï±äÇá×°ÑËÀ×ï±ä¡°ÎÞ×£©²ÎÓëåàÑ¡ÅãÉóÔ±£¬Æä½á¹ûÅãÉóÍŵĹ¹³É±äµÃÓÐÀûÓÚ»¨´óÇ®µÄ±»¸æ£¬¶ø²»ÀûÓÚ»¨²»ÆðÇ®Çë¡°´óÂÉʦ¡±µÄÊܺ¦Õß¡£ÐÁÆÖɭɱÈ˰¸¾ÍÊÇÊ®·ÖÃ÷ÏÔµÄʵÀý¡£ÐÁÆÖÉ­ÊǺÚÈË£¬±»·ÇÒáÃÀ¹úÈËÊÓΪ±¾×åÒáµÄ¡°Ó¢ÐÛ¡±£¬´ÓÇé¸ÐÉϾÍÌ»»¤Ëý¡£±»É±µÄÐÁµÄǰÆÞºÍËýµÄÇéÈ˶¼Êǰ×ÈË¡£¾­ÐÁÆÖÉ­ËùƸ´óÂÉʦµÄ¡°Å¬Á¦¡±£¬ÅãÉóÍÅ</span><span style='font-family:»ªÎÄ¿¬Ìå'>12<span lang=ZH-CN>Ãû³ÉÔ±»»À´»»È¥£¬×îºóΪºÚÈË</span>9<span lang=ZH-CN>Ãû£¬Î÷ÓïÒá</span>1<span lang=ZH-CN>Ãû£¬°×ÈË</span>2<span lang=ZH-CN>Ãû¡£ÕâÑùµÄ¹¹³É¾ÍʹµÃÅãÉóÍÅÄÚ´æÔÚÒ»ÖÖ²»¹«ÕýµÄÖÖ×åÆçÊÓÇéÐ÷£¬ÕâÊÇÐÁ°¸ÐÌÊÂÉóÅÐËùÒÔ»ÄÌÆµÄÖØÒªÔ­Òò¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='text-indent:.5in'><span lang=ZH-CN style='font-family: »ªÎÄ¿¬Ìå'>µÚÈý£¬¡°Ò»ÖÂͨ¹ý¡±Ô­ÔòÔÚÉóÅи´ÔÓ°¸¼þʱ£¬ÍùÍùÐв»Í¨¡£ÒòΪ°¸Ç鸴ÔÓÁË£¬·Ö±æ°¸¼þµÄÐÔÖʺÍ×ïÐÐÇáÖØµÄ³Ì¶È¾Í±È½ÏÀ§ÄÑ£¬»áÓв»Í¬¿´·¨£¬ÉõÖÁÑÏÖØ·ÖÆç¡£ºÎ¿öÅãÉóÍÅÔ±µÄˮƽ²Î²î²»Æë£¬Èç¹ûÓÐÈË˼Ïë¹ÌÖ´£¬Ìý²»½ø±ðÈËÒâ¼û£¬Ï²ºÃ¼á³Ö¼º¼û£¬ÄǾ͸üÄÑÒ»ÖÂͨ¹ý¡£ËùÒÔÐí¶à¹ú¼ÒµÄÅãÉóÍÅʵÐС°ÉÙÊý·þ´Ó¶àÊý¡±µÄÔ­Ôò£¬¶ø²»ÊÇ¡°Ò»ÖÂͨ¹ý¡±Ô­Ôò¡£ÕâÑù¾ÍºÜÉÙÓС°¹ÒÆðÀ´¡±µÄÏÖÏó¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l1 level1 lfo1; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚËÄ£¬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÅãÉóÍŵIJþöÊÇ¡°×îºóÅоö¡±£¬³ý·Ç³ÌÐòÓÐÎÊÌ⣬²»µÃÉÏËß¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÕâÌõ¹æ¶¨ÏÔÈ»²»ºÏÀí¡£ÃÀ¹úÅãÉóÍŽøÐÐÉóÅеÄˮƽʵ¼ÊÉϲ¢²»¸ß£¬ÎªÊ²Ä©ËûÃǵIJþö¾ÍÊÇ¡°×îºóÅоö¡±ÄØ£¿ÕæÕýµÄ·¨ÖÆ£¬Ó¦µ±Ò»Çзþ´Ó·¨ÂÉ£¬Èç¹ûÅãÉóÍŵIJþö²¢²»·ûºÏ·¨Âɹ涨£¬µ±È»Ó¦ÔÊÐíÉÏËß¡£ÔÚÕâ¸öÎÊÌâÉÏ£¬Î÷·½¹ú¼Ò×ö·¨¸÷²»Ïàͬ¡£µÂ¹úµÄÅãÉóÔ±ÊǸ¨Öú·¨¹ÙÅоö£¬ÒòΪµÂ¹úÓßÂÛÈÏΪ·¨¹ÙµÄרҵˮƽ±ÈÅãÉóÔ±¸ß£¬Ó¦µ±ÒÔ·¨¹ÙΪÖ÷½øÐÐÉóÅС£¼ÓÄôóµÄ·¨¹Ù¶ÔÅãÉóÍÅÒâ¼ûÓзñ¾öȨ£¬²¢ÇÒ¿ÉÒÔ¶ÔÅãÉóÍųÂÊö×Ô¼ºµÄÒâ¼û£¬ÒªÇóÅãÉóÍÅÔÙÉóÒé¡£ÃÀ¹úÖ»Ðí·¨¹ÙÏòÅãÉóÍŽ²½â·¨ÂÉÌõÎÄ£¬²»ÐíÓÃ×Ô¼ºµÄÒâ¼ûÓ°ÏìÅãÉóÍÅ£¬ÀíÓÉÊÇ×ðÖØÅãÉóÍÅ¡°×ÔÖ÷Åоö¡±¡£</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l1 level1 lfo1; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚÎ壬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÅãÉóÍÅÖÆ¶ÈÓÐÀû±»¸æ¡£ÓÉ·¨¹ÙÖ±½ÓÉóÅУ¬Ô­¸æ</span><span style='font-family:»ªÎÄ¿¬Ìå'> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>¼ì²ì¹ÙֻҪƾ</span><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>Ö¤¾Ý˵·þ·¨¹ÙÒ»ÈË£¬¾ÍÄܶ¨×¶øÓÉÅãÉóÍÅÉóÅУ¬Ô­¸æ</span><span style='font-family:»ªÎÄ¿¬Ìå'> .<span style="mso-spacerun: yes">&nbsp; </span><span lang=ZH-CN>¼ì²ì¹Ù¾Í±ØÐëÆ¾Ö¤¾Ý˵·þÅãÉóÍÅ</span>12<span lang=ZH-CN>È˲ÅÄܶ¨×ï¡£ºóÕßµ±È»±ÈǰÕßÀ§ÄÑ£¬Ò²¾Í¶Ô±»¸æ±È½ÏÓÐÀû¡£ËùÒÔËäȻԭ¸æºÍ±»¸æ¶¼ÓÐȨÀûÒªÇóÅãÉóÍÅÉóÅУ¬µ«ÊÂʵÉÏÔ­¸æÒªÇóÅãÉóÍÅÉóÅеĺÜÉÙ¡£</span><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:1.5in;text-indent:-1.0in;mso-list:l1 level1 lfo1; tab-stops:list 1.5in'><![if !supportLists]><span style='font-family:»ªÎÄ¿¬Ìå'>µÚÁù£¬<span style='font:7.0pt "Times New Roman"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span></span><![endif]><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÅãÉóÍÅÖÆ¶ÈÓÐÀû¸»ÈË¡£ÅãÉóÍÅÉóÅеķÑÓÃÊǺܸߵġ£ÓÉÅãÉóÍÅ</span><span style='font-family:»ªÎÄ¿¬Ìå'><o:p></o:p></span></p> <p class=MsoNormal><span lang=ZH-CN style='font-family:»ªÎÄ¿¬Ìå'>ÉóÀíʱ£¬ÂÉʦµÄ³öÍ¥·ÑÒ»°ãÊÇÒ»Ìì</span><span style='font-family:»ªÎÄ¿¬Ìå'>2000<span lang=ZH-CN>ÃÀÔª×óÓÒ£¬ËßËÏÁ½ÐÇÆÚ¾ÍÒª»¨Á½ÈýÍòÃÀÔªÂÉʦ·Ñ¡£Èç¹ûËßËÏ¿õÈճ־㬽öÂÉʦ·Ñ¾Í¿ÉÒÔʹÈËÇã¼Òµ´²ú¡£Èç¹û±»¸æ·½¹Ù˾´òÊäÁË£¬·¨¹Ù»¹¿ÉÄܼÓÖØ¶Ô±»¸æµÄÁ¿ÐÌ£¬ÒòΪ½øÐÐÅãÉóÍÅÉóÅУ¬Õþ¸®Ò²Òª»¨¸ü¶àµÄ·ÑÓá£ËùÒÔ£¬²»ÊǸ»Î̸»ÆÅ²»¸ÒÇáÒ×ÒªÇóÅãÉóÍÅÉóÅС£</span><o:p></o:p></span></p> <p class=MsoNormal><span style='font-family:»ªÎÄ¿¬Ìå'><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span lang=ZH-CN>×ÛÉÏËùÊö£¬ÊµÐÐÅãÉóÍÅ£¨»òÅãÉóÔ±£©Öƶȣ¬Ê¹ÈËÃñÒ²ÄܲÎÓëijЩ˾·¨¹¤×÷£¬È·ÊµÓÐÆäºÃ´¦£¬ÓÐÀûÓÚÃñÖ÷ºÍ·¨Öƽ¨Éè¡£µ«ÊÇÅãÉóÖÆ¶ÈµÄ½¨Á¢ºÍʵʩ£¬±ØÐë¸ù¾Ý¸÷¹ú¹úÇé°ìÊ£¬²»ÄܶԱð¹úµÄÅãÉóÖÆ¶ÈÕÕ³­ÕÕ°á¡£</span><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span lang=ZH-CN>£¨</span>2003<span lang=ZH-CN>£¬</span>12<span lang=ZH-CN>£¬</span>12<span lang=ZH-CN>ŦԼ£©</span><o:p></o:p></span></p> <p class=MsoNormal style='margin-left:.5in'><span style='font-family:»ªÎÄ¿¬Ìå'><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></span></p> </div> </body> </html>
todor-dk/HTML-Renderer
Source/Testing/HtmlRenderer.ExperimentalApp/Data/Files/陪审团/EDAAF90CC59504F9B30A8DDED9A75F57.html
HTML
bsd-3-clause
29,271
#! /usr/bin/env python #Copyright (c) 2016, Buti Al Delail #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 kuri_mbzirc_challenge_3 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 #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. #CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, import rospy import thread import threading import time import mavros import actionlib from math import * from mavros.utils import * from mavros import setpoint as SP from tf.transformations import quaternion_from_euler from kuri_msgs.msg import * class dropzone_landing: def __init__(self): self.done = False self.done_evt = threading.Event() self.isExploring = False self.progress = 0.0 self.x = 0.0 self.y = 0.0 self.z = 0.0 self.currentPoseX = 0 self.currentPoseY = 0 self.currentPoseZ = 0 self.navigating = False mavros.set_namespace('/uav_1/mavros') # publisher for mavros/setpoint_position/local self.pub = SP.get_pub_position_local(queue_size=10) # subscriber for mavros/local_position/local self.sub = rospy.Subscriber(mavros.get_topic('local_position', 'pose'), SP.PoseStamped, self.reached) self.objects_map = ObjectsMap() self.client = actionlib.SimpleActionClient('TrackingAction', TrackingAction) #client = self.client #client = self.actionServer.client print "Waiting for tracking server" self.client.wait_for_server() self.goal = TrackingGoal() self.goal.uav_id = 1 self.client.send_goal(self.goal) print "Waiting for result" self.client.wait_for_result() print "Result:" self.objects =self.client.get_result().tracked_objects.objects print self.objects try: thread.start_new_thread(self.navigate, ()) except: fault("Error: Unable to start thread") def navigate(self): rate = rospy.Rate(40) # 10hz msg = SP.PoseStamped( header=SP.Header( frame_id="base_footprint", # no matter, plugin don't use TF stamp=rospy.Time.now()), # stamp should update ) while not rospy.is_shutdown(): msg.pose.position.x = self.x msg.pose.position.y = self.y msg.pose.position.z = self.z # For demo purposes we will lock yaw/heading to north. yaw_degrees = 0 # North yaw = radians(yaw_degrees) quaternion = quaternion_from_euler(0, 0, yaw) msg.pose.orientation = SP.Quaternion(*quaternion) self.pub.publish(msg) rate.sleep() def setPose(self, x, y, z, delay=0, wait=True): self.done = False self.x = x self.y = y self.z = z self.navigating = True if wait: rate = rospy.Rate(5) while not self.done and not rospy.is_shutdown(): rate.sleep() time.sleep(delay) def takeoff(self, z, delay=0, wait=True): diff = z - self.currentPoseZ while not abs(diff)<0.2: diff = z - self.currentPoseZ if diff>0: self.setPose(self.currentPoseX,self.currentPoseY,self.currentPoseZ + 1, 0, False) else: self.setPose(self.currentPoseX,self.currentPoseY,self.currentPoseZ - 0.1, 0, False) def land(self, delay=0, wait=True): altitude = self.currentPoseZ while altitude > 0: altitude = self.currentPoseZ self.setPose(self.currentPoseX,self.currentPoseY,self.currentPoseZ - 0.5 ,2) def reached(self, topic): def is_near(msg, x, y, d): rospy.logdebug("Position %s: local: %d, target: %d, abs diff: %d", msg, x, y, abs(x - y)) return abs(x - y) < d self.currentPoseX = topic.pose.position.x self.currentPoseY = topic.pose.position.y self.currentPoseZ = topic.pose.position.z if is_near('X', topic.pose.position.x, self.x, 0.2) and \ is_near('Y', topic.pose.position.y, self.y, 0.2) and \ is_near('Z', topic.pose.position.z, self.z, 0.5): if self.navigating: self.done = True self.navigating = False self.done_evt.set() def explore(self): print 'explore started ' rate = rospy.Rate(30) self.newGoal = True if self.isExploring == False: #Change this later when we have a better exploration #self.isExploring = True while self.done == False: time.sleep(1) rospy.loginfo("Climb") self.progress += 0.1 self.takeoff(5) self.progress += 0.1 rospy.loginfo("Moving to Red_Object") self.reached_object = False red_object_id = -1 xspeed = 1 while self.reached_object == False: self.client.send_goal(self.goal) self.client.wait_for_result() self.objects = self.client.get_result().tracked_objects.objects islost = True for obj in self.objects: if red_object_id == -1 and (obj.color == 'RED' or obj.color == 'BLUE' or obj.color == 'GREEN'): #pick any nearby object red_object_id = obj.object_id if obj.object_id == red_object_id: islost = False print 'Moving to Drop zone', self.currentPoseX-obj.pose2.pose.position.x, self.currentPoseY-obj.pose2.pose.position.y, obj.pose.pose.position.x, obj.pose.pose.position.y if fabs(obj.pose2.pose.position.x) < 0.01 and fabs(obj.pose2.pose.position.y) > 0.01: print 'Moving Y' self.setPose(self.x, self.currentPoseY+obj.pose2.pose.position.y*xspeed, self.z, 0 , False) elif fabs(obj.pose2.pose.position.y) < 0.01 and fabs(obj.pose2.pose.position.x) > 0.01: print 'Moving X' self.setPose(self.currentPoseX-obj.pose2.pose.position.x*xspeed, self.y, self.z, 0 , False) else: print 'Moving XY' self.setPose(self.currentPoseX-obj.pose2.pose.position.x*xspeed, self.currentPoseY+obj.pose2.pose.position.y*xspeed, self.z, 0 , True) if fabs(obj.pose2.pose.position.x) < 0.3 and fabs(obj.pose2.pose.position.y) < 0.3 and self.z > 0.0: print 'Moving Z' land = 0.2 if self.z <= 3: xspeed = 1 if self.z <= 1.5: xspeed = 0.5 if self.z < 0.5: land = 0.05 self.setPose(self.x, self.y, self.z - land * xspeed, 1, False) if self.z <= 0.4: self.reached_object = True if islost == True: red_object_id = -1 if red_object_id == -1: rospy.loginfo("No object in sight, exploring") #self.setPose(self.x, self.y - 5, self.z, 1, True) rate.sleep() time.sleep(10) rospy.loginfo("Picked Object, climb") self.takeoff(1) self.takeoff(2) self.takeoff(3) self.takeoff(4) self.takeoff(5) #self.setPose(self.x, self.y, self.z) time.sleep(10) rospy.loginfo("Moving to DropZone") self.setPose(1, -21, 5) ##Go near dropzone self.progress += 0.1 self.reached_dropzone = False xspeed = 3 while self.reached_dropzone == False: self.client.send_goal(self.goal) self.client.wait_for_result() self.objects = self.client.get_result().tracked_objects.objects for obj in self.objects: if obj.color == 'DROP_ZONE': print 'Moving to Drop zone', self.currentPoseX-obj.pose2.pose.position.x, self.currentPoseY-obj.pose2.pose.position.y, obj.pose.pose.position.x, obj.pose.pose.position.y if fabs(obj.pose2.pose.position.x) < 0.1 and fabs(obj.pose2.pose.position.y) > 0.1: print 'Moving Y' self.setPose(self.x, self.currentPoseY+obj.pose2.pose.position.y*xspeed, self.z, 0 , False) elif fabs(obj.pose2.pose.position.y) < 0.1 and fabs(obj.pose2.pose.position.x) > 0.1: print 'Moving X' self.setPose(self.currentPoseX-obj.pose2.pose.position.x*xspeed, self.y, self.z, 0 , False) else: print 'Moving XY' self.setPose(self.currentPoseX-obj.pose2.pose.position.x*xspeed, self.currentPoseY+obj.pose2.pose.position.y*xspeed, self.z, 0 , True) if fabs(obj.pose2.pose.position.x) < 0.3 and fabs(obj.pose2.pose.position.y) < 0.3 and self.z > 1: print 'Moving Z' land = 0.5 if self.z <= 3: land = 0.2 xspeed = 0.5 self.setPose(self.x, self.y, self.z - land, 1, False) if self.z < 1.5: self.reached_dropzone = True rate.sleep() self.progress += 0.1 rospy.loginfo("Landed Object, climb") self.takeoff(7) rospy.loginfo("Bye!") def main(args): '''Initializes and cleanup ros node''' rospy.init_node('dropzone_landing', anonymous=True) d = dropzone_landing() d.explore() try: rospy.spin() except KeyboardInterrupt: print "Shutting down ROS Image feature detector module" cv2.destroyAllWindows() if __name__ == '__main__': main(sys.argv)
kuri-kustar/kuri_mbzirc_challenge_3
kuri_object_tracking/scripts/object_picktest.py
Python
bsd-3-clause
12,469
// ----------------------------------------------------------------------------------- // // Lightbox v2.05 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 3/18/11 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: '/images/zoom/loading.gif', fileBottomNavCloseImage: '/images/zoom/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ), Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.getAttribute("rel") == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; /*Bug Fixed by Andy Scott*/ this.lightboxImage.width = imgPreloader.width; this.lightboxImage.height = imgPreloader.height; /*End of Bug Fix*/ this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { this.caption.update(this.imageArray[this.activeImage][1]).show(); // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
aina1205/virtualliverf1
public/javascripts/zoom/lightbox.js
JavaScript
bsd-3-clause
18,518
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.17"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Vulkan Memory Allocator: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Vulkan Memory Allocator </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.17 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">VmaDeviceMemoryCallbacks Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="struct_vma_device_memory_callbacks.html">VmaDeviceMemoryCallbacks</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="struct_vma_device_memory_callbacks.html#a4f17f7b255101e733b44d5633aceabfb">pfnAllocate</a></td><td class="entry"><a class="el" href="struct_vma_device_memory_callbacks.html">VmaDeviceMemoryCallbacks</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="struct_vma_device_memory_callbacks.html#abe8a3328bbc916f6f712fdb6b299444c">pfnFree</a></td><td class="entry"><a class="el" href="struct_vma_device_memory_callbacks.html">VmaDeviceMemoryCallbacks</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="struct_vma_device_memory_callbacks.html#a24052de0937ddd54015a2df0363903c6">pUserData</a></td><td class="entry"><a class="el" href="struct_vma_device_memory_callbacks.html">VmaDeviceMemoryCallbacks</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.17 </small></address> </body> </html>
endlessm/chromium-browser
third_party/vulkan_memory_allocator/docs/html/struct_vma_device_memory_callbacks-members.html
HTML
bsd-3-clause
3,941
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_PREFERENCES_TRACKED_TRACKED_PERSISTENT_PREF_STORE_FACTORY_H_ #define SERVICES_PREFERENCES_TRACKED_TRACKED_PERSISTENT_PREF_STORE_FACTORY_H_ #include <utility> #include "base/sequenced_task_runner.h" #include "services/preferences/public/mojom/preferences.mojom.h" namespace base { class DictionaryValue; } class PersistentPrefStore; PersistentPrefStore* CreateTrackedPersistentPrefStore( prefs::mojom::TrackedPersistentPrefStoreConfigurationPtr config, scoped_refptr<base::SequencedTaskRunner> io_task_runner); // TODO(sammc): This should move somewhere more appropriate in the longer term. void InitializeMasterPrefsTracking( prefs::mojom::TrackedPersistentPrefStoreConfigurationPtr configuration, base::DictionaryValue* master_prefs); #endif // SERVICES_PREFERENCES_TRACKED_TRACKED_PERSISTENT_PREF_STORE_FACTORY_H_
endlessm/chromium-browser
services/preferences/tracked/tracked_persistent_pref_store_factory.h
C
bsd-3-clause
1,022
//////////////////////////////////////////////////////////////////////////////////// /// /// \file setlocalwaypoint.cpp /// \brief This file contains the implementation of a JAUS message. /// /// <br>Author(s): Bo Sun /// <br>Created: 30 November 2009 /// <br>Copyright (c) 2009 /// <br>Applied Cognition and Training in Immersive Virtual Environments /// <br>(ACTIVE) Laboratory /// <br>Institute for Simulation and Training (IST) /// <br>University of Central Florida (UCF) /// <br>All rights reserved. /// <br>Email: bsun@ist.ucf.edu /// <br>Web: http://active.ist.ucf.edu /// /// 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 ACTIVE LAB, IST, UCF, 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 ACTIVE LAB''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 UCF 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 "jaus/mobility/drivers/setlocalwaypoint.h" #include "jaus/core/scaledinteger.h" #include <cxutils/math/cxmath.h> #include <iomanip> const double JAUS::SetLocalWaypoint::Limits::MinPoint = -100000; const double JAUS::SetLocalWaypoint::Limits::MaxPoint = 100000; const double JAUS::SetLocalWaypoint::Limits::MinAngle = -CxUtils::CX_PI; const double JAUS::SetLocalWaypoint::Limits::MaxAngle = CxUtils::CX_PI; const double JAUS::SetLocalWaypoint::Limits::MinWaypointTolerance = 0.0; const double JAUS::SetLocalWaypoint::Limits::MaxWaypointTolerance = 100.0; const double JAUS::SetLocalWaypoint::Limits::MinPathTolerance = 0.0; const double JAUS::SetLocalWaypoint::Limits::MaxPathTolerance = 100000.0; using namespace JAUS; //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Constructor, initializes default values. /// /// \param[in] src Source ID of message sender. /// \param[in] dest Destination ID of message. /// //////////////////////////////////////////////////////////////////////////////////// SetLocalWaypoint::SetLocalWaypoint(const Address& dest, const Address& src) : Message(SET_LOCAL_WAYPOINT, dest, src) { mPresenceVector = 0; mX = 0; mY = 0; mZ = 0; mRoll = 0; mPitch = 0; mYaw = 0; mWaypointTolerance = 0; mPathTolerance = 0; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Copy constructor. /// //////////////////////////////////////////////////////////////////////////////////// SetLocalWaypoint::SetLocalWaypoint(const SetLocalWaypoint& message) : Message(SET_LOCAL_WAYPOINT) { *this = message; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Destructor. /// //////////////////////////////////////////////////////////////////////////////////// SetLocalWaypoint::~SetLocalWaypoint() { } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the latitude and updates the presence vector for the message. /// /// \param[in] value Desired X in meters [-100000, 100000]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetX(const double value) { if(value >= Limits::MinPoint && value <= Limits::MaxPoint) { mX = value; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the longitude and updates the presence vector for the message. /// /// \param[in] value Desired Y in meters [-100000, 100000]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetY(const double value) { if(value >= Limits::MinPoint && value <= Limits::MaxPoint) { mY = value; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the altitude and updates the presence vector for the /// message. /// /// \param[in] value Desired Z in meters [-100000, 100000]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetZ(const double value) { if(value >= Limits::MinPoint && value <= Limits::MaxPoint) { mZ = value; mPresenceVector |= PresenceVector::Z; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the roll and updates the presence vector for the message. /// /// \param[in] radians Desired roll in radians[-PI, PI]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetRoll(const double radians) { if(radians >= Limits::MinAngle && radians <= Limits::MaxAngle) { mRoll = radians; mPresenceVector |= PresenceVector::Roll; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the pitch value and updates the presence vector for the message. /// /// \param[in] radians Desired pitch in radians[-PI, PI]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetPitch(const double radians) { if(radians >= Limits::MinAngle && radians <= Limits::MaxAngle) { mPitch = radians; mPresenceVector |= PresenceVector::Pitch; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the yaw value and updates the presence vector for the message. /// /// \param[in] radians Desired pitch in radians[-PI, PI]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetYaw(const double radians) { if(radians >= Limits::MinAngle && radians <= Limits::MaxAngle) { mYaw = radians; mPresenceVector |= PresenceVector::Yaw; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the waypoint tolerance value and updates the presence vector for /// the message. /// /// \param[in] value Desired waypoint tolerance in meters[0, 100]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetWaypointTolerance(const double value) { if(value >= Limits::MinWaypointTolerance && value <= Limits::MaxWaypointTolerance) { mWaypointTolerance= value; mPresenceVector |= PresenceVector::WaypointTolerance; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets the path tolerance value and updates the presence vector for /// the message. /// /// \param[in] value Desired path tolerance in meters[0, 100000]. /// /// \return true on success, otherwise false. /// //////////////////////////////////////////////////////////////////////////////////// bool SetLocalWaypoint::SetPathTolerance(const double value) { if(value >= Limits::MinPathTolerance && value <= Limits::MaxPathTolerance) { mPathTolerance= value; mPresenceVector |= PresenceVector::PathTolerance; return true; } return false; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Writes message payload to the packet. /// /// Message contents are written to the packet following the JAUS standard. /// /// \param[out] packet Packet to write payload to. /// /// \return -1 on error, otherwise number of bytes written. /// //////////////////////////////////////////////////////////////////////////////////// int SetLocalWaypoint::WriteMessageBody(Packet& packet) const { int expected = BYTE_SIZE; int written = 0; written += packet.Write(mPresenceVector); expected += UINT_SIZE; written += ScaledInteger::Write(packet, mX, Limits::MaxPoint, Limits::MinPoint, ScaledInteger::UInt); expected += UINT_SIZE; written += ScaledInteger::Write(packet, mY, Limits::MaxPoint, Limits::MinPoint, ScaledInteger::UInt); if((mPresenceVector & PresenceVector::Z) > 0) { expected += UINT_SIZE; written += ScaledInteger::Write(packet, mZ, Limits::MaxPoint, Limits::MinPoint, ScaledInteger::UInt); } if((mPresenceVector & PresenceVector::Roll) > 0) { expected += USHORT_SIZE; written += ScaledInteger::Write(packet, mRoll, Limits::MaxAngle, Limits::MinAngle, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::Pitch) > 0) { expected += USHORT_SIZE; written += ScaledInteger::Write(packet, mPitch, Limits::MaxAngle, Limits::MinAngle, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::Yaw) > 0) { expected += USHORT_SIZE; written += ScaledInteger::Write(packet, mYaw, Limits::MaxAngle, Limits::MinAngle, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::WaypointTolerance) > 0) { expected += USHORT_SIZE; written += ScaledInteger::Write(packet, mWaypointTolerance, Limits::MaxWaypointTolerance, Limits::MinWaypointTolerance, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::PathTolerance) > 0) { expected += UINT_SIZE; written += ScaledInteger::Write(packet, mPathTolerance, Limits::MaxPathTolerance, Limits::MinPathTolerance, ScaledInteger::UInt); } return expected == written ? written : -1; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Reads message payload from the packet. /// /// Message contents are read from the packet following the JAUS standard. /// /// \param[in] packet Packet containing message payload data to read. /// /// \return -1 on error, otherwise number of bytes written. /// //////////////////////////////////////////////////////////////////////////////////// int SetLocalWaypoint::ReadMessageBody(const Packet& packet) { int expected = BYTE_SIZE; int read = 0; read += packet.Read(mPresenceVector); expected += UINT_SIZE; read += ScaledInteger::Read(packet, mX, Limits::MaxPoint, Limits::MinPoint, ScaledInteger::UInt); expected += UINT_SIZE; read += ScaledInteger::Read(packet, mY, Limits::MaxPoint, Limits::MinPoint, ScaledInteger::UInt); if((mPresenceVector & PresenceVector::Z) > 0) { expected += UINT_SIZE; read += ScaledInteger::Read(packet, mZ, Limits::MaxPoint, Limits::MinPoint, ScaledInteger::UInt); } if((mPresenceVector & PresenceVector::Roll) > 0) { expected += USHORT_SIZE; read += ScaledInteger::Read(packet, mRoll, Limits::MaxAngle, Limits::MinAngle, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::Pitch) > 0) { expected += USHORT_SIZE; read += ScaledInteger::Read(packet, mPitch, Limits::MaxAngle, Limits::MinAngle, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::Yaw) > 0) { expected += USHORT_SIZE; read += ScaledInteger::Read(packet, mYaw, Limits::MaxAngle, Limits::MinAngle, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::WaypointTolerance) > 0) { expected += USHORT_SIZE; read += ScaledInteger::Read(packet, mWaypointTolerance, Limits::MaxWaypointTolerance, Limits::MinWaypointTolerance, ScaledInteger::UShort); } if((mPresenceVector & PresenceVector::PathTolerance) > 0) { expected += UINT_SIZE; read += ScaledInteger::Read(packet, mPathTolerance, Limits::MaxPathTolerance, Limits::MinPathTolerance, ScaledInteger::UInt); } return expected == read ? read : -1; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Clears message payload data. /// //////////////////////////////////////////////////////////////////////////////////// void SetLocalWaypoint::ClearMessageBody() { mPresenceVector = 0; mX = 0; mY = 0; mZ = 0; mRoll = 0; mPitch = 0; mYaw = 0; mWaypointTolerance = 0; mPathTolerance = 0; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Runs a test case to validate the message class. /// /// \return 1 on success, otherwise 0. /// //////////////////////////////////////////////////////////////////////////////////// int SetLocalWaypoint::RunTestCase() const { int result = 0; Packet packet; SetLocalWaypoint msg1, msg2; msg1.SetYaw(0.55); msg1.SetPathTolerance(1.25); if((msg1.WriteMessageBody(packet) != -1) && (msg2.ReadMessageBody(packet) != -1)) { if(msg2.AreFieldsPresent(PresenceVector::Yaw | PresenceVector::PathTolerance) ) { result = 1; } } return result; } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Prints data to console. /// //////////////////////////////////////////////////////////////////////////////////// void SetLocalWaypoint::PrintMessageBody() const { std::cout << "XYZ: [" << std::fixed << std::setprecision(5) << mX << ", " << std::fixed << std::setprecision(5) << mY << ", " << std::fixed << std::setprecision(2) << mZ << "]\n"; if( (mPresenceVector & (PresenceVector::Yaw | PresenceVector::Pitch | PresenceVector::Roll)) > 0) { std::cout << "Orientation: [" << std::fixed << std::setprecision(1) << CxUtils::CxToDegrees(mRoll) << ", " << std::fixed << std::setprecision(1) << CxUtils::CxToDegrees(mPitch) << ", " << std::fixed << std::setprecision(1) << CxUtils::CxToDegrees(mYaw) << "]\n"; } if( (mPresenceVector & (PresenceVector::PathTolerance | PresenceVector::WaypointTolerance)) > 0) { std::cout << "Tolerance (Waypoint, Path): [" << mWaypointTolerance << ", " << mPathTolerance << "]" << std::endl; } } //////////////////////////////////////////////////////////////////////////////////// /// /// \brief Sets equal to. /// //////////////////////////////////////////////////////////////////////////////////// SetLocalWaypoint& SetLocalWaypoint::operator=(const SetLocalWaypoint& message) { if(this != &message) { CopyHeaderData(&message); mPresenceVector = message.mPresenceVector; mX = message.mX; mY = message.mY; mZ = message.mZ; mRoll = message.mRoll; mPitch = message.mPitch; mYaw = message.mYaw; mWaypointTolerance = message.mWaypointTolerance; mPathTolerance = message.mPathTolerance; } return *this; } /* End of File */
jmesmon/jaus--
src/jaus/mobility/drivers/setlocalwaypoint.cpp
C++
bsd-3-clause
17,224
chmod +x configure ./configure --prefix=$PREFIX --enable-shared make make install
hajs/pylodger
recipes/lib/libjasper/build.sh
Shell
bsd-3-clause
83
from setuptools import setup setup( name='pymail365', version='0.1', description='A python client for sending mail using Microsoft Office 365 rest service.', long_description=open('README.rst').read(), author='Mikko Hellsing', author_email='mikko@aino.se', license='BSD', url='https://github.com/aino/pymail365', packages=['pymail365'], zip_safe=False, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], )
aino/pymail365
setup.py
Python
bsd-3-clause
688
a :: Int a = 123 unittest "quote" [ (show {a}, "a"), (show {,a}, ",a"), (show {pred ,a}, "pred ,a"), ] unittest "quasiquote" [ (`a, a), (`(,a), 123), (`(pred ,a), pred 123), (let x = `(pred ,a) in x , 122), ] -- quine x = "x" q = \x. `(,x {,x}) -- godel isunprovable = "isunprovable" valueof = "valueof" g = \x -> `(isunprovable (valueof (,x {,x}))) unittest "quine & godel" [ (q {x}, x {x}), (q {q}, q {q}), (g {x}, isunprovable (valueof (x {x}))), (g {g}, isunprovable (valueof (g {g}))), ] {--}
ocean0yohsuke/Simply-Typed-Lambda
Start/UnitTest/Quote.hs
Haskell
bsd-3-clause
650
{% extends 'hqwebapp/base_section.html' %} {% load hq_shared_tags %} {% load i18n %} {% load crispy_forms_tags %} {% requirejs_main 'users/js/filtered_download' %} {% block page_content %} {% initial_page_data 'count_users_url' count_users_url %} {% crispy form %} {% endblock %}
dimagi/commcare-hq
corehq/apps/users/templates/users/filter_and_download.html
HTML
bsd-3-clause
286
<html> <head> <title>Venn diagram</title> </head> <body> <div id="venn"></div> <script type="text/javascript" src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> <script type="text/javascript" src="cljs.compiled.js"></script> </body> </html>
Sparrho/venn-cljs
index.html
HTML
bsd-3-clause
300
=pod =head1 NAME BIO_s_accept, BIO_set_accept_port, BIO_get_accept_port, BIO_set_nbio_accept, BIO_set_accept_bios, BIO_set_bind_mode, BIO_get_bind_mode, BIO_do_accept - accept BIO =head1 SYNOPSIS #include <openssl/bio.h> BIO_METHOD *BIO_s_accept(void); long BIO_set_accept_port(BIO *b, char *name); char *BIO_get_accept_port(BIO *b); BIO *BIO_new_accept(char *host_port); long BIO_set_nbio_accept(BIO *b, int n); long BIO_set_accept_bios(BIO *b, char *bio); long BIO_set_bind_mode(BIO *b, long mode); long BIO_get_bind_mode(BIO *b, long dummy); #define BIO_BIND_NORMAL 0 #define BIO_BIND_REUSEADDR_IF_UNUSED 1 #define BIO_BIND_REUSEADDR 2 int BIO_do_accept(BIO *b); =head1 DESCRIPTION BIO_s_accept() returns the accept BIO method. This is a wrapper round the platform's TCP/IP socket accept routines. Using accept BIOs, TCP/IP connections can be accepted and data transferred using only BIO routines. In this way any platform specific operations are hidden by the BIO abstraction. Read and write operations on an accept BIO will perform I/O on the underlying connection. If no connection is established and the port (see below) is set up properly then the BIO waits for an incoming connection. Accept BIOs support BIO_puts() but not BIO_gets(). If the close flag is set on an accept BIO then any active connection on that chain is shutdown and the socket closed when the BIO is freed. Calling BIO_reset() on a accept BIO will close any active connection and reset the BIO into a state where it awaits another incoming connection. BIO_get_fd() and BIO_set_fd() can be called to retrieve or set the accept socket. See L<BIO_s_fd(3)|BIO_s_fd(3)> BIO_set_accept_port() uses the string B<name> to set the accept port. The port is represented as a string of the form "host:port", where "host" is the interface to use and "port" is the port. Either or both values can be "*" which is interpreted as meaning any interface or port respectively. "port" has the same syntax as the port specified in BIO_set_conn_port() for connect BIOs, that is it can be a numerical port string or a string to lookup using getservbyname() and a string table. BIO_new_accept() combines BIO_new() and BIO_set_accept_port() into a single call: that is it creates a new accept BIO with port B<host_port>. BIO_set_nbio_accept() sets the accept socket to blocking mode (the default) if B<n> is 0 or non blocking mode if B<n> is 1. BIO_set_accept_bios() can be used to set a chain of BIOs which will be duplicated and prepended to the chain when an incoming connection is received. This is useful if, for example, a buffering or SSL BIO is required for each connection. The chain of BIOs must not be freed after this call, they will be automatically freed when the accept BIO is freed. BIO_set_bind_mode() and BIO_get_bind_mode() set and retrieve the current bind mode. If BIO_BIND_NORMAL (the default) is set then another socket cannot be bound to the same port. If BIO_BIND_REUSEADDR is set then other sockets can bind to the same port. If BIO_BIND_REUSEADDR_IF_UNUSED is set then and attempt is first made to use BIO_BIN_NORMAL, if this fails and the port is not in use then a second attempt is made using BIO_BIND_REUSEADDR. BIO_do_accept() serves two functions. When it is first called, after the accept BIO has been setup, it will attempt to create the accept socket and bind an address to it. Second and subsequent calls to BIO_do_accept() will await an incoming connection, or request a retry in non blocking mode. =head1 NOTES When an accept BIO is at the end of a chain it will await an incoming connection before processing I/O calls. When an accept BIO is not at then end of a chain it passes I/O calls to the next BIO in the chain. When a connection is established a new socket BIO is created for the connection and appended to the chain. That is the chain is now accept->socket. This effectively means that attempting I/O on an initial accept socket will await an incoming connection then perform I/O on it. If any additional BIOs have been set using BIO_set_accept_bios() then they are placed between the socket and the accept BIO, that is the chain will be accept->otherbios->socket. If a server wishes to process multiple connections (as is normally the case) then the accept BIO must be made available for further incoming connections. This can be done by waiting for a connection and then calling: connection = BIO_pop(accept); After this call B<connection> will contain a BIO for the recently established connection and B<accept> will now be a single BIO again which can be used to await further incoming connections. If no further connections will be accepted the B<accept> can be freed using BIO_free(). If only a single connection will be processed it is possible to perform I/O using the accept BIO itself. This is often undesirable however because the accept BIO will still accept additional incoming connections. This can be resolved by using BIO_pop() (see above) and freeing up the accept BIO after the initial connection. If the underlying accept socket is non-blocking and BIO_do_accept() is called to await an incoming connection it is possible for BIO_should_io_special() with the reason BIO_RR_ACCEPT. If this happens then it is an indication that an accept attempt would block: the application should take appropriate action to wait until the underlying socket has accepted a connection and retry the call. BIO_set_accept_port(), BIO_get_accept_port(), BIO_set_nbio_accept(), BIO_set_accept_bios(), BIO_set_bind_mode(), BIO_get_bind_mode() and BIO_do_accept() are macros. =head1 RETURN VALUES TBA =head1 EXAMPLE This example accepts two connections on port 4444, sends messages down each and finally closes both down. BIO *abio, *cbio, *cbio2; ERR_load_crypto_strings(); abio = BIO_new_accept("4444"); /* First call to BIO_accept() sets up accept BIO */ if(BIO_do_accept(abio) <= 0) { fprintf(stderr, "Error setting up accept\n"); ERR_print_errors_fp(stderr); exit(0); } /* Wait for incoming connection */ if(BIO_do_accept(abio) <= 0) { fprintf(stderr, "Error accepting connection\n"); ERR_print_errors_fp(stderr); exit(0); } fprintf(stderr, "Connection 1 established\n"); /* Retrieve BIO for connection */ cbio = BIO_pop(abio); BIO_puts(cbio, "Connection 1: Sending out Data on initial connection\n"); fprintf(stderr, "Sent out data on connection 1\n"); /* Wait for another connection */ if(BIO_do_accept(abio) <= 0) { fprintf(stderr, "Error accepting connection\n"); ERR_print_errors_fp(stderr); exit(0); } fprintf(stderr, "Connection 2 established\n"); /* Close accept BIO to refuse further connections */ cbio2 = BIO_pop(abio); BIO_free(abio); BIO_puts(cbio2, "Connection 2: Sending out Data on second\n"); fprintf(stderr, "Sent out data on connection 2\n"); BIO_puts(cbio, "Connection 1: Second connection established\n"); /* Close the two established connections */ BIO_free(cbio); BIO_free(cbio2); =head1 SEE ALSO TBA
GaloisInc/hacrypto
src/C/libssl/HEAD/src/doc/crypto/BIO_s_accept.pod
Perl
bsd-3-clause
7,022
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <string> #include "base/macros.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/data_model/address.h" #include "components/autofill/core/browser/geo/country_names.h" #include "components/autofill/core/common/autofill_features.h" #include "testing/gtest/include/gtest/gtest.h" using base::ASCIIToUTF16; namespace autofill { class AddressTest : public testing::Test { public: AddressTest() { CountryNames::SetLocaleString("en-US"); } }; // Test that country data can be properly returned as either a country code or a // localized country name. TEST_F(AddressTest, GetCountry) { Address address; EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); // Make sure that nothing breaks when the country code is missing. base::string16 country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(base::string16(), country); address.SetInfo(AutofillType(ADDRESS_HOME_COUNTRY), ASCIIToUTF16("US"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("United States"), country); country = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_NAME, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16("United States"), country); country = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16("US"), country); address.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("CA")); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("Canada"), country); country = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_NAME, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16("Canada"), country); country = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16("CA"), country); } // Test that country data can be properly returned as either a country code or a // full country name that can even be localized. TEST_F(AddressTest, SetHtmlCountryCodeTypeWithFullCountryName) { Address address; EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); // Enable the feature that allows for full country names although the // field type explicitly set to HTML_TYPE_COUNTRY_CODE. base::test::ScopedFeatureList feature; feature.InitAndEnableFeature( features::kAutofillAllowHtmlTypeCountryCodesWithFullNames); // Create an autofill type from HTML_TYPE_COUNTRY_CODE. AutofillType autofill_type(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE); // Test that the country value can be set and retrieved if it is not // a country code but a full country name. address.SetInfo(autofill_type, ASCIIToUTF16("Germany"), "en-US"); base::string16 actual_country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); base::string16 actual_country_code = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16("Germany"), actual_country); EXPECT_EQ(ASCIIToUTF16("DE"), actual_country_code); // Reset the country and verify that the reset works as expected. address.SetInfo(autofill_type, ASCIIToUTF16(""), "en-US"); actual_country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); actual_country_code = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16(""), actual_country); EXPECT_EQ(ASCIIToUTF16(""), actual_country_code); // Test that the country value can be set and retrieved if it is not // a country code but a full country name with a non-standard locale. address.SetInfo(autofill_type, ASCIIToUTF16("deutschland"), "de"); actual_country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); actual_country_code = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16("Germany"), actual_country); EXPECT_EQ(ASCIIToUTF16("DE"), actual_country_code); // Reset the country. address.SetInfo(autofill_type, ASCIIToUTF16(""), "en-US"); // Test that the country is still stored correctly with a supplied // country code. address.SetInfo(autofill_type, ASCIIToUTF16("DE"), "en-US"); actual_country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); actual_country_code = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16("DE"), actual_country_code); EXPECT_EQ(ASCIIToUTF16("Germany"), actual_country); // By disabling the feature, test that the country name deduction actually // uses the path for HTML_TYPE_COUNTRY_CODE. feature.Reset(); feature.InitAndDisableFeature( features::kAutofillAllowHtmlTypeCountryCodesWithFullNames); address.SetInfo(autofill_type, ASCIIToUTF16("Germany"), "en-US"); actual_country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); actual_country_code = address.GetInfo( AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE), "en-US"); EXPECT_EQ(ASCIIToUTF16(""), actual_country); EXPECT_EQ(ASCIIToUTF16(""), actual_country_code); } // Test that we properly detect country codes appropriate for each country. TEST_F(AddressTest, SetCountry) { Address address; EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); // Test basic conversion. address.SetInfo(AutofillType(ADDRESS_HOME_COUNTRY), ASCIIToUTF16("United States"), "en-US"); base::string16 country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("US"), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(ASCIIToUTF16("United States"), country); // Test basic synonym detection. address.SetInfo(AutofillType(ADDRESS_HOME_COUNTRY), ASCIIToUTF16("USA"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("US"), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(ASCIIToUTF16("United States"), country); // Test case-insensitivity. address.SetInfo(AutofillType(ADDRESS_HOME_COUNTRY), ASCIIToUTF16("canADA"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("CA"), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(ASCIIToUTF16("Canada"), country); // Test country code detection. address.SetInfo(AutofillType(ADDRESS_HOME_COUNTRY), ASCIIToUTF16("JP"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("JP"), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(ASCIIToUTF16("Japan"), country); // Test that we ignore unknown countries. address.SetInfo(AutofillType(ADDRESS_HOME_COUNTRY), ASCIIToUTF16("Unknown"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(base::string16(), country); // Test setting the country based on an HTML field type. AutofillType html_type_country_code = AutofillType(HTML_TYPE_COUNTRY_CODE, HTML_MODE_NONE); address.SetInfo(html_type_country_code, ASCIIToUTF16("US"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("US"), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(ASCIIToUTF16("United States"), country); // Test case-insensitivity when setting the country based on an HTML field // type. address.SetInfo(html_type_country_code, ASCIIToUTF16("cA"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(ASCIIToUTF16("CA"), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(ASCIIToUTF16("Canada"), country); // Test setting the country based on invalid data with an HTML field type. address.SetInfo(html_type_country_code, ASCIIToUTF16("unknown"), "en-US"); country = address.GetInfo(AutofillType(ADDRESS_HOME_COUNTRY), "en-US"); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); EXPECT_EQ(base::string16(), country); } // Test that we properly match typed values to stored country data. TEST_F(AddressTest, IsCountry) { Address address; address.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US")); const char* const kValidMatches[] = {"United States", "USA", "US", "United states", "us"}; for (const char* valid_match : kValidMatches) { SCOPED_TRACE(valid_match); ServerFieldTypeSet matching_types; address.GetMatchingTypes(ASCIIToUTF16(valid_match), "US", &matching_types); ASSERT_EQ(1U, matching_types.size()); EXPECT_EQ(ADDRESS_HOME_COUNTRY, *matching_types.begin()); } const char* const kInvalidMatches[] = {"United", "Garbage"}; for (const char* invalid_match : kInvalidMatches) { ServerFieldTypeSet matching_types; address.GetMatchingTypes(ASCIIToUTF16(invalid_match), "US", &matching_types); EXPECT_EQ(0U, matching_types.size()); } // Make sure that garbage values don't match when the country code is empty. address.SetRawInfo(ADDRESS_HOME_COUNTRY, base::string16()); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_COUNTRY)); ServerFieldTypeSet matching_types; address.GetMatchingTypes(ASCIIToUTF16("Garbage"), "US", &matching_types); EXPECT_EQ(0U, matching_types.size()); } // Verifies that Address::GetInfo() correctly combines address lines. TEST_F(AddressTest, GetStreetAddress) { const AutofillType type = AutofillType(ADDRESS_HOME_STREET_ADDRESS); // Address has no address lines. Address address; EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE3).empty()); EXPECT_EQ(base::string16(), address.GetInfo(type, "en-US")); // Address has only line 1. address.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Example Ave.")); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE3).empty()); EXPECT_EQ(ASCIIToUTF16("123 Example Ave."), address.GetInfo(type, "en-US")); // Address has only line 2. address.SetRawInfo(ADDRESS_HOME_LINE1, base::string16()); address.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Apt 42.")); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE3).empty()); EXPECT_EQ(ASCIIToUTF16("\nApt 42."), address.GetInfo(type, "en-US")); // Address has lines 1 and 2. address.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Example Ave.")); address.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Apt. 42")); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE3).empty()); EXPECT_EQ(ASCIIToUTF16("123 Example Ave.\n" "Apt. 42"), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); EXPECT_EQ(ASCIIToUTF16("123 Example Ave.\n" "Apt. 42"), address.GetInfo(type, "en-US")); // A wild third line appears. address.SetRawInfo(ADDRESS_HOME_LINE3, ASCIIToUTF16("Living room couch")); EXPECT_EQ(ASCIIToUTF16("Living room couch"), address.GetRawInfo(ADDRESS_HOME_LINE3)); EXPECT_EQ(ASCIIToUTF16("123 Example Ave.\n" "Apt. 42\n" "Living room couch"), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); // The second line vanishes. address.SetRawInfo(ADDRESS_HOME_LINE2, base::string16()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_TRUE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE3).empty()); EXPECT_EQ(ASCIIToUTF16("123 Example Ave.\n" "\n" "Living room couch"), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); } // Verifies that overwriting an address with N lines with one that has fewer // than N lines does not result in an address with blank lines at the end. TEST_F(AddressTest, GetStreetAddressAfterOverwritingLongAddressWithShorterOne) { // Start with an address that has two lines. Address address; address.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Example Ave.")); address.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Apt. 42")); // Now clear out the second address line. address.SetRawInfo(ADDRESS_HOME_LINE2, base::string16()); EXPECT_EQ(ASCIIToUTF16("123 Example Ave."), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); // Now clear out the first address line as well. address.SetRawInfo(ADDRESS_HOME_LINE1, base::string16()); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); } // Verifies that Address::SetRawInfo() is able to split address lines correctly. TEST_F(AddressTest, SetRawStreetAddress) { const base::string16 empty_street_address; const base::string16 short_street_address = ASCIIToUTF16("456 Nowhere Ln."); const base::string16 long_street_address = ASCIIToUTF16( "123 Example Ave.\n" "Apt. 42\n" "(The one with the blue door)"); Address address; EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); address.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, long_street_address); EXPECT_EQ(ASCIIToUTF16("123 Example Ave."), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(ASCIIToUTF16("Apt. 42"), address.GetRawInfo(ADDRESS_HOME_LINE2)); EXPECT_EQ(long_street_address, address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); // A short address should clear out unused address lines. address.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, short_street_address); EXPECT_EQ(ASCIIToUTF16("456 Nowhere Ln."), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); // An empty address should clear out all address lines. address.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, long_street_address); address.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, empty_street_address); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); } // Street addresses should be set properly. TEST_F(AddressTest, SetStreetAddress) { const base::string16 empty_street_address; const base::string16 multi_line_street_address = ASCIIToUTF16( "789 Fancy Pkwy.\n" "Unit 3.14\n" "Box 9"); const base::string16 single_line_street_address = ASCIIToUTF16("123 Main, Apt 7"); const AutofillType type = AutofillType(ADDRESS_HOME_STREET_ADDRESS); // Start with a non-empty address. Address address; address.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Example Ave.")); address.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Apt. 42")); address.SetRawInfo(ADDRESS_HOME_LINE3, ASCIIToUTF16("and a half")); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE3).empty()); // Attempting to set a multi-line address should succeed. EXPECT_TRUE(address.SetInfo(type, multi_line_street_address, "en-US")); EXPECT_EQ(ASCIIToUTF16("789 Fancy Pkwy."), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(ASCIIToUTF16("Unit 3.14"), address.GetRawInfo(ADDRESS_HOME_LINE2)); EXPECT_EQ(ASCIIToUTF16("Box 9"), address.GetRawInfo(ADDRESS_HOME_LINE3)); // Setting a single line street address should clear out subsequent lines. EXPECT_TRUE(address.SetInfo(type, single_line_street_address, "en-US")); EXPECT_EQ(single_line_street_address, address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE3)); // Attempting to set an empty address should also succeed, and clear out the // previously stored data. EXPECT_TRUE(address.SetInfo(type, multi_line_street_address, "en-US")); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE3).empty()); EXPECT_TRUE(address.SetInfo(type, empty_street_address, "en-US")); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE3)); } // Verifies that Address::SetInfio() rejects setting data for // ADDRESS_HOME_STREET_ADDRESS if the data has any interior blank lines. TEST_F(AddressTest, SetStreetAddressRejectsAddressesWithInteriorBlankLines) { // Start with a non-empty address. Address address; address.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Example Ave.")); address.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Apt. 42")); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS).empty()); // Attempting to set an address with interior blank lines should fail, and // clear out the previously stored address. EXPECT_FALSE(address.SetInfo(AutofillType(ADDRESS_HOME_STREET_ADDRESS), ASCIIToUTF16("Address line 1\n" "\n" "Address line 3"), "en-US")); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); } // Verifies that Address::SetInfio() rejects setting data for // ADDRESS_HOME_STREET_ADDRESS if the data has any leading blank lines. TEST_F(AddressTest, SetStreetAddressRejectsAddressesWithLeadingBlankLines) { // Start with a non-empty address. Address address; address.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Example Ave.")); address.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Apt. 42")); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS).empty()); // Attempting to set an address with leading blank lines should fail, and // clear out the previously stored address. EXPECT_FALSE(address.SetInfo(AutofillType(ADDRESS_HOME_STREET_ADDRESS), ASCIIToUTF16("\n" "Address line 2" "Address line 3"), "en-US")); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); } // Verifies that Address::SetInfio() rejects setting data for // ADDRESS_HOME_STREET_ADDRESS if the data has any trailing blank lines. TEST_F(AddressTest, SetStreetAddressRejectsAddressesWithTrailingBlankLines) { // Start with a non-empty address. Address address; address.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Example Ave.")); address.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Apt. 42")); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE1).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_LINE2).empty()); EXPECT_FALSE(address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS).empty()); // Attempting to set an address with leading blank lines should fail, and // clear out the previously stored address. EXPECT_FALSE(address.SetInfo(AutofillType(ADDRESS_HOME_STREET_ADDRESS), ASCIIToUTF16("Address line 1" "Address line 2" "\n"), "en-US")); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE1)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_LINE2)); EXPECT_EQ(base::string16(), address.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS)); } } // namespace autofill
endlessm/chromium-browser
components/autofill/core/browser/data_model/address_unittest.cc
C++
bsd-3-clause
21,176
package edu.ucdenver.ccp.datasource.fileparsers.hprd; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2015 Regents of the University of Colorado * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the Regents of the University of Colorado 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. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import edu.ucdenver.ccp.common.collections.CollectionsUtil; import edu.ucdenver.ccp.common.file.CharacterEncoding; import edu.ucdenver.ccp.common.file.FileUtil; import edu.ucdenver.ccp.datasource.fileparsers.RecordReader; import edu.ucdenver.ccp.datasource.fileparsers.test.RecordReaderTester; import edu.ucdenver.ccp.datasource.identifiers.ebi.uniprot.UniProtID; import edu.ucdenver.ccp.datasource.identifiers.hprd.HprdID; import edu.ucdenver.ccp.datasource.identifiers.ncbi.GenBankID; import edu.ucdenver.ccp.datasource.identifiers.ncbi.gene.EntrezGeneID; import edu.ucdenver.ccp.datasource.identifiers.ncbi.omim.OmimID; import edu.ucdenver.ccp.datasource.identifiers.ncbi.refseq.RefSeqID; /** * * @author Bill Baumgartner * */ public class HprdIdMappingsTxtFileParserTest extends RecordReaderTester { private static final String SAMPLE_HprdIdMappingsTxt_FILE_NAME = "HPRD_ID_MAPPINGS.txt"; @Override protected String getSampleFileName() { return SAMPLE_HprdIdMappingsTxt_FILE_NAME; } @Override protected RecordReader<?> initSampleRecordReader() throws IOException { return new HprdIdMappingsTxtFileParser(sampleInputFile, CharacterEncoding.US_ASCII); } @Test public void testParser() { try { HprdIdMappingsTxtFileParser parser = new HprdIdMappingsTxtFileParser(sampleInputFile, CharacterEncoding.US_ASCII); if (parser.hasNext()) { /* 00001 ALDH1A1 NM_000689.3 NP_000680.2 216 0 P00352 Aldehyde dehydrogenase 1 */ HprdIdMappingsTxtFileData record = parser.next(); assertEquals(new HprdID("00001"), record.getHprdID()); assertEquals("ALDH1A1", record.getGeneSymbol()); assertEquals(new RefSeqID("NM_000689.3"), record.getNucleotideAccession()); assertEquals(new RefSeqID("NP_000680.2"), record.getProteinAccession()); assertEquals(new EntrezGeneID(216), record.getEntrezGeneID()); assertNull(record.getOmimID()); assertEquals(CollectionsUtil.createList(new UniProtID("P00352")), record.getSwissProtIDs()); assertEquals("Aldehyde dehydrogenase 1", record.getMainName()); } else { fail("Parser should have returned a record here."); } if (parser.hasNext()) { /* * 19429 FXYD8 NM_001099278.1 NP_001092748.1 406875 - P58550 FXYD domain containing * ion transport regulator 8 */ HprdIdMappingsTxtFileData record = parser.next(); assertEquals(new HprdID("19429"), record.getHprdID()); assertEquals("FXYD8", record.getGeneSymbol()); assertEquals(new RefSeqID("NM_001099278.1"), record.getNucleotideAccession()); assertEquals(new RefSeqID("NP_001092748.1"), record.getProteinAccession()); assertEquals(new EntrezGeneID(406875), record.getEntrezGeneID()); assertNull(record.getOmimID()); assertEquals(CollectionsUtil.createList(new UniProtID("P58550")), record.getSwissProtIDs()); assertEquals("FXYD domain containing ion transport regulator 8", record.getMainName()); } else { fail("Parser should have returned a record here."); } if (parser.hasNext()) { /* 19398 - NM_001039496.1 NP_001034585.1 25858 - - DKFZP566E164 protein */ HprdIdMappingsTxtFileData record = parser.next(); assertEquals(new HprdID("19398"), record.getHprdID()); assertNull(record.getGeneSymbol()); assertEquals(new RefSeqID("NM_001039496.1"), record.getNucleotideAccession()); assertEquals(new RefSeqID("NP_001034585.1"), record.getProteinAccession()); assertEquals(new EntrezGeneID(25858), record.getEntrezGeneID()); assertNull(record.getOmimID()); assertEquals(new ArrayList<UniProtID>(), record.getSwissProtIDs()); assertEquals("DKFZP566E164 protein", record.getMainName()); } else { fail("Parser should have returned a record here."); } if (parser.hasNext()) { /* 01828 TGFB2 M19154.1 AAA50404.1 7042 190220 P61812,Q59EG9 TGF beta 2 */ HprdIdMappingsTxtFileData record = parser.next(); assertEquals(new HprdID("01828"), record.getHprdID()); assertEquals("TGFB2", record.getGeneSymbol()); assertEquals(new GenBankID("M19154.1"), record.getNucleotideAccession()); assertEquals(new GenBankID("AAA50404.1"), record.getProteinAccession()); assertEquals(new EntrezGeneID(7042), record.getEntrezGeneID()); assertEquals(new OmimID(190220), record.getOmimID()); assertEquals(CollectionsUtil.createList(new UniProtID("P61812"), new UniProtID("Q59EG9")), record.getSwissProtIDs()); assertEquals("TGF beta 2", record.getMainName()); } else { fail("Parser should have returned a record here."); } assertFalse(parser.hasNext()); } catch (IOException ioe) { ioe.printStackTrace(); fail("Parser threw an IOException"); } } protected Map<File, List<String>> getExpectedOutputFile2LinesMap() { final String NS = "<http://kabob.ucdenver.edu/ice/hprd/"; List<String> lines = CollectionsUtil .createList( NS + "HPRD_00001_ICE> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://kabob.ucdenver.edu/ice/hprd/HprdIce1> .", NS + "HPRD_00001_ICE> <http://purl.obolibrary.org/obo/IAO_0000136> <http://www.hprd.org/HPRD_00001> .", NS + "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NM_000689.3_ICE> .", NS + "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NP_000680.2_ICE> .", NS + "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToEntrezGeneICE> <http://www.ncbi.nlm.nih.gov/gene/EG_216_ICE> .", NS + "HPRD_00001_ICE> <http://www.hprd.org/isLinkedToUniProtICE> <http://purl.uniprot.org/uniprot/P00352_ICE> .", NS + "HPRD_19429_ICE> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://kabob.ucdenver.edu/ice/hprd/HprdIce1> .", NS + "HPRD_19429_ICE> <http://purl.obolibrary.org/obo/IAO_0000136> <http://www.hprd.org/HPRD_19429> .", NS + "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NM_001099278.1_ICE> .", NS + "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NP_001092748.1_ICE> .", NS + "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToEntrezGeneICE> <http://www.ncbi.nlm.nih.gov/gene/EG_406875_ICE> .", NS + "HPRD_19429_ICE> <http://www.hprd.org/isLinkedToUniProtICE> <http://purl.uniprot.org/uniprot/P58550_ICE> .", NS + "HPRD_19398_ICE> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://kabob.ucdenver.edu/ice/hprd/HprdIce1> .", NS + "HPRD_19398_ICE> <http://purl.obolibrary.org/obo/IAO_0000136> <http://www.hprd.org/HPRD_19398> .", NS + "HPRD_19398_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NM_001039496.1_ICE> .", NS + "HPRD_19398_ICE> <http://www.hprd.org/isLinkedToRefSeqICE> <http://www.ncbi.nlm.nih.gov/refseq/NP_001034585.1_ICE> .", NS + "HPRD_19398_ICE> <http://www.hprd.org/isLinkedToEntrezGeneICE> <http://www.ncbi.nlm.nih.gov/gene/EG_25858_ICE> ."); Map<File, List<String>> file2LinesMap = new HashMap<File, List<String>>(); file2LinesMap.put(FileUtil.appendPathElementsToDirectory(outputDirectory, "hprd-idmappings.nt"), lines); return file2LinesMap; } protected Map<String, Integer> getExpectedFileStatementCounts() { Map<String, Integer> counts = new HashMap<String, Integer>(); counts.put("hprd-idmappings.nt", 17); counts.put("kabob-meta-hprd-idmappings.nt", 6); return counts; } }
bill-baumgartner/datasource
datasource-fileparsers/src/test/java/edu/ucdenver/ccp/datasource/fileparsers/hprd/HprdIdMappingsTxtFileParserTest.java
Java
bsd-3-clause
9,642
{% if topics %}<div class="block"> <h3><a href="/{{ section.slug }}/topics/{% if date %}{{ date|date:"Y" }}/{{ date|date:"b" }}/{% endif %}">{{ section.tag_name }}</a></h3> <div>{% for topic in topics %}<a href="/{{ section.slug }}/{{ topic.slug }}/{% if date %}{{ date|date:"Y" }}/{{ date|date:"b" }}/{% endif %}">{{ topic.name }}</a>{% if not forloop.last %} &middot; {% endif %}{% endfor %}</div> </div>{% endif %}
boar/boar
boar/templates/articles/blocks/topics.html
HTML
bsd-3-clause
426
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD 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://framework.zend.com/license/new-bsd * 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 license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: MediaEntry.php 24593 2012-01-05 20:35:02Z matthew $ */ /** * @see Zend_Gdata_Media */ //require_once 'Zend/Gdata/Media.php'; /** * @see Zend_Gdata_Media_Entry */ //require_once 'Zend/Gdata/Media/Entry.php'; /** * @see Zend_Gdata_YouTube_Extension_MediaGroup */ //require_once 'Zend/Gdata/YouTube/Extension/MediaGroup.php'; /** * Represents the YouTube flavor of a Gdata Media Entry * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_YouTube_MediaEntry extends Zend_Gdata_Media_Entry { protected $_entryClassName = 'Zend_Gdata_YouTube_MediaEntry'; /** * media:group element * * @var Zend_Gdata_YouTube_Extension_MediaGroup */ protected $_mediaGroup = null; /** * Creates individual Entry objects of the appropriate type and * stores them as members of this entry based upon DOM data. * * @param DOMNode $child The DOMNode to process */ protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; switch ($absoluteNodeName) { case $this->lookupNamespace('media') . ':' . 'group': $mediaGroup = new Zend_Gdata_YouTube_Extension_MediaGroup(); $mediaGroup->transferFromDOM($child); $this->_mediaGroup = $mediaGroup; break; default: parent::takeChildFromDOM($child); break; } } }
webino/ZF1Gdata
src/Zend/Gdata/YouTube/MediaEntry.php
PHP
bsd-3-clause
2,354
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 5, transform = "Quantization", sigma = 0.0, exog_count = 100, ar_order = 12);
antoinecarme/pyaf
tests/artificial/transf_Quantization/trend_MovingAverage/cycle_5/ar_12/test_artificial_32_Quantization_MovingAverage_5_12_100.py
Python
bsd-3-clause
272
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_LOGGING_H_ #define BASE_LOGGING_H_ #pragma once #include <cassert> #include <string> #include <cstring> #include <sstream> #include "base/base_export.h" #include "base/basictypes.h" #include "base/debug/debugger.h" #include "build/build_config.h" // // Optional message capabilities // ----------------------------- // Assertion failed messages and fatal errors are displayed in a dialog box // before the application exits. However, running this UI creates a message // loop, which causes application messages to be processed and potentially // dispatched to existing application windows. Since the application is in a // bad state when this assertion dialog is displayed, these messages may not // get processed and hang the dialog, or the application might go crazy. // // Therefore, it can be beneficial to display the error dialog in a separate // process from the main application. When the logging system needs to display // a fatal error dialog box, it will look for a program called // "DebugMessage.exe" in the same directory as the application executable. It // will run this application with the message as the command line, and will // not include the name of the application as is traditional for easier // parsing. // // The code for DebugMessage.exe is only one line. In WinMain, do: // MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0); // // If DebugMessage.exe is not found, the logging code will use a normal // MessageBox, potentially causing the problems discussed above. // Instructions // ------------ // // Make a bunch of macros for logging. The way to log things is to stream // things to LOG(<a particular severity level>). E.g., // // LOG(INFO) << "Found " << num_cookies << " cookies"; // // You can also do conditional logging: // // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; // // The above will cause log messages to be output on the 1st, 11th, 21st, ... // times it is executed. Note that the special COUNTER value is used to // identify which repetition is happening. // // The CHECK(condition) macro is active in both debug and release builds and // effectively performs a LOG(FATAL) which terminates the process and // generates a crashdump unless a debugger is attached. // // There are also "debug mode" logging macros like the ones above: // // DLOG(INFO) << "Found cookies"; // // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; // // All "debug mode" logging is compiled away to nothing for non-debug mode // compiles. LOG_IF and development flags also work well together // because the code can be compiled away sometimes. // // We also have // // LOG_ASSERT(assertion); // DLOG_ASSERT(assertion); // // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion; // // There are "verbose level" logging macros. They look like // // VLOG(1) << "I'm printed when you run the program with --v=1 or more"; // VLOG(2) << "I'm printed when you run the program with --v=2 or more"; // // These always log at the INFO log level (when they log at all). // The verbose logging can also be turned on module-by-module. For instance, // --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0 // will cause: // a. VLOG(2) and lower messages to be printed from profile.{h,cc} // b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc} // c. VLOG(3) and lower messages to be printed from files prefixed with // "browser" // d. VLOG(4) and lower messages to be printed from files under a // "chromeos" directory. // e. VLOG(0) and lower messages to be printed from elsewhere // // The wildcarding functionality shown by (c) supports both '*' (match // 0 or more characters) and '?' (match any single character) // wildcards. Any pattern containing a forward or backward slash will // be tested against the whole pathname and not just the module. // E.g., "*/foo/bar/*=2" would change the logging level for all code // in source files under a "foo/bar" directory. // // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as // // if (VLOG_IS_ON(2)) { // // do some logging preparation and logging // // that can't be accomplished with just VLOG(2) << ...; // } // // There is also a VLOG_IF "verbose level" condition macro for sample // cases, when some extra computation and preparation for logs is not // needed. // // VLOG_IF(1, (size > 1024)) // << "I'm printed when size is more than 1024 and when you run the " // "program with --v=1 or more"; // // We also override the standard 'assert' to use 'DLOG_ASSERT'. // // Lastly, there is: // // PLOG(ERROR) << "Couldn't do foo"; // DPLOG(ERROR) << "Couldn't do foo"; // PLOG_IF(ERROR, cond) << "Couldn't do foo"; // DPLOG_IF(ERROR, cond) << "Couldn't do foo"; // PCHECK(condition) << "Couldn't do foo"; // DPCHECK(condition) << "Couldn't do foo"; // // which append the last system error to the message in string form (taken from // GetLastError() on Windows and errno on POSIX). // // The supported severity levels for macros that allow you to specify one // are (in increasing order of severity) INFO, WARNING, ERROR, ERROR_REPORT, // and FATAL. // // Very important: logging a message at the FATAL severity level causes // the program to terminate (after the message is logged). // // Note the special severity of ERROR_REPORT only available/relevant in normal // mode, which displays error dialog without terminating the program. There is // no error dialog for severity ERROR or below in normal mode. // // There is also the special severity of DFATAL, which logs FATAL in // debug mode, ERROR in normal mode. namespace logging { // Where to record logging output? A flat file and/or system debug log via // OutputDebugString. Defaults on Windows to LOG_ONLY_TO_FILE, and on // POSIX to LOG_ONLY_TO_SYSTEM_DEBUG_LOG (aka stderr). enum LoggingDestination { LOG_NONE, LOG_ONLY_TO_FILE, LOG_ONLY_TO_SYSTEM_DEBUG_LOG, LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG }; // Indicates that the log file should be locked when being written to. // Often, there is no locking, which is fine for a single threaded program. // If logging is being done from multiple threads or there can be more than // one process doing the logging, the file should be locked during writes to // make each log outut atomic. Other writers will block. // // All processes writing to the log file must have their locking set for it to // work properly. Defaults to DONT_LOCK_LOG_FILE. enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE }; // On startup, should we delete or append to an existing log file (if any)? // Defaults to APPEND_TO_OLD_LOG_FILE. enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE }; enum DcheckState { DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS, ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS }; // TODO(avi): do we want to do a unification of character types here? #if defined(OS_WIN) typedef wchar_t PathChar; #else typedef char PathChar; #endif // Define different names for the BaseInitLoggingImpl() function depending on // whether NDEBUG is defined or not so that we'll fail to link if someone tries // to compile logging.cc with NDEBUG but includes logging.h without defining it, // or vice versa. #if NDEBUG #define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG #else #define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG #endif // Implementation of the InitLogging() method declared below. We use a // more-specific name so we can #define it above without affecting other code // that has named stuff "InitLogging". BASE_EXPORT bool BaseInitLoggingImpl(const PathChar* log_file, LoggingDestination logging_dest, LogLockingState lock_log, OldFileDeletionState delete_old, DcheckState dcheck_state); // Sets the log file name and other global logging state. Calling this function // is recommended, and is normally done at the beginning of application init. // If you don't call it, all the flags will be initialized to their default // values, and there is a race condition that may leak a critical section // object if two threads try to do the first log at the same time. // See the definition of the enums above for descriptions and default values. // // The default log file is initialized to "debug.log" in the application // directory. You probably don't want this, especially since the program // directory may not be writable on an enduser's system. // // This function may be called a second time to re-direct logging (e.g after // loging in to a user partition), however it should never be called more than // twice. inline bool InitLogging(const PathChar* log_file, LoggingDestination logging_dest, LogLockingState lock_log, OldFileDeletionState delete_old, DcheckState dcheck_state) { return BaseInitLoggingImpl(log_file, logging_dest, lock_log, delete_old, dcheck_state); } // Sets the log level. Anything at or above this level will be written to the // log file/displayed to the user (if applicable). Anything below this level // will be silently ignored. The log level defaults to 0 (everything is logged // up to level INFO) if this function is not called. // Note that log messages for VLOG(x) are logged at level -x, so setting // the min log level to negative values enables verbose logging. BASE_EXPORT void SetMinLogLevel(int level); // Gets the current log level. BASE_EXPORT int GetMinLogLevel(); // Gets the VLOG default verbosity level. BASE_EXPORT int GetVlogVerbosity(); // Gets the current vlog level for the given file (usually taken from // __FILE__). // Note that |N| is the size *with* the null terminator. BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N); template <size_t N> int GetVlogLevel(const char (&file)[N]) { return GetVlogLevelHelper(file, N); } // Sets the common items you want to be prepended to each log message. // process and thread IDs default to off, the timestamp defaults to on. // If this function is not called, logging defaults to writing the timestamp // only. BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id, bool enable_timestamp, bool enable_tickcount); // Sets whether or not you'd like to see fatal debug messages popped up in // a dialog box or not. // Dialogs are not shown by default. BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs); // Sets the Log Assert Handler that will be used to notify of check failures. // The default handler shows a dialog box and then terminate the process, // however clients can use this function to override with their own handling // (e.g. a silent one for Unit Tests) typedef void (*LogAssertHandlerFunction)(const std::string& str); BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler); // Sets the Log Report Handler that will be used to notify of check failures // in non-debug mode. The default handler shows a dialog box and continues // the execution, however clients can use this function to override with their // own handling. typedef void (*LogReportHandlerFunction)(const std::string& str); BASE_EXPORT void SetLogReportHandler(LogReportHandlerFunction handler); // Sets the Log Message Handler that gets passed every log message before // it's sent to other log destinations (if any). // Returns true to signal that it handled the message and the message // should not be sent to other log destinations. typedef bool (*LogMessageHandlerFunction)(int severity, const char* file, int line, size_t message_start, const std::string& str); BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler); BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler(); typedef int LogSeverity; const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity // Note: the log severities are used to index into the array of names, // see log_severity_names. const LogSeverity LOG_INFO = 0; const LogSeverity LOG_WARNING = 1; const LogSeverity LOG_ERROR = 2; const LogSeverity LOG_ERROR_REPORT = 3; const LogSeverity LOG_FATAL = 4; const LogSeverity LOG_NUM_SEVERITIES = 5; // LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode #ifdef NDEBUG const LogSeverity LOG_DFATAL = LOG_ERROR; #else const LogSeverity LOG_DFATAL = LOG_FATAL; #endif // A few definitions of macros that don't generate much code. These are used // by LOG() and LOG_IF, etc. Since these are used all over our code, it's // better to have compact code for these operations. #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \ logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \ logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \ logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName, ...) \ logging::ClassName(__FILE__, __LINE__, \ logging::LOG_ERROR_REPORT , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \ logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \ logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_INFO \ COMPACT_GOOGLE_LOG_EX_INFO(LogMessage) #define COMPACT_GOOGLE_LOG_WARNING \ COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage) #define COMPACT_GOOGLE_LOG_ERROR \ COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage) #define COMPACT_GOOGLE_LOG_ERROR_REPORT \ COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(LogMessage) #define COMPACT_GOOGLE_LOG_FATAL \ COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage) #define COMPACT_GOOGLE_LOG_DFATAL \ COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage) // wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets // substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us // to keep using this syntax, we define this macro to do the same thing // as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that // the Windows SDK does for consistency. #define ERROR 0 #define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \ COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR // Needed for LOG_IS_ON(ERROR). const LogSeverity LOG_0 = LOG_ERROR; // As special cases, we can assume that LOG_IS_ON(ERROR_REPORT) and // LOG_IS_ON(FATAL) always hold. Also, LOG_IS_ON(DFATAL) always holds // in debug mode. In particular, CHECK()s will always fire if they // fail. #define LOG_IS_ON(severity) \ ((::logging::LOG_ ## severity) >= ::logging::GetMinLogLevel()) // We can't do any caching tricks with VLOG_IS_ON() like the // google-glog version since it requires GCC extensions. This means // that using the v-logging functions in conjunction with --vmodule // may be slow. #define VLOG_IS_ON(verboselevel) \ ((verboselevel) <= ::logging::GetVlogLevel(__FILE__)) // Helper macro which avoids evaluating the arguments to a stream if // the condition doesn't hold. #define LAZY_STREAM(stream, condition) \ !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream) // We use the preprocessor's merging operator, "##", so that, e.g., // LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny // subtle difference between ostream member streaming functions (e.g., // ostream::operator<<(int) and ostream non-member streaming functions // (e.g., ::operator<<(ostream&, string&): it turns out that it's // impossible to stream something like a string directly to an unnamed // ostream. We employ a neat hack by calling the stream() member // function of LogMessage which seems to avoid the problem. #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity)) #define LOG_IF(severity, condition) \ LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition)) #define SYSLOG(severity) LOG(severity) #define SYSLOG_IF(severity, condition) LOG_IF(severity, condition) // The VLOG macros log with negative verbosities. #define VLOG_STREAM(verbose_level) \ logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream() #define VLOG(verbose_level) \ LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level)) #define VLOG_IF(verbose_level, condition) \ LAZY_STREAM(VLOG_STREAM(verbose_level), \ VLOG_IS_ON(verbose_level) && (condition)) #if defined (OS_WIN) #define VPLOG_STREAM(verbose_level) \ logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \ ::logging::GetLastSystemErrorCode()).stream() #elif defined(OS_POSIX) #define VPLOG_STREAM(verbose_level) \ logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \ ::logging::GetLastSystemErrorCode()).stream() #endif #define VPLOG(verbose_level) \ LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level)) #define VPLOG_IF(verbose_level, condition) \ LAZY_STREAM(VPLOG_STREAM(verbose_level), \ VLOG_IS_ON(verbose_level) && (condition)) // TODO(akalin): Add more VLOG variants, e.g. VPLOG. #define LOG_ASSERT(condition) \ LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " #define SYSLOG_ASSERT(condition) \ SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " #if defined(OS_WIN) #define LOG_GETLASTERROR_STREAM(severity) \ COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \ ::logging::GetLastSystemErrorCode()).stream() #define LOG_GETLASTERROR(severity) \ LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), LOG_IS_ON(severity)) #define LOG_GETLASTERROR_MODULE_STREAM(severity, module) \ COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \ ::logging::GetLastSystemErrorCode(), module).stream() #define LOG_GETLASTERROR_MODULE(severity, module) \ LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \ LOG_IS_ON(severity)) // PLOG_STREAM is used by PLOG, which is the usual error logging macro // for each platform. #define PLOG_STREAM(severity) LOG_GETLASTERROR_STREAM(severity) #elif defined(OS_POSIX) #define LOG_ERRNO_STREAM(severity) \ COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \ ::logging::GetLastSystemErrorCode()).stream() #define LOG_ERRNO(severity) \ LAZY_STREAM(LOG_ERRNO_STREAM(severity), LOG_IS_ON(severity)) // PLOG_STREAM is used by PLOG, which is the usual error logging macro // for each platform. #define PLOG_STREAM(severity) LOG_ERRNO_STREAM(severity) #endif #define PLOG(severity) \ LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity)) #define PLOG_IF(severity, condition) \ LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition)) // http://crbug.com/16512 is open for a real fix for this. For now, Windows // uses OFFICIAL_BUILD and other platforms use the branding flag when NDEBUG is // defined. #if ( defined(OS_WIN) && defined(OFFICIAL_BUILD)) || \ (!defined(OS_WIN) && defined(NDEBUG) && defined(GOOGLE_CHROME_BUILD)) #define LOGGING_IS_OFFICIAL_BUILD 1 #else #define LOGGING_IS_OFFICIAL_BUILD 0 #endif // The actual stream used isn't important. #define EAT_STREAM_PARAMETERS \ true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL) // CHECK dies with a fatal error if condition is not true. It is *not* // controlled by NDEBUG, so the check will be executed regardless of // compilation mode. // // We make sure CHECK et al. always evaluates their arguments, as // doing CHECK(FunctionWithSideEffect()) is a common idiom. #if LOGGING_IS_OFFICIAL_BUILD // Make all CHECK functions discard their log strings to reduce code // bloat for official builds. // TODO(akalin): This would be more valuable if there were some way to // remove BreakDebugger() from the backtrace, perhaps by turning it // into a macro (like __debugbreak() on Windows). #define CHECK(condition) \ !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS #define PCHECK(condition) CHECK(condition) #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2)) #else #define CHECK(condition) \ LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \ << "Check failed: " #condition ". " #define PCHECK(condition) \ LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \ << "Check failed: " #condition ". " // Helper macro for binary operators. // Don't use this macro directly in your code, use CHECK_EQ et al below. // // TODO(akalin): Rewrite this so that constructs like if (...) // CHECK_EQ(...) else { ... } work properly. #define CHECK_OP(name, op, val1, val2) \ if (std::string* _result = \ logging::Check##name##Impl((val1), (val2), \ #val1 " " #op " " #val2)) \ logging::LogMessage(__FILE__, __LINE__, _result).stream() #endif // Build the error message string. This is separate from the "Impl" // function template because it is not performance critical and so can // be out of line, while the "Impl" code should be inline. Caller // takes ownership of the returned string. template<class t1, class t2> std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) { std::ostringstream ss; ss << names << " (" << v1 << " vs. " << v2 << ")"; std::string* msg = new std::string(ss.str()); return msg; } // MSVC doesn't like complex extern templates and DLLs. #if !defined(COMPILER_MSVC) // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated // in logging.cc. extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>( const int&, const int&, const char* names); extern template BASE_EXPORT std::string* MakeCheckOpString<unsigned long, unsigned long>( const unsigned long&, const unsigned long&, const char* names); extern template BASE_EXPORT std::string* MakeCheckOpString<unsigned long, unsigned int>( const unsigned long&, const unsigned int&, const char* names); extern template BASE_EXPORT std::string* MakeCheckOpString<unsigned int, unsigned long>( const unsigned int&, const unsigned long&, const char* names); extern template BASE_EXPORT std::string* MakeCheckOpString<std::string, std::string>( const std::string&, const std::string&, const char* name); #endif // Helper functions for CHECK_OP macro. // The (int, int) specialization works around the issue that the compiler // will not instantiate the template version of the function on values of // unnamed enum type - see comment below. #define DEFINE_CHECK_OP_IMPL(name, op) \ template <class t1, class t2> \ inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \ const char* names) { \ if (v1 op v2) return NULL; \ else return MakeCheckOpString(v1, v2, names); \ } \ inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \ if (v1 op v2) return NULL; \ else return MakeCheckOpString(v1, v2, names); \ } DEFINE_CHECK_OP_IMPL(EQ, ==) DEFINE_CHECK_OP_IMPL(NE, !=) DEFINE_CHECK_OP_IMPL(LE, <=) DEFINE_CHECK_OP_IMPL(LT, < ) DEFINE_CHECK_OP_IMPL(GE, >=) DEFINE_CHECK_OP_IMPL(GT, > ) #undef DEFINE_CHECK_OP_IMPL #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2) #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2) #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2) #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2) #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2) #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2) #if LOGGING_IS_OFFICIAL_BUILD // In order to have optimized code for official builds, remove DLOGs and // DCHECKs. #define ENABLE_DLOG 0 #define ENABLE_DCHECK 0 #elif defined(NDEBUG) // Otherwise, if we're a release build, remove DLOGs but not DCHECKs // (since those can still be turned on via a command-line flag). #define ENABLE_DLOG 0 #define ENABLE_DCHECK 1 #else // Otherwise, we're a debug build so enable DLOGs and DCHECKs. #define ENABLE_DLOG 1 #define ENABLE_DCHECK 1 #endif // Definitions for DLOG et al. #if ENABLE_DLOG #define DLOG_IS_ON(severity) LOG_IS_ON(severity) #define DLOG_IF(severity, condition) LOG_IF(severity, condition) #define DLOG_ASSERT(condition) LOG_ASSERT(condition) #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition) #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition) #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition) #else // ENABLE_DLOG // If ENABLE_DLOG is off, we want to avoid emitting any references to // |condition| (which may reference a variable defined only if NDEBUG // is not defined). Contrast this with DCHECK et al., which has // different behavior. #define DLOG_IS_ON(severity) false #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS #endif // ENABLE_DLOG // DEBUG_MODE is for uses like // if (DEBUG_MODE) foo.CheckThatFoo(); // instead of // #ifndef NDEBUG // foo.CheckThatFoo(); // #endif // // We tie its state to ENABLE_DLOG. enum { DEBUG_MODE = ENABLE_DLOG }; #undef ENABLE_DLOG #define DLOG(severity) \ LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity)) #if defined(OS_WIN) #define DLOG_GETLASTERROR(severity) \ LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity), DLOG_IS_ON(severity)) #define DLOG_GETLASTERROR_MODULE(severity, module) \ LAZY_STREAM(LOG_GETLASTERROR_STREAM(severity, module), \ DLOG_IS_ON(severity)) #elif defined(OS_POSIX) #define DLOG_ERRNO(severity) \ LAZY_STREAM(LOG_ERRNO_STREAM(severity), DLOG_IS_ON(severity)) #endif #define DPLOG(severity) \ LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity)) #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel)) #define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel)) // Definitions for DCHECK et al. #if ENABLE_DCHECK #if defined(NDEBUG) BASE_EXPORT extern DcheckState g_dcheck_state; #if defined(DCHECK_ALWAYS_ON) #define DCHECK_IS_ON() true #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL const LogSeverity LOG_DCHECK = LOG_FATAL; #else #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ COMPACT_GOOGLE_LOG_EX_ERROR_REPORT(ClassName , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_ERROR_REPORT const LogSeverity LOG_DCHECK = LOG_ERROR_REPORT; #define DCHECK_IS_ON() \ ((::logging::g_dcheck_state == \ ::logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS) && \ LOG_IS_ON(DCHECK)) #endif // defined(DCHECK_ALWAYS_ON) #else // defined(NDEBUG) // On a regular debug build, we want to have DCHECKs enabled. #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL const LogSeverity LOG_DCHECK = LOG_FATAL; #define DCHECK_IS_ON() true #endif // defined(NDEBUG) #else // ENABLE_DCHECK // These are just dummy values since DCHECK_IS_ON() is always false in // this case. #define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__) #define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO const LogSeverity LOG_DCHECK = LOG_INFO; #define DCHECK_IS_ON() false #endif // ENABLE_DCHECK #undef ENABLE_DCHECK // DCHECK et al. make sure to reference |condition| regardless of // whether DCHECKs are enabled; this is so that we don't get unused // variable warnings if the only use of a variable is in a DCHECK. // This behavior is different from DLOG_IF et al. #define DCHECK(condition) \ LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \ << "Check failed: " #condition ". " #define DPCHECK(condition) \ LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() && !(condition)) \ << "Check failed: " #condition ". " // Helper macro for binary operators. // Don't use this macro directly in your code, use DCHECK_EQ et al below. #define DCHECK_OP(name, op, val1, val2) \ if (DCHECK_IS_ON()) \ if (std::string* _result = \ logging::Check##name##Impl((val1), (val2), \ #val1 " " #op " " #val2)) \ logging::LogMessage( \ __FILE__, __LINE__, ::logging::LOG_DCHECK, \ _result).stream() // Equality/Inequality checks - compare two values, and log a // LOG_DCHECK message including the two values when the result is not // as expected. The values must have operator<<(ostream, ...) // defined. // // You may append to the error message like so: // DCHECK_NE(1, 2) << ": The world must be ending!"; // // We are very careful to ensure that each argument is evaluated exactly // once, and that anything which is legal to pass as a function argument is // legal here. In particular, the arguments may be temporary expressions // which will end up being destroyed at the end of the apparent statement, // for example: // DCHECK_EQ(string("abc")[1], 'b'); // // WARNING: These may not compile correctly if one of the arguments is a pointer // and the other is NULL. To work around this, simply static_cast NULL to the // type of the desired pointer. #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2) #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2) #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2) #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2) #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2) #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2) #define NOTREACHED() DCHECK(false) // Redefine the standard assert to use our nice log files #undef assert #define assert(x) DLOG_ASSERT(x) // This class more or less represents a particular log message. You // create an instance of LogMessage and then stream stuff to it. // When you finish streaming to it, ~LogMessage is called and the // full message gets streamed to the appropriate destination. // // You shouldn't actually use LogMessage's constructor to log things, // though. You should use the LOG() macro (and variants thereof) // above. class BASE_EXPORT LogMessage { public: LogMessage(const char* file, int line, LogSeverity severity, int ctr); // Two special constructors that generate reduced amounts of code at // LOG call sites for common cases. // // Used for LOG(INFO): Implied are: // severity = LOG_INFO, ctr = 0 // // Using this constructor instead of the more complex constructor above // saves a couple of bytes per call site. LogMessage(const char* file, int line); // Used for LOG(severity) where severity != INFO. Implied // are: ctr = 0 // // Using this constructor instead of the more complex constructor above // saves a couple of bytes per call site. LogMessage(const char* file, int line, LogSeverity severity); // A special constructor used for check failures. Takes ownership // of the given string. // Implied severity = LOG_FATAL LogMessage(const char* file, int line, std::string* result); // A special constructor used for check failures, with the option to // specify severity. Takes ownership of the given string. LogMessage(const char* file, int line, LogSeverity severity, std::string* result); ~LogMessage(); std::ostream& stream() { return stream_; } private: void Init(const char* file, int line); LogSeverity severity_; std::ostringstream stream_; size_t message_start_; // Offset of the start of the message (past prefix // info). // The file and line information passed in to the constructor. const char* file_; const int line_; #if defined(OS_WIN) // Stores the current value of GetLastError in the constructor and restores // it in the destructor by calling SetLastError. // This is useful since the LogMessage class uses a lot of Win32 calls // that will lose the value of GLE and the code that called the log function // will have lost the thread error value when the log call returns. class BASE_EXPORT SaveLastError { public: SaveLastError(); ~SaveLastError(); unsigned long get_error() const { return last_error_; } protected: unsigned long last_error_; }; SaveLastError last_error_; #endif DISALLOW_COPY_AND_ASSIGN(LogMessage); }; // A non-macro interface to the log facility; (useful // when the logging level is not a compile-time constant). inline void LogAtLevel(int const log_level, std::string const &msg) { LogMessage(__FILE__, __LINE__, log_level).stream() << msg; } // This class is used to explicitly ignore values in the conditional // logging macros. This avoids compiler warnings like "value computed // is not used" and "statement has no effect". class LogMessageVoidify { public: LogMessageVoidify() { } // This has to be an operator with a precedence lower than << but // higher than ?: void operator&(std::ostream&) { } }; #if defined(OS_WIN) typedef unsigned long SystemErrorCode; #elif defined(OS_POSIX) typedef int SystemErrorCode; #endif // Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to // pull in windows.h just for GetLastError() and DWORD. BASE_EXPORT SystemErrorCode GetLastSystemErrorCode(); #if defined(OS_WIN) // Appends a formatted system message of the GetLastError() type. class BASE_EXPORT Win32ErrorLogMessage { public: Win32ErrorLogMessage(const char* file, int line, LogSeverity severity, SystemErrorCode err, const char* module); Win32ErrorLogMessage(const char* file, int line, LogSeverity severity, SystemErrorCode err); // Appends the error message before destructing the encapsulated class. ~Win32ErrorLogMessage(); std::ostream& stream() { return log_message_.stream(); } private: SystemErrorCode err_; // Optional name of the module defining the error. const char* module_; LogMessage log_message_; DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage); }; #elif defined(OS_POSIX) // Appends a formatted system message of the errno type class BASE_EXPORT ErrnoLogMessage { public: ErrnoLogMessage(const char* file, int line, LogSeverity severity, SystemErrorCode err); // Appends the error message before destructing the encapsulated class. ~ErrnoLogMessage(); std::ostream& stream() { return log_message_.stream(); } private: SystemErrorCode err_; LogMessage log_message_; DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage); }; #endif // OS_WIN // Closes the log file explicitly if open. // NOTE: Since the log file is opened as necessary by the action of logging // statements, there's no guarantee that it will stay closed // after this call. BASE_EXPORT void CloseLogFile(); // Async signal safe logging mechanism. BASE_EXPORT void RawLog(int level, const char* message); #define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message) #define RAW_CHECK(condition) \ do { \ if (!(condition)) \ logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \ } while (0) } // namespace logging // These functions are provided as a convenience for logging, which is where we // use streams (it is against Google style to use streams in other places). It // is designed to allow you to emit non-ASCII Unicode strings to the log file, // which is normally ASCII. It is relatively slow, so try not to use it for // common cases. Non-ASCII characters will be converted to UTF-8 by these // operators. BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr); inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) { return out << wstr.c_str(); } // The NOTIMPLEMENTED() macro annotates codepaths which have // not been implemented yet. // // The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY: // 0 -- Do nothing (stripped by compiler) // 1 -- Warn at compile time // 2 -- Fail at compile time // 3 -- Fail at runtime (DCHECK) // 4 -- [default] LOG(ERROR) at runtime // 5 -- LOG(ERROR) at runtime, only once per call-site #ifndef NOTIMPLEMENTED_POLICY // Select default policy: LOG(ERROR) #define NOTIMPLEMENTED_POLICY 4 #endif #if defined(COMPILER_GCC) // On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name // of the current function in the NOTIMPLEMENTED message. #define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__ #else #define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED" #endif #if NOTIMPLEMENTED_POLICY == 0 #define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS #elif NOTIMPLEMENTED_POLICY == 1 // TODO, figure out how to generate a warning #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED) #elif NOTIMPLEMENTED_POLICY == 2 #define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED) #elif NOTIMPLEMENTED_POLICY == 3 #define NOTIMPLEMENTED() NOTREACHED() #elif NOTIMPLEMENTED_POLICY == 4 #define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG #elif NOTIMPLEMENTED_POLICY == 5 #define NOTIMPLEMENTED() do {\ static int count = 0;\ LOG_IF(ERROR, 0 == count++) << NOTIMPLEMENTED_MSG;\ } while(0) #endif #endif // BASE_LOGGING_H_
rogerwang/chromium
base/logging.h
C
bsd-3-clause
39,114
# Autogenerated by the mkresources management command 2014-11-13 23:53 from tastypie.resources import ModelResource from tastypie.fields import ToOneField, ToManyField from tastypie.constants import ALL, ALL_WITH_RELATIONS from ietf import api from ietf.message.models import * # pyflakes:ignore from ietf.person.resources import PersonResource from ietf.group.resources import GroupResource from ietf.doc.resources import DocumentResource class MessageResource(ModelResource): by = ToOneField(PersonResource, 'by') related_groups = ToManyField(GroupResource, 'related_groups', null=True) related_docs = ToManyField(DocumentResource, 'related_docs', null=True) class Meta: queryset = Message.objects.all() serializer = api.Serializer() #resource_name = 'message' filtering = { "id": ALL, "time": ALL, "subject": ALL, "frm": ALL, "to": ALL, "cc": ALL, "bcc": ALL, "reply_to": ALL, "body": ALL, "content_type": ALL, "by": ALL_WITH_RELATIONS, "related_groups": ALL_WITH_RELATIONS, "related_docs": ALL_WITH_RELATIONS, } api.message.register(MessageResource()) from ietf.person.resources import PersonResource class SendQueueResource(ModelResource): by = ToOneField(PersonResource, 'by') message = ToOneField(MessageResource, 'message') class Meta: queryset = SendQueue.objects.all() serializer = api.Serializer() #resource_name = 'sendqueue' filtering = { "id": ALL, "time": ALL, "send_at": ALL, "sent_at": ALL, "note": ALL, "by": ALL_WITH_RELATIONS, "message": ALL_WITH_RELATIONS, } api.message.register(SendQueueResource())
wpjesus/codematch
ietf/message/resources.py
Python
bsd-3-clause
1,927
/*************************************************************************** * Copyright (C) YEAR~YEAR by Your Name * * your-email@address.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "big5-internal.h" CONFIG_BINDING_BEGIN(FcitxBig5Config) CONFIG_BINDING_END()
allencch/fcitx-big5
src/big5-config.c
C
bsd-3-clause
1,552
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] OnStatusUpdate trigger -- [HMI API] OnStatusUpdate -- -- Description: -- PoliciesManager must notify HMI via SDL.OnStatusUpdate notification right after one of the statuses -- of UPDATING, UPDATE_NEEDED and UP_TO_DATE is changed from one to another. -- -- Steps: -- 1. Register new app1 -- 2. SDL->HMI: Verify status of SDL.OnStatusUpdate notification -- 3. Trigger PTU -- 4. Register new app2 -- -- Expected result: -- Status changes in a wollowing way: -- "UPDATE_NEEDED" -> "UPDATING" -> "UP_TO_DATE" -> "UPDATE_NEEDED" -> "UPDATING" --------------------------------------------------------------------------------------------- require('user_modules/script_runner').isTestApplicable({ { extendedPolicy = { "EXTERNAL_PROPRIETARY" } } }) --[[ Required Shared libraries ]] local mobileSession = require("mobile_session") local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") local utils = require ('user_modules/utils') --[[ Local variables ]] local policy_file_path = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath") .. "/" local policy_file_name = "PolicyTableUpdate" local file = "files/jsons/Policies/Policy_Table_Update/ptu_18707_1.json" --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Trigger_Device_consent() local is_test_fail = false self.hmi_app1_id = self.applications[config.application1.registerAppInterfaceParams.appName] local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId) :Do(function(_,_) local RequestId1 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE( RequestId1, {result = {code = 0, method = "SDL.GetUserFriendlyMessage"}}) :Do(function(_,_) testCasesForPolicyTable.time_trigger = timestamp() self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = utils.getDeviceMAC(), name = utils.getDeviceName(), isSDLAllowed = true}}) -- EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate", {file = policy_file_path .. "sdl_snapshot.json"}) :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) end) end) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data) self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end function Test:TestStep_PTU_Success() local requestId = self.hmiConnection:SendRequest("SDL.GetPolicyConfigurationData", { policyType = "module_config", property = "endpoints" }) EXPECT_HMIRESPONSE(requestId) :Do(function(_,_) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = policy_file_name}) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY"}) :Do(function(_,_) local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = policy_file_name, appID = self.hmi_app1_id}, file) EXPECT_HMICALL("BasicCommunication.SystemRequest",{ requestType = "PROPRIETARY", fileName = policy_file_path..policy_file_name }) :Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = policy_file_path .. policy_file_name}) end) EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"}) :Do(function(_, _) local requestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", { language = "EN-US", messageCodes = { "StatusUpToDate" } }) EXPECT_HMIRESPONSE(requestId) end) end) end) end function Test:TestStep_StartNewSession() self.mobileSession2 = mobileSession.MobileSession(self, self.mobileConnection) self.mobileSession2:StartService(7) end function Test:TestStep_RegisteNewApp() config.application2.registerAppInterfaceParams.appName = "App1" config.application2.registerAppInterfaceParams.fullAppID = "123_abc" local corId = self.mobileSession2:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application2.registerAppInterfaceParams.appName }}) self.mobileSession2:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate", {}) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
smartdevicelink/sdl_atf_test_scripts
test_scripts/Policies/Policy_Table_Update/156_ATF_PTU_OnStatusUpdate_Trigger.lua
Lua
bsd-3-clause
5,961
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKTEMPORALARRAYOPERATORFILTERWRAP_H #define NATIVE_EXTENSION_VTK_VTKTEMPORALARRAYOPERATORFILTERWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkTemporalArrayOperatorFilter.h> #include "vtkMultiTimeStepAlgorithmWrap.h" #include "../../plus/plus.h" class VtkTemporalArrayOperatorFilterWrap : public VtkMultiTimeStepAlgorithmWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkTemporalArrayOperatorFilterWrap(vtkSmartPointer<vtkTemporalArrayOperatorFilter>); VtkTemporalArrayOperatorFilterWrap(); ~VtkTemporalArrayOperatorFilterWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetFirstTimeStepIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOperator(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOutputArrayNameSuffix(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSecondTimeStepIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetFirstTimeStepIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOperator(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputArrayNameSuffix(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSecondTimeStepIndex(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKTEMPORALARRAYOPERATORFILTERWRAP_CLASSDEF VTK_NODE_PLUS_VTKTEMPORALARRAYOPERATORFILTERWRAP_CLASSDEF #endif }; #endif
axkibe/node-vtk
wrappers/8.1.1/vtkTemporalArrayOperatorFilterWrap.h
C
bsd-3-clause
2,001
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_COLLECTION_SUPPORT_HEAP_HASH_TABLE_BACKING_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_COLLECTION_SUPPORT_HEAP_HASH_TABLE_BACKING_H_ #include "third_party/blink/renderer/platform/heap/heap_page.h" #include "third_party/blink/renderer/platform/heap/threading_traits.h" #include "third_party/blink/renderer/platform/heap/trace_traits.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/conditional_destructor.h" namespace blink { template <typename Table> class HeapHashTableBacking final : public WTF::ConditionalDestructor< HeapHashTableBacking<Table>, std::is_trivially_destructible<typename Table::ValueType>::value> { DISALLOW_NEW(); IS_GARBAGE_COLLECTED_TYPE(); public: template <typename Backing> static void* AllocateObject(size_t size); void Finalize(); }; template <typename Table> struct ThreadingTrait<HeapHashTableBacking<Table>> { STATIC_ONLY(ThreadingTrait); using Key = typename Table::KeyType; using Value = typename Table::ValueType; static const ThreadAffinity kAffinity = (ThreadingTrait<Key>::kAffinity == kMainThreadOnly) && (ThreadingTrait<Value>::kAffinity == kMainThreadOnly) ? kMainThreadOnly : kAnyThread; }; // static template <typename Table> template <typename Backing> void* HeapHashTableBacking<Table>::AllocateObject(size_t size) { ThreadState* state = ThreadStateFor<ThreadingTrait<Backing>::kAffinity>::GetState(); DCHECK(state->IsAllocationAllowed()); const char* type_name = WTF_HEAP_PROFILER_TYPE_NAME(Backing); return state->Heap().AllocateOnArenaIndex( state, size, BlinkGC::kHashTableArenaIndex, GCInfoTrait<Backing>::Index(), type_name); } template <typename Table> void HeapHashTableBacking<Table>::Finalize() { using Value = typename Table::ValueType; static_assert( !std::is_trivially_destructible<Value>::value, "Finalization of trivially destructible classes should not happen."); HeapObjectHeader* header = HeapObjectHeader::FromPayload(this); // Use the payload size as recorded by the heap to determine how many // elements to finalize. size_t length = header->PayloadSize() / sizeof(Value); Value* table = reinterpret_cast<Value*>(this); for (unsigned i = 0; i < length; ++i) { if (!Table::IsEmptyOrDeletedBucket(table[i])) table[i].~Value(); } } template <typename Table> struct MakeGarbageCollectedTrait<HeapHashTableBacking<Table>> { static HeapHashTableBacking<Table>* Call(size_t num_elements) { CHECK_GT(num_elements, 0u); void* memory = HeapHashTableBacking<Table>::template AllocateObject< HeapHashTableBacking<Table>>(num_elements * sizeof(typename Table::ValueType)); HeapObjectHeader* header = HeapObjectHeader::FromPayload(memory); // Placement new as regular operator new() is deleted. HeapHashTableBacking<Table>* object = ::new (memory) HeapHashTableBacking<Table>(); header->MarkFullyConstructed<HeapObjectHeader::AccessMode::kAtomic>(); return object; } }; // The trace trait for the heap hashtable backing is used when we find a // direct pointer to the backing from the conservative stack scanner. This // normally indicates that there is an ongoing iteration over the table, and so // we disable weak processing of table entries. When the backing is found // through the owning hash table we mark differently, in order to do weak // processing. template <typename Table> struct TraceTrait<HeapHashTableBacking<Table>> { STATIC_ONLY(TraceTrait); using Backing = HeapHashTableBacking<Table>; using ValueType = typename Table::ValueTraits::TraitType; using Traits = typename Table::ValueTraits; public: static TraceDescriptor GetTraceDescriptor(const void* self) { return {self, Trace<WTF::kNoWeakHandling>}; } static TraceDescriptor GetWeakTraceDescriptor(const void* self) { return GetWeakTraceDescriptorImpl<ValueType>::GetWeakTraceDescriptor(self); } template <WTF::WeakHandlingFlag WeakHandling = WTF::kNoWeakHandling> static void Trace(Visitor* visitor, const void* self) { if (!Traits::kCanTraceConcurrently) { if (visitor->DeferredTraceIfConcurrent({self, &Trace})) return; } static_assert(WTF::IsTraceableInCollectionTrait<Traits>::value || WTF::IsWeak<ValueType>::value, "T should not be traced"); WTF::TraceInCollectionTrait<WeakHandling, Backing, void>::Trace(visitor, self); } private: template <typename ValueType> struct GetWeakTraceDescriptorImpl { static TraceDescriptor GetWeakTraceDescriptor(const void* backing) { return {backing, nullptr}; } }; template <typename K, typename V> struct GetWeakTraceDescriptorImpl<WTF::KeyValuePair<K, V>> { static TraceDescriptor GetWeakTraceDescriptor(const void* backing) { return GetWeakTraceDescriptorKVPImpl<K, V>::GetWeakTraceDescriptor( backing); } template <typename KeyType, typename ValueType, bool ephemeron_semantics = (WTF::IsWeak<KeyType>::value && !WTF::IsWeak<ValueType>::value && WTF::IsTraceable<ValueType>::value) || (WTF::IsWeak<ValueType>::value && !WTF::IsWeak<KeyType>::value && WTF::IsTraceable<KeyType>::value)> struct GetWeakTraceDescriptorKVPImpl { static TraceDescriptor GetWeakTraceDescriptor(const void* backing) { return {backing, nullptr}; } }; template <typename KeyType, typename ValueType> struct GetWeakTraceDescriptorKVPImpl<KeyType, ValueType, true> { static TraceDescriptor GetWeakTraceDescriptor(const void* backing) { return {backing, Trace<WTF::kWeakHandling>}; } }; }; }; } // namespace blink namespace WTF { // This trace method is for tracing a HashTableBacking either through regular // tracing (via the relevant TraceTraits) or when finding a HashTableBacking // through conservative stack scanning (which will treat all references in the // backing strongly). template <WTF::WeakHandlingFlag WeakHandling, typename Table> struct TraceHashTableBackingInCollectionTrait { using Value = typename Table::ValueType; using Traits = typename Table::ValueTraits; static void Trace(blink::Visitor* visitor, const void* self) { static_assert(IsTraceableInCollectionTrait<Traits>::value || WTF::IsWeak<Value>::value, "Table should not be traced"); const Value* array = reinterpret_cast<const Value*>(self); blink::HeapObjectHeader* header = blink::HeapObjectHeader::FromPayload(self); // Use the payload size as recorded by the heap to determine how many // elements to trace. size_t length = header->PayloadSize() / sizeof(Value); const bool is_concurrent = visitor->IsConcurrent(); for (size_t i = 0; i < length; ++i) { // If tracing concurrently, use a concurrent-safe version of // IsEmptyOrDeletedBucket (check performed on a local copy instead // of directly on the bucket). if (is_concurrent) { if (!HashTableHelper<Value, typename Table::ExtractorType, typename Table::KeyTraitsType>:: IsEmptyOrDeletedBucketSafe(array[i])) { blink::TraceCollectionIfEnabled<WeakHandling, Value, Traits>::Trace( visitor, &array[i]); } } else { if (!HashTableHelper<Value, typename Table::ExtractorType, typename Table::KeyTraitsType>:: IsEmptyOrDeletedBucket(array[i])) { blink::TraceCollectionIfEnabled<WeakHandling, Value, Traits>::Trace( visitor, &array[i]); } } } } }; template <typename Table> struct TraceInCollectionTrait<kNoWeakHandling, blink::HeapHashTableBacking<Table>, void> { static void Trace(blink::Visitor* visitor, const void* self) { TraceHashTableBackingInCollectionTrait<kNoWeakHandling, Table>::Trace( visitor, self); } }; template <typename Table> struct TraceInCollectionTrait<kWeakHandling, blink::HeapHashTableBacking<Table>, void> { static void Trace(blink::Visitor* visitor, const void* self) { TraceHashTableBackingInCollectionTrait<kWeakHandling, Table>::Trace(visitor, self); } }; // Trait for strong treatment of KeyValuePair. This is used to handle regular // KVP but also for strongification of otherwise weakly handled KVPs. template <typename Key, typename Value, typename Traits> struct TraceInCollectionTrait<kNoWeakHandling, KeyValuePair<Key, Value>, Traits> { using EphemeronHelper = blink::EphemeronKeyValuePair<Key, Value, typename Traits::KeyTraits, typename Traits::ValueTraits>; static void Trace(blink::Visitor* visitor, const KeyValuePair<Key, Value>& self) { TraceImpl(visitor, self); } private: template <bool = EphemeronHelper::is_ephemeron> static void TraceImpl(blink::Visitor* visitor, const KeyValuePair<Key, Value>& self); // Strongification of ephemerons, i.e., Weak/Strong and Strong/Weak. template <> static void TraceImpl<true>(blink::Visitor* visitor, const KeyValuePair<Key, Value>& self) { // Strongification of ephemerons, i.e., Weak/Strong and Strong/Weak. // The helper ensures that helper.key always refers to the weak part and // helper.value always refers to the dependent part. // We distinguish ephemeron from Weak/Weak and Strong/Strong to allow users // to override visitation behavior. An example is creating a heap snapshot, // where it is useful to annotate values as being kept alive from keys // rather than the table. EphemeronHelper helper(&self.key, &self.value); // Strongify the weak part. blink::TraceCollectionIfEnabled< kNoWeakHandling, typename EphemeronHelper::KeyType, typename EphemeronHelper::KeyTraits>::Trace(visitor, helper.key); // Strongify the dependent part. visitor->TraceEphemeron( *helper.key, helper.value, blink::TraceCollectionIfEnabled< kNoWeakHandling, typename EphemeronHelper::ValueType, typename EphemeronHelper::ValueTraits>::Trace); } template <> static void TraceImpl<false>(blink::Visitor* visitor, const KeyValuePair<Key, Value>& self) { // Strongification of non-ephemeron KVP, i.e., Strong/Strong or Weak/Weak. // Order does not matter here. blink::TraceCollectionIfEnabled< kNoWeakHandling, Key, typename Traits::KeyTraits>::Trace(visitor, &self.key); blink::TraceCollectionIfEnabled< kNoWeakHandling, Value, typename Traits::ValueTraits>::Trace(visitor, &self.value); } }; template <typename Key, typename Value, typename Traits> struct TraceInCollectionTrait<kWeakHandling, KeyValuePair<Key, Value>, Traits> { using EphemeronHelper = blink::EphemeronKeyValuePair<Key, Value, typename Traits::KeyTraits, typename Traits::ValueTraits>; static bool IsAlive(const blink::LivenessBroker& info, const KeyValuePair<Key, Value>& self) { // Needed for Weak/Weak, Strong/Weak (reverse ephemeron), and Weak/Strong // (ephemeron). Order of invocation does not matter as tracing weak key or // value does not have any side effects. return blink::TraceCollectionIfEnabled< WeakHandlingTrait<Key>::value, Key, typename Traits::KeyTraits>::IsAlive(info, self.key) && blink::TraceCollectionIfEnabled< WeakHandlingTrait<Value>::value, Value, typename Traits::ValueTraits>::IsAlive(info, self.value); } static void Trace(blink::Visitor* visitor, const KeyValuePair<Key, Value>& self) { EphemeronHelper helper(&self.key, &self.value); // The following passes on kNoWeakHandling for tracing value as the value // callback is only invoked to keep value alive iff key is alive, following // ephemeron semantics. visitor->TraceEphemeron( *helper.key, helper.value, blink::TraceCollectionIfEnabled< kNoWeakHandling, typename EphemeronHelper::ValueType, typename EphemeronHelper::ValueTraits>::Trace); } }; } // namespace WTF #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_HEAP_COLLECTION_SUPPORT_HEAP_HASH_TABLE_BACKING_H_
endlessm/chromium-browser
third_party/blink/renderer/platform/heap/collection_support/heap_hash_table_backing.h
C
bsd-3-clause
13,490
/** * File: MediaIntervalImpl.java Copyright (c) 2010 phyokyaw 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 */ package synergyviewcore.annotations.ui; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import synergyviewcore.annotations.model.Annotation; import synergyviewcore.annotations.model.AnnotationSetNode; import synergyviewcore.annotations.model.IntervalAnnotation; import synergyviewcore.annotations.ui.events.CaptionChangeEvent; import synergyviewcore.annotations.ui.events.ICaptionChangeListener; import synergyviewcore.annotations.ui.events.ICaptionChangeListener.CaptionPublishState; import synergyviewcore.util.DateTimeHelper; import de.jaret.util.date.IntervalImpl; import de.jaret.util.date.JaretDate; import de.jaret.util.ui.timebars.TimeBarMarker; import de.jaret.util.ui.timebars.TimeBarMarkerImpl; import de.jaret.util.ui.timebars.TimeBarMarkerListener; /** * The Class AnnotationIntervalImpl. * * @author phyokyaw */ public class AnnotationIntervalImpl extends IntervalImpl { /** The Constant PROP_LABLE. */ public static final String PROP_LABLE = "label"; /** The annotation. */ private IntervalAnnotation annotation; /** The caption change listeners. */ private List<ICaptionChangeListener> captionChangeListeners = new ArrayList<ICaptionChangeListener>(); /** The caption state. */ private CaptionPublishState captionState = CaptionPublishState.UNSET; /** The label. */ protected String label; /** The marker. */ private TimeBarMarkerImpl marker; /** The owner row. */ private SubjectRowModel ownerRow; /** The time bar marker listener. */ private TimeBarMarkerListener timeBarMarkerListener; /** * Instantiates a new annotation interval impl. */ @SuppressWarnings("unused") private AnnotationIntervalImpl() { super(); } /** * Instantiates a new annotation interval impl. * * @param annotationSetNode * the annotation set node * @param begin * the begin * @param end * the end * @param annotationValue * the annotation value * @param marker * the marker * @param owner * the owner */ public AnnotationIntervalImpl(AnnotationSetNode annotationSetNode, JaretDate begin, JaretDate end, IntervalAnnotation annotationValue, TimeBarMarkerImpl marker, SubjectRowModel owner) { super(begin, end); ownerRow = owner; this.annotation = annotationValue; this.marker = marker; timeBarMarkerListener = new TimeBarMarkerListener() { public void markerDescriptionChanged(TimeBarMarker arg0, String arg1, String arg2) { // } public void markerMoved(TimeBarMarker arg0, JaretDate arg1, JaretDate arg2) { if (isMarkerInrange()) { if (captionState == CaptionPublishState.UNSET) { captionState = CaptionPublishState.SET; for (ICaptionChangeListener captinListener : captionChangeListeners) { CaptionChangeEvent event = new CaptionChangeEvent(AnnotationIntervalImpl.this, annotation.getText(), captionState); captinListener.captionChange(AnnotationIntervalImpl.this, event); } } } else { if (captionState == CaptionPublishState.SET) { captionState = CaptionPublishState.UNSET; for (ICaptionChangeListener captinListener : captionChangeListeners) { CaptionChangeEvent event = new CaptionChangeEvent(AnnotationIntervalImpl.this, annotation.getText(), captionState); captinListener.captionChange(AnnotationIntervalImpl.this, event); } } } } }; this.marker.addTimeBarMarkerListener(timeBarMarkerListener); annotation.addPropertyChangeListener(Annotation.PROP_TEXT, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent arg0) { AnnotationIntervalImpl.this.setLabel((String) arg0.getNewValue()); } }); } /** * Adds the caption change listener. * * @param captionChangeListener * the caption change listener */ public void addCaptionChangeListener(ICaptionChangeListener captionChangeListener) { captionChangeListeners.add(captionChangeListener); } /** * Dispose. */ public void dispose() { if (this.marker != null) { this.marker.remTimeBarMarkerListener(timeBarMarkerListener); } } /** * Gets the annotation. * * @return the analysisCaption */ public Annotation getAnnotation() { return annotation; } /** * Gets the label. * * @return the label */ public String getLabel() { return this.label; } /** * Gets the owner. * * @return the owner */ public SubjectRowModel getOwner() { return ownerRow; } /** * Checks if is marker inrange. * * @return true, if is marker inrange */ public boolean isMarkerInrange() { if ((marker.getDate().compareTo(this.getBegin()) >= 0) && (marker.getDate().compareTo(this.getEnd()) < 0)) { return true; } else { return false; } } /** * Removes the caption change listener. * * @param captionChangeListener * the caption change listener */ public void removeCaptionChangeListener(ICaptionChangeListener captionChangeListener) { captionChangeListeners.remove(captionChangeListener); } /* * (non-Javadoc) * * @see de.jaret.util.date.IntervalImpl#setBegin(de.jaret.util.date.JaretDate) */ @Override public void setBegin(JaretDate begin) { super.setBegin(begin); annotation.setHr(this.getBegin().getHours()); annotation.setMi(this.getBegin().getMinutes()); annotation.setSec(this.getBegin().getSeconds()); annotation.setMilliSec(this.getBegin().getMillis()); annotation.setStartTime(DateTimeHelper.getMilliFromJaretDate(this.getBegin())); } /* * (non-Javadoc) * * @see de.jaret.util.date.IntervalImpl#setEnd(de.jaret.util.date.JaretDate) */ @Override public void setEnd(JaretDate end) { super.setEnd(end); annotation.setDuration((int) end.diffMilliSeconds(this.getBegin())); } /** * Sets the label. * * @param label * the new label */ public void setLabel(String label) { this.firePropertyChange(AnnotationIntervalImpl.PROP_LABLE, this.label, this.label = label); } /* * (non-Javadoc) * * @see de.jaret.util.date.IntervalImpl#toString() */ @Override public String toString() { return label != null ? label : super.toString(); } }
synergynet/synergyview
synergyview-core/src/synergyviewcore/annotations/ui/AnnotationIntervalImpl.java
Java
bsd-3-clause
7,362
# -*- coding: utf-8 -*- # # Copyright (c) 2016 - 2022 -- Lars Heuer # All rights reserved. # # License: BSD License # """\ Tests if the PNG serializer does not add more colors than needed. See also issue <https://github.com/heuer/segno/issues/62> """ from __future__ import unicode_literals, absolute_import import io import pytest import segno def test_plte(): qr = segno.make_qr('test') assert qr.version < 7 dark = 'red' buff_1 = io.BytesIO() buff_2 = io.BytesIO() qr.save(buff_1, kind='png', dark=dark, finder_dark=dark, version_dark='green') qr.save(buff_2, kind='png', dark=dark) assert buff_1.getvalue() == buff_2.getvalue() def test_plte2(): qr = segno.make_qr('test') assert qr.version < 7 dark = 'red' buff_1 = io.BytesIO() buff_2 = io.BytesIO() qr.save(buff_1, kind='png', dark=dark, finder_dark=dark, version_dark='green') qr.save(buff_2, kind='png', dark=dark) assert buff_1.getvalue() == buff_2.getvalue() def test_plte3(): qr = segno.make_qr('test') assert qr.version < 7 dark = 'red' buff_1 = io.BytesIO() buff_2 = io.BytesIO() qr.save(buff_1, kind='png', dark=dark, finder_dark=dark, version_dark='green') qr.save(buff_2, kind='png', dark=dark) assert buff_1.getvalue() == buff_2.getvalue() def test_plte_micro(): qr = segno.make_micro('RAIN') dark = 'red' buff_1 = io.BytesIO() buff_2 = io.BytesIO() qr.save(buff_1, kind='png', dark=dark, finder_dark=dark, alignment_dark='green') qr.save(buff_2, kind='png', dark=dark) assert buff_1.getvalue() == buff_2.getvalue() def test_plte_micro2(): qr = segno.make_micro('RAIN') dark = 'red' buff_1 = io.BytesIO() buff_2 = io.BytesIO() qr.save(buff_1, kind='png', dark=dark, finder_dark=dark, dark_module='green') qr.save(buff_2, kind='png', dark=dark) assert buff_1.getvalue() == buff_2.getvalue() if __name__ == '__main__': pytest.main([__file__])
heuer/segno
tests/test_png_plte.py
Python
bsd-3-clause
1,978
<?php /** * Set error reporting and display errors settings. You will want to change these when in production. */ error_reporting(-1); ini_set('display_errors', 1); /** * Website document root */ define('DOCROOT', __DIR__.DIRECTORY_SEPARATOR); /** * Path to the application directory. */ define('APPPATH', realpath(__DIR__.'/../tonichelp/').DIRECTORY_SEPARATOR); /** * Path to the default packages directory. */ define('PKGPATH', realpath(__DIR__.'/../fuel/packages/').DIRECTORY_SEPARATOR); /** * The path to the framework core. */ define('COREPATH', realpath(__DIR__.'/../fuel/core/').DIRECTORY_SEPARATOR); // Get the start time and memory for use later defined('FUEL_START_TIME') or define('FUEL_START_TIME', microtime(true)); defined('FUEL_START_MEM') or define('FUEL_START_MEM', memory_get_usage()); // Boot the app require APPPATH.'bootstrap.php'; // Generate the request, execute it and send the output. try { $response = Request::forge()->execute()->response(); } catch (HttpNotFoundException $e) { $route = array_key_exists('_404_', Router::$routes) ? Router::$routes['_404_']->translation : Config::get('routes._404_'); if ($route) { $response = Request::forge($route)->execute()->response(); } else { throw $e; } } // This will add the execution time and memory usage to the output. // Comment this out if you don't use it. $bm = Profiler::app_total(); $response->body( str_replace( array('{exec_time}', '{mem_usage}'), array(round($bm[0], 4), round($bm[1] / pow(1024, 2), 3)), $response->body() ) ); $response->send(true); // Fire off the shutdown event Event::shutdown();
DregondRahl/tonichelp
src/public/index.php
PHP
bsd-3-clause
1,625
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_TESTING_FAKE_BLOB_REGISTRY_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_TESTING_FAKE_BLOB_REGISTRY_H_ #include "third_party/blink/public/mojom/blob/blob_registry.mojom-blink.h" namespace blink { // Mocked BlobRegistry implementation for testing. Simply keeps track of all // blob registrations and blob lookup requests, binding each blob request to a // FakeBlob instance with the correct uuid. class FakeBlobRegistry : public mojom::blink::BlobRegistry { public: void Register(mojo::PendingReceiver<mojom::blink::Blob>, const String& uuid, const String& content_type, const String& content_disposition, Vector<mojom::blink::DataElementPtr> elements, RegisterCallback) override; void RegisterFromStream( const String& content_type, const String& content_disposition, uint64_t expected_length, mojo::ScopedDataPipeConsumerHandle, mojo::PendingAssociatedRemote<mojom::blink::ProgressClient>, RegisterFromStreamCallback) override; void GetBlobFromUUID(mojo::PendingReceiver<mojom::blink::Blob>, const String& uuid, GetBlobFromUUIDCallback) override; void URLStoreForOrigin( const scoped_refptr<const SecurityOrigin>&, mojo::PendingAssociatedReceiver<mojom::blink::BlobURLStore>) override; struct Registration { String uuid; String content_type; String content_disposition; Vector<mojom::blink::DataElementPtr> elements; }; Vector<Registration> registrations; struct OwnedReceiver { String uuid; }; Vector<OwnedReceiver> owned_receivers; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_TESTING_FAKE_BLOB_REGISTRY_H_
endlessm/chromium-browser
third_party/blink/renderer/platform/blob/testing/fake_blob_registry.h
C
bsd-3-clause
1,988
/// HEADER #include <csapex/view/widgets/port.h> /// COMPONENT #include <csapex/command/dispatcher.h> #include <csapex/command/add_connection.h> #include <csapex/command/command_factory.h> #include <csapex/msg/input.h> #include <csapex/msg/static_output.h> #include <csapex/model/connection.h> #include <csapex/view/designer/graph_view.h> #include <csapex/view/widgets/message_preview_widget.h> #include <csapex/view/designer/designer_scene.h> #include <csapex/signal/slot.h> #include <csapex/csapex_mime.h> /// SYSTEM #include <sstream> #include <iostream> #include <stdexcept> #include <QDrag> #include <QWidget> #include <QDragEnterEvent> #include <QMimeData> #include <QHelpEvent> #include <QEvent> #include <QInputDialog> #include <QApplication> #include <QTimer> using namespace csapex; Q_DECLARE_METATYPE(ConnectorPtr) Port::Port(QWidget* parent) : QFrame(parent), refresh_style_sheet_(false), minimized_(false), flipped_(false), hovered_(false), buttons_down_(0) { setFlipped(flipped_); setFocusPolicy(Qt::NoFocus); setAcceptDrops(true); setContextMenuPolicy(Qt::PreventContextMenu); setMinimizedSize(minimized_); setEnabled(true); double_click_timer_ = new QTimer(this); QObject::connect(double_click_timer_, &QTimer::timeout, this, &Port::mouseClickEvent); double_click_timer_->setInterval(200); } Port::Port(ConnectorPtr adaptee, QWidget* parent) : Port(parent) { adaptee_ = adaptee; createToolTip(); connections_.push_back(adaptee_->enabled_changed.connect([this](bool e) { setEnabledFlag(e); })); setProperty("optional", adaptee_->isOptional()); setProperty("type", QString::fromStdString(port_type::name(adaptee_->getConnectorType()))); } Port::~Port() { for (auto& c : connections_) { c.disconnect(); } } bool Port::event(QEvent* e) { if (e->type() == QEvent::ToolTip) { createToolTip(); } return QWidget::event(e); } bool Port::isOutput() const { if (!adaptee_) { return false; } return adaptee_->isOutput(); } bool Port::isInput() const { if (!adaptee_) { return false; } return adaptee_->isInput(); } ConnectorPtr Port::getAdaptee() const { return adaptee_; } void Port::paintEvent(QPaintEvent* e) { if (refresh_style_sheet_) { refresh_style_sheet_ = false; setStyleSheet(styleSheet()); } QFrame::paintEvent(e); } void Port::refreshStylesheet() { refresh_style_sheet_ = true; } void Port::setMinimizedSize(bool mini) { minimized_ = mini; if (mini) { setFixedSize(8, 8); } else { setFixedSize(16, 16); } } bool Port::isMinimizedSize() const { return minimized_; } void Port::setFlipped(bool flipped) { flipped_ = flipped; } bool Port::isFlipped() const { return flipped_; } bool Port::isHovered() const { return hovered_; } void Port::setEnabledFlag(bool processing_enabled) { bool enabled = processing_enabled; if (SlotPtr slot = std::dynamic_pointer_cast<Slot>(adaptee_)) { if (slot->isActive()) { enabled = true; } } setPortProperty("enabled", enabled); setPortProperty("disabled", !enabled); setEnabled(true); refreshStylesheet(); } void Port::setPortProperty(const std::string& name, bool b) { setProperty(name.c_str(), b); } void Port::createToolTip() { if (!adaptee_) { return; } std::string tooltip = adaptee_->makeStatusString(); setToolTip(QString::fromStdString(tooltip)); } void Port::startDrag() { if (!adaptee_) { return; } Q_EMIT mouseOut(this); bool left = (buttons_down_ & Qt::LeftButton) != 0; bool right = (buttons_down_ & Qt::RightButton) != 0; bool full_input = (adaptee_->isInput() && adaptee_->isConnected()); bool create = left && !full_input; bool move = (right && adaptee_->isConnected()) || (left && full_input); if (create || move) { QDrag* drag = new QDrag(this); QMimeData* mimeData = new QMimeData; if (move) { mimeData->setData(QString::fromStdString(csapex::mime::connection_move), QByteArray()); mimeData->setProperty("Connector", qVariantFromValue(adaptee_)); drag->setMimeData(mimeData); drag->exec(); } else { mimeData->setData(QString::fromStdString(csapex::mime::connection_create), QByteArray()); mimeData->setProperty("Connector", qVariantFromValue(adaptee_)); drag->setMimeData(mimeData); drag->exec(); } // adaptee_->connection_added_to(adaptee_); buttons_down_ = Qt::NoButton; } } void Port::mouseMoveEvent(QMouseEvent* e) { if (buttons_down_ == Qt::NoButton) { return; } startDrag(); e->accept(); } void Port::mouseDoubleClickEvent(QMouseEvent* e) { if (!adaptee_) { return; } e->accept(); double_click_timer_->stop(); bool ok = false; QString label = QInputDialog::getText(QApplication::activeWindow(), "Rename Port", "Enter a new name", QLineEdit::Normal, QString::fromStdString(adaptee_->getLabel()), &ok); if (ok) { changePortRequest(label); } buttons_down_ = e->buttons(); } void Port::mouseClickEvent() { startDrag(); buttons_down_ = Qt::NoButton; } void Port::mouseReleaseEvent(QMouseEvent* e) { double_click_timer_->setSingleShot(true); double_click_timer_->start(); if (e->button() == Qt::MiddleButton) { Q_EMIT removeConnectionsRequest(); } e->accept(); } void Port::dragEnterEvent(QDragEnterEvent* e) { if (e->mimeData()->hasFormat(QString::fromStdString(csapex::mime::connection_create))) { ConnectorPtr from = e->mimeData()->property("Connector").value<ConnectorPtr>(); if (from == adaptee_) { return; } bool compatible = Connection::isCompatibleWith(from.get(), adaptee_.get()) && Connection::isCompatibleWith(adaptee_.get(), from.get()); bool shift = Qt::ShiftModifier & QApplication::keyboardModifiers(); if (compatible || shift) { addConnectionPreview(from); e->acceptProposedAction(); } } else if (e->mimeData()->hasFormat(QString::fromStdString(csapex::mime::connection_move))) { ConnectorPtr from = e->mimeData()->property("Connector").value<ConnectorPtr>(); if (Connection::targetsCanBeMovedTo(from.get(), adaptee_.get())) { moveConnectionPreview(from); e->acceptProposedAction(); } } } void Port::dragMoveEvent(QDragMoveEvent* e) { if (e->mimeData()->hasFormat(QString::fromStdString(csapex::mime::connection_create))) { e->acceptProposedAction(); } else if (e->mimeData()->hasFormat(QString::fromStdString(csapex::mime::connection_move))) { e->acceptProposedAction(); } } void Port::dropEvent(QDropEvent* e) { if (e->mimeData()->hasFormat(QString::fromStdString(csapex::mime::connection_create))) { ConnectorPtr from = e->mimeData()->property("Connector").value<ConnectorPtr>(); if (from && from != adaptee_) { addConnectionRequest(from); } } else if (e->mimeData()->hasFormat(QString::fromStdString(csapex::mime::connection_move))) { ConnectorPtr from = e->mimeData()->property("Connector").value<ConnectorPtr>(); if (from) { moveConnectionRequest(from); e->setDropAction(Qt::MoveAction); } } } void Port::enterEvent(QEvent* /*e*/) { hovered_ = true; Q_EMIT mouseOver(this); } void Port::leaveEvent(QEvent* /*e*/) { hovered_ = false; Q_EMIT mouseOut(this); } void Port::mousePressEvent(QMouseEvent* e) { buttons_down_ = e->buttons(); } /// MOC #include "../../../include/csapex/view/widgets/moc_port.cpp"
cogsys-tuebingen/csapex
src/csapex_qt/src/view/widgets/port.cpp
C++
bsd-3-clause
7,877
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="Docutils 0.6: http://docutils.sourceforge.net/" /> <title>PyModel: Model-based testing in Python</title> <style type="text/css"> /* :Author: David Goodger (goodger@python.org) :Id: $Id: html4css1.css 5951 2009-05-18 18:03:10Z milde $ :Copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to customize this style sheet. */ /* used to remove borders from tables and images */ .borderless, table.borderless td, table.borderless th { border: 0 } table.borderless td, table.borderless th { /* Override padding for "table.docutils td" with "! important". The right padding separates the table cells. */ padding: 0 0.5em 0 0 ! important } .first { /* Override more specific margin styles with "! important". */ margin-top: 0 ! important } .last, .with-subtitle { margin-bottom: 0 ! important } .hidden { display: none } a.toc-backref { text-decoration: none ; color: black } blockquote.epigraph { margin: 2em 5em ; } dl.docutils dd { margin-bottom: 0.5em } /* Uncomment (and remove this text!) to get bold-faced definition list terms dl.docutils dt { font-weight: bold } */ div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.admonition, div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.admonition p.admonition-title, div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } /* Uncomment (and remove this text!) to get reduced vertical space in compound paragraphs. div.compound .compound-first, div.compound .compound-middle { margin-bottom: 0.5em } div.compound .compound-last, div.compound .compound-middle { margin-top: 0.5em } */ div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em ; margin-right: 2em } div.footer, div.header { clear: both; font-size: smaller } div.line-block { display: block ; margin-top: 1em ; margin-bottom: 1em } div.line-block div.line-block { margin-top: 0 ; margin-bottom: 0 ; margin-left: 1.5em } div.sidebar { margin: 0 0 0.5em 1em ; border: medium outset ; padding: 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.section-subtitle, h2.section-subtitle, h3.section-subtitle, h4.section-subtitle, h5.section-subtitle, h6.section-subtitle { margin-top: 0.4em } h1.title { text-align: center } h2.subtitle { text-align: center } hr.docutils { width: 75% } img.align-left, .figure.align-left{ clear: left ; float: left ; margin-right: 1em } img.align-right, .figure.align-right { clear: right ; float: right ; margin-left: 1em } .align-left { text-align: left } .align-center { clear: both ; text-align: center } .align-right { text-align: right } /* reset inner alignment in figures */ div.align-right { text-align: left } /* div.align-center * { */ /* text-align: left } */ ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font: inherit } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.pre { white-space: pre } span.problematic { color: red } span.section-subtitle { /* font-size relative to parent (h1..h6 element) */ font-size: 80% } table.citation { border-left: solid 1px gray; margin-left: 1px } table.docinfo { margin: 2em 4em } table.docutils { margin-top: 0.5em ; margin-bottom: 0.5em } table.footnote { border-left: solid 1px black; margin-left: 1px } table.docutils td, table.docutils th, table.docinfo td, table.docinfo th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } table.docutils th.field-name, table.docinfo th.docinfo-name { font-weight: bold ; text-align: left ; white-space: nowrap ; padding-left: 0 } h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { font-size: 100% } ul.auto-toc { list-style-type: none } </style> </head> <body> <div class="document" id="pymodel-model-based-testing-in-python"> <h1 class="title">PyModel: Model-based testing in Python</h1> <p><strong>PyModel</strong> is an open-source model-based testing framework in Python.</p> <p>In unit testing, the programmer codes the test cases, and also codes assertions that check whether each test case passed. In model-based testing, the programmer codes a &quot;model&quot; that generates as many test cases as desired and also acts as the oracle that checks the cases.</p> <p>Model-based testing is recommended where so many test cases are needed that it is not feasible to code them all by hand. This need arises when testing behaviors that exhibit history-dependence and nondeterminism, so that many variations (data values, interleavings, etc.) should be tested for each scenario (or use case). Examples include communication protocols, web applications, control systems, and user interfaces.</p> <p>PyModel supports on-the-fly testing, which can generate indefinitely long nonrepeating tests as the test run executes. PyModel can focus test cases on scenarios of interest by composition, a versatile technique that combines models by synchronizing shared actions and interleaving unshared actions. PyModel can guide test coverage according to programmable strategies coded by the programmer.</p> <p>PyModel provides three programs:</p> <blockquote> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field"><th class="field-name">pma.py:</th><td class="field-body">pymodel analyzer, generates a finite state machine (FSM) and computes properties by exploring a model program, FSM, test suite, or a product of these.</td> </tr> <tr class="field"><th class="field-name">pmg.py:</th><td class="field-body">pymodel graphics, generates a file of graphic commands from an FSM.</td> </tr> <tr class="field"><th class="field-name">pmt.py:</th><td class="field-body">pymodel tester, displays traces, generates tests offline, executes offline tests, or generates and executes tests on-the-fly.</td> </tr> </tbody> </table> </blockquote> <p>Use pma and pmg to visualize and preview the behavior of pmt. Every path through the graph created by pma (and drawn by pmg) is a trace (test run) that may be generated by pmt, when pma and pmt are invoked with the same arguments.</p> <p>PyModel requires Python 2.6 (because it uses <tt class="docutils literal">itertools.product</tt>).</p> <p>PyModel is influenced by NModel, but is not a translation or re-implementation.</p> </div> </body> </html>
nfredrik/pyModelStuff
README.html
HTML
bsd-3-clause
8,903
<dom-module id="data-login"> <style> :host{ @apply(--layout-center-center); @apply(--layout-vertical); } paper-material{ padding: 15px 30px; background-color: #FFF; height: 350px; width: 400px; } #logo{ width: 200px; height: 200px; margin-bottom: 30px; } .submit{ margin-top: 1em; } </style> <template> <iron-a11y-keys id="enter-key-submit" keys="enter" target="[[target]]" on-keys-pressed="submitForm"> </iron-a11y-keys> <iron-image id="logo" src="../images/mps-logo-no-text.png" preload sizing="contain" class=""></iron-image> <paper-material class="layout center-center" elevation="1"> <h1>Login</h1> <paper-toast id="login-info" text=""></paper-toast> <form is="iron-form" id="login-form" method="post" action="/login" on-iron-form-response="onResponse" on-iron-form-error="onError"> <paper-input label="User" name="email" required></paper-input> <paper-input type="password" name="password" label="Password" required></paper-input> <div class="submit layout vertical"> <paper-button raised on-click="submitForm" class="layout end">Login</paper-button> </div> <p class="small">Doesn't have an account? <a href="/appreg"> Register</a> first</p> </form> </paper-material> </template> </dom-module> <script> (function() { Polymer({ is:"data-login", properties:{ target: { type: Object, value: function() { return this.$$('#login-form'); } } }, submitForm:function(){ this.$$('#login-form').submit(); }, onResponse:function(ev){ if(ev.detail.status==='ok'){ var dataentry=Polymer.dom(document).querySelector('data-entry'); dataentry.loadForm(); page.redirect('/'); } else{ console.log(ev.detail.error); var info=this.$$('#login-info'); if(ev.detail.error==='no user') info.text="No user found, please register first!"; else if(ev.detail.error.error==='invalid password') info.text="Invalid password, please check your login"; info.show(); } }, onError:function(){ var info=this.$$('#login-info'); info.text="Something problem with login, please try again later"; info.show(); } }); })(); </script>
MyanmarAPI/data-entry-app
app/elements/data-login.html
HTML
bsd-3-clause
2,264
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_enforcer.h" #include <memory> #include "base/feature_list.h" #include "base/stl_util.h" #include "base/values.h" #include "chrome/browser/chromeos/child_accounts/time_limits/app_time_controller.h" #include "chrome/browser/chromeos/child_accounts/time_limits/app_time_limits_whitelist_policy_wrapper.h" #include "chrome/browser/chromeos/child_accounts/time_limits/app_types.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/common/chrome_features.h" #include "components/url_matcher/url_matcher.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/reload_type.h" #include "content/public/browser/web_contents.h" namespace chromeos { namespace app_time { // static bool WebTimeLimitEnforcer::IsEnabled() { return base::FeatureList::IsEnabled(features::kWebTimeLimits); } WebTimeLimitEnforcer::WebTimeLimitEnforcer( AppTimeController* app_time_controller) : app_time_controller_(app_time_controller) {} WebTimeLimitEnforcer::~WebTimeLimitEnforcer() = default; void WebTimeLimitEnforcer::OnWebTimeLimitReached(base::TimeDelta time_limit) { if (chrome_blocked_) return; time_limit_ = time_limit; chrome_blocked_ = true; ReloadAllWebContents(); } void WebTimeLimitEnforcer::OnWebTimeLimitEnded() { if (!chrome_blocked_) return; time_limit_ = base::TimeDelta(); chrome_blocked_ = false; ReloadAllWebContents(); } void WebTimeLimitEnforcer::OnTimeLimitWhitelistChanged( const AppTimeLimitsWhitelistPolicyWrapper& wrapper) { std::vector<std::string> whitelisted_urls = wrapper.GetWhitelistURLList(); // clean up |url_matcher_|; url_matcher_ = std::make_unique<url_matcher::URLMatcher>(); url_matcher::URLMatcherConditionSet::Vector condition_set_vector; auto* condition_factory = url_matcher_->condition_factory(); int id = 0; for (const auto& url : whitelisted_urls) { url_matcher::URLMatcherCondition condition = condition_factory->CreateURLMatchesCondition(url); url_matcher::URLMatcherConditionSet::Conditions conditions; conditions.insert(condition); condition_set_vector.push_back( base::MakeRefCounted<url_matcher::URLMatcherConditionSet>(id++, conditions)); } url_matcher_->AddConditionSets(condition_set_vector); // Filters have been updated. Now reload all WebContents. ReloadAllWebContents(); } bool WebTimeLimitEnforcer::IsURLWhitelisted(const GURL& url) const { // Block everything if |scheme_filter_| and |domain_matcher_| are not // instantiated yet. if (!url_matcher_) return false; if (web_app::IsValidExtensionUrl(url)) return app_time_controller_->IsExtensionWhitelisted(url.host()); auto matching_set_size = url_matcher_->MatchURL(url).size(); return matching_set_size > 0; } void WebTimeLimitEnforcer::ReloadAllWebContents() { auto* browser_list = BrowserList::GetInstance(); for (auto* browser : *browser_list) { auto* tab_strip_model = browser->tab_strip_model(); for (int i = 0; i < tab_strip_model->count(); i++) { auto* web_content = tab_strip_model->GetWebContentsAt(i); web_content->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ false); } } } } // namespace app_time } // namespace chromeos
endlessm/chromium-browser
chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_enforcer.cc
C++
bsd-3-clause
3,772
# MongoObject - PHP objects stored in Mongo # [![Build Status](https://travis-ci.org/dintel/mongo-object.svg)](https://travis-ci.org/dintel/mongo-object) MongoObject simplifies storing objects in Mongo database. Currently it provides following features: - Object class that can be used as base class for all your classes that has to be saved into Mongo - Mapper class that simplifies fetching of objects from Mongo - MapperService class that can be registered as Zend Framework 2 service factory for Mapper class.
dintel/mongo-object
README.md
Markdown
bsd-3-clause
520
<?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $searchModel app\models\GameSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Games'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="game-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Create Game', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ //['class' => 'yii\grid\SerialColumn'], 'gameNum', //'roundHash', 'randNum', 'winningTicket', 'winningPlayer', 'date', // 'user', //['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
Doggi/csgofast_rest
views/site/game.php
PHP
bsd-3-clause
944
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.4.4.12_A4_T1; * @section: 15.4.4.12, 8.6.2.1; * @assertion: [[Get]] from not an inherited property; * @description: [[Prototype]] of Array instance is Array.prototype, [[Prototype] of Array.prototype is Object.prototype; */ Array.prototype[1] = -1; var x = [0,1]; var arr = x.splice(1,1); //CHECK#1 if (arr.length !== 1) { $ERROR('#1: Array.prototype[1] = -1; x = [0,1]; var arr = x.splice(1,1); arr.length === 1. Actual: ' + (arr.length)); } //CHECK#2 if (arr[0] !== 1) { $ERROR('#2: Array.prototype[1] = -1; x = [0,1]; var arr = x.splice(1,1); arr[0] === 1. Actual: ' + (arr[0])); } //CHECK#3 if (arr[1] !== -1) { $ERROR('#3: Array.prototype[1] = -1; x = [0,1]; var arr = x.splice(1,1); arr[1] === -1. Actual: ' + (arr[1])); } //CHECK#4 if (x.length !== 1) { $ERROR('#4: Array.prototype[1] = -1; x = [0,1]; var arr = x.splice(1,1); x.length === 1. Actual: ' + (x.length)); } //CHECK#5 if (x[0] !== 0) { $ERROR('#5: Array.prototype[1] = -1; x = [0,1]; var arr = x.splice(1,1); x[0] === 0. Actual: ' + (x[0])); } //CHECK#6 if (x[1] !== -1) { $ERROR('#6: Array.prototype[1] = -1; x = [0,1]; var arr = x.splice(1,1); x[1] === -1. Actual: ' + (x[1])); } Object.prototype[1] = -1; Object.prototype.length = 2; Object.prototype.splice = Array.prototype.splice; x = {0:0, 1:1}; var arr = x.splice(1,1); //CHECK#7 if (arr.length !== 1) { $ERROR('#7: Object.prototype[1] = -1; Object.prototype.length = 2; Object.prototype.splice = Array.prototype.splice; x = {0:0, 1:1}; var arr = x.splice(1,1); arr.length === 1. Actual: ' + (arr.length)); } //CHECK#8 if (arr[0] !== 1) { $ERROR('#8: Object.prototype[1] = -1; Object.prototype.length = 2; Object.prototype.splice = Array.prototype.splice; x = {0:0, 1:1}; var arr = x.splice(1,1); arr[0] === 1. Actual: ' + (arr[0])); } //CHECK#9 if (arr[1] !== -1) { $ERROR('#9: Object.prototype[1] = -1; Object.prototype.length = 2; Object.prototype.splice = Array.prototype.splice; x = {0:0, 1:1}; var arr = x.splice(1,1); arr[1] === -1. Actual: ' + (arr[1])); } //CHECK#10 if (x.length !== 1) { $ERROR('#10: Object.prototype[1] = -1; Object.prototype.length = 2; Object.prototype.splice = Array.prototype.splice; x = {0:0, 1:1}; var arr = x.splice(1,1); x.length === 1. Actual: ' + (x.length)); } //CHECK#11 if (x[0] !== 0) { $ERROR('#11: Object.prototype[1] = -1; Object.prototype.length = 2; Object.prototype.splice = Array.prototype.splice; x = {0:0, 1:1}; var arr = x.splice(1,1); x[0] === 0. Actual: ' + (x[0])); } //CHECK#12 if (x[1] !== -1) { $ERROR('#12: Object.prototype[1] = -1; Object.prototype.length = 2; Object.prototype.splice = Array.prototype.splice; x = {0:0, 1:1}; var arr = x.splice(1,1); x[1] === -1. Actual: ' + (x[1])); }
luboid/ES5.Script
TestScripts/sputniktests/tests/Conformance/15_Native_ECMA_Script_Objects/15.4_Array_Objects/15.4.4_Properties_of_the_Array_Prototype_Object/15.4.4.12_Array_prototype_splice/S15.4.4.12_A4_T1.js
JavaScript
bsd-3-clause
2,940
# -*- coding: utf-8 -*- from __future__ import unicode_literals from cms.models import Page from cms.utils.i18n import get_language_list from django.db import migrations, models def forwards(apps, schema_editor): BlogConfig = apps.get_model('djangocms_blog', 'BlogConfig') BlogConfigTranslation = apps.get_model('djangocms_blog', 'BlogConfigTranslation') Post = apps.get_model('djangocms_blog', 'Post') BlogCategory = apps.get_model('djangocms_blog', 'BlogCategory') GenericBlogPlugin = apps.get_model('djangocms_blog', 'GenericBlogPlugin') LatestPostsPlugin = apps.get_model('djangocms_blog', 'LatestPostsPlugin') AuthorEntriesPlugin = apps.get_model('djangocms_blog', 'AuthorEntriesPlugin') config = None for page in Page.objects.drafts().filter(application_urls='BlogApp'): config, created = BlogConfig.objects.get_or_create(namespace=page.application_namespace) if not BlogConfigTranslation.objects.exists(): for lang in get_language_list(): title = page.get_title(lang) translation = BlogConfigTranslation.objects.create(language_code=lang, master_id=config.pk, app_title=title) if config: for model in (Post, BlogCategory, GenericBlogPlugin, LatestPostsPlugin, AuthorEntriesPlugin): for item in model.objects.filter(app_config__isnull=True): item.app_config = config item.save() def backwards(apps, schema_editor): # No need for backward data migration pass class Migration(migrations.Migration): dependencies = [ ('cms', '0004_auto_20140924_1038'), ('djangocms_blog', '0013_auto_20160201_2235'), ] operations = [ migrations.RunPython(forwards, backwards), ]
skirsdeda/djangocms-blog
djangocms_blog/migrations/0014_auto_20160215_1331.py
Python
bsd-3-clause
1,773
function FileData_Pairs(x) { x.t("managing","sample"); x.t("findings","vitro"); x.t("right","finish"); x.t("files","wish"); x.t("files","continue"); x.t("files","click"); x.t("files","consisting"); x.t("wish","adding"); x.t("description","enter"); x.t("once","click"); x.t("upload","button"); x.t("derived","data"); x.t("field","select"); x.t("sample","click"); x.t("sample","characterizations"); x.t("type","(required)"); x.t("close","window"); x.t("form","supporting"); x.t("form","already"); x.t("extend","page"); x.t("keywords","associate"); x.t("listed","point"); x.t("new","entry"); x.t("access","selected"); x.t("document","located"); x.t("document","graph"); x.t("file","managing"); x.t("file","description"); x.t("file","type"); x.t("file","extend"); x.t("file","form"); x.t("file","add"); x.t("file","url"); x.t("file","added"); x.t("file","title"); x.t("file","specifying"); x.t("file","adding"); x.t("entering","data"); x.t("add","files"); x.t("add","results"); x.t("add","characterization"); x.t("add","continue"); x.t("add","corresponding"); x.t("group","(s)"); x.t("granted","access"); x.t("results","form"); x.t("entry","enclosed"); x.t("entry","brackets"); x.t("entry","temporary"); x.t("entry","persisted"); x.t("images","select"); x.t("browse","button"); x.t("characterization","files"); x.t("characterization","describing"); x.t("characterization","follow"); x.t("characterization","adding"); x.t("supporting","documentation"); x.t("navigate","report"); x.t("url","document"); x.t("url","button"); x.t("enclosed","new"); x.t("publication","associated"); x.t("cancel","close"); x.t("brackets","indicating"); x.t("brackets","disappear"); x.t("window","add"); x.t("window","click"); x.t("continue","process"); x.t("continue","adding"); x.t("segment","window"); x.t("selected","file"); x.t("point","entry"); x.t("select","upload"); x.t("select","group"); x.t("button","navigate"); x.t("button","click"); x.t("button","enter"); x.t("indicating","entry"); x.t("finding","segment"); x.t("report","publication"); x.t("describing","findings"); x.t("added","specify"); x.t("follow","steps"); x.t("steps","click"); x.t("located","file"); x.t("lower","right"); x.t("documentation","vitro"); x.t("click","add"); x.t("click","browse"); x.t("click","enter"); x.t("click","save"); x.t("click","submit"); x.t("click","[other]"); x.t("enter","file"); x.t("enter","url"); x.t("enter","additional"); x.t("enter","following"); x.t("enter","alternative"); x.t("(required)","keywords"); x.t("(required)","document"); x.t("include","visibility"); x.t("disappear","finding"); x.t("graphs","spreadsheet"); x.t("additional","information"); x.t("title","(required)"); x.t("already","include"); x.t("temporary","once"); x.t("process","described"); x.t("spreadsheet","file"); x.t("spreadsheet","images"); x.t("(s)","granted"); x.t("page","add"); x.t("consisting","graphs"); x.t("specifying","files"); x.t("characterizations","adding"); x.t("graph","image"); x.t("information","file"); x.t("data","add"); x.t("data","cancel"); x.t("data","conditions"); x.t("persisted","brackets"); x.t("image","spreadsheet"); x.t("save","lower"); x.t("submit","update"); x.t("selections","listed"); x.t("finish","entering"); x.t("described","adding"); x.t("vitro","characterization"); x.t("associate","file"); x.t("corresponding","file"); x.t("following","file"); x.t("adding","files"); x.t("adding","file"); x.t("adding","data"); x.t("adding","vitro"); x.t("alternative","selections"); x.t("associated","sample"); x.t("visibility","field"); x.t("[other]","enter"); x.t("conditions","derived"); x.t("update","entry"); x.t("specify","enter"); }
NCIP/cananolab
docs/webappOnlineHelp/wwhdata/js/search/pairs/pair76.js
JavaScript
bsd-3-clause
3,762
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/bookmarks/bookmark_editor_view.h" #include <set> #include <string> #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/bookmarks/bookmark_utils.h" #include "chrome/browser/ui/bookmarks/bookmark_utils_desktop.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/locale_settings.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" #include "components/constrained_window/constrained_window_views.h" #include "components/history/core/browser/history_service.h" #include "components/strings/grit/components_strings.h" #include "components/url_formatter/url_fixer.h" #include "components/user_prefs/user_prefs.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/event.h" #include "ui/views/background.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/label.h" #include "ui/views/controls/menu/menu_runner.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/tree/tree_view.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/widget/widget.h" #include "url/gurl.h" using bookmarks::BookmarkExpandedStateTracker; using bookmarks::BookmarkModel; using bookmarks::BookmarkNode; namespace { std::unique_ptr<views::LabelButton> CreateNewFolderButton( views::ButtonListener* listener, bool enabled) { auto new_folder_button = views::MdTextButton::Create( listener, l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NEW_FOLDER_BUTTON)); new_folder_button->SetEnabled(enabled); return new_folder_button; } } // namespace BookmarkEditorView::BookmarkEditorView( Profile* profile, const BookmarkNode* parent, const EditDetails& details, BookmarkEditor::Configuration configuration) : profile_(profile), parent_(parent), details_(details), bb_model_(BookmarkModelFactory::GetForBrowserContext(profile)), show_tree_(configuration == SHOW_TREE) { DCHECK(profile); DCHECK(bb_model_); DCHECK(bb_model_->client()->CanBeEditedByUser(parent)); SetButtonLabel(ui::DIALOG_BUTTON_OK, l10n_util::GetStringUTF16(IDS_SAVE)); if (show_tree_) { new_folder_button_ = SetExtraView(CreateNewFolderButton(this, bb_model_->loaded())); } set_margins(ChromeLayoutProvider::Get()->GetDialogInsetsForContentType( views::CONTROL, views::CONTROL)); Init(); chrome::RecordDialogCreation(chrome::DialogIdentifier::BOOKMARK_EDITOR); } BookmarkEditorView::~BookmarkEditorView() { // The tree model is deleted before the view. Reset the model otherwise the // tree will reference a deleted model. if (tree_view_) tree_view_->SetModel(nullptr); bb_model_->RemoveObserver(this); } bool BookmarkEditorView::IsDialogButtonEnabled(ui::DialogButton button) const { if (button == ui::DIALOG_BUTTON_OK) { if (!bb_model_->loaded()) return false; if (details_.GetNodeType() != BookmarkNode::FOLDER) return GetInputURL().is_valid(); } return true; } ui::ModalType BookmarkEditorView::GetModalType() const { return ui::MODAL_TYPE_WINDOW; } bool BookmarkEditorView::CanResize() const { return true; } bool BookmarkEditorView::ShouldShowCloseButton() const { return false; } base::string16 BookmarkEditorView::GetWindowTitle() const { return l10n_util::GetStringUTF16(details_.GetWindowTitleId()); } bool BookmarkEditorView::Accept() { if (!IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK)) { if (details_.GetNodeType() != BookmarkNode::FOLDER) { // The url is invalid, focus the url field. url_tf_->SelectAll(true); url_tf_->RequestFocus(); } return false; } // Otherwise save changes and close the dialog box. ApplyEdits(); return true; } gfx::Size BookmarkEditorView::CalculatePreferredSize() const { if (!show_tree_) return views::View::CalculatePreferredSize(); return gfx::Size(views::Widget::GetLocalizedContentsSize( IDS_EDITBOOKMARK_DIALOG_WIDTH_CHARS, IDS_EDITBOOKMARK_DIALOG_HEIGHT_LINES)); } void BookmarkEditorView::OnTreeViewSelectionChanged( views::TreeView* tree_view) { } bool BookmarkEditorView::CanEdit(views::TreeView* tree_view, ui::TreeModelNode* node) { // Only allow editting of children of the bookmark bar node and other node. EditorNode* bb_node = tree_model_->AsNode(node); return (bb_node->parent() && bb_node->parent()->parent()); } void BookmarkEditorView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { UserInputChanged(); } bool BookmarkEditorView::HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) { return false; } void BookmarkEditorView::GetAccessibleNodeData(ui::AXNodeData* node_data) { views::DialogDelegateView::GetAccessibleNodeData(node_data); node_data->SetName(l10n_util::GetStringUTF8(IDS_BOOKMARK_EDITOR_TITLE)); } void BookmarkEditorView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK_EQ(new_folder_button_, sender); NewFolder(); } bool BookmarkEditorView::IsCommandIdChecked(int command_id) const { return false; } bool BookmarkEditorView::IsCommandIdEnabled(int command_id) const { switch (command_id) { case IDS_EDIT: case IDS_DELETE: return !running_menu_for_root_; case IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM: return true; default: NOTREACHED(); return false; } } bool BookmarkEditorView::GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) const { return GetWidget()->GetAccelerator(command_id, accelerator); } void BookmarkEditorView::ExecuteCommand(int command_id, int event_flags) { DCHECK(tree_view_->GetSelectedNode()); if (command_id == IDS_EDIT) { tree_view_->StartEditing(tree_view_->GetSelectedNode()); } else if (command_id == IDS_DELETE) { EditorNode* node = tree_model_->AsNode(tree_view_->GetSelectedNode()); if (!node) return; if (node->value != 0) { const BookmarkNode* b_node = bookmarks::GetBookmarkNodeByID(bb_model_, node->value); if (!b_node->children().empty() && !chrome::ConfirmDeleteBookmarkNode(b_node, GetWidget()->GetNativeWindow())) { // The folder is not empty and the user didn't confirm. return; } deletes_.push_back(node->value); } tree_model_->Remove(node->parent(), node); } else { DCHECK_EQ(IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM, command_id); NewFolder(); } } void BookmarkEditorView::Show(gfx::NativeWindow parent) { constrained_window::CreateBrowserModalDialogViews(this, parent); UserInputChanged(); if (show_tree_ && bb_model_->loaded()) ExpandAndSelect(); GetWidget()->Show(); // Select all the text in the name Textfield. title_tf_->SelectAll(true); // Give focus to the name Textfield. title_tf_->RequestFocus(); } void BookmarkEditorView::ShowContextMenuForViewImpl( views::View* source, const gfx::Point& point, ui::MenuSourceType source_type) { DCHECK_EQ(tree_view_, source); if (!tree_view_->GetSelectedNode()) return; running_menu_for_root_ = (tree_model_->GetParent(tree_view_->GetSelectedNode()) == tree_model_->GetRoot()); context_menu_runner_ = std::make_unique<views::MenuRunner>( GetMenuModel(), views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU); context_menu_runner_->RunMenuAt(source->GetWidget()->GetTopLevelWidget(), nullptr, gfx::Rect(point, gfx::Size()), views::MenuAnchorPosition::kTopRight, source_type); } const char* BookmarkEditorView::GetClassName() const { return "BookmarkEditorView"; } void BookmarkEditorView::BookmarkNodeMoved(BookmarkModel* model, const BookmarkNode* old_parent, size_t old_index, const BookmarkNode* new_parent, size_t new_index) { Reset(); } void BookmarkEditorView::BookmarkNodeAdded(BookmarkModel* model, const BookmarkNode* parent, size_t index) { Reset(); } void BookmarkEditorView::BookmarkNodeRemoved( BookmarkModel* model, const BookmarkNode* parent, size_t index, const BookmarkNode* node, const std::set<GURL>& removed_urls) { if ((details_.type == EditDetails::EXISTING_NODE && details_.existing_node->HasAncestor(node)) || (parent_ && parent_->HasAncestor(node))) { // The node, or its parent was removed. Close the dialog. GetWidget()->Close(); } else { Reset(); } } void BookmarkEditorView::BookmarkAllUserNodesRemoved( BookmarkModel* model, const std::set<GURL>& removed_urls) { Reset(); } void BookmarkEditorView::BookmarkNodeChildrenReordered( BookmarkModel* model, const BookmarkNode* node) { Reset(); } void BookmarkEditorView::Init() { bb_model_->AddObserver(this); base::string16 title; GURL url; if (details_.type == EditDetails::EXISTING_NODE) { title = details_.existing_node->GetTitle(); url = details_.existing_node->url(); } else if (details_.type == EditDetails::NEW_FOLDER) { title = l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NEW_FOLDER_NAME); } else if (details_.type == EditDetails::NEW_URL) { url = details_.url; title = details_.title; } auto title_tf = std::make_unique<views::Textfield>(); title_tf->SetAccessibleName( l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_EDITOR_NAME_LABEL)); title_tf->SetText(title); title_tf->set_controller(this); std::unique_ptr<views::TreeView> tree_view; if (show_tree_) { tree_view = std::make_unique<views::TreeView>(); tree_view->SetRootShown(false); tree_view->set_context_menu_controller(this); } views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>()); ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); const int labels_column_set_id = 0; const int single_column_view_set_id = 1; const int buttons_column_set_id = 2; using ColumnSize = views::GridLayout::ColumnSize; views::ColumnSet* column_set = layout->AddColumnSet(labels_column_set_id); column_set->AddColumn( provider->GetControlLabelGridAlignment(), views::GridLayout::CENTER, views::GridLayout::kFixedSize, ColumnSize::kUsePreferred, 0, 0); column_set->AddPaddingColumn( views::GridLayout::kFixedSize, provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_HORIZONTAL)); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::CENTER, 1.0, ColumnSize::kUsePreferred, 0, 0); column_set = layout->AddColumnSet(single_column_view_set_id); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1.0, ColumnSize::kUsePreferred, 0, 0); column_set = layout->AddColumnSet(buttons_column_set_id); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING, views::GridLayout::kFixedSize, ColumnSize::kUsePreferred, 0, 0); column_set->AddPaddingColumn( 1.0, provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_HORIZONTAL)); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING, views::GridLayout::kFixedSize, ColumnSize::kUsePreferred, 0, 0); column_set->AddPaddingColumn( views::GridLayout::kFixedSize, provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_HORIZONTAL)); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::LEADING, views::GridLayout::kFixedSize, ColumnSize::kUsePreferred, 0, 0); column_set->LinkColumnSizes({0, 2, 4}); layout->StartRow(views::GridLayout::kFixedSize, labels_column_set_id); layout->AddView(std::make_unique<views::Label>( l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NAME_LABEL))); title_tf_ = layout->AddView(std::move(title_tf)); if (details_.GetNodeType() != BookmarkNode::FOLDER) { auto url_tf = std::make_unique<views::Textfield>(); url_tf->SetText(chrome::FormatBookmarkURLForDisplay(url)); url_tf->set_controller(this); url_tf->SetAccessibleName( l10n_util::GetStringUTF16(IDS_BOOKMARK_AX_EDITOR_URL_LABEL)); url_tf->SetTextInputType(ui::TextInputType::TEXT_INPUT_TYPE_URL); layout->AddPaddingRow( views::GridLayout::kFixedSize, provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL)); layout->StartRow(views::GridLayout::kFixedSize, labels_column_set_id); layout->AddView(std::make_unique<views::Label>( l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_URL_LABEL))); url_tf_ = layout->AddView(std::move(url_tf)); } if (show_tree_) { layout->AddPaddingRow( views::GridLayout::kFixedSize, provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL)); layout->StartRow(1.0, single_column_view_set_id); tree_view_ = tree_view.get(); layout->AddView( views::TreeView::CreateScrollViewWithTree(std::move(tree_view))); } if (!show_tree_ || bb_model_->loaded()) Reset(); } void BookmarkEditorView::Reset() { if (!show_tree_) { if (parent()) UserInputChanged(); return; } if (new_folder_button_) new_folder_button_->SetEnabled(true); // Do this first, otherwise when we invoke SetModel with the real one // tree_view will try to invoke something on the model we just deleted. tree_view_->SetModel(nullptr); tree_model_ = std::make_unique<EditorTreeModel>(CreateRootNode()); tree_view_->SetModel(tree_model_.get()); tree_view_->SetController(this); context_menu_runner_.reset(); if (parent()) ExpandAndSelect(); } GURL BookmarkEditorView::GetInputURL() const { if (details_.GetNodeType() == BookmarkNode::FOLDER) return GURL(); return url_formatter::FixupURL(base::UTF16ToUTF8(url_tf_->GetText()), std::string()); } void BookmarkEditorView::UserInputChanged() { if (details_.GetNodeType() != BookmarkNode::FOLDER) { const GURL url(GetInputURL()); url_tf_->SetInvalid(!url.is_valid()); } DialogModelChanged(); } void BookmarkEditorView::NewFolder() { // Create a new entry parented to the selected item, or the bookmark // bar if nothing is selected. EditorNode* parent = tree_model_->AsNode(tree_view_->GetSelectedNode()); if (!parent) { NOTREACHED(); return; } tree_view_->StartEditing(AddNewFolder(parent)); } BookmarkEditorView::EditorNode* BookmarkEditorView::AddNewFolder( EditorNode* parent) { return tree_model_->Add( parent, std::make_unique<EditorNode>( l10n_util::GetStringUTF16(IDS_BOOKMARK_EDITOR_NEW_FOLDER_NAME), 0)); } void BookmarkEditorView::ExpandAndSelect() { BookmarkExpandedStateTracker::Nodes expanded_nodes = bb_model_->expanded_state_tracker()->GetExpandedNodes(); for (auto i(expanded_nodes.begin()); i != expanded_nodes.end(); ++i) { EditorNode* editor_node = FindNodeWithID(tree_model_->GetRoot(), (*i)->id()); if (editor_node) tree_view_->Expand(editor_node); } const BookmarkNode* to_select = parent_; if (details_.type == EditDetails::EXISTING_NODE) to_select = details_.existing_node->parent(); int64_t folder_id_to_select = to_select->id(); EditorNode* b_node = FindNodeWithID(tree_model_->GetRoot(), folder_id_to_select); if (!b_node) b_node = tree_model_->GetRoot()->children().front().get(); // Bookmark bar. tree_view_->SetSelectedNode(b_node); } std::unique_ptr<BookmarkEditorView::EditorNode> BookmarkEditorView::CreateRootNode() { std::unique_ptr<EditorNode> root_node = std::make_unique<EditorNode>(base::string16(), 0); const BookmarkNode* bb_root_node = bb_model_->root_node(); CreateNodes(bb_root_node, root_node.get()); DCHECK_GE(root_node->children().size(), 2u); DCHECK_LE(root_node->children().size(), 4u); DCHECK_EQ(BookmarkNode::BOOKMARK_BAR, bb_root_node->children()[0]->type()); DCHECK_EQ(BookmarkNode::OTHER_NODE, bb_root_node->children()[1]->type()); if (root_node->children().size() >= 3) DCHECK_EQ(BookmarkNode::MOBILE, bb_root_node->children()[2]->type()); return root_node; } void BookmarkEditorView::CreateNodes(const BookmarkNode* bb_node, BookmarkEditorView::EditorNode* b_node) { for (const auto& child_bb_node : bb_node->children()) { if (child_bb_node->IsVisible() && child_bb_node->is_folder() && bb_model_->client()->CanBeEditedByUser(child_bb_node.get())) { EditorNode* new_b_node = b_node->Add(std::make_unique<EditorNode>( child_bb_node->GetTitle(), child_bb_node->id())); CreateNodes(child_bb_node.get(), new_b_node); } } } BookmarkEditorView::EditorNode* BookmarkEditorView::FindNodeWithID( BookmarkEditorView::EditorNode* node, int64_t id) { if (node->value == id) return node; for (const auto& child : node->children()) { EditorNode* result = FindNodeWithID(child.get(), id); if (result) return result; } return nullptr; } void BookmarkEditorView::ApplyEdits() { DCHECK(bb_model_->loaded()); if (tree_view_) tree_view_->CommitEdit(); EditorNode* parent = show_tree_ ? tree_model_->AsNode(tree_view_->GetSelectedNode()) : nullptr; if (show_tree_ && !parent) { NOTREACHED(); return; } ApplyEdits(parent); } void BookmarkEditorView::ApplyEdits(EditorNode* parent) { DCHECK(!show_tree_ || parent); // We're going to apply edits to the bookmark bar model, which will call us // back. Normally when a structural edit occurs we reset the tree model. // We don't want to do that here, so we remove ourselves as an observer. bb_model_->RemoveObserver(this); GURL new_url(GetInputURL()); base::string16 new_title(title_tf_->GetText()); if (!show_tree_) { BookmarkEditor::ApplyEditsWithNoFolderChange( bb_model_, parent_, details_, new_title, new_url); return; } // Create the new folders and update the titles. const BookmarkNode* new_parent = nullptr; ApplyNameChangesAndCreateNewFolders( bb_model_->root_node(), tree_model_->GetRoot(), parent, &new_parent); BookmarkEditor::ApplyEditsWithPossibleFolderChange( bb_model_, new_parent, details_, new_title, new_url); BookmarkExpandedStateTracker::Nodes expanded_nodes; UpdateExpandedNodes(tree_model_->GetRoot(), &expanded_nodes); bb_model_->expanded_state_tracker()->SetExpandedNodes(expanded_nodes); // Remove the folders that were removed. This has to be done after all the // other changes have been committed. bookmarks::DeleteBookmarkFolders(bb_model_, deletes_); } void BookmarkEditorView::ApplyNameChangesAndCreateNewFolders( const BookmarkNode* bb_node, BookmarkEditorView::EditorNode* b_node, BookmarkEditorView::EditorNode* parent_b_node, const BookmarkNode** parent_bb_node) { if (parent_b_node == b_node) *parent_bb_node = bb_node; for (const auto& child_b_node : b_node->children()) { const BookmarkNode* child_bb_node = nullptr; if (child_b_node->value == 0) { // New folder. child_bb_node = bb_model_->AddFolder(bb_node, bb_node->children().size(), child_b_node->GetTitle()); child_b_node->value = child_bb_node->id(); } else { // Existing node, reset the title (BookmarkModel ignores changes if the // title is the same). const auto i = std::find_if( bb_node->children().cbegin(), bb_node->children().cend(), [&child_b_node](const auto& node) { return node->is_folder() && node->id() == child_b_node->value; }); DCHECK(i != bb_node->children().cend()); child_bb_node = i->get(); bb_model_->SetTitle(child_bb_node, child_b_node->GetTitle()); } ApplyNameChangesAndCreateNewFolders(child_bb_node, child_b_node.get(), parent_b_node, parent_bb_node); } } void BookmarkEditorView::UpdateExpandedNodes( EditorNode* editor_node, BookmarkExpandedStateTracker::Nodes* expanded_nodes) { if (!tree_view_->IsExpanded(editor_node)) return; // The root is 0. if (editor_node->value != 0) { expanded_nodes->insert( bookmarks::GetBookmarkNodeByID(bb_model_, editor_node->value)); } for (const auto& child : editor_node->children()) UpdateExpandedNodes(child.get(), expanded_nodes); } ui::SimpleMenuModel* BookmarkEditorView::GetMenuModel() { if (!context_menu_model_.get()) { context_menu_model_ = std::make_unique<ui::SimpleMenuModel>(this); context_menu_model_->AddItemWithStringId(IDS_EDIT, IDS_EDIT); context_menu_model_->AddItemWithStringId(IDS_DELETE, IDS_DELETE); context_menu_model_->AddItemWithStringId( IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM, IDS_BOOKMARK_EDITOR_NEW_FOLDER_MENU_ITEM); } return context_menu_model_.get(); } void BookmarkEditorView::EditorTreeModel::SetTitle( ui::TreeModelNode* node, const base::string16& title) { if (!title.empty()) ui::TreeNodeModel<EditorNode>::SetTitle(node, title); }
endlessm/chromium-browser
chrome/browser/ui/views/bookmarks/bookmark_editor_view.cc
C++
bsd-3-clause
22,275
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Code Coverage for /var/www/html/frontend/models/game/characters/interfaces/HealerInterface.php</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../../css/bootstrap.min.css" rel="stylesheet"> <link href="../../css/style.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="../../js/html5shiv.min.js"></script> <script src="../../js/respond.min.js"></script> <![endif]--> </head> <body> <header> <div class="container"> <div class="row"> <div class="col-md-12"> <ol class="breadcrumb"> <li><a href="../../index.html">/var/www/html/frontend/models/game</a></li> <li><a href="../index.html">characters</a></li> <li><a href="index.html">interfaces</a></li> <li class="active">HealerInterface.php</li> </ol> </div> </div> </div> </header> <div class="container"> <table class="table table-bordered"> <thead> <tr> <td>&nbsp;</td> <td colspan="10"><div align="center"><strong>Code Coverage</strong></div></td> </tr> <tr> <td>&nbsp;</td> <td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td> <td colspan="4"><div align="center"><strong>Functions and Methods</strong></div></td> <td colspan="3"><div align="center"><strong>Lines</strong></div></td> </tr> </thead> <tbody> <tr> <td class="success">Total</td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right"></div></td> <td class="success small"><div align="right">0&nbsp;/&nbsp;0</div></td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">0&nbsp;/&nbsp;0</div></td> <td class="success small"><abbr title="Change Risk Anti-Patterns (CRAP) Index">CRAP</abbr></td> <td class="success big"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100.00" aria-valuemin="0" aria-valuemax="100" style="width: 100.00%"> <span class="sr-only">100.00% covered (success)</span> </div> </div> </td> <td class="success small"><div align="right">100.00%</div></td> <td class="success small"><div align="right">0&nbsp;/&nbsp;0</div></td> </tr> </tbody> </table> <table id="code" class="table table-borderless table-condensed"> <tbody> <tr><td><div align="right"><a name="1"></a><a href="#1">1</a></div></td><td class="codeLine"><span class="default">&lt;?php</span></td></tr> <tr><td><div align="right"><a name="2"></a><a href="#2">2</a></div></td><td class="codeLine"><span class="comment">/**</span></td></tr> <tr><td><div align="right"><a name="3"></a><a href="#3">3</a></div></td><td class="codeLine"><span class="comment">&nbsp;*&nbsp;Created&nbsp;by&nbsp;PhpStorm.</span></td></tr> <tr><td><div align="right"><a name="4"></a><a href="#4">4</a></div></td><td class="codeLine"><span class="comment">&nbsp;*&nbsp;User:&nbsp;maksim.d</span></td></tr> <tr><td><div align="right"><a name="5"></a><a href="#5">5</a></div></td><td class="codeLine"><span class="comment">&nbsp;*&nbsp;Date:&nbsp;12/4/15</span></td></tr> <tr><td><div align="right"><a name="6"></a><a href="#6">6</a></div></td><td class="codeLine"><span class="comment">&nbsp;*&nbsp;Time:&nbsp;03:28</span></td></tr> <tr><td><div align="right"><a name="7"></a><a href="#7">7</a></div></td><td class="codeLine"><span class="comment">&nbsp;*/</span></td></tr> <tr><td><div align="right"><a name="8"></a><a href="#8">8</a></div></td><td class="codeLine"></td></tr> <tr><td><div align="right"><a name="9"></a><a href="#9">9</a></div></td><td class="codeLine"><span class="keyword">namespace</span><span class="default">&nbsp;</span><span class="default">frontend</span><span class="default">\</span><span class="default">models</span><span class="default">\</span><span class="default">game</span><span class="default">\</span><span class="default">characters</span><span class="default">\</span><span class="default">interfaces</span><span class="keyword">;</span></td></tr> <tr><td><div align="right"><a name="10"></a><a href="#10">10</a></div></td><td class="codeLine"></td></tr> <tr><td><div align="right"><a name="11"></a><a href="#11">11</a></div></td><td class="codeLine"></td></tr> <tr><td><div align="right"><a name="12"></a><a href="#12">12</a></div></td><td class="codeLine"><span class="keyword">use</span><span class="default">&nbsp;</span><span class="default">frontend</span><span class="default">\</span><span class="default">models</span><span class="default">\</span><span class="default">game</span><span class="default">\</span><span class="default">base</span><span class="default">\</span><span class="default">DoctorInterface</span><span class="keyword">;</span></td></tr> <tr><td><div align="right"><a name="13"></a><a href="#13">13</a></div></td><td class="codeLine"><span class="keyword">use</span><span class="default">&nbsp;</span><span class="default">frontend</span><span class="default">\</span><span class="default">models</span><span class="default">\</span><span class="default">game</span><span class="default">\</span><span class="default">base</span><span class="default">\</span><span class="default">SearchBeeInterface</span><span class="keyword">;</span></td></tr> <tr><td><div align="right"><a name="14"></a><a href="#14">14</a></div></td><td class="codeLine"><span class="keyword">use</span><span class="default">&nbsp;</span><span class="default">frontend</span><span class="default">\</span><span class="default">models</span><span class="default">\</span><span class="default">game</span><span class="default">\</span><span class="default">characters</span><span class="default">\</span><span class="default">base</span><span class="default">\</span><span class="default">interfaces</span><span class="default">\</span><span class="default">BeeInterface</span><span class="keyword">;</span></td></tr> <tr><td><div align="right"><a name="15"></a><a href="#15">15</a></div></td><td class="codeLine"></td></tr> <tr><td><div align="right"><a name="16"></a><a href="#16">16</a></div></td><td class="codeLine"><span class="keyword">interface</span><span class="default">&nbsp;</span><span class="default">HealerInterface</span><span class="default">&nbsp;</span><span class="keyword">extends</span><span class="default">&nbsp;</span><span class="default">BeeInterface</span><span class="keyword">,</span><span class="default">&nbsp;</span><span class="default">DoctorInterface</span><span class="keyword">,</span><span class="default">&nbsp;</span><span class="default">SearchBeeInterface</span></td></tr> <tr><td><div align="right"><a name="17"></a><a href="#17">17</a></div></td><td class="codeLine"><span class="keyword">{</span></td></tr> <tr><td><div align="right"><a name="18"></a><a href="#18">18</a></div></td><td class="codeLine"></td></tr> <tr><td><div align="right"><a name="19"></a><a href="#19">19</a></div></td><td class="codeLine"><span class="keyword">}</span></td></tr> </tbody> </table> <footer> <hr/> <h4>Legend</h4> <p> <span class="success"><strong>Executed</strong></span> <span class="danger"><strong>Not Executed</strong></span> <span class="warning"><strong>Dead Code</strong></span> </p> <p> <small>Generated by <a href="http://github.com/sebastianbergmann/php-code-coverage" target="_top">PHP_CodeCoverage 3.0.2</a> using <a href="http://php.net/" target="_top">PHP 5.6.14</a> and <a href="https://phpunit.de/">PHPUnit 5.1.0</a> at Mon Dec 7 0:37:06 UTC 2015.</small> </p> <a title="Back to the top" id="toplink" href="#"><span class="glyphicon glyphicon-arrow-up"></span></a> </footer> </div> <script src="../../js/jquery.min.js" type="text/javascript"></script> <script src="../../js/bootstrap.min.js" type="text/javascript"></script> <script src="../../js/holder.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { var $window = $(window) , $top_link = $('#toplink') , $body = $('body, html') , offset = $('#code').offset().top; $top_link.hide().click(function(event) { event.preventDefault(); $body.animate({scrollTop:0}, 800); }); $window.scroll(function() { if($window.scrollTop() > offset) { $top_link.fadeIn(); } else { $top_link.fadeOut(); } }).scroll(); $('.popin').popover({trigger: 'hover'}); }); </script> </body> </html>
macseem/bee-game
tests/coverage/characters/interfaces/HealerInterface.php.html
HTML
bsd-3-clause
9,350
<?php namespace Gaia\Serialize; class Base64 implements Iface { protected $s; public function __construct( Iface $s = NULL ){ if( ! $s ) $s = new PHP(''); $this->s = $s; } public function serialize( $data ){ return self::base64UrlEncode($this->s->serialize( $data )); } public function unserialize($payload) { if(! is_scalar( $payload ) ) return NULL; $payload = self::base64UrlDecode($payload); if( ! is_scalar( $payload ) ) return NULL; return $this->s->unserialize($payload); } protected static function base64UrlEncode( $input ){ return rtrim( strtr(base64_encode($input), '+/', '-_'), '='); } protected static function base64UrlDecode($input) { return base64_decode(strtr($input, '-_', '+/')); } }
Gaia-Interactive/gaia_core_php
lib/gaia/serialize/base64.php
PHP
bsd-3-clause
842
package de.plushnikov.bug.issue634; import lombok.Builder; import lombok.Getter; import lombok.NonNull; import lombok.Setter; @Builder @Getter @Setter public class SomeBoxClass { private Node.NodeBuilder intField; @NonNull private String someString; @NonNull private Node node; @NonNull private LinkedListImpl someImpl; }
mplushnikov/lombok-intellij-plugin
test-manual/src/main/java/de/plushnikov/bug/issue634/SomeBoxClass.java
Java
bsd-3-clause
342
"""private_base will be populated from puppet and placed in this directory""" import logging import os import dj_database_url from lib.settings_base import CACHE_PREFIX, ES_INDEXES, KNOWN_PROXIES, LOGGING from .. import splitstrip import private_base as private ENGAGE_ROBOTS = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = private.EMAIL_HOST DEBUG = False TEMPLATE_DEBUG = DEBUG DEBUG_PROPAGATE_EXCEPTIONS = False SESSION_COOKIE_SECURE = True REDIRECT_SECRET_KEY = private.REDIRECT_SECRET_KEY ADMINS = () DATABASES = {} DATABASES['default'] = dj_database_url.parse(private.DATABASES_DEFAULT_URL) DATABASES['default']['ENGINE'] = 'mysql_pool' DATABASES['default']['sa_pool_key'] = 'master' DATABASES['default']['OPTIONS'] = {'init_command': 'SET storage_engine=InnoDB'} DATABASES['slave'] = dj_database_url.parse(private.DATABASES_SLAVE_URL) DATABASES['slave']['ENGINE'] = 'mysql_pool' DATABASES['slave']['OPTIONS'] = {'init_command': 'SET storage_engine=InnoDB'} DATABASES['slave']['sa_pool_key'] = 'slave' SERVICES_DATABASE = dj_database_url.parse(private.SERVICES_DATABASE_URL) DATABASE_POOL_ARGS = { 'max_overflow': 10, 'pool_size': 5, 'recycle': 30 } SLAVE_DATABASES = ['slave'] CACHES = { 'default': { 'BACKEND': 'caching.backends.memcached.MemcachedCache', # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 'BACKEND': 'memcachepool.cache.UMemcacheCache', 'LOCATION': splitstrip(private.CACHES_DEFAULT_LOCATION), 'TIMEOUT': 500, 'KEY_PREFIX': CACHE_PREFIX, }, } SECRET_KEY = private.SECRET_KEY LOG_LEVEL = logging.DEBUG ## Celery BROKER_URL = private.BROKER_URL CELERY_ALWAYS_EAGER = True CELERY_IGNORE_RESULT = True CELERY_DISABLE_RATE_LIMITS = True CELERYD_PREFETCH_MULTIPLIER = 1 NETAPP_STORAGE = private.NETAPP_STORAGE_ROOT + '/shared_storage' MIRROR_STAGE_PATH = private.NETAPP_STORAGE_ROOT + '/public-staging' GUARDED_ADDONS_PATH = private.NETAPP_STORAGE_ROOT + '/guarded-addons' UPLOADS_PATH = NETAPP_STORAGE + '/uploads' USERPICS_PATH = UPLOADS_PATH + '/userpics' ADDON_ICONS_PATH = UPLOADS_PATH + '/addon_icons' COLLECTION_ICONS_PATH = UPLOADS_PATH + '/collection_icons' IMAGEASSETS_PATH = UPLOADS_PATH + '/imageassets' REVIEWER_ATTACHMENTS_PATH = UPLOADS_PATH + '/reviewer_attachment' PREVIEWS_PATH = UPLOADS_PATH + '/previews' SIGNED_APPS_PATH = NETAPP_STORAGE + '/signed_apps' SIGNED_APPS_REVIEWER_PATH = NETAPP_STORAGE + '/signed_apps_reviewer' PREVIEW_THUMBNAIL_PATH = PREVIEWS_PATH + '/thumbs/%s/%d.png' PREVIEW_FULL_PATH = PREVIEWS_PATH + '/full/%s/%d.%s' HERA = [] LOGGING['loggers'].update({ 'z.task': { 'level': logging.DEBUG }, 'z.hera': { 'level': logging.INFO }, 'z.redis': { 'level': logging.DEBUG }, 'z.pool': { 'level': logging.ERROR }, }) REDIS_BACKEND = private.REDIS_BACKENDS_CACHE REDIS_BACKENDS = { 'cache': private.REDIS_BACKENDS_CACHE, 'cache_slave': private.REDIS_BACKENDS_CACHE_SLAVE, 'master': private.REDIS_BACKENDS_MASTER, 'slave': private.REDIS_BACKENDS_SLAVE, } CACHE_MACHINE_USE_REDIS = True RECAPTCHA_PUBLIC_KEY = private.RECAPTCHA_PUBLIC_KEY RECAPTCHA_PRIVATE_KEY = private.RECAPTCHA_PRIVATE_KEY RECAPTCHA_URL = ('https://www.google.com/recaptcha/api/challenge?k=%s' % RECAPTCHA_PUBLIC_KEY) TMP_PATH = os.path.join(NETAPP_STORAGE, 'tmp') PACKAGER_PATH = os.path.join(TMP_PATH, 'packager') ADDONS_PATH = private.NETAPP_STORAGE_ROOT + '/files' PERF_THRESHOLD = 20 SPIDERMONKEY = '/usr/bin/tracemonkey' # Remove DetectMobileMiddleware from middleware in production. detect = 'mobility.middleware.DetectMobileMiddleware' csp = 'csp.middleware.CSPMiddleware' RESPONSYS_ID = private.RESPONSYS_ID CRONJOB_LOCK_PREFIX = 'addons-landfill' BUILDER_SECRET_KEY = private.BUILDER_SECRET_KEY BUILDER_VERSIONS_URL = "https://builder-addons-dev.allizom.org/repackage/sdk-versions/" ES_HOSTS = splitstrip(private.ES_HOSTS) ES_URLS = ['http://%s' % h for h in ES_HOSTS] ES_INDEXES = dict((k, '%s_landfill' % v) for k, v in ES_INDEXES.items()) BUILDER_UPGRADE_URL = "https://builder-addons-dev.allizom.org/repackage/rebuild/" STATSD_HOST = private.STATSD_HOST STATSD_PORT = private.STATSD_PORT STATSD_PREFIX = private.STATSD_PREFIX GRAPHITE_HOST = private.GRAPHITE_HOST GRAPHITE_PORT = private.GRAPHITE_PORT GRAPHITE_PREFIX = private.GRAPHITE_PREFIX CEF_PRODUCT = STATSD_PREFIX ES_TIMEOUT = 60 EXPOSE_VALIDATOR_TRACEBACKS = True KNOWN_PROXIES += ['10.2.83.105', '10.2.83.106', '10.2.83.107', '10.8.83.200', '10.8.83.201', '10.8.83.202', '10.8.83.203', '10.8.83.204', '10.8.83.210', '10.8.83.211', '10.8.83.212', '10.8.83.213', '10.8.83.214', '10.8.83.215', '10.8.83.251', '10.8.83.252', '10.8.83.253', ] NEW_FEATURES = True PERF_TEST_URL = 'http://talos-addon-master1.amotest.scl1.mozilla.com/trigger/trigger.cgi' REDIRECT_URL = 'https://outgoing.allizom.org/v1/' CLEANCSS_BIN = 'cleancss' UGLIFY_BIN = 'uglifyjs' CELERYD_TASK_SOFT_TIME_LIMIT = 240 LESS_PREPROCESS = True XSENDFILE_HEADER = 'X-Accel-Redirect' ALLOW_SELF_REVIEWS = True AES_KEYS = private.AES_KEYS
anaran/olympia
sites/landfill/settings_base.py
Python
bsd-3-clause
5,402
''' Created on 9 jan. 2013 @author: sander ''' from bitstring import BitStream, ConstBitStream, Bits from ipaddress import IPv4Address, IPv6Address from pylisp.packet.ip import protocol_registry from pylisp.packet.ip.protocol import Protocol from pylisp.utils import checksum import numbers class UDPMessage(Protocol): header_type = 17 def __init__(self, source_port=0, destination_port=0, checksum=0, payload=''): # Call the superclass constructor super(UDPMessage, self).__init__(payload=payload) self.source_port = source_port self.destination_port = destination_port self.checksum = checksum def sanitize(self): ''' Check if the current settings conform to the RFC and fix where possible ''' # Check ports if not isinstance(self.source_port, numbers.Integral) \ or self.source_port < 0 \ or self.source_port >= 2 ** 16: raise ValueError('Invalid source port') if not isinstance(self.destination_port, numbers.Integral) \ or self.destination_port < 0 \ or self.destination_port >= 2 ** 16: raise ValueError('Invalid destination port') # We can't calculate the checksum because we don't know enough by # ourself to construct the pseudo-header def generate_pseudo_header(self, source, destination): # Calculate the length of the UDP layer udp_length = 8 + len(bytes(self.payload)) if isinstance(source, IPv4Address) \ and isinstance(destination, IPv4Address): # Generate an IPv4 pseudo-header header = BitStream('uint:32=%d, ' 'uint:32=%d, ' 'uint:16=17, ' 'uint:16=%d' % (int(source), int(destination), udp_length)) elif isinstance(source, IPv6Address) \ and isinstance(destination, IPv6Address): # Generate an IPv6 pseudo-header header = BitStream('uint:128=%d, ' 'uint:128=%d, ' 'uint:32=%d, ' 'uint:32=17' % (int(source), int(destination), udp_length)) else: raise ValueError('Source and destination must belong to the same ' 'IP version') # Return the header bytes return header.bytes def calculate_checksum(self, source, destination): # Calculate the pseudo-header for the checksum calculation pseudo_header = self.generate_pseudo_header(source, destination) # Remember the current checksum, generate a message and restore the # original checksum old_checksum = self.checksum self.checksum = 0 message = self.to_bytes() self.checksum = old_checksum # Calculate the checksum my_checksum = checksum.ones_complement(pseudo_header + message) # If the computed checksum is zero, it is transmitted as all ones (the # equivalent in one's complement arithmetic). An all zero transmitted # checksum value means that the transmitter generated no checksum (for # debugging or for higher level protocols that don't care). if my_checksum == 0: my_checksum = 0xffff return my_checksum def verify_checksum(self, source, destination): # An all zero transmitted checksum value means that the transmitter # generated no checksum (for debugging or for higher level protocols # that don't care). if self.checksum == 0: return True return self.checksum == self.calculate_checksum(source, destination) def get_lisp_message(self, only_data=False, only_control=False): # Check the UDP ports lisp_data = (self.source_port == 4341 or self.destination_port == 4341) lisp_control = (self.source_port == 4342 or self.destination_port == 4342) if lisp_data and lisp_control: raise ValueError("Cannot mix LISP data and control ports") from pylisp.packet.lisp.control.base import ControlMessage from pylisp.packet.lisp.data import DataPacket if lisp_data or only_data: if not isinstance(self.payload, DataPacket): raise ValueError("Payload is not a LISP data packet") return self.payload elif lisp_control or only_control: if not isinstance(self.payload, ControlMessage): raise ValueError("Payload is not a LISP control message") return self.payload else: raise ValueError("No LISP content found") def get_lisp_data_packet(self): return self.get_lisp_message(only_data=True) def get_lisp_control_message(self): return self.get_lisp_message(only_control=True) @classmethod def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' packet = cls() # Convert to ConstBitStream (if not already provided) if not isinstance(bitstream, ConstBitStream): if isinstance(bitstream, Bits): bitstream = ConstBitStream(auto=bitstream) else: bitstream = ConstBitStream(bytes=bitstream) # Read the source and destination ports (packet.source_port, packet.destination_port) = bitstream.readlist('2*uint:16') # Store the length length = bitstream.read('uint:16') if length < 8: raise ValueError('Invalid UDP length') # Read the checksum packet.checksum = bitstream.read('uint:16') # And the rest is payload payload_bytes = length - 8 packet.payload = bitstream.read('bytes:%d' % payload_bytes) # LISP-specific handling if packet.source_port == 4341 or packet.destination_port == 4341: # Payload is a LISP data packet from pylisp.packet.lisp.data import DataPacket packet.payload = DataPacket.from_bytes(packet.payload) elif packet.source_port == 4342 or packet.destination_port == 4342: # Payload is a LISP control message from pylisp.packet.lisp.control.base import ControlMessage packet.payload = ControlMessage.from_bytes(packet.payload) # There should be no remaining bits if bitstream.pos != bitstream.len: raise ValueError('Bits remaining after processing packet') # Verify that the properties make sense packet.sanitize() return packet def to_bytes(self): ''' Create bytes from properties ''' # Verify that the properties make sense self.sanitize() # Write the source and destination ports bitstream = BitStream('uint:16=%d, ' 'uint:16=%d' % (self.source_port, self.destination_port)) # Write the length payload_bytes = bytes(self.payload) length = len(payload_bytes) + 8 bitstream += BitStream('uint:16=%d' % length) # Write the checksum bitstream += BitStream('uint:16=%d' % self.checksum) return bitstream.bytes + payload_bytes # Register this header type protocol_registry.register_type_class(UDPMessage)
steffann/pylisp
pylisp/packet/ip/udp.py
Python
bsd-3-clause
7,685
/* * Copyright © 2010-2012 Intel Corporation * Copyright © 2011-2012 Collabora, Ltd. * Copyright © 2013 Raspberry Pi Foundation * * 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 (including the next * paragraph) 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. */ #include "config.h" #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <linux/input.h> #include <assert.h> #include <signal.h> #include <math.h> #include <sys/types.h> #include "shell.h" #include "compositor/weston.h" #include "weston-desktop-shell-server-protocol.h" #include <libweston/config-parser.h> #include "shared/helpers.h" #include "shared/timespec-util.h" #include <libweston-desktop/libweston-desktop.h> #define DEFAULT_NUM_WORKSPACES 1 #define DEFAULT_WORKSPACE_CHANGE_ANIMATION_LENGTH 200 struct focus_state { struct desktop_shell *shell; struct weston_seat *seat; struct workspace *ws; struct weston_surface *keyboard_focus; struct wl_list link; struct wl_listener seat_destroy_listener; struct wl_listener surface_destroy_listener; }; /* * Surface stacking and ordering. * * This is handled using several linked lists of surfaces, organised into * ‘layers’. The layers are ordered, and each of the surfaces in one layer are * above all of the surfaces in the layer below. The set of layers is static and * in the following order (top-most first): * • Lock layer (only ever displayed on its own) * • Cursor layer * • Input panel layer * • Fullscreen layer * • Panel layer * • Workspace layers * • Background layer * * The list of layers may be manipulated to remove whole layers of surfaces from * display. For example, when locking the screen, all layers except the lock * layer are removed. * * A surface’s layer is modified on configuring the surface, in * set_surface_type() (which is only called when the surface’s type change is * _committed_). If a surface’s type changes (e.g. when making a window * fullscreen) its layer changes too. * * In order to allow popup and transient surfaces to be correctly stacked above * their parent surfaces, each surface tracks both its parent surface, and a * linked list of its children. When a surface’s layer is updated, so are the * layers of its children. Note that child surfaces are *not* the same as * subsurfaces — child/parent surfaces are purely for maintaining stacking * order. * * The children_link list of siblings of a surface (i.e. those surfaces which * have the same parent) only contains weston_surfaces which have a * shell_surface. Stacking is not implemented for non-shell_surface * weston_surfaces. This means that the following implication does *not* hold: * (shsurf->parent != NULL) ⇒ !wl_list_is_empty(shsurf->children_link) */ struct shell_surface { struct wl_signal destroy_signal; struct weston_desktop_surface *desktop_surface; struct weston_view *view; int32_t last_width, last_height; struct desktop_shell *shell; int32_t saved_x, saved_y; bool saved_position_valid; bool saved_rotation_valid; int unresponsive, grabbed; uint32_t resize_edges; struct { struct weston_transform transform; struct weston_matrix rotation; } rotation; struct { struct weston_transform transform; /* matrix from x, y */ struct weston_view *black_view; } fullscreen; struct weston_transform workspace_transform; struct weston_output *fullscreen_output; struct weston_output *output; struct wl_listener output_destroy_listener; struct surface_state { bool fullscreen; bool maximized; bool lowered; } state; struct { bool is_set; int32_t x; int32_t y; } xwayland; int focus_count; bool destroying; }; struct shell_grab { struct weston_pointer_grab grab; struct shell_surface *shsurf; struct wl_listener shsurf_destroy_listener; }; struct shell_touch_grab { struct weston_touch_grab grab; struct shell_surface *shsurf; struct wl_listener shsurf_destroy_listener; struct weston_touch *touch; }; struct weston_move_grab { struct shell_grab base; wl_fixed_t dx, dy; bool client_initiated; }; struct weston_touch_move_grab { struct shell_touch_grab base; int active; wl_fixed_t dx, dy; }; struct rotate_grab { struct shell_grab base; struct weston_matrix rotation; struct { float x; float y; } center; }; struct shell_seat { struct weston_seat *seat; struct wl_listener seat_destroy_listener; struct weston_surface *focused_surface; struct wl_listener caps_changed_listener; struct wl_listener pointer_focus_listener; struct wl_listener keyboard_focus_listener; }; static struct desktop_shell * shell_surface_get_shell(struct shell_surface *shsurf); static void set_busy_cursor(struct shell_surface *shsurf, struct weston_pointer *pointer); static void surface_rotate(struct shell_surface *surface, struct weston_pointer *pointer); static void shell_fade_startup(struct desktop_shell *shell); static void shell_fade(struct desktop_shell *shell, enum fade_type type); static struct shell_seat * get_shell_seat(struct weston_seat *seat); static void get_output_panel_size(struct desktop_shell *shell, struct weston_output *output, int *width, int *height); static void shell_surface_update_child_surface_layers(struct shell_surface *shsurf); static int shell_surface_get_label(struct weston_surface *surface, char *buf, size_t len) { const char *t, *c; struct weston_desktop_surface *desktop_surface = weston_surface_get_desktop_surface(surface); t = weston_desktop_surface_get_title(desktop_surface); c = weston_desktop_surface_get_app_id(desktop_surface); return snprintf(buf, len, "%s window%s%s%s%s%s", "top-level", t ? " '" : "", t ?: "", t ? "'" : "", c ? " of " : "", c ?: ""); } static void destroy_shell_grab_shsurf(struct wl_listener *listener, void *data) { struct shell_grab *grab; grab = container_of(listener, struct shell_grab, shsurf_destroy_listener); grab->shsurf = NULL; } struct weston_view * get_default_view(struct weston_surface *surface) { struct shell_surface *shsurf; struct weston_view *view; if (!surface || wl_list_empty(&surface->views)) return NULL; shsurf = get_shell_surface(surface); if (shsurf) return shsurf->view; wl_list_for_each(view, &surface->views, surface_link) if (weston_view_is_mapped(view)) return view; return container_of(surface->views.next, struct weston_view, surface_link); } static void shell_grab_start(struct shell_grab *grab, const struct weston_pointer_grab_interface *interface, struct shell_surface *shsurf, struct weston_pointer *pointer, enum weston_desktop_shell_cursor cursor) { struct desktop_shell *shell = shsurf->shell; weston_seat_break_desktop_grabs(pointer->seat); grab->grab.interface = interface; grab->shsurf = shsurf; grab->shsurf_destroy_listener.notify = destroy_shell_grab_shsurf; wl_signal_add(&shsurf->destroy_signal, &grab->shsurf_destroy_listener); shsurf->grabbed = 1; weston_pointer_start_grab(pointer, &grab->grab); if (shell->child.desktop_shell) { weston_desktop_shell_send_grab_cursor(shell->child.desktop_shell, cursor); weston_pointer_set_focus(pointer, get_default_view(shell->grab_surface), wl_fixed_from_int(0), wl_fixed_from_int(0)); } } static void get_panel_size(struct desktop_shell *shell, struct weston_view *view, int *width, int *height) { float x1, y1; float x2, y2; weston_view_to_global_float(view, 0, 0, &x1, &y1); weston_view_to_global_float(view, view->surface->width, view->surface->height, &x2, &y2); *width = (int)(x2 - x1); *height = (int)(y2 - y1); } static void get_output_panel_size(struct desktop_shell *shell, struct weston_output *output, int *width, int *height) { struct weston_view *view; *width = 0; *height = 0; if (!output) return; wl_list_for_each(view, &shell->panel_layer.view_list.link, layer_link.link) { if (view->surface->output == output) { get_panel_size(shell, view, width, height); return; } } /* the correct view wasn't found */ } static void get_output_work_area(struct desktop_shell *shell, struct weston_output *output, pixman_rectangle32_t *area) { int32_t panel_width = 0, panel_height = 0; if (!output) { area->x = 0; area->y = 0; area->width = 0; area->height = 0; return; } area->x = output->x; area->y = output->y; get_output_panel_size(shell, output, &panel_width, &panel_height); switch (shell->panel_position) { case WESTON_DESKTOP_SHELL_PANEL_POSITION_TOP: default: area->y += panel_height; /* fallthrough */ case WESTON_DESKTOP_SHELL_PANEL_POSITION_BOTTOM: area->width = output->width; area->height = output->height - panel_height; break; case WESTON_DESKTOP_SHELL_PANEL_POSITION_LEFT: area->x += panel_width; /* fallthrough */ case WESTON_DESKTOP_SHELL_PANEL_POSITION_RIGHT: area->width = output->width - panel_width; area->height = output->height; break; } } static void shell_grab_end(struct shell_grab *grab) { if (grab->shsurf) { wl_list_remove(&grab->shsurf_destroy_listener.link); grab->shsurf->grabbed = 0; if (grab->shsurf->resize_edges) { grab->shsurf->resize_edges = 0; } } weston_pointer_end_grab(grab->grab.pointer); } static void shell_touch_grab_start(struct shell_touch_grab *grab, const struct weston_touch_grab_interface *interface, struct shell_surface *shsurf, struct weston_touch *touch) { struct desktop_shell *shell = shsurf->shell; weston_seat_break_desktop_grabs(touch->seat); grab->grab.interface = interface; grab->shsurf = shsurf; grab->shsurf_destroy_listener.notify = destroy_shell_grab_shsurf; wl_signal_add(&shsurf->destroy_signal, &grab->shsurf_destroy_listener); grab->touch = touch; shsurf->grabbed = 1; weston_touch_start_grab(touch, &grab->grab); if (shell->child.desktop_shell) weston_touch_set_focus(touch, get_default_view(shell->grab_surface)); } static void shell_touch_grab_end(struct shell_touch_grab *grab) { if (grab->shsurf) { wl_list_remove(&grab->shsurf_destroy_listener.link); grab->shsurf->grabbed = 0; } weston_touch_end_grab(grab->touch); } static void center_on_output(struct weston_view *view, struct weston_output *output); static enum weston_keyboard_modifier get_modifier(char *modifier) { if (!modifier) return MODIFIER_SUPER; if (!strcmp("ctrl", modifier)) return MODIFIER_CTRL; else if (!strcmp("alt", modifier)) return MODIFIER_ALT; else if (!strcmp("super", modifier)) return MODIFIER_SUPER; else if (!strcmp("none", modifier)) return 0; else return MODIFIER_SUPER; } static enum animation_type get_animation_type(char *animation) { if (!animation) return ANIMATION_NONE; if (!strcmp("zoom", animation)) return ANIMATION_ZOOM; else if (!strcmp("fade", animation)) return ANIMATION_FADE; else if (!strcmp("dim-layer", animation)) return ANIMATION_DIM_LAYER; else return ANIMATION_NONE; } static void shell_configuration(struct desktop_shell *shell) { struct weston_config_section *section; char *s, *client; int allow_zap; section = weston_config_get_section(wet_get_config(shell->compositor), "shell", NULL, NULL); client = wet_get_libexec_path(WESTON_SHELL_CLIENT); weston_config_section_get_string(section, "client", &s, client); free(client); shell->client = s; weston_config_section_get_bool(section, "allow-zap", &allow_zap, true); shell->allow_zap = allow_zap; weston_config_section_get_string(section, "binding-modifier", &s, "super"); shell->binding_modifier = get_modifier(s); free(s); weston_config_section_get_string(section, "exposay-modifier", &s, "none"); shell->exposay_modifier = get_modifier(s); free(s); weston_config_section_get_string(section, "animation", &s, "none"); shell->win_animation_type = get_animation_type(s); free(s); weston_config_section_get_string(section, "close-animation", &s, "fade"); shell->win_close_animation_type = get_animation_type(s); free(s); weston_config_section_get_string(section, "startup-animation", &s, "fade"); shell->startup_animation_type = get_animation_type(s); free(s); if (shell->startup_animation_type == ANIMATION_ZOOM) shell->startup_animation_type = ANIMATION_NONE; weston_config_section_get_string(section, "focus-animation", &s, "none"); shell->focus_animation_type = get_animation_type(s); free(s); weston_config_section_get_uint(section, "num-workspaces", &shell->workspaces.num, DEFAULT_NUM_WORKSPACES); } struct weston_output * get_default_output(struct weston_compositor *compositor) { if (wl_list_empty(&compositor->output_list)) return NULL; return container_of(compositor->output_list.next, struct weston_output, link); } static int focus_surface_get_label(struct weston_surface *surface, char *buf, size_t len) { return snprintf(buf, len, "focus highlight effect for output %s", surface->output->name); } /* no-op func for checking focus surface */ static void focus_surface_committed(struct weston_surface *es, int32_t sx, int32_t sy) { } static struct focus_surface * get_focus_surface(struct weston_surface *surface) { if (surface->committed == focus_surface_committed) return surface->committed_private; else return NULL; } static bool is_focus_surface (struct weston_surface *es) { return (es->committed == focus_surface_committed); } static bool is_focus_view (struct weston_view *view) { return is_focus_surface (view->surface); } static struct focus_surface * create_focus_surface(struct weston_compositor *ec, struct weston_output *output) { struct focus_surface *fsurf = NULL; struct weston_surface *surface = NULL; fsurf = malloc(sizeof *fsurf); if (!fsurf) return NULL; fsurf->surface = weston_surface_create(ec); surface = fsurf->surface; if (surface == NULL) { free(fsurf); return NULL; } surface->committed = focus_surface_committed; surface->output = output; surface->is_mapped = true; surface->committed_private = fsurf; weston_surface_set_label_func(surface, focus_surface_get_label); fsurf->view = weston_view_create(surface); if (fsurf->view == NULL) { weston_surface_destroy(surface); free(fsurf); return NULL; } weston_view_set_output(fsurf->view, output); fsurf->view->is_mapped = true; weston_surface_set_size(surface, output->width, output->height); weston_view_set_position(fsurf->view, output->x, output->y); weston_surface_set_color(surface, 0.0, 0.0, 0.0, 1.0); pixman_region32_fini(&surface->opaque); pixman_region32_init_rect(&surface->opaque, output->x, output->y, output->width, output->height); pixman_region32_fini(&surface->input); pixman_region32_init(&surface->input); wl_list_init(&fsurf->workspace_transform.link); return fsurf; } static void focus_surface_destroy(struct focus_surface *fsurf) { weston_surface_destroy(fsurf->surface); free(fsurf); } static void focus_animation_done(struct weston_view_animation *animation, void *data) { struct workspace *ws = data; ws->focus_animation = NULL; } static void focus_state_destroy(struct focus_state *state) { wl_list_remove(&state->seat_destroy_listener.link); wl_list_remove(&state->surface_destroy_listener.link); free(state); } static void focus_state_seat_destroy(struct wl_listener *listener, void *data) { struct focus_state *state = container_of(listener, struct focus_state, seat_destroy_listener); wl_list_remove(&state->link); focus_state_destroy(state); } static void focus_state_surface_destroy(struct wl_listener *listener, void *data) { struct focus_state *state = container_of(listener, struct focus_state, surface_destroy_listener); struct weston_surface *main_surface; struct weston_view *next; struct weston_view *view; main_surface = weston_surface_get_main_surface(state->keyboard_focus); next = NULL; wl_list_for_each(view, &state->ws->layer.view_list.link, layer_link.link) { if (view->surface == main_surface) continue; if (is_focus_view(view)) continue; if (!get_shell_surface(view->surface)) continue; next = view; break; } /* if the focus was a sub-surface, activate its main surface */ if (main_surface != state->keyboard_focus) next = get_default_view(main_surface); if (next) { if (state->keyboard_focus) { wl_list_remove(&state->surface_destroy_listener.link); wl_list_init(&state->surface_destroy_listener.link); } state->keyboard_focus = NULL; activate(state->shell, next, state->seat, WESTON_ACTIVATE_FLAG_CONFIGURE); } else { if (state->shell->focus_animation_type == ANIMATION_DIM_LAYER) { if (state->ws->focus_animation) weston_view_animation_destroy(state->ws->focus_animation); state->ws->focus_animation = weston_fade_run( state->ws->fsurf_front->view, state->ws->fsurf_front->view->alpha, 0.0, 300, focus_animation_done, state->ws); } wl_list_remove(&state->link); focus_state_destroy(state); } } static struct focus_state * focus_state_create(struct desktop_shell *shell, struct weston_seat *seat, struct workspace *ws) { struct focus_state *state; state = malloc(sizeof *state); if (state == NULL) return NULL; state->shell = shell; state->keyboard_focus = NULL; state->ws = ws; state->seat = seat; wl_list_insert(&ws->focus_list, &state->link); state->seat_destroy_listener.notify = focus_state_seat_destroy; state->surface_destroy_listener.notify = focus_state_surface_destroy; wl_signal_add(&seat->destroy_signal, &state->seat_destroy_listener); wl_list_init(&state->surface_destroy_listener.link); return state; } static struct focus_state * ensure_focus_state(struct desktop_shell *shell, struct weston_seat *seat) { struct workspace *ws = get_current_workspace(shell); struct focus_state *state; wl_list_for_each(state, &ws->focus_list, link) if (state->seat == seat) break; if (&state->link == &ws->focus_list) state = focus_state_create(shell, seat, ws); return state; } static void focus_state_set_focus(struct focus_state *state, struct weston_surface *surface) { if (state->keyboard_focus) { wl_list_remove(&state->surface_destroy_listener.link); wl_list_init(&state->surface_destroy_listener.link); } state->keyboard_focus = surface; if (surface) wl_signal_add(&surface->destroy_signal, &state->surface_destroy_listener); } static void restore_focus_state(struct desktop_shell *shell, struct workspace *ws) { struct focus_state *state, *next; struct weston_surface *surface; struct wl_list pending_seat_list; struct weston_seat *seat, *next_seat; /* Temporarily steal the list of seats so that we can keep * track of the seats we've already processed */ wl_list_init(&pending_seat_list); wl_list_insert_list(&pending_seat_list, &shell->compositor->seat_list); wl_list_init(&shell->compositor->seat_list); wl_list_for_each_safe(state, next, &ws->focus_list, link) { struct weston_keyboard *keyboard = weston_seat_get_keyboard(state->seat); wl_list_remove(&state->seat->link); wl_list_insert(&shell->compositor->seat_list, &state->seat->link); if (!keyboard) continue; surface = state->keyboard_focus; weston_keyboard_set_focus(keyboard, surface); } /* For any remaining seats that we don't have a focus state * for we'll reset the keyboard focus to NULL */ wl_list_for_each_safe(seat, next_seat, &pending_seat_list, link) { struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat); wl_list_insert(&shell->compositor->seat_list, &seat->link); if (!keyboard) continue; weston_keyboard_set_focus(keyboard, NULL); } } static void replace_focus_state(struct desktop_shell *shell, struct workspace *ws, struct weston_seat *seat) { struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat); struct focus_state *state; wl_list_for_each(state, &ws->focus_list, link) { if (state->seat == seat) { focus_state_set_focus(state, keyboard->focus); return; } } } static void drop_focus_state(struct desktop_shell *shell, struct workspace *ws, struct weston_surface *surface) { struct focus_state *state; wl_list_for_each(state, &ws->focus_list, link) if (state->keyboard_focus == surface) focus_state_set_focus(state, NULL); } static void animate_focus_change(struct desktop_shell *shell, struct workspace *ws, struct weston_view *from, struct weston_view *to) { struct weston_output *output; bool focus_surface_created = false; /* FIXME: Only support dim animation using two layers */ if (from == to || shell->focus_animation_type != ANIMATION_DIM_LAYER) return; output = get_default_output(shell->compositor); if (ws->fsurf_front == NULL && (from || to)) { ws->fsurf_front = create_focus_surface(shell->compositor, output); if (ws->fsurf_front == NULL) return; ws->fsurf_front->view->alpha = 0.0; ws->fsurf_back = create_focus_surface(shell->compositor, output); if (ws->fsurf_back == NULL) { focus_surface_destroy(ws->fsurf_front); return; } ws->fsurf_back->view->alpha = 0.0; focus_surface_created = true; } else { weston_layer_entry_remove(&ws->fsurf_front->view->layer_link); weston_layer_entry_remove(&ws->fsurf_back->view->layer_link); } if (ws->focus_animation) { weston_view_animation_destroy(ws->focus_animation); ws->focus_animation = NULL; } if (to) weston_layer_entry_insert(&to->layer_link, &ws->fsurf_front->view->layer_link); else if (from) weston_layer_entry_insert(&ws->layer.view_list, &ws->fsurf_front->view->layer_link); if (focus_surface_created) { ws->focus_animation = weston_fade_run( ws->fsurf_front->view, ws->fsurf_front->view->alpha, 0.4, 300, focus_animation_done, ws); } else if (from) { weston_layer_entry_insert(&from->layer_link, &ws->fsurf_back->view->layer_link); ws->focus_animation = weston_stable_fade_run( ws->fsurf_front->view, 0.0, ws->fsurf_back->view, 0.4, focus_animation_done, ws); } else if (to) { weston_layer_entry_insert(&ws->layer.view_list, &ws->fsurf_back->view->layer_link); ws->focus_animation = weston_stable_fade_run( ws->fsurf_front->view, 0.0, ws->fsurf_back->view, 0.4, focus_animation_done, ws); } } static void workspace_destroy(struct workspace *ws) { struct focus_state *state, *next; wl_list_for_each_safe(state, next, &ws->focus_list, link) focus_state_destroy(state); if (ws->fsurf_front) focus_surface_destroy(ws->fsurf_front); if (ws->fsurf_back) focus_surface_destroy(ws->fsurf_back); free(ws); } static void seat_destroyed(struct wl_listener *listener, void *data) { struct weston_seat *seat = data; struct focus_state *state, *next; struct workspace *ws = container_of(listener, struct workspace, seat_destroyed_listener); wl_list_for_each_safe(state, next, &ws->focus_list, link) if (state->seat == seat) wl_list_remove(&state->link); } static struct workspace * workspace_create(struct desktop_shell *shell) { struct workspace *ws = malloc(sizeof *ws); if (ws == NULL) return NULL; weston_layer_init(&ws->layer, shell->compositor); wl_list_init(&ws->focus_list); wl_list_init(&ws->seat_destroyed_listener.link); ws->seat_destroyed_listener.notify = seat_destroyed; ws->fsurf_front = NULL; ws->fsurf_back = NULL; ws->focus_animation = NULL; return ws; } static int workspace_is_empty(struct workspace *ws) { return wl_list_empty(&ws->layer.view_list.link); } static struct workspace * get_workspace(struct desktop_shell *shell, unsigned int index) { struct workspace **pws = shell->workspaces.array.data; assert(index < shell->workspaces.num); pws += index; return *pws; } struct workspace * get_current_workspace(struct desktop_shell *shell) { return get_workspace(shell, shell->workspaces.current); } static void activate_workspace(struct desktop_shell *shell, unsigned int index) { struct workspace *ws; ws = get_workspace(shell, index); weston_layer_set_position(&ws->layer, WESTON_LAYER_POSITION_NORMAL); shell->workspaces.current = index; } static unsigned int get_output_height(struct weston_output *output) { return abs(output->region.extents.y1 - output->region.extents.y2); } static struct weston_transform * view_get_transform(struct weston_view *view) { struct focus_surface *fsurf = NULL; struct shell_surface *shsurf = NULL; if (is_focus_view(view)) { fsurf = get_focus_surface(view->surface); return &fsurf->workspace_transform; } shsurf = get_shell_surface(view->surface); if (shsurf) return &shsurf->workspace_transform; return NULL; } static void view_translate(struct workspace *ws, struct weston_view *view, double d) { struct weston_transform *transform = view_get_transform(view); if (!transform) return; if (wl_list_empty(&transform->link)) wl_list_insert(view->geometry.transformation_list.prev, &transform->link); weston_matrix_init(&transform->matrix); weston_matrix_translate(&transform->matrix, 0.0, d, 0.0); weston_view_geometry_dirty(view); } static void workspace_translate_out(struct workspace *ws, double fraction) { struct weston_view *view; unsigned int height; double d; wl_list_for_each(view, &ws->layer.view_list.link, layer_link.link) { height = get_output_height(view->surface->output); d = height * fraction; view_translate(ws, view, d); } } static void workspace_translate_in(struct workspace *ws, double fraction) { struct weston_view *view; unsigned int height; double d; wl_list_for_each(view, &ws->layer.view_list.link, layer_link.link) { height = get_output_height(view->surface->output); if (fraction > 0) d = -(height - height * fraction); else d = height + height * fraction; view_translate(ws, view, d); } } static void reverse_workspace_change_animation(struct desktop_shell *shell, unsigned int index, struct workspace *from, struct workspace *to) { shell->workspaces.current = index; shell->workspaces.anim_to = to; shell->workspaces.anim_from = from; shell->workspaces.anim_dir = -1 * shell->workspaces.anim_dir; shell->workspaces.anim_timestamp = (struct timespec) { 0 }; weston_layer_set_position(&to->layer, WESTON_LAYER_POSITION_NORMAL); weston_layer_set_position(&from->layer, WESTON_LAYER_POSITION_NORMAL - 1); weston_compositor_schedule_repaint(shell->compositor); } static void workspace_deactivate_transforms(struct workspace *ws) { struct weston_view *view; struct weston_transform *transform; wl_list_for_each(view, &ws->layer.view_list.link, layer_link.link) { transform = view_get_transform(view); if (!transform) continue; if (!wl_list_empty(&transform->link)) { wl_list_remove(&transform->link); wl_list_init(&transform->link); } weston_view_geometry_dirty(view); } } static void finish_workspace_change_animation(struct desktop_shell *shell, struct workspace *from, struct workspace *to) { struct weston_view *view; weston_compositor_schedule_repaint(shell->compositor); /* Views that extend past the bottom of the output are still * visible after the workspace animation ends but before its layer * is hidden. In that case, we need to damage below those views so * that the screen is properly repainted. */ wl_list_for_each(view, &from->layer.view_list.link, layer_link.link) weston_view_damage_below(view); wl_list_remove(&shell->workspaces.animation.link); workspace_deactivate_transforms(from); workspace_deactivate_transforms(to); shell->workspaces.anim_to = NULL; weston_layer_unset_position(&shell->workspaces.anim_from->layer); } static void animate_workspace_change_frame(struct weston_animation *animation, struct weston_output *output, const struct timespec *time) { struct desktop_shell *shell = container_of(animation, struct desktop_shell, workspaces.animation); struct workspace *from = shell->workspaces.anim_from; struct workspace *to = shell->workspaces.anim_to; int64_t t; double x, y; if (workspace_is_empty(from) && workspace_is_empty(to)) { finish_workspace_change_animation(shell, from, to); return; } if (timespec_is_zero(&shell->workspaces.anim_timestamp)) { if (shell->workspaces.anim_current == 0.0) shell->workspaces.anim_timestamp = *time; else timespec_add_msec(&shell->workspaces.anim_timestamp, time, /* Inverse of movement function 'y' below. */ -(asin(1.0 - shell->workspaces.anim_current) * DEFAULT_WORKSPACE_CHANGE_ANIMATION_LENGTH * M_2_PI)); } t = timespec_sub_to_msec(time, &shell->workspaces.anim_timestamp); /* * x = [0, π/2] * y(x) = sin(x) */ x = t * (1.0/DEFAULT_WORKSPACE_CHANGE_ANIMATION_LENGTH) * M_PI_2; y = sin(x); if (t < DEFAULT_WORKSPACE_CHANGE_ANIMATION_LENGTH) { weston_compositor_schedule_repaint(shell->compositor); workspace_translate_out(from, shell->workspaces.anim_dir * y); workspace_translate_in(to, shell->workspaces.anim_dir * y); shell->workspaces.anim_current = y; weston_compositor_schedule_repaint(shell->compositor); } else finish_workspace_change_animation(shell, from, to); } static void animate_workspace_change(struct desktop_shell *shell, unsigned int index, struct workspace *from, struct workspace *to) { struct weston_output *output; int dir; if (index > shell->workspaces.current) dir = -1; else dir = 1; shell->workspaces.current = index; shell->workspaces.anim_dir = dir; shell->workspaces.anim_from = from; shell->workspaces.anim_to = to; shell->workspaces.anim_current = 0.0; shell->workspaces.anim_timestamp = (struct timespec) { 0 }; output = container_of(shell->compositor->output_list.next, struct weston_output, link); wl_list_insert(&output->animation_list, &shell->workspaces.animation.link); weston_layer_set_position(&to->layer, WESTON_LAYER_POSITION_NORMAL); weston_layer_set_position(&from->layer, WESTON_LAYER_POSITION_NORMAL - 1); workspace_translate_in(to, 0); restore_focus_state(shell, to); weston_compositor_schedule_repaint(shell->compositor); } static void update_workspace(struct desktop_shell *shell, unsigned int index, struct workspace *from, struct workspace *to) { shell->workspaces.current = index; weston_layer_set_position(&to->layer, WESTON_LAYER_POSITION_NORMAL); weston_layer_unset_position(&from->layer); } static void change_workspace(struct desktop_shell *shell, unsigned int index) { struct workspace *from; struct workspace *to; struct focus_state *state; if (index == shell->workspaces.current) return; /* Don't change workspace when there is any fullscreen surfaces. */ if (!wl_list_empty(&shell->fullscreen_layer.view_list.link)) return; from = get_current_workspace(shell); to = get_workspace(shell, index); if (shell->workspaces.anim_from == to && shell->workspaces.anim_to == from) { restore_focus_state(shell, to); reverse_workspace_change_animation(shell, index, from, to); return; } if (shell->workspaces.anim_to != NULL) finish_workspace_change_animation(shell, shell->workspaces.anim_from, shell->workspaces.anim_to); restore_focus_state(shell, to); if (shell->focus_animation_type != ANIMATION_NONE) { wl_list_for_each(state, &from->focus_list, link) if (state->keyboard_focus) animate_focus_change(shell, from, get_default_view(state->keyboard_focus), NULL); wl_list_for_each(state, &to->focus_list, link) if (state->keyboard_focus) animate_focus_change(shell, to, NULL, get_default_view(state->keyboard_focus)); } if (workspace_is_empty(to) && workspace_is_empty(from)) update_workspace(shell, index, from, to); else animate_workspace_change(shell, index, from, to); } static bool workspace_has_only(struct workspace *ws, struct weston_surface *surface) { struct wl_list *list = &ws->layer.view_list.link; struct wl_list *e; if (wl_list_empty(list)) return false; e = list->next; if (e->next != list) return false; return container_of(e, struct weston_view, layer_link.link)->surface == surface; } static void surface_keyboard_focus_lost(struct weston_surface *surface) { struct weston_compositor *compositor = surface->compositor; struct weston_seat *seat; struct weston_surface *focus; wl_list_for_each(seat, &compositor->seat_list, link) { struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat); if (!keyboard) continue; focus = weston_surface_get_main_surface(keyboard->focus); if (focus == surface) weston_keyboard_set_focus(keyboard, NULL); } } static void take_surface_to_workspace_by_seat(struct desktop_shell *shell, struct weston_seat *seat, unsigned int index) { struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat); struct weston_surface *surface; struct weston_view *view; struct shell_surface *shsurf; struct workspace *from; struct workspace *to; struct focus_state *state; surface = weston_surface_get_main_surface(keyboard->focus); view = get_default_view(surface); if (view == NULL || index == shell->workspaces.current || is_focus_view(view)) return; from = get_current_workspace(shell); to = get_workspace(shell, index); weston_layer_entry_remove(&view->layer_link); weston_layer_entry_insert(&to->layer.view_list, &view->layer_link); shsurf = get_shell_surface(surface); if (shsurf != NULL) shell_surface_update_child_surface_layers(shsurf); replace_focus_state(shell, to, seat); drop_focus_state(shell, from, surface); if (shell->workspaces.anim_from == to && shell->workspaces.anim_to == from) { reverse_workspace_change_animation(shell, index, from, to); return; } if (shell->workspaces.anim_to != NULL) finish_workspace_change_animation(shell, shell->workspaces.anim_from, shell->workspaces.anim_to); if (workspace_is_empty(from) && workspace_has_only(to, surface)) update_workspace(shell, index, from, to); else { if (shsurf != NULL && wl_list_empty(&shsurf->workspace_transform.link)) wl_list_insert(&shell->workspaces.anim_sticky_list, &shsurf->workspace_transform.link); animate_workspace_change(shell, index, from, to); } state = ensure_focus_state(shell, seat); if (state != NULL) focus_state_set_focus(state, surface); } static void touch_move_grab_down(struct weston_touch_grab *grab, const struct timespec *time, int touch_id, wl_fixed_t x, wl_fixed_t y) { } static void touch_move_grab_up(struct weston_touch_grab *grab, const struct timespec *time, int touch_id) { struct weston_touch_move_grab *move = (struct weston_touch_move_grab *) container_of( grab, struct shell_touch_grab, grab); if (touch_id == 0) move->active = 0; if (grab->touch->num_tp == 0) { shell_touch_grab_end(&move->base); free(move); } } static void touch_move_grab_motion(struct weston_touch_grab *grab, const struct timespec *time, int touch_id, wl_fixed_t x, wl_fixed_t y) { struct weston_touch_move_grab *move = (struct weston_touch_move_grab *) grab; struct shell_surface *shsurf = move->base.shsurf; struct weston_surface *es; int dx = wl_fixed_to_int(grab->touch->grab_x + move->dx); int dy = wl_fixed_to_int(grab->touch->grab_y + move->dy); if (!shsurf || !move->active) return; es = weston_desktop_surface_get_surface(shsurf->desktop_surface); weston_view_set_position(shsurf->view, dx, dy); weston_compositor_schedule_repaint(es->compositor); } static void touch_move_grab_frame(struct weston_touch_grab *grab) { } static void touch_move_grab_cancel(struct weston_touch_grab *grab) { struct weston_touch_move_grab *move = (struct weston_touch_move_grab *) container_of( grab, struct shell_touch_grab, grab); shell_touch_grab_end(&move->base); free(move); } static const struct weston_touch_grab_interface touch_move_grab_interface = { touch_move_grab_down, touch_move_grab_up, touch_move_grab_motion, touch_move_grab_frame, touch_move_grab_cancel, }; static int surface_touch_move(struct shell_surface *shsurf, struct weston_touch *touch) { struct weston_touch_move_grab *move; if (!shsurf) return -1; if (weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) || weston_desktop_surface_get_maximized(shsurf->desktop_surface)) return 0; move = malloc(sizeof *move); if (!move) return -1; move->active = 1; move->dx = wl_fixed_from_double(shsurf->view->geometry.x) - touch->grab_x; move->dy = wl_fixed_from_double(shsurf->view->geometry.y) - touch->grab_y; shell_touch_grab_start(&move->base, &touch_move_grab_interface, shsurf, touch); return 0; } static void noop_grab_focus(struct weston_pointer_grab *grab) { } static void noop_grab_axis(struct weston_pointer_grab *grab, const struct timespec *time, struct weston_pointer_axis_event *event) { } static void noop_grab_axis_source(struct weston_pointer_grab *grab, uint32_t source) { } static void noop_grab_frame(struct weston_pointer_grab *grab) { } static void constrain_position(struct weston_move_grab *move, int *cx, int *cy) { struct shell_surface *shsurf = move->base.shsurf; struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); struct weston_pointer *pointer = move->base.grab.pointer; int x, y, bottom; const int safety = 50; pixman_rectangle32_t area; struct weston_geometry geometry; x = wl_fixed_to_int(pointer->x + move->dx); y = wl_fixed_to_int(pointer->y + move->dy); if (shsurf->shell->panel_position == WESTON_DESKTOP_SHELL_PANEL_POSITION_TOP) { get_output_work_area(shsurf->shell, surface->output, &area); geometry = weston_desktop_surface_get_geometry(shsurf->desktop_surface); bottom = y + geometry.height + geometry.y; if (bottom - safety < area.y) y = area.y + safety - geometry.height - geometry.y; if (move->client_initiated && y + geometry.y < area.y) y = area.y - geometry.y; } *cx = x; *cy = y; } static void move_grab_motion(struct weston_pointer_grab *grab, const struct timespec *time, struct weston_pointer_motion_event *event) { struct weston_move_grab *move = (struct weston_move_grab *) grab; struct weston_pointer *pointer = grab->pointer; struct shell_surface *shsurf = move->base.shsurf; struct weston_surface *surface; int cx, cy; weston_pointer_move(pointer, event); if (!shsurf) return; surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); constrain_position(move, &cx, &cy); weston_view_set_position(shsurf->view, cx, cy); weston_compositor_schedule_repaint(surface->compositor); } static void move_grab_button(struct weston_pointer_grab *grab, const struct timespec *time, uint32_t button, uint32_t state_w) { struct shell_grab *shell_grab = container_of(grab, struct shell_grab, grab); struct weston_pointer *pointer = grab->pointer; enum wl_pointer_button_state state = state_w; if (pointer->button_count == 0 && state == WL_POINTER_BUTTON_STATE_RELEASED) { shell_grab_end(shell_grab); free(grab); } } static void move_grab_cancel(struct weston_pointer_grab *grab) { struct shell_grab *shell_grab = container_of(grab, struct shell_grab, grab); shell_grab_end(shell_grab); free(grab); } static const struct weston_pointer_grab_interface move_grab_interface = { noop_grab_focus, move_grab_motion, move_grab_button, noop_grab_axis, noop_grab_axis_source, noop_grab_frame, move_grab_cancel, }; static int surface_move(struct shell_surface *shsurf, struct weston_pointer *pointer, bool client_initiated) { struct weston_move_grab *move; if (!shsurf) return -1; if (shsurf->grabbed || weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) || weston_desktop_surface_get_maximized(shsurf->desktop_surface)) return 0; move = malloc(sizeof *move); if (!move) return -1; move->dx = wl_fixed_from_double(shsurf->view->geometry.x) - pointer->grab_x; move->dy = wl_fixed_from_double(shsurf->view->geometry.y) - pointer->grab_y; move->client_initiated = client_initiated; shell_grab_start(&move->base, &move_grab_interface, shsurf, pointer, WESTON_DESKTOP_SHELL_CURSOR_MOVE); return 0; } struct weston_resize_grab { struct shell_grab base; uint32_t edges; int32_t width, height; }; static void resize_grab_motion(struct weston_pointer_grab *grab, const struct timespec *time, struct weston_pointer_motion_event *event) { struct weston_resize_grab *resize = (struct weston_resize_grab *) grab; struct weston_pointer *pointer = grab->pointer; struct shell_surface *shsurf = resize->base.shsurf; int32_t width, height; struct weston_size min_size, max_size; wl_fixed_t from_x, from_y; wl_fixed_t to_x, to_y; weston_pointer_move(pointer, event); if (!shsurf) return; weston_view_from_global_fixed(shsurf->view, pointer->grab_x, pointer->grab_y, &from_x, &from_y); weston_view_from_global_fixed(shsurf->view, pointer->x, pointer->y, &to_x, &to_y); width = resize->width; if (resize->edges & WL_SHELL_SURFACE_RESIZE_LEFT) { width += wl_fixed_to_int(from_x - to_x); } else if (resize->edges & WL_SHELL_SURFACE_RESIZE_RIGHT) { width += wl_fixed_to_int(to_x - from_x); } height = resize->height; if (resize->edges & WL_SHELL_SURFACE_RESIZE_TOP) { height += wl_fixed_to_int(from_y - to_y); } else if (resize->edges & WL_SHELL_SURFACE_RESIZE_BOTTOM) { height += wl_fixed_to_int(to_y - from_y); } max_size = weston_desktop_surface_get_max_size(shsurf->desktop_surface); min_size = weston_desktop_surface_get_min_size(shsurf->desktop_surface); min_size.width = MAX(1, min_size.width); min_size.height = MAX(1, min_size.height); if (width < min_size.width) width = min_size.width; else if (max_size.width > 0 && width > max_size.width) width = max_size.width; if (height < min_size.height) height = min_size.height; else if (max_size.width > 0 && width > max_size.width) width = max_size.width; weston_desktop_surface_set_size(shsurf->desktop_surface, width, height); } static void resize_grab_button(struct weston_pointer_grab *grab, const struct timespec *time, uint32_t button, uint32_t state_w) { struct weston_resize_grab *resize = (struct weston_resize_grab *) grab; struct weston_pointer *pointer = grab->pointer; enum wl_pointer_button_state state = state_w; if (pointer->button_count == 0 && state == WL_POINTER_BUTTON_STATE_RELEASED) { if (resize->base.shsurf != NULL) { struct weston_desktop_surface *desktop_surface = resize->base.shsurf->desktop_surface; weston_desktop_surface_set_resizing(desktop_surface, false); } shell_grab_end(&resize->base); free(grab); } } static void resize_grab_cancel(struct weston_pointer_grab *grab) { struct weston_resize_grab *resize = (struct weston_resize_grab *) grab; if (resize->base.shsurf != NULL) { struct weston_desktop_surface *desktop_surface = resize->base.shsurf->desktop_surface; weston_desktop_surface_set_resizing(desktop_surface, false); } shell_grab_end(&resize->base); free(grab); } static const struct weston_pointer_grab_interface resize_grab_interface = { noop_grab_focus, resize_grab_motion, resize_grab_button, noop_grab_axis, noop_grab_axis_source, noop_grab_frame, resize_grab_cancel, }; /* * Returns the bounding box of a surface and all its sub-surfaces, * in surface-local coordinates. */ static void surface_subsurfaces_boundingbox(struct weston_surface *surface, int32_t *x, int32_t *y, int32_t *w, int32_t *h) { pixman_region32_t region; pixman_box32_t *box; struct weston_subsurface *subsurface; pixman_region32_init_rect(&region, 0, 0, surface->width, surface->height); wl_list_for_each(subsurface, &surface->subsurface_list, parent_link) { pixman_region32_union_rect(&region, &region, subsurface->position.x, subsurface->position.y, subsurface->surface->width, subsurface->surface->height); } box = pixman_region32_extents(&region); if (x) *x = box->x1; if (y) *y = box->y1; if (w) *w = box->x2 - box->x1; if (h) *h = box->y2 - box->y1; pixman_region32_fini(&region); } static int surface_resize(struct shell_surface *shsurf, struct weston_pointer *pointer, uint32_t edges) { struct weston_resize_grab *resize; const unsigned resize_topbottom = WL_SHELL_SURFACE_RESIZE_TOP | WL_SHELL_SURFACE_RESIZE_BOTTOM; const unsigned resize_leftright = WL_SHELL_SURFACE_RESIZE_LEFT | WL_SHELL_SURFACE_RESIZE_RIGHT; const unsigned resize_any = resize_topbottom | resize_leftright; struct weston_geometry geometry; if (shsurf->grabbed || weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) || weston_desktop_surface_get_maximized(shsurf->desktop_surface)) return 0; /* Check for invalid edge combinations. */ if (edges == WL_SHELL_SURFACE_RESIZE_NONE || edges > resize_any || (edges & resize_topbottom) == resize_topbottom || (edges & resize_leftright) == resize_leftright) return 0; resize = malloc(sizeof *resize); if (!resize) return -1; resize->edges = edges; geometry = weston_desktop_surface_get_geometry(shsurf->desktop_surface); resize->width = geometry.width; resize->height = geometry.height; shsurf->resize_edges = edges; weston_desktop_surface_set_resizing(shsurf->desktop_surface, true); shell_grab_start(&resize->base, &resize_grab_interface, shsurf, pointer, edges); return 0; } static void busy_cursor_grab_focus(struct weston_pointer_grab *base) { struct shell_grab *grab = (struct shell_grab *) base; struct weston_pointer *pointer = base->pointer; struct weston_desktop_surface *desktop_surface; struct weston_view *view; wl_fixed_t sx, sy; view = weston_compositor_pick_view(pointer->seat->compositor, pointer->x, pointer->y, &sx, &sy); desktop_surface = weston_surface_get_desktop_surface(view->surface); if (!grab->shsurf || grab->shsurf->desktop_surface != desktop_surface) { shell_grab_end(grab); free(grab); } } static void busy_cursor_grab_motion(struct weston_pointer_grab *grab, const struct timespec *time, struct weston_pointer_motion_event *event) { weston_pointer_move(grab->pointer, event); } static void busy_cursor_grab_button(struct weston_pointer_grab *base, const struct timespec *time, uint32_t button, uint32_t state) { struct shell_grab *grab = (struct shell_grab *) base; struct shell_surface *shsurf = grab->shsurf; struct weston_pointer *pointer = grab->grab.pointer; struct weston_seat *seat = pointer->seat; if (shsurf && button == BTN_LEFT && state) { activate(shsurf->shell, shsurf->view, seat, WESTON_ACTIVATE_FLAG_CONFIGURE); surface_move(shsurf, pointer, false); } else if (shsurf && button == BTN_RIGHT && state) { activate(shsurf->shell, shsurf->view, seat, WESTON_ACTIVATE_FLAG_CONFIGURE); surface_rotate(shsurf, pointer); } } static void busy_cursor_grab_cancel(struct weston_pointer_grab *base) { struct shell_grab *grab = (struct shell_grab *) base; shell_grab_end(grab); free(grab); } static const struct weston_pointer_grab_interface busy_cursor_grab_interface = { busy_cursor_grab_focus, busy_cursor_grab_motion, busy_cursor_grab_button, noop_grab_axis, noop_grab_axis_source, noop_grab_frame, busy_cursor_grab_cancel, }; static void handle_pointer_focus(struct wl_listener *listener, void *data) { struct weston_pointer *pointer = data; struct weston_view *view = pointer->focus; struct shell_surface *shsurf; struct weston_desktop_client *client; if (!view) return; shsurf = get_shell_surface(view->surface); if (!shsurf) return; client = weston_desktop_surface_get_client(shsurf->desktop_surface); if (shsurf->unresponsive) set_busy_cursor(shsurf, pointer); else weston_desktop_client_ping(client); } static void shell_surface_lose_keyboard_focus(struct shell_surface *shsurf) { if (--shsurf->focus_count == 0) weston_desktop_surface_set_activated(shsurf->desktop_surface, false); } static void shell_surface_gain_keyboard_focus(struct shell_surface *shsurf) { if (shsurf->focus_count++ == 0) weston_desktop_surface_set_activated(shsurf->desktop_surface, true); } static void handle_keyboard_focus(struct wl_listener *listener, void *data) { struct weston_keyboard *keyboard = data; struct shell_seat *seat = get_shell_seat(keyboard->seat); if (seat->focused_surface) { struct shell_surface *shsurf = get_shell_surface(seat->focused_surface); if (shsurf) shell_surface_lose_keyboard_focus(shsurf); } seat->focused_surface = weston_surface_get_main_surface(keyboard->focus); if (seat->focused_surface) { struct shell_surface *shsurf = get_shell_surface(seat->focused_surface); if (shsurf) shell_surface_gain_keyboard_focus(shsurf); } } /* The surface will be inserted into the list immediately after the link * returned by this function (i.e. will be stacked immediately above the * returned link). */ static struct weston_layer_entry * shell_surface_calculate_layer_link (struct shell_surface *shsurf) { struct workspace *ws; if (weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) && !shsurf->state.lowered) { return &shsurf->shell->fullscreen_layer.view_list; } /* Move the surface to a normal workspace layer so that surfaces * which were previously fullscreen or transient are no longer * rendered on top. */ ws = get_current_workspace(shsurf->shell); return &ws->layer.view_list; } static void shell_surface_update_child_surface_layers (struct shell_surface *shsurf) { weston_desktop_surface_propagate_layer(shsurf->desktop_surface); } /* Update the surface’s layer. Mark both the old and new views as having dirty * geometry to ensure the changes are redrawn. * * If any child surfaces exist and are mapped, ensure they’re in the same layer * as this surface. */ static void shell_surface_update_layer(struct shell_surface *shsurf) { struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); struct weston_layer_entry *new_layer_link; new_layer_link = shell_surface_calculate_layer_link(shsurf); if (new_layer_link == NULL) return; if (new_layer_link == &shsurf->view->layer_link) return; weston_view_geometry_dirty(shsurf->view); weston_layer_entry_remove(&shsurf->view->layer_link); weston_layer_entry_insert(new_layer_link, &shsurf->view->layer_link); weston_view_geometry_dirty(shsurf->view); weston_surface_damage(surface); shell_surface_update_child_surface_layers(shsurf); } static void notify_output_destroy(struct wl_listener *listener, void *data) { struct shell_surface *shsurf = container_of(listener, struct shell_surface, output_destroy_listener); shsurf->output = NULL; shsurf->output_destroy_listener.notify = NULL; } static void shell_surface_set_output(struct shell_surface *shsurf, struct weston_output *output) { struct weston_surface *es = weston_desktop_surface_get_surface(shsurf->desktop_surface); /* get the default output, if the client set it as NULL check whether the output is available */ if (output) shsurf->output = output; else if (es->output) shsurf->output = es->output; else shsurf->output = get_default_output(es->compositor); if (shsurf->output_destroy_listener.notify) { wl_list_remove(&shsurf->output_destroy_listener.link); shsurf->output_destroy_listener.notify = NULL; } if (!shsurf->output) return; shsurf->output_destroy_listener.notify = notify_output_destroy; wl_signal_add(&shsurf->output->destroy_signal, &shsurf->output_destroy_listener); } static void weston_view_set_initial_position(struct weston_view *view, struct desktop_shell *shell); static void unset_fullscreen(struct shell_surface *shsurf) { /* Unset the fullscreen output, driver configuration and transforms. */ wl_list_remove(&shsurf->fullscreen.transform.link); wl_list_init(&shsurf->fullscreen.transform.link); if (shsurf->fullscreen.black_view) weston_surface_destroy(shsurf->fullscreen.black_view->surface); shsurf->fullscreen.black_view = NULL; if (shsurf->saved_position_valid) weston_view_set_position(shsurf->view, shsurf->saved_x, shsurf->saved_y); else weston_view_set_initial_position(shsurf->view, shsurf->shell); shsurf->saved_position_valid = false; if (shsurf->saved_rotation_valid) { wl_list_insert(&shsurf->view->geometry.transformation_list, &shsurf->rotation.transform.link); shsurf->saved_rotation_valid = false; } } static void unset_maximized(struct shell_surface *shsurf) { struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); /* undo all maximized things here */ shell_surface_set_output(shsurf, get_default_output(surface->compositor)); if (shsurf->saved_position_valid) weston_view_set_position(shsurf->view, shsurf->saved_x, shsurf->saved_y); else weston_view_set_initial_position(shsurf->view, shsurf->shell); shsurf->saved_position_valid = false; if (shsurf->saved_rotation_valid) { wl_list_insert(&shsurf->view->geometry.transformation_list, &shsurf->rotation.transform.link); shsurf->saved_rotation_valid = false; } } static void set_minimized(struct weston_surface *surface) { struct shell_surface *shsurf; struct workspace *current_ws; struct weston_view *view; view = get_default_view(surface); if (!view) return; assert(weston_surface_get_main_surface(view->surface) == view->surface); shsurf = get_shell_surface(surface); current_ws = get_current_workspace(shsurf->shell); weston_layer_entry_remove(&view->layer_link); weston_layer_entry_insert(&shsurf->shell->minimized_layer.view_list, &view->layer_link); drop_focus_state(shsurf->shell, current_ws, view->surface); surface_keyboard_focus_lost(surface); shell_surface_update_child_surface_layers(shsurf); weston_view_damage_below(view); } static struct desktop_shell * shell_surface_get_shell(struct shell_surface *shsurf) { return shsurf->shell; } static int black_surface_get_label(struct weston_surface *surface, char *buf, size_t len) { struct weston_view *fs_view = surface->committed_private; struct weston_surface *fs_surface = fs_view->surface; int n; int rem; int ret; n = snprintf(buf, len, "black background surface for "); if (n < 0) return n; rem = (int)len - n; if (rem < 0) rem = 0; if (fs_surface->get_label) ret = fs_surface->get_label(fs_surface, buf + n, rem); else ret = snprintf(buf + n, rem, "<unknown>"); if (ret < 0) return n; return n + ret; } static void black_surface_committed(struct weston_surface *es, int32_t sx, int32_t sy); static struct weston_view * create_black_surface(struct weston_compositor *ec, struct weston_view *fs_view, float x, float y, int w, int h) { struct weston_surface *surface = NULL; struct weston_view *view; surface = weston_surface_create(ec); if (surface == NULL) { weston_log("no memory\n"); return NULL; } view = weston_view_create(surface); if (surface == NULL) { weston_log("no memory\n"); weston_surface_destroy(surface); return NULL; } surface->committed = black_surface_committed; surface->committed_private = fs_view; weston_surface_set_label_func(surface, black_surface_get_label); weston_surface_set_color(surface, 0.0, 0.0, 0.0, 1); pixman_region32_fini(&surface->opaque); pixman_region32_init_rect(&surface->opaque, 0, 0, w, h); pixman_region32_fini(&surface->input); pixman_region32_init_rect(&surface->input, 0, 0, w, h); weston_surface_set_size(surface, w, h); weston_view_set_position(view, x, y); return view; } static void shell_ensure_fullscreen_black_view(struct shell_surface *shsurf) { struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); struct weston_output *output = shsurf->fullscreen_output; assert(weston_desktop_surface_get_fullscreen(shsurf->desktop_surface)); if (!shsurf->fullscreen.black_view) shsurf->fullscreen.black_view = create_black_surface(surface->compositor, shsurf->view, output->x, output->y, output->width, output->height); weston_view_geometry_dirty(shsurf->fullscreen.black_view); weston_layer_entry_remove(&shsurf->fullscreen.black_view->layer_link); weston_layer_entry_insert(&shsurf->view->layer_link, &shsurf->fullscreen.black_view->layer_link); weston_view_geometry_dirty(shsurf->fullscreen.black_view); weston_surface_damage(surface); shsurf->fullscreen.black_view->is_mapped = true; shsurf->state.lowered = false; } /* Create black surface and append it to the associated fullscreen surface. * Handle size dismatch and positioning according to the method. */ static void shell_configure_fullscreen(struct shell_surface *shsurf) { struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); int32_t surf_x, surf_y, surf_width, surf_height; /* Reverse the effect of lower_fullscreen_layer() */ weston_layer_entry_remove(&shsurf->view->layer_link); weston_layer_entry_insert(&shsurf->shell->fullscreen_layer.view_list, &shsurf->view->layer_link); if (!shsurf->fullscreen_output) { /* If there is no output, there's not much we can do. * Position the window somewhere, whatever. */ weston_view_set_position(shsurf->view, 0, 0); return; } shell_ensure_fullscreen_black_view(shsurf); surface_subsurfaces_boundingbox(surface, &surf_x, &surf_y, &surf_width, &surf_height); if (surface->buffer_ref.buffer) center_on_output(shsurf->view, shsurf->fullscreen_output); } static void shell_map_fullscreen(struct shell_surface *shsurf) { shell_configure_fullscreen(shsurf); } static struct weston_output * get_focused_output(struct weston_compositor *compositor) { struct weston_seat *seat; struct weston_output *output = NULL; wl_list_for_each(seat, &compositor->seat_list, link) { struct weston_touch *touch = weston_seat_get_touch(seat); struct weston_pointer *pointer = weston_seat_get_pointer(seat); struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat); /* Priority has touch focus, then pointer and * then keyboard focus. We should probably have * three for loops and check first for touch, * then for pointer, etc. but unless somebody has some * objections, I think this is sufficient. */ if (touch && touch->focus) output = touch->focus->output; else if (pointer && pointer->focus) output = pointer->focus->output; else if (keyboard && keyboard->focus) output = keyboard->focus->output; if (output) break; } return output; } static void destroy_shell_seat(struct wl_listener *listener, void *data) { struct shell_seat *shseat = container_of(listener, struct shell_seat, seat_destroy_listener); wl_list_remove(&shseat->seat_destroy_listener.link); free(shseat); } static void shell_seat_caps_changed(struct wl_listener *listener, void *data) { struct weston_keyboard *keyboard; struct weston_pointer *pointer; struct shell_seat *seat; seat = container_of(listener, struct shell_seat, caps_changed_listener); keyboard = weston_seat_get_keyboard(seat->seat); pointer = weston_seat_get_pointer(seat->seat); if (keyboard && wl_list_empty(&seat->keyboard_focus_listener.link)) { wl_signal_add(&keyboard->focus_signal, &seat->keyboard_focus_listener); } else if (!keyboard) { wl_list_remove(&seat->keyboard_focus_listener.link); wl_list_init(&seat->keyboard_focus_listener.link); } if (pointer && wl_list_empty(&seat->pointer_focus_listener.link)) { wl_signal_add(&pointer->focus_signal, &seat->pointer_focus_listener); } else if (!pointer) { wl_list_remove(&seat->pointer_focus_listener.link); wl_list_init(&seat->pointer_focus_listener.link); } } static struct shell_seat * create_shell_seat(struct weston_seat *seat) { struct shell_seat *shseat; shseat = calloc(1, sizeof *shseat); if (!shseat) { weston_log("no memory to allocate shell seat\n"); return NULL; } shseat->seat = seat; shseat->seat_destroy_listener.notify = destroy_shell_seat; wl_signal_add(&seat->destroy_signal, &shseat->seat_destroy_listener); shseat->keyboard_focus_listener.notify = handle_keyboard_focus; wl_list_init(&shseat->keyboard_focus_listener.link); shseat->pointer_focus_listener.notify = handle_pointer_focus; wl_list_init(&shseat->pointer_focus_listener.link); shseat->caps_changed_listener.notify = shell_seat_caps_changed; wl_signal_add(&seat->updated_caps_signal, &shseat->caps_changed_listener); shell_seat_caps_changed(&shseat->caps_changed_listener, NULL); return shseat; } static struct shell_seat * get_shell_seat(struct weston_seat *seat) { struct wl_listener *listener; listener = wl_signal_get(&seat->destroy_signal, destroy_shell_seat); assert(listener != NULL); return container_of(listener, struct shell_seat, seat_destroy_listener); } static void fade_out_done_idle_cb(void *data) { struct shell_surface *shsurf = data; weston_surface_destroy(shsurf->view->surface); if (shsurf->output_destroy_listener.notify) { wl_list_remove(&shsurf->output_destroy_listener.link); shsurf->output_destroy_listener.notify = NULL; } free(shsurf); } static void fade_out_done(struct weston_view_animation *animation, void *data) { struct shell_surface *shsurf = data; struct wl_event_loop *loop; loop = wl_display_get_event_loop(shsurf->shell->compositor->wl_display); if (weston_view_is_mapped(shsurf->view)) { weston_view_unmap(shsurf->view); wl_event_loop_add_idle(loop, fade_out_done_idle_cb, shsurf); } } struct shell_surface * get_shell_surface(struct weston_surface *surface) { if (weston_surface_is_desktop_surface(surface)) { struct weston_desktop_surface *desktop_surface = weston_surface_get_desktop_surface(surface); return weston_desktop_surface_get_user_data(desktop_surface); } return NULL; } /* * libweston-desktop */ static void desktop_surface_added(struct weston_desktop_surface *desktop_surface, void *shell) { struct weston_desktop_client *client = weston_desktop_surface_get_client(desktop_surface); struct wl_client *wl_client = weston_desktop_client_get_client(client); struct weston_view *view; struct shell_surface *shsurf; struct weston_surface *surface = weston_desktop_surface_get_surface(desktop_surface); view = weston_desktop_surface_create_view(desktop_surface); if (!view) return; shsurf = calloc(1, sizeof *shsurf); if (!shsurf) { if (wl_client) wl_client_post_no_memory(wl_client); else weston_log("no memory to allocate shell surface\n"); return; } weston_surface_set_label_func(surface, shell_surface_get_label); shsurf->shell = (struct desktop_shell *) shell; shsurf->unresponsive = 0; shsurf->saved_position_valid = false; shsurf->saved_rotation_valid = false; shsurf->desktop_surface = desktop_surface; shsurf->view = view; shsurf->fullscreen.black_view = NULL; wl_list_init(&shsurf->fullscreen.transform.link); shell_surface_set_output( shsurf, get_default_output(shsurf->shell->compositor)); wl_signal_init(&shsurf->destroy_signal); /* empty when not in use */ wl_list_init(&shsurf->rotation.transform.link); weston_matrix_init(&shsurf->rotation.rotation); wl_list_init(&shsurf->workspace_transform.link); weston_desktop_surface_set_user_data(desktop_surface, shsurf); weston_desktop_surface_set_activated(desktop_surface, shsurf->focus_count > 0); } static void desktop_surface_removed(struct weston_desktop_surface *desktop_surface, void *shell) { struct shell_surface *shsurf = weston_desktop_surface_get_user_data(desktop_surface); struct weston_surface *surface = weston_desktop_surface_get_surface(desktop_surface); if (!shsurf) return; wl_signal_emit(&shsurf->destroy_signal, shsurf); if (shsurf->fullscreen.black_view) weston_surface_destroy(shsurf->fullscreen.black_view->surface); weston_surface_set_label_func(surface, NULL); weston_desktop_surface_set_user_data(shsurf->desktop_surface, NULL); shsurf->desktop_surface = NULL; weston_desktop_surface_unlink_view(shsurf->view); if (weston_surface_is_mapped(surface) && shsurf->shell->win_close_animation_type == ANIMATION_FADE) { pixman_region32_fini(&surface->pending.input); pixman_region32_init(&surface->pending.input); pixman_region32_fini(&surface->input); pixman_region32_init(&surface->input); weston_fade_run(shsurf->view, 1.0, 0.0, 300.0, fade_out_done, shsurf); } else { weston_view_destroy(shsurf->view); if (shsurf->output_destroy_listener.notify) { wl_list_remove(&shsurf->output_destroy_listener.link); shsurf->output_destroy_listener.notify = NULL; } free(shsurf); } } static void set_maximized_position(struct desktop_shell *shell, struct shell_surface *shsurf) { pixman_rectangle32_t area; struct weston_geometry geometry; get_output_work_area(shell, shsurf->output, &area); geometry = weston_desktop_surface_get_geometry(shsurf->desktop_surface); weston_view_set_position(shsurf->view, area.x - geometry.x, area.y - geometry.y); } static void set_position_from_xwayland(struct shell_surface *shsurf) { struct weston_geometry geometry; float x; float y; assert(shsurf->xwayland.is_set); geometry = weston_desktop_surface_get_geometry(shsurf->desktop_surface); x = shsurf->xwayland.x - geometry.x; y = shsurf->xwayland.y - geometry.y; weston_view_set_position(shsurf->view, x, y); #ifdef WM_DEBUG weston_log("%s: XWM %d, %d; geometry %d, %d; view %f, %f\n", __func__, shsurf->xwayland.x, shsurf->xwayland.y, geometry.x, geometry.y, x, y); #endif } static void map(struct desktop_shell *shell, struct shell_surface *shsurf, int32_t sx, int32_t sy) { struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); struct weston_compositor *compositor = shell->compositor; struct weston_seat *seat; /* initial positioning, see also configure() */ if (shsurf->state.fullscreen) { center_on_output(shsurf->view, shsurf->fullscreen_output); shell_map_fullscreen(shsurf); } else if (shsurf->state.maximized) { set_maximized_position(shell, shsurf); } else if (shsurf->xwayland.is_set) { set_position_from_xwayland(shsurf); } else { weston_view_set_initial_position(shsurf->view, shell); } /* Surface stacking order, see also activate(). */ shell_surface_update_layer(shsurf); weston_view_update_transform(shsurf->view); shsurf->view->is_mapped = true; if (shsurf->state.maximized) { surface->output = shsurf->output; weston_view_set_output(shsurf->view, shsurf->output); } if (!shell->locked) { wl_list_for_each(seat, &compositor->seat_list, link) activate(shell, shsurf->view, seat, WESTON_ACTIVATE_FLAG_CONFIGURE); } if (!shsurf->state.fullscreen && !shsurf->state.maximized) { switch (shell->win_animation_type) { case ANIMATION_FADE: weston_fade_run(shsurf->view, 0.0, 1.0, 300.0, NULL, NULL); break; case ANIMATION_ZOOM: weston_zoom_run(shsurf->view, 0.5, 1.0, NULL, NULL); break; case ANIMATION_NONE: default: break; } } } static void desktop_surface_committed(struct weston_desktop_surface *desktop_surface, int32_t sx, int32_t sy, void *data) { struct shell_surface *shsurf = weston_desktop_surface_get_user_data(desktop_surface); struct weston_surface *surface = weston_desktop_surface_get_surface(desktop_surface); struct weston_view *view = shsurf->view; struct desktop_shell *shell = data; bool was_fullscreen; bool was_maximized; if (surface->width == 0) return; was_fullscreen = shsurf->state.fullscreen; was_maximized = shsurf->state.maximized; shsurf->state.fullscreen = weston_desktop_surface_get_fullscreen(desktop_surface); shsurf->state.maximized = weston_desktop_surface_get_maximized(desktop_surface); if (!weston_surface_is_mapped(surface)) { map(shell, shsurf, sx, sy); surface->is_mapped = true; if (shsurf->shell->win_close_animation_type == ANIMATION_FADE) ++surface->ref_count; return; } if (sx == 0 && sy == 0 && shsurf->last_width == surface->width && shsurf->last_height == surface->height && was_fullscreen == shsurf->state.fullscreen && was_maximized == shsurf->state.maximized) return; if (was_fullscreen) unset_fullscreen(shsurf); if (was_maximized) unset_maximized(shsurf); if ((shsurf->state.fullscreen || shsurf->state.maximized) && !shsurf->saved_position_valid) { shsurf->saved_x = shsurf->view->geometry.x; shsurf->saved_y = shsurf->view->geometry.y; shsurf->saved_position_valid = true; if (!wl_list_empty(&shsurf->rotation.transform.link)) { wl_list_remove(&shsurf->rotation.transform.link); wl_list_init(&shsurf->rotation.transform.link); weston_view_geometry_dirty(shsurf->view); shsurf->saved_rotation_valid = true; } } if (shsurf->state.fullscreen) { shell_configure_fullscreen(shsurf); } else if (shsurf->state.maximized) { set_maximized_position(shell, shsurf); surface->output = shsurf->output; } else { float from_x, from_y; float to_x, to_y; float x, y; if (shsurf->resize_edges) { sx = 0; sy = 0; } if (shsurf->resize_edges & WL_SHELL_SURFACE_RESIZE_LEFT) sx = shsurf->last_width - surface->width; if (shsurf->resize_edges & WL_SHELL_SURFACE_RESIZE_TOP) sy = shsurf->last_height - surface->height; weston_view_to_global_float(shsurf->view, 0, 0, &from_x, &from_y); weston_view_to_global_float(shsurf->view, sx, sy, &to_x, &to_y); x = shsurf->view->geometry.x + to_x - from_x; y = shsurf->view->geometry.y + to_y - from_y; weston_view_set_position(shsurf->view, x, y); } shsurf->last_width = surface->width; shsurf->last_height = surface->height; /* XXX: would a fullscreen surface need the same handling? */ if (surface->output) { wl_list_for_each(view, &surface->views, surface_link) weston_view_update_transform(view); } } static void get_maximized_size(struct shell_surface *shsurf, int32_t *width, int32_t *height) { struct desktop_shell *shell; pixman_rectangle32_t area; shell = shell_surface_get_shell(shsurf); get_output_work_area(shell, shsurf->output, &area); *width = area.width; *height = area.height; } static void set_fullscreen(struct shell_surface *shsurf, bool fullscreen, struct weston_output *output) { struct weston_desktop_surface *desktop_surface = shsurf->desktop_surface; struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); int32_t width = 0, height = 0; if (fullscreen) { /* handle clients launching in fullscreen */ if (output == NULL && !weston_surface_is_mapped(surface)) { /* Set the output to the one that has focus currently. */ output = get_focused_output(surface->compositor); } shell_surface_set_output(shsurf, output); shsurf->fullscreen_output = shsurf->output; width = shsurf->output->width; height = shsurf->output->height; } else if (weston_desktop_surface_get_maximized(desktop_surface)) { get_maximized_size(shsurf, &width, &height); } weston_desktop_surface_set_fullscreen(desktop_surface, fullscreen); weston_desktop_surface_set_size(desktop_surface, width, height); } static void desktop_surface_move(struct weston_desktop_surface *desktop_surface, struct weston_seat *seat, uint32_t serial, void *shell) { struct weston_pointer *pointer = weston_seat_get_pointer(seat); struct weston_touch *touch = weston_seat_get_touch(seat); struct shell_surface *shsurf = weston_desktop_surface_get_user_data(desktop_surface); struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); struct wl_resource *resource = surface->resource; struct weston_surface *focus; if (pointer && pointer->focus && pointer->button_count > 0 && pointer->grab_serial == serial) { focus = weston_surface_get_main_surface(pointer->focus->surface); if ((focus == surface) && (surface_move(shsurf, pointer, true) < 0)) wl_resource_post_no_memory(resource); } else if (touch && touch->focus && touch->grab_serial == serial) { focus = weston_surface_get_main_surface(touch->focus->surface); if ((focus == surface) && (surface_touch_move(shsurf, touch) < 0)) wl_resource_post_no_memory(resource); } } static void desktop_surface_resize(struct weston_desktop_surface *desktop_surface, struct weston_seat *seat, uint32_t serial, enum weston_desktop_surface_edge edges, void *shell) { struct weston_pointer *pointer = weston_seat_get_pointer(seat); struct shell_surface *shsurf = weston_desktop_surface_get_user_data(desktop_surface); struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); struct wl_resource *resource = surface->resource; struct weston_surface *focus; if (!pointer || pointer->button_count == 0 || pointer->grab_serial != serial || pointer->focus == NULL) return; focus = weston_surface_get_main_surface(pointer->focus->surface); if (focus != surface) return; if (surface_resize(shsurf, pointer, edges) < 0) wl_resource_post_no_memory(resource); } static void desktop_surface_fullscreen_requested(struct weston_desktop_surface *desktop_surface, bool fullscreen, struct weston_output *output, void *shell) { struct shell_surface *shsurf = weston_desktop_surface_get_user_data(desktop_surface); set_fullscreen(shsurf, fullscreen, output); } static void set_maximized(struct shell_surface *shsurf, bool maximized) { struct weston_desktop_surface *desktop_surface = shsurf->desktop_surface; struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); int32_t width = 0, height = 0; if (maximized) { struct weston_output *output; if (!weston_surface_is_mapped(surface)) output = get_focused_output(surface->compositor); else output = surface->output; shell_surface_set_output(shsurf, output); get_maximized_size(shsurf, &width, &height); } weston_desktop_surface_set_maximized(desktop_surface, maximized); weston_desktop_surface_set_size(desktop_surface, width, height); } static void desktop_surface_maximized_requested(struct weston_desktop_surface *desktop_surface, bool maximized, void *shell) { struct shell_surface *shsurf = weston_desktop_surface_get_user_data(desktop_surface); set_maximized(shsurf, maximized); } static void desktop_surface_minimized_requested(struct weston_desktop_surface *desktop_surface, void *shell) { struct weston_surface *surface = weston_desktop_surface_get_surface(desktop_surface); /* apply compositor's own minimization logic (hide) */ set_minimized(surface); } static void set_busy_cursor(struct shell_surface *shsurf, struct weston_pointer *pointer) { struct shell_grab *grab; if (pointer->grab->interface == &busy_cursor_grab_interface) return; grab = malloc(sizeof *grab); if (!grab) return; shell_grab_start(grab, &busy_cursor_grab_interface, shsurf, pointer, WESTON_DESKTOP_SHELL_CURSOR_BUSY); /* Mark the shsurf as ungrabbed so that button binding is able * to move it. */ shsurf->grabbed = 0; } static void end_busy_cursor(struct weston_compositor *compositor, struct weston_desktop_client *desktop_client) { struct shell_surface *shsurf; struct shell_grab *grab; struct weston_seat *seat; wl_list_for_each(seat, &compositor->seat_list, link) { struct weston_pointer *pointer = weston_seat_get_pointer(seat); struct weston_desktop_client *grab_client; if (!pointer) continue; if (pointer->grab->interface != &busy_cursor_grab_interface) continue; grab = (struct shell_grab *) pointer->grab; shsurf = grab->shsurf; if (!shsurf) continue; grab_client = weston_desktop_surface_get_client(shsurf->desktop_surface); if (grab_client == desktop_client) { shell_grab_end(grab); free(grab); } } } static void desktop_surface_set_unresponsive(struct weston_desktop_surface *desktop_surface, void *user_data) { struct shell_surface *shsurf = weston_desktop_surface_get_user_data(desktop_surface); bool *unresponsive = user_data; shsurf->unresponsive = *unresponsive; } static void desktop_surface_ping_timeout(struct weston_desktop_client *desktop_client, void *shell_) { struct desktop_shell *shell = shell_; struct shell_surface *shsurf; struct weston_seat *seat; bool unresponsive = true; weston_desktop_client_for_each_surface(desktop_client, desktop_surface_set_unresponsive, &unresponsive); wl_list_for_each(seat, &shell->compositor->seat_list, link) { struct weston_pointer *pointer = weston_seat_get_pointer(seat); struct weston_desktop_client *grab_client; if (!pointer || !pointer->focus) continue; shsurf = get_shell_surface(pointer->focus->surface); if (!shsurf) continue; grab_client = weston_desktop_surface_get_client(shsurf->desktop_surface); if (grab_client == desktop_client) set_busy_cursor(shsurf, pointer); } } static void desktop_surface_pong(struct weston_desktop_client *desktop_client, void *shell_) { struct desktop_shell *shell = shell_; bool unresponsive = false; weston_desktop_client_for_each_surface(desktop_client, desktop_surface_set_unresponsive, &unresponsive); end_busy_cursor(shell->compositor, desktop_client); } static void desktop_surface_set_xwayland_position(struct weston_desktop_surface *surface, int32_t x, int32_t y, void *shell_) { struct shell_surface *shsurf = weston_desktop_surface_get_user_data(surface); shsurf->xwayland.x = x; shsurf->xwayland.y = y; shsurf->xwayland.is_set = true; } static const struct weston_desktop_api shell_desktop_api = { .struct_size = sizeof(struct weston_desktop_api), .surface_added = desktop_surface_added, .surface_removed = desktop_surface_removed, .committed = desktop_surface_committed, .move = desktop_surface_move, .resize = desktop_surface_resize, .fullscreen_requested = desktop_surface_fullscreen_requested, .maximized_requested = desktop_surface_maximized_requested, .minimized_requested = desktop_surface_minimized_requested, .ping_timeout = desktop_surface_ping_timeout, .pong = desktop_surface_pong, .set_xwayland_position = desktop_surface_set_xwayland_position, }; /* ************************ * * end of libweston-desktop * * ************************ */ static void configure_static_view(struct weston_view *ev, struct weston_layer *layer, int x, int y) { struct weston_view *v, *next; if (!ev->output) return; wl_list_for_each_safe(v, next, &layer->view_list.link, layer_link.link) { if (v->output == ev->output && v != ev) { weston_view_unmap(v); v->surface->committed = NULL; weston_surface_set_label_func(v->surface, NULL); } } weston_view_set_position(ev, ev->output->x + x, ev->output->y + y); ev->surface->is_mapped = true; ev->is_mapped = true; if (wl_list_empty(&ev->layer_link.link)) { weston_layer_entry_insert(&layer->view_list, &ev->layer_link); weston_compositor_schedule_repaint(ev->surface->compositor); } } static struct shell_output * find_shell_output_from_weston_output(struct desktop_shell *shell, struct weston_output *output) { struct shell_output *shell_output; wl_list_for_each(shell_output, &shell->output_list, link) { if (shell_output->output == output) return shell_output; } return NULL; } static int background_get_label(struct weston_surface *surface, char *buf, size_t len) { return snprintf(buf, len, "background for output %s", surface->output->name); } static void background_committed(struct weston_surface *es, int32_t sx, int32_t sy) { struct desktop_shell *shell = es->committed_private; struct weston_view *view; view = container_of(es->views.next, struct weston_view, surface_link); configure_static_view(view, &shell->background_layer, 0, 0); } static void handle_background_surface_destroy(struct wl_listener *listener, void *data) { struct shell_output *output = container_of(listener, struct shell_output, background_surface_listener); weston_log("background surface gone\n"); wl_list_remove(&output->background_surface_listener.link); output->background_surface = NULL; } static void desktop_shell_set_background(struct wl_client *client, struct wl_resource *resource, struct wl_resource *output_resource, struct wl_resource *surface_resource) { struct desktop_shell *shell = wl_resource_get_user_data(resource); struct weston_surface *surface = wl_resource_get_user_data(surface_resource); struct shell_output *sh_output; struct weston_view *view, *next; if (surface->committed) { wl_resource_post_error(surface_resource, WL_DISPLAY_ERROR_INVALID_OBJECT, "surface role already assigned"); return; } wl_list_for_each_safe(view, next, &surface->views, surface_link) weston_view_destroy(view); view = weston_view_create(surface); surface->committed = background_committed; surface->committed_private = shell; weston_surface_set_label_func(surface, background_get_label); surface->output = weston_head_from_resource(output_resource)->output; weston_view_set_output(view, surface->output); sh_output = find_shell_output_from_weston_output(shell, surface->output); if (sh_output->background_surface) { /* The output already has a background, tell our helper * there is no need for another one. */ weston_desktop_shell_send_configure(resource, 0, surface_resource, 0, 0); } else { weston_desktop_shell_send_configure(resource, 0, surface_resource, surface->output->width, surface->output->height); sh_output->background_surface = surface; sh_output->background_surface_listener.notify = handle_background_surface_destroy; wl_signal_add(&surface->destroy_signal, &sh_output->background_surface_listener); } } static int panel_get_label(struct weston_surface *surface, char *buf, size_t len) { return snprintf(buf, len, "panel for output %s", surface->output->name); } static void panel_committed(struct weston_surface *es, int32_t sx, int32_t sy) { struct desktop_shell *shell = es->committed_private; struct weston_view *view; int width, height; int x = 0, y = 0; view = container_of(es->views.next, struct weston_view, surface_link); get_panel_size(shell, view, &width, &height); switch (shell->panel_position) { case WESTON_DESKTOP_SHELL_PANEL_POSITION_TOP: break; case WESTON_DESKTOP_SHELL_PANEL_POSITION_BOTTOM: y = view->output->height - height; break; case WESTON_DESKTOP_SHELL_PANEL_POSITION_LEFT: break; case WESTON_DESKTOP_SHELL_PANEL_POSITION_RIGHT: x = view->output->width - width; break; } configure_static_view(view, &shell->panel_layer, x, y); } static void handle_panel_surface_destroy(struct wl_listener *listener, void *data) { struct shell_output *output = container_of(listener, struct shell_output, panel_surface_listener); weston_log("panel surface gone\n"); wl_list_remove(&output->panel_surface_listener.link); output->panel_surface = NULL; } static void desktop_shell_set_panel(struct wl_client *client, struct wl_resource *resource, struct wl_resource *output_resource, struct wl_resource *surface_resource) { struct desktop_shell *shell = wl_resource_get_user_data(resource); struct weston_surface *surface = wl_resource_get_user_data(surface_resource); struct weston_view *view, *next; struct shell_output *sh_output; if (surface->committed) { wl_resource_post_error(surface_resource, WL_DISPLAY_ERROR_INVALID_OBJECT, "surface role already assigned"); return; } wl_list_for_each_safe(view, next, &surface->views, surface_link) weston_view_destroy(view); view = weston_view_create(surface); surface->committed = panel_committed; surface->committed_private = shell; weston_surface_set_label_func(surface, panel_get_label); surface->output = weston_head_from_resource(output_resource)->output; weston_view_set_output(view, surface->output); sh_output = find_shell_output_from_weston_output(shell, surface->output); if (sh_output->panel_surface) { /* The output already has a panel, tell our helper * there is no need for another one. */ weston_desktop_shell_send_configure(resource, 0, surface_resource, 0, 0); } else { weston_desktop_shell_send_configure(resource, 0, surface_resource, surface->output->width, surface->output->height); sh_output->panel_surface = surface; sh_output->panel_surface_listener.notify = handle_panel_surface_destroy; wl_signal_add(&surface->destroy_signal, &sh_output->panel_surface_listener); } } static int lock_surface_get_label(struct weston_surface *surface, char *buf, size_t len) { return snprintf(buf, len, "lock window"); } static void lock_surface_committed(struct weston_surface *surface, int32_t sx, int32_t sy) { struct desktop_shell *shell = surface->committed_private; struct weston_view *view; view = container_of(surface->views.next, struct weston_view, surface_link); if (surface->width == 0) return; center_on_output(view, get_default_output(shell->compositor)); if (!weston_surface_is_mapped(surface)) { weston_layer_entry_insert(&shell->lock_layer.view_list, &view->layer_link); weston_view_update_transform(view); surface->is_mapped = true; view->is_mapped = true; shell_fade(shell, FADE_IN); } } static void handle_lock_surface_destroy(struct wl_listener *listener, void *data) { struct desktop_shell *shell = container_of(listener, struct desktop_shell, lock_surface_listener); weston_log("lock surface gone\n"); shell->lock_surface = NULL; } static void desktop_shell_set_lock_surface(struct wl_client *client, struct wl_resource *resource, struct wl_resource *surface_resource) { struct desktop_shell *shell = wl_resource_get_user_data(resource); struct weston_surface *surface = wl_resource_get_user_data(surface_resource); shell->prepare_event_sent = false; if (!shell->locked) return; shell->lock_surface = surface; shell->lock_surface_listener.notify = handle_lock_surface_destroy; wl_signal_add(&surface->destroy_signal, &shell->lock_surface_listener); weston_view_create(surface); surface->committed = lock_surface_committed; surface->committed_private = shell; weston_surface_set_label_func(surface, lock_surface_get_label); } static void resume_desktop(struct desktop_shell *shell) { struct workspace *ws = get_current_workspace(shell); weston_layer_unset_position(&shell->lock_layer); if (shell->showing_input_panels) weston_layer_set_position(&shell->input_panel_layer, WESTON_LAYER_POSITION_TOP_UI); weston_layer_set_position(&shell->fullscreen_layer, WESTON_LAYER_POSITION_FULLSCREEN); weston_layer_set_position(&shell->panel_layer, WESTON_LAYER_POSITION_UI); weston_layer_set_position(&ws->layer, WESTON_LAYER_POSITION_NORMAL); restore_focus_state(shell, get_current_workspace(shell)); shell->locked = false; shell_fade(shell, FADE_IN); weston_compositor_damage_all(shell->compositor); } static void desktop_shell_unlock(struct wl_client *client, struct wl_resource *resource) { struct desktop_shell *shell = wl_resource_get_user_data(resource); shell->prepare_event_sent = false; if (shell->locked) resume_desktop(shell); } static void desktop_shell_set_grab_surface(struct wl_client *client, struct wl_resource *resource, struct wl_resource *surface_resource) { struct desktop_shell *shell = wl_resource_get_user_data(resource); shell->grab_surface = wl_resource_get_user_data(surface_resource); weston_view_create(shell->grab_surface); } static void desktop_shell_desktop_ready(struct wl_client *client, struct wl_resource *resource) { struct desktop_shell *shell = wl_resource_get_user_data(resource); shell_fade_startup(shell); } static void desktop_shell_set_panel_position(struct wl_client *client, struct wl_resource *resource, uint32_t position) { struct desktop_shell *shell = wl_resource_get_user_data(resource); if (position != WESTON_DESKTOP_SHELL_PANEL_POSITION_TOP && position != WESTON_DESKTOP_SHELL_PANEL_POSITION_BOTTOM && position != WESTON_DESKTOP_SHELL_PANEL_POSITION_LEFT && position != WESTON_DESKTOP_SHELL_PANEL_POSITION_RIGHT) { wl_resource_post_error(resource, WESTON_DESKTOP_SHELL_ERROR_INVALID_ARGUMENT, "bad position argument"); return; } shell->panel_position = position; } static const struct weston_desktop_shell_interface desktop_shell_implementation = { desktop_shell_set_background, desktop_shell_set_panel, desktop_shell_set_lock_surface, desktop_shell_unlock, desktop_shell_set_grab_surface, desktop_shell_desktop_ready, desktop_shell_set_panel_position }; static void move_binding(struct weston_pointer *pointer, const struct timespec *time, uint32_t button, void *data) { struct weston_surface *focus; struct weston_surface *surface; struct shell_surface *shsurf; if (pointer->focus == NULL) return; focus = pointer->focus->surface; surface = weston_surface_get_main_surface(focus); if (surface == NULL) return; shsurf = get_shell_surface(surface); if (shsurf == NULL || weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) || weston_desktop_surface_get_maximized(shsurf->desktop_surface)) return; surface_move(shsurf, pointer, false); } static void maximize_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t button, void *data) { struct weston_surface *focus = keyboard->focus; struct weston_surface *surface; struct shell_surface *shsurf; surface = weston_surface_get_main_surface(focus); if (surface == NULL) return; shsurf = get_shell_surface(surface); if (shsurf == NULL) return; set_maximized(shsurf, !weston_desktop_surface_get_maximized(shsurf->desktop_surface)); } static void fullscreen_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t button, void *data) { struct weston_surface *focus = keyboard->focus; struct weston_surface *surface; struct shell_surface *shsurf; bool fullscreen; surface = weston_surface_get_main_surface(focus); if (surface == NULL) return; shsurf = get_shell_surface(surface); if (shsurf == NULL) return; fullscreen = weston_desktop_surface_get_fullscreen(shsurf->desktop_surface); set_fullscreen(shsurf, !fullscreen, NULL); } static void touch_move_binding(struct weston_touch *touch, const struct timespec *time, void *data) { struct weston_surface *focus; struct weston_surface *surface; struct shell_surface *shsurf; if (touch->focus == NULL) return; focus = touch->focus->surface; surface = weston_surface_get_main_surface(focus); if (surface == NULL) return; shsurf = get_shell_surface(surface); if (shsurf == NULL || weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) || weston_desktop_surface_get_maximized(shsurf->desktop_surface)) return; surface_touch_move(shsurf, touch); } static void resize_binding(struct weston_pointer *pointer, const struct timespec *time, uint32_t button, void *data) { struct weston_surface *focus; struct weston_surface *surface; uint32_t edges = 0; int32_t x, y; struct shell_surface *shsurf; if (pointer->focus == NULL) return; focus = pointer->focus->surface; surface = weston_surface_get_main_surface(focus); if (surface == NULL) return; shsurf = get_shell_surface(surface); if (shsurf == NULL || weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) || weston_desktop_surface_get_maximized(shsurf->desktop_surface)) return; weston_view_from_global(shsurf->view, wl_fixed_to_int(pointer->grab_x), wl_fixed_to_int(pointer->grab_y), &x, &y); if (x < surface->width / 3) edges |= WL_SHELL_SURFACE_RESIZE_LEFT; else if (x < 2 * surface->width / 3) edges |= 0; else edges |= WL_SHELL_SURFACE_RESIZE_RIGHT; if (y < surface->height / 3) edges |= WL_SHELL_SURFACE_RESIZE_TOP; else if (y < 2 * surface->height / 3) edges |= 0; else edges |= WL_SHELL_SURFACE_RESIZE_BOTTOM; surface_resize(shsurf, pointer, edges); } static void surface_opacity_binding(struct weston_pointer *pointer, const struct timespec *time, struct weston_pointer_axis_event *event, void *data) { float step = 0.005; struct shell_surface *shsurf; struct weston_surface *focus = pointer->focus->surface; struct weston_surface *surface; /* XXX: broken for windows containing sub-surfaces */ surface = weston_surface_get_main_surface(focus); if (surface == NULL) return; shsurf = get_shell_surface(surface); if (!shsurf) return; shsurf->view->alpha -= event->value * step; if (shsurf->view->alpha > 1.0) shsurf->view->alpha = 1.0; if (shsurf->view->alpha < step) shsurf->view->alpha = step; weston_view_geometry_dirty(shsurf->view); weston_surface_damage(surface); } static void do_zoom(struct weston_seat *seat, const struct timespec *time, uint32_t key, uint32_t axis, double value) { struct weston_compositor *compositor = seat->compositor; struct weston_pointer *pointer = weston_seat_get_pointer(seat); struct weston_output *output; float increment; if (!pointer) { weston_log("Zoom hotkey pressed but seat '%s' contains no pointer.\n", seat->seat_name); return; } wl_list_for_each(output, &compositor->output_list, link) { if (pixman_region32_contains_point(&output->region, wl_fixed_to_double(pointer->x), wl_fixed_to_double(pointer->y), NULL)) { if (key == KEY_PAGEUP) increment = output->zoom.increment; else if (key == KEY_PAGEDOWN) increment = -output->zoom.increment; else if (axis == WL_POINTER_AXIS_VERTICAL_SCROLL) /* For every pixel zoom 20th of a step */ increment = output->zoom.increment * -value / 20.0; else increment = 0; output->zoom.level += increment; if (output->zoom.level < 0.0) output->zoom.level = 0.0; else if (output->zoom.level > output->zoom.max_level) output->zoom.level = output->zoom.max_level; if (!output->zoom.active) { if (output->zoom.level <= 0.0) continue; weston_output_activate_zoom(output, seat); } output->zoom.spring_z.target = output->zoom.level; weston_output_update_zoom(output); } } } static void zoom_axis_binding(struct weston_pointer *pointer, const struct timespec *time, struct weston_pointer_axis_event *event, void *data) { do_zoom(pointer->seat, time, 0, event->axis, event->value); } static void zoom_key_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { do_zoom(keyboard->seat, time, key, 0, 0); } static void terminate_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct weston_compositor *compositor = data; weston_compositor_exit(compositor); } static void rotate_grab_motion(struct weston_pointer_grab *grab, const struct timespec *time, struct weston_pointer_motion_event *event) { struct rotate_grab *rotate = container_of(grab, struct rotate_grab, base.grab); struct weston_pointer *pointer = grab->pointer; struct shell_surface *shsurf = rotate->base.shsurf; struct weston_surface *surface; float cx, cy, dx, dy, cposx, cposy, dposx, dposy, r; weston_pointer_move(pointer, event); if (!shsurf) return; surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); cx = 0.5f * surface->width; cy = 0.5f * surface->height; dx = wl_fixed_to_double(pointer->x) - rotate->center.x; dy = wl_fixed_to_double(pointer->y) - rotate->center.y; r = sqrtf(dx * dx + dy * dy); wl_list_remove(&shsurf->rotation.transform.link); weston_view_geometry_dirty(shsurf->view); if (r > 20.0f) { struct weston_matrix *matrix = &shsurf->rotation.transform.matrix; weston_matrix_init(&rotate->rotation); weston_matrix_rotate_xy(&rotate->rotation, dx / r, dy / r); weston_matrix_init(matrix); weston_matrix_translate(matrix, -cx, -cy, 0.0f); weston_matrix_multiply(matrix, &shsurf->rotation.rotation); weston_matrix_multiply(matrix, &rotate->rotation); weston_matrix_translate(matrix, cx, cy, 0.0f); wl_list_insert( &shsurf->view->geometry.transformation_list, &shsurf->rotation.transform.link); } else { wl_list_init(&shsurf->rotation.transform.link); weston_matrix_init(&shsurf->rotation.rotation); weston_matrix_init(&rotate->rotation); } /* We need to adjust the position of the surface * in case it was resized in a rotated state before */ cposx = shsurf->view->geometry.x + cx; cposy = shsurf->view->geometry.y + cy; dposx = rotate->center.x - cposx; dposy = rotate->center.y - cposy; if (dposx != 0.0f || dposy != 0.0f) { weston_view_set_position(shsurf->view, shsurf->view->geometry.x + dposx, shsurf->view->geometry.y + dposy); } /* Repaint implies weston_view_update_transform(), which * lazily applies the damage due to rotation update. */ weston_compositor_schedule_repaint(surface->compositor); } static void rotate_grab_button(struct weston_pointer_grab *grab, const struct timespec *time, uint32_t button, uint32_t state_w) { struct rotate_grab *rotate = container_of(grab, struct rotate_grab, base.grab); struct weston_pointer *pointer = grab->pointer; struct shell_surface *shsurf = rotate->base.shsurf; enum wl_pointer_button_state state = state_w; if (pointer->button_count == 0 && state == WL_POINTER_BUTTON_STATE_RELEASED) { if (shsurf) weston_matrix_multiply(&shsurf->rotation.rotation, &rotate->rotation); shell_grab_end(&rotate->base); free(rotate); } } static void rotate_grab_cancel(struct weston_pointer_grab *grab) { struct rotate_grab *rotate = container_of(grab, struct rotate_grab, base.grab); shell_grab_end(&rotate->base); free(rotate); } static const struct weston_pointer_grab_interface rotate_grab_interface = { noop_grab_focus, rotate_grab_motion, rotate_grab_button, noop_grab_axis, noop_grab_axis_source, noop_grab_frame, rotate_grab_cancel, }; static void surface_rotate(struct shell_surface *shsurf, struct weston_pointer *pointer) { struct weston_surface *surface = weston_desktop_surface_get_surface(shsurf->desktop_surface); struct rotate_grab *rotate; float dx, dy; float r; rotate = malloc(sizeof *rotate); if (!rotate) return; weston_view_to_global_float(shsurf->view, surface->width * 0.5f, surface->height * 0.5f, &rotate->center.x, &rotate->center.y); dx = wl_fixed_to_double(pointer->x) - rotate->center.x; dy = wl_fixed_to_double(pointer->y) - rotate->center.y; r = sqrtf(dx * dx + dy * dy); if (r > 20.0f) { struct weston_matrix inverse; weston_matrix_init(&inverse); weston_matrix_rotate_xy(&inverse, dx / r, -dy / r); weston_matrix_multiply(&shsurf->rotation.rotation, &inverse); weston_matrix_init(&rotate->rotation); weston_matrix_rotate_xy(&rotate->rotation, dx / r, dy / r); } else { weston_matrix_init(&shsurf->rotation.rotation); weston_matrix_init(&rotate->rotation); } shell_grab_start(&rotate->base, &rotate_grab_interface, shsurf, pointer, WESTON_DESKTOP_SHELL_CURSOR_ARROW); } static void rotate_binding(struct weston_pointer *pointer, const struct timespec *time, uint32_t button, void *data) { struct weston_surface *focus; struct weston_surface *base_surface; struct shell_surface *surface; if (pointer->focus == NULL) return; focus = pointer->focus->surface; base_surface = weston_surface_get_main_surface(focus); if (base_surface == NULL) return; surface = get_shell_surface(base_surface); if (surface == NULL || weston_desktop_surface_get_fullscreen(surface->desktop_surface) || weston_desktop_surface_get_maximized(surface->desktop_surface)) return; surface_rotate(surface, pointer); } /* Move all fullscreen layers down to the current workspace and hide their * black views. The surfaces' state is set to both fullscreen and lowered, * and this is reversed when such a surface is re-configured, see * shell_configure_fullscreen() and shell_ensure_fullscreen_black_view(). * * lowering_output = NULL - Lower on all outputs, else only lower on the * specified output. * * This should be used when implementing shell-wide overlays, such as * the alt-tab switcher, which need to de-promote fullscreen layers. */ void lower_fullscreen_layer(struct desktop_shell *shell, struct weston_output *lowering_output) { struct workspace *ws; struct weston_view *view, *prev; ws = get_current_workspace(shell); wl_list_for_each_reverse_safe(view, prev, &shell->fullscreen_layer.view_list.link, layer_link.link) { struct shell_surface *shsurf = get_shell_surface(view->surface); if (!shsurf) continue; /* Only lower surfaces which have lowering_output as their fullscreen * output, unless a NULL output asks for lowering on all outputs. */ if (lowering_output && (shsurf->fullscreen_output != lowering_output)) continue; /* We can have a non-fullscreen popup for a fullscreen surface * in the fullscreen layer. */ if (weston_desktop_surface_get_fullscreen(shsurf->desktop_surface)) { /* Hide the black view */ weston_layer_entry_remove(&shsurf->fullscreen.black_view->layer_link); wl_list_init(&shsurf->fullscreen.black_view->layer_link.link); weston_view_damage_below(shsurf->fullscreen.black_view); } /* Lower the view to the workspace layer */ weston_layer_entry_remove(&view->layer_link); weston_layer_entry_insert(&ws->layer.view_list, &view->layer_link); weston_view_damage_below(view); weston_surface_damage(view->surface); shsurf->state.lowered = true; } } void activate(struct desktop_shell *shell, struct weston_view *view, struct weston_seat *seat, uint32_t flags) { struct weston_surface *es = view->surface; struct weston_surface *main_surface; struct focus_state *state; struct workspace *ws; struct weston_surface *old_es; struct shell_surface *shsurf; main_surface = weston_surface_get_main_surface(es); shsurf = get_shell_surface(main_surface); assert(shsurf); /* Only demote fullscreen surfaces on the output of activated shsurf. * Leave fullscreen surfaces on unrelated outputs alone. */ if (shsurf->output) lower_fullscreen_layer(shell, shsurf->output); weston_view_activate(view, seat, flags); state = ensure_focus_state(shell, seat); if (state == NULL) return; old_es = state->keyboard_focus; focus_state_set_focus(state, es); if (weston_desktop_surface_get_fullscreen(shsurf->desktop_surface) && flags & WESTON_ACTIVATE_FLAG_CONFIGURE) shell_configure_fullscreen(shsurf); /* Update the surface’s layer. This brings it to the top of the stacking * order as appropriate. */ shell_surface_update_layer(shsurf); if (shell->focus_animation_type != ANIMATION_NONE) { ws = get_current_workspace(shell); animate_focus_change(shell, ws, get_default_view(old_es), get_default_view(es)); } } /* no-op func for checking black surface */ static void black_surface_committed(struct weston_surface *es, int32_t sx, int32_t sy) { } static bool is_black_surface_view(struct weston_view *view, struct weston_view **fs_view) { struct weston_surface *surface = view->surface; if (surface->committed == black_surface_committed) { if (fs_view) *fs_view = surface->committed_private; return true; } return false; } static void activate_binding(struct weston_seat *seat, struct desktop_shell *shell, struct weston_view *focus_view, uint32_t flags) { struct weston_view *main_view; struct weston_surface *main_surface; if (!focus_view) return; if (is_black_surface_view(focus_view, &main_view)) focus_view = main_view; main_surface = weston_surface_get_main_surface(focus_view->surface); if (!get_shell_surface(main_surface)) return; activate(shell, focus_view, seat, flags); } static void click_to_activate_binding(struct weston_pointer *pointer, const struct timespec *time, uint32_t button, void *data) { if (pointer->grab != &pointer->default_grab) return; if (pointer->focus == NULL) return; activate_binding(pointer->seat, data, pointer->focus, WESTON_ACTIVATE_FLAG_CLICKED | WESTON_ACTIVATE_FLAG_CONFIGURE); } static void touch_to_activate_binding(struct weston_touch *touch, const struct timespec *time, void *data) { if (touch->grab != &touch->default_grab) return; if (touch->focus == NULL) return; activate_binding(touch->seat, data, touch->focus, WESTON_ACTIVATE_FLAG_CONFIGURE); } static void unfocus_all_seats(struct desktop_shell *shell) { struct weston_seat *seat, *next; wl_list_for_each_safe(seat, next, &shell->compositor->seat_list, link) { struct weston_keyboard *keyboard = weston_seat_get_keyboard(seat); if (!keyboard) continue; weston_keyboard_set_focus(keyboard, NULL); } } static void lock(struct desktop_shell *shell) { struct workspace *ws = get_current_workspace(shell); if (shell->locked) { weston_compositor_sleep(shell->compositor); return; } shell->locked = true; /* Hide all surfaces by removing the fullscreen, panel and * toplevel layers. This way nothing else can show or receive * input events while we are locked. */ weston_layer_unset_position(&shell->panel_layer); weston_layer_unset_position(&shell->fullscreen_layer); if (shell->showing_input_panels) weston_layer_unset_position(&shell->input_panel_layer); weston_layer_unset_position(&ws->layer); weston_layer_set_position(&shell->lock_layer, WESTON_LAYER_POSITION_LOCK); weston_compositor_sleep(shell->compositor); /* Remove the keyboard focus on all seats. This will be * restored to the workspace's saved state via * restore_focus_state when the compositor is unlocked */ unfocus_all_seats(shell); /* TODO: disable bindings that should not work while locked. */ /* All this must be undone in resume_desktop(). */ } static void unlock(struct desktop_shell *shell) { struct wl_resource *shell_resource; if (!shell->locked || shell->lock_surface) { shell_fade(shell, FADE_IN); return; } /* If desktop-shell client has gone away, unlock immediately. */ if (!shell->child.desktop_shell) { resume_desktop(shell); return; } if (shell->prepare_event_sent) return; shell_resource = shell->child.desktop_shell; weston_desktop_shell_send_prepare_lock_surface(shell_resource); shell->prepare_event_sent = true; } static void shell_fade_done_for_output(struct weston_view_animation *animation, void *data) { struct shell_output *shell_output = data; struct desktop_shell *shell = shell_output->shell; shell_output->fade.animation = NULL; switch (shell_output->fade.type) { case FADE_IN: weston_surface_destroy(shell_output->fade.view->surface); shell_output->fade.view = NULL; break; case FADE_OUT: lock(shell); break; default: break; } } static struct weston_view * shell_fade_create_surface_for_output(struct desktop_shell *shell, struct shell_output *shell_output) { struct weston_compositor *compositor = shell->compositor; struct weston_surface *surface; struct weston_view *view; surface = weston_surface_create(compositor); if (!surface) return NULL; view = weston_view_create(surface); if (!view) { weston_surface_destroy(surface); return NULL; } weston_surface_set_size(surface, shell_output->output->width, shell_output->output->height); weston_view_set_position(view, shell_output->output->x, shell_output->output->y); weston_surface_set_color(surface, 0.0, 0.0, 0.0, 1.0); weston_layer_entry_insert(&compositor->fade_layer.view_list, &view->layer_link); pixman_region32_init(&surface->input); surface->is_mapped = true; view->is_mapped = true; return view; } static void shell_fade(struct desktop_shell *shell, enum fade_type type) { float tint; struct shell_output *shell_output; switch (type) { case FADE_IN: tint = 0.0; break; case FADE_OUT: tint = 1.0; break; default: weston_log("shell: invalid fade type\n"); return; } /* Create a separate fade surface for each output */ wl_list_for_each(shell_output, &shell->output_list, link) { shell_output->fade.type = type; if (shell_output->fade.view == NULL) { shell_output->fade.view = shell_fade_create_surface_for_output(shell, shell_output); if (!shell_output->fade.view) continue; shell_output->fade.view->alpha = 1.0 - tint; weston_view_update_transform(shell_output->fade.view); } if (shell_output->fade.view->output == NULL) { /* If the black view gets a NULL output, we lost the * last output and we'll just cancel the fade. This * happens when you close the last window under the * X11 or Wayland backends. */ shell->locked = false; weston_surface_destroy(shell_output->fade.view->surface); shell_output->fade.view = NULL; } else if (shell_output->fade.animation) { weston_fade_update(shell_output->fade.animation, tint); } else { shell_output->fade.animation = weston_fade_run(shell_output->fade.view, 1.0 - tint, tint, 300.0, shell_fade_done_for_output, shell_output); } } } static void do_shell_fade_startup(void *data) { struct desktop_shell *shell = data; struct shell_output *shell_output; if (shell->startup_animation_type == ANIMATION_FADE) { shell_fade(shell, FADE_IN); } else { weston_log("desktop shell: " "unexpected fade-in animation type %d\n", shell->startup_animation_type); wl_list_for_each(shell_output, &shell->output_list, link) { weston_surface_destroy(shell_output->fade.view->surface); shell_output->fade.view = NULL; } } } static void shell_fade_startup(struct desktop_shell *shell) { struct wl_event_loop *loop; struct shell_output *shell_output; bool has_fade = false; wl_list_for_each(shell_output, &shell->output_list, link) { if (!shell_output->fade.startup_timer) continue; wl_event_source_remove(shell_output->fade.startup_timer); shell_output->fade.startup_timer = NULL; has_fade = true; } if (has_fade) { loop = wl_display_get_event_loop(shell->compositor->wl_display); wl_event_loop_add_idle(loop, do_shell_fade_startup, shell); } } static int fade_startup_timeout(void *data) { struct desktop_shell *shell = data; shell_fade_startup(shell); return 0; } static void shell_fade_init(struct desktop_shell *shell) { /* Make compositor output all black, and wait for the desktop-shell * client to signal it is ready, then fade in. The timer triggers a * fade-in, in case the desktop-shell client takes too long. */ struct wl_event_loop *loop; struct shell_output *shell_output; if (shell->startup_animation_type == ANIMATION_NONE) return; wl_list_for_each(shell_output, &shell->output_list, link) { if (shell_output->fade.view != NULL) { weston_log("%s: warning: fade surface already exists\n", __func__); continue; } shell_output->fade.view = shell_fade_create_surface_for_output(shell, shell_output); if (!shell_output->fade.view) continue; weston_view_update_transform(shell_output->fade.view); weston_surface_damage(shell_output->fade.view->surface); loop = wl_display_get_event_loop(shell->compositor->wl_display); shell_output->fade.startup_timer = wl_event_loop_add_timer(loop, fade_startup_timeout, shell); wl_event_source_timer_update(shell_output->fade.startup_timer, 15000); } } static void idle_handler(struct wl_listener *listener, void *data) { struct desktop_shell *shell = container_of(listener, struct desktop_shell, idle_listener); struct weston_seat *seat; wl_list_for_each(seat, &shell->compositor->seat_list, link) weston_seat_break_desktop_grabs(seat); shell_fade(shell, FADE_OUT); /* lock() is called from shell_fade_done_for_output() */ } static void wake_handler(struct wl_listener *listener, void *data) { struct desktop_shell *shell = container_of(listener, struct desktop_shell, wake_listener); unlock(shell); } static void transform_handler(struct wl_listener *listener, void *data) { struct weston_surface *surface = data; struct shell_surface *shsurf = get_shell_surface(surface); const struct weston_xwayland_surface_api *api; int x, y; if (!shsurf) return; api = shsurf->shell->xwayland_surface_api; if (!api) { api = weston_xwayland_surface_get_api(shsurf->shell->compositor); shsurf->shell->xwayland_surface_api = api; } if (!api || !api->is_xwayland_surface(surface)) return; if (!weston_view_is_mapped(shsurf->view)) return; x = shsurf->view->geometry.x; y = shsurf->view->geometry.y; api->send_position(surface, x, y); } static void center_on_output(struct weston_view *view, struct weston_output *output) { int32_t surf_x, surf_y, width, height; float x, y; if (!output) { weston_view_set_position(view, 0, 0); return; } surface_subsurfaces_boundingbox(view->surface, &surf_x, &surf_y, &width, &height); x = output->x + (output->width - width) / 2 - surf_x / 2; y = output->y + (output->height - height) / 2 - surf_y / 2; weston_view_set_position(view, x, y); } static void weston_view_set_initial_position(struct weston_view *view, struct desktop_shell *shell) { struct weston_compositor *compositor = shell->compositor; int ix = 0, iy = 0; int32_t range_x, range_y; int32_t x, y; struct weston_output *output, *target_output = NULL; struct weston_seat *seat; pixman_rectangle32_t area; /* As a heuristic place the new window on the same output as the * pointer. Falling back to the output containing 0, 0. * * TODO: Do something clever for touch too? */ wl_list_for_each(seat, &compositor->seat_list, link) { struct weston_pointer *pointer = weston_seat_get_pointer(seat); if (pointer) { ix = wl_fixed_to_int(pointer->x); iy = wl_fixed_to_int(pointer->y); break; } } wl_list_for_each(output, &compositor->output_list, link) { if (pixman_region32_contains_point(&output->region, ix, iy, NULL)) { target_output = output; break; } } if (!target_output) { weston_view_set_position(view, 10 + random() % 400, 10 + random() % 400); return; } /* Valid range within output where the surface will still be onscreen. * If this is negative it means that the surface is bigger than * output. */ get_output_work_area(shell, target_output, &area); x = area.x; y = area.y; range_x = area.width - view->surface->width; range_y = area.height - view->surface->height; if (range_x > 0) x += random() % range_x; if (range_y > 0) y += random() % range_y; weston_view_set_position(view, x, y); } static bool check_desktop_shell_crash_too_early(struct desktop_shell *shell) { struct timespec now; if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) return false; /* * If the shell helper client dies before the session has been * up for roughly 30 seconds, better just make Weston shut down, * because the user likely has no way to interact with the desktop * anyway. */ if (now.tv_sec - shell->startup_time.tv_sec < 30) { weston_log("Error: %s apparently cannot run at all.\n", shell->client); weston_log_continue(STAMP_SPACE "Quitting..."); weston_compositor_exit_with_code(shell->compositor, EXIT_FAILURE); return true; } return false; } static void launch_desktop_shell_process(void *data); static void respawn_desktop_shell_process(struct desktop_shell *shell) { struct timespec time; /* if desktop-shell dies more than 5 times in 30 seconds, give up */ weston_compositor_get_time(&time); if (timespec_sub_to_msec(&time, &shell->child.deathstamp) > 30000) { shell->child.deathstamp = time; shell->child.deathcount = 0; } shell->child.deathcount++; if (shell->child.deathcount > 5) { weston_log("%s disconnected, giving up.\n", shell->client); return; } weston_log("%s disconnected, respawning...\n", shell->client); launch_desktop_shell_process(shell); } static void desktop_shell_client_destroy(struct wl_listener *listener, void *data) { struct desktop_shell *shell; shell = container_of(listener, struct desktop_shell, child.client_destroy_listener); wl_list_remove(&shell->child.client_destroy_listener.link); shell->child.client = NULL; /* * unbind_desktop_shell() will reset shell->child.desktop_shell * before the respawned process has a chance to create a new * desktop_shell object, because we are being called from the * wl_client destructor which destroys all wl_resources before * returning. */ if (!check_desktop_shell_crash_too_early(shell)) respawn_desktop_shell_process(shell); shell_fade_startup(shell); } static void launch_desktop_shell_process(void *data) { struct desktop_shell *shell = data; shell->child.client = weston_client_start(shell->compositor, shell->client); if (!shell->child.client) { weston_log("not able to start %s\n", shell->client); return; } shell->child.client_destroy_listener.notify = desktop_shell_client_destroy; wl_client_add_destroy_listener(shell->child.client, &shell->child.client_destroy_listener); } static void unbind_desktop_shell(struct wl_resource *resource) { struct desktop_shell *shell = wl_resource_get_user_data(resource); if (shell->locked) resume_desktop(shell); shell->child.desktop_shell = NULL; shell->prepare_event_sent = false; } static void bind_desktop_shell(struct wl_client *client, void *data, uint32_t version, uint32_t id) { struct desktop_shell *shell = data; struct wl_resource *resource; resource = wl_resource_create(client, &weston_desktop_shell_interface, 1, id); if (client == shell->child.client) { wl_resource_set_implementation(resource, &desktop_shell_implementation, shell, unbind_desktop_shell); shell->child.desktop_shell = resource; return; } wl_resource_post_error(resource, WL_DISPLAY_ERROR_INVALID_OBJECT, "permission to bind desktop_shell denied"); } struct switcher { struct desktop_shell *shell; struct weston_view *current; struct wl_listener listener; struct weston_keyboard_grab grab; struct wl_array minimized_array; }; static void switcher_next(struct switcher *switcher) { struct weston_view *view; struct weston_view *first = NULL, *prev = NULL, *next = NULL; struct shell_surface *shsurf; struct workspace *ws = get_current_workspace(switcher->shell); /* temporary re-display minimized surfaces */ struct weston_view *tmp; struct weston_view **minimized; wl_list_for_each_safe(view, tmp, &switcher->shell->minimized_layer.view_list.link, layer_link.link) { weston_layer_entry_remove(&view->layer_link); weston_layer_entry_insert(&ws->layer.view_list, &view->layer_link); minimized = wl_array_add(&switcher->minimized_array, sizeof *minimized); *minimized = view; } wl_list_for_each(view, &ws->layer.view_list.link, layer_link.link) { shsurf = get_shell_surface(view->surface); if (shsurf) { if (first == NULL) first = view; if (prev == switcher->current) next = view; prev = view; view->alpha = 0.25; weston_view_geometry_dirty(view); weston_surface_damage(view->surface); } if (is_black_surface_view(view, NULL)) { view->alpha = 0.25; weston_view_geometry_dirty(view); weston_surface_damage(view->surface); } } if (next == NULL) next = first; if (next == NULL) return; wl_list_remove(&switcher->listener.link); wl_signal_add(&next->destroy_signal, &switcher->listener); switcher->current = next; wl_list_for_each(view, &next->surface->views, surface_link) view->alpha = 1.0; shsurf = get_shell_surface(switcher->current->surface); if (shsurf && weston_desktop_surface_get_fullscreen(shsurf->desktop_surface)) shsurf->fullscreen.black_view->alpha = 1.0; } static void switcher_handle_view_destroy(struct wl_listener *listener, void *data) { struct switcher *switcher = container_of(listener, struct switcher, listener); switcher_next(switcher); } static void switcher_destroy(struct switcher *switcher) { struct weston_view *view; struct weston_keyboard *keyboard = switcher->grab.keyboard; struct workspace *ws = get_current_workspace(switcher->shell); wl_list_for_each(view, &ws->layer.view_list.link, layer_link.link) { if (is_focus_view(view)) continue; view->alpha = 1.0; weston_surface_damage(view->surface); } if (switcher->current) { activate(switcher->shell, switcher->current, keyboard->seat, WESTON_ACTIVATE_FLAG_CONFIGURE); } wl_list_remove(&switcher->listener.link); weston_keyboard_end_grab(keyboard); if (keyboard->input_method_resource) keyboard->grab = &keyboard->input_method_grab; /* re-hide surfaces that were temporary shown during the switch */ struct weston_view **minimized; wl_array_for_each(minimized, &switcher->minimized_array) { /* with the exception of the current selected */ if ((*minimized)->surface != switcher->current->surface) { weston_layer_entry_remove(&(*minimized)->layer_link); weston_layer_entry_insert(&switcher->shell->minimized_layer.view_list, &(*minimized)->layer_link); weston_view_damage_below(*minimized); } } wl_array_release(&switcher->minimized_array); free(switcher); } static void switcher_key(struct weston_keyboard_grab *grab, const struct timespec *time, uint32_t key, uint32_t state_w) { struct switcher *switcher = container_of(grab, struct switcher, grab); enum wl_keyboard_key_state state = state_w; if (key == KEY_TAB && state == WL_KEYBOARD_KEY_STATE_PRESSED) switcher_next(switcher); } static void switcher_modifier(struct weston_keyboard_grab *grab, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) { struct switcher *switcher = container_of(grab, struct switcher, grab); struct weston_seat *seat = grab->keyboard->seat; if ((seat->modifier_state & switcher->shell->binding_modifier) == 0) switcher_destroy(switcher); } static void switcher_cancel(struct weston_keyboard_grab *grab) { struct switcher *switcher = container_of(grab, struct switcher, grab); switcher_destroy(switcher); } static const struct weston_keyboard_grab_interface switcher_grab = { switcher_key, switcher_modifier, switcher_cancel, }; static void switcher_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct desktop_shell *shell = data; struct switcher *switcher; switcher = malloc(sizeof *switcher); switcher->shell = shell; switcher->current = NULL; switcher->listener.notify = switcher_handle_view_destroy; wl_list_init(&switcher->listener.link); wl_array_init(&switcher->minimized_array); lower_fullscreen_layer(switcher->shell, NULL); switcher->grab.interface = &switcher_grab; weston_keyboard_start_grab(keyboard, &switcher->grab); weston_keyboard_set_focus(keyboard, NULL); switcher_next(switcher); } static void backlight_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct weston_compositor *compositor = data; struct weston_output *output; long backlight_new = 0; /* TODO: we're limiting to simple use cases, where we assume just * control on the primary display. We'd have to extend later if we * ever get support for setting backlights on random desktop LCD * panels though */ output = get_default_output(compositor); if (!output) return; if (!output->set_backlight) return; if (key == KEY_F9 || key == KEY_BRIGHTNESSDOWN) backlight_new = output->backlight_current - 25; else if (key == KEY_F10 || key == KEY_BRIGHTNESSUP) backlight_new = output->backlight_current + 25; if (backlight_new < 5) backlight_new = 5; if (backlight_new > 255) backlight_new = 255; output->backlight_current = backlight_new; output->set_backlight(output, output->backlight_current); } static void force_kill_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct weston_surface *focus_surface; struct wl_client *client; struct desktop_shell *shell = data; struct weston_compositor *compositor = shell->compositor; pid_t pid; focus_surface = keyboard->focus; if (!focus_surface) return; wl_signal_emit(&compositor->kill_signal, focus_surface); client = wl_resource_get_client(focus_surface->resource); wl_client_get_credentials(client, &pid, NULL, NULL); /* Skip clients that we launched ourselves (the credentials of * the socketpair is ours) */ if (pid == getpid()) return; kill(pid, SIGKILL); } static void workspace_up_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct desktop_shell *shell = data; unsigned int new_index = shell->workspaces.current; if (shell->locked) return; if (new_index != 0) new_index--; change_workspace(shell, new_index); } static void workspace_down_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct desktop_shell *shell = data; unsigned int new_index = shell->workspaces.current; if (shell->locked) return; if (new_index < shell->workspaces.num - 1) new_index++; change_workspace(shell, new_index); } static void workspace_f_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct desktop_shell *shell = data; unsigned int new_index; if (shell->locked) return; new_index = key - KEY_F1; if (new_index >= shell->workspaces.num) new_index = shell->workspaces.num - 1; change_workspace(shell, new_index); } static void workspace_move_surface_up_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct desktop_shell *shell = data; unsigned int new_index = shell->workspaces.current; if (shell->locked) return; if (new_index != 0) new_index--; take_surface_to_workspace_by_seat(shell, keyboard->seat, new_index); } static void workspace_move_surface_down_binding(struct weston_keyboard *keyboard, const struct timespec *time, uint32_t key, void *data) { struct desktop_shell *shell = data; unsigned int new_index = shell->workspaces.current; if (shell->locked) return; if (new_index < shell->workspaces.num - 1) new_index++; take_surface_to_workspace_by_seat(shell, keyboard->seat, new_index); } static void shell_reposition_view_on_output_change(struct weston_view *view) { struct weston_output *output, *first_output; struct weston_compositor *ec = view->surface->compositor; struct shell_surface *shsurf; float x, y; int visible; if (wl_list_empty(&ec->output_list)) return; x = view->geometry.x; y = view->geometry.y; /* At this point the destroyed output is not in the list anymore. * If the view is still visible somewhere, we leave where it is, * otherwise, move it to the first output. */ visible = 0; wl_list_for_each(output, &ec->output_list, link) { if (pixman_region32_contains_point(&output->region, x, y, NULL)) { visible = 1; break; } } if (!visible) { first_output = container_of(ec->output_list.next, struct weston_output, link); x = first_output->x + first_output->width / 4; y = first_output->y + first_output->height / 4; weston_view_set_position(view, x, y); } else { weston_view_geometry_dirty(view); } shsurf = get_shell_surface(view->surface); if (!shsurf) return; shsurf->saved_position_valid = false; set_maximized(shsurf, false); set_fullscreen(shsurf, false, NULL); } void shell_for_each_layer(struct desktop_shell *shell, shell_for_each_layer_func_t func, void *data) { struct workspace **ws; func(shell, &shell->fullscreen_layer, data); func(shell, &shell->panel_layer, data); func(shell, &shell->background_layer, data); func(shell, &shell->lock_layer, data); func(shell, &shell->input_panel_layer, data); wl_array_for_each(ws, &shell->workspaces.array) func(shell, &(*ws)->layer, data); } static void shell_output_changed_move_layer(struct desktop_shell *shell, struct weston_layer *layer, void *data) { struct weston_view *view; wl_list_for_each(view, &layer->view_list.link, layer_link.link) shell_reposition_view_on_output_change(view); } static void handle_output_destroy(struct wl_listener *listener, void *data) { struct shell_output *output_listener = container_of(listener, struct shell_output, destroy_listener); struct desktop_shell *shell = output_listener->shell; shell_for_each_layer(shell, shell_output_changed_move_layer, NULL); if (output_listener->panel_surface) wl_list_remove(&output_listener->panel_surface_listener.link); if (output_listener->background_surface) wl_list_remove(&output_listener->background_surface_listener.link); wl_list_remove(&output_listener->destroy_listener.link); wl_list_remove(&output_listener->link); free(output_listener); } static void shell_resize_surface_to_output(struct desktop_shell *shell, struct weston_surface *surface, const struct weston_output *output) { if (!surface) return; weston_desktop_shell_send_configure(shell->child.desktop_shell, 0, surface->resource, output->width, output->height); } static void handle_output_resized(struct wl_listener *listener, void *data) { struct desktop_shell *shell = container_of(listener, struct desktop_shell, resized_listener); struct weston_output *output = (struct weston_output *)data; struct shell_output *sh_output = find_shell_output_from_weston_output(shell, output); shell_resize_surface_to_output(shell, sh_output->background_surface, output); shell_resize_surface_to_output(shell, sh_output->panel_surface, output); } static void create_shell_output(struct desktop_shell *shell, struct weston_output *output) { struct shell_output *shell_output; shell_output = zalloc(sizeof *shell_output); if (shell_output == NULL) return; shell_output->output = output; shell_output->shell = shell; shell_output->destroy_listener.notify = handle_output_destroy; wl_signal_add(&output->destroy_signal, &shell_output->destroy_listener); wl_list_insert(shell->output_list.prev, &shell_output->link); if (wl_list_length(&shell->output_list) == 1) shell_for_each_layer(shell, shell_output_changed_move_layer, NULL); } static void handle_output_create(struct wl_listener *listener, void *data) { struct desktop_shell *shell = container_of(listener, struct desktop_shell, output_create_listener); struct weston_output *output = (struct weston_output *)data; create_shell_output(shell, output); } static void handle_output_move_layer(struct desktop_shell *shell, struct weston_layer *layer, void *data) { struct weston_output *output = data; struct weston_view *view; float x, y; wl_list_for_each(view, &layer->view_list.link, layer_link.link) { if (view->output != output) continue; x = view->geometry.x + output->move_x; y = view->geometry.y + output->move_y; weston_view_set_position(view, x, y); } } static void handle_output_move(struct wl_listener *listener, void *data) { struct desktop_shell *shell; shell = container_of(listener, struct desktop_shell, output_move_listener); shell_for_each_layer(shell, handle_output_move_layer, data); } static void setup_output_destroy_handler(struct weston_compositor *ec, struct desktop_shell *shell) { struct weston_output *output; wl_list_init(&shell->output_list); wl_list_for_each(output, &ec->output_list, link) create_shell_output(shell, output); shell->output_create_listener.notify = handle_output_create; wl_signal_add(&ec->output_created_signal, &shell->output_create_listener); shell->output_move_listener.notify = handle_output_move; wl_signal_add(&ec->output_moved_signal, &shell->output_move_listener); } static void shell_destroy(struct wl_listener *listener, void *data) { struct desktop_shell *shell = container_of(listener, struct desktop_shell, destroy_listener); struct workspace **ws; struct shell_output *shell_output, *tmp; /* Force state to unlocked so we don't try to fade */ shell->locked = false; if (shell->child.client) { /* disable respawn */ wl_list_remove(&shell->child.client_destroy_listener.link); wl_client_destroy(shell->child.client); } wl_list_remove(&shell->destroy_listener.link); wl_list_remove(&shell->idle_listener.link); wl_list_remove(&shell->wake_listener.link); wl_list_remove(&shell->transform_listener.link); text_backend_destroy(shell->text_backend); input_panel_destroy(shell); wl_list_for_each_safe(shell_output, tmp, &shell->output_list, link) { wl_list_remove(&shell_output->destroy_listener.link); wl_list_remove(&shell_output->link); free(shell_output); } wl_list_remove(&shell->output_create_listener.link); wl_list_remove(&shell->output_move_listener.link); wl_list_remove(&shell->resized_listener.link); wl_array_for_each(ws, &shell->workspaces.array) workspace_destroy(*ws); wl_array_release(&shell->workspaces.array); free(shell->client); free(shell); } static void shell_add_bindings(struct weston_compositor *ec, struct desktop_shell *shell) { uint32_t mod; int i, num_workspace_bindings; if (shell->allow_zap) weston_compositor_add_key_binding(ec, KEY_BACKSPACE, MODIFIER_CTRL | MODIFIER_ALT, terminate_binding, ec); /* fixed bindings */ weston_compositor_add_button_binding(ec, BTN_LEFT, 0, click_to_activate_binding, shell); weston_compositor_add_button_binding(ec, BTN_RIGHT, 0, click_to_activate_binding, shell); weston_compositor_add_touch_binding(ec, 0, touch_to_activate_binding, shell); weston_compositor_add_key_binding(ec, KEY_BRIGHTNESSDOWN, 0, backlight_binding, ec); weston_compositor_add_key_binding(ec, KEY_BRIGHTNESSUP, 0, backlight_binding, ec); /* configurable bindings */ if (shell->exposay_modifier) weston_compositor_add_modifier_binding(ec, shell->exposay_modifier, exposay_binding, shell); mod = shell->binding_modifier; if (!mod) return; /* This binding is not configurable, but is only enabled if there is a * valid binding modifier. */ weston_compositor_add_axis_binding(ec, WL_POINTER_AXIS_VERTICAL_SCROLL, MODIFIER_SUPER | MODIFIER_ALT, surface_opacity_binding, NULL); weston_compositor_add_axis_binding(ec, WL_POINTER_AXIS_VERTICAL_SCROLL, mod, zoom_axis_binding, NULL); weston_compositor_add_key_binding(ec, KEY_PAGEUP, mod, zoom_key_binding, NULL); weston_compositor_add_key_binding(ec, KEY_PAGEDOWN, mod, zoom_key_binding, NULL); weston_compositor_add_key_binding(ec, KEY_M, mod | MODIFIER_SHIFT, maximize_binding, NULL); weston_compositor_add_key_binding(ec, KEY_F, mod | MODIFIER_SHIFT, fullscreen_binding, NULL); weston_compositor_add_button_binding(ec, BTN_LEFT, mod, move_binding, shell); weston_compositor_add_touch_binding(ec, mod, touch_move_binding, shell); weston_compositor_add_button_binding(ec, BTN_RIGHT, mod, resize_binding, shell); weston_compositor_add_button_binding(ec, BTN_LEFT, mod | MODIFIER_SHIFT, resize_binding, shell); if (ec->capabilities & WESTON_CAP_ROTATION_ANY) weston_compositor_add_button_binding(ec, BTN_MIDDLE, mod, rotate_binding, NULL); weston_compositor_add_key_binding(ec, KEY_TAB, mod, switcher_binding, shell); weston_compositor_add_key_binding(ec, KEY_F9, mod, backlight_binding, ec); weston_compositor_add_key_binding(ec, KEY_F10, mod, backlight_binding, ec); weston_compositor_add_key_binding(ec, KEY_K, mod, force_kill_binding, shell); weston_compositor_add_key_binding(ec, KEY_UP, mod, workspace_up_binding, shell); weston_compositor_add_key_binding(ec, KEY_DOWN, mod, workspace_down_binding, shell); weston_compositor_add_key_binding(ec, KEY_UP, mod | MODIFIER_SHIFT, workspace_move_surface_up_binding, shell); weston_compositor_add_key_binding(ec, KEY_DOWN, mod | MODIFIER_SHIFT, workspace_move_surface_down_binding, shell); /* Add bindings for mod+F[1-6] for workspace 1 to 6. */ if (shell->workspaces.num > 1) { num_workspace_bindings = shell->workspaces.num; if (num_workspace_bindings > 6) num_workspace_bindings = 6; for (i = 0; i < num_workspace_bindings; i++) weston_compositor_add_key_binding(ec, KEY_F1 + i, mod, workspace_f_binding, shell); } weston_install_debug_key_binding(ec, mod); } static void handle_seat_created(struct wl_listener *listener, void *data) { struct weston_seat *seat = data; create_shell_seat(seat); } WL_EXPORT int wet_shell_init(struct weston_compositor *ec, int *argc, char *argv[]) { struct weston_seat *seat; struct desktop_shell *shell; struct workspace **pws; unsigned int i; struct wl_event_loop *loop; shell = zalloc(sizeof *shell); if (shell == NULL) return -1; shell->compositor = ec; shell->destroy_listener.notify = shell_destroy; wl_signal_add(&ec->destroy_signal, &shell->destroy_listener); shell->idle_listener.notify = idle_handler; wl_signal_add(&ec->idle_signal, &shell->idle_listener); shell->wake_listener.notify = wake_handler; wl_signal_add(&ec->wake_signal, &shell->wake_listener); shell->transform_listener.notify = transform_handler; wl_signal_add(&ec->transform_signal, &shell->transform_listener); weston_layer_init(&shell->fullscreen_layer, ec); weston_layer_init(&shell->panel_layer, ec); weston_layer_init(&shell->background_layer, ec); weston_layer_init(&shell->lock_layer, ec); weston_layer_init(&shell->input_panel_layer, ec); weston_layer_set_position(&shell->fullscreen_layer, WESTON_LAYER_POSITION_FULLSCREEN); weston_layer_set_position(&shell->panel_layer, WESTON_LAYER_POSITION_UI); weston_layer_set_position(&shell->background_layer, WESTON_LAYER_POSITION_BACKGROUND); wl_array_init(&shell->workspaces.array); wl_list_init(&shell->workspaces.client_list); if (input_panel_setup(shell) < 0) return -1; shell->text_backend = text_backend_init(ec); if (!shell->text_backend) return -1; shell_configuration(shell); shell->exposay.state_cur = EXPOSAY_LAYOUT_INACTIVE; shell->exposay.state_target = EXPOSAY_TARGET_CANCEL; for (i = 0; i < shell->workspaces.num; i++) { pws = wl_array_add(&shell->workspaces.array, sizeof *pws); if (pws == NULL) return -1; *pws = workspace_create(shell); if (*pws == NULL) return -1; } activate_workspace(shell, 0); weston_layer_init(&shell->minimized_layer, ec); wl_list_init(&shell->workspaces.anim_sticky_list); wl_list_init(&shell->workspaces.animation.link); shell->workspaces.animation.frame = animate_workspace_change_frame; shell->desktop = weston_desktop_create(ec, &shell_desktop_api, shell); if (!shell->desktop) return -1; if (wl_global_create(ec->wl_display, &weston_desktop_shell_interface, 1, shell, bind_desktop_shell) == NULL) return -1; weston_compositor_get_time(&shell->child.deathstamp); shell->panel_position = WESTON_DESKTOP_SHELL_PANEL_POSITION_TOP; setup_output_destroy_handler(ec, shell); loop = wl_display_get_event_loop(ec->wl_display); wl_event_loop_add_idle(loop, launch_desktop_shell_process, shell); wl_list_for_each(seat, &ec->seat_list, link) handle_seat_created(NULL, seat); shell->seat_create_listener.notify = handle_seat_created; wl_signal_add(&ec->seat_created_signal, &shell->seat_create_listener); shell->resized_listener.notify = handle_output_resized; wl_signal_add(&ec->output_resized_signal, &shell->resized_listener); screenshooter_create(ec); shell_add_bindings(ec, shell); shell_fade_init(shell); clock_gettime(CLOCK_MONOTONIC, &shell->startup_time); return 0; }
endlessm/chromium-browser
third_party/weston/src/desktop-shell/shell.c
C
bsd-3-clause
141,882
# Copyright (c) 2019 Guo Yejun # # This file is part of FFmpeg. # # FFmpeg 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. # # FFmpeg 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 FFmpeg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # ============================================================================== import tensorflow as tf import numpy as np import sys, struct import convert_header as header __all__ = ['convert_from_tensorflow'] class Operand(object): IOTYPE_INPUT = 1 IOTYPE_OUTPUT = 2 IOTYPE_INTERMEDIATE = IOTYPE_INPUT | IOTYPE_OUTPUT DTYPE_FLOAT = 1 DTYPE_UINT8 = 4 index = 0 def __init__(self, name, dtype, dims): self.name = name self.dtype = dtype self.dims = dims self.iotype = 0 self.used_count = 0 self.index = Operand.index Operand.index = Operand.index + 1 self.iotype2str = {Operand.IOTYPE_INPUT: 'in', Operand.IOTYPE_OUTPUT: 'out', Operand.IOTYPE_INTERMEDIATE: 'inout'} self.dtype2str = {Operand.DTYPE_FLOAT: 'DT_FLOAT', Operand.DTYPE_UINT8: 'DT_UINT8'} def add_iotype(self, iotype): self.iotype = self.iotype | iotype if iotype == Operand.IOTYPE_INPUT: self.used_count = self.used_count + 1 def __str__(self): return "{}: (name: {}, iotype: {}, dtype: {}, dims: ({},{},{},{}) used_count: {})".format(self.index, self.name, self.iotype2str[self.iotype], self.dtype2str[self.dtype], self.dims[0], self.dims[1], self.dims[2], self.dims[3], self.used_count) def __lt__(self, other): return self.index < other.index class TFConverter: def __init__(self, graph_def, nodes, outfile, dump4tb): self.graph_def = graph_def self.nodes = nodes self.outfile = outfile self.dump4tb = dump4tb self.layer_number = 0 self.output_names = [] self.name_node_dict = {} self.edges = {} self.conv_activations = {'Relu':0, 'Tanh':1, 'Sigmoid':2, 'None':3, 'LeakyRelu':4} self.conv_paddings = {'VALID':0, 'SAME':1} self.converted_nodes = set() self.conv2d_scope_names = set() self.conv2d_scopename_inputname_dict = {} self.op2code = {'Conv2D':1, 'DepthToSpace':2, 'MirrorPad':3, 'Maximum':4, 'MathBinary':5} self.mathbin2code = {'Sub':0, 'Add':1, 'Mul':2, 'RealDiv':3} self.mirrorpad_mode = {'CONSTANT':0, 'REFLECT':1, 'SYMMETRIC':2} self.name_operand_dict = {} def add_operand(self, name, type): node = self.name_node_dict[name] if name not in self.name_operand_dict: dtype = node.attr['dtype'].type if dtype == 0: dtype = node.attr['T'].type dims = [-1,-1,-1,-1] if 'shape' in node.attr: dims[0] = node.attr['shape'].shape.dim[0].size dims[1] = node.attr['shape'].shape.dim[1].size dims[2] = node.attr['shape'].shape.dim[2].size dims[3] = node.attr['shape'].shape.dim[3].size operand = Operand(name, dtype, dims) self.name_operand_dict[name] = operand; self.name_operand_dict[name].add_iotype(type) return self.name_operand_dict[name].index def dump_for_tensorboard(self): graph = tf.get_default_graph() tf.import_graph_def(self.graph_def, name="") tf.summary.FileWriter('/tmp/graph', graph) print('graph saved, run "tensorboard --logdir=/tmp/graph" to see it') def get_conv2d_params(self, conv2d_scope_name): knode = self.name_node_dict[conv2d_scope_name + '/kernel'] bnode = self.name_node_dict[conv2d_scope_name + '/bias'] if conv2d_scope_name + '/dilation_rate' in self.name_node_dict: dnode = self.name_node_dict[conv2d_scope_name + '/dilation_rate'] else: dnode = None # the BiasAdd name is possible be changed into the output name, # if activation is None, and BiasAdd.next is the last op which is Identity if conv2d_scope_name + '/BiasAdd' in self.edges: anode = self.edges[conv2d_scope_name + '/BiasAdd'][0] if anode.op not in self.conv_activations: anode = None else: anode = None return knode, bnode, dnode, anode def dump_complex_conv2d_to_file(self, node, f): assert(node.op == 'Conv2D') self.layer_number = self.layer_number + 1 self.converted_nodes.add(node.name) scope_name = TFConverter.get_scope_name(node.name) #knode for kernel, bnode for bias, dnode for dilation, anode for activation knode, bnode, dnode, anode = self.get_conv2d_params(scope_name) if dnode is not None: dilation = struct.unpack('i', dnode.attr['value'].tensor.tensor_content[0:4])[0] else: dilation = 1 if anode is not None: activation = anode.op else: activation = 'None' padding = node.attr['padding'].s.decode("utf-8") # conv2d with dilation > 1 generates tens of nodes, not easy to parse them, so use this tricky method. if dilation > 1 and scope_name + '/stack' in self.name_node_dict: if self.name_node_dict[scope_name + '/stack'].op == "Const": padding = 'SAME' padding = self.conv_paddings[padding] ktensor = knode.attr['value'].tensor filter_height = ktensor.tensor_shape.dim[0].size filter_width = ktensor.tensor_shape.dim[1].size in_channels = ktensor.tensor_shape.dim[2].size out_channels = ktensor.tensor_shape.dim[3].size kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32) kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels) kernel = np.transpose(kernel, [3, 0, 1, 2]) has_bias = 1 np.array([self.op2code[node.op], dilation, padding, self.conv_activations[activation], in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f) kernel.tofile(f) btensor = bnode.attr['value'].tensor if btensor.tensor_shape.dim[0].size == 1: bias = struct.pack("f", btensor.float_val[0]) else: bias = btensor.tensor_content f.write(bias) input_name = self.conv2d_scopename_inputname_dict[scope_name] input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT) if anode is not None: output_operand_index = self.add_operand(anode.name, Operand.IOTYPE_OUTPUT) else: output_operand_index = self.add_operand(self.edges[bnode.name][0].name, Operand.IOTYPE_OUTPUT) np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f) def dump_simple_conv2d_to_file(self, node, f): assert(node.op == 'Conv2D') self.layer_number = self.layer_number + 1 self.converted_nodes.add(node.name) node0 = self.name_node_dict[node.input[0]] node1 = self.name_node_dict[node.input[1]] if node0.op == 'Const': knode = node0 input_name = node.input[1] else: knode = node1 input_name = node.input[0] ktensor = knode.attr['value'].tensor filter_height = ktensor.tensor_shape.dim[0].size filter_width = ktensor.tensor_shape.dim[1].size in_channels = ktensor.tensor_shape.dim[2].size out_channels = ktensor.tensor_shape.dim[3].size if filter_height * filter_width * in_channels * out_channels == 1: kernel = np.float32(ktensor.float_val[0]) else: kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32) kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels) kernel = np.transpose(kernel, [3, 0, 1, 2]) has_bias = 0 dilation = 1 padding = node.attr['padding'].s.decode("utf-8") np.array([self.op2code[node.op], dilation, self.conv_paddings[padding], self.conv_activations['None'], in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f) kernel.tofile(f) input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT) output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT) np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f) def dump_depth2space_to_file(self, node, f): assert(node.op == 'DepthToSpace') self.layer_number = self.layer_number + 1 block_size = node.attr['block_size'].i np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f) self.converted_nodes.add(node.name) input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT) output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT) np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f) def dump_mirrorpad_to_file(self, node, f): assert(node.op == 'MirrorPad') self.layer_number = self.layer_number + 1 mode = node.attr['mode'].s mode = self.mirrorpad_mode[mode.decode("utf-8")] np.array([self.op2code[node.op], mode], dtype=np.uint32).tofile(f) pnode = self.name_node_dict[node.input[1]] self.converted_nodes.add(pnode.name) paddings = pnode.attr['value'].tensor.tensor_content f.write(paddings) self.converted_nodes.add(node.name) input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT) output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT) np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f) def dump_maximum_to_file(self, node, f): assert(node.op == 'Maximum') self.layer_number = self.layer_number + 1 ynode = self.name_node_dict[node.input[1]] y = ynode.attr['value'].tensor.float_val[0] np.array([self.op2code[node.op]], dtype=np.uint32).tofile(f) np.array([y], dtype=np.float32).tofile(f) self.converted_nodes.add(node.name) input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT) output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT) np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f) def dump_mathbinary_to_file(self, node, f): self.layer_number = self.layer_number + 1 self.converted_nodes.add(node.name) i0_node = self.name_node_dict[node.input[0]] i1_node = self.name_node_dict[node.input[1]] np.array([self.op2code['MathBinary'], self.mathbin2code[node.op]], dtype=np.uint32).tofile(f) if i0_node.op == 'Const': scalar = i0_node.attr['value'].tensor.float_val[0] np.array([1], dtype=np.uint32).tofile(f) # broadcast: 1 np.array([scalar], dtype=np.float32).tofile(f) np.array([0], dtype=np.uint32).tofile(f) # broadcast: 0 input_operand_index = self.add_operand(i1_node.name, Operand.IOTYPE_INPUT) np.array([input_operand_index], dtype=np.uint32).tofile(f) elif i1_node.op == 'Const': scalar = i1_node.attr['value'].tensor.float_val[0] np.array([0], dtype=np.uint32).tofile(f) input_operand_index = self.add_operand(i0_node.name, Operand.IOTYPE_INPUT) np.array([input_operand_index], dtype=np.uint32).tofile(f) np.array([1], dtype=np.uint32).tofile(f) np.array([scalar], dtype=np.float32).tofile(f) else: np.array([0], dtype=np.uint32).tofile(f) input_operand_index = self.add_operand(i0_node.name, Operand.IOTYPE_INPUT) np.array([input_operand_index], dtype=np.uint32).tofile(f) np.array([0], dtype=np.uint32).tofile(f) input_operand_index = self.add_operand(i1_node.name, Operand.IOTYPE_INPUT) np.array([input_operand_index], dtype=np.uint32).tofile(f) output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT) np.array([output_operand_index], dtype=np.uint32).tofile(f) def dump_layers_to_file(self, f): for node in self.nodes: if node.name in self.converted_nodes: continue # conv2d with dilation generates very complex nodes, so handle it in special if self.in_conv2d_scope(node.name): if node.op == 'Conv2D': self.dump_complex_conv2d_to_file(node, f) continue if node.op == 'Conv2D': self.dump_simple_conv2d_to_file(node, f) elif node.op == 'DepthToSpace': self.dump_depth2space_to_file(node, f) elif node.op == 'MirrorPad': self.dump_mirrorpad_to_file(node, f) elif node.op == 'Maximum': self.dump_maximum_to_file(node, f) elif node.op == 'Sub': self.dump_mathbinary_to_file(node, f) elif node.op == 'Add': self.dump_mathbinary_to_file(node, f) elif node.op == 'Mul': self.dump_mathbinary_to_file(node, f) elif node.op == 'RealDiv': self.dump_mathbinary_to_file(node, f) def dump_operands_to_file(self, f): operands = sorted(self.name_operand_dict.values()) for operand in operands: #print('{}'.format(operand)) np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f) f.write(operand.name.encode('utf-8')) np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f) np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f) def dump_to_file(self): with open(self.outfile, 'wb') as f: f.write(header.str.encode('utf-8')) np.array([header.major, header.minor], dtype=np.uint32).tofile(f) self.dump_layers_to_file(f) self.dump_operands_to_file(f) np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f) def generate_name_node_dict(self): for node in self.nodes: self.name_node_dict[node.name] = node def generate_output_names(self): used_names = [] for node in self.nodes: for input in node.input: used_names.append(input) for node in self.nodes: if node.name not in used_names: self.output_names.append(node.name) def remove_identity(self): id_nodes = [] id_dict = {} for node in self.nodes: if node.op == 'Identity': name = node.name input = node.input[0] id_nodes.append(node) # do not change the output name if name in self.output_names: self.name_node_dict[input].name = name self.name_node_dict[name] = self.name_node_dict[input] del self.name_node_dict[input] else: id_dict[name] = input for idnode in id_nodes: self.nodes.remove(idnode) for node in self.nodes: for i in range(len(node.input)): input = node.input[i] if input in id_dict: node.input[i] = id_dict[input] def generate_edges(self): for node in self.nodes: for input in node.input: if input in self.edges: self.edges[input].append(node) else: self.edges[input] = [node] @staticmethod def get_scope_name(name): index = name.rfind('/') if index == -1: return "" return name[0:index] def in_conv2d_scope(self, name): inner_scope = TFConverter.get_scope_name(name) if inner_scope == "": return False; for scope in self.conv2d_scope_names: index = inner_scope.find(scope) if index == 0: return True return False def generate_conv2d_scope_info(self): # mostly, conv2d is a sub block in graph, get the scope name for node in self.nodes: if node.op == 'Conv2D': scope = TFConverter.get_scope_name(node.name) # for the case tf.nn.conv2d is called directly if scope == '': continue # for the case tf.nn.conv2d is called within a scope if scope + '/kernel' not in self.name_node_dict: continue self.conv2d_scope_names.add(scope) # get the input name to the conv2d sub block for node in self.nodes: scope = TFConverter.get_scope_name(node.name) if scope in self.conv2d_scope_names: if node.op == 'Conv2D' or node.op == 'Shape': for inp in node.input: if TFConverter.get_scope_name(inp) != scope: self.conv2d_scopename_inputname_dict[scope] = inp def run(self): self.generate_name_node_dict() self.generate_output_names() self.remove_identity() self.generate_edges() self.generate_conv2d_scope_info() if self.dump4tb: self.dump_for_tensorboard() self.dump_to_file() def convert_from_tensorflow(infile, outfile, dump4tb): with open(infile, 'rb') as f: # read the file in .proto format graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) nodes = graph_def.node converter = TFConverter(graph_def, nodes, outfile, dump4tb) converter.run()
endlessm/chromium-browser
third_party/ffmpeg/tools/python/convert_from_tensorflow.py
Python
bsd-3-clause
18,670
// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #ifndef STORAGE_ROCKSDB_INCLUDE_STATISTICS_H_ #define STORAGE_ROCKSDB_INCLUDE_STATISTICS_H_ #include <atomic> #include <cstddef> #include <cstdint> #include <string> #include <memory> #include <vector> namespace rocksdb { /** * Keep adding ticker's here. * 1. Any ticker should be added before TICKER_ENUM_MAX. * 2. Add a readable string in TickersNameMap below for the newly added ticker. */ enum Tickers { // total block cache misses // REQUIRES: BLOCK_CACHE_MISS == BLOCK_CACHE_INDEX_MISS + // BLOCK_CACHE_FILTER_MISS + // BLOCK_CACHE_DATA_MISS; BLOCK_CACHE_MISS, // total block cache hit // REQUIRES: BLOCK_CACHE_HIT == BLOCK_CACHE_INDEX_HIT + // BLOCK_CACHE_FILTER_HIT + // BLOCK_CACHE_DATA_HIT; BLOCK_CACHE_HIT, // # of blocks added to block cache. BLOCK_CACHE_ADD, // # of times cache miss when accessing index block from block cache. BLOCK_CACHE_INDEX_MISS, // # of times cache hit when accessing index block from block cache. BLOCK_CACHE_INDEX_HIT, // # of times cache miss when accessing filter block from block cache. BLOCK_CACHE_FILTER_MISS, // # of times cache hit when accessing filter block from block cache. BLOCK_CACHE_FILTER_HIT, // # of times cache miss when accessing data block from block cache. BLOCK_CACHE_DATA_MISS, // # of times cache hit when accessing data block from block cache. BLOCK_CACHE_DATA_HIT, // # of times bloom filter has avoided file reads. BLOOM_FILTER_USEFUL, // # of memtable hits. MEMTABLE_HIT, // # of memtable misses. MEMTABLE_MISS, /** * COMPACTION_KEY_DROP_* count the reasons for key drop during compaction * There are 3 reasons currently. */ COMPACTION_KEY_DROP_NEWER_ENTRY, // key was written with a newer value. COMPACTION_KEY_DROP_OBSOLETE, // The key is obsolete. COMPACTION_KEY_DROP_USER, // user compaction function has dropped the key. // Number of keys written to the database via the Put and Write call's NUMBER_KEYS_WRITTEN, // Number of Keys read, NUMBER_KEYS_READ, // Number keys updated, if inplace update is enabled NUMBER_KEYS_UPDATED, // Bytes written / read BYTES_WRITTEN, BYTES_READ, NO_FILE_CLOSES, NO_FILE_OPENS, NO_FILE_ERRORS, // Time system had to wait to do LO-L1 compactions STALL_L0_SLOWDOWN_MICROS, // Time system had to wait to move memtable to L1. STALL_MEMTABLE_COMPACTION_MICROS, // write throttle because of too many files in L0 STALL_L0_NUM_FILES_MICROS, RATE_LIMIT_DELAY_MILLIS, NO_ITERATORS, // number of iterators currently open // Number of MultiGet calls, keys read, and bytes read NUMBER_MULTIGET_CALLS, NUMBER_MULTIGET_KEYS_READ, NUMBER_MULTIGET_BYTES_READ, // Number of deletes records that were not required to be // written to storage because key does not exist NUMBER_FILTERED_DELETES, NUMBER_MERGE_FAILURES, SEQUENCE_NUMBER, // number of times bloom was checked before creating iterator on a // file, and the number of times the check was useful in avoiding // iterator creation (and thus likely IOPs). BLOOM_FILTER_PREFIX_CHECKED, BLOOM_FILTER_PREFIX_USEFUL, // Number of times we had to reseek inside an iteration to skip // over large number of keys with same userkey. NUMBER_OF_RESEEKS_IN_ITERATION, // Record the number of calls to GetUpadtesSince. Useful to keep track of // transaction log iterator refreshes GET_UPDATES_SINCE_CALLS, BLOCK_CACHE_COMPRESSED_MISS, // miss in the compressed block cache BLOCK_CACHE_COMPRESSED_HIT, // hit in the compressed block cache WAL_FILE_SYNCED, // Number of times WAL sync is done WAL_FILE_BYTES, // Number of bytes written to WAL // Writes can be processed by requesting thread or by the thread at the // head of the writers queue. WRITE_DONE_BY_SELF, WRITE_DONE_BY_OTHER, WRITE_WITH_WAL, // Number of Write calls that request WAL COMPACT_READ_BYTES, // Bytes read during compaction COMPACT_WRITE_BYTES, // Bytes written during compaction // Number of table's properties loaded directly from file, without creating // table reader object. NUMBER_DIRECT_LOAD_TABLE_PROPERTIES, TICKER_ENUM_MAX }; // The order of items listed in Tickers should be the same as // the order listed in TickersNameMap const std::vector<std::pair<Tickers, std::string>> TickersNameMap = { {BLOCK_CACHE_MISS, "rocksdb.block.cache.miss"}, {BLOCK_CACHE_HIT, "rocksdb.block.cache.hit"}, {BLOCK_CACHE_ADD, "rocksdb.block.cache.add"}, {BLOCK_CACHE_INDEX_MISS, "rocksdb.block.cache.index.miss"}, {BLOCK_CACHE_INDEX_HIT, "rocksdb.block.cache.index.hit"}, {BLOCK_CACHE_FILTER_MISS, "rocksdb.block.cache.filter.miss"}, {BLOCK_CACHE_FILTER_HIT, "rocksdb.block.cache.filter.hit"}, {BLOCK_CACHE_DATA_MISS, "rocksdb.block.cache.data.miss"}, {BLOCK_CACHE_DATA_HIT, "rocksdb.block.cache.data.hit"}, {BLOOM_FILTER_USEFUL, "rocksdb.bloom.filter.useful"}, {MEMTABLE_HIT, "rocksdb.memtable.hit"}, {MEMTABLE_MISS, "rocksdb.memtable.miss"}, {COMPACTION_KEY_DROP_NEWER_ENTRY, "rocksdb.compaction.key.drop.new"}, {COMPACTION_KEY_DROP_OBSOLETE, "rocksdb.compaction.key.drop.obsolete"}, {COMPACTION_KEY_DROP_USER, "rocksdb.compaction.key.drop.user"}, {NUMBER_KEYS_WRITTEN, "rocksdb.number.keys.written"}, {NUMBER_KEYS_READ, "rocksdb.number.keys.read"}, {NUMBER_KEYS_UPDATED, "rocksdb.number.keys.updated"}, {BYTES_WRITTEN, "rocksdb.bytes.written"}, {BYTES_READ, "rocksdb.bytes.read"}, {NO_FILE_CLOSES, "rocksdb.no.file.closes"}, {NO_FILE_OPENS, "rocksdb.no.file.opens"}, {NO_FILE_ERRORS, "rocksdb.no.file.errors"}, {STALL_L0_SLOWDOWN_MICROS, "rocksdb.l0.slowdown.micros"}, {STALL_MEMTABLE_COMPACTION_MICROS, "rocksdb.memtable.compaction.micros"}, {STALL_L0_NUM_FILES_MICROS, "rocksdb.l0.num.files.stall.micros"}, {RATE_LIMIT_DELAY_MILLIS, "rocksdb.rate.limit.delay.millis"}, {NO_ITERATORS, "rocksdb.num.iterators"}, {NUMBER_MULTIGET_CALLS, "rocksdb.number.multiget.get"}, {NUMBER_MULTIGET_KEYS_READ, "rocksdb.number.multiget.keys.read"}, {NUMBER_MULTIGET_BYTES_READ, "rocksdb.number.multiget.bytes.read"}, {NUMBER_FILTERED_DELETES, "rocksdb.number.deletes.filtered"}, {NUMBER_MERGE_FAILURES, "rocksdb.number.merge.failures"}, {SEQUENCE_NUMBER, "rocksdb.sequence.number"}, {BLOOM_FILTER_PREFIX_CHECKED, "rocksdb.bloom.filter.prefix.checked"}, {BLOOM_FILTER_PREFIX_USEFUL, "rocksdb.bloom.filter.prefix.useful"}, {NUMBER_OF_RESEEKS_IN_ITERATION, "rocksdb.number.reseeks.iteration"}, {GET_UPDATES_SINCE_CALLS, "rocksdb.getupdatessince.calls"}, {BLOCK_CACHE_COMPRESSED_MISS, "rocksdb.block.cachecompressed.miss"}, {BLOCK_CACHE_COMPRESSED_HIT, "rocksdb.block.cachecompressed.hit"}, {WAL_FILE_SYNCED, "rocksdb.wal.synced"}, {WAL_FILE_BYTES, "rocksdb.wal.bytes"}, {WRITE_DONE_BY_SELF, "rocksdb.write.self"}, {WRITE_DONE_BY_OTHER, "rocksdb.write.other"}, {WRITE_WITH_WAL, "rocksdb.write.wal"}, {COMPACT_READ_BYTES, "rocksdb.compact.read.bytes"}, {COMPACT_WRITE_BYTES, "rocksdb.compact.write.bytes"}, {NUMBER_DIRECT_LOAD_TABLE_PROPERTIES, "rocksdb.number.direct.load.table.properties"}, }; /** * Keep adding histogram's here. * Any histogram whould have value less than HISTOGRAM_ENUM_MAX * Add a new Histogram by assigning it the current value of HISTOGRAM_ENUM_MAX * Add a string representation in HistogramsNameMap below * And increment HISTOGRAM_ENUM_MAX */ enum Histograms { DB_GET, DB_WRITE, COMPACTION_TIME, TABLE_SYNC_MICROS, COMPACTION_OUTFILE_SYNC_MICROS, WAL_FILE_SYNC_MICROS, MANIFEST_FILE_SYNC_MICROS, // TIME SPENT IN IO DURING TABLE OPEN TABLE_OPEN_IO_MICROS, DB_MULTIGET, READ_BLOCK_COMPACTION_MICROS, READ_BLOCK_GET_MICROS, WRITE_RAW_BLOCK_MICROS, STALL_L0_SLOWDOWN_COUNT, STALL_MEMTABLE_COMPACTION_COUNT, STALL_L0_NUM_FILES_COUNT, HARD_RATE_LIMIT_DELAY_COUNT, SOFT_RATE_LIMIT_DELAY_COUNT, NUM_FILES_IN_SINGLE_COMPACTION, HISTOGRAM_ENUM_MAX, }; const std::vector<std::pair<Histograms, std::string>> HistogramsNameMap = { { DB_GET, "rocksdb.db.get.micros" }, { DB_WRITE, "rocksdb.db.write.micros" }, { COMPACTION_TIME, "rocksdb.compaction.times.micros" }, { TABLE_SYNC_MICROS, "rocksdb.table.sync.micros" }, { COMPACTION_OUTFILE_SYNC_MICROS, "rocksdb.compaction.outfile.sync.micros" }, { WAL_FILE_SYNC_MICROS, "rocksdb.wal.file.sync.micros" }, { MANIFEST_FILE_SYNC_MICROS, "rocksdb.manifest.file.sync.micros" }, { TABLE_OPEN_IO_MICROS, "rocksdb.table.open.io.micros" }, { DB_MULTIGET, "rocksdb.db.multiget.micros" }, { READ_BLOCK_COMPACTION_MICROS, "rocksdb.read.block.compaction.micros" }, { READ_BLOCK_GET_MICROS, "rocksdb.read.block.get.micros" }, { WRITE_RAW_BLOCK_MICROS, "rocksdb.write.raw.block.micros" }, { STALL_L0_SLOWDOWN_COUNT, "rocksdb.l0.slowdown.count"}, { STALL_MEMTABLE_COMPACTION_COUNT, "rocksdb.memtable.compaction.count"}, { STALL_L0_NUM_FILES_COUNT, "rocksdb.num.files.stall.count"}, { HARD_RATE_LIMIT_DELAY_COUNT, "rocksdb.hard.rate.limit.delay.count"}, { SOFT_RATE_LIMIT_DELAY_COUNT, "rocksdb.soft.rate.limit.delay.count"}, { NUM_FILES_IN_SINGLE_COMPACTION, "rocksdb.numfiles.in.singlecompaction" }, }; struct HistogramData { double median; double percentile95; double percentile99; double average; double standard_deviation; }; // Analyze the performance of a db class Statistics { public: virtual ~Statistics() {} virtual long getTickerCount(Tickers tickerType) = 0; virtual void recordTick(Tickers tickerType, uint64_t count = 0) = 0; virtual void setTickerCount(Tickers tickerType, uint64_t count) = 0; virtual void measureTime(Histograms histogramType, uint64_t time) = 0; virtual void histogramData(Histograms type, HistogramData* const data) = 0; // String representation of the statistic object. std::string ToString(); }; // Create a concrete DBStatistics object std::shared_ptr<Statistics> CreateDBStatistics(); } // namespace rocksdb #endif // STORAGE_ROCKSDB_INCLUDE_STATISTICS_H_
amimimor/docker-rocksdb
include/rocksdb/statistics.h
C
bsd-3-clause
10,492
// Copyright (c) 2013 - 2015 The Sporting Exchange Limited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by The Sporting Exchange Limited. // 4. Neither the name of The Sporting Exchange Limited 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 SPORTING EXCHANGE LIMITED ''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 SPORTING EXCHANGE LIMITED 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. #import <Foundation/Foundation.h> @class BNGCompetition; /** * Wrapper class around `BNGCompetition` which gives the client top-level information about the competition such as how many markets are associated with the comptition. */ @interface BNGCompetitionResult : NSObject /** * The competition which backs this wrapper class. */ @property (nonatomic) BNGCompetition *competition; /** * How many markets are associated with this `BNGCompetition` */ @property (nonatomic) NSInteger marketCount; /** * Where in the world this competition is being held. */ @property (nonatomic, copy) NSString *competitionRegion; @end
betfair/aping-ios-sdk
BNGAPI/BNGAPI/Classes/BNGCompetitionResult.h
C
bsd-3-clause
2,402
// Copyright 2015-present 650 Industries. All rights reserved. #import <React/RCTDevSettings.h> @interface EXDevSettings : RCTDevSettings - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithScopeKey:(NSString *)scopeKey isDevelopment:(BOOL)isDevelopment NS_DESIGNATED_INITIALIZER; @end
exponentjs/exponent
ios/Exponent/Versioned/Core/Internal/DevSupport/EXDevSettings.h
C
bsd-3-clause
328
# -*- coding: utf-8 -*- import os from django.conf import settings from django.core.urlresolvers import reverse from django.test import Client from .....checkout.tests import BaseCheckoutAppTests from .....delivery.tests import TestDeliveryProvider from .....order import handler as order_handler from .....payment import ConfirmationFormNeeded from .....payment.tests import TestPaymentProvider from .....pricing import handler as pricing_handler from .....product import handler as product_handler from .....product.tests import DeadParrot from .....product.tests.pricing import FiveZlotyPriceHandler from ..app import checkout_app from .....cart.tests import TestCart from .....order.tests import TestOrder class TestPaymentProviderWithConfirmation(TestPaymentProvider): def confirm(self, order, typ=None): raise ConfirmationFormNeeded(action='http://test.payment.gateway.example.com') class App(BaseCheckoutAppTests): checkout_app = checkout_app urls = BaseCheckoutAppTests.MockUrls(checkout_app=checkout_app) def setUp(self): checkout_app.cart_model = TestCart checkout_app.order_model = TestOrder self.parrot = DeadParrot.objects.create(slug='parrot', species='Hyacinth Macaw') self.dead_parrot = self.parrot.variants.create(color='blue', looks_alive=False) satchless_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..') self.custom_settings = { 'SATCHLESS_PRODUCT_VIEW_HANDLERS': ('satchless.cart.add_to_cart_handler',), 'TEMPLATE_DIRS': (os.path.join(satchless_dir, 'category', 'templates'), os.path.join(satchless_dir, 'order', 'templates'), os.path.join(satchless_dir, 'cart', 'templates'), os.path.join(satchless_dir, 'cart', 'templates'), os.path.join(os.path.join(os.path.dirname(__file__), 'templates')), os.path.join(os.path.join(os.path.dirname(__file__), '..', 'templates'))), 'TEMPLATE_LOADERS': ( 'django.template.loaders.filesystem.Loader', ) } self.original_settings = self._setup_settings(self.custom_settings) product_handler.init_queue() order_handler.delivery_queue = order_handler.DeliveryQueue(TestDeliveryProvider) order_handler.payment_queue = order_handler.PaymentQueue(TestPaymentProviderWithConfirmation) self.anon_client = Client() self.original_pricing_handlers = settings.SATCHLESS_PRICING_HANDLERS pricing_handler.pricing_queue = pricing_handler.PricingQueue(FiveZlotyPriceHandler) def tearDown(self): self._teardown_settings(self.original_settings, self.custom_settings) product_handler.init_queue() pricing_handler.pricing_queue = pricing_handler.PricingQueue(*self.original_pricing_handlers) def test_checkout_view_passes_with_correct_data(self): cart = self._get_or_create_cart_for_client(self.anon_client) cart.replace_item(self.dead_parrot, 1) order = self._get_or_create_order_for_client(self.anon_client) response = self._test_status(reverse('checkout:checkout', kwargs={'order_token': order.token}), client_instance=self.anon_client, data={'email': 'foo@example.com'}) dg = response.context['delivery_group_forms'] data = {'billing_first_name': 'First', 'billing_last_name': 'Last', 'billing_street_address_1': 'Via Rodeo 1', 'billing_city': 'Beverly Hills', 'billing_country': 'US', 'billing_country_area': 'AZ', 'billing_phone': '555-555-5555', 'billing_postal_code': '90210'} for g, typ, form in dg: data[form.add_prefix('email')] = 'foo@example.com' response = self._test_status(self.checkout_app.reverse('checkout', kwargs={'order_token': order.token}), client_instance=self.anon_client, status_code=302, method='post', data=data, follow=True) order = self.checkout_app.order_model.objects.get(pk=order.pk) self.assertRedirects(response, reverse('checkout:confirmation', kwargs={'order_token': order.token})) self.assertEqual(order.status, 'payment-pending') def test_confirmation_view_redirects_when_order_or_payment_is_missing(self): cart = self._get_or_create_cart_for_client(self.anon_client) cart.replace_item(self.dead_parrot, 1) order = self._get_or_create_order_for_client(self.anon_client) # without payment self._test_status(reverse('checkout:confirmation', kwargs={'order_token': order.token}), client_instance=self.anon_client, status_code=302) # finish checkout view response = self._test_status(self.checkout_app.reverse('checkout', kwargs={'order_token': order.token}), client_instance=self.anon_client, data={'email': 'foo@example.com'}) dg = response.context['delivery_group_forms'] data = {'billing_first_name': 'First', 'billing_last_name': 'Last', 'billing_street_address_1': 'Via Rodeo 1', 'billing_city': 'Beverly Hills', 'billing_country': 'US', 'billing_country_area': 'AZ', 'billing_phone': '555-555-5555', 'billing_postal_code': '90210'} for g, typ, form in dg: data[form.add_prefix('email')] = 'foo@example.com' response = self._test_status(self.checkout_app.reverse('checkout', kwargs={'order_token': order.token}), client_instance=self.anon_client, status_code=302, method='post', data=data, follow=True) self._test_status(self.checkout_app.reverse('confirmation', kwargs={'order_token': order.token}), client_instance=self.anon_client, status_code=200)
fusionbox/satchless
satchless/contrib/checkout/singlestep/tests/__init__.py
Python
bsd-3-clause
7,298
%w(quick_widget quick_button quick_checkbox quick_editfield quick_dropdown quick_dialogtab quick_label quick_radiobutton quick_treeview quick_addressfield quick_searchfield quick_toolbar quick_window quick_tab quick_treeitem quick_thumbnail quick_find quick_griditem quick_gridlayout quick_menu quick_menuitem quick_dropdownitem).each {|widget| require "operawatir/quickwidgets/#{widget}"}
operasoftware/operawatir
lib/operawatir/quickwidgets.rb
Ruby
bsd-3-clause
402
import datetime import logging import os import numpy as np from matplotlib.path import Path from matplotlib.widgets import Cursor, EllipseSelector, LassoSelector, RectangleSelector from sastool.io.credo_cct import Exposure from scipy.io import loadmat, savemat from ..core.exposureloader import ExposureLoader from ..core.filechooser import DoubleFileChooserDialog from ..core.plotimage import PlotImageWidget from ..core.toolwindow import ToolWindow logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class MaskEditor(ToolWindow, DoubleFileChooserDialog): def __init__(self, *args, **kwargs): self.mask = None self._undo_stack = [] self._im = None self._selector = None self._cursor = None self.exposureloader = None self.plot2d = None ToolWindow.__init__(self, *args, **kwargs) DoubleFileChooserDialog.__init__( self, self.widget, 'Open mask file...', 'Save mask file...', [('Mask files', '*.mat'), ('All files', '*')], self.instrument.config['path']['directories']['mask'], os.path.abspath(self.instrument.config['path']['directories']['mask']), ) def init_gui(self, *args, **kwargs): self.exposureloader = ExposureLoader(self.instrument) self.builder.get_object('loadexposure_expander').add(self.exposureloader) self.exposureloader.connect('open', self.on_loadexposure) self.plot2d = PlotImageWidget() self.builder.get_object('plotbox').pack_start(self.plot2d.widget, True, True, 0) self.builder.get_object('toolbar').set_sensitive(False) def on_loadexposure(self, exposureloader: ExposureLoader, im: Exposure): if self.mask is None: self.mask = im.mask self._im = im self.plot2d.set_image(im.intensity) self.plot2d.set_mask(self.mask) self.builder.get_object('toolbar').set_sensitive(True) def on_new(self, button): if self._im is None or self.mask is None: return False self.mask = np.ones_like(self.mask) self.plot2d.set_mask(self.mask) self.set_last_filename(None) def on_open(self, button): filename = self.get_open_filename() if filename is not None: mask = loadmat(filename) self.mask = mask[[k for k in mask.keys() if not k.startswith('__')][0]] self.plot2d.set_mask(self.mask) def on_save(self, button): filename = self.get_last_filename() if filename is None: return self.on_saveas(button) maskname = os.path.splitext(os.path.split(filename)[1])[0] savemat(filename, {maskname: self.mask}) def on_saveas(self, button): filename = self.get_save_filename(None) if filename is not None: self.on_save(button) def suggest_filename(self): return 'mask_dist_{0.year:d}{0.month:02d}{0.day:02d}.mat'.format(datetime.date.today()) def on_selectcircle_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Ellipse selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectrectangle_button', 'selectpolygon_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = EllipseSelector(self.plot2d.axis, self.on_ellipse_selected, rectprops={'facecolor': 'white', 'edgecolor': 'none', 'alpha': 0.7, 'fill': True, 'zorder': 10}, button=[1, ], interactive=False, lineprops={'zorder': 10}) self._selector.state.add('square') self._selector.state.add('center') else: assert isinstance(self._selector, EllipseSelector) self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True) def on_ellipse_selected(self, pos1, pos2): # pos1 and pos2 are mouse button press and release events, with xdata and ydata carrying # the two opposite corners of the bounding box of the circle. These are NOT the exact # button presses and releases! row = np.arange(self.mask.shape[0])[:, np.newaxis] column = np.arange(self.mask.shape[1])[np.newaxis, :] row0 = 0.5 * (pos1.ydata + pos2.ydata) col0 = 0.5 * (pos1.xdata + pos2.xdata) r2 = ((pos2.xdata - pos1.xdata) ** 2 + (pos2.ydata - pos1.ydata) ** 2) / 8 tobemasked = (row - row0) ** 2 + (column - col0) ** 2 <= r2 self._undo_stack.append(self.mask) if self.builder.get_object('mask_button').get_active(): self.mask &= ~tobemasked elif self.builder.get_object('unmask_button').get_active(): self.mask |= tobemasked elif self.builder.get_object('invertmask_button').get_active(): self.mask[tobemasked] = ~self.mask[tobemasked] else: pass self.builder.get_object('selectcircle_button').set_active(False) self.plot2d.set_mask(self.mask) def on_selectrectangle_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Rectangle selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectcircle_button', 'selectpolygon_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = RectangleSelector(self.plot2d.axis, self.on_rectangle_selected, rectprops={'facecolor': 'white', 'edgecolor': 'none', 'alpha': 0.7, 'fill': True, 'zorder': 10}, button=[1, ], interactive=False, lineprops={'zorder': 10}) else: self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True) def on_rectangle_selected(self, pos1, pos2): # pos1 and pos2 are mouse button press and release events, with xdata and ydata # carrying the two opposite corners of the bounding box of the rectangle. These # are NOT the exact button presses and releases! row = np.arange(self.mask.shape[0])[:, np.newaxis] column = np.arange(self.mask.shape[1])[np.newaxis, :] tobemasked = ((row >= min(pos1.ydata, pos2.ydata)) & (row <= max(pos1.ydata, pos2.ydata)) & (column >= min(pos1.xdata, pos2.xdata)) & (column <= max(pos1.xdata, pos2.xdata))) self._undo_stack.append(self.mask) if self.builder.get_object('mask_button').get_active(): self.mask = self.mask & (~tobemasked) elif self.builder.get_object('unmask_button').get_active(): self.mask = self.mask | tobemasked elif self.builder.get_object('invertmask_button').get_active(): self.mask[tobemasked] = ~self.mask[tobemasked] else: pass self.builder.get_object('selectrectangle_button').set_active(False) self.plot2d.set_mask(self.mask) def on_selectpolygon_toggled(self, button): if button.get_active(): self.set_sensitive(False, 'Polygon selection not ready', ['new_button', 'save_button', 'saveas_button', 'open_button', 'undo_button', 'selectrectangle_button', 'selectcircle_button', 'pixelhunting_button', 'loadexposure_expander', 'close_button', self.plot2d.toolbar, self.plot2d.settings_expander]) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() self._selector = LassoSelector(self.plot2d.axis, self.on_polygon_selected, lineprops={'color': 'white', 'zorder': 10}, button=[1, ], ) else: self._selector.set_active(False) self._selector.set_visible(False) self._selector = None self.plot2d.replot(keepzoom=False) self.set_sensitive(True) def on_polygon_selected(self, vertices): path = Path(vertices) col, row = np.meshgrid(np.arange(self.mask.shape[1]), np.arange(self.mask.shape[0])) points = np.vstack((col.flatten(), row.flatten())).T tobemasked = path.contains_points(points).reshape(self.mask.shape) self._undo_stack.append(self.mask) if self.builder.get_object('mask_button').get_active(): self.mask = self.mask & (~tobemasked) elif self.builder.get_object('unmask_button').get_active(): self.mask = self.mask | tobemasked elif self.builder.get_object('invertmask_button').get_active(): self.mask[tobemasked] = ~self.mask[tobemasked] else: pass self.plot2d.set_mask(self.mask) self.builder.get_object('selectpolygon_button').set_active(False) def on_mask_toggled(self, button): pass def on_unmask_toggled(self, button): pass def on_invertmask_toggled(self, button): pass def on_pixelhunting_toggled(self, button): if button.get_active(): self._cursor = Cursor(self.plot2d.axis, useblit=False, color='white', lw=1) self._cursor.connect_event('button_press_event', self.on_cursorclick) while self.plot2d.toolbar.mode != '': # turn off zoom, pan, etc. modes. self.plot2d.toolbar.zoom() else: self._cursor.disconnect_events() self._cursor = None self._undo_stack.append(self.mask) self.plot2d.replot(keepzoom=False) def on_cursorclick(self, event): if (event.inaxes == self.plot2d.axis) and (self.plot2d.toolbar.mode == ''): self.mask[round(event.ydata), round(event.xdata)] ^= True self._cursor.disconnect_events() self._cursor = None self.plot2d.replot(keepzoom=True) self.on_pixelhunting_toggled(self.builder.get_object('pixelhunting_button')) def cleanup(self): super().cleanup() self._undo_stack = [] def on_undo(self, button): try: self.mask = self._undo_stack.pop() except IndexError: return self.plot2d.set_mask(self.mask)
awacha/cct
attic/gui/tools/maskeditor.py
Python
bsd-3-clause
11,717
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ServiceWorkerRegistration_h #define ServiceWorkerRegistration_h #include "bindings/core/v8/ActiveScriptWrappable.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "core/dom/ActiveDOMObject.h" #include "core/events/EventTarget.h" #include "modules/serviceworkers/ServiceWorker.h" #include "modules/serviceworkers/ServiceWorkerRegistration.h" #include "platform/Supplementable.h" #include "public/platform/modules/serviceworker/WebServiceWorkerRegistration.h" #include "public/platform/modules/serviceworker/WebServiceWorkerRegistrationProxy.h" #include "wtf/OwnPtr.h" #include "wtf/PassOwnPtr.h" #include "wtf/PassRefPtr.h" #include "wtf/RefCounted.h" namespace blink { class ScriptPromise; class ScriptState; class WebServiceWorkerProvider; // The implementation of a service worker registration object in Blink. Actual // registration representation is in the embedder and this class accesses it // via WebServiceWorkerRegistration::Handle object. class ServiceWorkerRegistration final : public RefCountedGarbageCollectedEventTargetWithInlineData<ServiceWorkerRegistration> , public ActiveScriptWrappable , public ActiveDOMObject , public WebServiceWorkerRegistrationProxy , public Supplementable<ServiceWorkerRegistration> { DEFINE_WRAPPERTYPEINFO(); REFCOUNTED_GARBAGE_COLLECTED_EVENT_TARGET(ServiceWorkerRegistration); USING_GARBAGE_COLLECTED_MIXIN(ServiceWorkerRegistration); public: // EventTarget overrides. const AtomicString& interfaceName() const override; ExecutionContext* getExecutionContext() const override { return ActiveDOMObject::getExecutionContext(); } // WebServiceWorkerRegistrationProxy overrides. void dispatchUpdateFoundEvent() override; void setInstalling(std::unique_ptr<WebServiceWorker::Handle>) override; void setWaiting(std::unique_ptr<WebServiceWorker::Handle>) override; void setActive(std::unique_ptr<WebServiceWorker::Handle>) override; // Returns an existing registration object for the handle if it exists. // Otherwise, returns a new registration object. static ServiceWorkerRegistration* getOrCreate(ExecutionContext*, PassOwnPtr<WebServiceWorkerRegistration::Handle>); ServiceWorker* installing() { return m_installing; } ServiceWorker* waiting() { return m_waiting; } ServiceWorker* active() { return m_active; } String scope() const; WebServiceWorkerRegistration* webRegistration() { return m_handle->registration(); } ScriptPromise update(ScriptState*); ScriptPromise unregister(ScriptState*); DEFINE_ATTRIBUTE_EVENT_LISTENER(updatefound); ~ServiceWorkerRegistration() override; // Eager finalization needed to promptly release owned WebServiceWorkerRegistration. EAGERLY_FINALIZE(); DECLARE_VIRTUAL_TRACE(); private: ServiceWorkerRegistration(ExecutionContext*, PassOwnPtr<WebServiceWorkerRegistration::Handle>); // ActiveScriptWrappable overrides. bool hasPendingActivity() const final; // ActiveDOMObject overrides. void stop() override; // A handle to the registration representation in the embedder. OwnPtr<WebServiceWorkerRegistration::Handle> m_handle; WebServiceWorkerProvider* m_provider; Member<ServiceWorker> m_installing; Member<ServiceWorker> m_waiting; Member<ServiceWorker> m_active; bool m_stopped; }; class ServiceWorkerRegistrationArray { STATIC_ONLY(ServiceWorkerRegistrationArray); public: static HeapVector<Member<ServiceWorkerRegistration>> take(ScriptPromiseResolver* resolver, Vector<OwnPtr<WebServiceWorkerRegistration::Handle>>* webServiceWorkerRegistrations) { HeapVector<Member<ServiceWorkerRegistration>> registrations; for (auto& registration : *webServiceWorkerRegistrations) registrations.append(ServiceWorkerRegistration::getOrCreate(resolver->getExecutionContext(), registration.release())); return registrations; } }; } // namespace blink #endif // ServiceWorkerRegistration_h
was4444/chromium.src
third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerRegistration.h
C
bsd-3-clause
4,189
<?php $path= dirname(__FILE__)."/../../../settings.php"; include($path); global $db_url; $private_url = parse_url($db_url['genelist']); $genelist_connection=mysqli_connect($private_url['host'], $private_url['user'], $private_url['pass'],str_replace('/', '', $private_url['path'])) or die(mysqli_error()); ?>
irusri/GenIECMS
plugins/genelist/genelist/services/settings.php
PHP
bsd-3-clause
311
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime import "unsafe" const ( _Debugwbufs = true // if true check wbufs consistency _WorkbufSize = 1 * 256 // in bytes - if small wbufs are passed to GC in a timely fashion. ) // Garbage collector work pool abstraction. // // This implements a producer/consumer model for pointers to grey // objects. A grey object is one that is marked and on a work // queue. A black object is marked and not on a work queue. // // Write barriers, root discovery, stack scanning, and object scanning // produce pointers to grey objects. Scanning consumes pointers to // grey objects, thus blackening them, and then scans them, // potentially producing new pointers to grey objects. // A wbufptr holds a workbuf*, but protects it from write barriers. // workbufs never live on the heap, so write barriers are unnecessary. // Write barriers on workbuf pointers may also be dangerous in the GC. type wbufptr uintptr func wbufptrOf(w *workbuf) wbufptr { return wbufptr(unsafe.Pointer(w)) } func (wp wbufptr) ptr() *workbuf { return (*workbuf)(unsafe.Pointer(wp)) } // A gcWork provides the interface to produce and consume work for the // garbage collector. // // The usual pattern for using gcWork is: // // var gcw gcWork // disable preemption // .. call gcw.put() to produce and gcw.get() to consume .. // gcw.dispose() // enable preemption // // It's important that any use of gcWork during the mark phase prevent // the garbage collector from transitioning to mark termination since // gcWork may locally hold GC work buffers. This can be done by // disabling preemption (systemstack or acquirem). type gcWork struct { // Invariant: wbuf is never full or empty wbuf wbufptr // Bytes marked (blackened) on this gcWork. This is aggregated // into work.bytesMarked by dispose. bytesMarked uint64 // Scan work performed on this gcWork. This is aggregated into // gcController by dispose. scanWork int64 } // initFromCache fetches work from this M's currentwbuf cache. //go:nowritebarrier func (w *gcWork) initFromCache() { // TODO: Instead of making gcWork pull from the currentwbuf // cache, use a gcWork as the cache and make shade pass around // that gcWork. if w.wbuf == 0 { w.wbuf = wbufptr(xchguintptr(&getg().m.currentwbuf, 0)) } } // put enqueues a pointer for the garbage collector to trace. //go:nowritebarrier func (ww *gcWork) put(obj uintptr) { w := (*gcWork)(noescape(unsafe.Pointer(ww))) // TODO: remove when escape analysis is fixed wbuf := w.wbuf.ptr() if wbuf == nil { wbuf = getpartialorempty(42) w.wbuf = wbufptrOf(wbuf) } wbuf.obj[wbuf.nobj] = obj wbuf.nobj++ if wbuf.nobj == len(wbuf.obj) { putfull(wbuf, 50) w.wbuf = 0 } } // tryGet dequeues a pointer for the garbage collector to trace. // // If there are no pointers remaining in this gcWork or in the global // queue, tryGet returns 0. Note that there may still be pointers in // other gcWork instances or other caches. //go:nowritebarrier func (ww *gcWork) tryGet() uintptr { w := (*gcWork)(noescape(unsafe.Pointer(ww))) // TODO: remove when escape analysis is fixed wbuf := w.wbuf.ptr() if wbuf == nil { wbuf = trygetfull(74) if wbuf == nil { return 0 } w.wbuf = wbufptrOf(wbuf) } wbuf.nobj-- obj := wbuf.obj[wbuf.nobj] if wbuf.nobj == 0 { putempty(wbuf, 86) w.wbuf = 0 } return obj } // get dequeues a pointer for the garbage collector to trace, blocking // if necessary to ensure all pointers from all queues and caches have // been retrieved. get returns 0 if there are no pointers remaining. //go:nowritebarrier func (ww *gcWork) get() uintptr { w := (*gcWork)(noescape(unsafe.Pointer(ww))) // TODO: remove when escape analysis is fixed wbuf := w.wbuf.ptr() if wbuf == nil { wbuf = getfull(103) if wbuf == nil { return 0 } wbuf.checknonempty() w.wbuf = wbufptrOf(wbuf) } // TODO: This might be a good place to add prefetch code wbuf.nobj-- obj := wbuf.obj[wbuf.nobj] if wbuf.nobj == 0 { putempty(wbuf, 115) w.wbuf = 0 } return obj } // dispose returns any cached pointers to the global queue. //go:nowritebarrier func (w *gcWork) dispose() { if wbuf := w.wbuf; wbuf != 0 { putpartial(wbuf.ptr(), 167) w.wbuf = 0 } if w.bytesMarked != 0 { // dispose happens relatively infrequently. If this // atomic becomes a problem, we should first try to // dispose less and if necessary aggregate in a per-P // counter. xadd64(&work.bytesMarked, int64(w.bytesMarked)) w.bytesMarked = 0 } if w.scanWork != 0 { xaddint64(&gcController.scanWork, w.scanWork) w.scanWork = 0 } } // disposeToCache returns any cached pointers to this M's currentwbuf. // It calls throw if currentwbuf is non-nil. //go:nowritebarrier func (w *gcWork) disposeToCache() { if wbuf := w.wbuf; wbuf != 0 { wbuf = wbufptr(xchguintptr(&getg().m.currentwbuf, uintptr(wbuf))) if wbuf != 0 { throw("m.currentwbuf non-nil in disposeToCache") } w.wbuf = 0 } if w.bytesMarked != 0 { xadd64(&work.bytesMarked, int64(w.bytesMarked)) w.bytesMarked = 0 } if w.scanWork != 0 { xaddint64(&gcController.scanWork, w.scanWork) w.scanWork = 0 } } // balance moves some work that's cached in this gcWork back on the // global queue. //go:nowritebarrier func (w *gcWork) balance() { if wbuf := w.wbuf; wbuf != 0 && wbuf.ptr().nobj > 4 { w.wbuf = wbufptrOf(handoff(wbuf.ptr())) } } // Internally, the GC work pool is kept in arrays in work buffers. // The gcWork interface caches a work buffer until full (or empty) to // avoid contending on the global work buffer lists. type workbufhdr struct { node lfnode // must be first nobj int inuse bool // This workbuf is in use by some gorotuine and is not on the work.empty/partial/full queues. log [4]int // line numbers forming a history of ownership changes to workbuf } type workbuf struct { workbufhdr // account for the above fields obj [(_WorkbufSize - unsafe.Sizeof(workbufhdr{})) / ptrSize]uintptr } // workbuf factory routines. These funcs are used to manage the // workbufs. They cache workbuf in the m struct field currentwbuf. // If the GC asks for some work these are the only routines that // make partially full wbufs available to the GC. // Each of the gets and puts also take an distinct integer that is used // to record a brief history of changes to ownership of the workbuf. // The convention is to use a unique line number but any encoding // is permissible. For example if you want to pass in 2 bits of information // you could simple add lineno1*100000+lineno2. // logget records the past few values of entry to aid in debugging. // logget checks the buffer b is not currently in use. func (b *workbuf) logget(entry int) { if !_Debugwbufs { return } if b.inuse { println("runtime: logget fails log entry=", entry, "b.log[0]=", b.log[0], "b.log[1]=", b.log[1], "b.log[2]=", b.log[2], "b.log[3]=", b.log[3]) throw("logget: get not legal") } b.inuse = true copy(b.log[1:], b.log[:]) b.log[0] = entry } // logput records the past few values of entry to aid in debugging. // logput checks the buffer b is currently in use. func (b *workbuf) logput(entry int) { if !_Debugwbufs { return } if !b.inuse { println("runtime:logput fails log entry=", entry, "b.log[0]=", b.log[0], "b.log[1]=", b.log[1], "b.log[2]=", b.log[2], "b.log[3]=", b.log[3]) throw("logput: put not legal") } b.inuse = false copy(b.log[1:], b.log[:]) b.log[0] = entry } func (b *workbuf) checknonempty() { if b.nobj == 0 { println("runtime: nonempty check fails", "b.log[0]=", b.log[0], "b.log[1]=", b.log[1], "b.log[2]=", b.log[2], "b.log[3]=", b.log[3]) throw("workbuf is empty") } } func (b *workbuf) checkempty() { if b.nobj != 0 { println("runtime: empty check fails", "b.log[0]=", b.log[0], "b.log[1]=", b.log[1], "b.log[2]=", b.log[2], "b.log[3]=", b.log[3]) throw("workbuf is not empty") } } // checknocurrentwbuf checks that the m's currentwbuf field is empty func checknocurrentwbuf() { if getg().m.currentwbuf != 0 { throw("unexpected currentwbuf") } } // getempty pops an empty work buffer off the work.empty list, // allocating new buffers if none are available. // entry is used to record a brief history of ownership. //go:nowritebarrier func getempty(entry int) *workbuf { var b *workbuf if work.empty != 0 { b = (*workbuf)(lfstackpop(&work.empty)) if b != nil { b.checkempty() } } if b == nil { b = (*workbuf)(persistentalloc(unsafe.Sizeof(*b), _CacheLineSize, &memstats.gc_sys)) } b.logget(entry) return b } // putempty puts a workbuf onto the work.empty list. // Upon entry this go routine owns b. The lfstackpush relinquishes ownership. //go:nowritebarrier func putempty(b *workbuf, entry int) { b.checkempty() b.logput(entry) lfstackpush(&work.empty, &b.node) } // putfull puts the workbuf on the work.full list for the GC. // putfull accepts partially full buffers so the GC can avoid competing // with the mutators for ownership of partially full buffers. //go:nowritebarrier func putfull(b *workbuf, entry int) { b.checknonempty() b.logput(entry) lfstackpush(&work.full, &b.node) } // getpartialorempty tries to return a partially empty // and if none are available returns an empty one. // entry is used to provide a brief histoy of ownership // using entry + xxx00000 to // indicating that two line numbers in the call chain. //go:nowritebarrier func getpartialorempty(entry int) *workbuf { var b *workbuf // If this m has a buf in currentwbuf then as an optimization // simply return that buffer. If it turns out currentwbuf // is full, put it on the work.full queue and get another // workbuf off the partial or empty queue. if getg().m.currentwbuf != 0 { b = (*workbuf)(unsafe.Pointer(xchguintptr(&getg().m.currentwbuf, 0))) if b != nil { if b.nobj <= len(b.obj) { return b } putfull(b, entry+80100000) } } b = (*workbuf)(lfstackpop(&work.partial)) if b != nil { b.logget(entry) return b } // Let getempty do the logget check but // use the entry to encode that it passed // through this routine. b = getempty(entry + 80700000) return b } // putpartial puts empty buffers on the work.empty queue, // full buffers on the work.full queue and // others on the work.partial queue. // entry is used to provide a brief histoy of ownership // using entry + xxx00000 to // indicating that two call chain line numbers. //go:nowritebarrier func putpartial(b *workbuf, entry int) { if b.nobj == 0 { putempty(b, entry+81500000) } else if b.nobj < len(b.obj) { b.logput(entry) lfstackpush(&work.partial, &b.node) } else if b.nobj == len(b.obj) { b.logput(entry) lfstackpush(&work.full, &b.node) } else { throw("putpartial: bad Workbuf b.nobj") } } // trygetfull tries to get a full or partially empty workbuffer. // If one is not immediately available return nil //go:nowritebarrier func trygetfull(entry int) *workbuf { b := (*workbuf)(lfstackpop(&work.full)) if b == nil { b = (*workbuf)(lfstackpop(&work.partial)) } if b != nil { b.logget(entry) b.checknonempty() return b } // full and partial are both empty so see if there // is an work available on currentwbuf. // This is an optimization to shift // processing from the STW marktermination phase into // the concurrent mark phase. if getg().m.currentwbuf != 0 { b = (*workbuf)(unsafe.Pointer(xchguintptr(&getg().m.currentwbuf, 0))) if b != nil { if b.nobj != 0 { return b } putempty(b, 839) b = nil } } return b } // Get a full work buffer off the work.full or a partially // filled one off the work.partial list. If nothing is available // wait until all the other gc helpers have finished and then // return nil. // getfull acts as a barrier for work.nproc helpers. As long as one // gchelper is actively marking objects it // may create a workbuffer that the other helpers can work on. // The for loop either exits when a work buffer is found // or when _all_ of the work.nproc GC helpers are in the loop // looking for work and thus not capable of creating new work. // This is in fact the termination condition for the STW mark // phase. //go:nowritebarrier func getfull(entry int) *workbuf { b := (*workbuf)(lfstackpop(&work.full)) if b != nil { b.logget(entry) b.checknonempty() return b } b = (*workbuf)(lfstackpop(&work.partial)) if b != nil { b.logget(entry) return b } // Make sure that currentwbuf is also not a source for pointers to be // processed. This is an optimization that shifts processing // from the mark termination STW phase to the concurrent mark phase. if getg().m.currentwbuf != 0 { b = (*workbuf)(unsafe.Pointer(xchguintptr(&getg().m.currentwbuf, 0))) if b != nil { if b.nobj != 0 { return b } putempty(b, 877) b = nil } } xadd(&work.nwait, +1) for i := 0; ; i++ { if work.full != 0 || work.partial != 0 { xadd(&work.nwait, -1) b = (*workbuf)(lfstackpop(&work.full)) if b == nil { b = (*workbuf)(lfstackpop(&work.partial)) } if b != nil { b.logget(entry) b.checknonempty() return b } xadd(&work.nwait, +1) } if work.nwait == work.nproc { return nil } _g_ := getg() if i < 10 { _g_.m.gcstats.nprocyield++ procyield(20) } else if i < 20 { _g_.m.gcstats.nosyield++ osyield() } else { _g_.m.gcstats.nsleep++ usleep(100) } } } //go:nowritebarrier func handoff(b *workbuf) *workbuf { // Make new buffer with half of b's pointers. b1 := getempty(915) n := b.nobj / 2 b.nobj -= n b1.nobj = n memmove(unsafe.Pointer(&b1.obj[0]), unsafe.Pointer(&b.obj[b.nobj]), uintptr(n)*unsafe.Sizeof(b1.obj[0])) _g_ := getg() _g_.m.gcstats.nhandoff++ _g_.m.gcstats.nhandoffcnt += uint64(n) // Put b on full list - let first half of b get stolen. putfull(b, 942) return b1 } // 1 when you are harvesting so that the write buffer code shade can // detect calls during a presumable STW write barrier. var harvestingwbufs uint32 // harvestwbufs moves non-empty workbufs to work.full from m.currentwuf // Must be in a STW phase. // xchguintptr is used since there are write barrier calls from the GC helper // routines even during a STW phase. // TODO: chase down write barrier calls in STW phase and understand and eliminate // them. //go:nowritebarrier func harvestwbufs() { // announce to write buffer that you are harvesting the currentwbufs atomicstore(&harvestingwbufs, 1) for mp := allm; mp != nil; mp = mp.alllink { wbuf := (*workbuf)(unsafe.Pointer(xchguintptr(&mp.currentwbuf, 0))) // TODO: beat write barriers out of the mark termination and eliminate xchg // tempwbuf := (*workbuf)(unsafe.Pointer(tempm.currentwbuf)) // tempm.currentwbuf = 0 if wbuf != nil { if wbuf.nobj == 0 { putempty(wbuf, 945) } else { putfull(wbuf, 947) //use full instead of partial so GC doesn't compete to get wbuf } } } atomicstore(&harvestingwbufs, 0) }
AnuchitPrasertsang/go
src/runtime/mgcwork.go
GO
bsd-3-clause
15,116
/* Copyright (C) 1997,1998,1999 Kenji Hiranabe, Eiwa System Management, Inc. This program is free software. Implemented by Kenji Hiranabe(hiranabe@esm.co.jp), conforming to the Java(TM) 3D API specification by Sun Microsystems. 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. Kenji Hiranabe and Eiwa System Management,Inc. makes no representations about the suitability of this software for any purpose. It is provided "AS IS" with NO WARRANTY. */ #include "Vector2.h" #include "Tuple2.h" #include "Point2.h" #ifdef VM_INCLUDE_NAMESPACE using namespace kh_vecmath; #endif /** * test-2 for Vector2 */ #ifdef TESTALL int test_2() { #else int main(int, char**) { #endif Point2d p1(1,2); Point2d p2(4,6); // distance Point2d::value_type d = p1.distance(p2); assert(fabs(d - 5) < 1.0e-5); // distance L1 d = p1.distanceL1(p2); assert(d == 7); // distance Linf d = p1.distanceLinf(p2); assert(d == 4); return 0; }
nocnokneo/MITK
Utilities/vecmath/test-2.cpp
C++
bsd-3-clause
1,252
<?php /* +---------------------------------------------------------------------------------+ | Copyright (c) 2014 César D. Rodas | +---------------------------------------------------------------------------------+ | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are met: | | 1. Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | | | 2. Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | | | 3. All advertising materials mentioning features or use of this software | | must display the following acknowledgement: | | This product includes software developed by César D. Rodas. | | | | 4. Neither the name of the César D. Rodas 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 CÉSAR D. RODAS ''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 CÉSAR D. RODAS 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 | +---------------------------------------------------------------------------------+ | Authors: César Rodas <crodas@php.net> | +---------------------------------------------------------------------------------+ */ namespace crodas\QuickAdmin\Input; abstract class TBase { protected $instance; protected $input; protected $ann; protected $col; protected $prefix; public function __construct($instance, $col, $input, $ann, $prefix = null) { $this->instance = $instance; $this->col = $col; $this->input = $input; $this->ann = $ann; $this->prefix = $prefix ?: $this->col['collection']; } public function setValue($property, $document, $value, $qa) { return $property->set($document, $value); } public function isRequired() { return $this->ann->has('Required'); } public static function label($text) { $label = ""; foreach (explode("_", $text) as $n) { $label .= ucfirst($n) . " "; } return $label; } public function getLabel() { return self::label($this->input['property']); } public function getName() { return $this->prefix . '[' . $this->input['property'] . ']'; } public function getId() { return substr('t' . sha1($this->getName()), 0, 9); } public function getArgs() { return ['id' => $this->getId(), 'class' => 'form-control']; } abstract public function getHtml($form); }
crodas/QuickAdmin
lib/crodas/QuickAdmin/Input/TBase.php
PHP
bsd-3-clause
4,197
package COM.claymoresystems.ptls; import COM.claymoresystems.util.Util; import java.security.MessageDigest; import xjava.security.Parameterized; import java.io.*; class TestPRF { static byte[] PMS={ (byte)0x03,(byte)0x01,(byte)0xfd,(byte)0x07,(byte)0x21,(byte)0xd5,(byte)0x44,(byte)0xf8, (byte)0xd1,(byte)0x60,(byte)0x8a,(byte)0xbe,(byte)0x8b,(byte)0x7e,(byte)0xab,(byte)0x7f, (byte)0xbd,(byte)0xea,(byte)0xc6,(byte)0x38,(byte)0x3f,(byte)0xd5,(byte)0x86,(byte)0x2d, (byte)0x03,(byte)0x80,(byte)0x4a,(byte)0x81,(byte)0xea,(byte)0x94,(byte)0x2a,(byte)0x2f, (byte)0x55,(byte)0x0f,(byte)0x05,(byte)0xb2,(byte)0x60,(byte)0xf0,(byte)0xeb,(byte)0xb2, (byte)0x4c,(byte)0x02,(byte)0xc0,(byte)0x44,(byte)0x39,(byte)0x44,(byte)0x8a,(byte)0x87 }; static byte[] CR={ (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00, (byte)0x32,(byte)0xf8,(byte)0x11,(byte)0x3c,(byte)0x0c,(byte)0x31,(byte)0x14,(byte)0x7f, (byte)0xe5,(byte)0xe7,(byte)0x03,(byte)0x29,(byte)0xd9,(byte)0x11,(byte)0x55,(byte)0x34 }; static byte[] SR={ (byte)0x3d,(byte)0x44,(byte)0x11,(byte)0xe1,(byte)0x01,(byte)0xde,(byte)0xb0,(byte)0x06, (byte)0xcd,(byte)0x0a,(byte)0x6b,(byte)0x7c,(byte)0xfd,(byte)0x1c,(byte)0xba,(byte)0x36, (byte)0xa0,(byte)0x44,(byte)0x2e,(byte)0xe0,(byte)0x40,(byte)0x89,(byte)0x95,(byte)0x78, (byte)0x67,(byte)0x41,(byte)0x6e,(byte)0x09,(byte)0x3e,(byte)0x7c,(byte)0x16,(byte)0x2f }; public static void main(String[] args){ SSLDebug.setDebug(8); COM.claymoresystems.ptls.LoadProviders.init(); TLSPRF prf=new TLSPRF(); byte[] out=new byte[48]; prf.PRF(PMS,SSLPRF.SSL_PRF_MASTER_SECRET, CR,SR,out); Util.xdump("MS",out); } }
NCIP/cagrid2
puretls/src/main/java/COM/claymoresystems/ptls/TestPRF.java
Java
bsd-3-clause
1,974
/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef VP9_COMMON_VP9_QUANT_COMMON_H_ #define VP9_COMMON_VP9_QUANT_COMMON_H_ #include "string.h" #include "vp9/common/vp9_blockd.h" #include "vp9/common/vp9_onyxc_int.h" extern void vp9_init_quant_tables(void); extern int vp9_ac_yquant(int QIndex); extern int vp9_dc_quant(int QIndex, int Delta); extern int vp9_dc2quant(int QIndex, int Delta); extern int vp9_ac2quant(int QIndex, int Delta); extern int vp9_dc_uv_quant(int QIndex, int Delta); extern int vp9_ac_uv_quant(int QIndex, int Delta); #endif // VP9_COMMON_VP9_QUANT_COMMON_H_
matsumoto-r/synciga
src/third_party/libvpx/source/libvpx/vp9/common/vp9_quant_common.h
C
bsd-3-clause
953
# Rubysl::Rake TODO: Write a gem description ## Installation Add this line to your application's Gemfile: gem 'rubysl-rake' And then execute: $ bundle Or install it yourself as: $ gem install rubysl-rake ## Usage TODO: Write usage instructions here ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
rubysl/rubysl-rake
README.md
Markdown
bsd-3-clause
510
SnakeComp is an AI competition based on the popular snake game. By implementing the SnakeControl interface (deciding in each turn in which direction a snake moves), participants can submit their snake control and let several snakes compete with each other. Besides being fun, this project can be used to learn programming with Java or to facilitate small programming competitions. # Getting started The project can be built using gradle creating an executable jar file. But you can also start it from the main class (control.Main) directly. There are already some simple snake controls in the package control.samples. You can take these as a starting point how to implement your own snake control. To integrate your snake control into the competition, you need to implement the control.SnakeControl interface and make your class part of the control.samples package. Please keep all code needed for your snake control (except imports of course) within one file. You can either select a folder in the UI where your snake control file is located or you can specify that folder as a parameter when executing the jar file or the main class. The UI will show you the maze where the snakes will move and some buttons and sliders to configure the settings of the competition. You can specify the size of the maze, the number of walls, whether the maze should have a border of walls (then it is called an arena), the zoom level, how many pieces of food per snake will be in the maze, how long the snakes are initially, how fast the snakes move, how long snakes survive without eating, and whether snakes re-appear after they die. On clicking the start button, the competition will start. You can either wait until the competition is finished or you can abort the competition by clicking the abort button. Moreover, the UI shows some status information about the snakes (their names, their current length, whether they are alive, and the maximum length they ever reached if snakes re-appear after they die). # Rules In each turn, each snake moves one field into some direction (UP, LEFT, DOWN, or RIGHT). If a snake moves on a field with food, its length increases by one. If a snake moves on a field with a wall or another snake part (possibly from itself), it crashes and dies. Moreover, if a snake does not move on a field with food for too many turns, it dies of hunger. The snake control needs to decide on a given maze and position of the snake's head in which direction to move next. This decision has to be computed within 200 milliseconds. If a snake control takes too long to compute the next direction, the next direction is always set to UP and the snake dies if its control took too long for three times (not necessarily in a row). # How to contribute Pull requests are always welcome. # Trouble Shooting In case you encounter a NullPointerException when trying to load snake controls from a folder, check whether your Java installation is properly configured such that a JDK (not only JRE) version of Java is being executed from any path. If that does not solve your problem, you can just add your snake control to the list in the Main class and start the competition with the argument "samples". Then the list of snake controls specified in the Main class will be used for the competition without loading these files via the dynamic compiler.
cryingshadow/SnakeComp
README.md
Markdown
bsd-3-clause
3,383
def rotate[A](startIdx: Int, inputAry: List[A]): List[A] = { val rotatedElems = if (startIdx < 0) inputAry.take(inputAry.size + startIdx) else inputAry.take(startIdx) val nochangeElems = if (startIdx < 0) inputAry.drop(inputAry.size + startIdx) else inputAry.drop(startIdx) nochangeElems ::: rotatedElems } /* scala> def rotate[A](startIdx: Int, inputAry: List[A]): List[A] = { | val rotatedElems = if (startIdx < 0) inputAry.take(inputAry.size + startIdx) else inputAry.take(startIdx) | val nochangeElems = if (startIdx < 0) inputAry.drop(inputAry.size + startIdx) else inputAry.drop(startIdx) | | nochangeElems ::: rotatedElems | } rotate: [A](startIdx: Int, inputAry: List[A])List[A] scala> rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)) res0: List[Symbol] = List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'a, 'b, 'c) scala> rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)) res1: List[Symbol] = List('j, 'k, 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i) */
zuqqhi2/s-99
p19.scala
Scala
bsd-3-clause
1,010
<!DOCTYPE html><html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <meta charset="utf-8"> <title>Zend AMF API Documentation » \Zend_Server_Abstract</title> <meta name="author" content="Mike van Riel"> <meta name="description" content=""> <link href="../css/template.css" rel="stylesheet" media="all"> <script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script><script src="../js/jquery-ui-1.8.2.custom.min.js" type="text/javascript"></script><script src="../js/jquery.mousewheel.min.js" type="text/javascript"></script><script src="../js/bootstrap.js" type="text/javascript"></script><script src="../js/template.js" type="text/javascript"></script><script src="../js/prettify/prettify.min.js" type="text/javascript"></script><link rel="shortcut icon" href="../img/favicon.ico"> <link rel="apple-touch-icon" href="../img/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"><div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></a><a class="brand" href="../index.html">Zend AMF API Documentation</a><div class="nav-collapse"><ul class="nav"> <li class="dropdown"> <a href="#api" class="dropdown-toggle" data-toggle="dropdown"> API Documentation <b class="caret"></b></a><ul class="dropdown-menu"> <li><a>Packages</a></li> <li><a href="../packages/Zend.html"><i class="icon-folder-open"></i> Zend</a></li> <li><a href="../packages/Zend_Amf.html"><i class="icon-folder-open"></i> Zend_Amf</a></li> <li><a href="../packages/Zend_Auth.html"><i class="icon-folder-open"></i> Zend_Auth</a></li> <li><a href="../packages/Zend_Date.html"><i class="icon-folder-open"></i> Zend_Date</a></li> <li><a href="../packages/Zend_Loader.html"><i class="icon-folder-open"></i> Zend_Loader</a></li> <li><a href="../packages/Zend_Server.html"><i class="icon-folder-open"></i> Zend_Server</a></li> <li><a href="../packages/Zend_Session.html"><i class="icon-folder-open"></i> Zend_Session</a></li> <li><a href="../packages/Zend_Version.html"><i class="icon-folder-open"></i> Zend_Version</a></li> </ul> </li> <li class="dropdown" id="reports-menu"> <a href="#reports" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b></a><ul class="dropdown-menu"> <li><a href="../errors.html"><i class="icon-remove-sign"></i> Errors  <span class="label label-info">77</span></a></li> <li><a href="../markers.html"><i class="icon-map-marker"></i> Markers  <ul></ul></a></li> <li><a href="../deprecated.html"><i class="icon-stop"></i> Deprecated elements  <span class="label label-info">5</span></a></li> </ul> </li> </ul></div> </div></div> <div class="go_to_top"><a href="#___" style="color: inherit">Back to top  <i class="icon-upload icon-white"></i></a></div> </div> <div id="___" class="container"> <noscript><div class="alert alert-warning"> Javascript is disabled; several features are only available if Javascript is enabled. </div></noscript> <div class="row"> <div class="span4"> <div xmlns:php="http://php.net/xsl" class="btn-toolbar"> <div class="btn-group visibility" data-toggle="buttons-checkbox"> <button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button> </div> <div class="btn-group view pull-right" data-toggle="buttons-radio"> <button class="btn details" title="Show descriptions and method names"><i class="icon-list"></i></button><button class="btn simple" title="Show only method names"><i class="icon-align-justify"></i></button> </div> </div> <ul xmlns:php="http://php.net/xsl" class="side-nav nav nav-list"> <li class="nav-header"> <i title="Methods" class="icon-custom icon-method"></i> Methods <ul> <li class="method public "><a href="#method___construct" title="__construct() :: Constructor"><span class="description">Constructor</span><pre>__construct()</pre></a></li> <li class="method public "><a href="#method_getFunctions" title="getFunctions() :: Returns a list of registered methods"><span class="description">Returns a list of registered methods</span><pre>getFunctions()</pre></a></li> <li class="method public "><a href="#method_lowerCase" title="lowerCase() :: Lowercase a string"><span class="description">Lowercase a string</span><pre>lowerCase()</pre></a></li> </ul> </li> <li class="nav-header protected">» Protected <ul> <li class="method protected "><a href="#method__buildCallback" title="_buildCallback() :: Build callback for method signature"><span class="description">Build callback for method signature</span><pre>_buildCallback()</pre></a></li> <li class="method protected "><a href="#method__buildSignature" title="_buildSignature() :: Build a method signature"><span class="description">Build a method signature</span><pre>_buildSignature()</pre></a></li> <li class="method protected "><a href="#method__dispatch" title="_dispatch() :: Dispatch method"><span class="description">Dispatch method</span><pre>_dispatch()</pre></a></li> <li class="method protected "><a href="#method__fixType" title="_fixType() :: Map PHP type to protocol type"><span class="description">Map PHP type to protocol type</span><pre>_fixType()</pre></a></li> </ul> </li> <li class="nav-header"> <i title="Properties" class="icon-custom icon-property"></i> Properties <ul></ul> </li> <li class="nav-header protected">» Protected <ul> <li class="property protected "><a href="#property__overwriteExistingMethods" title="$_overwriteExistingMethods() :: "><span class="description">Flag; whether or not overwriting existing methods is allowed</span><pre>$_overwriteExistingMethods</pre></a></li> <li class="property protected "><a href="#property__table" title="$_table() :: "><span class="description"></span><pre>$_table</pre></a></li> <li class="property protected "><a href="#property_magic_methods" title="$magic_methods() :: "><span class="description">List of PHP magic methods (lowercased)</span><pre>$magic_methods</pre></a></li> </ul> </li> </ul> </div> <div class="span8"> <a xmlns:php="http://php.net/xsl" id="\Zend_Server_Abstract"></a><ul xmlns:php="http://php.net/xsl" class="breadcrumb"> <li> <a href="../index.html"><i title="Classes" class="icon-custom icon-class"></i></a><span class="divider">\</span> </li> <li class="active"> <span class="divider">\</span><a href="../classes/Zend_Server_Abstract.html">Zend_Server_Abstract</a> </li> </ul> <div xmlns:php="http://php.net/xsl" class="element class"> <p class="short_description">Zend_Server_Abstract</p> <div class="details"> <div class="long_description"></div> <table class="table table-bordered"> <tr> <th>category</th> <td>Zend</td> </tr> <tr> <th>package</th> <td><a href="../packages/Zend_Server.html">Zend_Server</a></td> </tr> <tr> <th>copyright</th> <td>Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)</td> </tr> <tr> <th>license</th> <td><a href="http://framework.zend.com/license/new-bsd">New BSD License</a></td> </tr> <tr> <th>version</th> <td>$Id$</td> </tr> </table> <h3> <i title="Methods" class="icon-custom icon-method"></i> Methods</h3> <a id="method___construct"></a><div class="element clickable method public method___construct " data-toggle="collapse" data-target=".method___construct .collapse" title="public"> <h2>Constructor</h2> <pre>__construct() : void</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"><p>Setup server description</p></div></div></div> </div> <a id="method_getFunctions"></a><div class="element clickable method public method_getFunctions " data-toggle="collapse" data-target=".method_getFunctions .collapse" title="public"> <h2>Returns a list of registered methods</h2> <pre>getFunctions() : \Zend_Server_Definition</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"><p>Returns an array of method definitions.</p></div> <table class="table table-bordered"><tr> <th>inherited_from</th> <td>\Zend_Server_Interface::getFunctions()</td> </tr></table> <h3>Returns</h3> <div class="subelement response"><code>\Zend_Server_Definition</code></div> </div></div> </div> <a id="method_lowerCase"></a><div class="element clickable method public method_lowerCase " data-toggle="collapse" data-target=".method_lowerCase .collapse" title="public"> <h2>Lowercase a string</h2> <pre>lowerCase($value, string $key) : string</pre> <div class="labels"><span class="label">Static</span></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"><p>Lowercase's a string by reference</p></div> <table class="table table-bordered"><tr> <th>deprecated</th> <td></td> </tr></table> <h3>Parameters</h3> <div class="subelement argument"><h4>$value</h4></div> <div class="subelement argument"> <h4>$key</h4> <code>string</code> </div> <h3>Returns</h3> <div class="subelement response"> <code>string</code>Lower cased string</div> </div></div> </div> <a id="method__buildCallback"></a><div class="element clickable method protected method__buildCallback " data-toggle="collapse" data-target=".method__buildCallback .collapse" title="protected"> <h2>Build callback for method signature</h2> <pre>_buildCallback(\Zend_Server_Reflection_Function_Abstract $reflection) : \Zend_Server_Method_Callback</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <h3>Parameters</h3> <div class="subelement argument"> <h4>$reflection</h4> <code>\Zend_Server_Reflection_Function_Abstract</code> </div> <h3>Returns</h3> <div class="subelement response"><code>\Zend_Server_Method_Callback</code></div> </div></div> </div> <a id="method__buildSignature"></a><div class="element clickable method protected method__buildSignature " data-toggle="collapse" data-target=".method__buildSignature .collapse" title="protected"> <h2>Build a method signature</h2> <pre>_buildSignature(\Zend_Server_Reflection_Function_Abstract $reflection, null|string|object $class<code> = null</code>) : \Zend_Server_Method_Definition</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <h3>Parameters</h3> <div class="subelement argument"> <h4>$reflection</h4> <code>\Zend_Server_Reflection_Function_Abstract</code> </div> <div class="subelement argument"> <h4>$class</h4> <code>null</code><code>string</code><code>object</code> </div> <h3>Exceptions</h3> <table class="table table-bordered"><tr> <th><code>\Zend_Server_Exception</code></th> <td>on duplicate entry</td> </tr></table> <h3>Returns</h3> <div class="subelement response"><code>\Zend_Server_Method_Definition</code></div> </div></div> </div> <a id="method__dispatch"></a><div class="element clickable method protected method__dispatch " data-toggle="collapse" data-target=".method__dispatch .collapse" title="protected"> <h2>Dispatch method</h2> <pre>_dispatch(\Zend_Server_Method_Definition $invocable, array $params) : mixed</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <h3>Parameters</h3> <div class="subelement argument"> <h4>$invocable</h4> <code>\Zend_Server_Method_Definition</code> </div> <div class="subelement argument"> <h4>$params</h4> <code>array</code> </div> <h3>Returns</h3> <div class="subelement response"><code>mixed</code></div> </div></div> </div> <a id="method__fixType"></a><div class="element clickable method protected method__fixType " data-toggle="collapse" data-target=".method__fixType .collapse" title="protected"> <h2>Map PHP type to protocol type</h2> <pre>_fixType(string $type) : string</pre> <div class="labels"></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <h3>Parameters</h3> <div class="subelement argument"> <h4>$type</h4> <code>string</code> </div> <h3>Returns</h3> <div class="subelement response"><code>string</code></div> </div></div> </div> <h3> <i title="Properties" class="icon-custom icon-property"></i> Properties</h3> <a id="property__overwriteExistingMethods"> </a><div class="element clickable property protected property__overwriteExistingMethods" data-toggle="collapse" data-target=".property__overwriteExistingMethods .collapse" title="protected"> <h2>Flag; whether or not overwriting existing methods is allowed</h2> <pre>$_overwriteExistingMethods : boolean</pre> <div class="row collapse"><div class="detail-description"> <h3>Default</h3> <div class="subelement argument"><code>false</code></div> </div></div> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> <a id="property__table"> </a><div class="element clickable property protected property__table" data-toggle="collapse" data-target=".property__table .collapse" title="protected"> <h2>$_table</h2> <pre>$_table : \Zend_Server_Definition</pre> <div class="row collapse"><div class="detail-description"> <h3>Default</h3> <div class="subelement argument"></div> </div></div> <div class="labels"></div> <div class="row collapse"><div class="detail-description"><div class="long_description"></div></div></div> </div> <a id="property_magic_methods"> </a><div class="element clickable property protected property_magic_methods" data-toggle="collapse" data-target=".property_magic_methods .collapse" title="protected"> <h2>List of PHP magic methods (lowercased)</h2> <pre>$magic_methods : array</pre> <div class="row collapse"><div class="detail-description"> <h3>Default</h3> <div class="subelement argument"><code>array('__call', '__clone', '__construct', '__destruct', '__get', '__isset', '__set', '__set_state', '__sleep', '__tostring', '__unset', '__wakeup')</code></div> </div></div> <div class="labels"><span class="label">Static</span></div> <div class="row collapse"><div class="detail-description"> <div class="long_description"></div> <table class="table table-bordered"><tr> <th>deprecated</th> <td></td> </tr></table> </div></div> </div> </div> </div> </div> </div> <div class="row"><footer class="span12"> Template is built using <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap 2</a> and icons provided by <a href="http://glyphicons.com/">Glyphicons</a>.<br> Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor 2.8.5</a> and<br> generated on 2015-11-23T12:38:54-06:00.<br></footer></div> </div> </body> </html>
Notan/awery_zend_amf
documentation/api/core/classes/Zend_Server_Abstract.html
HTML
bsd-3-clause
15,436
import numpy as np from numpy.testing import (assert_equal, assert_almost_equal, assert_raises) import skimage from skimage import data from skimage._shared._warnings import expected_warnings from skimage.filters.thresholding import (threshold_adaptive, threshold_otsu, threshold_li, threshold_yen, threshold_isodata, threshold_mean, threshold_triangle, threshold_minimum) class TestSimpleImage(): def setup(self): self.image = np.array([[0, 0, 1, 3, 5], [0, 1, 4, 3, 4], [1, 2, 5, 4, 1], [2, 4, 5, 2, 1], [4, 5, 1, 0, 0]], dtype=int) def test_otsu(self): assert threshold_otsu(self.image) == 2 def test_otsu_negative_int(self): image = self.image - 2 assert threshold_otsu(image) == 0 def test_otsu_float_image(self): image = np.float64(self.image) assert 2 <= threshold_otsu(image) < 3 def test_li(self): assert int(threshold_li(self.image)) == 2 def test_li_negative_int(self): image = self.image - 2 assert int(threshold_li(image)) == 0 def test_li_float_image(self): image = np.float64(self.image) assert 2 <= threshold_li(image) < 3 def test_li_constant_image(self): assert_raises(ValueError, threshold_li, np.ones((10,10))) def test_yen(self): assert threshold_yen(self.image) == 2 def test_yen_negative_int(self): image = self.image - 2 assert threshold_yen(image) == 0 def test_yen_float_image(self): image = np.float64(self.image) assert 2 <= threshold_yen(image) < 3 def test_yen_arange(self): image = np.arange(256) assert threshold_yen(image) == 127 def test_yen_binary(self): image = np.zeros([2, 256], dtype=np.uint8) image[0] = 255 assert threshold_yen(image) < 1 def test_yen_blank_zero(self): image = np.zeros((5, 5), dtype=np.uint8) assert threshold_yen(image) == 0 def test_yen_blank_max(self): image = np.empty((5, 5), dtype=np.uint8) image.fill(255) assert threshold_yen(image) == 255 def test_isodata(self): assert threshold_isodata(self.image) == 2 assert threshold_isodata(self.image, return_all=True) == [2] def test_isodata_blank_zero(self): image = np.zeros((5, 5), dtype=np.uint8) assert threshold_isodata(image) == 0 assert threshold_isodata(image, return_all=True) == [0] def test_isodata_linspace(self): image = np.linspace(-127, 0, 256) assert -63.8 < threshold_isodata(image) < -63.6 assert_almost_equal(threshold_isodata(image, return_all=True), [-63.74804688, -63.25195312]) def test_isodata_16bit(self): np.random.seed(0) imfloat = np.random.rand(256, 256) assert 0.49 < threshold_isodata(imfloat, nbins=1024) < 0.51 assert all(0.49 < threshold_isodata(imfloat, nbins=1024, return_all=True)) def test_threshold_adaptive_generic(self): def func(arr): return arr.sum() / arr.shape[0] ref = np.array( [[False, False, False, False, True], [False, False, True, False, True], [False, False, True, True, False], [False, True, True, False, False], [ True, True, False, False, False]] ) out = threshold_adaptive(self.image, 3, method='generic', param=func) assert_equal(ref, out) def test_threshold_adaptive_gaussian(self): ref = np.array( [[False, False, False, False, True], [False, False, True, False, True], [False, False, True, True, False], [False, True, True, False, False], [ True, True, False, False, False]] ) out = threshold_adaptive(self.image, 3, method='gaussian') assert_equal(ref, out) out = threshold_adaptive(self.image, 3, method='gaussian', param=1./3.) assert_equal(ref, out) def test_threshold_adaptive_mean(self): ref = np.array( [[False, False, False, False, True], [False, False, True, False, True], [False, False, True, True, False], [False, True, True, False, False], [ True, True, False, False, False]] ) out = threshold_adaptive(self.image, 3, method='mean') assert_equal(ref, out) def test_threshold_adaptive_median(self): ref = np.array( [[False, False, False, False, True], [False, False, True, False, False], [False, False, True, False, False], [False, False, True, True, False], [False, True, False, False, False]] ) out = threshold_adaptive(self.image, 3, method='median') assert_equal(ref, out) def test_otsu_camera_image(): camera = skimage.img_as_ubyte(data.camera()) assert 86 < threshold_otsu(camera) < 88 def test_otsu_coins_image(): coins = skimage.img_as_ubyte(data.coins()) assert 106 < threshold_otsu(coins) < 108 def test_otsu_coins_image_as_float(): coins = skimage.img_as_float(data.coins()) assert 0.41 < threshold_otsu(coins) < 0.42 def test_otsu_astro_image(): img = skimage.img_as_ubyte(data.astronaut()) with expected_warnings(['grayscale']): assert 109 < threshold_otsu(img) < 111 def test_otsu_one_color_image(): img = np.ones((10, 10), dtype=np.uint8) assert_raises(ValueError, threshold_otsu, img) def test_li_camera_image(): camera = skimage.img_as_ubyte(data.camera()) assert 63 < threshold_li(camera) < 65 def test_li_coins_image(): coins = skimage.img_as_ubyte(data.coins()) assert 95 < threshold_li(coins) < 97 def test_li_coins_image_as_float(): coins = skimage.img_as_float(data.coins()) assert 0.37 < threshold_li(coins) < 0.38 def test_li_astro_image(): img = skimage.img_as_ubyte(data.astronaut()) assert 66 < threshold_li(img) < 68 def test_yen_camera_image(): camera = skimage.img_as_ubyte(data.camera()) assert 197 < threshold_yen(camera) < 199 def test_yen_coins_image(): coins = skimage.img_as_ubyte(data.coins()) assert 109 < threshold_yen(coins) < 111 def test_yen_coins_image_as_float(): coins = skimage.img_as_float(data.coins()) assert 0.43 < threshold_yen(coins) < 0.44 def test_adaptive_even_block_size_error(): img = data.camera() assert_raises(ValueError, threshold_adaptive, img, block_size=4) def test_isodata_camera_image(): camera = skimage.img_as_ubyte(data.camera()) threshold = threshold_isodata(camera) assert np.floor((camera[camera <= threshold].mean() + camera[camera > threshold].mean()) / 2.0) == threshold assert threshold == 87 assert threshold_isodata(camera, return_all=True) == [87] def test_isodata_coins_image(): coins = skimage.img_as_ubyte(data.coins()) threshold = threshold_isodata(coins) assert np.floor((coins[coins <= threshold].mean() + coins[coins > threshold].mean()) / 2.0) == threshold assert threshold == 107 assert threshold_isodata(coins, return_all=True) == [107] def test_isodata_moon_image(): moon = skimage.img_as_ubyte(data.moon()) threshold = threshold_isodata(moon) assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert threshold == 86 thresholds = threshold_isodata(moon, return_all=True) for threshold in thresholds: assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert_equal(thresholds, [86, 87, 88, 122, 123, 124, 139, 140]) def test_isodata_moon_image_negative_int(): moon = skimage.img_as_ubyte(data.moon()).astype(np.int32) moon -= 100 threshold = threshold_isodata(moon) assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert threshold == -14 thresholds = threshold_isodata(moon, return_all=True) for threshold in thresholds: assert np.floor((moon[moon <= threshold].mean() + moon[moon > threshold].mean()) / 2.0) == threshold assert_equal(thresholds, [-14, -13, -12, 22, 23, 24, 39, 40]) def test_isodata_moon_image_negative_float(): moon = skimage.img_as_ubyte(data.moon()).astype(np.float64) moon -= 100 assert -14 < threshold_isodata(moon) < -13 thresholds = threshold_isodata(moon, return_all=True) assert_almost_equal(thresholds, [-13.83789062, -12.84179688, -11.84570312, 22.02148438, 23.01757812, 24.01367188, 38.95507812, 39.95117188]) def test_threshold_minimum(): camera = skimage.img_as_ubyte(data.camera()) threshold = threshold_minimum(camera) assert threshold == 76 threshold = threshold_minimum(camera, bias='max') assert threshold == 77 astronaut = skimage.img_as_ubyte(data.astronaut()) threshold = threshold_minimum(astronaut) assert threshold == 117 def test_threshold_minimum_synthetic(): img = np.arange(25*25, dtype=np.uint8).reshape((25, 25)) img[0:9, :] = 50 img[14:25, :] = 250 threshold = threshold_minimum(img, bias='min') assert threshold == 93 threshold = threshold_minimum(img, bias='mid') assert threshold == 159 threshold = threshold_minimum(img, bias='max') assert threshold == 225 def test_threshold_minimum_failure(): img = np.zeros((16*16), dtype=np.uint8) assert_raises(RuntimeError, threshold_minimum, img) def test_mean(): img = np.zeros((2, 6)) img[:, 2:4] = 1 img[:, 4:] = 2 assert(threshold_mean(img) == 1.) def test_triangle_uint_images(): assert(threshold_triangle(np.invert(data.text())) == 151) assert(threshold_triangle(data.text()) == 104) assert(threshold_triangle(data.coins()) == 80) assert(threshold_triangle(np.invert(data.coins())) == 175) def test_triangle_float_images(): text = data.text() int_bins = text.max() - text.min() + 1 # Set nbins to match the uint case and threshold as float. assert(round(threshold_triangle( text.astype(np.float), nbins=int_bins)) == 104) # Check that rescaling image to floats in unit interval is equivalent. assert(round(threshold_triangle(text / 255., nbins=int_bins) * 255) == 104) # Repeat for inverted image. assert(round(threshold_triangle( np.invert(text).astype(np.float), nbins=int_bins)) == 151) assert (round(threshold_triangle( np.invert(text) / 255., nbins=int_bins) * 255) == 151) def test_triangle_flip(): # Depending on the skewness, the algorithm flips the histogram. # We check that the flip doesn't affect too much the result. img = data.camera() inv_img = np.invert(img) t = threshold_triangle(inv_img) t_inv_img = inv_img > t t_inv_inv_img = np.invert(t_inv_img) t = threshold_triangle(img) t_img = img > t # Check that most of the pixels are identical # See numpy #7685 for a future np.testing API unequal_pos = np.where(t_img.ravel() != t_inv_inv_img.ravel()) assert(len(unequal_pos[0]) / t_img.size < 1e-2) if __name__ == '__main__': np.testing.run_module_suite()
vighneshbirodkar/scikit-image
skimage/filters/tests/test_thresholding.py
Python
bsd-3-clause
11,985
/* * Copyright (c) 2009, Pirate Party Switzerland * All rights reserved. * * Licensed under the New BSD License as seen in License.txt */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Pirate.PiVote.Serialization; namespace Pirate.PiVote.Crypto { /// <summary> /// Information that accompanies a request for a signature by a CA. /// </summary> [SerializeObject("Information that accompanies a request for a signature by a CA.")] public class SignatureRequestInfo : Serializable { /// <summary> /// Email address of requester. /// </summary> [SerializeField(0, "Email address of requester.")] public string EmailAddress { get; private set; } /// <summary> /// Encrypted request data. /// </summary> [SerializeField(1, "Encrypted request data.", 1)] public byte[] EncryptedSignatureRequest { get; private set; } public override byte Version { get { return 1; } } /// <summary> /// Is this request info valid? /// </summary> /// <remarks> /// Email address can be empty. If so you won't get any emails. /// </remarks> public bool Valid { get { return EmailAddress.IsNullOrEmpty() || Mailer.IsEmailAddressValid(EmailAddress); } } /// <summary> /// Create a new signature request. /// </summary> /// <param name="emailAddress">Email address of requester.</param> /// <param name="fromDataHash">Symmetrically encrypted signature request.</param> public SignatureRequestInfo(string emailAddress, byte[] encryptedSignatureRequest) { EmailAddress = emailAddress; EncryptedSignatureRequest = encryptedSignatureRequest; } /// <summary> /// Creates an object by deserializing from binary data. /// </summary> /// <param name="context">Context for deserialization.</param> public SignatureRequestInfo(DeserializeContext context, byte version) : base(context, version) { } /// <summary> /// Serializes the object to binary. /// </summary> /// <param name="context">Context for serializable.</param> public override void Serialize(SerializeContext context) { base.Serialize(context); context.Write(EmailAddress); context.Write(EncryptedSignatureRequest); } /// <summary> /// Deserializes binary data to object. /// </summary> /// <param name="context">Context for deserialization</param> protected override void Deserialize(DeserializeContext context, byte version) { base.Deserialize(context, version); EmailAddress = context.ReadString(); if (version >= 1) { EncryptedSignatureRequest = context.ReadBytes(); } else { EncryptedSignatureRequest = new byte[0]; } } } }
dbrgn/pi-vote
Common/Crypto/Certificate/SignatureRequestInfo.cs
C#
bsd-3-clause
2,995