code
stringlengths
4
1.01M
language
stringclasses
2 values
class Blog < ActiveRecord::Base has_many :posts has_many :comments, :through => :posts attr_accessible :name, :subdomain searchable :include => { :posts => :author } do string :subdomain text :name end # Make sure that includes are added to with multiple searchable calls searchable(:include => :comments) {} end
Java
<!doctype html> <html> <title>shrinkwrap</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../static/style.css"> <body> <div id="wrapper"> <h1><a href="../doc/shrinkwrap.html">shrinkwrap</a></h1> <p>Lock down dependency versions</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm shrinkwrap</code></pre> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>This command locks down the versions of a package&#39;s dependencies so that you can control exactly which versions of each dependency will be used when your package is installed.</p> <p>By default, &quot;npm install&quot; recursively installs the target&#39;s dependencies (as specified in package.json), choosing the latest available version that satisfies the dependency&#39;s semver pattern. In some situations, particularly when shipping software where each change is tightly managed, it&#39;s desirable to fully specify each version of each dependency recursively so that subsequent builds and deploys do not inadvertently pick up newer versions of a dependency that satisfy the semver pattern. Specifying specific semver patterns in each dependency&#39;s package.json would facilitate this, but that&#39;s not always possible or desirable, as when another author owns the npm package. It&#39;s also possible to check dependencies directly into source control, but that may be undesirable for other reasons.</p> <p>As an example, consider package A:</p> <pre><code>{ &quot;name&quot;: &quot;A&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;dependencies&quot;: { &quot;B&quot;: &quot;&lt;0.1.0&quot; } }</code></pre> <p>package B:</p> <pre><code>{ &quot;name&quot;: &quot;B&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: { &quot;C&quot;: &quot;&lt;0.1.0&quot; } }</code></pre> <p>and package C:</p> <pre><code>{ &quot;name&quot;: &quot;C, &quot;version&quot;: &quot;0.0.1&quot; }</code></pre> <p>If these are the only versions of A, B, and C available in the registry, then a normal &quot;npm install A&quot; will install:</p> <pre><code>[email protected] `-- [email protected] `-- [email protected]</code></pre> <p>However, if [email protected] is published, then a fresh &quot;npm install A&quot; will install:</p> <pre><code>[email protected] `-- [email protected] `-- [email protected]</code></pre> <p>assuming the new version did not modify B&#39;s dependencies. Of course, the new version of B could include a new version of C and any number of new dependencies. If such changes are undesirable, the author of A could specify a dependency on [email protected]. However, if A&#39;s author and B&#39;s author are not the same person, there&#39;s no way for A&#39;s author to say that he or she does not want to pull in newly published versions of C when B hasn&#39;t changed at all.</p> <p>In this case, A&#39;s author can run</p> <pre><code>npm shrinkwrap</code></pre> <p>This generates npm-shrinkwrap.json, which will look something like this:</p> <pre><code>{ &quot;name&quot;: &quot;A&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;dependencies&quot;: { &quot;B&quot;: { &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: { &quot;C&quot;: { &quot;version&quot;: &quot;0.1.0&quot; } } } } }</code></pre> <p>The shrinkwrap command has locked down the dependencies based on what&#39;s currently installed in node_modules. When &quot;npm install&quot; installs a package with a npm-shrinkwrap.json file in the package root, the shrinkwrap file (rather than package.json files) completely drives the installation of that package and all of its dependencies (recursively). So now the author publishes [email protected], and subsequent installs of this package will use [email protected] and [email protected], regardless the dependencies and versions listed in A&#39;s, B&#39;s, and C&#39;s package.json files.</p> <h3 id="Using-shrinkwrapped-packages">Using shrinkwrapped packages</h3> <p>Using a shrinkwrapped package is no different than using any other package: you can &quot;npm install&quot; it by hand, or add a dependency to your package.json file and &quot;npm install&quot; it.</p> <h3 id="Building-shrinkwrapped-packages">Building shrinkwrapped packages</h3> <p>To shrinkwrap an existing package:</p> <ol><li>Run &quot;npm install&quot; in the package root to install the current versions of all dependencies.</li><li>Validate that the package works as expected with these versions.</li><li>Run &quot;npm shrinkwrap&quot;, add npm-shrinkwrap.json to git, and publish your package.</li></ol> <p>To add or update a dependency in a shrinkwrapped package:</p> <ol><li>Run &quot;npm install&quot; in the package root to install the current versions of all dependencies.</li><li>Add or update dependencies. &quot;npm install&quot; each new or updated package individually and then update package.json. Note that they must be explicitly named in order to be installed: running <code>npm install</code> with no arguments will merely reproduce the existing shrinkwrap.</li><li>Validate that the package works as expected with the new dependencies.</li><li>Run &quot;npm shrinkwrap&quot;, commit the new npm-shrinkwrap.json, and publish your package.</li></ol> <p>You can use <a href="../doc/outdated.html">outdated(1)</a> to view dependencies with newer versions available.</p> <h3 id="Other-Notes">Other Notes</h3> <p>Since &quot;npm shrinkwrap&quot; uses the locally installed packages to construct the shrinkwrap file, devDependencies will be included if and only if you&#39;ve installed them already when you make the shrinkwrap.</p> <p>A shrinkwrap file must be consistent with the package&#39;s package.json file. &quot;npm shrinkwrap&quot; will fail if required dependencies are not already installed, since that would result in a shrinkwrap that wouldn&#39;t actually work. Similarly, the command will fail if there are extraneous packages (not referenced by package.json), since that would indicate that package.json is not correct.</p> <p>If shrinkwrapped package A depends on shrinkwrapped package B, B&#39;s shrinkwrap will not be used as part of the installation of A. However, because A&#39;s shrinkwrap is constructed from a valid installation of B and recursively specifies all dependencies, the contents of B&#39;s shrinkwrap will implicitly be included in A&#39;s shrinkwrap.</p> <h3 id="Caveats">Caveats</h3> <p>Shrinkwrap files only lock down package versions, not actual package contents. While discouraged, a package author can republish an existing version of a package, causing shrinkwrapped packages using that version to pick up different code than they were before. If you want to avoid any risk that a byzantine author replaces a package you&#39;re using with code that breaks your application, you could modify the shrinkwrap file to use git URL references rather than version numbers so that npm always fetches all packages from git.</p> <p>If you wish to lock down the specific bytes included in a package, for example to have 100% confidence in being able to reproduce a deployment or build, then you ought to check your dependencies into source control, or pursue some other mechanism that can verify contents rather than versions.</p> <h2 id="SEE-ALSO">SEE ALSO</h2> <ul><li><a href="../doc/install.html">install(1)</a></li><li><a href="../doc/json.html">json(1)</a></li><li><a href="../doc/list.html">list(1)</a></li></ul> </div> <p id="footer">shrinkwrap &mdash; [email protected]</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l -- } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script> </body></html>
Java
from __future__ import unicode_literals __all__ = ( 'Key', 'Keys', ) class Key(object): def __init__(self, name): #: Descriptive way of writing keys in configuration files. e.g. <C-A> #: for ``Control-A``. self.name = name def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.name) class Keys(object): Escape = Key('<Escape>') ControlA = Key('<C-A>') ControlB = Key('<C-B>') ControlC = Key('<C-C>') ControlD = Key('<C-D>') ControlE = Key('<C-E>') ControlF = Key('<C-F>') ControlG = Key('<C-G>') ControlH = Key('<C-H>') ControlI = Key('<C-I>') # Tab ControlJ = Key('<C-J>') # Enter ControlK = Key('<C-K>') ControlL = Key('<C-L>') ControlM = Key('<C-M>') # Enter ControlN = Key('<C-N>') ControlO = Key('<C-O>') ControlP = Key('<C-P>') ControlQ = Key('<C-Q>') ControlR = Key('<C-R>') ControlS = Key('<C-S>') ControlT = Key('<C-T>') ControlU = Key('<C-U>') ControlV = Key('<C-V>') ControlW = Key('<C-W>') ControlX = Key('<C-X>') ControlY = Key('<C-Y>') ControlZ = Key('<C-Z>') ControlSpace = Key('<C-Space>') ControlBackslash = Key('<C-Backslash>') ControlSquareClose = Key('<C-SquareClose>') ControlCircumflex = Key('<C-Circumflex>') ControlUnderscore = Key('<C-Underscore>') ControlLeft = Key('<C-Left>') ControlRight = Key('<C-Right>') ControlUp = Key('<C-Up>') ControlDown = Key('<C-Down>') Up = Key('<Up>') Down = Key('<Down>') Right = Key('<Right>') Left = Key('<Left>') Home = Key('<Home>') End = Key('<End>') Delete = Key('<Delete>') ShiftDelete = Key('<ShiftDelete>') PageUp = Key('<PageUp>') PageDown = Key('<PageDown>') BackTab = Key('<BackTab>') # shift + tab Tab = ControlI Backspace = ControlH F1 = Key('<F1>') F2 = Key('<F2>') F3 = Key('<F3>') F4 = Key('<F4>') F5 = Key('<F5>') F6 = Key('<F6>') F7 = Key('<F7>') F8 = Key('<F8>') F9 = Key('<F9>') F10 = Key('<F10>') F11 = Key('<F11>') F12 = Key('<F12>') F13 = Key('<F13>') F14 = Key('<F14>') F15 = Key('<F15>') F16 = Key('<F16>') F17 = Key('<F17>') F18 = Key('<F18>') F19 = Key('<F19>') F20 = Key('<F20>') # Matches any key. Any = Key('<Any>') # Special CPRResponse = Key('<Cursor-Position-Response>')
Java
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project 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 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 org.hisp.dhis.expression; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.hisp.dhis.analytics.DataType; import org.hisp.dhis.common.DimensionalItemId; import org.hisp.dhis.common.DimensionalItemObject; import org.hisp.dhis.constant.Constant; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.indicator.IndicatorValue; import org.hisp.dhis.organisationunit.OrganisationUnitGroup; import org.hisp.dhis.period.Period; /** * Expressions are mathematical formulas and can contain references to various * elements. * * @author Margrethe Store * @author Lars Helge Overland * @author Jim Grace */ public interface ExpressionService { String ID = ExpressionService.class.getName(); String DAYS_DESCRIPTION = "[Number of days]"; String SYMBOL_DAYS = "[days]"; String SYMBOL_WILDCARD = "*"; String UID_EXPRESSION = "[a-zA-Z]\\w{10}"; String INT_EXPRESSION = "^(0|-?[1-9]\\d*)$"; // ------------------------------------------------------------------------- // Expression CRUD operations // ------------------------------------------------------------------------- /** * Adds a new Expression to the database. * * @param expression The Expression to add. * @return The generated identifier for this Expression. */ long addExpression( Expression expression ); /** * Updates an Expression. * * @param expression The Expression to update. */ void updateExpression( Expression expression ); /** * Deletes an Expression from the database. * * @param expression the expression. */ void deleteExpression( Expression expression ); /** * Get the Expression with the given identifier. * * @param id The identifier. * @return an Expression with the given identifier. */ Expression getExpression( long id ); /** * Gets all Expressions. * * @return A list with all Expressions. */ List<Expression> getAllExpressions(); // ------------------------------------------------------------------------- // Indicator expression logic // ------------------------------------------------------------------------- /** * Returns all dimensional item objects which are present in numerator and * denominator of the given indicators, as a map from id to object. * * @param indicators the collection of indicators. * @return a map from dimensional item id to object. */ Map<DimensionalItemId, DimensionalItemObject> getIndicatorDimensionalItemMap( Collection<Indicator> indicators ); /** * Returns all OrganisationUnitGroups in the numerator and denominator * expressions in the given Indicators. Returns an empty set if the given * indicators are null or empty. * * @param indicators the set of indicators. * @return a Set of OrganisationUnitGroups. */ List<OrganisationUnitGroup> getOrgUnitGroupCountGroups( Collection<Indicator> indicators ); /** * Generates the calculated value for the given parameters based on the * values in the given maps. * * @param indicator the indicator for which to calculate the value. * @param periods a List of periods for which to calculate the value. * @param itemMap map of dimensional item id to object in expression. * @param valueMap the map of data values. * @param orgUnitCountMap the map of organisation unit group member counts. * @return the calculated value as a double. */ IndicatorValue getIndicatorValueObject( Indicator indicator, List<Period> periods, Map<DimensionalItemId, DimensionalItemObject> itemMap, Map<DimensionalItemObject, Object> valueMap, Map<String, Integer> orgUnitCountMap ); /** * Substitutes any constants and org unit group member counts in the * numerator and denominator on all indicators in the given collection. * * @param indicators the set of indicators. */ void substituteIndicatorExpressions( Collection<Indicator> indicators ); // ------------------------------------------------------------------------- // Get information about the expression // ------------------------------------------------------------------------- /** * Tests whether the expression is valid. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return the ExpressionValidationOutcome of the validation. */ ExpressionValidationOutcome expressionIsValid( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * DimensionalItemObjects from a numeric valued expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return An description containing DimensionalItemObjects names. */ String getExpressionDescription( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * DimensionalItemObjects from an expression string, for an expression that * will return the specified data type. * * @param expression the expression string. * @param parseType the type of expression to parse. * @param dataType the data type for the expression to return. * @return An description containing DimensionalItemObjects names. */ String getExpressionDescription( String expression, ParseType parseType, DataType dataType ); /** * Gets information we need from an expression string. * * @param params the expression parameters. * @return the expression information. */ ExpressionInfo getExpressionInfo( ExpressionParams params ); /** * From expression info, create a "base" expression parameters object with * certain metadata fields supplied that are needed for later evaluation. * <p> * Before evaluation, the caller will need to add to this "base" object * fields such as expression, parseType, dataType, valueMap, etc. * * @param info the expression information. * @return the expression parameters with metadata pre-filled. */ ExpressionParams getBaseExpressionParams( ExpressionInfo info ); /** * Returns UIDs of Data Elements and associated Option Combos (if any) found * in the Data Element Operands an expression. * <p/> * If the Data Element Operand consists of just a Data Element, or if the * Option Combo is a wildcard "*", returns just dataElementUID. * <p/> * If an Option Combo is present, returns dataElementUID.optionComboUID. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data element identifiers. */ Set<String> getExpressionElementAndOptionComboIds( String expression, ParseType parseType ); /** * Returns all data elements found in the given expression string, including * those found in data element operands. Returns an empty set if the given * expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data elements included in the expression string. */ Set<DataElement> getExpressionDataElements( String expression, ParseType parseType ); /** * Returns all CategoryOptionCombo uids in the given expression string that * are used as a data element operand categoryOptionCombo or * attributeOptionCombo. Returns an empty set if the expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of CategoryOptionCombo uids in the expression string. */ Set<String> getExpressionOptionComboIds( String expression, ParseType parseType ); /** * Returns all dimensional item object ids in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of dimensional item object ids. */ Set<DimensionalItemId> getExpressionDimensionalItemIds( String expression, ParseType parseType ); /** * Returns set of all OrganisationUnitGroup UIDs in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return Map of UIDs to OrganisationUnitGroups in the expression string. */ Set<String> getExpressionOrgUnitGroupIds( String expression, ParseType parseType ); // ------------------------------------------------------------------------- // Compute the value of the expression // ------------------------------------------------------------------------- /** * Generates the calculated value for an expression. * * @param params the expression parameters. * @return the calculated value. */ Object getExpressionValue( ExpressionParams params ); // ------------------------------------------------------------------------- // Gets a (possibly cached) constant map // ------------------------------------------------------------------------- /** * Gets the (possibly cached) constant map. * * @return the constant map. */ Map<String, Constant> getConstantMap(); }
Java
#!/usr/bin/env python """ ================ sMRI: FreeSurfer ================ This script, smri_freesurfer.py, demonstrates the ability to call reconall on a set of subjects and then make an average subject. python smri_freesurfer.py Import necessary modules from nipype. """ import os import nipype.pipeline.engine as pe import nipype.interfaces.io as nio from nipype.interfaces.freesurfer.preprocess import ReconAll from nipype.interfaces.freesurfer.utils import MakeAverageSubject subject_list = ['s1', 's3'] data_dir = os.path.abspath('data') subjects_dir = os.path.abspath('amri_freesurfer_tutorial/subjects_dir') wf = pe.Workflow(name="l1workflow") wf.base_dir = os.path.abspath('amri_freesurfer_tutorial/workdir') """ Grab data """ datasource = pe.MapNode(interface=nio.DataGrabber(infields=['subject_id'], outfields=['struct']), name='datasource', iterfield=['subject_id']) datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = dict(struct=[['subject_id', 'struct']]) datasource.inputs.subject_id = subject_list """ Run recon-all """ recon_all = pe.MapNode(interface=ReconAll(), name='recon_all', iterfield=['subject_id', 'T1_files']) recon_all.inputs.subject_id = subject_list if not os.path.exists(subjects_dir): os.mkdir(subjects_dir) recon_all.inputs.subjects_dir = subjects_dir wf.connect(datasource, 'struct', recon_all, 'T1_files') """ Make average subject """ average = pe.Node(interface=MakeAverageSubject(), name="average") average.inputs.subjects_dir = subjects_dir wf.connect(recon_all, 'subject_id', average, 'subjects_ids') wf.run("MultiProc", plugin_args={'n_procs': 4})
Java
{% extends "email/_notification.html" %} {% set replied_comment = notification.comment.parent_comment %} {% set replied_content = notification.comment.parent_comment.reply_content %} {% block headline %} <span><strong>Your thread</strong> received a <strong>reply</strong> from {% endblock %} {% block email_type %}thread reply notifications{% endblock %}
Java
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkUSNavigationProcessWidget.h" #include "ui_QmitkUSNavigationProcessWidget.h" #include "../NavigationStepWidgets/QmitkUSAbstractNavigationStep.h" #include "../SettingsWidgets/QmitkUSNavigationAbstractSettingsWidget.h" #include "mitkDataNode.h" #include "mitkNavigationDataToNavigationDataFilter.h" #include <QTimer> #include <QSignalMapper> #include <QShortcut> QmitkUSNavigationProcessWidget::QmitkUSNavigationProcessWidget(QWidget* parent) : QWidget(parent), m_SettingsWidget(0), m_BaseNode(mitk::DataNode::New()), m_CurrentTabIndex(0), m_CurrentMaxStep(0), m_ImageAlreadySetToNode(false), m_ReadySignalMapper(new QSignalMapper(this)), m_NoLongerReadySignalMapper(new QSignalMapper(this)), m_StdMultiWidget(0), m_UsePlanningStepWidget(false), ui(new Ui::QmitkUSNavigationProcessWidget) { m_Parent = parent; ui->setupUi(this); // remove the default page ui->stepsToolBox->removeItem(0); //set shortcuts QShortcut *nextShortcut = new QShortcut(QKeySequence("F10"), parent); QShortcut *prevShortcut = new QShortcut(QKeySequence("F11"), parent); connect(nextShortcut, SIGNAL(activated()), this, SLOT(OnNextButtonClicked())); connect(prevShortcut, SIGNAL(activated()), this, SLOT(OnPreviousButtonClicked())); //connect other slots connect( ui->restartStepButton, SIGNAL(clicked()), this, SLOT(OnRestartStepButtonClicked()) ); connect( ui->previousButton, SIGNAL(clicked()), this, SLOT(OnPreviousButtonClicked()) ); connect( ui->nextButton, SIGNAL(clicked()), this, SLOT(OnNextButtonClicked()) ); connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); connect (ui->settingsButton, SIGNAL(clicked()), this, SLOT(OnSettingsButtonClicked()) ); connect( m_ReadySignalMapper, SIGNAL(mapped(int)), this, SLOT(OnStepReady(int)) ); connect( m_NoLongerReadySignalMapper, SIGNAL(mapped(int)), this, SLOT(OnStepNoLongerReady(int)) ); ui->settingsFrameWidget->setHidden(true); } QmitkUSNavigationProcessWidget::~QmitkUSNavigationProcessWidget() { ui->stepsToolBox->blockSignals(true); for ( NavigationStepVector::iterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it ) { if ( (*it)->GetNavigationStepState() > QmitkUSAbstractNavigationStep::State_Stopped ) { (*it)->StopStep(); } delete *it; } m_NavigationSteps.clear(); if ( m_SettingsNode.IsNotNull() && m_DataStorage.IsNotNull() ) { m_DataStorage->Remove(m_SettingsNode); } delete ui; } void QmitkUSNavigationProcessWidget::EnableInteraction(bool enable) { if (enable) { ui->restartStepButton->setEnabled(true); ui->previousButton->setEnabled(true); ui->nextButton->setEnabled(true); ui->stepsToolBox->setEnabled(true); } else { ui->restartStepButton->setEnabled(false); ui->previousButton->setEnabled(false); ui->nextButton->setEnabled(false); ui->stepsToolBox->setEnabled(false); } } void QmitkUSNavigationProcessWidget::SetDataStorage(itk::SmartPointer<mitk::DataStorage> dataStorage) { m_DataStorage = dataStorage; if ( dataStorage.IsNull() ) { mitkThrow() << "Data Storage must not be null for QmitkUSNavigationProcessWidget."; } // test if base node is already in the data storage and add it if not m_BaseNode = dataStorage->GetNamedNode(QmitkUSAbstractNavigationStep::DATANAME_BASENODE); if ( m_BaseNode.IsNull() ) { m_BaseNode = mitk::DataNode::New(); m_BaseNode->SetName(QmitkUSAbstractNavigationStep::DATANAME_BASENODE); dataStorage->Add(m_BaseNode); } // base node and image stream node may be the same node if ( strcmp(QmitkUSAbstractNavigationStep::DATANAME_BASENODE, QmitkUSAbstractNavigationStep::DATANAME_IMAGESTREAM) != 0) { m_ImageStreamNode = dataStorage->GetNamedNode(QmitkUSAbstractNavigationStep::DATANAME_IMAGESTREAM); if (m_ImageStreamNode.IsNull()) { // Create Node for US Stream m_ImageStreamNode = mitk::DataNode::New(); m_ImageStreamNode->SetName(QmitkUSAbstractNavigationStep::DATANAME_IMAGESTREAM); dataStorage->Add(m_ImageStreamNode); } } else { m_ImageStreamNode = m_BaseNode; } m_SettingsNode = dataStorage->GetNamedDerivedNode(QmitkUSAbstractNavigationStep::DATANAME_SETTINGS, m_BaseNode); if ( m_SettingsNode.IsNull() ) { m_SettingsNode = mitk::DataNode::New(); m_SettingsNode->SetName(QmitkUSAbstractNavigationStep::DATANAME_SETTINGS); dataStorage->Add(m_SettingsNode, m_BaseNode); } if (m_SettingsWidget) { m_SettingsWidget->SetSettingsNode(m_SettingsNode); } } void QmitkUSNavigationProcessWidget::SetSettingsWidget(QmitkUSNavigationAbstractSettingsWidget* settingsWidget) { // disconnect slots to settings widget if there was a widget before if ( m_SettingsWidget ) { disconnect( ui->settingsSaveButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnSave()) ); disconnect( ui->settingsCancelButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnCancel()) ); disconnect (m_SettingsWidget, SIGNAL(Saved()), this, SLOT(OnSettingsWidgetReturned()) ); disconnect (m_SettingsWidget, SIGNAL(Canceled()), this, SLOT(OnSettingsWidgetReturned()) ); disconnect (m_SettingsWidget, SIGNAL(SettingsChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsChanged(itk::SmartPointer<mitk::DataNode>)) ); ui->settingsWidget->removeWidget(m_SettingsWidget); } m_SettingsWidget = settingsWidget; if ( m_SettingsWidget ) { m_SettingsWidget->LoadSettings(); connect( ui->settingsSaveButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnSave()) ); connect( ui->settingsCancelButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnCancel()) ); connect (m_SettingsWidget, SIGNAL(Saved()), this, SLOT(OnSettingsWidgetReturned()) ); connect (m_SettingsWidget, SIGNAL(Canceled()), this, SLOT(OnSettingsWidgetReturned()) ); connect (m_SettingsWidget, SIGNAL(SettingsChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsChanged(itk::SmartPointer<mitk::DataNode>)) ); if ( m_SettingsNode.IsNotNull() ) { m_SettingsWidget->SetSettingsNode(m_SettingsNode, true); } ui->settingsWidget->addWidget(m_SettingsWidget); } ui->settingsButton->setEnabled(m_SettingsWidget != 0); } void QmitkUSNavigationProcessWidget::SetNavigationSteps(NavigationStepVector navigationSteps) { disconnect( this, SLOT(OnTabChanged(int)) ); for ( int n = ui->stepsToolBox->count()-1; n >= 0; --n ) { ui->stepsToolBox->removeItem(n); } connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); m_NavigationSteps.clear(); m_NavigationSteps = navigationSteps; this->InitializeNavigationStepWidgets(); // notify all navigation step widgets about the current settings for (NavigationStepIterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->OnSettingsChanged(m_SettingsNode); } } void QmitkUSNavigationProcessWidget::ResetNavigationProcess() { MITK_INFO("QmitkUSNavigationProcessWidget") << "Resetting navigation process."; ui->stepsToolBox->blockSignals(true); for ( int n = 0; n <= m_CurrentMaxStep; ++n ) { m_NavigationSteps.at(n)->StopStep(); if ( n > 0 ) { ui->stepsToolBox->setItemEnabled(n, false); } } ui->stepsToolBox->blockSignals(false); m_CurrentMaxStep = 0; ui->stepsToolBox->setCurrentIndex(0); if ( m_NavigationSteps.size() > 0 ) { m_NavigationSteps.at(0)->ActivateStep(); } this->UpdatePrevNextButtons(); } void QmitkUSNavigationProcessWidget::UpdateNavigationProgress() { if ( m_CombinedModality.IsNotNull() && !m_CombinedModality->GetIsFreezed() ) { m_CombinedModality->Modified(); m_CombinedModality->Update(); if ( m_LastNavigationDataFilter.IsNotNull() ) { m_LastNavigationDataFilter->Update(); } mitk::Image::Pointer image = m_CombinedModality->GetOutput(); // make sure that always the current image is set to the data node if ( image.IsNotNull() && m_ImageStreamNode->GetData() != image.GetPointer() && image->IsInitialized() ) { m_ImageStreamNode->SetData(image); m_ImageAlreadySetToNode = true; } } if ( m_CurrentTabIndex > 0 && static_cast<unsigned int>(m_CurrentTabIndex) < m_NavigationSteps.size() ) { m_NavigationSteps.at(m_CurrentTabIndex)->Update(); } } void QmitkUSNavigationProcessWidget::OnNextButtonClicked() { if (m_CombinedModality.IsNotNull() && m_CombinedModality->GetIsFreezed()) {return;} //no moving through steps when the modality is NULL or frozen int currentIndex = ui->stepsToolBox->currentIndex(); if (currentIndex >= m_CurrentMaxStep) { MITK_WARN << "Next button clicked though no next tab widget is available."; return; } ui->stepsToolBox->setCurrentIndex(++currentIndex); this->UpdatePrevNextButtons(); } void QmitkUSNavigationProcessWidget::OnPreviousButtonClicked() { if (m_CombinedModality.IsNotNull() && m_CombinedModality->GetIsFreezed()) {return;} //no moving through steps when the modality is NULL or frozen int currentIndex = ui->stepsToolBox->currentIndex(); if (currentIndex <= 0) { MITK_WARN << "Previous button clicked though no previous tab widget is available."; return; } ui->stepsToolBox->setCurrentIndex(--currentIndex); this->UpdatePrevNextButtons(); } void QmitkUSNavigationProcessWidget::OnRestartStepButtonClicked() { MITK_INFO("QmitkUSNavigationProcessWidget") << "Restarting step " << m_CurrentTabIndex << " (" << m_NavigationSteps.at(m_CurrentTabIndex)->GetTitle().toStdString() << ")."; m_NavigationSteps.at(ui->stepsToolBox->currentIndex())->RestartStep(); m_NavigationSteps.at(ui->stepsToolBox->currentIndex())->ActivateStep(); } void QmitkUSNavigationProcessWidget::OnTabChanged(int index) { if ( index < 0 || index >= static_cast<int>(m_NavigationSteps.size()) ) { return; } else if ( m_CurrentTabIndex == index ) { // just activate the step if it is the same step againg m_NavigationSteps.at(index)->ActivateStep(); return; } MITK_INFO("QmitkUSNavigationProcessWidget") << "Activating navigation step " << index << " (" << m_NavigationSteps.at(index)->GetTitle().toStdString() <<")."; if (index > m_CurrentTabIndex) { this->UpdateFilterPipeline(); // finish all previous steps to make sure that all data is valid for (int n = m_CurrentTabIndex; n < index; ++n) { m_NavigationSteps.at(n)->FinishStep(); } } // deactivate the previously active step if ( m_CurrentTabIndex > 0 && m_NavigationSteps.size() > static_cast<unsigned int>(m_CurrentTabIndex) ) { m_NavigationSteps.at(m_CurrentTabIndex)->DeactivateStep(); } // start step of the current tab if it wasn't started before if ( m_NavigationSteps.at(index)->GetNavigationStepState() == QmitkUSAbstractNavigationStep::State_Stopped ) { m_NavigationSteps.at(index)->StartStep(); } m_NavigationSteps.at(index)->ActivateStep(); if (static_cast<unsigned int>(index) < m_NavigationSteps.size()) ui->restartStepButton->setEnabled(m_NavigationSteps.at(index)->GetIsRestartable()); this->UpdatePrevNextButtons(); m_CurrentTabIndex = index; emit SignalActiveNavigationStepChanged(index); } void QmitkUSNavigationProcessWidget::OnSettingsButtonClicked() { this->SetSettingsWidgetVisible(true); } void QmitkUSNavigationProcessWidget::OnSettingsWidgetReturned() { this->SetSettingsWidgetVisible(false); } void QmitkUSNavigationProcessWidget::OnSettingsNodeChanged(itk::SmartPointer<mitk::DataNode> dataNode) { if ( m_SettingsWidget ) m_SettingsWidget->SetSettingsNode(dataNode); } void QmitkUSNavigationProcessWidget::OnStepReady(int index) { if (m_CurrentMaxStep <= index) { m_CurrentMaxStep = index + 1; this->UpdatePrevNextButtons(); for (int n = 0; n <= m_CurrentMaxStep; ++n) { ui->stepsToolBox->setItemEnabled(n, true); } } emit SignalNavigationStepFinished(index, true); } void QmitkUSNavigationProcessWidget::OnStepNoLongerReady(int index) { if (m_CurrentMaxStep > index) { m_CurrentMaxStep = index; this->UpdatePrevNextButtons(); this->UpdateFilterPipeline(); for (int n = m_CurrentMaxStep+1; n < ui->stepsToolBox->count(); ++n) { ui->stepsToolBox->setItemEnabled(n, false); m_NavigationSteps.at(n)->StopStep(); } } emit SignalNavigationStepFinished(index, false); } void QmitkUSNavigationProcessWidget::OnCombinedModalityChanged(itk::SmartPointer<mitk::USCombinedModality> combinedModality) { m_CombinedModality = combinedModality; m_ImageAlreadySetToNode = false; if ( combinedModality.IsNotNull() ) { if ( combinedModality->GetNavigationDataSource().IsNull() ) { MITK_WARN << "There is no navigation data source set for the given combined modality."; return; } this->UpdateFilterPipeline(); } for (NavigationStepIterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->SetCombinedModality(combinedModality); } emit SignalCombinedModalityChanged(combinedModality); } void QmitkUSNavigationProcessWidget::OnSettingsChanged(const mitk::DataNode::Pointer dataNode) { static bool methodEntered = false; if ( methodEntered ) { MITK_WARN("QmitkUSNavigationProcessWidget") << "Ignoring recursive call to 'OnSettingsChanged()'. " << "Make sure to no emit 'SignalSettingsNodeChanged' in an 'OnSettingsChanged()' method."; return; } methodEntered = true; std::string application; if ( dataNode->GetStringProperty("settings.application", application) ) { QString applicationQString = QString::fromStdString(application); if ( applicationQString != ui->titleLabel->text() ) { ui->titleLabel->setText(applicationQString); } } // notify all navigation step widgets about the changed settings for (NavigationStepIterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->OnSettingsChanged(dataNode); } emit SignalSettingsChanged(dataNode); methodEntered = false; } void QmitkUSNavigationProcessWidget::InitializeNavigationStepWidgets() { // do not listen for steps tool box signal during insertion of items into tool box disconnect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); m_CurrentMaxStep = 0; mitk::DataStorage::Pointer dataStorage = m_DataStorage; for (unsigned int n = 0; n < m_NavigationSteps.size(); ++n) { QmitkUSAbstractNavigationStep* curNavigationStep = m_NavigationSteps.at(n); curNavigationStep->SetDataStorage(dataStorage); connect( curNavigationStep, SIGNAL(SignalReadyForNextStep()), m_ReadySignalMapper, SLOT(map())); connect( curNavigationStep, SIGNAL(SignalNoLongerReadyForNextStep()), m_NoLongerReadySignalMapper, SLOT(map()) ); connect( curNavigationStep, SIGNAL(SignalCombinedModalityChanged(itk::SmartPointer<mitk::USCombinedModality>)), this, SLOT(OnCombinedModalityChanged(itk::SmartPointer<mitk::USCombinedModality>)) ); connect( curNavigationStep, SIGNAL(SignalIntermediateResult(const itk::SmartPointer<mitk::DataNode>)), this, SIGNAL(SignalIntermediateResult(const itk::SmartPointer<mitk::DataNode>)) ); connect( curNavigationStep, SIGNAL(SignalSettingsNodeChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsNodeChanged(itk::SmartPointer<mitk::DataNode>)) ); m_ReadySignalMapper->setMapping(curNavigationStep, n); m_NoLongerReadySignalMapper->setMapping(curNavigationStep, n); ui->stepsToolBox->insertItem(n, curNavigationStep, QString("Step ") + QString::number(n+1) + ": " + curNavigationStep->GetTitle()); if ( n > 0 ) { ui->stepsToolBox->setItemEnabled(n, false); } } ui->restartStepButton->setEnabled(m_NavigationSteps.at(0)->GetIsRestartable()); ui->stepsToolBox->setCurrentIndex(0); // activate the first navigation step widgets if ( ! m_NavigationSteps.empty() ) { m_NavigationSteps.at(0)->ActivateStep(); } // after filling the steps tool box the signal is interesting again connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); this->UpdateFilterPipeline(); } void QmitkUSNavigationProcessWidget::UpdatePrevNextButtons() { int currentIndex = ui->stepsToolBox->currentIndex(); ui->previousButton->setEnabled(currentIndex > 0); ui->nextButton->setEnabled(currentIndex < m_CurrentMaxStep); } void QmitkUSNavigationProcessWidget::UpdateFilterPipeline() { if ( m_CombinedModality.IsNull() ) { return; } std::vector<mitk::NavigationDataToNavigationDataFilter::Pointer> filterList; mitk::NavigationDataSource::Pointer navigationDataSource = m_CombinedModality->GetNavigationDataSource(); for (unsigned int n = 0; n <= m_CurrentMaxStep && n < m_NavigationSteps.size(); ++n) { QmitkUSAbstractNavigationStep::FilterVector filter = m_NavigationSteps.at(n)->GetFilter(); if ( ! filter.empty() ) { filterList.insert(filterList.end(), filter.begin(), filter.end()); } } if ( ! filterList.empty() ) { for (unsigned int n = 0; n < navigationDataSource->GetNumberOfOutputs(); ++n) { filterList.at(0)->SetInput(n, navigationDataSource->GetOutput(n)); } for (std::vector<mitk::NavigationDataToNavigationDataFilter::Pointer>::iterator it = filterList.begin()+1; it != filterList.end(); ++it) { std::vector<mitk::NavigationDataToNavigationDataFilter::Pointer>::iterator prevIt = it-1; for (unsigned int n = 0; n < (*prevIt)->GetNumberOfOutputs(); ++n) { (*it)->SetInput(n, (*prevIt)->GetOutput(n)); } } m_LastNavigationDataFilter = filterList.at(filterList.size()-1); } else { m_LastNavigationDataFilter = navigationDataSource.GetPointer(); } } void QmitkUSNavigationProcessWidget::SetSettingsWidgetVisible(bool visible) { ui->settingsFrameWidget->setVisible(visible); ui->stepsToolBox->setHidden(visible); ui->settingsButton->setHidden(visible); ui->restartStepButton->setHidden(visible); ui->previousButton->setHidden(visible); ui->nextButton->setHidden(visible); } void QmitkUSNavigationProcessWidget::FinishCurrentNavigationStep() { int currentIndex = ui->stepsToolBox->currentIndex(); QmitkUSAbstractNavigationStep* curNavigationStep = m_NavigationSteps.at(currentIndex); curNavigationStep->FinishStep(); }
Java
// Copyright 2021 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/image_editor/screenshot_flow.h" #include <memory> #include "base/logging.h" #include "build/build_config.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/compositor/paint_recorder.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/render_text.h" #include "ui/snapshot/snapshot.h" #include "ui/views/background.h" #if defined(OS_MAC) #include "chrome/browser/image_editor/event_capture_mac.h" #include "components/lens/lens_features.h" #include "content/public/browser/render_view_host.h" #include "ui/views/widget/widget.h" #endif #if defined(USE_AURA) #include "ui/aura/window.h" #include "ui/wm/core/window_util.h" #endif namespace image_editor { // Colors for semitransparent overlay. static constexpr SkColor kColorSemitransparentOverlayMask = SkColorSetARGB(0x7F, 0x00, 0x00, 0x00); static constexpr SkColor kColorSemitransparentOverlayVisible = SkColorSetARGB(0x00, 0x00, 0x00, 0x00); static constexpr SkColor kColorSelectionRect = SkColorSetRGB(0xEE, 0xEE, 0xEE); // Minimum selection rect edge size to treat as a valid capture region. static constexpr int kMinimumValidSelectionEdgePixels = 30; ScreenshotFlow::ScreenshotFlow(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), web_contents_(web_contents->GetWeakPtr()) { weak_this_ = weak_factory_.GetWeakPtr(); } ScreenshotFlow::~ScreenshotFlow() { RemoveUIOverlay(); } void ScreenshotFlow::CreateAndAddUIOverlay() { if (screen_capture_layer_) return; web_contents_observer_ = std::make_unique<UnderlyingWebContentsObserver>( web_contents_.get(), this); screen_capture_layer_ = std::make_unique<ui::Layer>(ui::LayerType::LAYER_TEXTURED); screen_capture_layer_->SetName("ScreenshotRegionSelectionLayer"); screen_capture_layer_->SetFillsBoundsOpaquely(false); screen_capture_layer_->set_delegate(this); #if defined(OS_MAC) gfx::Rect bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_->GetContentNativeView(); views::Widget* widget = views::Widget::GetWidgetForNativeView(web_contents_view); ui::Layer* content_layer = widget->GetLayer(); const gfx::Rect offset_bounds = widget->GetWindowBoundsInScreen(); bounds.Offset(-offset_bounds.x(), -offset_bounds.y()); event_capture_mac_ = std::make_unique<EventCaptureMac>( this, web_contents_->GetTopLevelNativeWindow()); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::Layer* content_layer = native_window->layer(); const gfx::Rect bounds = native_window->bounds(); // Capture mouse down and drag events on our window. native_window->AddPreTargetHandler(this); #endif content_layer->Add(screen_capture_layer_.get()); content_layer->StackAtTop(screen_capture_layer_.get()); screen_capture_layer_->SetBounds(bounds); screen_capture_layer_->SetVisible(true); SetCursor(ui::mojom::CursorType::kCross); // After setup is done, we should set the capture mode to active. capture_mode_ = CaptureMode::SELECTION_RECTANGLE; } void ScreenshotFlow::RemoveUIOverlay() { if (capture_mode_ == CaptureMode::NOT_CAPTURING) return; capture_mode_ = CaptureMode::NOT_CAPTURING; if (!web_contents_ || !screen_capture_layer_) return; #if defined(OS_MAC) views::Widget* widget = views::Widget::GetWidgetForNativeView( web_contents_->GetContentNativeView()); if (!widget) return; ui::Layer* content_layer = widget->GetLayer(); event_capture_mac_.reset(); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); native_window->RemovePreTargetHandler(this); ui::Layer* content_layer = native_window->layer(); #endif content_layer->Remove(screen_capture_layer_.get()); screen_capture_layer_->set_delegate(nullptr); screen_capture_layer_.reset(); // Restore the cursor to pointer; there's no corresponding GetCursor() // to store the pre-capture-mode cursor, and the pointer will have moved // in the meantime. SetCursor(ui::mojom::CursorType::kPointer); } void ScreenshotFlow::Start(ScreenshotCaptureCallback flow_callback) { flow_callback_ = std::move(flow_callback); CreateAndAddUIOverlay(); RequestRepaint(gfx::Rect()); } void ScreenshotFlow::StartFullscreenCapture( ScreenshotCaptureCallback flow_callback) { // Start and finish the capture process by screenshotting the full window. // There is no region selection step in this mode. flow_callback_ = std::move(flow_callback); CaptureAndRunScreenshotCompleteCallback(ScreenshotCaptureResultCode::SUCCESS, gfx::Rect(web_contents_->GetSize())); } void ScreenshotFlow::CaptureAndRunScreenshotCompleteCallback( ScreenshotCaptureResultCode result_code, gfx::Rect region) { if (region.IsEmpty()) { RunScreenshotCompleteCallback(result_code, gfx::Rect(), gfx::Image()); return; } gfx::Rect bounds = web_contents_->GetViewBounds(); #if defined(OS_MAC) const gfx::NativeView& native_view = web_contents_->GetContentNativeView(); gfx::Image img; bool rval = ui::GrabViewSnapshot(native_view, region, &img); // If |img| is empty, clients should treat it as a canceled action, but // we have a DCHECK for development as we expected this call to succeed. DCHECK(rval); RunScreenshotCompleteCallback(result_code, bounds, img); #else ui::GrabWindowSnapshotAsyncCallback screenshot_callback = base::BindOnce(&ScreenshotFlow::RunScreenshotCompleteCallback, weak_this_, result_code, bounds); const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::GrabWindowSnapshotAsync(native_window, region, std::move(screenshot_callback)); #endif } void ScreenshotFlow::CancelCapture() { RemoveUIOverlay(); } void ScreenshotFlow::OnKeyEvent(ui::KeyEvent* event) { if (event->type() == ui::ET_KEY_PRESSED && event->key_code() == ui::VKEY_ESCAPE) { event->StopPropagation(); CompleteCapture(ScreenshotCaptureResultCode::USER_ESCAPE_EXIT, gfx::Rect()); } } void ScreenshotFlow::OnMouseEvent(ui::MouseEvent* event) { if (!event->IsLocatedEvent()) return; const ui::LocatedEvent* located_event = ui::LocatedEvent::FromIfValid(event); if (!located_event) return; gfx::Point location = located_event->location(); #if defined(OS_MAC) // Offset |location| be relative to the WebContents widget, vs the parent // window, recomputed rather than cached in case e.g. user disables // bookmarks bar from another window. gfx::Rect web_contents_bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_->GetContentNativeView(); views::Widget* widget = views::Widget::GetWidgetForNativeView(web_contents_view); const gfx::Rect widget_bounds = widget->GetWindowBoundsInScreen(); location.set_x(location.x() + (widget_bounds.x() - web_contents_bounds.x())); location.set_y(location.y() + (widget_bounds.y() - web_contents_bounds.y())); // Don't capture clicks on browser ui outside the webcontents. if (location.x() < 0 || location.y() < 0 || location.x() > web_contents_bounds.width() || location.y() > web_contents_bounds.height()) { return; } #endif switch (event->type()) { case ui::ET_MOUSE_MOVED: SetCursor(ui::mojom::CursorType::kCross); event->SetHandled(); break; case ui::ET_MOUSE_PRESSED: if (event->IsLeftMouseButton()) { drag_start_ = location; drag_end_ = location; event->SetHandled(); } break; case ui::ET_MOUSE_DRAGGED: if (event->IsLeftMouseButton()) { drag_end_ = location; RequestRepaint(gfx::Rect()); event->SetHandled(); } break; case ui::ET_MOUSE_RELEASED: if (capture_mode_ == CaptureMode::SELECTION_RECTANGLE || capture_mode_ == CaptureMode::SELECTION_ELEMENT) { event->SetHandled(); gfx::Rect selection = gfx::BoundingRect(drag_start_, drag_end_); drag_start_.SetPoint(0, 0); drag_end_.SetPoint(0, 0); if (selection.width() >= kMinimumValidSelectionEdgePixels && selection.height() >= kMinimumValidSelectionEdgePixels) { CompleteCapture(ScreenshotCaptureResultCode::SUCCESS, selection); } else { RequestRepaint(gfx::Rect()); } } break; default: break; } } void ScreenshotFlow::CompleteCapture(ScreenshotCaptureResultCode result_code, const gfx::Rect& region) { RemoveUIOverlay(); CaptureAndRunScreenshotCompleteCallback(result_code, region); } void ScreenshotFlow::RunScreenshotCompleteCallback( ScreenshotCaptureResultCode result_code, gfx::Rect bounds, gfx::Image image) { ScreenshotCaptureResult result; result.result_code = result_code; result.image = image; result.screen_bounds = bounds; std::move(flow_callback_).Run(result); } void ScreenshotFlow::OnPaintLayer(const ui::PaintContext& context) { if (!screen_capture_layer_) return; const gfx::Rect& screen_bounds(screen_capture_layer_->bounds()); ui::PaintRecorder recorder(context, screen_bounds.size()); gfx::Canvas* canvas = recorder.canvas(); auto selection_rect = gfx::BoundingRect(drag_start_, drag_end_); PaintSelectionLayer(canvas, selection_rect, gfx::Rect()); paint_invalidation_ = gfx::Rect(); } void ScreenshotFlow::RequestRepaint(gfx::Rect region) { if (!screen_capture_layer_) return; if (region.IsEmpty()) { const gfx::Size& layer_size = screen_capture_layer_->size(); region = gfx::Rect(0, 0, layer_size.width(), layer_size.height()); } paint_invalidation_.Union(region); screen_capture_layer_->SchedulePaint(region); } void ScreenshotFlow::PaintSelectionLayer(gfx::Canvas* canvas, const gfx::Rect& selection, const gfx::Rect& invalidation_region) { // Adjust for hidpi and lodpi support. canvas->UndoDeviceScaleFactor(); // Clear the canvas with our mask color. canvas->DrawColor(kColorSemitransparentOverlayMask); // Allow the user's selection to show through, and add a border around it. if (!selection.IsEmpty()) { float scale_factor = screen_capture_layer_->device_scale_factor(); gfx::Rect selection_scaled = gfx::ScaleToEnclosingRect(selection, scale_factor); canvas->FillRect(selection_scaled, kColorSemitransparentOverlayVisible, SkBlendMode::kClear); canvas->DrawRect(gfx::RectF(selection_scaled), kColorSelectionRect); } } void ScreenshotFlow::SetCursor(ui::mojom::CursorType cursor_type) { if (!web_contents_) { return; } #if defined(OS_MAC) if (cursor_type == ui::mojom::CursorType::kCross && lens::features::kRegionSearchMacCursorFix.Get()) { EventCaptureMac::SetCrossCursor(); return; } #endif content::RenderWidgetHost* host = web_contents_->GetMainFrame()->GetRenderWidgetHost(); if (host) { ui::Cursor cursor(cursor_type); host->SetCursor(cursor); } } bool ScreenshotFlow::IsCaptureModeActive() { return capture_mode_ != CaptureMode::NOT_CAPTURING; } void ScreenshotFlow::WebContentsDestroyed() { if (IsCaptureModeActive()) { CancelCapture(); } } void ScreenshotFlow::OnVisibilityChanged(content::Visibility visibility) { if (IsCaptureModeActive()) { CancelCapture(); } } // UnderlyingWebContentsObserver monitors the WebContents and exits screen // capture mode if a navigation occurs. class ScreenshotFlow::UnderlyingWebContentsObserver : public content::WebContentsObserver { public: UnderlyingWebContentsObserver(content::WebContents* web_contents, ScreenshotFlow* screenshot_flow) : content::WebContentsObserver(web_contents), screenshot_flow_(screenshot_flow) {} ~UnderlyingWebContentsObserver() override = default; UnderlyingWebContentsObserver(const UnderlyingWebContentsObserver&) = delete; UnderlyingWebContentsObserver& operator=( const UnderlyingWebContentsObserver&) = delete; // content::WebContentsObserver void PrimaryPageChanged(content::Page& page) override { // We only care to complete/cancel a capture if the capture mode is // currently active. if (screenshot_flow_->IsCaptureModeActive()) screenshot_flow_->CompleteCapture( ScreenshotCaptureResultCode::USER_NAVIGATED_EXIT, gfx::Rect()); } private: ScreenshotFlow* screenshot_flow_; }; } // namespace image_editor
Java
// Copyright (c) 2011 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 CHROME_COMMON_CHROME_CONTENT_CLIENT_H_ #define CHROME_COMMON_CHROME_CONTENT_CLIENT_H_ #pragma once #include "base/compiler_specific.h" #include "content/public/common/content_client.h" namespace chrome { class ChromeContentClient : public content::ContentClient { public: static const char* const kPDFPluginName; static const char* const kNaClPluginName; static const char* const kNaClOldPluginName; virtual void SetActiveURL(const GURL& url) OVERRIDE; virtual void SetGpuInfo(const content::GPUInfo& gpu_info) OVERRIDE; virtual void AddPepperPlugins( std::vector<content::PepperPluginInfo>* plugins) OVERRIDE; virtual void AddNPAPIPlugins( webkit::npapi::PluginList* plugin_list) OVERRIDE; virtual bool CanSendWhileSwappedOut(const IPC::Message* msg) OVERRIDE; virtual bool CanHandleWhileSwappedOut(const IPC::Message& msg) OVERRIDE; virtual std::string GetUserAgent(bool* overriding) const OVERRIDE; virtual string16 GetLocalizedString(int message_id) const OVERRIDE; virtual base::StringPiece GetDataResource(int resource_id) const OVERRIDE; #if defined(OS_WIN) virtual bool SandboxPlugin(CommandLine* command_line, sandbox::TargetPolicy* policy) OVERRIDE; #endif #if defined(OS_MACOSX) virtual bool GetSandboxProfileForSandboxType( int sandbox_type, int* sandbox_profile_resource_id) const OVERRIDE; #endif }; } // namespace chrome #endif // CHROME_COMMON_CHROME_CONTENT_CLIENT_H_
Java
/* * Copyright (C) 2007, 2008, 2013 Apple Inc. 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. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBDATABASE_DATABASE_TRACKER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBDATABASE_DATABASE_TRACKER_H_ #include <memory> #include "base/callback.h" #include "base/macros.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webdatabase/database_error.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/string_hash.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/threading_primitives.h" namespace blink { class Database; class DatabaseContext; class Page; class SecurityOrigin; class MODULES_EXPORT DatabaseTracker { USING_FAST_MALLOC(DatabaseTracker); public: static DatabaseTracker& Tracker(); DatabaseTracker(const DatabaseTracker&) = delete; DatabaseTracker& operator=(const DatabaseTracker&) = delete; // This singleton will potentially be used from multiple worker threads and // the page's context thread simultaneously. To keep this safe, it's // currently using 4 locks. In order to avoid deadlock when taking multiple // locks, you must take them in the correct order: // m_databaseGuard before quotaManager if both locks are needed. // m_openDatabaseMapGuard before quotaManager if both locks are needed. // m_databaseGuard and m_openDatabaseMapGuard currently don't overlap. // notificationMutex() is currently independent of the other locks. bool CanEstablishDatabase(DatabaseContext*, DatabaseError&); String FullPathForDatabase(const SecurityOrigin*, const String& name, bool create_if_does_not_exist = true); void AddOpenDatabase(Database*); void RemoveOpenDatabase(Database*); uint64_t GetMaxSizeForDatabase(const Database*); void CloseDatabasesImmediately(const SecurityOrigin*, const String& name); using DatabaseCallback = base::RepeatingCallback<void(Database*)>; void ForEachOpenDatabaseInPage(Page*, DatabaseCallback); void PrepareToOpenDatabase(Database*); void FailedToOpenDatabase(Database*); private: using DatabaseSet = HashSet<CrossThreadPersistent<Database>>; using DatabaseNameMap = HashMap<String, DatabaseSet*>; using DatabaseOriginMap = HashMap<String, DatabaseNameMap*>; DatabaseTracker(); void CloseOneDatabaseImmediately(const String& origin_identifier, const String& name, Database*); Mutex open_database_map_guard_; mutable std::unique_ptr<DatabaseOriginMap> open_database_map_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBDATABASE_DATABASE_TRACKER_H_
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE457_Use_of_Uninitialized_Variable__char_pointer_64b.c Label Definition File: CWE457_Use_of_Uninitialized_Variable.c.label.xml Template File: sources-sinks-64b.tmpl.c */ /* * @description * CWE: 457 Use of Uninitialized Variable * BadSource: no_init Don't initialize data * GoodSource: Initialize data * Sinks: use * GoodSink: Initialize then use data * BadSink : Use data * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_badSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_goodG2BSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_goodB2GSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* FIX: Ensure data is initialized before use */ data = "string"; printLine(data); } #endif /* OMITGOOD */
Java
// 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/common/child_histogram_message_filter.h" #include <ctype.h> #include "base/bind.h" #include "base/message_loop.h" #include "base/metrics/statistics_recorder.h" #include "base/pickle.h" #include "content/common/child_process.h" #include "content/common/child_process_messages.h" #include "content/common/child_thread.h" namespace content { ChildHistogramMessageFilter::ChildHistogramMessageFilter() : channel_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(histogram_snapshot_manager_(this)) { } ChildHistogramMessageFilter::~ChildHistogramMessageFilter() { } void ChildHistogramMessageFilter::OnFilterAdded(IPC::Channel* channel) { channel_ = channel; } void ChildHistogramMessageFilter::OnFilterRemoved() { } bool ChildHistogramMessageFilter::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChildHistogramMessageFilter, message) IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildHistogramData, OnGetChildHistogramData) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ChildHistogramMessageFilter::SendHistograms(int sequence_number) { ChildProcess::current()->io_message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&ChildHistogramMessageFilter::UploadAllHistograms, this, sequence_number)); } void ChildHistogramMessageFilter::OnGetChildHistogramData(int sequence_number) { UploadAllHistograms(sequence_number); } void ChildHistogramMessageFilter::UploadAllHistograms(int sequence_number) { DCHECK_EQ(0u, pickled_histograms_.size()); base::StatisticsRecorder::CollectHistogramStats("ChildProcess"); // Push snapshots into our pickled_histograms_ vector. // Note: Before serializing, we set the kIPCSerializationSourceFlag for all // the histograms, so that the receiving process can distinguish them from the // local histograms. histogram_snapshot_manager_.PrepareDeltas( base::Histogram::kIPCSerializationSourceFlag, false); channel_->Send(new ChildProcessHostMsg_ChildHistogramData( sequence_number, pickled_histograms_)); pickled_histograms_.clear(); static int count = 0; count++; DHISTOGRAM_COUNTS("Histogram.ChildProcessHistogramSentCount", count); } void ChildHistogramMessageFilter::RecordDelta( const base::HistogramBase& histogram, const base::HistogramSamples& snapshot) { DCHECK_NE(0, snapshot.TotalCount()); Pickle pickle; histogram.SerializeInfo(&pickle); snapshot.Serialize(&pickle); pickled_histograms_.push_back( std::string(static_cast<const char*>(pickle.data()), pickle.size())); } void ChildHistogramMessageFilter::InconsistencyDetected( base::Histogram::Inconsistencies problem) { UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesChildProcess", problem, base::Histogram::NEVER_EXCEEDED_VALUE); } void ChildHistogramMessageFilter::UniqueInconsistencyDetected( base::Histogram::Inconsistencies problem) { UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesChildProcessUnique", problem, base::Histogram::NEVER_EXCEEDED_VALUE); } void ChildHistogramMessageFilter::InconsistencyDetectedInLoggedCount( int amount) { UMA_HISTOGRAM_COUNTS("Histogram.InconsistentSnapshotChildProcess", std::abs(amount)); } } // namespace content
Java
/* * Copyright (C) 2013 Soumith Chintala * */ #include <jni.h> #include <stdio.h> #include <stdlib.h> #include "torchandroid.h" #include <assert.h> extern "C" { JNIEXPORT jstring JNICALL Java_com_torch_Torch_jni_1call( JNIEnv* env, jobject thiz, jobject assetManager, jstring nativeLibraryDir_, jstring luaFile_ ) { // D("Hello from C"); // get native asset manager AAssetManager* manager = AAssetManager_fromJava(env, assetManager); assert( NULL != manager); const char *nativeLibraryDir = env->GetStringUTFChars(nativeLibraryDir_, 0); const char *file = env->GetStringUTFChars(luaFile_, 0); char buffer[4096]; // buffer for textview output D("Torch.call(%s), nativeLibraryDir=%s", file, nativeLibraryDir); buffer[0] = 0; lua_State *L = inittorch(manager, nativeLibraryDir); // create a lua_State assert( NULL != manager); // load and run file int ret; long size = android_asset_get_size(file); if (size != -1) { char *filebytes = android_asset_get_bytes(file); ret = luaL_dobuffer(L, filebytes, size, "main"); } // check if script ran succesfully. If not, print error to logcat if (ret == 1) { D("Error doing resource: %s:%s\n", file, lua_tostring(L,-1)); strlcat(buffer, lua_tostring(L,-1), sizeof(buffer)); } else strlcat(buffer, "Torch script ran succesfully. Check Logcat for more details.", sizeof(buffer)); // destroy the Lua State lua_close(L); return env->NewStringUTF(buffer); } }
Java
<?php use yii\helpers\Html; ?> <?php foreach ($_model as $photo): ?> <div class="thumb" style="float:left;padding: 2px" data-name="<?= $photo->name ?>" onclick="ShowFullImage('<?= $photo->name ?>')" > <div> <?= Html::img('/upload/multy-thumbs/' . $photo->name, ['height' => '70px']); ?> </div> <div style="" > <?= $photo->name; ?> </div> </div> <?php endforeach; ?> <style> .jpreloader.back_background{ background-color: #111214; bottom: 0; height: 100%; left: 0; opacity: 0.9; position: fixed; right: 0; top: 0; width: 100%; display: block; background-image: url("/img/preloader.gif"); background-repeat: no-repeat; background-position:center center; } </style>
Java
package io.flutter.embedding.engine.mutatorsstack; import static junit.framework.TestCase.*; import static org.mockito.Mockito.*; import android.graphics.Matrix; import android.view.MotionEvent; import io.flutter.embedding.android.AndroidTouchProcessor; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class FlutterMutatorViewTest { @Test public void canDragViews() { final AndroidTouchProcessor touchProcessor = mock(AndroidTouchProcessor.class); final FlutterMutatorView view = new FlutterMutatorView(RuntimeEnvironment.systemContext, 1.0f, touchProcessor); final FlutterMutatorsStack mutatorStack = mock(FlutterMutatorsStack.class); assertTrue(view.onInterceptTouchEvent(mock(MotionEvent.class))); { view.readyToDisplay(mutatorStack, /*left=*/ 1, /*top=*/ 2, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 3, /*top=*/ 4, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 5, /*top=*/ 6, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(3, 4); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 7, /*top=*/ 8, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(7, 8); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } } }
Java
package org.hisp.dhis.dxf2.adx; /* * Copyright (c) 2015, UiO * 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. * * 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. */ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.xerces.util.XMLChar; import org.hisp.dhis.dataelement.DataElementCategory; import org.hisp.dhis.dataelement.DataElementCategoryCombo; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.DataSetElement; /** * @author bobj */ public class AdxDataSetMetadata { // Lookup category options per cat option combo private final Map<Integer, Map<String, String>> categoryOptionMap; AdxDataSetMetadata( DataSet dataSet ) throws AdxException { categoryOptionMap = new HashMap<>(); Set<DataElementCategoryCombo> catCombos = new HashSet<>(); catCombos.add( dataSet.getCategoryCombo() ); for ( DataSetElement element : dataSet.getDataSetElements() ) { catCombos.add( element.getResolvedCategoryCombo() ); } for ( DataElementCategoryCombo categoryCombo : catCombos ) { for ( DataElementCategoryOptionCombo catOptCombo : categoryCombo.getOptionCombos() ) { addExplodedCategoryAttributes( catOptCombo ); } } } private void addExplodedCategoryAttributes( DataElementCategoryOptionCombo coc ) throws AdxException { Map<String, String> categoryAttributes = new HashMap<>(); if ( !coc.isDefault() ) { for ( DataElementCategory category : coc.getCategoryCombo().getCategories() ) { String categoryCode = category.getCode(); if ( categoryCode == null || !XMLChar.isValidName( categoryCode ) ) { throw new AdxException( "Category code for " + category.getName() + " is missing or invalid: " + categoryCode ); } String catOptCode = category.getCategoryOption( coc ).getCode(); if ( catOptCode == null || catOptCode.isEmpty() ) { throw new AdxException( "CategoryOption code for " + category.getCategoryOption( coc ).getName() + " is missing" ); } categoryAttributes.put( categoryCode, catOptCode ); } } categoryOptionMap.put( coc.getId(), categoryAttributes ); } public Map<String, String> getExplodedCategoryAttributes( int cocId ) { return this.categoryOptionMap.get( cocId ); } }
Java
<?php /** * Created by PhpStorm. * User: qhuy * Date: 18/12/2014 * Time: 21:59 */ namespace backend\models; use common\helpers\CommonUtils; use common\helpers\CVietnameseTools; use common\helpers\MediaToolBoxHelper; use common\helpers\MyCurl; use common\models\Content; use common\models\News; use garyjl\simplehtmldom\SimpleHtmlDom; use Imagine\Image\Box; use Imagine\Image\ManipulatorInterface; use Yii; use yii\base\Model; use yii\helpers\FileHelper; use yii\helpers\Url; use yii\validators\ImageValidator; use yii\validators\UrlValidator; use yii\web\UploadedFile; class Image extends Model { const TYPE_POSTER = 1; const TYPE_THUMBNAIL = 2; const TYPE_SLIDESHOW = 3; const TYPE_AUTO = 4; const ORIENTATION_PORTRAIT = 1; const ORIENTATION_LANDSCAPE = 2; const RATIO_W = 16; const RATIO_H = 9; const RATIO_MULIPLIER_UPPER_LIMIT = 120;//Ty le toi da limit (1920x1080) public static $imageConfig = null; private $_id = ''; public $content_id; public $name; public $url; public $type = self::TYPE_POSTER; public $orientation; public static $image_types = [ self::TYPE_POSTER => 'poster', self::TYPE_SLIDESHOW => 'slide show', self::TYPE_THUMBNAIL => 'thumbnail', self::TYPE_AUTO => 'auto' ]; public static $image_orient = [ self::ORIENTATION_LANDSCAPE => 'landscape', self::ORIENTATION_PORTRAIT => 'portrait' ]; /** * @var $image UploadedFile */ public $image; /** * Create snapshot param * @param Content $video */ private static function initParamSnapshot($video, $position) { $snapshots = []; $folderSave = self::createFolderImage($video->id); if (!$folderSave) { return false; } if($position <= 0 || $position > $video->duration){ $position = rand(1, $video->duration); } $saveFileName = time() . '_' . CVietnameseTools::makeValidFileName($video->display_name . '_' . $position . '_snapshot.jpg'); $snapshot = new Snapshot(); $snapshot->time = $position; $snapshot->file_path = Yii::getAlias($folderSave) . $saveFileName; $snapshot->size = '100%'; $snapshots[] = $snapshot; return $snapshots; } private static function toAlias($path) { $basePath = Yii::getAlias('@webroot'); Yii::info(preg_quote($basePath, '/')); return preg_replace('/'.preg_quote($basePath, '/').'/', '@webroot', $path); } /** * @inheritdoc */ public function rules() { return [ [['image'], 'file', 'extensions' => ['jpg', 'png', 'jpeg', 'gif']], ['id', 'safe'], [['type', 'orientation'], 'integer'], [['url', 'name'], 'string', 'max' => 500], ]; } public function fields() { // if ($this->scenario == static::SCENARIO_DEFAULT) { // return parent::fields(); // } //List scenario $res = [ // field name is "email", the corresponding attribute name is "email_address" 'name', 'url', 'type', 'orientation', ]; return $res; } public function getId() { if (empty($this->_id)) { $this->_id = md5($this->url); } return $this->_id; } /** * Return full path url */ public function getImageUrl() { $validator = new UrlValidator(); if ($validator->validate($this->url)) { return $this->url; } else { if (preg_match('/(@[a-z]*)/', $this->url)) { return Yii::getAlias($this->url); } else { $configImage = self::getImageConfig(); $baseUrl = isset($configImage['base_url']) ? $configImage['base_url'] : Yii::getAlias('@web'); return $baseUrl . $this->url; } } } public function getFilePath() { $validator = new UrlValidator(); if ($validator->validate($this->url)) { return null; } else { if (preg_match('/(@[a-z]*)/', $this->url)) { return Yii::getAlias(str_replace('@web', '@webroot', $this->url)); } else { $configImage = self::getImageConfig(); $baseUrl = isset($configImage['base_url']) ? $configImage['base_url'] : Yii::getAlias('@webroot'); return $baseUrl . $this->url; } } } public function getWidthHeight() { if(is_file($this->getFilePath())){ $imageSize = getimagesize($this->getFilePath()); if ($imageSize) { return $imageSize[0] . 'x'. $imageSize[1]; } else { return 'N/A'; } }else{ return 'File not found'; } } public function getNameImageFullSave() { return time() . '_' . CVietnameseTools::makeValidFileName($this->name); } public static function getImageConfig() { if (Image::$imageConfig == null) { Image::$imageConfig = [ 'folder' => '@webroot' . DIRECTORY_SEPARATOR . Yii::getAlias('@content_images') . DIRECTORY_SEPARATOR, 'base_url' => Yii::getAlias('@web') . '/' . Yii::getAlias('@content_images') . DIRECTORY_SEPARATOR ]; } return Image::$imageConfig; } /** * Create folder to store image * Each store have image separate with video id * @return full path folder with alias (@webroot/...) */ public static function createFolderImage($video_id) { $configImage = self::getImageConfig(); $basePath = Yii::getAlias($configImage['folder']); if (!is_dir($basePath)) { FileHelper::createDirectory($basePath, 0777); } if (!is_dir($basePath) || $video_id == null) { Yii::error("Folder base path not exist: " . $basePath); return false; } $fullPath = $basePath . $video_id; if (!is_dir($fullPath)) { if (!FileHelper::createDirectory($fullPath, 0777)) { Yii::error("Can not create folder save image: " . $fullPath); return false; } } if (!substr($configImage['folder'], -1) == '/') { $configImage['folder'] .= '/'; } return $configImage['folder'] . $video_id . '/'; } /** * Thuc hien save image khi dc upload len * @param $content News * @return bool * @throws \yii\web\UnauthorizedHttpException */ public function saveImage($content) { $video_id = $content->id; $folderSave = self::createFolderImage($video_id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } if ($this->image == null) { $this->addError('image', "Image file not found!"); return false; } $saveFileName = $this->getNameImageFullSave(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); if (!$this->image->saveAs($imagePath)) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::ORIENTATION_LANDSCAPE; } else { $this->orientation = self::ORIENTATION_PORTRAIT; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; if ($this->type == self::TYPE_AUTO) { $this->autoGenerateImages($content, $folderSave, $saveFileName); } return true; } /** * replaces '/(@[a-z]*)root/' => '$1' * @param string $path * @return string */ public function resolveUrl($path) { return preg_replace('/(@[a-z]*)root/', '$1', $path); } /** * @param $content News */ public function save($content) { return $content->addImage($this->getArray()); } public function getArray() { return [ 'name' => $this->name, 'url' => $this->url, 'type' => $this->type, 'orientation' => $this->orientation ]; } public function delete() { //Delete image $file_path = $this->getFilePath(); if (is_dir($file_path)) { return true; } if ($file_path && file_exists($file_path)) { return unlink($this->getFilePath()); } return true; } /** * @param $video Content * @return bool */ public function loadImageYt($video) { $ch = new MyCurl(); $folderSave = self::createFolderImage($video->id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } $yt_info = CommonUtils::getVideoYoutubeInfo($video->youtube_id); if ($yt_info == null || $yt_info->snippet == null || $yt_info->snippet->thumbnails == null) { return false; } $img_yt_url = ''; $thumbnails = $yt_info->snippet->thumbnails; $img_yt_url = $this->getHighestImage($thumbnails); if (empty($img_yt_url)) { return false; } $image_extention = end(explode('.', $img_yt_url)); $this->name = $video->display_name . '_yt.' . $image_extention; $this->type = self::TYPE_AUTO; $saveFileName = $this->getNameImageFullSave(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); $response = $ch->download($img_yt_url, Yii::getAlias($folderSave), $saveFileName); if (!$response) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::ORIENTATION_LANDSCAPE; } else { $this->orientation = self::ORIENTATION_PORTRAIT; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; $this->autoGenerateImages($video, $folderSave, $saveFileName); if ($yt_info->contentDetails != null) { $video->duration = CommonUtils::convertYtDurationToSeconds($yt_info->contentDetails->duration); $video->update(false); } return true; } /** * @param Content $video * @return bool */ public static function loadImageSnapshot($video, $video_file, $position = 0) { $snapshots = self::initParamSnapshot($video,$position); $response = MediaToolBoxHelper::getVideoSnapshot($video_file, $snapshots); if (!$response) { Yii::error('Can not get snapshot'); return false; } foreach ($response as $snapshot) { $image = new Image(); $folderSave = self::toAlias(pathinfo($snapshot->file_path, PATHINFO_DIRNAME).DIRECTORY_SEPARATOR); $saveFileName = pathinfo($snapshot->file_path, PATHINFO_BASENAME); $image->name = $saveFileName; $image->autoGenerateImages($video, $folderSave, $saveFileName); } return true; } /** * Load first image from content to create some image * @param $content Content */ public function loadImageFromContent($content) { $ch = new MyCurl(); $folderSave = self::createFolderImage($content->id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } $img_content_url = ''; $html = SimpleHtmlDom::str_get_html($content->content); // Get first image foreach($html->find('img') as $element){ $img_content_url = $element->src; if(!empty($img_content_url)) break; } if(empty($img_content_url)){ return false; } $url_validator = new UrlValidator(); if(!$url_validator->validate($img_content_url)){ $img_content_url = Yii::$app->getUrlManager()->getHostInfo().$img_content_url; } Yii::info($img_content_url); $image_extention = end(explode('.', $img_content_url)); $this->name = $content->display_name . '_content.' . $image_extention; $this->type = self::TYPE_AUTO; $saveFileName = $this->getNameImageFullSave(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'Image'); $response = $ch->download($img_content_url, Yii::getAlias($folderSave), $saveFileName); if (!$response || !CommonUtils::validateImage($imagePath)) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::ORIENTATION_LANDSCAPE; } else { $this->orientation = self::ORIENTATION_PORTRAIT; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; $this->autoGenerateImages($content, $folderSave, $saveFileName); return true; } /** * Tu dong generate ra cac file dinh dang khac nhau * @param $video * @param $folderSave //Dang tuong doi example '@webroot/content_images/45/ * @param $saveFileName * @return bool */ public function autoGenerateImages($video, $folderSave, $saveFileName) { $imagePath = Yii::getAlias($folderSave) . $saveFileName; $imageSize = getimagesize($imagePath); $img_width = 1; $img_height = 1; if (count($imageSize) > 0) { $img_width = $imageSize[0]; $img_height = $imageSize[1]; } else { return false; } //Resize to slide $slide = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height, self::TYPE_SLIDESHOW); if (!$slide->save($video)) { return false; } //Resize to poster $poster = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height); if (!$poster->save($video)) { return false; }; //Resize to thumbnail $poster = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height, self::TYPE_THUMBNAIL); if (!$poster->save($video)) { return false; } } /** * @param $imageTool \yii\imagine\Image * @param $width * @param $heigh */ private function resizeImage($folder, $filename, $width, $height, $type = self::TYPE_POSTER) { $model = new Image(); $box_src = new Box($width, $height); $box = null; switch ($type) { case self::TYPE_THUMBNAIL: $box = new Box(320, 180); break; default: if (($width / $height) === (self::RATIO_W / self::RATIO_H)) { $box = $box_src; } else { list($new_width, $new_height) = $this->getNewSize($width, $height, self::RATIO_W / self::RATIO_H); $box = new Box($new_width, $new_height); } } $imageTool = \yii\imagine\Image::getImagine()->open($filename); $image = $imageTool->thumbnail($box, ManipulatorInterface::THUMBNAIL_OUTBOUND); $model->name = self::$image_types[$type] . '_' . $this->name; $model->type = $type; $saveFileName = $model->getNameImageFullSave(); $imagePath = Yii::getAlias($folder) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); if (!$image->save($imagePath)) { return null; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $model->orientation = self::ORIENTATION_LANDSCAPE; } else { $model->orientation = self::ORIENTATION_PORTRAIT; } } $model->url = $this->resolveUrl($folder) . $saveFileName; return $model; } private function getHighestImage($thumbnails) { if ($thumbnails->maxres != null) { return $thumbnails->maxres->url; } if ($thumbnails->standard != null) { return $thumbnails->standard->url; } if ($thumbnails->high != null) { return $thumbnails->high->url; } if ($thumbnails->medium != null) { return $thumbnails->medium->url; } if ($thumbnails->default != null) { return $thumbnails->default->url; } } private function getNewSize($width, $height, $ratio) { // Find closest ratio multiple to image size if ($width > $height) { // landscape $ratioMultiple = round($height / self::RATIO_H, 0, PHP_ROUND_HALF_DOWN); } else { // portrait $ratioMultiple = round($width / self::RATIO_W, 0, PHP_ROUND_HALF_DOWN); } $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; if ($newWidth > self::RATIO_W * self::RATIO_MULIPLIER_UPPER_LIMIT || $newHeight > self::RATIO_H * self::RATIO_MULIPLIER_UPPER_LIMIT) { // File is larger than upper limit $ratioMultiple = self::RATIO_MULIPLIER_UPPER_LIMIT; } $this->tweakMultiplier($ratioMultiple, $width, $height); $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; return [ $newWidth, $newHeight ]; } /** * Xac dinh ratio sao cho new_width, new_height kho qua kich thuoc anh that * @param $ratioMultiple * @param $fitInsideWidth * @param $fitInsideHeight */ protected function tweakMultiplier(&$ratioMultiple, $fitInsideWidth, $fitInsideHeight) { $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; if ($newWidth > $fitInsideWidth || $newHeight > $fitInsideHeight) { $ratioMultiple--; $this->tweakMultiplier($ratioMultiple, $fitInsideWidth, $fitInsideHeight); } else { return; } } }
Java
Ext.define('Ozone.data.Dashboard', { extend: 'Ext.data.Model', idProperty: 'guid', fields:[ 'alteredByAdmin', 'guid', {name:'id', mapping: 'guid'}, { name: 'isdefault', type: 'boolean', defaultValue: false }, { name: 'dashboardPosition', type: 'int' }, 'EDashboardLayoutList', 'name', { name: 'state', defaultValue: [] }, 'removed', 'groups', 'isGroupDashboard', 'description', 'createdDate', 'prettyCreatedDate', 'editedDate', 'prettyEditedDate', { name: 'stack', defaultValue: null }, { name: 'locked', type: 'boolean', defaultValue: false }, { name: 'layoutConfig', defaultValue: null }, { name: 'createdBy', model: 'User'}, { name: 'user', model: 'User'} ], constructor: function(data, id, raw) { if(data.layoutConfig && typeof data.layoutConfig === 'string' && data.layoutConfig !== Object.prototype.toString()) { data.layoutConfig = Ext.JSON.decode(data.layoutConfig); } //todo see if we still need this if(data.layoutConfig === Object.prototype.toString()) { data.layoutConfig = ""; } if(!data.guid) { data.guid = guid.util.guid(); } this.callParent(arguments); } }); Ext.define('Ozone.data.stores.AdminDashboardStore', { extend:'Ozone.data.OWFStore', model: 'Ozone.data.Dashboard', alias: 'store.admindashboardstore', remoteSort: true, totalProperty:'results', sorters: [ { property : 'dashboardPosition', direction: 'ASC' } ], constructor: function(config) { Ext.applyIf(config, { api: { read: "/dashboard", create: "/dashboard", update: "/dashboard", destroy: "/dashboard" }, reader: { root: 'data' }, writer: { root: 'data' } }); this.callParent(arguments); }, reorder: function() { if (this.getCount() > 0) { for (var i = 0; i < this.getCount(); i++) { var dashboard = this.getAt(i); dashboard.set('dashboardPosition', i + 1); } } } }); Ext.define('Ozone.components.admin.grid.DashboardGroupsGrid', { extend: 'Ext.grid.Panel', alias: ['widget.dashboardgroupsgrid'], quickSearchFields: ['name'], plugins: new Ozone.components.focusable.FocusableGridPanel(), cls: 'grid-dashboard', defaultPageSize: 50, multiSelect: true, forceFit: true, baseParams: null, initComponent: function() { //create new store if (this.store == null) { this.store = Ext.StoreMgr.lookup({ type: 'admindashboardstore', pageSize: this.defaultPageSize }); } if (this.baseParams) { this.setBaseParams(this.baseParams); } Ext.apply(this, { columnLines:true, columns: [ { itemId: 'guid', header: 'GUID', dataIndex: 'guid', flex: 1, width: 210, minWidth: 210, sortable: true, hidden: true, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { return '<div class="grid-text">' + value +'</div>'; } },{ itemId: 'name', header: 'Dashboard Title', dataIndex: 'name', flex: 3, minWidth: 200, sortable: true, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { var title = value; var dashboardLayoutList = record.get('EDashboardLayoutList'); //List of valid ENUM Dashboard Layout Strings var dashboardLayout = record.get('layout'); //current dashboard layout string var iconClass = "grid-dashboard-default-icon-layout"; // if(dashboardLayout && dashboardLayoutList){ // if(dashboardLayoutList.indexOf(dashboardLayout) != -1){ // iconClass = "grid-dashboard-icon-layout-" + dashboardLayout; // } // } // var retVal = '<div class="grid-dashboard-title-box"><div class="grid-dashboard-icon ' + iconClass +'"></div>'; // retVal += '<div class="grid-dashboard-title">' + title + '</div>'; // retVal += '</div>'; return '<p class="grid-dashboard-title '+ iconClass + '">' + Ext.htmlEncode(title) + '</p>'; } }, { itemId: 'groups', header: 'Groups', dataIndex: 'groups', flex: 1, sortable: false, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { return '<div class="grid-text grid-dashboard-group-count">' + value.length +'</div>'; } }, { itemId: 'widgets', header: 'Widgets', dataIndex: 'layoutConfig', flex: 1, sortable: false, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { var widgetCount = 0; if (value) { var countWidgets = function(cfg) { if(!cfg || !cfg.items) return; if(cfg.items.length === 0) { if(cfg.widgets && cfg.widgets.length > 0) { widgetCount += cfg.widgets.length; } } else { for(var i = 0, len = cfg.items.length; i < len; i++) { countWidgets(cfg.items[i]); } } return widgetCount; }; widgetCount = countWidgets(value); } return '<div class="grid-text grid-dashboard-widget-count">' + widgetCount +'</div>'; } } ] }); Ext.apply(this, { multiSelect: true, dockedItems: [Ext.create('Ext.toolbar.Paging', { dock: 'bottom', store: this.store, displayInfo: true, hidden: this.hidePagingToolbar, itemId: 'dashboard-groups-grid-paging' })] }); this.callParent(arguments); }, getSelectedDashboards: function(){ return this.getSelectionModel().getSelection(); }, load: function() { this.store.loadPage(1); }, refresh: function() { this.store.loadPage(this.store.currentPage); }, getTopToolbar: function() { return this.getDockedItems('toolbar[dock="top"]')[0]; }, getBottomToolbar: function() { return this.getDockedItems('toolbar[dock="bottom"]')[0]; }, applyFilter: function(filterText, fields) { this.store.proxy.extraParams = undefined; if (filterText) { var filters = []; for (var i = 0; i < fields.length; i++) { filters.push({ filterField: fields[i], filterValue: filterText }); } this.store.proxy.extraParams = { filters: Ext.JSON.encode(filters), filterOperator: 'OR' }; } if (this.baseParams) { this.setBaseParams(this.baseParams); } this.store.loadPage(1,{ params: { offset: 0, max: this.store.pageSize } }); }, clearFilters: function() { this.store.proxy.extraParams = undefined; if (this.baseParams) { this.setBaseParams(this.baseParams); } this.store.load({ params: { start: 0, max: this.store.pageSize } }); }, setBaseParams: function(params) { this.baseParams = params; if (this.store.proxy.extraParams) { Ext.apply(this.store.proxy.extraParams, params); } else { this.store.proxy.extraParams = params; } }, setStore: function(store, cols) { this.reconfigure(store, cols); var pgtb = this.getBottomToolbar(); if (pgtb) { pgtb.bindStore(store); } } }); Ext.define('Ozone.components.admin.dashboard.DashboardDetailPanel', { extend: 'Ext.panel.Panel', alias: ['widget.dashboarddetailpanel', 'widget.dashboarddetail'], viewDashboard: null, loadedRecord: null, initComponent: function() { //init quicktips Ext.tip.QuickTipManager.init(true,{ dismissDelay: 60000, showDelay: 2000 }); this.viewDashboard = Ext.create('Ext.view.View', { store: Ext.create('Ext.data.Store', { storeId: 'storeDashboardItem', fields: [ { name: 'name', type: 'string' }, { name: 'layout', type: 'string' }, { name: 'EDashboardLayoutList', type: 'string' }, { name: 'isGroupDashboard', type: 'boolean'}, { name: 'groups', model: 'Group'}, { name: 'description', type: 'string' }, { name: 'createdDate', type: 'string' }, { name: 'prettyCreatedDate', type: 'string' }, { name: 'editedDate', type: 'string' }, { name: 'prettyEditedDate', type: 'string' }, { name: 'createdBy', model: 'User' }, { name: 'stack', model: 'Stack'} ] }), deferEmptyText: false, tpl: new Ext.XTemplate( '<tpl for=".">', '<div class="selector">', '<div id="detail-info" class="detail-info">', '<div class="dashboard-detail-icon-block">', '{[this.renderIconBlock(values)]}', '</div>', '<div class="dashboard-detail-info-block">', '<div class="detail-header-block">', '{[this.renderDetailHeaderBlock(values)]}', '</div>', '<div class="detail-block">', '<div><span class="detail-label">Description:</span> {description:htmlEncode}</span></div><br>', '<div><span class="detail-label">Groups:</span> {[this.renderGroups(values)]}</div>', '<div><span class="detail-label">Created:</span> <span {createdDate:this.renderToolTip}>{prettyCreatedDate:this.renderDate}</span></div>', '<div><span class="detail-label">Author:</span> {[this.renderUserRealName(values)]}</div>', '<div><span class="detail-label">Last Modified:</span> <span {editedDate:this.renderToolTip}>{prettyEditedDate:this.renderDate}</span></div>', '</div>', '</div>', '</div>', '</div>', '</tpl>', { compiled: true, renderDate: function(value) { return value ? value : ''; }, renderToolTip: function (value) { var str = 'data-qtip="' + value + '"'; return str; }, renderUserRealName: function(values) { var createdBy = values.createdBy; return (createdBy.userRealName ? Ext.htmlEncode(createdBy.userRealName) : '') }, renderGroups: function(values) { var groups = values.groups; var stack = values.stack; var retVal = ''; if (!stack && groups && groups.length > 0) { for (var i = -1; ++i < groups.length;) { retVal += Ext.htmlEncode(groups[i].name) + ', '; } retVal = retVal.substring(0, retVal.length - 2); } return retVal; }, renderIconBlock: function(values) { var iconClass = "dashboard-default-icon-layout"; var retVal = '<div class="dashboard-icon ' + iconClass + '"></div>'; return retVal; }, renderDetailHeaderBlock: function(values){ var isGroupDashboard = values.isGroupDashboard; var title = values.name; var retVal = '<div class="dashboard-title-block">'; retVal += '<div class="dashboard-title detail-title">' + Ext.htmlEncode(title) + '</div>'; retVal += (isGroupDashboard) ? '<div>This is a group dashboard.</div>' : ''; retVal += '</div>'; return retVal; } } ), emptyText: 'No dashboard selected', itemSelector: 'div.selector', autoScroll: 'true' }); this.items = [this.viewDashboard]; this.callParent(arguments); }, loadData: function(record) { this.viewDashboard.store.loadData([record], false); this.loadedRecord = record; }, removeData: function() { this.viewDashboard.store.removeAll(false); this.loadedRecord = null; } }); Ext.define('Ozone.components.admin.dashboard.GroupDashboardManagementPanel', { extend: 'Ozone.components.admin.ManagementPanel', alias: ['widget.groupdashboardmanagement','widget.groupdashboardmanagementpanel','widget.Ozone.components.admin.GroupDashboardManagementPanel'], layout: 'fit', cls: 'groupdashboardmanagementpanel', gridDashboards: null, pnlDashboardDetail: null, txtHeading: null, lastAction: null, guid_EditCopyWidget: null, widgetStateHandler: null, dragAndDrop: true, launchesWidgets: true, channel: 'AdminChannel', defaultTitle: 'Group Dashboards', minButtonWidth: 80, detailsAutoOpen: true, initComponent: function() { var me = this; OWF.Preferences.getUserPreference({ namespace: 'owf.admin.DashboardEditCopy', name: 'guid_to_launch', onSuccess: function(result) { me.guid_EditCopyWidget = result.value; }, onFailure: function(err){ /* No op */ me.showAlert('Preferences Error', 'Error looking up Dashboard Editor: ' + err); } }); this.gridDashboards = Ext.create('Ozone.components.admin.grid.DashboardGroupsGrid', { preventHeader: true, region: 'center', border: false }); this.gridDashboards.setBaseParams({ adminEnabled: true, isGroupDashboard: true, isStackDashboard: false }); this.gridDashboards.store.load({ params: { offset: 0, max: this.pageSize } }); this.relayEvents(this.gridDashboards, ['datachanged', 'select', 'deselect', 'itemdblclick']); this.pnlDashboardDetail = Ext.create('Ozone.components.admin.dashboard.DashboardDetailPanel', { layout: { type: 'fit', align: 'stretch' }, region: 'east', preventHeader: true, collapseMode: 'mini', collapsible: true, collapsed: true, split: true, border: false, width: 266 }); this.txtHeading = Ext.create('Ext.toolbar.TextItem', { text: '<span class="heading-bold">'+this.defaultTitle+'</span>' }); this.searchBox = Ext.widget('searchbox'); this.items = [{ xtype: 'panel', layout: 'border', border: false, items: [ this.gridDashboards, this.pnlDashboardDetail ] }]; this.dockedItems = [{ xtype: 'toolbar', dock: 'top', layout: { type: 'hbox', align: 'stretchmax' }, items: [ this.txtHeading, { xtype: 'tbfill' }, this.searchBox ] }, { xtype: 'toolbar', dock: 'bottom', ui: 'footer', defaults: { minWidth: this.minButtonWidth }, items: [{ xtype: 'button', text: 'Create', handler: function(button, evt) { evt.stopPropagation(); me.doCreate(); } }, { xtype: 'button', text: 'Edit', handler: function() { me.doEdit(); } }, { xtype: 'button', text: 'Delete', handler: function(button) { me.doDelete(); } }] }]; this.gridDashboards.store.on( 'load', function(thisStore, records, options){ if ((this.pnlDashboardDetail != null ) && (!this.pnlDashboardDetail.collapsed) && (this.pnlDashboardDetail.loadedRecord != null)){ for(var idx=0; idx < records.length; idx++){ if(records[idx].id == this.pnlDashboardDetail.loadedRecord.id){ this.pnlDashboardDetail.loadData(records[idx]); break; } } } }, this ); this.on( 'datachanged', function(store, opts) { //collapse and clear detail panel if the store is refreshed if (this.pnlDashboardDetail != null ) { this.pnlDashboardDetail.collapse(); this.pnlDashboardDetail.removeData(); } //refresh launch menu if (!this.disableLaunchMenuRefresh) { this.refreshWidgetLaunchMenu(); } }, this ); this.on( 'select', function(rowModel, record, index, opts) { this.pnlDashboardDetail.loadData(record); if (this.pnlDashboardDetail.collapsed && this.detailsAutoOpen) {this.pnlDashboardDetail.expand();} }, this ); this.searchBox.on( 'searchChanged', function(searchbox, value) { var grid = this.gridDashboards; if (grid) { if (!value) this.gridDashboards.clearFilters(); else this.gridDashboards.applyFilter(value, ['name', 'description']); } }, this ); this.on({ 'itemdblclick': { scope: this, fn: this.doEdit } }); this.gridDashboards.getView().on({ itemkeydown: { scope: this, fn: function(view, record, dom, index, evt) { switch(evt.getKey()) { case evt.SPACE: case evt.ENTER: this.doEdit(); } } } }); this.callParent(arguments); OWF.Eventing.subscribe('AdminChannel', owfdojo.hitch(this, function(sender, msg, channel) { if(msg.domain === 'Dashboard') { this.gridDashboards.getBottomToolbar().doRefresh(); } })); this.on( 'afterrender', function() { var splitterEl = this.el.down(".x-collapse-el"); splitterEl.on('click', function() { var collapsed = this.el.down(".x-splitter-collapsed"); if(collapsed) { this.detailsAutoOpen = true; } else { this.detailsAutoOpen = false; } }, this); }, this ); }, onLaunchFailed: function(response) { if (response.error) { this.showAlert('Launch Error', 'Dashboard Editor Launch Failed: ' + response.message); } }, doCreate: function() { var dataString = Ozone.util.toString({ copyFlag: false, isCreate: true, isGroupDashboard: true }); OWF.Launcher.launch({ guid: this.guid_EditCopyWidget, launchOnlyIfClosed: false, data: dataString }, this.onLaunchFailed); }, doEdit: function() { var records = this.gridDashboards.getSelectedDashboards(); if (records && records.length > 0) { for (var i = 0; i < records.length; i++) { var id = records[i].getId();//From Id property of Dashboard Model var dataString = Ozone.util.toString({ id: id, copyFlag: false, isCreate: false, isGroupDashboard: true }); OWF.Launcher.launch({ title: '$1 - ' + records[i].get('name'), titleRegex: /(.*)/, guid: this.guid_EditCopyWidget, launchOnlyIfClosed: false, data: dataString }, this.onLaunchFailed); } } else { this.showAlert("Error", "You must select at least one dashboard to edit"); } }, doDelete: function() { var records = this.gridDashboards.getSelectionModel().getSelection(); if (records && records.length > 0) { var msg = 'This action will permanently delete '; if (records.length == 1) { msg += '<span class="heading-bold">' + Ext.htmlEncode(records[0].data.name) + '</span>.'; } else { msg += 'the selected <span class="heading-bold">' + records.length + ' dashboards</span>.'; } this.showConfirmation('Warning', msg, function(btn, text, opts) { if(btn == 'ok') { var store = this.gridDashboards.getStore(); store.remove(records); var remainingRecords = store.getTotalCount() - records.length; store.on({ write: { fn: function() { if(store.data.items.length == 0 && store.currentPage > 1) { var lastPage = store.getPageFromRecordIndex(remainingRecords - 1); var pageToLoad = (lastPage >= store.currentPage) ? store.currentPage : lastPage; store.loadPage(pageToLoad); } this.gridDashboards.getBottomToolbar().doRefresh(); this.pnlDashboardDetail.removeData(); if(!this.pnlDashboardDetail.collapsed) { this.pnlDashboardDetail.collapse();} this.refreshWidgetLaunchMenu(); }, scope: this, single: true } }); store.save(); } }); } else { this.showAlert("Error", "You must select at least one dashboard to delete"); } } });
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_45.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-45.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: file Read input from a file * GoodSource: Full path and file name * Sinks: fopen * BadSink : Open the file named in data using fopen() * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #define FOPEN _wfopen #else #define FOPEN fopen #endif namespace CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_45 { static wchar_t * badData; static wchar_t * goodG2BData; #ifndef OMITBAD static void badSink() { wchar_t * data = badData; { FILE *pFile = NULL; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ pFile = FOPEN(data, L"wb+"); if (pFile != NULL) { fclose(pFile); } } } void bad() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (FILENAME_MAX-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } badData = data; badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink() { wchar_t * data = goodG2BData; { FILE *pFile = NULL; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ pFile = FOPEN(data, L"wb+"); if (pFile != NULL) { fclose(pFile); } } } static void goodG2B() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; #ifdef _WIN32 /* FIX: Use a fixed, full path and file name */ wcscat(data, L"c:\\temp\\file.txt"); #else /* FIX: Use a fixed, full path and file name */ wcscat(data, L"/tmp/file.txt"); #endif goodG2BData = data; goodG2BSink(); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_45; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__new_twoIntsStruct_52b.cpp Label Definition File: CWE401_Memory_Leak__new.label.xml Template File: sources-sinks-52b.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: Allocate data using new * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call delete on data * BadSink : no deallocation of data * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif namespace CWE401_Memory_Leak__new_twoIntsStruct_52 { #ifndef OMITBAD /* bad function declaration */ void badSink_c(twoIntsStruct * data); void badSink_b(twoIntsStruct * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(twoIntsStruct * data); void goodG2BSink_b(twoIntsStruct * data) { goodG2BSink_c(data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink_c(twoIntsStruct * data); void goodB2GSink_b(twoIntsStruct * data) { goodB2GSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */
Java
/*********************************************************************** * Copyright (c) 2009, Secure Endpoints Inc. * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #include <config.h> #include <roken.h> #include <strsafe.h> #ifndef _WIN32 #error This implementation is Windows specific. #endif /** * wait_for_process_timed waits for a process to terminate or until a * specified timeout occurs. * * @param[in] pid Process id for the monitored process * @param[in] func Timeout callback function. When the wait times out, * the callback function is called. The possible return values * from the callback function are: * * - ((time_t) -2) Exit loop without killing child and return SE_E_EXECTIMEOUT. * - ((time_t) -1) Kill child with SIGTERM and wait for child to exit. * - 0 Don't timeout again * - n Seconds to next timeout * * @param[in] ptr Optional parameter for func() * * @param[in] timeout Seconds to first timeout. * * @retval SE_E_UNSPECIFIED Unspecified system error * @retval SE_E_FORKFAILED Fork failure (not applicable for _WIN32 targets) * @retval SE_E_WAITPIDFAILED waitpid errors * @retval SE_E_EXECTIMEOUT exec timeout * @retval 0 <= Return value from subprocess * @retval SE_E_NOTFOUND The program coudln't be found * @retval 128- The signal that killed the subprocess +128. */ ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL wait_for_process_timed(pid_t pid, time_t (*func)(void *), void *ptr, time_t timeout) { HANDLE hProcess; DWORD wrv = 0; DWORD dtimeout; int rv = 0; hProcess = OpenProcess(SYNCHRONIZE, FALSE, pid); if (hProcess == NULL) { return SE_E_WAITPIDFAILED; } dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); do { wrv = WaitForSingleObject(hProcess, dtimeout); if (wrv == WAIT_OBJECT_0) { DWORD prv = 0; GetExitCodeProcess(hProcess, &prv); rv = (int) prv; break; } else if (wrv == WAIT_TIMEOUT) { if (func == NULL) continue; timeout = (*func)(ptr); if (timeout == (time_t)-1) { if (TerminateProcess(hProcess, 128 + 9)) { dtimeout = INFINITE; continue; } rv = SE_E_UNSPECIFIED; break; } else if (timeout == (time_t) -2) { rv = SE_E_EXECTIMEOUT; break; } else { dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); continue; } } else { rv = SE_E_UNSPECIFIED; break; } } while(TRUE); CloseHandle(hProcess); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL wait_for_process(pid_t pid) { return wait_for_process_timed(pid, NULL, NULL, 0); } static char * collect_commandline(const char * fn, va_list * ap) { size_t len = 0; size_t alloc_len = 0; const char * s; char * cmd = NULL; for (s = fn; s; s = (char *) va_arg(*ap, char *)) { size_t cmp_len; int need_quote = FALSE; if (FAILED(StringCchLength(s, MAX_PATH, &cmp_len))) { if (cmd) free(cmd); return NULL; } if (cmp_len == 0) continue; if (strchr(s, ' ') && /* need to quote any component that has embedded spaces, but not if they are already quoted. */ s[0] != '"' && s[cmp_len - 1] != '"') { need_quote = TRUE; cmp_len += 2 * sizeof(char); } if (s != fn) cmp_len += 1 * sizeof(char); if (alloc_len < len + cmp_len + 1) { char * nc; alloc_len += ((len + cmp_len - alloc_len) / MAX_PATH + 1) * MAX_PATH; nc = (char *) realloc(cmd, alloc_len * sizeof(char)); if (nc == NULL) { if (cmd) free(cmd); return NULL; } } if (cmd == NULL) return NULL; if (s != fn) cmd[len++] = ' '; if (need_quote) { StringCchPrintf(cmd + len, alloc_len - len, "\"%s\"", s); } else { StringCchCopy(cmd + len, alloc_len - len, s); } len += cmp_len; } return cmd; } ROKEN_LIB_FUNCTION pid_t ROKEN_LIB_CALL pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd, const char *file, ...) { HANDLE hOut_r = NULL; HANDLE hOut_w = NULL; HANDLE hIn_r = NULL; HANDLE hIn_w = NULL; HANDLE hErr_r = NULL; HANDLE hErr_w = NULL; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; char * commandline = NULL; pid_t rv = (pid_t) -1; { va_list ap; va_start(ap, file); commandline = collect_commandline(file, &ap); if (commandline == NULL) return rv; } ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&sa, sizeof(sa)); pi.hProcess = NULL; pi.hThread = NULL; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; if ((stdout_fd && !CreatePipe(&hOut_r, &hOut_w, &sa, 0 /* Use default */)) || (stdin_fd && !CreatePipe(&hIn_r, &hIn_w, &sa, 0)) || (stderr_fd && !CreatePipe(&hErr_r, &hErr_w, &sa, 0)) || (!stdout_fd && (hOut_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) || (!stdin_fd && (hIn_r = CreateFile("CON",GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) || (!stderr_fd && (hErr_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)) goto _exit; /* We don't want the child processes inheriting these */ if (hOut_r) SetHandleInformation(hOut_r, HANDLE_FLAG_INHERIT, FALSE); if (hIn_w) SetHandleInformation(hIn_w, HANDLE_FLAG_INHERIT, FALSE); if (hErr_r) SetHandleInformation(hErr_r, HANDLE_FLAG_INHERIT, FALSE); si.cb = sizeof(si); si.lpReserved = NULL; si.lpDesktop = NULL; si.lpTitle = NULL; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = hIn_r; si.hStdOutput = hOut_w; si.hStdError = hErr_w; if (!CreateProcess(file, commandline, NULL, NULL, TRUE, /* bInheritHandles */ CREATE_NO_WINDOW, /* dwCreationFlags */ NULL, /* lpEnvironment */ NULL, /* lpCurrentDirectory */ &si, &pi)) { rv = (pid_t) (GetLastError() == ERROR_FILE_NOT_FOUND)? 127 : -1; goto _exit; } if (stdin_fd) { *stdin_fd = _fdopen(_open_osfhandle((intptr_t) hIn_w, 0), "wb"); if (*stdin_fd) hIn_w = NULL; } if (stdout_fd) { *stdout_fd = _fdopen(_open_osfhandle((intptr_t) hOut_r, _O_RDONLY), "rb"); if (*stdout_fd) hOut_r = NULL; } if (stderr_fd) { *stderr_fd = _fdopen(_open_osfhandle((intptr_t) hErr_r, _O_RDONLY), "rb"); if (*stderr_fd) hErr_r = NULL; } rv = (pid_t) pi.dwProcessId; _exit: if (pi.hProcess) CloseHandle(pi.hProcess); if (pi.hThread) CloseHandle(pi.hThread); if (hIn_r) CloseHandle(hIn_r); if (hIn_w) CloseHandle(hIn_w); if (hOut_r) CloseHandle(hOut_r); if (hOut_w) CloseHandle(hOut_w); if (hErr_r) CloseHandle(hErr_r); if (hErr_w) CloseHandle(hErr_w); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp_timed(const char *file, char *const args[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnvp(_P_NOWAIT, file, args); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp(const char *file, char *const args[]) { return simple_execvp_timed(file, args, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve_timed(const char *file, char *const args[], char *const envp[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnve(_P_NOWAIT, file, args, envp); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve(const char *file, char *const args[], char *const envp[]) { return simple_execve_timed(file, args, envp, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execlp(const char *file, ...) { va_list ap; char **argv; int ret; va_start(ap, file); argv = vstrcollect(&ap); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execvp(file, argv); free(argv); return ret; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execle(const char *file, ... /* ,char *const envp[] */) { va_list ap; char **argv; char *const* envp; int ret; va_start(ap, file); argv = vstrcollect(&ap); envp = va_arg(ap, char **); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execve(file, argv, envp); free(argv); return ret; }
Java
/* * Copyright (c) 2007-2009 The LIBLINEAR Project. * 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. Neither name of copyright holders 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 REGENTS 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. */ #ifndef DOXYGEN_SHOULD_SKIP_THIS #ifndef _LIBLINEAR_H #define _LIBLINEAR_H #include <shogun/lib/config.h> #include <shogun/optimization/liblinear/tron.h> #include <shogun/features/DotFeatures.h> namespace shogun { #undef I #ifdef __cplusplus extern "C" { #endif /** problem */ struct liblinear_problem { /** l */ int32_t l; /** n */ int32_t n; /** y */ float64_t* y; /** sparse features x */ std::shared_ptr<DotFeatures> x; /** if bias shall be used */ bool use_bias; }; /** parameter */ struct liblinear_parameter { /** solver type */ int32_t solver_type; /* these are for training only */ /** stopping criteria */ float64_t eps; /** C */ float64_t C; /** number of weights */ int32_t nr_weight; /** weight label */ int32_t *weight_label; /** weight */ float64_t* weight; }; /** model */ struct liblinear_model { /** parameter */ struct liblinear_parameter param; /** number of classes */ int32_t nr_class; /** number of features */ int32_t nr_feature; /** w */ float64_t *w; /** label of each class (label[n]) */ int32_t *label; /** bias */ float64_t bias; }; void destroy_model(struct liblinear_model *model_); void destroy_param(struct liblinear_parameter *param); #ifdef __cplusplus } #endif /** class l2loss_svm_vun */ class l2loss_svm_fun : public function { public: /** constructor * * @param prob prob * @param Cp Cp * @param Cn Cn */ l2loss_svm_fun(const liblinear_problem *prob, float64_t Cp, float64_t Cn); ~l2loss_svm_fun(); /** fun * * @param w w * @return something floaty */ float64_t fun(float64_t *w); /** grad * * @param w w * @param g g */ void grad(float64_t *w, float64_t *g); /** Hv * * @param s s * @param Hs Hs */ void Hv(float64_t *s, float64_t *Hs); /** get number of variables * * @return number of variables */ int32_t get_nr_variable(); private: void Xv(float64_t *v, float64_t *Xv); void subXv(float64_t *v, float64_t *Xv); void subXTv(float64_t *v, float64_t *XTv); float64_t *C; float64_t *z; float64_t *D; int32_t *I; int32_t sizeI; const liblinear_problem *prob; }; /** class l2r_lr_fun */ class l2r_lr_fun : public function { public: /** constructor * * @param prob prob * @param Cp Cp * @param Cn Cn */ l2r_lr_fun(const liblinear_problem *prob, float64_t* C); ~l2r_lr_fun(); /** fun * * @param w w * @return something floaty */ float64_t fun(float64_t *w); /** grad * * @param w w * @param g g */ void grad(float64_t *w, float64_t *g); /** Hv * * @param s s * @param Hs Hs */ void Hv(float64_t *s, float64_t *Hs); int32_t get_nr_variable(); private: void Xv(float64_t *v, float64_t *Xv); void XTv(float64_t *v, float64_t *XTv); float64_t *C; float64_t *z; float64_t *D; const liblinear_problem *m_prob; }; class l2r_l2_svc_fun : public function { public: l2r_l2_svc_fun(const liblinear_problem *prob, float64_t* Cs); ~l2r_l2_svc_fun(); double fun(double *w); void grad(double *w, double *g); void Hv(double *s, double *Hs); int get_nr_variable(); protected: void Xv(double *v, double *Xv); void subXv(double *v, double *Xv); void subXTv(double *v, double *XTv); double *C; double *z; double *D; int *I; int sizeI; const liblinear_problem *m_prob; }; class l2r_l2_svr_fun: public l2r_l2_svc_fun { public: l2r_l2_svr_fun(const liblinear_problem *prob, double *Cs, double p); double fun(double *w); void grad(double *w, double *g); private: double m_p; }; struct mcsvm_state { double* w; double* B; double* G; double* alpha; double* alpha_new; int* index; double* QD; int* d_ind; double* d_val; int* alpha_index; int* y_index; int* active_size_i; bool allocated,inited; mcsvm_state() { w = NULL; B = NULL; G = NULL; alpha = NULL; alpha_new = NULL; index = NULL; QD = NULL; d_ind = NULL; d_val = NULL; alpha_index = NULL; y_index = NULL; active_size_i = NULL; allocated = false; inited = false; } ~mcsvm_state() { SG_FREE(w); SG_FREE(B); SG_FREE(G); SG_FREE(alpha); SG_FREE(alpha_new); SG_FREE(index); SG_FREE(QD); SG_FREE(d_ind); SG_FREE(d_val); SG_FREE(alpha_index); SG_FREE(y_index); SG_FREE(active_size_i); } }; class Solver_MCSVM_CS { public: Solver_MCSVM_CS(const liblinear_problem *prob, int nr_class, double *C, double *w0, double eps, int max_iter, double train_time, mcsvm_state* given_state); ~Solver_MCSVM_CS(); template <typename PRNG> void solve(PRNG& prng); private: void solve_sub_problem(double A_i, int yi, double C_yi, int active_i, double *alpha_new); bool be_shrunk(int i, int m, int yi, double alpha_i, double minG); double *C; int w_size, l; int nr_class; int max_iter; double eps; double max_train_time; double* w0; const liblinear_problem *prob; mcsvm_state* state; }; } #endif //_LIBLINEAR_H #endif // DOXYGEN_SHOULD_SKIP_THIS
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22a.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml Template File: sources-sink-22a.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: memcpy * BadSink : Copy twoIntsStruct array to data using memcpy * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" #ifndef OMITBAD /* The global variable below is used to drive control flow in the source function */ int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badGlobal = 0; twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badSource(twoIntsStruct * data); void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_bad() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badGlobal = 1; /* true */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badSource(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* The global variables below are used to drive control flow in the source functions. */ int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Global = 0; int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Global = 0; /* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Source(twoIntsStruct * data); static void goodG2B1() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Global = 0; /* false */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Source(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */ twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Source(twoIntsStruct * data); static void goodG2B2() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Global = 1; /* true */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Source(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
Java
// 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. #include "chrome/browser/chromeos/login/users/chrome_user_manager_impl.h" #include <cstddef> #include <set> #include "ash/multi_profile_uma.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/login/signin/auth_sync_observer.h" #include "chrome/browser/chromeos/login/signin/auth_sync_observer_factory.h" #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h" #include "chrome/browser/chromeos/login/users/multi_profile_user_controller.h" #include "chrome/browser/chromeos/login/users/supervised_user_manager_impl.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_local_account.h" #include "chrome/browser/chromeos/profiles/multiprofiles_session_aborted_dialog.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/session_length_limiter.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/supervised_user/chromeos/manager_password_service_factory.h" #include "chrome/browser/supervised_user/chromeos/supervised_user_password_service_factory.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/crash_keys.h" #include "chrome/common/pref_names.h" #include "chrome/grit/theme_resources.h" #include "chromeos/chromeos_switches.h" #include "chromeos/login/user_names.h" #include "chromeos/settings/cros_settings_names.h" #include "components/session_manager/core/session_manager.h" #include "components/user_manager/remove_user_delegate.h" #include "components/user_manager/user_image/user_image.h" #include "components/user_manager/user_type.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "policy/policy_constants.h" #include "ui/base/resource/resource_bundle.h" #include "ui/wm/core/wm_core_switches.h" using content::BrowserThread; namespace chromeos { namespace { // A vector pref of the the regular users known on this device, arranged in LRU // order. const char kRegularUsers[] = "LoggedInUsers"; // A vector pref of the public accounts defined on this device. const char kPublicAccounts[] = "PublicAccounts"; // A string pref that gets set when a public account is removed but a user is // currently logged into that account, requiring the account's data to be // removed after logout. const char kPublicAccountPendingDataRemoval[] = "PublicAccountPendingDataRemoval"; } // namespace // static void ChromeUserManagerImpl::RegisterPrefs(PrefRegistrySimple* registry) { ChromeUserManager::RegisterPrefs(registry); registry->RegisterListPref(kPublicAccounts); registry->RegisterStringPref(kPublicAccountPendingDataRemoval, std::string()); SupervisedUserManager::RegisterPrefs(registry); SessionLengthLimiter::RegisterPrefs(registry); } // static scoped_ptr<ChromeUserManager> ChromeUserManagerImpl::CreateChromeUserManager() { return scoped_ptr<ChromeUserManager>(new ChromeUserManagerImpl()); } ChromeUserManagerImpl::ChromeUserManagerImpl() : ChromeUserManager(base::ThreadTaskRunnerHandle::Get(), BrowserThread::GetBlockingPool()), cros_settings_(CrosSettings::Get()), device_local_account_policy_service_(NULL), supervised_user_manager_(new SupervisedUserManagerImpl(this)), weak_factory_(this) { UpdateNumberOfUsers(); // UserManager instance should be used only on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); registrar_.Add(this, chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); // Since we're in ctor postpone any actions till this is fully created. if (base::MessageLoop::current()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies, weak_factory_.GetWeakPtr())); } local_accounts_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefDeviceLocalAccounts, base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies, weak_factory_.GetWeakPtr())); multi_profile_user_controller_.reset( new MultiProfileUserController(this, GetLocalState())); policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); avatar_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver( cros_settings_, connector->GetDeviceLocalAccountPolicyService(), policy::key::kUserAvatarImage, this)); avatar_policy_observer_->Init(); wallpaper_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver( cros_settings_, connector->GetDeviceLocalAccountPolicyService(), policy::key::kWallpaperImage, this)); wallpaper_policy_observer_->Init(); } ChromeUserManagerImpl::~ChromeUserManagerImpl() { } void ChromeUserManagerImpl::Shutdown() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::Shutdown(); local_accounts_subscription_.reset(); // Stop the session length limiter. session_length_limiter_.reset(); if (device_local_account_policy_service_) device_local_account_policy_service_->RemoveObserver(this); for (UserImageManagerMap::iterator it = user_image_managers_.begin(), ie = user_image_managers_.end(); it != ie; ++it) { it->second->Shutdown(); } multi_profile_user_controller_.reset(); avatar_policy_observer_.reset(); wallpaper_policy_observer_.reset(); registrar_.RemoveAll(); } MultiProfileUserController* ChromeUserManagerImpl::GetMultiProfileUserController() { return multi_profile_user_controller_.get(); } UserImageManager* ChromeUserManagerImpl::GetUserImageManager( const std::string& user_id) { UserImageManagerMap::iterator ui = user_image_managers_.find(user_id); if (ui != user_image_managers_.end()) return ui->second.get(); linked_ptr<UserImageManagerImpl> mgr(new UserImageManagerImpl(user_id, this)); user_image_managers_[user_id] = mgr; return mgr.get(); } SupervisedUserManager* ChromeUserManagerImpl::GetSupervisedUserManager() { return supervised_user_manager_.get(); } user_manager::UserList ChromeUserManagerImpl::GetUsersAdmittedForMultiProfile() const { // Supervised users are not allowed to use multi-profiles. if (GetLoggedInUsers().size() == 1 && GetPrimaryUser()->GetType() != user_manager::USER_TYPE_REGULAR) { return user_manager::UserList(); } user_manager::UserList result; const user_manager::UserList& users = GetUsers(); for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR && !(*it)->is_logged_in()) { MultiProfileUserController::UserAllowedInSessionReason check; multi_profile_user_controller_->IsUserAllowedInSession((*it)->email(), &check); if (check == MultiProfileUserController::NOT_ALLOWED_PRIMARY_USER_POLICY_FORBIDS) { return user_manager::UserList(); } // Users with a policy that prevents them being added to a session will be // shown in login UI but will be grayed out. // Same applies to owner account (see http://crbug.com/385034). if (check == MultiProfileUserController::ALLOWED || check == MultiProfileUserController::NOT_ALLOWED_POLICY_FORBIDS || check == MultiProfileUserController::NOT_ALLOWED_OWNER_AS_SECONDARY || check == MultiProfileUserController::NOT_ALLOWED_POLICY_CERT_TAINTED) { result.push_back(*it); } } } return result; } user_manager::UserList ChromeUserManagerImpl::GetUnlockUsers() const { const user_manager::UserList& logged_in_users = GetLoggedInUsers(); if (logged_in_users.empty()) return user_manager::UserList(); user_manager::UserList unlock_users; Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(GetPrimaryUser()); std::string primary_behavior = profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior); // Specific case: only one logged in user or // primary user has primary-only multi-profile policy. if (logged_in_users.size() == 1 || primary_behavior == MultiProfileUserController::kBehaviorPrimaryOnly) { if (GetPrimaryUser()->can_lock()) unlock_users.push_back(primary_user_); } else { // Fill list of potential unlock users based on multi-profile policy state. for (user_manager::UserList::const_iterator it = logged_in_users.begin(); it != logged_in_users.end(); ++it) { user_manager::User* user = (*it); Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user); const std::string behavior = profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior); if (behavior == MultiProfileUserController::kBehaviorUnrestricted && user->can_lock()) { unlock_users.push_back(user); } else if (behavior == MultiProfileUserController::kBehaviorPrimaryOnly) { NOTREACHED() << "Spotted primary-only multi-profile policy for non-primary user"; } } } return unlock_users; } void ChromeUserManagerImpl::SessionStarted() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SessionStarted(); content::NotificationService::current()->Notify( chrome::NOTIFICATION_SESSION_STARTED, content::Source<UserManager>(this), content::Details<const user_manager::User>(GetActiveUser())); } void ChromeUserManagerImpl::RemoveUserInternal( const std::string& user_email, user_manager::RemoveUserDelegate* delegate) { CrosSettings* cros_settings = CrosSettings::Get(); const base::Closure& callback = base::Bind(&ChromeUserManagerImpl::RemoveUserInternal, weak_factory_.GetWeakPtr(), user_email, delegate); // Ensure the value of owner email has been fetched. if (CrosSettingsProvider::TRUSTED != cros_settings->PrepareTrustedValues(callback)) { // Value of owner email is not fetched yet. RemoveUserInternal will be // called again after fetch completion. return; } std::string owner; cros_settings->GetString(kDeviceOwner, &owner); if (user_email == owner) { // Owner is not allowed to be removed from the device. return; } RemoveNonOwnerUserInternal(user_email, delegate); } void ChromeUserManagerImpl::SaveUserOAuthStatus( const std::string& user_id, user_manager::User::OAuthTokenStatus oauth_token_status) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SaveUserOAuthStatus(user_id, oauth_token_status); GetUserFlow(user_id)->HandleOAuthTokenStatusChange(oauth_token_status); } void ChromeUserManagerImpl::SaveUserDisplayName( const std::string& user_id, const base::string16& display_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SaveUserDisplayName(user_id, display_name); // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. if (!IsUserNonCryptohomeDataEphemeral(user_id)) supervised_user_manager_->UpdateManagerName(user_id, display_name); } void ChromeUserManagerImpl::StopPolicyObserverForTesting() { avatar_policy_observer_.reset(); wallpaper_policy_observer_.reset(); } void ChromeUserManagerImpl::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED: if (!device_local_account_policy_service_) { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part() ->browser_policy_connector_chromeos(); device_local_account_policy_service_ = connector->GetDeviceLocalAccountPolicyService(); if (device_local_account_policy_service_) device_local_account_policy_service_->AddObserver(this); } RetrieveTrustedDevicePolicies(); UpdateOwnership(); break; case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: { Profile* profile = content::Details<Profile>(details).ptr(); if (IsUserLoggedIn() && !IsLoggedInAsGuest() && !IsLoggedInAsKioskApp()) { if (IsLoggedInAsSupervisedUser()) SupervisedUserPasswordServiceFactory::GetForProfile(profile); if (IsLoggedInAsRegularUser()) ManagerPasswordServiceFactory::GetForProfile(profile); if (!profile->IsOffTheRecord()) { AuthSyncObserver* sync_observer = AuthSyncObserverFactory::GetInstance()->GetForProfile(profile); sync_observer->StartObserving(); multi_profile_user_controller_->StartObserving(profile); } } break; } case chrome::NOTIFICATION_PROFILE_CREATED: { Profile* profile = content::Source<Profile>(source).ptr(); user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile); if (user != NULL) user->set_profile_is_created(); // If there is pending user switch, do it now. if (!GetPendingUserSwitchID().empty()) { // Call SwitchActiveUser async because otherwise it may cause // ProfileManager::GetProfile before the profile gets registered // in ProfileManager. It happens in case of sync profile load when // NOTIFICATION_PROFILE_CREATED is called synchronously. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ChromeUserManagerImpl::SwitchActiveUser, weak_factory_.GetWeakPtr(), GetPendingUserSwitchID())); SetPendingUserSwitchID(std::string()); } break; } default: NOTREACHED(); } } void ChromeUserManagerImpl::OnExternalDataSet(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)->OnExternalDataSet(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicySet(policy, user_id); else NOTREACHED(); } void ChromeUserManagerImpl::OnExternalDataCleared(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)->OnExternalDataCleared(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyCleared(policy, user_id); else NOTREACHED(); } void ChromeUserManagerImpl::OnExternalDataFetched( const std::string& policy, const std::string& user_id, scoped_ptr<std::string> data) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)->OnExternalDataFetched(policy, data.Pass()); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyFetched(policy, user_id, data.Pass()); else NOTREACHED(); } void ChromeUserManagerImpl::OnPolicyUpdated(const std::string& user_id) { const user_manager::User* user = FindUser(user_id); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) return; UpdatePublicAccountDisplayName(user_id); } void ChromeUserManagerImpl::OnDeviceLocalAccountsChanged() { // No action needed here, changes to the list of device-local accounts get // handled via the kAccountsPrefDeviceLocalAccounts device setting observer. } bool ChromeUserManagerImpl::CanCurrentUserLock() const { return ChromeUserManager::CanCurrentUserLock() && GetCurrentUserFlow()->CanLockScreen(); } bool ChromeUserManagerImpl::IsUserNonCryptohomeDataEphemeral( const std::string& user_id) const { // Data belonging to the obsolete public accounts whose data has not been // removed yet is not ephemeral. bool is_obsolete_public_account = IsPublicAccountMarkedForRemoval(user_id); return !is_obsolete_public_account && ChromeUserManager::IsUserNonCryptohomeDataEphemeral(user_id); } bool ChromeUserManagerImpl::AreEphemeralUsersEnabled() const { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); return GetEphemeralUsersEnabled() && (connector->IsEnterpriseManaged() || !GetOwnerEmail().empty()); } const std::string& ChromeUserManagerImpl::GetApplicationLocale() const { return g_browser_process->GetApplicationLocale(); } PrefService* ChromeUserManagerImpl::GetLocalState() const { return g_browser_process ? g_browser_process->local_state() : NULL; } void ChromeUserManagerImpl::HandleUserOAuthTokenStatusChange( const std::string& user_id, user_manager::User::OAuthTokenStatus status) const { GetUserFlow(user_id)->HandleOAuthTokenStatusChange(status); } bool ChromeUserManagerImpl::IsEnterpriseManaged() const { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); return connector->IsEnterpriseManaged(); } void ChromeUserManagerImpl::LoadPublicAccounts( std::set<std::string>* public_sessions_set) { const base::ListValue* prefs_public_sessions = GetLocalState()->GetList(kPublicAccounts); std::vector<std::string> public_sessions; ParseUserList(*prefs_public_sessions, std::set<std::string>(), &public_sessions, public_sessions_set); for (std::vector<std::string>::const_iterator it = public_sessions.begin(); it != public_sessions.end(); ++it) { users_.push_back(user_manager::User::CreatePublicAccountUser(*it)); UpdatePublicAccountDisplayName(*it); } } void ChromeUserManagerImpl::PerformPreUserListLoadingActions() { // Clean up user list first. All code down the path should be synchronous, // so that local state after transaction rollback is in consistent state. // This process also should not trigger EnsureUsersLoaded again. if (supervised_user_manager_->HasFailedUserCreationTransaction()) supervised_user_manager_->RollbackUserCreationTransaction(); } void ChromeUserManagerImpl::PerformPostUserListLoadingActions() { for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.end(); ui != ue; ++ui) { GetUserImageManager((*ui)->email())->LoadUserImage(); } } void ChromeUserManagerImpl::PerformPostUserLoggedInActions( bool browser_restart) { // Initialize the session length limiter and start it only if // session limit is defined by the policy. session_length_limiter_.reset( new SessionLengthLimiter(NULL, browser_restart)); } bool ChromeUserManagerImpl::IsDemoApp(const std::string& user_id) const { return DemoAppLauncher::IsDemoAppSession(user_id); } bool ChromeUserManagerImpl::IsKioskApp(const std::string& user_id) const { policy::DeviceLocalAccount::Type device_local_account_type; return policy::IsDeviceLocalAccountUser(user_id, &device_local_account_type) && device_local_account_type == policy::DeviceLocalAccount::TYPE_KIOSK_APP; } bool ChromeUserManagerImpl::IsPublicAccountMarkedForRemoval( const std::string& user_id) const { return user_id == GetLocalState()->GetString(kPublicAccountPendingDataRemoval); } void ChromeUserManagerImpl::RetrieveTrustedDevicePolicies() { // Local state may not be initialized in unit_tests. if (!GetLocalState()) return; SetEphemeralUsersEnabled(false); SetOwnerEmail(std::string()); // Schedule a callback if device policy has not yet been verified. if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues( base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies, weak_factory_.GetWeakPtr()))) { return; } bool ephemeral_users_enabled = false; cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled, &ephemeral_users_enabled); SetEphemeralUsersEnabled(ephemeral_users_enabled); std::string owner_email; cros_settings_->GetString(kDeviceOwner, &owner_email); SetOwnerEmail(owner_email); EnsureUsersLoaded(); bool changed = UpdateAndCleanUpPublicAccounts( policy::GetDeviceLocalAccounts(cros_settings_)); // If ephemeral users are enabled and we are on the login screen, take this // opportunity to clean up by removing all regular users except the owner. if (GetEphemeralUsersEnabled() && !IsUserLoggedIn()) { ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); prefs_users_update->Clear(); for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();) { const std::string user_email = (*it)->email(); if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR && user_email != GetOwnerEmail()) { RemoveNonCryptohomeData(user_email); DeleteUser(*it); it = users_.erase(it); changed = true; } else { if ((*it)->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) prefs_users_update->Append(new base::StringValue(user_email)); ++it; } } } if (changed) NotifyUserListChanged(); } void ChromeUserManagerImpl::GuestUserLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::GuestUserLoggedIn(); // TODO(nkostylev): Add support for passing guest session cryptohome // mount point. Legacy (--login-profile) value will be used for now. // http://crosbug.com/230859 active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), user_manager::User::USER_IMAGE_INVALID, false); // Initializes wallpaper after active_user_ is set. WallpaperManager::Get()->SetUserWallpaperNow(chromeos::login::kGuestUserName); } void ChromeUserManagerImpl::RegularUserLoggedIn(const std::string& user_id) { ChromeUserManager::RegularUserLoggedIn(user_id); if (IsCurrentUserNew()) WallpaperManager::Get()->SetUserWallpaperNow(user_id); GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); // Make sure that new data is persisted to Local State. GetLocalState()->CommitPendingWrite(); } void ChromeUserManagerImpl::RegularUserLoggedInAsEphemeral( const std::string& user_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::RegularUserLoggedInAsEphemeral(user_id); GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); WallpaperManager::Get()->SetUserWallpaperNow(user_id); } void ChromeUserManagerImpl::SupervisedUserLoggedIn(const std::string& user_id) { // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn(). // Remove the user from the user list. active_user_ = RemoveRegularOrSupervisedUserFromList(user_id); // If the user was not found on the user list, create a new user. if (!GetActiveUser()) { SetIsCurrentUserNew(true); active_user_ = user_manager::User::CreateSupervisedUser(user_id); // Leaving OAuth token status at the default state = unknown. WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { if (supervised_user_manager_->CheckForFirstRun(user_id)) { SetIsCurrentUserNew(true); WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { SetIsCurrentUserNew(false); } } // Add the user to the front of the user list. ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); prefs_users_update->Insert(0, new base::StringValue(user_id)); users_.insert(users_.begin(), active_user_); // Now that user is in the list, save display name. if (IsCurrentUserNew()) { SaveUserDisplayName(GetActiveUser()->email(), GetActiveUser()->GetDisplayName()); } GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); // Make sure that new data is persisted to Local State. GetLocalState()->CommitPendingWrite(); } void ChromeUserManagerImpl::PublicAccountUserLoggedIn( user_manager::User* user) { SetIsCurrentUserNew(true); active_user_ = user; // The UserImageManager chooses a random avatar picture when a user logs in // for the first time. Tell the UserImageManager that this user is not new to // prevent the avatar from getting changed. GetUserImageManager(user->email())->UserLoggedIn(false, true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); } void ChromeUserManagerImpl::KioskAppLoggedIn(const std::string& app_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); policy::DeviceLocalAccount::Type device_local_account_type; DCHECK(policy::IsDeviceLocalAccountUser(app_id, &device_local_account_type)); DCHECK_EQ(policy::DeviceLocalAccount::TYPE_KIOSK_APP, device_local_account_type); active_user_ = user_manager::User::CreateKioskAppUser(app_id); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), user_manager::User::USER_IMAGE_INVALID, false); WallpaperManager::Get()->SetUserWallpaperNow(app_id); // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like // the kiosk_app_id in these objects, removing the need to re-parse the // device-local account list here to extract the kiosk_app_id. const std::vector<policy::DeviceLocalAccount> device_local_accounts = policy::GetDeviceLocalAccounts(cros_settings_); const policy::DeviceLocalAccount* account = NULL; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { if (it->user_id == app_id) { account = &*it; break; } } std::string kiosk_app_id; if (account) { kiosk_app_id = account->kiosk_app_id; } else { LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id; NOTREACHED(); } CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id); // Disable window animation since kiosk app runs in a single full screen // window and window animation causes start-up janks. command_line->AppendSwitch(wm::switches::kWindowAnimationsDisabled); } void ChromeUserManagerImpl::DemoAccountLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); active_user_ = user_manager::User::CreateKioskAppUser(DemoAppLauncher::kDemoUserName); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), user_manager::User::USER_IMAGE_INVALID, false); WallpaperManager::Get()->SetUserWallpaperNow(DemoAppLauncher::kDemoUserName); CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); command_line->AppendSwitchASCII(::switches::kAppId, DemoAppLauncher::kDemoAppId); // Disable window animation since the demo app runs in a single full screen // window and window animation causes start-up janks. CommandLine::ForCurrentProcess()->AppendSwitch( wm::switches::kWindowAnimationsDisabled); } void ChromeUserManagerImpl::RetailModeUserLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); SetIsCurrentUserNew(true); active_user_ = user_manager::User::CreateRetailModeUser(); GetUserImageManager(chromeos::login::kRetailModeUserName) ->UserLoggedIn(IsCurrentUserNew(), true); WallpaperManager::Get()->SetUserWallpaperNow( chromeos::login::kRetailModeUserName); } void ChromeUserManagerImpl::NotifyOnLogin() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); UserSessionManager::OverrideHomedir(); UpdateNumberOfUsers(); ChromeUserManager::NotifyOnLogin(); // TODO(nkostylev): Deprecate this notification in favor of // ActiveUserChanged() observer call. content::NotificationService::current()->Notify( chrome::NOTIFICATION_LOGIN_USER_CHANGED, content::Source<UserManager>(this), content::Details<const user_manager::User>(GetActiveUser())); UserSessionManager::GetInstance()->PerformPostUserLoggedInActions(); } void ChromeUserManagerImpl::UpdateOwnership() { bool is_owner = DeviceSettingsService::Get()->HasPrivateOwnerKey(); VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner"); SetCurrentUserIsOwner(is_owner); } void ChromeUserManagerImpl::RemoveNonCryptohomeData( const std::string& user_id) { ChromeUserManager::RemoveNonCryptohomeData(user_id); WallpaperManager::Get()->RemoveUserWallpaperInfo(user_id); GetUserImageManager(user_id)->DeleteUserImage(); supervised_user_manager_->RemoveNonCryptohomeData(user_id); multi_profile_user_controller_->RemoveCachedValues(user_id); } void ChromeUserManagerImpl::CleanUpPublicAccountNonCryptohomeDataPendingRemoval() { PrefService* local_state = GetLocalState(); const std::string public_account_pending_data_removal = local_state->GetString(kPublicAccountPendingDataRemoval); if (public_account_pending_data_removal.empty() || (IsUserLoggedIn() && public_account_pending_data_removal == GetActiveUser()->email())) { return; } RemoveNonCryptohomeData(public_account_pending_data_removal); local_state->ClearPref(kPublicAccountPendingDataRemoval); } void ChromeUserManagerImpl::CleanUpPublicAccountNonCryptohomeData( const std::vector<std::string>& old_public_accounts) { std::set<std::string> users; for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) users.insert((*it)->email()); // If the user is logged into a public account that has been removed from the // user list, mark the account's data as pending removal after logout. if (IsLoggedInAsPublicAccount()) { const std::string active_user_id = GetActiveUser()->email(); if (users.find(active_user_id) == users.end()) { GetLocalState()->SetString(kPublicAccountPendingDataRemoval, active_user_id); users.insert(active_user_id); } } // Remove the data belonging to any other public accounts that are no longer // found on the user list. for (std::vector<std::string>::const_iterator it = old_public_accounts.begin(); it != old_public_accounts.end(); ++it) { if (users.find(*it) == users.end()) RemoveNonCryptohomeData(*it); } } bool ChromeUserManagerImpl::UpdateAndCleanUpPublicAccounts( const std::vector<policy::DeviceLocalAccount>& device_local_accounts) { // Try to remove any public account data marked as pending removal. CleanUpPublicAccountNonCryptohomeDataPendingRemoval(); // Get the current list of public accounts. std::vector<std::string> old_public_accounts; for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) old_public_accounts.push_back((*it)->email()); } // Get the new list of public accounts from policy. std::vector<std::string> new_public_accounts; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the // standard login framework: http://crbug.com/234694 if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) new_public_accounts.push_back(it->user_id); } // If the list of public accounts has not changed, return. if (new_public_accounts.size() == old_public_accounts.size()) { bool changed = false; for (size_t i = 0; i < new_public_accounts.size(); ++i) { if (new_public_accounts[i] != old_public_accounts[i]) { changed = true; break; } } if (!changed) return false; } // Persist the new list of public accounts in a pref. ListPrefUpdate prefs_public_accounts_update(GetLocalState(), kPublicAccounts); prefs_public_accounts_update->Clear(); for (std::vector<std::string>::const_iterator it = new_public_accounts.begin(); it != new_public_accounts.end(); ++it) { prefs_public_accounts_update->AppendString(*it); } // Remove the old public accounts from the user list. for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();) { if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) { if (*it != GetLoggedInUser()) DeleteUser(*it); it = users_.erase(it); } else { ++it; } } // Add the new public accounts to the front of the user list. for (std::vector<std::string>::const_reverse_iterator it = new_public_accounts.rbegin(); it != new_public_accounts.rend(); ++it) { if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email()) users_.insert(users_.begin(), GetLoggedInUser()); else users_.insert(users_.begin(), user_manager::User::CreatePublicAccountUser(*it)); UpdatePublicAccountDisplayName(*it); } for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.begin() + new_public_accounts.size(); ui != ue; ++ui) { GetUserImageManager((*ui)->email())->LoadUserImage(); } // Remove data belonging to public accounts that are no longer found on the // user list. CleanUpPublicAccountNonCryptohomeData(old_public_accounts); return true; } void ChromeUserManagerImpl::UpdatePublicAccountDisplayName( const std::string& user_id) { std::string display_name; if (device_local_account_policy_service_) { policy::DeviceLocalAccountPolicyBroker* broker = device_local_account_policy_service_->GetBrokerForUser(user_id); if (broker) display_name = broker->GetDisplayName(); } // Set or clear the display name. SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name)); } UserFlow* ChromeUserManagerImpl::GetCurrentUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!IsUserLoggedIn()) return GetDefaultUserFlow(); return GetUserFlow(GetLoggedInUser()->email()); } UserFlow* ChromeUserManagerImpl::GetUserFlow(const std::string& user_id) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::const_iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) return it->second; return GetDefaultUserFlow(); } void ChromeUserManagerImpl::SetUserFlow(const std::string& user_id, UserFlow* flow) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ResetUserFlow(user_id); specific_flows_[user_id] = flow; } void ChromeUserManagerImpl::ResetUserFlow(const std::string& user_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) { delete it->second; specific_flows_.erase(it); } } bool ChromeUserManagerImpl::AreSupervisedUsersAllowed() const { bool supervised_users_allowed = false; cros_settings_->GetBoolean(kAccountsPrefSupervisedUsersEnabled, &supervised_users_allowed); return supervised_users_allowed; } UserFlow* ChromeUserManagerImpl::GetDefaultUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!default_flow_.get()) default_flow_.reset(new DefaultUserFlow()); return default_flow_.get(); } void ChromeUserManagerImpl::NotifyUserListChanged() { content::NotificationService::current()->Notify( chrome::NOTIFICATION_USER_LIST_CHANGED, content::Source<UserManager>(this), content::NotificationService::NoDetails()); } void ChromeUserManagerImpl::NotifyUserAddedToSession( const user_manager::User* added_user, bool user_switch_pending) { if (user_switch_pending) SetPendingUserSwitchID(added_user->email()); UpdateNumberOfUsers(); ChromeUserManager::NotifyUserAddedToSession(added_user, user_switch_pending); } void ChromeUserManagerImpl::OnUserNotAllowed(const std::string& user_email) { LOG(ERROR) << "Shutdown session because a user is not allowed to be in the " "current session"; chromeos::ShowMultiprofilesSessionAbortedDialog(user_email); } void ChromeUserManagerImpl::UpdateNumberOfUsers() { size_t users = GetLoggedInUsers().size(); if (users) { // Write the user number as UMA stat when a multi user session is possible. if ((users + GetUsersAdmittedForMultiProfile().size()) > 1) ash::MultiProfileUMA::RecordUserCount(users); } base::debug::SetCrashKeyValue( crash_keys::kNumberOfUsers, base::StringPrintf("%" PRIuS, GetLoggedInUsers().size())); } } // namespace chromeos
Java
/* * pointcloud_publisher_node.cpp * * Created on: Aug 19, 2021 * Author: Edo Jelavic * Institute: ETH Zurich, Robotic Systems Lab */ #include <pcl_conversions/pcl_conversions.h> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include "grid_map_pcl/helpers.hpp" namespace gm = ::grid_map::grid_map_pcl; using Point = ::pcl::PointXYZ; using PointCloud = ::pcl::PointCloud<Point>; void publishCloud(const std::string& filename, const ros::Publisher& pub, const std::string& frame) { PointCloud::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); cloud = gm::loadPointcloudFromPcd(filename); cloud->header.frame_id = frame; sensor_msgs::PointCloud2 msg; pcl::toROSMsg(*cloud, msg); ROS_INFO_STREAM("Publishing loaded cloud, number of points: " << cloud->points.size()); msg.header.stamp = ros::Time::now(); pub.publish(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "point_cloud_pub_node"); ros::NodeHandle nh("~"); const std::string pathToCloud = gm::getPcdFilePath(nh); const std::string cloudFrame = nh.param<std::string>("cloud_frame", ""); // publish cloud ros::Publisher cloudPub = nh.advertise<sensor_msgs::PointCloud2>("raw_pointcloud", 1, true); publishCloud(pathToCloud, cloudPub, cloudFrame); // run ros::spin(); return EXIT_SUCCESS; }
Java
// 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 CHROME_BROWSER_METRICS_CHROMEOS_METRICS_PROVIDER_H_ #define CHROME_BROWSER_METRICS_CHROMEOS_METRICS_PROVIDER_H_ #include "base/memory/weak_ptr.h" #include "chrome/browser/metrics/perf_provider_chromeos.h" #include "components/metrics/metrics_provider.h" namespace device { class BluetoothAdapter; } namespace metrics { class ChromeUserMetricsExtension; } class PrefRegistrySimple; class PrefService; // Performs ChromeOS specific metrics logging. class ChromeOSMetricsProvider : public metrics::MetricsProvider { public: ChromeOSMetricsProvider(); ~ChromeOSMetricsProvider() override; static void RegisterPrefs(PrefRegistrySimple* registry); // Records a crash. static void LogCrash(const std::string& crash_type); // Loads hardware class information. When this task is complete, |callback| // is run. void InitTaskGetHardwareClass(const base::Closure& callback); // metrics::MetricsProvider: void OnDidCreateMetricsLog() override; void ProvideSystemProfileMetrics( metrics::SystemProfileProto* system_profile_proto) override; void ProvideStabilityMetrics( metrics::SystemProfileProto* system_profile_proto) override; void ProvideGeneralMetrics( metrics::ChromeUserMetricsExtension* uma_proto) override; private: // Called on the FILE thread to load hardware class information. void InitTaskGetHardwareClassOnFileThread(); // Update the number of users logged into a multi-profile session. // If the number of users change while the log is open, the call invalidates // the user count value. void UpdateMultiProfileUserCount( metrics::SystemProfileProto* system_profile_proto); // Sets the Bluetooth Adapter instance used for the WriteBluetoothProto() // call. void SetBluetoothAdapter(scoped_refptr<device::BluetoothAdapter> adapter); // Writes info about paired Bluetooth devices on this system. void WriteBluetoothProto(metrics::SystemProfileProto* system_profile_proto); metrics::PerfProvider perf_provider_; // Bluetooth Adapter instance for collecting information about paired devices. scoped_refptr<device::BluetoothAdapter> adapter_; // Whether the user count was registered at the last log initialization. bool registered_user_count_at_log_initialization_; // The user count at the time that a log was last initialized. Contains a // valid value only if |registered_user_count_at_log_initialization_| is // true. uint64 user_count_at_log_initialization_; // Hardware class (e.g., hardware qualification ID). This class identifies // the configured system components such as CPU, WiFi adapter, etc. std::string hardware_class_; base::WeakPtrFactory<ChromeOSMetricsProvider> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ChromeOSMetricsProvider); }; #endif // CHROME_BROWSER_METRICS_CHROMEOS_METRICS_PROVIDER_H_
Java
// 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. #ifndef MEDIA_GPU_VAAPI_VAAPI_JPEG_DECODER_H_ #define MEDIA_GPU_VAAPI_VAAPI_JPEG_DECODER_H_ #include <stdint.h> #include <memory> #include "base/macros.h" #include "media/gpu/vaapi/vaapi_image_decoder.h" namespace media { namespace fuzzing { class VaapiJpegDecoderWrapper; } // namespace fuzzing struct JpegFrameHeader; struct JpegParseResult; class ScopedVAImage; // Returns the internal format required for a JPEG image given its parsed // |frame_header|. If the image's subsampling format is not one of 4:2:0, 4:2:2, // or 4:4:4, returns kInvalidVaRtFormat. unsigned int VaSurfaceFormatForJpeg(const JpegFrameHeader& frame_header); class VaapiJpegDecoder : public VaapiImageDecoder { public: VaapiJpegDecoder(); VaapiJpegDecoder(const VaapiJpegDecoder&) = delete; VaapiJpegDecoder& operator=(const VaapiJpegDecoder&) = delete; ~VaapiJpegDecoder() override; // VaapiImageDecoder implementation. gpu::ImageDecodeAcceleratorType GetType() const override; SkYUVColorSpace GetYUVColorSpace() const override; // Get the decoded data from the last Decode() call as a ScopedVAImage. The // VAImage's format will be either |preferred_image_fourcc| if the conversion // from the internal format is supported or a fallback FOURCC (see // VaapiWrapper::GetJpegDecodeSuitableImageFourCC() for details). Returns // nullptr on failure and sets *|status| to the reason for failure. std::unique_ptr<ScopedVAImage> GetImage(uint32_t preferred_image_fourcc, VaapiImageDecodeStatus* status); private: friend class fuzzing::VaapiJpegDecoderWrapper; // VaapiImageDecoder implementation. VaapiImageDecodeStatus AllocateVASurfaceAndSubmitVABuffers( base::span<const uint8_t> encoded_image) override; // AllocateVASurfaceAndSubmitVABuffers() is implemented by calling the // following methods. They are here so that a fuzzer can inject (almost) // arbitrary data into libva by skipping the parsing and image support checks // in AllocateVASurfaceAndSubmitVABuffers(). bool MaybeCreateSurface(unsigned int picture_va_rt_format, const gfx::Size& new_coded_size, const gfx::Size& new_visible_size); bool SubmitBuffers(const JpegParseResult& parse_result); }; } // namespace media #endif // MEDIA_GPU_VAAPI_VAAPI_JPEG_DECODER_H_
Java
using System; using Inbox2.Framework; namespace Inbox2.Core.Configuration { public static class CloudApi { public static string ApiBaseUrl { get { return String.Format("http://api{0}.inbox2.com/", String.IsNullOrEmpty(CommandLine.Current.Environment) ? String.Empty : "." + CommandLine.Current.Environment); } } public static string ApplicationKey { get { return "ZABhADQAMgA4AGQAYQAyAA=="; } } public static string AccessToken { get { return SettingsManager.ClientSettings.AppConfiguration.AuthToken; } } } }
Java
// 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. #include "content/browser/payments/payment_app_info_fetcher.h" #include <limits> #include <utility> #include "base/base64.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "components/payments/content/icon/icon_size.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/manifest_icon_downloader.h" #include "content/public/browser/page.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/manifest/manifest_icon_selector.h" #include "third_party/blink/public/common/manifest/manifest_util.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" #include "third_party/blink/public/mojom/manifest/manifest.mojom.h" #include "ui/gfx/codec/png_codec.h" #include "url/origin.h" namespace content { PaymentAppInfoFetcher::PaymentAppInfo::PaymentAppInfo() {} PaymentAppInfoFetcher::PaymentAppInfo::~PaymentAppInfo() {} void PaymentAppInfoFetcher::Start( const GURL& context_url, scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, PaymentAppInfoFetchCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::unique_ptr<std::vector<GlobalRenderFrameHostId>> frame_routing_ids = service_worker_context->GetWindowClientFrameRoutingIds( blink::StorageKey(url::Origin::Create(context_url))); SelfDeleteFetcher* fetcher = new SelfDeleteFetcher(std::move(callback)); fetcher->Start(context_url, std::move(frame_routing_ids)); } PaymentAppInfoFetcher::WebContentsHelper::WebContentsHelper( WebContents* web_contents) : WebContentsObserver(web_contents) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } PaymentAppInfoFetcher::WebContentsHelper::~WebContentsHelper() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } PaymentAppInfoFetcher::SelfDeleteFetcher::SelfDeleteFetcher( PaymentAppInfoFetchCallback callback) : fetched_payment_app_info_(std::make_unique<PaymentAppInfo>()), callback_(std::move(callback)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } PaymentAppInfoFetcher::SelfDeleteFetcher::~SelfDeleteFetcher() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } void PaymentAppInfoFetcher::SelfDeleteFetcher::Start( const GURL& context_url, const std::unique_ptr<std::vector<GlobalRenderFrameHostId>>& frame_routing_ids) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (frame_routing_ids->empty()) { // Cannot print this error to the developer console, because the appropriate // developer console has not been found. LOG(ERROR) << "Unable to find the top level web content for retrieving the web " "app manifest of a payment handler for \"" << context_url << "\"."; RunCallbackAndDestroy(); return; } for (const auto& frame : *frame_routing_ids) { // Find out the render frame host registering the payment app. Although a // service worker can manage instruments, the first instrument must be set // on a page that has a link to a web app manifest, so it can be fetched // here. RenderFrameHostImpl* render_frame_host = RenderFrameHostImpl::FromID(frame.child_id, frame.frame_routing_id); if (!render_frame_host || context_url.spec().compare( render_frame_host->GetLastCommittedURL().spec()) != 0) { continue; } // Get the main frame since web app manifest is only available in the main // frame's document by definition. The main frame's document must come from // the same origin. RenderFrameHostImpl* top_level_render_frame_host = render_frame_host; while (top_level_render_frame_host->GetParent() != nullptr) { top_level_render_frame_host = top_level_render_frame_host->GetParent(); } WebContentsImpl* top_level_web_content = static_cast<WebContentsImpl*>( WebContents::FromRenderFrameHost(top_level_render_frame_host)); if (!top_level_web_content) { top_level_render_frame_host->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to find the web page for \"" + context_url.spec() + "\" to fetch payment handler manifest (for name and icon)."); continue; } if (top_level_web_content->IsHidden()) { top_level_render_frame_host->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to fetch payment handler manifest (for name and icon) for " "\"" + context_url.spec() + "\" from a hidden top level web page \"" + top_level_web_content->GetLastCommittedURL().spec() + "\"."); continue; } if (!url::IsSameOriginWith(context_url, top_level_web_content->GetLastCommittedURL())) { top_level_render_frame_host->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to fetch payment handler manifest (for name and icon) for " "\"" + context_url.spec() + "\" from a cross-origin top level web page \"" + top_level_web_content->GetLastCommittedURL().spec() + "\"."); continue; } web_contents_helper_ = std::make_unique<WebContentsHelper>(top_level_web_content); top_level_render_frame_host->GetPage().GetManifest( base::BindOnce(&PaymentAppInfoFetcher::SelfDeleteFetcher:: FetchPaymentAppManifestCallback, weak_ptr_factory_.GetWeakPtr())); return; } // Cannot print this error to the developer console, because the appropriate // developer console has not been found. LOG(ERROR) << "Unable to find the top level web content for retrieving the web " "app manifest of a payment handler for \"" << context_url << "\"."; RunCallbackAndDestroy(); } void PaymentAppInfoFetcher::SelfDeleteFetcher::RunCallbackAndDestroy() { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback_), std::move(fetched_payment_app_info_))); delete this; } void PaymentAppInfoFetcher::SelfDeleteFetcher::FetchPaymentAppManifestCallback( const GURL& url, blink::mojom::ManifestPtr manifest) { DCHECK_CURRENTLY_ON(BrowserThread::UI); manifest_url_ = url; if (manifest_url_.is_empty()) { WarnIfPossible( "The page that installed the payment handler does not contain a web " "app manifest link: <link rel=\"manifest\" " "href=\"some-file-name-here\">. This manifest defines the payment " "handler's name and icon. User may not recognize this payment handler " "in UI, because it will be labeled only by its origin."); RunCallbackAndDestroy(); return; } if (blink::IsEmptyManifest(manifest)) { WarnIfPossible( "Unable to download a valid payment handler web app manifest from \"" + manifest_url_.spec() + "\". This manifest cannot be empty and must in JSON format. The " "manifest defines the payment handler's name and icon. User may not " "recognize this payment handler in UI, because it will be labeled only " "by its origin."); RunCallbackAndDestroy(); return; } fetched_payment_app_info_->prefer_related_applications = manifest->prefer_related_applications; for (const auto& related_application : manifest->related_applications) { fetched_payment_app_info_->related_applications.emplace_back( StoredRelatedApplication()); if (related_application.platform) { base::UTF16ToUTF8( related_application.platform->c_str(), related_application.platform->length(), &(fetched_payment_app_info_->related_applications.back().platform)); } if (related_application.id) { base::UTF16ToUTF8( related_application.id->c_str(), related_application.id->length(), &(fetched_payment_app_info_->related_applications.back().id)); } } if (!manifest->name) { WarnIfPossible("The payment handler's web app manifest \"" + manifest_url_.spec() + "\" does not contain a \"name\" field. User may not " "recognize this payment handler in UI, because it will be " "labeled only by its origin."); } else if (manifest->name->empty()) { WarnIfPossible( "The \"name\" field in the payment handler's web app manifest \"" + manifest_url_.spec() + "\" is empty. User may not recognize this payment handler in UI, " "because it will be labeled only by its origin."); } else { base::UTF16ToUTF8(manifest->name->c_str(), manifest->name->length(), &(fetched_payment_app_info_->name)); } if (manifest->icons.empty()) { WarnIfPossible( "Unable to download the payment handler's icon, because the web app " "manifest \"" + manifest_url_.spec() + "\" does not contain an \"icons\" field with a valid URL in \"src\" " "sub-field. User may not recognize this payment handler in UI."); RunCallbackAndDestroy(); return; } WebContents* web_contents = web_contents_helper_->web_contents(); if (!web_contents) { LOG(WARNING) << "Unable to download the payment handler's icon because no " "renderer was found, possibly because the page was closed " "or navigated away during installation. User may not " "recognize this payment handler in UI, because it will be " "labeled only by its name and origin."; RunCallbackAndDestroy(); return; } gfx::NativeView native_view = web_contents->GetNativeView(); icon_url_ = blink::ManifestIconSelector::FindBestMatchingIcon( manifest->icons, payments::IconSizeCalculator::IdealIconHeight(native_view), payments::IconSizeCalculator::MinimumIconHeight(), ManifestIconDownloader::kMaxWidthToHeightRatio, blink::mojom::ManifestImageResource_Purpose::ANY); if (!icon_url_.is_valid()) { WarnIfPossible( "No suitable payment handler icon found in the \"icons\" field defined " "in the web app manifest \"" + manifest_url_.spec() + "\". This is most likely due to unsupported MIME types in the " "\"icons\" field. User may not recognize this payment handler in UI."); RunCallbackAndDestroy(); return; } bool can_download = ManifestIconDownloader::Download( web_contents, icon_url_, payments::IconSizeCalculator::IdealIconHeight(native_view), payments::IconSizeCalculator::MinimumIconHeight(), /* maximum_icon_size_in_px= */ std::numeric_limits<int>::max(), base::BindOnce(&PaymentAppInfoFetcher::SelfDeleteFetcher::OnIconFetched, weak_ptr_factory_.GetWeakPtr()), false /* square_only */); // |can_download| is false only if web contents are null or the icon URL is // not valid. Both of these conditions are manually checked above, so // |can_download| should never be false. The manual checks above are necessary // to provide more detailed error messages. DCHECK(can_download); } void PaymentAppInfoFetcher::SelfDeleteFetcher::OnIconFetched( const SkBitmap& icon) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (icon.drawsNothing()) { WarnIfPossible("Unable to download a valid payment handler icon from \"" + icon_url_.spec() + "\", which is defined in the web app manifest \"" + manifest_url_.spec() + "\". User may not recognize this payment handler in UI."); RunCallbackAndDestroy(); return; } std::vector<unsigned char> bitmap_data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap(icon, false, &bitmap_data); DCHECK(success); base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(&bitmap_data[0]), bitmap_data.size()), &(fetched_payment_app_info_->icon)); RunCallbackAndDestroy(); } void PaymentAppInfoFetcher::SelfDeleteFetcher::WarnIfPossible( const std::string& message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(web_contents_helper_); if (web_contents_helper_->web_contents()) { web_contents_helper_->web_contents()->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kWarning, message); } else { LOG(WARNING) << message; } } } // namespace content
Java
// 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 NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_STREAM_SEQUENCER_BUFFER_PEER_H_ #define NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_STREAM_SEQUENCER_BUFFER_PEER_H_ #include "net/third_party/quic/core/quic_stream_sequencer_buffer.h" namespace quic { namespace test { class QuicStreamSequencerBufferPeer { public: explicit QuicStreamSequencerBufferPeer(QuicStreamSequencerBuffer* buffer); QuicStreamSequencerBufferPeer(const QuicStreamSequencerBufferPeer&) = delete; QuicStreamSequencerBufferPeer& operator=( const QuicStreamSequencerBufferPeer&) = delete; // Read from this buffer_ into the given destination buffer_ up to the // size of the destination. Returns the number of bytes read. Reading from // an empty buffer_->returns 0. size_t Read(char* dest_buffer, size_t size); // If buffer is empty, the blocks_ array must be empty, which means all // blocks are deallocated. bool CheckEmptyInvariants(); bool IsBlockArrayEmpty(); bool CheckInitialState(); bool CheckBufferInvariants(); size_t GetInBlockOffset(QuicStreamOffset offset); QuicStreamSequencerBuffer::BufferBlock* GetBlock(size_t index); int IntervalSize(); size_t max_buffer_capacity(); size_t ReadableBytes(); void set_total_bytes_read(QuicStreamOffset total_bytes_read); void AddBytesReceived(QuicStreamOffset offset, QuicByteCount length); bool IsBufferAllocated(); size_t block_count(); const QuicIntervalSet<QuicStreamOffset>& bytes_received(); private: QuicStreamSequencerBuffer* buffer_; }; } // namespace test } // namespace quic #endif // NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_STREAM_SEQUENCER_BUFFER_PEER_H_
Java
// 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. /** * @fileoverview A command is an abstraction of an action a user can do in the * UI. * * When the focus changes in the document for each command a canExecute event * is dispatched on the active element. By listening to this event you can * enable and disable the command by setting the event.canExecute property. * * When a command is executed a command event is dispatched on the active * element. Note that you should stop the propagation after you have handled the * command if there might be other command listeners higher up in the DOM tree. */ cr.define('cr.ui', function() { /** * This is used to identify keyboard shortcuts. * @param {string} shortcut The text used to describe the keys for this * keyboard shortcut. * @constructor */ function KeyboardShortcut(shortcut) { var mods = {}; var ident = ''; shortcut.split('-').forEach(function(part) { var partLc = part.toLowerCase(); switch (partLc) { case 'alt': case 'ctrl': case 'meta': case 'shift': mods[partLc + 'Key'] = true; break; default: if (ident) throw Error('Invalid shortcut'); ident = part; } }); this.ident_ = ident; this.mods_ = mods; } KeyboardShortcut.prototype = { /** * Whether the keyboard shortcut object matches a keyboard event. * @param {!Event} e The keyboard event object. * @return {boolean} Whether we found a match or not. */ matchesEvent: function(e) { if (e.keyIdentifier == this.ident_) { // All keyboard modifiers needs to match. var mods = this.mods_; return ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].every(function(k) { return e[k] == !!mods[k]; }); } return false; } }; /** * Creates a new command element. * @constructor * @extends {HTMLElement} */ var Command = cr.ui.define('command'); Command.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the command. */ decorate: function() { CommandManager.init(this.ownerDocument); if (this.hasAttribute('shortcut')) this.shortcut = this.getAttribute('shortcut'); }, /** * Executes the command by dispatching a command event on the given element. * If |element| isn't given, the active element is used instead. * If the command is {@code disabled} this does nothing. * @param {HTMLElement=} opt_element Optional element to dispatch event on. */ execute: function(opt_element) { if (this.disabled) return; var doc = this.ownerDocument; if (doc.activeElement) { var e = new cr.Event('command', true, false); e.command = this; (opt_element || doc.activeElement).dispatchEvent(e); } }, /** * Call this when there have been changes that might change whether the * command can be executed or not. * @param {Node=} opt_node Node for which to actuate command state. */ canExecuteChange: function(opt_node) { dispatchCanExecuteEvent(this, opt_node || this.ownerDocument.activeElement); }, /** * The keyboard shortcut that triggers the command. This is a string * consisting of a keyIdentifier (as reported by WebKit in keydown) as * well as optional key modifiers joinded with a '-'. * * Multiple keyboard shortcuts can be provided by separating them by * whitespace. * * For example: * "F1" * "U+0008-Meta" for Apple command backspace. * "U+0041-Ctrl" for Control A * "U+007F U+0008-Meta" for Delete and Command Backspace * * @type {string} */ shortcut_: '', get shortcut() { return this.shortcut_; }, set shortcut(shortcut) { var oldShortcut = this.shortcut_; if (shortcut !== oldShortcut) { this.keyboardShortcuts_ = shortcut.split(/\s+/).map(function(shortcut) { return new KeyboardShortcut(shortcut); }); // Set this after the keyboardShortcuts_ since that might throw. this.shortcut_ = shortcut; cr.dispatchPropertyChange(this, 'shortcut', this.shortcut_, oldShortcut); } }, /** * Whether the event object matches the shortcut for this command. * @param {!Event} e The key event object. * @return {boolean} Whether it matched or not. */ matchesEvent: function(e) { if (!this.keyboardShortcuts_) return false; return this.keyboardShortcuts_.some(function(keyboardShortcut) { return keyboardShortcut.matchesEvent(e); }); } }; /** * The label of the command. * @type {string} */ cr.defineProperty(Command, 'label', cr.PropertyKind.ATTR); /** * Whether the command is disabled or not. * @type {boolean} */ cr.defineProperty(Command, 'disabled', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is hidden or not. * @type {boolean} */ cr.defineProperty(Command, 'hidden', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is checked or not. * @type {boolean} */ cr.defineProperty(Command, 'checked', cr.PropertyKind.BOOL_ATTR); /** * Dispatches a canExecute event on the target. * @param {cr.ui.Command} command The command that we are testing for. * @param {Element} target The target element to dispatch the event on. */ function dispatchCanExecuteEvent(command, target) { var e = new CanExecuteEvent(command, true); target.dispatchEvent(e); command.disabled = !e.canExecute; } /** * The command managers for different documents. */ var commandManagers = {}; /** * Keeps track of the focused element and updates the commands when the focus * changes. * @param {!Document} doc The document that we are managing the commands for. * @constructor */ function CommandManager(doc) { doc.addEventListener('focus', this.handleFocus_.bind(this), true); // Make sure we add the listener to the bubbling phase so that elements can // prevent the command. doc.addEventListener('keydown', this.handleKeyDown_.bind(this), false); } /** * Initializes a command manager for the document as needed. * @param {!Document} doc The document to manage the commands for. */ CommandManager.init = function(doc) { var uid = cr.getUid(doc); if (!(uid in commandManagers)) { commandManagers[uid] = new CommandManager(doc); } }; CommandManager.prototype = { /** * Handles focus changes on the document. * @param {Event} e The focus event object. * @private */ handleFocus_: function(e) { var target = e.target; // Ignore focus on a menu button or command item if (target.menu || target.command) return; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); commands.forEach(function(command) { dispatchCanExecuteEvent(command, target); }); }, /** * Handles the keydown event and routes it to the right command. * @param {!Event} e The keydown event. */ handleKeyDown_: function(e) { var target = e.target; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); for (var i = 0, command; command = commands[i]; i++) { if (!command.disabled && command.matchesEvent(e)) { e.preventDefault(); // We do not want any other element to handle this. e.stopPropagation(); command.execute(); return; } } } }; /** * The event type used for canExecute events. * @param {!cr.ui.Command} command The command that we are evaluating. * @extends {Event} * @constructor * @class */ function CanExecuteEvent(command) { var e = command.ownerDocument.createEvent('Event'); e.initEvent('canExecute', true, false); e.__proto__ = CanExecuteEvent.prototype; e.command = command; return e; } CanExecuteEvent.prototype = { __proto__: Event.prototype, /** * The current command * @type {cr.ui.Command} */ command: null, /** * Whether the target can execute the command. Setting this also stops the * propagation. * @type {boolean} */ canExecute_: false, get canExecute() { return this.canExecute_; }, set canExecute(canExecute) { this.canExecute_ = !!canExecute; this.stopPropagation(); } }; // Export return { Command: Command, CanExecuteEvent: CanExecuteEvent }; });
Java
/** ****************************************************************************** * api-scanner - Scan for API imports from a packaged 360 game * ****************************************************************************** * Copyright 2015 x1nixmzeng. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "api_scanner_loader.h" namespace xe { namespace tools { DEFINE_string(target, "", "List of file to extract imports from"); int api_scanner_main(std::vector<std::wstring>& args) { // XXX we need gflags to split multiple flags into arrays for us if (args.size() == 2 || !FLAGS_target.empty()) { apiscanner_loader loader_; std::wstring target(cvars::target.empty() ? args[1] : xe::to_wstring(cvars::target)); std::wstring target_abs = xe::to_absolute_path(target); // XXX For each target? if (loader_.LoadTitleImports(target)) { for (const auto title : loader_.GetAllTitles()) { printf("%08x\n", title.title_id); for (const auto import : title.imports) { printf("\t%s\n", import.c_str()); } } } } return 0; } } // namespace tools } // namespace xe DEFINE_ENTRY_POINT(L"api-scanner", L"api-scanner --target=<target file>", xe::tools::api_scanner_main);
Java
// Copyright (c) 2011 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 COMPONENTS_ERROR_PAGE_COMMON_LOCALIZED_ERROR_H_ #define COMPONENTS_ERROR_PAGE_COMMON_LOCALIZED_ERROR_H_ #include <memory> #include <string> #include "base/values.h" #include "url/gurl.h" namespace base { class DictionaryValue; } namespace error_page { class LocalizedError { public: // Information about elements shown on the error page. struct PageState { PageState(); ~PageState(); PageState(const PageState& other) = delete; PageState(PageState&& other); PageState& operator=(PageState&& other); // Strings used within the error page HTML/JS. base::DictionaryValue strings; bool is_offline_error = false; bool reload_button_shown = false; bool download_button_shown = false; bool offline_content_feature_enabled = false; bool auto_fetch_allowed = false; }; LocalizedError() = delete; LocalizedError(const LocalizedError&) = delete; LocalizedError& operator=(const LocalizedError&) = delete; // Returns a |PageState| that describes the elements that should be shown on // on HTTP errors, like 404 or connection reset. static PageState GetPageState( int error_code, const std::string& error_domain, const GURL& failed_url, bool is_post, bool is_secure_dns_network_error, bool stale_copy_in_cache, bool can_show_network_diagnostics_dialog, bool is_incognito, bool offline_content_feature_enabled, bool auto_fetch_feature_enabled, bool is_kiosk_mode, // whether device is currently in single app (kiosk) // mode const std::string& locale, bool is_blocked_by_extension); // Returns a description of the encountered error. static std::u16string GetErrorDetails(const std::string& error_domain, int error_code, bool is_secure_dns_network_error, bool is_post); // Returns true if an error page exists for the specified parameters. static bool HasStrings(const std::string& error_domain, int error_code); }; } // namespace error_page #endif // COMPONENTS_ERROR_PAGE_COMMON_LOCALIZED_ERROR_H_
Java
using System.Linq.Expressions; using NHibernate.Metadata; namespace NHibernate.Linq.Expressions { public class EntityExpression : NHibernateExpression { private readonly string _alias; private readonly string _associationPath; private readonly IClassMetadata _metaData; private readonly Expression _expression; public string Alias { get { return _alias; } } public string AssociationPath { get { return _associationPath; } } public IClassMetadata MetaData { get { return _metaData; } } public Expression Expression { get { return _expression; } } public EntityExpression(string associationPath, string alias, System.Type type, IClassMetadata metaData, Expression expression) : base(IsRoot(expression) ? NHibernateExpressionType.RootEntity : NHibernateExpressionType.Entity, type) { _associationPath = associationPath; _alias = alias; _metaData = metaData; _expression = expression; } private static bool IsRoot(Expression expr) { if (expr == null) return true; if (!(expr is EntityExpression)) return true; return false; } public override string ToString() { return Alias; } public virtual string GetAliasedIdentifierPropertyName() { if ((NHibernateExpressionType)this.NodeType == NHibernateExpressionType.RootEntity) { return this.MetaData.IdentifierPropertyName; } return string.Format("{0}.{1}", this.Alias, this.MetaData.IdentifierPropertyName); } } }
Java
/* * Copyright (C) 2006 Alexey Proskuryakov ([email protected]) * Copyright (C) 2009 Google Inc. All rights reserved. * Copyright (C) 2011 Apple Inc. 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. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ #ifndef HTTPParsers_h #define HTTPParsers_h #include "platform/PlatformExport.h" #include "wtf/Allocator.h" #include "wtf/Forward.h" #include "wtf/HashSet.h" #include "wtf/Vector.h" #include "wtf/text/StringHash.h" namespace blink { typedef enum { ContentDispositionNone, ContentDispositionInline, ContentDispositionAttachment, ContentDispositionOther } ContentDispositionType; enum ContentTypeOptionsDisposition { ContentTypeOptionsNone, ContentTypeOptionsNosniff }; enum XFrameOptionsDisposition { XFrameOptionsInvalid, XFrameOptionsDeny, XFrameOptionsSameOrigin, XFrameOptionsAllowAll, XFrameOptionsConflict }; // Be sure to update the behavior of XSSAuditor::combineXSSProtectionHeaderAndCSP whenever you change this enum's content or ordering. enum ReflectedXSSDisposition { ReflectedXSSUnset = 0, AllowReflectedXSS, ReflectedXSSInvalid, FilterReflectedXSS, BlockReflectedXSS }; using CommaDelimitedHeaderSet = HashSet<String, CaseFoldingHash>; struct CacheControlHeader { DISALLOW_NEW(); bool parsed : 1; bool containsNoCache : 1; bool containsNoStore : 1; bool containsMustRevalidate : 1; double maxAge; double staleWhileRevalidate; CacheControlHeader() : parsed(false) , containsNoCache(false) , containsNoStore(false) , containsMustRevalidate(false) , maxAge(0.0) , staleWhileRevalidate(0.0) { } }; PLATFORM_EXPORT ContentDispositionType contentDispositionType(const String&); PLATFORM_EXPORT bool isValidHTTPHeaderValue(const String&); PLATFORM_EXPORT bool isValidHTTPFieldContentRFC7230(const String&); PLATFORM_EXPORT bool isValidHTTPToken(const String&); PLATFORM_EXPORT bool parseHTTPRefresh(const String& refresh, bool fromHttpEquivMeta, double& delay, String& url); PLATFORM_EXPORT double parseDate(const String&); // Given a Media Type (like "foo/bar; baz=gazonk" - usually from the // 'Content-Type' HTTP header), extract and return the "type/subtype" portion // ("foo/bar"). // Note: This function does not in any way check that the "type/subtype" pair // is well-formed. PLATFORM_EXPORT AtomicString extractMIMETypeFromMediaType(const AtomicString&); PLATFORM_EXPORT String extractCharsetFromMediaType(const String&); PLATFORM_EXPORT void findCharsetInMediaType(const String& mediaType, unsigned& charsetPos, unsigned& charsetLen, unsigned start = 0); PLATFORM_EXPORT ReflectedXSSDisposition parseXSSProtectionHeader(const String& header, String& failureReason, unsigned& failurePosition, String& reportURL); PLATFORM_EXPORT XFrameOptionsDisposition parseXFrameOptionsHeader(const String&); PLATFORM_EXPORT CacheControlHeader parseCacheControlDirectives(const AtomicString& cacheControlHeader, const AtomicString& pragmaHeader); PLATFORM_EXPORT void parseCommaDelimitedHeader(const String& headerValue, CommaDelimitedHeaderSet&); PLATFORM_EXPORT ContentTypeOptionsDisposition parseContentTypeOptionsHeader(const String& header); } // namespace blink #endif
Java
// Copyright 2011 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 x509 import ( "strings" "time" "unicode/utf8" ) type InvalidReason int const ( // NotAuthorizedToSign results when a certificate is signed by another // which isn't marked as a CA certificate. NotAuthorizedToSign InvalidReason = iota // Expired results when a certificate has expired, based on the time // given in the VerifyOptions. Expired // CANotAuthorizedForThisName results when an intermediate or root // certificate has a name constraint which doesn't include the name // being checked. CANotAuthorizedForThisName ) // CertificateInvalidError results when an odd error occurs. Users of this // library probably want to handle all these errors uniformly. type CertificateInvalidError struct { Cert *Certificate Reason InvalidReason } func (e CertificateInvalidError) Error() string { switch e.Reason { case NotAuthorizedToSign: return "x509: certificate is not authorized to sign other other certificates" case Expired: return "x509: certificate has expired or is not yet valid" case CANotAuthorizedForThisName: return "x509: a root or intermediate certificate is not authorized to sign in this domain" } return "x509: unknown error" } // HostnameError results when the set of authorized names doesn't match the // requested name. type HostnameError struct { Certificate *Certificate Host string } func (h HostnameError) Error() string { var valid string c := h.Certificate if len(c.DNSNames) > 0 { valid = strings.Join(c.DNSNames, ", ") } else { valid = c.Subject.CommonName } return "certificate is valid for " + valid + ", not " + h.Host } // UnknownAuthorityError results when the certificate issuer is unknown type UnknownAuthorityError struct { cert *Certificate } func (e UnknownAuthorityError) Error() string { return "x509: certificate signed by unknown authority" } // VerifyOptions contains parameters for Certificate.Verify. It's a structure // because other PKIX verification APIs have ended up needing many options. type VerifyOptions struct { DNSName string Intermediates *CertPool Roots *CertPool CurrentTime time.Time // if zero, the current time is used } const ( leafCertificate = iota intermediateCertificate rootCertificate ) // isValid performs validity checks on the c. func (c *Certificate) isValid(certType int, opts *VerifyOptions) error { now := opts.CurrentTime if now.IsZero() { now = time.Now() } if now.Before(c.NotBefore) || now.After(c.NotAfter) { return CertificateInvalidError{c, Expired} } if len(c.PermittedDNSDomains) > 0 { for _, domain := range c.PermittedDNSDomains { if opts.DNSName == domain || (strings.HasSuffix(opts.DNSName, domain) && len(opts.DNSName) >= 1+len(domain) && opts.DNSName[len(opts.DNSName)-len(domain)-1] == '.') { continue } return CertificateInvalidError{c, CANotAuthorizedForThisName} } } // KeyUsage status flags are ignored. From Engineering Security, Peter // Gutmann: A European government CA marked its signing certificates as // being valid for encryption only, but no-one noticed. Another // European CA marked its signature keys as not being valid for // signatures. A different CA marked its own trusted root certificate // as being invalid for certificate signing. Another national CA // distributed a certificate to be used to encrypt data for the // country’s tax authority that was marked as only being usable for // digital signatures but not for encryption. Yet another CA reversed // the order of the bit flags in the keyUsage due to confusion over // encoding endianness, essentially setting a random keyUsage in // certificates that it issued. Another CA created a self-invalidating // certificate by adding a certificate policy statement stipulating // that the certificate had to be used strictly as specified in the // keyUsage, and a keyUsage containing a flag indicating that the RSA // encryption key could only be used for Diffie-Hellman key agreement. if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) { return CertificateInvalidError{c, NotAuthorizedToSign} } return nil } // Verify attempts to verify c by building one or more chains from c to a // certificate in opts.roots, using certificates in opts.Intermediates if // needed. If successful, it returns one or more chains where the first // element of the chain is c and the last element is from opts.Roots. // // WARNING: this doesn't do any revocation checking. func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) { err = c.isValid(leafCertificate, &opts) if err != nil { return } if len(opts.DNSName) > 0 { err = c.VerifyHostname(opts.DNSName) if err != nil { return } } return c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts) } func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate { n := make([]*Certificate, len(chain)+1) copy(n, chain) n[len(chain)] = cert return n } func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) { for _, rootNum := range opts.Roots.findVerifiedParents(c) { root := opts.Roots.certs[rootNum] err = root.isValid(rootCertificate, opts) if err != nil { continue } chains = append(chains, appendToFreshChain(currentChain, root)) } nextIntermediate: for _, intermediateNum := range opts.Intermediates.findVerifiedParents(c) { intermediate := opts.Intermediates.certs[intermediateNum] for _, cert := range currentChain { if cert == intermediate { continue nextIntermediate } } err = intermediate.isValid(intermediateCertificate, opts) if err != nil { continue } var childChains [][]*Certificate childChains, ok := cache[intermediateNum] if !ok { childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts) cache[intermediateNum] = childChains } chains = append(chains, childChains...) } if len(chains) > 0 { err = nil } if len(chains) == 0 && err == nil { err = UnknownAuthorityError{c} } return } func matchHostnames(pattern, host string) bool { if len(pattern) == 0 || len(host) == 0 { return false } patternParts := strings.Split(pattern, ".") hostParts := strings.Split(host, ".") if len(patternParts) != len(hostParts) { return false } for i, patternPart := range patternParts { if patternPart == "*" { continue } if patternPart != hostParts[i] { return false } } return true } // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use // an explicitly ASCII function to avoid any sharp corners resulting from // performing Unicode operations on DNS labels. func toLowerCaseASCII(in string) string { // If the string is already lower-case then there's nothing to do. isAlreadyLowerCase := true for _, c := range in { if c == utf8.RuneError { // If we get a UTF-8 error then there might be // upper-case ASCII bytes in the invalid sequence. isAlreadyLowerCase = false break } if 'A' <= c && c <= 'Z' { isAlreadyLowerCase = false break } } if isAlreadyLowerCase { return in } out := []byte(in) for i, c := range out { if 'A' <= c && c <= 'Z' { out[i] += 'a' - 'A' } } return string(out) } // VerifyHostname returns nil if c is a valid certificate for the named host. // Otherwise it returns an error describing the mismatch. func (c *Certificate) VerifyHostname(h string) error { lowered := toLowerCaseASCII(h) if len(c.DNSNames) > 0 { for _, match := range c.DNSNames { if matchHostnames(toLowerCaseASCII(match), lowered) { return nil } } // If Subject Alt Name is given, we ignore the common name. } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) { return nil } return HostnameError{c, h} }
Java
/* * Implements dynamic task queues to provide load balancing * Sanjeev Kumar --- December, 2004 */ #ifndef __TASKQ_INTERNAL_H__ #define __TASKQ_INTERNAL_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef MAXFLOW #include <taskQMaxflow.h> #else #include "../include/taskQ.h" #endif #ifdef USE_ATHREADS // Alamere threads #include "taskQAThread.h" #endif #define CACHE_LINE_SIZE 256 /* Largest cache line size */ // #define HERE printf( ">>> at %s : %d\n", __FILE__, __LINE__) // #define HERE printf( "%ld $$$ at %s : %d\n", ( long)alt_index(), __FILE__, __LINE__) #define HERE // #define TRACE printf( "%ld ### at %s : %d\n", ( long)alt_index(), __FILE__, __LINE__); fflush( stdout); // #define TRACE printf( ">>> at %s : %d\n", __FILE__, __LINE__) // #define TRACE printf( ">>> %10d at %s : %d\n", pthread_self(), __FILE__, __LINE__) #define TRACE #define ERROR { printf( "Error in TaskQ: This function should not have been called at %s : %d\n", __FILE__, __LINE__); exit(0); } // #define IF_STATS(s) s #define IF_STATS(s) #define TQ_ASSERT(v) { \ if ( !(v)) { \ printf( "TQ Assertion failed at %s:%d\n", __FILE__, __LINE__); \ exit(1); \ } \ } #define UNDEFINED_VALUE ( ( void *)-999) // #define DEBUG_TASKQ #ifdef DEBUG_TASKQ #define DEBUG_ASSERT(v) TQ_ASSERT(v) #define IF_DEBUG(v) v #define DEBUG_ANNOUNCE { printf( "\n\n>>>>>>>>>>>>>>>>>>>>>> Running the DEBUG version of the TaskQ <<<<<<<<<<<<<<<<<<<\n\n\n"); } #else #define DEBUG_ASSERT(v) #define IF_DEBUG(v) #define DEBUG_ANNOUNCE #endif #define NUM_FIELDS (MAX_DIMENSION+1) static inline void copyTask( void *taskDest[NUM_FIELDS], void *taskSrc[NUM_FIELDS]) { int i; for ( i = 0; i < NUM_FIELDS; i++) taskDest[i] = taskSrc[i]; } static inline void copyArgs1( void *task[NUM_FIELDS], TaskQTask1 taskFunction, void *arg1) { TQ_ASSERT( NUM_FIELDS >= 2); task[0] = ( void *)taskFunction; task[1] = arg1; IF_DEBUG( { int i; for ( i = 2; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } static inline void copyArgs2( void *task[NUM_FIELDS], TaskQTask2 taskFunction, void *arg1, void *arg2) { TQ_ASSERT( NUM_FIELDS >= 3); task[0] = ( void *)taskFunction; task[1] = arg1; task[2] = arg2; IF_DEBUG( { int i; for ( i = 3; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } static inline void copyArgs3( void *task[NUM_FIELDS], TaskQTask3 taskFunction, void *arg1, void *arg2, void *arg3) { TQ_ASSERT( NUM_FIELDS >= 4); task[0] = ( void *)taskFunction; task[1] = arg1; task[2] = arg2; task[3] = arg3; IF_DEBUG( { int i; for ( i = 4; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } // The following functions are used to enqueue a grid of tasks typedef void ( *AssignTasksFn)( TaskQTask3 taskFn, int numDimensions, int queueNo, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]); void standardize( int n, long min1[MAX_DIMENSION], long max1[MAX_DIMENSION], long step1[MAX_DIMENSION], long min2[MAX_DIMENSION], long max2[MAX_DIMENSION], long step2[MAX_DIMENSION]) { long k; DEBUG_ASSERT( MAX_DIMENSION == 3); for ( k = 0; k < MAX_DIMENSION; k++) { if ( k < n) { min1[k] = min2[k]; max1[k] = max2[k]; step1[k] = step2[k]; } else { min1[k] = 0; max1[k] = 1; step1[k] = 1; } } } static inline void assignTasksStandardized( AssignTasksFn fn, TaskQTask3 taskFn, int numDimensions, int queueNo, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { long min1[MAX_DIMENSION], max1[MAX_DIMENSION], step1[MAX_DIMENSION]; standardize( numDimensions, min1, max1, step1, min, max, step); fn( taskFn, numDimensions, queueNo, min1, max1, step1); } static void enqueueGridRec( AssignTasksFn fn, TaskQTask3 taskFn, int numDimensions, int startQueue, int totalQueues, int currentDimension, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { if ( totalQueues == 1) { assignTasksStandardized( fn, taskFn, numDimensions, startQueue, min, max, step); } else { long j, k; for ( j = 0, k = currentDimension; j < numDimensions; j++, k = (k+1) % numDimensions) if ( max[k] - min[k] > 1) break; if ( max[k] - min[k] == 1) { // Only one task left. Put it in the first queue assignTasksStandardized( fn, taskFn, numDimensions, startQueue, min, max, step); // The rest get nothing for ( j = 0; j < numDimensions; j++) max[j] = min[j]; for ( j = 1; j < totalQueues; j++) assignTasksStandardized( fn, taskFn, numDimensions, startQueue+j, min, max, step); } else { // Split it into two halfs and give half to each long next, middle, half, alt[MAX_DIMENSION]; middle = min[k] + ( max[k] - min[k])/2; next = (k+1) % numDimensions; half = totalQueues/2; // First half for ( j = 0; j < numDimensions; j++) if ( j == k) alt[j] = middle; else alt[j] = max[j]; enqueueGridRec( fn, taskFn, numDimensions, startQueue, half, next, min, alt, step); // Seconf half for ( j = 0; j < numDimensions; j++) if ( j == k) alt[j] = middle; else alt[j] = min[j]; enqueueGridRec( fn, taskFn, numDimensions, startQueue+half, totalQueues-half, next, alt, max, step); } } } long countTasks( int n, long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { long k, count = 1; for ( k = 0; k < n; k++) count *= max[k]/step[k]; return count; } static inline void enqueueGridHelper( AssignTasksFn assignFunction, TaskQTask3 taskFunction, int numDimensions, int numTaskQs, long dimensionSize[MAX_DIMENSION], long tileSize[MAX_DIMENSION]) { long i, min[MAX_DIMENSION], max[MAX_DIMENSION]; for ( i = 0; i < numDimensions; i++) { DEBUG_ASSERT( dimensionSize[i] > 0); TQ_ASSERT( dimensionSize[i] % tileSize[i] == 0); min[i] = 0; max[i] = dimensionSize[i] / tileSize[i]; } enqueueGridRec( assignFunction, taskFunction, numDimensions, 0, numTaskQs, 0, min, max, tileSize); } // These are used to get/set task queue parameters static long paramValues[] = { ( long)UNDEFINED_VALUE, 1, ( long)UNDEFINED_VALUE }; void taskQSetParam( enum TaskQParam param, long value) { TQ_ASSERT( ( param > 0) && ( param < TaskQNumParams)); TQ_ASSERT( paramValues[TaskQNumParams] == ( long)UNDEFINED_VALUE); paramValues[param] = value; } long taskQGetParam( enum TaskQParam param) { TQ_ASSERT( ( param > 0) && ( param < TaskQNumParams)); TQ_ASSERT( paramValues[TaskQNumParams] == ( long)UNDEFINED_VALUE); return paramValues[param]; } #endif
Java
/* * * Copyright 2015, Google Inc. * 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 Google Inc. 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 * 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. * */ #include "src/core/lib/surface/completion_queue.h" #include <stdio.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/atm.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/support/string.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/event_string.h" #include "src/core/lib/surface/surface_trace.h" typedef struct { grpc_pollset_worker **worker; void *tag; } plucker; /* Completion queue structure */ struct grpc_completion_queue { /** owned by pollset */ gpr_mu *mu; /** completed events */ grpc_cq_completion completed_head; grpc_cq_completion *completed_tail; /** Number of pending events (+1 if we're not shutdown) */ gpr_refcount pending_events; /** Once owning_refs drops to zero, we will destroy the cq */ gpr_refcount owning_refs; /** 0 initially, 1 once we've begun shutting down */ int shutdown; int shutdown_called; int is_server_cq; int num_pluckers; plucker pluckers[GRPC_MAX_COMPLETION_QUEUE_PLUCKERS]; grpc_closure pollset_shutdown_done; #ifndef NDEBUG void **outstanding_tags; size_t outstanding_tag_count; size_t outstanding_tag_capacity; #endif grpc_completion_queue *next_free; }; #define POLLSET_FROM_CQ(cq) ((grpc_pollset *)(cq + 1)) static gpr_mu g_freelist_mu; static grpc_completion_queue *g_freelist; static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *cc, bool success); void grpc_cq_global_init(void) { gpr_mu_init(&g_freelist_mu); } void grpc_cq_global_shutdown(void) { gpr_mu_destroy(&g_freelist_mu); while (g_freelist) { grpc_completion_queue *next = g_freelist->next_free; grpc_pollset_destroy(POLLSET_FROM_CQ(g_freelist)); #ifndef NDEBUG gpr_free(g_freelist->outstanding_tags); #endif gpr_free(g_freelist); g_freelist = next; } } struct grpc_cq_alarm { grpc_timer alarm; grpc_cq_completion completion; /** completion queue where events about this alarm will be posted */ grpc_completion_queue *cq; /** user supplied tag */ void *tag; }; grpc_completion_queue *grpc_completion_queue_create(void *reserved) { grpc_completion_queue *cc; GPR_ASSERT(!reserved); GPR_TIMER_BEGIN("grpc_completion_queue_create", 0); GRPC_API_TRACE("grpc_completion_queue_create(reserved=%p)", 1, (reserved)); gpr_mu_lock(&g_freelist_mu); if (g_freelist == NULL) { gpr_mu_unlock(&g_freelist_mu); cc = gpr_malloc(sizeof(grpc_completion_queue) + grpc_pollset_size()); grpc_pollset_init(POLLSET_FROM_CQ(cc), &cc->mu); #ifndef NDEBUG cc->outstanding_tags = NULL; cc->outstanding_tag_capacity = 0; #endif } else { cc = g_freelist; g_freelist = g_freelist->next_free; gpr_mu_unlock(&g_freelist_mu); /* pollset already initialized */ } /* Initial ref is dropped by grpc_completion_queue_shutdown */ gpr_ref_init(&cc->pending_events, 1); /* One for destroy(), one for pollset_shutdown */ gpr_ref_init(&cc->owning_refs, 2); cc->completed_tail = &cc->completed_head; cc->completed_head.next = (uintptr_t)cc->completed_tail; cc->shutdown = 0; cc->shutdown_called = 0; cc->is_server_cq = 0; cc->num_pluckers = 0; #ifndef NDEBUG cc->outstanding_tag_count = 0; #endif grpc_closure_init(&cc->pollset_shutdown_done, on_pollset_shutdown_done, cc); GPR_TIMER_END("grpc_completion_queue_create", 0); return cc; } #ifdef GRPC_CQ_REF_COUNT_DEBUG void grpc_cq_internal_ref(grpc_completion_queue *cc, const char *reason, const char *file, int line) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p ref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count + 1, reason); #else void grpc_cq_internal_ref(grpc_completion_queue *cc) { #endif gpr_ref(&cc->owning_refs); } static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *arg, bool success) { grpc_completion_queue *cc = arg; GRPC_CQ_INTERNAL_UNREF(cc, "pollset_destroy"); } #ifdef GRPC_CQ_REF_COUNT_DEBUG void grpc_cq_internal_unref(grpc_completion_queue *cc, const char *reason, const char *file, int line) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p unref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count - 1, reason); #else void grpc_cq_internal_unref(grpc_completion_queue *cc) { #endif if (gpr_unref(&cc->owning_refs)) { GPR_ASSERT(cc->completed_head.next == (uintptr_t)&cc->completed_head); grpc_pollset_reset(POLLSET_FROM_CQ(cc)); gpr_mu_lock(&g_freelist_mu); cc->next_free = g_freelist; g_freelist = cc; gpr_mu_unlock(&g_freelist_mu); } } void grpc_cq_begin_op(grpc_completion_queue *cc, void *tag) { #ifndef NDEBUG gpr_mu_lock(cc->mu); GPR_ASSERT(!cc->shutdown_called); if (cc->outstanding_tag_count == cc->outstanding_tag_capacity) { cc->outstanding_tag_capacity = GPR_MAX(4, 2 * cc->outstanding_tag_capacity); cc->outstanding_tags = gpr_realloc(cc->outstanding_tags, sizeof(*cc->outstanding_tags) * cc->outstanding_tag_capacity); } cc->outstanding_tags[cc->outstanding_tag_count++] = tag; gpr_mu_unlock(cc->mu); #endif gpr_ref(&cc->pending_events); } /* Signal the end of an operation - if this is the last waiting-to-be-queued event, then enter shutdown mode */ /* Queue a GRPC_OP_COMPLETED operation */ void grpc_cq_end_op(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cc, void *tag, int success, void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, grpc_cq_completion *storage), void *done_arg, grpc_cq_completion *storage) { int shutdown; int i; grpc_pollset_worker *pluck_worker; #ifndef NDEBUG int found = 0; #endif GPR_TIMER_BEGIN("grpc_cq_end_op", 0); storage->tag = tag; storage->done = done; storage->done_arg = done_arg; storage->next = ((uintptr_t)&cc->completed_head) | ((uintptr_t)(success != 0)); gpr_mu_lock(cc->mu); #ifndef NDEBUG for (i = 0; i < (int)cc->outstanding_tag_count; i++) { if (cc->outstanding_tags[i] == tag) { cc->outstanding_tag_count--; GPR_SWAP(void *, cc->outstanding_tags[i], cc->outstanding_tags[cc->outstanding_tag_count]); found = 1; break; } } GPR_ASSERT(found); #endif shutdown = gpr_unref(&cc->pending_events); if (!shutdown) { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; pluck_worker = NULL; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag) { pluck_worker = *cc->pluckers[i].worker; break; } } grpc_pollset_kick(POLLSET_FROM_CQ(cc), pluck_worker); gpr_mu_unlock(cc->mu); } else { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; GPR_ASSERT(!cc->shutdown); GPR_ASSERT(cc->shutdown_called); cc->shutdown = 1; grpc_pollset_shutdown(exec_ctx, POLLSET_FROM_CQ(cc), &cc->pollset_shutdown_done); gpr_mu_unlock(cc->mu); } GPR_TIMER_END("grpc_cq_end_op", 0); } grpc_event grpc_completion_queue_next(grpc_completion_queue *cc, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_pollset_worker *worker = NULL; int first_loop = 1; gpr_timespec now; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_next", 0); GRPC_API_TRACE( "grpc_completion_queue_next(" "cc=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 5, (cc, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC); GRPC_CQ_INTERNAL_REF(cc, "next"); gpr_mu_lock(cc->mu); for (;;) { if (cc->completed_tail != &cc->completed_head) { grpc_cq_completion *c = (grpc_cq_completion *)cc->completed_head.next; cc->completed_head.next = c->next & ~(uintptr_t)1; if (c == cc->completed_tail) { cc->completed_tail = &cc->completed_head; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); break; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); continue; } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } } GRPC_SURFACE_TRACE_RETURNED_EVENT(cc, &ret); GRPC_CQ_INTERNAL_UNREF(cc, "next"); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_next", 0); return ret; } static int add_plucker(grpc_completion_queue *cc, void *tag, grpc_pollset_worker **worker) { if (cc->num_pluckers == GRPC_MAX_COMPLETION_QUEUE_PLUCKERS) { return 0; } cc->pluckers[cc->num_pluckers].tag = tag; cc->pluckers[cc->num_pluckers].worker = worker; cc->num_pluckers++; return 1; } static void del_plucker(grpc_completion_queue *cc, void *tag, grpc_pollset_worker **worker) { int i; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag && cc->pluckers[i].worker == worker) { cc->num_pluckers--; GPR_SWAP(plucker, cc->pluckers[i], cc->pluckers[cc->num_pluckers]); return; } } GPR_UNREACHABLE_CODE(return ); } grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cc, void *tag, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_cq_completion *c; grpc_cq_completion *prev; grpc_pollset_worker *worker = NULL; gpr_timespec now; int first_loop = 1; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_pluck", 0); GRPC_API_TRACE( "grpc_completion_queue_pluck(" "cc=%p, tag=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 6, (cc, tag, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC); GRPC_CQ_INTERNAL_REF(cc, "pluck"); gpr_mu_lock(cc->mu); for (;;) { prev = &cc->completed_head; while ((c = (grpc_cq_completion *)(prev->next & ~(uintptr_t)1)) != &cc->completed_head) { if (c->tag == tag) { prev->next = (prev->next & (uintptr_t)1) | (c->next & ~(uintptr_t)1); if (c == cc->completed_tail) { cc->completed_tail = prev; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); goto done; } prev = c; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } if (!add_plucker(cc, tag, &worker)) { gpr_log(GPR_DEBUG, "Too many outstanding grpc_completion_queue_pluck calls: maximum " "is %d", GRPC_MAX_COMPLETION_QUEUE_PLUCKERS); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); /* TODO(ctiller): should we use a different result here */ ret.type = GRPC_QUEUE_TIMEOUT; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { del_plucker(cc, tag, &worker); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } del_plucker(cc, tag, &worker); } done: GRPC_SURFACE_TRACE_RETURNED_EVENT(cc, &ret); GRPC_CQ_INTERNAL_UNREF(cc, "pluck"); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_pluck", 0); return ret; } /* Shutdown simply drops a ref that we reserved at creation time; if we drop to zero here, then enter shutdown mode and wake up any waiters */ void grpc_completion_queue_shutdown(grpc_completion_queue *cc) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_shutdown", 0); GRPC_API_TRACE("grpc_completion_queue_shutdown(cc=%p)", 1, (cc)); gpr_mu_lock(cc->mu); if (cc->shutdown_called) { gpr_mu_unlock(cc->mu); GPR_TIMER_END("grpc_completion_queue_shutdown", 0); return; } cc->shutdown_called = 1; if (gpr_unref(&cc->pending_events)) { GPR_ASSERT(!cc->shutdown); cc->shutdown = 1; grpc_pollset_shutdown(&exec_ctx, POLLSET_FROM_CQ(cc), &cc->pollset_shutdown_done); } gpr_mu_unlock(cc->mu); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_shutdown", 0); } void grpc_completion_queue_destroy(grpc_completion_queue *cc) { GRPC_API_TRACE("grpc_completion_queue_destroy(cc=%p)", 1, (cc)); GPR_TIMER_BEGIN("grpc_completion_queue_destroy", 0); grpc_completion_queue_shutdown(cc); GRPC_CQ_INTERNAL_UNREF(cc, "destroy"); GPR_TIMER_END("grpc_completion_queue_destroy", 0); } grpc_pollset *grpc_cq_pollset(grpc_completion_queue *cc) { return POLLSET_FROM_CQ(cc); } void grpc_cq_mark_server_cq(grpc_completion_queue *cc) { cc->is_server_cq = 1; } int grpc_cq_is_server_cq(grpc_completion_queue *cc) { return cc->is_server_cq; }
Java
import shutil from nose.tools import * from holland.lib.lvm import LogicalVolume from holland.lib.lvm.snapshot import * from tests.constants import * class TestSnapshot(object): def setup(self): self.tmpdir = tempfile.mkdtemp() def teardown(self): shutil.rmtree(self.tmpdir) def test_snapshot_fsm(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) snapshot.start(lv) def test_snapshot_fsm_with_callbacks(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) def handle_event(event, *args, **kwargs): pass snapshot.register('pre-mount', handle_event) snapshot.register('post-mount', handle_event) snapshot.start(lv) def test_snapshot_fsm_with_failures(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) def bad_callback(event, *args, **kwargs): raise Exception("Oooh nooo!") for evt in ('initialize', 'pre-snapshot', 'post-snapshot', 'pre-mount', 'post-mount', 'pre-unmount', 'post-unmount', 'pre-remove', 'post-remove', 'finish'): snapshot.register(evt, bad_callback) assert_raises(CallbackFailuresError, snapshot.start, lv) snapshot.unregister(evt, bad_callback) if snapshot.sigmgr._handlers: raise Exception("WTF. sigmgr handlers still exist when checking event => %r", evt)
Java
/* * This file is part of Pebble. * * Copyright (c) 2014 by Mitchell Bösecke * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.mitchellbosecke.pebble.extension; import com.mitchellbosecke.pebble.attributes.AttributeResolver; import com.mitchellbosecke.pebble.operator.BinaryOperator; import com.mitchellbosecke.pebble.operator.UnaryOperator; import com.mitchellbosecke.pebble.tokenParser.TokenParser; import java.util.List; import java.util.Map; public abstract class AbstractExtension implements Extension { @Override public List<TokenParser> getTokenParsers() { return null; } @Override public List<BinaryOperator> getBinaryOperators() { return null; } @Override public List<UnaryOperator> getUnaryOperators() { return null; } @Override public Map<String, Filter> getFilters() { return null; } @Override public Map<String, Test> getTests() { return null; } @Override public Map<String, Function> getFunctions() { return null; } @Override public Map<String, Object> getGlobalVariables() { return null; } @Override public List<NodeVisitorFactory> getNodeVisitors() { return null; } @Override public List<AttributeResolver> getAttributeResolver() { return null; } }
Java
<!DOCTYPE html> <!-- Copyright (c) 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. --> <link rel="import" href="/core/analysis/analysis_sub_view.html"> <link rel="import" href="/core/analysis/util.html"> <link rel="import" href="/core/analysis/analysis_link.html"> <link rel="import" href="/base/utils.html"> <polymer-element name="tv-c-single-cpu-slice-sub-view" extends="tracing-analysis-sub-view"> <template> <style> table { border-collapse: collapse; border-width: 0; margin-bottom: 25px; width: 100%; } table tr > td:first-child { padding-left: 2px; } table tr > td { padding: 2px 4px 2px 4px; vertical-align: text-top; width: 150px; } table td td { padding: 0 0 0 0; width: auto; } tr { vertical-align: top; } tr:nth-child(2n+0) { background-color: #e2e2e2; } </style> <table> <tr> <td>Running process:</td><td id="process-name"></td> </tr> <tr> <td>Running thread:</td><td id="thread-name"></td> </tr> <tr> <td>Start:</td><td id="start"></td> </tr> <tr> <td>Duration:</td><td id="duration"></td> </tr> <tr> <td>Active slices:</td><td id="running-thread"></td> </tr> <tr> <td>Args:</td> <td> <tv-c-analysis-generic-object-view id="args"> </tv-c-analysis-generic-object-view> </td> </tr> </table> </template> <script> 'use strict'; Polymer({ created: function() { this.currentSelection_ = undefined; }, get selection() { return this.currentSelection_; }, set selection(selection) { if (selection.length !== 1) throw new Error('Only supports single slices'); if (!(selection[0] instanceof tv.c.trace_model.CpuSlice)) throw new Error('Only supports thread time slices'); this.currentSelection_ = selection; var cpuSlice = selection[0]; var thread = cpuSlice.threadThatWasRunning; var shadowRoot = this.shadowRoot; if (thread) { shadowRoot.querySelector('#process-name').textContent = thread.parent.userFriendlyName; shadowRoot.querySelector('#thread-name').textContent = thread.userFriendlyName; } else { shadowRoot.querySelector('#process-name').parentElement.style.display = 'none'; shadowRoot.querySelector('#thread-name').textContent = cpuSlice.title; } shadowRoot.querySelector('#start').textContent = tv.c.analysis.tsString(cpuSlice.start); shadowRoot.querySelector('#duration').textContent = tv.c.analysis.tsString(cpuSlice.duration); var runningThreadEl = shadowRoot.querySelector('#running-thread'); var timeSlice = cpuSlice.getAssociatedTimeslice(); if (!timeSlice) { runningThreadEl.parentElement.style.display = 'none'; } else { var threadLink = document.createElement('tv-c-analysis-link'); threadLink.selection = new tv.c.Selection(timeSlice); threadLink.textContent = 'Click to select'; runningThreadEl.parentElement.style.display = ''; runningThreadEl.textContent = ''; runningThreadEl.appendChild(threadLink); } shadowRoot.querySelector('#args').object = cpuSlice.args; } }); </script> </polymer-element>
Java
//***************************************************************************** // // fontcmss46b.c - Font definition for the 46 point Cmss bold font. // // Copyright (c) 2008-2010 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 6288 of the Stellaris Graphics Library. // //***************************************************************************** //***************************************************************************** // // This file is generated by ftrasterize; DO NOT EDIT BY HAND! // //***************************************************************************** #include "grlib.h" //***************************************************************************** // // Details of this font: // Style: cmss // Size: 46 point // Bold: yes // Italic: no // Memory usage: 5636 bytes // //***************************************************************************** //***************************************************************************** // // The compressed data for the 46 point Cmss bold font. // //***************************************************************************** static const unsigned char g_pucCmss46bData[5434] = { 5, 18, 0, 101, 32, 37, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 240, 240, 70, 70, 70, 70, 70, 70, 0, 14, 32, 29, 20, 240, 240, 166, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 84, 100, 100, 100, 99, 115, 100, 100, 99, 115, 0, 80, 112, 129, 40, 0, 12, 18, 131, 240, 180, 115, 240, 180, 100, 240, 180, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 180, 100, 240, 164, 116, 240, 164, 116, 223, 15, 4, 95, 15, 6, 79, 15, 6, 95, 15, 4, 240, 36, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 47, 15, 4, 95, 15, 6, 79, 15, 6, 95, 15, 4, 228, 100, 240, 164, 116, 240, 164, 115, 240, 180, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 179, 116, 240, 164, 116, 240, 164, 115, 240, 180, 100, 240, 179, 116, 240, 179, 130, 0, 12, 80, 70, 23, 131, 240, 83, 240, 56, 206, 143, 1, 111, 2, 102, 19, 37, 86, 35, 67, 85, 51, 197, 51, 197, 51, 198, 35, 198, 35, 203, 219, 205, 190, 174, 173, 189, 218, 219, 195, 38, 195, 38, 195, 53, 195, 53, 195, 53, 66, 99, 53, 68, 67, 38, 70, 35, 22, 95, 3, 95, 2, 127, 172, 230, 240, 67, 240, 83, 0, 24, 64, 124, 44, 86, 240, 82, 234, 240, 36, 204, 245, 181, 54, 213, 196, 85, 212, 197, 101, 181, 197, 101, 165, 213, 101, 164, 229, 101, 149, 229, 101, 133, 245, 101, 117, 240, 21, 101, 116, 240, 53, 70, 101, 240, 53, 54, 101, 240, 78, 85, 240, 108, 100, 240, 152, 117, 240, 240, 133, 240, 240, 148, 104, 240, 165, 91, 240, 117, 92, 240, 101, 85, 54, 240, 84, 101, 69, 240, 69, 85, 101, 240, 37, 101, 101, 240, 36, 117, 101, 240, 20, 133, 101, 245, 133, 101, 229, 149, 101, 228, 165, 101, 213, 165, 101, 197, 181, 101, 181, 213, 69, 196, 229, 54, 181, 252, 196, 240, 42, 226, 240, 86, 0, 45, 16, 93, 37, 0, 6, 5, 240, 249, 240, 203, 240, 165, 53, 240, 133, 69, 240, 132, 101, 240, 101, 101, 240, 101, 101, 240, 101, 101, 240, 101, 101, 240, 101, 85, 240, 117, 69, 240, 134, 53, 240, 149, 22, 132, 219, 149, 201, 181, 200, 196, 230, 197, 215, 197, 201, 165, 188, 149, 165, 39, 117, 166, 39, 102, 165, 71, 85, 166, 87, 54, 166, 103, 22, 182, 109, 198, 123, 215, 121, 247, 91, 114, 95, 15, 2, 111, 15, 1, 126, 61, 167, 168, 0, 47, 17, 10, 240, 86, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 40, 112, 48, 16, 147, 196, 180, 180, 181, 180, 181, 165, 181, 181, 165, 181, 166, 166, 166, 165, 181, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 181, 182, 166, 166, 181, 181, 182, 181, 181, 197, 196, 197, 196, 212, 212, 211, 64, 48, 16, 3, 212, 212, 212, 197, 196, 197, 197, 181, 182, 181, 181, 182, 166, 166, 181, 182, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 165, 181, 166, 166, 165, 181, 166, 165, 181, 165, 180, 181, 180, 180, 180, 195, 208, 52, 23, 131, 240, 69, 240, 53, 240, 53, 195, 67, 67, 85, 51, 53, 70, 35, 38, 71, 19, 23, 95, 2, 155, 240, 19, 240, 27, 159, 2, 87, 19, 23, 70, 35, 38, 69, 51, 53, 83, 67, 67, 197, 240, 53, 240, 53, 240, 67, 0, 70, 64, 103, 38, 0, 30, 66, 240, 240, 84, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 95, 15, 2, 95, 15, 4, 79, 15, 4, 95, 15, 2, 240, 84, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 82, 0, 31, 18, 10, 0, 35, 6, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 8, 48, 9, 17, 0, 46, 109, 77, 77, 0, 43, 13, 10, 0, 35, 6, 70, 70, 70, 70, 70, 0, 14, 32, 94, 23, 240, 18, 240, 84, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 67, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 82, 240, 80, 71, 24, 240, 240, 22, 240, 26, 221, 165, 69, 149, 101, 133, 102, 102, 102, 101, 133, 101, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 85, 133, 101, 133, 102, 102, 102, 102, 118, 85, 149, 69, 174, 202, 240, 22, 0, 31, 48, 44, 21, 240, 243, 240, 21, 231, 156, 156, 156, 162, 54, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 175, 1, 79, 2, 95, 1, 0, 29, 48, 69, 24, 0, 6, 103, 252, 190, 159, 1, 118, 72, 85, 119, 85, 135, 83, 166, 98, 166, 98, 166, 240, 54, 240, 54, 240, 54, 240, 38, 240, 54, 240, 38, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 63, 4, 95, 4, 95, 4, 95, 4, 95, 4, 0, 33, 64, 66, 24, 240, 240, 23, 236, 190, 159, 1, 118, 86, 116, 134, 114, 150, 114, 150, 240, 54, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 218, 233, 251, 240, 70, 240, 70, 240, 69, 240, 70, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 81, 198, 67, 182, 68, 150, 87, 87, 95, 3, 143, 173, 232, 0, 31, 32, 70, 25, 0, 7, 86, 240, 55, 240, 40, 240, 40, 240, 25, 240, 25, 244, 21, 244, 21, 229, 21, 228, 37, 213, 37, 212, 53, 197, 53, 196, 69, 181, 69, 180, 85, 165, 85, 149, 101, 149, 101, 133, 117, 133, 117, 143, 6, 79, 6, 79, 6, 79, 6, 240, 21, 240, 85, 240, 85, 240, 85, 240, 85, 240, 85, 240, 85, 0, 35, 48, 68, 24, 0, 6, 47, 1, 143, 1, 143, 1, 143, 1, 143, 1, 134, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 61, 191, 159, 1, 135, 70, 117, 102, 117, 117, 131, 134, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 82, 182, 83, 165, 85, 134, 87, 87, 111, 2, 143, 188, 231, 0, 31, 48, 67, 24, 240, 240, 55, 235, 204, 189, 167, 82, 150, 240, 54, 240, 38, 240, 54, 240, 53, 240, 69, 240, 54, 54, 150, 41, 118, 27, 104, 70, 103, 102, 87, 117, 87, 118, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 85, 134, 85, 134, 85, 134, 86, 117, 117, 102, 118, 71, 143, 173, 203, 247, 0, 31, 32, 73, 24, 0, 6, 15, 4, 95, 5, 79, 5, 79, 5, 79, 4, 240, 53, 240, 54, 240, 53, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 54, 240, 54, 240, 38, 240, 54, 240, 54, 240, 54, 240, 53, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 31, 96, 65, 24, 240, 248, 236, 190, 159, 1, 118, 87, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 102, 102, 118, 70, 158, 202, 206, 150, 70, 118, 102, 101, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 86, 102, 103, 71, 127, 1, 158, 188, 232, 0, 31, 32, 67, 24, 240, 240, 22, 251, 206, 159, 150, 70, 118, 101, 117, 118, 86, 133, 86, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 119, 85, 119, 86, 103, 102, 57, 107, 22, 121, 38, 150, 54, 240, 53, 240, 69, 240, 69, 240, 54, 240, 53, 145, 134, 132, 86, 158, 158, 188, 247, 0, 31, 64, 21, 10, 0, 16, 38, 70, 70, 70, 70, 70, 0, 11, 102, 70, 70, 70, 70, 70, 0, 14, 32, 26, 10, 0, 16, 38, 70, 70, 70, 70, 70, 0, 11, 102, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 8, 48, 37, 10, 0, 13, 102, 70, 70, 70, 70, 70, 240, 240, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 240, 144, 32, 37, 0, 69, 79, 15, 1, 95, 15, 3, 79, 15, 3, 95, 15, 1, 0, 33, 31, 15, 1, 95, 15, 3, 79, 15, 3, 95, 15, 1, 0, 70, 57, 22, 0, 31, 5, 240, 23, 247, 247, 247, 240, 21, 0, 10, 53, 240, 37, 240, 37, 240, 37, 240, 37, 240, 37, 240, 21, 240, 37, 240, 22, 240, 21, 240, 22, 246, 247, 246, 246, 240, 22, 240, 22, 240, 22, 146, 86, 132, 86, 86, 95, 2, 111, 153, 0, 6, 80, 49, 21, 0, 5, 104, 174, 111, 1, 85, 86, 84, 118, 81, 150, 246, 246, 246, 231, 215, 230, 230, 230, 245, 240, 21, 245, 240, 21, 240, 21, 240, 20, 240, 36, 240, 36, 240, 36, 0, 9, 118, 246, 246, 246, 246, 246, 0, 30, 16, 84, 31, 0, 9, 25, 240, 78, 255, 3, 199, 102, 182, 165, 149, 198, 117, 124, 117, 94, 101, 95, 1, 85, 69, 72, 85, 53, 118, 84, 69, 118, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 85, 53, 117, 101, 53, 117, 101, 70, 69, 133, 77, 149, 91, 181, 103, 215, 240, 168, 150, 175, 4, 239, 240, 73, 0, 44, 80, 33, 0, 9, 87, 240, 169, 240, 139, 240, 123, 240, 123, 240, 109, 240, 93, 240, 86, 22, 240, 70, 39, 240, 54, 39, 240, 54, 39, 240, 38, 71, 240, 22, 71, 240, 22, 71, 246, 103, 230, 103, 230, 103, 214, 135, 198, 135, 198, 135, 182, 167, 175, 8, 175, 8, 159, 10, 143, 10, 134, 214, 118, 231, 102, 231, 102, 246, 86, 240, 23, 70, 240, 23, 69, 240, 54, 0, 45, 112, 71, 30, 0, 7, 79, 3, 207, 6, 159, 7, 143, 8, 118, 153, 102, 183, 102, 199, 86, 214, 86, 214, 86, 214, 86, 198, 102, 198, 102, 182, 118, 151, 143, 6, 159, 4, 191, 7, 134, 168, 102, 199, 86, 214, 86, 215, 70, 230, 70, 230, 70, 230, 70, 230, 70, 215, 70, 214, 86, 184, 95, 9, 111, 8, 127, 7, 143, 4, 0, 42, 80, 71, 30, 0, 8, 122, 240, 47, 2, 191, 4, 175, 5, 152, 118, 135, 195, 119, 225, 134, 240, 134, 240, 150, 240, 150, 240, 134, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 166, 240, 150, 240, 150, 240, 166, 240, 151, 241, 135, 211, 137, 118, 143, 7, 175, 5, 207, 1, 240, 42, 0, 42, 48, 87, 33, 0, 8, 47, 4, 239, 7, 191, 9, 159, 10, 134, 170, 118, 215, 118, 231, 102, 246, 102, 240, 22, 86, 240, 22, 86, 240, 37, 86, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 22, 86, 240, 22, 86, 247, 86, 231, 102, 215, 118, 185, 127, 10, 143, 9, 159, 7, 191, 4, 0, 47, 16, 71, 26, 0, 6, 79, 6, 95, 6, 95, 6, 95, 6, 95, 6, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 95, 5, 111, 5, 111, 5, 111, 5, 102, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 95, 7, 79, 7, 79, 7, 79, 7, 79, 7, 0, 36, 32, 70, 25, 0, 6, 47, 5, 95, 6, 79, 6, 79, 6, 79, 5, 86, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 79, 3, 127, 4, 111, 4, 111, 3, 118, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 0, 36, 96, 72, 30, 0, 8, 122, 240, 47, 1, 207, 5, 159, 6, 136, 134, 119, 195, 119, 226, 118, 240, 17, 102, 240, 150, 240, 150, 240, 134, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 170, 70, 170, 70, 170, 70, 170, 86, 214, 86, 214, 87, 198, 102, 198, 103, 182, 119, 166, 136, 134, 159, 6, 175, 5, 207, 1, 240, 42, 0, 42, 48, 71, 31, 0, 7, 102, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 79, 12, 79, 12, 79, 12, 79, 12, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 0, 43, 16, 38, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 43, 21, 0, 6, 86, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 81, 150, 82, 134, 84, 71, 111, 95, 125, 184, 0, 27, 48, 75, 32, 0, 8, 6, 246, 86, 231, 86, 215, 102, 199, 118, 183, 134, 167, 150, 151, 166, 135, 182, 119, 198, 103, 214, 87, 230, 71, 246, 55, 240, 22, 24, 240, 47, 1, 240, 31, 2, 255, 2, 255, 3, 234, 39, 217, 71, 200, 87, 199, 119, 182, 151, 166, 166, 166, 167, 150, 183, 134, 199, 118, 199, 118, 215, 102, 231, 86, 247, 70, 240, 21, 0, 44, 80, 71, 23, 0, 5, 102, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 47, 4, 79, 4, 79, 4, 79, 4, 79, 4, 0, 32, 16, 117, 40, 0, 10, 8, 240, 88, 73, 240, 57, 74, 240, 26, 74, 240, 26, 74, 240, 26, 75, 235, 75, 235, 70, 20, 228, 22, 70, 21, 197, 22, 70, 21, 197, 22, 70, 37, 165, 38, 70, 37, 165, 38, 70, 37, 165, 38, 70, 53, 133, 54, 70, 53, 133, 54, 70, 54, 101, 70, 70, 69, 101, 70, 70, 69, 101, 70, 70, 85, 69, 86, 70, 85, 69, 86, 70, 85, 69, 86, 70, 101, 37, 102, 70, 101, 37, 102, 70, 107, 118, 70, 122, 118, 70, 122, 118, 70, 136, 134, 70, 136, 134, 70, 135, 150, 70, 150, 150, 70, 164, 166, 70, 240, 150, 0, 55, 64, 89, 32, 0, 8, 24, 229, 74, 198, 74, 198, 75, 182, 75, 182, 76, 166, 76, 166, 70, 22, 150, 70, 22, 150, 70, 38, 134, 70, 38, 134, 70, 54, 118, 70, 54, 118, 70, 70, 102, 70, 70, 102, 70, 86, 86, 70, 86, 86, 70, 102, 70, 70, 102, 70, 70, 118, 54, 70, 118, 54, 70, 134, 38, 70, 134, 38, 70, 150, 22, 70, 150, 22, 70, 172, 70, 172, 70, 187, 70, 187, 70, 202, 70, 202, 70, 217, 0, 44, 64, 86, 33, 240, 240, 217, 240, 111, 240, 47, 3, 223, 6, 199, 120, 166, 182, 150, 214, 134, 214, 118, 246, 102, 246, 102, 246, 101, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 86, 246, 102, 246, 102, 246, 118, 214, 135, 183, 151, 151, 169, 104, 191, 6, 223, 4, 240, 31, 240, 105, 0, 43, 70, 29, 0, 7, 47, 3, 191, 6, 143, 7, 127, 8, 102, 168, 86, 198, 86, 199, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 199, 70, 198, 86, 168, 95, 8, 111, 7, 127, 6, 143, 3, 182, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 0, 42, 96, 104, 34, 240, 240, 234, 240, 127, 240, 47, 3, 255, 6, 200, 104, 183, 167, 151, 199, 134, 230, 118, 240, 22, 102, 240, 22, 102, 240, 22, 101, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 86, 240, 23, 86, 102, 70, 102, 103, 54, 118, 103, 23, 119, 94, 151, 93, 153, 75, 191, 7, 239, 3, 240, 47, 3, 240, 79, 1, 240, 200, 240, 184, 240, 200, 240, 199, 0, 26, 32, 71, 29, 0, 7, 47, 3, 191, 6, 143, 7, 127, 8, 102, 168, 86, 198, 86, 199, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 199, 70, 198, 86, 167, 111, 7, 127, 6, 143, 4, 166, 103, 166, 103, 166, 119, 150, 134, 150, 135, 134, 150, 134, 151, 118, 167, 102, 182, 102, 183, 86, 198, 86, 199, 70, 214, 70, 229, 0, 40, 48, 65, 26, 0, 7, 57, 239, 159, 3, 143, 3, 119, 102, 118, 148, 102, 193, 118, 240, 86, 240, 86, 240, 87, 240, 73, 240, 59, 255, 207, 1, 191, 1, 191, 1, 207, 236, 240, 56, 240, 87, 240, 71, 240, 86, 240, 86, 66, 230, 67, 214, 69, 167, 71, 119, 95, 6, 95, 5, 127, 3, 175, 233, 0, 33, 112, 70, 32, 0, 8, 15, 13, 79, 13, 79, 13, 79, 13, 79, 13, 246, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 0, 45, 112, 72, 30, 0, 7, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 86, 199, 86, 198, 103, 167, 120, 104, 159, 5, 191, 3, 223, 240, 57, 0, 39, 16, 82, 35, 0, 8, 102, 240, 70, 71, 240, 54, 87, 240, 22, 103, 240, 22, 103, 247, 119, 230, 135, 230, 135, 215, 151, 198, 167, 198, 167, 183, 183, 166, 199, 166, 214, 150, 231, 134, 231, 119, 247, 102, 240, 23, 102, 240, 23, 87, 240, 39, 70, 240, 55, 70, 240, 55, 55, 240, 71, 38, 240, 87, 38, 240, 102, 22, 240, 125, 240, 125, 240, 139, 240, 155, 240, 155, 240, 169, 240, 185, 0, 50, 122, 49, 0, 12, 37, 231, 228, 86, 216, 198, 70, 201, 197, 102, 185, 197, 102, 185, 197, 102, 171, 166, 102, 171, 165, 134, 149, 21, 165, 134, 149, 21, 165, 134, 133, 38, 134, 134, 133, 38, 133, 166, 117, 53, 133, 166, 117, 54, 102, 166, 101, 70, 102, 166, 101, 70, 101, 198, 85, 85, 101, 198, 85, 86, 70, 198, 69, 102, 69, 230, 53, 102, 69, 230, 53, 117, 69, 230, 53, 118, 38, 230, 37, 134, 37, 240, 22, 21, 134, 37, 240, 22, 21, 149, 37, 240, 22, 20, 172, 240, 27, 171, 240, 58, 186, 240, 58, 186, 240, 57, 202, 240, 57, 201, 240, 88, 216, 240, 87, 231, 0, 69, 77, 34, 0, 8, 87, 215, 120, 184, 136, 167, 152, 151, 184, 120, 200, 103, 232, 71, 240, 23, 56, 240, 24, 39, 240, 63, 240, 93, 240, 124, 240, 123, 240, 153, 240, 184, 240, 184, 240, 169, 240, 170, 240, 140, 240, 110, 240, 71, 23, 240, 71, 39, 240, 39, 56, 247, 88, 216, 103, 215, 135, 183, 152, 152, 168, 135, 199, 119, 216, 88, 232, 71, 240, 23, 0, 47, 32, 74, 34, 0, 8, 71, 240, 38, 72, 247, 87, 231, 104, 215, 120, 183, 151, 167, 168, 151, 184, 119, 215, 103, 232, 87, 248, 55, 240, 39, 39, 240, 56, 23, 240, 78, 240, 108, 240, 124, 240, 138, 240, 168, 240, 199, 240, 198, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 0, 48, 96, 72, 29, 0, 7, 63, 9, 95, 9, 95, 9, 95, 9, 95, 9, 240, 88, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 127, 9, 79, 10, 79, 10, 79, 10, 79, 10, 0, 40, 48, 48, 15, 10, 91, 74, 86, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 154, 91, 74, 80, 29, 21, 240, 240, 243, 131, 100, 116, 99, 131, 100, 116, 100, 116, 86, 86, 70, 86, 70, 86, 70, 86, 70, 86, 70, 86, 0, 84, 64, 48, 15, 26, 75, 90, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 90, 75, 90, 64, 17, 19, 240, 240, 213, 215, 185, 149, 21, 117, 52, 100, 100, 83, 132, 0, 86, 10, 10, 240, 86, 70, 70, 70, 70, 0, 48, 17, 10, 240, 131, 100, 99, 100, 100, 86, 70, 70, 70, 70, 70, 0, 40, 64, 48, 24, 0, 36, 105, 206, 159, 2, 117, 102, 115, 150, 98, 166, 240, 54, 240, 54, 240, 54, 204, 143, 1, 103, 86, 87, 102, 86, 118, 70, 134, 70, 134, 70, 134, 71, 103, 87, 72, 92, 22, 106, 38, 134, 84, 0, 33, 80, 71, 24, 0, 6, 6, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 54, 150, 26, 127, 3, 104, 71, 86, 118, 86, 118, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 118, 86, 118, 87, 86, 111, 3, 102, 25, 149, 38, 0, 34, 32, 45, 23, 0, 35, 56, 205, 159, 127, 1, 103, 100, 102, 146, 101, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 54, 161, 102, 146, 103, 101, 111, 2, 127, 157, 200, 0, 32, 96, 69, 25, 0, 8, 37, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 166, 54, 138, 22, 127, 3, 103, 87, 86, 134, 86, 134, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 86, 134, 86, 134, 102, 88, 111, 4, 138, 22, 166, 68, 0, 35, 45, 25, 0, 41, 72, 253, 175, 1, 135, 86, 102, 133, 102, 148, 101, 165, 70, 165, 70, 165, 79, 6, 79, 6, 70, 240, 70, 240, 70, 240, 86, 240, 70, 194, 102, 163, 103, 102, 127, 3, 158, 232, 0, 35, 64, 41, 20, 0, 6, 8, 170, 155, 134, 66, 118, 97, 118, 230, 230, 230, 230, 230, 204, 125, 140, 166, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 0, 28, 112, 63, 27, 0, 44, 89, 68, 143, 4, 127, 5, 102, 70, 181, 102, 150, 102, 150, 102, 150, 102, 150, 102, 150, 102, 150, 102, 166, 70, 206, 221, 225, 40, 243, 240, 147, 240, 159, 1, 191, 3, 175, 4, 143, 4, 111, 7, 85, 182, 69, 213, 69, 213, 70, 197, 86, 150, 127, 4, 159, 2, 219, 0, 8, 71, 23, 0, 5, 102, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 70, 118, 42, 86, 27, 89, 55, 71, 102, 71, 102, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 0, 32, 16, 35, 10, 240, 86, 70, 70, 70, 70, 70, 0, 6, 102, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 46, 17, 240, 240, 182, 167, 167, 167, 167, 182, 0, 12, 6, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 66, 71, 76, 92, 91, 150, 240, 240, 192, 65, 23, 0, 5, 101, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 118, 85, 103, 85, 87, 101, 71, 117, 55, 133, 39, 149, 23, 172, 187, 203, 204, 189, 174, 150, 38, 149, 70, 133, 86, 117, 87, 101, 102, 101, 118, 85, 134, 69, 134, 0, 32, 16, 38, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 71, 37, 0, 60, 22, 70, 134, 118, 42, 58, 102, 27, 44, 86, 18, 58, 71, 71, 104, 102, 71, 103, 118, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 0, 51, 48, 50, 23, 0, 37, 54, 70, 118, 42, 86, 27, 86, 18, 55, 71, 102, 71, 102, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 0, 32, 16, 45, 26, 0, 43, 24, 254, 191, 1, 150, 102, 118, 134, 102, 134, 101, 165, 86, 166, 70, 166, 70, 166, 70, 166, 70, 166, 70, 166, 70, 166, 86, 135, 86, 134, 104, 87, 127, 3, 159, 1, 190, 248, 0, 37, 16, 67, 24, 0, 37, 37, 150, 41, 118, 27, 111, 4, 88, 71, 86, 118, 86, 119, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 118, 86, 118, 87, 71, 111, 2, 118, 25, 134, 38, 166, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 8, 32, 69, 24, 0, 36, 101, 69, 137, 22, 127, 2, 111, 3, 88, 56, 86, 103, 86, 118, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 86, 118, 86, 103, 102, 72, 111, 3, 122, 22, 150, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 6, 64, 32, 17, 0, 27, 86, 67, 70, 37, 70, 22, 70, 22, 74, 120, 151, 167, 166, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 0, 24, 96, 34, 19, 0, 29, 8, 156, 109, 101, 68, 85, 114, 85, 229, 231, 203, 156, 140, 139, 170, 214, 244, 81, 148, 67, 132, 69, 85, 78, 94, 123, 167, 0, 27, 16, 35, 20, 0, 17, 118, 230, 230, 230, 230, 230, 191, 95, 95, 134, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 231, 51, 125, 140, 138, 197, 0, 28, 80, 50, 23, 0, 37, 54, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 103, 70, 103, 71, 72, 91, 22, 105, 37, 135, 0, 30, 48, 43, 24, 0, 39, 5, 165, 70, 149, 70, 134, 85, 133, 101, 133, 102, 102, 117, 101, 133, 101, 134, 70, 149, 69, 165, 69, 166, 38, 166, 38, 181, 37, 204, 204, 218, 234, 234, 248, 240, 24, 0, 34, 32, 71, 35, 0, 56, 117, 147, 149, 69, 133, 133, 70, 117, 118, 85, 102, 117, 101, 103, 101, 102, 87, 101, 102, 87, 86, 117, 67, 21, 69, 133, 67, 21, 69, 134, 51, 21, 69, 134, 36, 21, 53, 165, 36, 37, 37, 165, 35, 53, 37, 166, 19, 53, 22, 185, 53, 21, 201, 74, 200, 90, 200, 90, 215, 89, 230, 120, 245, 119, 0, 49, 48, 45, 24, 0, 39, 6, 133, 86, 118, 102, 86, 134, 70, 150, 38, 188, 203, 233, 240, 24, 240, 38, 240, 54, 240, 39, 240, 40, 250, 213, 37, 182, 38, 150, 69, 149, 101, 118, 102, 86, 134, 69, 165, 0, 33, 64, 61, 24, 0, 39, 5, 165, 70, 149, 70, 134, 86, 117, 102, 117, 118, 86, 118, 85, 149, 70, 150, 54, 165, 53, 182, 37, 182, 21, 213, 21, 219, 233, 249, 240, 24, 240, 23, 240, 54, 240, 54, 240, 53, 240, 69, 240, 69, 240, 68, 240, 69, 194, 69, 219, 218, 233, 240, 22, 0, 8, 16, 34, 22, 0, 35, 127, 2, 95, 2, 95, 2, 246, 247, 231, 246, 246, 247, 231, 246, 246, 247, 246, 246, 246, 247, 246, 255, 3, 79, 3, 79, 3, 0, 30, 96, 13, 29, 0, 72, 79, 10, 79, 10, 79, 10, 0, 80, 32, 22, 54, 0, 127, 0, 8, 15, 15, 15, 5, 79, 15, 15, 5, 79, 15, 15, 5, 0, 127, 0, 22, 21, 19, 240, 240, 150, 38, 85, 53, 101, 53, 85, 68, 100, 69, 100, 68, 115, 83, 0, 86, 64, 19, 20, 240, 240, 212, 99, 103, 67, 90, 20, 68, 26, 83, 72, 83, 100, 0, 93, 48, }; //***************************************************************************** // // The font definition for the 46 point Cmss bold font. // //***************************************************************************** const tFont g_sFontCmss46b = { // // The format of the font. // FONT_FMT_PIXEL_RLE, // // The maximum width of the font. // 49, // // The height of the font. // 45, // // The baseline of the font. // 34, // // The offset to each character in the font. // { 0, 5, 42, 71, 200, 270, 394, 487, 504, 552, 600, 652, 755, 773, 782, 795, 889, 960, 1004, 1073, 1139, 1209, 1277, 1344, 1417, 1482, 1549, 1570, 1596, 1633, 1665, 1722, 1771, 1855, 1935, 2006, 2077, 2164, 2235, 2305, 2377, 2448, 2486, 2529, 2604, 2675, 2792, 2881, 2967, 3037, 3141, 3212, 3277, 3347, 3419, 3501, 3623, 3700, 3774, 3846, 3894, 3923, 3971, 3988, 3998, 4015, 4063, 4134, 4179, 4248, 4293, 4334, 4397, 4468, 4503, 4549, 4614, 4652, 4723, 4773, 4818, 4885, 4954, 4986, 5020, 5055, 5105, 5148, 5219, 5264, 5325, 5359, 5372, 5394, 5415, }, // // A pointer to the actual font data // g_pucCmss46bData };
Java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.cluster.routing.allocation; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.cluster.ESAllocationTestCase; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING; /** * A base testcase that allows to run tests based on the output of the CAT API * The input is a line based cat/shards output like: * kibana-int 0 p STARTED 2 24.8kb 10.202.245.2 r5-9-35 * * the test builds up a clusterstate from the cat input and optionally runs a full balance on it. * This can be used to debug cluster allocation decisions. */ public abstract class CatAllocationTestCase extends ESAllocationTestCase { protected abstract Path getCatPath() throws IOException; public void testRun() throws IOException { Set<String> nodes = new HashSet<>(); Map<String, Idx> indices = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(getCatPath(), StandardCharsets.UTF_8)) { String line = null; // regexp FTW Pattern pattern = Pattern.compile("^(.+)\\s+(\\d)\\s+([rp])\\s+(STARTED|RELOCATING|INITIALIZING|UNASSIGNED)" + "\\s+\\d+\\s+[0-9.a-z]+\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+).*$"); while((line = reader.readLine()) != null) { final Matcher matcher; if ((matcher = pattern.matcher(line)).matches()) { final String index = matcher.group(1); Idx idx = indices.get(index); if (idx == null) { idx = new Idx(index); indices.put(index, idx); } final int shard = Integer.parseInt(matcher.group(2)); final boolean primary = matcher.group(3).equals("p"); ShardRoutingState state = ShardRoutingState.valueOf(matcher.group(4)); String ip = matcher.group(5); nodes.add(ip); ShardRouting routing = TestShardRouting.newShardRouting(index, shard, ip, null, primary, state); idx.add(routing); logger.debug("Add routing {}", routing); } else { fail("can't read line: " + line); } } } logger.info("Building initial routing table"); MetaData.Builder builder = MetaData.builder(); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); for(Idx idx : indices.values()) { IndexMetaData.Builder idxMetaBuilder = IndexMetaData.builder(idx.name).settings(settings(Version.CURRENT)) .numberOfShards(idx.numShards()).numberOfReplicas(idx.numReplicas()); for (ShardRouting shardRouting : idx.routing) { if (shardRouting.active()) { Set<String> allocationIds = idxMetaBuilder.getInSyncAllocationIds(shardRouting.id()); if (allocationIds == null) { allocationIds = new HashSet<>(); } else { allocationIds = new HashSet<>(allocationIds); } allocationIds.add(shardRouting.allocationId().getId()); idxMetaBuilder.putInSyncAllocationIds(shardRouting.id(), allocationIds); } } IndexMetaData idxMeta = idxMetaBuilder.build(); builder.put(idxMeta, false); IndexRoutingTable.Builder tableBuilder = new IndexRoutingTable.Builder(idxMeta.getIndex()).initializeAsRecovery(idxMeta); Map<Integer, IndexShardRoutingTable> shardIdToRouting = new HashMap<>(); for (ShardRouting r : idx.routing) { IndexShardRoutingTable refData = new IndexShardRoutingTable.Builder(r.shardId()).addShard(r).build(); if (shardIdToRouting.containsKey(r.getId())) { refData = new IndexShardRoutingTable.Builder(shardIdToRouting.get(r.getId())).addShard(r).build(); } shardIdToRouting.put(r.getId(), refData); } for (IndexShardRoutingTable t: shardIdToRouting.values()) { tableBuilder.addIndexShard(t); } IndexRoutingTable table = tableBuilder.build(); routingTableBuilder.add(table); } MetaData metaData = builder.build(); RoutingTable routingTable = routingTableBuilder.build(); DiscoveryNodes.Builder builderDiscoNodes = DiscoveryNodes.builder(); for (String node : nodes) { builderDiscoNodes.add(newNode(node)); } ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.CLUSTER_NAME_SETTING .getDefault(Settings.EMPTY)).metaData(metaData).routingTable(routingTable).nodes(builderDiscoNodes.build()).build(); if (balanceFirst()) { clusterState = rebalance(clusterState); } clusterState = allocateNew(clusterState); } protected abstract ClusterState allocateNew(ClusterState clusterState); protected boolean balanceFirst() { return true; } private ClusterState rebalance(ClusterState clusterState) { RoutingTable routingTable;AllocationService strategy = createAllocationService(Settings.builder() .build()); RoutingAllocation.Result routingResult = strategy.reroute(clusterState, "reroute"); clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build(); int numRelocations = 0; while (true) { List<ShardRouting> initializing = clusterState.routingTable().shardsWithState(INITIALIZING); if (initializing.isEmpty()) { break; } logger.debug("Initializing shards: {}", initializing); numRelocations += initializing.size(); routingResult = strategy.applyStartedShards(clusterState, initializing); clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build(); } logger.debug("--> num relocations to get balance: {}", numRelocations); return clusterState; } public class Idx { final String name; final List<ShardRouting> routing = new ArrayList<>(); public Idx(String name) { this.name = name; } public void add(ShardRouting r) { routing.add(r); } public int numReplicas() { int count = 0; for (ShardRouting msr : routing) { if (msr.primary() == false && msr.id()==0) { count++; } } return count; } public int numShards() { int max = 0; for (ShardRouting msr : routing) { if (msr.primary()) { max = Math.max(msr.getId()+1, max); } } return max; } } }
Java
.editable:hover { background-color: #FDFDFF; box-shadow: 0 0 20px #D5E3ED; -webkit-background-clip: padding-box; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar { box-shadow: 0 0 5px #999; position: fixed; top: 10px; left: 10px; width: 50px; -webkit-background-clip: padding-box; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar .dialog { background-color: #f8f8f7; box-shadow: 0 0 10px #999; display: block; left: 60px; padding: 10px; position: absolute; top: 120px; width: 300px; -webkit-background-clip: padding-box; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar a { display: inline-block; height: 50px; width: 48px; border: 1px solid #ddd; } #wysihtml5-toolbar a.cmd { background-color: #f8f8f7; background-position: center center; background-repeat: no-repeat; text-indent: -999px; } #wysihtml5-toolbar a.cmd:first-child { -webkit-border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; border-radius: 5px 5px 0 0; } #wysihtml5-toolbar a.cmd:last-child { background-color: red; -webkit-border-radius: 0 0 5px 5px; -moz-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; } #wysihtml5-toolbar a.italic { background-image: url(/static/images/icons/glyphicons_101_italic.png); } #wysihtml5-toolbar a.bold { background-image: url(/static/images/icons/glyphicons_102_bold.png); } #wysihtml5-toolbar a.link { background-image: url(/static/images/icons/glyphicons_050_link.png); } #wysihtml5-toolbar a.img { background-image: url(/static/images/icons/glyphicons_011_camera.png); } #wysihtml5-toolbar a.list { background-image: url(/static/images/icons/glyphicons_114_list.png); } #wysihtml5-toolbar a.blockquote { background-image: url(/static/images/icons/glyphicons_108_left_indent.png); } #wysihtml5-toolbar a.heading { color: #000; font-weight: bold; height: 30px; padding: 10px 0 0 0; text-align: center; text-indent: 0; } #wysihtml5-toolbar a.save { background-color: #C1E3D4; background-image: url(/static/images/icons/glyphicons_206_ok_2.png); } #wysihtml5-toolbar a.cancel { background-color: #E3C1D1; background-image: url(/static/images/icons/glyphicons_207_remove_2.png); }
Java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.rules.design; import net.sourceforge.pmd.AbstractRule; import net.sourceforge.pmd.ast.ASTAssignmentOperator; import net.sourceforge.pmd.ast.ASTConditionalExpression; import net.sourceforge.pmd.ast.ASTEqualityExpression; import net.sourceforge.pmd.ast.ASTExpression; import net.sourceforge.pmd.ast.ASTName; import net.sourceforge.pmd.ast.ASTNullLiteral; import net.sourceforge.pmd.ast.ASTStatementExpression; import net.sourceforge.pmd.symboltable.VariableNameDeclaration; // TODO - should check that this is not the first assignment. e.g., this is OK: // Object x; // x = null; public class NullAssignmentRule extends AbstractRule { public Object visit(ASTNullLiteral node, Object data) { if (node.getNthParent(5) instanceof ASTStatementExpression) { ASTStatementExpression n = (ASTStatementExpression) node.getNthParent(5); if (isAssignmentToFinalField(n)) { return data; } if (n.jjtGetNumChildren() > 2 && n.jjtGetChild(1) instanceof ASTAssignmentOperator) { addViolation(data, node); } } else if (node.getNthParent(4) instanceof ASTConditionalExpression) { // "false" expression of ternary if (isBadTernary((ASTConditionalExpression)node.getNthParent(4))) { addViolation(data, node); } } else if (node.getNthParent(5) instanceof ASTConditionalExpression && node.getNthParent(4) instanceof ASTExpression) { // "true" expression of ternary if (isBadTernary((ASTConditionalExpression)node.getNthParent(5))) { addViolation(data, node); } } return data; } private boolean isAssignmentToFinalField(ASTStatementExpression n) { ASTName name = n.getFirstChildOfType(ASTName.class); return name != null && name.getNameDeclaration() instanceof VariableNameDeclaration && ((VariableNameDeclaration) name.getNameDeclaration()).getAccessNodeParent().isFinal(); } private boolean isBadTernary(ASTConditionalExpression n) { return n.isTernary() && !(n.jjtGetChild(0) instanceof ASTEqualityExpression); } }
Java
/** * 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. * */ 'use strict'; jest.disableAutomock(); const React = require('React'); const ReactTestRenderer = require('react-test-renderer'); const VirtualizedList = require('VirtualizedList'); describe('VirtualizedList', () => { it('renders simple list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders empty list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={[]} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders null list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={undefined} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders all the bells and whistles', () => { const component = ReactTestRenderer.create( <VirtualizedList ItemSeparatorComponent={() => <separator />} ListFooterComponent={() => <footer />} ListHeaderComponent={() => <header />} data={new Array(5).fill().map((_, ii) => ({id: String(ii)}))} keyExtractor={(item, index) => item.id} getItemLayout={({index}) => ({length: 50, offset: index * 50})} numColumns={2} refreshing={false} onRefresh={jest.fn()} renderItem={({item}) => <item value={item.id} />} /> ); expect(component).toMatchSnapshot(); }); it('test getItem functionality where data is not an Array', () => { const component = ReactTestRenderer.create( <VirtualizedList data={new Map([['id_0', {key: 'item_0'}]])} getItem={(data, index) => data.get('id_' + index)} getItemCount={(data: Map) => data.size} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); });
Java
<?php namespace Sabre\DAVACL\PrincipalBackend; /** * Abstract Principal Backend * * Currently this class has no function. It's here for consistency and so we * have a non-bc-breaking way to add a default generic implementation to * functions we may add in the future. * * @copyright Copyright (C) 2007-2014 fruux GmbH (https://fruux.com/). * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ abstract class AbstractBackend implements BackendInterface { /** * Finds a principal by its URI. * * This method may receive any type of uri, but mailto: addresses will be * the most common. * * Implementation of this API is optional. It is currently used by the * CalDAV system to find principals based on their email addresses. If this * API is not implemented, some features may not work correctly. * * This method must return a relative principal path, or null, if the * principal was not found or you refuse to find it. * * @param string $uri * @return string */ function findByUri($uri) { // Note that the default implementation here is a bit slow and could // likely be optimized. if (substr($uri,0,7)!=='mailto:') { return; } $result = $this->searchPrincipals( '', ['{http://sabredav.org/ns}email-address' => substr($uri,7)] ); if ($result) { return $result[0]; } } }
Java
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 8; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-3,4)),ceild(4*t2-Nz-4,8));t3<=min(min(min(floord(4*t2+Ny,8),floord(Nt+Ny-4,8)),floord(2*t1+Ny+1,8)),floord(4*t1-4*t2+Nz+Ny-1,8));t3++) { for (t4=max(max(max(0,ceild(t1-31,32)),ceild(4*t2-Nz-60,64)),ceild(8*t3-Ny-60,64));t4<=min(min(min(min(floord(4*t2+Nx,64),floord(Nt+Nx-4,64)),floord(2*t1+Nx+1,64)),floord(8*t3+Nx+4,64)),floord(4*t1-4*t2+Nz+Nx-1,64));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),8*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),8*t3+6),64*t4+62),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(8*t3,t5+1);t7<=min(8*t3+7,t5+Ny-2);t7++) { lbv=max(64*t4,t5+1); ubv=min(64*t4+63,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
Java
/* * Copyright © 2018-2019, VideoLAN and dav1d authors * Copyright © 2018-2019, Two Orioles, LLC * 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. * * 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. */ #include "config.h" #include <stddef.h> #include <stdint.h> #include <string.h> #include "common/attributes.h" #include "common/intops.h" #include "src/itx.h" #include "src/itx_1d.h" static NOINLINE void inv_txfm_add_c(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob, const int w, const int h, const int shift, const itx_1d_fn first_1d_fn, const itx_1d_fn second_1d_fn, const int has_dconly HIGHBD_DECL_SUFFIX) { assert(w >= 4 && w <= 64); assert(h >= 4 && h <= 64); assert(eob >= 0); const int is_rect2 = w * 2 == h || h * 2 == w; const int rnd = (1 << shift) >> 1; if (eob < has_dconly) { int dc = coeff[0]; coeff[0] = 0; if (is_rect2) dc = (dc * 181 + 128) >> 8; dc = (dc * 181 + 128) >> 8; dc = (dc + rnd) >> shift; dc = (dc * 181 + 128 + 2048) >> 12; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + dc); return; } const int sh = imin(h, 32), sw = imin(w, 32); #if BITDEPTH == 8 const int row_clip_min = INT16_MIN; const int col_clip_min = INT16_MIN; #else const int row_clip_min = (int) ((unsigned) ~bitdepth_max << 7); const int col_clip_min = (int) ((unsigned) ~bitdepth_max << 5); #endif const int row_clip_max = ~row_clip_min; const int col_clip_max = ~col_clip_min; int32_t tmp[64 * 64], *c = tmp; for (int y = 0; y < sh; y++, c += w) { if (is_rect2) for (int x = 0; x < sw; x++) c[x] = (coeff[y + x * sh] * 181 + 128) >> 8; else for (int x = 0; x < sw; x++) c[x] = coeff[y + x * sh]; first_1d_fn(c, 1, row_clip_min, row_clip_max); } memset(coeff, 0, sizeof(*coeff) * sw * sh); for (int i = 0; i < w * sh; i++) tmp[i] = iclip((tmp[i] + rnd) >> shift, col_clip_min, col_clip_max); for (int x = 0; x < w; x++) second_1d_fn(&tmp[x], w, col_clip_min, col_clip_max); c = tmp; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + ((*c++ + 8) >> 4)); } #define inv_txfm_fn(type1, type2, w, h, shift, has_dconly) \ static void \ inv_txfm_add_##type1##_##type2##_##w##x##h##_c(pixel *dst, \ const ptrdiff_t stride, \ coef *const coeff, \ const int eob \ HIGHBD_DECL_SUFFIX) \ { \ inv_txfm_add_c(dst, stride, coeff, eob, w, h, shift, \ dav1d_inv_##type1##w##_1d_c, dav1d_inv_##type2##h##_1d_c, \ has_dconly HIGHBD_TAIL_SUFFIX); \ } #define inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(dct, dct, w, h, shift, 1) #define inv_txfm_fn32(w, h, shift) \ inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(identity, identity, w, h, shift, 0) #define inv_txfm_fn16(w, h, shift) \ inv_txfm_fn32(w, h, shift) \ inv_txfm_fn(adst, dct, w, h, shift, 0) \ inv_txfm_fn(dct, adst, w, h, shift, 0) \ inv_txfm_fn(adst, adst, w, h, shift, 0) \ inv_txfm_fn(dct, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, dct, w, h, shift, 0) \ inv_txfm_fn(adst, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, adst, w, h, shift, 0) \ inv_txfm_fn(flipadst, flipadst, w, h, shift, 0) \ inv_txfm_fn(identity, dct, w, h, shift, 0) \ inv_txfm_fn(dct, identity, w, h, shift, 0) \ #define inv_txfm_fn84(w, h, shift) \ inv_txfm_fn16(w, h, shift) \ inv_txfm_fn(identity, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, identity, w, h, shift, 0) \ inv_txfm_fn(identity, adst, w, h, shift, 0) \ inv_txfm_fn(adst, identity, w, h, shift, 0) \ inv_txfm_fn84( 4, 4, 0) inv_txfm_fn84( 4, 8, 0) inv_txfm_fn84( 4, 16, 1) inv_txfm_fn84( 8, 4, 0) inv_txfm_fn84( 8, 8, 1) inv_txfm_fn84( 8, 16, 1) inv_txfm_fn32( 8, 32, 2) inv_txfm_fn84(16, 4, 1) inv_txfm_fn84(16, 8, 1) inv_txfm_fn16(16, 16, 2) inv_txfm_fn32(16, 32, 1) inv_txfm_fn64(16, 64, 2) inv_txfm_fn32(32, 8, 2) inv_txfm_fn32(32, 16, 1) inv_txfm_fn32(32, 32, 2) inv_txfm_fn64(32, 64, 1) inv_txfm_fn64(64, 16, 2) inv_txfm_fn64(64, 32, 1) inv_txfm_fn64(64, 64, 2) static void inv_txfm_add_wht_wht_4x4_c(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob HIGHBD_DECL_SUFFIX) { int32_t tmp[4 * 4], *c = tmp; for (int y = 0; y < 4; y++, c += 4) { for (int x = 0; x < 4; x++) c[x] = coeff[y + x * 4] >> 2; dav1d_inv_wht4_1d_c(c, 1); } memset(coeff, 0, sizeof(*coeff) * 4 * 4); for (int x = 0; x < 4; x++) dav1d_inv_wht4_1d_c(&tmp[x], 4); c = tmp; for (int y = 0; y < 4; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < 4; x++) dst[x] = iclip_pixel(dst[x] + *c++); } COLD void bitfn(dav1d_itx_dsp_init)(Dav1dInvTxfmDSPContext *const c) { #define assign_itx_all_fn64(w, h, pfx) \ c->itxfm_add[pfx##TX_##w##X##h][DCT_DCT ] = \ inv_txfm_add_dct_dct_##w##x##h##_c #define assign_itx_all_fn32(w, h, pfx) \ assign_itx_all_fn64(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][IDTX] = \ inv_txfm_add_identity_identity_##w##x##h##_c #define assign_itx_all_fn16(w, h, pfx) \ assign_itx_all_fn32(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][DCT_ADST ] = \ inv_txfm_add_adst_dct_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_DCT ] = \ inv_txfm_add_dct_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_ADST] = \ inv_txfm_add_adst_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_FLIPADST] = \ inv_txfm_add_flipadst_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_ADST] = \ inv_txfm_add_adst_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][DCT_FLIPADST] = \ inv_txfm_add_flipadst_dct_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_DCT] = \ inv_txfm_add_dct_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_FLIPADST] = \ inv_txfm_add_flipadst_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_DCT] = \ inv_txfm_add_dct_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_DCT] = \ inv_txfm_add_identity_dct_##w##x##h##_c #define assign_itx_all_fn84(w, h, pfx) \ assign_itx_all_fn16(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][H_FLIPADST] = \ inv_txfm_add_flipadst_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_FLIPADST] = \ inv_txfm_add_identity_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_ADST] = \ inv_txfm_add_adst_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_ADST] = \ inv_txfm_add_identity_adst_##w##x##h##_c; \ memset(c, 0, sizeof(*c)); /* Zero unused function pointer elements. */ c->itxfm_add[TX_4X4][WHT_WHT] = inv_txfm_add_wht_wht_4x4_c; assign_itx_all_fn84( 4, 4, ); assign_itx_all_fn84( 4, 8, R); assign_itx_all_fn84( 4, 16, R); assign_itx_all_fn84( 8, 4, R); assign_itx_all_fn84( 8, 8, ); assign_itx_all_fn84( 8, 16, R); assign_itx_all_fn32( 8, 32, R); assign_itx_all_fn84(16, 4, R); assign_itx_all_fn84(16, 8, R); assign_itx_all_fn16(16, 16, ); assign_itx_all_fn32(16, 32, R); assign_itx_all_fn64(16, 64, R); assign_itx_all_fn32(32, 8, R); assign_itx_all_fn32(32, 16, R); assign_itx_all_fn32(32, 32, ); assign_itx_all_fn64(32, 64, R); assign_itx_all_fn64(64, 16, R); assign_itx_all_fn64(64, 32, R); assign_itx_all_fn64(64, 64, ); #if HAVE_ASM #if ARCH_AARCH64 || ARCH_ARM bitfn(dav1d_itx_dsp_init_arm)(c); #endif #if ARCH_X86 bitfn(dav1d_itx_dsp_init_x86)(c); #endif #endif }
Java
// 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 <limits.h> #include <stddef.h> #include <stdint.h> #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/string_piece.h" #include "ipc/ipc_message.h" #include "tools/ipc_fuzzer/message_lib/message_cracker.h" #include "tools/ipc_fuzzer/message_lib/message_file.h" #include "tools/ipc_fuzzer/message_lib/message_file_format.h" #include "tools/ipc_fuzzer/message_lib/message_names.h" namespace ipc_fuzzer { namespace { // Helper class to read IPC message file into a MessageVector and // fix message types. class Reader { public: Reader(const base::FilePath& path); bool Read(MessageVector* messages); private: template <typename T> bool CutObject(const T** object); // Reads the header, checks magic and version. bool ReadHeader(); bool MapFile(); bool ReadMessages(); // Last part of the file is a string table for message names. bool ReadStringTable(); // Reads type <-> name mapping into name_map_. References string table. bool ReadNameTable(); // Removes obsolete messages from the vector. bool RemoveUnknownMessages(); // Does type -> name -> correct_type fixup. void FixMessageTypes(); // Raw data. base::FilePath path_; base::MemoryMappedFile mapped_file_; base::StringPiece file_data_; base::StringPiece string_table_; // Parsed data. const FileHeader* header_; MessageVector* messages_; MessageNames name_map_; DISALLOW_COPY_AND_ASSIGN(Reader); }; Reader::Reader(const base::FilePath& path) : path_(path), header_(NULL), messages_(NULL) { } template <typename T> bool Reader::CutObject(const T** object) { if (file_data_.size() < sizeof(T)) { LOG(ERROR) << "Unexpected EOF."; return false; } *object = reinterpret_cast<const T*>(file_data_.data()); file_data_.remove_prefix(sizeof(T)); return true; } bool Reader::ReadHeader() { if (!CutObject<FileHeader>(&header_)) return false; if (header_->magic != FileHeader::kMagicValue) { LOG(ERROR) << path_.value() << " is not an IPC message file."; return false; } if (header_->version != FileHeader::kCurrentVersion) { LOG(ERROR) << "Wrong version for message file " << path_.value() << ". " << "File version is " << header_->version << ", " << "current version is " << FileHeader::kCurrentVersion << "."; return false; } return true; } bool Reader::MapFile() { if (!mapped_file_.Initialize(path_)) { LOG(ERROR) << "Failed to map testcase: " << path_.value(); return false; } const char* data = reinterpret_cast<const char*>(mapped_file_.data()); file_data_ = base::StringPiece(data, mapped_file_.length()); return true; } bool Reader::ReadMessages() { for (size_t i = 0; i < header_->message_count; ++i) { const char* begin = file_data_.begin(); const char* end = file_data_.end(); IPC::Message::NextMessageInfo info; IPC::Message::FindNext(begin, end, &info); if (!info.message_found) { LOG(ERROR) << "Failed to parse message."; return false; } CHECK_EQ(info.message_end, info.pickle_end); size_t msglen = info.message_end - begin; if (msglen > INT_MAX) { LOG(ERROR) << "Message too large."; return false; } // Copy is necessary to fix message type later. IPC::Message const_message(begin, msglen); messages_->push_back(std::make_unique<IPC::Message>(const_message)); file_data_.remove_prefix(msglen); } return true; } bool Reader::ReadStringTable() { size_t name_count = header_->name_count; if (!name_count) return true; if (name_count > file_data_.size() / sizeof(NameTableEntry)) { LOG(ERROR) << "Invalid name table size: " << name_count; return false; } size_t string_table_offset = name_count * sizeof(NameTableEntry); string_table_ = file_data_.substr(string_table_offset); if (string_table_.empty()) { LOG(ERROR) << "Missing string table."; return false; } if (string_table_.end()[-1] != '\0') { LOG(ERROR) << "String table doesn't end with NUL."; return false; } return true; } bool Reader::ReadNameTable() { for (size_t i = 0; i < header_->name_count; ++i) { const NameTableEntry* entry; if (!CutObject<NameTableEntry>(&entry)) return false; size_t offset = entry->string_table_offset; if (offset >= string_table_.size()) { LOG(ERROR) << "Invalid string table offset: " << offset; return false; } name_map_.Add(entry->type, string_table_.data() + offset); } return true; } bool Reader::RemoveUnknownMessages() { MessageVector::iterator it = messages_->begin(); while (it != messages_->end()) { uint32_t type = (*it)->type(); if (!name_map_.TypeExists(type)) { LOG(ERROR) << "Missing name table entry for type " << type; return false; } const std::string& name = name_map_.TypeToName(type); if (!MessageNames::GetInstance()->NameExists(name)) { LOG(WARNING) << "Unknown message " << name; it = messages_->erase(it); } else { ++it; } } return true; } // Message types are based on line numbers, so a minor edit of *_messages.h // changes the types of messages in that file. The types are fixed here to // increase the lifetime of message files. This is only a partial fix because // message arguments and structure layouts can change as well. void Reader::FixMessageTypes() { for (const auto& message : *messages_) { uint32_t type = message->type(); const std::string& name = name_map_.TypeToName(type); uint32_t correct_type = MessageNames::GetInstance()->NameToType(name); if (type != correct_type) MessageCracker::SetMessageType(message.get(), correct_type); } } bool Reader::Read(MessageVector* messages) { messages_ = messages; if (!MapFile()) return false; if (!ReadHeader()) return false; if (!ReadMessages()) return false; if (!ReadStringTable()) return false; if (!ReadNameTable()) return false; if (!RemoveUnknownMessages()) return false; FixMessageTypes(); return true; } } // namespace bool MessageFile::Read(const base::FilePath& path, MessageVector* messages) { Reader reader(path); return reader.Read(messages); } } // namespace ipc_fuzzer
Java
// Copyright (c) 2011 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/renderer_host/chrome_url_request_user_data.h" namespace { const char* const kKeyName = "chrome_url_request_user_data"; } // namespace ChromeURLRequestUserData::ChromeURLRequestUserData() : is_prerender_(false) { } // static ChromeURLRequestUserData* ChromeURLRequestUserData::Get( const net::URLRequest* request) { DCHECK(request); return static_cast<ChromeURLRequestUserData*>(request->GetUserData(kKeyName)); } // static ChromeURLRequestUserData* ChromeURLRequestUserData::Create( net::URLRequest* request) { DCHECK(request); DCHECK(!Get(request)); ChromeURLRequestUserData* user_data = new ChromeURLRequestUserData(); request->SetUserData(kKeyName, user_data); return user_data; } // static void ChromeURLRequestUserData::Delete(net::URLRequest* request) { DCHECK(request); request->SetUserData(kKeyName, NULL); }
Java
// Copyright (c) 2011 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 CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ #define CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ #pragma once #include <set> #include "base/id_map.h" #include "base/memory/scoped_ptr.h" #include "base/process.h" #include "base/process_util.h" #include "base/time.h" #include "chrome/common/visitedlink_common.h" #include "ipc/ipc_sync_channel.h" #include "ui/gfx/surface/transport_dib.h" class Profile; struct ViewMsg_ClosePage_Params; namespace base { class SharedMemory; } namespace net { class URLRequestContextGetter; } // Virtual interface that represents the browser side of the browser <-> // renderer communication channel. There will generally be one // RenderProcessHost per renderer process. // // The concrete implementation of this class for normal use is the // BrowserRenderProcessHost. It may also be implemented by a testing interface // for mocking purposes. class RenderProcessHost : public IPC::Channel::Sender, public IPC::Channel::Listener { public: typedef IDMap<RenderProcessHost>::iterator iterator; // We classify renderers according to their highest privilege, and try // to group pages into renderers with similar privileges. // Note: it may be possible for a renderer to have multiple privileges, // in which case we call it an "extension" renderer. enum Type { TYPE_NORMAL, // Normal renderer, no extra privileges. TYPE_WEBUI, // Renderer with WebUI privileges, like New Tab. TYPE_EXTENSION, // Renderer with extension privileges. }; // Details for RENDERER_PROCESS_CLOSED notifications. struct RendererClosedDetails { RendererClosedDetails(base::TerminationStatus status, int exit_code, bool was_extension_renderer) { this->status = status; this->exit_code = exit_code; this->was_extension_renderer = was_extension_renderer; } base::TerminationStatus status; int exit_code; bool was_extension_renderer; }; explicit RenderProcessHost(Profile* profile); virtual ~RenderProcessHost(); // Returns the user profile associated with this renderer process. Profile* profile() const { return profile_; } // Returns the unique ID for this child process. This can be used later in // a call to FromID() to get back to this object (this is used to avoid // sending non-threadsafe pointers to other threads). // // This ID will be unique for all child processes, including workers, plugins, // etc. It is generated by ChildProcessInfo. int id() const { return id_; } // Returns true iff channel_ has been set to non-NULL. Use this for checking // if there is connection or not. bool HasConnection() { return channel_.get() != NULL; } bool sudden_termination_allowed() const { return sudden_termination_allowed_; } void set_sudden_termination_allowed(bool enabled) { sudden_termination_allowed_ = enabled; } // Used for refcounting, each holder of this object must Attach and Release // just like it would for a COM object. This object should be allocated on // the heap; when no listeners own it any more, it will delete itself. void Attach(IPC::Channel::Listener* listener, int routing_id); // See Attach() void Release(int listener_id); // Listeners should call this when they've sent a "Close" message and // they're waiting for a "Close_ACK", so that if the renderer process // goes away we'll know that it was intentional rather than a crash. void ReportExpectingClose(int32 listener_id); // Allows iteration over this RenderProcessHost's RenderViewHost listeners. // Use from UI thread only. typedef IDMap<IPC::Channel::Listener>::const_iterator listeners_iterator; listeners_iterator ListenersIterator() { return listeners_iterator(&listeners_); } IPC::Channel::Listener* GetListenerByID(int routing_id) { return listeners_.Lookup(routing_id); } IPC::SyncChannel* channel() { return channel_.get(); } // Called to inform the render process host of a new "max page id" for a // render view host. The render process host computes the largest page id // across all render view hosts and uses the value when it needs to // initialize a new renderer in place of the current one. void UpdateMaxPageID(int32 page_id); void set_ignore_input_events(bool ignore_input_events) { ignore_input_events_ = ignore_input_events; } bool ignore_input_events() { return ignore_input_events_; } // Returns how long the child has been idle. The definition of idle // depends on when a derived class calls mark_child_process_activity_time(). // This is a rough indicator and its resolution should not be better than // 10 milliseconds. base::TimeDelta get_child_process_idle_time() const { return base::TimeTicks::Now() - child_process_activity_time_; } // Call this function when it is evident that the child process is actively // performing some operation, for example if we just received an IPC message. void mark_child_process_activity_time() { child_process_activity_time_ = base::TimeTicks::Now(); } // Try to shutdown the associated render process as fast as possible, but // only if |count| matches the number of render widgets that this process // controls. bool FastShutdownForPageCount(size_t count); bool fast_shutdown_started() { return fast_shutdown_started_; } // Virtual interface --------------------------------------------------------- // Initialize the new renderer process, returning true on success. This must // be called once before the object can be used, but can be called after // that with no effect. Therefore, if the caller isn't sure about whether // the process has been created, it should just call Init(). virtual bool Init( bool is_accessibility_enabled, bool is_extensions_process) = 0; // Gets the next available routing id. virtual int GetNextRoutingID() = 0; // Called on the UI thread to cancel any outstanding resource requests for // the specified render widget. virtual void CancelResourceRequests(int render_widget_id) = 0; // Called on the UI thread to simulate a ClosePage_ACK message to the // ResourceDispatcherHost. Necessary for a cross-site request, in the case // that the original RenderViewHost is not live and thus cannot run an // onunload handler. virtual void CrossSiteClosePageACK( const ViewMsg_ClosePage_Params& params) = 0; // Called on the UI thread to wait for the next UpdateRect message for the // specified render widget. Returns true if successful, and the msg out- // param will contain a copy of the received UpdateRect message. virtual bool WaitForUpdateMsg(int render_widget_id, const base::TimeDelta& max_delay, IPC::Message* msg) = 0; // Called when a received message cannot be decoded. virtual void ReceivedBadMessage() = 0; // Track the count of visible widgets. Called by listeners to register and // unregister visibility. virtual void WidgetRestored() = 0; virtual void WidgetHidden() = 0; // Called when RenderView is created by a listener. virtual void ViewCreated() = 0; // Informs the renderer about a new visited link table. virtual void SendVisitedLinkTable(base::SharedMemory* table_memory) = 0; // Notify the renderer that a link was visited. virtual void AddVisitedLinks( const VisitedLinkCommon::Fingerprints& links) = 0; // Clear internal visited links buffer and ask the renderer to update link // coloring state for all of its links. virtual void ResetVisitedLinks() = 0; // Try to shutdown the associated renderer process as fast as possible. // If this renderer has any RenderViews with unload handlers, then this // function does nothing. The current implementation uses TerminateProcess. // Returns True if it was able to do fast shutdown. virtual bool FastShutdownIfPossible() = 0; // Synchronously sends the message, waiting for the specified timeout. The // implementor takes ownership of the given Message regardless of whether or // not this method succeeds. Returns true on success. virtual bool SendWithTimeout(IPC::Message* msg, int timeout_ms) = 0; // Returns the process object associated with the child process. In certain // tests or single-process mode, this will actually represent the current // process. // // NOTE: this is not necessarily valid immediately after calling Init, as // Init starts the process asynchronously. It's guaranteed to be valid after // the first IPC arrives. virtual base::ProcessHandle GetHandle() = 0; // Transport DIB functions --------------------------------------------------- // Return the TransportDIB for the given id. On Linux, this can involve // mapping shared memory. On Mac, the shared memory is created in the browser // process and the cached metadata is returned. On Windows, this involves // duplicating the handle from the remote process. The RenderProcessHost // still owns the returned DIB. virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) = 0; // Static management functions ----------------------------------------------- // Flag to run the renderer in process. This is primarily // for debugging purposes. When running "in process", the // browser maintains a single RenderProcessHost which communicates // to a RenderProcess which is instantiated in the same process // with the Browser. All IPC between the Browser and the // Renderer is the same, it's just not crossing a process boundary. static bool run_renderer_in_process() { return run_renderer_in_process_; } static void set_run_renderer_in_process(bool value) { run_renderer_in_process_ = value; } // Allows iteration over all the RenderProcessHosts in the browser. Note // that each host may not be active, and therefore may have NULL channels. static iterator AllHostsIterator(); // Returns the RenderProcessHost given its ID. Returns NULL if the ID does // not correspond to a live RenderProcessHost. static RenderProcessHost* FromID(int render_process_id); // Returns true if the caller should attempt to use an existing // RenderProcessHost rather than creating a new one. static bool ShouldTryToUseExistingProcessHost(); // Get an existing RenderProcessHost associated with the given profile, if // possible. The renderer process is chosen randomly from suitable renderers // that share the same profile and type. // Returns NULL if no suitable renderer process is available, in which case // the caller is free to create a new renderer. static RenderProcessHost* GetExistingProcessHost(Profile* profile, Type type); // Overrides the default heuristic for limiting the max renderer process // count. This is useful for unit testing process limit behaviors. // A value of zero means to use the default heuristic. static void SetMaxRendererProcessCount(size_t count); protected: // A proxy for our IPC::Channel that lives on the IO thread (see // browser_process.h) scoped_ptr<IPC::SyncChannel> channel_; // The registered listeners. When this list is empty or all NULL, we should // delete ourselves IDMap<IPC::Channel::Listener> listeners_; // The maximum page ID we've ever seen from the renderer process. int32 max_page_id_; // True if fast shutdown has been performed on this RPH. bool fast_shutdown_started_; // True if we've posted a DeleteTask and will be deleted soon. bool deleting_soon_; private: // The globally-unique identifier for this RPH. int id_; Profile* profile_; // set of listeners that expect the renderer process to close std::set<int> listeners_expecting_close_; // True if the process can be shut down suddenly. If this is true, then we're // sure that all the RenderViews in the process can be shutdown suddenly. If // it's false, then specific RenderViews might still be allowed to be shutdown // suddenly by checking their SuddenTerminationAllowed() flag. This can occur // if one tab has an unload event listener but another tab in the same process // doesn't. bool sudden_termination_allowed_; // Set to true if we shouldn't send input events. We actually do the // filtering for this at the render widget level. bool ignore_input_events_; // See getter above. static bool run_renderer_in_process_; // Records the last time we regarded the child process active. base::TimeTicks child_process_activity_time_; DISALLOW_COPY_AND_ASSIGN(RenderProcessHost); }; // Factory object for RenderProcessHosts. Using this factory allows tests to // swap out a different one to use a TestRenderProcessHost. class RenderProcessHostFactory { public: virtual ~RenderProcessHostFactory() {} virtual RenderProcessHost* CreateRenderProcessHost( Profile* profile) const = 0; }; #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_
Java
package org.scalameter import org.scalameter.examples.BoxingCountBench import org.scalameter.examples.MethodInvocationCountBench class BoxingCountBenchTest extends InvocationCountMeasurerTest { test("BoxingCountTest.all should be deterministic") { checkInvocationCountMeasurerTest(new BoxingCountBench) } } class MethodInvocationCountBenchTest extends InvocationCountMeasurerTest { test("MethodInvocationCountTest.allocations should be deterministic") { checkInvocationCountMeasurerTest(new MethodInvocationCountBench) } }
Java
define(["require"], function (require) { function boot(ev) { ev.target.removeEventListener("click", boot); require(["demos/water/water"]); } const start = document.querySelector(".code-demo.water [data-trigger='water.start']"); start.addEventListener("click", boot); start.disabled = false; });
Java
#locale-settings { margin-top: 30px; } #preferred-locale { margin-top: 10px; } #locale-settings .label { color: #aaa; display: inline-block; font-size: 16px; font-weight: 300; margin: 6px 10px 0 0; text-align: right; width: 280px; vertical-align: top; } #locale-settings .locale-selector { display: inline-block; } #locale-settings .locale-selector .locale.select { width: 280px; } #locale-settings .locale-selector .locale.select .button { background: #272a2f; color: #aaaaaa; font-size: 16px; font-weight: 400; height: 36px; margin: 0; padding: 8px 12px; width: 100%; } #locale-settings .locale-selector .locale.select .menu { background: #272a2f; border: 1px solid #333941; border-top: none; top: 36px; left: -1px; width: 282px; z-index: 30; } #main form { margin: 0 auto; } #main form section { margin: 0 auto 70px; } #main form section h3 { margin-bottom: 20px; } #main .controls .cancel { float: none; margin: 9px; } #profile-form { display: block; position: relative; text-align: left; width: 620px; } #profile-form .field { text-align: left; } #profile-form .field:not(:last-child) { margin-bottom: 20px; } #profile-form .field input { color: #ffffff; background: #333941; border: 1px solid #4d5967; border-radius: 3px; float: none; width: 290px; padding: 4px; -moz-box-sizing: border-box; box-sizing: border-box; } #profile-form button { margin-top: 10px; } #profile-form .help { color: #888888; font-style: italic; margin-top: 5px; } .errorlist { color: #f36; list-style: none; margin: 0; margin-top: 5px; text-align: left; } .check-list { cursor: pointer; }
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__char_connect_socket_w32CreateFile_66a.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-66a.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed file name * Sinks: w32CreateFile * BadSink : Open the file named in data using CreateFile() * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH "c:\\temp\\" #else #include <wchar.h> #define BASEPATH "/tmp/" #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" namespace CWE23_Relative_Path_Traversal__char_connect_socket_w32CreateFile_66 { #ifndef OMITBAD /* bad function declaration */ void badSink(char * dataArray[]); void bad() { char * data; char * dataArray[5]; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } /* put data in array */ dataArray[2] = data; badSink(dataArray); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(char * dataArray[]); static void goodG2B() { char * data; char * dataArray[5]; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; /* FIX: Use a fixed file name */ strcat(data, "file.txt"); dataArray[2] = data; goodG2BSink(dataArray); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE23_Relative_Path_Traversal__char_connect_socket_w32CreateFile_66; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
Java
/* * Copyright (c) 2014 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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 copyright holders 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 * 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. * * Authors: Andreas Sandberg */ #include "debug/VIOPci.hh" #include "dev/virtio/pci.hh" #include "mem/packet_access.hh" #include "params/PciVirtIO.hh" PciVirtIO::PciVirtIO(const Params *params) : PciDevice(params), queueNotify(0), interruptDeliveryPending(false), vio(*params->vio), callbackKick(this) { // Override the subsystem ID with the device ID from VirtIO config.subsystemID = htole(vio.deviceId); BARSize[0] = BAR0_SIZE_BASE + vio.configSize; vio.registerKickCallback(&callbackKick); } PciVirtIO::~PciVirtIO() { } Tick PciVirtIO::read(PacketPtr pkt) { const unsigned M5_VAR_USED size(pkt->getSize()); int bar; Addr offset; if (!getBAR(pkt->getAddr(), bar, offset)) panic("Invalid PCI memory access to unmapped memory.\n"); assert(bar == 0); DPRINTF(VIOPci, "Reading offset 0x%x [len: %i]\n", offset, size); // Forward device configuration writes to the device VirtIO model if (offset >= OFF_VIO_DEVICE) { vio.readConfig(pkt, offset - OFF_VIO_DEVICE); return 0; } pkt->makeResponse(); switch(offset) { case OFF_DEVICE_FEATURES: DPRINTF(VIOPci, " DEVICE_FEATURES request\n"); assert(size == sizeof(uint32_t)); pkt->set<uint32_t>(vio.deviceFeatures); break; case OFF_GUEST_FEATURES: DPRINTF(VIOPci, " GUEST_FEATURES request\n"); assert(size == sizeof(uint32_t)); pkt->set<uint32_t>(vio.getGuestFeatures()); break; case OFF_QUEUE_ADDRESS: DPRINTF(VIOPci, " QUEUE_ADDRESS request\n"); assert(size == sizeof(uint32_t)); pkt->set<uint32_t>(vio.getQueueAddress()); break; case OFF_QUEUE_SIZE: DPRINTF(VIOPci, " QUEUE_SIZE request\n"); assert(size == sizeof(uint16_t)); pkt->set<uint16_t>(vio.getQueueSize()); break; case OFF_QUEUE_SELECT: DPRINTF(VIOPci, " QUEUE_SELECT\n"); assert(size == sizeof(uint16_t)); pkt->set<uint16_t>(vio.getQueueSelect()); break; case OFF_QUEUE_NOTIFY: DPRINTF(VIOPci, " QUEUE_NOTIFY request\n"); assert(size == sizeof(uint16_t)); pkt->set<uint16_t>(queueNotify); break; case OFF_DEVICE_STATUS: DPRINTF(VIOPci, " DEVICE_STATUS request\n"); assert(size == sizeof(uint8_t)); pkt->set<uint8_t>(vio.getDeviceStatus()); break; case OFF_ISR_STATUS: { DPRINTF(VIOPci, " ISR_STATUS\n"); assert(size == sizeof(uint8_t)); uint8_t isr_status(interruptDeliveryPending ? 1 : 0); interruptDeliveryPending = false; pkt->set<uint8_t>(isr_status); } break; default: panic("Unhandled read offset (0x%x)\n", offset); } return 0; } Tick PciVirtIO::write(PacketPtr pkt) { const unsigned M5_VAR_USED size(pkt->getSize()); int bar; Addr offset; if (!getBAR(pkt->getAddr(), bar, offset)) panic("Invalid PCI memory access to unmapped memory.\n"); assert(bar == 0); DPRINTF(VIOPci, "Writing offset 0x%x [len: %i]\n", offset, size); // Forward device configuration writes to the device VirtIO model if (offset >= OFF_VIO_DEVICE) { vio.writeConfig(pkt, offset - OFF_VIO_DEVICE); return 0; } pkt->makeResponse(); switch(offset) { case OFF_DEVICE_FEATURES: warn("Guest tried to write device features."); break; case OFF_GUEST_FEATURES: DPRINTF(VIOPci, " WRITE GUEST_FEATURES request\n"); assert(size == sizeof(uint32_t)); vio.setGuestFeatures(pkt->get<uint32_t>()); break; case OFF_QUEUE_ADDRESS: DPRINTF(VIOPci, " WRITE QUEUE_ADDRESS\n"); assert(size == sizeof(uint32_t)); vio.setQueueAddress(pkt->get<uint32_t>()); break; case OFF_QUEUE_SIZE: panic("Guest tried to write queue size."); break; case OFF_QUEUE_SELECT: DPRINTF(VIOPci, " WRITE QUEUE_SELECT\n"); assert(size == sizeof(uint16_t)); vio.setQueueSelect(pkt->get<uint16_t>()); break; case OFF_QUEUE_NOTIFY: DPRINTF(VIOPci, " WRITE QUEUE_NOTIFY\n"); assert(size == sizeof(uint16_t)); queueNotify = pkt->get<uint16_t>(); vio.onNotify(queueNotify); break; case OFF_DEVICE_STATUS: { assert(size == sizeof(uint8_t)); uint8_t status(pkt->get<uint8_t>()); DPRINTF(VIOPci, "VirtIO set status: 0x%x\n", status); vio.setDeviceStatus(status); } break; case OFF_ISR_STATUS: warn("Guest tried to write ISR status."); break; default: panic("Unhandled read offset (0x%x)\n", offset); } return 0; } void PciVirtIO::kick() { DPRINTF(VIOPci, "kick(): Sending interrupt...\n"); interruptDeliveryPending = true; intrPost(); } PciVirtIO * PciVirtIOParams::create() { return new PciVirtIO(this); }
Java
/* $NetBSD: ecoff_machdep.h,v 1.1 2002/03/13 05:03:18 simonb Exp $ */ #include <mips/ecoff_machdep.h>
Java
\documentclass{jarticle} \usepackage{plext} \usepackage{calc} \begin{document} %% cf. latex.ltx macros (from ltboxes) あいうえお\makebox[60pt]{かきく}さしすせそ\par あいうえお\makebox[-30pt]{かきく}さしすせそ\par % calc extension check あいうえお\makebox[60pt+10pt]{かきく}さしすせそ\par あいうえお\makebox[-30pt/2*3]{かきく}さしすせそ\par % robustness \section{あいうえお\makebox[60pt]{かきく}さしすせそ} \section{あいうえお\makebox[-30pt]{かきく}さしすせそ} %% plext.sty macros あいうえお\pbox[60pt]{かきく}さしすせそ\par あいうえお\pbox[-30pt]{かきく}さしすせそ\par % natural width % calc extension check あいうえお\pbox[60pt+10pt]{かきく}さしすせそ\par あいうえお\pbox[-30pt/2*3]{かきく}さしすせそ\par % natural width % robustness \section{あいうえお\pbox<t>[60pt]{かきく}さしすせそ} \section{あいうえお\pbox<t>[-30pt]{かきく}さしすせそ} \end{document}
Java
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * 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 [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Adminhtml * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class Mage_Adminhtml_Block_Permissions_Tab_Rolesusers extends Mage_Adminhtml_Block_Widget_Tabs { public function __construct() { parent::__construct(); $roleId = $this->getRequest()->getParam('rid', false); $users = Mage::getModel("admin/user")->getCollection()->load(); $this->setTemplate('permissions/rolesusers.phtml') ->assign('users', $users->getItems()) ->assign('roleId', $roleId); } protected function _prepareLayout() { $this->setChild('userGrid', $this->getLayout()->createBlock('adminhtml/permissions_role_grid_user', 'roleUsersGrid')); return parent::_prepareLayout(); } protected function _getGridHtml() { return $this->getChildHtml('userGrid'); } protected function _getJsObjectName() { return $this->getChild('userGrid')->getJsObjectName(); } }
Java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_free_long_84_goodB2G.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_free.label.xml Template File: sources-sinks-84_goodB2G.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete * BadSink : Deallocate data using free() * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE762_Mismatched_Memory_Management_Routines__new_free_long_84.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_free_long_84 { CWE762_Mismatched_Memory_Management_Routines__new_free_long_84_goodB2G::CWE762_Mismatched_Memory_Management_Routines__new_free_long_84_goodB2G(long * dataCopy) { data = dataCopy; /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new long; } CWE762_Mismatched_Memory_Management_Routines__new_free_long_84_goodB2G::~CWE762_Mismatched_Memory_Management_Routines__new_free_long_84_goodB2G() { /* FIX: Deallocate the memory using delete */ delete data; } } #endif /* OMITGOOD */
Java
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "ERANAMES": [ "Before Christ", "Anno Domini" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "STANDALONEMONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "d/M/yy h:mm a", "shortDate": "d/M/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-jm", "localeID": "en_JM", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
Java
/* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. */ /* * bufpool.c++ * * $Date: 2004/05/12 15:29:36 $ $Revision: 1.2 $ * $Header: /home/krh/git/sync/mesa-cvs-repo/Mesa/src/glu/sgi/libnurbs/internals/bufpool.cc,v 1.2 2004/05/12 15:29:36 brianp Exp $ */ #include "glimports.h" #include "myassert.h" #include "bufpool.h" /*----------------------------------------------------------------------------- * Pool - allocate a new pool of buffers *----------------------------------------------------------------------------- */ Pool::Pool( int _buffersize, int initpoolsize, const char *n ) { if((unsigned)_buffersize < sizeof(Buffer)) buffersize = sizeof(Buffer); else buffersize = _buffersize; initsize = initpoolsize * buffersize; nextsize = initsize; name = n; magic = is_allocated; nextblock = 0; curblock = 0; freelist = 0; nextfree = 0; } /*----------------------------------------------------------------------------- * ~Pool - free a pool of buffers and the pool itself *----------------------------------------------------------------------------- */ Pool::~Pool( void ) { assert( (this != 0) && (magic == is_allocated) ); while( nextblock ) { delete [] blocklist[--nextblock]; blocklist[nextblock] = 0; } magic = is_free; } void Pool::grow( void ) { assert( (this != 0) && (magic == is_allocated) ); curblock = new char[nextsize]; blocklist[nextblock++] = curblock; nextfree = nextsize; nextsize *= 2; } /*----------------------------------------------------------------------------- * Pool::clear - free buffers associated with pool but keep pool *----------------------------------------------------------------------------- */ void Pool::clear( void ) { assert( (this != 0) && (magic == is_allocated) ); while( nextblock ) { delete [] blocklist[--nextblock]; blocklist[nextblock] = 0; } curblock = 0; freelist = 0; nextfree = 0; if( nextsize > initsize ) nextsize /= 2; }
Java
#ifndef fl_gl_cyclic_color_wheel_h #define fl_gl_cyclic_color_wheel_h #include <FL/gl.h> /* GLfloat GLubyte GLuint GLenum */ #include <FL/Fl.H> #include <FL/Fl_Gl_Window.H> #include <FL/Fl_Value_Input.H> #include <FL/Fl_Check_Button.H> class fl_gl_cyclic_color_wheel : public Fl_Gl_Window { public: fl_gl_cyclic_color_wheel(int x,int y ,int w,int h ,const char*l=0); void init_widget_set( const int number ,Fl_Value_Input* valinp_hue_min ,Fl_Value_Input* valinp_hue_max ,Fl_Check_Button* chebut_enable_sw ,Fl_Check_Button* chebut_rotate360_sw ); void init_number_and_is_max( const int number ,const bool is_max); void set_min_or_max(const bool is_max ); void set_reset(void); private: /* マウスドラッグ開始位置 */ int mouse_x_when_push_ ,mouse_y_when_push_; /* Hue Color Wheel表示開始位置 */ double x_offset_; double hue_offset_; /* 各Hue min,maxの範囲を参考表示 */ class guide_widget_set_ { public: Fl_Value_Input* valinp_hue_min; Fl_Value_Input* valinp_hue_max; Fl_Check_Button* chebut_enable_sw; Fl_Check_Button* chebut_rotate360_sw; }; std::vector< guide_widget_set_ > guide_widget_sets_; int hue_range_number_; bool hue_range_is_max_; //---------- void draw(); void draw_object_(); int handle(int event); void handle_push_( const int mx ,const int my ); void handle_updownleftright_( const int mx ,const int my ); void handle_keyboard_( const int key , const char* text ); double xpos_from_hue_(const double hue); double hue_from_xpos_(const double xpos); double limit_new_hue_( double hue_o_new ,bool& rotate360_sw ); void set_min_or_max_to_gui_( const bool rot360_sw ); }; #endif /* !fl_gl_cyclic_color_wheel_h */
Java
from django.apps import AppConfig class ContentStoreAppConfig(AppConfig): name = "contentstore" def ready(self): import contentstore.signals contentstore.signals
Java
// 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 "base/prefs/json_pref_store.h" #include <algorithm> #include "base/bind.h" #include "base/callback.h" #include "base/file_util.h" #include "base/json/json_file_value_serializer.h" #include "base/json/json_string_value_serializer.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop_proxy.h" #include "base/sequenced_task_runner.h" #include "base/threading/sequenced_worker_pool.h" #include "base/values.h" namespace { // Some extensions we'll tack on to copies of the Preferences files. const base::FilePath::CharType* kBadExtension = FILE_PATH_LITERAL("bad"); // Differentiates file loading between origin thread and passed // (aka file) thread. class FileThreadDeserializer : public base::RefCountedThreadSafe<FileThreadDeserializer> { public: FileThreadDeserializer(JsonPrefStore* delegate, base::SequencedTaskRunner* sequenced_task_runner) : no_dir_(false), error_(PersistentPrefStore::PREF_READ_ERROR_NONE), delegate_(delegate), sequenced_task_runner_(sequenced_task_runner), origin_loop_proxy_(base::MessageLoopProxy::current()) { } void Start(const base::FilePath& path) { DCHECK(origin_loop_proxy_->BelongsToCurrentThread()); sequenced_task_runner_->PostTask( FROM_HERE, base::Bind(&FileThreadDeserializer::ReadFileAndReport, this, path)); } // Deserializes JSON on the sequenced task runner. void ReadFileAndReport(const base::FilePath& path) { DCHECK(sequenced_task_runner_->RunsTasksOnCurrentThread()); value_.reset(DoReading(path, &error_, &no_dir_)); origin_loop_proxy_->PostTask( FROM_HERE, base::Bind(&FileThreadDeserializer::ReportOnOriginThread, this)); } // Reports deserialization result on the origin thread. void ReportOnOriginThread() { DCHECK(origin_loop_proxy_->BelongsToCurrentThread()); delegate_->OnFileRead(value_.release(), error_, no_dir_); } static base::Value* DoReading(const base::FilePath& path, PersistentPrefStore::PrefReadError* error, bool* no_dir) { int error_code; std::string error_msg; JSONFileValueSerializer serializer(path); base::Value* value = serializer.Deserialize(&error_code, &error_msg); HandleErrors(value, path, error_code, error_msg, error); *no_dir = !base::PathExists(path.DirName()); return value; } static void HandleErrors(const base::Value* value, const base::FilePath& path, int error_code, const std::string& error_msg, PersistentPrefStore::PrefReadError* error); private: friend class base::RefCountedThreadSafe<FileThreadDeserializer>; ~FileThreadDeserializer() {} bool no_dir_; PersistentPrefStore::PrefReadError error_; scoped_ptr<base::Value> value_; const scoped_refptr<JsonPrefStore> delegate_; const scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_; const scoped_refptr<base::MessageLoopProxy> origin_loop_proxy_; }; // static void FileThreadDeserializer::HandleErrors( const base::Value* value, const base::FilePath& path, int error_code, const std::string& error_msg, PersistentPrefStore::PrefReadError* error) { *error = PersistentPrefStore::PREF_READ_ERROR_NONE; if (!value) { DVLOG(1) << "Error while loading JSON file: " << error_msg << ", file: " << path.value(); switch (error_code) { case JSONFileValueSerializer::JSON_ACCESS_DENIED: *error = PersistentPrefStore::PREF_READ_ERROR_ACCESS_DENIED; break; case JSONFileValueSerializer::JSON_CANNOT_READ_FILE: *error = PersistentPrefStore::PREF_READ_ERROR_FILE_OTHER; break; case JSONFileValueSerializer::JSON_FILE_LOCKED: *error = PersistentPrefStore::PREF_READ_ERROR_FILE_LOCKED; break; case JSONFileValueSerializer::JSON_NO_SUCH_FILE: *error = PersistentPrefStore::PREF_READ_ERROR_NO_FILE; break; default: *error = PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE; // JSON errors indicate file corruption of some sort. // Since the file is corrupt, move it to the side and continue with // empty preferences. This will result in them losing their settings. // We keep the old file for possible support and debugging assistance // as well as to detect if they're seeing these errors repeatedly. // TODO(erikkay) Instead, use the last known good file. base::FilePath bad = path.ReplaceExtension(kBadExtension); // If they've ever had a parse error before, put them in another bucket. // TODO(erikkay) if we keep this error checking for very long, we may // want to differentiate between recent and long ago errors. if (base::PathExists(bad)) *error = PersistentPrefStore::PREF_READ_ERROR_JSON_REPEAT; base::Move(path, bad); break; } } else if (!value->IsType(base::Value::TYPE_DICTIONARY)) { *error = PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE; } } } // namespace scoped_refptr<base::SequencedTaskRunner> JsonPrefStore::GetTaskRunnerForFile( const base::FilePath& filename, base::SequencedWorkerPool* worker_pool) { std::string token("json_pref_store-"); token.append(filename.AsUTF8Unsafe()); return worker_pool->GetSequencedTaskRunnerWithShutdownBehavior( worker_pool->GetNamedSequenceToken(token), base::SequencedWorkerPool::BLOCK_SHUTDOWN); } JsonPrefStore::JsonPrefStore(const base::FilePath& filename, base::SequencedTaskRunner* sequenced_task_runner) : path_(filename), sequenced_task_runner_(sequenced_task_runner), prefs_(new base::DictionaryValue()), read_only_(false), writer_(filename, sequenced_task_runner), initialized_(false), read_error_(PREF_READ_ERROR_OTHER) {} bool JsonPrefStore::GetValue(const std::string& key, const base::Value** result) const { base::Value* tmp = NULL; if (!prefs_->Get(key, &tmp)) return false; if (result) *result = tmp; return true; } void JsonPrefStore::AddObserver(PrefStore::Observer* observer) { observers_.AddObserver(observer); } void JsonPrefStore::RemoveObserver(PrefStore::Observer* observer) { observers_.RemoveObserver(observer); } bool JsonPrefStore::HasObservers() const { return observers_.might_have_observers(); } bool JsonPrefStore::IsInitializationComplete() const { return initialized_; } bool JsonPrefStore::GetMutableValue(const std::string& key, base::Value** result) { return prefs_->Get(key, result); } void JsonPrefStore::SetValue(const std::string& key, base::Value* value) { DCHECK(value); scoped_ptr<base::Value> new_value(value); base::Value* old_value = NULL; prefs_->Get(key, &old_value); if (!old_value || !value->Equals(old_value)) { prefs_->Set(key, new_value.release()); ReportValueChanged(key); } } void JsonPrefStore::SetValueSilently(const std::string& key, base::Value* value) { DCHECK(value); scoped_ptr<base::Value> new_value(value); base::Value* old_value = NULL; prefs_->Get(key, &old_value); if (!old_value || !value->Equals(old_value)) { prefs_->Set(key, new_value.release()); if (!read_only_) writer_.ScheduleWrite(this); } } void JsonPrefStore::RemoveValue(const std::string& key) { if (prefs_->Remove(key, NULL)) ReportValueChanged(key); } void JsonPrefStore::MarkNeedsEmptyValue(const std::string& key) { keys_need_empty_value_.insert(key); } bool JsonPrefStore::ReadOnly() const { return read_only_; } PersistentPrefStore::PrefReadError JsonPrefStore::GetReadError() const { return read_error_; } PersistentPrefStore::PrefReadError JsonPrefStore::ReadPrefs() { if (path_.empty()) { OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false); return PREF_READ_ERROR_FILE_NOT_SPECIFIED; } PrefReadError error; bool no_dir; base::Value* value = FileThreadDeserializer::DoReading(path_, &error, &no_dir); OnFileRead(value, error, no_dir); return error; } void JsonPrefStore::ReadPrefsAsync(ReadErrorDelegate *error_delegate) { initialized_ = false; error_delegate_.reset(error_delegate); if (path_.empty()) { OnFileRead(NULL, PREF_READ_ERROR_FILE_NOT_SPECIFIED, false); return; } // Start async reading of the preferences file. It will delete itself // in the end. scoped_refptr<FileThreadDeserializer> deserializer( new FileThreadDeserializer(this, sequenced_task_runner_.get())); deserializer->Start(path_); } void JsonPrefStore::CommitPendingWrite() { if (writer_.HasPendingWrite() && !read_only_) writer_.DoScheduledWrite(); } void JsonPrefStore::ReportValueChanged(const std::string& key) { FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnPrefValueChanged(key)); if (!read_only_) writer_.ScheduleWrite(this); } void JsonPrefStore::OnFileRead(base::Value* value_owned, PersistentPrefStore::PrefReadError error, bool no_dir) { scoped_ptr<base::Value> value(value_owned); read_error_ = error; if (no_dir) { FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnInitializationCompleted(false)); return; } initialized_ = true; switch (error) { case PREF_READ_ERROR_ACCESS_DENIED: case PREF_READ_ERROR_FILE_OTHER: case PREF_READ_ERROR_FILE_LOCKED: case PREF_READ_ERROR_JSON_TYPE: case PREF_READ_ERROR_FILE_NOT_SPECIFIED: read_only_ = true; break; case PREF_READ_ERROR_NONE: DCHECK(value.get()); prefs_.reset(static_cast<base::DictionaryValue*>(value.release())); break; case PREF_READ_ERROR_NO_FILE: // If the file just doesn't exist, maybe this is first run. In any case // there's no harm in writing out default prefs in this case. break; case PREF_READ_ERROR_JSON_PARSE: case PREF_READ_ERROR_JSON_REPEAT: break; default: NOTREACHED() << "Unknown error: " << error; } if (error_delegate_.get() && error != PREF_READ_ERROR_NONE) error_delegate_->OnError(error); FOR_EACH_OBSERVER(PrefStore::Observer, observers_, OnInitializationCompleted(true)); } JsonPrefStore::~JsonPrefStore() { CommitPendingWrite(); } bool JsonPrefStore::SerializeData(std::string* output) { // TODO(tc): Do we want to prune webkit preferences that match the default // value? JSONStringValueSerializer serializer(output); serializer.set_pretty_print(true); scoped_ptr<base::DictionaryValue> copy( prefs_->DeepCopyWithoutEmptyChildren()); // Iterates |keys_need_empty_value_| and if the key exists in |prefs_|, // ensure its empty ListValue or DictonaryValue is preserved. for (std::set<std::string>::const_iterator it = keys_need_empty_value_.begin(); it != keys_need_empty_value_.end(); ++it) { const std::string& key = *it; base::Value* value = NULL; if (!prefs_->Get(key, &value)) continue; if (value->IsType(base::Value::TYPE_LIST)) { const base::ListValue* list = NULL; if (value->GetAsList(&list) && list->empty()) copy->Set(key, new base::ListValue); } else if (value->IsType(base::Value::TYPE_DICTIONARY)) { const base::DictionaryValue* dict = NULL; if (value->GetAsDictionary(&dict) && dict->empty()) copy->Set(key, new base::DictionaryValue); } } return serializer.Serialize(*(copy.get())); }
Java
<?php /** * Zym Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * * @category Zym * @package Zym_View * @subpackage Helper * @copyright Copyright (c) 2008 Zym. (http://www.zym-project.com/) * @license http://www.zym-project.com/license New BSD License */ /** * @see Zend_Controller_Front */ require_once 'Zend/Controller/Front.php'; /** * Get response obj * * @author Geoffrey Tran * @license http://www.zym-project.com/license New BSD License * @package Zym_View * @subpackage Helper * @copyright Copyright (c) 2008 Zym. (http://www.zym-project.com/) */ class Zym_View_Helper_GetResponse { /** * Get the response object * * @return Zend_Controller_Response_Abstract */ public function getResponse() { return Zend_Controller_Front::getInstance()->getResponse(); } }
Java
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * 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 [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_XmlConnect * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Xmlconnect form checkbox element * * @category Mage * @package Mage_XmlConnect * @author Magento Core Team <[email protected]> */ class Mage_XmlConnect_Model_Simplexml_Form_Element_Checkbox extends Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract { /** * Init checkbox element * * @param array $attributes */ public function __construct($attributes = array()) { parent::__construct($attributes); $this->setType('checkbox'); } /** * Add value to element * * @param Mage_XmlConnect_Model_Simplexml_Element $xmlObj * @return Mage_XmlConnect_Model_Simplexml_Form_Element_Abstract */ protected function _addValue(Mage_XmlConnect_Model_Simplexml_Element $xmlObj) { $xmlObj->addAttribute('value', (int)$this->getValue()); return $this; } }
Java
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * 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 [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Catalog * @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Catalog product option values collection * * @category Mage * @package Mage_Catalog * @author Magento Core Team <[email protected]> */ class Mage_Catalog_Model_Resource_Product_Option_Value_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract { /** * Resource initialization */ protected function _construct() { $this->_init('catalog/product_option_value'); } /** * Add price, title to result * * @param int $storeId * @return Mage_Catalog_Model_Resource_Product_Option_Value_Collection */ public function getValues($storeId) { $this->addPriceToResult($storeId) ->addTitleToResult($storeId); return $this; } /** * Add titles to result * * @param int $storeId * @return Mage_Catalog_Model_Resource_Product_Option_Value_Collection */ public function addTitlesToResult($storeId) { $adapter = $this->getConnection(); $optionTypePriceTable = $this->getTable('catalog/product_option_type_price'); $optionTitleTable = $this->getTable('catalog/product_option_type_title'); $priceExpr = $adapter->getCheckSql( 'store_value_price.price IS NULL', 'default_value_price.price', 'store_value_price.price' ); $priceTypeExpr = $adapter->getCheckSql( 'store_value_price.price_type IS NULL', 'default_value_price.price_type', 'store_value_price.price_type' ); $titleExpr = $adapter->getCheckSql( 'store_value_title.title IS NULL', 'default_value_title.title', 'store_value_title.title' ); $joinExprDefaultPrice = 'default_value_price.option_type_id = main_table.option_type_id AND ' . $adapter->quoteInto('default_value_price.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID); $joinExprStorePrice = 'store_value_price.option_type_id = main_table.option_type_id AND ' . $adapter->quoteInto('store_value_price.store_id = ?', $storeId); $joinExprTitle = 'store_value_title.option_type_id = main_table.option_type_id AND ' . $adapter->quoteInto('store_value_title.store_id = ?', $storeId); $this->getSelect() ->joinLeft( array('default_value_price' => $optionTypePriceTable), $joinExprDefaultPrice, array('default_price'=>'price','default_price_type'=>'price_type') ) ->joinLeft( array('store_value_price' => $optionTypePriceTable), $joinExprStorePrice, array( 'store_price' => 'price', 'store_price_type' => 'price_type', 'price' => $priceExpr, 'price_type' => $priceTypeExpr ) ) ->join( array('default_value_title' => $optionTitleTable), 'default_value_title.option_type_id = main_table.option_type_id', array('default_title' => 'title') ) ->joinLeft( array('store_value_title' => $optionTitleTable), $joinExprTitle, array( 'store_title' => 'title', 'title' => $titleExpr) ) ->where('default_value_title.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID); return $this; } /** * Add title result * * @param int $storeId * @return Mage_Catalog_Model_Resource_Product_Option_Value_Collection */ public function addTitleToResult($storeId) { $optionTitleTable = $this->getTable('catalog/product_option_type_title'); $titleExpr = $this->getConnection() ->getCheckSql('store_value_title.title IS NULL', 'default_value_title.title', 'store_value_title.title'); $joinExpr = 'store_value_title.option_type_id = main_table.option_type_id AND ' . $this->getConnection()->quoteInto('store_value_title.store_id = ?', $storeId); $this->getSelect() ->join( array('default_value_title' => $optionTitleTable), 'default_value_title.option_type_id = main_table.option_type_id', array('default_title' => 'title') ) ->joinLeft( array('store_value_title' => $optionTitleTable), $joinExpr, array( 'store_title' => 'title', 'title' => $titleExpr ) ) ->where('default_value_title.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID); return $this; } /** * Add price to result * * @param int $storeId * @return Mage_Catalog_Model_Resource_Product_Option_Value_Collection */ public function addPriceToResult($storeId) { $optionTypeTable = $this->getTable('catalog/product_option_type_price'); $priceExpr = $this->getConnection() ->getCheckSql('store_value_price.price IS NULL', 'default_value_price.price', 'store_value_price.price'); $priceTypeExpr = $this->getConnection() ->getCheckSql( 'store_value_price.price_type IS NULL', 'default_value_price.price_type', 'store_value_price.price_type' ); $joinExprDefault = 'default_value_price.option_type_id = main_table.option_type_id AND ' . $this->getConnection()->quoteInto('default_value_price.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID); $joinExprStore = 'store_value_price.option_type_id = main_table.option_type_id AND ' . $this->getConnection()->quoteInto('store_value_price.store_id = ?', $storeId); $this->getSelect() ->joinLeft( array('default_value_price' => $optionTypeTable), $joinExprDefault, array( 'default_price' => 'price', 'default_price_type'=>'price_type' ) ) ->joinLeft( array('store_value_price' => $optionTypeTable), $joinExprStore, array( 'store_price' => 'price', 'store_price_type' => 'price_type', 'price' => $priceExpr, 'price_type' => $priceTypeExpr ) ); return $this; } /** * Add option filter * * @param array $optionIds * @param int $storeId * @return Mage_Catalog_Model_Resource_Product_Option_Value_Collection */ public function getValuesByOption($optionIds, $storeId = null) { if (!is_array($optionIds)) { $optionIds = array($optionIds); } return $this->addFieldToFilter('main_table.option_type_id', array('in' => $optionIds)); } /** * Add option to filter * * @param array|Mage_Catalog_Model_Product_Option|int $option * @return Mage_Catalog_Model_Resource_Product_Option_Value_Collection */ public function addOptionToFilter($option) { if (empty($option)) { $this->addFieldToFilter('option_id', ''); } elseif (is_array($option)) { $this->addFieldToFilter('option_id', array('in' => $option)); } elseif ($option instanceof Mage_Catalog_Model_Product_Option) { $this->addFieldToFilter('option_id', $option->getId()); } else { $this->addFieldToFilter('option_id', $option); } return $this; } }
Java
# -*- coding: utf-8 -*- """Git tools.""" from shlex import split from plumbum import ProcessExecutionError from plumbum.cmd import git DEVELOPMENT_BRANCH = "develop" def run_git(*args, dry_run=False, quiet=False): """Run a git command, print it before executing and capture the output.""" command = git[split(" ".join(args))] if not quiet: print("{}{}".format("[DRY-RUN] " if dry_run else "", command)) if dry_run: return "" rv = command() if not quiet and rv: print(rv) return rv def branch_exists(branch): """Return True if the branch exists.""" try: run_git("rev-parse --verify {}".format(branch), quiet=True) return True except ProcessExecutionError: return False def get_current_branch(): """Get the current branch name.""" return run_git("rev-parse --abbrev-ref HEAD", quiet=True).strip()
Java
package testclasses; import de.unifreiburg.cs.proglang.jgs.support.DynamicLabel; import util.printer.SecurePrinter; public class PrintMediumSuccess { public static void main(String[] args) { String med = "This is medium information"; med = DynamicLabel.makeMedium(med); SecurePrinter.printMedium(med); String low = "This is low information"; low = DynamicLabel.makeLow(low); SecurePrinter.printMedium(low); } }
Java
define(["pat-autoscale", "jquery"], function(pattern, jQuery) { describe("pat-autoscale", function() { beforeEach(function() { $("<div/>", {id: "lab"}).appendTo(document.body); $(window).off(".autoscale"); }); afterEach(function() { $("#lab").remove(); }); describe("setup", function() { var force_method, mozilla, msie, version; beforeEach(function() { force_method=pattern.force_method; mozilla=jQuery.browser.mozilla; msie=jQuery.browser.msie; version=jQuery.browser.version; pattern.force_method=null; jQuery.browser.mozilla=false; jQuery.browser.msie=false; }); afterEach(function() { pattern.force_method=force_method; jQuery.browser.mozilla=mozilla; jQuery.browser.msie=msie; jQuery.browser.version=version; }); it("Force zoom on old IE versions", function() { jQuery.browser.msie=true; jQuery.browser.version="8.192.921"; pattern._setup(); expect(pattern.force_method).toBe("zoom"); }); it("Force nothing on recent IE versions", function() { jQuery.browser.msie=true; jQuery.browser.version="9.0.19A"; pattern._setup(); expect(pattern.force_method).toBe(null); }); it("Force scale on gecko", function() { // See https://bugzilla.mozilla.org/show_bug.cgi?id=390936 jQuery.browser.mozilla=true; pattern._setup(); expect(pattern.force_method).toBe("scale"); }); it("Force nothing on other browsers", function() { pattern._setup(); expect(pattern.force_method).toBe(null); }); }); describe("init", function() { var force_method; beforeEach(function() { force_method=pattern.force_method; }); afterEach(function() { pattern.force_method=force_method; }); it("Return jQuery object", function() { var jq = jasmine.createSpyObj("jQuery", ["each"]); jq.each.andReturn(jq); expect(pattern.init(jq)).toBe(jq); }); it("Perform initial scaling", function() { $("<div/>", {id: "parent"}).css({width: "200px"}) .append($("<div/>", {id: "child", "data-pat-auto-scale": "scale"}) .css({width: "50px"})) .appendTo("#lab"); var $child = $("#child"); spyOn(pattern, "scale"); pattern.init($child); expect(pattern.scale).toHaveBeenCalled(); }); it("Honour method override", function() { $("<div/>", {id: "parent"}).css({width: "200px"}) .append($("<div/>", {id: "child", "data-pat-auto-scale": "scale"}) .css({width: "50px"})) .appendTo("#lab"); var $child = $("#child"); pattern.force_method = "forced"; pattern.init($child); expect($child.data("patterns.auto-scale").method).toBe("forced"); }); }); describe("scale", function() { it("Scale element", function() { $("<div/>", {id: "parent"}).css({width: "200px"}) .append($("<div/>", {id: "child"}).css({width: "50px"})) .appendTo("#lab"); var child = document.getElementById("child"); $(child).data("patterns.auto-scale", {method: "scale", minWidth: 0, maxWidth: 1000}); pattern.scale.apply(child, []); expect(child.getAttribute("style")).toMatch(/transform: scale\(4\);/); }); it("Zoom element", function() { $("<div/>", {id: "parent"}).css({width: "200px"}) .append($("<div/>", {id: "child"}).css({width: "50px"})) .appendTo("#lab"); var child = document.getElementById("child"); $(child).data("patterns.auto-scale", {method: "zoom", minWidth: 0, maxWidth: 1000}); pattern.scale.apply(child, []); expect(child.style.zoom).toBe("4"); }); it("Honour minimum width", function() { $("<div/>", {id: "parent"}).css({width: "100px"}) .append($("<div/>", {id: "child"}).css({width: "400px"})) .appendTo("#lab"); var child = document.getElementById("child"); $(child).data("patterns.auto-scale", {method: "zoom", minWidth: 200, maxWidth: 1000}); pattern.scale.apply(child, []); expect(child.style.zoom).toBe("0.5"); }); it("Honour maximum width", function() { $("<div/>", {id: "parent"}).css({width: "200px"}) .append($("<div/>", {id: "child"}).css({width: "50px"})) .appendTo("#lab"); var child = document.getElementById("child"); $(child).data("patterns.auto-scale", {method: "zoom", minWidth: 0, maxWidth: 100}); pattern.scale.apply(child, []); expect(child.style.zoom).toBe("2"); }); it("Add scaled class", function() { $("<div/>", {id: "parent"}).css({width: "200px"}) .append($("<div/>", {id: "child"}).css({width: "50px"})) .appendTo("#lab"); var child = document.getElementById("child"); $(child).data("patterns.auto-scale", {method: "zoom", minWidth: 0, maxWidth: 1000}); pattern.scale.apply(child, []); expect($(child).hasClass("scaled")).toBeTruthy(); }); }); }); });
Java
require 'spec_helper' RSpec.describe Spree::CheckoutController, type: :controller do # copied from original checkout controller spec let(:token) { 'some_token' } let(:user) { FactoryGirl.create(:user) } let(:order) { OrderWalkthrough.up_to(:delivery) } before do allow_any_instance_of(ActionDispatch::Request).to receive(:remote_ip).and_return("128.0.0.1") allow(controller).to receive(:try_spree_current_user).and_return(user) allow(controller).to receive(:spree_current_user).and_return(user) allow(controller).to receive(:current_order).and_return(order) end describe "PATCH /checkout/update/payment" do context "when payment_method is PayU" do let(:payment_method) { FactoryGirl.create :payu_payment_method } let(:payment_params) do { state: "payment", order: { payments_attributes: [{ payment_method_id: payment_method.id }] } } end subject { spree_post :update, payment_params } before do # we need to fake it because it's returned back with order allow(SecureRandom).to receive(:uuid).and_return("36332498-294f-41a1-980c-7b2ec0e3a8a4") allow(OpenPayU::Configuration).to receive(:merchant_pos_id).and_return("145278") allow(OpenPayU::Configuration).to receive(:signature_key).and_return("S3CRET_KEY") end let(:payu_order_create_status) { "SUCCESS" } let!(:payu_order_create) do stub_request(:post, "https://145278:[email protected]/api/v2/orders") .with(body: { merchantPosId: "145278", customerIp: "128.0.0.1", extOrderId: order.id, description: "Order from Spree Test Store", currencyCode: "USD", totalAmount: 2000, orderUrl: "http://test.host/orders/#{order.number}", notifyUrl: "http://test.host/payu/notify", continueUrl: "http://test.host/orders/#{order.number}", buyer: { email: user.email, phone: "555-555-0199", firstName: "John", lastName: "Doe", language: "PL", delivery: { street: "10 Lovely Street", postalCode: "35005", city: "Herndon", countryCode: "US" } }, products: { products: [ { name: order.line_items.first.product.name, unitPrice: 1000, quantity: 1 } ] }, reqId: "{36332498-294f-41a1-980c-7b2ec0e3a8a4}" }, headers: { 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby' } ) .to_return( status: 200, body: { status: { statusCode: payu_order_create_status }, redirect_uri: "http://payu.com/redirect/url/4321" }.to_json, headers: {} ) end it "creates new PayU order" do expect { subject }.to_not raise_error expect(payu_order_create).to have_been_requested end context "when PayU order creation succeeded" do it "updates order payment" do subject payment = order.payments.last expect(payment.payment_method).to eq(payment_method) expect(payment).to be_pending expect(payment.amount).to eq(order.total) end it "redirects to payu redirect url" do expect(subject).to redirect_to("http://payu.com/redirect/url/4321") end context "when payment save failed" do before do allow_any_instance_of(Spree::Payment).to receive(:save).and_return(false) allow_any_instance_of(Spree::Payment).to receive(:errors) .and_return(double(full_messages: ["payment save failed"])) end it "logs errors" do subject expect(flash[:error]).to include("payment save failed") end it "renders checkout state with redirect" do expect(subject).to redirect_to "http://test.host/checkout/payment" end end context "when order transition failed" do before do allow(order).to receive(:next).and_return(false) allow(order).to(receive(:errors) .and_return(double(full_messages: ["order cannot transition to this state"]))) end it "logs errors" do subject expect(flash[:error]).to include("order cannot transition to this state") end it "renders checkout state with redirect" do expect(subject).to redirect_to "http://test.host/checkout/payment" end end end context "when PayU order creation returns unexpected status" do let(:payu_order_create_status) { "FAIL" } it "logs error in order" do subject expect(assigns(:order).errors[:base]).to include("PayU error ") end it "renders :edit page" do expect(subject).to render_template(:edit) end end context "when something failed inside PayU order creation" do before do allow(OpenPayU::Order).to receive(:create).and_raise(RuntimeError.new("Payment timeout!")) end it "logs error in order" do subject expect(assigns(:order).errors[:base]).to include("PayU error Payment timeout!") end it "renders :edit page" do expect(subject).to render_template(:edit) end end end context "when order attributes are missing" do let(:payment_params) { { state: "payment", order: { some: "details" } } } subject { spree_post :update, payment_params } it "renders checkout state with redirect" do expect(subject).to redirect_to "http://test.host/checkout/payment" end it "logs error" do subject expect(flash[:error]).to include("No payment found") end end end end
Java
/* * Copyright 2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MONGOC_BULK_OPERATION_H #define MONGOC_BULK_OPERATION_H #include <bson.h> #include "mongoc-macros.h" #include "mongoc-write-concern.h" #define MONGOC_BULK_WRITE_FLAGS_INIT \ { \ true, MONGOC_BYPASS_DOCUMENT_VALIDATION_DEFAULT, 0 \ } BSON_BEGIN_DECLS /* forward decl */ struct _mongoc_client_session_t; typedef struct _mongoc_bulk_operation_t mongoc_bulk_operation_t; typedef struct _mongoc_bulk_write_flags_t mongoc_bulk_write_flags_t; MONGOC_EXPORT (void) mongoc_bulk_operation_destroy (mongoc_bulk_operation_t *bulk); MONGOC_EXPORT (uint32_t) mongoc_bulk_operation_execute (mongoc_bulk_operation_t *bulk, bson_t *reply, bson_error_t *error); MONGOC_EXPORT (void) mongoc_bulk_operation_delete (mongoc_bulk_operation_t *bulk, const bson_t *selector) BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_remove); MONGOC_EXPORT (void) mongoc_bulk_operation_delete_one (mongoc_bulk_operation_t *bulk, const bson_t *selector) BSON_GNUC_DEPRECATED_FOR (mongoc_bulk_operation_remove_one); MONGOC_EXPORT (void) mongoc_bulk_operation_insert (mongoc_bulk_operation_t *bulk, const bson_t *document); MONGOC_EXPORT (bool) mongoc_bulk_operation_insert_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *document, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) mongoc_bulk_operation_remove (mongoc_bulk_operation_t *bulk, const bson_t *selector); MONGOC_EXPORT (bool) mongoc_bulk_operation_remove_many_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) mongoc_bulk_operation_remove_one (mongoc_bulk_operation_t *bulk, const bson_t *selector); MONGOC_EXPORT (bool) mongoc_bulk_operation_remove_one_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) mongoc_bulk_operation_replace_one (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, bool upsert); MONGOC_EXPORT (bool) mongoc_bulk_operation_replace_one_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) mongoc_bulk_operation_update (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, bool upsert); MONGOC_EXPORT (bool) mongoc_bulk_operation_update_many_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) mongoc_bulk_operation_update_one (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, bool upsert); MONGOC_EXPORT (bool) mongoc_bulk_operation_update_one_with_opts (mongoc_bulk_operation_t *bulk, const bson_t *selector, const bson_t *document, const bson_t *opts, bson_error_t *error); /* OUT */ MONGOC_EXPORT (void) mongoc_bulk_operation_set_bypass_document_validation ( mongoc_bulk_operation_t *bulk, bool bypass); /* * The following functions are really only useful by language bindings and * those wanting to replay a bulk operation to a number of clients or * collections. */ MONGOC_EXPORT (mongoc_bulk_operation_t *) mongoc_bulk_operation_new (bool ordered); MONGOC_EXPORT (void) mongoc_bulk_operation_set_write_concern ( mongoc_bulk_operation_t *bulk, const mongoc_write_concern_t *write_concern); MONGOC_EXPORT (void) mongoc_bulk_operation_set_database (mongoc_bulk_operation_t *bulk, const char *database); MONGOC_EXPORT (void) mongoc_bulk_operation_set_collection (mongoc_bulk_operation_t *bulk, const char *collection); MONGOC_EXPORT (void) mongoc_bulk_operation_set_client (mongoc_bulk_operation_t *bulk, void *client); MONGOC_EXPORT (void) mongoc_bulk_operation_set_client_session ( mongoc_bulk_operation_t *bulk, struct _mongoc_client_session_t *client_session); /* These names include the term "hint" for backward compatibility, should be * mongoc_bulk_operation_get_server_id, mongoc_bulk_operation_set_server_id. */ MONGOC_EXPORT (void) mongoc_bulk_operation_set_hint (mongoc_bulk_operation_t *bulk, uint32_t server_id); MONGOC_EXPORT (uint32_t) mongoc_bulk_operation_get_hint (const mongoc_bulk_operation_t *bulk); MONGOC_EXPORT (const mongoc_write_concern_t *) mongoc_bulk_operation_get_write_concern (const mongoc_bulk_operation_t *bulk); BSON_END_DECLS #endif /* MONGOC_BULK_OPERATION_H */
Java
#include "pri.h" #include "calcu_erase_dot_noise.h" #include "iip_erase_dot_noise.h" void iip_erase_dot_noise::_exec_uchar( long l_width, long l_height, long l_area_xpos, long l_area_ypos, long l_area_xsize, long l_area_ysize, long l_channels, unsigned char *ucharp_in, unsigned char *ucharp_out ) { long l_start, l_scansize; long xx,yy; unsigned char *ucharp_in_y1,*ucharp_in_y2,*ucharp_in_y3; unsigned char *ucharp_in_x11,*ucharp_in_x12,*ucharp_in_x13, *ucharp_in_x21,*ucharp_in_x22,*ucharp_in_x23, *ucharp_in_x31,*ucharp_in_x32,*ucharp_in_x33; unsigned char *ucharp_out_y1,*ucharp_out_y2; unsigned char *ucharp_out_x1,*ucharp_out_x2; unsigned char *ucharp_tmp; calcu_erase_dot_noise cl_dot; l_height; /* 初期値 */ l_scansize = l_width * l_channels; l_start = l_area_ypos * l_scansize + l_area_xpos * l_channels; ucharp_in += l_start; ucharp_out += l_start; /* 縦方向ポインター初期化 */ ucharp_in_y1 = ucharp_in; ucharp_in_y2 = ucharp_in_y3 = NULL; ucharp_out_y1 = ucharp_out; ucharp_out_y2 = NULL; /* 縦方向ループ */ for (yy = 0L; yy < l_area_ysize; ++yy, /* 縦方向の3連ポインター進める */ ucharp_in_y3 = ucharp_in_y2, ucharp_in_y2 = ucharp_in_y1, ucharp_in_y1 += l_scansize, ucharp_out_y2 = ucharp_out_y1, ucharp_out_y1 += l_scansize ) { /* カウントダウン表示中 */ if (ON == this->get_i_cv_sw()) { pri_funct_cv_run(yy); } /* 3連満ちるまで */ if (NULL == ucharp_in_y3) { continue; } /* 横方向ポインター初期化 */ ucharp_in_x11 = ucharp_in_y1; ucharp_in_x12 = ucharp_in_x13 = NULL; ucharp_in_x21 = ucharp_in_y2; ucharp_in_x22 = ucharp_in_x23 = NULL; ucharp_in_x31 = ucharp_in_y3; ucharp_in_x32 = ucharp_in_x33 = NULL; ucharp_out_x1 = ucharp_out_y2; ucharp_out_x2 = NULL; /* 横方向ループ */ for (xx = 0L; xx < l_area_xsize; ++xx, /* 横方向の3x3連ポインター進める */ ucharp_in_x33 = ucharp_in_x32, ucharp_in_x32 = ucharp_in_x31, ucharp_in_x31 += l_channels, ucharp_in_x23 = ucharp_in_x22, ucharp_in_x22 = ucharp_in_x21, ucharp_in_x21 += l_channels, ucharp_in_x13 = ucharp_in_x12, ucharp_in_x12 = ucharp_in_x11, ucharp_in_x11 += l_channels, ucharp_out_x2 = ucharp_out_x1, ucharp_out_x1 += l_channels ) { /* 3連満ちるまで */ if (NULL == ucharp_in_x13) { continue; } /* dotをつぶすか判断 */ ucharp_tmp = cl_dot.get_ucharp( ucharp_in_x11,ucharp_in_x12,ucharp_in_x13, ucharp_in_x21,ucharp_in_x22,ucharp_in_x23, ucharp_in_x31,ucharp_in_x32,ucharp_in_x33 ); /* dotをつぶす */ if (NULL != ucharp_tmp) { ucharp_out_x2[CH_RED] = ucharp_tmp[CH_RED]; ucharp_out_x2[CH_GRE] = ucharp_tmp[CH_GRE]; ucharp_out_x2[CH_BLU] = ucharp_tmp[CH_BLU]; } } } }
Java
// Copyright (c) 2013-2015 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package wire_test import ( "bytes" "io" ) // fixedWriter implements the io.Writer interface and intentially allows // testing of error paths by forcing short writes. type fixedWriter struct { b []byte pos int } // Write writes the contents of p to w. When the contents of p would cause // the writer to exceed the maximum allowed size of the fixed writer, // io.ErrShortWrite is returned and the writer is left unchanged. // // This satisfies the io.Writer interface. func (w *fixedWriter) Write(p []byte) (n int, err error) { lenp := len(p) if w.pos+lenp > cap(w.b) { return 0, io.ErrShortWrite } n = lenp w.pos += copy(w.b[w.pos:], p) return } // Bytes returns the bytes already written to the fixed writer. func (w *fixedWriter) Bytes() []byte { return w.b } // newFixedWriter returns a new io.Writer that will error once more bytes than // the specified max have been written. func newFixedWriter(max int) io.Writer { b := make([]byte, max, max) fw := fixedWriter{b, 0} return &fw } // fixedReader implements the io.Reader interface and intentially allows // testing of error paths by forcing short reads. type fixedReader struct { buf []byte pos int iobuf *bytes.Buffer } // Read reads the next len(p) bytes from the fixed reader. When the number of // bytes read would exceed the maximum number of allowed bytes to be read from // the fixed writer, an error is returned. // // This satisfies the io.Reader interface. func (fr *fixedReader) Read(p []byte) (n int, err error) { n, err = fr.iobuf.Read(p) fr.pos += n return } // newFixedReader returns a new io.Reader that will error once more bytes than // the specified max have been read. func newFixedReader(max int, buf []byte) io.Reader { b := make([]byte, max, max) if buf != nil { copy(b[:], buf) } iobuf := bytes.NewBuffer(b) fr := fixedReader{b, 0, iobuf} return &fr }
Java
java_import 'org.apollo.game.action.DistancedAction' # A distanced action which opens a door. class OpenDoorAction < DistancedAction include DoorConstants attr_reader :door def initialize(mob, door) super(0, true, mob, door.position, DOOR_SIZE) @door = door end def executeAction mob.turn_to(@door.position) DoorUtil.toggle(@door) stop end def equals(other) get_class == other.get_class && @door == other.door end end # MessageListener for opening and closing doors. on :message, :first_object_action do |player, message| if DoorUtil.door?(message.id) door = DoorUtil.get_door_object(message.position, message.id) player.start_action(OpenDoorAction.new(player, door)) unless door.nil? end end
Java
import * as React from 'react'; import { BsPrefixComponent } from './helpers'; interface NavbarToggleProps { label?: string; } declare class NavbarToggle< As extends React.ReactType = 'button' > extends BsPrefixComponent<As, NavbarToggleProps> {} export default NavbarToggle;
Java
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { public partial class LineSymbolDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LineSymbolDialog)); this.lblSymbologyType = new System.Windows.Forms.Label(); this.lblPredefinedSymbol = new System.Windows.Forms.Label(); this.lblSymbolPreview = new System.Windows.Forms.Label(); this.btnSymbolDetails = new System.Windows.Forms.Button(); this.cmbCategories = new System.Windows.Forms.ComboBox(); this.predefinedLineSymbolControl1 = new DotSpatial.Symbology.Forms.PredefinedLineSymbolControl(); this.symbolPreview1 = new DotSpatial.Symbology.Forms.SymbolPreview(); this.dialogButtons1 = new DotSpatial.Symbology.Forms.DialogButtons(); this.SuspendLayout(); // // lblSymbologyType // resources.ApplyResources(this.lblSymbologyType, "lblSymbologyType"); this.lblSymbologyType.Name = "lblSymbologyType"; // // lblPredefinedSymbol // resources.ApplyResources(this.lblPredefinedSymbol, "lblPredefinedSymbol"); this.lblPredefinedSymbol.Name = "lblPredefinedSymbol"; // // lblSymbolPreview // resources.ApplyResources(this.lblSymbolPreview, "lblSymbolPreview"); this.lblSymbolPreview.Name = "lblSymbolPreview"; // // btnSymbolDetails // resources.ApplyResources(this.btnSymbolDetails, "btnSymbolDetails"); this.btnSymbolDetails.Name = "btnSymbolDetails"; this.btnSymbolDetails.UseVisualStyleBackColor = true; this.btnSymbolDetails.Click += new System.EventHandler(this.BtnSymbolDetailsClick); // // cmbCategories // resources.ApplyResources(this.cmbCategories, "cmbCategories"); this.cmbCategories.FormattingEnabled = true; this.cmbCategories.Name = "cmbCategories"; this.cmbCategories.SelectedIndexChanged += new System.EventHandler(this.CmbCategoriesSelectedIndexChanged); // // predefinedLineSymbolControl1 // resources.ApplyResources(this.predefinedLineSymbolControl1, "predefinedLineSymbolControl1"); this.predefinedLineSymbolControl1.BackColor = System.Drawing.Color.White; this.predefinedLineSymbolControl1.CategoryFilter = String.Empty; this.predefinedLineSymbolControl1.CellMargin = 8; this.predefinedLineSymbolControl1.CellSize = new System.Drawing.Size(62, 62); this.predefinedLineSymbolControl1.ControlRectangle = new System.Drawing.Rectangle(0, 0, 272, 253); this.predefinedLineSymbolControl1.DefaultCategoryFilter = "All"; this.predefinedLineSymbolControl1.DynamicColumns = true; this.predefinedLineSymbolControl1.IsInitialized = false; this.predefinedLineSymbolControl1.IsSelected = true; this.predefinedLineSymbolControl1.Name = "predefinedLineSymbolControl1"; this.predefinedLineSymbolControl1.SelectedIndex = -1; this.predefinedLineSymbolControl1.SelectionBackColor = System.Drawing.Color.LightGray; this.predefinedLineSymbolControl1.SelectionForeColor = System.Drawing.Color.White; this.predefinedLineSymbolControl1.ShowSymbolNames = true; this.predefinedLineSymbolControl1.TextFont = new System.Drawing.Font("Arial", 8F); this.predefinedLineSymbolControl1.VerticalScrollEnabled = true; // // symbolPreview1 // resources.ApplyResources(this.symbolPreview1, "symbolPreview1"); this.symbolPreview1.BackColor = System.Drawing.Color.White; this.symbolPreview1.Name = "symbolPreview1"; // // dialogButtons1 // resources.ApplyResources(this.dialogButtons1, "dialogButtons1"); this.dialogButtons1.Name = "dialogButtons1"; // // LineSymbolDialog // resources.ApplyResources(this, "$this"); this.Controls.Add(this.dialogButtons1); this.Controls.Add(this.predefinedLineSymbolControl1); this.Controls.Add(this.cmbCategories); this.Controls.Add(this.symbolPreview1); this.Controls.Add(this.btnSymbolDetails); this.Controls.Add(this.lblSymbolPreview); this.Controls.Add(this.lblPredefinedSymbol); this.Controls.Add(this.lblSymbologyType); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "LineSymbolDialog"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private Button btnSymbolDetails; private ComboBox cmbCategories; private DialogButtons dialogButtons1; private Label lblPredefinedSymbol; private Label lblSymbolPreview; private Label lblSymbologyType; private PredefinedLineSymbolControl predefinedLineSymbolControl1; private SymbolPreview symbolPreview1; } }
Java
function* f() { var x; try { x = yield 1; } catch (ex) { yield ex; } return 2; } var g = f(); expect(g.next()).toEqual({value: 1, done: false}); expect(g.next()).toEqual({value: 2, done: true}); g = f(); expect(g.next()).toEqual({value: 1, done: false}); expect(g.throw(3)).toEqual({value: 3, done: false}); expect(g.next()).toEqual({value: 2, done: true});
Java
package events import ( "errors" "github.com/miketheprogrammer/go-thrust/lib/commands" "github.com/miketheprogrammer/go-thrust/lib/dispatcher" ) /* Create a new EventHandler for a give event. */ func NewHandler(event string, fn interface{}) (ThrustEventHandler, error) { h := ThrustEventHandler{} h.Event = event h.Type = "event" err := h.SetHandleFunc(fn) dispatcher.RegisterHandler(h) return h, err } /** Begin Thrust Handler Code. **/ type Handler interface { Handle(cr commands.CommandResponse) Register() SetHandleFunc(fn interface{}) } type ThrustEventHandler struct { Type string Event string Handler interface{} } func (teh ThrustEventHandler) Handle(cr commands.CommandResponse) { if cr.Action != "event" { return } if cr.Type != teh.Event && teh.Event != "*" { return } cr.Event.Type = cr.Type if fn, ok := teh.Handler.(func(commands.CommandResponse)); ok == true { fn(cr) return } if fn, ok := teh.Handler.(func(commands.EventResult)); ok == true { fn(cr.Event) return } } func (teh *ThrustEventHandler) SetHandleFunc(fn interface{}) error { if fn, ok := fn.(func(commands.CommandResponse)); ok == true { teh.Handler = fn return nil } if fn, ok := fn.(func(commands.EventResult)); ok == true { teh.Handler = fn return nil } return errors.New("Invalid Handler Definition") }
Java
package edu.pacificu.cs493f15_1.paperorplasticapp; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
Java
from __future__ import unicode_literals from .atomicparsley import AtomicParsleyPP from .ffmpeg import ( FFmpegPostProcessor, FFmpegAudioFixPP, FFmpegEmbedSubtitlePP, FFmpegExtractAudioPP, FFmpegFixupStretchedPP, FFmpegMergerPP, FFmpegMetadataPP, FFmpegVideoConvertorPP, ) from .xattrpp import XAttrMetadataPP from .execafterdownload import ExecAfterDownloadPP def get_postprocessor(key): return globals()[key + 'PP'] __all__ = [ 'AtomicParsleyPP', 'ExecAfterDownloadPP', 'FFmpegAudioFixPP', 'FFmpegEmbedSubtitlePP', 'FFmpegExtractAudioPP', 'FFmpegFixupStretchedPP', 'FFmpegMergerPP', 'FFmpegMetadataPP', 'FFmpegPostProcessor', 'FFmpegVideoConvertorPP', 'XAttrMetadataPP', ]
Java
package com.hearthsim.test.minion; import com.hearthsim.card.Card; import com.hearthsim.card.CharacterIndex; import com.hearthsim.card.basic.minion.BoulderfistOgre; import com.hearthsim.card.basic.minion.RaidLeader; import com.hearthsim.card.classic.minion.common.ScarletCrusader; import com.hearthsim.card.classic.minion.rare.Abomination; import com.hearthsim.card.minion.Minion; import com.hearthsim.exception.HSException; import com.hearthsim.model.BoardModel; import com.hearthsim.model.PlayerModel; import com.hearthsim.model.PlayerSide; import com.hearthsim.util.tree.HearthTreeNode; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class TestAbomination { private HearthTreeNode board; private PlayerModel currentPlayer; private PlayerModel waitingPlayer; @Before public void setup() throws HSException { board = new HearthTreeNode(new BoardModel()); currentPlayer = board.data_.getCurrentPlayer(); waitingPlayer = board.data_.getWaitingPlayer(); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new RaidLeader()); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new BoulderfistOgre()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new ScarletCrusader()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new RaidLeader()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new BoulderfistOgre()); Card fb = new Abomination(); currentPlayer.placeCardHand(fb); currentPlayer.setMana((byte) 8); waitingPlayer.setMana((byte) 8); } @Test public void test0() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, CharacterIndex.HERO, board); assertNull(ret); assertEquals(currentPlayer.getHand().size(), 1); assertEquals(currentPlayer.getNumMinions(), 2); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 8); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } @Test public void test1() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 4); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } @Test public void test2() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalHealth(), 4); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); //attack the Ogre... should kill everything except the Scarlet Crusader Minion attacker = currentPlayer.getCharacter(CharacterIndex.MINION_1); attacker.hasAttacked(false); ret = attacker.attack(PlayerSide.WAITING_PLAYER, CharacterIndex.MINION_3, ret); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 1); assertEquals(waitingPlayer.getNumMinions(), 1); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 28); assertEquals(waitingPlayer.getHero().getHealth(), 28); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 5); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 6); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 3); assertFalse(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } @Test public void test3() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 4); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); //Silence the Abomination first, then attack with it Minion attacker = currentPlayer.getCharacter(CharacterIndex.MINION_1); attacker.silenced(PlayerSide.CURRENT_PLAYER, board); attacker.hasAttacked(false); attacker.attack(PlayerSide.WAITING_PLAYER, CharacterIndex.MINION_3, ret); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 2); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } }
Java
// Type definitions for yargs 17.0 // Project: https://github.com/chevex/yargs, https://yargs.js.org // Definitions by: Martin Poelstra <https://github.com/poelstra> // Mizunashi Mana <https://github.com/mizunashi-mana> // Jeffery Grajkowski <https://github.com/pushplay> // Jimi (Dimitris) Charalampidis <https://github.com/JimiC> // Steffen Viken Valvåg <https://github.com/steffenvv> // Emily Marigold Klassen <https://github.com/forivall> // ExE Boss <https://github.com/ExE-Boss> // Aankhen <https://github.com/Aankhen> // Ben Coe <https://github.com/bcoe> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 // The following TSLint rules have been disabled: // unified-signatures: Because there is useful information in the argument names of the overloaded signatures // Convention: // Use 'union types' when: // - parameter types have similar signature type (i.e. 'string | ReadonlyArray<string>') // - parameter names have the same semantic meaning (i.e. ['command', 'commands'] , ['key', 'keys']) // An example for not using 'union types' is the declaration of 'env' where `prefix` and `enable` parameters // have different semantics. On the other hand, in the declaration of 'usage', a `command: string` parameter // has the same semantic meaning with declaring an overload method by using `commands: ReadonlyArray<string>`, // thus it's preferred to use `command: string | ReadonlyArray<string>` // Use parameterless declaration instead of declaring all parameters optional, // when all parameters are optional and more than one import { DetailedArguments, Configuration } from 'yargs-parser'; declare namespace yargs { type BuilderCallback<T, R> = ((args: Argv<T>) => PromiseLike<Argv<R>>) | ((args: Argv<T>) => Argv<R>) | ((args: Argv<T>) => void); type ParserConfigurationOptions = Configuration & { /** Sort commands alphabetically. Default is `false` */ 'sort-commands': boolean; }; /** * The type parameter `T` is the expected shape of the parsed options. * `Arguments<T>` is those options plus `_` and `$0`, and an indexer falling * back to `unknown` for unknown options. * * For the return type / `argv` property, we create a mapped type over * `Arguments<T>` to simplify the inferred type signature in client code. */ interface Argv<T = {}> { (): { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>; (args: ReadonlyArray<string>, cwd?: string): Argv<T>; /** * Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa. * * Optionally `.alias()` can take an object that maps keys to aliases. * Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings. */ // Aliases for previously declared options can inherit the types of those options. alias<K1 extends keyof T, K2 extends string>(shortName: K1, longName: K2 | ReadonlyArray<K2>): Argv<T & { [key in K2]: T[K1] }>; alias<K1 extends keyof T, K2 extends string>(shortName: K2, longName: K1 | ReadonlyArray<K1>): Argv<T & { [key in K2]: T[K1] }>; alias(shortName: string | ReadonlyArray<string>, longName: string | ReadonlyArray<string>): Argv<T>; alias(aliases: { [shortName: string]: string | ReadonlyArray<string> }): Argv<T>; /** * Get the arguments as a plain old object. * * Arguments without a corresponding flag show up in the `argv._` array. * * The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl. * * If `yargs` is executed in an environment that embeds node and there's no script name (e.g. Electron or nw.js), * it will ignore the first parameter since it expects it to be the script name. In order to override * this behavior, use `.parse(process.argv.slice(1))` instead of .argv and the first parameter won't be ignored. */ argv: { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>; /** * Tell the parser to interpret `key` as an array. * If `.array('foo')` is set, `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`. * Also, if you use the option multiple times all the values will be flattened in one array so `--foo foo --foo bar` will be parsed as `['foo', 'bar']` * * When the option is used with a positional, use `--` to tell `yargs` to stop adding values to the array. */ array<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToArray<T[key]> }>; array<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: Array<string | number> | undefined }>; /** * Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`. * * `key` will default to `false`, unless a `default(key, undefined)` is explicitly set. * * If `key` is an array, interpret all the elements as booleans. */ boolean<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: boolean | undefined }>; boolean<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: boolean | undefined }>; /** * Check that certain conditions are met in the provided arguments. * @param func Called with two arguments, the parsed `argv` hash and an array of options and their aliases. * If `func` throws or returns a non-truthy value, show the thrown error, usage information, and exit. * @param global Indicates whether `check()` should be enabled both at the top-level and for each sub-command. */ check(func: (argv: Arguments<T>, aliases: { [alias: string]: string }) => any, global?: boolean): Argv<T>; /** * Limit valid values for key to a predefined set of choices, given as an array or as an individual value. * If this method is called multiple times, all enumerated values will be merged together. * Choices are generally strings or numbers, and value matching is case-sensitive. * * Optionally `.choices()` can take an object that maps multiple keys to their choices. * * Choices can also be specified as choices in the object given to `option()`. */ choices<K extends keyof T, C extends ReadonlyArray<any>>(key: K, values: C): Argv<Omit<T, K> & { [key in K]: C[number] | undefined }>; choices<K extends string, C extends ReadonlyArray<any>>(key: K, values: C): Argv<T & { [key in K]: C[number] | undefined }>; choices<C extends { [key: string]: ReadonlyArray<any> }>(choices: C): Argv<Omit<T, keyof C> & { [key in keyof C]: C[key][number] | undefined }>; /** * Provide a synchronous function to coerce or transform the value(s) given on the command line for `key`. * * The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error. * The returned value will be used as the value for `key` (or one of its aliases) in `argv`. * * If the function throws, the error will be treated as a validation failure, delegating to either a custom `.fail()` handler or printing the error message in the console. * * Coercion will be applied to a value after all other modifications, such as `.normalize()`. * * Optionally `.coerce()` can take an object that maps several keys to their respective coercion function. * * You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to `.coerce()`. * * If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`, coercion will be applied to the final object that has been parsed */ coerce<K extends keyof T, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<Omit<T, K> & { [key in K]: V | undefined }>; coerce<K extends string, V>(key: K | ReadonlyArray<K>, func: (arg: any) => V): Argv<T & { [key in K]: V | undefined }>; coerce<O extends { [key: string]: (arg: any) => any }>(opts: O): Argv<Omit<T, keyof O> & { [key in keyof O]: ReturnType<O[key]> | undefined }>; /** * Define the commands exposed by your application. * @param command Should be a string representing the command or an array of strings representing the command and its aliases. * @param description Use to provide a description for each command your application accepts (the values stored in `argv._`). * Set `description` to false to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion. * @param [builder] Object to give hints about the options that your command accepts. * Can also be a function. This function is executed with a yargs instance, and can be used to provide advanced command specific help. * * Note that when `void` is returned, the handler `argv` object type will not include command-specific arguments. * @param [handler] Function, which will be executed with the parsed `argv` object. */ command<U = T>( command: string | ReadonlyArray<string>, description: string, builder?: BuilderCallback<T, U>, handler?: (args: Arguments<U>) => void, middlewares?: MiddlewareFunction[], deprecated?: boolean | string, ): Argv<U>; command<O extends { [key: string]: Options }>( command: string | ReadonlyArray<string>, description: string, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void, middlewares?: MiddlewareFunction[], deprecated?: boolean | string, ): Argv<T>; command<U>(command: string | ReadonlyArray<string>, description: string, module: CommandModule<T, U>): Argv<U>; command<U = T>( command: string | ReadonlyArray<string>, showInHelp: false, builder?: BuilderCallback<T, U>, handler?: (args: Arguments<U>) => void, middlewares?: MiddlewareFunction[], deprecated?: boolean | string, ): Argv<T>; command<O extends { [key: string]: Options }>( command: string | ReadonlyArray<string>, showInHelp: false, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void, ): Argv<T>; command<U>(command: string | ReadonlyArray<string>, showInHelp: false, module: CommandModule<T, U>): Argv<U>; command<U>(module: CommandModule<T, U>): Argv<U>; // Advanced API /** Apply command modules from a directory relative to the module calling this method. */ commandDir(dir: string, opts?: RequireDirectoryOptions): Argv<T>; /** * Enable bash/zsh-completion shortcuts for commands and options. * * If invoked without parameters, `.completion()` will make completion the command to output the completion script. * * @param [cmd] When present in `argv._`, will result in the `.bashrc` or `.zshrc` completion script being outputted. * To enable bash/zsh completions, concat the generated script to your `.bashrc` or `.bash_profile` (or `.zshrc` for zsh). * @param [description] Provide a description in your usage instructions for the command that generates the completion scripts. * @param [func] Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method. */ completion(): Argv<T>; completion(cmd: string, func?: AsyncCompletionFunction): Argv<T>; completion(cmd: string, func?: SyncCompletionFunction): Argv<T>; completion(cmd: string, func?: PromiseCompletionFunction): Argv<T>; completion(cmd: string, description?: string | false, func?: AsyncCompletionFunction): Argv<T>; completion(cmd: string, description?: string | false, func?: SyncCompletionFunction): Argv<T>; completion(cmd: string, description?: string | false, func?: PromiseCompletionFunction): Argv<T>; /** * Tells the parser that if the option specified by `key` is passed in, it should be interpreted as a path to a JSON config file. * The file is loaded and parsed, and its properties are set as arguments. * Because the file is loaded using Node's require(), the filename MUST end in `.json` to be interpreted correctly. * * If invoked without parameters, `.config()` will make --config the option to pass the JSON config file. * * @param [description] Provided to customize the config (`key`) option in the usage string. * @param [explicitConfigurationObject] An explicit configuration `object` */ config(): Argv<T>; config(key: string | ReadonlyArray<string>, description?: string, parseFn?: (configPath: string) => object): Argv<T>; config(key: string | ReadonlyArray<string>, parseFn: (configPath: string) => object): Argv<T>; config(explicitConfigurationObject: object): Argv<T>; /** * Given the key `x` is set, the key `y` must not be set. `y` can either be a single string or an array of argument names that `x` conflicts with. * * Optionally `.conflicts()` can accept an object specifying multiple conflicting keys. */ conflicts(key: string, value: string | ReadonlyArray<string>): Argv<T>; conflicts(conflicts: { [key: string]: string | ReadonlyArray<string> }): Argv<T>; /** * Interpret `key` as a boolean flag, but set its parsed value to the number of flag occurrences rather than `true` or `false`. Default value is thus `0`. */ count<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: number }>; count<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number }>; /** * Set `argv[key]` to `value` if no option was specified in `process.argv`. * * Optionally `.default()` can take an object that maps keys to default values. * * The default value can be a `function` which returns a value. The name of the function will be used in the usage string. * * Optionally, `description` can also be provided and will take precedence over displaying the value in the usage instructions. */ default<K extends keyof T, V>(key: K, value: V, description?: string): Argv<Omit<T, K> & { [key in K]: V }>; default<K extends string, V>(key: K, value: V, description?: string): Argv<T & { [key in K]: V }>; default<D extends { [key: string]: any }>(defaults: D, description?: string): Argv<Omit<T, keyof D> & D>; /** * @deprecated since version 6.6.0 * Use '.demandCommand()' or '.demandOption()' instead */ demand<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; demand<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>; demand(key: string | ReadonlyArray<string>, required?: boolean): Argv<T>; demand(positionals: number, msg: string): Argv<T>; demand(positionals: number, required?: boolean): Argv<T>; demand(positionals: number, max: number, msg?: string): Argv<T>; /** * @param key If is a string, show the usage information and exit if key wasn't specified in `process.argv`. * If is an array, demand each element. * @param msg If string is given, it will be printed when the argument is missing, instead of the standard error message. * @param demand Controls whether the option is demanded; this is useful when using .options() to specify command line parameters. */ demandOption<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; demandOption<K extends string>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<T & { [key in K]: unknown }>; demandOption(key: string | ReadonlyArray<string>, demand?: boolean): Argv<T>; /** * Demand in context of commands. * You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met. */ demandCommand(): Argv<T>; demandCommand(min: number, minMsg?: string): Argv<T>; demandCommand(min: number, max?: number, minMsg?: string, maxMsg?: string): Argv<T>; /** * Shows a [deprecated] notice in front of the option */ deprecateOption(option: string, msg?: string): Argv<T>; /** * Describe a `key` for the generated usage information. * * Optionally `.describe()` can take an object that maps keys to descriptions. */ describe(key: string | ReadonlyArray<string>, description: string): Argv<T>; describe(descriptions: { [key: string]: string }): Argv<T>; /** Should yargs attempt to detect the os' locale? Defaults to `true`. */ detectLocale(detect: boolean): Argv<T>; /** * Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments. * * Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo) * * If this method is called with no argument or with an empty string or with true, then all env vars will be applied to argv. * * Program arguments are defined in this order of precedence: * 1. Command line args * 2. Env vars * 3. Config file/objects * 4. Configured defaults * * Env var parsing is disabled by default, but you can also explicitly disable it by calling `.env(false)`, e.g. if you need to undo previous configuration. */ env(): Argv<T>; env(prefix: string): Argv<T>; env(enable: boolean): Argv<T>; /** A message to print at the end of the usage instructions */ epilog(msg: string): Argv<T>; /** A message to print at the end of the usage instructions */ epilogue(msg: string): Argv<T>; /** * Give some example invocations of your program. * Inside `cmd`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl. * Examples will be printed out as part of the help message. */ example(command: string, description: string): Argv<T>; example(command: ReadonlyArray<[string, string?]>): Argv<T>; /** Manually indicate that the program should exit, and provide context about why we wanted to exit. Follows the behavior set by `.exitProcess().` */ exit(code: number, err: Error): void; /** * By default, yargs exits the process when the user passes a help flag, the user uses the `.version` functionality, validation fails, or the command handler fails. * Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated. */ exitProcess(enabled: boolean): Argv<T>; /** * Method to execute when a failure occurs, rather than printing the failure message. * @param func Is called with the failure message that would have been printed, the Error instance originally thrown and yargs state when the failure occurred. */ fail(func: ((msg: string, err: Error, yargs: Argv<T>) => any) | boolean): Argv<T>; /** * Allows to programmatically get completion choices for any line. * @param args An array of the words in the command line to complete. * @param done The callback to be called with the resulting completions. */ getCompletion(args: ReadonlyArray<string>, done: (completions: ReadonlyArray<string>) => void): Argv<T>; /** * Indicate that an option (or group of options) should not be reset when a command is executed * * Options default to being global. */ global(key: string | ReadonlyArray<string>): Argv<T>; /** Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions */ group(key: string | ReadonlyArray<string>, groupName: string): Argv<T>; /** Hides a key from the generated usage information. Unless a `--show-hidden` option is also passed with `--help` (see `showHidden()`). */ hide(key: string): Argv<T>; /** * Configure an (e.g. `--help`) and implicit command that displays the usage string and exits the process. * By default yargs enables help on the `--help` option. * * Note that any multi-char aliases (e.g. `help`) used for the help option will also be used for the implicit command. * If there are no multi-char aliases (e.g. `h`), then all single-char aliases will be used for the command. * * If invoked without parameters, `.help()` will use `--help` as the option and help as the implicit command to trigger help output. * * @param [description] Customizes the description of the help option in the usage string. * @param [enableExplicit] If `false` is provided, it will disable --help. */ help(): Argv<T>; help(enableExplicit: boolean): Argv<T>; help(option: string, enableExplicit: boolean): Argv<T>; help(option: string, description?: string, enableExplicit?: boolean): Argv<T>; /** * Given the key `x` is set, it is required that the key `y` is set. * y` can either be the name of an argument to imply, a number indicating the position of an argument or an array of multiple implications to associate with `x`. * * Optionally `.implies()` can accept an object specifying multiple implications. */ implies(key: string, value: string | ReadonlyArray<string>): Argv<T>; implies(implies: { [key: string]: string | ReadonlyArray<string> }): Argv<T>; /** * Return the locale that yargs is currently using. * * By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language. */ locale(): string; /** * Override the auto-detected locale from the user's operating system with a static locale. * Note that the OS locale can be modified by setting/exporting the `LC_ALL` environment variable. */ locale(loc: string): Argv<T>; /** * Define global middleware functions to be called first, in list order, for all cli command. * @param callbacks Can be a function or a list of functions. Each callback gets passed a reference to argv. * @param [applyBeforeValidation] Set to `true` to apply middleware before validation. This will execute the middleware prior to validation checks, but after parsing. */ middleware(callbacks: MiddlewareFunction<T> | ReadonlyArray<MiddlewareFunction<T>>, applyBeforeValidation?: boolean): Argv<T>; /** * The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity. * * Optionally `.nargs()` can take an object of `key`/`narg` pairs. */ nargs(key: string, count: number): Argv<T>; nargs(nargs: { [key: string]: number }): Argv<T>; /** The key provided represents a path and should have `path.normalize()` applied. */ normalize<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>; normalize<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>; /** * Tell the parser to always interpret key as a number. * * If `key` is an array, all elements will be parsed as numbers. * * If the option is given on the command line without a value, `argv` will be populated with `undefined`. * * If the value given on the command line cannot be parsed as a number, `argv` will be populated with `NaN`. * * Note that decimals, hexadecimals, and scientific notation are all accepted. */ number<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToNumber<T[key]> }>; number<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: number | undefined }>; /** * Method to execute when a command finishes successfully. * @param func Is called with the successful result of the command that finished. */ onFinishCommand(func: (result: any) => void): Argv<T>; /** * This method can be used to make yargs aware of options that could exist. * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option. */ option<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>; option<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>; option<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>; /** * This method can be used to make yargs aware of options that could exist. * You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option. */ options<K extends keyof T, O extends Options>(key: K, options: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>; options<K extends string, O extends Options>(key: K, options: O): Argv<T & { [key in K]: InferredOptionType<O> }>; options<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>; /** * Parse `args` instead of `process.argv`. Returns the `argv` object. `args` may either be a pre-processed argv array, or a raw argument string. * * Note: Providing a callback to parse() disables the `exitProcess` setting until after the callback is invoked. * @param [context] Provides a useful mechanism for passing state information to commands */ parse(): { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>; parse(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): { [key in keyof Arguments<T>]: Arguments<T>[key] } | Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>; parseSync(): { [key in keyof Arguments<T>]: Arguments<T>[key] }; parseSync(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): { [key in keyof Arguments<T>]: Arguments<T>[key] }; parseAsync(): Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>; parseAsync(arg: string | ReadonlyArray<string>, context?: object, parseCallback?: ParseCallback<T>): Promise<{ [key in keyof Arguments<T>]: Arguments<T>[key] }>; /** * If the arguments have not been parsed, this property is `false`. * * If the arguments have been parsed, this contain detailed parsed arguments. */ parsed: DetailedArguments | false; /** Allows to configure advanced yargs features. */ parserConfiguration(configuration: Partial<ParserConfigurationOptions>): Argv<T>; /** * Similar to `config()`, indicates that yargs should interpret the object from the specified key in package.json as a configuration object. * @param [cwd] If provided, the package.json will be read from this location */ pkgConf(key: string | ReadonlyArray<string>, cwd?: string): Argv<T>; /** * Allows you to configure a command's positional arguments with an API similar to `.option()`. * `.positional()` should be called in a command's builder function, and is not available on the top-level yargs instance. If so, it will throw an error. */ positional<K extends keyof T, O extends PositionalOptions>(key: K, opt: O): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>; positional<K extends string, O extends PositionalOptions>(key: K, opt: O): Argv<T & { [key in K]: InferredOptionType<O> }>; /** Should yargs provide suggestions regarding similar commands if no matching command is found? */ recommendCommands(): Argv<T>; /** * @deprecated since version 6.6.0 * Use '.demandCommand()' or '.demandOption()' instead */ require<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; require(key: string, msg: string): Argv<T>; require(key: string, required: boolean): Argv<T>; require(keys: ReadonlyArray<number>, msg: string): Argv<T>; require(keys: ReadonlyArray<number>, required: boolean): Argv<T>; require(positionals: number, required: boolean): Argv<T>; require(positionals: number, msg: string): Argv<T>; /** * @deprecated since version 6.6.0 * Use '.demandCommand()' or '.demandOption()' instead */ required<K extends keyof T>(key: K | ReadonlyArray<K>, msg?: string | true): Argv<Defined<T, K>>; required(key: string, msg: string): Argv<T>; required(key: string, required: boolean): Argv<T>; required(keys: ReadonlyArray<number>, msg: string): Argv<T>; required(keys: ReadonlyArray<number>, required: boolean): Argv<T>; required(positionals: number, required: boolean): Argv<T>; required(positionals: number, msg: string): Argv<T>; requiresArg(key: string | ReadonlyArray<string>): Argv<T>; /** Set the name of your script ($0). Default is the base filename executed by node (`process.argv[1]`) */ scriptName($0: string): Argv<T>; /** * Generate a bash completion script. * Users of your application can install this script in their `.bashrc`, and yargs will provide completion shortcuts for commands and options. */ showCompletionScript(): Argv<T>; /** * Configure the `--show-hidden` option that displays the hidden keys (see `hide()`). * @param option If `boolean`, it enables/disables this option altogether. i.e. hidden keys will be permanently hidden if first argument is `false`. * If `string` it changes the key name ("--show-hidden"). * @param description Changes the default description ("Show hidden options") */ showHidden(option?: string | boolean): Argv<T>; showHidden(option: string, description?: string): Argv<T>; /** * Print the usage data using the console function consoleLevel for printing. * @param [consoleLevel='error'] */ showHelp(consoleLevel?: string): Argv<T>; /** * Provide the usage data as a string. * @param printCallback a function with a single argument. */ showHelp(printCallback: (s: string) => void): Argv<T>; /** * By default, yargs outputs a usage string if any error is detected. * Use the `.showHelpOnFail()` method to customize this behavior. * @param enable If `false`, the usage string is not output. * @param [message] Message that is output after the error message. */ showHelpOnFail(enable: boolean, message?: string): Argv<T>; /** Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped. */ skipValidation(key: string | ReadonlyArray<string>): Argv<T>; /** * Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error. * * Unrecognized commands will also be reported as errors. */ strict(): Argv<T>; strict(enabled: boolean): Argv<T>; /** * Similar to .strict(), except that it only applies to unrecognized commands. * A user can still provide arbitrary options, but unknown positional commands * will raise an error. */ strictCommands(): Argv<T>; strictCommands(enabled: boolean): Argv<T>; /** * Similar to `.strict()`, except that it only applies to unrecognized options. A * user can still provide arbitrary positional options, but unknown options * will raise an error. */ strictOptions(): Argv<T>; strictOptions(enabled: boolean): Argv<T>; /** * Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input. * * If `key` is an array, interpret all the elements as strings. * * `.string('_')` will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers. */ string<K extends keyof T>(key: K | ReadonlyArray<K>): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>; string<K extends string>(key: K | ReadonlyArray<K>): Argv<T & { [key in K]: string | undefined }>; // Intended to be used with '.wrap()' terminalWidth(): number; updateLocale(obj: { [key: string]: string }): Argv<T>; /** * Override the default strings used by yargs with the key/value pairs provided in obj * * If you explicitly specify a locale(), you should do so before calling `updateStrings()`. */ updateStrings(obj: { [key: string]: string }): Argv<T>; /** * Set a usage message to show which commands to use. * Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl. * * If the optional `description`/`builder`/`handler` are provided, `.usage()` acts an an alias for `.command()`. * This allows you to use `.usage()` to configure the default command that will be run as an entry-point to your application * and allows you to provide configuration for the positional arguments accepted by your program: */ usage(message: string): Argv<T>; usage<U>(command: string | ReadonlyArray<string>, description: string, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>; usage<U>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: (args: Argv<T>) => Argv<U>, handler?: (args: Arguments<U>) => void): Argv<T>; usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, description: string, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>; usage<O extends { [key: string]: Options }>(command: string | ReadonlyArray<string>, showInHelp: boolean, builder?: O, handler?: (args: Arguments<InferredOptionTypes<O>>) => void): Argv<T>; /** * Add an option (e.g. `--version`) that displays the version number (given by the version parameter) and exits the process. * By default yargs enables version for the `--version` option. * * If no arguments are passed to version (`.version()`), yargs will parse the package.json of your module and use its version value. * * If the boolean argument `false` is provided, it will disable `--version`. */ version(): Argv<T>; version(version: string): Argv<T>; version(enable: boolean): Argv<T>; version(optionKey: string, version: string): Argv<T>; version(optionKey: string, description: string, version: string): Argv<T>; /** * Format usage output to wrap at columns many columns. * * By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to specify no column limit (no right-align). * Use `.wrap(yargs.terminalWidth())` to maximize the width of yargs' usage instructions. */ wrap(columns: number | null): Argv<T>; } type Arguments<T = {}> = T & { /** Non-option arguments */ _: Array<string | number>; /** The script name or node command */ $0: string; /** All remaining options */ [argName: string]: unknown; }; interface RequireDirectoryOptions { /** Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list. */ recurse?: boolean; /** The types of files to look for when requiring command modules. */ extensions?: ReadonlyArray<string>; /** * A synchronous function called for each command module encountered. * Accepts `commandObject`, `pathToFile`, and `filename` as arguments. * Returns `commandObject` to include the command; any falsy value to exclude/skip it. */ visit?: (commandObject: any, pathToFile?: string, filename?: string) => any; /** Whitelist certain modules */ include?: RegExp | ((pathToFile: string) => boolean); /** Blacklist certain modules. */ exclude?: RegExp | ((pathToFile: string) => boolean); } interface Options { /** string or array of strings, alias(es) for the canonical option key, see `alias()` */ alias?: string | ReadonlyArray<string>; /** boolean, interpret option as an array, see `array()` */ array?: boolean; /** boolean, interpret option as a boolean flag, see `boolean()` */ boolean?: boolean; /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */ choices?: Choices; /** function, coerce or transform parsed command line values into another value, see `coerce()` */ coerce?: (arg: any) => any; /** boolean, interpret option as a path to a JSON config file, see `config()` */ config?: boolean; /** function, provide a custom config parsing function, see `config()` */ configParser?: (configPath: string) => object; /** string or object, require certain keys not to be set, see `conflicts()` */ conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** boolean, interpret option as a count of boolean flags, see `count()` */ count?: boolean; /** value, set a default value for the option, see `default()` */ default?: any; /** string, use this description for the default value in help content, see `default()` */ defaultDescription?: string; /** * @deprecated since version 6.6.0 * Use 'demandOption' instead */ demand?: boolean | string; /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */ deprecate?: boolean | string; /** boolean or string, mark the argument as deprecated, see `deprecateOption()` */ deprecated?: boolean | string; /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */ demandOption?: boolean | string; /** string, the option description for help content, see `describe()` */ desc?: string; /** string, the option description for help content, see `describe()` */ describe?: string; /** string, the option description for help content, see `describe()` */ description?: string; /** boolean, indicate that this key should not be reset when a command is invoked, see `global()` */ global?: boolean; /** string, when displaying usage instructions place the option under an alternative group heading, see `group()` */ group?: string; /** don't display option in help output. */ hidden?: boolean; /** string or object, require certain keys to be set, see `implies()` */ implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** number, specify how many arguments should be consumed for the option, see `nargs()` */ nargs?: number; /** boolean, apply path.normalize() to the option, see `normalize()` */ normalize?: boolean; /** boolean, interpret option as a number, `number()` */ number?: boolean; /** * @deprecated since version 6.6.0 * Use 'demandOption' instead */ require?: boolean | string; /** * @deprecated since version 6.6.0 * Use 'demandOption' instead */ required?: boolean | string; /** boolean, require the option be specified with a value, see `requiresArg()` */ requiresArg?: boolean; /** boolean, skips validation if the option is present, see `skipValidation()` */ skipValidation?: boolean; /** boolean, interpret option as a string, see `string()` */ string?: boolean; type?: "array" | "count" | PositionalOptionsType; } interface PositionalOptions { /** string or array of strings, see `alias()` */ alias?: string | ReadonlyArray<string>; /** boolean, interpret option as an array, see `array()` */ array?: boolean; /** value or array of values, limit valid option arguments to a predefined set, see `choices()` */ choices?: Choices; /** function, coerce or transform parsed command line values into another value, see `coerce()` */ coerce?: (arg: any) => any; /** string or object, require certain keys not to be set, see `conflicts()` */ conflicts?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** value, set a default value for the option, see `default()` */ default?: any; /** boolean or string, demand the option be given, with optional error message, see `demandOption()` */ demandOption?: boolean | string; /** string, the option description for help content, see `describe()` */ desc?: string; /** string, the option description for help content, see `describe()` */ describe?: string; /** string, the option description for help content, see `describe()` */ description?: string; /** string or object, require certain keys to be set, see `implies()` */ implies?: string | ReadonlyArray<string> | { [key: string]: string | ReadonlyArray<string> }; /** boolean, apply path.normalize() to the option, see normalize() */ normalize?: boolean; type?: PositionalOptionsType; } /** Remove keys K in T */ type Omit<T, K> = { [key in Exclude<keyof T, K>]: T[key] }; /** Remove undefined as a possible value for keys K in T */ type Defined<T, K extends keyof T> = Omit<T, K> & { [key in K]: Exclude<T[key], undefined> }; /** Convert T to T[] and T | undefined to T[] | undefined */ type ToArray<T> = Array<Exclude<T, undefined>> | Extract<T, undefined>; /** Gives string[] if T is an array type, otherwise string. Preserves | undefined. */ type ToString<T> = (Exclude<T, undefined> extends any[] ? string[] : string) | Extract<T, undefined>; /** Gives number[] if T is an array type, otherwise number. Preserves | undefined. */ type ToNumber<T> = (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>; type InferredOptionType<O extends Options | PositionalOptions> = O extends ( | { required: string | true } | { require: string | true } | { demand: string | true } | { demandOption: string | true } ) ? Exclude<InferredOptionTypeInner<O>, undefined> : InferredOptionTypeInner<O>; type InferredOptionTypeInner<O extends Options | PositionalOptions> = O extends { default: any, coerce: (arg: any) => infer T } ? T : O extends { default: infer D } ? D : O extends { type: "count" } ? number : O extends { count: true } ? number : RequiredOptionType<O> | undefined; type RequiredOptionType<O extends Options | PositionalOptions> = O extends { type: "array", string: true } ? string[] : O extends { type: "array", number: true } ? number[] : O extends { type: "array", normalize: true } ? string[] : O extends { type: "string", array: true } ? string[] : O extends { type: "number", array: true } ? number[] : O extends { string: true, array: true } ? string[] : O extends { number: true, array: true } ? number[] : O extends { normalize: true, array: true } ? string[] : O extends { type: "array" } ? Array<string | number> : O extends { type: "boolean" } ? boolean : O extends { type: "number" } ? number : O extends { type: "string" } ? string : O extends { array: true } ? Array<string | number> : O extends { boolean: true } ? boolean : O extends { number: true } ? number : O extends { string: true } ? string : O extends { normalize: true } ? string : O extends { choices: ReadonlyArray<infer C> } ? C : O extends { coerce: (arg: any) => infer T } ? T : unknown; type InferredOptionTypes<O extends { [key: string]: Options }> = { [key in keyof O]: InferredOptionType<O[key]> }; interface CommandModule<T = {}, U = {}> { /** array of strings (or a single string) representing aliases of `exports.command`, positional args defined in an alias are ignored */ aliases?: ReadonlyArray<string> | string; /** object declaring the options the command accepts, or a function accepting and returning a yargs instance */ builder?: CommandBuilder<T, U>; /** string (or array of strings) that executes this command when given on the command line, first string may contain positional args */ command?: ReadonlyArray<string> | string; /** boolean (or string) to show deprecation notice */ deprecated?: boolean | string; /** string used as the description for the command in help text, use `false` for a hidden command */ describe?: string | false; /** a function which will be passed the parsed argv. */ handler: (args: Arguments<U>) => void; } type ParseCallback<T = {}> = (err: Error | undefined, argv: Arguments<T>|Promise<Arguments<T>>, output: string) => void; type CommandBuilder<T = {}, U = {}> = { [key: string]: Options } | ((args: Argv<T>) => Argv<U>) | ((args: Argv<T>) => PromiseLike<Argv<U>>); type SyncCompletionFunction = (current: string, argv: any) => string[]; type AsyncCompletionFunction = (current: string, argv: any, done: (completion: ReadonlyArray<string>) => void) => void; type PromiseCompletionFunction = (current: string, argv: any) => Promise<string[]>; type MiddlewareFunction<T = {}> = (args: Arguments<T>) => void; type Choices = ReadonlyArray<string | number | true | undefined>; type PositionalOptionsType = "boolean" | "number" | "string"; } declare var yargs: yargs.Argv; export = yargs;
Java
using Mono.Cecil; namespace Cake.Web.Docs.Reflection.Model { /// <summary> /// Represents reflected method information. /// </summary> public interface IMethodInfo { /// <summary> /// Gets the method identity. /// </summary> /// <value>The method identity.</value> string Identity { get; } /// <summary> /// Gets the method definition. /// </summary> /// <value> /// The method definition. /// </value> MethodDefinition Definition { get; } /// <summary> /// The associated metadata. /// </summary> IDocumentationMetadata Metadata { get; } } }
Java
package im.actor.server.api.rpc.service import im.actor.api.rpc.Implicits._ import im.actor.api.rpc._ import im.actor.api.rpc.counters.UpdateCountersChanged import im.actor.api.rpc.groups.{ UpdateGroupInvite, UpdateGroupUserInvited } import im.actor.api.rpc.messaging._ import im.actor.api.rpc.misc.ResponseVoid import im.actor.api.rpc.peers.{ GroupOutPeer, PeerType } import im.actor.server._ import im.actor.server.api.rpc.service.groups.{ GroupInviteConfig, GroupsServiceImpl } import im.actor.server.group.GroupOffice import im.actor.server.presences.{ GroupPresenceManager, PresenceManager } import im.actor.server.util.ACLUtils import scala.concurrent.Future import scala.util.Random class MessagingServiceHistorySpec extends BaseAppSuite with GroupsServiceHelpers with ImplicitFileStorageAdapter with ImplicitSessionRegionProxy with ImplicitGroupRegions with ImplicitAuthService with ImplicitSequenceService with SequenceMatchers { behavior of "MessagingServiceHistoryService" "Private messaging" should "load history" in s.privat it should "load dialogs" in s.dialogs // TODO: remove this test's dependency on previous example it should "mark messages received and send updates" in s.historyPrivate.markReceived it should "mark messages read and send updates" in s.historyPrivate.markRead "Group messaging" should "mark messages received and send updates" in s.historyGroup.markReceived it should "mark messages read and send updates" in s.historyGroup.markRead it should "Load all history in public groups" in s.public implicit private val presenceManagerRegion = PresenceManager.startRegion() implicit private val groupPresenceManagerRegion = GroupPresenceManager.startRegion() private val groupInviteConfig = GroupInviteConfig("http://actor.im") implicit private val service = messaging.MessagingServiceImpl(mediator) implicit private val groupsService = new GroupsServiceImpl(groupInviteConfig) private object s { val (user1, authId1, _) = createUser() val sessionId1 = createSessionId() val (user2, authId2, _) = createUser() val sessionId2 = createSessionId() val clientData1 = ClientData(authId1, sessionId1, Some(user1.id)) val clientData2 = ClientData(authId2, sessionId2, Some(user2.id)) val user1Model = getUserModel(user1.id) val user1AccessHash = ACLUtils.userAccessHash(authId2, user1.id, user1Model.accessSalt) val user1Peer = peers.OutPeer(PeerType.Private, user1.id, user1AccessHash) val user2Model = getUserModel(user2.id) val user2AccessHash = ACLUtils.userAccessHash(authId1, user2.id, user2Model.accessSalt) val user2Peer = peers.OutPeer(PeerType.Private, user2.id, user2AccessHash) def privat() = { val step = 100L val (message1Date, message2Date, message3Date) = { implicit val clientData = clientData1 val message1Date = whenReady(service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 1", Vector.empty, None)))(_.toOption.get.date) Thread.sleep(step) val message2Date = whenReady(service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 2", Vector.empty, None)))(_.toOption.get.date) Thread.sleep(step) val message3Date = whenReady(service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 3", Vector.empty, None)))(_.toOption.get.date) Thread.sleep(step) whenReady(service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 4", Vector.empty, None)))(_ ⇒ ()) (message1Date, message2Date, message3Date) } Thread.sleep(300) { implicit val clientData = clientData2 whenReady(service.handleMessageReceived(user1Peer, message2Date)) { resp ⇒ resp should matchPattern { case Ok(ResponseVoid) ⇒ } } whenReady(service.handleMessageRead(user1Peer, message1Date)) { resp ⇒ resp should matchPattern { case Ok(ResponseVoid) ⇒ } } } Thread.sleep(1000) { implicit val clientData = clientData1 whenReady(service.handleLoadHistory(user2Peer, message3Date, 100)) { resp ⇒ resp should matchPattern { case Ok(_) ⇒ } val respBody = resp.toOption.get respBody.users.length should ===(0) respBody.history.length should ===(3) respBody.history.map(_.state) should ===(Seq(Some(MessageState.Sent), Some(MessageState.Received), Some(MessageState.Read))) } } } def dialogs() = { { implicit val clientData = clientData1 whenReady(service.handleLoadDialogs(0, 100)) { resp ⇒ resp should matchPattern { case Ok(_) ⇒ } val respBody = resp.toOption.get respBody.dialogs.length should ===(1) val dialog = respBody.dialogs.head dialog.unreadCount should ===(0) respBody.users.length should ===(2) } } { implicit val clientData = clientData2 whenReady(service.handleLoadDialogs(0, 100)) { resp ⇒ resp should matchPattern { case Ok(_) ⇒ } val respBody = resp.toOption.get respBody.dialogs.length should ===(1) val dialog = respBody.dialogs.head dialog.unreadCount should ===(3) respBody.users.length should ===(1) } } } def public() = { val groupId = Random.nextInt val (pubUser, pubAuthId, _) = createUser() val accessHash = whenReady(GroupOffice.create(groupId, pubUser.id, pubAuthId, "Public group", Random.nextLong, Set.empty))(_.accessHash) whenReady(GroupOffice.makePublic(groupId, "Public group description"))(identity) val groupOutPeer = GroupOutPeer(groupId, accessHash) val firstMessage = TextMessage("First", Vector.empty, None) val secondMessage = TextMessage("Second", Vector.empty, None) { implicit val clientData = clientData1 whenReady(groupsService.handleEnterGroup(groupOutPeer))(identity) whenReady(service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), firstMessage))(identity) } { implicit val clientData = clientData2 whenReady(groupsService.handleEnterGroup(groupOutPeer))(identity) whenReady(service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), secondMessage))(identity) Thread.sleep(2000) whenReady(service.handleLoadHistory(groupOutPeer.asOutPeer, 0, 100)) { resp ⇒ val history = resp.toOption.get.history //history does not contain message about group creation, as group was not created by Zero user history.length shouldEqual 4 history.map(_.message) should contain allOf (firstMessage, secondMessage) } } } object historyPrivate { val (user1, authId1, _) = createUser() def markReceived() = { val (user2, authId2, _) = createUser() val sessionId = createSessionId() val clientData1 = ClientData(authId1, sessionId1, Some(user1.id)) val clientData2 = ClientData(authId2, sessionId2, Some(user2.id)) val user1AccessHash = ACLUtils.userAccessHash(authId2, user1.id, getUserModel(user1.id).accessSalt) val user1Peer = peers.OutPeer(PeerType.Private, user1.id, user1AccessHash) val user2AccessHash = ACLUtils.userAccessHash(authId1, user2.id, getUserModel(user2.id).accessSalt) val user2Peer = peers.OutPeer(PeerType.Private, user2.id, user2AccessHash) val startDate = { implicit val clientData = clientData1 val startDate = System.currentTimeMillis() val sendMessages = Future.sequence(Seq( service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 1", Vector.empty, None)), futureSleep(1500).flatMap(_ ⇒ service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 2", Vector.empty, None))), futureSleep(3000).flatMap(_ ⇒ service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 3", Vector.empty, None))) )) whenReady(sendMessages)(_ ⇒ ()) startDate } { implicit val clientData = clientData2 whenReady(service.handleMessageReceived(user1Peer, startDate + 2000)) { resp ⇒ resp should matchPattern { case Ok(ResponseVoid) ⇒ } } Thread.sleep(100) // Let peer managers write to db whenReady(db.run(persist.Dialog.find(user1.id, models.Peer.privat(user2.id)))) { dialogOpt ⇒ dialogOpt.get.lastReceivedAt.getMillis should be < startDate + 3000 dialogOpt.get.lastReceivedAt.getMillis should be > startDate + 1000 } } { implicit val clientData = clientData1 expectUpdatesOrdered(failUnmatched)(0, Array.empty, List( UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageReceived.header )) { case (UpdateMessageSent.header, update) ⇒ parseUpdate[UpdateMessageSent](update) case (UpdateMessageReceived.header, update) ⇒ parseUpdate[UpdateMessageReceived](update) } } } def markRead() = { val (user1, authId1, _) = createUser() val (user2, authId21, _) = createUser() val sessionId = createSessionId() val clientData1 = ClientData(authId1, sessionId, Some(user1.id)) val clientData21 = ClientData(authId21, sessionId, Some(user2.id)) val clientData22 = ClientData(createAuthId(user2.id), sessionId, Some(user2.id)) val user1AccessHash = ACLUtils.userAccessHash(authId21, user1.id, getUserModel(user1.id).accessSalt) val user1Peer = peers.OutPeer(PeerType.Private, user1.id, user1AccessHash) val user2AccessHash = ACLUtils.userAccessHash(authId1, user2.id, getUserModel(user2.id).accessSalt) val user2Peer = peers.OutPeer(PeerType.Private, user2.id, user2AccessHash) val startDate = { implicit val clientData = clientData1 val startDate = System.currentTimeMillis() val sendMessages = Future.sequence(Seq( service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 1", Vector.empty, None)), futureSleep(1500).flatMap(_ ⇒ service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 2", Vector.empty, None))), futureSleep(3000).flatMap(_ ⇒ service.handleSendMessage(user2Peer, Random.nextLong(), TextMessage("Hi Shiva 3", Vector.empty, None))) )) whenReady(sendMessages)(_ ⇒ ()) startDate } { implicit val clientData = clientData21 whenReady(service.handleMessageRead(user1Peer, startDate + 2000)) { resp ⇒ resp should matchPattern { case Ok(ResponseVoid) ⇒ } } Thread.sleep(100) // Let peer managers write to db whenReady(db.run(persist.Dialog.find(user1.id, models.Peer.privat(user2.id)))) { optDialog ⇒ val dialog = optDialog.get dialog.lastReadAt.getMillis should be < startDate + 3000 dialog.lastReadAt.getMillis should be > startDate + 1000 } whenReady(service.handleLoadDialogs(Long.MaxValue, 100)) { resp ⇒ val dialog = resp.toOption.get.dialogs.head dialog.unreadCount shouldEqual 1 } } { implicit val clientData = clientData1 expectUpdatesOrdered(ignoreUnmatched)(0, Array.empty, List( UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageRead.header )) { case (UpdateMessageRead.header, update) ⇒ parseUpdate[UpdateMessageRead](update) } } { implicit val clientData = clientData21 expectUpdatesOrdered(ignoreUnmatched)(0, Array.empty, List( UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header )) { case _ ⇒ } } { //UpdateMessageReadByMe sent to user2 second device implicit val clientData = clientData22 expectUpdatesOrdered(ignoreUnmatched)(0, Array.empty, List( UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header, UpdateMessageReadByMe.header )) { case _ ⇒ } } } } object historyGroup { def markReceived() = { val (user1, authId1, _) = createUser() val (user2, authId2, _) = createUser() val sessionId = createSessionId() val clientData1 = ClientData(authId1, sessionId, Some(user1.id)) val clientData2 = ClientData(authId2, sessionId, Some(user2.id)) val groupOutPeer = { implicit val clientData = clientData1 createGroup("Fun group", Set(user2.id)).groupPeer } val startDate = System.currentTimeMillis() { implicit val clientData = clientData1 val sendMessages = Future.sequence(Seq( service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), TextMessage("Hi Shiva 1", Vector.empty, None)), futureSleep(1500).flatMap(_ ⇒ service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), TextMessage("Hi Shiva 2", Vector.empty, None))), futureSleep(3000).flatMap(_ ⇒ service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), TextMessage("Hi Shiva 3", Vector.empty, None))) )) whenReady(sendMessages)(_ ⇒ ()) } { implicit val clientData = clientData2 whenReady(service.handleMessageReceived(groupOutPeer.asOutPeer, startDate + 2000)) { resp ⇒ resp should matchPattern { case Ok(ResponseVoid) ⇒ } } Thread.sleep(100) // Let peer managers write to db whenReady(db.run(persist.Dialog.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { dialogOpt ⇒ dialogOpt.get.lastReceivedAt.getMillis should be < startDate + 3000 dialogOpt.get.lastReceivedAt.getMillis should be > startDate + 1000 } } { implicit val clientData = clientData1 expectUpdatesUnorderedOnly(ignoreUnmatched)(0, Array.empty, List( UpdateGroupUserInvited.header, UpdateGroupInvite.header, UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageReceived.header )) { case _ ⇒ } } } def markRead() = { val (user1, authId1, _) = createUser() val (user2, authId2, _) = createUser() val sessionId = createSessionId() val clientData1 = ClientData(authId1, sessionId, Some(user1.id)) val clientData2 = ClientData(authId2, sessionId, Some(user2.id)) val groupOutPeer = { implicit val clientData = clientData1 createGroup("Fun group", Set(user2.id)).groupPeer } val startDate = System.currentTimeMillis() { implicit val clientData = clientData1 val sendMessages = Future.sequence(Seq( service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), TextMessage("Hi Shiva 1", Vector.empty, None)), futureSleep(1500).flatMap(_ ⇒ service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), TextMessage("Hi Shiva 2", Vector.empty, None))), futureSleep(3000).flatMap(_ ⇒ service.handleSendMessage(groupOutPeer.asOutPeer, Random.nextLong(), TextMessage("Hi Shiva 3", Vector.empty, None))) )) whenReady(sendMessages)(_ ⇒ ()) } Thread.sleep(300) { implicit val clientData = clientData2 whenReady(service.handleMessageRead(groupOutPeer.asOutPeer, startDate + 2000)) { resp ⇒ resp should matchPattern { case Ok(ResponseVoid) ⇒ } } Thread.sleep(300) whenReady(db.run(persist.Dialog.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { dialogOpt ⇒ dialogOpt.get.lastReadAt.getMillis should be < startDate + 3000 dialogOpt.get.lastReadAt.getMillis should be > startDate + 1000 } whenReady(service.handleLoadDialogs(Long.MaxValue, 100)) { resp ⇒ val dialog = resp.toOption.get.dialogs.head dialog.unreadCount shouldEqual 1 } } { implicit val clientData = clientData1 expectUpdatesUnorderedOnly(ignoreUnmatched)(0, Array.empty, List( UpdateGroupUserInvited.header, UpdateGroupInvite.header, UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageSent.header, UpdateMessageRead.header, UpdateMessage.header, UpdateCountersChanged.header )) { case (UpdateMessageRead.header, update) ⇒ parseUpdate[UpdateMessageRead](update) } } { implicit val clientData = clientData2 expectUpdatesUnorderedOnly(ignoreUnmatched)(0, Array.empty, List( UpdateGroupInvite.header, UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header, UpdateMessage.header, UpdateCountersChanged.header, UpdateMessage.header, UpdateMessageSent.header, //sent message with GroupServiceMessages.userJoined UpdateMessageReadByMe.header, UpdateCountersChanged.header )) { case (UpdateMessageReadByMe.header, update) ⇒ parseUpdate[UpdateMessageReadByMe](update) case (UpdateMessageSent.header, update) ⇒ parseUpdate[UpdateMessageSent](update) } } } } } }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2d357d86-395a-43e1-9c1b-da7a228f2e0a")]
Java
<?php /** * This file is part of the Zephir. * * (c) Phalcon Team <[email protected]> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Zephir\Detectors; /** * ForValueUseDetector. * * Detects whether the traversed variable is modified within the 'for's block */ class ForValueUseDetector extends WriteDetector { /** * ForValueUseDetector constructor. * * Initialize detector with safe defaults */ public function __construct() { $this->setDetectionFlags(self::DETECT_NONE); } }
Java
<?php namespace Platformsh\Cli\Command\Integration; use Platformsh\Cli\Command\PlatformCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class IntegrationDeleteCommand extends PlatformCommand { /** * {@inheritdoc} */ protected function configure() { $this ->setName('integration:delete') ->addArgument('id', InputArgument::REQUIRED, 'The integration ID') ->setDescription('Delete an integration from a project'); $this->addProjectOption(); } protected function execute(InputInterface $input, OutputInterface $output) { $this->validateInput($input); $id = $input->getArgument('id'); $integration = $this->getSelectedProject() ->getIntegration($id); if (!$integration) { $this->stdErr->writeln("Integration not found: <error>$id</error>"); return 1; } if (!$integration->operationAvailable('delete')) { $this->stdErr->writeln("The integration <error>$id</error> cannot be deleted"); return 1; } $type = $integration->getProperty('type'); $confirmText = "Delete the integration <info>$id</info> (type: $type)?"; if (!$this->getHelper('question') ->confirm($confirmText, $input, $this->stdErr) ) { return 1; } $integration->delete(); $this->stdErr->writeln("Deleted integration <info>$id</info>"); return 0; } }
Java
# Wind River Workbench generated Makefile. # Do not edit!!! # # The file ".wrmakefile" is the template used by the Wind River Workbench to # generate the makefiles of this project. Add user-specific build targets and # make rules only(!) in this project's ".wrmakefile" file. These will then be # automatically dumped into the makefiles. WIND_HOME := $(subst \,/,$(WIND_HOME)) WIND_BASE := $(subst \,/,$(WIND_BASE)) WIND_USR := $(subst \,/,$(WIND_USR)) WRVX_COMPBASE := $(subst \,/,$(WRVX_COMPBASE)) all : pre_build main_all post_build _clean :: @echo "make: removing targets and objects of `pwd`" TRACE=0 TRACEON=$(TRACE:0=@) TRACE_FLAG=$(TRACEON:1=) JOBS?=1 TARGET_JOBS?=$(JOBS) MAKEFILE := Makefile FLEXIBLE_BUILD := 1 BUILD_SPEC = SIMNTdiab DEBUG_MODE = 1 ifeq ($(DEBUG_MODE),1) MODE_DIR := Debug else MODE_DIR := NonDebug endif OBJ_DIR := . WS_ROOT_DIR := C:/_HP PRJ_ROOT_DIR := $(WS_ROOT_DIR)/StateMachine #Global Build Macros PROJECT_TYPE = DKM DEFINES = EXPAND_DBG = 0 #BuildSpec specific Build Macros VX_CPU_FAMILY = simpc CPU = SIMNT TOOL_FAMILY = diab TOOL = diab TOOL_PATH = CC_ARCH_SPEC = -tX86LH:vxworks69 VSB_DIR = $(WIND_BASE)/target/lib VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h LIBPATH = LIBS = IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND_BASE)/target/h/wrn/coreip IDE_LIBRARIES = IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\" -DIP_PORT_VXWORKS=69 #BuildTool flags ifeq ($(DEBUG_MODE),1) DEBUGFLAGS_C-Compiler = -g DEBUGFLAGS_C++-Compiler = -g DEBUGFLAGS_Linker = -g DEBUGFLAGS_Partial-Image-Linker = DEBUGFLAGS_Librarian = DEBUGFLAGS_Assembler = -g else DEBUGFLAGS_C-Compiler = -XO -Xsize-opt DEBUGFLAGS_C++-Compiler = -XO -Xsize-opt DEBUGFLAGS_Linker = -XO -Xsize-opt DEBUGFLAGS_Partial-Image-Linker = DEBUGFLAGS_Librarian = DEBUGFLAGS_Assembler = -XO -Xsize-opt endif #Project Targets PROJECT_TARGETS = StateMachine/$(MODE_DIR)/StateMachine.out \ StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage.o #Rules # StateMachine ifeq ($(DEBUG_MODE),1) StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -g StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -g StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -g StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -g else StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -XO -Xsize-opt StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -XO -Xsize-opt StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -XO -Xsize-opt StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = StateMachine/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -XO -Xsize-opt endif StateMachine/$(MODE_DIR)/% : IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND_BASE)/target/h/wrn/coreip StateMachine/$(MODE_DIR)/% : IDE_LIBRARIES = StateMachine/$(MODE_DIR)/% : IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\" -DIP_PORT_VXWORKS=69 StateMachine/$(MODE_DIR)/% : PROJECT_TYPE = DKM StateMachine/$(MODE_DIR)/% : DEFINES = StateMachine/$(MODE_DIR)/% : EXPAND_DBG = 0 StateMachine/$(MODE_DIR)/% : VX_CPU_FAMILY = simpc StateMachine/$(MODE_DIR)/% : CPU = SIMNT StateMachine/$(MODE_DIR)/% : TOOL_FAMILY = diab StateMachine/$(MODE_DIR)/% : TOOL = diab StateMachine/$(MODE_DIR)/% : TOOL_PATH = StateMachine/$(MODE_DIR)/% : CC_ARCH_SPEC = -tX86LH:vxworks69 StateMachine/$(MODE_DIR)/% : VSB_DIR = $(WIND_BASE)/target/lib StateMachine/$(MODE_DIR)/% : VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h StateMachine/$(MODE_DIR)/% : LIBPATH = StateMachine/$(MODE_DIR)/% : LIBS = StateMachine/$(MODE_DIR)/% : OBJ_DIR := StateMachine/$(MODE_DIR) OBJECTS_StateMachine = StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage.o ifeq ($(TARGET_JOBS),1) StateMachine/$(MODE_DIR)/StateMachine.out : $(OBJECTS_StateMachine) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@";rm -f "$@";ddump -Ng $(OBJECTS_StateMachine) | tclsh $(WIND_BASE)/host/resource/hutils/tcl/munch.tcl -c pentium -tags $(VSB_DIR)/tags/simpc/SIMNT/common/dkm.tags > $(OBJ_DIR)/ctdt.c; $(TOOL_PATH)dcc $(DEBUGFLAGS_Linker) $(CC_ARCH_SPEC) -Xdollar-in-ident -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) $(IDE_DEFINES) $(DEFINES) -o $(OBJ_DIR)/ctdt.o -c $(OBJ_DIR)/ctdt.c; $(TOOL_PATH)dld -tX86LH:vxworks69 -X -r5 -f 0x90,1,1 -r4 -o "$@" $(OBJ_DIR)/ctdt.o $(OBJECTS_StateMachine) $(IDE_LIBRARIES) $(LIBPATH) $(LIBS) $(ADDED_LIBPATH) $(ADDED_LIBS) && if [ "$(EXPAND_DBG)" = "1" ]; then plink "$@";fi else StateMachine/$(MODE_DIR)/StateMachine.out : StateMachine/$(MODE_DIR)/StateMachine.out_jobs endif StateMachine/$(MODE_DIR)/StateMachine_compile_file : $(FILE) ; _clean :: StateMachine/$(MODE_DIR)/StateMachine_clean StateMachine/$(MODE_DIR)/StateMachine_clean : $(TRACE_FLAG)if [ -d "StateMachine" ]; then cd "StateMachine"; rm -rf $(MODE_DIR); fi # StateMachine_partialImage ifeq ($(DEBUG_MODE),1) StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -g StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -g StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -g StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -g else StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -XO -Xsize-opt StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -XO -Xsize-opt StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -XO -Xsize-opt StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker = StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Librarian = StateMachine_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -XO -Xsize-opt endif StateMachine_partialImage/$(MODE_DIR)/% : IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND_BASE)/target/h/wrn/coreip StateMachine_partialImage/$(MODE_DIR)/% : IDE_LIBRARIES = StateMachine_partialImage/$(MODE_DIR)/% : IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\" -DIP_PORT_VXWORKS=69 StateMachine_partialImage/$(MODE_DIR)/% : PROJECT_TYPE = DKM StateMachine_partialImage/$(MODE_DIR)/% : DEFINES = StateMachine_partialImage/$(MODE_DIR)/% : EXPAND_DBG = 0 StateMachine_partialImage/$(MODE_DIR)/% : VX_CPU_FAMILY = simpc StateMachine_partialImage/$(MODE_DIR)/% : CPU = SIMNT StateMachine_partialImage/$(MODE_DIR)/% : TOOL_FAMILY = diab StateMachine_partialImage/$(MODE_DIR)/% : TOOL = diab StateMachine_partialImage/$(MODE_DIR)/% : TOOL_PATH = StateMachine_partialImage/$(MODE_DIR)/% : CC_ARCH_SPEC = -tX86LH:vxworks69 StateMachine_partialImage/$(MODE_DIR)/% : VSB_DIR = $(WIND_BASE)/target/lib StateMachine_partialImage/$(MODE_DIR)/% : VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h StateMachine_partialImage/$(MODE_DIR)/% : LIBPATH = StateMachine_partialImage/$(MODE_DIR)/% : LIBS = StateMachine_partialImage/$(MODE_DIR)/% : OBJ_DIR := StateMachine_partialImage/$(MODE_DIR) StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/diaTimer.o : $(PRJ_ROOT_DIR)/diaTimer.cpp $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/disp.o : $(PRJ_ROOT_DIR)/hardware/disp.c $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -Xc-new -Xdialect-c89 -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/hwFunc.o : $(PRJ_ROOT_DIR)/hardware/hwFunc.c $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -Xc-new -Xdialect-c89 -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/kbd.o : $(PRJ_ROOT_DIR)/hardware/kbd.c $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -Xc-new -Xdialect-c89 -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/keyboard.o : $(PRJ_ROOT_DIR)/keyboard.cpp $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/main.o : $(PRJ_ROOT_DIR)/main.cpp $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/setMyIP.o : $(PRJ_ROOT_DIR)/setMyIP.cpp $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/stateMachine.o : $(PRJ_ROOT_DIR)/stateMachine.cpp $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/stateTable.o : $(PRJ_ROOT_DIR)/stateTable.cpp $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/systemManager.o : $(PRJ_ROOT_DIR)/systemManager.cpp $(FORCE_FILE_BUILD) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dcc $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -W:c:,-Xclib-optim-off -Xansi -Xlocal-data-area-static-only -W:c++:.CPP -ei1518,4177,4223,4301,4550,5409,1606 -ei4193,4826,4381,4237,1573,4007,4082,4177,4223,4260,4550,5361,5828,2273,5387,5388 -ei1522,4092,4111,4152,4167,4171,4174,4186,4188,4191,4192,4223,4231,4236,4284,4375,4494,4513,5152,5457 -Xforce-declarations -Xmake-dependency=0xd $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<" OBJECTS_StateMachine_partialImage = StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/diaTimer.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/disp.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/hwFunc.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/kbd.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/keyboard.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/main.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/setMyIP.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/stateMachine.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/stateTable.o \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/systemManager.o ifeq ($(TARGET_JOBS),1) StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage.o : $(OBJECTS_StateMachine_partialImage) $(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)dld -tX86LH:vxworks69 -X -r5 -f 0x90,1,1 -o "$@" $(OBJECTS_StateMachine_partialImage) $(ADDED_OBJECTS) $(IDE_LIBRARIES) $(LIBPATH) $(LIBS) $(ADDED_LIBPATH) $(ADDED_LIBS) && if [ "$(EXPAND_DBG)" = "1" ]; then plink "$@";fi else StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage.o : StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage.o_jobs endif StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage_compile_file : $(FILE) ; _clean :: StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage_clean StateMachine_partialImage/$(MODE_DIR)/StateMachine_partialImage_clean : $(TRACE_FLAG)if [ -d "StateMachine_partialImage" ]; then cd "StateMachine_partialImage"; rm -rf $(MODE_DIR); fi force : TARGET_JOBS_RULE?=echo "Update the makefile template via File > Import > Build Settings : Update makefile template";exit 1 %_jobs : $(TRACE_FLAG)$(TARGET_JOBS_RULE) DEP_FILES := StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/diaTimer.d StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/disp.d StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/hwFunc.d \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/hardware/kbd.d StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/keyboard.d StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/main.d \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/setMyIP.d StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/stateMachine.d StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/stateTable.d \ StateMachine_partialImage/$(MODE_DIR)/Objects/StateMachine/systemManager.d -include $(DEP_FILES) WIND_SCOPETOOLS_BASE := $(subst \,/,$(WIND_SCOPETOOLS_BASE)) clean_scopetools : $(TRACE_FLAG)rm -rf $(PRJ_ROOT_DIR)/.coveragescope/db CLEAN_STEP := clean_scopetools -include $(PRJ_ROOT_DIR)/*.makefile -include *.makefile TARGET_JOBS_RULE=$(MAKE) -f $(MAKEFILE) --jobs $(TARGET_JOBS) $(MFLAGS) $* TARGET_JOBS=1 ifeq ($(JOBS),1) main_all : external_build $(PROJECT_TARGETS) @echo "make: built targets of `pwd`" else main_all : external_build @$(MAKE) -f $(MAKEFILE) --jobs $(JOBS) $(MFLAGS) $(PROJECT_TARGETS) TARGET_JOBS=1 &&\ echo "make: built targets of `pwd`" endif # entry point for extending the build external_build :: @echo "" # main entry point for pre processing prior to the build pre_build :: $(PRE_BUILD_STEP) generate_sources @echo "" # entry point for generating sources prior to the build generate_sources :: @echo "" # main entry point for post processing after the build post_build :: $(POST_BUILD_STEP) deploy_output @echo "" # entry point for deploying output after the build deploy_output :: @echo "" clean :: external_clean $(CLEAN_STEP) _clean # entry point for extending the build clean external_clean :: @echo ""
Java
__author__ = 'Nishanth' from juliabox.cloud import JBPluginCloud from juliabox.jbox_util import JBoxCfg, retry_on_errors from googleapiclient.discovery import build from oauth2client.client import GoogleCredentials import threading class JBoxGCD(JBPluginCloud): provides = [JBPluginCloud.JBP_DNS, JBPluginCloud.JBP_DNS_GCD] threadlocal = threading.local() INSTALLID = None REGION = None DOMAIN = None @staticmethod def configure(): cloud_host = JBoxCfg.get('cloud_host') JBoxGCD.INSTALLID = cloud_host['install_id'] JBoxGCD.REGION = cloud_host['region'] JBoxGCD.DOMAIN = cloud_host['domain'] @staticmethod def domain(): if JBoxGCD.DOMAIN is None: JBoxGCD.configure() return JBoxGCD.DOMAIN @staticmethod def connect(): c = getattr(JBoxGCD.threadlocal, 'conn', None) if c is None: JBoxGCD.configure() creds = GoogleCredentials.get_application_default() JBoxGCD.threadlocal.conn = c = build("dns", "v1", credentials=creds) return c @staticmethod @retry_on_errors(retries=2) def add_cname(name, value): JBoxGCD.connect().changes().create( project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION, body={'kind': 'dns#change', 'additions': [ {'rrdatas': [value], 'kind': 'dns#resourceRecordSet', 'type': 'A', 'name': name, 'ttl': 300} ] }).execute() @staticmethod @retry_on_errors(retries=2) def delete_cname(name): resp = JBoxGCD.connect().resourceRecordSets().list( project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION, name=name, type='A').execute() if len(resp['rrsets']) == 0: JBoxGCD.log_debug('No prior dns registration found for %s', name) else: cname = resp['rrsets'][0]['rrdatas'][0] ttl = resp['rrsets'][0]['ttl'] JBoxGCD.connect().changes().create( project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION, body={'kind': 'dns#change', 'deletions': [ {'rrdatas': [str(cname)], 'kind': 'dns#resourceRecordSet', 'type': 'A', 'name': name, 'ttl': ttl} ] }).execute() JBoxGCD.log_warn('Prior dns registration was found for %s', name)
Java
require 'rails' module StripeI18n class Railtie < ::Rails::Railtie initializer 'stripe-i18n' do |app| StripeI18n::Railtie.instance_eval do pattern = pattern_from app.config.i18n.available_locales add("rails/locale/#{pattern}.yml") end end protected def self.add(pattern) files = Dir[File.join(File.dirname(__FILE__), '../..', pattern)] I18n.load_path.concat(files) end def self.pattern_from(args) array = Array(args || []) array.blank? ? '*' : "{#{array.join ','}}" end end end
Java
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.node_monitors; import hudson.Extension; import hudson.FilePath; import hudson.Functions; import hudson.model.Computer; import hudson.remoting.Callable; import jenkins.model.Jenkins; import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace; import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; import java.text.ParseException; /** * Checks available disk space of the remote FS root. * Requires Mustang. * * @author Kohsuke Kawaguchi * @since 1.123 */ public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor { @DataBoundConstructor public DiskSpaceMonitor(String freeSpaceThreshold) throws ParseException { super(freeSpaceThreshold); } public DiskSpaceMonitor() {} public DiskSpace getFreeSpace(Computer c) { return DESCRIPTOR.get(c); } @Override public String getColumnCaption() { // Hide this column from non-admins return Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ? super.getColumnCaption() : null; } public static final DiskSpaceMonitorDescriptor DESCRIPTOR = new DiskSpaceMonitorDescriptor() { public String getDisplayName() { return Messages.DiskSpaceMonitor_DisplayName(); } @Override protected Callable<DiskSpace, IOException> createCallable(Computer c) { FilePath p = c.getNode().getRootPath(); if(p==null) return null; return p.asCallableWith(new GetUsableSpace()); } }; @Extension public static DiskSpaceMonitorDescriptor install() { if(Functions.isMustangOrAbove()) return DESCRIPTOR; return null; } }
Java
class PersonalFileUploader < FileUploader def self.dynamic_path_segment(model) File.join(CarrierWave.root, model_path(model)) end def self.base_dir File.join(root_dir, '-', 'system') end private def secure_url File.join(self.class.model_path(model), secret, file.filename) end def self.model_path(model) if model File.join("/#{base_dir}", model.class.to_s.underscore, model.id.to_s) else File.join("/#{base_dir}", 'temp') end end end
Java
<?php /** * @copyright 2006-2013, Miles Johnson - http://milesj.me * @license http://opensource.org/licenses/mit-license.php * @link http://milesj.me/code/php/transit */ namespace Transit\Transformer\Image; use Transit\File; use \InvalidArgumentException; /** * Crops a photo, but resizes and keeps aspect ratio depending on which side is larger. * * @package Transit\Transformer\Image */ class CropTransformer extends AbstractImageTransformer { const TOP = 'top'; const BOTTOM = 'bottom'; const LEFT = 'left'; const RIGHT = 'right'; const CENTER = 'center'; /** * Configuration. * * @type array { * @type string $location Location to crop from the source image * @type int $quality Quality of JPEG image * @type int $width Width of output image * @type int $height Height of output image * } */ protected $_config = array( 'location' => self::CENTER, 'quality' => 100, 'width' => null, 'height' => null ); /** * {@inheritdoc} * * @throws \InvalidArgumentException */ public function transform(File $file, $self = false) { $config = $this->getConfig(); $baseWidth = $file->width(); $baseHeight = $file->height(); $width = $config['width']; $height = $config['height']; if (is_numeric($width) && !$height) { $height = round(($baseHeight / $baseWidth) * $width); } else if (is_numeric($height) && !$width) { $width = round(($baseWidth / $baseHeight) * $height); } else if (!is_numeric($height) && !is_numeric($width)) { throw new InvalidArgumentException('Invalid width and height for crop'); } $location = $config['location']; $widthScale = $baseWidth / $width; $heightScale = $baseHeight / $height; $src_x = 0; $src_y = 0; $src_w = $baseWidth; $src_h = $baseHeight; // If an array is passed, use those dimensions if (is_array($location)) { list($src_x, $src_y, $src_w, $src_h) = $location; // Source width is larger, use height scale as the base } else { if ($widthScale > $heightScale) { $src_w = $width * $heightScale; // Position horizontally in the middle if ($location === self::CENTER) { $src_x = ($baseWidth / 2) - (($width / 2) * $heightScale); // Position at the far right } else if ($location === self::RIGHT || $location === self::BOTTOM) { $src_x = $baseWidth - $src_w; } // Source height is larger, use width scale as the base } else { $src_h = $height * $widthScale; // Position vertically in the middle if ($location === self::CENTER) { $src_y = ($baseHeight / 2) - (($height / 2) * $widthScale); // Position at the bottom } else if ($location === self::RIGHT || $location === self::BOTTOM) { $src_y = $baseHeight - $src_h; } } } return $this->_process($file, array( 'dest_w' => $width, 'dest_h' => $height, 'source_x' => $src_x, 'source_y' => $src_y, 'source_w' => $src_w, 'source_h' => $src_h, 'quality' => $config['quality'], 'overwrite' => $self )); } }
Java
--- title: Putain de code ! url: http://putaindecode.io/ source: https://github.com/putaindecode/putaindecode.io showcaseTags: - open-source - community - learning - multi-languages ---
Java
teleirc ======= Telegram <-> IRC gateway. * Uses the [node-telegram-bot](https://github.com/orzFly/node-telegram-bot) library for Telegram communication * IRC communication via martynsmith's [node-irc](https://github.com/martynsmith/node-irc) module * All Telegram messages are sent to IRC channel * IRC messages sent to Telegram only when bot is hilighted (configurable) Setup ----- git clone https://github.com/FruitieX/teleirc cd teleirc npm install cp teleirc_config.js.example ~/.teleirc_config.js Next, set up your bot via the [BotFather](https://telegram.me/botfather) Telegram user. Save your bot token in `~/.teleirc_config.js`. Remember to allow the bot to see all messages via the `/setprivacy` command to `BotFather`, otherwise only messages starting with a slash are visible to teleirc. Now read through the rest of `~/.teleirc_config.js` and change the configuration as appropriate. When you're done, launch teleirc with: npm start Optional: - For your convenience, there is an included systemd unit file in `teleirc.service`. - You can change your Telegram Bot's profile picture with the `/setuserpic` BotFather command. Special thanks -------------- Thanks to [warbaque](https://github.com/warbaque) for an implementation using Telegram Bot API!
Java
require 'spec_helper' describe "php::5_5_4" do let(:facts) { default_test_facts } it do should contain_php__version("5.5.4") end end
Java
<?php /* * $Id: MssqlPlatform.php 3752 2007-04-11 09:11:18Z fabien $ * * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://propel.phpdb.org>. */ require_once 'propel/engine/platform/DefaultPlatform.php'; include_once 'propel/engine/database/model/Domain.php'; /** * MS SQL Platform implementation. * * @author Hans Lellelid <[email protected]> (Propel) * @author Martin Poeschl <[email protected]> (Torque) * @version $Revision: 536 $ * @package propel.engine.platform */ class MssqlPlatform extends DefaultPlatform { /** * Initializes db specific domain mapping. */ protected function initialize() { parent::initialize(); $this->setSchemaDomainMapping(new Domain(PropelTypes::INTEGER, "INT")); $this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, "INT")); $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, "FLOAT")); $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "TEXT")); $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "TEXT")); $this->setSchemaDomainMapping(new Domain(PropelTypes::DATE, "DATETIME")); $this->setSchemaDomainMapping(new Domain(PropelTypes::BU_DATE, "DATETIME")); $this->setSchemaDomainMapping(new Domain(PropelTypes::TIME, "DATETIME")); $this->setSchemaDomainMapping(new Domain(PropelTypes::TIMESTAMP, "DATETIME")); $this->setSchemaDomainMapping(new Domain(PropelTypes::BU_TIMESTAMP, "DATETIME")); $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BINARY(7132)")); $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "IMAGE")); $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "IMAGE")); $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "IMAGE")); } /** * @see Platform#getMaxColumnNameLength() */ public function getMaxColumnNameLength() { return 128; } /** * @return Explicitly returns <code>NULL</code> if null values are * allowed (as recomended by Microsoft). * @see Platform#getNullString(boolean) */ public function getNullString($notNull) { return ($notNull ? "NOT NULL" : "NULL"); } /** * @see Platform::supportsNativeDeleteTrigger() */ public function supportsNativeDeleteTrigger() { return true; } /** * @see Platform::hasSize(String) */ public function hasSize($sqlType) { return !("INT" == $sqlType || "TEXT" == $sqlType); } /** * @see Platform::quoteIdentifier() */ public function quoteIdentifier($text) { return '[' . $text . ']'; } }
Java