repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
dcarroll/Analytics-Cloud-Dataset-Utils
src/main/java/com/sforce/dataset/flow/monitor/JobEntry.java
3407
/* * Copyright (c) 2014, salesforce.com, 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 salesforce.com, 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. */ package com.sforce.dataset.flow.monitor; public class JobEntry implements Comparable<JobEntry> { String errorMessage = null; long startTimeEpoch = 0; int status = 0; long endTimeEpoch = 0; String _uid = null; String type = null; String endTime = null; String startTime = null; String _type = null; long duration= 0; long _createdDateTime = 0; String workflowName = null; String nodeUrl = null; public String getErrorMessage() { return errorMessage; } public long getStartTimeEpoch() { return startTimeEpoch; } public int getStatus() { return status; } public long getEndTimeEpoch() { return endTimeEpoch; } public String get_uid() { return _uid; } public String getType() { return type; } public String getEndTime() { return endTime; } public String getStartTime() { return startTime; } public String get_type() { return _type; } public long getDuration() { return duration; } public long get_createdDateTime() { return _createdDateTime; } public String getWorkflowName() { return workflowName; } public String getNodeUrl() { return nodeUrl; } @Override public String toString() { return "JobEntry [errorMessage=" + errorMessage + ", startTimeEpoch=" + startTimeEpoch + ", status=" + status + ", endTimeEpoch=" + endTimeEpoch + ", _uid=" + _uid + ", type=" + type + ", endTime=" + endTime + ", startTime=" + startTime + ", _type=" + _type + ", duration=" + duration + ", _createdDateTime=" + _createdDateTime + ", workflowName=" + workflowName + ", nodeUrl=" + nodeUrl + "]"; } @Override public int compareTo(JobEntry o) { if (this.startTimeEpoch > o.startTimeEpoch) return 1; else if (this.startTimeEpoch < o.startTimeEpoch) return -1; else return 0; } }
bsd-3-clause
advancingu/QmlOgre
lib/ogreengine.cpp
4971
/*! * \copyright (c) Nokia Corporation and/or its subsidiary(-ies) (qt-info@nokia.com) and/or contributors * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * \license{This source file is part of QmlOgre abd subject to the BSD license that is bundled * with this source code in the file LICENSE.} */ #include "ogreengine.h" #include "ogreitem.h" #include <QOpenGLFunctions> OgreEngine::OgreEngine(QQuickWindow *window) : QObject(), m_resources_cfg(Ogre::StringUtil::BLANK) { qmlRegisterType<OgreItem>("Ogre", 1, 0, "OgreItem"); qmlRegisterType<OgreEngine>("OgreEngine", 1, 0, "OgreEngine"); setQuickWindow(window); } OgreEngine::~OgreEngine() { delete m_ogreContext; } Ogre::Root* OgreEngine::startEngine() { m_resources_cfg = "resources.cfg"; activateOgreContext(); Ogre::Root *ogreRoot = new Ogre::Root; Ogre::RenderSystem *renderSystem = ogreRoot->getRenderSystemByName("OpenGL Rendering Subsystem"); ogreRoot->setRenderSystem(renderSystem); ogreRoot->initialise(false); Ogre::NameValuePairList params; params["externalGLControl"] = "true"; params["currentGLContext"] = "true"; //Finally create our window. m_ogreWindow = ogreRoot->createRenderWindow("OgreWindow", 1, 1, false, &params); m_ogreWindow->setVisible(false); m_ogreWindow->update(false); doneOgreContext(); return ogreRoot; } void OgreEngine::stopEngine(Ogre::Root *ogreRoot) { if (ogreRoot) { // m_root->detachRenderTarget(m_renderTexture); // TODO tell node(s) to detach } delete ogreRoot; } void OgreEngine::setQuickWindow(QQuickWindow *window) { Q_ASSERT(window); m_quickWindow = window; m_qtContext = QOpenGLContext::currentContext(); // create a new shared OpenGL context to be used exclusively by Ogre m_ogreContext = new QOpenGLContext(); m_ogreContext->setFormat(m_quickWindow->requestedFormat()); m_ogreContext->setShareContext(m_qtContext); m_ogreContext->create(); } void OgreEngine::activateOgreContext() { glPopAttrib(); glPopClientAttrib(); m_qtContext->functions()->glUseProgram(0); m_qtContext->doneCurrent(); m_ogreContext->makeCurrent(m_quickWindow); } void OgreEngine::doneOgreContext() { m_ogreContext->functions()->glBindBuffer(GL_ARRAY_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); m_ogreContext->functions()->glBindRenderbuffer(GL_RENDERBUFFER, 0); m_ogreContext->functions()->glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); // unbind all possible remaining buffers; just to be on safe side m_ogreContext->functions()->glBindBuffer(GL_ARRAY_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_COPY_READ_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_COPY_WRITE_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0); // m_ogreContext->functions()->glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); // m_ogreContext->functions()->glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_TEXTURE_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, 0); m_ogreContext->functions()->glBindBuffer(GL_UNIFORM_BUFFER, 0); m_ogreContext->doneCurrent(); m_qtContext->makeCurrent(m_quickWindow); glPushAttrib(GL_ALL_ATTRIB_BITS); glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); } QOpenGLContext* OgreEngine::ogreContext() const { return m_ogreContext; } QSGTexture* OgreEngine::createTextureFromId(uint id, const QSize &size, QQuickWindow::CreateTextureOptions options) const { return m_quickWindow->createTextureFromId(id, size, options); } void OgreEngine::setupResources(void) { // Load resource paths from config file Ogre::ConfigFile cf; cf.load(m_resources_cfg); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); }
bsd-3-clause
fu-tao/meelier_c2.0
public/assets/manage/js/editor_pt_view.js
784
(function(win){ var editorPTView = win.editorPTView = function(obj, data, domain) { obj.html(''); for(var i=0; i<data.length; i++) { var t = data[i].type; var v = data[i].value; var box = $('<div class="item"></div>'); switch (t) { case 'img': box.append('<img class="img" src="' + (domain + v) + '">'); break; case 'text': box.append('<p class="text">' + v + '</p>'); break; case 'title': box.append('<h3 class="title">' + v + '</h3>'); break; } obj.append(box); } obj.removeClass('hide'); } })(window);
bsd-3-clause
gjo/babel
babel/core.py
30389
# -*- coding: utf-8 -*- """ babel.core ~~~~~~~~~~ Core locale representation and locale data access. :copyright: (c) 2013 by the Babel Team. :license: BSD, see LICENSE for more details. """ import os from babel import localedata from babel._compat import pickle, string_types __all__ = ['UnknownLocaleError', 'Locale', 'default_locale', 'negotiate_locale', 'parse_locale'] _global_data = None def _raise_no_data_error(): raise RuntimeError('The babel data files are not available. ' 'This usually happens because you are using ' 'a source checkout from Babel and you did ' 'not build the data files. Just make sure ' 'to run "python setup.py import_cldr" before ' 'installing the library.') def get_global(key): """Return the dictionary for the given key in the global data. The global data is stored in the ``babel/global.dat`` file and contains information independent of individual locales. >>> get_global('zone_aliases')['UTC'] u'Etc/GMT' >>> get_global('zone_territories')['Europe/Berlin'] u'DE' .. versionadded:: 0.9 :param key: the data key """ global _global_data if _global_data is None: dirname = os.path.join(os.path.dirname(__file__)) filename = os.path.join(dirname, 'global.dat') if not os.path.isfile(filename): _raise_no_data_error() fileobj = open(filename, 'rb') try: _global_data = pickle.load(fileobj) finally: fileobj.close() return _global_data.get(key, {}) LOCALE_ALIASES = { 'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ', 'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES', 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES', 'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it': 'it_IT', 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV', 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL', 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI', 'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA' } class UnknownLocaleError(Exception): """Exception thrown when a locale is requested for which no locale data is available. """ def __init__(self, identifier): """Create the exception. :param identifier: the identifier string of the unsupported locale """ Exception.__init__(self, 'unknown locale %r' % identifier) #: The identifier of the locale that could not be found. self.identifier = identifier class Locale(object): """Representation of a specific locale. >>> locale = Locale('en', 'US') >>> repr(locale) "Locale('en', territory='US')" >>> locale.display_name u'English (United States)' A `Locale` object can also be instantiated from a raw locale string: >>> locale = Locale.parse('en-US', sep='-') >>> repr(locale) "Locale('en', territory='US')" `Locale` objects provide access to a collection of locale data, such as territory and language names, number and date format patterns, and more: >>> locale.number_symbols['decimal'] u'.' If a locale is requested for which no locale data is available, an `UnknownLocaleError` is raised: >>> Locale.parse('en_DE') Traceback (most recent call last): ... UnknownLocaleError: unknown locale 'en_DE' For more information see :rfc:`3066`. """ def __init__(self, language, territory=None, script=None, variant=None): """Initialize the locale object from the given identifier components. >>> locale = Locale('en', 'US') >>> locale.language 'en' >>> locale.territory 'US' :param language: the language code :param territory: the territory (country or region) code :param script: the script code :param variant: the variant code :raise `UnknownLocaleError`: if no locale data is available for the requested locale """ #: the language code self.language = language #: the territory (country or region) code self.territory = territory #: the script code self.script = script #: the variant code self.variant = variant self.__data = None identifier = str(self) if not localedata.exists(identifier): raise UnknownLocaleError(identifier) @classmethod def default(cls, category=None, aliases=LOCALE_ALIASES): """Return the system default locale for the specified category. >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']: ... os.environ[name] = '' >>> os.environ['LANG'] = 'fr_FR.UTF-8' >>> Locale.default('LC_MESSAGES') Locale('fr', territory='FR') The following fallbacks to the variable are always considered: - ``LANGUAGE`` - ``LC_ALL`` - ``LC_CTYPE`` - ``LANG`` :param category: one of the ``LC_XXX`` environment variable names :param aliases: a dictionary of aliases for locale identifiers """ # XXX: use likely subtag expansion here instead of the # aliases dictionary. locale_string = default_locale(category, aliases=aliases) return cls.parse(locale_string) @classmethod def negotiate(cls, preferred, available, sep='_', aliases=LOCALE_ALIASES): """Find the best match between available and requested locale strings. >>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT']) Locale('de', territory='DE') >>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de']) Locale('de') >>> Locale.negotiate(['de_DE', 'de'], ['en_US']) You can specify the character used in the locale identifiers to separate the differnet components. This separator is applied to both lists. Also, case is ignored in the comparison: >>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-') Locale('de', territory='DE') :param preferred: the list of locale identifers preferred by the user :param available: the list of locale identifiers available :param aliases: a dictionary of aliases for locale identifiers """ identifier = negotiate_locale(preferred, available, sep=sep, aliases=aliases) if identifier: return Locale.parse(identifier, sep=sep) @classmethod def parse(cls, identifier, sep='_', resolve_likely_subtags=True): """Create a `Locale` instance for the given locale identifier. >>> l = Locale.parse('de-DE', sep='-') >>> l.display_name u'Deutsch (Deutschland)' If the `identifier` parameter is not a string, but actually a `Locale` object, that object is returned: >>> Locale.parse(l) Locale('de', territory='DE') This also can perform resolving of likely subtags which it does by default. This is for instance useful to figure out the most likely locale for a territory you can use ``'und'`` as the language tag: >>> Locale.parse('und_AT') Locale('de', territory='AT') :param identifier: the locale identifier string :param sep: optional component separator :param resolve_likely_subtags: if this is specified then a locale will have its likely subtag resolved if the locale otherwise does not exist. For instance ``zh_TW`` by itself is not a locale that exists but Babel can automatically expand it to the full form of ``zh_hant_TW``. Note that this expansion is only taking place if no locale exists otherwise. For instance there is a locale ``en`` that can exist by itself. :raise `ValueError`: if the string does not appear to be a valid locale identifier :raise `UnknownLocaleError`: if no locale data is available for the requested locale """ if identifier is None: return None elif isinstance(identifier, Locale): return identifier elif not isinstance(identifier, string_types): raise TypeError('Unxpected value for identifier: %r' % (identifier,)) parts = parse_locale(identifier, sep=sep) input_id = get_locale_identifier(parts) def _try_load(parts): try: return cls(*parts) except UnknownLocaleError: return None locale = _try_load(parts) if locale is not None: return locale if not resolve_likely_subtags: raise UnknownLocaleError(input_id) # From here onwards is some very bad likely subtag resolving. This # whole logic is not entirely correct but good enough (tm) for the # time being. This has been added so that zh_TW does not cause # errors for people when they upgrade. Later we should properly # implement ICU like fuzzy locale objects and provide a way to # maximize and minimize locale tags. language, territory, script, variant = parts language = get_global('language_aliases').get(language, language) territory = get_global('territory_aliases').get(territory, territory) script = get_global('script_aliases').get(script, script) variant = get_global('variant_aliases').get(variant, variant) if territory == 'ZZ': territory = None if script == 'Zzzz': script = None parts = language, territory, script, variant new_id = get_locale_identifier(parts) likely_subtag = get_global('likely_subtags').get(new_id) if likely_subtag is None: raise UnknownLocaleError(input_id) parts2 = parse_locale(likely_subtag) # Success on first hit, return it. locale = _try_load(parts2) if locale is not None: return locale # Now try without script and variant locale = _try_load(parts2[:2]) if locale is not None: return locale raise UnknownLocaleError(input_id) def __eq__(self, other): for key in ('language', 'territory', 'script', 'variant'): if not hasattr(other, key): return False return (self.language == other.language) and \ (self.territory == other.territory) and \ (self.script == other.script) and \ (self.variant == other.variant) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): parameters = [''] for key in ('territory', 'script', 'variant'): value = getattr(self, key) if value is not None: parameters.append('%s=%r' % (key, value)) parameter_string = '%r' % self.language + ', '.join(parameters) return 'Locale(%s)' % parameter_string def __str__(self): return get_locale_identifier((self.language, self.territory, self.script, self.variant)) @property def _data(self): if self.__data is None: self.__data = localedata.LocaleDataDict(localedata.load(str(self))) return self.__data def get_display_name(self, locale=None): """Return the display name of the locale using the given locale. The display name will include the language, territory, script, and variant, if those are specified. >>> Locale('zh', 'CN', script='Hans').get_display_name('en') u'Chinese (Simplified, China)' :param locale: the locale to use """ if locale is None: locale = self locale = Locale.parse(locale) retval = locale.languages.get(self.language) if self.territory or self.script or self.variant: details = [] if self.script: details.append(locale.scripts.get(self.script)) if self.territory: details.append(locale.territories.get(self.territory)) if self.variant: details.append(locale.variants.get(self.variant)) details = filter(None, details) if details: retval += ' (%s)' % u', '.join(details) return retval display_name = property(get_display_name, doc="""\ The localized display name of the locale. >>> Locale('en').display_name u'English' >>> Locale('en', 'US').display_name u'English (United States)' >>> Locale('sv').display_name u'svenska' :type: `unicode` """) def get_language_name(self, locale=None): """Return the language of this locale in the given locale. >>> Locale('zh', 'CN', script='Hans').get_language_name('de') u'Chinesisch' .. versionadded:: 1.0 :param locale: the locale to use """ if locale is None: locale = self locale = Locale.parse(locale) return locale.languages.get(self.language) language_name = property(get_language_name, doc="""\ The localized language name of the locale. >>> Locale('en', 'US').language_name u'English' """) def get_territory_name(self, locale=None): """Return the territory name in the given locale.""" if locale is None: locale = self locale = Locale.parse(locale) return locale.territories.get(self.territory) territory_name = property(get_territory_name, doc="""\ The localized territory name of the locale if available. >>> Locale('de', 'DE').territory_name u'Deutschland' """) def get_script_name(self, locale=None): """Return the script name in the given locale.""" if locale is None: locale = self locale = Locale.parse(locale) return locale.scripts.get(self.script) script_name = property(get_script_name, doc="""\ The localized script name of the locale if available. >>> Locale('ms', 'SG', script='Latn').script_name u'Latin' """) @property def english_name(self): """The english display name of the locale. >>> Locale('de').english_name u'German' >>> Locale('de', 'DE').english_name u'German (Germany)' :type: `unicode`""" return self.get_display_name(Locale('en')) #{ General Locale Display Names @property def languages(self): """Mapping of language codes to translated language names. >>> Locale('de', 'DE').languages['ja'] u'Japanisch' See `ISO 639 <http://www.loc.gov/standards/iso639-2/>`_ for more information. """ return self._data['languages'] @property def scripts(self): """Mapping of script codes to translated script names. >>> Locale('en', 'US').scripts['Hira'] u'Hiragana' See `ISO 15924 <http://www.evertype.com/standards/iso15924/>`_ for more information. """ return self._data['scripts'] @property def territories(self): """Mapping of script codes to translated script names. >>> Locale('es', 'CO').territories['DE'] u'Alemania' See `ISO 3166 <http://www.iso.org/iso/en/prods-services/iso3166ma/>`_ for more information. """ return self._data['territories'] @property def variants(self): """Mapping of script codes to translated script names. >>> Locale('de', 'DE').variants['1901'] u'Alte deutsche Rechtschreibung' """ return self._data['variants'] #{ Number Formatting @property def currencies(self): """Mapping of currency codes to translated currency names. This only returns the generic form of the currency name, not the count specific one. If an actual number is requested use the :func:`babel.numbers.get_currency_name` function. >>> Locale('en').currencies['COP'] u'Colombian Peso' >>> Locale('de', 'DE').currencies['COP'] u'Kolumbianischer Peso' """ return self._data['currency_names'] @property def currency_symbols(self): """Mapping of currency codes to symbols. >>> Locale('en', 'US').currency_symbols['USD'] u'$' >>> Locale('es', 'CO').currency_symbols['USD'] u'US$' """ return self._data['currency_symbols'] @property def number_symbols(self): """Symbols used in number formatting. >>> Locale('fr', 'FR').number_symbols['decimal'] u',' """ return self._data['number_symbols'] @property def decimal_formats(self): """Locale patterns for decimal number formatting. >>> Locale('en', 'US').decimal_formats[None] <NumberPattern u'#,##0.###'> """ return self._data['decimal_formats'] @property def currency_formats(self): """Locale patterns for currency number formatting. >>> print Locale('en', 'US').currency_formats[None] <NumberPattern u'\\xa4#,##0.00'> """ return self._data['currency_formats'] @property def percent_formats(self): """Locale patterns for percent number formatting. >>> Locale('en', 'US').percent_formats[None] <NumberPattern u'#,##0%'> """ return self._data['percent_formats'] @property def scientific_formats(self): """Locale patterns for scientific number formatting. >>> Locale('en', 'US').scientific_formats[None] <NumberPattern u'#E0'> """ return self._data['scientific_formats'] #{ Calendar Information and Date Formatting @property def periods(self): """Locale display names for day periods (AM/PM). >>> Locale('en', 'US').periods['am'] u'AM' """ return self._data['periods'] @property def days(self): """Locale display names for weekdays. >>> Locale('de', 'DE').days['format']['wide'][3] u'Donnerstag' """ return self._data['days'] @property def months(self): """Locale display names for months. >>> Locale('de', 'DE').months['format']['wide'][10] u'Oktober' """ return self._data['months'] @property def quarters(self): """Locale display names for quarters. >>> Locale('de', 'DE').quarters['format']['wide'][1] u'1. Quartal' """ return self._data['quarters'] @property def eras(self): """Locale display names for eras. >>> Locale('en', 'US').eras['wide'][1] u'Anno Domini' >>> Locale('en', 'US').eras['abbreviated'][0] u'BC' """ return self._data['eras'] @property def time_zones(self): """Locale display names for time zones. >>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight'] u'British Summer Time' >>> Locale('en', 'US').time_zones['America/St_Johns']['city'] u'St. John\u2019s' """ return self._data['time_zones'] @property def meta_zones(self): """Locale display names for meta time zones. Meta time zones are basically groups of different Olson time zones that have the same GMT offset and daylight savings time. >>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight'] u'Central European Summer Time' .. versionadded:: 0.9 """ return self._data['meta_zones'] @property def zone_formats(self): """Patterns related to the formatting of time zones. >>> Locale('en', 'US').zone_formats['fallback'] u'%(1)s (%(0)s)' >>> Locale('pt', 'BR').zone_formats['region'] u'Hor\\xe1rio %s' .. versionadded:: 0.9 """ return self._data['zone_formats'] @property def first_week_day(self): """The first day of a week, with 0 being Monday. >>> Locale('de', 'DE').first_week_day 0 >>> Locale('en', 'US').first_week_day 6 """ return self._data['week_data']['first_day'] @property def weekend_start(self): """The day the weekend starts, with 0 being Monday. >>> Locale('de', 'DE').weekend_start 5 """ return self._data['week_data']['weekend_start'] @property def weekend_end(self): """The day the weekend ends, with 0 being Monday. >>> Locale('de', 'DE').weekend_end 6 """ return self._data['week_data']['weekend_end'] @property def min_week_days(self): """The minimum number of days in a week so that the week is counted as the first week of a year or month. >>> Locale('de', 'DE').min_week_days 4 """ return self._data['week_data']['min_days'] @property def date_formats(self): """Locale patterns for date formatting. >>> Locale('en', 'US').date_formats['short'] <DateTimePattern u'M/d/yy'> >>> Locale('fr', 'FR').date_formats['long'] <DateTimePattern u'd MMMM y'> """ return self._data['date_formats'] @property def time_formats(self): """Locale patterns for time formatting. >>> Locale('en', 'US').time_formats['short'] <DateTimePattern u'h:mm a'> >>> Locale('fr', 'FR').time_formats['long'] <DateTimePattern u'HH:mm:ss z'> """ return self._data['time_formats'] @property def datetime_formats(self): """Locale patterns for datetime formatting. >>> Locale('en').datetime_formats['full'] u"{1} 'at' {0}" >>> Locale('th').datetime_formats['medium'] u'{1}, {0}' """ return self._data['datetime_formats'] @property def plural_form(self): """Plural rules for the locale. >>> Locale('en').plural_form(1) 'one' >>> Locale('en').plural_form(0) 'other' >>> Locale('fr').plural_form(0) 'one' >>> Locale('ru').plural_form(100) 'many' """ return self._data['plural_form'] def default_locale(category=None, aliases=LOCALE_ALIASES): """Returns the system default locale for a given category, based on environment variables. >>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']: ... os.environ[name] = '' >>> os.environ['LANG'] = 'fr_FR.UTF-8' >>> default_locale('LC_MESSAGES') 'fr_FR' The "C" or "POSIX" pseudo-locales are treated as aliases for the "en_US_POSIX" locale: >>> os.environ['LC_MESSAGES'] = 'POSIX' >>> default_locale('LC_MESSAGES') 'en_US_POSIX' The following fallbacks to the variable are always considered: - ``LANGUAGE`` - ``LC_ALL`` - ``LC_CTYPE`` - ``LANG`` :param category: one of the ``LC_XXX`` environment variable names :param aliases: a dictionary of aliases for locale identifiers """ varnames = (category, 'LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG') for name in filter(None, varnames): locale = os.getenv(name) if locale: if name == 'LANGUAGE' and ':' in locale: # the LANGUAGE variable may contain a colon-separated list of # language codes; we just pick the language on the list locale = locale.split(':')[0] if locale in ('C', 'POSIX'): locale = 'en_US_POSIX' elif aliases and locale in aliases: locale = aliases[locale] try: return get_locale_identifier(parse_locale(locale)) except ValueError: pass def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES): """Find the best match between available and requested locale strings. >>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT']) 'de_DE' >>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de']) 'de' Case is ignored by the algorithm, the result uses the case of the preferred locale identifier: >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at']) 'de_DE' >>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at']) 'de_DE' By default, some web browsers unfortunately do not include the territory in the locale identifier for many locales, and some don't even allow the user to easily add the territory. So while you may prefer using qualified locale identifiers in your web-application, they would not normally match the language-only locale sent by such browsers. To workaround that, this function uses a default mapping of commonly used langauge-only locale identifiers to identifiers including the territory: >>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US']) 'ja_JP' Some browsers even use an incorrect or outdated language code, such as "no" for Norwegian, where the correct locale identifier would actually be "nb_NO" (Bokmål) or "nn_NO" (Nynorsk). The aliases are intended to take care of such cases, too: >>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE']) 'nb_NO' You can override this default mapping by passing a different `aliases` dictionary to this function, or you can bypass the behavior althogher by setting the `aliases` parameter to `None`. :param preferred: the list of locale strings preferred by the user :param available: the list of locale strings available :param sep: character that separates the different parts of the locale strings :param aliases: a dictionary of aliases for locale identifiers """ available = [a.lower() for a in available if a] for locale in preferred: ll = locale.lower() if ll in available: return locale if aliases: alias = aliases.get(ll) if alias: alias = alias.replace('_', sep) if alias.lower() in available: return alias parts = locale.split(sep) if len(parts) > 1 and parts[0].lower() in available: return parts[0] return None def parse_locale(identifier, sep='_'): """Parse a locale identifier into a tuple of the form ``(language, territory, script, variant)``. >>> parse_locale('zh_CN') ('zh', 'CN', None, None) >>> parse_locale('zh_Hans_CN') ('zh', 'CN', 'Hans', None) The default component separator is "_", but a different separator can be specified using the `sep` parameter: >>> parse_locale('zh-CN', sep='-') ('zh', 'CN', None, None) If the identifier cannot be parsed into a locale, a `ValueError` exception is raised: >>> parse_locale('not_a_LOCALE_String') Traceback (most recent call last): ... ValueError: 'not_a_LOCALE_String' is not a valid locale identifier Encoding information and locale modifiers are removed from the identifier: >>> parse_locale('it_IT@euro') ('it', 'IT', None, None) >>> parse_locale('en_US.UTF-8') ('en', 'US', None, None) >>> parse_locale('de_DE.iso885915@euro') ('de', 'DE', None, None) See :rfc:`4646` for more information. :param identifier: the locale identifier string :param sep: character that separates the different components of the locale identifier :raise `ValueError`: if the string does not appear to be a valid locale identifier """ if '.' in identifier: # this is probably the charset/encoding, which we don't care about identifier = identifier.split('.', 1)[0] if '@' in identifier: # this is a locale modifier such as @euro, which we don't care about # either identifier = identifier.split('@', 1)[0] parts = identifier.split(sep) lang = parts.pop(0).lower() if not lang.isalpha(): raise ValueError('expected only letters, got %r' % lang) script = territory = variant = None if parts: if len(parts[0]) == 4 and parts[0].isalpha(): script = parts.pop(0).title() if parts: if len(parts[0]) == 2 and parts[0].isalpha(): territory = parts.pop(0).upper() elif len(parts[0]) == 3 and parts[0].isdigit(): territory = parts.pop(0) if parts: if len(parts[0]) == 4 and parts[0][0].isdigit() or \ len(parts[0]) >= 5 and parts[0][0].isalpha(): variant = parts.pop() if parts: raise ValueError('%r is not a valid locale identifier' % identifier) return lang, territory, script, variant def get_locale_identifier(tup, sep='_'): """The reverse of :func:`parse_locale`. It creates a locale identifier out of a ``(language, territory, script, variant)`` tuple. Items can be set to ``None`` and trailing ``None``\s can also be left out of the tuple. >>> get_locale_identifier(('de', 'DE', None, '1999')) 'de_DE_1999' .. versionadded:: 1.0 :param tup: the tuple as returned by :func:`parse_locale`. :param sep: the separator for the identifier. """ tup = tuple(tup[:4]) lang, territory, script, variant = tup + (None,) * (4 - len(tup)) return sep.join(filter(None, (lang, script, territory, variant)))
bsd-3-clause
paramono/amocrm
tests/__init__.py
333
import unittest # from .base_mocksettings import BaseMockSettingsTest from .test_value import TestValue from .test_field import TestField from .test_field_children import * from .test_contact import * from .test_lead import * from .test_settings import * from .test_manager import * if __name__ == '__main__': unittest.main()
bsd-3-clause
sherryshare/blaze-2.0
blazemark/src/mtl/DMatTSMatMult.cpp
4772
//================================================================================================= /*! // \file src/mtl/DMatTSMatMult.cpp // \brief Source file for the MTL dense matrix/transpose sparse matrix multiplication kernel // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <iostream> #include <boost/numeric/mtl/mtl.hpp> #include <blaze/util/Timing.h> #include <blazemark/mtl/DMatTSMatMult.h> #include <blazemark/mtl/init/Compressed2D.h> #include <blazemark/mtl/init/Dense2D.h> #include <blazemark/system/Config.h> namespace blazemark { namespace mtl { //================================================================================================= // // KERNEL FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief MTL dense matrix/transpose sparse matrix multiplication kernel. // // \param N The number of rows and columns of the matrices. // \param F The number of non-zero elements in each column of the sparse matrix. // \param steps The number of iteration steps to perform. // \return Minimum runtime of the kernel function. // // This kernel function implements the dense matrix/transpose sparse matrix multiplication by // means of the MTL functionality. */ double dmattsmatmult( size_t N, size_t F, size_t steps ) { using ::blazemark::element_t; typedef ::mtl::tag::row_major row_major; typedef ::mtl::tag::col_major col_major; typedef ::mtl::matrix::parameters<row_major> row_parameters; typedef ::mtl::matrix::parameters<col_major> col_parameters; typedef ::mtl::dense2D<element_t,row_parameters> dense2D; typedef ::mtl::compressed2D<element_t,col_parameters> compressed2D; typedef ::mtl::matrix::inserter<compressed2D> inserter; ::blaze::setSeed( seed ); dense2D A( N, N ), C( N, N ); compressed2D B( N, N ); ::blaze::timing::WcTimer timer; init( A ); init( B, F ); C = A * B; for( size_t rep=0UL; rep<reps; ++rep ) { timer.start(); for( size_t step=0UL; step<steps; ++step ) { C = A * B; } timer.end(); if( num_rows(C) != N ) std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n"; if( timer.last() > maxtime ) break; } const double minTime( timer.min() ); const double avgTime( timer.average() ); if( minTime * ( 1.0 + deviation*0.01 ) < avgTime ) std::cerr << " MTL kernel 'dmattsmatmult': Time deviation too large!!!\n"; return minTime; } //************************************************************************************************* } // namespace mtl } // namespace blazemark
bsd-3-clause
jimrc/IntroStatShinyApps
www/helper.js
260
function toggleContent1() { // Get the DOM reference var contentId = document.getElementById("getcat1Data"); // Toggle contentId.style.display == "block" ? contentId.style.display = "none" : contentId.style.display = "block"; }
bsd-3-clause
walkerka/opentoonz
toonz/sources/tnztools/viewtools.cpp
5801
#include "tools/tool.h" #include "tstopwatch.h" #include "tools/cursors.h" #include "tgeometry.h" #include "tproperty.h" #include <math.h> #include "tgl.h" namespace { //============================================================================= // Zoom Tool //----------------------------------------------------------------------------- class ZoomTool : public TTool { int m_oldY; TPointD m_center; bool m_dragging; double m_factor; public: ZoomTool() : TTool("T_Zoom"), m_dragging(false), m_oldY(0), m_factor(1) { bind(TTool::AllTargets); } ToolType getToolType() const { return TTool::GenericTool; } void updateMatrix() { return setMatrix(TAffine()); } void leftButtonDown(const TPointD &pos, const TMouseEvent &e) { if (!m_viewer) return; m_dragging = true; int v = 1; if (e.isAltPressed()) v = -1; m_oldY = e.m_pos.y; // m_center = getViewer()->winToWorld(e.m_pos); m_center = TPointD(e.m_pos.x, e.m_pos.y); m_factor = 1; invalidate(); } void leftButtonDrag(const TPointD &pos, const TMouseEvent &e) { int d = m_oldY - e.m_pos.y; m_oldY = e.m_pos.y; double f = exp(-d * 0.01); m_factor = f; m_viewer->zoom(m_center, f); } void leftButtonUp(const TPointD &pos, const TMouseEvent &e) { m_dragging = false; invalidate(); } void rightButtonDown(const TPointD &, const TMouseEvent &e) { if (!m_viewer) return; invalidate(); } void draw() { if (!m_dragging) return; TPointD center = m_viewer->winToWorld(TPoint(m_center.x, m_center.y)); double pixelSize = getPixelSize(); double unit = pixelSize; glPushMatrix(); glTranslated(center.x, center.y, 0); glScaled(unit, unit, unit); glColor3f(1, 0, 0); double u = 4; glBegin(GL_LINES); glVertex2d(0, -10); glVertex2d(0, 10); glVertex2d(-10, 0); glVertex2d(10, 0); glEnd(); glPopMatrix(); } int getCursorId() const { return ToolCursor::ZoomCursor; } } zoomTool; //============================================================================= // Hand Tool //----------------------------------------------------------------------------- class HandTool : public TTool { TStopWatch m_sw; TPoint m_oldPos; public: HandTool() : TTool("T_Hand") { bind(TTool::AllTargets); } ToolType getToolType() const { return TTool::GenericTool; } void updateMatrix() { return setMatrix(TAffine()); } void leftButtonDown(const TPointD &pos, const TMouseEvent &e) { if (!m_viewer) return; m_oldPos = e.m_pos; m_sw.start(true); } void leftButtonDrag(const TPointD &pos, const TMouseEvent &e) { if (!m_viewer) return; if (m_sw.getTotalTime() < 10) return; m_sw.stop(); m_sw.start(true); TPoint delta = e.m_pos - m_oldPos; delta.y = -delta.y; m_viewer->pan(delta); m_oldPos = e.m_pos; } void leftButtonUp(const TPointD &pos, const TMouseEvent &e) { if (!m_viewer) return; m_sw.stop(); } int getCursorId() const { return ToolCursor::PanCursor; } } handTool; //============================================================================= // Rotate Tool //----------------------------------------------------------------------------- class RotateTool : public TTool { TStopWatch m_sw; TPointD m_oldPos; TPointD m_center; bool m_dragging; double m_angle; TPoint m_oldMousePos; TBoolProperty m_cameraCentered; TPropertyGroup m_prop; public: RotateTool() : TTool("T_Rotate") , m_dragging(false) , m_cameraCentered("Rotate On Camera Center", false) , m_angle(0) { bind(TTool::AllTargets); m_prop.bind(m_cameraCentered); } ToolType getToolType() const { return TTool::GenericTool; } void updateMatrix() { return setMatrix(TAffine()); } TPropertyGroup *getProperties(int targetType) { return &m_prop; } void leftButtonDown(const TPointD &pos, const TMouseEvent &e) { if (!m_viewer) return; m_angle = 0.0; m_dragging = true; m_oldPos = pos; m_oldMousePos = e.m_pos; // m_center = TPointD(0,0); m_sw.start(true); invalidate(); // m_center = // viewAffine.inv()*TPointD(0,0);//m_viewer->winToWorld(m_viewer); // virtual TPointD winToWorld(const TPoint &winPos) const = 0; } void leftButtonDrag(const TPointD &pos, const TMouseEvent &e) { if (!m_viewer) return; if (m_sw.getTotalTime() < 50) return; m_sw.stop(); m_sw.start(true); TPointD p = pos; if (m_viewer->is3DView()) { TPoint d = e.m_pos - m_oldMousePos; m_oldMousePos = e.m_pos; double factor = 0.5; m_viewer->rotate3D(factor * d.x, -factor * d.y); } else { TPointD a = p - m_center; TPointD b = m_oldPos - m_center; if (norm2(a) > 0 && norm2(b) > 0) { double ang = asin(cross(b, a) / (norm(a) * norm(b))) * M_180_PI; m_angle = m_angle + ang; m_viewer->rotate(m_center, m_angle); } } m_oldPos = p; } void leftButtonUp(const TPointD &pos, const TMouseEvent &e) { m_dragging = false; invalidate(); m_sw.stop(); } void draw() { glColor3f(1, 0, 0); double u = 50; if (m_cameraCentered.getValue()) m_center = TPointD(0, 0); else { TAffine aff = m_viewer->getViewMatrix().inv(); u = u * sqrt(aff.det()); m_center = aff * TPointD(0, 0); } tglDrawSegment(TPointD(-u + m_center.x, m_center.y), TPointD(u + m_center.x, m_center.y)); tglDrawSegment(TPointD(m_center.x, -u + m_center.y), TPointD(m_center.x, u + m_center.y)); } int getCursorId() const { return ToolCursor::RotateCursor; } } rotateTool; } // namespace
bsd-3-clause
nachocove/DDay-iCal-Xamarin
DDay.Collections/DDay.Collections.Test/GroupedCollectionTests.cs
8710
using System; using System.Diagnostics; using System.Linq; using NUnit.Framework; namespace DDay.Collections.Test { [TestFixture] public class GroupedCollectionTests { IGroupedList<long, Person> _People; IGroupedCollection<long, Doctor> _Doctors; Person _JonSchmidt; Person _BobRoss; Person _ForrestGump; Person _MichaelJackson; Person _DoogieHowser; [SetUp] public void Setup() { _JonSchmidt = new Person() { Group = 1, Name = "Jon Schmidt" }; _BobRoss = new Person() { Group = 2, Name = "Bob Ross" }; _ForrestGump = new Doctor() { Group = 3, Name = "Forrest Gump", ProviderNumber = "123456" }; _MichaelJackson = new Person() { Group = 4, Name = "Michael Jackson" }; _DoogieHowser = new Doctor() { Group = 5, Name = "Doogie Howser", ProviderNumber = "234567" }; _People = new GroupedList<long, Person>(); _People.Add(_ForrestGump); _People.Add(_JonSchmidt); _People.Add(_BobRoss); _People.Add(_DoogieHowser); _People.Add(_MichaelJackson); _Doctors = new GroupedCollectionProxy<long, Person, Doctor>(_People); } /// <summary> /// Ensures that the Add() correctly adds items when /// called from the original list. /// </summary> [Test] public void Add1() { var newDoctor = new Doctor() { Group = 5, Name = "New Doctor", ProviderNumber = "23456" }; Assert.AreEqual(5, _People.Count); Assert.AreEqual(2, _Doctors.Count); _People.Add(newDoctor); Assert.AreEqual(6, _People.Count); Assert.AreEqual(3, _Doctors.Count); } /// <summary> /// Tests the basic operation of the AllOf() method. /// </summary> [Test] public void AllOf1() { Assert.AreEqual(1, _People.AllOf(1).Count()); Assert.AreEqual(1, _People.AllOf(2).Count()); Assert.AreEqual(1, _People.AllOf(3).Count()); Assert.AreEqual(1, _People.AllOf(4).Count()); Assert.AreEqual(1, _People.AllOf(5).Count()); } /// <summary> /// Tests the AllOf() method after one of the /// object's keys has changed. /// </summary> [Test] public void AllOf2() { Assert.AreEqual(1, _People.AllOf(4).Count()); Assert.AreEqual(1, _People.AllOf(5).Count()); _MichaelJackson.Group = 5; Assert.AreEqual(2, _People.AllOf(5).Count()); Assert.AreEqual(0, _People.AllOf(4).Count()); } /// <summary> /// Tests the basic function of the Count property. /// </summary> [Test] public void Count1() { Assert.AreEqual(5, _People.Count); } /// <summary> /// Ensures the Count property works as expected with proxied lists. /// </summary> [Test] public void CountProxy1() { Assert.AreEqual(2, _Doctors.Count); } /// <summary> /// Ensure that the KeyedList enumerator properly enumerates the items in the list. /// </summary> [Test] public void Enumeration1() { var people = new Person[] { _ForrestGump, _JonSchmidt, _BobRoss, _DoogieHowser, _MichaelJackson }; int i = 0; foreach (var person in _People) { Assert.AreSame(people[i++], person); } } /// <summary> /// Ensures that the indexer properly retrieves the items at the specified index. /// </summary> [Test] public void Indexer1() { Assert.AreSame(_ForrestGump, _People[0]); Assert.AreSame(_JonSchmidt, _People[1]); Assert.AreSame(_BobRoss, _People[2]); Assert.AreSame(_DoogieHowser, _People[3]); Assert.AreSame(_MichaelJackson, _People[4]); } /// <summary> /// Ensures that proxies properly order their items. /// </summary> [Test] public void ProxyOrder1() { Assert.AreSame(_ForrestGump, _Doctors.First()); Assert.AreSame(_DoogieHowser, _Doctors.Skip(1).First()); } /// <summary> /// Ensures that proxies properly order their items. /// </summary> [Test] public void ProxyOrder2() { var newDoctor = new Doctor() { Group = 5, Name = "New Doctor", ProviderNumber = "23456" }; _Doctors.Add(newDoctor); Person[] list = { _ForrestGump, _DoogieHowser, newDoctor }; Assert.IsTrue(_Doctors.SequenceEqual(list.OfType<Doctor>())); } /// <summary> /// Ensures that proxies properly order their items. /// </summary> [Test] public void ProxyOrder3() { var newDoctor = new Doctor() { Group = 5, Name = "New Doctor", ProviderNumber = "23456" }; _People.Insert(0, newDoctor); Person[] list = { newDoctor, _ForrestGump, _DoogieHowser }; Assert.IsTrue(_Doctors.SequenceEqual(list.OfType<Doctor>())); } /// <summary> /// Ensures that proxies properly order their items. /// </summary> [Test] public void ProxyOrder4() { var newDoctor = new Doctor() { Group = 5, Name = "New Doctor", ProviderNumber = "23456" }; _People.Insert(3, newDoctor); Person[] list = { _ForrestGump, newDoctor, _DoogieHowser }; Assert.IsTrue(_Doctors.SequenceEqual(list.OfType<Doctor>())); } /// <summary> /// Ensures the IndexOf() method works as expected. /// </summary> [Test] public void IndexOf1() { Assert.AreEqual(0, _People.IndexOf(_ForrestGump)); Assert.AreEqual(1, _People.IndexOf(_JonSchmidt)); Assert.AreEqual(2, _People.IndexOf(_BobRoss)); Assert.AreEqual(3, _People.IndexOf(_DoogieHowser)); Assert.AreEqual(4, _People.IndexOf(_MichaelJackson)); } [Test] public void Insert1() { Assert.AreEqual(5, _People.Count); Assert.AreEqual(2, _Doctors.Count); var newDoctor = new Doctor() { Group = 5, Name = "New Doctor", ProviderNumber = "23456" }; _People.Insert(0, newDoctor); Assert.AreEqual(6, _People.Count); Assert.AreEqual(3, _Doctors.Count); Assert.AreEqual(newDoctor, _Doctors.First()); var middleDoctor = new Doctor() { Group = 5, Name = "Middle Doctor", ProviderNumber = "23456" }; _People.Insert(2, middleDoctor); Assert.AreEqual(7, _People.Count); Assert.AreEqual(4, _Doctors.Count); Assert.AreEqual(middleDoctor, _Doctors.Skip(2).First()); } /// <summary> /// Ensures items are properly removed /// when calling Remove() from the original list. /// </summary> [Test] public void Remove1() { Assert.AreEqual(5, _People.Count); Assert.AreEqual(2, _Doctors.Count); _People.Remove(_DoogieHowser); Assert.AreEqual(4, _People.Count); Assert.AreEqual(1, _Doctors.Count); } /// <summary> /// Ensures items are properly removed /// when calling Remove() from the proxied list. /// </summary> [Test] public void RemoveProxy1() { Assert.AreEqual(2, _Doctors.Count); Assert.AreEqual(5, _People.Count); _People.Remove(_DoogieHowser); Assert.AreEqual(1, _Doctors.Count); Assert.AreEqual(4, _People.Count); } /// <summary> /// Ensure items are presented in ascending order (by group) /// </summary> [Test] public void SortKeys1() { _People.SortKeys(); long group = -1; foreach (var person in _People) { Assert.True(group <= person.Group); group = person.Group; } } } }
bsd-3-clause
sprockets/sprockets.mixins.postgresql
sprockets/mixins/postgresql/__init__.py
3458
""" PostgreSQL Client Mixins ======================== Sprockets mixins that automatically connects to PostgreSQL using `sprockets.clients.postgresql <http://sprocketsclientspostgresql.rtfd.org>`_. Handlers implementing one of the mixins should set an attribute called ``DBNAME`` that specifies the database name to connect to. The value of ``DBNAME`` will be passed into the creation of the :py:class:`Session <sprockets.clients.postgresql.Session>` or :py:class:`TornadoSession <sprockets.clients.postgresql.TornadoSession>` object. The Session classes wrap the Queries :py:class:`Session <queries.Session>` or :py:class:`TornadoSession <queries.tornado_session.TornadoSession>` providing environment variable based configuration. The environment variables should be set using the ``DBNAME_[VARIABLE]`` format where ``[VARIABLE]`` is one of ``HOST``, ``PORT``, ``DBNAME``, ``USER``, and ``PASSWORD``. """ version_info = (1, 0, 1) __version__ = '.'.join(str(v) for v in version_info) from sprockets.clients import postgresql class HandlerMixin(object): """A handler mixin for connecting to PostgreSQL. The mixin automatically creates the database session using the DBNAME attribute of the class as the database name for the :py:class:`Session <sprockets.clients.postgresql.Session>` object creation. Using the mixin, the name of the session attribute will be ``<dbname>_session``, automatically created when initializing the object. Example: .. code:: python from sprockets.mixins import postgresql from tornado import web class FooRequestHandler(postgresql.HandlerMixin, web.RequestHandler,): DBNAME = 'foo' def get(self, *args, **kwargs): result = self.foo_session.query('SELECT * FROM bar') self.finish({'data': result.items()}) """ DBNAME = 'postgres' def initialize(self): setattr(self, '%s_session' % self.DBNAME, postgresql.Session(self.DBNAME)) try: super(HandlerMixin, self).initialize() except AttributeError: pass class AsyncHandlerMixin(object): """A asynchronous Tornado handler mixin for connecting to PostgreSQL. The mixin automatically creates the database session using the DBNAME attribute of the class as the database name for the :py:class:`TornadoSession <sprockets.clients.postgresql.TornadoSession>` object creation. Using the mixin, the name of the session attribute will be ``<dbname>_session``, automatically created when initializing the object. Example: .. code:: python from sprockets.mixins import postgresql from tornado import web class FooRequestHandler(postgresql.AsyncHandlerMixin, web.RequestHandler): DBNAME = 'foo' @web.asynchronous def get(self, *args, **kwargs): result = yield self.foo_session.query('SELECT * FROM bar') self.finish({'data': result.items()}) result.free() """ DBNAME = 'postgres' def initialize(self): setattr(self, '%s_session' % self.DBNAME, postgresql.TornadoSession(self.DBNAME)) try: super(AsyncHandlerMixin, self).initialize() except AttributeError: pass
bsd-3-clause
mishbahr/staticgen-demo
staticgen_demo/plugins/picture/migrations/0001_initial.py
899
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import filer.fields.image class Migration(migrations.Migration): dependencies = [ ('cms', '0013_urlconfrevision'), ('filer', '0002_auto_20150606_2003'), ] operations = [ migrations.CreateModel( name='Picture', fields=[ ('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')), ('caption', models.TextField(verbose_name='Caption', blank=True)), ('image', filer.fields.image.FilerImageField(related_name='picture_plugins', verbose_name='Image', to='filer.Image')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), ]
bsd-3-clause
zekizeki/agentservice
OpenSim/Region/ScriptEngine/DotNetEngine/ScriptManager.cs
25048
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 OpenSimulator 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 DEVELOPERS ``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 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. */ using System; using System.Reflection; using System.Globalization; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using OpenSim.Region.ScriptEngine.Shared.Api.Runtime; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.ScriptEngine.Shared.CodeTools; namespace OpenSim.Region.ScriptEngine.DotNetEngine { public class InstanceData { public IScript Script; public string State; public bool Running; public bool Disabled; public string Source; public int StartParam; public AppDomain AppDomain; public Dictionary<string, IScriptApi> Apis; public Dictionary<KeyValuePair<int,int>, KeyValuePair<int,int>> LineMap; // public ISponsor ScriptSponsor; } public class ScriptManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Declares private Thread scriptLoadUnloadThread; private static Thread staticScriptLoadUnloadThread = null; private Queue<LUStruct> LUQueue = new Queue<LUStruct>(); private static bool PrivateThread; private int LoadUnloadMaxQueueSize; private Object scriptLock = new Object(); private bool m_started = false; private Dictionary<InstanceData, DetectParams[]> detparms = new Dictionary<InstanceData, DetectParams[]>(); // Load/Unload structure private struct LUStruct { public uint localID; public UUID itemID; public string script; public LUType Action; public int startParam; public bool postOnRez; } private enum LUType { Unknown = 0, Load = 1, Unload = 2 } public Dictionary<uint, Dictionary<UUID, InstanceData>> Scripts = new Dictionary<uint, Dictionary<UUID, InstanceData>>(); private Compiler LSLCompiler; public Scene World { get { return m_scriptEngine.World; } } #endregion public void Initialize() { // Create our compiler LSLCompiler = new Compiler(m_scriptEngine); } public void _StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez) { m_log.DebugFormat( "[{0}]: ScriptManager StartScript: localID: {1}, itemID: {2}", m_scriptEngine.ScriptEngineName, localID, itemID); // We will initialize and start the script. // It will be up to the script itself to hook up the correct events. string CompiledScriptFile = String.Empty; SceneObjectPart m_host = World.GetSceneObjectPart(localID); if (null == m_host) { m_log.ErrorFormat( "[{0}]: Could not find scene object part corresponding "+ "to localID {1} to start script", m_scriptEngine.ScriptEngineName, localID); return; } UUID assetID = UUID.Zero; TaskInventoryItem taskInventoryItem = new TaskInventoryItem(); if (m_host.TaskInventory.TryGetValue(itemID, out taskInventoryItem)) assetID = taskInventoryItem.AssetID; ScenePresence presence = World.GetScenePresence(taskInventoryItem.OwnerID); CultureInfo USCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = USCulture; try { // Compile (We assume LSL) CompiledScriptFile = LSLCompiler.PerformScriptCompile(Script, assetID.ToString(), taskInventoryItem.OwnerID); if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage( "Compile successful", false); m_log.InfoFormat("[SCRIPT]: Compiled assetID {0}: {1}", assetID, CompiledScriptFile); InstanceData id = new InstanceData(); IScript CompiledScript; CompiledScript = m_scriptEngine.m_AppDomainManager.LoadScript( CompiledScriptFile, out id.AppDomain); //Register the sponsor // ISponsor scriptSponsor = new ScriptSponsor(); // ILease lease = (ILease)RemotingServices.GetLifetimeService(CompiledScript as MarshalByRefObject); // lease.Register(scriptSponsor); // id.ScriptSponsor = scriptSponsor; id.LineMap = LSLCompiler.LineMap(); id.Script = CompiledScript; id.Source = Script; id.StartParam = startParam; id.State = "default"; id.Running = true; id.Disabled = false; // Add it to our script memstruct m_scriptEngine.m_ScriptManager.SetScript(localID, itemID, id); id.Apis = new Dictionary<string, IScriptApi>(); ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { id.Apis[api] = am.CreateApi(api); id.Apis[api].Initialize(m_scriptEngine, m_host, localID, itemID); } foreach (KeyValuePair<string,IScriptApi> kv in id.Apis) { CompiledScript.InitApi(kv.Key, kv.Value); } // Fire the first start-event int eventFlags = m_scriptEngine.m_ScriptManager.GetStateEventFlags( localID, itemID); m_host.SetScriptEvents(itemID, eventFlags); m_scriptEngine.m_EventQueueManager.AddToScriptQueue( localID, itemID, "state_entry", new DetectParams[0], new object[] { }); if (postOnRez) { m_scriptEngine.m_EventQueueManager.AddToScriptQueue( localID, itemID, "on_rez", new DetectParams[0], new object[] { new LSL_Types.LSLInteger(startParam) }); } string[] warnings = LSLCompiler.GetWarnings(); if (warnings != null && warnings.Length != 0) { if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage( "Script saved with warnings, check debug window!", false); foreach (string warning in warnings) { try { // DISPLAY WARNING INWORLD string text = "Warning:\n" + warning; if (text.Length > 1100) text = text.Substring(0, 1099); World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, m_host.AbsolutePosition, m_host.Name, m_host.UUID, false); } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Error displaying warning in-world: " + e2.ToString()); m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " + "Warning:\r\n" + warning); } } } } catch (Exception e) // LEGIT: User Scripting { if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage( "Script saved with errors, check debug window!", false); try { // DISPLAY ERROR INWORLD string text = "Error compiling script:\n" + e.Message.ToString(); if (text.Length > 1100) text = text.Substring(0, 1099); World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, m_host.AbsolutePosition, m_host.Name, m_host.UUID, false); } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Error displaying error in-world: " + e2.ToString()); m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " + "Errormessage: Error compiling script:\r\n" + e2.Message.ToString()); } } } public void _StopScript(uint localID, UUID itemID) { InstanceData id = GetScript(localID, itemID); if (id == null) return; m_log.DebugFormat("[{0}]: Unloading script", m_scriptEngine.ScriptEngineName); // Stop long command on script AsyncCommandManager.RemoveScript(m_scriptEngine, localID, itemID); try { // Get AppDomain // Tell script not to accept new requests id.Running = false; id.Disabled = true; AppDomain ad = id.AppDomain; // Remove from internal structure RemoveScript(localID, itemID); // Tell AppDomain that we have stopped script m_scriptEngine.m_AppDomainManager.StopScript(ad); } catch (Exception e) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception stopping script localID: " + localID + " LLUID: " + itemID.ToString() + ": " + e.ToString()); } } public void ReadConfig() { // TODO: Requires sharing of all ScriptManagers to single thread PrivateThread = true; LoadUnloadMaxQueueSize = m_scriptEngine.ScriptConfigSource.GetInt( "LoadUnloadMaxQueueSize", 100); } #region Object init/shutdown public ScriptEngine m_scriptEngine; public ScriptManager(ScriptEngine scriptEngine) { m_scriptEngine = scriptEngine; } public void Setup() { ReadConfig(); Initialize(); } public void Start() { m_started = true; AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); // // CREATE THREAD // Private or shared // if (PrivateThread) { // Assign one thread per region //scriptLoadUnloadThread = StartScriptLoadUnloadThread(); } else { // Shared thread - make sure one exist, then assign it to the private if (staticScriptLoadUnloadThread == null) { //staticScriptLoadUnloadThread = // StartScriptLoadUnloadThread(); } scriptLoadUnloadThread = staticScriptLoadUnloadThread; } } ~ScriptManager() { // Abort load/unload thread try { if (scriptLoadUnloadThread != null && scriptLoadUnloadThread.IsAlive == true) { scriptLoadUnloadThread.Abort(); //scriptLoadUnloadThread.Join(); } } catch { } } #endregion #region Load / Unload scripts (Thread loop) public void DoScriptLoadUnload() { if (!m_started) return; lock (LUQueue) { if (LUQueue.Count > 0) { LUStruct item = LUQueue.Dequeue(); if (item.Action == LUType.Unload) { _StopScript(item.localID, item.itemID); RemoveScript(item.localID, item.itemID); } else if (item.Action == LUType.Load) { m_log.DebugFormat("[{0}]: Loading script", m_scriptEngine.ScriptEngineName); _StartScript(item.localID, item.itemID, item.script, item.startParam, item.postOnRez); } } } } #endregion #region Helper functions private static Assembly CurrentDomain_AssemblyResolve( object sender, ResolveEventArgs args) { return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null; } #endregion #region Start/Stop/Reset script /// <summary> /// Fetches, loads and hooks up a script to an objects events /// </summary> /// <param name="itemID"></param> /// <param name="localID"></param> public void StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez) { lock (LUQueue) { if ((LUQueue.Count >= LoadUnloadMaxQueueSize) && m_started) { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: ERROR: Load/unload queue item count is at " + LUQueue.Count + ". Config variable \"LoadUnloadMaxQueueSize\" "+ "is set to " + LoadUnloadMaxQueueSize + ", so ignoring new script."); return; } LUStruct ls = new LUStruct(); ls.localID = localID; ls.itemID = itemID; ls.script = Script; ls.Action = LUType.Load; ls.startParam = startParam; ls.postOnRez = postOnRez; LUQueue.Enqueue(ls); } } /// <summary> /// Disables and unloads a script /// </summary> /// <param name="localID"></param> /// <param name="itemID"></param> public void StopScript(uint localID, UUID itemID) { LUStruct ls = new LUStruct(); ls.localID = localID; ls.itemID = itemID; ls.Action = LUType.Unload; ls.startParam = 0; ls.postOnRez = false; lock (LUQueue) { LUQueue.Enqueue(ls); } } #endregion #region Perform event execution in script // Execute a LL-event-function in Script internal void ExecuteEvent(uint localID, UUID itemID, string FunctionName, DetectParams[] qParams, object[] args) { int ExeStage=0; // ;^) Ewe Loon, for debuging InstanceData id=null; try // ;^) Ewe Loon,fix { // ;^) Ewe Loon,fix ExeStage = 1; // ;^) Ewe Loon, for debuging id = GetScript(localID, itemID); if (id == null) return; ExeStage = 2; // ;^) Ewe Loon, for debuging if (qParams.Length>0) // ;^) Ewe Loon,fix detparms[id] = qParams; ExeStage = 3; // ;^) Ewe Loon, for debuging if (id.Running) id.Script.ExecuteEvent(id.State, FunctionName, args); ExeStage = 4; // ;^) Ewe Loon, for debuging if (qParams.Length>0) // ;^) Ewe Loon,fix detparms.Remove(id); ExeStage = 5; // ;^) Ewe Loon, for debuging } catch (Exception e) // ;^) Ewe Loon, From here down tis fix { if ((ExeStage == 3)&&(qParams.Length>0)) detparms.Remove(id); SceneObjectPart ob = m_scriptEngine.World.GetSceneObjectPart(localID); m_log.InfoFormat("[Script Error] ,{0},{1},@{2},{3},{4},{5}", ob.Name , FunctionName, ExeStage, e.Message, qParams.Length, detparms.Count); if (ExeStage != 2) throw e; } } public uint GetLocalID(UUID itemID) { foreach (KeyValuePair<uint, Dictionary<UUID, InstanceData> > k in Scripts) { if (k.Value.ContainsKey(itemID)) return k.Key; } return 0; } public int GetStateEventFlags(uint localID, UUID itemID) { try { InstanceData id = GetScript(localID, itemID); if (id == null) { return 0; } int evflags = id.Script.GetStateEventFlags(id.State); return (int)evflags; } catch (Exception) { } return 0; } #endregion #region Internal functions to keep track of script public List<UUID> GetScriptKeys(uint localID) { if (Scripts.ContainsKey(localID) == false) return new List<UUID>(); Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); return new List<UUID>(Obj.Keys); } public InstanceData GetScript(uint localID, UUID itemID) { lock (scriptLock) { InstanceData id = null; if (Scripts.ContainsKey(localID) == false) return null; Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); if (Obj==null) return null; if (Obj.ContainsKey(itemID) == false) return null; // Get script Obj.TryGetValue(itemID, out id); return id; } } public void SetScript(uint localID, UUID itemID, InstanceData id) { lock (scriptLock) { // Create object if it doesn't exist if (Scripts.ContainsKey(localID) == false) { Scripts.Add(localID, new Dictionary<UUID, InstanceData>()); } // Delete script if it exists Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); if (Obj.ContainsKey(itemID) == true) Obj.Remove(itemID); // Add to object Obj.Add(itemID, id); } } public void RemoveScript(uint localID, UUID itemID) { if (localID == 0) localID = GetLocalID(itemID); // Don't have that object? if (Scripts.ContainsKey(localID) == false) return; // Delete script if it exists Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); if (Obj.ContainsKey(itemID) == true) Obj.Remove(itemID); } #endregion public void ResetScript(uint localID, UUID itemID) { InstanceData id = GetScript(localID, itemID); string script = id.Source; StopScript(localID, itemID); SceneObjectPart part = World.GetSceneObjectPart(localID); part.Inventory.GetInventoryItem(itemID).PermsMask = 0; part.Inventory.GetInventoryItem(itemID).PermsGranter = UUID.Zero; StartScript(localID, itemID, script, id.StartParam, false); } #region Script serialization/deserialization public void GetSerializedScript(uint localID, UUID itemID) { // Serialize the script and return it // Should not be a problem FileStream fs = File.Create("SERIALIZED_SCRIPT_" + itemID); BinaryFormatter b = new BinaryFormatter(); b.Serialize(fs, GetScript(localID, itemID)); fs.Close(); } public void PutSerializedScript(uint localID, UUID itemID) { // Deserialize the script and inject it into an AppDomain // How to inject into an AppDomain? } #endregion public DetectParams[] GetDetectParams(InstanceData id) { if (detparms.ContainsKey(id)) return detparms[id]; return null; } public int GetStartParameter(UUID itemID) { uint localID = GetLocalID(itemID); InstanceData id = GetScript(localID, itemID); if (id == null) return 0; return id.StartParam; } public IScriptApi GetApi(UUID itemID, string name) { uint localID = GetLocalID(itemID); InstanceData id = GetScript(localID, itemID); if (id == null) return null; if (id.Apis.ContainsKey(name)) return id.Apis[name]; return null; } } }
bsd-3-clause
bg0jr/Maui
src/Trading/Maui.Trading/Model/ISortedSet.cs
198
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Maui.Trading.Model { public interface ISortedSet<T> : IEnumerable<T> { } }
bsd-3-clause
jwcobb/ticketevolution-php-dataloaders
library/DataLoader/Db/Table/Configurations.php
3272
<?php /** * LICENSE * * This source file is subject to the new BSD (3-Clause) License that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://choosealicense.com/licenses/bsd-3-clause/ * * @category TicketEvolution * @package TicketEvolution\Db * @subpackage Table * @copyright Copyright (c) 2013 J Cobb. (http://jcobb.org) * @license http://choosealicense.com/licenses/bsd-3-clause/ BSD (3-Clause) License */ namespace DataLoader\Db\Table; use DataLoader\Db\Table\AbstractTable; /** * @category TicketEvolution * @package TicketEvolution\Db * @subpackage Table * @copyright Copyright (c) 2013 J Cobb. (http://jcobb.org) * @license http://choosealicense.com/licenses/bsd-3-clause/ BSD (3-Clause) License */ class Configurations extends AbstractTable { /** * The table name. * * @var string */ protected $_name = 'tevoConfigurations'; /** * The primary key column or columns. * A compound key should be declared as an array. * You may declare a single-column primary key * as a string. * * @var mixed */ protected $_primary = 'configurationId'; /** * The column that we use to indicate status in boolean form * * @var string */ protected $_statusColumn = 'configurationsStatus'; /** * Classname for row * * @var string */ //protected $_rowClass = 'DataLoader\Db\Table\Row'; /** * Sets where default column values should be taken from * * @var string */ protected $_defaultSource = self::DEFAULT_DB; /** * Simple array of class names of tables that are "children" of the current * table, in other words tables that contain a foreign key to this one. * Array elements are not table names; they are class names of classes that * extend Zend_Db_Table_Abstract. * * @var array */ protected $_dependentTables = array(); /** * Associative array map of declarative referential integrity rules. * This array has one entry per foreign key in the current table. * Each key is a mnemonic name for one reference rule. * * Each value is also an associative array, with the following keys: * - columns = array of names of column(s) in the child table. * - refTableClass = class name of the parent table. * - refColumns = array of names of column(s) in the parent table, * in the same order as those in the 'columns' entry. * - onDelete = "cascade" means that a delete in the parent table also * causes a delete of referencing rows in the child table. * - onUpdate = "cascade" means that an update of primary key values in * the parent table also causes an update of referencing * rows in the child table. * * @var array */ protected $_referenceMap = array( 'Venues' => array( 'columns' => 'venueId', 'refTableClass' => 'DataLoader\Db\Table\Venues', 'refColumns' => 'venueId' ), ); }
bsd-3-clause
nwjs/chromium.src
chrome/browser/media/cdm_document_service_impl_test.cc
12317
// 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/media/cdm_document_service_impl.h" #include <memory> #include "base/files/file.h" #include "base/files/file_util.h" #include "base/json/values_util.h" #include "base/logging.h" #include "base/run_loop.h" #include "base/test/gmock_callback_support.h" #include "base/test/mock_callback.h" #include "base/unguessable_token.h" #include "base/values.h" #include "chrome/browser/media/cdm_pref_service_helper.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_browser_process.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/user_prefs/user_prefs.h" #include "media/cdm/win/media_foundation_cdm.h" #include "media/mojo/mojom/cdm_document_service.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" using testing::_; using testing::DoAll; using testing::SaveArg; namespace { // copied from cdm_pref_service_helper.cc for testing const char kOriginId[] = "origin_id"; base::FilePath CreateDummyCdmDataFile(const base::FilePath& cdm_store_path_root, const base::UnguessableToken& origin_id) { // Create a fake CDM file auto cdm_store_path = cdm_store_path_root.AppendASCII(origin_id.ToString()); base::CreateDirectory(cdm_store_path); auto cdm_data_file_path = cdm_store_path.AppendASCII("cdm_data_file.txt"); base::File file(cdm_data_file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE); return cdm_data_file_path; } } // namespace namespace content { const char kTestOrigin[] = "https://foo.bar"; const char kTestOrigin2[] = "https://bar.foo"; using GetMediaFoundationCdmDataMockCB = base::MockOnceCallback<void( std::unique_ptr<media::MediaFoundationCdmData>)>; class CdmDocumentServiceImplTest : public ChromeRenderViewHostTestHarness { public: void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); // The Media Foundation CDM depends on functionalities only available in // Windows 10 and newer versions. if (!media::MediaFoundationCdm::IsAvailable()) { GTEST_SKIP() << "skipping all test for this fixture when not running on " "Windows 10."; } } void NavigateToUrlAndCreateCdmDocumentService(GURL url) { // The lifetime of `cdm_document_service_` is tied to the lifetime of the // Frame. When changing URL we need to unbind `cdm_document_service_` before // we can bind it to the new frame. if (cdm_document_service_.is_bound()) ASSERT_TRUE(cdm_document_service_.Unbind()); NavigateAndCommit(url); CdmDocumentServiceImpl::Create( web_contents()->GetMainFrame(), cdm_document_service_.BindNewPipeAndPassReceiver()); } std::unique_ptr<media::MediaFoundationCdmData> GetMediaFoundationCdmData() { std::unique_ptr<media::MediaFoundationCdmData> media_foundation_cdm_data; GetMediaFoundationCdmDataMockCB mock_cb; base::RunLoop run_loop; EXPECT_CALL(mock_cb, Run(_)) .WillOnce([&media_foundation_cdm_data, &run_loop]( std::unique_ptr<media::MediaFoundationCdmData> ptr) { media_foundation_cdm_data = std::move(ptr); run_loop.Quit(); }); cdm_document_service_->GetMediaFoundationCdmData(mock_cb.Get()); run_loop.Run(); return media_foundation_cdm_data; } void SetCdmClientToken(const std::vector<uint8_t>& client_token) { cdm_document_service_->SetCdmClientToken(client_token); base::RunLoop().RunUntilIdle(); } void CorruptCdmPreference() { PrefService* user_prefs = profile()->GetPrefs(); // Create (or overwrite) an entry with only an origin id to simulate some // kind of corruption or simply an update to the preference format. base::Value entry(base::Value::Type::DICTIONARY); entry.SetKey(kOriginId, base::UnguessableTokenToValue( base::UnguessableToken::Create())); DictionaryPrefUpdate update(user_prefs, prefs::kMediaCdmOriginData); base::DictionaryValue* dict = update.Get(); const std::string serialized_origin = web_contents()->GetMainFrame()->GetLastCommittedOrigin().Serialize(); dict->SetKey(serialized_origin, std::move(entry)); } protected: mojo::Remote<media::mojom::CdmDocumentService> cdm_document_service_; }; // Verify that we get a non null origin id. TEST_F(CdmDocumentServiceImplTest, GetOriginId) { NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); auto data = GetMediaFoundationCdmData(); ASSERT_FALSE(data->origin_id.is_empty()); } // Verify that we get a non null and different origin id if the preference gets // corrupted. TEST_F(CdmDocumentServiceImplTest, GetOriginIdAfterCorruption) { NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); auto data_before = GetMediaFoundationCdmData(); CorruptCdmPreference(); auto data_after = GetMediaFoundationCdmData(); ASSERT_FALSE(data_after->origin_id.is_empty()); ASSERT_NE(data_before->origin_id, data_after->origin_id); } // Verify that we can correctly get an existing origin id. TEST_F(CdmDocumentServiceImplTest, GetSameOriginId) { NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); base::UnguessableToken origin_id1 = GetMediaFoundationCdmData()->origin_id; // Create an unrelated origin id NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin2)); base::UnguessableToken origin_id2 = GetMediaFoundationCdmData()->origin_id; // Get the origin id for the first origin NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); base::UnguessableToken origin_id3 = GetMediaFoundationCdmData()->origin_id; ASSERT_NE(origin_id2, origin_id1); ASSERT_EQ(origin_id1, origin_id3); } TEST_F(CdmDocumentServiceImplTest, GetNullClientToken) { NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); auto media_foundation_cdm_data = GetMediaFoundationCdmData(); ASSERT_FALSE(media_foundation_cdm_data->client_token); } TEST_F(CdmDocumentServiceImplTest, SetClientToken) { NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); // Call GetMediaFoundationCdmData to create the origin id first, otherwise // `SetCdmClientToken()` will assume the preference data associated with the // origin was recently cleared and will not save the client token. ignore_result(GetMediaFoundationCdmData()); std::vector<uint8_t> expected_client_token = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; SetCdmClientToken(expected_client_token); auto media_foundation_cdm_data = GetMediaFoundationCdmData(); ASSERT_EQ(media_foundation_cdm_data->client_token, expected_client_token); } // Sets a client token for one origin and check that we get the same // client token after navigating back to that origin. TEST_F(CdmDocumentServiceImplTest, GetSameClientToken) { const auto kOrigin = url::Origin::Create(GURL(kTestOrigin)); const auto kOtherOrigin = url::Origin::Create(GURL(kTestOrigin2)); NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); // Call GetMediaFoundationCdmData to create the origin id first, otherwise // `SetCdmClientToken()` will assume the preference data associated with the // origin was recently cleared and will not save the client token. ignore_result(GetMediaFoundationCdmData()); std::vector<uint8_t> expected_client_token = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; SetCdmClientToken(expected_client_token); NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin2)); ignore_result(GetMediaFoundationCdmData()); SetCdmClientToken({1, 2, 3, 4, 5}); NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); auto media_foundation_cdm_data = GetMediaFoundationCdmData(); ASSERT_EQ(media_foundation_cdm_data->client_token, expected_client_token); } // If an entry cannot be parsed correctly, `SetCdmClientToken` should simply // remove that entry and return without saving the client token. TEST_F(CdmDocumentServiceImplTest, SetClientTokenAfterCorruption) { NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); ignore_result(GetMediaFoundationCdmData()); CorruptCdmPreference(); std::vector<uint8_t> expected_client_token = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; SetCdmClientToken(expected_client_token); auto media_foundation_cdm_data = GetMediaFoundationCdmData(); ASSERT_FALSE(media_foundation_cdm_data->client_token.has_value()); } // Check that we can clear the CDM preferences. `GetMediaFoundationCdmData()` // should return a new origin_id after the clearing operation. TEST_F(CdmDocumentServiceImplTest, ClearCdmPreferenceData) { const auto kOrigin = url::Origin::Create(GURL(kTestOrigin)); NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); auto cdm_data = GetMediaFoundationCdmData(); base::UnguessableToken origin_id = cdm_data->origin_id; base::FilePath cdm_data_file_path = CreateDummyCdmDataFile( cdm_data->cdm_store_path_root, cdm_data->origin_id); base::Time start = base::Time::Now() - base::Hours(1); base::Time end; // null time base::RunLoop loop1; // With the filter returning false, the origin id should not be destroyed. CdmDocumentServiceImpl::ClearCdmData( profile(), start, end, base::BindRepeating([](const GURL& url) { return false; }), loop1.QuitClosure()); loop1.Run(); base::UnguessableToken same_origin_id = GetMediaFoundationCdmData()->origin_id; ASSERT_EQ(origin_id, same_origin_id); ASSERT_TRUE(base::PathExists(cdm_data_file_path)); base::RunLoop loop2; CdmDocumentServiceImpl::ClearCdmData( profile(), start, end, base::BindRepeating([](const GURL& url) { return true; }), loop2.QuitClosure()); loop2.Run(); base::UnguessableToken new_origin_id = GetMediaFoundationCdmData()->origin_id; ASSERT_NE(origin_id, new_origin_id); ASSERT_FALSE(base::PathExists(cdm_data_file_path)); } // Check that we only clear the CDM preference that were set between start and // end. TEST_F(CdmDocumentServiceImplTest, ClearCdmPreferenceDataWrongTime) { const auto kOrigin = url::Origin::Create(GURL(kTestOrigin)); NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); auto cdm_data = GetMediaFoundationCdmData(); base::UnguessableToken origin_id = cdm_data->origin_id; base::FilePath cdm_data_file_path = CreateDummyCdmDataFile(cdm_data->cdm_store_path_root, origin_id); base::Time start = base::Time::Now() - base::Hours(4); base::Time end = start - base::Hours(2); auto null_filter = base::RepeatingCallback<bool(const GURL&)>(); base::RunLoop loop; CdmDocumentServiceImpl::ClearCdmData(profile(), start, end, null_filter, loop.QuitClosure()); loop.Run(); base::UnguessableToken new_origin_id = GetMediaFoundationCdmData()->origin_id; ASSERT_EQ(origin_id, new_origin_id); ASSERT_TRUE(base::PathExists(cdm_data_file_path)); } TEST_F(CdmDocumentServiceImplTest, ClearCdmPreferenceDataNullFilter) { const auto kOrigin = url::Origin::Create(GURL(kTestOrigin)); NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); base::UnguessableToken origin_id_1 = GetMediaFoundationCdmData()->origin_id; NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin2)); base::UnguessableToken origin_id_2 = GetMediaFoundationCdmData()->origin_id; base::Time start = base::Time::Now() - base::Hours(1); base::Time end; // null time auto null_filter = base::RepeatingCallback<bool(const GURL&)>(); base::RunLoop loop; CdmDocumentServiceImpl::ClearCdmData(profile(), start, end, null_filter, loop.QuitClosure()); loop.Run(); base::UnguessableToken new_origin_id = GetMediaFoundationCdmData()->origin_id; ASSERT_NE(origin_id_2, new_origin_id); NavigateToUrlAndCreateCdmDocumentService(GURL(kTestOrigin)); new_origin_id = GetMediaFoundationCdmData()->origin_id; ASSERT_NE(origin_id_1, new_origin_id); } } // namespace content
bsd-3-clause
kambisports/VigorJS
src/common/EventBus.js
2859
import _ from 'underscore'; import Events from 'backbone'; import EventKeys from './EventKeys'; class EventRegistry {} _.extend(EventRegistry.prototype, Events); // A global EventBus for the entire application // // @example How to subscribe to events // EventBus.subscribe EventKeys.EXAMPLE_EVENT_KEY, (event) -> // # do something with `event` here... // class EventBus { // Bind a `callback` function to an event key. Passing `all` as key will // bind the callback to all events fired. // // @param [String] the event key to subscribe to. See datacommunication/EventKeys for available keys. // @param [function] the callback that receives the event when it is sent subscribe(key, callback) { if (!this._eventKeyExists(key)) { throw `key '${key}' does not exist in EventKeys`; } if ('function' !== typeof callback) { throw 'callback is not a function'; } return this.eventRegistry.on(key, callback); } // Bind a callback to only be triggered a single time. // After the first time the callback is invoked, it will be removed. // // @param [String] the event key to subscribe to. See datacommunication/EventKeys for available keys. // @param [function] the callback that receives the single event when it is sent subscribeOnce(key, callback) { if (!this._eventKeyExists(key)) { throw `key '${key}' does not exist in EventKeys`; } if ('function' !== typeof callback) { throw 'callback is not a function'; } return this.eventRegistry.once(key, callback); } // Remove a callback. // // @param [String] the event key to unsubscribe from. // @param [Function] the callback that is to be unsubscribed unsubscribe(key, callback) { if (!this._eventKeyExists(key)) { throw `key '${key}' does not exist in EventKeys`; } if ('function' !== typeof callback) { throw 'callback is not a function'; } return this.eventRegistry.off(key, callback); } // Send an event message to all bound callbacks. Callbacks are passed the // message argument, (unless you're listening on `all`, which will // cause your callback to receive the true name of the event as the first // argument). // // @param [String] the event key to send the message on. // @param [Object] the message to send send(key, message) { if (!this._eventKeyExists(key)) { throw `key '${key}' does not exist in EventKeys`; } return this.eventRegistry.trigger(key, message); } _eventKeyExists(key) { const keys = []; for (let property in EventKeys) { if (EventKeys.hasOwnProperty(property)) { let value = EventKeys[property]; keys.push(value); } } return keys.indexOf(key) >= 0; } } EventBus.prototype.eventRegistry = new EventRegistry(); export default new EventBus();
bsd-3-clause
gladgod/zhiliao
zhiliao/forms/admin.py
6178
from __future__ import unicode_literals from future.builtins import open, bytes from copy import deepcopy from io import BytesIO, StringIO from csv import writer from datetime import datetime from mimetypes import guess_type from os.path import join from django.conf.urls import patterns, url from django.contrib import admin from django.contrib.messages import info from django.core.files.storage import FileSystemStorage from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.utils.translation import ungettext, ugettext_lazy as _ from zhiliao.conf import settings from zhiliao.core.admin import TabularDynamicInlineAdmin from .forms import EntriesForm from .models import Form, Field, FormEntry, FieldEntry from zhiliao.pages.admin import PageAdmin from zhiliao.utils.static import static_lazy as static from zhiliao.utils.urls import admin_url, slugify fs = FileSystemStorage(location=settings.FORMS_UPLOAD_ROOT) # Copy the fieldsets for PageAdmin and add the extra fields for FormAdmin. form_fieldsets = deepcopy(PageAdmin.fieldsets) form_fieldsets[0][1]["fields"][3:0] = ["content", "button_text", "response"] form_fieldsets = list(form_fieldsets) form_fieldsets.insert(1, (_("Email"), {"fields": ("send_email", "email_from", "email_copies", "email_subject", "email_message")})) inline_field_excludes = [] if not settings.FORMS_USE_HTML5: inline_field_excludes += ["placeholder_text"] class FieldAdmin(TabularDynamicInlineAdmin): """ Admin class for the form field. Inherits from TabularDynamicInlineAdmin to add dynamic "Add another" link and drag/drop ordering. """ model = Field exclude = inline_field_excludes class FormAdmin(PageAdmin): """ Admin class for the Form model. Includes the urls & views for exporting form entries as CSV and downloading files uploaded via the forms app. """ class Media: css = {"all": (static("zhiliao/css/admin/form.css"),)} inlines = (FieldAdmin,) list_display = ("title", "status", "email_copies",) list_display_links = ("title",) list_editable = ("status", "email_copies") list_filter = ("status",) search_fields = ("title", "content", "response", "email_from", "email_copies") fieldsets = form_fieldsets def get_urls(self): """ Add the entries view to urls. """ urls = super(FormAdmin, self).get_urls() extra_urls = patterns("", url("^(?P<form_id>\d+)/entries/$", self.admin_site.admin_view(self.entries_view), name="form_entries"), url("^file/(?P<field_entry_id>\d+)/$", self.admin_site.admin_view(self.file_view), name="form_file"), ) return extra_urls + urls def entries_view(self, request, form_id): """ Displays the form entries in a HTML table with option to export as CSV file. """ if request.POST.get("back"): change_url = admin_url(Form, "change", form_id) return HttpResponseRedirect(change_url) form = get_object_or_404(Form, id=form_id) entries_form = EntriesForm(form, request, request.POST or None) delete_entries_perm = "%s.delete_formentry" % FormEntry._meta.app_label can_delete_entries = request.user.has_perm(delete_entries_perm) submitted = entries_form.is_valid() if submitted: if request.POST.get("export"): response = HttpResponse(content_type="text/csv") timestamp = slugify(datetime.now().ctime()) fname = "%s-%s.csv" % (form.slug, timestamp) header = "attachment; filename=%s" % fname response["Content-Disposition"] = header queue = StringIO() delimiter = settings.FORMS_CSV_DELIMITER try: csv = writer(queue, delimiter=delimiter) writerow = csv.writerow except TypeError: queue = BytesIO() delimiter = bytes(delimiter, encoding="utf-8") csv = writer(queue, delimiter=delimiter) writerow = lambda row: csv.writerow([c.encode("utf-8") if hasattr(c, "encode") else c for c in row]) writerow(entries_form.columns()) for row in entries_form.rows(csv=True): writerow(row) data = queue.getvalue() response.write(data) return response elif request.POST.get("delete") and can_delete_entries: selected = request.POST.getlist("selected") if selected: entries = FormEntry.objects.filter(id__in=selected) count = entries.count() if count > 0: entries.delete() message = ungettext("1 entry deleted", "%(count)s entries deleted", count) info(request, message % {"count": count}) template = "admin/forms/entries.html" context = {"title": _("View Entries"), "entries_form": entries_form, "opts": self.model._meta, "original": form, "can_delete_entries": can_delete_entries, "submitted": submitted} return render_to_response(template, context, RequestContext(request)) def file_view(self, request, field_entry_id): """ Output the file for the requested field entry. """ field_entry = get_object_or_404(FieldEntry, id=field_entry_id) path = join(fs.location, field_entry.value) response = HttpResponse(content_type=guess_type(path)[0]) f = open(path, "r+b") response["Content-Disposition"] = "attachment; filename=%s" % f.name response.write(f.read()) f.close() return response admin.site.register(Form, FormAdmin)
bsd-3-clause
code4sac/adopt-a-light
app/models/problem_type.rb
88
class ProblemType < ActiveRecord::Base attr_accessible :name has_many :problems end
bsd-3-clause
Ghands/go
src/cmd/internal/ld/macho.go
19866
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ld import ( "sort" "strings" ) type MachoHdr struct { cpu uint32 subcpu uint32 } type MachoSect struct { name string segname string addr uint64 size uint64 off uint32 align uint32 reloc uint32 nreloc uint32 flag uint32 res1 uint32 res2 uint32 } type MachoSeg struct { name string vsize uint64 vaddr uint64 fileoffset uint64 filesize uint64 prot1 uint32 prot2 uint32 nsect uint32 msect uint32 sect []MachoSect flag uint32 } type MachoLoad struct { type_ uint32 data []uint32 } /* * Total amount of space to reserve at the start of the file * for Header, PHeaders, and SHeaders. * May waste some. */ const ( INITIAL_MACHO_HEADR = 4 * 1024 ) const ( MACHO_CPU_AMD64 = 1<<24 | 7 MACHO_CPU_386 = 7 MACHO_SUBCPU_X86 = 3 MACHO_CPU_ARM = 12 MACHO_SUBCPU_ARM = 0 MACHO_SUBCPU_ARMV7 = 9 MACHO32SYMSIZE = 12 MACHO64SYMSIZE = 16 MACHO_X86_64_RELOC_UNSIGNED = 0 MACHO_X86_64_RELOC_SIGNED = 1 MACHO_X86_64_RELOC_BRANCH = 2 MACHO_X86_64_RELOC_GOT_LOAD = 3 MACHO_X86_64_RELOC_GOT = 4 MACHO_X86_64_RELOC_SUBTRACTOR = 5 MACHO_X86_64_RELOC_SIGNED_1 = 6 MACHO_X86_64_RELOC_SIGNED_2 = 7 MACHO_X86_64_RELOC_SIGNED_4 = 8 MACHO_ARM_RELOC_VANILLA = 0 MACHO_ARM_RELOC_BR24 = 5 MACHO_GENERIC_RELOC_VANILLA = 0 MACHO_FAKE_GOTPCREL = 100 ) // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Mach-O file writing // http://developer.apple.com/mac/library/DOCUMENTATION/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html var macho64 bool var machohdr MachoHdr var load []MachoLoad var seg [16]MachoSeg var nseg int var ndebug int var nsect int const ( SymKindLocal = 0 + iota SymKindExtdef SymKindUndef NumSymKind ) var nkind [NumSymKind]int var sortsym []*LSym var nsortsym int // Amount of space left for adding load commands // that refer to dynamic libraries. Because these have // to go in the Mach-O header, we can't just pick a // "big enough" header size. The initial header is // one page, the non-dynamic library stuff takes // up about 1300 bytes; we overestimate that as 2k. var load_budget int = INITIAL_MACHO_HEADR - 2*1024 func Machoinit() { switch Thearch.Thechar { // 64-bit architectures case '6', '9': macho64 = true // 32-bit architectures default: break } } func getMachoHdr() *MachoHdr { return &machohdr } func newMachoLoad(type_ uint32, ndata uint32) *MachoLoad { if macho64 && (ndata&1 != 0) { ndata++ } load = append(load, MachoLoad{}) l := &load[len(load)-1] l.type_ = type_ l.data = make([]uint32, ndata) return l } func newMachoSeg(name string, msect int) *MachoSeg { if nseg >= len(seg) { Diag("too many segs") Errorexit() } s := &seg[nseg] nseg++ s.name = name s.msect = uint32(msect) s.sect = make([]MachoSect, msect) return s } func newMachoSect(seg *MachoSeg, name string, segname string) *MachoSect { if seg.nsect >= seg.msect { Diag("too many sects in segment %s", seg.name) Errorexit() } s := &seg.sect[seg.nsect] seg.nsect++ s.name = name s.segname = segname nsect++ return s } // Generic linking code. var dylib []string var linkoff int64 func machowrite() int { o1 := Cpos() loadsize := 4 * 4 * ndebug for i := 0; i < len(load); i++ { loadsize += 4 * (len(load[i].data) + 2) } if macho64 { loadsize += 18 * 4 * nseg loadsize += 20 * 4 * nsect } else { loadsize += 14 * 4 * nseg loadsize += 17 * 4 * nsect } if macho64 { Thearch.Lput(0xfeedfacf) } else { Thearch.Lput(0xfeedface) } Thearch.Lput(machohdr.cpu) Thearch.Lput(machohdr.subcpu) if Linkmode == LinkExternal { Thearch.Lput(1) /* file type - mach object */ } else { Thearch.Lput(2) /* file type - mach executable */ } Thearch.Lput(uint32(len(load)) + uint32(nseg) + uint32(ndebug)) Thearch.Lput(uint32(loadsize)) Thearch.Lput(1) /* flags - no undefines */ if macho64 { Thearch.Lput(0) /* reserved */ } var j int var s *MachoSeg var t *MachoSect for i := 0; i < nseg; i++ { s = &seg[i] if macho64 { Thearch.Lput(25) /* segment 64 */ Thearch.Lput(72 + 80*s.nsect) strnput(s.name, 16) Thearch.Vput(s.vaddr) Thearch.Vput(s.vsize) Thearch.Vput(s.fileoffset) Thearch.Vput(s.filesize) Thearch.Lput(s.prot1) Thearch.Lput(s.prot2) Thearch.Lput(s.nsect) Thearch.Lput(s.flag) } else { Thearch.Lput(1) /* segment 32 */ Thearch.Lput(56 + 68*s.nsect) strnput(s.name, 16) Thearch.Lput(uint32(s.vaddr)) Thearch.Lput(uint32(s.vsize)) Thearch.Lput(uint32(s.fileoffset)) Thearch.Lput(uint32(s.filesize)) Thearch.Lput(s.prot1) Thearch.Lput(s.prot2) Thearch.Lput(s.nsect) Thearch.Lput(s.flag) } for j = 0; uint32(j) < s.nsect; j++ { t = &s.sect[j] if macho64 { strnput(t.name, 16) strnput(t.segname, 16) Thearch.Vput(t.addr) Thearch.Vput(t.size) Thearch.Lput(t.off) Thearch.Lput(t.align) Thearch.Lput(t.reloc) Thearch.Lput(t.nreloc) Thearch.Lput(t.flag) Thearch.Lput(t.res1) /* reserved */ Thearch.Lput(t.res2) /* reserved */ Thearch.Lput(0) /* reserved */ } else { strnput(t.name, 16) strnput(t.segname, 16) Thearch.Lput(uint32(t.addr)) Thearch.Lput(uint32(t.size)) Thearch.Lput(t.off) Thearch.Lput(t.align) Thearch.Lput(t.reloc) Thearch.Lput(t.nreloc) Thearch.Lput(t.flag) Thearch.Lput(t.res1) /* reserved */ Thearch.Lput(t.res2) /* reserved */ } } } var l *MachoLoad for i := 0; i < len(load); i++ { l = &load[i] Thearch.Lput(l.type_) Thearch.Lput(4 * (uint32(len(l.data)) + 2)) for j = 0; j < len(l.data); j++ { Thearch.Lput(l.data[j]) } } return int(Cpos() - o1) } func domacho() { if Debug['d'] != 0 { return } // empirically, string table must begin with " \x00". s := Linklookup(Ctxt, ".machosymstr", 0) s.Type = SMACHOSYMSTR s.Reachable = true Adduint8(Ctxt, s, ' ') Adduint8(Ctxt, s, '\x00') s = Linklookup(Ctxt, ".machosymtab", 0) s.Type = SMACHOSYMTAB s.Reachable = true if Linkmode != LinkExternal { s := Linklookup(Ctxt, ".plt", 0) // will be __symbol_stub s.Type = SMACHOPLT s.Reachable = true s = Linklookup(Ctxt, ".got", 0) // will be __nl_symbol_ptr s.Type = SMACHOGOT s.Reachable = true s.Align = 4 s = Linklookup(Ctxt, ".linkedit.plt", 0) // indirect table for .plt s.Type = SMACHOINDIRECTPLT s.Reachable = true s = Linklookup(Ctxt, ".linkedit.got", 0) // indirect table for .got s.Type = SMACHOINDIRECTGOT s.Reachable = true } } func Machoadddynlib(lib string) { // Will need to store the library name rounded up // and 24 bytes of header metadata. If not enough // space, grab another page of initial space at the // beginning of the output file. load_budget -= (len(lib)+7)/8*8 + 24 if load_budget < 0 { HEADR += 4096 INITTEXT += 4096 load_budget += 4096 } dylib = append(dylib, lib) } func machoshbits(mseg *MachoSeg, sect *Section, segname string) { buf := "__" + strings.Replace(sect.Name[1:], ".", "_", -1) msect := newMachoSect(mseg, buf, segname) if sect.Rellen > 0 { msect.reloc = uint32(sect.Reloff) msect.nreloc = uint32(sect.Rellen / 8) } for 1<<msect.align < sect.Align { msect.align++ } msect.addr = sect.Vaddr msect.size = sect.Length if sect.Vaddr < sect.Seg.Vaddr+sect.Seg.Filelen { // data in file if sect.Length > sect.Seg.Vaddr+sect.Seg.Filelen-sect.Vaddr { Diag("macho cannot represent section %s crossing data and bss", sect.Name) } msect.off = uint32(sect.Seg.Fileoff + sect.Vaddr - sect.Seg.Vaddr) } else { // zero fill msect.off = 0 msect.flag |= 1 } if sect.Rwx&1 != 0 { msect.flag |= 0x400 /* has instructions */ } if sect.Name == ".plt" { msect.name = "__symbol_stub1" msect.flag = 0x80000408 /* only instructions, code, symbol stubs */ msect.res1 = 0 //nkind[SymKindLocal]; msect.res2 = 6 } if sect.Name == ".got" { msect.name = "__nl_symbol_ptr" msect.flag = 6 /* section with nonlazy symbol pointers */ msect.res1 = uint32(Linklookup(Ctxt, ".linkedit.plt", 0).Size / 4) /* offset into indirect symbol table */ } if sect.Name == ".init_array" { msect.name = "__mod_init_func" msect.flag = 9 // S_MOD_INIT_FUNC_POINTERS } } func Asmbmacho() { /* apple MACH */ va := INITTEXT - int64(HEADR) mh := getMachoHdr() switch Thearch.Thechar { default: Diag("unknown mach architecture") Errorexit() fallthrough case '5': mh.cpu = MACHO_CPU_ARM mh.subcpu = MACHO_SUBCPU_ARMV7 case '6': mh.cpu = MACHO_CPU_AMD64 mh.subcpu = MACHO_SUBCPU_X86 case '8': mh.cpu = MACHO_CPU_386 mh.subcpu = MACHO_SUBCPU_X86 } var ms *MachoSeg if Linkmode == LinkExternal { /* segment for entire file */ ms = newMachoSeg("", 40) ms.fileoffset = Segtext.Fileoff ms.filesize = Segdata.Fileoff + Segdata.Filelen - Segtext.Fileoff } /* segment for zero page */ if Linkmode != LinkExternal { ms = newMachoSeg("__PAGEZERO", 0) ms.vsize = uint64(va) } /* text */ v := Rnd(int64(uint64(HEADR)+Segtext.Length), int64(INITRND)) if Linkmode != LinkExternal { ms = newMachoSeg("__TEXT", 20) ms.vaddr = uint64(va) ms.vsize = uint64(v) ms.fileoffset = 0 ms.filesize = uint64(v) ms.prot1 = 7 ms.prot2 = 5 } for sect := Segtext.Sect; sect != nil; sect = sect.Next { machoshbits(ms, sect, "__TEXT") } /* data */ if Linkmode != LinkExternal { w := int64(Segdata.Length) ms = newMachoSeg("__DATA", 20) ms.vaddr = uint64(va) + uint64(v) ms.vsize = uint64(w) ms.fileoffset = uint64(v) ms.filesize = Segdata.Filelen ms.prot1 = 3 ms.prot2 = 3 } for sect := Segdata.Sect; sect != nil; sect = sect.Next { machoshbits(ms, sect, "__DATA") } if Linkmode != LinkExternal { switch Thearch.Thechar { default: Diag("unknown macho architecture") Errorexit() fallthrough case '5': ml := newMachoLoad(5, 17+2) /* unix thread */ ml.data[0] = 1 /* thread type */ ml.data[1] = 17 /* word count */ ml.data[2+15] = uint32(Entryvalue()) /* start pc */ case '6': ml := newMachoLoad(5, 42+2) /* unix thread */ ml.data[0] = 4 /* thread type */ ml.data[1] = 42 /* word count */ ml.data[2+32] = uint32(Entryvalue()) /* start pc */ ml.data[2+32+1] = uint32(Entryvalue() >> 16 >> 16) // hide >>32 for 8l case '8': ml := newMachoLoad(5, 16+2) /* unix thread */ ml.data[0] = 1 /* thread type */ ml.data[1] = 16 /* word count */ ml.data[2+10] = uint32(Entryvalue()) /* start pc */ } } if Debug['d'] == 0 { // must match domacholink below s1 := Linklookup(Ctxt, ".machosymtab", 0) s2 := Linklookup(Ctxt, ".linkedit.plt", 0) s3 := Linklookup(Ctxt, ".linkedit.got", 0) s4 := Linklookup(Ctxt, ".machosymstr", 0) if Linkmode != LinkExternal { ms := newMachoSeg("__LINKEDIT", 0) ms.vaddr = uint64(va) + uint64(v) + uint64(Rnd(int64(Segdata.Length), int64(INITRND))) ms.vsize = uint64(s1.Size) + uint64(s2.Size) + uint64(s3.Size) + uint64(s4.Size) ms.fileoffset = uint64(linkoff) ms.filesize = ms.vsize ms.prot1 = 7 ms.prot2 = 3 } ml := newMachoLoad(2, 4) /* LC_SYMTAB */ ml.data[0] = uint32(linkoff) /* symoff */ ml.data[1] = uint32(nsortsym) /* nsyms */ ml.data[2] = uint32(linkoff + s1.Size + s2.Size + s3.Size) /* stroff */ ml.data[3] = uint32(s4.Size) /* strsize */ machodysymtab() if Linkmode != LinkExternal { ml := newMachoLoad(14, 6) /* LC_LOAD_DYLINKER */ ml.data[0] = 12 /* offset to string */ stringtouint32(ml.data[1:], "/usr/lib/dyld") for i := 0; i < len(dylib); i++ { ml = newMachoLoad(12, 4+(uint32(len(dylib[i]))+1+7)/8*2) /* LC_LOAD_DYLIB */ ml.data[0] = 24 /* offset of string from beginning of load */ ml.data[1] = 0 /* time stamp */ ml.data[2] = 0 /* version */ ml.data[3] = 0 /* compatibility version */ stringtouint32(ml.data[4:], dylib[i]) } } } // TODO: dwarf headers go in ms too if Debug['s'] == 0 && Linkmode != LinkExternal { dwarfaddmachoheaders() } a := machowrite() if int32(a) > HEADR { Diag("HEADR too small: %d > %d", a, HEADR) } } func symkind(s *LSym) int { if s.Type == SDYNIMPORT { return SymKindUndef } if s.Cgoexport != 0 { return SymKindExtdef } return SymKindLocal } func addsym(s *LSym, name string, type_ int, addr int64, size int64, ver int, gotype *LSym) { if s == nil { return } switch type_ { default: return case 'D', 'B', 'T': break } if sortsym != nil { sortsym[nsortsym] = s nkind[symkind(s)]++ } nsortsym++ } type machoscmp []*LSym func (x machoscmp) Len() int { return len(x) } func (x machoscmp) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x machoscmp) Less(i, j int) bool { s1 := x[i] s2 := x[j] k1 := symkind(s1) k2 := symkind(s2) if k1 != k2 { return k1-k2 < 0 } return stringsCompare(s1.Extname, s2.Extname) < 0 } func machogenasmsym(put func(*LSym, string, int, int64, int64, int, *LSym)) { genasmsym(put) for s := Ctxt.Allsym; s != nil; s = s.Allsym { if s.Type == SDYNIMPORT || s.Type == SHOSTOBJ { if s.Reachable { put(s, "", 'D', 0, 0, 0, nil) } } } } func machosymorder() { // On Mac OS X Mountain Lion, we must sort exported symbols // So we sort them here and pre-allocate dynid for them // See http://golang.org/issue/4029 for i := 0; i < len(dynexp); i++ { dynexp[i].Reachable = true } machogenasmsym(addsym) sortsym = make([]*LSym, nsortsym) nsortsym = 0 machogenasmsym(addsym) sort.Sort(machoscmp(sortsym[:nsortsym])) for i := 0; i < nsortsym; i++ { sortsym[i].Dynid = int32(i) } } func machosymtab() { var s *LSym var o *LSym var p string symtab := Linklookup(Ctxt, ".machosymtab", 0) symstr := Linklookup(Ctxt, ".machosymstr", 0) for i := 0; i < nsortsym; i++ { s = sortsym[i] Adduint32(Ctxt, symtab, uint32(symstr.Size)) // Only add _ to C symbols. Go symbols have dot in the name. if !strings.Contains(s.Extname, ".") { Adduint8(Ctxt, symstr, '_') } // replace "·" as ".", because DTrace cannot handle it. if !strings.Contains(s.Extname, "·") { Addstring(symstr, s.Extname) } else { for p = s.Extname; p != ""; p = p[1:] { if uint8(p[0]) == 0xc2 && uint8((p[1:])[0]) == 0xb7 { Adduint8(Ctxt, symstr, '.') p = p[1:] } else { Adduint8(Ctxt, symstr, uint8(p[0])) } } Adduint8(Ctxt, symstr, '\x00') } if s.Type == SDYNIMPORT || s.Type == SHOSTOBJ { Adduint8(Ctxt, symtab, 0x01) // type N_EXT, external symbol Adduint8(Ctxt, symtab, 0) // no section Adduint16(Ctxt, symtab, 0) // desc adduintxx(Ctxt, symtab, 0, Thearch.Ptrsize) // no value } else { if s.Cgoexport != 0 { Adduint8(Ctxt, symtab, 0x0f) } else { Adduint8(Ctxt, symtab, 0x0e) } o = s for o.Outer != nil { o = o.Outer } if o.Sect == nil { Diag("missing section for %s", s.Name) Adduint8(Ctxt, symtab, 0) } else { Adduint8(Ctxt, symtab, uint8((o.Sect.(*Section)).Extnum)) } Adduint16(Ctxt, symtab, 0) // desc adduintxx(Ctxt, symtab, uint64(Symaddr(s)), Thearch.Ptrsize) } } } func machodysymtab() { ml := newMachoLoad(11, 18) /* LC_DYSYMTAB */ n := 0 ml.data[0] = uint32(n) /* ilocalsym */ ml.data[1] = uint32(nkind[SymKindLocal]) /* nlocalsym */ n += nkind[SymKindLocal] ml.data[2] = uint32(n) /* iextdefsym */ ml.data[3] = uint32(nkind[SymKindExtdef]) /* nextdefsym */ n += nkind[SymKindExtdef] ml.data[4] = uint32(n) /* iundefsym */ ml.data[5] = uint32(nkind[SymKindUndef]) /* nundefsym */ ml.data[6] = 0 /* tocoffset */ ml.data[7] = 0 /* ntoc */ ml.data[8] = 0 /* modtaboff */ ml.data[9] = 0 /* nmodtab */ ml.data[10] = 0 /* extrefsymoff */ ml.data[11] = 0 /* nextrefsyms */ // must match domacholink below s1 := Linklookup(Ctxt, ".machosymtab", 0) s2 := Linklookup(Ctxt, ".linkedit.plt", 0) s3 := Linklookup(Ctxt, ".linkedit.got", 0) ml.data[12] = uint32(linkoff + s1.Size) /* indirectsymoff */ ml.data[13] = uint32((s2.Size + s3.Size) / 4) /* nindirectsyms */ ml.data[14] = 0 /* extreloff */ ml.data[15] = 0 /* nextrel */ ml.data[16] = 0 /* locreloff */ ml.data[17] = 0 /* nlocrel */ } func Domacholink() int64 { machosymtab() // write data that will be linkedit section s1 := Linklookup(Ctxt, ".machosymtab", 0) s2 := Linklookup(Ctxt, ".linkedit.plt", 0) s3 := Linklookup(Ctxt, ".linkedit.got", 0) s4 := Linklookup(Ctxt, ".machosymstr", 0) // Force the linkedit section to end on a 16-byte // boundary. This allows pure (non-cgo) Go binaries // to be code signed correctly. // // Apple's codesign_allocate (a helper utility for // the codesign utility) can do this fine itself if // it is run on a dynamic Mach-O binary. However, // when it is run on a pure (non-cgo) Go binary, where // the linkedit section is mostly empty, it fails to // account for the extra padding that it itself adds // when adding the LC_CODE_SIGNATURE load command // (which must be aligned on a 16-byte boundary). // // By forcing the linkedit section to end on a 16-byte // boundary, codesign_allocate will not need to apply // any alignment padding itself, working around the // issue. for s4.Size%16 != 0 { Adduint8(Ctxt, s4, 0) } size := int(s1.Size + s2.Size + s3.Size + s4.Size) if size > 0 { linkoff = Rnd(int64(uint64(HEADR)+Segtext.Length), int64(INITRND)) + Rnd(int64(Segdata.Filelen), int64(INITRND)) + Rnd(int64(Segdwarf.Filelen), int64(INITRND)) Cseek(linkoff) Cwrite(s1.P[:s1.Size]) Cwrite(s2.P[:s2.Size]) Cwrite(s3.P[:s3.Size]) Cwrite(s4.P[:s4.Size]) } return Rnd(int64(size), int64(INITRND)) } func machorelocsect(sect *Section, first *LSym) { // If main section has no bits, nothing to relocate. if sect.Vaddr >= sect.Seg.Vaddr+sect.Seg.Filelen { return } sect.Reloff = uint64(Cpos()) var sym *LSym for sym = first; sym != nil; sym = sym.Next { if !sym.Reachable { continue } if uint64(sym.Value) >= sect.Vaddr { break } } eaddr := int32(sect.Vaddr + sect.Length) var r *Reloc var ri int for ; sym != nil; sym = sym.Next { if !sym.Reachable { continue } if sym.Value >= int64(eaddr) { break } Ctxt.Cursym = sym for ri = 0; ri < len(sym.R); ri++ { r = &sym.R[ri] if r.Done != 0 { continue } if Thearch.Machoreloc1(r, int64(uint64(sym.Value+int64(r.Off))-sect.Vaddr)) < 0 { Diag("unsupported obj reloc %d/%d to %s", r.Type, r.Siz, r.Sym.Name) } } } sect.Rellen = uint64(Cpos()) - sect.Reloff } func Machoemitreloc() { for Cpos()&7 != 0 { Cput(0) } machorelocsect(Segtext.Sect, Ctxt.Textp) for sect := Segtext.Sect.Next; sect != nil; sect = sect.Next { machorelocsect(sect, datap) } for sect := Segdata.Sect; sect != nil; sect = sect.Next { machorelocsect(sect, datap) } }
bsd-3-clause
BrantYii/store
backend/views/backenduser/_form.php
1751
<?php /** * Copyright (C) 2014 Dinesh Sharma - All Rights Reserved * You may use, distribute and modify this code under the * terms of the GPL license. * * You should have received a copy of the GPL license with * this file. If not, please visit : * https://gnu.org/licenses/gpl.html */ use yii\helpers\Html; use yii\widgets\ActiveForm; /** * @var yii\web\View $this * @var backend\models\BackendUser $model * @var yii\widgets\ActiveForm $form */ ?> <div class="half-div"> <?php $form = ActiveForm::begin(); ?> <div class="caption-heading"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?= Html::a('<i class="glyphicon glyphicon-circle-arrow-left"></i>&nbsp'.Yii::t('app', 'Back'), ['index'], ['class' => 'btn btn-warning']) ?> <?= $this->title ?> </div> <?= $form->field($model, 'username')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'password_hash')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'email')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'role')->textInput() ?> <?= $form->field($model, 'created_by')->textInput() ?> <?= $form->field($model, 'updated_by')->textInput() ?> <?= $form->field($model, 'status')->textInput() ?> <?= $form->field($model, 'created_at')->textInput() ?> <?= $form->field($model, 'updated_at')->textInput() ?> <?= $form->field($model, 'auth_key')->textInput(['maxlength' => 32]) ?> <?= $form->field($model, 'password_reset_token')->textInput(['maxlength' => 32]) ?> <?php ActiveForm::end(); ?> </div>
bsd-3-clause
patrickm/chromium.src
ui/aura/window_event_dispatcher_unittest.cc
71814
// 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 "ui/aura/window_event_dispatcher.h" #include <vector> #include "base/bind.h" #include "base/run_loop.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/aura/client/event_client.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/env.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/env_test_helper.h" #include "ui/aura/test/event_generator.h" #include "ui/aura/test/test_cursor_client.h" #include "ui/aura/test/test_screen.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_tracker.h" #include "ui/base/hit_test.h" #include "ui/events/event.h" #include "ui/events/event_handler.h" #include "ui/events/event_utils.h" #include "ui/events/gestures/gesture_configuration.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/events/test/test_event_handler.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/screen.h" #include "ui/gfx/transform.h" namespace aura { namespace { bool PlatformSupportsMultipleHosts() { #if defined(USE_OZONE) // Creating multiple WindowTreeHostOzone instances is broken. return false; #else return true; #endif } // A delegate that always returns a non-client component for hit tests. class NonClientDelegate : public test::TestWindowDelegate { public: NonClientDelegate() : non_client_count_(0), mouse_event_count_(0), mouse_event_flags_(0x0) { } virtual ~NonClientDelegate() {} int non_client_count() const { return non_client_count_; } gfx::Point non_client_location() const { return non_client_location_; } int mouse_event_count() const { return mouse_event_count_; } gfx::Point mouse_event_location() const { return mouse_event_location_; } int mouse_event_flags() const { return mouse_event_flags_; } virtual int GetNonClientComponent(const gfx::Point& location) const OVERRIDE { NonClientDelegate* self = const_cast<NonClientDelegate*>(this); self->non_client_count_++; self->non_client_location_ = location; return HTTOPLEFT; } virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { mouse_event_count_++; mouse_event_location_ = event->location(); mouse_event_flags_ = event->flags(); event->SetHandled(); } private: int non_client_count_; gfx::Point non_client_location_; int mouse_event_count_; gfx::Point mouse_event_location_; int mouse_event_flags_; DISALLOW_COPY_AND_ASSIGN(NonClientDelegate); }; // A simple event handler that consumes key events. class ConsumeKeyHandler : public ui::test::TestEventHandler { public: ConsumeKeyHandler() {} virtual ~ConsumeKeyHandler() {} // Overridden from ui::EventHandler: virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE { ui::test::TestEventHandler::OnKeyEvent(event); event->StopPropagation(); } private: DISALLOW_COPY_AND_ASSIGN(ConsumeKeyHandler); }; bool IsFocusedWindow(aura::Window* window) { return client::GetFocusClient(window)->GetFocusedWindow() == window; } } // namespace typedef test::AuraTestBase WindowEventDispatcherTest; TEST_F(WindowEventDispatcherTest, OnHostMouseEvent) { // Create two non-overlapping windows so we don't have to worry about which // is on top. scoped_ptr<NonClientDelegate> delegate1(new NonClientDelegate()); scoped_ptr<NonClientDelegate> delegate2(new NonClientDelegate()); const int kWindowWidth = 123; const int kWindowHeight = 45; gfx::Rect bounds1(100, 200, kWindowWidth, kWindowHeight); gfx::Rect bounds2(300, 400, kWindowWidth, kWindowHeight); scoped_ptr<aura::Window> window1(CreateTestWindowWithDelegate( delegate1.get(), -1234, bounds1, root_window())); scoped_ptr<aura::Window> window2(CreateTestWindowWithDelegate( delegate2.get(), -5678, bounds2, root_window())); // Send a mouse event to window1. gfx::Point point(101, 201); ui::MouseEvent event1( ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); DispatchEventUsingWindowDispatcher(&event1); // Event was tested for non-client area for the target window. EXPECT_EQ(1, delegate1->non_client_count()); EXPECT_EQ(0, delegate2->non_client_count()); // The non-client component test was in local coordinates. EXPECT_EQ(gfx::Point(1, 1), delegate1->non_client_location()); // Mouse event was received by target window. EXPECT_EQ(1, delegate1->mouse_event_count()); EXPECT_EQ(0, delegate2->mouse_event_count()); // Event was in local coordinates. EXPECT_EQ(gfx::Point(1, 1), delegate1->mouse_event_location()); // Non-client flag was set. EXPECT_TRUE(delegate1->mouse_event_flags() & ui::EF_IS_NON_CLIENT); } TEST_F(WindowEventDispatcherTest, RepostEvent) { // Test RepostEvent in RootWindow. It only works for Mouse Press. EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); gfx::Point point(10, 10); ui::MouseEvent event( ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); host()->dispatcher()->RepostEvent(event); RunAllPendingInMessageLoop(); EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); } // Check that we correctly track the state of the mouse buttons in response to // button press and release events. TEST_F(WindowEventDispatcherTest, MouseButtonState) { EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); gfx::Point location; scoped_ptr<ui::MouseEvent> event; // Press the left button. event.reset(new ui::MouseEvent( ui::ET_MOUSE_PRESSED, location, location, ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); DispatchEventUsingWindowDispatcher(event.get()); EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); // Additionally press the right. event.reset(new ui::MouseEvent( ui::ET_MOUSE_PRESSED, location, location, ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); DispatchEventUsingWindowDispatcher(event.get()); EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); // Release the left button. event.reset(new ui::MouseEvent( ui::ET_MOUSE_RELEASED, location, location, ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); DispatchEventUsingWindowDispatcher(event.get()); EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); // Release the right button. We should ignore the Shift-is-down flag. event.reset(new ui::MouseEvent( ui::ET_MOUSE_RELEASED, location, location, ui::EF_SHIFT_DOWN, ui::EF_RIGHT_MOUSE_BUTTON)); DispatchEventUsingWindowDispatcher(event.get()); EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); // Press the middle button. event.reset(new ui::MouseEvent( ui::ET_MOUSE_PRESSED, location, location, ui::EF_MIDDLE_MOUSE_BUTTON, ui::EF_MIDDLE_MOUSE_BUTTON)); DispatchEventUsingWindowDispatcher(event.get()); EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); } TEST_F(WindowEventDispatcherTest, TranslatedEvent) { scoped_ptr<Window> w1(test::CreateTestWindowWithDelegate(NULL, 1, gfx::Rect(50, 50, 100, 100), root_window())); gfx::Point origin(100, 100); ui::MouseEvent root(ui::ET_MOUSE_PRESSED, origin, origin, 0, 0); EXPECT_EQ("100,100", root.location().ToString()); EXPECT_EQ("100,100", root.root_location().ToString()); ui::MouseEvent translated_event( root, static_cast<Window*>(root_window()), w1.get(), ui::ET_MOUSE_ENTERED, root.flags()); EXPECT_EQ("50,50", translated_event.location().ToString()); EXPECT_EQ("100,100", translated_event.root_location().ToString()); } namespace { class TestEventClient : public client::EventClient { public: static const int kNonLockWindowId = 100; static const int kLockWindowId = 200; explicit TestEventClient(Window* root_window) : root_window_(root_window), lock_(false) { client::SetEventClient(root_window_, this); Window* lock_window = test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_); lock_window->set_id(kLockWindowId); Window* non_lock_window = test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_); non_lock_window->set_id(kNonLockWindowId); } virtual ~TestEventClient() { client::SetEventClient(root_window_, NULL); } // Starts/stops locking. Locking prevents windows other than those inside // the lock container from receiving events, getting focus etc. void Lock() { lock_ = true; } void Unlock() { lock_ = false; } Window* GetLockWindow() { return const_cast<Window*>( static_cast<const TestEventClient*>(this)->GetLockWindow()); } const Window* GetLockWindow() const { return root_window_->GetChildById(kLockWindowId); } Window* GetNonLockWindow() { return root_window_->GetChildById(kNonLockWindowId); } private: // Overridden from client::EventClient: virtual bool CanProcessEventsWithinSubtree( const Window* window) const OVERRIDE { return lock_ ? window->Contains(GetLockWindow()) || GetLockWindow()->Contains(window) : true; } virtual ui::EventTarget* GetToplevelEventTarget() OVERRIDE { return NULL; } Window* root_window_; bool lock_; DISALLOW_COPY_AND_ASSIGN(TestEventClient); }; } // namespace TEST_F(WindowEventDispatcherTest, CanProcessEventsWithinSubtree) { TestEventClient client(root_window()); test::TestWindowDelegate d; ui::test::TestEventHandler* nonlock_ef = new ui::test::TestEventHandler; ui::test::TestEventHandler* lock_ef = new ui::test::TestEventHandler; client.GetNonLockWindow()->SetEventFilter(nonlock_ef); client.GetLockWindow()->SetEventFilter(lock_ef); Window* w1 = test::CreateTestWindowWithBounds(gfx::Rect(10, 10, 20, 20), client.GetNonLockWindow()); w1->set_id(1); Window* w2 = test::CreateTestWindowWithBounds(gfx::Rect(30, 30, 20, 20), client.GetNonLockWindow()); w2->set_id(2); scoped_ptr<Window> w3( test::CreateTestWindowWithDelegate(&d, 3, gfx::Rect(30, 30, 20, 20), client.GetLockWindow())); w1->Focus(); EXPECT_TRUE(IsFocusedWindow(w1)); client.Lock(); // Since we're locked, the attempt to focus w2 will be ignored. w2->Focus(); EXPECT_TRUE(IsFocusedWindow(w1)); EXPECT_FALSE(IsFocusedWindow(w2)); { // Attempting to send a key event to w1 (not in the lock container) should // cause focus to be reset. test::EventGenerator generator(root_window()); generator.PressKey(ui::VKEY_SPACE, 0); EXPECT_EQ(NULL, client::GetFocusClient(w1)->GetFocusedWindow()); EXPECT_FALSE(IsFocusedWindow(w1)); } { // Events sent to a window not in the lock container will not be processed. // i.e. never sent to the non-lock container's event filter. test::EventGenerator generator(root_window(), w1); generator.ClickLeftButton(); EXPECT_EQ(0, nonlock_ef->num_mouse_events()); // Events sent to a window in the lock container will be processed. test::EventGenerator generator3(root_window(), w3.get()); generator3.PressLeftButton(); EXPECT_EQ(1, lock_ef->num_mouse_events()); } // Prevent w3 from being deleted by the hierarchy since its delegate is owned // by this scope. w3->parent()->RemoveChild(w3.get()); } TEST_F(WindowEventDispatcherTest, IgnoreUnknownKeys) { ui::test::TestEventHandler* filter = new ConsumeKeyHandler; root_window()->SetEventFilter(filter); // passes ownership ui::KeyEvent unknown_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN, 0, false); DispatchEventUsingWindowDispatcher(&unknown_event); EXPECT_FALSE(unknown_event.handled()); EXPECT_EQ(0, filter->num_key_events()); ui::KeyEvent known_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false); DispatchEventUsingWindowDispatcher(&known_event); EXPECT_TRUE(known_event.handled()); EXPECT_EQ(1, filter->num_key_events()); } TEST_F(WindowEventDispatcherTest, NoDelegateWindowReceivesKeyEvents) { scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); w1->Show(); w1->Focus(); ui::test::TestEventHandler handler; w1->AddPreTargetHandler(&handler); ui::KeyEvent key_press(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false); DispatchEventUsingWindowDispatcher(&key_press); EXPECT_TRUE(key_press.handled()); EXPECT_EQ(1, handler.num_key_events()); w1->RemovePreTargetHandler(&handler); } // Tests that touch-events that are beyond the bounds of the root-window do get // propagated to the event filters correctly with the root as the target. TEST_F(WindowEventDispatcherTest, TouchEventsOutsideBounds) { ui::test::TestEventHandler* filter = new ui::test::TestEventHandler; root_window()->SetEventFilter(filter); // passes ownership gfx::Point position = root_window()->bounds().origin(); position.Offset(-10, -10); ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&press); EXPECT_EQ(1, filter->num_touch_events()); position = root_window()->bounds().origin(); position.Offset(root_window()->bounds().width() + 10, root_window()->bounds().height() + 10); ui::TouchEvent release(ui::ET_TOUCH_RELEASED, position, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&release); EXPECT_EQ(2, filter->num_touch_events()); } // Tests that scroll events are dispatched correctly. TEST_F(WindowEventDispatcherTest, ScrollEventDispatch) { base::TimeDelta now = ui::EventTimeForNow(); ui::test::TestEventHandler* filter = new ui::test::TestEventHandler; root_window()->SetEventFilter(filter); test::TestWindowDelegate delegate; scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate)); w1->SetBounds(gfx::Rect(20, 20, 40, 40)); // A scroll event on the root-window itself is dispatched. ui::ScrollEvent scroll1(ui::ET_SCROLL, gfx::Point(10, 10), now, 0, 0, -10, 0, -10, 2); DispatchEventUsingWindowDispatcher(&scroll1); EXPECT_EQ(1, filter->num_scroll_events()); // Scroll event on a window should be dispatched properly. ui::ScrollEvent scroll2(ui::ET_SCROLL, gfx::Point(25, 30), now, 0, -10, 0, -10, 0, 2); DispatchEventUsingWindowDispatcher(&scroll2); EXPECT_EQ(2, filter->num_scroll_events()); } namespace { // FilterFilter that tracks the types of events it's seen. class EventFilterRecorder : public ui::EventHandler { public: typedef std::vector<ui::EventType> Events; typedef std::vector<gfx::Point> EventLocations; EventFilterRecorder() : wait_until_event_(ui::ET_UNKNOWN) { } const Events& events() const { return events_; } const EventLocations& mouse_locations() const { return mouse_locations_; } gfx::Point mouse_location(int i) const { return mouse_locations_[i]; } const EventLocations& touch_locations() const { return touch_locations_; } void WaitUntilReceivedEvent(ui::EventType type) { wait_until_event_ = type; run_loop_.reset(new base::RunLoop()); run_loop_->Run(); } Events GetAndResetEvents() { Events events = events_; Reset(); return events; } void Reset() { events_.clear(); mouse_locations_.clear(); touch_locations_.clear(); } // ui::EventHandler overrides: virtual void OnEvent(ui::Event* event) OVERRIDE { ui::EventHandler::OnEvent(event); events_.push_back(event->type()); if (wait_until_event_ == event->type() && run_loop_) { run_loop_->Quit(); wait_until_event_ = ui::ET_UNKNOWN; } } virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { mouse_locations_.push_back(event->location()); } virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE { touch_locations_.push_back(event->location()); } private: scoped_ptr<base::RunLoop> run_loop_; ui::EventType wait_until_event_; Events events_; EventLocations mouse_locations_; EventLocations touch_locations_; DISALLOW_COPY_AND_ASSIGN(EventFilterRecorder); }; // Converts an EventType to a string. std::string EventTypeToString(ui::EventType type) { switch (type) { case ui::ET_TOUCH_RELEASED: return "TOUCH_RELEASED"; case ui::ET_TOUCH_CANCELLED: return "TOUCH_CANCELLED"; case ui::ET_TOUCH_PRESSED: return "TOUCH_PRESSED"; case ui::ET_TOUCH_MOVED: return "TOUCH_MOVED"; case ui::ET_MOUSE_PRESSED: return "MOUSE_PRESSED"; case ui::ET_MOUSE_DRAGGED: return "MOUSE_DRAGGED"; case ui::ET_MOUSE_RELEASED: return "MOUSE_RELEASED"; case ui::ET_MOUSE_MOVED: return "MOUSE_MOVED"; case ui::ET_MOUSE_ENTERED: return "MOUSE_ENTERED"; case ui::ET_MOUSE_EXITED: return "MOUSE_EXITED"; case ui::ET_GESTURE_SCROLL_BEGIN: return "GESTURE_SCROLL_BEGIN"; case ui::ET_GESTURE_SCROLL_END: return "GESTURE_SCROLL_END"; case ui::ET_GESTURE_SCROLL_UPDATE: return "GESTURE_SCROLL_UPDATE"; case ui::ET_GESTURE_PINCH_BEGIN: return "GESTURE_PINCH_BEGIN"; case ui::ET_GESTURE_PINCH_END: return "GESTURE_PINCH_END"; case ui::ET_GESTURE_PINCH_UPDATE: return "GESTURE_PINCH_UPDATE"; case ui::ET_GESTURE_TAP: return "GESTURE_TAP"; case ui::ET_GESTURE_TAP_DOWN: return "GESTURE_TAP_DOWN"; case ui::ET_GESTURE_TAP_CANCEL: return "GESTURE_TAP_CANCEL"; case ui::ET_GESTURE_SHOW_PRESS: return "GESTURE_SHOW_PRESS"; case ui::ET_GESTURE_BEGIN: return "GESTURE_BEGIN"; case ui::ET_GESTURE_END: return "GESTURE_END"; default: // We should explicitly require each event type. NOTREACHED(); break; } return ""; } std::string EventTypesToString(const EventFilterRecorder::Events& events) { std::string result; for (size_t i = 0; i < events.size(); ++i) { if (i != 0) result += " "; result += EventTypeToString(events[i]); } return result; } } // namespace // Verifies a repost mouse event targets the window with capture (if there is // one). TEST_F(WindowEventDispatcherTest, RepostTargetsCaptureWindow) { // Set capture on |window| generate a mouse event (that is reposted) and not // over |window| and verify |window| gets it (|window| gets it because it has // capture). EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); scoped_ptr<Window> window(CreateNormalWindow(1, root_window(), NULL)); window->SetBounds(gfx::Rect(20, 20, 40, 30)); EventFilterRecorder* recorder = new EventFilterRecorder; window->SetEventFilter(recorder); // Takes ownership. window->SetCapture(); const ui::MouseEvent press_event( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); host()->dispatcher()->RepostEvent(press_event); RunAllPendingInMessageLoop(); // Necessitated by RepostEvent(). // Mouse moves/enters may be generated. We only care about a pressed. EXPECT_TRUE(EventTypesToString(recorder->events()).find("MOUSE_PRESSED") != std::string::npos) << EventTypesToString(recorder->events()); } TEST_F(WindowEventDispatcherTest, MouseMovesHeld) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); // passes ownership test::TestWindowDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); ui::MouseEvent mouse_move_event(ui::ET_MOUSE_MOVED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); DispatchEventUsingWindowDispatcher(&mouse_move_event); // Discard MOUSE_ENTER. filter->Reset(); host()->dispatcher()->HoldPointerMoves(); // Check that we don't immediately dispatch the MOUSE_DRAGGED event. ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); DispatchEventUsingWindowDispatcher(&mouse_dragged_event); EXPECT_TRUE(filter->events().empty()); // Check that we do dispatch the held MOUSE_DRAGGED event before another type // of event. ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); DispatchEventUsingWindowDispatcher(&mouse_pressed_event); EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED", EventTypesToString(filter->events())); filter->Reset(); // Check that we coalesce held MOUSE_DRAGGED events. ui::MouseEvent mouse_dragged_event2(ui::ET_MOUSE_DRAGGED, gfx::Point(10, 10), gfx::Point(10, 10), 0, 0); DispatchEventUsingWindowDispatcher(&mouse_dragged_event); DispatchEventUsingWindowDispatcher(&mouse_dragged_event2); EXPECT_TRUE(filter->events().empty()); DispatchEventUsingWindowDispatcher(&mouse_pressed_event); EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED", EventTypesToString(filter->events())); filter->Reset(); // Check that on ReleasePointerMoves, held events are not dispatched // immediately, but posted instead. DispatchEventUsingWindowDispatcher(&mouse_dragged_event); host()->dispatcher()->ReleasePointerMoves(); EXPECT_TRUE(filter->events().empty()); RunAllPendingInMessageLoop(); EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(filter->events())); filter->Reset(); // However if another message comes in before the dispatch of the posted // event, check that the posted event is dispatched before this new event. host()->dispatcher()->HoldPointerMoves(); DispatchEventUsingWindowDispatcher(&mouse_dragged_event); host()->dispatcher()->ReleasePointerMoves(); DispatchEventUsingWindowDispatcher(&mouse_pressed_event); EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED", EventTypesToString(filter->events())); filter->Reset(); RunAllPendingInMessageLoop(); EXPECT_TRUE(filter->events().empty()); // Check that if the other message is another MOUSE_DRAGGED, we still coalesce // them. host()->dispatcher()->HoldPointerMoves(); DispatchEventUsingWindowDispatcher(&mouse_dragged_event); host()->dispatcher()->ReleasePointerMoves(); DispatchEventUsingWindowDispatcher(&mouse_dragged_event2); EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(filter->events())); filter->Reset(); RunAllPendingInMessageLoop(); EXPECT_TRUE(filter->events().empty()); // Check that synthetic mouse move event has a right location when issued // while holding pointer moves. ui::MouseEvent mouse_dragged_event3(ui::ET_MOUSE_DRAGGED, gfx::Point(28, 28), gfx::Point(28, 28), 0, 0); host()->dispatcher()->HoldPointerMoves(); DispatchEventUsingWindowDispatcher(&mouse_dragged_event); DispatchEventUsingWindowDispatcher(&mouse_dragged_event2); window->SetBounds(gfx::Rect(15, 15, 80, 80)); DispatchEventUsingWindowDispatcher(&mouse_dragged_event3); RunAllPendingInMessageLoop(); EXPECT_TRUE(filter->events().empty()); host()->dispatcher()->ReleasePointerMoves(); RunAllPendingInMessageLoop(); EXPECT_EQ("MOUSE_MOVED", EventTypesToString(filter->events())); EXPECT_EQ(gfx::Point(13, 13), filter->mouse_location(0)); filter->Reset(); } TEST_F(WindowEventDispatcherTest, TouchMovesHeld) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); // passes ownership test::TestWindowDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); const gfx::Point touch_location(60, 60); // Starting the touch and throwing out the first few events, since the system // is going to generate synthetic mouse events that are not relevant to the // test. ui::TouchEvent touch_pressed_event(ui::ET_TOUCH_PRESSED, touch_location, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&touch_pressed_event); filter->WaitUntilReceivedEvent(ui::ET_GESTURE_SHOW_PRESS); filter->Reset(); host()->dispatcher()->HoldPointerMoves(); // Check that we don't immediately dispatch the TOUCH_MOVED event. ui::TouchEvent touch_moved_event(ui::ET_TOUCH_MOVED, touch_location, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&touch_moved_event); EXPECT_TRUE(filter->events().empty()); // Check that on ReleasePointerMoves, held events are not dispatched // immediately, but posted instead. DispatchEventUsingWindowDispatcher(&touch_moved_event); host()->dispatcher()->ReleasePointerMoves(); EXPECT_TRUE(filter->events().empty()); RunAllPendingInMessageLoop(); EXPECT_EQ("TOUCH_MOVED", EventTypesToString(filter->events())); filter->Reset(); // If another touch event occurs then the held touch should be dispatched // immediately before it. ui::TouchEvent touch_released_event(ui::ET_TOUCH_RELEASED, touch_location, 0, base::TimeDelta()); filter->Reset(); host()->dispatcher()->HoldPointerMoves(); DispatchEventUsingWindowDispatcher(&touch_moved_event); DispatchEventUsingWindowDispatcher(&touch_released_event); EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_TAP_CANCEL GESTURE_END", EventTypesToString(filter->events())); filter->Reset(); host()->dispatcher()->ReleasePointerMoves(); RunAllPendingInMessageLoop(); EXPECT_TRUE(filter->events().empty()); } class HoldPointerOnScrollHandler : public ui::test::TestEventHandler { public: HoldPointerOnScrollHandler(WindowEventDispatcher* dispatcher, EventFilterRecorder* filter) : dispatcher_(dispatcher), filter_(filter), holding_moves_(false) { } virtual ~HoldPointerOnScrollHandler() {} private: virtual void OnGestureEvent(ui::GestureEvent* gesture) OVERRIDE { if (gesture->type() == ui::ET_GESTURE_SCROLL_UPDATE) { CHECK(!holding_moves_); holding_moves_ = true; dispatcher_->HoldPointerMoves(); filter_->Reset(); } else if (gesture->type() == ui::ET_GESTURE_SCROLL_END) { dispatcher_->ReleasePointerMoves(); holding_moves_ = false; } } WindowEventDispatcher* dispatcher_; EventFilterRecorder* filter_; bool holding_moves_; DISALLOW_COPY_AND_ASSIGN(HoldPointerOnScrollHandler); }; // Tests that touch-move events don't contribute to an in-progress scroll // gesture if touch-move events are being held by the dispatcher. TEST_F(WindowEventDispatcherTest, TouchMovesHeldOnScroll) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); test::TestWindowDelegate delegate; HoldPointerOnScrollHandler handler(host()->dispatcher(), filter); scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); window->AddPreTargetHandler(&handler); test::EventGenerator generator(root_window()); generator.GestureScrollSequence( gfx::Point(60, 60), gfx::Point(10, 60), base::TimeDelta::FromMilliseconds(100), 25); // |handler| will have reset |filter| and started holding the touch-move // events when scrolling started. At the end of the scroll (i.e. upon // touch-release), the held touch-move event will have been dispatched first, // along with the subsequent events (i.e. touch-release, scroll-end, and // gesture-end). const EventFilterRecorder::Events& events = filter->events(); EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_SCROLL_END GESTURE_END", EventTypesToString(events)); ASSERT_EQ(2u, filter->touch_locations().size()); EXPECT_EQ(gfx::Point(-40, 10).ToString(), filter->touch_locations()[0].ToString()); EXPECT_EQ(gfx::Point(-40, 10).ToString(), filter->touch_locations()[1].ToString()); } // Tests that synthetic mouse events are ignored when mouse // events are disabled. TEST_F(WindowEventDispatcherTest, DispatchSyntheticMouseEvents) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); // passes ownership test::TestWindowDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); window->Show(); window->SetCapture(); test::TestCursorClient cursor_client(root_window()); // Dispatch a non-synthetic mouse event when mouse events are enabled. ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), gfx::Point(10, 10), 0, 0); DispatchEventUsingWindowDispatcher(&mouse1); EXPECT_FALSE(filter->events().empty()); filter->Reset(); // Dispatch a synthetic mouse event when mouse events are enabled. ui::MouseEvent mouse2(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EF_IS_SYNTHESIZED, 0); DispatchEventUsingWindowDispatcher(&mouse2); EXPECT_FALSE(filter->events().empty()); filter->Reset(); // Dispatch a synthetic mouse event when mouse events are disabled. cursor_client.DisableMouseEvents(); DispatchEventUsingWindowDispatcher(&mouse2); EXPECT_TRUE(filter->events().empty()); } // Tests that a mouse exit is dispatched to the last known cursor location // when the cursor becomes invisible. TEST_F(WindowEventDispatcherTest, DispatchMouseExitWhenCursorHidden) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); // passes ownership test::TestWindowDelegate delegate; gfx::Point window_origin(7, 18); scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)), root_window())); window->Show(); // Dispatch a mouse move event into the window. gfx::Point mouse_location(gfx::Point(15, 25)); ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location, mouse_location, 0, 0); EXPECT_TRUE(filter->events().empty()); DispatchEventUsingWindowDispatcher(&mouse1); EXPECT_FALSE(filter->events().empty()); filter->Reset(); // Hide the cursor and verify a mouse exit was dispatched. host()->OnCursorVisibilityChanged(false); EXPECT_FALSE(filter->events().empty()); EXPECT_EQ("MOUSE_EXITED", EventTypesToString(filter->events())); // Verify the mouse exit was dispatched at the correct location // (in the correct coordinate space). int translated_x = mouse_location.x() - window_origin.x(); int translated_y = mouse_location.y() - window_origin.y(); gfx::Point translated_point(translated_x, translated_y); EXPECT_EQ(filter->mouse_location(0).ToString(), translated_point.ToString()); } class DeletingEventFilter : public ui::EventHandler { public: DeletingEventFilter() : delete_during_pre_handle_(false) {} virtual ~DeletingEventFilter() {} void Reset(bool delete_during_pre_handle) { delete_during_pre_handle_ = delete_during_pre_handle; } private: // Overridden from ui::EventHandler: virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE { if (delete_during_pre_handle_) delete event->target(); } virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { if (delete_during_pre_handle_) delete event->target(); } bool delete_during_pre_handle_; DISALLOW_COPY_AND_ASSIGN(DeletingEventFilter); }; class DeletingWindowDelegate : public test::TestWindowDelegate { public: DeletingWindowDelegate() : window_(NULL), delete_during_handle_(false), got_event_(false) {} virtual ~DeletingWindowDelegate() {} void Reset(Window* window, bool delete_during_handle) { window_ = window; delete_during_handle_ = delete_during_handle; got_event_ = false; } bool got_event() const { return got_event_; } private: // Overridden from WindowDelegate: virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE { if (delete_during_handle_) delete window_; got_event_ = true; } virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { if (delete_during_handle_) delete window_; got_event_ = true; } Window* window_; bool delete_during_handle_; bool got_event_; DISALLOW_COPY_AND_ASSIGN(DeletingWindowDelegate); }; TEST_F(WindowEventDispatcherTest, DeleteWindowDuringDispatch) { // Verifies that we can delete a window during each phase of event handling. // Deleting the window should not cause a crash, only prevent further // processing from occurring. scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); DeletingWindowDelegate d11; Window* w11 = CreateNormalWindow(11, w1.get(), &d11); WindowTracker tracker; DeletingEventFilter* w1_filter = new DeletingEventFilter; w1->SetEventFilter(w1_filter); client::GetFocusClient(w1.get())->FocusWindow(w11); test::EventGenerator generator(root_window(), w11); // First up, no one deletes anything. tracker.Add(w11); d11.Reset(w11, false); generator.PressLeftButton(); EXPECT_TRUE(tracker.Contains(w11)); EXPECT_TRUE(d11.got_event()); generator.ReleaseLeftButton(); // Delegate deletes w11. This will prevent the post-handle step from applying. w1_filter->Reset(false); d11.Reset(w11, true); generator.PressKey(ui::VKEY_A, 0); EXPECT_FALSE(tracker.Contains(w11)); EXPECT_TRUE(d11.got_event()); // Pre-handle step deletes w11. This will prevent the delegate and the post- // handle steps from applying. w11 = CreateNormalWindow(11, w1.get(), &d11); w1_filter->Reset(true); d11.Reset(w11, false); generator.PressLeftButton(); EXPECT_FALSE(tracker.Contains(w11)); EXPECT_FALSE(d11.got_event()); } namespace { // A window delegate that detaches the parent of the target's parent window when // it receives a tap event. class DetachesParentOnTapDelegate : public test::TestWindowDelegate { public: DetachesParentOnTapDelegate() {} virtual ~DetachesParentOnTapDelegate() {} private: virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE { if (event->type() == ui::ET_GESTURE_TAP_DOWN) { event->SetHandled(); return; } if (event->type() == ui::ET_GESTURE_TAP) { Window* parent = static_cast<Window*>(event->target())->parent(); parent->parent()->RemoveChild(parent); event->SetHandled(); } } DISALLOW_COPY_AND_ASSIGN(DetachesParentOnTapDelegate); }; } // namespace // Tests that the gesture recognizer is reset for all child windows when a // window hides. No expectations, just checks that the test does not crash. TEST_F(WindowEventDispatcherTest, GestureRecognizerResetsTargetWhenParentHides) { scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); DetachesParentOnTapDelegate delegate; scoped_ptr<Window> parent(CreateNormalWindow(22, w1.get(), NULL)); Window* child = CreateNormalWindow(11, parent.get(), &delegate); test::EventGenerator generator(root_window(), child); generator.GestureTapAt(gfx::Point(40, 40)); } namespace { // A window delegate that processes nested gestures on tap. class NestedGestureDelegate : public test::TestWindowDelegate { public: NestedGestureDelegate(test::EventGenerator* generator, const gfx::Point tap_location) : generator_(generator), tap_location_(tap_location), gesture_end_count_(0) {} virtual ~NestedGestureDelegate() {} int gesture_end_count() const { return gesture_end_count_; } private: virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE { switch (event->type()) { case ui::ET_GESTURE_TAP_DOWN: event->SetHandled(); break; case ui::ET_GESTURE_TAP: if (generator_) generator_->GestureTapAt(tap_location_); event->SetHandled(); break; case ui::ET_GESTURE_END: ++gesture_end_count_; break; default: break; } } test::EventGenerator* generator_; const gfx::Point tap_location_; int gesture_end_count_; DISALLOW_COPY_AND_ASSIGN(NestedGestureDelegate); }; } // namespace // Tests that gesture end is delivered after nested gesture processing. TEST_F(WindowEventDispatcherTest, GestureEndDeliveredAfterNestedGestures) { NestedGestureDelegate d1(NULL, gfx::Point()); scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &d1)); w1->SetBounds(gfx::Rect(0, 0, 100, 100)); test::EventGenerator nested_generator(root_window(), w1.get()); NestedGestureDelegate d2(&nested_generator, w1->bounds().CenterPoint()); scoped_ptr<Window> w2(CreateNormalWindow(1, root_window(), &d2)); w2->SetBounds(gfx::Rect(100, 0, 100, 100)); // Tap on w2 which triggers nested gestures for w1. test::EventGenerator generator(root_window(), w2.get()); generator.GestureTapAt(w2->bounds().CenterPoint()); // Both windows should get their gesture end events. EXPECT_EQ(1, d1.gesture_end_count()); EXPECT_EQ(1, d2.gesture_end_count()); } // Tests whether we can repost the Tap down gesture event. TEST_F(WindowEventDispatcherTest, RepostTapdownGestureTest) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); // passes ownership test::TestWindowDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); ui::GestureEventDetails details(ui::ET_GESTURE_TAP_DOWN, 0.0f, 0.0f); gfx::Point point(10, 10); ui::GestureEvent event( ui::ET_GESTURE_TAP_DOWN, point.x(), point.y(), 0, ui::EventTimeForNow(), details, 0); host()->dispatcher()->RepostEvent(event); RunAllPendingInMessageLoop(); // TODO(rbyers): Currently disabled - crbug.com/170987 EXPECT_FALSE(EventTypesToString(filter->events()).find("GESTURE_TAP_DOWN") != std::string::npos); filter->Reset(); } // This class inherits from the EventFilterRecorder class which provides a // facility to record events. This class additionally provides a facility to // repost the ET_GESTURE_TAP_DOWN gesture to the target window and records // events after that. class RepostGestureEventRecorder : public EventFilterRecorder { public: RepostGestureEventRecorder(aura::Window* repost_source, aura::Window* repost_target) : repost_source_(repost_source), repost_target_(repost_target), reposted_(false), done_cleanup_(false) {} virtual ~RepostGestureEventRecorder() {} virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE { if (reposted_ && event->type() == ui::ET_TOUCH_PRESSED) { done_cleanup_ = true; Reset(); } EventFilterRecorder::OnTouchEvent(event); } virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE { EXPECT_EQ(done_cleanup_ ? repost_target_ : repost_source_, event->target()); if (event->type() == ui::ET_GESTURE_TAP_DOWN) { if (!reposted_) { EXPECT_NE(repost_target_, event->target()); reposted_ = true; repost_target_->GetHost()->dispatcher()->RepostEvent(*event); // Ensure that the reposted gesture event above goes to the // repost_target_; repost_source_->GetRootWindow()->RemoveChild(repost_source_); return; } } EventFilterRecorder::OnGestureEvent(event); } // Ignore mouse events as they don't fire at all times. This causes // the GestureRepostEventOrder test to fail randomly. virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE {} private: aura::Window* repost_source_; aura::Window* repost_target_; // set to true if we reposted the ET_GESTURE_TAP_DOWN event. bool reposted_; // set true if we're done cleaning up after hiding repost_source_; bool done_cleanup_; DISALLOW_COPY_AND_ASSIGN(RepostGestureEventRecorder); }; // Tests whether events which are generated after the reposted gesture event // are received after that. In this case the scroll sequence events should // be received after the reposted gesture event. TEST_F(WindowEventDispatcherTest, GestureRepostEventOrder) { // Expected events at the end for the repost_target window defined below. const char kExpectedTargetEvents[] = // TODO)(rbyers): Gesture event reposting is disabled - crbug.com/279039. // "GESTURE_BEGIN GESTURE_TAP_DOWN " "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED " "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE TOUCH_MOVED " "GESTURE_SCROLL_UPDATE TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED " "GESTURE_SCROLL_END GESTURE_END"; // We create two windows. // The first window (repost_source) is the one to which the initial tap // gesture is sent. It reposts this event to the second window // (repost_target). // We then generate the scroll sequence for repost_target and look for two // ET_GESTURE_TAP_DOWN events in the event list at the end. test::TestWindowDelegate delegate; scoped_ptr<aura::Window> repost_target(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); scoped_ptr<aura::Window> repost_source(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(0, 0, 50, 50), root_window())); RepostGestureEventRecorder* repost_event_recorder = new RepostGestureEventRecorder(repost_source.get(), repost_target.get()); root_window()->SetEventFilter(repost_event_recorder); // passes ownership // Generate a tap down gesture for the repost_source. This will be reposted // to repost_target. test::EventGenerator repost_generator(root_window(), repost_source.get()); repost_generator.GestureTapAt(gfx::Point(40, 40)); RunAllPendingInMessageLoop(); test::EventGenerator scroll_generator(root_window(), repost_target.get()); scroll_generator.GestureScrollSequence( gfx::Point(80, 80), gfx::Point(100, 100), base::TimeDelta::FromMilliseconds(100), 3); RunAllPendingInMessageLoop(); int tap_down_count = 0; for (size_t i = 0; i < repost_event_recorder->events().size(); ++i) { if (repost_event_recorder->events()[i] == ui::ET_GESTURE_TAP_DOWN) ++tap_down_count; } // We expect two tap down events. One from the repost and the other one from // the scroll sequence posted above. // TODO(rbyers): Currently disabled - crbug.com/170987 EXPECT_EQ(1, tap_down_count); EXPECT_EQ(kExpectedTargetEvents, EventTypesToString(repost_event_recorder->events())); } class OnMouseExitDeletingEventFilter : public EventFilterRecorder { public: OnMouseExitDeletingEventFilter() : window_to_delete_(NULL) {} virtual ~OnMouseExitDeletingEventFilter() {} void set_window_to_delete(Window* window_to_delete) { window_to_delete_ = window_to_delete; } private: // Overridden from ui::EventHandler: virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { EventFilterRecorder::OnMouseEvent(event); if (window_to_delete_) { delete window_to_delete_; window_to_delete_ = NULL; } } Window* window_to_delete_; DISALLOW_COPY_AND_ASSIGN(OnMouseExitDeletingEventFilter); }; // Tests that RootWindow drops mouse-moved event that is supposed to be sent to // a child, but the child is destroyed because of the synthesized mouse-exit // event generated on the previous mouse_moved_handler_. TEST_F(WindowEventDispatcherTest, DeleteWindowDuringMouseMovedDispatch) { // Create window 1 and set its event filter. Window 1 will take ownership of // the event filter. scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); OnMouseExitDeletingEventFilter* w1_filter = new OnMouseExitDeletingEventFilter(); w1->SetEventFilter(w1_filter); w1->SetBounds(gfx::Rect(20, 20, 60, 60)); EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler()); test::EventGenerator generator(root_window(), w1.get()); // Move mouse over window 1 to set it as the |mouse_moved_handler_| for the // root window. generator.MoveMouseTo(51, 51); EXPECT_EQ(w1.get(), host()->dispatcher()->mouse_moved_handler()); // Create window 2 under the mouse cursor and stack it above window 1. Window* w2 = CreateNormalWindow(2, root_window(), NULL); w2->SetBounds(gfx::Rect(30, 30, 40, 40)); root_window()->StackChildAbove(w2, w1.get()); // Set window 2 as the window that is to be deleted when a mouse-exited event // happens on window 1. w1_filter->set_window_to_delete(w2); // Move mosue over window 2. This should generate a mouse-exited event for // window 1 resulting in deletion of window 2. The original mouse-moved event // that was targeted to window 2 should be dropped since window 2 is // destroyed. This test passes if no crash happens. generator.MoveMouseTo(52, 52); EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler()); // Check events received by window 1. EXPECT_EQ("MOUSE_ENTERED MOUSE_MOVED MOUSE_EXITED", EventTypesToString(w1_filter->events())); } namespace { // Used to track if OnWindowDestroying() is invoked and if there is a valid // RootWindow at such time. class ValidRootDuringDestructionWindowObserver : public aura::WindowObserver { public: ValidRootDuringDestructionWindowObserver(bool* got_destroying, bool* has_valid_root) : got_destroying_(got_destroying), has_valid_root_(has_valid_root) { } // WindowObserver: virtual void OnWindowDestroying(aura::Window* window) OVERRIDE { *got_destroying_ = true; *has_valid_root_ = (window->GetRootWindow() != NULL); } private: bool* got_destroying_; bool* has_valid_root_; DISALLOW_COPY_AND_ASSIGN(ValidRootDuringDestructionWindowObserver); }; } // namespace // Verifies GetRootWindow() from ~Window returns a valid root. TEST_F(WindowEventDispatcherTest, ValidRootDuringDestruction) { if (!PlatformSupportsMultipleHosts()) return; bool got_destroying = false; bool has_valid_root = false; ValidRootDuringDestructionWindowObserver observer(&got_destroying, &has_valid_root); { scoped_ptr<WindowTreeHost> host( WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100))); host->InitHost(); // Owned by WindowEventDispatcher. Window* w1 = CreateNormalWindow(1, host->window(), NULL); w1->AddObserver(&observer); } EXPECT_TRUE(got_destroying); EXPECT_TRUE(has_valid_root); } namespace { // See description above DontResetHeldEvent for details. class DontResetHeldEventWindowDelegate : public test::TestWindowDelegate { public: explicit DontResetHeldEventWindowDelegate(aura::Window* root) : root_(root), mouse_event_count_(0) {} virtual ~DontResetHeldEventWindowDelegate() {} int mouse_event_count() const { return mouse_event_count_; } // TestWindowDelegate: virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && mouse_event_count_++ == 0) { ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EF_SHIFT_DOWN, 0); root_->GetHost()->dispatcher()->RepostEvent(mouse_event); } } private: Window* root_; int mouse_event_count_; DISALLOW_COPY_AND_ASSIGN(DontResetHeldEventWindowDelegate); }; } // namespace // Verifies RootWindow doesn't reset |RootWindow::held_repostable_event_| after // dispatching. This is done by using DontResetHeldEventWindowDelegate, which // tracks the number of events with ui::EF_SHIFT_DOWN set (all reposted events // have EF_SHIFT_DOWN). When the first event is seen RepostEvent() is used to // schedule another reposted event. TEST_F(WindowEventDispatcherTest, DontResetHeldEvent) { DontResetHeldEventWindowDelegate delegate(root_window()); scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate)); w1->SetBounds(gfx::Rect(0, 0, 40, 40)); ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EF_SHIFT_DOWN, 0); root_window()->GetHost()->dispatcher()->RepostEvent(pressed); ui::MouseEvent pressed2(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10), gfx::Point(10, 10), 0, 0); // Dispatch an event to flush event scheduled by way of RepostEvent(). DispatchEventUsingWindowDispatcher(&pressed2); // Delegate should have seen reposted event (identified by way of // EF_SHIFT_DOWN). Dispatch another event to flush the second // RepostedEvent(). EXPECT_EQ(1, delegate.mouse_event_count()); DispatchEventUsingWindowDispatcher(&pressed2); EXPECT_EQ(2, delegate.mouse_event_count()); } namespace { // See description above DeleteHostFromHeldMouseEvent for details. class DeleteHostFromHeldMouseEventDelegate : public test::TestWindowDelegate { public: explicit DeleteHostFromHeldMouseEventDelegate(WindowTreeHost* host) : host_(host), got_mouse_event_(false), got_destroy_(false) { } virtual ~DeleteHostFromHeldMouseEventDelegate() {} bool got_mouse_event() const { return got_mouse_event_; } bool got_destroy() const { return got_destroy_; } // TestWindowDelegate: virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { if ((event->flags() & ui::EF_SHIFT_DOWN) != 0) { got_mouse_event_ = true; delete host_; } } virtual void OnWindowDestroyed(Window* window) OVERRIDE { got_destroy_ = true; } private: WindowTreeHost* host_; bool got_mouse_event_; bool got_destroy_; DISALLOW_COPY_AND_ASSIGN(DeleteHostFromHeldMouseEventDelegate); }; } // namespace // Verifies if a WindowTreeHost is deleted from dispatching a held mouse event // we don't crash. TEST_F(WindowEventDispatcherTest, DeleteHostFromHeldMouseEvent) { if (!PlatformSupportsMultipleHosts()) return; // Should be deleted by |delegate|. WindowTreeHost* h2 = WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100)); h2->InitHost(); DeleteHostFromHeldMouseEventDelegate delegate(h2); // Owned by |h2|. Window* w1 = CreateNormalWindow(1, h2->window(), &delegate); w1->SetBounds(gfx::Rect(0, 0, 40, 40)); ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EF_SHIFT_DOWN, 0); h2->dispatcher()->RepostEvent(pressed); // RunAllPendingInMessageLoop() to make sure the |pressed| is run. RunAllPendingInMessageLoop(); EXPECT_TRUE(delegate.got_mouse_event()); EXPECT_TRUE(delegate.got_destroy()); } TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveTouches) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); // passes ownership test::TestWindowDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); gfx::Point position1 = root_window()->bounds().origin(); ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position1, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&press); EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN", EventTypesToString(filter->GetAndResetEvents())); window->Hide(); EXPECT_EQ("TOUCH_CANCELLED GESTURE_TAP_CANCEL GESTURE_END", EventTypesToString(filter->events())); } TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveGestures) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); // passes ownership test::TestWindowDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); gfx::Point position1 = root_window()->bounds().origin(); gfx::Point position2 = root_window()->bounds().CenterPoint(); ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position1, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&press); ui::TouchEvent move(ui::ET_TOUCH_MOVED, position2, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&move); ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, position1, 1, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&press2); EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED " "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE " "TOUCH_PRESSED GESTURE_BEGIN GESTURE_PINCH_BEGIN", EventTypesToString(filter->GetAndResetEvents())); window->Hide(); EXPECT_EQ("TOUCH_CANCELLED GESTURE_PINCH_END GESTURE_END TOUCH_CANCELLED " "GESTURE_SCROLL_END GESTURE_END", EventTypesToString(filter->events())); } // Places two windows side by side. Presses down on one window, and starts a // scroll. Sets capture on the other window and ensures that the "ending" events // aren't sent to the window which gained capture. TEST_F(WindowEventDispatcherTest, EndingEventDoesntRetarget) { scoped_ptr<Window> window1(CreateNormalWindow(1, root_window(), NULL)); window1->SetBounds(gfx::Rect(0, 0, 40, 40)); scoped_ptr<Window> window2(CreateNormalWindow(2, root_window(), NULL)); window2->SetBounds(gfx::Rect(40, 0, 40, 40)); EventFilterRecorder* filter1 = new EventFilterRecorder(); window1->SetEventFilter(filter1); // passes ownership EventFilterRecorder* filter2 = new EventFilterRecorder(); window2->SetEventFilter(filter2); // passes ownership gfx::Point position = window1->bounds().origin(); ui::TouchEvent press(ui::ET_TOUCH_PRESSED, position, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&press); gfx::Point position2 = window1->bounds().CenterPoint(); ui::TouchEvent move(ui::ET_TOUCH_MOVED, position2, 0, base::TimeDelta()); DispatchEventUsingWindowDispatcher(&move); window2->SetCapture(); EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED " "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE " "TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END", EventTypesToString(filter1->events())); EXPECT_TRUE(filter2->events().empty()); } namespace { // This class creates and manages a window which is destroyed as soon as // capture is lost. This is the case for the drag and drop capture window. class CaptureWindowTracker : public test::TestWindowDelegate { public: CaptureWindowTracker() {} virtual ~CaptureWindowTracker() {} void CreateCaptureWindow(aura::Window* root_window) { capture_window_.reset(test::CreateTestWindowWithDelegate( this, -1234, gfx::Rect(20, 20, 20, 20), root_window)); capture_window_->SetCapture(); } void reset() { capture_window_.reset(); } virtual void OnCaptureLost() OVERRIDE { capture_window_.reset(); } virtual void OnWindowDestroyed(Window* window) OVERRIDE { TestWindowDelegate::OnWindowDestroyed(window); capture_window_.reset(); } aura::Window* capture_window() { return capture_window_.get(); } private: scoped_ptr<aura::Window> capture_window_; DISALLOW_COPY_AND_ASSIGN(CaptureWindowTracker); }; } // Verifies handling loss of capture by the capture window being hidden. TEST_F(WindowEventDispatcherTest, CaptureWindowHidden) { CaptureWindowTracker capture_window_tracker; capture_window_tracker.CreateCaptureWindow(root_window()); capture_window_tracker.capture_window()->Hide(); EXPECT_EQ(NULL, capture_window_tracker.capture_window()); } // Verifies handling loss of capture by the capture window being destroyed. TEST_F(WindowEventDispatcherTest, CaptureWindowDestroyed) { CaptureWindowTracker capture_window_tracker; capture_window_tracker.CreateCaptureWindow(root_window()); capture_window_tracker.reset(); EXPECT_EQ(NULL, capture_window_tracker.capture_window()); } class ExitMessageLoopOnMousePress : public ui::test::TestEventHandler { public: ExitMessageLoopOnMousePress() {} virtual ~ExitMessageLoopOnMousePress() {} protected: virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { ui::test::TestEventHandler::OnMouseEvent(event); if (event->type() == ui::ET_MOUSE_PRESSED) base::MessageLoopForUI::current()->Quit(); } private: DISALLOW_COPY_AND_ASSIGN(ExitMessageLoopOnMousePress); }; class WindowEventDispatcherTestWithMessageLoop : public WindowEventDispatcherTest { public: WindowEventDispatcherTestWithMessageLoop() {} virtual ~WindowEventDispatcherTestWithMessageLoop() {} void RunTest() { // Reset any event the window may have received when bringing up the window // (e.g. mouse-move events if the mouse cursor is over the window). handler_.Reset(); // Start a nested message-loop, post an event to be dispatched, and then // terminate the message-loop. When the message-loop unwinds and gets back, // the reposted event should not have fired. scoped_ptr<ui::MouseEvent> mouse(new ui::MouseEvent(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10), gfx::Point(10, 10), ui::EF_NONE, ui::EF_NONE)); message_loop()->PostTask( FROM_HERE, base::Bind(&WindowEventDispatcherTestWithMessageLoop::RepostEventHelper, host()->dispatcher(), base::Passed(&mouse))); message_loop()->PostTask(FROM_HERE, message_loop()->QuitClosure()); base::MessageLoop::ScopedNestableTaskAllower allow(message_loop()); base::RunLoop loop; loop.Run(); EXPECT_EQ(0, handler_.num_mouse_events()); // Let the current message-loop run. The event-handler will terminate the // message-loop when it receives the reposted event. } base::MessageLoop* message_loop() { return base::MessageLoopForUI::current(); } protected: virtual void SetUp() OVERRIDE { WindowEventDispatcherTest::SetUp(); window_.reset(CreateNormalWindow(1, root_window(), NULL)); window_->AddPreTargetHandler(&handler_); } virtual void TearDown() OVERRIDE { window_.reset(); WindowEventDispatcherTest::TearDown(); } private: // Used to avoid a copying |event| when binding to a closure. static void RepostEventHelper(WindowEventDispatcher* dispatcher, scoped_ptr<ui::MouseEvent> event) { dispatcher->RepostEvent(*event); } scoped_ptr<Window> window_; ExitMessageLoopOnMousePress handler_; DISALLOW_COPY_AND_ASSIGN(WindowEventDispatcherTestWithMessageLoop); }; TEST_F(WindowEventDispatcherTestWithMessageLoop, EventRepostedInNonNestedLoop) { CHECK(!message_loop()->is_running()); // Perform the test in a callback, so that it runs after the message-loop // starts. message_loop()->PostTask( FROM_HERE, base::Bind( &WindowEventDispatcherTestWithMessageLoop::RunTest, base::Unretained(this))); message_loop()->Run(); } class WindowEventDispatcherTestInHighDPI : public WindowEventDispatcherTest { public: WindowEventDispatcherTestInHighDPI() {} virtual ~WindowEventDispatcherTestInHighDPI() {} protected: virtual void SetUp() OVERRIDE { WindowEventDispatcherTest::SetUp(); test_screen()->SetDeviceScaleFactor(2.f); } }; TEST_F(WindowEventDispatcherTestInHighDPI, EventLocationTransform) { test::TestWindowDelegate delegate; scoped_ptr<aura::Window> child(test::CreateTestWindowWithDelegate(&delegate, 1234, gfx::Rect(20, 20, 100, 100), root_window())); child->Show(); ui::test::TestEventHandler handler_child; ui::test::TestEventHandler handler_root; root_window()->AddPreTargetHandler(&handler_root); child->AddPreTargetHandler(&handler_child); { ui::MouseEvent move(ui::ET_MOUSE_MOVED, gfx::Point(30, 30), gfx::Point(30, 30), ui::EF_NONE, ui::EF_NONE); DispatchEventUsingWindowDispatcher(&move); EXPECT_EQ(0, handler_child.num_mouse_events()); EXPECT_EQ(1, handler_root.num_mouse_events()); } { ui::MouseEvent move(ui::ET_MOUSE_MOVED, gfx::Point(50, 50), gfx::Point(50, 50), ui::EF_NONE, ui::EF_NONE); DispatchEventUsingWindowDispatcher(&move); // The child receives an ENTER, and a MOVED event. EXPECT_EQ(2, handler_child.num_mouse_events()); // The root receives both the ENTER and the MOVED events dispatched to // |child|, as well as an EXIT event. EXPECT_EQ(3, handler_root.num_mouse_events()); } child->RemovePreTargetHandler(&handler_child); root_window()->RemovePreTargetHandler(&handler_root); } TEST_F(WindowEventDispatcherTestInHighDPI, TouchMovesHeldOnScroll) { EventFilterRecorder* filter = new EventFilterRecorder; root_window()->SetEventFilter(filter); test::TestWindowDelegate delegate; HoldPointerOnScrollHandler handler(host()->dispatcher(), filter); scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); window->AddPreTargetHandler(&handler); test::EventGenerator generator(root_window()); generator.GestureScrollSequence( gfx::Point(120, 120), gfx::Point(20, 120), base::TimeDelta::FromMilliseconds(100), 25); // |handler| will have reset |filter| and started holding the touch-move // events when scrolling started. At the end of the scroll (i.e. upon // touch-release), the held touch-move event will have been dispatched first, // along with the subsequent events (i.e. touch-release, scroll-end, and // gesture-end). const EventFilterRecorder::Events& events = filter->events(); EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_SCROLL_END GESTURE_END", EventTypesToString(events)); ASSERT_EQ(2u, filter->touch_locations().size()); EXPECT_EQ(gfx::Point(-40, 10).ToString(), filter->touch_locations()[0].ToString()); EXPECT_EQ(gfx::Point(-40, 10).ToString(), filter->touch_locations()[1].ToString()); } class SelfDestructDelegate : public test::TestWindowDelegate { public: SelfDestructDelegate() {} virtual ~SelfDestructDelegate() {} virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { window_.reset(); } void set_window(scoped_ptr<aura::Window> window) { window_ = window.Pass(); } bool has_window() const { return !!window_.get(); } private: scoped_ptr<aura::Window> window_; DISALLOW_COPY_AND_ASSIGN(SelfDestructDelegate); }; TEST_F(WindowEventDispatcherTest, SynthesizedLocatedEvent) { test::EventGenerator generator(root_window()); generator.MoveMouseTo(10, 10); EXPECT_EQ("10,10", Env::GetInstance()->last_mouse_location().ToString()); // Synthesized event should not update the mouse location. ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(), ui::EF_IS_SYNTHESIZED, 0); generator.Dispatch(&mouseev); EXPECT_EQ("10,10", Env::GetInstance()->last_mouse_location().ToString()); generator.MoveMouseTo(0, 0); EXPECT_EQ("0,0", Env::GetInstance()->last_mouse_location().ToString()); // Make sure the location gets updated when a syntheiszed enter // event destroyed the window. SelfDestructDelegate delegate; scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); delegate.set_window(window.Pass()); EXPECT_TRUE(delegate.has_window()); generator.MoveMouseTo(100, 100); EXPECT_FALSE(delegate.has_window()); EXPECT_EQ("100,100", Env::GetInstance()->last_mouse_location().ToString()); } class StaticFocusClient : public client::FocusClient { public: explicit StaticFocusClient(Window* focused) : focused_(focused) {} virtual ~StaticFocusClient() {} private: // client::FocusClient: virtual void AddObserver(client::FocusChangeObserver* observer) OVERRIDE {} virtual void RemoveObserver(client::FocusChangeObserver* observer) OVERRIDE {} virtual void FocusWindow(Window* window) OVERRIDE {} virtual void ResetFocusWithinActiveWindow(Window* window) OVERRIDE {} virtual Window* GetFocusedWindow() OVERRIDE { return focused_; } Window* focused_; DISALLOW_COPY_AND_ASSIGN(StaticFocusClient); }; // Tests that host-cancel-mode event can be dispatched to a dispatcher safely // when the focused window does not live in the dispatcher's tree. TEST_F(WindowEventDispatcherTest, HostCancelModeWithFocusedWindowOutside) { test::TestWindowDelegate delegate; scoped_ptr<Window> focused(CreateTestWindowWithDelegate(&delegate, 123, gfx::Rect(20, 30, 100, 50), NULL)); StaticFocusClient focus_client(focused.get()); client::SetFocusClient(root_window(), &focus_client); EXPECT_FALSE(root_window()->Contains(focused.get())); EXPECT_EQ(focused.get(), client::GetFocusClient(root_window())->GetFocusedWindow()); host()->dispatcher()->DispatchCancelModeEvent(); EXPECT_EQ(focused.get(), client::GetFocusClient(root_window())->GetFocusedWindow()); } // Dispatches a mouse-move event to |target| when it receives a mouse-move // event. class DispatchEventHandler : public ui::EventHandler { public: explicit DispatchEventHandler(Window* target) : target_(target), dispatched_(false) {} virtual ~DispatchEventHandler() {} bool dispatched() const { return dispatched_; } private: // ui::EventHandler: virtual void OnMouseEvent(ui::MouseEvent* mouse) OVERRIDE { if (mouse->type() == ui::ET_MOUSE_MOVED) { ui::MouseEvent move(ui::ET_MOUSE_MOVED, target_->bounds().CenterPoint(), target_->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE); ui::EventDispatchDetails details = target_->GetHost()->dispatcher()->OnEventFromSource(&move); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_FALSE(details.target_destroyed); EXPECT_EQ(target_, move.target()); dispatched_ = true; } ui::EventHandler::OnMouseEvent(mouse); } Window* target_; bool dispatched_; DISALLOW_COPY_AND_ASSIGN(DispatchEventHandler); }; // Moves |window| to |root_window| when it receives a mouse-move event. class MoveWindowHandler : public ui::EventHandler { public: MoveWindowHandler(Window* window, Window* root_window) : window_to_move_(window), root_window_to_move_to_(root_window) {} virtual ~MoveWindowHandler() {} private: // ui::EventHandler: virtual void OnMouseEvent(ui::MouseEvent* mouse) OVERRIDE { if (mouse->type() == ui::ET_MOUSE_MOVED) { root_window_to_move_to_->AddChild(window_to_move_); } ui::EventHandler::OnMouseEvent(mouse); } Window* window_to_move_; Window* root_window_to_move_to_; DISALLOW_COPY_AND_ASSIGN(MoveWindowHandler); }; // Tests that nested event dispatch works correctly if the target of the older // event being dispatched is moved to a different dispatcher in response to an // event in the inner loop. TEST_F(WindowEventDispatcherTest, NestedEventDispatchTargetMoved) { if (!PlatformSupportsMultipleHosts()) return; scoped_ptr<WindowTreeHost> second_host( WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50))); second_host->InitHost(); Window* second_root = second_host->window(); // Create two windows parented to |root_window()|. test::TestWindowDelegate delegate; scoped_ptr<Window> first(CreateTestWindowWithDelegate(&delegate, 123, gfx::Rect(20, 10, 10, 20), root_window())); scoped_ptr<Window> second(CreateTestWindowWithDelegate(&delegate, 234, gfx::Rect(40, 10, 50, 20), root_window())); // Setup a handler on |first| so that it dispatches an event to |second| when // |first| receives an event. DispatchEventHandler dispatch_event(second.get()); first->AddPreTargetHandler(&dispatch_event); // Setup a handler on |second| so that it moves |first| into |second_root| // when |second| receives an event. MoveWindowHandler move_window(first.get(), second_root); second->AddPreTargetHandler(&move_window); // Some sanity checks: |first| is inside |root_window()|'s tree. EXPECT_EQ(root_window(), first->GetRootWindow()); // The two root windows are different. EXPECT_NE(root_window(), second_root); // Dispatch an event to |first|. ui::MouseEvent move(ui::ET_MOUSE_MOVED, first->bounds().CenterPoint(), first->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE); ui::EventDispatchDetails details = host()->dispatcher()->OnEventFromSource(&move); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_TRUE(details.target_destroyed); EXPECT_EQ(first.get(), move.target()); EXPECT_TRUE(dispatch_event.dispatched()); EXPECT_EQ(second_root, first->GetRootWindow()); first->RemovePreTargetHandler(&dispatch_event); second->RemovePreTargetHandler(&move_window); } class AlwaysMouseDownInputStateLookup : public InputStateLookup { public: AlwaysMouseDownInputStateLookup() {} virtual ~AlwaysMouseDownInputStateLookup() {} private: // InputStateLookup: virtual bool IsMouseButtonDown() const OVERRIDE { return true; } DISALLOW_COPY_AND_ASSIGN(AlwaysMouseDownInputStateLookup); }; TEST_F(WindowEventDispatcherTest, CursorVisibilityChangedWhileCaptureWindowInAnotherDispatcher) { if (!PlatformSupportsMultipleHosts()) return; test::EventCountDelegate delegate; scoped_ptr<Window> window(CreateTestWindowWithDelegate(&delegate, 123, gfx::Rect(20, 10, 10, 20), root_window())); window->Show(); scoped_ptr<WindowTreeHost> second_host( WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50))); second_host->InitHost(); WindowEventDispatcher* second_dispatcher = second_host->dispatcher(); // Install an InputStateLookup on the Env that always claims that a // mouse-button is down. test::EnvTestHelper(Env::GetInstance()).SetInputStateLookup( scoped_ptr<InputStateLookup>(new AlwaysMouseDownInputStateLookup())); window->SetCapture(); // Because the mouse button is down, setting the capture on |window| will set // it as the mouse-move handler for |root_window()|. EXPECT_EQ(window.get(), host()->dispatcher()->mouse_moved_handler()); // This does not set |window| as the mouse-move handler for the second // dispatcher. EXPECT_EQ(NULL, second_dispatcher->mouse_moved_handler()); // However, some capture-client updates the capture in each root-window on a // capture. Emulate that here. Because of this, the second dispatcher also has // |window| as the mouse-move handler. client::CaptureDelegate* second_capture_delegate = second_dispatcher; second_capture_delegate->UpdateCapture(NULL, window.get()); EXPECT_EQ(window.get(), second_dispatcher->mouse_moved_handler()); // Reset the mouse-event counts for |window|. delegate.GetMouseMotionCountsAndReset(); // Notify both hosts that the cursor is now hidden. This should send a single // mouse-exit event to |window|. host()->OnCursorVisibilityChanged(false); second_host->OnCursorVisibilityChanged(false); EXPECT_EQ("0 0 1", delegate.GetMouseMotionCountsAndReset()); } } // namespace aura
bsd-3-clause
Rolinh/tweetmining
src/features/user_mentions_count_feature.py
338
from features import abstract_feature as af class UserMentionsCountFeature(af.AbstractFeature): def __repr__(self): return "<UserMentionsCountFeature>" def __str__(self): return "User Mentions Count Feature" def extract(self, tweet): return "user_mentions_count", len(tweet.entities.user_mentions)
bsd-3-clause
vercas/vLogs
vLogs/Objects/Message Payload.cs
1954
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace vLogs.Objects { using Utilities; /// <summary> /// A payload containing a described exception. /// </summary> public class MessagePayload : IPayload { #region IPayload Members /// <summary> /// Gets the type of this payload. /// </summary> public PayloadTypes Type { get { return PayloadTypes.Exception; } } #endregion /// <summary> /// Gets the type of message of the payload. /// </summary> public MessageType MessageType { get; internal set; } /// <summary> /// Gets the message of the payload. /// </summary> public String Message { get; internal set; } /// <summary> /// Initializes a new instance of the <see cref="vLogs.Objects.MessagePayload"/> class with the specified message and type. /// </summary> /// <param name="type">The type of message.</param> /// <param name="message"></param> public MessagePayload(MessageType type, string message) { if (message == null) throw new ArgumentNullException("message"); this.MessageType = type; this.Message = message; } } /// <summary> /// Possible logging message types. /// </summary> public enum MessageType : byte { /// <summary> /// Message is for informative purposes. /// </summary> Information = 0, /// <summary> /// Message is for warning purposes. /// </summary> Warning = 1, /// <summary> /// Message represents an error. /// </summary> Error = 2, } }
bsd-3-clause
trsouz/service-url
test/index.js
2341
var chai = require('chai'), expect = chai.expect, should = chai.should, Service = require('..'), exampleUrl = 'http://posttestserver.com/:path:format', exampleDefaultParams = { path: 'post', format: '.php', dir: 'nodejs/service-url/' }, exampleActions = { 'data': { method: 'GET', params: { path: 'data', format: null, dir: 'data/' } }, 'login': { method: 'POST', params: { path: 'login', username: '@user', password: '@pass' } }, 'get': { method: 'GET' }, 'save': { method: 'POST', params: { action: 'save.do' } }, 'remove': { method: 'POST', params: { action: 'delete.do' } }, 'delete': { method: 'POST', params: { action: 'delete.do' } }, 'query': { method: 'GET', params: { action: 'listByFilter.do', start: 0, limit: 15 } } }, service = new Service(); route = service.resource(exampleUrl, exampleDefaultParams, exampleActions); describe('Basic of module', function () { it('module should be a function', function (done) { expect(Service).to.be.a('function'); done(); }); it('new instance of module return object', function (done) { expect(new Service()).to.be.a('object'); done(); }); it('new instance of module has function resource', function (done) { expect(new Service()).to.have.property('resource').and.to.be.a('function'); done(); }); }); describe('Methods', function () { it('getConfig', function (done) { var config = route.getConfig('get'); expect(config).to.contain.keys('url', 'params'); done(); }); it('getUrl', function (done) { expect(route.getUrl('get')).to.equal('http://posttestserver.com/post.php?dir=nodejs%2Fservice-url%2F'); done(); }); }); describe('Request tests', function () { it('basic test get', function (done) { route.get().then(function(data){ done(); }, function(data){ done(); }); }); it('basic test data', function (done) { route.data().then(function(result){ expect(result.data).to.contain('<a href="2014/">2014/</a>'); done(); }, function(result){ done(); }); }); });
bsd-3-clause
gsouf/UForm
src/UForm/Form/Element/Container.php
4172
<?php namespace UForm\Form\Element; use UForm\Filtering\FilterChain; use UForm\Form\Element; /** * Element that intends to contain other elements. * It only aims to be a common parent for Group and Collection * * In some ways it is opposed to the Primary element that cant contain other elements * * @see UForm\Form\Element\Container\Group * @see UForm\Form\Element\Container\Collection * @see UForm\Form\Element\Container\Primary * @semanticType container */ abstract class Container extends Element { public function __construct($name = null) { parent::__construct($name); $this->addSemanticType('container'); } /** * Get an element by its name * @param $name * @return Element */ abstract public function getElement($name); /** * Get the elements contained in this container. * Values are required because a collection requires values to be generated * @param mixed $values used for the "collection" element that is rendered according to a value set * @return Element[] the elements contained in this container */ abstract public function getElements($values = null); /** * Get an element located directly in this element. There is an exception for unnamed elements : * we will search inside directElements of unnamed elements * @param string $name name of the element to get * @param mixed $values used for the "collection" element that is rendered according to a value set * @return null|Element|Container the element found or null if the element does not exist */ public function getDirectElement($name, $values = null) { foreach ($this->getElements($values) as $elm) { if ($name == $elm->getName()) { return $elm; } elseif (!$elm->getName() && $elm instanceof Container) { /* @var $elm \UForm\Form\Element\Container */ $element = $elm->getDirectElement($name); if ($element) { return $element; } } } return null; } /** * Get direct elements with the given name * @param $name * @param null $values * @return Element[] */ public function getDirectElements($name, $values = null) { $elements = []; foreach ($this->getElements($values) as $elm) { if ($name == $elm->getName()) { $elements[] = $elm; } elseif (!$elm->getName() && $elm instanceof Container) { /* @var $elm \UForm\Form\Element\Container */ $elements += $elm->getDirectElements($name, $values); } } return $elements; } /** * check if this element contains at least one element that is an instance of the given type * @param string $className the name of the class to search for * @return bool true if the instance was found */ public function hasDirectElementInstance($className) { foreach ($this->getElements() as $el) { if (is_a($el, $className)) { return true; } } return false; } /** * Check if this element contains at least one element with the given semantic type * @param string $type the type to search for * @return bool true if the semantic type was found */ public function hasDirectElementSemanticType($type) { foreach ($this->getElements() as $el) { if ($el->hasSemanticType($type)) { return true; } } return false; } public function prepareFilterChain(FilterChain $filterChain) { parent::prepareFilterChain($filterChain); foreach ($this->getElements() as $v) { $v->prepareFilterChain($filterChain); } } /** * @inheritdoc */ public function setParent(Container $parent) { $r = parent::setParent($parent); foreach ($this->getElements() as $element) { $element->refreshParent(); } return $r; } }
bsd-3-clause
dials/dials
algorithms/integration/kapton_2019_correction.py
32368
from __future__ import annotations import logging import math import sys import numpy as np from scitbx.matrix import col from dials.algorithms.integration.kapton_correction import get_absorption_correction from dials.algorithms.shoebox import MaskCode from dials.array_family import flex logging.basicConfig() logger = logging.getLogger(__name__) class KaptonTape_2019: """Class for defining Kapton tape using dxtbx models and finding the path through the tape traversed by s1 vector""" def __init__( self, height_mm, thickness_mm, half_width_mm, rotation_angle_deg, wavelength_ang=None, ): self.height_mm = h = height_mm # plugin controlled self.thickness_mm = t = thickness_mm # plugin controlled self.half_width_mm = w = half_width_mm # plugin controlled self.tape_depth_mm = a = half_width_mm * 20.0 # Big number in mm self.angle_rad = rotation_angle_deg * math.pi / 180.0 # plugin controlled self.wavelength_ang = wavelength_ang self.num_pixels = 5000 # number of pixels to put in fictitious kapton faces # Now set up the kapton physical model using dxtbx detector objects # # determine absorption coeff (mm-1) through kapton for a given X-ray energy G = get_absorption_correction() attenuation_length_mm = G(self.wavelength_ang) self.abs_coeff = 1 / attenuation_length_mm def create_kapton_face(ori, fast, slow, image_size, pixel_size, name): """Create a face of the kapton as a dxtbx detector object""" from dxtbx.model import Detector d = Detector() p = d.add_panel() p.set_local_frame(fast.elems, slow.elems, ori.elems) p.set_pixel_size((pixel_size, pixel_size)) p.set_image_size(image_size) p.set_trusted_range((-1, 2e6)) p.set_name(f"KAPTON_{name}") return d # Set up the bounding box of the kapton rA = col((t / 2, a / 2, -w)) rB = col((t / 2, a / 2, w)) rC = col((t / 2, -a / 2, w)) rD = col((t / 2, -a / 2, -w)) rE = col((-t / 2, a / 2, -w)) rF = col((-t / 2, a / 2, w)) rG = col((-t / 2, -a / 2, w)) rH = col((-t / 2, -a / 2, -w)) # Now add a rotation # rotation about z-axis rot_axis = col((0, 0, 1)) rot_mat = rot_axis.axis_and_angle_as_r3_rotation_matrix( self.angle_rad, deg=False ) rA = rot_mat * rA rB = rot_mat * rB rC = rot_mat * rC rD = rot_mat * rD rE = rot_mat * rE rF = rot_mat * rF rG = rot_mat * rG rH = rot_mat * rH # Now add an offset to all the points in the direction normal to the ABCD plane rAB = rA - rB rCB = rC - rB # Get normal in the direction of the drop drop_normal = rCB.cross(rAB).normalize() offset = -(h + t / 2) * drop_normal rA = rA + offset rB = rB + offset rC = rC + offset rD = rD + offset rE = rE + offset rF = rF + offset rG = rG + offset rH = rH + offset # Store these edge points if needed later self.edge_points = [rA, rB, rC, rD, rE, rF, rG, rH] # Now set up the 6 faces faces = [] px_off = 0 fast = (rA - rB).normalize() slow = (rC - rB).normalize() pixel_size = self.half_width_mm * 2.0 / self.num_pixels image_size = ( self.num_pixels + px_off, int(self.tape_depth_mm / pixel_size) + px_off, ) # Face YZ0 ori = rB faces.append(create_kapton_face(ori, fast, slow, image_size, pixel_size, "yz0")) # face YZ1 ori = rF faces.append(create_kapton_face(ori, fast, slow, image_size, pixel_size, "yz1")) # fast = (rB - rF).normalize() slow = (rG - rF).normalize() pixel_size = self.thickness_mm / self.num_pixels image_size = ( self.num_pixels + px_off, int(self.tape_depth_mm / pixel_size) + px_off, ) # Face XY0 ori = rF faces.append(create_kapton_face(ori, fast, slow, image_size, pixel_size, "xy0")) # face XY1 ori = rE faces.append(create_kapton_face(ori, fast, slow, image_size, pixel_size, "xy1")) # fast = (rA - rE).normalize() slow = (rF - rE).normalize() pixel_size = self.thickness_mm / self.num_pixels image_size = ( self.num_pixels + px_off, int(self.half_width_mm * 2.0 / pixel_size) + px_off, ) # Face XZ0 ori = rE faces.append(create_kapton_face(ori, fast, slow, image_size, pixel_size, "xz0")) # face XY1 ori = rH faces.append(create_kapton_face(ori, fast, slow, image_size, pixel_size, "xz1")) # self.faces = faces def get_kapton_path_mm(self, s1): """Get kapton path length traversed by an s1 vecto. If no kapton intersection or just touches the edge, then None is returned""" intersection_points = [] # determine path length through kapton tape for face in self.faces: try: px = [int(p) for p in face[0].get_ray_intersection_px(s1)] # faces are single panel anyway if ( px[0] < 0 or px[1] < 0 or px[0] > face[0].get_image_size()[0] or px[1] > face[0].get_image_size()[1] ): continue intersection_points.append( face[0].get_lab_coord(face[0].get_ray_intersection(s1)) ) # faces are single panel anyway except RuntimeError: pass if not intersection_points: return 0.0 if len(intersection_points) == 1: logger.warning( "Ray not intersecting 2 faces.Either s1 vector does not intersect kapton or just touches edge of kapton tape \ No correction is needed for those cases." ) return 0.0 n_intersection_points = len(intersection_points) kapton_path_mm = [] for ii in range(n_intersection_points - 1): for jj in range(ii + 1, n_intersection_points): kapton_path_mm.append( ( col(intersection_points[ii]) - col(intersection_points[jj]) ).length() ) return max(kapton_path_mm) def abs_correction(self, s1): """Compute absorption correction using beers law. Takes in a tuple for a single s1 vector and does absorption correction""" kapton_path_mm = self.get_kapton_path_mm(s1) if kapton_path_mm is not None: absorption_correction = 1 / math.exp( -self.abs_coeff * kapton_path_mm ) # unitless, >=1 return absorption_correction def abs_correction_flex(self, s1_flex): """Compute the absorption correction using beers law. Takes in a flex array of s1 vectors, determines path lengths for each and then determines absorption correction for each s1 vector""" kapton_faces = self.faces from dials.algorithms.integration import get_kapton_path_cpp # new style, much faster # Note, the last two faces should never be hit by a photon so don't need to check them kapton_path_mm = get_kapton_path_cpp(kapton_faces[:4], s1_flex) # old style, really slow # for s1 in s1_flex: # kapton_path_mm.append(self.get_kapton_path_mm(s1)) # determine absorption correction if kapton_path_mm is not None: absorption_correction = 1 / flex.exp( -self.abs_coeff * kapton_path_mm ) # unitless, >=1 return absorption_correction def distance_of_point_from_line(self, r0, r1, r2): """Evaluates distance between point and a line between two points Note that implementation ignores z dimension""" x0, y0, z0 = r0 x1, y1, z1 = r1 x2, y2, z2 = r2 num = (y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1 denom = math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)) return abs(num) / denom def get_edge_distances(self, edges): dist_list = flex.double() dist_list_idx = [] n_edges = len(edges) for edge_1 in range(n_edges - 1): pt1 = col(edges[edge_1]) for edge_2 in range(edge_1 + 1, n_edges): pt2 = col(edges[edge_2]) distance = (pt1 - pt2).length() dist_list.append(distance) dist_list_idx.append((edge_1, edge_2)) return dist_list, dist_list_idx def abs_bounding_lines_in_mm(self, detector): """Return bounding lines of kapton""" def _check_int_edge_pts(int_edge_pts): """Function to ensure that the combination of int_edge_pts will not result in a kapton edge to be defined by 2 identical int_edge_pts. """ new_int_edge_pts = int_edge_pts.copy() if len(set(int_edge_pts)) == 4: return int_edge_pts elif len(set(int_edge_pts)) == 2: sys.exit( "Insuffient number of intersection points to define both Kapton edges" ) else: # Find different permuations of intersecting kapton edge points that won't # result in kapton_edges defined by identical points if ( int_edge_pts[0] == int_edge_pts[1] or int_edge_pts[2] == int_edge_pts[3] ): new_int_edge_pts[1] = int_edge_pts[3] new_int_edge_pts[3] = int_edge_pts[1] return new_int_edge_pts def _orient_det_edge_pts(det_edge_pts): """ Function to orient the detector edge points counterclockwise such that the first edge point index is in the upper left quadrant (i.e., -x, +y). This isn't explictly necessary but nevertheless useful b/c the function abs_bounding_lines_on_image always assumes that the detector edges used to help calculate the Kapton absorption max and edge are a parallel to the y-axis. This function enforces that a convention so that this assumption in the later logic will be true. """ assert len(det_edge_pts) == 4, "Detectors can only be defined by 4 points" n_edges = float(len(det_edge_pts)) # find center of detector x = [p[0] for p in det_edge_pts] y = [p[1] for p in det_edge_pts] z = [p[2] for p in det_edge_pts] center = [sum(x) / n_edges, sum(y) / n_edges, sum(z) / n_edges] # define reference vectors used to determine rel. orientation x_ref = [center[0] + 100, center[1], center[2]] y_ref = [center[0], center[1] + 100, center[2]] x_ref_vec = (col(x_ref) - col(center)).normalize() y_ref_vec = (col(y_ref) - col(center)).normalize() # determine orientation of each edge pt wrt x and y axis x_axis_angles = [] y_axis_angles = [] for edge in det_edge_pts: vec = (col(edge) - col(center)).normalize() x_axis_angles.append(np.degrees(np.arccos(vec.dot(x_ref_vec)))) y_axis_angles.append(np.degrees(np.arccos(vec.dot(y_ref_vec)))) x_axis_angles = [ (90.0 - xang) if xang > 90.0 else xang for xang in x_axis_angles ] y_axis_angles = [ (90.0 - yang) if yang > 90.0 else yang for yang in y_axis_angles ] # assign edge pt indices based on quadrant position starting in 4th quadrant (-x.-y) # proceeding counterclockwise edge_0 = np.where( (np.asarray(x_axis_angles) < 0) & (np.asarray(y_axis_angles) > 0) )[0][0] edge_1 = np.where( (np.asarray(x_axis_angles) < 0) & (np.asarray(y_axis_angles) < 0) )[0][0] edge_2 = np.where( (np.asarray(x_axis_angles) > 0) & (np.asarray(y_axis_angles) < 0) )[0][0] edge_3 = np.where( (np.asarray(x_axis_angles) > 0) & (np.asarray(y_axis_angles) > 0) )[0][0] return [ det_edge_pts[edge_0], det_edge_pts[edge_1], det_edge_pts[edge_2], det_edge_pts[edge_3], ] def _make_kapton_distance_vec( det_edge_pt1, det_edge_pt2, int_edge_pt1, int_edge_pt2 ): """ Function to create vectors that descibe the distance btw two points where rays from Kapton edges intersect with detector relative to detector edges """ dist_det_edge_x = det_edge_pt2[0] - det_edge_pt1[0] dist_det_edge_y = det_edge_pt2[1] - det_edge_pt1[1] mid_pt = [ det_edge_pt1[0] + dist_det_edge_x / 2, det_edge_pt1[1] + dist_det_edge_y / 2, ] kapton_int_pt1_vec = ( col([int_edge_pt1[0], int_edge_pt1[1]]) - col([mid_pt[0], mid_pt[1]]) ).normalize() kapton_int_pt2_vec = ( col([int_edge_pt2[0], int_edge_pt2[1]]) - col([mid_pt[0], mid_pt[1]]) ).normalize() return kapton_int_pt1_vec, kapton_int_pt2_vec # first get bounding directions from detector: detz = flex.mean(flex.double([panel.get_origin()[2] for panel in detector])) edges = [] for ii, panel in enumerate(detector): f_size, s_size = panel.get_image_size() for point in [(0, 0), (0, s_size), (f_size, 0), (f_size, s_size)]: x, y = panel.get_pixel_lab_coord(point)[0:2] edges.append((x, y, detz)) # Use the idea that the corners of the detector are end points of the diagonal and # will be top 2 max dimension among all end points dlist, dlist_idx = self.get_edge_distances(edges) sorted_idx = flex.sort_permutation(dlist, reverse=True) edge_pts = [ edges[dlist_idx[sorted_idx[0]][0]], edges[dlist_idx[sorted_idx[1]][0]], edges[dlist_idx[sorted_idx[0]][1]], edges[dlist_idx[sorted_idx[1]][1]], ] self.detector_edges = edge_pts edge_pts = _orient_det_edge_pts(edge_pts) # Now get the maximum extent of the intersection of the rays with the detector all_ints = [] kapton_path_list = [] for ii, edge_point in enumerate(self.edge_points): s1 = edge_point.normalize() kapton_path_mm = self.get_kapton_path_mm(s1) for panel in detector: try: x_int, y_int = panel.get_lab_coord(panel.get_ray_intersection(s1))[ 0:2 ] except RuntimeError: pass int_point = (x_int, y_int, detz) # Arbitrary tolerance of couple of pixels otherwise these points # were getting clustered together tolerance = min(panel.get_pixel_size()) * 2.0 if ( sum( (col(trial_pt) - col(int_point)).length() <= tolerance for trial_pt in all_ints ) == 0 ): all_ints.append(int_point) kapton_path_list.append(kapton_path_mm) # Use the idea that the extreme edges of the intersection points are end points # of the diagonal and will be the top 2 max dimension among all end points dlist, dlist_idx = self.get_edge_distances(all_ints) sorted_idx = flex.sort_permutation(dlist, reverse=True) int_edge_pts = [ all_ints[dlist_idx[sorted_idx[0]][0]], all_ints[dlist_idx[sorted_idx[1]][0]], all_ints[dlist_idx[sorted_idx[0]][1]], all_ints[dlist_idx[sorted_idx[1]][1]], ] int_edge_pts = _check_int_edge_pts(int_edge_pts) # Sort out the edge points and the int_edge_points which are on the same side kapton_edge_1 = (col(int_edge_pts[0]) - col(int_edge_pts[1])).normalize() kapton_edge_2 = (col(int_edge_pts[2]) - col(int_edge_pts[3])).normalize() # Make sure the edges of the detector and the kapton are in the same orientation # first for kapton edge 1 edge_idx = (0, 1, 2, 3) side_1 = (col(edge_pts[edge_idx[0]]) - col(edge_pts[edge_idx[1]])).normalize() side_2 = (col(edge_pts[edge_idx[2]]) - col(edge_pts[edge_idx[3]])).normalize() v1 = kapton_edge_1.dot(side_1) v2 = kapton_edge_2.dot(side_2) if v1 < 0.0: edge_idx = (edge_idx[1], edge_idx[0], edge_idx[2], edge_idx[3]) if v2 < 0.0: edge_idx = (edge_idx[0], edge_idx[1], edge_idx[3], edge_idx[2]) # Define two vectors that describe the positions of the top two intersecion edge pts # (intersection of the kapton rays with the detector) relative to the center of the # detector. These vectors will allow us to determine and assign which intersection # edge points are associated with the absorption max or edge (aka min) edge. kapton_int_pt1_vector, kapton_int_pt2_vector = _make_kapton_distance_vec( edge_pts[edge_idx[0]], edge_pts[edge_idx[3]], int_edge_pts[0], int_edge_pts[3], ) if kapton_int_pt1_vector[0] == kapton_int_pt2_vector[0]: # the same kapton int_pt was used to define a kapton edge twice # try another one kapton_int_pt1_vector, kapton_int_pt2_vector = _make_kapton_distance_vec( edge_pts[edge_idx[0]], edge_pts[edge_idx[3]], int_edge_pts[1], int_edge_pts[2], ) int_edge_idx = None # abs max edge is left of min edge if (kapton_int_pt1_vector[0] < 0) & (kapton_int_pt2_vector[0] > 0): int_edge_idx = [0, 1, 2, 3] # both edges are on the left side of det elif (kapton_int_pt1_vector[0] < 0) & (kapton_int_pt2_vector[0] < 0): # abs max edge to the left of min edge if kapton_int_pt1_vector[0] < kapton_int_pt2_vector[0]: int_edge_idx = [2, 3, 0, 1] # abs max edge to the right of min edge elif kapton_int_pt1_vector[0] > kapton_int_pt2_vector[0]: int_edge_idx = [0, 1, 2, 3] # both edges are on the right side of det elif (kapton_int_pt1_vector[0] > 0) & (kapton_int_pt2_vector[0] > 0): # abs max edge is to right of min edge if kapton_int_pt1_vector[0] > kapton_int_pt2_vector[0]: int_edge_idx = [2, 3, 0, 1] # abs max edge is the the left of min edge elif kapton_int_pt1_vector[0] < kapton_int_pt2_vector[0]: int_edge_idx = [0, 1, 2, 3] # abs max edge is right of min edge elif (kapton_int_pt1_vector[0] > 0) & (kapton_int_pt2_vector[0] < 0): int_edge_idx = [2, 3, 0, 1] pair_values = [ ( edge_pts[edge_idx[0]], edge_pts[edge_idx[1]], edge_pts[edge_idx[2]], edge_pts[edge_idx[3]], ), ( int_edge_pts[int_edge_idx[0]], int_edge_pts[int_edge_idx[1]], int_edge_pts[int_edge_idx[2]], int_edge_pts[int_edge_idx[3]], ), ] return pair_values def abs_bounding_lines_on_image(self, detector): pair_values = self.abs_bounding_lines_in_mm(detector) r0, r1, r2, r3 = pair_values[0] ra, rb, rc, rd = pair_values[1] # Get slope, intercept from 0-2 edge line and 1-3 edge line def get_line_equation(rA, rB): xA, yA, zA = rA xB, yB, zB = rB m = (yB - yA) / (xB - xA) c = yA - m * xA return (m, c) def get_line_intersection(m1, c1, m2, c2): x = (c2 - c1) / (m1 - m2) y = m1 * x + c1 return (x, y) m03, c03 = get_line_equation(r0, r3) m12, c12 = get_line_equation(r1, r2) # Get slope, intercept for a-b and c-d mab, cab = get_line_equation(ra, rb) mcd, ccd = get_line_equation(rc, rd) # Get intersection between 0-2 with a-b r03_ab = get_line_intersection(m03, c03, mab, cab) # Get line intersection between 1-3 and a-b r12_ab = get_line_intersection(m12, c12, mab, cab) # Get line intersection between 0-2 and c-d r03_cd = get_line_intersection(m03, c03, mcd, ccd) # Get line intersection between 1-3 and c-d r12_cd = get_line_intersection(m12, c12, mcd, ccd) # returns pairs of x,y return [ (r03_ab[0], r03_ab[1], r12_ab[0], r12_ab[1]), (r03_cd[0], r03_cd[1], r12_cd[0], r12_cd[1]), ] class image_kapton_correction: def __init__( self, panel_size_px=None, # pixel_size_mm=None, # detector_dist_mm=None, # wavelength_ang=None, reflections_sele=None, params=None, expt=None, refl=None, smart_sigmas=True, logger=None, ): self.panel_size_px = panel_size_px self.pixel_size_mm = pixel_size_mm self.detector_dist_mm = detector_dist_mm self.wavelength_ang = wavelength_ang self.reflections_sele = reflections_sele self.params = params self.expt = expt self.refl = refl self.smart_sigmas = smart_sigmas self.logger = logger self.extract_params() def extract_params(self): h = self.params.xtal_height_above_kapton_mm.value t = self.params.kapton_thickness_mm.value w = self.params.kapton_half_width_mm.value a = self.params.rotation_angle_deg.value self.kapton_params = (h, t, w, a) if self.smart_sigmas: sig_h = self.params.xtal_height_above_kapton_mm.sigma sig_t = self.params.kapton_thickness_mm.sigma sig_w = self.params.kapton_half_width_mm.sigma sig_a = self.params.rotation_angle_deg.sigma self.kapton_params_sigmas = (sig_h, sig_t, sig_w, sig_a) assert all( sig >= 0 for sig in self.kapton_params_sigmas ), "Kapton param sigmas must be non-negative" self.kapton_params_maxes = [ [ self.kapton_params[i] + self.kapton_params_sigmas[j] if j == i else self.kapton_params[i] for i in range(4) ] for j in range(4) ] self.kapton_params_mins = [ [ max(self.kapton_params[i] - self.kapton_params_sigmas[j], 0.001) if j == i else self.kapton_params[i] for i in range(3) ] + [a] for j in range(3) ] + [[self.kapton_params[i] for i in range(3)] + [a - sig_a]] def __call__(self, plot=False): def correction_and_within_spot_sigma(params_version, variance_within_spot=True): # instantiate Kapton absorption class here absorption = KaptonTape_2019( params_version[0], params_version[1], params_version[2], params_version[3], self.wavelength_ang, ) # *map(float, self.panel_size_px)) # detector = self.expt.detector absorption_corrections = flex.double() absorption_sigmas = ( flex.double() ) # std dev of corrections for pixels within a spot, default sigma if variance_within_spot: mask_code = MaskCode.Foreground | MaskCode.Valid for iref in range(len(self.reflections_sele)): kapton_correction_vector = flex.double() # foreground: integration mask shoebox = self.reflections_sele[iref]["shoebox"] foreground = ( (shoebox.mask.as_1d() & mask_code) == mask_code ).iselection() f_absolute, s_absolute, z_absolute = ( shoebox.coords().select(foreground).parts() ) panel_number = self.reflections_sele[iref]["panel"] lab_coords = detector[panel_number].get_lab_coord( detector[panel_number].pixel_to_millimeter( flex.vec2_double(f_absolute, s_absolute) ) ) s1 = lab_coords.each_normalize() # Real step right here kapton_correction_vector.extend(absorption.abs_correction_flex(s1)) # average_kapton_correction = flex.mean(kapton_correction_vector) absorption_corrections.append(average_kapton_correction) try: spot_px_stddev = flex.mean_and_variance( kapton_correction_vector ).unweighted_sample_standard_deviation() except Exception: assert ( len(kapton_correction_vector) == 1 ), "stddev could not be calculated" spot_px_stddev = 0 absorption_sigmas.append(spot_px_stddev) return absorption_corrections, absorption_sigmas else: s1_flex = self.reflections_sele["s1"].each_normalize() absorption_corrections = absorption.abs_correction_flex(s1_flex) return absorption_corrections, None # loop through modified Kapton parameters to get alternative corrections and estimate sigmas as # maximum variation between these versions of the corrections, on a per-spot basis, or the standard # deviation within a single spot, whichever is larger. self.logger.info("Calculating kapton corrections to integrated intensities...") corrections, sigmas = correction_and_within_spot_sigma( self.kapton_params, variance_within_spot=self.params.within_spot_sigmas ) if self.smart_sigmas: for p in self.kapton_params_mins + self.kapton_params_maxes: self.logger.info("Calculating smart sigmas...") modif_corrections, _ = correction_and_within_spot_sigma( p, variance_within_spot=False ) perturbed = flex.abs(corrections - modif_corrections) if sigmas is None: sigmas = perturbed else: replace_sel = perturbed > sigmas sigmas.set_selected(replace_sel, perturbed.select(replace_sel)) if plot: from matplotlib import pyplot as plt for (title, data) in [("corrections", corrections), ("sigmas", sigmas)]: plt.hist(data, 20) plt.title(title) plt.show() if self.logger is not None: self.logger.info( "Returning absorption corrections and sigmas for %d spots" % len(corrections) ) return corrections, sigmas class multi_kapton_correction: def __init__(self, experiments, integrated, kapton_params, logger=None): self.experiments = experiments self.reflections = integrated self.params = kapton_params self.logger = logger def __call__(self): self.corrected_reflections = flex.reflection_table() for expt, refl in zip( self.experiments, self.reflections.split_by_experiment_id() ): # extract experiment details detector = expt.detector panels = list(detector) panel_size_px = [p.get_image_size() for p in panels] pixel_size_mm = [p.get_pixel_size()[0] for p in panels] detector_dist_mm = [p.get_distance() for p in panels] beam = expt.beam wavelength_ang = beam.get_wavelength() # exclude reflections with no foreground pixels refl_valid = refl.select( refl["num_pixels.valid"] > 0 and refl["num_pixels.foreground"] > 0 ) refl_zero = refl_valid.select(refl_valid["intensity.sum.value"] == 0) refl_nonzero = refl_valid.select(refl_valid["intensity.sum.value"] != 0) def correct(refl_sele, smart_sigmas=True): kapton_correction = image_kapton_correction( panel_size_px=panel_size_px, pixel_size_mm=pixel_size_mm, detector_dist_mm=detector_dist_mm, wavelength_ang=wavelength_ang, reflections_sele=refl_sele, params=self.params, expt=expt, refl=refl, smart_sigmas=smart_sigmas, logger=self.logger, ) k_corr, k_sigmas = kapton_correction() refl_sele["kapton_absorption_correction"] = k_corr if smart_sigmas: refl_sele["kapton_absorption_correction_sigmas"] = k_sigmas # apply corrections and propagate error # term1 = (sig(C)/C)^2 # term2 = (sig(Imeas)/Imeas)^2 # I' = C*I # sig^2(I') = (I')^2*(term1 + term2) integrated_data = refl_sele["intensity.sum.value"] integrated_variance = refl_sele["intensity.sum.variance"] integrated_sigma = flex.sqrt(integrated_variance) term1 = flex.pow(k_sigmas / k_corr, 2) term2 = flex.pow(integrated_sigma / integrated_data, 2) integrated_data *= k_corr integrated_variance = flex.pow(integrated_data, 2) * (term1 + term2) refl_sele["intensity.sum.value"] = integrated_data refl_sele["intensity.sum.variance"] = integrated_variance # order is purposeful: the two lines above require that integrated_data # has already been corrected! else: refl_sele["intensity.sum.value"] *= k_corr refl_sele["intensity.sum.variance"] *= flex.pow2(k_corr) return refl_sele if len(refl_zero) > 0 and self.params.smart_sigmas: # process nonzero intensity reflections with smart sigmas as requested # but turn them off for zero intensity reflections to avoid a division by zero # during error propagation. Not at all certain this is the best way. self.corrected_reflections.extend( correct(refl_nonzero, smart_sigmas=True) ) self.corrected_reflections.extend( correct(refl_zero, smart_sigmas=False) ) else: self.corrected_reflections.extend( correct(refl_valid, smart_sigmas=self.params.smart_sigmas) ) return self.experiments, self.corrected_reflections
bsd-3-clause
jthomale/pycallnumber
pycallnumber/units/callnumbers/parts.py
7061
"""Work with structures commonly found in many call number types.""" from __future__ import unicode_literals from pycallnumber.template import CompoundTemplate from pycallnumber.unit import CompoundUnit from pycallnumber.units.simple import Alphabetic, Numeric, Formatting,\ DEFAULT_SEPARATOR_TYPE from pycallnumber.units.compound import AlphaNumeric, AlphaNumericSymbol from pycallnumber.units.numbers import Number, OrdinalNumber from pycallnumber.units.dates.datestring import DateString class Cutter(AlphaNumericSymbol): definition = ('a compact alphanumeric code used to arrange things ' 'alphabetically') Letters = Alphabetic.derive( classname='Cutter.Letters', short_description='1 to 3 letters', min_length=1, max_length=3 ) StringNumber = Numeric.derive( classname='Cutter.StringNumber', short_description='a number that sorts as a decimal', max_val=.99999999 ) template = CompoundTemplate( short_description=('a string with 1 to 3 letters followed by a ' 'number; the alphabetic and numeric portions ' 'can be separated by optional whitespace'), separator_type=DEFAULT_SEPARATOR_TYPE, groups=[ {'name': 'letters', 'min': 1, 'max': 1, 'type': Letters}, {'name': 'number', 'min': 1, 'max': 1, 'type': StringNumber} ] ) class Edition(AlphaNumeric): definition = 'information identifying the edition of an item' Year = Numeric.derive( classname='Edition.Year', min_length=4, max_length=4 ) template = CompoundTemplate( short_description=('a 4-digit year, optionally followed by one or ' 'more letters (no whitespace between them)'), separator_type=None, groups=[ {'min': 1, 'max': 1, 'name': 'year', 'type': Year}, {'min': 0, 'max': 1, 'name': 'letters', 'type': Alphabetic} ] ) class Item(AlphaNumericSymbol): definition = ('information such as volume number, copy number, opus ' 'number, etc., that may be included at the end of a call ' 'number to help further differentiate an item from others ' 'with the same call number') Separator = Formatting.derive( min_length=1, max_length=None ) FormattingNoSpace = Formatting.derive( classname='Item.FormattingNoSpace', short_description='any non-alphanumeric, non-whitespace character', min_length=1, max_length=None, base_pattern=r'[^A-Za-z0-9\s]', use_formatting_in_sort=False, use_formatting_in_search=False ) SpaceOrPeriod = Formatting.derive( classname='Item.SpaceOrPeriod', short_description='a period followed by optional whitespace', min_length=1, max_length=1, base_pattern=r'(?:(?:\.|\s)\s*)' ) Space = Formatting.derive( classname='Item.Space', short_description='whitespace', min_length=1, max_length=1, base_pattern=r'\s' ) AnythingButSpace = AlphaNumericSymbol.derive( classname='Item.AnythingButSpace', short_description=('any combination of letters, symbols, and numbers ' 'with no whitespace'), groups=[ {'min': 1, 'max': None, 'name': 'parts', 'inner_sep_type': None, 'possible_types': [Alphabetic, Numeric, FormattingNoSpace]} ] ) Label = Alphabetic.derive( classname='Item.Label', for_sort=lambda x: '', for_search=lambda x: '' ) IdString = AlphaNumericSymbol.derive( classname='Item.IdString', short_description=('a string with at least one number; can have any ' 'characters except whitespace'), separator_type=None, groups=[ {'min': 0, 'max': None, 'name': 'pre_number', 'inner_sep_type': None, 'possible_types': [Alphabetic, FormattingNoSpace]}, {'min': 1, 'max': 1, 'name': 'first_number', 'type': Number}, {'min': 0, 'max': None, 'name': 'everything_else', 'inner_sep_type': None, 'possible_types': [Alphabetic, Number, FormattingNoSpace]} ] ) LabelThenNumber = AlphaNumericSymbol.derive( classname='Item.LabelThenNumber', short_description=('a string with a one-word label (which can contain ' 'formatting), followed by a period and/or ' 'whitespace, followed by one or more numbers (and ' 'possibly letters and formatting), such as ' '\'Op. 1\', \'volume 1a\', or \'no. A-1\'; when ' 'sorting, the label is ignored so that, e.g., ' '\'Volume 1\' sorts before \'vol 2\''), separator_type=SpaceOrPeriod, groups=[ {'min': 0, 'max': None, 'name': 'label', 'inner_sep_type': None, 'possible_types': [Label, FormattingNoSpace]}, {'min': 1, 'max': 1, 'name': 'number', 'type': IdString}, ], for_sort=lambda x: '{}{}'.format(CompoundUnit.sort_break, AlphaNumericSymbol.for_sort(x)) ) NumberThenLabel = AlphaNumericSymbol.derive( classname='Item.NumberThenLabel', short_description=('a string with an ordinal number and then a one-' 'word label, like \'101st Congress\' or \'2nd ' 'vol.\'; when sorting, the label is ignored so ' 'that, e.g., \'1st Congress\' sorts before \'2nd ' 'CONG.\''), separator_type=Space, groups=[ {'min': 1, 'max': 1, 'name': 'number', 'type': OrdinalNumber}, {'min': 1, 'max': 1, 'name': 'label', 'type': Label} ], for_sort=lambda x: '{}{}'.format(CompoundUnit.sort_break, AlphaNumericSymbol.for_sort(x)) ) template = CompoundTemplate( short_description=('a string (any string) that gets parsed into ' 'groups of labeled numbers and other groups of ' 'words, symbols, and dates, where labels are ' 'ignored for sorting; \'Volume 1 Copy 1\' sorts ' 'before \'v. 1 c. 2\', which sorts before ' '\'VOL 1 CP 2 SUPP\'; dates are normalized to ' 'YYYYMMDD format for sorting'), groups=[ {'min': 1, 'max': None, 'name': 'parts', 'inner_sep_type': Separator, 'possible_types': [DateString, NumberThenLabel, LabelThenNumber, AnythingButSpace]} ] )
bsd-3-clause
motech/MOTECH-Mobile
motech-mobile-imp/src/main/java/org/motechproject/mobile/imp/serivce/oxd/StudyProcessor.java
3839
/** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. 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 Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * 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 GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.motechproject.mobile.imp.serivce.oxd; import java.util.ArrayList; import java.util.List; import org.fcitmuk.epihandy.DeserializationListenerAdapter; import org.fcitmuk.epihandy.FormData; import org.fcitmuk.epihandy.StudyData; import org.fcitmuk.epihandy.StudyDataList; /** * The class monitors the deserialization of <code>StudyData</code>, an openXdata mobile-server common object * for transporting form data. * * The Adapter interface is from the openXdata project * * @author Henry Sampson (henry@dreamoval.com) and Brent Atkinson * Date Created: Mar 3, 2010 */ public class StudyProcessor extends DeserializationListenerAdapter { int numForms = 0; StudyDataList model; List<List<String>> studyFormXmlList = new ArrayList<List<String>>(); @Override public void processingStudy(StudyData studyData) { List<String> formList = new ArrayList<String>(); studyFormXmlList.add(formList); } @Override public void formProcessed(StudyData studyData, FormData formData, String xml) { // Get the last list (should be our study), and add xml to end of it int lastFormListIndex = studyFormXmlList.size() - 1; List<String> lastFormList = studyFormXmlList.get(lastFormListIndex); lastFormList.add(xml); numForms++; } @Override public void complete(StudyDataList studyDataList, List<String> xmlForms) { model = studyDataList; } /** * Returns the total number of forms processed so far. * * @return */ public int getNumForms() { return numForms; } /** * Returns the deserialized object model read off the wire. * * @return */ public StudyDataList getModel() { return model; } /** * Returns 2-dimensional array indexed by study, then form * * @return */ public String[][] getConvertedStudies() { String[][] studies = new String[studyFormXmlList.size()][]; for (int i = 0; i < studies.length; i++) studies[i] = studyFormXmlList.get(i).toArray(new String[] {}); return studies; } }
bsd-3-clause
bfyang5130/tuanlogs
backend/themes/base/nginx/city.php
9961
<?php /* @var $this yii\web\View */ use yii\widgets\Breadcrumbs; use backend\services\NginxService; use backend\services\NginxHightchartService; use miloschuman\highcharts\Highcharts; $this->title = '地区访问信息'; $search_date = Yii::$app->request->get("date"); if (empty($search_date)) { $search_date = date('Y-m-d'); } $table = Yii::$app->request->get("table"); if (empty($table)) { $table = 1; } if ($table == 1) { $table = NginxHightchartService::AccessStatistic; } else { $table = NginxHightchartService::AccessStatisticOne; } $cityname = Yii::$app->request->get("cityname"); $pinyinname = Yii::$app->request->get("pinyin"); if (empty($cityname) && empty($pinyinname)) { $cityname = '广东'; } elseif (!empty($pinyinname)) { $pinyincity = \Yii::$app->params['pinyincity']; if (isset($pinyincity[$pinyinname])) { $cityname = $pinyincity[$pinyinname]; } else { $cityname = '广东'; } } else { $cityname = urldecode($cityname); } ?> <div class="site-index"> <?php echo Breadcrumbs::widget([ 'itemTemplate' => "<li><i>{link}</i></li>\n", // template for all links 'links' => [ [ 'label' => '首页' ], ], ]); ?> <div class="body-content"> <div class="panel panel-default"> <?= $this->render('common_top.php'); ?> <div class="panel-body"> <div class="tab-content"> <div class="tab-pane active"> <div class="row"> <div class="col-lg-12"> <table class="table table-bordered table-striped table-condensed"> <tbody> <tr> <td><h5><?= $search_date . $cityname ?>城市访问情况:</h5></td> </tr> <tr> <td> <h4>城市访问情况</h4> <?php //获得访问来源 $pieflat_form = NginxHightchartService::getPiePlatHightChart($search_date, "DetailType1=:topT", [':topT' => $cityname], 'DetailType2', $table, '访问来源'); if ($pieflat_form): ?> <?= Highcharts::widget([ 'options' => [ 'chart' => [ 'type' => 'pie', 'plotShadow' => true, //设置阴影 'height' => 450, ], 'title' => [ 'text' => '城市访问情况' ], 'credits' => [ 'enabled' => false//不显示highCharts版权信息 ], 'plotOptions' => [ 'pie' => [ 'allowPointSelect' => true, 'cursor' => 'pointer', 'dataLabels' => [ 'enabled' => false ], 'showInLegend' => true ], ], 'legend' => [ 'verticalAlign' => "bottom", ], 'series' => [$pieflat_form['in_country']['series']] ] ]); endif; ?> </td> </tr> </tbody> </table> </div> <div class="col-lg-12"> <table class="table table-bordered table-striped table-condensed"> <tbody> <tr> <td><h5><?= $search_date . $cityname ?>24小时访问情况:</h5></td> </tr> <tr> <td> <h4>24小时访问情况</h4> <?php //获得访问来源 $pieflat_form = NginxHightchartService::getSplinePlatHightChart($search_date, "DetailType1=:topT", [':topT' => $cityname], 'CheckTime', $table, '访问来源'); if ($pieflat_form): ?> <?= Highcharts::widget([ 'options' => [ 'chart' => [ 'type' => 'spline', 'plotShadow' => true, //设置阴影 'height' => 450, ], 'title' => [ 'text' => '24小时城市访问情况' ], 'xAxis' => [ 'categories' => $pieflat_form['in_country']['categories'], 'title' => array('text' => null), ], 'yAxis' => [ 'min' => 0, 'title' => array('text' => ''), 'align' => 'high', 'labels' => array("overflow" => "justify") ], 'credits' => [ 'enabled' => false//不显示highCharts版权信息 ], 'plotOptions' => [ 'spline' => [ 'allowPointSelect' => true, 'cursor' => 'pointer', 'dataLabels' => [ 'enabled' => TRUE ], 'showInLegend' => true ], ], 'legend' => [ 'verticalAlign' => "bottom", ], 'series' => [$pieflat_form['in_country']['series']] ] ]); endif; ?> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div>
bsd-3-clause
CCLab/Raw-Salad
scripts/db/universal/csv2json.py
2320
#!/usr/bin/python # # simple JSON file export from CSV dumps (universal) # # what should be taken into consideration, and what this script doesn't do: # - the header should consist of ascii symbols only # - the header shoudn't contain any special symbol like \", ",", ":", "|" etc. (except "_" and "-") # - there should be no spaces in the header # - decimal separator should be dot ".", not comma "," # - all changes should be done manually in csv before convert # import optparse import csv import json import itertools #----------------------------------------------- # parse CSV, convert it to JSON and save to file def csv_parse(filename_csv, filename_json, delimit, quote, jsindent): try: csv_src= open(filename_csv, 'rb') except IOError as e: print 'Unable to open src_file:\n %s\n' % e else: csv_read= csv.reader(csv_src, delimiter= delimit, quotechar= quote) json_write= open(filename_json, 'w') out= [] for row in csv_read: keys= tuple(row) keys_len= len(keys) row= iter(row) out= [ dict(zip( keys, row )) for row in csv_read ] try: print >>json_write, json.dumps(out, indent=jsindent, ensure_ascii=False) except IOError as writerr: print 'Unable to save out_file:\n %s\n' % writerr finally: csv_src.close() json_write.close() print "File saved: " + filename_json #----------------------------- # process command line options cmdparser = optparse.OptionParser() cmdparser.add_option("--src_file",action="store",help="input CSV file (required)") cmdparser.add_option("--out_file",action="store",help="output JSON file (optional, SRC_FILE.JSON if not specified)") cmdparser.add_option("--i",action="store",dest='indent',help="indent in JSON file") opts, args = cmdparser.parse_args() if opts.src_file is not None: filename_csv= opts.src_file if opts.out_file is None: filename_json= filename_csv.rstrip('.csv')+'.json' else: filename_json= opts.out_file indt= opts.indent if indt is not None: indt= int(indt) csv_delim= ';' csv_quote= '"' csv_parse(filename_csv, filename_json, csv_delim, csv_quote, indt) #call a function that process the whole thing
bsd-3-clause
NCIP/annotation-and-image-markup
AIMToolkit_v3.0.2_rv11/source/dcmtk-3.6.0/dcmsr/libsrc/dsrmaccc.cc
3847
/* * * Copyright (C) 2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmsr * * Author: Joerg Riesmeier * * Purpose: * classes: DSRMacularGridThicknessAndVolumeReportConstraintChecker * * Last Update: $Author: joergr $ * Update Date: $Date: 2010-10-14 13:14:41 $ * CVS/RCS Revision: $Revision: 1.2 $ * Status: $State: Exp $ * * CVS/RCS Log at end of file * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmsr/dsrmaccc.h" DSRMacularGridThicknessAndVolumeReportConstraintChecker::DSRMacularGridThicknessAndVolumeReportConstraintChecker() : DSRIODConstraintChecker() { } DSRMacularGridThicknessAndVolumeReportConstraintChecker::~DSRMacularGridThicknessAndVolumeReportConstraintChecker() { } OFBool DSRMacularGridThicknessAndVolumeReportConstraintChecker::isByReferenceAllowed() const { return OFFalse; } OFBool DSRMacularGridThicknessAndVolumeReportConstraintChecker::isTemplateSupportRequired() const { return OFTrue; } const char *DSRMacularGridThicknessAndVolumeReportConstraintChecker::getRootTemplateIdentifier() const { return "2100"; } DSRTypes::E_DocumentType DSRMacularGridThicknessAndVolumeReportConstraintChecker::getDocumentType() const { return DT_MacularGridThicknessAndVolumeReport; } OFBool DSRMacularGridThicknessAndVolumeReportConstraintChecker::checkContentRelationship(const E_ValueType sourceValueType, const E_RelationshipType relationshipType, const E_ValueType targetValueType, const OFBool byReference) const { /* the following code implements the constraints of table A.35.11.3.1.2-1 in DICOM PS3.3 */ OFBool result = OFFalse; /* by-reference relationships not allowed at all */ if (!byReference) { /* row 1 of the table */ if ((relationshipType == RT_hasObsContext) && (sourceValueType == VT_Container)) { result = (targetValueType == VT_Code) || (targetValueType == VT_PName) || (targetValueType == VT_Text) || (targetValueType == VT_UIDRef) || (targetValueType == VT_Date) || (targetValueType == VT_Num); } /* row 2 of the table */ else if ((relationshipType == RT_contains) && (sourceValueType == VT_Container)) { result = (targetValueType == VT_Container) || (targetValueType == VT_Num) || (targetValueType == VT_Text) || (targetValueType == VT_Code); } /* row 3 of the table */ else if (relationshipType == RT_hasConceptMod) { result = (targetValueType == VT_Code); } /* row 4 of the table */ else if ((relationshipType == RT_hasObsContext) && (sourceValueType == VT_Num)) { result = (targetValueType == VT_Text); } /* row 5 of the table */ else if ((relationshipType == RT_inferredFrom) && (sourceValueType == VT_Num)) { result = (targetValueType == VT_Image); } } return result; } /* * CVS/RCS Log: * $Log: dsrmaccc.cc,v $ * Revision 1.2 2010-10-14 13:14:41 joergr * Updated copyright header. Added reference to COPYRIGHT file. * * Revision 1.1 2010-09-30 08:56:46 joergr * Added support for the Macular Grid Thickness and Volume Report IOD. * * */
bsd-3-clause
philippfrenzel/karaokekings
views/songs/_form.php
1158
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\Songs */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="songs-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'title')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'artist')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'lyrics')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'year')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'duo')->textInput() ?> <?= $form->field($model, 'tags')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'status')->textInput(['maxlength' => 255]) ?> <?= $form->field($model, 'created_at')->textInput() ?> <?= $form->field($model, 'updated_at')->textInput() ?> <?= $form->field($model, 'deleted_at')->textInput() ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
bsd-3-clause
parhansson/KMotionX
PC VCS Examples/ExtendedLoggingKflop/Models/AxisDefinitionModel.cs
3102
using Catel.Data; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using Catel.MVVM; using System.ComponentModel; using Catel.Runtime.Serialization; namespace ExtendedLoggingKflop.Models { public enum PlotAxisPositionEnum { YAxisLeft, YAxisRight } /// <summary> /// AxisDefinitionModel model which fully supports serialization, property changed notifications, /// backwards compatibility and error checking. /// </summary> #if !SILVERLIGHT [Serializable] #endif public class AxisDefinitionModel : SavableModelBase<AxisDefinitionModel> { #region Fields #endregion #region Constructors /// <summary> /// Initializes a new object from scratch. /// </summary> public AxisDefinitionModel() { Key = Guid.NewGuid().ToString(); } #if !SILVERLIGHT /// <summary> /// Initializes a new object based on <see cref="SerializationInfo"/>. /// </summary> /// <param name="info"><see cref="SerializationInfo"/> that contains the information.</param> /// <param name="context"><see cref="StreamingContext"/>.</param> protected AxisDefinitionModel(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif #endregion #region Properties // TODO: Define your custom properties here using the modelprop code snippet // Using Catel.Fody so we declare properties just like regular properties // and Fody turns them into Catel properties [DefaultValue(PlotAxisPositionEnum.YAxisRight)] public PlotAxisPositionEnum AxisPosition { get; set; } [Required] public string AxisTitle { get; set; } public string Key { get; set; } public string Unit { get; set; } [ExcludeFromSerializationAttribute] public Object OxyAxis { get; set; } #endregion #region Methods /// <summary> /// Validates the field values of this object. Override this method to enable /// validation of field values. /// </summary> /// <param name="validationResults">The validation results, add additional results to this list.</param> protected override void ValidateFields(List<IFieldValidationResult> validationResults) { } /// <summary> /// Validates the field values of this object. Override this method to enable /// validation of field values. /// </summary> /// <param name="validationResults">The validation results, add additional results to this list.</param> protected override void ValidateBusinessRules(List<IBusinessRuleValidationResult> validationResults) { } #endregion } }
bsd-3-clause
kgacova/Orchard
src/Orchard/ContentManagement/Handlers/ContentHandlerBase.cs
2564
namespace Orchard.ContentManagement.Handlers { public class ContentHandlerBase : IContentHandler { public virtual void Activating(ActivatingContentContext context) {} public virtual void Activated(ActivatedContentContext context) {} public virtual void Initializing(InitializingContentContext context) { } public virtual void Initialized(InitializingContentContext context) { } public virtual void Creating(CreateContentContext context) { } public virtual void Created(CreateContentContext context) {} public virtual void Loading(LoadContentContext context) {} public virtual void Loaded(LoadContentContext context) {} public virtual void Updating(UpdateContentContext context) { } public virtual void Updated(UpdateContentContext context) { } public virtual void Versioning(VersionContentContext context) { } public virtual void Versioned(VersionContentContext context) {} public virtual void Publishing(PublishContentContext context) {} public virtual void Published(PublishContentContext context) {} public virtual void Unpublishing(PublishContentContext context) {} public virtual void Unpublished(PublishContentContext context) {} public virtual void Removing(RemoveContentContext context) {} public virtual void Removed(RemoveContentContext context) {} public virtual void Indexing(IndexContentContext context) {} public virtual void Indexed(IndexContentContext context) {} public virtual void Importing(ImportContentContext context) {} public virtual void Imported(ImportContentContext context) {} public virtual void ImportCompleted(ImportContentContext importContentContext) {} public virtual void Exporting(ExportContentContext context) {} public virtual void Exported(ExportContentContext context) {} public virtual void Restoring(RestoreContentContext context) { } public virtual void Restored(RestoreContentContext context) { } public virtual void Destroying(DestroyContentContext context) {} public virtual void Destroyed(DestroyContentContext context) {} public virtual void GetContentItemMetadata(GetContentItemMetadataContext context) {} public virtual void BuildDisplay(BuildDisplayContext context) {} public virtual void BuildEditor(BuildEditorContext context) {} public virtual void UpdateEditor(UpdateEditorContext context) {} } }
bsd-3-clause
juliocesarcarvajal/ako
js-plugin/responsive-nav/demos/require-js/main.js
95
require(["../../responsive-nav"], function() { var navigation = responsiveNav("#nav"); });
bsd-3-clause
veontomo/teresaStore
views/product/create.php
487
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\Product */ $this->title = Yii::t('app', 'Create {modelClass}', [ 'modelClass' => 'Product', ]); $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Products'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="product-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
bsd-3-clause
stan-dev/math
stan/math/rev/fun/svd_V.hpp
2228
#ifndef STAN_MATH_REV_FUN_SVD_V_HPP #define STAN_MATH_REV_FUN_SVD_V_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/err/check_nonzero_size.hpp> #include <stan/math/prim/fun/typedefs.hpp> #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/rev/fun/value_of.hpp> namespace stan { namespace math { /** * Given input matrix m, return matrix V where `m = UDV^{T}` * * Adjoint update equation comes from Equation (4) in Differentiable Programming * Tensor Networks(H. Liao, J. Liu, et al., arXiv:1903.09650). * * @tparam EigMat type of input matrix * @param m MxN input matrix * @return Orthogonal matrix V */ template <typename EigMat, require_rev_matrix_t<EigMat>* = nullptr> inline auto svd_V(const EigMat& m) { using ret_type = return_var_matrix_t<Eigen::MatrixXd, EigMat>; check_nonzero_size("svd_V", "m", m); const int M = std::min(m.rows(), m.cols()); auto arena_m = to_arena(m); Eigen::JacobiSVD<Eigen::MatrixXd> svd( arena_m.val(), Eigen::ComputeThinU | Eigen::ComputeThinV); auto arena_D = to_arena(svd.singularValues()); arena_t<Eigen::MatrixXd> arena_Fm(M, M); for (int i = 0; i < M; i++) { for (int j = 0; j < M; j++) { if (j == i) { arena_Fm(i, j) = 0.0; } else { arena_Fm(i, j) = 1.0 / (arena_D[j] - arena_D[i]) - 1.0 / (arena_D[i] + arena_D[j]); } } } auto arena_U = to_arena(svd.matrixU()); arena_t<ret_type> arena_V = svd.matrixV(); reverse_pass_callback([arena_m, arena_U, arena_D, arena_V, arena_Fm, M]() mutable { Eigen::MatrixXd VTVadj = arena_V.val_op().transpose() * arena_V.adj_op(); arena_m.adj() += 0.5 * arena_U * (arena_Fm.array() * (VTVadj - VTVadj.transpose()).array()) .matrix() * arena_V.val_op().transpose() + arena_U * arena_D.asDiagonal().inverse() * arena_V.adj_op().transpose() * (Eigen::MatrixXd::Identity(arena_m.cols(), arena_m.cols()) - arena_V.val_op() * arena_V.val_op().transpose()); }); return ret_type(arena_V); } } // namespace math } // namespace stan #endif
bsd-3-clause
chrisblackni/onxshop
controllers/bo/component/ecommerce/recipe_list_filter.php
547
<?php /** * * Copyright (c) 2013-2014 Onxshop Ltd (https://onxshop.com) * Licensed under the New BSD License. See the file LICENSE.txt for details. */ class Onxshop_Controller_Bo_Component_Ecommerce_Recipe_List_Filter extends Onxshop_Controller { /** * main action */ public function mainAction() { if (isset($_POST['recipe-list-filter'])) $_SESSION['bo']['recipe-list-filter'] = $_POST['recipe-list-filter']; $filter = $_SESSION['bo']['recipe-list-filter']; $this->tpl->assign('FILTER', $filter); return true; } }
bsd-3-clause
highweb-project/highweb-webcl-html5spec
components/autofill/core/browser/webdata/autofill_wallet_syncable_service.cc
11525
// Copyright 2015 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 "components/autofill/core/browser/webdata/autofill_wallet_syncable_service.h" #include <stddef.h> #include <set> #include <utility> #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/webdata/autofill_table.h" #include "components/autofill/core/browser/webdata/autofill_webdata_backend.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "sync/api/sync_error_factory.h" #include "sync/protocol/sync.pb.h" namespace autofill { namespace { void* UserDataKey() { // Use the address of a static so that COMDAT folding won't ever fold // with something else. static int user_data_key = 0; return reinterpret_cast<void*>(&user_data_key); } const char* CardTypeFromWalletCardType( sync_pb::WalletMaskedCreditCard::WalletCardType type) { switch (type) { case sync_pb::WalletMaskedCreditCard::AMEX: return kAmericanExpressCard; case sync_pb::WalletMaskedCreditCard::DISCOVER: return kDiscoverCard; case sync_pb::WalletMaskedCreditCard::JCB: return kJCBCard; case sync_pb::WalletMaskedCreditCard::MASTER_CARD: return kMasterCard; case sync_pb::WalletMaskedCreditCard::VISA: return kVisaCard; // These aren't supported by the client, so just declare a generic card. case sync_pb::WalletMaskedCreditCard::MAESTRO: case sync_pb::WalletMaskedCreditCard::SOLO: case sync_pb::WalletMaskedCreditCard::SWITCH: default: return kGenericCard; } } CreditCard::ServerStatus ServerToLocalStatus( sync_pb::WalletMaskedCreditCard::WalletCardStatus status) { switch (status) { case sync_pb::WalletMaskedCreditCard::VALID: return CreditCard::OK; case sync_pb::WalletMaskedCreditCard::EXPIRED: default: DCHECK_EQ(sync_pb::WalletMaskedCreditCard::EXPIRED, status); return CreditCard::EXPIRED; } } CreditCard CardFromSpecifics(const sync_pb::WalletMaskedCreditCard& card) { CreditCard result(CreditCard::MASKED_SERVER_CARD, card.id()); result.SetNumber(base::UTF8ToUTF16(card.last_four())); result.SetServerStatus(ServerToLocalStatus(card.status())); result.SetTypeForMaskedCard(CardTypeFromWalletCardType(card.type())); result.SetRawInfo(CREDIT_CARD_NAME_FULL, base::UTF8ToUTF16(card.name_on_card())); result.SetExpirationMonth(card.exp_month()); result.SetExpirationYear(card.exp_year()); return result; } AutofillProfile ProfileFromSpecifics( const sync_pb::WalletPostalAddress& address) { AutofillProfile profile(AutofillProfile::SERVER_PROFILE, std::string()); // AutofillProfile stores multi-line addresses with newline separators. std::vector<std::string> street_address(address.street_address().begin(), address.street_address().end()); profile.SetRawInfo(ADDRESS_HOME_STREET_ADDRESS, base::UTF8ToUTF16(base::JoinString(street_address, "\n"))); profile.SetRawInfo(COMPANY_NAME, base::UTF8ToUTF16(address.company_name())); profile.SetRawInfo(ADDRESS_HOME_STATE, base::UTF8ToUTF16(address.address_1())); profile.SetRawInfo(ADDRESS_HOME_CITY, base::UTF8ToUTF16(address.address_2())); profile.SetRawInfo(ADDRESS_HOME_DEPENDENT_LOCALITY, base::UTF8ToUTF16(address.address_3())); // AutofillProfile doesn't support address_4 ("sub dependent locality"). profile.SetRawInfo(ADDRESS_HOME_ZIP, base::UTF8ToUTF16(address.postal_code())); profile.SetRawInfo(ADDRESS_HOME_SORTING_CODE, base::UTF8ToUTF16(address.sorting_code())); profile.SetRawInfo(ADDRESS_HOME_COUNTRY, base::UTF8ToUTF16(address.country_code())); profile.set_language_code(address.language_code()); // SetInfo instead of SetRawInfo so the constituent pieces will be parsed // for these data types. profile.SetInfo(AutofillType(NAME_FULL), base::UTF8ToUTF16(address.recipient_name()), profile.language_code()); profile.SetInfo(AutofillType(PHONE_HOME_WHOLE_NUMBER), base::UTF8ToUTF16(address.phone_number()), profile.language_code()); profile.GenerateServerProfileIdentifier(); return profile; } // This function handles conditionally updating the AutofillTable with either // a set of CreditCards or AutocompleteProfiles only when the existing data // doesn't match. // // It's passed the getter and setter function on the AutofillTable for the // corresponding data type, and expects the types to implement a Compare // function. Note that the guid can't be used here as a key since these are // generated locally and will be different each time, and the server ID can't // be used because it's empty for addresses (though it could be used for credit // cards if we wanted separate implementations). // // Returns true if anything changed. The previous number of items in the table // (for sync tracking) will be placed into *prev_item_count. template<class Data> bool SetDataIfChanged( AutofillTable* table, const std::vector<Data>& data, bool (AutofillTable::*getter)(std::vector<Data*>*), void (AutofillTable::*setter)(const std::vector<Data>&), size_t* prev_item_count) { ScopedVector<Data> existing_data; (table->*getter)(&existing_data.get()); *prev_item_count = existing_data.size(); // If the user has a large number of addresses, don't bother verifying // anything changed and just rewrite the data. const size_t kTooBigToCheckThreshold = 8; bool difference_found; if (existing_data.size() != data.size() || data.size() > kTooBigToCheckThreshold) { difference_found = true; } else { difference_found = false; // Implement brute-force searching. Address and card counts are typically // small, and comparing them is relatively expensive (many string // compares). A std::set only uses operator< requiring multiple calls to // check equality, giving 8 compares for 2 elements and 16 for 3. For these // set sizes, brute force O(n^2) is faster. for (const Data* cur_existing : existing_data) { bool found_match_for_cur_existing = false; for (const Data& cur_new : data) { if (cur_existing->Compare(cur_new) == 0) { found_match_for_cur_existing = true; break; } } if (!found_match_for_cur_existing) { difference_found = true; break; } } } if (difference_found) { (table->*setter)(data); return true; } return false; } } // namespace AutofillWalletSyncableService::AutofillWalletSyncableService( AutofillWebDataBackend* webdata_backend, const std::string& app_locale) : webdata_backend_(webdata_backend) { } AutofillWalletSyncableService::~AutofillWalletSyncableService() { } syncer::SyncMergeResult AutofillWalletSyncableService::MergeDataAndStartSyncing( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, scoped_ptr<syncer::SyncChangeProcessor> sync_processor, scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) { DCHECK(thread_checker_.CalledOnValidThread()); sync_processor_ = std::move(sync_processor); return SetSyncData(initial_sync_data); } void AutofillWalletSyncableService::StopSyncing(syncer::ModelType type) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(type, syncer::AUTOFILL_WALLET_DATA); sync_processor_.reset(); } syncer::SyncDataList AutofillWalletSyncableService::GetAllSyncData( syncer::ModelType type) const { DCHECK(thread_checker_.CalledOnValidThread()); // This data type is never synced "up" so we don't need to implement this. syncer::SyncDataList current_data; return current_data; } syncer::SyncError AutofillWalletSyncableService::ProcessSyncChanges( const tracked_objects::Location& from_here, const syncer::SyncChangeList& change_list) { DCHECK(thread_checker_.CalledOnValidThread()); // Don't bother handling incremental updates. Wallet data changes very rarely // and has few items. Instead, just get all the current data and save it. SetSyncData(sync_processor_->GetAllSyncData(syncer::AUTOFILL_WALLET_DATA)); return syncer::SyncError(); } // static void AutofillWalletSyncableService::CreateForWebDataServiceAndBackend( AutofillWebDataService* web_data_service, AutofillWebDataBackend* webdata_backend, const std::string& app_locale) { web_data_service->GetDBUserData()->SetUserData( UserDataKey(), new AutofillWalletSyncableService(webdata_backend, app_locale)); } // static AutofillWalletSyncableService* AutofillWalletSyncableService::FromWebDataService( AutofillWebDataService* web_data_service) { return static_cast<AutofillWalletSyncableService*>( web_data_service->GetDBUserData()->GetUserData(UserDataKey())); } void AutofillWalletSyncableService::InjectStartSyncFlare( const syncer::SyncableService::StartSyncFlare& flare) { flare_ = flare; } syncer::SyncMergeResult AutofillWalletSyncableService::SetSyncData( const syncer::SyncDataList& data_list) { std::vector<CreditCard> wallet_cards; std::vector<AutofillProfile> wallet_addresses; for (const syncer::SyncData& data : data_list) { DCHECK_EQ(syncer::AUTOFILL_WALLET_DATA, data.GetDataType()); const sync_pb::AutofillWalletSpecifics& autofill_specifics = data.GetSpecifics().autofill_wallet(); if (autofill_specifics.type() == sync_pb::AutofillWalletSpecifics::MASKED_CREDIT_CARD) { wallet_cards.push_back( CardFromSpecifics(autofill_specifics.masked_card())); } else { DCHECK_EQ(sync_pb::AutofillWalletSpecifics::POSTAL_ADDRESS, autofill_specifics.type()); wallet_addresses.push_back( ProfileFromSpecifics(autofill_specifics.address())); } } // In the common case, the database won't have changed. Committing an update // to the database will require at least one DB page write and will schedule // a fsync. To avoid this I/O, it should be more efficient to do a read and // only do the writes if something changed. AutofillTable* table = AutofillTable::FromWebDatabase(webdata_backend_->GetDatabase()); size_t prev_card_count = 0; size_t prev_address_count = 0; bool changed_cards = SetDataIfChanged( table, wallet_cards, &AutofillTable::GetServerCreditCards, &AutofillTable::SetServerCreditCards, &prev_card_count); bool changed_addresses = SetDataIfChanged( table, wallet_addresses, &AutofillTable::GetServerProfiles, &AutofillTable::SetServerProfiles, &prev_address_count); syncer::SyncMergeResult merge_result(syncer::AUTOFILL_WALLET_DATA); merge_result.set_num_items_before_association( static_cast<int>(prev_card_count + prev_address_count)); merge_result.set_num_items_after_association( static_cast<int>(wallet_cards.size() + wallet_addresses.size())); if (webdata_backend_ && (changed_cards || changed_addresses)) webdata_backend_->NotifyOfMultipleAutofillChanges(); return merge_result; } } // namespace autofil
bsd-3-clause
endlessm/chromium-browser
chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/form/AssistantFormSelectionInput.java
5768
// 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. package org.chromium.chrome.browser.autofill_assistant.form; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.TextView; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.AssistantTextUtils; import org.chromium.chrome.browser.autofill_assistant.user_data.AssistantChoiceList; import java.util.ArrayList; import java.util.List; /** A form input that allows to choose between multiple choices. */ class AssistantFormSelectionInput extends AssistantFormInput { interface Delegate { void onChoiceSelectionChanged(int choiceIndex, boolean selected); void onLinkClicked(int link); } private final String mLabel; private final List<AssistantFormSelectionChoice> mChoices; private final boolean mAllowMultipleChoices; private final Delegate mDelegate; private final List<View> mChoiceViews = new ArrayList<>(); public AssistantFormSelectionInput(String label, List<AssistantFormSelectionChoice> choices, boolean allowMultipleChoices, Delegate delegate) { mLabel = label; mChoices = choices; mAllowMultipleChoices = allowMultipleChoices; mDelegate = delegate; } @Override public View createView(Context context, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); ViewGroup root = (ViewGroup) inflater.inflate( R.layout.autofill_assistant_form_selection_input, parent, /* attachToRoot= */ false); TextView label = root.findViewById(org.chromium.chrome.autofill_assistant.R.id.label); if (mLabel.isEmpty()) { label.setVisibility(View.GONE); } else { AssistantTextUtils.applyVisualAppearanceTags(label, mLabel, mDelegate::onLinkClicked); } if (mChoices.isEmpty()) { return root; } ViewGroup checkboxList = root.findViewById(R.id.checkbox_list); AssistantChoiceList radiobuttonList = root.findViewById(R.id.radiobutton_list); radiobuttonList.setAllowMultipleChoices(false); for (int i = 0; i < mChoices.size(); i++) { AssistantFormSelectionChoice choice = mChoices.get(i); int index = i; // needed for the lambda. View choiceView; if (mAllowMultipleChoices) { choiceView = inflater.inflate(R.layout.autofill_assistant_form_checkbox, checkboxList, /* attachToRoot= */ false); checkboxList.addView(choiceView); CheckBox checkBox = choiceView.findViewById(R.id.checkbox); checkBox.setOnCheckedChangeListener( (compoundButton, isChecked) -> mDelegate.onChoiceSelectionChanged(index, isChecked)); choiceView.findViewById(R.id.descriptions) .setOnClickListener( unusedView -> checkBox.setChecked(!checkBox.isChecked())); checkBox.setChecked(choice.isInitiallySelected()); } else { choiceView = inflater.inflate(R.layout.autofill_assistant_form_radiobutton, null); radiobuttonList.addItem(choiceView, /* hasEditButton= */ false, (isChecked) -> { mDelegate.onChoiceSelectionChanged(index, isChecked); // Workaround for radio buttons in FormAction: de-select all other // items. This is needed because the current selection state is not part // of AssistantFormModel (but it should be). TODO(b/150201921). if (isChecked) { for (View view : mChoiceViews) { if (view == choiceView) { continue; } radiobuttonList.setChecked(view, false); } } }, /* itemEditedListener= */ null); radiobuttonList.setChecked(choiceView, choice.isInitiallySelected()); } mChoiceViews.add(choiceView); TextView choiceLabel = choiceView.findViewById(R.id.label); TextView descriptionLine1 = choiceView.findViewById(R.id.description_line_1); TextView descriptionLine2 = choiceView.findViewById(R.id.description_line_2); AssistantTextUtils.applyVisualAppearanceTags( choiceLabel, choice.getLabel(), mDelegate::onLinkClicked); AssistantTextUtils.applyVisualAppearanceTags( descriptionLine1, choice.getDescriptionLine1(), mDelegate::onLinkClicked); AssistantTextUtils.applyVisualAppearanceTags( descriptionLine2, choice.getDescriptionLine2(), mDelegate::onLinkClicked); hideIfEmpty(choiceLabel); hideIfEmpty(descriptionLine1); hideIfEmpty(descriptionLine2); setMinimumHeight(choiceView, descriptionLine1, descriptionLine2); } if (mAllowMultipleChoices) { checkboxList.setVisibility(View.VISIBLE); } else { radiobuttonList.setVisibility(View.VISIBLE); } return root; } }
bsd-3-clause
etscrivner/turkleton
turkleton/connection.py
2261
# -*- coding: utf-8 -*- """ mturk.connection ~~~~~~~~~~~~~~~~ Simplified interface for connecting to Mechanical Turk. """ from boto.mturk import connection from turkleton import errors # The host for the Mechanical Turk sandbox. MTURK_SANDBOX_HOST = 'mechanicalturk.sandbox.amazonaws.com' # Global containing the boto connection to Mechanical Turk for this process. mturk_connection = None class ConnectionError(errors.Error): """Error involving the connection to Mechanical Turk""" pass def get_connection(): """Return the Mechanical Turk connection for this process. :rtype: boto.mturk.connection.MTurkConnection """ global mturk_connection if not mturk_connection: raise ConnectionError( 'It is required that you setup() turkleton before use.' ) return mturk_connection def set_connection(boto_connection): """Set the Mechanical Turk connection for this process. :param boto_connection: A connection :type boto_connection: boto.mturk.connection.MTurkConnection """ global mturk_connection mturk_connection = boto_connection def setup(access_key_id, secret_access_key, host=None): """Setup the global connection to Mechanical Turk. :param access_key_id: The access key id :type access_key_id: str or unicode :param secret_access_key: The access secret key :type secret_access_key: str or unicode :param host: (Optional, default is production MTurk) The host to connect to :type host: str or unicode :rtype: boto.mturk.connection.Connection """ boto_connection = connection.MTurkConnection( aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key, host=host ) set_connection(boto_connection) return boto_connection def setup_sandbox(access_key_id, secret_access_key): """Setup a global connection to the Mechanical Turk sandbox. :param access_key_id: The access key id :type access_key_id: str or unicode :param secret_access_key: The access secret key :type secret_access_key: str or unicode :rtype: boto.mturk.connection.Connection """ return setup( access_key_id, secret_access_key, MTURK_SANDBOX_HOST )
bsd-3-clause
qedsoftware/commcare-hq
corehq/form_processor/migrations/0007_index_case_uuid_on_commcarecaseindex.py
554
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('form_processor', '0006_commcarecaseindexsql'), ] operations = [ migrations.AlterField( model_name='commcarecaseindexsql', name='case', field=models.ForeignKey(to='form_processor.CommCareCaseSQL', db_column=b'case_uuid', to_field=b'case_uuid', on_delete=models.CASCADE), preserve_default=True, ), ]
bsd-3-clause
danakj/chromium
third_party/WebKit/Source/modules/presentation/PresentationRequest.cpp
6434
// Copyright 2015 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 "modules/presentation/PresentationRequest.h" #include "bindings/core/v8/CallbackPromiseAdapter.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "core/dom/DOMException.h" #include "core/dom/Document.h" #include "core/dom/ExecutionContext.h" #include "core/frame/Settings.h" #include "core/frame/UseCounter.h" #include "modules/EventTargetModules.h" #include "modules/presentation/PresentationAvailability.h" #include "modules/presentation/PresentationAvailabilityCallbacks.h" #include "modules/presentation/PresentationConnection.h" #include "modules/presentation/PresentationConnectionCallbacks.h" #include "modules/presentation/PresentationController.h" #include "modules/presentation/PresentationError.h" #include "platform/UserGestureIndicator.h" namespace blink { namespace { // TODO(mlamouri): refactor in one common place. WebPresentationClient* presentationClient(ExecutionContext* executionContext) { DCHECK(executionContext); Document* document = toDocument(executionContext); if (!document->frame()) return nullptr; PresentationController* controller = PresentationController::from(*document->frame()); return controller ? controller->client() : nullptr; } Settings* settings(ExecutionContext* executionContext) { DCHECK(executionContext); Document* document = toDocument(executionContext); return document->settings(); } } // anonymous namespace // static PresentationRequest* PresentationRequest::create(ExecutionContext* executionContext, const String& url, ExceptionState& exceptionState) { KURL parsedUrl = KURL(executionContext->url(), url); if (!parsedUrl.isValid() || parsedUrl.protocolIsAbout()) { exceptionState.throwTypeError("'" + url + "' can't be resolved to a valid URL."); return nullptr; } PresentationRequest* request = new PresentationRequest(executionContext, parsedUrl); request->suspendIfNeeded(); return request; } const AtomicString& PresentationRequest::interfaceName() const { return EventTargetNames::PresentationRequest; } ExecutionContext* PresentationRequest::getExecutionContext() const { return ActiveDOMObject::getExecutionContext(); } void PresentationRequest::addedEventListener(const AtomicString& eventType, RegisteredEventListener& registeredListener) { EventTargetWithInlineData::addedEventListener(eventType, registeredListener); if (eventType == EventTypeNames::connectionavailable) UseCounter::count(getExecutionContext(), UseCounter::PresentationRequestConnectionAvailableEventListener); } bool PresentationRequest::hasPendingActivity() const { if (!getExecutionContext() || getExecutionContext()->activeDOMObjectsAreStopped()) return false; // Prevents garbage collecting of this object when not hold by another // object but still has listeners registered. return hasEventListeners(); } ScriptPromise PresentationRequest::start(ScriptState* scriptState) { Settings* contextSettings = settings(getExecutionContext()); bool isUserGestureRequired = !contextSettings || contextSettings->presentationRequiresUserGesture(); if (isUserGestureRequired && !UserGestureIndicator::utilizeUserGesture()) return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(InvalidAccessError, "PresentationRequest::start() requires user gesture.")); if (toDocument(getExecutionContext())->isSandboxed(SandboxPresentation)) return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(SecurityError, "The document is sandboxed and lacks the 'allow-presentation' flag.")); WebPresentationClient* client = presentationClient(getExecutionContext()); if (!client) return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(InvalidStateError, "The PresentationRequest is no longer associated to a frame.")); ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); client->startSession(m_url.getString(), new PresentationConnectionCallbacks(resolver, this)); return resolver->promise(); } ScriptPromise PresentationRequest::reconnect(ScriptState* scriptState, const String& id) { if (toDocument(getExecutionContext())->isSandboxed(SandboxPresentation)) return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(SecurityError, "The document is sandboxed and lacks the 'allow-presentation' flag.")); WebPresentationClient* client = presentationClient(getExecutionContext()); if (!client) return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(InvalidStateError, "The PresentationRequest is no longer associated to a frame.")); ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); client->joinSession(m_url.getString(), id, new PresentationConnectionCallbacks(resolver, this)); return resolver->promise(); } ScriptPromise PresentationRequest::getAvailability(ScriptState* scriptState) { if (toDocument(getExecutionContext())->isSandboxed(SandboxPresentation)) return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(SecurityError, "The document is sandboxed and lacks the 'allow-presentation' flag.")); WebPresentationClient* client = presentationClient(getExecutionContext()); if (!client) return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(InvalidStateError, "The PresentationRequest is no longer associated to a frame.")); ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); client->getAvailability(m_url.getString(), new PresentationAvailabilityCallbacks(resolver, m_url)); return resolver->promise(); } const KURL& PresentationRequest::url() const { return m_url; } DEFINE_TRACE(PresentationRequest) { EventTargetWithInlineData::trace(visitor); ActiveDOMObject::trace(visitor); } PresentationRequest::PresentationRequest(ExecutionContext* executionContext, const KURL& url) : ActiveScriptWrappable(this) , ActiveDOMObject(executionContext) , m_url(url) { } } // namespace blink
bsd-3-clause
PeekAndPoke/aviator
src/PeekAndPoke/Aviator/Middleware/ResponseFactory.php
708
<?php /** * Created by IntelliJ IDEA. * User: gerk * Date: 21.12.16 * Time: 21:27 */ declare(strict_types=1); namespace PeekAndPoke\Aviator\Middleware; use Psr\Http\Message\ResponseInterface; /** * @author Karsten J. Gerber <kontakt@karsten-gerber.de> */ interface ResponseFactory { /** * Create a PSR-7 Response Object * * @param int $status The HTTP status code for the response * @param array $headers The parsed headers for the response * @param mixed $body The body for the response * * @return ResponseInterface The generated response */ public function create(int $status = 200, array $headers = [], $body = null) : ResponseInterface; }
bsd-3-clause
Mak-Di/yii2
tests/framework/log/LoggerTest.php
13421
<?php /** * @author Carsten Brandt <mail@cebe.cc> */ namespace yiiunit\framework\log; use yii\log\Logger; use yiiunit\TestCase; /** * @group log */ class LoggerTest extends TestCase { /** * @var Logger */ protected $logger; /** * @var Dispatcher */ protected $dispatcher; protected function setUp() { $this->logger = new Logger(); $this->dispatcher = $this->getMock('yii\\log\\Dispatcher', ['dispatch']); } /** * @covers yii\log\Logger::Log() */ public function testLog() { $this->logger->log('test1', Logger::LEVEL_INFO); $this->assertEquals(1, count($this->logger->messages)); $this->assertEquals('test1', $this->logger->messages[0][0]); $this->assertEquals(Logger::LEVEL_INFO, $this->logger->messages[0][1]); $this->assertEquals('application', $this->logger->messages[0][2]); $this->assertEquals([], $this->logger->messages[0][4]); $this->logger->log('test2', Logger::LEVEL_ERROR, 'category'); $this->assertEquals(2, count($this->logger->messages)); $this->assertEquals('test2', $this->logger->messages[1][0]); $this->assertEquals(Logger::LEVEL_ERROR, $this->logger->messages[1][1]); $this->assertEquals('category', $this->logger->messages[1][2]); $this->assertEquals([], $this->logger->messages[1][4]); } /** * @covers yii\log\Logger::Log() */ public function testLogWithTraceLevel() { $this->logger->traceLevel = 3; $this->logger->log('test3', Logger::LEVEL_INFO); $this->assertEquals(1, count($this->logger->messages)); $this->assertEquals('test3', $this->logger->messages[0][0]); $this->assertEquals(Logger::LEVEL_INFO, $this->logger->messages[0][1]); $this->assertEquals('application', $this->logger->messages[0][2]); $this->assertEquals([ 'file' => __FILE__, 'line' => 58, 'function' => 'log', 'class' => get_class($this->logger), 'type' => '->' ], $this->logger->messages[0][4][0]); $this->assertEquals(3, count($this->logger->messages[0][4])); } /** * @covers yii\log\Logger::Log() */ public function testLogWithFlush() { $logger = $this->getMock('yii\\log\\Logger', ['flush']); $logger->flushInterval = 1; $logger->expects($this->exactly(1))->method('flush'); $logger->log('test1', Logger::LEVEL_INFO); } /** * @covers yii\log\Logger::Flush() */ public function testFlushWithoutDispatcher() { $dispatcher = $this->getMock('\stdClass'); $dispatcher->expects($this->never())->method($this->anything()); $this->logger->messages = ['anything']; $this->logger->dispatcher = $dispatcher; $this->logger->flush(); $this->assertEmpty($this->logger->messages); } /** * @covers yii\log\Logger::Flush() */ public function testFlushWithDispatcherAndDefaultParam() { $message = ['anything']; $this->dispatcher->expects($this->once()) ->method('dispatch')->with($this->equalTo($message), $this->equalTo(false)); $this->logger->messages = $message; $this->logger->dispatcher = $this->dispatcher; $this->logger->flush(); $this->assertEmpty($this->logger->messages); } /** * @covers yii\log\Logger::Flush() */ public function testFlushWithDispatcherAndDefinedParam() { $message = ['anything']; $this->dispatcher->expects($this->once()) ->method('dispatch')->with($this->equalTo($message), $this->equalTo(true)); $this->logger->messages = $message; $this->logger->dispatcher = $this->dispatcher; $this->logger->flush(true); $this->assertEmpty($this->logger->messages); } /** * @covers yii\log\Logger::getDbProfiling() */ public function testGetDbProfiling() { $timings = [ ['duration' => 5], ['duration' => 15], ['duration' => 30], ]; $logger = $this->getMock('yii\\log\\Logger', ['getProfiling']); $logger->method('getProfiling')->willReturn($timings); $logger->expects($this->once()) ->method('getProfiling') ->with($this->equalTo(['yii\db\Command::query', 'yii\db\Command::execute'])); $this->assertEquals([3, 50], $logger->getDbProfiling()); } /** * @covers yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithEmptyMessages() { $this->assertEmpty($this->logger->calculateTimings([])); } /** * @covers yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileNotBeginOrEnd() { $messages = [ ['message0', Logger::LEVEL_ERROR, 'category', 'time', 'trace'], ['message1', Logger::LEVEL_INFO, 'category', 'time', 'trace'], ['message2', Logger::LEVEL_PROFILE, 'category', 'time', 'trace'], ['message3', Logger::LEVEL_TRACE, 'category', 'time', 'trace'], ['message4', Logger::LEVEL_WARNING, 'category', 'time', 'trace'], ]; $this->assertEmpty($this->logger->calculateTimings($messages)); } /** * @covers yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileBeginEnd() { $messages = [ 'anyKey' => ['token', Logger::LEVEL_PROFILE_BEGIN, 'category', 10, 'trace'], 'anyKey2' => ['token', Logger::LEVEL_PROFILE_END, 'category', 15, 'trace'], ]; $this->assertEquals([ [ 'info' => 'token', 'category' => 'category', 'timestamp' => 10, 'trace' => 'trace', 'level' => 0, 'duration' => 5, ] ], $this->logger->calculateTimings($messages) ); } /** * @covers yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileBeginEndAndNestedLevels() { $messages = [ ['firstLevel', Logger::LEVEL_PROFILE_BEGIN, 'firstLevelCategory', 10, 'firstTrace'], ['secondLevel', Logger::LEVEL_PROFILE_BEGIN, 'secondLevelCategory', 15, 'secondTrace'], ['secondLevel', Logger::LEVEL_PROFILE_END, 'secondLevelCategory', 55, 'secondTrace'], ['firstLevel', Logger::LEVEL_PROFILE_END, 'firstLevelCategory', 80, 'firstTrace'], ]; $this->assertEquals([ [ 'info' => 'firstLevel', 'category' => 'firstLevelCategory', 'timestamp' => 10, 'trace' => 'firstTrace', 'level' => 0, 'duration' => 70, ], [ 'info' => 'secondLevel', 'category' => 'secondLevelCategory', 'timestamp' => 15, 'trace' => 'secondTrace', 'level' => 1, 'duration' => 40, ] ], $this->logger->calculateTimings($messages) ); } /** * @covers yii\log\Logger::getElapsedTime() */ public function testGetElapsedTime() { $timeBefore = \microtime(true) - YII_BEGIN_TIME; $actual = $this->logger->getElapsedTime(); $timeAfter = \microtime(true) - YII_BEGIN_TIME; $this->assertGreaterThan($timeBefore, $actual); $this->assertLessThan($timeAfter, $actual); } /** * @covers yii\log\Logger::getLevelName() */ public function testGetLevelName() { $this->assertEquals('info', Logger::getLevelName(Logger::LEVEL_INFO)); $this->assertEquals('error', Logger::getLevelName(Logger::LEVEL_ERROR)); $this->assertEquals('warning', Logger::getLevelName(Logger::LEVEL_WARNING)); $this->assertEquals('trace', Logger::getLevelName(Logger::LEVEL_TRACE)); $this->assertEquals('profile', Logger::getLevelName(Logger::LEVEL_PROFILE)); $this->assertEquals('profile begin', Logger::getLevelName(Logger::LEVEL_PROFILE_BEGIN)); $this->assertEquals('profile end', Logger::getLevelName(Logger::LEVEL_PROFILE_END)); $this->assertEquals('unknown', Logger::getLevelName(0)); } /** * @covers yii\log\Logger::getProfiling() */ public function testGetProfilingWithEmptyCategoriesAndExcludeCategories() { $messages = ['anyData']; $returnValue = 'return value'; $logger = $this->getMock('yii\\log\\Logger', ['calculateTimings']); $logger->messages = $messages; $logger->method('calculateTimings')->willReturn($returnValue); $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals($returnValue, $logger->getProfiling()); } /** * @covers yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesAndNotMatched() { $messages = ['anyData']; $returnValue = [ [ 'info' => 'token', 'category' => 'category', 'timestamp' => 10, 'trace' => 'trace', 'level' => 0, 'duration' => 5, ] ]; $logger = $this->getMock('yii\\log\\Logger', ['calculateTimings']); $logger->messages = $messages; $logger->method('calculateTimings')->willReturn($returnValue); $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([], $logger->getProfiling(['not-matched-category'])); } /** * @covers yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesAndMatched() { $messages = ['anyData']; $matchedByCategoryName = [ 'info' => 'token', 'category' => 'category', 'timestamp' => 10, 'trace' => 'trace', 'level' => 0, 'duration' => 5, ]; $secondCategory = [ 'info' => 'secondToken', 'category' => 'category2', 'timestamp' => 10, 'trace' => 'trace', 'level' => 0, 'duration' => 5, ]; $returnValue = [ 'anyKey' => $matchedByCategoryName, $secondCategory ]; /** * Matched by category name */ $logger = $this->getMock('yii\\log\\Logger', ['calculateTimings']); $logger->messages = $messages; $logger->method('calculateTimings')->willReturn($returnValue); $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$matchedByCategoryName], $logger->getProfiling(['category'])); /** * Matched by prefix */ $logger = $this->getMock('yii\\log\\Logger', ['calculateTimings']); $logger->messages = $messages; $logger->method('calculateTimings')->willReturn($returnValue); $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$matchedByCategoryName, $secondCategory], $logger->getProfiling(['category*'])); } /** * @covers yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesMatchedAndExcludeCategories() { $messages = ['anyData']; $fistCategory = [ 'info' => 'fistToken', 'category' => 'cat', 'timestamp' => 10, 'trace' => 'trace', 'level' => 0, 'duration' => 5, ]; $secondCategory = [ 'info' => 'secondToken', 'category' => 'category2', 'timestamp' => 10, 'trace' => 'trace', 'level' => 0, 'duration' => 5, ]; $returnValue = [ $fistCategory, $secondCategory, [ 'info' => 'anotherToken', 'category' => 'category3', 'timestamp' => 10, 'trace' => 'trace', 'level' => 0, 'duration' => 5, ] ]; /** * Exclude by category name */ $logger = $this->getMock('yii\\log\\Logger', ['calculateTimings']); $logger->messages = $messages; $logger->method('calculateTimings')->willReturn($returnValue); $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$fistCategory, $secondCategory], $logger->getProfiling(['cat*'], ['category3'])); /** * Exclude by category prefix */ $logger = $this->getMock('yii\\log\\Logger', ['calculateTimings']); $logger->messages = $messages; $logger->method('calculateTimings')->willReturn($returnValue); $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$fistCategory], $logger->getProfiling(['cat*'], ['category*'])); } }
bsd-3-clause
kjbartel/clmagma
control/get_nb_tahiti.cpp
7290
/* -- clMAGMA (version 1.3.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2014 @author Stan Tomov @author Mark Gates @author Azzam Haidar */ #include "magma.h" #include "common_magma.h" #ifdef __cplusplus extern "C" { #endif // ==== Definition of blocking sizes for AMD Tahiti cards #ifdef HAVE_clBLAS /* //////////////////////////////////////////////////////////////////////////// -- Return nb for potrf based on m */ magma_int_t magma_get_spotrf_nb( magma_int_t m ) { if (m <= 1024) return 128; else return 320; } magma_int_t magma_get_dpotrf_nb( magma_int_t m ) { if (m <= 4256) return 128; else return 256; } magma_int_t magma_get_cpotrf_nb( magma_int_t m ) { return 128; } magma_int_t magma_get_zpotrf_nb( magma_int_t m ) { return 64; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for geqp3 based on m */ magma_int_t magma_get_sgeqp3_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_dgeqp3_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_cgeqp3_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_zgeqp3_nb( magma_int_t m ) { return 32; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for geqrf based on m */ magma_int_t magma_get_sgeqrf_nb( magma_int_t m ) { if (m < 2000) return 128; else return 128; } magma_int_t magma_get_dgeqrf_nb( magma_int_t m ) { if (m <= 2048) return 64; else return 128; } magma_int_t magma_get_cgeqrf_nb( magma_int_t m ) { if (m <= 2048) return 32; else if (m <= 4032) return 64; else return 128; } magma_int_t magma_get_zgeqrf_nb( magma_int_t m ) { if (m <= 2048) return 32; else if (m <= 4032) return 64; else return 128; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for geqlf based on m */ magma_int_t magma_get_sgeqlf_nb( magma_int_t m ) { return magma_get_sgeqrf_nb(m); } magma_int_t magma_get_dgeqlf_nb( magma_int_t m ) { return magma_get_dgeqrf_nb(m); } magma_int_t magma_get_cgeqlf_nb( magma_int_t m ) { if (m <= 2048) return 32; else if (m <= 4032) return 64; else return 128; } magma_int_t magma_get_zgeqlf_nb( magma_int_t m ) { if (m <= 1024) return 64; else return 128; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for gelqf based on m */ magma_int_t magma_get_sgelqf_nb( magma_int_t m ) { return magma_get_sgeqrf_nb(m); } magma_int_t magma_get_dgelqf_nb( magma_int_t m ) { return magma_get_dgeqrf_nb(m); } magma_int_t magma_get_cgelqf_nb( magma_int_t m ) { if (m <= 2048) return 32; else if (m <= 4032) return 64; else return 128; } magma_int_t magma_get_zgelqf_nb( magma_int_t m ) { if (m <= 1024) return 64; else return 128; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for getrf based on m */ magma_int_t magma_get_sgetrf_nb( magma_int_t m ) { if (m <= 3200) return 128; else if (m < 9000) return 256; else return 320; } magma_int_t magma_get_dgetrf_nb( magma_int_t m ) { if (m <= 2048) return 64; else if (m < 7200) return 192; else return 256; } magma_int_t magma_get_cgetrf_nb( magma_int_t m ) { if (m <= 2048) return 64; else return 128; } magma_int_t magma_get_zgetrf_nb( magma_int_t m ) { if (m <= 3072) return 32; else if (m <= 9024) return 64; else return 128; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for gehrd based on m */ magma_int_t magma_get_sgehrd_nb( magma_int_t m ) { if (m <= 1024) return 32; else return 96; } magma_int_t magma_get_dgehrd_nb( magma_int_t m ) { if (m <= 2048) return 32; else return 64; } magma_int_t magma_get_cgehrd_nb( magma_int_t m ) { if (m <= 1024) return 32; else return 64; } magma_int_t magma_get_zgehrd_nb( magma_int_t m ) { if (m <= 2048) return 32; else return 64; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for sytrd based on m */ magma_int_t magma_get_ssytrd_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_dsytrd_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_chetrd_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_zhetrd_nb( magma_int_t m ) { return 32; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for sytrf based on m */ magma_int_t magma_get_zhetrf_nb( magma_int_t m ) { return 256; } magma_int_t magma_get_chetrf_nb( magma_int_t m ) { return 256; } magma_int_t magma_get_dsytrf_nb( magma_int_t m ) { return 96; } magma_int_t magma_get_ssytrf_nb( magma_int_t m ) { return 256; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for gebrd based on m */ magma_int_t magma_get_sgebrd_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_dgebrd_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_cgebrd_nb( magma_int_t m ) { return 32; } magma_int_t magma_get_zgebrd_nb( magma_int_t m ) { return 32; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for sygst based on m */ magma_int_t magma_get_ssygst_nb( magma_int_t m ) { return 64; } magma_int_t magma_get_dsygst_nb( magma_int_t m ) { return 64; } magma_int_t magma_get_chegst_nb( magma_int_t m ) { return 64; } magma_int_t magma_get_zhegst_nb( magma_int_t m ) { return 64; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for getri based on m */ magma_int_t magma_get_sgetri_nb( magma_int_t m ) { return 64; } magma_int_t magma_get_dgetri_nb( magma_int_t m ) { return 64; } magma_int_t magma_get_cgetri_nb( magma_int_t m ) { return 64; } magma_int_t magma_get_zgetri_nb( magma_int_t m ) { return 64; } /* //////////////////////////////////////////////////////////////////////////// -- Return nb for gesvd based on m */ magma_int_t magma_get_sgesvd_nb( magma_int_t m ) { return magma_get_sgebrd_nb(m); } magma_int_t magma_get_dgesvd_nb( magma_int_t m ) { return magma_get_dgebrd_nb(m); } magma_int_t magma_get_cgesvd_nb( magma_int_t m ) { return magma_get_cgebrd_nb(m); } magma_int_t magma_get_zgesvd_nb( magma_int_t m ) { return magma_get_zgebrd_nb(m); } /* //////////////////////////////////////////////////////////////////////////// -- Return smlsiz for the divide and conquewr routine dlaex0 dstedx zstedx */ magma_int_t magma_get_smlsize_divideconquer() { return 128; } #endif // HAVE_clBLAS #ifdef __cplusplus } // extern "C" #endif
bsd-3-clause
desmond1121/fresco
imagepipeline/src/test/java/com/facebook/imagepipeline/producers/ResizeAndRotateProducerTest.java
22249
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.imagepipeline.producers; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.TimeUnit; import android.net.Uri; import android.os.SystemClock; import com.facebook.common.executors.UiThreadImmediateExecutorService; import com.facebook.common.memory.PooledByteBuffer; import com.facebook.common.memory.PooledByteBufferFactory; import com.facebook.common.memory.PooledByteBufferOutputStream; import com.facebook.common.references.CloseableReference; import com.facebook.common.soloader.SoLoaderShim; import com.facebook.imageformat.DefaultImageFormats; import com.facebook.imageformat.ImageFormat; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.common.RotationOptions; import com.facebook.imagepipeline.image.EncodedImage; import com.facebook.imagepipeline.nativecode.JpegTranscoder; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.testing.FakeClock; import com.facebook.imagepipeline.testing.TestExecutorService; import com.facebook.imagepipeline.testing.TestScheduledExecutorService; import com.facebook.imagepipeline.testing.TrivialPooledByteBuffer; import org.junit.*; import org.junit.runner.*; import org.mockito.Mock; import org.mockito.*; import org.mockito.invocation.*; import org.mockito.stubbing.*; import org.powermock.api.mockito.*; import org.powermock.core.classloader.annotations.*; import org.powermock.modules.junit4.rule.*; import org.robolectric.*; import org.robolectric.annotation.*; import static com.facebook.imagepipeline.producers.ResizeAndRotateProducer.calculateDownsampleNumerator; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" }) @Config(manifest= Config.NONE) @PrepareOnlyThisForTest({JpegTranscoder.class, SystemClock.class, UiThreadImmediateExecutorService.class}) public class ResizeAndRotateProducerTest { static { SoLoaderShim.setInTestMode(); } @Mock public Producer mInputProducer; @Mock public ImageRequest mImageRequest; @Mock public ProducerListener mProducerListener; @Mock public Consumer<EncodedImage> mConsumer; @Mock public ProducerContext mProducerContext; @Mock public PooledByteBufferFactory mPooledByteBufferFactory; @Mock public PooledByteBufferOutputStream mPooledByteBufferOutputStream; @Rule public PowerMockRule rule = new PowerMockRule(); private static final int MIN_TRANSFORM_INTERVAL_MS = ResizeAndRotateProducer.MIN_TRANSFORM_INTERVAL_MS; private TestExecutorService mTestExecutorService; private ResizeAndRotateProducer mResizeAndRotateProducer; private Consumer<EncodedImage> mResizeAndRotateProducerConsumer; private CloseableReference<PooledByteBuffer> mIntermediateResult; private CloseableReference<PooledByteBuffer> mFinalResult; private PooledByteBuffer mPooledByteBuffer; private FakeClock mFakeClockForWorker; private FakeClock mFakeClockForScheduled; private TestScheduledExecutorService mTestScheduledExecutorService; private UiThreadImmediateExecutorService mUiThreadImmediateExecutorService; private EncodedImage mIntermediateEncodedImage; private EncodedImage mFinalEncodedImage; @Before public void setUp() { MockitoAnnotations.initMocks(this); mFakeClockForWorker = new FakeClock(); mFakeClockForScheduled = new FakeClock(); mFakeClockForWorker.incrementBy(1000); mFakeClockForScheduled.incrementBy(1000); PowerMockito.mockStatic(SystemClock.class); when(SystemClock.uptimeMillis()).thenAnswer( new Answer<Long>() { @Override public Long answer(InvocationOnMock invocation) throws Throwable { return mFakeClockForWorker.now(); } }); when(mImageRequest.getSourceUri()).thenReturn(Uri.parse("http://testuri")); mTestExecutorService = new TestExecutorService(mFakeClockForWorker); mTestScheduledExecutorService = new TestScheduledExecutorService(mFakeClockForScheduled); mUiThreadImmediateExecutorService = mock(UiThreadImmediateExecutorService.class); when(mUiThreadImmediateExecutorService.schedule( any(Runnable.class), anyLong(), any(TimeUnit.class))) .thenAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return mTestScheduledExecutorService.schedule( (Runnable) invocation.getArguments()[0], (long) invocation.getArguments()[1], (TimeUnit) invocation.getArguments()[2]); } }); PowerMockito.mockStatic(UiThreadImmediateExecutorService.class); when(UiThreadImmediateExecutorService.getInstance()).thenReturn( mUiThreadImmediateExecutorService); PowerMockito.mockStatic(JpegTranscoder.class); PowerMockito.when(JpegTranscoder.isRotationAngleAllowed(anyInt())).thenCallRealMethod(); mTestExecutorService = new TestExecutorService(mFakeClockForWorker); when(mProducerContext.getImageRequest()).thenReturn(mImageRequest); when(mProducerContext.getListener()).thenReturn(mProducerListener); when(mProducerListener.requiresExtraMap(anyString())).thenReturn(true); mIntermediateResult = CloseableReference.of(mock(PooledByteBuffer.class)); mFinalResult = CloseableReference.of(mock(PooledByteBuffer.class)); mResizeAndRotateProducerConsumer = null; doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { mResizeAndRotateProducerConsumer = (Consumer<EncodedImage>) invocation.getArguments()[0]; return null; } }).when(mInputProducer).produceResults(any(Consumer.class), any(ProducerContext.class)); doReturn(mPooledByteBufferOutputStream).when(mPooledByteBufferFactory).newOutputStream(); mPooledByteBuffer = new TrivialPooledByteBuffer(new byte[]{1}, 0); doReturn(mPooledByteBuffer).when(mPooledByteBufferOutputStream).toByteBuffer(); } @Test public void testDoesNotTransformIfImageRotationAngleUnkown() { whenResizingEnabled(); whenRequestSpecificRotation(RotationOptions.NO_ROTATION); provideIntermediateResult( DefaultImageFormats.JPEG, 800, 800, EncodedImage.UNKNOWN_ROTATION_ANGLE); verifyIntermediateResultPassedThroughUnchanged(); provideFinalResult(DefaultImageFormats.JPEG, 800, 800, EncodedImage.UNKNOWN_ROTATION_ANGLE); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesNotTransformIfRotationDisabled() { whenResizingEnabled(); whenDisableRotation(); provideIntermediateResult(DefaultImageFormats.JPEG); verifyIntermediateResultPassedThroughUnchanged(); provideFinalResult(DefaultImageFormats.JPEG); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesNotTransformIfMetadataAngleAndRequestedRotationHaveOppositeValues() { whenResizingEnabled(); whenRequestSpecificRotation(RotationOptions.ROTATE_270); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 90); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesNotTransformIfNotRequested() { whenResizingDisabled(); whenRequestsRotationFromMetadataWithoutDeferring(); provideIntermediateResult(DefaultImageFormats.JPEG); verifyIntermediateResultPassedThroughUnchanged(); provideFinalResult(DefaultImageFormats.JPEG); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesNotTransformIfNotJpeg() throws Exception { whenResizingEnabled(); whenRequestsRotationFromMetadataWithoutDeferring(); provideIntermediateResult(DefaultImageFormats.WEBP_SIMPLE); verifyIntermediateResultPassedThroughUnchanged(); provideFinalResult(DefaultImageFormats.WEBP_SIMPLE); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesRotateIfJpegAndCannotDeferRotationAndResizingDisabled() throws Exception { whenResizingDisabled(); testDoesRotateIfJpegAndCannotDeferRotation(); } @Test public void testDoesRotateIfJpegAndCannotDeferRotationAndResizingEnabled() throws Exception { whenResizingEnabled(); testDoesRotateIfJpegAndCannotDeferRotation(); } private void testDoesRotateIfJpegAndCannotDeferRotation() throws Exception { int rotationAngle = 180; int sourceWidth = 10; int sourceHeight = 10; whenRequestWidthAndHeight(sourceWidth, sourceHeight); whenRequestsRotationFromMetadataWithoutDeferring(); provideIntermediateResult(DefaultImageFormats.JPEG, sourceWidth, sourceHeight, rotationAngle); verifyNoIntermediateResultPassedThrough(); provideFinalResult(DefaultImageFormats.JPEG, sourceWidth, sourceHeight, rotationAngle); verifyAFinalResultPassedThrough(); assertEquals(2, mFinalResult.getUnderlyingReferenceTestOnly().getRefCountTestOnly()); assertTrue(mPooledByteBuffer.isClosed()); verifyJpegTranscoderInteractions(8, rotationAngle); } @Test public void testDoesNotRotateIfCanDeferRotationAndResizeNotNeeded() throws Exception { whenResizingEnabled(); int rotationAngle = 180; int sourceWidth = 10; int sourceHeight = 10; whenRequestWidthAndHeight(sourceWidth, sourceHeight); whenRequestsRotationFromMetadataWithDeferringAllowed(); provideIntermediateResult(DefaultImageFormats.JPEG, sourceWidth, sourceHeight, rotationAngle); verifyIntermediateResultPassedThroughUnchanged(); provideFinalResult(DefaultImageFormats.JPEG, sourceWidth, sourceHeight, rotationAngle); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesResizeAndRotateIfCanDeferRotationButResizeIsNeeded() throws Exception { whenResizingEnabled(); int rotationAngle = 90; int sourceWidth = 10; int sourceHeight = 10; whenRequestWidthAndHeight(sourceWidth, sourceHeight); whenRequestsRotationFromMetadataWithDeferringAllowed(); provideIntermediateResult( DefaultImageFormats.JPEG, sourceWidth * 2, sourceHeight * 2, rotationAngle); verifyNoIntermediateResultPassedThrough(); provideFinalResult(DefaultImageFormats.JPEG, sourceWidth * 2, sourceHeight * 2, rotationAngle); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(4, rotationAngle); } @Test public void testDoesResizeIfJpegAndResizingEnabled() throws Exception { whenResizingEnabled(); final int preferredWidth = 300; final int preferredHeight = 600; whenRequestWidthAndHeight(preferredWidth, preferredHeight); whenRequestSpecificRotation(RotationOptions.NO_ROTATION); provideIntermediateResult(DefaultImageFormats.JPEG, preferredWidth * 2, preferredHeight * 2, 0); verifyNoIntermediateResultPassedThrough(); provideFinalResult(DefaultImageFormats.JPEG, preferredWidth * 2, preferredHeight * 2, 0); verifyAFinalResultPassedThrough(); assertEquals(2, mFinalResult.getUnderlyingReferenceTestOnly().getRefCountTestOnly()); assertTrue(mPooledByteBuffer.isClosed()); verifyJpegTranscoderInteractions(4, 0); } @Test public void testDoesNotResizeIfJpegButResizingDisabled() throws Exception { whenResizingDisabled(); final int preferredWidth = 300; final int preferredHeight = 600; whenRequestWidthAndHeight(preferredWidth, preferredHeight); whenRequestSpecificRotation(RotationOptions.NO_ROTATION); provideIntermediateResult(DefaultImageFormats.JPEG, preferredWidth * 2, preferredHeight * 2, 0); verifyIntermediateResultPassedThroughUnchanged(); provideFinalResult(DefaultImageFormats.JPEG, preferredWidth * 2, preferredHeight * 2, 0); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesNotUpscale() { whenResizingEnabled(); whenRequestWidthAndHeight(150, 150); whenRequestSpecificRotation(RotationOptions.NO_ROTATION); provideFinalResult(DefaultImageFormats.JPEG, 100, 100, 0); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesNotUpscaleWhenRotating() { whenResizingEnabled(); whenRequestWidthAndHeight(150, 150); whenRequestsRotationFromMetadataWithoutDeferring(); provideFinalResult(DefaultImageFormats.JPEG, 100, 100, 90); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(8, 90); } @Test public void testDoesComputeRightNumeratorWhenRotating_0() { whenResizingEnabled(); whenRequestWidthAndHeight(50, 100); whenRequestsRotationFromMetadataWithoutDeferring(); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 0); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(4, 0); } @Test public void testDoesComputeRightNumeratorWhenRotating_90() { whenResizingEnabled(); whenRequestWidthAndHeight(50, 100); whenRequestsRotationFromMetadataWithoutDeferring(); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 90); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(2, 90); } @Test public void testDoesComputeRightNumeratorWhenRotating_180() { whenResizingEnabled(); whenRequestWidthAndHeight(50, 100); whenRequestsRotationFromMetadataWithoutDeferring(); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 180); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(4, 180); } @Test public void testDoesComputeRightNumeratorWhenRotating_270() { whenResizingEnabled(); whenRequestWidthAndHeight(50, 100); whenRequestsRotationFromMetadataWithoutDeferring(); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 270); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(2, 270); } @Test public void testDoesRotateWhenNoResizeOptionsIfCannotBeDeferred() { whenResizingEnabled(); whenRequestWidthAndHeight(0, 0); whenRequestsRotationFromMetadataWithoutDeferring(); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 90); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(8, 90); } @Test public void testDoesNotRotateWhenNoResizeOptionsAndCanBeDeferred() { whenResizingEnabled(); whenRequestWidthAndHeight(0, 0); whenRequestsRotationFromMetadataWithDeferringAllowed(); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 90); verifyFinalResultPassedThroughUnchanged(); verifyZeroJpegTranscoderInteractions(); } @Test public void testDoesRotateWhenSpecificRotationRequested() { whenResizingEnabled(); whenRequestWidthAndHeight(200, 400); whenRequestSpecificRotation(RotationOptions.ROTATE_270); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 0); verifyAFinalResultPassedThrough(); verifyJpegTranscoderInteractions(8, 270); } @Test public void testDoesNothingWhenNotAskedToDoAnything() { whenResizingEnabled(); whenRequestWidthAndHeight(0, 0); whenDisableRotation(); provideFinalResult(DefaultImageFormats.JPEG, 400, 200, 90); verifyAFinalResultPassedThrough(); verifyZeroJpegTranscoderInteractions(); } @Test public void testRoundNumerator() { assertEquals(1, ResizeAndRotateProducer.roundNumerator( 1.0f/8, ResizeOptions.DEFAULT_ROUNDUP_FRACTION)); assertEquals(1, ResizeAndRotateProducer.roundNumerator( 5.0f/32, ResizeOptions.DEFAULT_ROUNDUP_FRACTION)); assertEquals(1, ResizeAndRotateProducer.roundNumerator( 1.0f/6 - 0.01f, ResizeOptions.DEFAULT_ROUNDUP_FRACTION)); assertEquals(2, ResizeAndRotateProducer.roundNumerator( 1.0f/6, ResizeOptions.DEFAULT_ROUNDUP_FRACTION)); assertEquals(2, ResizeAndRotateProducer.roundNumerator( 3.0f/16, ResizeOptions.DEFAULT_ROUNDUP_FRACTION)); assertEquals(2, ResizeAndRotateProducer.roundNumerator( 2.0f/8, ResizeOptions.DEFAULT_ROUNDUP_FRACTION)); } @Test public void testDownsamplingRatioUsage() { assertEquals(8, calculateDownsampleNumerator(1)); assertEquals(4, calculateDownsampleNumerator(2)); assertEquals(2, calculateDownsampleNumerator(4)); assertEquals(1, calculateDownsampleNumerator(8)); assertEquals(1, calculateDownsampleNumerator(16)); assertEquals(1, calculateDownsampleNumerator(32)); } @Test public void testResizeRatio() { ResizeOptions resizeOptions = new ResizeOptions(512, 512); assertEquals( 0.5f, ResizeAndRotateProducer.determineResizeRatio(resizeOptions, 1024, 1024), 0.01); assertEquals( 0.25f, ResizeAndRotateProducer.determineResizeRatio(resizeOptions, 2048, 4096), 0.01); assertEquals( 0.5f, ResizeAndRotateProducer.determineResizeRatio(resizeOptions, 4096, 512), 0.01); } private void verifyIntermediateResultPassedThroughUnchanged() { verify(mConsumer).onNewResult(mIntermediateEncodedImage, false); } private void verifyNoIntermediateResultPassedThrough() { verify(mConsumer, never()).onNewResult(any(EncodedImage.class), eq(false)); } private void verifyFinalResultPassedThroughUnchanged() { verify(mConsumer).onNewResult(mFinalEncodedImage, true); } private void verifyAFinalResultPassedThrough() { verify(mConsumer).onNewResult(any(EncodedImage.class), eq(true)); } private static void verifyJpegTranscoderInteractions(int numerator, int rotationAngle) { PowerMockito.verifyStatic(); try { JpegTranscoder.transcodeJpeg( any(InputStream.class), any(OutputStream.class), eq(rotationAngle), eq(numerator), eq(ResizeAndRotateProducer.DEFAULT_JPEG_QUALITY)); } catch (IOException ioe) { throw new RuntimeException(ioe); } } private static void verifyZeroJpegTranscoderInteractions() { PowerMockito.verifyStatic(never()); try { JpegTranscoder.transcodeJpeg( any(InputStream.class), any(OutputStream.class), anyInt(), anyInt(), anyInt()); } catch (IOException ioe) { throw new RuntimeException(ioe); } } private void provideIntermediateResult(ImageFormat imageFormat) { provideIntermediateResult(imageFormat, 800, 800, 0); } private void provideIntermediateResult( ImageFormat imageFormat, int width, int height, int rotationAngle) { mIntermediateEncodedImage = buildEncodedImage(mIntermediateResult, imageFormat, width, height, rotationAngle); mResizeAndRotateProducerConsumer.onNewResult(mIntermediateEncodedImage, false); } private void provideFinalResult(ImageFormat imageFormat) { provideFinalResult(imageFormat, 800, 800, 0); } private void provideFinalResult( ImageFormat imageFormat, int width, int height, int rotationAngle) { mFinalEncodedImage = buildEncodedImage(mFinalResult, imageFormat, width, height, rotationAngle); mResizeAndRotateProducerConsumer.onNewResult(mFinalEncodedImage, true); mFakeClockForScheduled.incrementBy(MIN_TRANSFORM_INTERVAL_MS); mFakeClockForWorker.incrementBy(MIN_TRANSFORM_INTERVAL_MS); } private static EncodedImage buildEncodedImage( CloseableReference<PooledByteBuffer> pooledByteBufferRef, ImageFormat imageFormat, int width, int height, int rotationAngle) { EncodedImage encodedImage = new EncodedImage(pooledByteBufferRef); encodedImage.setImageFormat(imageFormat); encodedImage.setRotationAngle(rotationAngle); encodedImage.setWidth(width); encodedImage.setHeight(height); return encodedImage; } private void whenResizingEnabled() { whenResizingEnabledIs(true); } private void whenResizingDisabled() { whenResizingEnabledIs(false); } private void whenResizingEnabledIs(boolean resizingEnabled) { mResizeAndRotateProducer = new ResizeAndRotateProducer( mTestExecutorService, mPooledByteBufferFactory, resizingEnabled, mInputProducer, false); mResizeAndRotateProducer.produceResults(mConsumer, mProducerContext); } private void whenRequestWidthAndHeight(int preferredWidth, int preferredHeight) { when(mImageRequest.getPreferredWidth()).thenReturn(preferredWidth); when(mImageRequest.getPreferredHeight()).thenReturn(preferredHeight); ResizeOptions resizeOptions = null; if (preferredWidth > 0 || preferredHeight > 0) { resizeOptions = new ResizeOptions(preferredWidth, preferredHeight); } when(mImageRequest.getResizeOptions()).thenReturn(resizeOptions); } private void whenRequestSpecificRotation( @RotationOptions.RotationAngle int rotationAngle) { when(mImageRequest.getRotationOptions()) .thenReturn(RotationOptions.forceRotation(rotationAngle)); } private void whenDisableRotation() { when(mImageRequest.getRotationOptions()) .thenReturn(RotationOptions.disableRotation()); } private void whenRequestsRotationFromMetadataWithDeferringAllowed() { when(mImageRequest.getRotationOptions()) .thenReturn(RotationOptions.autoRotateAtRenderTime()); } private void whenRequestsRotationFromMetadataWithoutDeferring() { when(mImageRequest.getRotationOptions()) .thenReturn(RotationOptions.autoRotate()); } }
bsd-3-clause
bredy/gooddata-js
test/xhr_test.js
15135
// Copyright (C) 2007-2013, GoodData(R) Corporation. All rights reserved. define(['gooddata', 'jquery'], function(gd, $) { describe("xhr", function() { before(function() { xhr = gd.xhr; }); /* $.ajax returns jqXhr object with deferred interface this add jqXhr properties according to options to simulate jqXhr */ function fakeJqXhr(options, d) { for (var i = 0; i < d.length; i++) { $.extend(d[i], options); } } var d = [], expects = []; beforeEach(function() { var mock = sinon.mock($); /** mock result for first three calls of $.ajax */ for (var i = 0; i < 3; i++) { d.push($.Deferred()); expects.push(mock.expects('ajax').returns(d[i])); } }); afterEach(function() { d = []; expects = []; if ($.ajax.restore) $.ajax.restore(); }); function mockResponse(status, headers) { return { status: status, getResponseHeader: function(header) { return headers ? headers[header] : null; } }; } describe('$.ajax request', function() { it('should handle successful request', function(done) { xhr.ajax('/some/url').done(function(data, textStatus, xhr) { expect(expects[0].calledOnce).to.be.ok(); expect(data).to.be('Hello'); expect(xhr.status).to.be(200); done(); }); var settings = expects[0].lastCall.args[0]; expect(settings.url).to.be('/some/url'); expect(settings.contentType).to.be('application/json'); d[0].resolve('Hello', '', mockResponse(200)); }); it('should stringify JSON data for GDC backend', function(done) { xhr.ajax('/some/url', { type: 'post', data: { foo: 'bar'} }).done(function(data, textStatus, xhr) { done(); }); var settings = expects[0].lastCall.args[0]; expect(settings.data).to.be('{"foo":"bar"}'); d[0].resolve('Ok', '', mockResponse(200)); }); it('should handle unsuccessful request', function(done) { xhr.ajax('/some/url').fail(function(xhr) { expect(expects[0].calledOnce).to.be.ok(); expect(xhr.status).to.be(404); done(); }); d[0].reject(mockResponse(404)); }); it('should support url in settings', function(done) { xhr.ajax({ url: '/some/url'}).done(function(data, textStatus, xhr) { expect(expects[0].calledOnce).to.be.ok(); expect(xhr.status).to.be(200); done(); }); var settings = expects[0].lastCall.args[0]; expect(settings.url).to.be('/some/url'); d[0].resolve('Hello', '', mockResponse(200)); }); it('should work with sucess callback in settings', function(done) { xhr.ajax({ url: '/some/url', success: function(data, textStatus, xhr) { expect(data).to.be('Hello'); expect(xhr.status).to.be(200); done(); }}); d[0].resolve('Hello', '', mockResponse(200)); }); it('should work with error callback in settings', function(done) { xhr.ajax({ url: '/some/url', error: function(xhr, textStatus, err) { expect(xhr.status, 404); done(); }}); d[0].reject(mockResponse(404)); }); it('should work with complete callback in settings for success', function(done) { xhr.ajax({ url: '/some/url', complete: function() { done(); }}); d[0].resolve('Hello', '', { status: 200}); }); it('should work with complete callback in settings for failure', function(done) { xhr.ajax({ url: '/some/url', complete: function() { done(); }}); d[0].reject(mockResponse(404)); }); it('should have accept header set on application/json', function() { xhr.ajax({ url: '/some/url'}).done(function(data, textStatus, xhr) { expect(expects[0].calledOnce).to.be.ok(); expect(xhr.status).to.be(200); done(); }); var settings = expects[0].lastCall.args[0]; expect(settings.headers.Accept).to.be("application/json; charset=utf-8"); }); }); describe('$.ajax unathorized handling', function() { it('should renew token when TT expires', function(done) { var options = { url: '/some/url'}; xhr.ajax(options).done(function(data, textStatus, xhr) { expect(expects[2].calledOnce).to.be.ok(); expect(xhr.status).to.be(200); expect(data).to.be('Hello'); done(); }); fakeJqXhr(options, d); d[0].reject(mockResponse(401)); //first request d[1].resolve({}, '', mockResponse(200)); //token request d[2].resolve('Hello', '', mockResponse(200)); //request retry }); it('should fail if token renewal fails and unathorize handler is not set', function(done) { var options = { url: '/some/url'}; xhr.ajax(options).fail(function(xhr) { expect(xhr.status).to.be(401); expect(expects[1].calledOnce).to.be.ok(); expect(expects[2].notCalled).to.be.ok(); done(); }); fakeJqXhr(options, d); d[0].reject(mockResponse(401)); //first request d[1].reject(mockResponse(401)); //token request }); it('should invole unathorized handler is token request fail', function(done) { var options = { url: '/some/url', unauthorized: function(xhr) { expect(xhr.status).to.be(401); expect(expects[1].calledOnce).to.be.ok(); expect(expects[2].notCalled).to.be.ok(); done(); } }; fakeJqXhr(options, d); xhr.ajax(options); d[0].reject(mockResponse(401)); //first request d[1].reject(mockResponse(401)); //token request }); it('should correctly handle multiple requests with token request in progress', function(done) { var optionsFirst = { url: '/some/url/1' }; var optionsSecond = { url: '/some/url/2' }; $.extend(d[0], optionsFirst); $.extend(d[1], optionsSecond); xhr.ajax(optionsFirst); d[0].reject(mockResponse(401)); // now, token request should be in progress // so this "failure" should continue after // token request and should correctly fail xhr.ajax(optionsSecond).fail(function(xhr) { expect(xhr.status).to.be(403); done(); }); // simulate token request failed d[1].reject(mockResponse(403)); }); }); describe('$.ajax polling', function() { it('should retry request after delay', function(done) { var options = { url: '/some/url', pollDelay: 0 }; fakeJqXhr(options, d); xhr.ajax(options).done(function(data) { expect(data).to.be('OK'); expect(expects[0].lastCall.args[0].method).to.be('GET'); expect(expects[1].lastCall.args[0].method).to.be('GET'); expect(expects[2].lastCall.args[0].method).to.be('GET'); done(); }); d[0].resolve(null, '', mockResponse(202)); d[1].resolve(null, '', mockResponse(202)); d[2].resolve('OK', '', mockResponse(200)); }); it('should not poll if client forbids it', function(done) { var options = { url: '/some/url', pollDelay: 0, dontPollOnResult: true }; fakeJqXhr(options, d); xhr.ajax(options).done(function(data) { expect(data).to.be('FIRST_RESPONSE'); expect(expects[0].calledOnce).to.be.ok(); expect(expects[1].notCalled).to.be.ok(); expect(expects[2].notCalled).to.be.ok(); expect(expects[0].lastCall.args[0].method).to.be(undefined); done(); }); d[0].resolve('FIRST_RESPONSE', '', mockResponse(202)); d[1].resolve('SECOND_RESPONSE', '', mockResponse(202)); d[2].resolve('THIRD_RESPONSE', '', mockResponse(200)); }); it('should correctly reject after retry 404', function(done) { var options = { url: '/some/url', pollDelay: 0 }; fakeJqXhr(options, d); xhr.ajax(options).fail(function(xhr) { expect(xhr.status).to.be(404); done(); }); d[0].resolve(null, '', mockResponse(202)); d[1].resolve(null, '', mockResponse(202)); d[2].reject(mockResponse(404)); }); }); describe('$.ajax polling with different location', function() { it('should retry request after delay', function(done) { var options = { url: '/some/url', pollDelay: 0 }; fakeJqXhr(options, d); xhr.ajax(options).done(function(data) { expect(data).to.be('OK'); expect(expects[0].lastCall.args[0].method).to.be('GET'); expect(expects[1].lastCall.args[0].method).to.be('GET'); expect(expects[2].lastCall.args[0].method).to.be('GET'); expect(expects[2].lastCall.args[0].url).to.be('/other/url'); done(); }); d[0].resolve(null, '', mockResponse(202, {'Location': '/other/url'})); d[1].resolve(null, '', mockResponse(202, {'Location': '/other/url'})); d[2].resolve('OK', '', mockResponse(200)); }); it('should folow multiple redirects', function(done) { var options = { url: '/some/url', pollDelay: 0 }; fakeJqXhr(options, d); xhr.ajax(options).done(function(data) { expect(data).to.be('OK'); expect(expects[2].lastCall.args[0].url).to.be('/other/url2'); done(); }); d[0].resolve(null, '', mockResponse(202, {'Location': '/other/url'})); d[1].resolve(null, '', mockResponse(202, {'Location': '/other/url2'})); d[2].resolve('OK', '', mockResponse(200)); }); it('should correctly reject after retry 404', function(done) { var options = { url: '/some/url', pollDelay: 0 }; fakeJqXhr(options, d); xhr.ajax(options).fail(function(xhr) { expect(xhr.status).to.be(404); done(); }); d[0].resolve(null, '', mockResponse(202, {'Location': '/other/url'})); d[1].resolve(null, '', mockResponse(202, {'Location': '/other/url'})); d[2].reject(mockResponse(404)); }); }); describe('shortcut methods', function() { before(function() { sinon.stub(xhr, 'ajax'); }); after(function() { xhr.ajax.restore(); }); beforeEach(function() { xhr.ajax.reset(); }); it('should call xhr.ajax with get method', function() { xhr.get('url', { contentType: 'text/csv' }); expect(xhr.ajax.getCall(0).args).to.be.eql(['url', { method: 'GET', contentType: 'text/csv' }]); }); it('should call xhr.ajax with post method', function() { var data = { message: 'THIS IS SPARTA!' }; xhr.post('url', { data: data, contentType: 'text/csv' }); expect(xhr.ajax.getCall(0).args).to.be.eql(['url', { method: 'POST', data: data, contentType: 'text/csv' }]); }); }); describe('enrichSettingWithCustomDomain', function() { it('should not touch settings if no domain set', function() { var settings = { url: '/test1' }, res = xhr.enrichSettingWithCustomDomain(settings, undefined); expect(res.url).to.be('/test1'); expect(res.xhrFields).to.be(undefined); }); it('should add domain before url', function() { var settings = { url: '/test1' }, res = xhr.enrichSettingWithCustomDomain(settings, 'https://domain.tld'); expect(res.url).to.be('https://domain.tld/test1'); expect(res.xhrFields).to.eql({ withCredentials: true }); }); it('should not double domain in settings url', function() { var settings = { url: 'https://domain.tld/test1' }, res = xhr.enrichSettingWithCustomDomain(settings, 'https://domain.tld'); expect(res.url).to.be('https://domain.tld/test1'); expect(res.xhrFields).to.eql({ withCredentials: true }); }); }); }); });
bsd-3-clause
e-dukan/spree_invoice_print
lib/generators/spree_invoice_print/install/install_generator.rb
1215
module SpreeInvoicePrint module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_javascripts append_file 'app/assets/javascripts/store/all.js', "//= require store/spree_invoice_print\n" append_file 'app/assets/javascripts/admin/all.js', "//= require admin/spree_invoice_print\n" end def add_stylesheets inject_into_file 'app/assets/stylesheets/store/all.css', " *= require store/spree_invoice_print\n", :before => /\*\//, :verbose => true inject_into_file 'app/assets/stylesheets/admin/all.css', " *= require admin/spree_invoice_print\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_invoice_print' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
bsd-3-clause
go-hep/hplot
vgshiny/vg.go
2727
// Copyright 2016 The go-hep 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 vgshiny provides a vg.Canvas implementation backed by a shiny/screen.Window package vgshiny // import "github.com/go-hep/hplot/vgshiny" import ( "image" "image/color" "image/draw" "github.com/gonum/plot/vg" "github.com/gonum/plot/vg/vgimg" "golang.org/x/exp/shiny/screen" "golang.org/x/mobile/event/key" "golang.org/x/mobile/event/paint" ) // Canvas implements the vg.Canvas interface, // drawing to a shiny.screen/Window buffer. type Canvas struct { *vgimg.Canvas win screen.Window buf screen.Buffer img draw.Image } // New creates a new canvas with the given width and height. func New(s screen.Screen, w, h vg.Length) (*Canvas, error) { ww := w / vg.Inch * vg.Length(vgimg.DefaultDPI) hh := h / vg.Inch * vg.Length(vgimg.DefaultDPI) size := image.Pt(int(ww+0.5), int(hh+0.5)) img := draw.Image(image.NewRGBA(image.Rect(0, 0, size.X, size.Y))) cc := vgimg.NewWith(vgimg.UseImage(img)) win, err := s.NewWindow(&screen.NewWindowOptions{ Width: size.X, Height: size.Y, }) if err != nil { return nil, err } buf, err := s.NewBuffer(size) if err != nil { return nil, err } return &Canvas{ win: win, buf: buf, Canvas: cc, img: img, }, nil } // Paint paints the canvas' content on the screen. func (c *Canvas) Paint() screen.PublishResult { w, h := c.Size() rect := image.Rect(0, 0, int(w), int(h)) sr := c.img.Bounds() c.win.Fill(rect, color.Black, draw.Src) draw.Draw(c.buf.RGBA(), c.buf.Bounds(), c.img, image.Point{}, draw.Src) c.win.Upload(image.Point{}, c.buf, sr) return c.win.Publish() } // Release releases shiny/screen resources. func (c *Canvas) Release() { c.buf.Release() c.win.Release() c.buf = nil c.win = nil } // Send sends an event to the underlying shiny window. func (c *Canvas) Send(evt interface{}) { c.win.Send(evt) } // Run runs the function f for each event on the event queue of the underlying shiny window. // f is expected to return true to continue processing events and false otherwise. // If f is nil, a default processing function will be used. // The default processing functions handles paint.Event events and exits when 'q' or 'ESC' are pressed. func (c *Canvas) Run(f func(e interface{}) bool) { if f == nil { f = func(e interface{}) bool { switch e := e.(type) { case paint.Event: c.Paint() case key.Event: switch e.Code { case key.CodeEscape, key.CodeQ: if e.Direction == key.DirPress { return false } } } return true } } for { e := c.win.NextEvent() if !f(e) { return } } }
bsd-3-clause
jbcisne/zf2Agenda
module/Contato/src/Contato/View/Helper/MenuAtivo.php
429
<?php namespace Contato\View\Helper; use Zend\View\Helper\AbstractHelper; use Zend\Http\Request; class MenuAtivo extends AbstractHelper { protected $request; public function __construct(Request $request) { $this->request = $request; } public function __invoke($url_menu = '') { return $this->request->getUri()->getPath() == $url_menu ? 'class="active"' : ''; } }
bsd-3-clause
troikaitsulutions/templeadvisor
themes/be/views/becategory/category_update.php
162
<?php $this->pageTitle=t('Update Category Info'); $this->titleImage='images/pencil2.png'; $this->widget('cmswidgets.category.CategoryUpdateWidget',array()); ?>
bsd-3-clause
Icybee/module-sites
lib/Helpers/ResolveSite.php
2946
<?php /* * This file is part of the Icybee package. * * (c) Olivier Laviale <olivier.laviale@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Icybee\Modules\Sites\Helpers; use ICanBoogie\ActiveRecord; use ICanBoogie\Core; use Icybee\Modules\Sites\Site; /** * Resolves best matching site. */ class ResolveSite { /** * @var callable */ private $sites_provider; /** * @var callable|null */ private $mock_initializer; /** * @param callable $sites_provider * @param callable|null $mock_initializer */ public function __construct(callable $sites_provider, callable $mock_initializer = null) { $this->sites_provider = $sites_provider; $this->mock_initializer = $mock_initializer; } /** * @param string $host * @param string $path * * @return Site * * @throws ActiveRecord\Exception */ public function __invoke($host, $path) { $sites = $this->retrieve_sites(); return ($sites ? $this->find_best_match($host, $path, $sites) : null) ?: $this->mock_site(); } /** * @return Site[] * * @throws ActiveRecord\Exception */ protected function retrieve_sites() { try { $provider = $this->sites_provider; return $provider(); } catch (ActiveRecord\Exception $e) { throw $e; } catch (\Exception $e) { return []; } } /** * Find best site match. * * @param string $host * @param string $path * @param array $sites * * @return Site|null */ protected function find_best_match($host, $path, array $sites) { $parts = array_reverse(explode('.', $host)); $tld = null; $domain = null; $subdomain = null; if (isset($parts[0])) { $tld = $parts[0]; } if (isset($parts[1])) { $domain = $parts[1]; } if (isset($parts[2])) { $subdomain = implode('.', array_slice($parts, 2)); } $match = null; $match_score = -1; foreach ($sites as $site) { $score = 0; if ($site->tld) { $score += ($site->tld == $tld) ? 1000 : -1000; } if ($site->domain) { $score += ($site->domain == $domain) ? 100 : -100; } if ($site->subdomain) { $score += ($site->subdomain == $subdomain || (!$site->subdomain && $subdomain == 'www')) ? 10 : -10; } $site_path = $site->path; if ($site_path) { $score += ($path == $site_path || preg_match('#^' . $site_path . '/#', $path)) ? 1 : -1; } else if ($path == '/') { $score += 1; } if ($score > $match_score) { $match = $site; $match_score = $score; } } return $match; } /** * Returns a default site active record. * * @return Site */ private function mock_site() { $site = Site::from([ 'title' => 'Undefined', 'status' => Site::STATUS_OK ]); $initializer = $this->mock_initializer; if ($initializer) { $initializer($site); } return $site; } }
bsd-3-clause
g-votte/eclipse-collections
eclipse-collections/src/main/java/org/eclipse/collections/impl/set/immutable/primitive/ImmutableBooleanSetFactoryImpl.java
2476
/* * Copyright (c) 2016 Goldman Sachs. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.eclipse.collections.impl.set.immutable.primitive; import org.eclipse.collections.api.BooleanIterable; import org.eclipse.collections.api.factory.set.primitive.ImmutableBooleanSetFactory; import org.eclipse.collections.api.set.primitive.ImmutableBooleanSet; /** * ImmutableBooleanSetFactoryImpl is a factory implementation which creates instances of type {@link ImmutableBooleanSet}. * * @since 4.0. */ public class ImmutableBooleanSetFactoryImpl implements ImmutableBooleanSetFactory { @Override public ImmutableBooleanSet empty() { return ImmutableBooleanEmptySet.INSTANCE; } @Override public ImmutableBooleanSet of() { return this.empty(); } @Override public ImmutableBooleanSet with() { return this.empty(); } @Override public ImmutableBooleanSet of(boolean one) { return this.with(one); } @Override public ImmutableBooleanSet with(boolean one) { return one ? ImmutableTrueSet.INSTANCE : ImmutableFalseSet.INSTANCE; } @Override public ImmutableBooleanSet of(boolean... items) { return this.with(items); } @Override public ImmutableBooleanSet with(boolean... items) { if (items == null || items.length == 0) { return this.with(); } if (items.length == 1) { return this.with(items[0]); } ImmutableBooleanSet result = ImmutableBooleanEmptySet.INSTANCE; for (boolean item : items) { result = result.newWith(item); } return result; } @Override public ImmutableBooleanSet ofAll(BooleanIterable items) { return this.withAll(items); } @Override public ImmutableBooleanSet withAll(BooleanIterable items) { if (items instanceof ImmutableBooleanSet) { return (ImmutableBooleanSet) items; } return this.with(items.toArray()); } }
bsd-3-clause
scheib/chromium
content/shell/app/shell_main.cc
1384
// 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 "build/build_config.h" #include "content/public/app/content_main.h" #include "content/shell/app/shell_main_delegate.h" #if defined(OS_WIN) #include "base/win/win_util.h" #include "content/public/app/sandbox_helper_win.h" #include "sandbox/win/src/sandbox_types.h" #endif #if defined(OS_WIN) #if !defined(WIN_CONSOLE_APP) int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) { #else int main() { HINSTANCE instance = GetModuleHandle(NULL); #endif // Load and pin user32.dll to avoid having to load it once tests start while // on the main thread loop where blocking calls are disallowed. base::win::PinUser32(); sandbox::SandboxInterfaceInfo sandbox_info = {nullptr}; content::InitializeSandboxInfo(&sandbox_info); content::ShellMainDelegate delegate; content::ContentMainParams params(&delegate); params.instance = instance; params.sandbox_info = &sandbox_info; return content::ContentMain(std::move(params)); } #else int main(int argc, const char** argv) { content::ShellMainDelegate delegate; content::ContentMainParams params(&delegate); params.argc = argc; params.argv = argv; return content::ContentMain(std::move(params)); } #endif // OS_POSIX
bsd-3-clause
rongeb/anit_cms_for_zf3
vendor/zendframework/zend-inputfilter/src/BaseInputFilter.php
16768
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\InputFilter; use ArrayAccess; use Traversable; use Zend\Stdlib\ArrayUtils; use Zend\Stdlib\InitializableInterface; class BaseInputFilter implements InputFilterInterface, UnknownInputsCapableInterface, InitializableInterface, ReplaceableInputInterface { /** * @var null|array */ protected $data; /** * @var InputInterface[]|InputFilterInterface[] */ protected $inputs = []; /** * @var InputInterface[]|InputFilterInterface[] */ protected $invalidInputs; /** * @var null|string[] Input names */ protected $validationGroup; /** * @var InputInterface[]|InputFilterInterface[] */ protected $validInputs; /** * This function is automatically called when creating element with factory. It * allows to perform various operations (add elements...) * * @return void */ public function init() { } /** * Countable: number of inputs in this input filter * * Only details the number of direct children. * * @return int */ public function count() { return count($this->inputs); } /** * Add an input to the input filter * * @param InputInterface|InputFilterInterface $input * @param null|string $name Name used to retrieve this input * @throws Exception\InvalidArgumentException * @return InputFilterInterface */ public function add($input, $name = null) { if (! $input instanceof InputInterface && ! $input instanceof InputFilterInterface) { throw new Exception\InvalidArgumentException(sprintf( '%s expects an instance of %s or %s as its first argument; received "%s"', __METHOD__, InputInterface::class, InputFilterInterface::class, (is_object($input) ? get_class($input) : gettype($input)) )); } if ($input instanceof InputInterface && (empty($name) || is_int($name))) { $name = $input->getName(); } if (isset($this->inputs[$name]) && $this->inputs[$name] instanceof InputInterface) { // The element already exists, so merge the config. Please note // that this merges the new input into the original. $original = $this->inputs[$name]; $original->merge($input); return $this; } $this->inputs[$name] = $input; return $this; } /** * Replace a named input * * @param mixed $input Any of the input types allowed on add() method. * @param string $name Name of the input to replace * @throws Exception\InvalidArgumentException If input to replace not exists. * @return self */ public function replace($input, $name) { if (! array_key_exists($name, $this->inputs)) { throw new Exception\InvalidArgumentException(sprintf( '%s: no input found matching "%s"', __METHOD__, $name )); } $this->remove($name); $this->add($input, $name); return $this; } /** * Retrieve a named input * * @param string $name * @throws Exception\InvalidArgumentException * @return InputInterface|InputFilterInterface */ public function get($name) { if (! array_key_exists($name, $this->inputs)) { throw new Exception\InvalidArgumentException(sprintf( '%s: no input found matching "%s"', __METHOD__, $name )); } return $this->inputs[$name]; } /** * Test if an input or input filter by the given name is attached * * @param string $name * @return bool */ public function has($name) { return array_key_exists($name, $this->inputs); } /** * Remove a named input * * @param string $name * @return InputFilterInterface */ public function remove($name) { unset($this->inputs[$name]); return $this; } /** * Set data to use when validating and filtering * * @param null|array|Traversable $data null is cast to an empty array. * @throws Exception\InvalidArgumentException * @return InputFilterInterface */ public function setData($data) { // A null value indicates an empty set if (null === $data) { $data = []; } if ($data instanceof Traversable) { $data = ArrayUtils::iteratorToArray($data); } if (! is_array($data)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects an array or Traversable argument; received %s', __METHOD__, (is_object($data) ? get_class($data) : gettype($data)) )); } $this->data = $data; $this->populate(); return $this; } /** * Is the data set valid? * * @param mixed|null $context * @throws Exception\RuntimeException * @return bool */ public function isValid($context = null) { if (null === $this->data) { throw new Exception\RuntimeException(sprintf( '%s: no data present to validate!', __METHOD__ )); } $inputs = $this->validationGroup ?: array_keys($this->inputs); return $this->validateInputs($inputs, $this->data, $context); } /** * Validate a set of inputs against the current data * * @param string[] $inputs Array of input names. * @param array|ArrayAccess $data * @param mixed|null $context * @return bool */ protected function validateInputs(array $inputs, $data = [], $context = null) { $inputContext = $context ?: (array_merge($this->getRawValues(), (array) $data)); $this->validInputs = []; $this->invalidInputs = []; $valid = true; foreach ($inputs as $name) { $input = $this->inputs[$name]; // Validate an input filter if ($input instanceof InputFilterInterface) { if (! $input->isValid($context)) { $this->invalidInputs[$name] = $input; $valid = false; continue; } $this->validInputs[$name] = $input; continue; } // If input is not InputInterface then silently continue (BC safe) if (! $input instanceof InputInterface) { continue; } // If input is optional (not required), and value is not set, then ignore. if (! array_key_exists($name, $data) && ! $input->isRequired() ) { continue; } // Validate an input if (! $input->isValid($inputContext)) { // Validation failure $this->invalidInputs[$name] = $input; $valid = false; if ($input->breakOnFailure()) { return false; } continue; } $this->validInputs[$name] = $input; } return $valid; } /** * Provide a list of one or more elements indicating the complete set to validate * * When provided, calls to {@link isValid()} will only validate the provided set. * * If the initial value is {@link VALIDATE_ALL}, the current validation group, if * any, should be cleared. * * Implementations should allow passing a single array value, or multiple arguments, * each specifying a single input. * * @param mixed $name * @throws Exception\InvalidArgumentException * @return InputFilterInterface */ public function setValidationGroup($name) { if ($name === self::VALIDATE_ALL) { $this->validationGroup = null; foreach ($this->getInputs() as $input) { if ($input instanceof InputFilterInterface) { $input->setValidationGroup(self::VALIDATE_ALL); } } return $this; } if (is_array($name)) { $inputs = []; foreach ($name as $key => $value) { if (! $this->has($key)) { $inputs[] = $value; continue; } $inputs[] = $key; if ($this->inputs[$key] instanceof InputFilterInterface) { // Recursively populate validation groups for sub input filters $this->inputs[$key]->setValidationGroup($value); } } } else { $inputs = func_get_args(); } if (! empty($inputs)) { $this->validateValidationGroup($inputs); $this->validationGroup = $inputs; } return $this; } /** * Return a list of inputs that were invalid. * * Implementations should return an associative array of name/input pairs * that failed validation. * * @return InputInterface[] */ public function getInvalidInput() { return is_array($this->invalidInputs) ? $this->invalidInputs : []; } /** * Return a list of inputs that were valid. * * Implementations should return an associative array of name/input pairs * that passed validation. * * @return InputInterface[] */ public function getValidInput() { return is_array($this->validInputs) ? $this->validInputs : []; } /** * Retrieve a value from a named input * * @param string $name * @throws Exception\InvalidArgumentException * @return mixed */ public function getValue($name) { if (! array_key_exists($name, $this->inputs)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a valid input name; "%s" was not found in the filter', __METHOD__, $name )); } $input = $this->inputs[$name]; if ($input instanceof InputFilterInterface) { return $input->getValues(); } return $input->getValue(); } /** * Return a list of filtered values * * List should be an associative array, with the values filtered. If * validation failed, this should raise an exception. * * @return array */ public function getValues() { $inputs = $this->validationGroup ?: array_keys($this->inputs); $values = []; foreach ($inputs as $name) { $input = $this->inputs[$name]; if ($input instanceof InputFilterInterface) { $values[$name] = $input->getValues(); continue; } $values[$name] = $input->getValue(); } return $values; } /** * Retrieve a raw (unfiltered) value from a named input * * @param string $name * @throws Exception\InvalidArgumentException * @return mixed */ public function getRawValue($name) { if (! array_key_exists($name, $this->inputs)) { throw new Exception\InvalidArgumentException(sprintf( '%s expects a valid input name; "%s" was not found in the filter', __METHOD__, $name )); } $input = $this->inputs[$name]; if ($input instanceof InputFilterInterface) { return $input->getRawValues(); } return $input->getRawValue(); } /** * Return a list of unfiltered values * * List should be an associative array of named input/value pairs, * with the values unfiltered. * * @return array */ public function getRawValues() { $values = []; foreach ($this->inputs as $name => $input) { if ($input instanceof InputFilterInterface) { $values[$name] = $input->getRawValues(); continue; } $values[$name] = $input->getRawValue(); } return $values; } /** * Return a list of validation failure messages * * Should return an associative array of named input/message list pairs. * Pairs should only be returned for inputs that failed validation. * * @return array */ public function getMessages() { $messages = []; foreach ($this->getInvalidInput() as $name => $input) { $messages[$name] = $input->getMessages(); } return $messages; } /** * Ensure all names of a validation group exist as input in the filter * * @param string[] $inputs Input names * @return void * @throws Exception\InvalidArgumentException */ protected function validateValidationGroup(array $inputs) { foreach ($inputs as $name) { if (! array_key_exists($name, $this->inputs)) { throw new Exception\InvalidArgumentException(sprintf( 'setValidationGroup() expects a list of valid input names; "%s" was not found', $name )); } } } /** * Populate the values of all attached inputs * * @return void */ protected function populate() { foreach (array_keys($this->inputs) as $name) { $input = $this->inputs[$name]; if ($input instanceof CollectionInputFilter) { $input->clearValues(); $input->clearRawValues(); } if (! array_key_exists($name, $this->data)) { // No value; clear value in this input if ($input instanceof InputFilterInterface) { $input->setData([]); continue; } if ($input instanceof Input) { $input->resetValue(); continue; } $input->setValue(null); continue; } $value = $this->data[$name]; if ($input instanceof InputFilterInterface) { // Fixes #159 if (! is_array($value) && ! $value instanceof Traversable) { $value = []; } $input->setData($value); continue; } $input->setValue($value); } } /** * Is the data set has unknown input ? * * @throws Exception\RuntimeException * @return bool */ public function hasUnknown() { return $this->getUnknown() ? true : false; } /** * Return the unknown input * * @throws Exception\RuntimeException * @return array */ public function getUnknown() { if (null === $this->data) { throw new Exception\RuntimeException(sprintf( '%s: no data present!', __METHOD__ )); } $data = array_keys($this->data); $inputs = array_keys($this->inputs); $diff = array_diff($data, $inputs); $unknownInputs = []; $intersect = array_intersect($diff, $data); if (! empty($intersect)) { foreach ($intersect as $key) { $unknownInputs[$key] = $this->data[$key]; } } return $unknownInputs; } /** * Get an array of all inputs * * @return InputInterface[]|InputFilterInterface[] */ public function getInputs() { return $this->inputs; } /** * Merges the inputs from an InputFilter into the current one * * @param BaseInputFilter $inputFilter * * @return self */ public function merge(BaseInputFilter $inputFilter) { foreach ($inputFilter->getInputs() as $name => $input) { $this->add($input, $name); } return $this; } }
bsd-3-clause
releaznl/releaz-project-manager
frontend/views/request-project/step-2.php
2655
<?php /* @var $this yii\web\View */ use yii\widgets\ActiveForm; use yii\widgets\Breadcrumbs; use yii\helpers\ArrayHelper; use yii\helpers\Html; $this->title = $category->name; ?> <h1><?php echo $category->name ?></h1> <ul class="steps"> <li class="active"><span>Stap 1</span><?= Html::a(Yii::t('request-project', 'Strategy'), ['/request-project/step-1'])?></li> <li class="active"><span>Stap 2</span><?= Html::a(Yii::t('request-project', 'Design'), ['/request-project/step-2'])?></li> <li><span>Stap 3</span><?= Html::a(Yii::t('request-project', 'Planning'), ['/request-project/step-3'])?></li> <li><span>Stap 4</span><?= Html::a(Yii::t('request-project', 'Hosting'), ['/request-project/step-4'])?></li> <li><span>Stap 5</span><?= Html::a(Yii::t('request-project', 'Website promotion'), ['/request-project/step-5']) ?></li> <li><span>Stap 6</span><?= Html::a(Yii::t('request-project', 'Overview'), ['/request-project/overview']) ?></li> </ul> <div class="col-sm-6"> <div class="row"> <div class="block"> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <?php echo $form->field($model, 'website1')->textInput(['placeholder' => 'bijvoorbeeld www.keesonline.nl']); ?> <?php echo $form->field($model, 'website2')->textInput(['placeholder' => 'bijvoorbeeld www.keesonline.nl'])->label(false); ?> <?php echo $form->field($model, 'website3')->textInput(['placeholder' => 'bijvoorbeeld www.keesonline.nl'])->label(false); ?> <?php echo $form->field($model, 'goal')->textArea(['placeholder' => 'bijvoorbeeld meer offerte aanvragen']) ?> <?php // Toevoegen slider ?> <?php echo $form->field($model, 'target_audience')->textArea(['placeholder' => 'bijvoorbeeld werkenden 30 - 50 jaar']) ?> <?php echo $form->field($model, 'current_style')->fileInput() ?> <?= $form->field($model, 'comment')->textArea() ?> <?= Html::a(Yii::t('common','Last step'), ['step-1'], ['class' => 'btn btn-primary']) ?> <?= Html::submitButton(Yii::t('common','Next step'), ['class' => 'btn btn-primary']) ?> <?php ActiveForm::end() ?> </div> </div> </div> <div class="col-sm-6"> <div class="row"> <div class="block info"> <?php echo $category->description ?></p> </div> <div class="call"> Kom je er niet uit of heb je vragen?<br /> <a href="tel:+31858769957">085 876 99 57</a> </div> </div> </div>
bsd-3-clause
ranvirp/discom
tests/codeception/unit/fixtures/data/geography_columns.php
257
<?php return [ 'geography_columns1'=>[ 'f_table_catalog'=> '', 'f_table_schema'=> '', 'f_table_name'=> '', 'f_geography_column'=> '', 'coord_dimension'=> '', 'srid'=> '', 'type'=> '', ], ];
bsd-3-clause
PolymerLabs/arcs-live
concrete-storage/node_modules/@firebase/database/dist/src/api/DataSnapshot.d.ts
3742
/** * @license * Copyright 2017 Google 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. */ import { Node } from '../core/snap/Node'; import { Reference } from './Reference'; import { Index } from '../core/snap/indexes/Index'; /** * Class representing a firebase data snapshot. It wraps a SnapshotNode and * surfaces the public methods (val, forEach, etc.) we want to expose. */ export declare class DataSnapshot { private readonly node_; private readonly ref_; private readonly index_; /** * @param {!Node} node_ A SnapshotNode to wrap. * @param {!Reference} ref_ The ref of the location this snapshot came from. * @param {!Index} index_ The iteration order for this snapshot */ constructor(node_: Node, ref_: Reference, index_: Index); /** * Retrieves the snapshot contents as JSON. Returns null if the snapshot is * empty. * * @return {*} JSON representation of the DataSnapshot contents, or null if empty. */ val(): any; /** * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting * the entire node contents. * @return {*} JSON representation of the DataSnapshot contents, or null if empty. */ exportVal(): any; toJSON(): any; /** * Returns whether the snapshot contains a non-null value. * * @return {boolean} Whether the snapshot contains a non-null value, or is empty. */ exists(): boolean; /** * Returns a DataSnapshot of the specified child node's contents. * * @param {!string} childPathString Path to a child. * @return {!DataSnapshot} DataSnapshot for child node. */ child(childPathString: string): DataSnapshot; /** * Returns whether the snapshot contains a child at the specified path. * * @param {!string} childPathString Path to a child. * @return {boolean} Whether the child exists. */ hasChild(childPathString: string): boolean; /** * Returns the priority of the object, or null if no priority was set. * * @return {string|number|null} The priority. */ getPriority(): string | number | null; /** * Iterates through child nodes and calls the specified action for each one. * * @param {function(!DataSnapshot)} action Callback function to be called * for each child. * @return {boolean} True if forEach was canceled by action returning true for * one of the child nodes. */ forEach(action: (d: DataSnapshot) => boolean | void): boolean; /** * Returns whether this DataSnapshot has children. * @return {boolean} True if the DataSnapshot contains 1 or more child nodes. */ hasChildren(): boolean; readonly key: string; /** * Returns the number of children for this DataSnapshot. * @return {number} The number of children that this DataSnapshot contains. */ numChildren(): number; /** * @return {Reference} The Firebase reference for the location this snapshot's data came from. */ getRef(): Reference; readonly ref: Reference; }
bsd-3-clause
brian978/Acamar-SkeletonApplication
module/Application/src/main/Controller/IndexController.php
3132
<?php /** * Acamar-SkeletonApplication * * @link https://github.com/brian978/Acamar-SkeletonApplication * @copyright Copyright (c) 2014 * @license https://github.com/brian978/Acamar-SkeletonApplication/blob/master/LICENSE New BSD License */ namespace Application\Controller; use Acamar\Mvc\Controller\AbstractController; use Application\Model\Table\AuthorsTable; use Application\Model\Table\BooksTable; use Application\Model\Table\Maps\BooksMaps; use Application\Model\Table\PublishersTable; /** * Class IndexController * * @package Application\Controller */ class IndexController extends AbstractController { public function indexAction() { $books = new BooksTable(); return [ 'books' => $books->getBooks(), ]; } public function addAction() { $defaults = [ 'title' => '', 'isbn' => '', ]; $data = array_merge($defaults, $this->getRequest()->getPost()); // We save the object if ($this->getRequest()->isPost()) { $data = array_merge($data, $this->getRequest()->getPost()); $table = new BooksTable(); $table->saveArray($data, BooksMaps::MAP_BOOK); $this->getResponse() ->getHeaders() ->set('Location', '/index/index'); return 0; } $publishers = (new PublishersTable())->getPublishers(); $authors = (new AuthorsTable())->getAuthors(); return [ 'post' => $data, 'publishers' => $publishers, 'authors' => $authors, ]; } public function editAction() { $id = (int) $this->getEvent()->getRoute()->getParam('id'); $table = new BooksTable(); $data = $table->getBookArray($id); if (empty($data)) { $this->getResponse() ->getHeaders() ->set('Location', '/index/index'); return 0; } // We save the object if ($this->getRequest()->isPost()) { $data = array_merge($data, $this->getRequest()->getPost()); // Converting the data structure $object = $table->getObjectMapper()->populate($data, BooksMaps::MAP_BOOK); $data = $table->getObjectMapper()->extract($object, BooksMaps::MAP_BOOK_DB_SAVE); $table->saveArray($data, BooksMaps::MAP_BOOK_DB_SAVE); } $publishers = (new PublishersTable())->getPublishers(); $authors = (new AuthorsTable())->getAuthors(); return [ 'post' => $data, 'publishers' => $publishers, 'authors' => $authors, ]; } public function deleteAction() { $id = (int) $this->getEvent()->getRoute()->getParam('id'); $table = new BooksTable(); $object = $table->getBook($id); if ($object->getId() !== 0) { $table->deleteObject($object, BooksMaps::MAP_BOOK); } $this->getResponse() ->getHeaders() ->set('Location', '/index/index'); return 0; } }
bsd-3-clause
endlessm/chromium-browser
chrome/browser/notifications/popups_only_ui_controller_unittest.cc
4820
// 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 "chrome/browser/notifications/popups_only_ui_controller.h" #include <stddef.h> #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "content/public/test/test_utils.h" #include "ui/message_center/message_center.h" #include "ui/message_center/notification_list.h" #include "ui/message_center/public/cpp/message_center_constants.h" #include "ui/message_center/public/cpp/notification.h" #include "ui/message_center/public/cpp/notification_delegate.h" #include "ui/message_center/public/cpp/notification_types.h" #include "ui/message_center/views/message_popup_collection.h" #include "ui/views/controls/label.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/test/widget_test.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" using message_center::MessageCenter; using message_center::Notification; using message_center::NotifierId; namespace { class PopupsOnlyUiControllerTest : public views::test::WidgetTest { public: PopupsOnlyUiControllerTest() = default; ~PopupsOnlyUiControllerTest() override = default; void SetUp() override { set_native_widget_type(NativeWidgetType::kDesktop); views::test::WidgetTest::SetUp(); MessageCenter::Initialize(); } void TearDown() override { MessageCenter::Get()->RemoveAllNotifications( false, MessageCenter::RemoveType::ALL); for (views::Widget* widget : GetAllWidgets()) widget->CloseNow(); MessageCenter::Shutdown(); views::test::WidgetTest::TearDown(); } protected: void AddNotification(const std::string& id) { auto notification = std::make_unique<Notification>( message_center::NOTIFICATION_TYPE_SIMPLE, id, base::ASCIIToUTF16("Test Web Notification"), base::ASCIIToUTF16("Notification message body."), gfx::Image(), base::ASCIIToUTF16("Some Chrome extension"), GURL("chrome-extension://abbccedd"), NotifierId(message_center::NotifierType::APPLICATION, id), message_center::RichNotificationData(), nullptr); MessageCenter::Get()->AddNotification(std::move(notification)); } void UpdateNotification(const std::string& id) { auto notification = std::make_unique<Notification>( message_center::NOTIFICATION_TYPE_SIMPLE, id, base::ASCIIToUTF16("Updated Test Web Notification"), base::ASCIIToUTF16("Notification message body."), gfx::Image(), base::ASCIIToUTF16("Some Chrome extension"), GURL("chrome-extension://abbccedd"), NotifierId(message_center::NotifierType::APPLICATION, id), message_center::RichNotificationData(), nullptr); MessageCenter::Get()->UpdateNotification(id, std::move(notification)); } void RemoveNotification(const std::string& id) { MessageCenter::Get()->RemoveNotification(id, false); } bool HasNotification(const std::string& id) { return !!MessageCenter::Get()->FindVisibleNotificationById(id); } private: DISALLOW_COPY_AND_ASSIGN(PopupsOnlyUiControllerTest); }; TEST_F(PopupsOnlyUiControllerTest, WebNotificationPopupBubble) { auto ui_controller = std::make_unique<PopupsOnlyUiController>(); // Adding a notification should show the popup bubble. AddNotification("id1"); EXPECT_TRUE(ui_controller->popups_visible()); // Updating a notification should not hide the popup bubble. AddNotification("id2"); UpdateNotification("id2"); EXPECT_TRUE(ui_controller->popups_visible()); // Removing the first notification should not hide the popup bubble. RemoveNotification("id1"); EXPECT_TRUE(ui_controller->popups_visible()); // Removing the visible notification should hide the popup bubble. RemoveNotification("id2"); EXPECT_FALSE(ui_controller->popups_visible()); } TEST_F(PopupsOnlyUiControllerTest, ManyPopupNotifications) { auto ui_controller = std::make_unique<PopupsOnlyUiController>(); // Add the max visible popup notifications +1, ensure the correct num visible. size_t notifications_to_add = message_center::kMaxVisiblePopupNotifications + 1; for (size_t i = 0; i < notifications_to_add; ++i) { std::string id = base::StringPrintf("id%d", static_cast<int>(i)); AddNotification(id); } EXPECT_TRUE(ui_controller->popups_visible()); MessageCenter* message_center = MessageCenter::Get(); EXPECT_EQ(notifications_to_add, message_center->NotificationCount()); message_center::NotificationList::PopupNotifications popups = message_center->GetPopupNotifications(); EXPECT_EQ(message_center::kMaxVisiblePopupNotifications, popups.size()); } } // namespace
bsd-3-clause
cedriclaunay/gaffer
src/GafferImage/ImageMixinBase.cpp
3896
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2013, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 "IECore/Exception.h" #include "GafferImage/ImageMixinBase.h" using namespace IECore; using namespace Gaffer; using namespace GafferImage; IE_CORE_DEFINERUNTIMETYPED( ImageMixinBase ); ImageMixinBase::ImageMixinBase( const std::string &name ) : ImageProcessor( name ) { } ImageMixinBase::~ImageMixinBase() { } void ImageMixinBase::hashFormat( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const { throw Exception( "Unexpected call to ImageMixinBase::hashFormat" ); } void ImageMixinBase::hashDataWindow( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const { throw Exception( "Unexpected call to ImageMixinBase::hashDataWindow" ); } void ImageMixinBase::hashChannelNames( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const { throw Exception( "Unexpected call to ImageMixinBase::hashChannelNames" ); } void ImageMixinBase::hashChannelData( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const { throw Exception( "Unexpected call to ImageMixinBase::hashChannelData" ); } GafferImage::Format ImageMixinBase::computeFormat( const Gaffer::Context *context, const ImagePlug *parent ) const { throw Exception( "Unexpected call to ImageMixinBase::computeFormat" ); } Imath::Box2i ImageMixinBase::computeDataWindow( const Gaffer::Context *context, const ImagePlug *parent ) const { throw Exception( "Unexpected call to ImageMixinBase::computeDataWindow" ); } IECore::ConstStringVectorDataPtr ImageMixinBase::computeChannelNames( const Gaffer::Context *context, const ImagePlug *parent ) const { throw Exception( "Unexpected call to ImageMixinBase::computeChannelNames" ); } IECore::ConstFloatVectorDataPtr ImageMixinBase::computeChannelData( const std::string &channelName, const Imath::V2i &tileOrigin, const Gaffer::Context *context, const ImagePlug *parent ) const { throw Exception( "Unexpected call to ImageMixinBase::computeChannelData" ); }
bsd-3-clause
TonyBrewer/OpenHT
ht_lib/sysc/SyscMonLib.cpp
12157
/* Copyright (c) 2015 Convey Computer Corporation * * This file is part of the OpenHT toolset located at: * * https://github.com/TonyBrewer/OpenHT * * Use and distribution licensed under the BSD 3-clause license. * See the LICENSE file for the complete license text. */ #define HT_LIB_SYSC #include "Ht.h" #include <vector> #include <algorithm> using namespace std; #include "SyscMonLib.h" namespace Ht { CSyscMon::CSyscMon(char const * pPlatform, int unitCnt) { m_pSyscMonLib = new CSyscMonLib(pPlatform, unitCnt); RegisterModule("HIF", 0, 0, 0, 0, 1); } int CSyscMon::RegisterModule(char const * pPathName, char const * pSyscPath, int htIdW, int instrW, char const ** pInstrNames, int memPortCnt) { m_pSyscMonLib->m_pModList.push_back(new CSyscMonMod(pPathName, pSyscPath, htIdW, instrW, pInstrNames, memPortCnt)); return (int)m_pSyscMonLib->m_pModList.size()-1; } void CSyscMon::UpdateValidInstrCnt(int modId, int htInstr) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_htValidCnt += 1; pMod->m_htInstrValidCnt[htInstr] += 1; } void CSyscMon::UpdateRetryInstrCnt(int modId, int htInstr) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_htRetryCnt += 1; pMod->m_htInstrRetryCnt[htInstr] += 1; } void CSyscMon::UpdateModuleMemReadBytes(int modId, int portId, Int64 bytes) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_readMemBytes[portId] += bytes; } void CSyscMon::UpdateModuleMemReads(int modId, int portId, Int64 cnt) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_readMemCnt[portId] += cnt; } void CSyscMon::UpdateModuleMemRead64s(int modId, int portId, Int64 cnt) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_read64MemCnt[portId] += cnt; } void CSyscMon::UpdateModuleMemWriteBytes(int modId, int portId, Int64 bytes) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_writeMemBytes[portId] += bytes; } void CSyscMon::UpdateModuleMemWrites(int modId, int portId, Int64 cnt) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_writeMemCnt[portId] += cnt; } void CSyscMon::UpdateModuleMemWrite64s(int modId, int portId, Int64 cnt) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_write64MemCnt[portId] += cnt; } void CSyscMon::UpdateActiveClks(int modId, Int64 cnt) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_activeClks += cnt; } void CSyscMon::UpdateActiveCnt(int modId, uint32_t activeCnt) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; if (activeCnt > pMod->m_maxActiveCnt) pMod->m_maxActiveCnt = activeCnt; pMod->m_activeSum += activeCnt; pMod->m_activeClks += 1; } void CSyscMon::UpdateRunningCnt(int modId, uint32_t runningCnt) { if (m_pSyscMonLib == 0) return; assert(modId < (int)m_pSyscMonLib->m_pModList.size()); CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[modId]; pMod->m_runningSum += runningCnt; } void CSyscMon::UpdateMemReqClocks(bool bHost, Int64 reqClocks) { if (m_pSyscMonLib == 0) return; if (m_pSyscMonLib->m_minMemClks[bHost] > reqClocks) m_pSyscMonLib->m_minMemClks[bHost] = reqClocks; if (m_pSyscMonLib->m_maxMemClks[bHost] < reqClocks) m_pSyscMonLib->m_maxMemClks[bHost] = reqClocks; m_pSyscMonLib->m_totalMemClks[bHost] += reqClocks; m_pSyscMonLib->m_totalMemOps[bHost] += 1; } void CSyscMon::UpdateTotalMemReadBytes(bool bHost, Int64 bytes) { if (m_pSyscMonLib == 0) return; m_pSyscMonLib->m_totalMemReadBytes[bHost] += bytes; } void CSyscMon::UpdateTotalMemRead64s(bool bHost, Int64 cnt) { if (m_pSyscMonLib == 0) return; m_pSyscMonLib->m_totalMemRead64s[bHost] += cnt; } void CSyscMon::UpdateTotalMemReads(bool bHost, Int64 cnt) { if (m_pSyscMonLib == 0) return; m_pSyscMonLib->m_totalMemReads[bHost] += cnt; } void CSyscMon::UpdateTotalMemWriteBytes(bool bHost, Int64 bytes) { if (m_pSyscMonLib == 0) return; m_pSyscMonLib->m_totalMemWriteBytes[bHost] += bytes; } void CSyscMon::UpdateTotalMemWrite64s(bool bHost, Int64 cnt) { if (m_pSyscMonLib == 0) return; m_pSyscMonLib->m_totalMemWrite64s[bHost] += cnt; } void CSyscMon::UpdateTotalMemWrites(bool bHost, Int64 cnt) { if (m_pSyscMonLib == 0) return; m_pSyscMonLib->m_totalMemWrites[bHost] += cnt; } bool CSyscMonLib::HtMonSortByActiveCnt(const CSyscMonMod * pModA, const CSyscMonMod * pModB) { return pModA->m_activeSum > pModB->m_activeSum; } CSyscMon::~CSyscMon() { vector<CSyscMonMod *> sortedModList = m_pSyscMonLib->m_pModList; std::sort(sortedModList.begin(), sortedModList.end(), CSyscMonLib::HtMonSortByActiveCnt); // Generate the report FILE * monFp; if (!(monFp = fopen("HtMonRpt.txt", "w"))) { fprintf(stderr, "Could not open HtMonRpt.txt\n"); exit(1); } long long sim_cyc = (long long)sc_time_stamp().value()/10000; fprintf(monFp, "Simulated Cycles : %8lld\n", sim_cyc); fprintf(monFp, "Platform : %8s\n", m_pSyscMonLib->m_pPlatform); fprintf(monFp, "Unit Count : %8d\n", m_pSyscMonLib->m_unitCnt); fprintf(monFp, "\n#\n"); fprintf(monFp, "# Memory Summary\n"); fprintf(monFp, "#\n"); fprintf(monFp, "Host Latency (cyc) : %8lld / %9lld / %8lld (Min / Avg / Max)\n", m_pSyscMonLib->m_minMemClks[1], m_pSyscMonLib->m_totalMemClks[1] / max(1LL, m_pSyscMonLib->m_totalMemOps[1]), m_pSyscMonLib->m_maxMemClks[1]); fprintf(monFp, "CP Latency (cyc) : %8lld / %9lld / %8lld (Min / Avg / Max)\n", min(m_pSyscMonLib->m_minMemClks[0], m_pSyscMonLib->m_maxMemClks[0]), m_pSyscMonLib->m_totalMemClks[0] / max(1LL, m_pSyscMonLib->m_totalMemOps[0]), m_pSyscMonLib->m_maxMemClks[0]); fprintf(monFp, "Host Operations : %8lld / %9lld\t\t (Read / Write)\n", m_pSyscMonLib->m_totalMemReads[1] + m_pSyscMonLib->m_totalMemRead64s[1], m_pSyscMonLib->m_totalMemWrites[1] + m_pSyscMonLib->m_totalMemWrite64s[1]); fprintf(monFp, "CP Operations : %8lld / %9lld\t\t (Read / Write)\n", m_pSyscMonLib->m_totalMemReads[0] + m_pSyscMonLib->m_totalMemRead64s[0], m_pSyscMonLib->m_totalMemWrites[0] + m_pSyscMonLib->m_totalMemWrite64s[0]); fprintf(monFp, "Host Efficiency : %7.2f%% / %8.2f%%\t\t (Read / Write)\n", 100.0 * m_pSyscMonLib->m_totalMemReadBytes[1] / (64 * m_pSyscMonLib->m_totalMemReads[1] + 64 * m_pSyscMonLib->m_totalMemRead64s[1]), 100.0 * m_pSyscMonLib->m_totalMemWriteBytes[1] / (64 * m_pSyscMonLib->m_totalMemWrites[1] + 64 * m_pSyscMonLib->m_totalMemWrite64s[1])); fprintf(monFp, "CP Efficiency : %7.2f%% / %8.2f%%\t\t (Read / Write)\n", 100.0 * m_pSyscMonLib->m_totalMemReadBytes[0] / max(1LL, (64 * m_pSyscMonLib->m_totalMemReads[0] + 64 * m_pSyscMonLib->m_totalMemRead64s[0])), 100.0 * m_pSyscMonLib->m_totalMemWriteBytes[0] / max(1LL, (64 * m_pSyscMonLib->m_totalMemWrites[0] + 64 * m_pSyscMonLib->m_totalMemWrite64s[0]))); long long rq_cyc, rs_cyc; rq_cyc = m_pSyscMonLib->m_totalMemReads[1] + m_pSyscMonLib->m_totalMemRead64s[1]; rq_cyc += m_pSyscMonLib->m_totalMemWrites[1] + m_pSyscMonLib->m_totalMemWrite64s[1] * 8; rs_cyc = m_pSyscMonLib->m_totalMemReads[1] + m_pSyscMonLib->m_totalMemRead64s[1] * 8; rs_cyc += m_pSyscMonLib->m_totalMemWrites[1] + m_pSyscMonLib->m_totalMemWrite64s[1]; fprintf(monFp, "Host Utiliztion : %7.2f%% / %8.2f%%\t\t (Req / Resp)\n", 100.0 * rq_cyc / sortedModList[0]->m_activeClks / m_pSyscMonLib->m_unitCnt, 100.0 * rs_cyc / sortedModList[0]->m_activeClks / m_pSyscMonLib->m_unitCnt); rq_cyc = m_pSyscMonLib->m_totalMemReads[0] + m_pSyscMonLib->m_totalMemRead64s[0]; rq_cyc += m_pSyscMonLib->m_totalMemWrites[0] + m_pSyscMonLib->m_totalMemWrite64s[0] * 8; rs_cyc = m_pSyscMonLib->m_totalMemReads[0] + m_pSyscMonLib->m_totalMemRead64s[0] * 8; rs_cyc += m_pSyscMonLib->m_totalMemWrites[0] + m_pSyscMonLib->m_totalMemWrite64s[0]; fprintf(monFp, "CP Utiliztion : %7.2f%% / %8.2f%%\t\t (Req / Resp)\n", 100.0 * rq_cyc / sortedModList[0]->m_activeClks / m_pSyscMonLib->m_unitCnt, 100.0 * rs_cyc / sortedModList[0]->m_activeClks / m_pSyscMonLib->m_unitCnt); fprintf(monFp, "\n#\n"); fprintf(monFp, "%-35s %10s %10s %10s %10s\n", "# Memory Operations", "Read ", "ReadMw ", "Write ", "WriteMw "); fprintf(monFp, "%-35s %10s %10s %10s %10s\n", "#", "----------", "----------", "----------", "----------"); fprintf(monFp, "%-35s %10lld %10lld %10lld %10lld\n", "<total>", m_pSyscMonLib->m_totalMemReads[0] + m_pSyscMonLib->m_totalMemReads[1], m_pSyscMonLib->m_totalMemRead64s[0] + m_pSyscMonLib->m_totalMemRead64s[1], m_pSyscMonLib->m_totalMemWrites[0] + m_pSyscMonLib->m_totalMemWrites[1], m_pSyscMonLib->m_totalMemWrite64s[0] + m_pSyscMonLib->m_totalMemWrite64s[1]); for (size_t i = 0; i < m_pSyscMonLib->m_pModList.size(); i += 1) { CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[i]; Int64 readMemCnt = 0; Int64 read64MemCnt = 0; Int64 writeMemCnt = 0; Int64 write64MemCnt = 0; for (int j = 0; j < pMod->m_memPortCnt; j += 1) { readMemCnt += pMod->m_readMemCnt[j]; read64MemCnt += pMod->m_read64MemCnt[j]; writeMemCnt += pMod->m_writeMemCnt[j]; write64MemCnt += pMod->m_write64MemCnt[j]; } fprintf(monFp, "%-35s %10lld %10lld %10lld %10lld\n", pMod->m_pathName.c_str(), readMemCnt, read64MemCnt, writeMemCnt, write64MemCnt); if (pMod->m_memPortCnt > 1) for (int j = 0; j < pMod->m_memPortCnt; j += 1) { char buf[64]; sprintf(buf, " Memory Port %d", j); fprintf(monFp, "%-35s %10lld %10lld %10lld %10lld\n", buf, pMod->m_readMemCnt[j], pMod->m_read64MemCnt[j], pMod->m_writeMemCnt[j], pMod->m_write64MemCnt[j]); } } fprintf(monFp, "\n#\n"); fprintf(monFp, "%-35s %10s %10s %10s %10s\n", "# Thread Utilization", "Avg. Run ", "Avg. Alloc", "Max. Alloc", "Available"); fprintf(monFp, "%-35s %10s %10s %10s %10s\n", "#", "----------", "----------", "----------", "----------"); for (size_t i = 0; i < m_pSyscMonLib->m_pModList.size(); i += 1) { CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[i]; fprintf(monFp, "%-35s %10lld %10lld %10lld %10lld\n", pMod->m_pathName.c_str(), pMod->m_runningSum / max(1LL, pMod->m_activeClks), pMod->m_activeSum / max(1LL, pMod->m_activeClks), pMod->m_maxActiveCnt, pMod->m_availableCnt); } fprintf(monFp, "\n#\n"); fprintf(monFp, "%-35s %10s %10s %10s %10s\n", "# Module Utilization", "Valid ", "Retry ", "Active Cyc", "Act. Util"); fprintf(monFp, "%-35s %10s %10s %10s %10s\n", "#", "----------", "----------", "----------", "----------"); for (size_t i = 0; i < m_pSyscMonLib->m_pModList.size(); i += 1) { CSyscMonMod * pMod = m_pSyscMonLib->m_pModList[i]; fprintf(monFp, "%-35s %10lld %10lld %10lld %9.2f%%\n", pMod->m_pathName.c_str(), pMod->m_htValidCnt, pMod->m_htRetryCnt, pMod->m_activeClks, 100.0 * pMod->m_activeClks / sim_cyc); for (int i = 0; i < (1 << pMod->m_modInstrW); i += 1) { if (pMod->m_htInstrValidCnt[i] > 0 || pMod->m_htInstrRetryCnt[i] > 0) fprintf(monFp, " %-33s %10lld %10lld\n", pMod->m_pInstrNames[i], pMod->m_htInstrValidCnt[i], pMod->m_htInstrRetryCnt[i]); } } fclose(monFp); CSyscMonLib * pTmp = m_pSyscMonLib; m_pSyscMonLib = 0; delete pTmp; } }
bsd-3-clause
rlgomes/dtf
src/java/com/yahoo/dtf/components/FunctionsLockHook.java
1336
package com.yahoo.dtf.components; import java.util.ArrayList; import com.yahoo.dtf.actions.Action; import com.yahoo.dtf.actions.component.Lockcomponent; import com.yahoo.dtf.actions.function.ExportFuncs; import com.yahoo.dtf.actions.function.Function; import com.yahoo.dtf.exception.DTFException; import com.yahoo.dtf.logger.DTFLogger; public class FunctionsLockHook implements LockHook { public ArrayList<Action> init(String id) throws DTFException { DTFLogger log = Action.getLogger(); ArrayList<Action> result = new ArrayList<Action>(); /* * Export necessary functions to the locked component. */ ArrayList<Function> functions = Function.getExportableFunctions(); if (functions.size() == 0) { if (log.isDebugEnabled()) log.debug("No exported functions."); } else { ExportFuncs export = new ExportFuncs(); for (int i = 0; i < functions.size(); i++) { Function function = functions.get(i); export.addAction(function); if (log.isDebugEnabled()) log.debug("Sending function [" + function.getName() + "]"); } result.add(export); } return result; } }
bsd-3-clause
cfmobile/arca-android
arca-core/arca-service/src/test/java/io/pivotal/arca/service/OperationServiceTest.java
1733
package io.pivotal.arca.service; import android.content.Intent; import android.os.IBinder; import android.test.ServiceTestCase; public class OperationServiceTest extends ServiceTestCase<OperationService> { public OperationServiceTest() { super(OperationService.class); } public void testOperationServiceActionStart() { assertEquals(OperationService.Action.START, OperationService.Action.valueOf("START")); } public void testOperationServiceActionCancel() { assertEquals(OperationService.Action.CANCEL, OperationService.Action.valueOf("CANCEL")); } public void testOperationServiceActionValues() { final OperationService.Action[] actions = OperationService.Action.values(); assertEquals(OperationService.Action.START, actions[0]); assertEquals(OperationService.Action.CANCEL, actions[1]); } // =========================================== public void testOperationServiceStartable() { final Intent intent = new Intent(getContext(), OperationService.class); startService(intent); } public void testOperationServiceNotBindable() { final Intent intent = new Intent(getContext(), OperationService.class); final IBinder binder = bindService(intent); assertNull(binder); } // =========================================== public void testOperationServiceStartWithoutContext() { assertFalse(OperationService.start(null, null)); } public void testOperationServiceCancelWithoutContext() { assertFalse(OperationService.cancel(null, null)); } public void testOperationServiceStartWithoutOperation() { assertFalse(OperationService.start(getContext(), null)); } public void testOperationServiceCancelWithoutOperation() { assertFalse(OperationService.cancel(getContext(), null)); } }
bsd-3-clause
Naburimannu/libtcodpy-tutorial
miscellany.py
2299
# Copyright 2016 Thomas C. Hudson # Governed by the license described in LICENSE.txt import libtcodpy as libtcod import log import algebra from components import * import actions import map import spells def dagger(): return Object(algebra.Location(0, 0), '-', 'dagger', libtcod.sky, item=Item(description='A leaf-shaped bronze knife; provides +2 Attack'), equipment=Equipment(slot='right hand', power_bonus=2)) def healing_potion(pos=algebra.Location(0, 0)): return Object(pos, '!', 'healing potion', libtcod.violet, item=Item(use_function=spells.cast_heal, description='A flask of revivifying alchemical mixtures; heals ' + str(spells.HEAL_AMOUNT) + ' hp.')) def lightning_scroll(pos=algebra.Location(0, 0)): return Object(pos, '#', 'scroll of lightning bolt', libtcod.light_yellow, item=Item(use_function=spells.cast_lightning, description='Reading these runes will strike your nearest foe with lightning for ' + str(spells.LIGHTNING_DAMAGE) + ' hp.')) def fireball_scroll(pos=algebra.Location(0, 0)): return Object(pos, '#', 'scroll of fireball', libtcod.light_yellow, item=Item(use_function=spells.cast_fireball, description='Reading these runes will cause a burst of flame inflicting ' + str(spells.FIREBALL_DAMAGE) + ' hp on nearby creatures.')) def confusion_scroll(pos=algebra.Location(0, 0)): return Object(pos, '#', 'scroll of confusion', libtcod.light_yellow, item=Item(use_function=spells.cast_confuse, description='Reading these runes will confuse the creature you focus on for a short time.')) def sword(pos=algebra.Location(0, 0)): return Object(pos, '/', 'sword', libtcod.sky, item=Item(description='A heavy-tipped bronze chopping sword; provides +3 Attack'), equipment=Equipment(slot='right hand', power_bonus=3)) def shield(pos=algebra.Location(0, 0)): return Object(pos, '[', 'shield', libtcod.darker_orange, item=Item(description='A bronze-edged oval shield; provides +1 Defense'), equipment=Equipment(slot='left hand', defense_bonus=1))
bsd-3-clause
criquelmes/yii-facilito
facilito/protected/gii/crud/templates/simple/create.php
648
<?php /** * The following variables are available in this template: * - $this: the CrudCode object */ ?> <?php echo "<?php\n"; ?> /* @var $this <?php echo $this->getControllerClass(); ?> */ /* @var $model <?php echo $this->getModelClass(); ?> */ <?php $label=$this->pluralize($this->class2name($this->modelClass)); echo "\$this->breadcrumbs=array( '$label'=>array('index'), 'Create', );\n"; ?> $this->menu=array( array('label'=>'Manage <?php echo $this->modelClass; ?>', 'url'=>array('admin')), ); ?> <h1>Create <?php echo $this->modelClass; ?></h1> <?php echo "<?php echo \$this->renderPartial('_form', array('model'=>\$model)); ?>"; ?>
bsd-3-clause
konecnyjakub/mytester
src/ICodeCoverageEngine.php
289
<?php declare(strict_types=1); namespace MyTester; /** * @author Jakub Konečný * @internal */ interface ICodeCoverageEngine { public function getName(): string; public function isAvailable(): bool; public function start(): void; public function collect(): array; }
bsd-3-clause
bokko79/servicemapp
frontend/views/layouts/html/html_service.php
1070
<?php /* @var $this \yii\web\View */ /* @var $content string */ use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use frontend\assets\AppAsset; use common\widgets\Alert; AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <meta charset="<?= Yii::$app->charset ?>"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <!-- FONTS --> <link href='http://fonts.googleapis.com/css?family=Roboto:100,300,700,400,500,900' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <?= $content ?> <?php $this->endBody() ?> <?= $this->render('../partial/js/glob-nav-6box.php') ?> </body> </html> <?php $this->endPage() ?>
bsd-3-clause
hansegg/nemukvideo
config/autoload/global.php
858
<?php /** * Global Configuration Override * * You can use this file for overriding configuration values from modules, etc. * You would place values in here that are agnostic to the environment and not * sensitive to security. * * @NOTE: In practice, this file will typically be INCLUDED in your source * control, so do not include passwords or other sensitive information in this * file. */ return array( 'db' => array( 'driver' => 'Pdo', 'dsn' => 'mysql:dbname=db_video;host=localhost', 'username' => 'root', 'password' => '', 'driver_options' => array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' ), ), 'service_manager' => array( 'factories' => array( 'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory', ), ), );
bsd-3-clause
AgooDev/Agoo
routes/currencies.js
3698
/** * Copyright (c) 2016-present, Agoo.com.co <http://www.agoo.com.co>. * 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 or translated in the assets folder. */ // Load required packages var logger = require('../config/logger').logger; var Currency = require('../models/currencies').Currency; // ENDPOINT: /currencies METHOD: GET exports.getCurrencies = function(req, res){ // Use the 'Currencies' model to find all Currencies Currency.find(function (err, currencies) { // Check for errors and show message if(err){ logger.error(err); res.send(err); } // success res.json(currencies); }); }; // ENDPOINT: /currencies/:id METHOD: GET exports.getCurrencyById = function(req, res){ // Use the 'Currencies' model to find single Currencies Currency.findById(req.params.id, function (err, currency) { // Check for errors and show message if(err){ logger.error(err); res.send(err); } // success res.json(currency); }); }; // ENDPOINT: /currencies METHOD: POST exports.postCurrency = function (req, res) { // Create a new instance of the Currencies model var currency = new Currency(); // Set the Currencies properties that came from the POST data currency.name = req.body.name; currency.save(function(err){ // Check for errors and show message if(err){ logger.error(err); res.send(err); } // success res.json({ message: 'Currency created successfully!', data: currency }); }); }; // ENDPOINT: /currencies/:id METHOD: PUT exports.putCurrency = function(req, res){ Currency.findById(req.params.id, function (err, currency) { // Check for errors and show message if(err){ logger.error(err); res.send(err); } // Set the Currencies properties that came from the PUT data currency.name = req.body.name; currency.enabled = req.body.enabled; currency.save(function(err){ // Check for errors and show message if(err){ logger.error(err); res.send(err); } // success res.json({message: 'Currency updated successfully', data: currency }); }); }); }; // ENDPOINT: /currencies/:id METHOD: PATCH exports.patchCurrency = function(req, res){ Currency.findById(req.params.id, function (err, currency) { // Check for errors and show message if(err){ logger.error(err); res.send(err); } currency.enabled = req.body.enabled; currency.save(function(err){ // Check for errors and show message if(err){ logger.error(err); res.send(err); } var message = ''; if(currency.enabled === true){ message = 'Currency enabled successfully'; }else{ message = 'Currency disbled successfully'; } // success res.json({message: message, data: currency }); }); }); }; // ENDPOINT: /currencies/:id METHOD: DELETE exports.deleteCurrency = function(req, res){ Currency.findByIdAndRemove(req.params.id, function(err){ // Check for errors and show message if(err){ logger.error(err); res.send(err); } // success res.json({ message: 'Currency deleted successfully!' }); }); };
bsd-3-clause
gtaylor/btmux_battlesnake
battlesnake/plugins/contrib/arena_master/staging_room/inbound_commands.py
10965
from twisted.internet.defer import inlineCallbacks from battlesnake.core.inbound_command_handling.base import BaseCommand, \ CommandError from battlesnake.core.inbound_command_handling.command_table import \ InboundCommandTable from battlesnake.outbound_commands import think_fn_wrappers from battlesnake.outbound_commands import mux_commands from battlesnake.plugins.contrib.factions.api import get_faction from battlesnake.plugins.contrib.factions.defines import DEFENDER_FACTION_DBREF from battlesnake.plugins.contrib.unit_library.api import get_unit_by_ref, \ get_ref_unit_pool from battlesnake.plugins.contrib.unit_spawning.outbound_commands import \ create_unit from battlesnake.plugins.contrib.arena_master.puppets.defines import \ GAME_STATE_STAGING, GAME_STATE_FINISHED, GAME_STATE_IN_BETWEEN, \ ARENA_DIFFICULTY_LEVELS, GAME_STATE_ACTIVE from battlesnake.plugins.contrib.arena_master.puppets.puppet_store import \ PUPPET_STORE from battlesnake.plugins.contrib.arena_master.staging_room.idesc import \ pemit_staging_room_idesc from battlesnake.plugins.contrib.arena_master.arena_crud.destruction import \ destroy_arena class ArenaInternalDescriptionCommand(BaseCommand): """ This gets emitted immediately following the staging room's name line, giving it the appearance of being the room's description. It contains a summary of the status of the arena. """ command_name = "am_arenaidesc" #@inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol arena_master_dbref = parsed_line.kwargs['arena_dbref'] try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError( "Invalid arena ID. Please notify a staff member.") pemit_staging_room_idesc(p, puppet, invoker_dbref) class SimpleSpawnCommand(BaseCommand): """ A really basic spawn command we can use to test arenas. """ command_name = "am_simplespawn" @inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol unit_ref = parsed_line.kwargs['unit_ref'] arena_master_dbref = parsed_line.kwargs['arena_master_dbref'] try: ref_pool = yield get_ref_unit_pool(unit_ref) except ValueError: raise CommandError('Invalid unit reference!') if ref_pool == 'ai': raise CommandError("You may only spawn human pool units.") try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError('Invalid puppet dbref: %s' % arena_master_dbref) game_state = puppet.game_state if game_state == GAME_STATE_STAGING: raise CommandError( "The match hasn't started yet. The arena leader still needs " "to %ch%cgbegin%cn.") elif game_state == GAME_STATE_FINISHED: raise CommandError("The match is already over!") elif game_state != GAME_STATE_IN_BETWEEN: raise CommandError("You can only spawn between waves.") yield think_fn_wrappers.btsetcharvalue(p, invoker_dbref, 'bruise', 0, 0) yield think_fn_wrappers.btsetcharvalue(p, invoker_dbref, 'lethal', 0, 0) map_dbref = puppet.map_dbref faction = get_faction(DEFENDER_FACTION_DBREF) unit_x, unit_y = puppet.get_defender_spawn_coords() unit = yield get_unit_by_ref(unit_ref) unit_dbref = yield create_unit( p, unit.reference, map_dbref, faction, unit_x, unit_y, pilot_dbref=invoker_dbref, zone_dbref=arena_master_dbref) yield think_fn_wrappers.tel(p, invoker_dbref, unit_dbref) yield mux_commands.force(p, invoker_dbref, 'startup') message = ( "[name({invoker_dbref})] has spawned a " "%ch[ucstr({unit_ref})]%cn.".format( invoker_dbref=invoker_dbref, unit_ref=unit_ref) ) puppet.pemit_throughout_zone(message) class BeginMatchCommand(BaseCommand): """ Gets the party started. Allows spawning, sets to "In-Between" state, and is one command away from releasing the kraken. """ command_name = "am_beginmatch" @inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol arena_master_dbref = parsed_line.kwargs['arena_master_dbref'] try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError('Invalid puppet dbref: %s' % arena_master_dbref) leader_dbref = puppet.leader_dbref if leader_dbref != invoker_dbref: raise CommandError("Only the arena leader can do that.") game_state = puppet.game_state if game_state == GAME_STATE_FINISHED: raise CommandError("The match is already over!") elif game_state != GAME_STATE_STAGING: raise CommandError("The match has already begun!") yield puppet.change_game_state(GAME_STATE_IN_BETWEEN) puppet.pemit_throughout_zone( "The match has begun. You may now %ch%cgspawn%cn.") class EndMatchCommand(BaseCommand): """ Lets the arena leader end the match and clean the arena up. """ command_name = "am_endmatch" @inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol arena_master_dbref = parsed_line.kwargs['arena_master_dbref'] try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError('Invalid puppet dbref: %s' % arena_master_dbref) leader_dbref = puppet.leader_dbref if leader_dbref != invoker_dbref: raise CommandError("Only the arena leader can do that.") game_state = puppet.game_state if game_state == GAME_STATE_ACTIVE: raise CommandError("You can't end a match while a wave is underway.") if game_state != GAME_STATE_FINISHED: yield puppet.change_game_state(GAME_STATE_FINISHED) puppet.pemit_throughout_zone( "[name({invoker_dbref})] has ended the match.".format( invoker_dbref=invoker_dbref)) yield destroy_arena(p, arena_master_dbref) class AbortWaveCommand(BaseCommand): """ Prematurely aborts the wave. """ command_name = "am_abortwave" @inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol arena_master_dbref = parsed_line.kwargs['arena_master_dbref'] try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError('Invalid puppet dbref: %s' % arena_master_dbref) leader_dbref = puppet.leader_dbref if leader_dbref != invoker_dbref: raise CommandError("Only the arena leader can do that.") game_state = puppet.game_state if game_state != GAME_STATE_ACTIVE: raise CommandError("You can only abort active matches.") yield puppet.change_state_to_finished(p) puppet.pemit_throughout_zone( "[name({invoker_dbref})] has aborted the match.".format( invoker_dbref=invoker_dbref)) class RestartMatchCommand(BaseCommand): """ Lets the arena leader reset the arena to wave 1 and go again. """ command_name = "am_restartmatch" @inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol arena_master_dbref = parsed_line.kwargs['arena_master_dbref'] try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError('Invalid puppet dbref: %s' % arena_master_dbref) leader_dbref = puppet.leader_dbref if leader_dbref != invoker_dbref: raise CommandError("Only the arena leader can do that.") game_state = puppet.game_state if game_state != GAME_STATE_FINISHED: raise CommandError("You can only restart a finished match.") yield puppet.reset_arena() class TransferLeaderStatusCommand(BaseCommand): """ Transfers the arena leader status to someone else. """ command_name = "am_transferleader" @inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol arena_master_dbref = parsed_line.kwargs['arena_master_dbref'] new_leader_dbref = parsed_line.kwargs['new_leader_dbref'] try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError('Invalid puppet dbref: %s' % arena_master_dbref) leader_dbref = puppet.leader_dbref if leader_dbref != invoker_dbref: raise CommandError("Only the arena leader can do that.") message = ( "%ch%cy[name({invoker_dbref})]%cw has transferred arena leadership " "to %cc[name({new_leader_dbref})]%cw.%cn".format( invoker_dbref=invoker_dbref, new_leader_dbref=new_leader_dbref)) puppet.pemit_throughout_zone(message) yield puppet.set_arena_leader(new_leader_dbref) class SetDifficultyCommand(BaseCommand): """ Used to adjust an arena's difficulty modifier. """ command_name = "am_setdifficulty" @inlineCallbacks def run(self, protocol, parsed_line, invoker_dbref): p = protocol arena_master_dbref = parsed_line.kwargs['arena_master_dbref'] difficulty_level = parsed_line.kwargs['difficulty_level'] try: puppet = PUPPET_STORE.get_puppet_by_dbref(arena_master_dbref) except KeyError: raise CommandError('Invalid puppet dbref: %s' % arena_master_dbref) leader_dbref = puppet.leader_dbref if leader_dbref != invoker_dbref: raise CommandError("Only the arena leader can do that.") game_state = puppet.game_state if game_state != GAME_STATE_STAGING: raise CommandError( "Difficulty can only be adjusted during pre-match staging.") difficulty_level = difficulty_level.lower() if difficulty_level not in ARENA_DIFFICULTY_LEVELS: raise CommandError( "Invalid difficulty level. Must be one of: %s" % ( ', '.join(ARENA_DIFFICULTY_LEVELS),) ) yield puppet.set_difficulty(difficulty_level) class ArenaStagingRoomCommandTable(InboundCommandTable): commands = [ ArenaInternalDescriptionCommand, SetDifficultyCommand, BeginMatchCommand, SimpleSpawnCommand, EndMatchCommand, AbortWaveCommand, RestartMatchCommand, TransferLeaderStatusCommand, ]
bsd-3-clause
fndomariano/budget-zf2
module/Application/tests/src/Application/Controller/ClientControllerTest.php
4007
<?php namespace Application\Controller; use Core\Test\ControllerTestCase; use Application\Controller\IndexController; use Application\Model\Client; use Zend\Http\Request; use Zend\Stdlib\Parameters; use Zend\View\Renderer\PhpRenderer; /** * @group Controller */ class ClientControllerTest extends ControllerTestCase { /** * Namespace completa do Controller * @var string */ protected $controllerFQDN = 'Application\Controller\ClientController'; /** * Nome da rota. Geralmente o nome do módulo * @var string */ protected $controllerRoute = 'application'; /** * Testa o acesso a uma action que não existe */ public function test404() { $this->routeMatch->setParam('action', 'action_nao_existente'); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertEquals(404, $response->getStatusCode()); } /** * Testa a página inicial, que deve mostrar os orçamentos */ public function testIndexAction() { // Cria clients para testar $clientA = $this->addClient(); $clientB = $this->addClient(); // Invoca a rota index $this->routeMatch->setParam('action', 'index'); $result = $this->controller->dispatch($this->request, $this->response); // Verifica o response $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); // Testa se um ViewModel foi retornado $this->assertInstanceOf('Zend\View\Model\ViewModel', $result); // Testa os dados da view $variables = $result->getVariables(); $this->assertArrayHasKey('clients', $variables); // Faz a comparação dos dados $controllerData = $variables["clients"]->getCurrentItems()->toArray(); $this->assertEquals($clientA->name, $controllerData[0]['name']); $this->assertEquals($clientB->name, $controllerData[1]['name']); } /** * Testa a página inicial, que deve mostrar os posts com paginador */ public function testIndexActionPaginator() { // Cria clients para testar $client = array(); for($i=0; $i< 25; $i++) { $client[] = $this->addClient(); } // Invoca a rota index $this->routeMatch->setParam('action', 'index'); $result = $this->controller->dispatch($this->request, $this->response); // Verifica o response $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); // Testa se um ViewModel foi retornado $this->assertInstanceOf('Zend\View\Model\ViewModel', $result); // Testa os dados da view $variables = $result->getVariables(); $this->assertArrayHasKey('clients', $variables); //testa o paginator $paginator = $variables["clients"]; $this->assertEquals('Zend\Paginator\Paginator', get_class($paginator)); $clients = $paginator->getCurrentItems()->toArray(); $this->assertEquals(10, count($clients)); $this->assertEquals($client[0]->id, $clients[0]['id']); $this->assertEquals($client[1]->id, $clients[1]['id']); //testa a terceira página da paginação $this->routeMatch->setParam('action', 'index'); $this->routeMatch->setParam('page', 3); $result = $this->controller->dispatch($this->request, $this->response); $variables = $result->getVariables(); $controllerData = $variables["clients"]->getCurrentItems()->toArray(); $this->assertEquals(5, count($controllerData)); } /** * Adiciona um orçamento para os testes */ private function addClient() { $client = new Client(); $client->name = 'Fernando Mariano'; $client->email = 'fernando.mar16@gmail.com'; $client->phone = '(47)8853-6307'; $saved = $this->getTable('Application\Model\Client')->save($client); return $saved; } }
bsd-3-clause
lifei/flask-admin
flask_admin/tests/geoa/test_basic.py
7096
from __future__ import unicode_literals import json import re from flask_admin.contrib.geoa import ModelView from flask_admin.contrib.geoa.fields import GeoJSONField from geoalchemy2 import Geometry from geoalchemy2.shape import to_shape from nose.tools import eq_, ok_ from . import setup def create_models(db): class GeoModel(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20)) point = db.Column(Geometry("POINT")) line = db.Column(Geometry("LINESTRING")) polygon = db.Column(Geometry("POLYGON")) multi = db.Column(Geometry("MULTIPOINT")) def __unicode__(self): return self.name db.create_all() return GeoModel def test_model(): app, db, admin = setup() GeoModel = create_models(db) db.create_all() GeoModel.query.delete() db.session.commit() view = ModelView(GeoModel, db.session) admin.add_view(view) eq_(view.model, GeoModel) eq_(view._primary_key, 'id') # Verify form eq_(view._create_form_class.point.field_class, GeoJSONField) eq_(view._create_form_class.point.kwargs['geometry_type'], "POINT") eq_(view._create_form_class.line.field_class, GeoJSONField) eq_(view._create_form_class.line.kwargs['geometry_type'], "LINESTRING") eq_(view._create_form_class.polygon.field_class, GeoJSONField) eq_(view._create_form_class.polygon.kwargs['geometry_type'], "POLYGON") eq_(view._create_form_class.multi.field_class, GeoJSONField) eq_(view._create_form_class.multi.kwargs['geometry_type'], "MULTIPOINT") # Make some test clients client = app.test_client() rv = client.get('/admin/geomodel/') eq_(rv.status_code, 200) rv = client.get('/admin/geomodel/new/') eq_(rv.status_code, 200) rv = client.post('/admin/geomodel/new/', data={ "name": "test1", "point": '{"type": "Point", "coordinates": [125.8, 10.0]}', "line": '{"type": "LineString", "coordinates": [[50.2345, 94.2], [50.21, 94.87]]}', "polygon": '{"type": "Polygon", "coordinates": [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]}', "multi": '{"type": "MultiPoint", "coordinates": [[100.0, 0.0], [101.0, 1.0]]}', }) eq_(rv.status_code, 302) model = db.session.query(GeoModel).first() eq_(model.name, "test1") eq_(to_shape(model.point).geom_type, "Point") eq_(list(to_shape(model.point).coords), [(125.8, 10.0)]) eq_(to_shape(model.line).geom_type, "LineString") eq_(list(to_shape(model.line).coords), [(50.2345, 94.2), (50.21, 94.87)]) eq_(to_shape(model.polygon).geom_type, "Polygon") eq_(list(to_shape(model.polygon).exterior.coords), [(100.0, 0.0), (101.0, 0.0), (101.0, 1.0), (100.0, 1.0), (100.0, 0.0)]) eq_(to_shape(model.multi).geom_type, "MultiPoint") eq_(len(to_shape(model.multi).geoms), 2) eq_(list(to_shape(model.multi).geoms[0].coords), [(100.0, 0.0)]) eq_(list(to_shape(model.multi).geoms[1].coords), [(101.0, 1.0)]) rv = client.get('/admin/geomodel/') eq_(rv.status_code, 200) html = rv.data.decode('utf-8') pattern = r'(.|\n)+({.*"type": ?"Point".*})</textarea>(.|\n)+' group = re.match(pattern, html).group(2) p = json.loads(group) eq_(p['coordinates'][0], 125.8) eq_(p['coordinates'][1], 10.0) url = '/admin/geomodel/edit/?id=%s' % model.id rv = client.get(url) eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_(r' name="multi">{"type":"MultiPoint","coordinates":[[100,0],[101,1]]}</textarea>' in data) # rv = client.post(url, data={ # "name": "edited", # "point": '{"type": "Point", "coordinates": [99.9, 10.5]}', # "line": '', # set to NULL in the database # }) # eq_(rv.status_code, 302) # # model = db.session.query(GeoModel).first() # eq_(model.name, "edited") # eq_(to_shape(model.point).geom_type, "Point") # eq_(list(to_shape(model.point).coords), [(99.9, 10.5)]) # eq_(to_shape(model.line), None) # eq_(to_shape(model.polygon).geom_type, "Polygon") # eq_(list(to_shape(model.polygon).exterior.coords), # [(100.0, 0.0), (101.0, 0.0), (101.0, 1.0), (100.0, 1.0), (100.0, 0.0)]) # eq_(to_shape(model.multi).geom_type, "MultiPoint") # eq_(len(to_shape(model.multi).geoms), 2) # eq_(list(to_shape(model.multi).geoms[0].coords), [(100.0, 0.0)]) # eq_(list(to_shape(model.multi).geoms[1].coords), [(101.0, 1.0)]) url = '/admin/geomodel/delete/?id=%s' % model.id rv = client.post(url) eq_(rv.status_code, 302) eq_(db.session.query(GeoModel).count(), 0) def test_mapbox_fix_point_coordinates(): app, db, admin = setup() app.config['MAPBOX_FIX_COORDINATES_ORDER'] = True GeoModel = create_models(db) db.create_all() GeoModel.query.delete() db.session.commit() view = ModelView(GeoModel, db.session) admin.add_view(view) # Make some test clients client = app.test_client() rv = client.post('/admin/geomodel/new/', data={ "name": "test1", "point": '{"type": "Point", "coordinates": [125.8, 10.0]}', "line": '{"type": "LineString", "coordinates": [[50.2345, 94.2], [50.21, 94.87]]}', "polygon": '{"type": "Polygon", "coordinates": [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]}', "multi": '{"type": "MultiPoint", "coordinates": [[100.0, 0.0], [101.0, 1.0]]}', }) model = db.session.query(GeoModel).first() # Notice how the coordinates are reversed here, i.e. longitude first which # is the way it's stored in PostGIS columns. eq_(list(to_shape(model.point).coords), [(10.0, 125.8)]) eq_(list(to_shape(model.line).coords), [(94.2, 50.2345), (94.87, 50.21)]) eq_(list(to_shape(model.polygon).exterior.coords), [(0.0, 100.0), (0.0, 101.0), (1.0, 101.0), (1.0, 100.0), (0.0, 100.0)]) eq_(list(to_shape(model.multi).geoms[0].coords), [(0.0, 100.0)]) eq_(list(to_shape(model.multi).geoms[1].coords), [(1.0, 101.0)]) rv = client.get('/admin/geomodel/') eq_(rv.status_code, 200) html = rv.data.decode('utf-8') pattern = r'(.|\n)+({.*"type": ?"Point".*})</textarea>(.|\n)+' group = re.match(pattern, html).group(2) p = json.loads(group) # Reversed order again, so that it's parsed correctly by leaflet eq_(p['coordinates'][0], 10.0) eq_(p['coordinates'][1], 125.8) def test_none(): app, db, admin = setup() GeoModel = create_models(db) db.create_all() GeoModel.query.delete() db.session.commit() view = ModelView(GeoModel, db.session) admin.add_view(view) # Make some test clients client = app.test_client() rv = client.post('/admin/geomodel/new/', data={ "name": "test1", }) eq_(rv.status_code, 302) model = db.session.query(GeoModel).first() url = '/admin/geomodel/edit/?id=%s' % model.id rv = client.get(url) eq_(rv.status_code, 200) data = rv.data.decode('utf-8') ok_(r' name="point"></textarea>' in data)
bsd-3-clause
leesab/irods
iRODS/server/re/src/reNaraMetaData.cpp
2904
/** * @file reNaraMetaData.c * */ #include "reNaraMetaData.hpp" #include "apiHeaderAll.hpp" #include "irods_stacktrace.hpp" /** * \fn msiExtractNaraMetadata (ruleExecInfo_t *rei) * * \brief This microservice extracts NARA style metadata from a local configuration file. * * \module core * * \since pre-2.1 * * \author DICE * \date 2007 * * \usage See clients/icommands/test/rules3.0/ * * \param[in,out] rei - The RuleExecInfo structure that is automatically * handled by the rule engine. The user does not include rei as a * parameter in the rule invocation. * * \DolVarDependence none * \DolVarModified none * \iCatAttrDependence none * \iCatAttrModified none * \sideeffect none * * \return integer * \retval 0 on success * \pre none * \post none * \sa none **/ int msiExtractNaraMetadata( ruleExecInfo_t *rei ) { FILE *fp; char str[500]; char *substring; int counter; int flag; char attr[100]; char value[500]; modAVUMetadataInp_t modAVUMetadataInp; int status; /* specify the location of the metadata file here */ char metafile[MAX_NAME_LEN]; snprintf( metafile, MAX_NAME_LEN, "%-s/reConfigs/%-s", getConfigDir(), NARA_META_DATA_FILE ); if ( ( fp = fopen( metafile, "r" ) ) == NULL ) { rodsLog( LOG_ERROR, "msiExtractNaraMetadata: Cannot open the metadata file %s.", metafile ); return ( UNIX_FILE_OPEN_ERR ); } memset( &modAVUMetadataInp, 0, sizeof( modAVUMetadataInp ) ); modAVUMetadataInp.arg0 = "add"; while ( !feof( fp ) ) { counter = 0; flag = 0; if ( fgets( str, 500, fp ) ) { substring = strtok( str, "|" ); while ( substring != NULL ) { if ( flag == 0 && strcmp( substring, rei->doi->objPath ) == 0 ) { flag = 2; } if ( counter == 1 ) { strcpy( attr, substring ); } if ( flag == 2 && counter == 2 ) { strcpy( value, substring ); /*Call the function to insert metadata here.*/ modAVUMetadataInp.arg1 = "-d"; modAVUMetadataInp.arg2 = rei->doi->objPath; modAVUMetadataInp.arg3 = attr; modAVUMetadataInp.arg4 = value; modAVUMetadataInp.arg5 = ""; status = rsModAVUMetadata( rei->rsComm, &modAVUMetadataInp ); if ( status < 0 ) { irods::log( ERROR( status, "rsModAVUMetadata failed." ) ); } rodsLog( LOG_DEBUG, "msiExtractNaraMetadata: %s:%s", attr, value ); } substring = strtok( NULL, "|" ); counter++; } } } fclose( fp ); return( 0 ); }
bsd-3-clause
snowman1ng/SoundManager2-Seek-Reverse
demo/bar-ui/script/bar-ui.js
41962
/*jslint plusplus: true, white: true, nomen: true */ /*global console, document, navigator, soundManager, window */ (function(window) { /** * SoundManager 2: "Bar UI" player * Copyright (c) 2014, Scott Schiller. All rights reserved. * http://www.schillmania.com/projects/soundmanager2/ * Code provided under BSD license. * http://schillmania.com/projects/soundmanager2/license.txt */ "use strict"; var Player, players = [], // CSS selector that will get us the top-level DOM node for the player UI. playerSelector = '.sm2-bar-ui', playerOptions, utils; /** * Slightly hackish: event callbacks. * Override globally by setting window.sm2BarPlayers.on = {}, or individually by window.sm2BarPlayers[0].on = {} etc. */ players.on = { /* play: function(player) { console.log('playing', player); }, finish: function(player) { // each sound console.log('finish', player); }, pause: function(player) { console.log('pause', player); }, error: function(player) { console.log('error', player); } end: function(player) { // end of playlist console.log('end', player); } */ }; playerOptions = { // useful when multiple players are in use, or other SM2 sounds are active etc. stopOtherSounds: true, // CSS class to let the browser load the URL directly e.g., <a href="foo.mp3" class="sm2-exclude">download foo.mp3</a> excludeClass: 'sm2-exclude' }; soundManager.setup({ // trade-off: higher UI responsiveness (play/progress bar), but may use more CPU. html5PollingInterval: 50, flashVersion: 9 }); soundManager.onready(function() { var nodes, i, j; nodes = utils.dom.getAll(playerSelector); if (nodes && nodes.length) { for (i=0, j=nodes.length; i<j; i++) { players.push(new Player(nodes[i])); } } }); /** * player bits */ Player = function(playerNode) { var css, dom, extras, playlistController, soundObject, actions, actionData, defaultItem, defaultVolume, firstOpen, exports; css = { disabled: 'disabled', selected: 'selected', active: 'active', legacy: 'legacy', noVolume: 'no-volume', playlistOpen: 'playlist-open' }; dom = { o: null, playlist: null, playlistTarget: null, playlistContainer: null, time: null, player: null, progress: null, progressTrack: null, progressBar: null, duration: null, volume: null }; // prepended to tracks when a sound fails to load/play extras = { loadFailedCharacter: '<span title="Failed to load/play." class="load-error">✖</span>' }; function stopOtherSounds() { if (playerOptions.stopOtherSounds) { soundManager.stopAll(); } } function callback(method) { if (method) { // fire callback, passing current turntable object if (exports.on && exports.on[method]) { exports.on[method](exports); } else if (players.on[method]) { players.on[method](exports); } } } function getTime(msec, useString) { // convert milliseconds to hh:mm:ss, return as object literal or string var nSec = Math.floor(msec/1000), hh = Math.floor(nSec/3600), min = Math.floor(nSec/60) - Math.floor(hh * 60), sec = Math.floor(nSec -(hh*3600) -(min*60)); // if (min === 0 && sec === 0) return null; // return 0:00 as null return (useString ? ((hh ? hh + ':' : '') + (hh && min < 10 ? '0' + min : min) + ':' + ( sec < 10 ? '0' + sec : sec ) ) : { 'min': min, 'sec': sec }); } function setTitle(item) { // given a link, update the "now playing" UI. // if this is an <li> with an inner link, grab and use the text from that. var links = item.getElementsByTagName('a'); if (links.length) { item = links[0]; } // remove any failed character sequence, also dom.playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li>' + item.innerHTML.replace(extras.loadFailedCharacter, '') + '</li></ul>'; if (dom.playlistTarget.getElementsByTagName('li')[0].scrollWidth > dom.playlistTarget.offsetWidth) { // this item can use <marquee>, in fact. dom.playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li><marquee>' + item.innerHTML + '</marquee></li></ul>'; } } function makeSound(url) { var sound = soundManager.createSound({ url: url, volume: defaultVolume, whileplaying: function() { var progressMaxLeft = 100, left, width; left = Math.min(progressMaxLeft, Math.max(0, (progressMaxLeft * (this.position / this.durationEstimate)))) + '%'; width = Math.min(100, Math.max(0, (100 * this.position / this.durationEstimate))) + '%'; if (this.duration) { dom.progress.style.left = left; dom.progressBar.style.width = width; // TODO: only write changes dom.time.innerHTML = getTime(this.position, true); } }, onbufferchange: function(isBuffering) { if (isBuffering) { utils.css.add(dom.o, 'buffering'); } else { utils.css.remove(dom.o, 'buffering'); } }, onplay: function() { utils.css.swap(dom.o, 'paused', 'playing'); callback('play'); }, onpause: function() { utils.css.swap(dom.o, 'playing', 'paused'); callback('pause'); }, onresume: function() { utils.css.swap(dom.o, 'paused', 'playing'); }, whileloading: function() { if (!this.isHTML5) { dom.duration.innerHTML = getTime(this.durationEstimate, true); } }, onload: function(ok) { if (ok) { dom.duration.innerHTML = getTime(this.duration, true); } else if (this._iO && this._iO.onerror) { this._iO.onerror(); } }, onerror: function() { // sound failed to load. var item, element, html; item = playlistController.getItem(); if (item) { // note error, delay 2 seconds and advance? // playlistTarget.innerHTML = '<ul class="sm2-playlist-bd"><li>' + item.innerHTML + '</li></ul>'; if (extras.loadFailedCharacter) { dom.playlistTarget.innerHTML = dom.playlistTarget.innerHTML.replace('<li>' ,'<li>' + extras.loadFailedCharacter + ' '); if (playlistController.data.playlist && playlistController.data.playlist[playlistController.data.selectedIndex]) { element = playlistController.data.playlist[playlistController.data.selectedIndex].getElementsByTagName('a')[0]; html = element.innerHTML; if (html.indexOf(extras.loadFailedCharacter) === -1) { element.innerHTML = extras.loadFailedCharacter + ' ' + html; } } } } callback('error'); // load next, possibly with delay. if (navigator.userAgent.match(/mobile/i)) { // mobile will likely block the next play() call if there is a setTimeout() - so don't use one here. actions.next(); } else { if (playlistController.data.timer) { window.clearTimeout(playlistController.data.timer); } playlistController.data.timer = window.setTimeout(actions.next, 2000); } }, onstop: function() { utils.css.remove(dom.o, 'playing'); }, onfinish: function() { var lastIndex, item; utils.css.remove(dom.o, 'playing'); dom.progress.style.left = '0%'; lastIndex = playlistController.data.selectedIndex; callback('finish'); // next track? item = playlistController.getNext(); // don't play the same item over and over again, if at end of playlist etc. if (item && playlistController.data.selectedIndex !== lastIndex) { playlistController.select(item); setTitle(item); stopOtherSounds(); // play next this.play({ url: playlistController.getURL() }); } else { // end of playlist case // explicitly stop? // this.stop(); callback('end'); } } }); return sound; } function playLink(link) { // if a link is OK, play it. if (soundManager.canPlayURL(link.href)) { // if there's a timer due to failure to play one track, cancel it. // catches case when user may use previous/next after an error. if (playlistController.data.timer) { window.clearTimeout(playlistController.data.timer); playlistController.data.timer = null; } if (!soundObject) { soundObject = makeSound(link.href); } // required to reset pause/play state on iOS so whileplaying() works? odd. soundObject.stop(); playlistController.select(link.parentNode); setTitle(link.parentNode); // reset the UI // TODO: function that also resets/hides timing info. dom.progress.style.left = '0px'; dom.progressBar.style.width = '0px'; stopOtherSounds(); soundObject.play({ url: link.href, position: 0 }); } } function PlaylistController() { var data; data = { // list of nodes? playlist: [], // NOTE: not implemented yet. // shuffledIndex: [], // shuffleMode: false, // selection selectedIndex: 0, loopMode: false, timer: null }; function getPlaylist() { return data.playlist; } function getItem(offset) { var list, item; // given the current selection (or an offset), return the current item. // if currently null, may be end of list case. bail. if (data.selectedIndex === null) { return offset; } list = getPlaylist(); // use offset if provided, otherwise take default selected. offset = (offset !== undefined ? offset : data.selectedIndex); // safety check - limit to between 0 and list length offset = Math.max(0, Math.min(offset, list.length)); item = list[offset]; return item; } function findOffsetFromItem(item) { // given an <li> item, find it in the playlist array and return the index. var list, i, j, offset; offset = -1; list = getPlaylist(); if (list) { for (i=0, j=list.length; i<j; i++) { if (list[i] === item) { offset = i; break; } } } return offset; } function getNext() { // don't increment if null. if (data.selectedIndex !== null) { data.selectedIndex++; } if (data.playlist.length > 1) { if (data.selectedIndex >= data.playlist.length) { if (data.loopMode) { // loop to beginning data.selectedIndex = 0; } else { // no change data.selectedIndex--; // end playback // data.selectedIndex = null; } } } else { data.selectedIndex = null; } return getItem(); } function getPrevious() { data.selectedIndex--; if (data.selectedIndex < 0) { // wrapping around beginning of list? loop or exit. if (data.loopMode) { data.selectedIndex = data.playlist.length - 1; } else { // undo data.selectedIndex++; } } return getItem(); } function resetLastSelected() { // remove UI highlight(s) on selected items. var items, i, j; items = utils.dom.getAll(dom.playlist, '.' + css.selected); for (i=0, j=items.length; i<j; i++) { utils.css.remove(items[i], css.selected); } } function select(item) { var offset, itemTop, itemBottom, containerHeight, scrollTop, itemPadding, liElement; // remove last selected, if any resetLastSelected(); if (item) { liElement = utils.dom.ancestor('li', item); utils.css.add(liElement, css.selected); itemTop = item.offsetTop; itemBottom = itemTop + item.offsetHeight; containerHeight = dom.playlistContainer.offsetHeight; scrollTop = dom.playlist.scrollTop; itemPadding = 8; if (itemBottom > containerHeight + scrollTop) { // bottom-align dom.playlist.scrollTop = itemBottom - containerHeight + itemPadding; } else if (itemTop < scrollTop) { // top-align dom.playlist.scrollTop = item.offsetTop - itemPadding; } } // update selected offset, too. offset = findOffsetFromItem(liElement); data.selectedIndex = offset; } function playItemByOffset(offset) { var item; offset = (offset || 0); item = getItem(offset); if (item) { playLink(item.getElementsByTagName('a')[0]); } } function getURL() { // return URL of currently-selected item var item, url; item = getItem(); if (item) { url = item.getElementsByTagName('a')[0].href; } return url; } function refreshDOM() { // get / update playlist from DOM if (!dom.playlist) { if (window.console && console.warn) { console.warn('refreshDOM(): playlist node not found?'); } return false; } data.playlist = dom.playlist.getElementsByTagName('li'); } function initDOM() { dom.playlistTarget = utils.dom.get(dom.o, '.sm2-playlist-target'); dom.playlistContainer = utils.dom.get(dom.o, '.sm2-playlist-drawer'); dom.playlist = utils.dom.get(dom.o, '.sm2-playlist-bd'); } function init() { // inherit the default SM2 volume defaultVolume = soundManager.defaultOptions.volume; initDOM(); refreshDOM(); // animate playlist open, if HTML classname indicates so. if (utils.css.has(dom.o, css.playlistOpen)) { // hackish: run this after API has returned window.setTimeout(function() { actions.menu(true); }, 1); } } init(); return { data: data, refresh: refreshDOM, getNext: getNext, getPrevious: getPrevious, getItem: getItem, getURL: getURL, playItemByOffset: playItemByOffset, select: select }; } function isRightClick(e) { // only pay attention to left clicks. old IE differs where there's no e.which, but e.button is 1 on left click. if (e && ((e.which && e.which === 2) || (e.which === undefined && e.button !== 1))) { // http://www.quirksmode.org/js/events_properties.html#button return true; } } function getActionData(target) { // DOM measurements for volume slider if (!target) { return false; } actionData.volume.x = utils.position.getOffX(target); actionData.volume.y = utils.position.getOffY(target); actionData.volume.width = target.offsetWidth; actionData.volume.height = target.offsetHeight; // potentially dangerous: this should, but may not be a percentage-based value. actionData.volume.backgroundSize = parseInt(utils.style.get(target, 'background-size'), 10); // IE gives pixels even if background-size specified as % in CSS. Boourns. if (window.navigator.userAgent.match(/msie|trident/i)) { actionData.volume.backgroundSize = (actionData.volume.backgroundSize / actionData.volume.width) * 100; } } function handleMouseDown(e) { var links, target; target = e.target || e.srcElement; if (isRightClick(e)) { return true; } // normalize to <a>, if applicable. if (target.nodeName.toLowerCase() !== 'a') { links = target.getElementsByTagName('a'); if (links && links.length) { target = target.getElementsByTagName('a')[0]; } } if (utils.css.has(target, 'sm2-volume-control')) { // drag case for volume getActionData(target); utils.events.add(document, 'mousemove', actions.adjustVolume); utils.events.add(document, 'mouseup', actions.releaseVolume); // and apply right away return actions.adjustVolume(e); } } function handleClick(e) { var evt, target, offset, targetNodeName, methodName, href, handled; evt = (e || window.event); target = evt.target || evt.srcElement; if (target && target.nodeName) { targetNodeName = target.nodeName.toLowerCase(); if (targetNodeName !== 'a') { // old IE (IE 8) might return nested elements inside the <a>, eg., <b> etc. Try to find the parent <a>. if (target.parentNode) { do { target = target.parentNode; targetNodeName = target.nodeName.toLowerCase(); } while (targetNodeName !== 'a' && target.parentNode); if (!target) { // something went wrong. bail. return false; } } } if (targetNodeName === 'a') { // yep, it's a link. href = target.href; if (soundManager.canPlayURL(href)) { // not excluded if (!utils.css.has(target, playerOptions.excludeClass)) { // find this in the playlist playLink(target); handled = true; } } else { // is this one of the action buttons, eg., play/pause, volume, etc.? offset = target.href.lastIndexOf('#'); if (offset !== -1) { methodName = target.href.substr(offset+1); if (methodName && actions[methodName]) { handled = true; actions[methodName](e); } } } // fall-through case if (handled) { // prevent browser fall-through return utils.events.preventDefault(evt); } } } } function handleMouse(e) { var target, barX, barWidth, x, newPosition, sound; target = dom.progressTrack; barX = utils.position.getOffX(target); barWidth = target.offsetWidth; x = (e.clientX - barX); newPosition = (x / barWidth); sound = soundObject; if (sound && sound.duration) { sound.setPosition(sound.duration * newPosition); // a little hackish: ensure UI updates immediately with current position, even if audio is buffering and hasn't moved there yet. if (sound._iO && sound._iO.whileplaying) { sound._iO.whileplaying.apply(sound); } } if (e.preventDefault) { e.preventDefault(); } return false; } function releaseMouse(e) { utils.events.remove(document, 'mousemove', handleMouse); utils.css.remove(dom.o, 'grabbing'); utils.events.remove(document, 'mouseup', releaseMouse); utils.events.preventDefault(e); return false; } function init() { // init DOM? if (!playerNode) { console.warn('init(): No playerNode element?'); } dom.o = playerNode; // are we dealing with a crap browser? apply legacy CSS if so. if (window.navigator.userAgent.match(/msie [678]/i)) { utils.css.add(dom.o, css.legacy); } if (window.navigator.userAgent.match(/mobile/i)) { // majority of mobile devices don't let HTML5 audio set volume. utils.css.add(dom.o, css.noVolume); } dom.progress = utils.dom.get(dom.o, '.sm2-progress-ball'); dom.progressTrack = utils.dom.get(dom.o, '.sm2-progress-track'); dom.progressBar = utils.dom.get(dom.o, '.sm2-progress-bar'); dom.volume = utils.dom.get(dom.o, 'a.sm2-volume-control'); // measure volume control dimensions if (dom.volume) { getActionData(dom.volume); } dom.duration = utils.dom.get(dom.o, '.sm2-inline-duration'); dom.time = utils.dom.get(dom.o, '.sm2-inline-time'); playlistController = new PlaylistController(); defaultItem = playlistController.getItem(0); playlistController.select(defaultItem); if (defaultItem) { setTitle(defaultItem); } utils.events.add(dom.o, 'mousedown', handleMouseDown); utils.events.add(dom.o, 'click', handleClick); utils.events.add(dom.progressTrack, 'mousedown', function(e) { if (isRightClick(e)) { return true; } utils.css.add(dom.o, 'grabbing'); utils.events.add(document, 'mousemove', handleMouse); utils.events.add(document, 'mouseup', releaseMouse); return handleMouse(e); }); } // --- actionData = { volume: { x: 0, y: 0, width: 0, height: 0, backgroundSize: 0 } }; actions = { /* option to go directly to a time in the sound */ timeSeek: function(goToTime) { if (!soundObject) { console.log("SoundObject not yet created. Play it first."); return false; } else { console.log("Playing at " + goToTime + " milliseconds."); return soundObject.setPosition(goToTime); } }, play: function(offsetOrEvent) { /** * This is an overloaded function that takes mouse/touch events or offset-based item indices. * Remember, "auto-play" will not work on mobile devices unless this function is called immediately from a touch or click event. * If you have the link but not the offset, you can also pass a fake event object with a target of an <a> inside the playlist - e.g. { target: someMP3Link } */ var target, href, e; if (offsetOrEvent !== undefined && !isNaN(offsetOrEvent)) { // smells like a number. return playlistController.playItemByOffset(offsetOrEvent); } // DRY things a bit e = offsetOrEvent; if (e && e.target) { target = e.target || e.srcElement; href = target.href; } // haaaack - if null due to no event, OR '#' due to play/pause link, get first link from playlist if (!href || href.indexOf('#') !== -1) { href = dom.playlist.getElementsByTagName('a')[0].href; } if (!soundObject) { soundObject = makeSound(href); } // edge case: if the current sound is not playing, stop all others. if (!soundObject.playState) { stopOtherSounds(); } // TODO: if user pauses + unpauses a sound that had an error, try to play next? soundObject.togglePause(); // special case: clear "play next" timeout, if one exists. // edge case: user pauses after a song failed to load. if (soundObject.paused && playlistController.data.timer) { window.clearTimeout(playlistController.data.timer); playlistController.data.timer = null; } }, pause: function() { if (soundObject && soundObject.readyState) { soundObject.pause(); } }, resume: function() { if (soundObject && soundObject.readyState) { soundObject.resume(); } }, stop: function() { // just an alias for pause, really. // don't actually stop because that will mess up some UI state, i.e., dragging the slider. return actions.pause(); }, next: function(/* e */) { var item, lastIndex; // special case: clear "play next" timeout, if one exists. if (playlistController.data.timer) { window.clearTimeout(playlistController.data.timer); playlistController.data.timer = null; } lastIndex = playlistController.data.selectedIndex; item = playlistController.getNext(true); // don't play the same item again if (item && playlistController.data.selectedIndex !== lastIndex) { playLink(item.getElementsByTagName('a')[0]); } }, prev: function(/* e */) { var item, lastIndex; lastIndex = playlistController.data.selectedIndex; item = playlistController.getPrevious(); // don't play the same item again if (item && playlistController.data.selectedIndex !== lastIndex) { playLink(item.getElementsByTagName('a')[0]); } }, shuffle: function(e) { // NOTE: not implemented yet. var target = (e ? e.target || e.srcElement : utils.dom.get(dom.o, '.shuffle')); if (target && !utils.css.has(target, css.disabled)) { utils.css.toggle(target.parentNode, css.active); playlistController.data.shuffleMode = !playlistController.data.shuffleMode; } }, repeat: function(e) { var target = (e ? e.target || e.srcElement : utils.dom.get(dom.o, '.repeat')); if (target && !utils.css.has(target, css.disabled)) { utils.css.toggle(target.parentNode, css.active); playlistController.data.loopMode = !playlistController.data.loopMode; } }, menu: function(ignoreToggle) { var isOpen; isOpen = utils.css.has(dom.o, css.playlistOpen); // hackish: reset scrollTop in default first open case. odd, but some browsers have a non-zero scroll offset the first time the playlist opens. if (playlistController && !playlistController.data.selectedIndex && !firstOpen) { dom.playlist.scrollTop = 0; firstOpen = true; } // sniff out booleans from mouse events, as this is referenced directly by event handlers. if (typeof ignoreToggle !== 'boolean' || !ignoreToggle) { if (!isOpen) { // explicitly set height:0, so the first closed -> open animation runs properly dom.playlistContainer.style.height = '0px'; } isOpen = utils.css.toggle(dom.o, css.playlistOpen); } // playlist dom.playlistContainer.style.height = (isOpen ? dom.playlistContainer.scrollHeight : 0) + 'px'; }, adjustVolume: function(e) { /** * NOTE: this is the mousemove() event handler version. * Use setVolume(50), etc., to assign volume directly. */ var backgroundMargin, pixelMargin, target, value, volume; value = 0; target = dom.volume; // safety net if (e === undefined) { return false; } if (!e || e.clientX === undefined) { // called directly or with a non-mouseEvent object, etc. // proxy to the proper method. if (arguments.length && window.console && window.console.warn) { console.warn('Bar UI: call setVolume(' + e + ') instead of adjustVolume(' + e + ').'); } return actions.setVolume.apply(this, arguments); } // based on getStyle() result // figure out spacing around background image based on background size, eg. 60% background size. // 60% wide means 20% margin on each side. backgroundMargin = (100 - actionData.volume.backgroundSize) / 2; // relative position of mouse over element value = Math.max(0, Math.min(1, (e.clientX - actionData.volume.x) / actionData.volume.width)); target.style.clip = 'rect(0px, ' + (actionData.volume.width * value) + 'px, ' + actionData.volume.height + 'px, ' + (actionData.volume.width * (backgroundMargin/100)) + 'px)'; // determine logical volume, including background margin pixelMargin = ((backgroundMargin/100) * actionData.volume.width); volume = Math.max(0, Math.min(1, ((e.clientX - actionData.volume.x) - pixelMargin) / (actionData.volume.width - (pixelMargin*2)))) * 100; // set volume if (soundObject) { soundObject.setVolume(volume); } defaultVolume = volume; return utils.events.preventDefault(e); }, releaseVolume: function(/* e */) { utils.events.remove(document, 'mousemove', actions.adjustVolume); utils.events.remove(document, 'mouseup', actions.releaseVolume); }, setVolume: function(volume) { // set volume (0-100) and update volume slider UI. var backgroundSize, backgroundMargin, backgroundOffset, target, from, to; if (volume === undefined || isNaN(volume)) { return; } if (dom.volume) { target = dom.volume; // based on getStyle() result backgroundSize = actionData.volume.backgroundSize; // figure out spacing around background image based on background size, eg. 60% background size. // 60% wide means 20% margin on each side. backgroundMargin = (100 - backgroundSize) / 2; // margin as pixel value relative to width backgroundOffset = actionData.volume.width * (backgroundMargin/100); from = backgroundOffset; to = from + ((actionData.volume.width - (backgroundOffset*2)) * (volume/100)); target.style.clip = 'rect(0px, ' + to + 'px, ' + actionData.volume.height + 'px, ' + from + 'px)'; } // apply volume to sound, as applicable if (soundObject) { soundObject.setVolume(volume); } defaultVolume = volume; } }; init(); // TODO: mixin actions -> exports exports = { // Per-instance events: window.sm2BarPlayers[0].on = { ... } etc. See global players.on example above for reference. on: null, actions: actions, dom: dom, playlistController: playlistController }; return exports; }; // barebones utilities for logic, CSS, DOM, events etc. utils = { array: (function() { function compare(property) { var result; return function(a, b) { if (a[property] < b[property]) { result = -1; } else if (a[property] > b[property]) { result = 1; } else { result = 0; } return result; }; } function shuffle(array) { // Fisher-Yates shuffle algo var i, j, temp; for (i = array.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i+1)); temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } return { compare: compare, shuffle: shuffle }; }()), css: (function() { function hasClass(o, cStr) { return (o.className !== undefined ? new RegExp('(^|\\s)' + cStr + '(\\s|$)').test(o.className) : false); } function addClass(o, cStr) { if (!o || !cStr || hasClass(o, cStr)) { return false; // safety net } o.className = (o.className ? o.className + ' ' : '') + cStr; } function removeClass(o, cStr) { if (!o || !cStr || !hasClass(o, cStr)) { return false; } o.className = o.className.replace(new RegExp('( ' + cStr + ')|(' + cStr + ')', 'g'), ''); } function swapClass(o, cStr1, cStr2) { var tmpClass = { className: o.className }; removeClass(tmpClass, cStr1); addClass(tmpClass, cStr2); o.className = tmpClass.className; } function toggleClass(o, cStr) { var found, method; found = hasClass(o, cStr); method = (found ? removeClass : addClass); method(o, cStr); // indicate the new state... return !found; } return { has: hasClass, add: addClass, remove: removeClass, swap: swapClass, toggle: toggleClass }; }()), dom: (function() { function getAll(param1, param2) { var node, selector, results; if (arguments.length === 1) { // .selector case node = document.documentElement; // first param is actually the selector selector = param1; } else { // node, .selector node = param1; selector = param2; } // sorry, IE 7 users; IE 8+ required. if (node && node.querySelectorAll) { results = node.querySelectorAll(selector); } return results; } function get(/* parentNode, selector */) { var results = getAll.apply(this, arguments); // hackish: if an array, return the last item. if (results && results.length) { return results[results.length-1]; } // handle "not found" case return results && results.length === 0 ? null : results; } function ancestor(nodeName, element, checkCurrent) { var result; if (!element || !nodeName) { return element; } nodeName = nodeName.toUpperCase(); // return if current node matches. if (checkCurrent && element && element.nodeName === nodeName) { return element; } while (element && element.nodeName !== nodeName && element.parentNode) { element = element.parentNode; } return (element && element.nodeName === nodeName ? element : null); } return { ancestor: ancestor, get: get, getAll: getAll }; }()), position: (function() { function getOffX(o) { // http://www.xs4all.nl/~ppk/js/findpos.html var curleft = 0; if (o.offsetParent) { while (o.offsetParent) { curleft += o.offsetLeft; o = o.offsetParent; } } else if (o.x) { curleft += o.x; } return curleft; } function getOffY(o) { // http://www.xs4all.nl/~ppk/js/findpos.html var curtop = 0; if (o.offsetParent) { while (o.offsetParent) { curtop += o.offsetTop; o = o.offsetParent; } } else if (o.y) { curtop += o.y; } return curtop; } return { getOffX: getOffX, getOffY: getOffY }; }()), style: (function() { function get(node, styleProp) { // http://www.quirksmode.org/dom/getstyles.html var value; if (node.currentStyle) { value = node.currentStyle[styleProp]; } else if (window.getComputedStyle) { value = document.defaultView.getComputedStyle(node, null).getPropertyValue(styleProp); } return value; } return { get: get }; }()), events: (function() { var add, remove, preventDefault; add = function(o, evtName, evtHandler) { // return an object with a convenient detach method. var eventObject = { detach: function() { return remove(o, evtName, evtHandler); } }; if (window.addEventListener) { o.addEventListener(evtName, evtHandler, false); } else { o.attachEvent('on' + evtName, evtHandler); } return eventObject; }; remove = (window.removeEventListener !== undefined ? function(o, evtName, evtHandler) { return o.removeEventListener(evtName, evtHandler, false); } : function(o, evtName, evtHandler) { return o.detachEvent('on' + evtName, evtHandler); }); preventDefault = function(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; e.cancelBubble = true; } return false; }; return { add: add, preventDefault: preventDefault, remove: remove }; }()), features: (function() { var getAnimationFrame, localAnimationFrame, localFeatures, prop, styles, testDiv, transform; testDiv = document.createElement('div'); /** * hat tip: paul irish * http://paulirish.com/2011/requestanimationframe-for-smart-animating/ * https://gist.github.com/838785 */ localAnimationFrame = (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || null); // apply to window, avoid "illegal invocation" errors in Chrome getAnimationFrame = localAnimationFrame ? function() { return localAnimationFrame.apply(window, arguments); } : null; function has(prop) { // test for feature support var result = testDiv.style[prop]; return (result !== undefined ? prop : null); } // note local scope. localFeatures = { transform: { ie: has('-ms-transform'), moz: has('MozTransform'), opera: has('OTransform'), webkit: has('webkitTransform'), w3: has('transform'), prop: null // the normalized property value }, rotate: { has3D: false, prop: null }, getAnimationFrame: getAnimationFrame }; localFeatures.transform.prop = ( localFeatures.transform.w3 || localFeatures.transform.moz || localFeatures.transform.webkit || localFeatures.transform.ie || localFeatures.transform.opera ); function attempt(style) { try { testDiv.style[transform] = style; } catch(e) { // that *definitely* didn't work. return false; } // if we can read back the style, it should be cool. return !!testDiv.style[transform]; } if (localFeatures.transform.prop) { // try to derive the rotate/3D support. transform = localFeatures.transform.prop; styles = { css_2d: 'rotate(0deg)', css_3d: 'rotate3d(0,0,0,0deg)' }; if (attempt(styles.css_3d)) { localFeatures.rotate.has3D = true; prop = 'rotate3d'; } else if (attempt(styles.css_2d)) { prop = 'rotate'; } localFeatures.rotate.prop = prop; } testDiv = null; return localFeatures; }()) }; // --- // expose to global window.sm2BarPlayers = players; window.sm2BarPlayerOptions = playerOptions; window.SM2BarPlayer = Player; }(window));
bsd-3-clause
ericingram/spectrum
tests/core/specItemIt/errorHandling/catchPhpErrors/enabled/breakOnFirstPhpError/Test.php
3800
<?php /* * (c) Mikhail Kharitonov <mail@mkharitonov.net> * * For the full copyright and license information, see the * LICENSE.txt file that was distributed with this source code. */ namespace spectrum\core\specItemIt\errorHandling\catchPhpErrors\enabled\breakOnFirstPhpError; use spectrum\core\plugins\Manager; use spectrum\core\SpecItem; require_once __DIR__ . '/../../../../../../init.php'; abstract class Test extends \spectrum\core\specItemIt\errorHandling\catchPhpErrors\enabled\Test { public function testShouldBeReturnFalse() { $it = $this->it; $it->setTestCallback(function() use($it) { $it->getRunResultsBuffer()->addResult(true); trigger_error(''); }); $this->assertFalse($it->run()); } public function testErrorLevelSets_ShouldBeCatchErrorsWithProperErrorLevel() { $it = $this->it; $it->errorHandling->setCatchPhpErrors(\E_USER_NOTICE); $it->setTestCallback(function() { trigger_error('', \E_USER_NOTICE); }); $this->assertFalse($it->run()); } public function testErrorLevelSets_ShouldNotBeCatchErrorsWithDifferentErrorLevel() { $it = $this->it; $it->errorHandling->setCatchPhpErrors(\E_USER_ERROR); $it->setTestCallback(function() use(&$isExecuted) { trigger_error('', \E_USER_NOTICE); $isExecuted = true; }); $result = $it->run(); $this->assertNull($result); $this->assertTrue($isExecuted); } public function testShouldBeIgnoreErrorsSuppressedByErrorControlOperators() { $it = $this->it; $it->setTestCallback(function() use(&$isExecuted, $it) { @trigger_error(''); $it->getRunResultsBuffer()->addResult(true); $isExecuted = true; }); $result = $it->run(); $this->assertTrue($result); $this->assertTrue($isExecuted); } public function testShouldBeCatchWorldBuildersErrors() { $it = $this->it; $it->builders->add(function(){ trigger_error(''); }); $it->setTestCallback(function(){}); $this->assertFalse($it->run()); } public function testShouldBeCatchWorldDestroyersErrors() { $it = $this->it; $it->setTestCallback(function(){}); $it->destroyers->add(function(){ trigger_error(''); }); $this->assertFalse($it->run()); } public function testShouldBeRestoreErrorHandler() { $it = $this->it; $it->setTestCallback(function(){ trigger_error(''); }); set_error_handler('trim'); $it->run(); $this->assertEquals('trim', $this->getErrorHandler()); restore_error_handler(); } public function testShouldBeRestoreErrorHandlerIfPropertyDisabledDuringRun() { $it = $this->it; $it->setTestCallback(function() use($it){ $it->errorHandling->setCatchPhpErrors(false); }); set_error_handler('trim'); $it->run(); $this->assertEquals('trim', $this->getErrorHandler()); restore_error_handler(); } public function testShouldBeUnsetRunResultsBuffer() { $it = $this->it; $it->setTestCallback(function(){ trigger_error(''); }); $it->run(); $this->assertNull($it->getRunResultsBuffer()); } public function testShouldBeRestoreRunningSpecItemInRegistry() { $runningSpecItemBackup = \spectrum\core\Registry::getRunningSpecItem(); $it = $this->it; $it->setTestCallback(function(){ trigger_error(''); }); $it->run(); $this->assertSame($runningSpecItemBackup, \spectrum\core\Registry::getRunningSpecItem()); } public function testShouldBeStopRun() { $it = $this->it; $it->setTestCallback(function(){ trigger_error(''); }); $it->run(); $this->assertFalse($it->isRunning()); } public function testShouldBeDispatchEventOnRunAfter() { Manager::registerPlugin('foo', '\spectrum\core\testEnv\PluginEventOnRunStub'); $it = $this->it; $it->setTestCallback(function(){ trigger_error(''); }); $it->run(); $this->assertEventTriggeredCount(1, 'onRunAfter'); Manager::unregisterPlugin('foo'); } }
bsd-3-clause
cedtanghe/elixir-di
src/ProviderAbstract.php
653
<?php namespace Elixir\DI; /** * @author Cédric Tanghe <ced.tanghe@gmail.com> */ abstract class ProviderAbstract implements ProviderInterface { /** * @var bool */ protected $deferred = false; /** * @var array */ protected $provides = []; /** * {@inheritdoc} */ public function isDeferred() { return $this->deferred; } /** * {@inheritdoc} */ public function provided($service) { return in_array($service, $this->provides()); } /** * {@inheritdoc} */ public function provides() { return $this->provides; } }
bsd-3-clause
rogst/datadogpy
datadog/api/__init__.py
817
# flake8: noqa # API settings _api_key = None _application_key = None _api_version = 'v1' _api_host = None _host_name = None _cacert = True # HTTP(S) settings _proxies = None _timeout = 3 _max_timeouts = 3 _max_retries = 3 _backoff_period = 300 _swallow = True # Resources from datadog.api.comments import Comment from datadog.api.downtimes import Downtime from datadog.api.timeboards import Timeboard from datadog.api.events import Event from datadog.api.infrastructure import Infrastructure from datadog.api.metrics import Metric from datadog.api.monitors import Monitor from datadog.api.screenboards import Screenboard from datadog.api.graphs import Graph from datadog.api.hosts import Host from datadog.api.service_checks import ServiceCheck from datadog.api.tags import Tag from datadog.api.users import User
bsd-3-clause
darilek/AjaxControlToolkit
AjaxControlToolkit/DropDown/DropDownExtender.cs
6930
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// DropDown is an ASP.NET AJAX extender that can be attached almost to any ASP.NET control to provide a SharePoint-style drop-down menu. /// </summary> [TargetControlType(typeof(WebControl))] [TargetControlType(typeof(HtmlControl))] [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(PopupExtender))] [RequiredScript(typeof(HoverExtender))] [RequiredScript(typeof(AnimationExtender))] [ClientCssResource(Constants.DropDownName)] [ClientScriptResource("Sys.Extended.UI.DropDownBehavior", Constants.DropDownName)] [Designer(typeof(DropDownExtenderDesigner))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.DropDownName + Constants.IconPostfix)] public class DropDownExtender : DynamicPopulateExtenderControlBase { /// <summary> /// A ID of a control that will be displayed as a dropdown. /// </summary> [DefaultValue("")] [IDReferenceProperty(typeof(Control))] [ExtenderControlProperty] [ElementReference] [ClientPropertyName("dropDownControl")] public string DropDownControlID { get { return (string)(ViewState["DropDownControlID"] ?? String.Empty); } set { ViewState["DropDownControlID"] = value; } } /// <summary> /// Highlight border color. /// </summary> [DefaultValue(typeof(Color), "")] [ExtenderControlProperty] [ClientPropertyName("highlightBorderColor")] public Color HighlightBorderColor { get { return (Color)(ViewState["HighlightBorderColor"] ?? Color.Empty); } set { ViewState["HighlightBorderColor"] = value; } } /// <summary> /// Highlight background color. /// </summary> [DefaultValue(typeof(Color), "")] [ExtenderControlProperty] [ClientPropertyName("highlightBackgroundColor")] public Color HighlightBackColor { get { return (Color)(ViewState["HighlightBackColor"] ?? Color.Empty); } set { ViewState["HighlightBackColor"] = value; } } /// <summary> /// An arrow's background color. /// </summary> [DefaultValue(typeof(Color), "")] [ExtenderControlProperty] [ClientPropertyName("dropArrowBackgroundColor")] public Color DropArrowBackColor { get { return (Color)(ViewState["DropArrowBackColor"] ?? Color.Empty); } set { ViewState["DropArrowBackColor"] = value; } } /// <summary> /// An arrow's image URL. /// </summary> [DefaultValue("")] [UrlProperty] [ExtenderControlProperty] [ClientPropertyName("dropArrowImageUrl")] public string DropArrowImageUrl { get { return (string)(ViewState["DropArrowImageUrl"] ?? String.Empty); } set { ViewState["DropArrowImageUrl"] = value; } } /// <summary> /// Arrow width. /// </summary> [DefaultValue(typeof(Unit), "")] [ExtenderControlProperty] [ClientPropertyName("dropArrowWidth")] public Unit DropArrowWidth { get { return (Unit)(ViewState["DropArrowWidth"] ?? Unit.Empty); } set { ViewState["DropArrowWidth"] = value; } } /// <summary> /// The popup event /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("popup")] public string OnClientPopup { get { return (string)(ViewState["OnClientPopup"] ?? String.Empty); } set { ViewState["OnClientPopup"] = value; } } /// <summary> /// The populating event /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("populating")] public string OnClientPopulating { get { return (string)(ViewState["OnClientPopulating"] ?? String.Empty); } set { ViewState["OnClientPopulating"] = value; } } /// <summary> /// The populated event /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("populated")] public string OnClientPopulated { get { return (string)(ViewState["OnClientPopulated"] ?? String.Empty); } set { ViewState["OnClientPopulated"] = value; } } /// <summary> /// OnShow animation will be played each time the dropdown is displayed. /// The dropdown will be positioned correctly but hidden. /// Animation can be used to display the dropdown with other visual effects. /// </summary> [ExtenderControlProperty] [ClientPropertyName("onShow")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnShow { get { return GetAnimation(ref _onShow, "OnShow"); } set { SetAnimation(ref _onShow, "OnShow", value); } } Animation _onShow; /// <summary> /// OnHide animation will be played each time the dropdown is hidden. /// </summary> [ExtenderControlProperty] [ClientPropertyName("onHide")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnHide { get { return GetAnimation(ref _onHide, "OnHide"); } set { SetAnimation(ref _onHide, "OnHide", value); } } Animation _onHide; // If the DynamicControlID was not supplied, use the DropDownControlID instead. // This is in place for backward compatability (when DropDownExtender.DynamicControlID // didn't exist and DropDownExtender.DropDownControlID was used instead) protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // If the dynamic populate functionality is being used but // no target is specified, used the drop down control if((!String.IsNullOrEmpty(DynamicContextKey) || !String.IsNullOrEmpty(DynamicServicePath) || !String.IsNullOrEmpty(DynamicServiceMethod)) && String.IsNullOrEmpty(DynamicControlID)) DynamicControlID = DropDownControlID; ResolveControlIDs(_onShow); ResolveControlIDs(_onHide); } } } #pragma warning restore 1591
bsd-3-clause
Christian-G/terena-core
application/modules/core/models/resources/Submission/Set.php
1732
<?php /** * CORE Conference Manager * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://www.terena.org/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to webmaster@terena.org so we can send you a copy immediately. * * @copyright Copyright (c) 2011 TERENA (http://www.terena.org) * @license http://www.terena.org/license/new-bsd New BSD License * @revision $Id$ */ /** * Submission rowset * * @package Core_Resource * @subpackage Core_Resource_Submission * @author Christian Gijtenbeek <gijtenbeek@terena.org> */ class Core_Resource_Submission_Set extends Zend_Db_Table_Rowset_Abstract { /** * ?? what is this doing here? Is this called from anywhere?? * */ public function getReviewers() { $query = "select u.email, rs.reviewer_submission_id as id from reviewers_submissions rs left join users u on (rs.user_id = u.user_id) where rs.submission_id=:submission_id"; return $this->getTable()->getAdapter()->query( $query, array(':submission_id' => $this->submission_id) )->fetchAll(); } /** * @todo: This can be removed?? belongs in Item.php * */ public function getSubmissionOneliner() { return $this->title; } /** * Get total number of reviewers for a submission * @return array */ public function getNumberOfReviewers() { $query = "select submission_id, count(*) from reviewers_submissions group by reviewers_submissions.submission_id"; return $this->getTable()->getAdapter()->fetchPairs($query); } }
bsd-3-clause
teasim/teasim-helpers
source/getWidth.js
443
/* ========================================= * Copyright (c) 2015-present, Billgo. * Copyright (c) 2015-present, Facebook, Inc. * * All rights reserved. *======================================== */ import isWindow from "./isWindow.js"; import getOffset from "./getOffset.js"; export default function getWidth(node, client) { const win = isWindow(node); return win ? win.innerWidth : client ? node.innerWidth : getOffset(node).width; }
bsd-3-clause
ltcmelo/psychec
C/parser/DiagnosticsReporter_Lexer.cpp
1954
// Copyright (c) 2020/21 Leandro T. C. Melo <ltcmelo@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "Lexer.h" #include "SyntaxTree.h" #include "../common/diagnostics/Diagnostic.h" using namespace psy; using namespace C; const std::string Lexer::DiagnosticsReporter::ID_of_IncompatibleLanguageDialect = "Lexer-001"; void Lexer::DiagnosticsReporter::IncompatibleLanguageDialect( const std::string& feature, LanguageDialect::Std expectedStd) { DiagnosticDescriptor descriptor(ID_of_IncompatibleLanguageDialect, "Incompatible language dialect", feature + " is available in " + to_string(expectedStd), DiagnosticSeverity::Warning, DiagnosticCategory::Syntax); lexer_->tree_->newDiagnostic(descriptor, lexer_->tree_->freeTokenSlot()); }
bsd-3-clause
3den/atomizer
tests/lib/utils.js
4907
/*globals describe,it,afterEach */ 'use strict'; var expect = require('chai').expect; var utils = require('../../src/lib/utils'); describe('utils', function () { describe('hexToRgb()', function () { it('should return null given an invalid hex', function () { var result = utils.hexToRgb('ghk'); expect(result).to.be.null; }); it('should return expected rgb object given a hex in full form', function () { var result = utils.hexToRgb('#000000'); var expected = {r: 0, g: 0, b: 0}; expect(result).to.deep.equal(expected); }); it('should return expected rgb object given a hex in shorthand form', function () { var result = utils.hexToRgb('#000'); var expected = {r: 0, g: 0, b: 0}; expect(result).to.deep.equal(expected); }); }); describe('mergeConfigs()', function () { it('should merge non-conflicting breakpoints correctly', function () { var config1 = { breakPoints: { 'sm': '@media(min-width: 600px)' } }; var config2 = { breakPoints: { 'md': '@media(min-width: 800px)' } }; var expected = { breakPoints: { 'sm': '@media(min-width: 600px)', 'md': '@media(min-width: 800px)' } }; var result = utils.mergeConfigs([config1, config2]); expect(result).to.deep.equal(expected); }); it('should merge conflicting breakpoints where the latter config is kept', function () { var config1 = { breakPoints: { 'sm': '@media(min-width: 600px)' } }; var config2 = { breakPoints: { 'sm': '@media(min-width: 550px)' } }; var expected = { breakPoints: { 'sm': '@media(min-width: 550px)' } }; var result = utils.mergeConfigs([config1, config2]); expect(result).to.deep.equal(expected); }); it('should merge classNames correctly', function () { var config1 = { classNames: ['D-ib', 'Bd-foo'] }; var config2 = { classNames: ['D-n!', 'D-ib'] }; var config3 = { classNames: ['C-#333', 'D-ib'] }; var expected = { classNames: ['D-ib', 'Bd-foo', 'D-n!', 'C-#333'] }; var result = utils.mergeConfigs([config1, config2, config3]); expect(result).to.deep.equal(expected); }); it('should merge customs correctly', function () { var config1 = { custom: { 'foo': '1px solid red' } }; var config2 = { custom: { 'bar': '2px dashed blue' } }; var expected = { custom: { 'foo': '1px solid red', 'bar': '2px dashed blue' } }; var result = utils.mergeConfigs([config1, config2]); expect(result).to.deep.equal(expected); }); it('should merge conflicting customs where the latter config is kept', function () { var config1 = { custom: { 'foo': '1px solid red' } }; var config2 = { custom: { 'foo': '2px dashed blue' } }; var expected = { custom: { 'foo': '2px dashed blue' } }; var result = utils.mergeConfigs([config1, config2]); expect(result).to.deep.equal(expected); }); }); describe('repeatString()', function () { it('should not repeat string if count < 0', function () { var result = utils.repeatString('test', 0); expect(result).to.be.empty; }); it('should output string once if count is 1', function () { var result = utils.repeatString('test', 1); expect(result).to.equal('test'); }); it('should output string twice if count is 2', function () { var result = utils.repeatString('test', 2); expect(result).to.equal('testtest'); }); it('should output string twice if count is 3', function () { var result = utils.repeatString('test', 3); expect(result).to.equal('testtesttest'); }); }); });
bsd-3-clause
olivebranches/newstand
config/console.php
740
<?php Yii::setAlias('@tests', dirname(__DIR__) . '/tests'); $params = require(__DIR__ . '/params.php'); $db = require(__DIR__ . '/db.php'); return [ 'id' => 'basic-console', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log', 'gii'], 'controllerNamespace' => 'app\commands', 'modules' => [ 'gii' => 'yii\gii\Module', ], 'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'log' => [ 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'db' => $db, ], 'params' => $params, ];
bsd-3-clause
hscstudio/osyawwal2
backend/modules/pusdiklat/execution/views/meeting-activity2/view.php
9434
<?php use yii\helpers\Html; use yii\widgets\DetailView; use yii\helpers\Inflector; use kartik\grid\GridView; use backend\models\Reference; use backend\models\Activity; use backend\models\Person; $controller = $this->context; $menus = $controller->module->getMenuItems(); $this->params['sideMenu'][$controller->module->uniqueId]=$menus; $this->title = 'Perbarui '. Inflector::camel2words($model->name); $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Meeting Activities'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; // Ngeformat $satker = Reference::findOne($model->satker_id)->name; $namaHari = [ 'Mon' => 'Senin', 'Tue' => 'Selasa', 'Wed' => 'Rabu', 'Thu' => 'Kamis', 'Fri' => 'Jumat', 'Sat' => 'Sabtu', 'Sun' => 'Minggu' ]; $namaBulan = [ 'January' => 'Januari', 'February' => 'Febuari', 'March' => 'Maret', 'April' => 'April', 'May' => 'Mei', 'June' => 'Juni', 'July' => 'Juli', 'August' => 'Agustus', 'September' => 'September', 'October' => 'Oktober', 'November' => 'November', 'December' => 'Desember' ]; $start = $namaHari[date('D', strtotime($model->start))]. date(', d ', strtotime($model->start)). $namaBulan[date('F', strtotime($model->start))]. date(' Y', strtotime($model->start)). ' - pukul '. date('H:i', strtotime($model->start)); $end = $namaHari[date('D', strtotime($model->end))]. date(', d ', strtotime($model->end)). $namaBulan[date('F', strtotime($model->end))]. date(' Y', strtotime($model->end)). ' - pukul '. date('H:i', strtotime($model->end)); $lokasi = explode('|', $model->location); $lokasi[0] = Reference::findOne($model->location)->name; $diasramakan_icons = [ '1'=>'<i class="fa fa-fw fa-check-circle"></i> Ya', '0'=>'<i class="fa fa-fw fa-times-circle"></i> Tidak' ]; $diasramakan_classes = ['1'=>'success','0'=>'danger']; $diasramakan_title = ['1'=>'Berjalan','0'=>'Batal']; $diasramakan = Html::tag( 'div', $diasramakan_icons[$model->hostel], [ 'class'=>'label label-'.$diasramakan_classes[$model->hostel], ] ); $status_icons = [ '0'=>'<i class="fa fa-fw fa-fire"></i> Rencana', '1'=>'<i class="fa fa-fw fa-refresh"></i> Siap', '2'=>'<i class="fa fa-fw fa-check-circle"></i> Berjalan', '3'=>'<i class="fa fa-fw fa-times-circle"></i> Batal' ]; $status_classes = ['0'=>'warning','1'=>'info','2'=>'success','3'=>'danger']; $status_title = ['0'=>'Rencana','1'=>'Siap','2'=>'Berjalan','3'=>'Batal']; $status = Html::tag( 'div', $status_icons[$model->status], [ 'class'=>'label label-'.$status_classes[$model->status], ] ); $dibuatOleh = Person::findOne($model->created_by)->name; // baikin ya :DDDD $terakhirDiubahOleh = Person::findOne($model->modified_by)->name; // baikin ya :DDDD // dah ?> <div class="activity-view panel panel-default"> <div class="panel-heading"> <div class="pull-right"> <?= (Yii::$app->request->isAjax)?'':Html::a('<i class="fa fa-fw fa-arrow-left"></i> Back', ['index'], ['class' => 'btn btn-xs btn-primary']) ?> </div> <h1 class="panel-title"><?= Html::encode($this->title) ?></h1> </div> <div class="panel-body"> <ul class="nav nav-tabs" role="tablist" id="tab_wizard"> <li class="active"><a href="#property" role="tab" data-toggle="tab">Info Umum <span class='label label-info'>1</span></a></li> <li class=""><a href="#history" role="tab" data-toggle="tab">Riwayat Revisi <span class='label label-warning'>2</span></a></li> </ul> <div class="tab-content" style="border: 1px solid #ddd; border-top-color: transparent; padding:10px; background-color: #fff;"> <div class="tab-pane fade-in active" id="property"> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ [ 'label' => 'Satker', 'value' => $satker, ], 'name', 'description:ntext', [ 'label' => 'Mulai', 'value' => $start, ], [ 'label' => 'Akhir', 'value' => $end, ], [ 'label' => 'Lokasi', 'value' => $lokasi[0].'. '.$lokasi[1], ], [ 'label' => 'Diasramakan', 'format' => 'raw', 'value' => $diasramakan, ], [ 'label' => 'Status', 'format' => 'raw', 'value' => $status, ], [ 'label' => 'Dibuat Oleh', 'value' => $dibuatOleh ], [ 'label' => 'Terakhir Diubah Oleh', 'value' => $terakhirDiubahOleh ], ], ]) ?> </div> <div class="tab-pane fade" id="history"> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'revision', [ 'attribute' => 'name', 'vAlign'=>'middle', 'hAlign'=>'left', 'headerOptions'=>['class'=>'kv-sticky-column'], 'contentOptions'=>['class'=>'kv-sticky-column'], 'format'=>'raw', 'value' => function ($data){ return Html::a($data->name,'#',[ 'title'=>$data->description. '<br>'.$data->location. '<br>'.$data->hostel, 'data-toggle'=>"tooltip", 'data-placement'=>"top", 'data-html'=>'true', ]); }, ], [ 'attribute' => 'start', 'vAlign'=>'middle', 'hAlign'=>'center', 'headerOptions'=>['class'=>'kv-sticky-column'], 'contentOptions'=>['class'=>'kv-sticky-column'], 'width'=>'100px', 'format'=>'raw', 'value' => function ($data){ return Html::tag('span',date('d M Y',strtotime($data->start)),[ 'class'=>'label label-info', ]); }, ], [ 'attribute' => 'end', 'vAlign'=>'middle', 'hAlign'=>'center', 'headerOptions'=>['class'=>'kv-sticky-column'], 'contentOptions'=>['class'=>'kv-sticky-column'], 'width'=>'100px', 'format'=>'raw', 'value' => function ($data){ return Html::tag('span',date('d M Y',strtotime($data->end)),[ 'class'=>'label label-info', ]); }, ], [ 'label' => 'Hadirin', 'vAlign'=>'left', 'hAlign'=>'center', 'width' => '75px', 'headerOptions'=>['class'=>'kv-sticky-column'], 'contentOptions'=>['class'=>'kv-sticky-column'], 'format'=>'raw', 'value' => function ($data){ return Html::a($data->meeting->attendance_count_plan,null, [ 'class'=>'label label-primary', 'data-pjax'=>'0', ]); }, ], [ 'format' => 'raw', 'label' => 'PIC', 'vAlign'=>'middle', 'hAlign'=>'center', 'width'=>'70px', 'headerOptions'=>['class'=>'kv-sticky-column'], 'contentOptions'=>['class'=>'kv-sticky-column'], 'value' => function ($data){ $object_person=\backend\models\ObjectPerson::find() ->where([ 'object'=>'activity', 'object_id'=>$data->id, 'type'=>'organisation_1213020100', // CEK KD_UNIT_ORG 1213020100 IN TABLE ORGANISATION IS SUBBIDANG PROGRAM ]) ->one(); $options = [ 'class'=>'label label-info', 'data-toggle'=>'tooltip', 'data-pjax'=>'0', 'data-html'=>'true', 'title'=>($object_person!=null)?'CURRENT PIC PROGRAM <br> '.$object_person->person->name.'':'PIC IS UNAVAILABLE', ]; $person_name = ($object_person!=null)?substr($object_person->person->name,0,5).'.':'-'; return Html::tag('span',$person_name,$options); } ], [ 'attribute' => 'status', 'filter' => false, 'label' => 'Status', 'vAlign'=>'middle', 'hAlign'=>'center', 'width'=>'75px', 'headerOptions'=>['class'=>'kv-sticky-column'], 'contentOptions'=>['class'=>'kv-sticky-column'], 'format'=>'raw', 'value' => function ($data){ $status_icons = [ '0'=>'<span class="glyphicon glyphicon-fire"></span>', '1'=>'<span class="glyphicon glyphicon-refresh"></span>', '2'=>'<span class="glyphicon glyphicon-check"></span>', '3'=>'<span class="glyphicon glyphicon-remove"></span>' ]; $status_classes = ['0'=>'warning','1'=>'info','2'=>'success','3'=>'danger']; $status_title = ['0'=>'Plan','1'=>'Ready','2'=>'Execution','3'=>'Cancel']; return Html::tag( 'span', $status_icons[$data->status], [ 'class'=>'label label-'.$status_classes[$data->status], 'data-toggle'=>'tooltip', 'data-pjax'=>'0', 'title'=>$status_title[$data->status], ] ); }, ], [ 'attribute' => 'modified', 'vAlign'=>'middle', 'hAlign'=>'center', 'headerOptions'=>['class'=>'kv-sticky-column'], 'contentOptions'=>['class'=>'kv-sticky-column'], 'width'=>'140px', 'format'=>'raw', 'value' => function ($data){ return Html::tag('span',date('d M Y H:i:s',strtotime($data->modified)),[ 'class'=>'label label-info', ]); }, ], ] ]) ?> </div> </div> </div> </div>
bsd-3-clause
frankee/muduo
muduo/net/protorpc/RpcCodec.cc
5046
// Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // Author: Shuo Chen (chenshuo at chenshuo dot com) #include <muduo/net/protorpc/RpcCodec.h> #include <muduo/base/Logging.h> #include <muduo/net/Endian.h> #include <muduo/net/TcpConnection.h> #include <muduo/net/protorpc/rpc.pb.h> #include <muduo/net/protorpc/google-inl.h> #include <zlib.h> using namespace muduo; using namespace muduo::net; namespace { int ProtobufVersionCheck() { GOOGLE_PROTOBUF_VERIFY_VERSION; return 0; } int dummy = ProtobufVersionCheck(); } void RpcCodec::send(const TcpConnectionPtr& conn, const RpcMessage& message) { // FIXME: can we move serialization & checksum to other thread? Buffer buf; buf.append("RPC0", 4); // code copied from MessageLite::SerializeToArray() and MessageLite::SerializePartialToArray(). GOOGLE_DCHECK(message.IsInitialized()) << InitializationErrorMessage("serialize", message); int byte_size = message.ByteSize(); buf.ensureWritableBytes(byte_size + kHeaderLen); uint8_t* start = reinterpret_cast<uint8_t*>(buf.beginWrite()); uint8_t* end = message.SerializeWithCachedSizesToArray(start); if (end - start != byte_size) { ByteSizeConsistencyError(byte_size, message.ByteSize(), static_cast<int>(end - start)); } buf.hasWritten(byte_size); int32_t checkSum = static_cast<int32_t>( ::adler32(1, reinterpret_cast<const Bytef*>(buf.peek()), static_cast<int>(buf.readableBytes()))); buf.appendInt32(checkSum); assert(buf.readableBytes() == implicit_cast<size_t>(kHeaderLen + byte_size + kHeaderLen)); int32_t len = sockets::hostToNetwork32(static_cast<int32_t>(buf.readableBytes())); buf.prepend(&len, sizeof len); conn->send(&buf); } void RpcCodec::onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp receiveTime) { while (buf->readableBytes() >= kMinMessageLen + kHeaderLen) { const int32_t len = buf->peekInt32(); if (len > kMaxMessageLen || len < kMinMessageLen) { errorCallback_(conn, buf, receiveTime, kInvalidLength); } else if (buf->readableBytes() >= implicit_cast<size_t>(len + kHeaderLen)) { RpcMessage message; // FIXME: can we move deserialization & callback to other thread? ErrorCode errorCode = parse(buf->peek()+kHeaderLen, len, &message); if (errorCode == kNoError) { // FIXME: try { } catch (...) { } messageCallback_(conn, message, receiveTime); buf->retrieve(kHeaderLen+len); } else { errorCallback_(conn, buf, receiveTime, errorCode); } } else { break; } } } namespace { const string kNoErrorStr = "NoError"; const string kInvalidLengthStr = "InvalidLength"; const string kCheckSumErrorStr = "CheckSumError"; const string kInvalidNameLenStr = "InvalidNameLen"; const string kUnknownMessageTypeStr = "UnknownMessageType"; const string kParseErrorStr = "ParseError"; const string kUnknownErrorStr = "UnknownError"; } const string& RpcCodec::errorCodeToString(ErrorCode errorCode) { switch (errorCode) { case kNoError: return kNoErrorStr; case kInvalidLength: return kInvalidLengthStr; case kCheckSumError: return kCheckSumErrorStr; case kInvalidNameLen: return kInvalidNameLenStr; case kUnknownMessageType: return kUnknownMessageTypeStr; case kParseError: return kParseErrorStr; default: return kUnknownErrorStr; } } void RpcCodec::defaultErrorCallback(const TcpConnectionPtr& conn, Buffer* buf, Timestamp, ErrorCode errorCode) { LOG_ERROR << "ProtobufCodec::defaultErrorCallback - " << errorCodeToString(errorCode); if (conn && conn->connected()) { conn->shutdown(); } } int32_t RpcCodec::asInt32(const char* buf) { int32_t be32 = 0; ::memcpy(&be32, buf, sizeof(be32)); return sockets::networkToHost32(be32); } RpcCodec::ErrorCode RpcCodec::parse(const char* buf, int len, RpcMessage* message) { ErrorCode error = kNoError; // check sum int32_t expectedCheckSum = asInt32(buf + len - kHeaderLen); int32_t checkSum = static_cast<int32_t>( ::adler32(1, reinterpret_cast<const Bytef*>(buf), static_cast<int>(len - kHeaderLen))); if (checkSum == expectedCheckSum) { if (memcmp(buf, "RPC0", kHeaderLen) == 0) { // parse from buffer const char* data = buf + kHeaderLen; int32_t dataLen = len - 2*kHeaderLen; if (message->ParseFromArray(data, dataLen)) { error = kNoError; } else { error = kParseError; } } else { error = kUnknownMessageType; } } else { error = kCheckSumError; } return error; }
bsd-3-clause
hung101/kbs
frontend/controllers/BspElaunLatihanPraktikalMonthController.php
3840
<?php namespace frontend\controllers; use Yii; use app\models\BspElaunLatihanPraktikalMonth; use frontend\models\BspElaunLatihanPraktikalMonthSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * BspElaunLatihanPraktikalMonthController implements the CRUD actions for BspElaunLatihanPraktikalMonth model. */ class BspElaunLatihanPraktikalMonthController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all BspElaunLatihanPraktikalMonth models. * @return mixed */ public function actionIndex() { $searchModel = new BspElaunLatihanPraktikalMonthSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } //delete() /** * Displays a single BspElaunLatihanPraktikalMonth model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->renderAjax('view', [ 'model' => $this->findModel($id), 'readonly' => true, ]); } /** * Creates a new BspElaunLatihanPraktikalMonth model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate($bsp_elaun_latihan_praktikal_id) { $model = new BspElaunLatihanPraktikalMonth(); Yii::$app->session->open(); if($bsp_elaun_latihan_praktikal_id != ''){ $model->bsp_elaun_latihan_praktikal_id = $bsp_elaun_latihan_praktikal_id; } else { if(isset(Yii::$app->session->id)){ $model->session_id = Yii::$app->session->id; } } if ($model->load(Yii::$app->request->post()) && $model->save()) { return '1'; } return $this->renderAjax('create', [ 'model' => $model, 'readonly' => false, ]); } /** * Updates an existing BspElaunLatihanPraktikalMonth model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return '1'; } else { return $this->renderAjax('update', [ 'model' => $model, 'readonly' => false, ]); } } /** * Deletes an existing BspElaunLatihanPraktikalMonth model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); //return $this->redirect(['index']); } /** * Finds the BspElaunLatihanPraktikalMonth model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return BspElaunLatihanPraktikalMonth the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = BspElaunLatihanPraktikalMonth::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
bsd-3-clause
ziutek/emgo
egpath/src/nrf5/examples/core51822/ble-connect/nordicuart.go
5735
package main import ( "bluetooth/att" "bluetooth/gatt" "bluetooth/uuid" "fmt" ) //emgo:const var ( srvNordicUART = uuid.UUID{0x6E400001B5A3F393, 0xE0A9E50E24DCCA9E} chrNordicUARTTx = uuid.UUID{0x6E400002B5A3F393, 0xE0A9E50E24DCCA9E} chrNordicUARTRx = uuid.UUID{0x6E400003B5A3F393, 0xE0A9E50E24DCCA9E} ) type chr struct { Handle uint16 Prop byte ValHandle uint16 UUID uuid.UUID } type service struct { Handle uint16 GroupEndHandle uint16 UUID uuid.UUID Chrs []chr } type gattServer struct { services []service } func (gs *gattServer) ServeATT(w *att.ResponseWriter, r *att.Request) { fmt.Printf("\r\nMethod/Cmd: %v/%v\r\n", r.Method, r.Cmd) fmt.Printf("Handle-End: %04x-%04x\r\n", r.Handle, r.EndHandle) fmt.Printf("Other: %04x\r\n", r.Other) fmt.Printf("UUID: %v\r\n\r\n", r.UUID) switch r.Method { case att.Read: gs.read(w, r) case att.ReadByType: gs.readByType(w, r) case att.ReadByGroupType: gs.readByGroupType(w, r) case att.FindInformation: gs.findInformation(w, r) default: w.SetError(att.RequestNotSupported, r) } if err := w.Send(); err != nil { fmt.Printf("Can't send response: %v\r\n", err) } } func (gs *gattServer) readByType(w *att.ResponseWriter, r *att.Request) { fmt.Printf("readByType\r\n") if r.UUID.CanShorten(32) { switch r.UUID.Short32() { case 0x2803: // GATT Characteristic Declaration. fieldSize := 0 loop: for i := range gs.services { srv := &gs.services[i] for k := range srv.Chrs { chr := &srv.Chrs[k] if chr.ValHandle == 0 { continue } if chr.Handle >= r.Handle && chr.Handle <= r.EndHandle { short := chr.UUID.CanShorten(16) if fieldSize == 0 { if short { fieldSize = 5 + 2 } else { fieldSize = 5 + 16 } w.SetReadByType(fieldSize) } else if fieldSize == 5+2 && !short || fieldSize == 5+16 && short { break loop } w.AppendWord16(chr.Handle) w.AppendByte(chr.Prop) w.AppendWord16(chr.ValHandle) if short { w.AppendUUID16(chr.UUID.Short16()) } else { w.AppendUUID(chr.UUID) } if !w.Commit() { break loop // MTU reached. } fmt.Printf( "Chr: %x %v %x %v\r\n", chr.Handle, chr.Prop, chr.ValHandle, chr.UUID, ) } } } if fieldSize != 0 { return } } } w.SetError(att.AttributeNotFound, r) } func (gs *gattServer) readByGroupType(w *att.ResponseWriter, r *att.Request) { fmt.Printf("readByGroupType\r\n") if r.UUID.CanShorten(32) { switch r.UUID.Short32() { case 0x2800: // GATT Primary Service Declaration fieldSize := 0 loop: for i := range gs.services { srv := &gs.services[i] if srv.Handle >= r.Handle && srv.Handle <= r.EndHandle { short := srv.UUID.CanShorten(16) if fieldSize == 0 { if short { fieldSize = 4 + 2 } else { fieldSize = 4 + 16 } w.SetReadByGroupType(fieldSize) } else if fieldSize == 4+2 && !short || fieldSize == 4+16 && short { break loop } w.AppendWord16(srv.Handle) w.AppendWord16(srv.GroupEndHandle) if short { w.AppendUUID16(srv.UUID.Short16()) } else { w.AppendUUID(srv.UUID) } if !w.Commit() { break loop // MTU reached. } fmt.Printf( "Srv: %x %x %v\r\n", srv.Handle, srv.GroupEndHandle, srv.UUID, ) } } if fieldSize != 0 { return } } } w.SetError(att.AttributeNotFound, r) } func (gs *gattServer) findInformation(w *att.ResponseWriter, r *att.Request) { fmt.Printf("findInformation\r\n") var format att.FindInformationFormat loop: for i := range gs.services { srv := &gs.services[i] // BUG: Information about services not returned. for k := range srv.Chrs { chr := &srv.Chrs[k] if chr.Handle >= r.Handle && chr.Handle <= r.EndHandle { short := chr.UUID.CanShorten(16) if format == 0 { if short { format = att.HandleUUID16 } else { format = att.HandleUUID } w.SetFindInformation(format) } else if format == att.HandleUUID16 && !short || format == att.HandleUUID && short { break loop } w.AppendWord16(chr.Handle) if short { w.AppendUUID16(chr.UUID.Short16()) } else { w.AppendUUID(chr.UUID) } if !w.Commit() { break loop // MTU reached. } fmt.Printf( "Chr: %x %v %x %v\r\n", chr.Handle, chr.Prop, chr.ValHandle, chr.UUID, ) } } } if format != 0 { return } w.SetError(att.AttributeNotFound, r) } func (gs *gattServer) read(w *att.ResponseWriter, r *att.Request) { w.SetRead() w.AppendString("Hello world!") w.Commit() } const ( srvGenericAccessProfile uuid.UUID16 = 0x1800 srvGenericAttributeProfile uuid.UUID16 = 0x1801 ) var gattSrv = &gattServer{ services: []service{ { 0x0001, 0x0007, srvGenericAccessProfile.Full(), []chr{ { 0x0002, gatt.Write | gatt.Read, 0x0003, gatt.DeviceName.Full(), }, { 0x0004, gatt.Read, 0x0005, gatt.Apperance.Full(), }, { 0x0006, gatt.Read, 0x0007, gatt.PeriphPrefConnParams.Full(), }, }, }, { 0x0008, 0x000B, srvGenericAttributeProfile.Full(), []chr{ { 0x0009, gatt.Indicate, 0x000A, gatt.ServiceChanged.Full(), }, { 0x000B, 0, 0, gatt.ClientChrConfig.Full(), }, }, }, { 0x000C, 0xFFFF, srvNordicUART, []chr{ { 0x000D, gatt.Notify, 0x000E, chrNordicUARTRx, }, { 0x000F, 0, 0, gatt.ClientChrConfig.Full(), }, { 0x0010, gatt.Write | gatt.WriteWithoutResp, 0x0011, chrNordicUARTTx, }, }, }, }, }
bsd-3-clause
x-clone/brackit.brackitdb
brackitdb-driver/src/main/java/org/brackit/driver/BrackitConnection.java
5175
/* * [New BSD License] * Copyright (c) 2011-2012, Brackit Project Team <info@brackit.org> * 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 Brackit Project Team nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.brackit.driver; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; /** * * @author Sebastian Baechle * */ public class BrackitConnection { private final Socket bit; private final OutputStream to; private final InputStream from; public BrackitConnection(String host, int port) throws BrackitException { try { bit = new Socket(host, port); from = new BufferedInputStream(bit.getInputStream()); to = new BufferedOutputStream(bit.getOutputStream()); } catch (Exception e) { e.printStackTrace(); throw new BrackitException("Connection failed", e); } } public void begin() throws BrackitException { send('b'); } public void commit() throws BrackitException { send('c'); } public void rollback() throws BrackitException { send('r'); } public String query(String query) throws BrackitException { return send('q', query); } public void query(String query, OutputStream out) throws BrackitException { send('q', query, out); } private String send(char cmd) throws BrackitException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); send(cmd, (InputStream) null, out); return out.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new BrackitException(e); } } private String send(char cmd, String query) throws BrackitException { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); send(cmd, new ByteArrayInputStream(query.getBytes("UTF-8")), out); return out.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new BrackitException(e); } } private void send(char cmd, String query, OutputStream out) throws BrackitException { try { send(cmd, new ByteArrayInputStream(query.getBytes("UTF-8")), out); } catch (UnsupportedEncodingException e) { throw new BrackitException(e); } } private void send(char cmd, InputStream in, OutputStream out) throws BrackitException { try { to.write(cmd); int r; if (in != null) { while ((r = in.read()) > 0) { to.write(r); } to.write(0); } to.flush(); while ((r = from.read()) > 0) { out.write(r); } out.flush(); // check for success if ((from.read() != 's')) { ByteArrayOutputStream err = new ByteArrayOutputStream(); while ((r = from.read()) > 0) { err.write(r); } err.flush(); throw new BrackitException(err.toString("UTF-8")); } } catch (IOException e) { throw new BrackitException(e); } } public void close() { try { to.close(); } catch (IOException e) { e.printStackTrace(); } try { from.close(); } catch (IOException e) { e.printStackTrace(); } try { bit.close(); } catch (IOException e) { e.printStackTrace(); } } private static class Client implements Runnable { public void run() { try { BrackitConnection c = new BrackitConnection("localhost", 11011); c.send('q', new ByteArrayInputStream("1+1".getBytes("UTF-8")), System.out); c.close(); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { // Server s = new Server(11011); // new Thread(s).start(); Client c = new Client(); new Thread(c).start(); } }
bsd-3-clause
erezlife/django-scheduler
schedule/utils.py
4739
from functools import wraps import pytz import heapq from annoying.functions import get_object_or_None from django.core.exceptions import PermissionDenied from django.utils import timezone from schedule.conf.settings import CHECK_EVENT_PERM_FUNC, CHECK_CALENDAR_PERM_FUNC class EventListManager(object): """ This class is responsible for doing functions on a list of events. It is used to when one has a list of events and wants to access the occurrences from these events in as a group """ def __init__(self, events): self.events = events def occurrences_after(self, after=None, tzinfo=pytz.utc): """ It is often useful to know what the next occurrence is given a list of events. This function produces a generator that yields the the most recent occurrence after the date ``after`` from any of the events in ``self.events`` """ from schedule.models import Occurrence if after is None: after = timezone.now() occ_replacer = OccurrenceReplacer( Occurrence.objects.filter(event__in=self.events)) generators = [event._occurrences_after_generator(after) for event in self.events] occurrences = [] for generator in generators: try: heapq.heappush(occurrences, (generator.next(), generator)) except StopIteration: pass while True: if len(occurrences) == 0: raise StopIteration generator = occurrences[0][1] try: next = heapq.heapreplace(occurrences, (generator.next(), generator))[0] except StopIteration: next = heapq.heappop(occurrences)[0] yield occ_replacer.get_occurrence(next) class OccurrenceReplacer(object): """ When getting a list of occurrences, the last thing that needs to be done before passing it forward is to make sure all of the occurrences that have been stored in the datebase replace, in the list you are returning, the generated ones that are equivalent. This class makes this easier. """ def __init__(self, persisted_occurrences): lookup = [((occ.event, occ.original_start, occ.original_end), occ) for occ in persisted_occurrences] self.lookup = dict(lookup) def get_occurrence(self, occ): """ Return a persisted occurrences matching the occ and remove it from lookup since it has already been matched """ return self.lookup.pop( (occ.event, occ.original_start, occ.original_end), occ) def has_occurrence(self, occ): return (occ.event, occ.original_start, occ.original_end) in self.lookup def get_additional_occurrences(self, start, end): """ Return persisted occurrences which are now in the period """ return [occ for key, occ in self.lookup.items() if (occ.start < end and occ.end >= start and not occ.cancelled)] def check_event_permissions(function): @wraps(function) def decorator(request, *args, **kwargs): from schedule.models import Event, Calendar user = request.user # check event permission event = get_object_or_None(Event, pk=kwargs.get('event_id', None)) allowed = CHECK_EVENT_PERM_FUNC(event, user) if not allowed: raise PermissionDenied # check calendar permissions calendar = None if event: calendar = event.calendar elif 'calendar_slug' in kwargs: calendar = Calendar.objects.get(slug=kwargs['calendar_slug']) allowed = CHECK_CALENDAR_PERM_FUNC(calendar, user) if not allowed: raise PermissionDenied # all checks passed return function(request, *args, **kwargs) return decorator def coerce_date_dict(date_dict): """ given a dictionary (presumed to be from request.GET) it returns a tuple that represents a date. It will return from year down to seconds until one is not found. ie if year, month, and seconds are in the dictionary, only year and month will be returned, the rest will be returned as min. If none of the parts are found return an empty tuple. """ keys = ['year', 'month', 'day', 'hour', 'minute', 'second'] ret_val = { 'year': 1, 'month': 1, 'day': 1, 'hour': 0, 'minute': 0, 'second': 0} modified = False for key in keys: try: ret_val[key] = int(date_dict[key]) modified = True except KeyError: break return modified and ret_val or {}
bsd-3-clause
groupon/monsoon
impl/src/main/java/com/groupon/lex/metrics/timeseries/ChainingTSCPair.java
15610
package com.groupon.lex.metrics.timeseries; import com.groupon.lex.metrics.GroupName; import com.groupon.lex.metrics.SimpleGroupPath; import com.groupon.lex.metrics.history.CollectHistory; import com.groupon.lex.metrics.lib.ForwardIterator; import com.groupon.lex.metrics.lib.LazyMap; import gnu.trove.TLongCollection; import gnu.trove.list.TLongList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.TObjectLongMap; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TLongObjectHashMap; import gnu.trove.map.hash.TObjectLongHashMap; import gnu.trove.set.TLongSet; import gnu.trove.set.hash.TLongHashSet; import static java.lang.Long.min; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; public abstract class ChainingTSCPair implements TimeSeriesCollectionPair { private static final Logger LOG = Logger.getLogger(ChainingTSCPair.class.getName()); @NonNull private final CollectHistory history; private final TimestampChain timestamps; private final Map<GroupName, TsvChain> data = new THashMap<>(); private final TObjectLongMap<GroupName> activeGroups; public ChainingTSCPair(@NonNull CollectHistory history, @NonNull ExpressionLookBack lookback) { this.history = history; Stream<TimeSeriesCollection> filtered; try { filtered = lookback.filter(new ForwardIterator<>(history.streamReversed().iterator())); } catch (UnsupportedOperationException ex) { LOG.log(Level.WARNING, "history reverse streaming not supported, fallback to duration hint"); final DateTime end = history.getEnd(); final DateTime begin = end.minus(lookback.hintDuration()); filtered = history.stream(begin, end); } final TscStreamReductor reduction = filtered .collect(TscStreamReductor::new, TscStreamReductor::add, TscStreamReductor::addAll); this.timestamps = new TimestampChain(reduction.timestamps); this.activeGroups = reduction.groups; LOG.log(Level.INFO, "recovered {0} scrapes from history", timestamps.size()); // Fill data with empty, faultable group data. activeGroups.forEachKey(group -> { data.put(group, new TsvChain()); return true; }); validatePrevious(); // Should never trigger. } @Override public String toString() { return "ChainingTSCPair[" + timestamps.toString() + "]"; } @Override public abstract TimeSeriesCollection getCurrentCollection(); @Override public Optional<TimeSeriesCollection> getPreviousCollection(int n) { if (n == 0) return Optional.of(getCurrentCollection()); if (n < 0) throw new IllegalArgumentException("cannot look into the future"); if (n - 1 >= timestamps.size()) return Optional.empty(); return Optional.of(new TSCollectionImpl(timestamps.get(n - 1))); } @Override public int size() { return timestamps.size() + 1; } private void update_(TimeSeriesCollection tsc) { timestamps.add(tsc.getTimestamp()); tsc.getTSValues().stream() .forEach(tsv -> { data.compute(tsv.getGroup(), (grp, tsvChain) -> { if (tsvChain == null) tsvChain = new TsvChain(tsc.getTimestamp(), tsv); else tsvChain.add(tsc.getTimestamp(), tsv); return tsvChain; }); activeGroups.put(tsv.getGroup(), tsc.getTimestamp().getMillis()); }); } private void apply_lookback_(ExpressionLookBack lookBack) { final TLongHashSet retainTs = lookBack.filter(new ForwardIterator<>(timestamps.stream().mapToObj(TSCollectionImpl::new).iterator())) .map(TimeSeriesCollection::getTimestamp) .mapToLong(DateTime::getMillis) .collect(TLongHashSet::new, TLongHashSet::add, TLongHashSet::addAll); timestamps.retainAll(retainTs); data.values().forEach(tsvChain -> tsvChain.retainAll(retainTs)); // Drop inactive groups. final long oldestTs = timestamps.backLong(); activeGroups.retainEntries((group, ts) -> ts >= oldestTs); data.keySet().retainAll(activeGroups.keySet()); } private void validatePrevious() { try { if (!timestamps.isEmpty() && !(timestamps.front().isBefore(getCurrentCollection().getTimestamp()))) throw new IllegalArgumentException("previous timestamps must be before current and ordered in reverse chronological order"); } catch (IllegalArgumentException ex) { LOG.log(Level.SEVERE, "programmer error", ex); throw ex; } } protected final void update(TimeSeriesCollection tsc, ExpressionLookBack lookback, Runnable doBeforeValidation) { update_(tsc); apply_lookback_(lookback); doBeforeValidation.run(); validatePrevious(); } private static class TimestampChain { /** * All timestamps that are to be kept, sorted in ascending order, * placing the most recent collection last. */ private final TLongList timestamps; public TimestampChain(@NonNull TLongSet set) { timestamps = new TLongArrayList(set); timestamps.sort(); } public void add(@NonNull DateTime ts) { final long tsMillis = ts.getMillis(); if (timestamps.isEmpty() || tsMillis > frontLong()) { timestamps.add(tsMillis); } else { final int bsPos = timestamps.binarySearch(tsMillis); if (bsPos < 0) { // Insert only if not present. final int insPos = -(bsPos + 1); timestamps.insert(insPos, tsMillis); } } } public boolean isEmpty() { return timestamps.isEmpty(); } public int size() { return timestamps.size(); } public long get(int idx) { return timestamps.get(timestamps.size() - 1 - idx); } public LongStream stream() { return IntStream.range(0, size()) .mapToLong(this::get); } public DateTime front() { return new DateTime(frontLong(), DateTimeZone.UTC); } public long frontLong() { return get(0); } public DateTime back() { return new DateTime(backLong(), DateTimeZone.UTC); } public long backLong() { return get(size() - 1); } public void retainAll(TLongCollection values) { timestamps.retainAll(values); } @Override public String toString() { return timestamps.toString(); } } private class TsvChain { /** * tailRefForAccess is used to access the value from requests for data * access only. The internal clock in the soft reference is thus only * advanced if the data is used, as opposed to when it is updated. This * allows the GC to make intelligent decision on when to expire the * referenced object. */ private SoftReference<TLongObjectMap<TimeSeriesValue>> tailRefForAccess; /** * tailRefForUpdate is used to access the value for updates only. By * using the weak reference, we don't impose a restriction on the GC to * maintain the referenced object, allowing it to be collected if it * hasn't been used in a while. * * It is important that the updates don't keep the object alive, hence * we cannot access it through the tailRefForAccess pointer. * * This pointer is always kept in sync with tailRefForAccess (setting * both by the code, while cleaning both by the GC). */ private WeakReference<TLongObjectMap<TimeSeriesValue>> tailRefForUpdate; public TsvChain() { tailRefForAccess = new SoftReference<>(null); tailRefForUpdate = new WeakReference<>(null); } public TsvChain(@NonNull DateTime initTs, @NonNull TimeSeriesValue initTsv) { final TLongObjectHashMap<TimeSeriesValue> tail = new TLongObjectHashMap<>(); tail.put(initTs.getMillis(), initTsv); tailRefForAccess = new SoftReference<>(tail); tailRefForUpdate = new WeakReference<>(tail); } public synchronized void add(@NonNull DateTime ts, @NonNull TimeSeriesValue tv) { final TLongObjectMap<TimeSeriesValue> tail = tailRefForUpdate.get(); if (tail != null) tail.put(ts.getMillis(), tv); } public synchronized Optional<TimeSeriesValue> get(GroupName name, long ts) { { final TLongObjectMap<TimeSeriesValue> tail = tailRefForAccess.get(); /* * Use the tail values immediately, if any of the following is true: * - The timestamp ought to be included due to timestamps retention. * - The timestamp is present in tail. * - The tail contains at least one timestamp before/at the sought timestamp. */ if (tail != null && (timestamps.backLong() <= ts || tail.containsKey(ts) || !tail.keySet().forEach(v -> v > ts))) return Optional.ofNullable(tail.get(ts)); } final DateTime streamStart; if (timestamps.isEmpty()) streamStart = new DateTime(ts, DateTimeZone.UTC); else streamStart = new DateTime(min(timestamps.backLong(), ts), DateTimeZone.UTC); final TLongObjectHashMap<TimeSeriesValue> tail = history.streamGroup(streamStart, name) .unordered() .parallel() .collect(TLongObjectHashMap<TimeSeriesValue>::new, (map, tsvEntry) -> map.put(tsvEntry.getKey().getMillis(), tsvEntry.getValue()), TLongObjectHashMap::putAll); tailRefForAccess = new SoftReference<>(tail); tailRefForUpdate = new WeakReference<>(tail); return Optional.ofNullable(tail.get(ts)); } public synchronized void retainAll(TLongCollection timestamps) { final TLongObjectMap<TimeSeriesValue> tail = tailRefForUpdate.get(); if (tail != null) tail.retainEntries((ts, value) -> timestamps.contains(ts)); } } @RequiredArgsConstructor private class TSCollectionImpl extends AbstractTimeSeriesCollection { private final long ts; private final Map<GroupName, Optional<TimeSeriesValue>> tsvSet = new LazyMap<>(this::faultGroup, data.keySet()); @Override public DateTime getTimestamp() { return new DateTime(ts, DateTimeZone.UTC); } @Override public boolean isEmpty() { return tsvSet.values().stream().noneMatch(Optional::isPresent); } @Override public Set<GroupName> getGroups(Predicate<? super GroupName> filter) { return tsvSet.entrySet().stream() .filter(entry -> filter.test(entry.getKey())) .filter(entry -> entry.getValue().isPresent()) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } @Override public Set<SimpleGroupPath> getGroupPaths(Predicate<? super SimpleGroupPath> filter) { return tsvSet.entrySet().stream() .filter(entry -> filter.test(entry.getKey().getPath())) .collect(Collectors.groupingBy(entry -> entry.getKey().getPath())).entrySet().stream() .filter(listing -> listing.getValue().stream().map(Map.Entry::getValue).anyMatch(Optional::isPresent)) .map(Map.Entry::getKey) .collect(Collectors.toSet()); } @Override public Collection<TimeSeriesValue> getTSValues() { return tsvSet.values().stream() .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } @Override public TimeSeriesValueSet getTSValue(SimpleGroupPath name) { return new TimeSeriesValueSet(tsvSet.entrySet().stream() .filter(entry -> Objects.equals(entry.getKey().getPath(), name)) .map(Map.Entry::getValue) .filter(Optional::isPresent) .map(Optional::get)); } @Override public Optional<TimeSeriesValue> get(GroupName name) { return tsvSet.getOrDefault(name, Optional.empty()); } @Override public TimeSeriesValueSet get(Predicate<? super SimpleGroupPath> pathFilter, Predicate<? super GroupName> groupFilter) { return new TimeSeriesValueSet(tsvSet.entrySet().stream() .filter(entry -> pathFilter.test(entry.getKey().getPath())) .filter(entry -> groupFilter.test(entry.getKey())) .map(Map.Entry::getValue) .filter(Optional::isPresent) .map(Optional::get)); } private Optional<TimeSeriesValue> faultGroup(GroupName name) { try { final TsvChain tsvChain = data.get(name); if (tsvChain == null) return Optional.empty(); return tsvChain.get(name, ts); } catch (Exception ex) { LOG.log(Level.WARNING, "error while retrieving historical data", ex); return Optional.empty(); // Pretend data is absent. } } } @RequiredArgsConstructor private static class TscStreamReductor { private final TLongSet timestamps; private final TObjectLongHashMap<GroupName> groups; public TscStreamReductor() { this(new TLongHashSet(), new TObjectLongHashMap<>()); } public void add(TimeSeriesCollection tsc) { final long tsMillis = tsc.getTimestamp().getMillis(); timestamps.add(tsMillis); final Set<GroupName> updateGroups = tsc.getGroups(group -> !groups.containsKey(group) || tsMillis > groups.get(group)); updateGroups.forEach(group -> groups.put(group, tsMillis)); } public void addAll(TscStreamReductor other) { timestamps.addAll(other.timestamps); other.groups.forEachEntry((group, ts) -> { if (groups.get(group) < ts) groups.put(group, ts); return true; }); } } }
bsd-3-clause
xingcuntian/advanced_study
console/migrations/m150713_083040_init.php
1301
<?php use yii\db\Schema; use yii\db\Migration; class m150713_083040_init extends Migration { const TBL_NAME = '{{%user}}'; public function safeUp() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable(self::TBL_NAME, [ 'id' => Schema::TYPE_PK, 'username' => Schema::TYPE_STRING . ' NOT NULL', 'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL', 'password_hash' => Schema::TYPE_STRING . ' NOT NULL', 'password_reset_token' => Schema::TYPE_STRING, 'email' => Schema::TYPE_STRING . ' NOT NULL', 'role' => Schema::TYPE_SMALLINT.' NOT NULL DEFAULT 10', 'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10', 'created_at' => Schema::TYPE_INTEGER . ' NOT NULL', 'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL', ], $tableOptions); $this->createIndex('username', self::TBL_NAME, ['username'], true); $this->createIndex('email', self::TBL_NAME, ['email'], true);//true 是唯一索引 } public function safeDown() { $this->dropTable(self::TBL_NAME); } }
bsd-3-clause
HwisooSo/gemV-update
src/base/vulnerability/vul_rename.hh
3452
/* * Copyright (c) 20014-15 Arizona State University * 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 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: Srinivas Tanikella * * Compiler and Microarchitecture Lab, ASU * http://aviral.lab.asu.edu */ #ifndef __VUL_RENAME_HH__ #define __VUL_RENAME_HH__ #include "cpu/o3/comm.hh" #include "base/vulnerability/vul_main.hh" #include "base/statistics.hh" #include "debug/VulTracker.hh" #include "base/vulnerability/vul_structs.hh" #include <vector> class RenameVulCalc { private: /** Size of a field in the rename map */ const int size; /** Size of a field in the History buffer */ const int hist_size; /** Number of threads */ const int numThreads; /** Number of entries in the rename map */ const int numEntries; /** Number of entries in the History buffer */ const int numHistEntries; std::list<History> **hist; std::list<History> **bufHist; Tick **prevTick; Tick **hbPrevTick; Stats::Scalar renameVul; Stats::Scalar histbufVul; Stats::Scalar histbufMaxEntries; unsigned int lastHistbufMax; unsigned long long notVul; const unsigned int RegIndexWidth; const unsigned int PhysRegIndexWidth; const unsigned int SeqNumWidth; public: RenameVulCalc(int, int, unsigned int, unsigned int, unsigned int); ~RenameVulCalc(); void vulOnRead(PhysRegIndex phys_reg, InstSeqNum seqNum, int tid); void vulOnReadSrc(PhysRegIndex phys_reg, InstSeqNum seqNum, int tid); void vulOnReadHB(PhysRegIndex phys_reg, InstSeqNum seqNum, int tid); void vulOnWrite(PhysRegIndex phys_reg, InstSeqNum seqNum, int tid); void vulOnWriteHB(PhysRegIndex phys_reg, InstSeqNum seqNum, int tid, unsigned int numOfEntries); void vulOnCommit(InstSeqNum seqNum, int tid); //void vulOnCommitHB(InstSeqNum seqNum, int tid); void vulOnRemove(InstSeqNum seqNum, int tid); void regStats(); }; #endif //__VUL_RENAME_HH_
bsd-3-clause
coolms/common
src/Service/Exception/InvalidArgumentException.php
642
<?php /** * CoolMS2 Common Module (http://www.coolms.com/) * * @link http://github.com/coolms/common for the canonical source repository * @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com) * @license http://www.coolms.com/license/new-bsd New BSD License * @author Dmitry Popov <d.popov@altgraphic.com> */ namespace CmsCommon\Service\Exception; use CmsCommon\Exception\InvalidArgumentException as BaseInvalidArgumentException; /** * Invalid argument exception for CmsCommon\Service */ class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface { }
bsd-3-clause
chromium/vs-chromium
src/DkmIntegration/IdeComponent/Utility.cs
946
// 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. using Microsoft.VisualStudio.Debugger.Evaluation; namespace VsChromium.DkmIntegration.IdeComponent { public static class Utility { public static void GetExpressionName(DkmVisualizedExpression expression, out string name, out string fullName) { if (expression.TagValue == DkmVisualizedExpression.Tag.RootVisualizedExpression) { DkmRootVisualizedExpression rootExpr = (DkmRootVisualizedExpression)expression; name = rootExpr.Name; fullName = rootExpr.FullName; } else { DkmChildVisualizedExpression childExpr = (DkmChildVisualizedExpression)expression; name = childExpr.EvaluationResult.Name; fullName = childExpr.EvaluationResult.FullName; } } } }
bsd-3-clause
frankiez/qing-mps
src/application/views/errors/404.php
228
<?php defined('SYSPATH') or die('No direct script access.'); ?> <!DOCTYPE html> <html> <head> <meta charset=UTF-8> <title>Page not found</title> </head> <body> <p>404 Page not found</p> <p><?=$message ?></p> </body> </html>
bsd-3-clause
metal/metal-dom
src/DomDelegatedEventHandle.js
1314
'use strict'; import { array, core } from 'metal'; import domData from './domData'; import { EventHandle } from 'metal-events'; /** * This is a special EventHandle, that is responsible for dom delegated events * (only the ones that receive a target element, not a selector string). * @extends {EventHandle} */ class DomDelegatedEventHandle extends EventHandle { /** * The constructor for `DomDelegatedEventHandle`. * @param {!Event} emitter Element the event was subscribed to. * @param {string} event The name of the event that was subscribed to. * @param {!Function} listener The listener subscribed to the event. * @param {string=} opt_selector An optional selector used when delegating * the event. * @constructor */ constructor(emitter, event, listener, opt_selector) { super(emitter, event, listener); this.selector_ = opt_selector; } /** * @inheritDoc */ removeListener() { var data = domData.get(this.emitter_); var selector = this.selector_; var arr = core.isString(selector) ? data.delegating[this.event_].selectors : data.listeners; var key = core.isString(selector) ? selector : this.event_; array.remove(arr[key] || [], this.listener_); if (arr[key] && arr[key].length === 0) { delete arr[key]; } } } export default DomDelegatedEventHandle;
bsd-3-clause
maferelo/saleor
saleor/graphql/order/resolvers.py
2401
import graphene import graphene_django_optimizer as gql_optimizer from ...core.permissions import OrderPermissions from ...order import OrderStatus, models from ...order.events import OrderEvents from ...order.models import OrderEvent from ...order.utils import sum_order_totals from ..utils import filter_by_period, filter_by_query_param, sort_queryset from .enums import OrderStatusFilter from .sorters import OrderSortField from .types import Order ORDER_SEARCH_FIELDS = ("id", "discount_name", "token", "user_email", "user__email") def filter_orders(qs, info, created, status, query): qs = filter_by_query_param(qs, query, ORDER_SEARCH_FIELDS) # filter orders by status if status is not None: if status == OrderStatusFilter.READY_TO_FULFILL: qs = qs.ready_to_fulfill() elif status == OrderStatusFilter.READY_TO_CAPTURE: qs = qs.ready_to_capture() # filter orders by creation date if created is not None: qs = filter_by_period(qs, created, "created") return gql_optimizer.query(qs, info) def resolve_orders(info, created, status, query, sort_by=None): qs = models.Order.objects.confirmed() qs = sort_queryset(qs, sort_by, OrderSortField) return filter_orders(qs, info, created, status, query) def resolve_draft_orders(info, created, query, sort_by=None): qs = models.Order.objects.drafts() qs = sort_queryset(qs, sort_by, OrderSortField) return filter_orders(qs, info, created, None, query) def resolve_orders_total(_info, period): qs = models.Order.objects.confirmed().exclude(status=OrderStatus.CANCELED) qs = filter_by_period(qs, period, "created") return sum_order_totals(qs) def resolve_order(info, order_id): """Return order only for user assigned to it or proper staff user.""" user = info.context.user order = graphene.Node.get_node_from_global_id(info, order_id, Order) if user.has_perm(OrderPermissions.MANAGE_ORDERS) or order.user == user: return order return None def resolve_homepage_events(): # Filter only selected events to be displayed on homepage. types = [ OrderEvents.PLACED, OrderEvents.PLACED_FROM_DRAFT, OrderEvents.ORDER_FULLY_PAID, ] return OrderEvent.objects.filter(type__in=types) def resolve_order_by_token(token): return models.Order.objects.filter(token=token).first()
bsd-3-clause
TOGoS/TMCRS
src/togos/minecraft/regionshifter/RegionFile.java
14804
/* * Further modifications by TOGoS for use in TMCRS: * - Removed use of templates, auto[un]boxing, and foreach loops * to make source compatible with Java 1.4 * - Added ability to write chunks in both formats (gzip and deflate) * - Implement AutoCloseable */ /* ** 2011 January 5 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. **/ /* * 2011 February 16 * * This source code is based on the work of Scaevolus (see notice above). * It has been slightly modified by Mojang AB (constants instead of magic * numbers, a chunk timestamp header, and auto-formatted according to our * formatter template). */ // Interfaces with region files on the disk /* Region File Format Concept: The minimum unit of storage on hard drives is 4KB. 90% of Minecraft chunks are smaller than 4KB. 99% are smaller than 8KB. Write a simple container to store chunks in single files in runs of 4KB sectors. Each region file represents a 32x32 group of chunks. The conversion from chunk number to region number is floor(coord / 32): a chunk at (30, -3) would be in region (0, -1), and one at (70, -30) would be at (3, -1). Region files are named "r.x.z.data", where x and z are the region coordinates. A region file begins with a 4KB header that describes where chunks are stored in the file. A 4-byte big-endian integer represents sector offsets and sector counts. The chunk offset for a chunk (x, z) begins at byte 4*(x+z*32) in the file. The bottom byte of the chunk offset indicates the number of sectors the chunk takes up, and the top 3 bytes represent the sector number of the chunk. Given a chunk offset o, the chunk data begins at byte 4096*(o/256) and takes up at most 4096*(o%256) bytes. A chunk cannot exceed 1MB in size. If a chunk offset is 0, the corresponding chunk is not stored in the region file. Chunk data begins with a 4-byte big-endian integer representing the chunk data length in bytes, not counting the length field. The length must be smaller than 4096 times the number of sectors. The next byte is a version field, to allow backwards-compatible updates to how chunks are encoded. A version of 1 represents a gzipped NBT file. The gzipped data is the chunk length - 1. A version of 2 represents a deflated (zlib compressed) NBT file. The deflated data is the chunk length - 1. */ package togos.minecraft.regionshifter; import java.io.*; import java.util.ArrayList; import java.util.zip.*; public class RegionFile implements AutoCloseable { public static final int VERSION_GZIP = 1; public static final int VERSION_DEFLATE = 2; private static final int SECTOR_BYTES = 4096; private static final int SECTOR_INTS = SECTOR_BYTES / 4; static final int CHUNK_HEADER_SIZE = 5; private static final byte emptySector[] = new byte[4096]; private final File fileName; private RandomAccessFile file; private final int offsets[]; private final int chunkTimestamps[]; private ArrayList<Boolean> sectorFree; private int sizeDelta; private long lastModified = 0; public RegionFile(File path) { offsets = new int[SECTOR_INTS]; chunkTimestamps = new int[SECTOR_INTS]; fileName = path; debugln("REGION LOAD " + fileName); sizeDelta = 0; try { if (path.exists()) { lastModified = path.lastModified(); } file = new RandomAccessFile(path, "rw"); if (file.length() < SECTOR_BYTES) { /* we need to write the chunk offset table */ for (int i = 0; i < SECTOR_INTS; ++i) { file.writeInt(0); } // write another sector for the timestamp info for (int i = 0; i < SECTOR_INTS; ++i) { file.writeInt(0); } sizeDelta += SECTOR_BYTES * 2; } if ((file.length() & 0xfff) != 0) { file.seek(file.length()); /* the file size is not a multiple of 4KB, grow it */ for (int i = 0; i < (file.length() & 0xfff); ++i) { file.write((byte) 0); } } /* set up the available sector map */ int nSectors = (int) file.length() / SECTOR_BYTES; sectorFree = new ArrayList<Boolean>(nSectors); for (int i = 0; i < nSectors; ++i) { sectorFree.add(Boolean.TRUE); } sectorFree.set(0, Boolean.FALSE); // chunk offset table sectorFree.set(1, Boolean.FALSE); // for the last modified info file.seek(0); for (int i = 0; i < SECTOR_INTS; ++i) { int offset = file.readInt(); offsets[i] = offset; if (offset != 0 && (offset >> 8) + (offset & 0xFF) <= sectorFree.size()) { for (int sectorNum = 0; sectorNum < (offset & 0xFF); ++sectorNum) { sectorFree.set((offset >> 8) + sectorNum, Boolean.FALSE); } } } for (int i = 0; i < SECTOR_INTS; ++i) { int lastModValue = file.readInt(); chunkTimestamps[i] = lastModValue; } } catch (IOException e) { e.printStackTrace(); } } public File getFile() { return fileName; } /* the modification date of the region file when it was first opened */ public long lastModified() { return lastModified; } /* gets how much the region file has grown since it was last checked */ public synchronized int getSizeDelta() { int ret = sizeDelta; sizeDelta = 0; return ret; } // various small debug printing helpers private void debug(String in) { // System.out.print(in); } private void debugln(String in) { debug(in + "\n"); } private void debug(String mode, int x, int z, String in) { debug("REGION " + mode + " " + fileName.getName() + "[" + x + "," + z + "] = " + in); } private void debug(String mode, int x, int z, int count, String in) { debug("REGION " + mode + " " + fileName.getName() + "[" + x + "," + z + "] " + count + "B = " + in); } private void debugln(String mode, int x, int z, String in) { debug(mode, x, z, in + "\n"); } /* * gets an (uncompressed) stream representing the chunk data returns null if * the chunk is not found or an error occurs */ public synchronized DataInputStream getChunkDataInputStream(int x, int z) { if (outOfBounds(x, z)) { debugln("READ", x, z, "out of bounds"); return null; } try { int offset = getOffset(x, z); if (offset == 0) { // debugln("READ", x, z, "miss"); return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > sectorFree.size()) { debugln("READ", x, z, "invalid sector"); return null; } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors); return null; } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream(new GZIPInputStream(new ByteArrayInputStream(data))); // debug("READ", x, z, " = found"); return ret; } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(data))); // debug("READ", x, z, " = found"); return ret; } debugln("READ", x, z, "unknown version " + version); return null; } catch (IOException e) { debugln("READ", x, z, "exception"); return null; } } public DataOutputStream getChunkDataOutputStream(int x, int z) { if (outOfBounds(x, z)) return null; return new DataOutputStream(new DeflaterOutputStream(getChunkOutputStream(x, z, VERSION_DEFLATE))); } /** * Returns a low-level OutputStream object that is not wrapped in * compressing and DataOutputStream objects. May be useful if * data to be written is already compressed. * @author TOGoS */ public OutputStream getChunkOutputStream( int x, int z, int format ) { if (outOfBounds(x, z)) return null; return new ChunkBuffer(x, z, format); } /* * lets chunk writing be multithreaded by not locking the whole file as a * chunk is serializing -- only writes when serialization is over */ class ChunkBuffer extends ByteArrayOutputStream { public final int x, z, format; public ChunkBuffer(int x, int z, int format) { super(8096); // initialize to 8KB this.x = x; this.z = z; this.format = format; } public void close() { RegionFile.this.write(x, z, buf, count, format); } } /* write a chunk at (x,z) with length bytes of data to disk */ protected synchronized void write(int x, int z, byte[] data, int length, int format) { try { int offset = getOffset(x, z); int sectorNumber = offset >> 8; int sectorsAllocated = offset & 0xFF; int sectorsNeeded = (length + CHUNK_HEADER_SIZE) / SECTOR_BYTES + 1; // maximum chunk size is 1MB if (sectorsNeeded >= 256) { return; } if (sectorNumber != 0 && sectorsAllocated == sectorsNeeded) { /* we can simply overwrite the old sectors */ debug("SAVE", x, z, length, "rewrite"); write(sectorNumber, data, length, format); } else { /* we need to allocate new sectors */ /* mark the sectors previously used for this chunk as free */ for (int i = 0; i < sectorsAllocated; ++i) { sectorFree.set(sectorNumber + i, Boolean.TRUE); } /* scan for a free space large enough to store this chunk */ int runStart = sectorFree.indexOf(Boolean.TRUE); int runLength = 0; if (runStart != -1) { for (int i = runStart; i < sectorFree.size(); ++i) { if (runLength != 0) { if( sectorFree.get(i) ) runLength++; else runLength = 0; } else if( sectorFree.get(i) ) { runStart = i; runLength = 1; } if (runLength >= sectorsNeeded) { break; } } } if (runLength >= sectorsNeeded) { /* we found a free space large enough */ debug("SAVE", x, z, length, "reuse"); sectorNumber = runStart; setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); for (int i = 0; i < sectorsNeeded; ++i) { sectorFree.set(sectorNumber + i, Boolean.FALSE); } write(sectorNumber, data, length, format); } else { /* * no free space large enough found -- we need to grow the * file */ debug("SAVE", x, z, length, "grow"); file.seek(file.length()); sectorNumber = sectorFree.size(); for (int i = 0; i < sectorsNeeded; ++i) { file.write(emptySector); sectorFree.add(Boolean.FALSE); } sizeDelta += SECTOR_BYTES * sectorsNeeded; write(sectorNumber, data, length, format); setOffset(x, z, (sectorNumber << 8) | sectorsNeeded); } } setTimestamp(x, z, (int) (System.currentTimeMillis() / 1000L)); } catch (IOException e) { e.printStackTrace(); } } /* write a chunk data to the region file at specified sector number */ private void write(int sectorNumber, byte[] data, int length, int format) throws IOException { debugln(" " + sectorNumber); file.seek(sectorNumber * SECTOR_BYTES); file.writeInt(length + 1); // chunk length file.writeByte(format); // chunk version number file.write(data, 0, length); // chunk data } /* is this an invalid chunk coordinate? */ private boolean outOfBounds(int x, int z) { return x < 0 || x >= 32 || z < 0 || z >= 32; } private int getOffset(int x, int z) { return offsets[x + z * 32]; } public boolean hasChunk(int x, int z) { return getOffset(x, z) != 0; } private void setOffset(int x, int z, int offset) throws IOException { offsets[x + z * 32] = offset; file.seek((x + z * 32) * 4); file.writeInt(offset); } private void setTimestamp(int x, int z, int value) throws IOException { chunkTimestamps[x + z * 32] = value; file.seek(SECTOR_BYTES + (x + z * 32) * 4); file.writeInt(value); } public void close() throws IOException { if( file != null ) { file.close(); file = null; } } }
bsd-3-clause