code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace Kunstmaan\GeneratorBundle\Generator; use Symfony\Component\HttpKernel\Bundle\BundleInterface; /** * Generates all classes/files for a new page */ class PageGenerator extends KunstmaanGenerator { /** * @var BundleInterface */ private $bundle; /** * @var string */ private $entity; /** * @var string */ private $prefix; /** * @var array */ private $fields; /** * @var string */ private $template; /** * @var array */ private $sections; /** * @var array */ private $parentPages; /** * Generate the page. * * @param BundleInterface $bundle The bundle * @param string $entity The entity name * @param string $prefix The database prefix * @param array $fields The fields * @param string $template The page template * @param array $sections The page sections * @param array $parentPages The parent pages * * @throws \RuntimeException */ public function generate( BundleInterface $bundle, $entity, $prefix, array $fields, $template, array $sections, array $parentPages ) { $this->bundle = $bundle; $this->entity = $entity; $this->prefix = $prefix; $this->fields = $fields; $this->template = $template; $this->sections = $sections; $this->parentPages = $parentPages; $this->generatePageEntity(); $this->generatePageFormType(); $this->generatePageTemplateConfiguration(); $this->updateParentPages(); } /** * Generate the page entity. * * @throws \RuntimeException */ private function generatePageEntity() { list($entityCode, $entityPath) = $this->generateEntity( $this->bundle, $this->entity, $this->fields, 'Pages', $this->prefix, 'Kunstmaan\NodeBundle\Entity\AbstractPage' ); // Add implements HasPageTemplateInterface $search = 'extends \Kunstmaan\NodeBundle\Entity\AbstractPage'; $entityCode = str_replace( $search, $search . ' implements \Kunstmaan\PagePartBundle\Helper\HasPageTemplateInterface', $entityCode ); // Add some extra functions in the generated entity :s $params = array( 'bundle' => $this->bundle->getName(), 'page' => $this->entity, 'template' => substr($this->template, 0, strlen($this->template) - 4), 'sections' => array_map( function ($val) { return substr($val, 0, strlen($val) - 4); }, $this->sections ), 'adminType' => '\\' . $this->bundle->getNamespace() . '\\Form\\Pages\\' . $this->entity . 'AdminType', 'namespace' => $this->registry->getAliasNamespace($this->bundle->getName()) . '\\Pages\\' . $this->entity ); $extraCode = $this->render('/Entity/Pages/ExtraFunctions.php', $params); $pos = strrpos($entityCode, '}'); $trimmed = substr($entityCode, 0, $pos); $entityCode = $trimmed . $extraCode . "\n}"; // Write class to filesystem $this->filesystem->mkdir(dirname($entityPath)); file_put_contents($entityPath, $entityCode); $this->assistant->writeLine('Generating entity : <info>OK</info>'); } /** * Generate the admin form type entity. */ private function generatePageFormType() { $this->generateEntityAdminType( $this->bundle, $this->entity, 'Pages', $this->fields, '\Kunstmaan\NodeBundle\Form\PageAdminType' ); $this->assistant->writeLine('Generating form type : <info>OK</info>'); } /** * Generate the page template -and pagepart configuration. */ private function generatePageTemplateConfiguration() { $this->installDefaultPageTemplates($this->bundle); $this->installDefaultPagePartConfiguration($this->bundle); $this->assistant->writeLine('Generating template configuration : <info>OK</info>'); } /** * Update the getPossibleChildTypes function of the parent Page classes */ private function updateParentPages() { $phpCode = " array(\n"; $phpCode .= " 'name' => '" . $this->entity . "',\n"; $phpCode .= " 'class'=> '" . $this->bundle->getNamespace() . "\\Entity\\Pages\\" . $this->entity . "'\n"; $phpCode .= " ),"; // When there is a BehatTestPage, we should also allow the new page as sub page $behatTestPage = $this->bundle->getPath() . '/Entity/Pages/BehatTestPage.php'; if (file_exists($behatTestPage)) { $this->parentPages[] = $behatTestPage; } foreach ($this->parentPages as $file) { $data = file_get_contents($file); $data = preg_replace( '/(function\s*getPossibleChildTypes\s*\(\)\s*\{\s*return\s*array\s*\()/', "$1\n$phpCode", $data ); file_put_contents($file, $data); } } }
Amrit01/KunstmaanBundlesCMS
src/Kunstmaan/GeneratorBundle/Generator/PageGenerator.php
PHP
mit
5,521
/** * */ var obj = { num: 123, str: 'hello', }; obj.
JonathanUsername/flow
newtests/autocomplete/foo.js
JavaScript
mit
61
function error_log(message, message_type, destination, extra_headers) { // http://kevin.vanzonneveld.net // + original by: Paul Hutchinson (http://restaurantthing.com/) // + revised by: Brett Zamir (http://brett-zamir.me) // % note 1: The dependencies, mail(), syslog(), and file_put_contents() // % note 1: are either not fullly implemented or implemented at all // - depends on: mail // - depends on: syslog // - depends on: file_put_contents // * example 1: error_log('Oops!'); // * returns 1: true var that = this, _sapi = function() { // SAPI logging (we treat console as the "server" logging; the // syslog option could do so potentially as well) if (!that.window.console || !that.window.console.log) { return false; } that.window.console.log(message); return true; }; message_type = message_type || 0; switch (message_type) { case 1: // Email var subject = 'PHP error_log message'; // Apparently no way to customize the subject return this.mail(destination, subject, message, extra_headers); case 2: // No longer an option in PHP, but had been to send via TCP/IP to 'destination' (name or IP:port) // use socket_create() and socket_send()? return false; case 0: // syslog or file depending on ini var log = this.php_js && this.php_js.ini && this.php_js.ini.error_log && this.php_js.ini.error_log.local_value; if (!log) { return _sapi(); } if (log === 'syslog') { return this.syslog(4, message); // presumably 'LOG_ERR' (4) is correct? } destination = log; // Fall-through case 3: // File logging var ret = this.file_put_contents(destination, message, 8); // FILE_APPEND (8) return ret === false ? false : true; case 4: // SAPI logging return _sapi(); default: // Unrecognized value return false; } return false; // Shouldn't get here }
cigraphics/phpjs
experimental/errorfunc/error_log.js
JavaScript
mit
2,020
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/content_settings/content_settings_store.h" #include <set> #include "base/debug/alias.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/values.h" #include "chrome/browser/content_settings/content_settings_origin_identifier_value_map.h" #include "chrome/browser/content_settings/content_settings_rule.h" #include "chrome/browser/content_settings/content_settings_utils.h" #include "chrome/browser/extensions/api/content_settings/content_settings_api_constants.h" #include "chrome/browser/extensions/api/content_settings/content_settings_helpers.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; using content_settings::ConcatenationIterator; using content_settings::Rule; using content_settings::RuleIterator; using content_settings::OriginIdentifierValueMap; using content_settings::ResourceIdentifier; using content_settings::ValueToContentSetting; namespace extensions { namespace helpers = content_settings_helpers; namespace keys = content_settings_api_constants; struct ContentSettingsStore::ExtensionEntry { // Extension id std::string id; // Whether extension is enabled in the profile. bool enabled; // Content settings. OriginIdentifierValueMap settings; // Persistent incognito content settings. OriginIdentifierValueMap incognito_persistent_settings; // Session-only incognito content settings. OriginIdentifierValueMap incognito_session_only_settings; }; ContentSettingsStore::ContentSettingsStore() { DCHECK(OnCorrectThread()); } ContentSettingsStore::~ContentSettingsStore() { STLDeleteValues(&entries_); } RuleIterator* ContentSettingsStore::GetRuleIterator( ContentSettingsType type, const content_settings::ResourceIdentifier& identifier, bool incognito) const { ScopedVector<RuleIterator> iterators; // Iterate the extensions based on install time (last installed extensions // first). ExtensionEntryMap::const_reverse_iterator entry; // The individual |RuleIterators| shouldn't lock; pass |lock_| to the // |ConcatenationIterator| in a locked state. scoped_ptr<base::AutoLock> auto_lock(new base::AutoLock(lock_)); for (entry = entries_.rbegin(); entry != entries_.rend(); ++entry) { if (!entry->second->enabled) continue; if (incognito) { iterators.push_back( entry->second->incognito_session_only_settings.GetRuleIterator( type, identifier, NULL)); iterators.push_back( entry->second->incognito_persistent_settings.GetRuleIterator( type, identifier, NULL)); } else { iterators.push_back( entry->second->settings.GetRuleIterator(type, identifier, NULL)); } } return new ConcatenationIterator(&iterators, auto_lock.release()); } void ContentSettingsStore::SetExtensionContentSetting( const std::string& ext_id, const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType type, const content_settings::ResourceIdentifier& identifier, ContentSetting setting, ExtensionPrefsScope scope) { { base::AutoLock lock(lock_); OriginIdentifierValueMap* map = GetValueMap(ext_id, scope); if (setting == CONTENT_SETTING_DEFAULT) { map->DeleteValue(primary_pattern, secondary_pattern, type, identifier); } else { map->SetValue(primary_pattern, secondary_pattern, type, identifier, new base::FundamentalValue(setting)); } } // Send notification that content settings changed. // TODO(markusheintz): Notifications should only be sent if the set content // setting is effective and not hidden by another setting of another // extension installed more recently. NotifyOfContentSettingChanged(ext_id, scope != kExtensionPrefsScopeRegular); } void ContentSettingsStore::RegisterExtension( const std::string& ext_id, const base::Time& install_time, bool is_enabled) { base::AutoLock lock(lock_); ExtensionEntryMap::iterator i = FindEntry(ext_id); ExtensionEntry* entry; if (i != entries_.end()) { entry = i->second; } else { entry = new ExtensionEntry; entries_.insert(std::make_pair(install_time, entry)); } entry->id = ext_id; entry->enabled = is_enabled; } void ContentSettingsStore::UnregisterExtension( const std::string& ext_id) { bool notify = false; bool notify_incognito = false; { base::AutoLock lock(lock_); ExtensionEntryMap::iterator i = FindEntry(ext_id); if (i == entries_.end()) return; notify = !i->second->settings.empty(); notify_incognito = !i->second->incognito_persistent_settings.empty() || !i->second->incognito_session_only_settings.empty(); delete i->second; entries_.erase(i); } if (notify) NotifyOfContentSettingChanged(ext_id, false); if (notify_incognito) NotifyOfContentSettingChanged(ext_id, true); } void ContentSettingsStore::SetExtensionState( const std::string& ext_id, bool is_enabled) { bool notify = false; bool notify_incognito = false; { base::AutoLock lock(lock_); ExtensionEntryMap::const_iterator i = FindEntry(ext_id); if (i == entries_.end()) return; notify = !i->second->settings.empty(); notify_incognito = !i->second->incognito_persistent_settings.empty() || !i->second->incognito_session_only_settings.empty(); i->second->enabled = is_enabled; } if (notify) NotifyOfContentSettingChanged(ext_id, false); if (notify_incognito) NotifyOfContentSettingChanged(ext_id, true); } OriginIdentifierValueMap* ContentSettingsStore::GetValueMap( const std::string& ext_id, ExtensionPrefsScope scope) { ExtensionEntryMap::const_iterator i = FindEntry(ext_id); if (i != entries_.end()) { switch (scope) { case kExtensionPrefsScopeRegular: return &(i->second->settings); case kExtensionPrefsScopeRegularOnly: // TODO(bauerb): Implement regular-only content settings. NOTREACHED(); return NULL; case kExtensionPrefsScopeIncognitoPersistent: return &(i->second->incognito_persistent_settings); case kExtensionPrefsScopeIncognitoSessionOnly: return &(i->second->incognito_session_only_settings); } } return NULL; } const OriginIdentifierValueMap* ContentSettingsStore::GetValueMap( const std::string& ext_id, ExtensionPrefsScope scope) const { ExtensionEntryMap::const_iterator i = FindEntry(ext_id); if (i == entries_.end()) return NULL; switch (scope) { case kExtensionPrefsScopeRegular: return &(i->second->settings); case kExtensionPrefsScopeRegularOnly: // TODO(bauerb): Implement regular-only content settings. NOTREACHED(); return NULL; case kExtensionPrefsScopeIncognitoPersistent: return &(i->second->incognito_persistent_settings); case kExtensionPrefsScopeIncognitoSessionOnly: return &(i->second->incognito_session_only_settings); } NOTREACHED(); return NULL; } void ContentSettingsStore::ClearContentSettingsForExtension( const std::string& ext_id, ExtensionPrefsScope scope) { bool notify = false; { base::AutoLock lock(lock_); OriginIdentifierValueMap* map = GetValueMap(ext_id, scope); if (!map) { // Fail gracefully in Release builds. NOTREACHED(); return; } notify = !map->empty(); map->clear(); } if (notify) { NotifyOfContentSettingChanged(ext_id, scope != kExtensionPrefsScopeRegular); } } base::ListValue* ContentSettingsStore::GetSettingsForExtension( const std::string& extension_id, ExtensionPrefsScope scope) const { base::AutoLock lock(lock_); const OriginIdentifierValueMap* map = GetValueMap(extension_id, scope); if (!map) return NULL; base::ListValue* settings = new base::ListValue(); OriginIdentifierValueMap::EntryMap::const_iterator it; for (it = map->begin(); it != map->end(); ++it) { scoped_ptr<RuleIterator> rule_iterator( map->GetRuleIterator(it->first.content_type, it->first.resource_identifier, NULL)); // We already hold the lock. while (rule_iterator->HasNext()) { const Rule& rule = rule_iterator->Next(); base::DictionaryValue* setting_dict = new base::DictionaryValue(); setting_dict->SetString(keys::kPrimaryPatternKey, rule.primary_pattern.ToString()); setting_dict->SetString(keys::kSecondaryPatternKey, rule.secondary_pattern.ToString()); setting_dict->SetString( keys::kContentSettingsTypeKey, helpers::ContentSettingsTypeToString(it->first.content_type)); setting_dict->SetString(keys::kResourceIdentifierKey, it->first.resource_identifier); ContentSetting content_setting = ValueToContentSetting(rule.value.get()); DCHECK_NE(CONTENT_SETTING_DEFAULT, content_setting); setting_dict->SetString( keys::kContentSettingKey, helpers::ContentSettingToString(content_setting)); settings->Append(setting_dict); } } return settings; } void ContentSettingsStore::SetExtensionContentSettingFromList( const std::string& extension_id, const base::ListValue* list, ExtensionPrefsScope scope) { for (base::ListValue::const_iterator it = list->begin(); it != list->end(); ++it) { if ((*it)->GetType() != Value::TYPE_DICTIONARY) { NOTREACHED(); continue; } base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(*it); std::string primary_pattern_str; dict->GetString(keys::kPrimaryPatternKey, &primary_pattern_str); ContentSettingsPattern primary_pattern = ContentSettingsPattern::FromString(primary_pattern_str); DCHECK(primary_pattern.IsValid()); std::string secondary_pattern_str; dict->GetString(keys::kSecondaryPatternKey, &secondary_pattern_str); ContentSettingsPattern secondary_pattern = ContentSettingsPattern::FromString(secondary_pattern_str); DCHECK(secondary_pattern.IsValid()); std::string content_settings_type_str; dict->GetString(keys::kContentSettingsTypeKey, &content_settings_type_str); ContentSettingsType content_settings_type = helpers::StringToContentSettingsType(content_settings_type_str); DCHECK_NE(CONTENT_SETTINGS_TYPE_DEFAULT, content_settings_type); std::string resource_identifier; dict->GetString(keys::kResourceIdentifierKey, &resource_identifier); std::string content_setting_string; dict->GetString(keys::kContentSettingKey, &content_setting_string); ContentSetting setting = CONTENT_SETTING_DEFAULT; bool result = helpers::StringToContentSetting(content_setting_string, &setting); DCHECK(result); SetExtensionContentSetting(extension_id, primary_pattern, secondary_pattern, content_settings_type, resource_identifier, setting, scope); } } void ContentSettingsStore::AddObserver(Observer* observer) { DCHECK(OnCorrectThread()); observers_.AddObserver(observer); } void ContentSettingsStore::RemoveObserver(Observer* observer) { DCHECK(OnCorrectThread()); observers_.RemoveObserver(observer); } void ContentSettingsStore::NotifyOfContentSettingChanged( const std::string& extension_id, bool incognito) { FOR_EACH_OBSERVER( ContentSettingsStore::Observer, observers_, OnContentSettingChanged(extension_id, incognito)); } bool ContentSettingsStore::OnCorrectThread() { // If there is no UI thread, we're most likely in a unit test. return !BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI); } ContentSettingsStore::ExtensionEntryMap::iterator ContentSettingsStore::FindEntry(const std::string& ext_id) { ExtensionEntryMap::iterator i; for (i = entries_.begin(); i != entries_.end(); ++i) { if (i->second->id == ext_id) return i; } return entries_.end(); } ContentSettingsStore::ExtensionEntryMap::const_iterator ContentSettingsStore::FindEntry(const std::string& ext_id) const { ExtensionEntryMap::const_iterator i; for (i = entries_.begin(); i != entries_.end(); ++i) { if (i->second->id == ext_id) return i; } return entries_.end(); } } // namespace extensions
qtekfun/htcDesire820Kernel
external/chromium_org/chrome/browser/extensions/api/content_settings/content_settings_store.cc
C++
gpl-2.0
12,997
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Version details. * * @package report * @subpackage backups * @copyright 2007 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; $plugin->version = 2017051500; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2017050500; // Requires this Moodle version $plugin->component = 'report_backups'; // Full name of the plugin (used for diagnostics)
cbradley456/moodle
report/backups/version.php
PHP
gpl-3.0
1,202
'use strict' const Buffer = require('safe-buffer').Buffer const crypto = require('crypto') const Transform = require('stream').Transform const SPEC_ALGORITHMS = ['sha256', 'sha384', 'sha512'] const BASE64_REGEX = /^[a-z0-9+/]+(?:=?=?)$/i const SRI_REGEX = /^([^-]+)-([^?]+)([?\S*]*)$/ const STRICT_SRI_REGEX = /^([^-]+)-([A-Za-z0-9+/=]{44,88})(\?[\x21-\x7E]*)*$/ const VCHAR_REGEX = /^[\x21-\x7E]+$/ class Hash { get isHash () { return true } constructor (hash, opts) { const strict = !!(opts && opts.strict) this.source = hash.trim() // 3.1. Integrity metadata (called "Hash" by ssri) // https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description const match = this.source.match( strict ? STRICT_SRI_REGEX : SRI_REGEX ) if (!match) { return } if (strict && !SPEC_ALGORITHMS.some(a => a === match[1])) { return } this.algorithm = match[1] this.digest = match[2] const rawOpts = match[3] this.options = rawOpts ? rawOpts.slice(1).split('?') : [] } hexDigest () { return this.digest && Buffer.from(this.digest, 'base64').toString('hex') } toJSON () { return this.toString() } toString (opts) { if (opts && opts.strict) { // Strict mode enforces the standard as close to the foot of the // letter as it can. if (!( // The spec has very restricted productions for algorithms. // https://www.w3.org/TR/CSP2/#source-list-syntax SPEC_ALGORITHMS.some(x => x === this.algorithm) && // Usually, if someone insists on using a "different" base64, we // leave it as-is, since there's multiple standards, and the // specified is not a URL-safe variant. // https://www.w3.org/TR/CSP2/#base64_value this.digest.match(BASE64_REGEX) && // Option syntax is strictly visual chars. // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-option-expression // https://tools.ietf.org/html/rfc5234#appendix-B.1 (this.options || []).every(opt => opt.match(VCHAR_REGEX)) )) { return '' } } const options = this.options && this.options.length ? `?${this.options.join('?')}` : '' return `${this.algorithm}-${this.digest}${options}` } } class Integrity { get isIntegrity () { return true } toJSON () { return this.toString() } toString (opts) { opts = opts || {} let sep = opts.sep || ' ' if (opts.strict) { // Entries must be separated by whitespace, according to spec. sep = sep.replace(/\S+/g, ' ') } return Object.keys(this).map(k => { return this[k].map(hash => { return Hash.prototype.toString.call(hash, opts) }).filter(x => x.length).join(sep) }).filter(x => x.length).join(sep) } concat (integrity, opts) { const other = typeof integrity === 'string' ? integrity : stringify(integrity, opts) return parse(`${this.toString(opts)} ${other}`, opts) } hexDigest () { return parse(this, {single: true}).hexDigest() } match (integrity, opts) { const other = parse(integrity, opts) const algo = other.pickAlgorithm(opts) return ( this[algo] && other[algo] && this[algo].find(hash => other[algo].find(otherhash => hash.digest === otherhash.digest ) ) ) || false } pickAlgorithm (opts) { const pickAlgorithm = (opts && opts.pickAlgorithm) || getPrioritizedHash const keys = Object.keys(this) if (!keys.length) { throw new Error(`No algorithms available for ${ JSON.stringify(this.toString()) }`) } return keys.reduce((acc, algo) => { return pickAlgorithm(acc, algo) || acc }) } } module.exports.parse = parse function parse (sri, opts) { opts = opts || {} if (typeof sri === 'string') { return _parse(sri, opts) } else if (sri.algorithm && sri.digest) { const fullSri = new Integrity() fullSri[sri.algorithm] = [sri] return _parse(stringify(fullSri, opts), opts) } else { return _parse(stringify(sri, opts), opts) } } function _parse (integrity, opts) { // 3.4.3. Parse metadata // https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata if (opts.single) { return new Hash(integrity, opts) } return integrity.trim().split(/\s+/).reduce((acc, string) => { const hash = new Hash(string, opts) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) } module.exports.stringify = stringify function stringify (obj, opts) { if (obj.algorithm && obj.digest) { return Hash.prototype.toString.call(obj, opts) } else if (typeof obj === 'string') { return stringify(parse(obj, opts), opts) } else { return Integrity.prototype.toString.call(obj, opts) } } module.exports.fromHex = fromHex function fromHex (hexDigest, algorithm, opts) { const optString = (opts && opts.options && opts.options.length) ? `?${opts.options.join('?')}` : '' return parse( `${algorithm}-${ Buffer.from(hexDigest, 'hex').toString('base64') }${optString}`, opts ) } module.exports.fromData = fromData function fromData (data, opts) { opts = opts || {} const algorithms = opts.algorithms || ['sha512'] const optString = opts.options && opts.options.length ? `?${opts.options.join('?')}` : '' return algorithms.reduce((acc, algo) => { const digest = crypto.createHash(algo).update(data).digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) } module.exports.fromStream = fromStream function fromStream (stream, opts) { opts = opts || {} const P = opts.Promise || Promise const istream = integrityStream(opts) return new P((resolve, reject) => { stream.pipe(istream) stream.on('error', reject) istream.on('error', reject) let sri istream.on('integrity', s => { sri = s }) istream.on('end', () => resolve(sri)) istream.on('data', () => {}) }) } module.exports.checkData = checkData function checkData (data, sri, opts) { opts = opts || {} sri = parse(sri, opts) if (!Object.keys(sri).length) { if (opts.error) { throw Object.assign( new Error('No valid integrity hashes to check against'), { code: 'EINTEGRITY' } ) } else { return false } } const algorithm = sri.pickAlgorithm(opts) const digest = crypto.createHash(algorithm).update(data).digest('base64') const newSri = parse({algorithm, digest}) const match = newSri.match(sri, opts) if (match || !opts.error) { return match } else if (typeof opts.size === 'number' && (data.length !== opts.size)) { const err = new Error(`data size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${data.length}`) err.code = 'EBADSIZE' err.found = data.length err.expected = opts.size err.sri = sri throw err } else { const err = new Error(`Integrity checksum failed when using ${algorithm}: Wanted ${sri}, but got ${newSri}. (${data.length} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = sri err.algorithm = algorithm err.sri = sri throw err } } module.exports.checkStream = checkStream function checkStream (stream, sri, opts) { opts = opts || {} const P = opts.Promise || Promise const checker = integrityStream(Object.assign({}, opts, { integrity: sri })) return new P((resolve, reject) => { stream.pipe(checker) stream.on('error', reject) checker.on('error', reject) let sri checker.on('verified', s => { sri = s }) checker.on('end', () => resolve(sri)) checker.on('data', () => {}) }) } module.exports.integrityStream = integrityStream function integrityStream (opts) { opts = opts || {} // For verification const sri = opts.integrity && parse(opts.integrity, opts) const goodSri = sri && Object.keys(sri).length const algorithm = goodSri && sri.pickAlgorithm(opts) const digests = goodSri && sri[algorithm] // Calculating stream const algorithms = Array.from( new Set( (opts.algorithms || ['sha512']) .concat(algorithm ? [algorithm] : []) ) ) const hashes = algorithms.map(crypto.createHash) let streamSize = 0 const stream = new Transform({ transform (chunk, enc, cb) { streamSize += chunk.length hashes.forEach(h => h.update(chunk, enc)) cb(null, chunk, enc) } }).on('end', () => { const optString = (opts.options && opts.options.length) ? `?${opts.options.join('?')}` : '' const newSri = parse(hashes.map((h, i) => { return `${algorithms[i]}-${h.digest('base64')}${optString}` }).join(' '), opts) // Integrity verification mode const match = goodSri && newSri.match(sri, opts) if (typeof opts.size === 'number' && streamSize !== opts.size) { const err = new Error(`stream size mismatch when checking ${sri}.\n Wanted: ${opts.size}\n Found: ${streamSize}`) err.code = 'EBADSIZE' err.found = streamSize err.expected = opts.size err.sri = sri stream.emit('error', err) } else if (opts.integrity && !match) { const err = new Error(`${sri} integrity checksum failed when using ${algorithm}: wanted ${digests} but got ${newSri}. (${streamSize} bytes)`) err.code = 'EINTEGRITY' err.found = newSri err.expected = digests err.algorithm = algorithm err.sri = sri stream.emit('error', err) } else { stream.emit('size', streamSize) stream.emit('integrity', newSri) match && stream.emit('verified', match) } }) return stream } module.exports.create = createIntegrity function createIntegrity (opts) { opts = opts || {} const algorithms = opts.algorithms || ['sha512'] const optString = opts.options && opts.options.length ? `?${opts.options.join('?')}` : '' const hashes = algorithms.map(crypto.createHash) return { update: function (chunk, enc) { hashes.forEach(h => h.update(chunk, enc)) return this }, digest: function (enc) { const integrity = algorithms.reduce((acc, algo) => { const digest = hashes.shift().digest('base64') const hash = new Hash( `${algo}-${digest}${optString}`, opts ) if (hash.algorithm && hash.digest) { const algo = hash.algorithm if (!acc[algo]) { acc[algo] = [] } acc[algo].push(hash) } return acc }, new Integrity()) return integrity } } } const NODE_HASHES = new Set(crypto.getHashes()) // This is a Best Effort™ at a reasonable priority for hash algos const DEFAULT_PRIORITY = [ 'md5', 'whirlpool', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512', // TODO - it's unclear _which_ of these Node will actually use as its name // for the algorithm, so we guesswork it based on the OpenSSL names. 'sha3', 'sha3-256', 'sha3-384', 'sha3-512', 'sha3_256', 'sha3_384', 'sha3_512' ].filter(algo => NODE_HASHES.has(algo)) function getPrioritizedHash (algo1, algo2) { return DEFAULT_PRIORITY.indexOf(algo1.toLowerCase()) >= DEFAULT_PRIORITY.indexOf(algo2.toLowerCase()) ? algo1 : algo2 }
veerhiremath7/veerhiremath7.github.io
node_modules/ssri/index.js
JavaScript
unlicense
11,559
/// <reference path="fourslash.ts" /> // @allowNonTsExtensions: true // @Filename: file.js //// /** //// * @param {number} a //// * @param {string} b //// */ //// exports.foo = function(a, b) { //// a/*a*/; //// b/*b*/ //// }; goTo.marker('a'); edit.insert('.'); verify.completionListContains('toFixed', undefined, undefined, 'method'); goTo.marker('b'); edit.insert('.'); verify.completionListContains('substr', undefined, undefined, 'method');
plantain-00/TypeScript
tests/cases/fourslash/getJavaScriptCompletions18.ts
TypeScript
apache-2.0
477
//===--- ScratchBuffer.cpp - Scratch space for forming tokens -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ScratchBuffer interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/ScratchBuffer.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/MemoryBuffer.h" #include <cstring> using namespace clang; // ScratchBufSize - The size of each chunk of scratch memory. Slightly less //than a page, almost certainly enough for anything. :) static const unsigned ScratchBufSize = 4060; ScratchBuffer::ScratchBuffer(SourceManager &SM) : SourceMgr(SM), CurBuffer(0) { // Set BytesUsed so that the first call to getToken will require an alloc. BytesUsed = ScratchBufSize; } /// getToken - Splat the specified text into a temporary MemoryBuffer and /// return a SourceLocation that refers to the token. This is just like the /// method below, but returns a location that indicates the physloc of the /// token. SourceLocation ScratchBuffer::getToken(const char *Buf, unsigned Len, const char *&DestPtr) { if (BytesUsed+Len+2 > ScratchBufSize) AllocScratchBuffer(Len+2); // Prefix the token with a \n, so that it looks like it is the first thing on // its own virtual line in caret diagnostics. CurBuffer[BytesUsed++] = '\n'; // Return a pointer to the character data. DestPtr = CurBuffer+BytesUsed; // Copy the token data into the buffer. memcpy(CurBuffer+BytesUsed, Buf, Len); // Remember that we used these bytes. BytesUsed += Len+1; // Add a NUL terminator to the token. This keeps the tokens separated, in // case they get relexed, and puts them on their own virtual lines in case a // diagnostic points to one. CurBuffer[BytesUsed-1] = '\0'; return BufferStartLoc.getLocWithOffset(BytesUsed-Len-1); } void ScratchBuffer::AllocScratchBuffer(unsigned RequestLen) { // Only pay attention to the requested length if it is larger than our default // page size. If it is, we allocate an entire chunk for it. This is to // support gigantic tokens, which almost certainly won't happen. :) if (RequestLen < ScratchBufSize) RequestLen = ScratchBufSize; llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getNewMemBuffer(RequestLen, "<scratch space>"); FileID FID = SourceMgr.createFileIDForMemBuffer(Buf); BufferStartLoc = SourceMgr.getLocForStartOfFile(FID); CurBuffer = const_cast<char*>(Buf->getBufferStart()); BytesUsed = 1; CurBuffer[0] = '0'; // Start out with a \0 for cleanliness. }
jeltz/rust-debian-package
src/llvm/tools/clang/lib/Lex/ScratchBuffer.cpp
C++
apache-2.0
2,830
<?php /** * Validates an integer representation of pixels according to the HTML spec. */ class HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef { protected $max; public function __construct($max = null) { $this->max = $max; } public function validate($string, $config, $context) { $string = trim($string); if ($string === '0') return $string; if ($string === '') return false; $length = strlen($string); if (substr($string, $length - 2) == 'px') { $string = substr($string, 0, $length - 2); } if (!is_numeric($string)) return false; $int = (int) $string; if ($int < 0) return '0'; // upper-bound value, extremely high values can // crash operating systems, see <http://ha.ckers.org/imagecrash.html> // WARNING, above link WILL crash you if you're using Windows if ($this->max !== null && $int > $this->max) return (string) $this->max; return (string) $int; } public function make($string) { if ($string === '') $max = null; else $max = (int) $string; $class = get_class($this); return new $class($max); } }
cappetta/CyberCloud
puppet/garbage/website/files/DVWA/external/phpids/0.6/lib/IDS/vendors/htmlpurifier/HTMLPurifier/AttrDef/HTML/Pixels.php
PHP
apache-2.0
1,343
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.rds.model; import java.io.Serializable; /** * <p> * Contains the result of a successful invocation of the * ModifyDBParameterGroup or ResetDBParameterGroup action. * </p> */ public class ResetDBParameterGroupResult implements Serializable, Cloneable { /** * Provides the name of the DB parameter group. */ private String dBParameterGroupName; /** * Provides the name of the DB parameter group. * * @return Provides the name of the DB parameter group. */ public String getDBParameterGroupName() { return dBParameterGroupName; } /** * Provides the name of the DB parameter group. * * @param dBParameterGroupName Provides the name of the DB parameter group. */ public void setDBParameterGroupName(String dBParameterGroupName) { this.dBParameterGroupName = dBParameterGroupName; } /** * Provides the name of the DB parameter group. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param dBParameterGroupName Provides the name of the DB parameter group. * * @return A reference to this updated object so that method calls can be chained * together. */ public ResetDBParameterGroupResult withDBParameterGroupName(String dBParameterGroupName) { this.dBParameterGroupName = dBParameterGroupName; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDBParameterGroupName() != null) sb.append("DBParameterGroupName: " + getDBParameterGroupName() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDBParameterGroupName() == null) ? 0 : getDBParameterGroupName().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ResetDBParameterGroupResult == false) return false; ResetDBParameterGroupResult other = (ResetDBParameterGroupResult)obj; if (other.getDBParameterGroupName() == null ^ this.getDBParameterGroupName() == null) return false; if (other.getDBParameterGroupName() != null && other.getDBParameterGroupName().equals(this.getDBParameterGroupName()) == false) return false; return true; } @Override public ResetDBParameterGroupResult clone() { try { return (ResetDBParameterGroupResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
mahaliachante/aws-sdk-java
aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/ResetDBParameterGroupResult.java
Java
apache-2.0
3,865
cask 'kk7ds-python-runtime' do version '10.1' sha256 '5cee8acb941e39f93a4df6a99ed29a14c48da0bc5beb3b31068852b1fad8b009' url "http://www.d-rats.com/download/OSX_Runtime/KK7DS_Python_Runtime_R#{version.major}.pkg" name 'KK7DS Python Runtime' homepage 'http://www.d-rats.com/download/OSX_Runtime/' pkg "KK7DS_Python_Runtime_R#{version.major}.pkg" uninstall pkgutil: 'com.danplanet.python_runtime', delete: '/opt/kk7ds' end
gerrypower/homebrew-cask
Casks/kk7ds-python-runtime.rb
Ruby
bsd-2-clause
450
# == Schema Information # # Table name: runner_projects # # id :integer not null, primary key # runner_id :integer not null # project_id :integer not null # created_at :datetime # updated_at :datetime # module Ci class RunnerProject < ActiveRecord::Base extend Ci::Model belongs_to :runner, class_name: 'Ci::Runner' belongs_to :project, class_name: 'Ci::Project' validates_uniqueness_of :runner_id, scope: :project_id end end
Exeia/gitlabhq
app/models/ci/runner_project.rb
Ruby
mit
494
// { dg-options "-std=gnu++0x" } // 2010-03-23 Paolo Carlini <paolo.carlini@oracle.com> // // Copyright (C) 2010-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <type_traits> #include <testsuite_hooks.h> #include <testsuite_tr1.h> void test01() { bool test __attribute__((unused)) = true; using std::is_literal_type; using namespace __gnu_test; VERIFY( (test_category<is_literal_type, int>(true)) ); VERIFY( (test_category<is_literal_type, unsigned char>(true)) ); VERIFY( (test_category<is_literal_type, TType>(true)) ); VERIFY( (test_category<is_literal_type, PODType>(true)) ); VERIFY( (test_category<is_literal_type, NType>(false)) ); VERIFY( (test_category<is_literal_type, SLType>(false)) ); VERIFY( (test_category<is_literal_type, LType>(true)) ); VERIFY( (test_category<is_literal_type, LType[5]>(true)) ); VERIFY( (test_category<is_literal_type, NLType>(false)) ); VERIFY( (test_category<is_literal_type, NLType[5]>(false)) ); VERIFY( (test_category<is_literal_type, LTypeDerived>(true)) ); VERIFY( (test_category<is_literal_type, LTypeDerived[5]>(true)) ); } int main() { test01(); return 0; }
pschorf/gcc-races
libstdc++-v3/testsuite/20_util/is_literal_type/value.cc
C++
gpl-2.0
1,855
// Copyright (C) 2004-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-require-fileio "" } // 27.6.1.3 unformatted input functions // NB: ostream has a particular "seeks" category. Adopt this for istreams too. // @require@ %-*.tst %-*.txt // @diff@ %-*.tst %-*.txt #include <istream> #include <sstream> #include <fstream> #include <testsuite_hooks.h> // fstreams void test04(void) { typedef std::wistream::off_type off_type; bool test __attribute__((unused)) = true; std::wistream::pos_type pos01, pos02, pos03, pos04, pos05, pos06; std::ios_base::iostate state01, state02; const char str_lit01[] = "wistream_seeks-1.txt"; const char str_lit02[] = "wistream_seeks-2.txt"; std::wifstream if01(str_lit01, std::ios_base::in | std::ios_base::out); std::wifstream if02(str_lit01, std::ios_base::in); std::wifstream if03(str_lit02, std::ios_base::out | std::ios_base::trunc); VERIFY( if01.good() ); VERIFY( if02.good() ); VERIFY( if03.good() ); std::wistream is01(if01.rdbuf()); std::wistream is02(if02.rdbuf()); std::wistream is03(if03.rdbuf()); // pos_type tellg() // in | out pos01 = is01.tellg(); pos02 = is01.tellg(); VERIFY( pos01 == pos02 ); // in pos03 = is02.tellg(); pos04 = is02.tellg(); VERIFY( pos03 == pos04 ); // out pos05 = is03.tellg(); pos06 = is03.tellg(); VERIFY( pos05 == pos06 ); // cur // NB: see library issues list 136. It's the v-3 interp that seekg // only sets the input buffer, or else istreams with buffers that // have _M_mode == ios_base::out will fail to have consistency // between seekg and tellg. state01 = is01.rdstate(); is01.seekg(10, std::ios_base::cur); state02 = is01.rdstate(); pos01 = is01.tellg(); VERIFY( pos01 == pos02 + off_type(10) ); VERIFY( state01 == state02 ); pos02 = is01.tellg(); VERIFY( pos02 == pos01 ); } int main() { test04(); return 0; }
atgreen/gcc
libstdc++-v3/testsuite/27_io/basic_istream/tellg/wchar_t/fstream.cc
C++
gpl-2.0
2,596
// { dg-do compile } // { dg-options "-std=gnu++0x" } // Copyright (C) 2012-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <list> // libstdc++/43813 void test01() { std::list<double*> l(7, 0); l.assign(7, 0); l.insert(l.begin(), 7, 0); }
atgreen/gcc
libstdc++-v3/testsuite/23_containers/list/requirements/do_the_right_thing.cc
C++
gpl-2.0
950
<?php /** * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ namespace Aws\S3\Sync; use \FilesystemIterator as FI; use Aws\Common\Model\MultipartUpload\AbstractTransfer; use Aws\S3\Model\Acp; use Guzzle\Common\Event; use Guzzle\Service\Command\CommandInterface; class UploadSyncBuilder extends AbstractSyncBuilder { /** @var string|Acp Access control policy to set on each object */ protected $acp = 'private'; /** @var int */ protected $multipartUploadSize; /** * Set the path that contains files to recursively upload to Amazon S3 * * @param string $path Path that contains files to upload * * @return self */ public function uploadFromDirectory($path) { $this->baseDir = $path; $this->sourceIterator = $this->filterIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator( $path, FI::SKIP_DOTS | FI::UNIX_PATHS | FI::FOLLOW_SYMLINKS ))); return $this; } /** * Set a glob expression that will match files to upload to Amazon S3 * * @param string $glob Glob expression * * @return self * @link http://www.php.net/manual/en/function.glob.php */ public function uploadFromGlob($glob) { $this->sourceIterator = $this->filterIterator( new \GlobIterator($glob, FI::SKIP_DOTS | FI::UNIX_PATHS | FI::FOLLOW_SYMLINKS) ); return $this; } /** * Set a canned ACL to apply to each uploaded object * * @param string $acl Canned ACL for each upload * * @return self */ public function setAcl($acl) { $this->acp = $acl; return $this; } /** * Set an Access Control Policy to apply to each uploaded object * * @param Acp $acp Access control policy * * @return self */ public function setAcp(Acp $acp) { $this->acp = $acp; return $this; } /** * Set the multipart upload size threshold. When the size of a file exceeds this value, the file will be uploaded * using a multipart upload. * * @param int $size Size threshold * * @return self */ public function setMultipartUploadSize($size) { $this->multipartUploadSize = $size; return $this; } protected function specificBuild() { $sync = new UploadSync(array( 'client' => $this->client, 'bucket' => $this->bucket, 'iterator' => $this->sourceIterator, 'source_converter' => $this->sourceConverter, 'target_converter' => $this->targetConverter, 'concurrency' => $this->concurrency, 'multipart_upload_size' => $this->multipartUploadSize, 'acl' => $this->acp )); return $sync; } protected function getTargetIterator() { return $this->createS3Iterator(); } protected function getDefaultSourceConverter() { return new KeyConverter($this->baseDir, $this->keyPrefix . $this->delimiter, $this->delimiter); } protected function getDefaultTargetConverter() { return new KeyConverter('s3://' . $this->bucket . '/', '', DIRECTORY_SEPARATOR); } protected function addDebugListener(AbstractSync $sync, $resource) { $sync->getEventDispatcher()->addListener(UploadSync::BEFORE_TRANSFER, function (Event $e) use ($resource) { $c = $e['command']; if ($c instanceof CommandInterface) { $uri = $c['Body']->getUri(); $size = $c['Body']->getSize(); fwrite($resource, "Uploading {$uri} -> {$c['Key']} ({$size} bytes)\n"); return; } // Multipart upload $body = $c->getSource(); $totalSize = $body->getSize(); $progress = 0; fwrite($resource, "Beginning multipart upload: " . $body->getUri() . ' -> '); fwrite($resource, $c->getState()->getFromId('Key') . " ({$totalSize} bytes)\n"); $c->getEventDispatcher()->addListener( AbstractTransfer::BEFORE_PART_UPLOAD, function ($e) use (&$progress, $totalSize, $resource) { $command = $e['command']; $size = $command['Body']->getContentLength(); $percentage = number_format(($progress / $totalSize) * 100, 2); fwrite($resource, "- Part {$command['PartNumber']} ({$size} bytes, {$percentage}%)\n"); $progress .= $size; } ); }); } }
jacobdfriedmann/jacobfriedmanndotcom
wp-content/plugins/wp-amazon-web-services-master/vendor/aws/Aws/S3/Sync/UploadSyncBuilder.php
PHP
gpl-2.0
5,208
/** * DO NOT EDIT THIS FILE. * See the following change record for more information, * https://www.drupal.org/node/2815083 * @preserve **/ (function (_, $, Backbone, Drupal) { Drupal.quickedit.EntityModel = Drupal.quickedit.BaseModel.extend({ defaults: { el: null, entityID: null, entityInstanceID: null, id: null, label: null, fields: null, isActive: false, inTempStore: false, isDirty: false, isCommitting: false, state: 'closed', fieldsInTempStore: [], reload: false }, initialize: function initialize() { this.set('fields', new Drupal.quickedit.FieldCollection()); this.listenTo(this, 'change:state', this.stateChange); this.listenTo(this.get('fields'), 'change:state', this.fieldStateChange); Drupal.quickedit.BaseModel.prototype.initialize.call(this); }, stateChange: function stateChange(entityModel, state, options) { var to = state; switch (to) { case 'closed': this.set({ isActive: false, inTempStore: false, isDirty: false }); break; case 'launching': break; case 'opening': entityModel.get('fields').each(function (fieldModel) { fieldModel.set('state', 'candidate', options); }); break; case 'opened': this.set('isActive', true); break; case 'committing': { var fields = this.get('fields'); fields.chain().filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['active']).length; }).each(function (fieldModel) { fieldModel.set('state', 'candidate'); }); fields.chain().filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], Drupal.quickedit.app.changedFieldStates).length; }).each(function (fieldModel) { fieldModel.set('state', 'saving'); }); break; } case 'deactivating': { var changedFields = this.get('fields').filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['changed', 'invalid']).length; }); if ((changedFields.length || this.get('fieldsInTempStore').length) && !options.saved && !options.confirmed) { this.set('state', 'opened', { confirming: true }); _.defer(function () { Drupal.quickedit.app.confirmEntityDeactivation(entityModel); }); } else { var invalidFields = this.get('fields').filter(function (fieldModel) { return _.intersection([fieldModel.get('state')], ['invalid']).length; }); entityModel.set('reload', this.get('fieldsInTempStore').length || invalidFields.length); entityModel.get('fields').each(function (fieldModel) { if (_.intersection([fieldModel.get('state')], ['candidate', 'highlighted']).length) { fieldModel.trigger('change:state', fieldModel, fieldModel.get('state'), options); } else { fieldModel.set('state', 'candidate', options); } }); } break; } case 'closing': options.reason = 'stop'; this.get('fields').each(function (fieldModel) { fieldModel.set({ inTempStore: false, state: 'inactive' }, options); }); break; } }, _updateInTempStoreAttributes: function _updateInTempStoreAttributes(entityModel, fieldModel) { var current = fieldModel.get('state'); var previous = fieldModel.previous('state'); var fieldsInTempStore = entityModel.get('fieldsInTempStore'); if (current === 'saved') { entityModel.set('inTempStore', true); fieldModel.set('inTempStore', true); fieldsInTempStore.push(fieldModel.get('fieldID')); fieldsInTempStore = _.uniq(fieldsInTempStore); entityModel.set('fieldsInTempStore', fieldsInTempStore); } else if (current === 'candidate' && previous === 'inactive') { fieldModel.set('inTempStore', _.intersection([fieldModel.get('fieldID')], fieldsInTempStore).length > 0); } }, fieldStateChange: function fieldStateChange(fieldModel, state) { var entityModel = this; var fieldState = state; switch (this.get('state')) { case 'closed': case 'launching': break; case 'opening': _.defer(function () { entityModel.set('state', 'opened', { 'accept-field-states': Drupal.quickedit.app.readyFieldStates }); }); break; case 'opened': if (fieldState === 'changed') { entityModel.set('isDirty', true); } else { this._updateInTempStoreAttributes(entityModel, fieldModel); } break; case 'committing': { if (fieldState === 'invalid') { _.defer(function () { entityModel.set('state', 'opened', { reason: 'invalid' }); }); } else { this._updateInTempStoreAttributes(entityModel, fieldModel); } var options = { 'accept-field-states': Drupal.quickedit.app.readyFieldStates }; if (entityModel.set('isCommitting', true, options)) { entityModel.save({ success: function success() { entityModel.set({ state: 'deactivating', isCommitting: false }, { saved: true }); }, error: function error() { entityModel.set('isCommitting', false); entityModel.set('state', 'opened', { reason: 'networkerror' }); var message = Drupal.t('Your changes to <q>@entity-title</q> could not be saved, either due to a website problem or a network connection problem.<br>Please try again.', { '@entity-title': entityModel.get('label') }); Drupal.quickedit.util.networkErrorModal(Drupal.t('Network problem!'), message); } }); } break; } case 'deactivating': _.defer(function () { entityModel.set('state', 'closing', { 'accept-field-states': Drupal.quickedit.app.readyFieldStates }); }); break; case 'closing': _.defer(function () { entityModel.set('state', 'closed', { 'accept-field-states': ['inactive'] }); }); break; } }, save: function save(options) { var entityModel = this; var entitySaverAjax = Drupal.ajax({ url: Drupal.url('quickedit/entity/' + entityModel.get('entityID')), error: function error() { options.error.call(entityModel); } }); entitySaverAjax.commands.quickeditEntitySaved = function (ajax, response, status) { entityModel.get('fields').each(function (fieldModel) { fieldModel.set('inTempStore', false); }); entityModel.set('inTempStore', false); entityModel.set('fieldsInTempStore', []); if (options.success) { options.success.call(entityModel); } }; entitySaverAjax.execute(); }, validate: function validate(attrs, options) { var acceptedFieldStates = options['accept-field-states'] || []; var currentState = this.get('state'); var nextState = attrs.state; if (currentState !== nextState) { if (_.indexOf(this.constructor.states, nextState) === -1) { return '"' + nextState + '" is an invalid state'; } if (!this._acceptStateChange(currentState, nextState, options)) { return 'state change not accepted'; } else if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) { return 'state change not accepted because fields are not in acceptable state'; } } var currentIsCommitting = this.get('isCommitting'); var nextIsCommitting = attrs.isCommitting; if (currentIsCommitting === false && nextIsCommitting === true) { if (!this._fieldsHaveAcceptableStates(acceptedFieldStates)) { return 'isCommitting change not accepted because fields are not in acceptable state'; } } else if (currentIsCommitting === true && nextIsCommitting === true) { return 'isCommitting is a mutex, hence only changes are allowed'; } }, _acceptStateChange: function _acceptStateChange(from, to, context) { var accept = true; if (!this.constructor.followsStateSequence(from, to)) { accept = false; if (from === 'closing' && to === 'closed') { accept = true; } else if (from === 'committing' && to === 'opened' && context.reason && (context.reason === 'invalid' || context.reason === 'networkerror')) { accept = true; } else if (from === 'deactivating' && to === 'opened' && context.confirming) { accept = true; } else if (from === 'opened' && to === 'deactivating' && context.confirmed) { accept = true; } } return accept; }, _fieldsHaveAcceptableStates: function _fieldsHaveAcceptableStates(acceptedFieldStates) { var accept = true; if (acceptedFieldStates.length > 0) { var fieldStates = this.get('fields').pluck('state') || []; if (_.difference(fieldStates, acceptedFieldStates).length) { accept = false; } } return accept; }, destroy: function destroy(options) { Drupal.quickedit.BaseModel.prototype.destroy.call(this, options); this.stopListening(); this.get('fields').reset(); }, sync: function sync() {} }, { states: ['closed', 'launching', 'opening', 'opened', 'committing', 'deactivating', 'closing'], followsStateSequence: function followsStateSequence(from, to) { return _.indexOf(this.states, from) < _.indexOf(this.states, to); } }); Drupal.quickedit.EntityCollection = Backbone.Collection.extend({ model: Drupal.quickedit.EntityModel }); })(_, jQuery, Backbone, Drupal);
isauragalafate/drupal8
web/core/modules/quickedit/js/models/EntityModel.js
JavaScript
gpl-2.0
10,662
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/file_system/entry_watcher_service_factory.h" #include "chrome/browser/extensions/api/file_system/entry_watcher_service.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "content/public/browser/browser_context.h" namespace extensions { EntryWatcherServiceFactory* EntryWatcherServiceFactory::GetInstance() { return Singleton<EntryWatcherServiceFactory>::get(); } EntryWatcherServiceFactory::EntryWatcherServiceFactory() : BrowserContextKeyedServiceFactory( "EntryWatcherService", BrowserContextDependencyManager::GetInstance()) { } EntryWatcherServiceFactory::~EntryWatcherServiceFactory() { } KeyedService* EntryWatcherServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { return new EntryWatcherService(Profile::FromBrowserContext(context)); } bool EntryWatcherServiceFactory::ServiceIsCreatedWithBrowserContext() const { // Required to restore persistent watchers as soon as the profile is loaded. return true; } } // namespace extensions
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/extensions/api/file_system/entry_watcher_service_factory.cc
C++
gpl-3.0
1,309
<?php use LibreNMS\Exceptions\InvalidIpException; use LibreNMS\Util\IP; echo '<div class="container-fluid">'; echo "<div class='row'> <div class='col-md-12'> <div class='panel panel-default panel-condensed'> <div class='panel-heading'>"; if ($config['overview_show_sysDescr']) { echo '<i class="fa fa-id-card fa-lg icon-theme" aria-hidden="true"></i> <strong>'.$device['sysDescr'].'</strong>'; } echo '</div> <table class="table table-hover table-condensed table-striped">'; $uptime = formatUptime($device['uptime']); $uptime_text = 'Uptime'; if ($device['status'] == 0) { // Rewrite $uptime to be downtime if device is down $uptime = formatUptime(time() - strtotime($device['last_polled'])); $uptime_text = 'Downtime'; } if ($device['os'] == 'ios') { formatCiscoHardware($device); } if ($device['features']) { $device['features'] = '('.$device['features'].')'; } $device['os_text'] = $config['os'][$device['os']]['text']; echo '<tr> <td>System Name</td> <td>'.$device['sysName'].' </td> </tr>'; if (!empty($device['ip'])) { echo "<tr><td>Resolved IP</td><td>{$device['ip']}</td></tr>"; } elseif ($config['force_ip_to_sysname'] === true) { try { $ip = IP::parse($device['hostname']); echo "<tr><td>IP Address</td><td>$ip</td></tr>"; } catch (InvalidIpException $e) { // don't add an ip line } } if ($device['purpose']) { echo '<tr> <td>Description</td> <td>'.display($device['purpose']).'</td> </tr>'; } if ($device['hardware']) { echo '<tr> <td>Hardware</td> <td>'.$device['hardware'].'</td> </tr>'; } echo '<tr> <td>Operating System</td> <td>'.$device['os_text'].' '.$device['version'].' '.$device['features'].' </td> </tr>'; if ($device['serial']) { echo '<tr> <td>Serial</td> <td>'.$device['serial'].'</td> </tr>'; } if ($device['sysObjectID']) { echo '<tr> <td>Object ID</td> <td>'.$device['sysObjectID'].'</td> </tr>'; } if ($device['sysContact']) { echo '<tr> <td>Contact</td>'; if (get_dev_attrib($device, 'override_sysContact_bool')) { echo ' <td>'.htmlspecialchars(get_dev_attrib($device, 'override_sysContact_string')).'</td> </tr> <tr> <td>SNMP Contact</td>'; } echo ' <td>'.htmlspecialchars($device['sysContact']).'</td> </tr>'; } if ($device['location']) { echo '<tr> <td>Location</td> <td>'.$device['location'].'</td> </tr>'; if (get_dev_attrib($device, 'override_sysLocation_bool') && !empty($device['real_location'])) { echo '<tr> <td>SNMP Location</td> <td>'.$device['real_location'].'</td> </tr>'; } } $loc = parse_location($device['location']); if (!is_array($loc)) { $loc = dbFetchRow("SELECT `lat`,`lng` FROM `locations` WHERE `location`=? LIMIT 1", array($device['location'])); } if (is_array($loc)) { echo '<tr> <td>Lat / Lng</td> <td>['.$loc['lat'].','.$loc['lng'].'] <div class="pull-right"><a href="https://maps.google.com/?q='.$loc['lat'].'+'.$loc['lng'].'" target="_blank" class="btn btn-success btn-xs" role="button"><i class="fa fa-map-marker" style="color:white" aria-hidden="true"></i> Map</button></div></a></td> </tr>'; } if ($uptime) { echo "<tr> <td>$uptime_text</td> <td>".$uptime."</td> </tr>"; } echo '</table> </div> </div> </div> </div>';
wikimedia/operations-software-librenms
html/includes/dev-overview-data.inc.php
PHP
gpl-3.0
3,565
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.codeInsight.stdlib; import com.intellij.psi.PsiElement; import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.psi.resolve.PyCanonicalPathProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; /** * @author yole */ public class PyStdlibCanonicalPathProvider implements PyCanonicalPathProvider { @Nullable @Override public QualifiedName getCanonicalPath(@NotNull QualifiedName qName, PsiElement foothold) { return restoreStdlibCanonicalPath(qName); } public static QualifiedName restoreStdlibCanonicalPath(QualifiedName qName) { if (qName.getComponentCount() > 0) { final List<String> components = qName.getComponents(); final String head = components.get(0); if (head.equals("_abcoll") || head.equals("_collections")) { components.set(0, "collections"); return QualifiedName.fromComponents(components); } else if (head.equals("posix") || head.equals("nt")) { components.set(0, "os"); return QualifiedName.fromComponents(components); } else if (head.equals("_functools")) { components.set(0, "functools"); return QualifiedName.fromComponents(components); } else if (head.equals("_struct")) { components.set(0, "struct"); return QualifiedName.fromComponents(components); } else if (head.equals("_io") || head.equals("_pyio") || head.equals("_fileio")) { components.set(0, "io"); return QualifiedName.fromComponents(components); } else if (head.equals("_datetime")) { components.set(0, "datetime"); return QualifiedName.fromComponents(components); } else if (head.equals("ntpath") || head.equals("posixpath") || head.equals("path")) { final List<String> result = new ArrayList<String>(); result.add("os"); components.set(0, "path"); result.addAll(components); return QualifiedName.fromComponents(result); } else if (head.equals("_sqlite3")) { components.set(0, "sqlite3"); return QualifiedName.fromComponents(components); } else if (head.equals("_pickle")) { components.set(0, "pickle"); return QualifiedName.fromComponents(components); } } return null; } }
akosyakov/intellij-community
python/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibCanonicalPathProvider.java
Java
apache-2.0
3,015
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.elasticfilesystem.model; import com.amazonaws.AmazonServiceException; /** * <p> * Returned if the specified <code>FileSystemId</code> does not exist in the * requester's AWS account. * </p> */ public class FileSystemNotFoundException extends AmazonServiceException { private static final long serialVersionUID = 1L; private String errorCode; /** * Constructs a new FileSystemNotFoundException with the specified error * message. * * @param message * Describes the error encountered. */ public FileSystemNotFoundException(String message) { super(message); } /** * Sets the value of the ErrorCode property for this object. * * @param errorCode * The new value for the ErrorCode property for this object. */ public void setErrorCode(String errorCode) { this.errorCode = errorCode; } /** * Returns the value of the ErrorCode property for this object. * * @return The value of the ErrorCode property for this object. */ public String getErrorCode() { return this.errorCode; } /** * Sets the value of the ErrorCode property for this object. * * @param errorCode * The new value for the ErrorCode property for this object. * @return Returns a reference to this object so that method calls can be * chained together. */ public FileSystemNotFoundException withErrorCode(String errorCode) { setErrorCode(errorCode); return this; } }
mahaliachante/aws-sdk-java
aws-java-sdk-efs/src/main/java/com/amazonaws/services/elasticfilesystem/model/FileSystemNotFoundException.java
Java
apache-2.0
2,190
/// <reference path='fourslash.ts' /> // @Filename: foo.ts //// export function /*Destination*/bar() { return "bar"; } //// import('./foo').then(({ [|ba/*1*/r|] }) => undefined); verify.goToDefinition("1", "Destination");
basarat/TypeScript
tests/cases/fourslash/goToDefinitionDynamicImport4.ts
TypeScript
apache-2.0
234
/* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.openadmin.web.filter; import org.broadleafcommerce.common.web.BroadleafTimeZoneResolverImpl; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; import java.util.TimeZone; /** * * @author Phillip Verheyden (phillipuniverse) */ @Component("blAdminTimeZoneResolver") public class BroadleafAdminTimeZoneResolver extends BroadleafTimeZoneResolverImpl { @Override public TimeZone resolveTimeZone(WebRequest request) { //TODO: eventually this should support a using a timezone from the currently logged in Admin user preferences return super.resolveTimeZone(request); } }
cloudbearings/BroadleafCommerce
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/filter/BroadleafAdminTimeZoneResolver.java
Java
apache-2.0
1,370
/* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2014 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.openadmin.server.security.service; import java.util.List; /** * <p> * Provides row-level security to the various CRUD operations in the admin * * <p> * This security service can be extended by the use of {@link RowLevelSecurityProviders}, of which this service has a list. * To add additional providers, add this to an applicationContext merged into the admin application: * * {@code * <bean id="blCustomRowSecurityProviders" class="org.springframework.beans.factory.config.ListFactoryBean" > * <property name="sourceList"> * <list> * <ref bean="customProvider" /> * </list> * </property> * </bean> * <bean class="org.broadleafcommerce.common.extensibility.context.merge.LateStageMergeBeanPostProcessor"> * <property name="collectionRef" value="blCustomRowSecurityProviders" /> * <property name="targetRef" value="blRowLevelSecurityProviders" /> * </bean> * } * * @author Phillip Verheyden (phillipuniverse) * @author Brian Polster (bpolster) */ public interface RowLevelSecurityService extends RowLevelSecurityProvider { /** * Gets all of the registered providers * @return the providers configured for this service */ public List<RowLevelSecurityProvider> getProviders(); }
cengizhanozcan/BroadleafCommerce
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/security/service/RowLevelSecurityService.java
Java
apache-2.0
1,996
var $ = require('common:widget/ui/jquery/jquery.js'); var UT = require('common:widget/ui/ut/ut.js'); var FBClient = {}; var TPL_CONF = require('home:widget/ui/facebook/fbclient-tpl.js'); /** * Fackbook module init function * @return {object} [description] */ var WIN = window, DOC = document, conf = WIN.conf.FBClient, undef; var UI_CONF = { // ui el uiMod: "#fbMod" , uiBtnLogin: ".fb-mod_login_btn" , uiBtnLogout: ".fb-mod_logout" , uiBtnRefresh: ".fb-mod_refresh" , uiSide: ".fb-mod_side" , uiBtnClose: ".fb-mod_close" , uiWrap: ".fb-mod_wrap" , uiList: ".fb-mod_list" , uiUsrinfo: ".fb-mod_usrinfo" , uiAvatar: ".fb-mod_avatar" , uiTextareaSubmit: ".fb-mod_submit" , uiBtnSubmit: ".fb-mod_submit_btn" , uiBody: ".fb-mod_body" , uiTip: ".fb-mod_tip" , uiSideHome: ".fb-mod_side_home" , uiSideFriend: ".fb-mod_side_friend em" , uiSideMessages: ".fb-mod_side_messages em" , uiSideNotifications: ".fb-mod_side_notifications em" , uiBodyLoader: ".fb-mod_body_loader" }; FBClient.init = function() { // DOC.body.innerHTML += '<div id="fb-root"></div>'; var that = this, $this = $(UI_CONF.uiMod); /* ui controller */ that.ui = { uiMod: $this , side: $this.find(UI_CONF.uiSide) , btnLogin: $this.find(UI_CONF.uiBtnLogin) , btnLogout: $this.find(UI_CONF.uiBtnLogout) , btnClose: $this.find(UI_CONF.uiBtnClose) , btnRefresh: $this.find(UI_CONF.uiBtnRefresh) , wrap: $this.find(UI_CONF.uiWrap) , list: $this.find(UI_CONF.uiList) , usrinfo: $this.find(UI_CONF.uiUsrinfo) , avatar: $this.find(UI_CONF.uiAvatar) , textareaSubmit: $this.find(UI_CONF.uiTextareaSubmit) , btnSubmit: $this.find(UI_CONF.uiBtnSubmit) , body: $this.find(UI_CONF.uiBody) , tip: $this.find(UI_CONF.uiTip) , sideHome: $this.find(UI_CONF.uiSideHome) , sideFriend: $this.find(UI_CONF.uiSideFriend) , sideNotifications: $this.find(UI_CONF.uiSideNotifications) , sideMessages: $this.find(UI_CONF.uiSideMessages) , bodyLoader: $this.find(UI_CONF.uiBodyLoader) , panelHome: $this.find(".fb-mod_c") , panelFriend: $('<div class="fb-mod_c fb-mod_c_friend" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , panelNotifications: $('<div class="fb-mod_c fb-mod_c_notifications" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , panelMessages: $('<div class="fb-mod_c fb-mod_c_messages" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , bubble: $('<div class="fb-mod_bubble">' + (conf.tplBubble || "NEW") + '</div>') , placeholder: function(first, last) { return $(TPL_CONF.tplPlaceholder.replaceTpl({first: first, last: last })) } }; // live loader that.ui.liveLoader = that.ui.bodyLoader.clone(!0) .css({"width": "370px"}) .insertBefore(that.ui.list).hide(); $("body").append('<div id="fb-root" class=" fb_reset"></div>'); that.ui.wrap.append(that.ui.panelFriend).append(that.ui.panelNotifications).append(that.ui.panelMessages); // window.ActiveXObject && !window.XMLHttpRequest && $("body").append(that.ui.fakeBox = $(that.ui.textareaSubmit[0].cloneNode(false)).css({ "position": "absolute" , "top" : "0" , "left": "0" , "right": "-10000px" , "visibility": "hidden" , "padding-top": "0" , "padding-bottom": "0" , "height": "18" //for fixed , "width": that.ui.textareaSubmit.width() })); that.supportAnimate = function(style, name) { return 't' + name in style || 'webkitT' + name in style || 'MozT' + name in style || 'OT' + name in style; }((new Image).style, "ransition"); /* status controller 0 ==> none 1 ==> doing 2 ==> done */ that.status = { login: 0 , fold: 0 , sdkLoaded: 0 , scrollLoaded: 0 , insertLoaded: 0 , fixed: 0 , eventBinded: 0 , bubble: 0 }; // bubble !$.cookie("fb_bubble") && (that.status.bubble = 1, that.ui.uiMod.append(that.ui.bubble)); /* post status cache */ that.cache = { prePost: null , nextPost: null , refreshPost: null , noOldPost: 0 , myPost: 0 , stayTip: "" , userID: null , userName: "" , panel: that.ui.panelHome , curSideType: "" , panelRendered: 0 }; that.ui.btnClose.mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"}); that.foldHandle.call(that, e); }); $(".fb-mod_side_logo").mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"}); that.foldHandle.call(that, e); }); $(".fb-mod_side_home").mousedown(function(e) { UT && that.status.fold === 0 && UT.send({"type": "click", "position": "fb", "sort": "pull","modId":"fb-box"}); UT && UT.send({"type": "click", "position": "fb", "sort": "icon_home","modId":"fb-box"}); that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_home_cur", that.ui.panelHome); }); $(".fb-mod_side_friend").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_friend", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_friend_cur", that.ui.panelFriend); }); $(".fb-mod_side_messages").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_messages", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_messages_cur", that.ui.panelMessages); }); $(".fb-mod_side_notifications").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_notifications", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_notifications_cur", that.ui.panelNotifications); }); that.ui.btnRefresh.mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": "refresh","modId":"fb-box"}); }); $(".fb-mod_side_friend").click(function(e) { e.preventDefault(); }); $(".fb-mod_side_messages").click(function(e) { e.preventDefault(); }); $(".fb-mod_side_notifications").click(function(e) { e.preventDefault(); }); // 7. FB-APP的打开、收缩机制;——点击F、箭头、new三个地方打开,点击F、箭头两个地方关闭;做上新功能上线的提示图标,放cookies内; // // kill the feature // that.ui.side.mouseover(function(e) { // that.status.fold === 0 && that.foldHandle.call(that, e); // }); that.ui.textareaSubmit.attr("placeholder", conf.tplSuggestText); // sdk loading that.status.sdkLoaded = 1; /*$.ajax({ url: that.conf.modPath, dataType: "script", cache: true, success: function() { }, error: function() { } });*/ require.async('home:widget/ui/facebook/fbclient-core.js'); }; if(window.ActiveXObject && !window.XMLHttpRequest) { var body = DOC.body; if(body) { body.style.backgroundAttachment = 'fixed'; if(body.currentStyle.backgroundImage == "none") { body.style.backgroundImage = (DOC.domain.indexOf("https:") == 0) ? 'url(https:///)' : 'url(about:blank)'; } } } FBClient.clickHandle = function($el, type, panel) { var that = this, fold = that.status.fold, sideHome = that.ui.sideHome, cache = that.cache; // fold && sideHome.removeClass(type); cache.curSide && cache.curSide.removeClass(cache.curSideType); $el && $el.addClass(type); cache.curSide = $el; cache.curSideType = type; cache.panel && cache.panel.hide(); panel && panel.show(); cache.panel = panel; }; FBClient.foldHandle = function(e) { var that = this, fold = that.status.fold, sdkLoaded = that.status.sdkLoaded; // playing animation if(fold === 1) return; that.status.fold = 1; that.clickHandle(fold ? null : that.ui.sideHome, fold ? "" : "fb-mod_side_home_cur", that.ui.panelHome); that.status.bubble && ($.cookie("fb_bubble", 1), that.status.bubble = 0, that.ui.bubble.hide()); fold ? that.ui.uiMod.removeClass("fb-mod--fixed").addClass("fb-mod--fold") : that.ui.uiMod.removeClass("fb-mod--fold"); setTimeout(function() { // fold ? sideHome.removeClass("fb-mod_side_home_cur") : that.ui.sideHome.addClass("fb-mod_side_home_cur"), that.cache.curSideType = "fb-mod_side_home_cur"; (that.status.fold = fold ? 0 : 2) && that.status.fixed && that.ui.uiMod.addClass("fb-mod--fixed"); if (!that.status.eventBinded) { if (sdkLoaded === 2) { that.bindEvent.call(that); that.status.eventBinded = 2; } else { var t = setInterval(function () { if (that.status.sdkLoaded === 2) { that.bindEvent.call(that); that.status.eventBinded = 2; clearInterval(t); } }, 1000); } } if(fold || sdkLoaded) return; !function(el) { if($.browser.mozilla){ el.addEventListener('DOMMouseScroll',function(e){ el.scrollTop += e.detail > 0 ? 30 : -30; e.preventDefault(); }, !1); } else el.onmousewheel = function(e){ e = e || WIN.event; el.scrollTop += e.wheelDelta > 0 ? -30 : 30; e.returnValue = false; }; }(that.ui.body[0]) }, that.supportAnimate ? 300 : 0); }; module.exports = FBClient;
femxd/fxd
test/diff_fis3_smarty/product_code/hao123_fis3_smarty/home/widget/ui/facebook/fbclient.js
JavaScript
bsd-2-clause
11,122
""" Contains CheesePreprocessor """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from ...preprocessors.base import Preprocessor #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class CheesePreprocessor(Preprocessor): """ Adds a cheese tag to the resources object """ def __init__(self, **kw): """ Public constructor """ super(CheesePreprocessor, self).__init__(**kw) def preprocess(self, nb, resources): """ Sphinx preprocessing to apply on each notebook. Parameters ---------- nb : NotebookNode Notebook being converted resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. """ resources['cheese'] = 'real' return nb, resources
unnikrishnankgs/va
venv/lib/python3.5/site-packages/nbconvert/exporters/tests/cheese.py
Python
bsd-2-clause
1,485
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /* JOrbis * Copyright (C) 2000 ymnk, JCraft,Inc. * * Written by: 2000 ymnk<ymnk@jcraft.com> * * Many thanks to * Monty <monty@xiph.org> and * The XIPHOPHORUS Company http://www.xiph.org/ . * JOrbis has been based on their awesome works, Vorbis codec. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.jcraft.jorbis; // psychoacoustic setup class PsyInfo{ int athp; int decayp; int smoothp; int noisefitp; int noisefit_subblock; float noisefit_threshdB; float ath_att; int tonemaskp; float[] toneatt_125Hz=new float[5]; float[] toneatt_250Hz=new float[5]; float[] toneatt_500Hz=new float[5]; float[] toneatt_1000Hz=new float[5]; float[] toneatt_2000Hz=new float[5]; float[] toneatt_4000Hz=new float[5]; float[] toneatt_8000Hz=new float[5]; int peakattp; float[] peakatt_125Hz=new float[5]; float[] peakatt_250Hz=new float[5]; float[] peakatt_500Hz=new float[5]; float[] peakatt_1000Hz=new float[5]; float[] peakatt_2000Hz=new float[5]; float[] peakatt_4000Hz=new float[5]; float[] peakatt_8000Hz=new float[5]; int noisemaskp; float[] noiseatt_125Hz=new float[5]; float[] noiseatt_250Hz=new float[5]; float[] noiseatt_500Hz=new float[5]; float[] noiseatt_1000Hz=new float[5]; float[] noiseatt_2000Hz=new float[5]; float[] noiseatt_4000Hz=new float[5]; float[] noiseatt_8000Hz=new float[5]; float max_curve_dB; float attack_coeff; float decay_coeff; void free(){ } }
XtremeMP-Project/xtrememp-fx
xtrememp-audio-spi-vorbis/src/com/jcraft/jorbis/PsyInfo.java
Java
bsd-3-clause
2,222
/** * 404 (Not Found) Handler * * Usage: * return res.notFound(); * return res.notFound(err); * return res.notFound(err, 'some/specific/notfound/view'); * * e.g.: * ``` * return res.notFound(); * ``` * * NOTE: * If a request doesn't match any explicit routes (i.e. `config/routes.js`) * or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()` * automatically. */ module.exports = function notFound (data, options) { // Get access to `req`, `res`, & `sails` var req = this.req; var res = this.res; var sails = req._sails; // Set status code res.status(404); // Log error to console if (data !== undefined) { sails.log.verbose('Sending 404 ("Not Found") response: \n',data); } else sails.log.verbose('Sending 404 ("Not Found") response'); // Only include errors in response if application environment // is not set to 'production'. In production, we shouldn't // send back any identifying information about errors. if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { data = undefined; } // If the user-agent wants JSON, always respond with JSON if (req.wantsJSON) { return res.jsonx(data); } // If second argument is a string, we take that to mean it refers to a view. // If it was omitted, use an empty object (`{}`) options = (typeof options === 'string') ? { view: options } : options || {}; // If a view was provided in options, serve it. // Otherwise try to guess an appropriate view, or if that doesn't // work, just send JSON. if (options.view) { return res.view(options.view, { data: data }); } // If no second argument provided, try to serve the default view, // but fall back to sending JSON(P) if any errors occur. else return res.view('404', { data: data }, function (err, html) { // If a view error occured, fall back to JSON(P). if (err) { // // Additionally: // • If the view was missing, ignore the error but provide a verbose log. if (err.code === 'E_VIEW_FAILED') { sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err); } // Otherwise, if this was a more serious error, log to the console with the details. else { sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); } return res.jsonx(data); } return res.send(html); }); };
Karnith/sails-generate-backend-gulp
templates/api/responses/notFound.js
JavaScript
mit
2,543
// 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. package org.chromium.base; import android.os.Looper; import android.os.MessageQueue; import android.os.SystemClock; import android.util.Log; import android.util.Printer; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; /** * Java mirror of Chrome trace event API. See base/trace_event/trace_event.h. Unlike the native * version, Java does not have stack objects, so a TRACE_EVENT() which does both TRACE_EVENT_BEGIN() * and TRACE_EVENT_END() in ctor/dtor is not possible. * It is OK to use tracing before the native library has loaded, but such traces will * be ignored. (Perhaps we could devise to buffer them up in future?). */ @JNINamespace("base::android") public class TraceEvent { private static volatile boolean sEnabled = false; private static volatile boolean sATraceEnabled = false; // True when taking an Android systrace. private static class BasicLooperMonitor implements Printer { @Override public void println(final String line) { if (line.startsWith(">")) { beginHandling(line); } else { assert line.startsWith("<"); endHandling(line); } } void beginHandling(final String line) { if (sEnabled) nativeBeginToplevel(); } void endHandling(final String line) { if (sEnabled) nativeEndToplevel(); } } /** * A class that records, traces and logs statistics about the UI thead's Looper. * The output of this class can be used in a number of interesting ways: * <p> * <ol><li> * When using chrometrace, there will be a near-continuous line of * measurements showing both event dispatches as well as idles; * </li><li> * Logging messages are output for events that run too long on the * event dispatcher, making it easy to identify problematic areas; * </li><li> * Statistics are output whenever there is an idle after a non-trivial * amount of activity, allowing information to be gathered about task * density and execution cadence on the Looper; * </li></ol> * <p> * The class attaches itself as an idle handler to the main Looper, and * monitors the execution of events and idle notifications. Task counters * accumulate between idle notifications and get reset when a new idle * notification is received. */ private static final class IdleTracingLooperMonitor extends BasicLooperMonitor implements MessageQueue.IdleHandler { // Tags for dumping to logcat or TraceEvent private static final String TAG = "TraceEvent.LooperMonitor"; private static final String IDLE_EVENT_NAME = "Looper.queueIdle"; // Calculation constants private static final long FRAME_DURATION_MILLIS = 1000L / 60L; // 60 FPS // A reasonable threshold for defining a Looper event as "long running" private static final long MIN_INTERESTING_DURATION_MILLIS = FRAME_DURATION_MILLIS; // A reasonable threshold for a "burst" of tasks on the Looper private static final long MIN_INTERESTING_BURST_DURATION_MILLIS = MIN_INTERESTING_DURATION_MILLIS * 3; // Stats tracking private long mLastIdleStartedAt = 0L; private long mLastWorkStartedAt = 0L; private int mNumTasksSeen = 0; private int mNumIdlesSeen = 0; private int mNumTasksSinceLastIdle = 0; // State private boolean mIdleMonitorAttached = false; // Called from within the begin/end methods only. // This method can only execute on the looper thread, because that is // the only thread that is permitted to call Looper.myqueue(). private final void syncIdleMonitoring() { if (sEnabled && !mIdleMonitorAttached) { // approximate start time for computational purposes mLastIdleStartedAt = SystemClock.elapsedRealtime(); Looper.myQueue().addIdleHandler(this); mIdleMonitorAttached = true; Log.v(TAG, "attached idle handler"); } else if (mIdleMonitorAttached && !sEnabled) { Looper.myQueue().removeIdleHandler(this); mIdleMonitorAttached = false; Log.v(TAG, "detached idle handler"); } } @Override final void beginHandling(final String line) { // Close-out any prior 'idle' period before starting new task. if (mNumTasksSinceLastIdle == 0) { TraceEvent.end(IDLE_EVENT_NAME); } mLastWorkStartedAt = SystemClock.elapsedRealtime(); syncIdleMonitoring(); super.beginHandling(line); } @Override final void endHandling(final String line) { final long elapsed = SystemClock.elapsedRealtime() - mLastWorkStartedAt; if (elapsed > MIN_INTERESTING_DURATION_MILLIS) { traceAndLog(Log.WARN, "observed a task that took " + elapsed + "ms: " + line); } super.endHandling(line); syncIdleMonitoring(); mNumTasksSeen++; mNumTasksSinceLastIdle++; } private static void traceAndLog(int level, String message) { TraceEvent.instant("TraceEvent.LooperMonitor:IdleStats", message); Log.println(level, TAG, message); } @Override public final boolean queueIdle() { final long now = SystemClock.elapsedRealtime(); if (mLastIdleStartedAt == 0) mLastIdleStartedAt = now; final long elapsed = now - mLastIdleStartedAt; mNumIdlesSeen++; TraceEvent.begin(IDLE_EVENT_NAME, mNumTasksSinceLastIdle + " tasks since last idle."); if (elapsed > MIN_INTERESTING_BURST_DURATION_MILLIS) { // Dump stats String statsString = mNumTasksSeen + " tasks and " + mNumIdlesSeen + " idles processed so far, " + mNumTasksSinceLastIdle + " tasks bursted and " + elapsed + "ms elapsed since last idle"; traceAndLog(Log.DEBUG, statsString); } mLastIdleStartedAt = now; mNumTasksSinceLastIdle = 0; return true; // stay installed } } // Holder for monitor avoids unnecessary construction on non-debug runs private static final class LooperMonitorHolder { private static final BasicLooperMonitor sInstance = CommandLine.getInstance().hasSwitch(BaseSwitches.ENABLE_IDLE_TRACING) ? new IdleTracingLooperMonitor() : new BasicLooperMonitor(); } /** * Register an enabled observer, such that java traces are always enabled with native. */ public static void registerNativeEnabledObserver() { nativeRegisterEnabledObserver(); } /** * Notification from native that tracing is enabled/disabled. */ @CalledByNative public static void setEnabled(boolean enabled) { sEnabled = enabled; // Android M+ systrace logs this on its own. Only log it if not writing to Android systrace. if (sATraceEnabled) return; ThreadUtils.getUiThreadLooper().setMessageLogging( enabled ? LooperMonitorHolder.sInstance : null); } /** * Enables or disabled Android systrace path of Chrome tracing. If enabled, all Chrome * traces will be also output to Android systrace. Because of the overhead of Android * systrace, this is for WebView only. */ public static void setATraceEnabled(boolean enabled) { if (sATraceEnabled == enabled) return; sATraceEnabled = enabled; if (enabled) { // Calls TraceEvent.setEnabled(true) via // TraceLog::EnabledStateObserver::OnTraceLogEnabled nativeStartATrace(); } else { // Calls TraceEvent.setEnabled(false) via // TraceLog::EnabledStateObserver::OnTraceLogDisabled nativeStopATrace(); } } /** * @return True if tracing is enabled, false otherwise. * It is safe to call trace methods without checking if TraceEvent * is enabled. */ public static boolean enabled() { return sEnabled; } /** * Triggers the 'instant' native trace event with no arguments. * @param name The name of the event. */ public static void instant(String name) { if (sEnabled) nativeInstant(name, null); } /** * Triggers the 'instant' native trace event. * @param name The name of the event. * @param arg The arguments of the event. */ public static void instant(String name, String arg) { if (sEnabled) nativeInstant(name, arg); } /** * Triggers the 'start' native trace event with no arguments. * @param name The name of the event. * @param id The id of the asynchronous event. */ public static void startAsync(String name, long id) { if (sEnabled) nativeStartAsync(name, id); } /** * Triggers the 'finish' native trace event with no arguments. * @param name The name of the event. * @param id The id of the asynchronous event. */ public static void finishAsync(String name, long id) { if (sEnabled) nativeFinishAsync(name, id); } /** * Triggers the 'begin' native trace event with no arguments. * @param name The name of the event. */ public static void begin(String name) { if (sEnabled) nativeBegin(name, null); } /** * Triggers the 'begin' native trace event. * @param name The name of the event. * @param arg The arguments of the event. */ public static void begin(String name, String arg) { if (sEnabled) nativeBegin(name, arg); } /** * Triggers the 'end' native trace event with no arguments. * @param name The name of the event. */ public static void end(String name) { if (sEnabled) nativeEnd(name, null); } /** * Triggers the 'end' native trace event. * @param name The name of the event. * @param arg The arguments of the event. */ public static void end(String name, String arg) { if (sEnabled) nativeEnd(name, arg); } private static native void nativeRegisterEnabledObserver(); private static native void nativeStartATrace(); private static native void nativeStopATrace(); private static native void nativeInstant(String name, String arg); private static native void nativeBegin(String name, String arg); private static native void nativeEnd(String name, String arg); private static native void nativeBeginToplevel(); private static native void nativeEndToplevel(); private static native void nativeStartAsync(String name, long id); private static native void nativeFinishAsync(String name, long id); }
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/base/android/java/src/org/chromium/base/TraceEvent.java
Java
mit
11,372
/* * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package build.tools.jdwpgen; import java.util.*; import java.io.*; class AltNode extends AbstractGroupNode implements TypeNode { SelectNode select = null; void constrain(Context ctx) { super.constrain(ctx); if (!(nameNode instanceof NameValueNode)) { error("Alt name must have value: " + nameNode); } if (parent instanceof SelectNode) { select = (SelectNode)parent; } else { error("Alt must be in Select"); } } void document(PrintWriter writer) { docRowStart(writer); writer.println("<td colspan=" + (maxStructIndent - structIndent + 1) + ">"); writer.println("Case " + nameNode.name + " - if <i>" + ((SelectNode)parent).typeNode.name + "</i> is " + nameNode.value() + ":"); writer.println("<td>" + comment() + "&nbsp;"); ++structIndent; super.document(writer); --structIndent; } String javaClassImplements() { return " extends " + select.commonBaseClass(); } void genJavaClassSpecifics(PrintWriter writer, int depth) { indent(writer, depth); writer.print("static final " + select.typeNode.javaType()); writer.println(" ALT_ID = " + nameNode.value() + ";"); if (context.isWritingCommand()) { genJavaCreateMethod(writer, depth); } else { indent(writer, depth); writer.println(select.typeNode.javaParam() + "() {"); indent(writer, depth+1); writer.println("return ALT_ID;"); indent(writer, depth); writer.println("}"); } super.genJavaClassSpecifics(writer, depth); } void genJavaWriteMethod(PrintWriter writer, int depth) { genJavaWriteMethod(writer, depth, ""); } void genJavaReadsSelectCase(PrintWriter writer, int depth, String common) { indent(writer, depth); writer.println("case " + nameNode.value() + ":"); indent(writer, depth+1); writer.println(common + " = new " + name + "(vm, ps);"); indent(writer, depth+1); writer.println("break;"); } void genJavaCreateMethod(PrintWriter writer, int depth) { indent(writer, depth); writer.print("static " + select.name() + " create("); writer.print(javaParams()); writer.println(") {"); indent(writer, depth+1); writer.print("return new " + select.name() + "("); writer.print("ALT_ID, new " + javaClassName() + "("); for (Iterator it = components.iterator(); it.hasNext();) { TypeNode tn = (TypeNode)it.next(); writer.print(tn.name()); if (it.hasNext()) { writer.print(", "); } } writer.println("));"); indent(writer, depth); writer.println("}"); } }
rokn/Count_Words_2015
testing/openjdk/jdk/make/tools/src/build/tools/jdwpgen/AltNode.java
Java
mit
4,156
/* * Copyright (C) 2005-2020 Team Kodi * This file is part of Kodi - https://kodi.tv * * SPDX-License-Identifier: GPL-2.0-or-later * See LICENSES/README.md for more information. */ #include "DRMEncoder.h" #include <cstring> #include <errno.h> #include <stdexcept> #include <string> using namespace KODI::WINDOWING::GBM; CDRMEncoder::CDRMEncoder(int fd, uint32_t encoder) : CDRMObject(fd), m_encoder(drmModeGetEncoder(m_fd, encoder)) { if (!m_encoder) throw std::runtime_error("drmModeGetEncoder failed: " + std::string{strerror(errno)}); }
asavah/xbmc
xbmc/windowing/gbm/drm/DRMEncoder.cpp
C++
gpl-2.0
562
# # Copyright (C) 2014 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb') require 'db/migrate/20141217222534_cleanup_duplicate_external_feeds' describe 'CleanupDuplicateExternalFeeds' do before do @migration = CleanupDuplicateExternalFeeds.new @migration.down end it "should find duplicates" do c1 = course_model feeds = 3.times.map { external_feed_model({}, false) } feeds.each{ |f| f.save(validate: false) } feeds[2].update_attribute(:url, "http://another-non-default-place.com") c2 = course_model feeds << external_feed_model expect(ExternalFeed.where(id: feeds).count).to eq 4 @migration.up expect(ExternalFeed.where(id: [feeds[0], feeds[2], feeds[3]]).count).to eq 3 expect(ExternalFeed.where(id: feeds[1]).count).to eq 0 end it "should cleanup associated entries and announcements of duplicates" do course_with_teacher @context = @course feeds = 2.times.map { external_feed_model({}, false) } feeds.each{ |f| f.save(validate: false) } entries = feeds.map do |feed| feed.external_feed_entries.create!( :user => @teacher, :title => 'blah', :message => 'blah', :workflow_state => :active ) end announcements = feeds.map do |feed| a = announcement_model a.update_attribute(:external_feed_id, feed.id) a end @migration.up expect(ExternalFeed.where(id: feeds[0]).count).to eq 1 expect(ExternalFeedEntry.where(id: entries[0]).count).to eq 1 expect(announcements[0].reload.external_feed_id).to eq feeds[0].id expect(ExternalFeed.where(id: feeds[1]).count).to eq 0 expect(ExternalFeedEntry.where(id: entries[1]).count).to eq 0 expect(announcements[1].reload.external_feed_id).to eq feeds[0].id end it "sets a default for any NULL verbosity field" do course = course_model feed = external_feed_model ExternalFeed.where(id: feed).update_all(verbosity: nil) @migration.up expect(feed.reload.verbosity).to eq 'full' end end
Rvor/canvas-lms
spec/migrations/cleanup_duplicate_external_feeds_spec.rb
Ruby
agpl-3.0
2,707
/* * Copyright (c) 2015, 张涛. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kymjs.blog.ui.widget; import java.io.File; import java.io.IOException; import org.kymjs.blog.AppConfig; import org.kymjs.blog.R; import org.kymjs.kjframe.ui.KJActivityStack; import org.kymjs.kjframe.ui.ViewInject; import org.kymjs.kjframe.utils.FileUtils; import org.kymjs.kjframe.utils.StringUtils; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.widget.TextView; /** * * {@link #RecordButton}需要的工具类 * * @author kymjs (http://www.kymjs.com/) * */ public class RecordButtonUtil { private final static String TAG = "AudioUtil"; public static final String AUDOI_DIR = FileUtils.getSDCardPath() + File.separator + AppConfig.audioPath; // 录音音频保存根路径 private String mAudioPath; // 要播放的声音的路径 private boolean mIsRecording;// 是否正在录音 private boolean mIsPlaying;// 是否正在播放 private MediaRecorder mRecorder; private MediaPlayer mPlayer; private OnPlayListener listener; public boolean isPlaying() { return mIsPlaying; } /** * 设置要播放的声音的路径 * * @param path */ public void setAudioPath(String path) { this.mAudioPath = path; } /** * 播放声音结束时调用 * * @param l */ public void setOnPlayListener(OnPlayListener l) { this.listener = l; } // 初始化 录音器 private void initRecorder() { mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); mRecorder.setOutputFile(mAudioPath); mIsRecording = true; } /** * 开始录音,并保存到文件中 */ public void recordAudio() { initRecorder(); try { mRecorder.prepare(); mRecorder.start(); } catch (IOException e) { ViewInject.toast("小屁孩不听你说话了,请返回重试"); } } /** * 获取音量值,只是针对录音音量 * * @return */ public int getVolumn() { int volumn = 0; // 录音 if (mRecorder != null && mIsRecording) { volumn = mRecorder.getMaxAmplitude(); if (volumn != 0) volumn = (int) (10 * Math.log(volumn) / Math.log(10)) / 5; } return volumn; } /** * 停止录音 */ public void stopRecord() { if (mRecorder != null) { mRecorder.stop(); mRecorder.release(); mRecorder = null; mIsRecording = false; } } public void stopPlay() { if (mPlayer != null) { mPlayer.stop(); mPlayer.release(); mPlayer = null; mIsPlaying = false; if (listener != null) { listener.stopPlay(); } } } public void startPlay(String audioPath, TextView timeView) { if (!mIsPlaying) { if (!StringUtils.isEmpty(audioPath)) { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(audioPath); mPlayer.prepare(); if (timeView != null) { int len = (mPlayer.getDuration() + 500) / 1000; timeView.setText(len + "s"); } mPlayer.start(); if (listener != null) { listener.starPlay(); } mIsPlaying = true; mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { stopPlay(); } }); } catch (Exception e) { e.printStackTrace(); } } else { ViewInject.toast(KJActivityStack.create().topActivity() .getString(R.string.record_sound_notfound)); } } else { stopPlay(); } // end playing } /** * 开始播放 */ public void startPlay() { startPlay(mAudioPath, null); } public interface OnPlayListener { /** * 播放声音结束时调用 */ void stopPlay(); /** * 播放声音开始时调用 */ void starPlay(); } }
supercwn/KJFrameForAndroid
KJFrame/app/src/main/java/org/kymjs/blog/ui/widget/RecordButtonUtil.java
Java
apache-2.0
5,318
/** * Copyright 2015 IBM Corp. * * 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. **/ var express = require("express"); var util = require("util"); var path = require("path"); var fs = require("fs"); var clone = require("clone"); var defaultContext = { page: { title: "Node-RED", favicon: "favicon.ico" }, header: { title: "Node-RED", image: "red/images/node-red.png" }, asset: { red: (process.env.NODE_ENV == "development")? "red/red.js":"red/red.min.js" } }; var themeContext = clone(defaultContext); var themeSettings = null; function serveFile(app,baseUrl,file) { try { var stats = fs.statSync(file); var url = baseUrl+path.basename(file); //console.log(url,"->",file); app.get(url,function(req, res) { res.sendfile(file); }); return "theme"+url; } catch(err) { //TODO: log filenotfound return null; } } module.exports = { init: function(settings) { var i; var url; themeContext = clone(defaultContext); themeSettings = null; if (settings.editorTheme) { var theme = settings.editorTheme; themeSettings = {}; var themeApp = express(); if (theme.page) { if (theme.page.css) { var styles = theme.page.css; if (!util.isArray(styles)) { styles = [styles]; } themeContext.page.css = []; for (i=0;i<styles.length;i++) { url = serveFile(themeApp,"/css/",styles[i]); if (url) { themeContext.page.css.push(url); } } } if (theme.page.favicon) { url = serveFile(themeApp,"/favicon/",theme.page.favicon) if (url) { themeContext.page.favicon = url; } } themeContext.page.title = theme.page.title || themeContext.page.title; } if (theme.header) { themeContext.header.title = theme.header.title || themeContext.header.title; if (theme.header.hasOwnProperty("url")) { themeContext.header.url = theme.header.url; } if (theme.header.hasOwnProperty("image")) { if (theme.header.image) { url = serveFile(themeApp,"/header/",theme.header.image); if (url) { themeContext.header.image = url; } } else { themeContext.header.image = null; } } } if (theme.deployButton) { if (theme.deployButton.type == "simple") { themeSettings.deployButton = { type: "simple" } if (theme.deployButton.label) { themeSettings.deployButton.label = theme.deployButton.label; } if (theme.deployButton.icon) { url = serveFile(themeApp,"/deploy/",theme.deployButton.icon); if (url) { themeSettings.deployButton.icon = url; } } } } if (theme.hasOwnProperty("userMenu")) { themeSettings.userMenu = theme.userMenu; } if (theme.login) { if (theme.login.image) { url = serveFile(themeApp,"/login/",theme.login.image); if (url) { themeContext.login = { image: url } } } } if (theme.hasOwnProperty("menu")) { themeSettings.menu = theme.menu; } return themeApp; } }, context: function() { return themeContext; }, settings: function() { return themeSettings; } }
mikestebbins/node-red
red/api/theme.js
JavaScript
apache-2.0
5,062
<?php /* * This file is part of SwiftMailer. * (c) 2004-2009 Chris Corbyn * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Autoloader and dependency injection initialization for Swift Mailer. */ //Load Swift utility class require_once dirname(__FILE__) . '/Swift.php'; //Start the autoloader Swift::registerAutoload(); //Load the init script to set up dependency injection require_once dirname(__FILE__) . '/swift_init.php';
monokal/docker-orangehrm
www/symfony/lib/vendor/symfony/lib/vendor/swiftmailer/swift_required_pear.php
PHP
gpl-2.0
524
using System; namespace fizz_buzz { class Program { static void Main(string[] args) { for (int i = 1; i < 101; i++) { if (i % 3 < 1) Console.Write("fizz"); if (i % 5 < 1) Console.Write("buzz"); if (i % 3 > 0 && i % 5 > 0) Console.Write("{0}", i); Console.WriteLine(""); } } } }
aloisdg/code-problems
solutions/cs/shortest-fizz-buzz.cs
C#
mit
477
require "rack/chunked" module ActionController #:nodoc: # Allows views to be streamed back to the client as they are rendered. # # By default, Rails renders views by first rendering the template # and then the layout. The response is sent to the client after the whole # template is rendered, all queries are made, and the layout is processed. # # Streaming inverts the rendering flow by rendering the layout first and # streaming each part of the layout as they are processed. This allows the # header of the HTML (which is usually in the layout) to be streamed back # to client very quickly, allowing JavaScripts and stylesheets to be loaded # earlier than usual. # # This approach was introduced in Rails 3.1 and is still improving. Several # Rack middlewares may not work and you need to be careful when streaming. # Those points are going to be addressed soon. # # In order to use streaming, you will need to use a Ruby version that # supports fibers (fibers are supported since version 1.9.2 of the main # Ruby implementation). # # Streaming can be added to a given template easily, all you need to do is # to pass the :stream option. # # class PostsController # def index # @posts = Post.all # render stream: true # end # end # # == When to use streaming # # Streaming may be considered to be overkill for lightweight actions like # +new+ or +edit+. The real benefit of streaming is on expensive actions # that, for example, do a lot of queries on the database. # # In such actions, you want to delay queries execution as much as you can. # For example, imagine the following +dashboard+ action: # # def dashboard # @posts = Post.all # @pages = Page.all # @articles = Article.all # end # # Most of the queries here are happening in the controller. In order to benefit # from streaming you would want to rewrite it as: # # def dashboard # # Allow lazy execution of the queries # @posts = Post.all # @pages = Page.all # @articles = Article.all # render stream: true # end # # Notice that :stream only works with templates. Rendering :json # or :xml with :stream won't work. # # == Communication between layout and template # # When streaming, rendering happens top-down instead of inside-out. # Rails starts with the layout, and the template is rendered later, # when its +yield+ is reached. # # This means that, if your application currently relies on instance # variables set in the template to be used in the layout, they won't # work once you move to streaming. The proper way to communicate # between layout and template, regardless of whether you use streaming # or not, is by using +content_for+, +provide+ and +yield+. # # Take a simple example where the layout expects the template to tell # which title to use: # # <html> # <head><title><%= yield :title %></title></head> # <body><%= yield %></body> # </html> # # You would use +content_for+ in your template to specify the title: # # <%= content_for :title, "Main" %> # Hello # # And the final result would be: # # <html> # <head><title>Main</title></head> # <body>Hello</body> # </html> # # However, if +content_for+ is called several times, the final result # would have all calls concatenated. For instance, if we have the following # template: # # <%= content_for :title, "Main" %> # Hello # <%= content_for :title, " page" %> # # The final result would be: # # <html> # <head><title>Main page</title></head> # <body>Hello</body> # </html> # # This means that, if you have <code>yield :title</code> in your layout # and you want to use streaming, you would have to render the whole template # (and eventually trigger all queries) before streaming the title and all # assets, which kills the purpose of streaming. For this purpose, you can use # a helper called +provide+ that does the same as +content_for+ but tells the # layout to stop searching for other entries and continue rendering. # # For instance, the template above using +provide+ would be: # # <%= provide :title, "Main" %> # Hello # <%= content_for :title, " page" %> # # Giving: # # <html> # <head><title>Main</title></head> # <body>Hello</body> # </html> # # That said, when streaming, you need to properly check your templates # and choose when to use +provide+ and +content_for+. # # == Headers, cookies, session and flash # # When streaming, the HTTP headers are sent to the client right before # it renders the first line. This means that, modifying headers, cookies, # session or flash after the template starts rendering will not propagate # to the client. # # == Middlewares # # Middlewares that need to manipulate the body won't work with streaming. # You should disable those middlewares whenever streaming in development # or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it # needs to inject contents in the HTML body. # # Also <tt>Rack::Cache</tt> won't work with streaming as it does not support # streaming bodies yet. Whenever streaming Cache-Control is automatically # set to "no-cache". # # == Errors # # When it comes to streaming, exceptions get a bit more complicated. This # happens because part of the template was already rendered and streamed to # the client, making it impossible to render a whole exception page. # # Currently, when an exception happens in development or production, Rails # will automatically stream to the client: # # "><script>window.location = "/500.html"</script></html> # # The first two characters (">) are required in case the exception happens # while rendering attributes for a given tag. You can check the real cause # for the exception in your logger. # # == Web server support # # Not all web servers support streaming out-of-the-box. You need to check # the instructions for each of them. # # ==== Unicorn # # Unicorn supports streaming but it needs to be configured. For this, you # need to create a config file as follow: # # # unicorn.config.rb # listen 3000, tcp_nopush: false # # And use it on initialization: # # unicorn_rails --config-file unicorn.config.rb # # You may also want to configure other parameters like <tt>:tcp_nodelay</tt>. # Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen # # If you are using Unicorn with NGINX, you may need to tweak NGINX. # Streaming should work out of the box on Rainbows. # # ==== Passenger # # To be described. # module Streaming extend ActiveSupport::Concern private # Set proper cache control and transfer encoding when streaming def _process_options(options) super if options[:stream] if request.version == "HTTP/1.0" options.delete(:stream) else headers["Cache-Control"] ||= "no-cache" headers["Transfer-Encoding"] = "chunked" headers.delete("Content-Length") end end end # Call render_body if we are streaming instead of usual +render+. def _render_template(options) if options.delete(:stream) Rack::Chunked::Body.new view_renderer.render_body(view_context, options) else super end end end end
lrosskamp/makealist-public
vendor/cache/ruby/2.3.0/gems/actionpack-5.1.2/lib/action_controller/metal/streaming.rb
Ruby
mit
7,653
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace System { public static partial class Environment { private static string? GetEnvironmentVariableCore(string variable) { Span<char> buffer = stackalloc char[128]; // a somewhat reasonable default size int requiredSize = Interop.Kernel32.GetEnvironmentVariable(variable, buffer); if (requiredSize == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND) { return null; } if (requiredSize <= buffer.Length) { return new string(buffer.Slice(0, requiredSize)); } char[] chars = ArrayPool<char>.Shared.Rent(requiredSize); try { buffer = chars; requiredSize = Interop.Kernel32.GetEnvironmentVariable(variable, buffer); if ((requiredSize == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND) || requiredSize > buffer.Length) { return null; } return new string(buffer.Slice(0, requiredSize)); } finally { ArrayPool<char>.Shared.Return(chars); } } private static void SetEnvironmentVariableCore(string variable, string? value) { if (!Interop.Kernel32.SetEnvironmentVariable(variable, value)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Interop.Errors.ERROR_ENVVAR_NOT_FOUND: // Allow user to try to clear a environment variable return; case Interop.Errors.ERROR_FILENAME_EXCED_RANGE: // The error message from Win32 is "The filename or extension is too long", // which is not accurate. throw new ArgumentException(SR.Argument_LongEnvVarValue); case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY: case Interop.Errors.ERROR_NO_SYSTEM_RESOURCES: throw new OutOfMemoryException(Interop.Kernel32.GetMessage(errorCode)); default: throw new ArgumentException(Interop.Kernel32.GetMessage(errorCode)); } } } public static unsafe IDictionary GetEnvironmentVariables() { char* pStrings = Interop.Kernel32.GetEnvironmentStrings(); if (pStrings == null) { throw new OutOfMemoryException(); } try { // Format for GetEnvironmentStrings is: // [=HiddenVar=value\0]* [Variable=value\0]* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Search for terminating \0\0 (two unicode \0's). char* p = pStrings; while (!(*p == '\0' && *(p + 1) == '\0')) { p++; } Span<char> block = new Span<char>(pStrings, (int)(p - pStrings + 1)); // Format for GetEnvironmentStrings is: // (=HiddenVar=value\0 | Variable=value\0)* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Note the =HiddenVar's aren't always at the beginning. // Copy strings out, parsing into pairs and inserting into the table. // The first few environment variable entries start with an '='. // The current working directory of every drive (except for those drives // you haven't cd'ed into in your DOS window) are stored in the // environment block (as =C:=pwd) and the program's exit code is // as well (=ExitCode=00000000). var results = new Hashtable(); for (int i = 0; i < block.Length; i++) { int startKey = i; // Skip to key. On some old OS, the environment block can be corrupted. // Some will not have '=', so we need to check for '\0'. while (block[i] != '=' && block[i] != '\0') { i++; } if (block[i] == '\0') { continue; } // Skip over environment variables starting with '=' if (i - startKey == 0) { while (block[i] != 0) { i++; } continue; } string key = new string(block.Slice(startKey, i - startKey)); i++; // skip over '=' int startValue = i; while (block[i] != 0) { i++; // Read to end of this entry } string value = new string(block.Slice(startValue, i - startValue)); // skip over 0 handled by for loop's i++ try { results.Add(key, value); } catch (ArgumentException) { // Throw and catch intentionally to provide non-fatal notification about corrupted environment block } } return results; } finally { bool success = Interop.Kernel32.FreeEnvironmentStrings(pStrings); Debug.Assert(success); } } } }
BrennanConroy/corefx
src/Common/src/CoreLib/System/Environment.Variables.Windows.cs
C#
mit
6,424
export { Moon16 as default } from "../../";
markogresak/DefinitelyTyped
types/carbon__icons-react/es/moon/16.d.ts
TypeScript
mit
44
export { Mpeg16 as default } from "../../";
georgemarshall/DefinitelyTyped
types/carbon__icons-react/es/MPEG/16.d.ts
TypeScript
mit
44
<?php namespace Illuminate\Mail\Transport; use Swift_Mime_Message; use Illuminate\Support\Collection; class ArrayTransport extends Transport { /** * The collection of Swift Messages. * * @var \Illuminate\Support\Collection */ protected $messages; /** * Create a new array transport instance. * * @return void */ public function __construct() { $this->messages = new Collection; } /** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $this->messages[] = $message; return $this->numberOfRecipients($message); } /** * Retrieve the collection of messages. * * @return \Illuminate\Support\Collection */ public function messages() { return $this->messages; } /** * Clear all of the messages from the local collection. * * @return void */ public function flush() { return $this->messages = new Collection; } }
vileopratama/portal-toyotadjakarta
vendor/laravel/framework/src/Illuminate/Mail/Transport/ArrayTransport.php
PHP
mit
1,109
/*! asynquence-contrib v0.13.0 (c) Kyle Simpson MIT License: http://getify.mit-license.org */ (function UMD(dependency,definition){ if (typeof module !== "undefined" && module.exports) { // make dependency injection wrapper first module.exports = function $$inject$dependency(dep) { // only try to `require(..)` if dependency is a string module path if (typeof dep == "string") { try { dep = require(dep); } catch (err) { // dependency not yet fulfilled, so just return // dependency injection wrapper again return $$inject$dependency; } } return definition(dep); }; // if possible, immediately try to resolve wrapper // (with peer dependency) if (typeof dependency == "string") { module.exports = module.exports( require("path").join("..",dependency) ); } } else if (typeof define == "function" && define.amd) { define([dependency],definition); } else { definition(dependency); } })(this.ASQ || "asynquence",function DEF(ASQ){ "use strict"; var ARRAY_SLICE = Array.prototype.slice, ø = Object.create(null), brand = "__ASQ__", schedule = ASQ.__schedule, tapSequence = ASQ.__tapSequence ; function wrapGate(api,fns,success,failure,reset) { fns = fns.map(function $$map(v,idx){ var def; // tap any directly-provided sequences immediately if (ASQ.isSequence(v)) { def = { seq: v }; tapSequence(def); return function $$fn(next) { def.seq.val(function $$val(){ success(next,idx,ARRAY_SLICE.call(arguments)); }) .or(function $$or(){ failure(next,idx,ARRAY_SLICE.call(arguments)); }); }; } else { return function $$fn(next) { var args = ARRAY_SLICE.call(arguments); args[0] = function $$next() { success(next,idx,ARRAY_SLICE.call(arguments)); }; args[0].fail = function $$fail() { failure(next,idx,ARRAY_SLICE.call(arguments)); }; args[0].abort = function $$abort() { reset(); }; args[0].errfcb = function $$errfcb(err) { if (err) { failure(next,idx,[err]); } else { success(next,idx,ARRAY_SLICE.call(arguments,1)); } }; v.apply(ø,args); }; } }); api.then(function $$then(){ var args = ARRAY_SLICE.call(arguments); fns.forEach(function $$each(fn){ fn.apply(ø,args); }); }); } function isPromise(v) { var val_type = typeof v; return ( v !== null && ( val_type == "object" || val_type == "function" ) && !ASQ.isSequence(v) && // NOTE: `then` duck-typing of promises is stupid typeof v.then == "function" ); } // "after" ASQ.extend("after",function $$extend(api,internals){ return function $$after(num) { var orig_args = arguments.length > 1 ? ARRAY_SLICE.call(arguments,1) : void 0 ; num = +num || 0; api.then(function $$then(done){ var args = orig_args || ARRAY_SLICE.call(arguments,1); setTimeout(function $$set$timeout(){ done.apply(ø,args); },num); }); return api; }; }); ASQ.after = function $$after() { return ASQ().after.apply(ø,arguments); }; // "any" ASQ.extend("any",function $$extend(api,internals){ return function $$any() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages.length = 0; } function complete(trigger) { if (success_messages.length > 0) { // any successful segment's message(s) sent // to main sequence to proceed as success success_messages.length = fns.length; trigger.apply(ø,success_messages); } else { // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, success_messages = [], sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "errfcb" ASQ.extend("errfcb",function $$extend(api,internals){ return function $$errfcb() { // create a fake sequence to extract the callbacks var sq = { val: function $$then(cb){ sq.val_cb = cb; return sq; }, or: function $$or(cb){ sq.or_cb = cb; return sq; } }; // trick `seq(..)`s checks for a sequence sq[brand] = true; // immediately register our fake sequence on the // main sequence api.seq(sq); // provide the "error-first" callback return function $$errorfirst$callback(err) { if (err) { sq.or_cb(err); } else { sq.val_cb.apply(ø,ARRAY_SLICE.call(arguments,1)); } }; }; }); // "failAfter" ASQ.extend("failAfter",function $$extend(api,internals){ return function $$failAfter(num) { var args = arguments.length > 1 ? ARRAY_SLICE.call(arguments,1) : void 0 ; num = +num || 0; api.then(function $$then(done){ setTimeout(function $$set$timeout(){ done.fail.apply(ø,args); },num); }); return api; }; }); ASQ.failAfter = function $$fail$after() { return ASQ().failAfter.apply(ø,arguments); }; // "first" ASQ.extend("first",function $$extend(api,internals){ return function $$first() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { error_messages.length = 0; } function success(trigger,idx,args) { if (!finished) { finished = true; // first successful segment triggers // main sequence to proceed as success trigger( args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ); reset(); } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete without success? if (completed === fns.length) { finished = true; // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); reset(); } } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "go-style CSP" "use strict"; (function IIFE() { // filter out already-resolved queue entries function filterResolved(queue) { return queue.filter(function $$filter(entry) { return !entry.resolved; }); } function closeQueue(queue, finalValue) { queue.forEach(function $$each(iter) { if (!iter.resolved) { iter.next(); iter.next(finalValue); } }); queue.length = 0; } function channel(bufSize) { var ch = { close: function $$close() { ch.closed = true; closeQueue(ch.put_queue, false); closeQueue(ch.take_queue, ASQ.csp.CLOSED); }, closed: false, messages: [], put_queue: [], take_queue: [], buffer_size: +bufSize || 0 }; return ch; } function unblock(iter) { if (iter && !iter.resolved) { iter.next(iter.next().value); } } function put(channel, value) { var ret; if (channel.closed) { return false; } // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); // immediate put? if (channel.messages.length < channel.buffer_size) { channel.messages.push(value); unblock(channel.take_queue.shift()); return true; } // queued put else { channel.put_queue.push( // make a notifiable iterable for 'put' blocking ASQ.iterable().then(function $$then() { if (!channel.closed) { channel.messages.push(value); return true; } else { return false; } })); // wrap a sequence/promise around the iterable ret = ASQ(channel.put_queue[channel.put_queue.length - 1]); // take waiting on this queued put? if (channel.take_queue.length > 0) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } return ret; } } function putAsync(channel, value, cb) { var ret = ASQ(put(channel, value)); if (cb && typeof cb == "function") { ret.val(cb); } else { return ret; } } function take(channel) { var ret; try { ret = takem(channel); } catch (err) { ret = err; } if (ASQ.isSequence(ret)) { ret.pCatch(function $$pcatch(err) { return err; }); } return ret; } function takeAsync(channel, cb) { var ret = ASQ(take(channel)); if (cb && typeof cb == "function") { ret.val(cb); } else { return ret; } } function takem(channel) { var msg; if (channel.closed) { return ASQ.csp.CLOSED; } // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); // immediate take? if (channel.messages.length > 0) { msg = channel.messages.shift(); unblock(channel.put_queue.shift()); if (msg instanceof Error) { throw msg; } return msg; } // queued take else { channel.take_queue.push( // make a notifiable iterable for 'take' blocking ASQ.iterable().then(function $$then() { if (!channel.closed) { var v = channel.messages.shift(); if (v instanceof Error) { throw v; } return v; } else { return ASQ.csp.CLOSED; } })); // wrap a sequence/promise around the iterable msg = ASQ(channel.take_queue[channel.take_queue.length - 1]); // put waiting on this take? if (channel.put_queue.length > 0) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } return msg; } } function takemAsync(channel, cb) { var ret = ASQ(takem(channel)); if (cb && typeof cb == "function") { ret.pThen(cb, cb); } else { return ret.val(function $$val(v) { if (v instanceof Error) { throw v; } return v; }); } } function alts(actions) { var closed, open, handlers, i, isq, ret, resolved = false; // used `alts(..)` incorrectly? if (!Array.isArray(actions) || actions.length == 0) { throw Error("Invalid usage"); } closed = []; open = []; handlers = []; // separate actions by open/closed channel status actions.forEach(function $$each(action) { var channel = Array.isArray(action) ? action[0] : action; // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); if (channel.closed) { closed.push(channel); } else { open.push(action); } }); // if no channels are still open, we're done if (open.length == 0) { return { value: ASQ.csp.CLOSED, channel: closed }; } // can any channel action be executed immediately? for (i = 0; i < open.length; i++) { // put action if (Array.isArray(open[i])) { // immediate put? if (open[i][0].messages.length < open[i][0].buffer_size) { return { value: put(open[i][0], open[i][1]), channel: open[i][0] }; } } // immediate take? else if (open[i].messages.length > 0) { return { value: take(open[i]), channel: open[i] }; } } isq = ASQ.iterable(); var ret = ASQ(isq); // setup channel action handlers for (i = 0; i < open.length; i++) { (function iteration(action, channel, value) { // put action? if (Array.isArray(action)) { channel = action[0]; value = action[1]; // define put handler handlers.push(ASQ.iterable().then(function $$then() { resolved = true; // mark all handlers across this `alts(..)` as resolved now handlers = handlers.filter(function $$filter(handler) { return !(handler.resolved = true); }); // channel still open? if (!channel.closed) { channel.messages.push(value); isq.next({ value: true, channel: channel }); } // channel already closed? else { isq.next({ value: false, channel: channel }); } })); // queue up put handler channel.put_queue.push(handlers[handlers.length - 1]); // take waiting on this queued put? if (channel.take_queue.length > 0) { schedule(function handleUnblocking() { if (!resolved) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } }, 0); } } // take action? else { channel = action; // define take handler handlers.push(ASQ.iterable().then(function $$then() { resolved = true; // mark all handlers across this `alts(..)` as resolved now handlers = handlers.filter(function $$filter(handler) { return !(handler.resolved = true); }); // channel still open? if (!channel.closed) { isq.next({ value: channel.messages.shift(), channel: channel }); } // channel already closed? else { isq.next({ value: ASQ.csp.CLOSED, channel: channel }); } })); // queue up take handler channel.take_queue.push(handlers[handlers.length - 1]); // put waiting on this queued take? if (channel.put_queue.length > 0) { schedule(function handleUnblocking() { if (!resolved) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } }); } } })(open[i]); } return ret; } function altsAsync(chans, cb) { var ret = ASQ(alts(channel)); if (cb && typeof cb == "function") { ret.pThen(cb, cb); } else { return ret; } } function timeout(delay) { var ch = channel(); setTimeout(ch.close, delay); return ch; } function go(gen, args) { // goroutine arguments passed? if (arguments.length > 1) { if (!args || !Array.isArray(args)) { args = [args]; } } else { args = []; } return regeneratorRuntime.mark(function $$go(token) { var unblock, ret, msg, err, type, done, it; return regeneratorRuntime.wrap(function $$go$(context$3$0) { while (1) switch (context$3$0.prev = context$3$0.next) { case 0: unblock = function unblock() { if (token.block && !token.block.marked) { token.block.marked = true; token.block.next(); } }; done = false; // keep track of how many goroutines are running // so we can infer when we're done go'ing token.go_count = (token.go_count || 0) + 1; // need to initialize a set of goroutines? if (token.go_count === 1) { // create a default channel for these goroutines token.channel = channel(); token.channel.messages = token.messages; token.channel.go = function $$go() { // unblock the goroutine handling for these // new goroutine(s)? unblock(); // add the goroutine(s) to the handling queue token.add(go.apply(ø, arguments)); }; // starting out with initial channel messages? if (token.channel.messages.length > 0) { // fake back-pressure blocking for each token.channel.put_queue = token.channel.messages.map(function $$map() { // make a notifiable iterable for 'put' blocking return ASQ.iterable().then(function $$then() { unblock(token.channel.take_queue.shift()); return !token.channel.closed; }); }); } } // initialize the generator it = gen.apply(ø, [token.channel].concat(args)); (function iterate() { function next() { // keep going with next step in goroutine? if (!done) { iterate(); } // unblock overall goroutine handling to // continue with other goroutines else { unblock(); } } // has a resumption value been achieved yet? if (!ret) { // try to resume the goroutine try { // resume with injected exception? if (err) { ret = it["throw"](err); err = null; } // resume normally else { ret = it.next(msg); } } // resumption failed, so bail catch (e) { done = true; err = e; msg = null; unblock(); return; } // keep track of the result of the resumption done = ret.done; ret = ret.value; type = typeof ret; // if this goroutine is complete, unblock the // overall goroutine handling if (done) { unblock(); } // received a thenable/promise back? if (isPromise(ret)) { ret = ASQ().promise(ret); } // wait for the value? if (ASQ.isSequence(ret)) { ret.val(function $$val() { ret = null; msg = arguments.length > 1 ? ASQ.messages.apply(ø, arguments) : arguments[0]; next(); }).or(function $$or() { ret = null; msg = arguments.length > 1 ? ASQ.messages.apply(ø, arguments) : arguments[0]; if (msg instanceof Error) { err = msg; msg = null; } next(); }); } // immediate value, prepare it to go right back in else { msg = ret; ret = null; next(); } } })(); // keep this goroutine alive until completion case 6: if (done) { context$3$0.next = 15; break; } context$3$0.next = 9; return token; case 9: if (!(!done && !token.block)) { context$3$0.next = 13; break; } context$3$0.next = 12; return token.block = ASQ.iterable(); case 12: token.block = false; case 13: context$3$0.next = 6; break; case 15: // this goroutine is done now token.go_count--; // all goroutines done? if (token.go_count === 0) { // any lingering blocking need to be cleaned up? unblock(); // capture any untaken messages msg = ASQ.messages.apply(ø, token.messages); // need to implicitly force-close channel? if (token.channel && !token.channel.closed) { token.channel.closed = true; token.channel.put_queue.length = token.channel.take_queue.length = 0; token.channel.close = token.channel.go = token.channel.messages = null; } token.channel = null; } // make sure leftover error or message are // passed along if (!err) { context$3$0.next = 21; break; } throw err; case 21: if (!(token.go_count === 0)) { context$3$0.next = 25; break; } return context$3$0.abrupt("return", msg); case 25: return context$3$0.abrupt("return", token); case 26: case "end": return context$3$0.stop(); } }, $$go, this); }); } ASQ.csp = { chan: channel, put: put, putAsync: putAsync, take: take, takeAsync: takeAsync, takem: takem, takemAsync: takemAsync, alts: alts, altsAsync: altsAsync, timeout: timeout, go: go, CLOSED: {} }; })(); // unblock the overall goroutine handling // transfer control to another goroutine // need to block overall goroutine handling // while idle? // wait here while idle// "ASQ.iterable()" "use strict"; (function IIFE() { var template; ASQ.iterable = function $$iterable() { function throwSequenceErrors() { throw sequence_errors.length === 1 ? sequence_errors[0] : sequence_errors; } function notifyErrors() { var fn; seq_tick = null; if (seq_error) { if (or_queue.length === 0 && !error_reported) { error_reported = true; throwSequenceErrors(); } while (or_queue.length > 0) { error_reported = true; fn = or_queue.shift(); try { fn.apply(ø, sequence_errors); } catch (err) { if (checkBranding(err)) { sequence_errors = sequence_errors.concat(err); } else { sequence_errors.push(err); } if (or_queue.length === 0) { throwSequenceErrors(); } } } } } function val() { if (seq_error || seq_aborted || arguments.length === 0) { return sequence_api; } var args = ARRAY_SLICE.call(arguments).map(function mapper(arg) { if (typeof arg != "function") return function $$val() { return arg; };else return arg; }); val_queue.push.apply(val_queue, args); return sequence_api; } function or() { if (seq_aborted || arguments.length === 0) { return sequence_api; } or_queue.push.apply(or_queue, arguments); if (!seq_tick) { seq_tick = schedule(notifyErrors); } return sequence_api; } function pipe() { if (seq_aborted || arguments.length === 0) { return sequence_api; } ARRAY_SLICE.call(arguments).forEach(function $$each(fn) { val(fn).or(fn.fail); }); return sequence_api; } function next() { if (seq_error || seq_aborted || val_queue.length === 0) { if (val_queue.length > 0) { $throw$("Sequence cannot be iterated"); } return { done: true }; } try { return { value: val_queue.shift().apply(ø, arguments) }; } catch (err) { if (ASQ.isMessageWrapper(err)) { $throw$.apply(ø, err); } else { $throw$(err); } return {}; } } function $throw$() { if (seq_error || seq_aborted) { return sequence_api; } sequence_errors.push.apply(sequence_errors, arguments); seq_error = true; if (!seq_tick) { seq_tick = schedule(notifyErrors); } return sequence_api; } function $return$(val) { if (seq_error || seq_aborted) { val = void 0; } abort(); return { done: true, value: val }; } function abort() { if (seq_error || seq_aborted) { return; } seq_aborted = true; clearTimeout(seq_tick); seq_tick = null; val_queue.length = or_queue.length = sequence_errors.length = 0; } function duplicate() { var isq; template = { val_queue: val_queue.slice(), or_queue: or_queue.slice() }; isq = ASQ.iterable(); template = null; return isq; } // opt-out of global error reporting for this sequence function defer() { or_queue.push(function $$ignored() {}); return sequence_api; } // *********************************************** // Object branding utilities // *********************************************** function brandIt(obj) { Object.defineProperty(obj, brand, { enumerable: false, value: true }); return obj; } var sequence_api, seq_error = false, error_reported = false, seq_aborted = false, seq_tick, val_queue = [], or_queue = [], sequence_errors = []; // *********************************************** // Setup the ASQ.iterable() public API // *********************************************** sequence_api = brandIt({ val: val, then: val, or: or, pipe: pipe, next: next, "throw": $throw$, "return": $return$, abort: abort, duplicate: duplicate, defer: defer }); // useful for ES6 `for..of` loops, // add `@@iterator` to simply hand back // our iterable sequence itself! sequence_api[typeof Symbol == "function" && Symbol.iterator || "@@iterator"] = function $$iter() { return sequence_api; }; // templating the iterable-sequence setup? if (template) { val_queue = template.val_queue.slice(0); or_queue = template.or_queue.slice(0); } // treat ASQ.iterable() constructor parameters as having been // passed to `val()` sequence_api.val.apply(ø, arguments); return sequence_api; }; })();// "last" ASQ.extend("last",function $$extend(api,internals){ return function $$last() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages = null; } function complete(trigger) { if (success_messages != null) { // last successful segment's message(s) sent // to main sequence to proceed as success trigger( success_messages.length > 1 ? ASQ.messages.apply(ø,success_messages) : success_messages[0] ); } else { // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages = args; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)), success_messages ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "map" ASQ.extend("map",function $$extend(api,internals){ return function $$map(pArr,pEach) { if (internals("seq_error") || internals("seq_aborted")) { return api; } api.seq(function $$seq(){ var tmp, args = ARRAY_SLICE.call(arguments), arr = pArr, each = pEach; // if missing `map(..)` args, use value-messages (if any) if (!each) each = args.shift(); if (!arr) arr = args.shift(); // if arg types in reverse order (each,arr), swap if (typeof arr === "function" && Array.isArray(each)) { tmp = arr; arr = each; each = tmp; } return ASQ.apply(ø,args) .gate.apply(ø,arr.map(function $$map(item){ return function $$segment(){ each.apply(ø,[item].concat(ARRAY_SLICE.call(arguments))); }; })); }) .val(function $$val(){ // collect all gate segment output into one value-message // Note: return a normal array here, not a message wrapper! return ARRAY_SLICE.call(arguments); }); return api; }; }); // "none" ASQ.extend("none",function $$extend(api,internals){ return function $$none() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages.length = 0; } function complete(trigger) { if (success_messages.length > 0) { // any successful segment's message(s) sent // to main sequence to proceed as **error** success_messages.length = fns.length; trigger.fail.apply(ø,success_messages); } else { // send errors as **success** to main sequence error_messages.length = fns.length; trigger.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)), success_messages = [] ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "pThen" ASQ.extend("pThen",function $$extend(api,internals){ return function $$pthen(success,failure) { if (internals("seq_aborted")) { return api; } var ignore_success_handler = false, ignore_failure_handler = false; if (typeof success === "function") { api.then(function $$then(done){ if (!ignore_success_handler) { var ret, msgs = ASQ.messages.apply(ø,arguments); msgs.shift(); if (msgs.length === 1) { msgs = msgs[0]; } ignore_failure_handler = true; try { ret = success(msgs); } catch (err) { if (!ASQ.isMessageWrapper(err)) { err = [err]; } done.fail.apply(ø,err); return; } // returned a sequence? if (ASQ.isSequence(ret)) { ret.pipe(done); } // returned a message wrapper? else if (ASQ.isMessageWrapper(ret)) { done.apply(ø,ret); } // returned a promise/thenable? else if (isPromise(ret)) { ret.then(done,done.fail); } // just a normal value to pass along else { done(ret); } } else { done.apply(ø,ARRAY_SLICE.call(arguments,1)); } }); } if (typeof failure === "function") { api.or(function $$or(){ if (!ignore_failure_handler) { var ret, msgs = ASQ.messages.apply(ø,arguments), smgs, or_queue = ARRAY_SLICE.call(internals("or_queue")) ; if (msgs.length === 1) { msgs = msgs[0]; } ignore_success_handler = true; // NOTE: if this call throws, that'll automatically // be handled by core as we'd want it to be ret = failure(msgs); // if we get this far: // first, inject return value (if any) as // next step's sequence messages smgs = internals("sequence_messages"); smgs.length = 0; if (typeof ret !== "undefined") { if (!ASQ.isMessageWrapper(ret)) { ret = [ret]; } smgs.push.apply(smgs,ret); } // reset internal error state, because we've exclusively // handled any errors up to this point of the sequence internals("sequence_errors").length = 0; internals("seq_error",false); internals("then_ready",true); // temporarily empty the or-queue internals("or_queue").length = 0; // make sure to schedule success-procession on the chain api.val(function $$val(){ // pass thru messages return ASQ.messages.apply(ø,arguments); }); // at next cycle, reinstate the or-queue (if any) if (or_queue.length > 0) { schedule(function $$schedule(){ api.or.apply(ø,or_queue); }); } } }); } return api; }; }); // "pCatch" ASQ.extend("pCatch",function $$extend(api,internals){ return function $$pcatch(failure) { if (internals("seq_aborted")) { return api; } api.pThen(void 0,failure); return api; }; }); // "race" ASQ.extend("race",function $$extend(api,internals){ return function $$race() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(v){ var def; // tap any directly-provided sequences immediately if (ASQ.isSequence(v)) { def = { seq: v }; tapSequence(def); return function $$fn(done) { def.seq.pipe(done); }; } else return v; }); api.then(function $$then(done){ var args = ARRAY_SLICE.call(arguments); fns.forEach(function $$each(fn){ fn.apply(ø,args); }); }); return api; }; }); // "react" (reactive sequences) ASQ.react = function $$react(reactor) { function next() { if (template) { var sq = template.duplicate(); sq.unpause.apply(ø,arguments); return sq; } return ASQ(function $$asq(){ throw "Disabled Sequence"; }); } function registerTeardown(fn) { if (template && typeof fn === "function") { teardowns.push(fn); } } var template = ASQ().duplicate(), teardowns = [] ; // add reactive sequence kill switch template.stop = function $$stop() { if (template) { template = null; teardowns.forEach(Function.call,Function.call); teardowns.length = 0; } }; next.onStream = function $$onStream() { ARRAY_SLICE.call(arguments) .forEach(function $$each(stream){ stream.on("data",next); stream.on("error",next); }); }; next.unStream = function $$unStream() { ARRAY_SLICE.call(arguments) .forEach(function $$each(stream){ stream.removeListener("data",next); stream.removeListener("error",next); }); }; // make sure `reactor(..)` is called async ASQ.__schedule(function $$schedule(){ reactor.call(template,next,registerTeardown); }); return template; }; // "react" helpers (function IIFE(){ function tapSequences() { function tapSequence(seq) { // temporary `trigger` which, if called before being replaced // below, creates replacement proxy sequence with the // event message(s) re-fired function trigger() { var args = ARRAY_SLICE.call(arguments); def.seq = ASQ.react(function $$react(next){ next.apply(ø,args); }); } if (ASQ.isSequence(seq)) { var def = { seq: seq }; // listen for events from the sequence-stream seq.val(function $$val(){ trigger.apply(ø,arguments); return ASQ.messages.apply(ø,arguments); }); // make a reactive sequence to act as a proxy to the original // sequence def.seq = ASQ.react(function $$react(next){ // replace the temporary trigger (created above) // with this proxy's trigger trigger = next; }); return def; } } return ARRAY_SLICE.call(arguments) .map(tapSequence) .filter(Boolean); } function createReactOperator(buffer) { return function $$react$operator(){ function reactor(next,registerTeardown){ function processSequence(def) { // sequence-stream event listener function trigger() { var args = ASQ.messages.apply(ø,arguments); // still observing sequence-streams? if (seqs && seqs.length > 0) { // store event message(s), if any seq_events[seq_id] = [].concat( buffer ? seq_events[seq_id] : [], args.length > 0 ? [args] : undefined ); // collect event message(s) across the // sequence-stream sources var messages = seq_events.reduce(function reducer(msgs,eventList,idx){ if (eventList.length > 0) msgs.push(eventList[0]); return msgs; },[]); // did all sequence-streams get an event? if (messages.length == seq_events.length) { if (messages.length == 1) messages = messages[0]; // fire off reactive sequence instance next.apply(ø,messages); // discard stored event message(s) seq_events.forEach(function $$each(eventList){ eventList.shift(); }); } } // keep sequence going return args; } var seq_id = seq_events.length; seq_events.push([]); def.seq.val(trigger); } // process all sequence-streams seqs.forEach(processSequence); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ seqs = seq_events = null; }); } var seq_events = [], // observe all sequence-streams seqs = tapSequences.apply(null,arguments) ; if (seqs.length == 0) return; return ASQ.react(reactor); }; } ASQ.react.all = ASQ.react.zip = createReactOperator(/*buffer=*/true); ASQ.react.latest = ASQ.react.combine = createReactOperator(/*buffer=false*/); ASQ.react.any = ASQ.react.merge = function $$react$any(){ function reactor(next,registerTeardown){ function processSequence(def){ function trigger(){ var args = ASQ.messages.apply(ø,arguments); // still observing sequence-streams? if (seqs && seqs.length > 0) { // fire off reactive sequence instance next.apply(ø,args); } // keep sequence going return args; } // sequence-stream event listener def.seq.val(trigger); } // observe all sequence-streams seqs.forEach(processSequence); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ seqs = null; }); } // observe all sequence-streams var seqs = tapSequences.apply(null,arguments); if (seqs.length == 0) return; return ASQ.react(reactor); }; ASQ.react.distinct = function $$react$distinct(seq){ function filterer() { function isDuplicate(msgs) { return ( msgs.length == messages.length && msgs.every(function $$every(val,idx){ return val === messages[idx]; }) ); } var messages = ASQ.messages.apply(ø,arguments); // any messages to check against? if (messages.length > 0) { // messages already sent before? if (prev_messages.some(isDuplicate)) { // bail on duplicate messages return false; } // save messages for future distinct checking prev_messages.push(messages); } // allow distinct non-duplicate value through return true; } var prev_messages = []; return ASQ.react.filter(seq,filterer); }; ASQ.react.filter = function $$react$filter(seq,filterer){ function reactor(next,registerTeardown) { function trigger(){ var messages = ASQ.messages.apply(ø,arguments); if (filterer && filterer.apply(ø,messages)) { // fire off reactive sequence instance next.apply(ø,messages); } // keep sequence going return messages; } // sequence-stream event listener def.seq.val(trigger); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ def = filterer = null; }); } // observe sequence-stream var def = tapSequences(seq)[0]; if (!def) return; return ASQ.react(reactor); }; ASQ.react.fromObservable = function $$react$from$observable(obsv){ function reactor(next,registerTeardown){ // process buffer (if any) buffer.forEach(next); buffer.length = 0; // start non-buffered notifications? if (!buffer.complete) { notify = next; } registerTeardown(function $$teardown(){ obsv.dispose(); }); } function notify(v) { buffer.push(v); } var buffer = []; obsv.subscribe( function $$on$next(v){ notify(v); }, function $$on$error(){}, function $$on$complete(){ buffer.complete = true; obsv.dispose(); } ); return ASQ.react(reactor); }; ASQ.extend("toObservable",function $$extend(api,internals){ return function $$to$observable(){ function init(observer) { function define(pair){ function listen(){ var args = ASQ.messages.apply(ø,arguments); observer[pair[1]].apply(observer, args.length == 1 ? [args[0]] : args ); return args; } api[pair[0]](listen); } [["val","onNext"],["or","onError"]] .forEach(define); } return Rx.Observable.create(init); }; }); })(); // "runner" ASQ.extend("runner",function $$extend(api,internals){ return function $$runner() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var args = ARRAY_SLICE.call(arguments); api .then(function $$then(mainDone){ function wrap(v) { // function? expected to produce an iterator // (like a generator) or a promise if (typeof v === "function") { // call function passing in the control token // note: neutralize `this` in call to prevent // unexpected behavior v = v.call(ø,next_val); // promise returned (ie, from async function)? if (isPromise(v)) { // wrap it in iterable sequence v = ASQ.iterable(v); } } // an iterable sequence? duplicate it (in case of multiple runs) else if (ASQ.isSequence(v) && "next" in v) { v = v.duplicate(); } // wrap anything else in iterable sequence else { v = ASQ.iterable(v); } // a sequence to tap for errors? if (ASQ.isSequence(v)) { // listen for any sequence failures v.or(function $$or(){ // signal iteration-error mainDone.fail.apply(ø,arguments); }); } return v; } function addWrapped() { iterators.push.apply( iterators, ARRAY_SLICE.call(arguments).map(wrap) ); } var iterators = args, token = { messages: ARRAY_SLICE.call(arguments,1), add: addWrapped }, iter, ret, next_val = token ; // map co-routines to round-robin list of iterators iterators = iterators.map(wrap); // async iteration of round-robin list (function iterate(){ // get next co-routine in list iter = iterators.shift(); // process the iteration try { // multiple messages to send to an iterable // sequence? if (ASQ.isMessageWrapper(next_val) && ASQ.isSequence(iter) ) { ret = iter.next.apply(iter,next_val); } else { ret = iter.next(next_val); } } catch (err) { return mainDone.fail(err); } // bail on run in aborted sequence if (internals("seq_aborted")) return; // was the control token yielded? if (ret.value === token) { // round-robin: put co-routine back into the list // at the end where it was so it can be processed // again on next loop-iteration iterators.push(iter); next_val = token; schedule(iterate); // async recurse } else { // not a recognized ASQ instance returned? if (!ASQ.isSequence(ret.value)) { // received a thenable/promise back? if (isPromise(ret.value)) { // wrap in a sequence ret.value = ASQ().promise(ret.value); } // thunk yielded? else if (typeof ret.value === "function") { // wrap thunk call in a sequence var fn = ret.value; ret.value = ASQ(function $$ASQ(done){ fn(done.errfcb); }); } // message wrapper returned? else if (ASQ.isMessageWrapper(ret.value)) { // wrap message(s) in a sequence ret.value = ASQ.apply(ø, // don't let `apply(..)` discard an empty message // wrapper! instead, pass it along as its own value // itself. ret.value.length > 0 ? ret.value : ASQ.messages(undefined) ); } // non-undefined value returned? else if (typeof ret.value !== "undefined") { // wrap the value in a sequence ret.value = ASQ(ret.value); } else { // make an empty sequence ret.value = ASQ(); } } ret.value .val(function $$val(){ // bail on run in aborted sequence if (internals("seq_aborted")) return; if (arguments.length > 0) { // save any return messages for input // to next iteration next_val = arguments.length > 1 ? ASQ.messages.apply(ø,arguments) : arguments[0] ; } // still more to iterate? if (!ret.done) { // was the control token passed along? if (next_val === token) { // round-robin: put co-routine back into the list // at the end, so that the the next iterator can be // processed on next loop-iteration iterators.push(iter); } else { // put co-routine back in where it just // was so it can be processed again on // next loop-iteration iterators.unshift(iter); } } // still have some co-routine runs to process? if (iterators.length > 0) { iterate(); // async recurse } // all done! else { // previous value message? if (typeof next_val !== "undefined") { // not a message wrapper array? if (!ASQ.isMessageWrapper(next_val)) { // wrap value for the subsequent `apply(..)` next_val = [next_val]; } } else { // nothing to affirmatively pass along next_val = []; } // signal done with all co-routine runs mainDone.apply(ø,next_val); } }) .or(function $$or(){ // bail on run in aborted sequence if (internals("seq_aborted")) return; try { // if an error occurs in the step-continuation // promise or sequence, throw it back into the // generator or iterable-sequence iter["throw"].apply(iter,arguments); } catch (err) { // if an error comes back out of after the throw, // pass it out to the main sequence, as iteration // must now be complete mainDone.fail(err); } }); } })(); }); return api; }; }); // "toPromise" ASQ.extend("toPromise",function $$extend(api,internals){ return function $$to$promise() { return new Promise(function $$executor(resolve,reject){ api .val(function $$val(){ var args = ARRAY_SLICE.call(arguments); resolve.call(ø,args.length > 1 ? args : args[0]); return ASQ.messages.apply(ø,args); }) .or(function $$or(){ var args = ARRAY_SLICE.call(arguments); reject.call(ø,args.length > 1 ? args : args[0]); }); }); }; }); // "try" ASQ.extend("try",function $$extend(api,internals){ return function $$try() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(fn){ return function $$then(mainDone) { var main_args = ARRAY_SLICE.call(arguments), sq = ASQ.apply(ø,main_args.slice(1)) ; sq .then(function $$inner$then(){ fn.apply(ø,arguments); }) .val(function $$val(){ mainDone.apply(ø,arguments); }) .or(function $$inner$or(){ var msgs = ASQ.messages.apply(ø,arguments); // failed, so map error(s) as `catch` mainDone({ "catch": msgs.length > 1 ? msgs : msgs[0] }); }); }; }); api.then.apply(ø,fns); return api; }; }); // "until" ASQ.extend("until",function $$extend(api,internals){ return function $$until() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(fn){ return function $$then(mainDone) { var main_args = ARRAY_SLICE.call(arguments), sq = ASQ.apply(ø,main_args.slice(1)) ; sq .then(function $$inner$then(){ var args = ARRAY_SLICE.call(arguments); args[0]["break"] = function $$break(){ mainDone.fail.apply(ø,arguments); sq.abort(); }; fn.apply(ø,args); }) .val(function $$val(){ mainDone.apply(ø,arguments); }) .or(function $$inner$or(){ // failed, retry $$then.apply(ø,main_args); }); }; }); api.then.apply(ø,fns); return api; }; }); // "waterfall" ASQ.extend("waterfall",function $$extend(api,internals){ return function $$waterfall() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ var msgs = ASQ.messages(), sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; fns.forEach(function $$each(fn){ sq.then(fn) .val(function $$val(){ var args = ASQ.messages.apply(ø,arguments); msgs.push(args.length > 1 ? args : args[0]); return msgs; }); }); sq.pipe(done); }); return api; }; }); // "wrap" ASQ.wrap = function $$wrap(fn,opts) { function checkThis(t,o) { return (!t || (typeof window != "undefined" && t === window) || (typeof global != "undefined" && t === global) ) ? o : t; } var errfcb, params_first, act, this_obj; opts = (opts && typeof opts == "object") ? opts : {}; if ( (opts.errfcb && opts.splitcb) || (opts.errfcb && opts.simplecb) || (opts.splitcb && opts.simplecb) || ("errfcb" in opts && !opts.errfcb && !opts.splitcb && !opts.simplecb) || (opts.params_first && opts.params_last) ) { throw Error("Invalid options"); } // initialize default flags this_obj = (opts["this"] && typeof opts["this"] == "object") ? opts["this"] : ø; errfcb = opts.errfcb || !(opts.splitcb || opts.simplecb); params_first = !!opts.params_first || (!opts.params_last && !("params_first" in opts || opts.params_first)) || ("params_last" in opts && !opts.params_first && !opts.params_last) ; if (params_first) { act = "push"; } else { act = "unshift"; } if (opts.gen) { return function $$wrapped$gen() { return ASQ.apply(ø,arguments).runner(fn); }; } if (errfcb) { return function $$wrapped$errfcb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done.errfcb); fn.apply(_this,args); }); }; } if (opts.splitcb) { return function $$wrapped$splitcb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done,done.fail); fn.apply(_this,args); }); }; } if (opts.simplecb) { return function $$wrapped$simplecb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done); fn.apply(_this,args); }); }; } }; // just return `ASQ` itself for convenience sake return ASQ; });
x112358/cdnjs
ajax/libs/asynquence-contrib/0.13.0/contrib.src.js
JavaScript
mit
50,809
<?php define( "MSG_TIMEOUT", 2.0 ); define( "MSG_DATA_SIZE", 4+256 ); if ( canEdit( 'Monitors' ) ) { $zmuCommand = getZmuCommand( " -m ".validInt($_REQUEST['id']) ); switch ( validJsStr($_REQUEST['command']) ) { case "disableAlarms" : { $zmuCommand .= " -n"; break; } case "enableAlarms" : { $zmuCommand .= " -c"; break; } case "forceAlarm" : { $zmuCommand .= " -a"; break; } case "cancelForcedAlarm" : { $zmuCommand .= " -c"; break; } default : { ajaxError( "Unexpected command '".validJsStr($_REQUEST['command'])."'" ); } } ajaxResponse( exec( escapeshellcmd( $zmuCommand ) ) ); } ajaxError( 'Unrecognised action or insufficient permissions' ); ?>
seebaer1976/ZoneMinder
web/ajax/alarm.php
PHP
gpl-2.0
907
/** * Copyright 2014 Google Inc. All Rights Reserved. * * 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. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * Cloud Storage API * * @classdesc Lets you store and retrieve potentially-large, immutable data objects. * @namespace storage * @version v1 * @variation v1 * @this Storage * @param {object=} options Options for Storage */ function Storage(options) { var self = this; this._options = options || {}; this.bucketAccessControls = { /** * storage.bucketAccessControls.delete * * @desc Permanently deletes the ACL entry for the specified entity on the specified bucket. * * @alias storage.bucketAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.get * * @desc Returns the ACL entry for the specified entity on the specified bucket. * * @alias storage.bucketAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.insert * * @desc Creates a new ACL entry on the specified bucket. * * @alias storage.bucketAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.list * * @desc Retrieves ACL entries on the specified bucket. * * @alias storage.bucketAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.patch * * @desc Updates an ACL entry on the specified bucket. This method supports patch semantics. * * @alias storage.bucketAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.update * * @desc Updates an ACL entry on the specified bucket. * * @alias storage.bucketAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); } }; this.buckets = { /** * storage.buckets.delete * * @desc Permanently deletes an empty bucket. * * @alias storage.buckets.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - If set, only deletes the bucket if its metageneration matches this value. * @param {string=} params.ifMetagenerationNotMatch - If set, only deletes the bucket if its metageneration does not match this value. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'DELETE' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.get * * @desc Returns metadata for the specified bucket. * * @alias storage.buckets.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.insert * * @desc Creates a new bucket. * * @alias storage.buckets.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string} params.project - A valid API project identifier. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b', method: 'POST' }, params: params, requiredParams: ['project'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.list * * @desc Retrieves a list of buckets for a given project. * * @alias storage.buckets.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {integer=} params.maxResults - Maximum number of buckets to return. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to buckets whose names begin with this prefix. * @param {string} params.project - A valid API project identifier. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b', method: 'GET' }, params: params, requiredParams: ['project'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.patch * * @desc Updates a bucket. This method supports patch semantics. * * @alias storage.buckets.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'PATCH' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.update * * @desc Updates a bucket. * * @alias storage.buckets.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'PUT' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); } }; this.channels = { /** * storage.channels.stop * * @desc Stop watching resources through this channel * * @alias storage.channels.stop * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ stop: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/channels/stop', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.defaultObjectAccessControls = { /** * storage.defaultObjectAccessControls.delete * * @desc Permanently deletes the default object ACL entry for the specified entity on the specified bucket. * * @alias storage.defaultObjectAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.get * * @desc Returns the default object ACL entry for the specified entity on the specified bucket. * * @alias storage.defaultObjectAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.insert * * @desc Creates a new default object ACL entry on the specified bucket. * * @alias storage.defaultObjectAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.list * * @desc Retrieves default object ACL entries on the specified bucket. * * @alias storage.defaultObjectAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - If present, only return default ACL listing if the bucket's current metageneration matches this value. * @param {string=} params.ifMetagenerationNotMatch - If present, only return default ACL listing if the bucket's current metageneration does not match the given value. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.patch * * @desc Updates a default object ACL entry on the specified bucket. This method supports patch semantics. * * @alias storage.defaultObjectAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.update * * @desc Updates a default object ACL entry on the specified bucket. * * @alias storage.defaultObjectAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); } }; this.objectAccessControls = { /** * storage.objectAccessControls.delete * * @desc Permanently deletes the ACL entry for the specified entity on the specified object. * * @alias storage.objectAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.get * * @desc Returns the ACL entry for the specified entity on the specified object. * * @alias storage.objectAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.insert * * @desc Creates a new ACL entry on the specified object. * * @alias storage.objectAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl', method: 'POST' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.list * * @desc Retrieves ACL entries on the specified object. * * @alias storage.objectAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl', method: 'GET' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.patch * * @desc Updates an ACL entry on the specified object. This method supports patch semantics. * * @alias storage.objectAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.update * * @desc Updates an ACL entry on the specified object. * * @alias storage.objectAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); } }; this.objects = { /** * storage.objects.compose * * @desc Concatenates a list of existing objects into a new object in the same bucket. * * @alias storage.objects.compose * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.destinationBucket - Name of the bucket in which to store the new object. * @param {string} params.destinationObject - Name of the new object. * @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ compose: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{destinationBucket}/o/{destinationObject}/compose', method: 'POST' }, params: params, requiredParams: ['destinationBucket', 'destinationObject'], pathParams: ['destinationBucket', 'destinationObject'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.copy * * @desc Copies an object to a specified location. Optionally overrides metadata. * * @alias storage.objects.copy * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.destinationBucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. * @param {string} params.destinationObject - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. * @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the destination object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the destination object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the destination object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the destination object's current metageneration does not match the given value. * @param {string=} params.ifSourceGenerationMatch - Makes the operation conditional on whether the source object's generation matches the given value. * @param {string=} params.ifSourceGenerationNotMatch - Makes the operation conditional on whether the source object's generation does not match the given value. * @param {string=} params.ifSourceMetagenerationMatch - Makes the operation conditional on whether the source object's current metageneration matches the given value. * @param {string=} params.ifSourceMetagenerationNotMatch - Makes the operation conditional on whether the source object's current metageneration does not match the given value. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. * @param {string} params.sourceBucket - Name of the bucket in which to find the source object. * @param {string=} params.sourceGeneration - If present, selects a specific revision of the source object (as opposed to the latest version, the default). * @param {string} params.sourceObject - Name of the source object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ copy: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}', method: 'POST' }, params: params, requiredParams: ['sourceBucket', 'sourceObject', 'destinationBucket', 'destinationObject'], pathParams: ['destinationBucket', 'destinationObject', 'sourceBucket', 'sourceObject'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.delete * * @desc Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used. * * @alias storage.objects.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.get * * @desc Retrieves an object or its metadata. * * @alias storage.objects.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'GET' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.insert * * @desc Stores a new object and metadata. * * @alias storage.objects.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. * @param {string=} params.contentEncoding - If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string=} params.name - Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. * @param {object} params.resource - Media resource metadata * @param {object} params.media - Media object * @param {string} params.media.mimeType - Media mime-type * @param {string|object} params.media.body - Media body contents * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o', method: 'POST' }, params: params, mediaUrl: 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o', requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.list * * @desc Retrieves a list of objects matching the criteria. * * @alias storage.objects.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to look for objects. * @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. * @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to objects whose names begin with this prefix. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {boolean=} params.versions - If true, lists all versions of a file as distinct results. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.patch * * @desc Updates an object's metadata. This method supports patch semantics. * * @alias storage.objects.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.update * * @desc Updates an object's metadata. * * @alias storage.objects.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.watchAll * * @desc Watch for changes on all objects in a bucket. * * @alias storage.objects.watchAll * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to look for objects. * @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. * @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to objects whose names begin with this prefix. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {boolean=} params.versions - If true, lists all versions of a file as distinct results. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ watchAll: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/watch', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); } }; } /** * Exports Storage object * @type Storage */ module.exports = Storage;
Shance/newsaity74.ru
templates/blank_j3/node_modules/psi/node_modules/googleapis/apis/storage/v1.js
JavaScript
gpl-2.0
48,996
/* =========================================================================== Copyright (c) 2010-2015 Darkstar Dev Teams This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ This file is part of DarkStar-server source code. =========================================================================== */ #include "../../common/socket.h" #include "char_sync.h" #include "../entities/charentity.h" CCharSyncPacket::CCharSyncPacket(CCharEntity* PChar) { this->type = 0x67; this->size = 0x14; WBUFB(data,(0x04)) = 0x02; WBUFB(data,(0x05)) = 0x09; WBUFW(data,(0x06)) = PChar->targid; WBUFL(data,(0x08)) = PChar->id; WBUFB(data,(0x10)) = PChar->StatusEffectContainer->HasStatusEffect(EFFECT_LEVEL_SYNC) ? 4 : 0; // 0x02 - Campaign Battle, 0x04 - Level Sync WBUFB(data,(0x25)) = PChar->jobs.job[PChar->GetMJob()]; // реальный уровень персонажа (при ограничении уровня отличается от m_mlvl) }
n0xus/darkstar
src/map/packets/char_sync.cpp
C++
gpl-3.0
1,592
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Statistics.php 20096 2010-01-06 02:05:09Z bkarwin $ */ /** * @see Zend_Gdata_Extension */ #require_once 'Zend/Gdata/Extension.php'; /** * Represents the yt:statistics element used by the YouTube data API * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_YouTube_Extension_Statistics extends Zend_Gdata_Extension { protected $_rootNamespace = 'yt'; protected $_rootElement = 'statistics'; /** * The videoWatchCount attribute specifies the number of videos * that a user has watched on YouTube. The videoWatchCount attribute * is only specified when the <yt:statistics> tag appears within a * user profile entry. * * @var integer */ protected $_videoWatchCount = null; /** * When the viewCount attribute refers to a video entry, the attribute * specifies the number of times that the video has been viewed. * When the viewCount attribute refers to a user profile, the attribute * specifies the number of times that the user's profile has been * viewed. * * @var integer */ protected $_viewCount = null; /** * The subscriberCount attribute specifies the number of YouTube users * who have subscribed to a particular user's YouTube channel. * The subscriberCount attribute is only specified when the * <yt:statistics> tag appears within a user profile entry. * * @var integer */ protected $_subscriberCount = null; /** * The lastWebAccess attribute indicates the most recent time that * a particular user used YouTube. * * @var string */ protected $_lastWebAccess = null; /** * The favoriteCount attribute specifies the number of YouTube users * who have added a video to their list of favorite videos. The * favoriteCount attribute is only specified when the * <yt:statistics> tag appears within a video entry. * * @var integer */ protected $_favoriteCount = null; /** * Constructs a new Zend_Gdata_YouTube_Extension_Statistics object. * @param string $viewCount(optional) The viewCount value * @param string $videoWatchCount(optional) The videoWatchCount value * @param string $subscriberCount(optional) The subscriberCount value * @param string $lastWebAccess(optional) The lastWebAccess value * @param string $favoriteCount(optional) The favoriteCount value */ public function __construct($viewCount = null, $videoWatchCount = null, $subscriberCount = null, $lastWebAccess = null, $favoriteCount = null) { $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces); parent::__construct(); $this->_viewCount = $viewCount; $this->_videoWatchCount = $videoWatchCount; $this->_subscriberCount = $subscriberCount; $this->_lastWebAccess = $lastWebAccess; $this->_favoriteCount = $favoriteCount; } /** * Retrieves a DOMElement which corresponds to this element and all * child properties. This is used to build an entry back into a DOM * and eventually XML text for sending to the server upon updates, or * for application storage/persistence. * * @param DOMDocument $doc The DOMDocument used to construct DOMElements * @return DOMElement The DOMElement representing this element and all * child properties. */ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_videoWatchCount !== null) { $element->setAttribute('watchCount', $this->_videoWatchCount); } if ($this->_viewCount !== null) { $element->setAttribute('viewCount', $this->_viewCount); } if ($this->_subscriberCount !== null) { $element->setAttribute('subscriberCount', $this->_subscriberCount); } if ($this->_lastWebAccess !== null) { $element->setAttribute('lastWebAccess', $this->_lastWebAccess); } if ($this->_favoriteCount !== null) { $element->setAttribute('favoriteCount', $this->_favoriteCount); } return $element; } /** * Given a DOMNode representing an attribute, tries to map the data into * instance members. If no mapping is defined, the name and valueare * stored in an array. * TODO: Convert attributes to proper types * * @param DOMNode $attribute The DOMNode attribute needed to be handled */ protected function takeAttributeFromDOM($attribute) { switch ($attribute->localName) { case 'videoWatchCount': $this->_videoWatchCount = $attribute->nodeValue; break; case 'viewCount': $this->_viewCount = $attribute->nodeValue; break; case 'subscriberCount': $this->_subscriberCount = $attribute->nodeValue; break; case 'lastWebAccess': $this->_lastWebAccess = $attribute->nodeValue; break; case 'favoriteCount': $this->_favoriteCount = $attribute->nodeValue; break; default: parent::takeAttributeFromDOM($attribute); } } /** * Get the value for this element's viewCount attribute. * * @return int The value associated with this attribute. */ public function getViewCount() { return $this->_viewCount; } /** * Set the value for this element's viewCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setViewCount($value) { $this->_viewCount = $value; return $this; } /** * Get the value for this element's videoWatchCount attribute. * * @return int The value associated with this attribute. */ public function getVideoWatchCount() { return $this->_videoWatchCount; } /** * Set the value for this element's videoWatchCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setVideoWatchCount($value) { $this->_videoWatchCount = $value; return $this; } /** * Get the value for this element's subscriberCount attribute. * * @return int The value associated with this attribute. */ public function getSubscriberCount() { return $this->_subscriberCount; } /** * Set the value for this element's subscriberCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setSubscriberCount($value) { $this->_subscriberCount = $value; return $this; } /** * Get the value for this element's lastWebAccess attribute. * * @return int The value associated with this attribute. */ public function getLastWebAccess() { return $this->_lastWebAccess; } /** * Set the value for this element's lastWebAccess attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setLastWebAccess($value) { $this->_lastWebAccess = $value; return $this; } /** * Get the value for this element's favoriteCount attribute. * * @return int The value associated with this attribute. */ public function getFavoriteCount() { return $this->_favoriteCount; } /** * Set the value for this element's favoriteCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setFavoriteCount($value) { $this->_favoriteCount = $value; return $this; } /** * Magic toString method allows using this directly via echo * Works best in PHP >= 4.2.0 * * @return string */ public function __toString() { return 'View Count=' . $this->_viewCount . ' VideoWatchCount=' . $this->_videoWatchCount . ' SubscriberCount=' . $this->_subscriberCount . ' LastWebAccess=' . $this->_lastWebAccess . ' FavoriteCount=' . $this->_favoriteCount; } }
dbashyal/MagentoStarterBase
trunk/lib/Zend/Gdata/YouTube/Extension/Statistics.php
PHP
lgpl-3.0
9,761
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.glacier.model.transform; import com.amazonaws.AmazonServiceException; import com.amazonaws.transform.GlacierErrorUnmarshaller; import com.amazonaws.util.json.JSONObject; import com.amazonaws.services.glacier.model.InvalidParameterValueException; public class InvalidParameterValueExceptionUnmarshaller extends GlacierErrorUnmarshaller { public InvalidParameterValueExceptionUnmarshaller() { super(InvalidParameterValueException.class); } @Override public boolean match(String errorTypeFromHeader, JSONObject json) throws Exception { if (errorTypeFromHeader == null) { // Parse error type from the JSON content if it's not available in the response headers String errorCodeFromContent = parseErrorCode(json); return (errorCodeFromContent != null && errorCodeFromContent.equals("InvalidParameterValueException")); } else { return errorTypeFromHeader.equals("InvalidParameterValueException"); } } @Override public AmazonServiceException unmarshall(JSONObject json) throws Exception { InvalidParameterValueException e = (InvalidParameterValueException)super.unmarshall(json); e.setErrorCode("InvalidParameterValueException"); e.setType(parseMember("Type", json)); e.setCode(parseMember("Code", json)); return e; } }
mahaliachante/aws-sdk-java
aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/transform/InvalidParameterValueExceptionUnmarshaller.java
Java
apache-2.0
2,012
/* * Copyright (C) 2010-2013 The SINA WEIBO Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sina.weibo.sdk.openapi.models; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * 微博结构体。 * * @author SINA * @since 2013-11-22 */ public class Status { /** 微博创建时间 */ public String created_at; /** 微博ID */ public String id; /** 微博MID */ public String mid; /** 字符串型的微博ID */ public String idstr; /** 微博信息内容 */ public String text; /** 微博来源 */ public String source; /** 是否已收藏,true:是,false:否 */ public boolean favorited; /** 是否被截断,true:是,false:否 */ public boolean truncated; /**(暂未支持)回复ID */ public String in_reply_to_status_id; /**(暂未支持)回复人UID */ public String in_reply_to_user_id; /**(暂未支持)回复人昵称 */ public String in_reply_to_screen_name; /** 缩略图片地址(小图),没有时不返回此字段 */ public String thumbnail_pic; /** 中等尺寸图片地址(中图),没有时不返回此字段 */ public String bmiddle_pic; /** 原始图片地址(原图),没有时不返回此字段 */ public String original_pic; /** 地理信息字段 */ public Geo geo; /** 微博作者的用户信息字段 */ public User user; /** 被转发的原微博信息字段,当该微博为转发微博时返回 */ public Status retweeted_status; /** 转发数 */ public int reposts_count; /** 评论数 */ public int comments_count; /** 表态数 */ public int attitudes_count; /** 暂未支持 */ public int mlevel; /** * 微博的可见性及指定可见分组信息。该 object 中 type 取值, * 0:普通微博,1:私密微博,3:指定分组微博,4:密友微博; * list_id为分组的组号 */ public Visible visible; /** 微博配图地址。多图时返回多图链接。无配图返回"[]" */ public ArrayList<String> pic_urls; /** 微博流内的推广微博ID */ //public Ad ad; public static Status parse(String jsonString) { try { JSONObject jsonObject = new JSONObject(jsonString); return Status.parse(jsonObject); } catch (JSONException e) { e.printStackTrace(); } return null; } public static Status parse(JSONObject jsonObject) { if (null == jsonObject) { return null; } Status status = new Status(); status.created_at = jsonObject.optString("created_at"); status.id = jsonObject.optString("id"); status.mid = jsonObject.optString("mid"); status.idstr = jsonObject.optString("idstr"); status.text = jsonObject.optString("text"); status.source = jsonObject.optString("source"); status.favorited = jsonObject.optBoolean("favorited", false); status.truncated = jsonObject.optBoolean("truncated", false); // Have NOT supported status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id"); status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id"); status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name"); status.thumbnail_pic = jsonObject.optString("thumbnail_pic"); status.bmiddle_pic = jsonObject.optString("bmiddle_pic"); status.original_pic = jsonObject.optString("original_pic"); status.geo = Geo.parse(jsonObject.optJSONObject("geo")); status.user = User.parse(jsonObject.optJSONObject("user")); status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status")); status.reposts_count = jsonObject.optInt("reposts_count"); status.comments_count = jsonObject.optInt("comments_count"); status.attitudes_count = jsonObject.optInt("attitudes_count"); status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported status.visible = Visible.parse(jsonObject.optJSONObject("visible")); JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls"); if (picUrlsArray != null && picUrlsArray.length() > 0) { int length = picUrlsArray.length(); status.pic_urls = new ArrayList<String>(length); JSONObject tmpObject = null; for (int ix = 0; ix < length; ix++) { tmpObject = picUrlsArray.optJSONObject(ix); if (tmpObject != null) { status.pic_urls.add(tmpObject.optString("thumbnail_pic")); } } } //status.ad = jsonObject.optString("ad", ""); return status; } }
zjupure/SneezeReader
weibosdk/src/main/java/com/sina/weibo/sdk/openapi/models/Status.java
Java
apache-2.0
5,659
// Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'> // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(window.crypto && window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes;
enketosurvey/mo
www/lib/rsa/rng.js
JavaScript
apache-2.0
2,112
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.aggregations.bucket.filter; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.search.aggregations.AggregationStreams; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.bucket.InternalSingleBucketAggregation; import java.io.IOException; /** * */ public class InternalFilter extends InternalSingleBucketAggregation implements Filter { public final static Type TYPE = new Type("filter"); public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() { @Override public InternalFilter readResult(StreamInput in) throws IOException { InternalFilter result = new InternalFilter(); result.readFrom(in); return result; } }; public static void registerStreams() { AggregationStreams.registerStream(STREAM, TYPE.stream()); } InternalFilter() {} // for serialization InternalFilter(String name, long docCount, InternalAggregations subAggregations) { super(name, docCount, subAggregations); } @Override public Type type() { return TYPE; } @Override protected InternalSingleBucketAggregation newAggregation(String name, long docCount, InternalAggregations subAggregations) { return new InternalFilter(name, docCount, subAggregations); } }
corochoone/elasticsearch
src/main/java/org/elasticsearch/search/aggregations/bucket/filter/InternalFilter.java
Java
apache-2.0
2,222
/* ========================================================== * bootstrap-formhelpers-countries.en_US.js * https://github.com/vlamanna/BootstrapFormHelpers * ========================================================== * Copyright 2012 Vincent Lamanna * * 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. * ========================================================== */ var BFHCountriesList = { 'AF': 'Afghanistan', 'AL': 'Albania', 'DZ': 'Algeria', 'AS': 'American Samoa', 'AD': 'Andorra', 'AO': 'Angola', 'AI': 'Anguilla', 'AQ': 'Antarctica', 'AG': 'Antigua and Barbuda', 'AR': 'Argentina', 'AM': 'Armenia', 'AW': 'Aruba', 'AU': 'Australia', 'AT': 'Austria', 'AZ': 'Azerbaijan', 'BH': 'Bahrain', 'BD': 'Bangladesh', 'BB': 'Barbados', 'BY': 'Belarus', 'BE': 'Belgium', 'BZ': 'Belize', 'BJ': 'Benin', 'BM': 'Bermuda', 'BT': 'Bhutan', 'BO': 'Bolivia', 'BA': 'Bosnia and Herzegovina', 'BW': 'Botswana', 'BV': 'Bouvet Island', 'BR': 'Brazil', 'IO': 'British Indian Ocean Territory', 'VG': 'British Virgin Islands', 'BN': 'Brunei', 'BG': 'Bulgaria', 'BF': 'Burkina Faso', 'BI': 'Burundi', 'CI': 'Côte d\'Ivoire', 'KH': 'Cambodia', 'CM': 'Cameroon', 'CA': 'Canada', 'CV': 'Cape Verde', 'KY': 'Cayman Islands', 'CF': 'Central African Republic', 'TD': 'Chad', 'CL': 'Chile', 'CN': 'China', 'CX': 'Christmas Island', 'CC': 'Cocos (Keeling) Islands', 'CO': 'Colombia', 'KM': 'Comoros', 'CG': 'Congo', 'CK': 'Cook Islands', 'CR': 'Costa Rica', 'HR': 'Croatia', 'CU': 'Cuba', 'CY': 'Cyprus', 'CZ': 'Czech Republic', 'CD': 'Democratic Republic of the Congo', 'DK': 'Denmark', 'DJ': 'Djibouti', 'DM': 'Dominica', 'DO': 'Dominican Republic', 'TP': 'East Timor', 'EC': 'Ecuador', 'EG': 'Egypt', 'SV': 'El Salvador', 'GQ': 'Equatorial Guinea', 'ER': 'Eritrea', 'EE': 'Estonia', 'ET': 'Ethiopia', 'FO': 'Faeroe Islands', 'FK': 'Falkland Islands', 'FJ': 'Fiji', 'FI': 'Finland', 'MK': 'Former Yugoslav Republic of Macedonia', 'FR': 'France', 'FX': 'France, Metropolitan', 'GF': 'French Guiana', 'PF': 'French Polynesia', 'TF': 'French Southern Territories', 'GA': 'Gabon', 'GE': 'Georgia', 'DE': 'Germany', 'GH': 'Ghana', 'GI': 'Gibraltar', 'GR': 'Greece', 'GL': 'Greenland', 'GD': 'Grenada', 'GP': 'Guadeloupe', 'GU': 'Guam', 'GT': 'Guatemala', 'GN': 'Guinea', 'GW': 'Guinea-Bissau', 'GY': 'Guyana', 'HT': 'Haiti', 'HM': 'Heard and Mc Donald Islands', 'HN': 'Honduras', 'HK': 'Hong Kong', 'HU': 'Hungary', 'IS': 'Iceland', 'IN': 'India', 'ID': 'Indonesia', 'IR': 'Iran', 'IQ': 'Iraq', 'IE': 'Ireland', 'IL': 'Israel', 'IT': 'Italy', 'JM': 'Jamaica', 'JP': 'Japan', 'JO': 'Jordan', 'KZ': 'Kazakhstan', 'KE': 'Kenya', 'KI': 'Kiribati', 'KW': 'Kuwait', 'KG': 'Kyrgyzstan', 'LA': 'Laos', 'LV': 'Latvia', 'LB': 'Lebanon', 'LS': 'Lesotho', 'LR': 'Liberia', 'LY': 'Libya', 'LI': 'Liechtenstein', 'LT': 'Lithuania', 'LU': 'Luxembourg', 'MO': 'Macau', 'MG': 'Madagascar', 'MW': 'Malawi', 'MY': 'Malaysia', 'MV': 'Maldives', 'ML': 'Mali', 'MT': 'Malta', 'MH': 'Marshall Islands', 'MQ': 'Martinique', 'MR': 'Mauritania', 'MU': 'Mauritius', 'YT': 'Mayotte', 'MX': 'Mexico', 'FM': 'Micronesia', 'MD': 'Moldova', 'MC': 'Monaco', 'MN': 'Mongolia', 'ME': 'Montenegro', 'MS': 'Montserrat', 'MA': 'Morocco', 'MZ': 'Mozambique', 'MM': 'Myanmar', 'NA': 'Namibia', 'NR': 'Nauru', 'NP': 'Nepal', 'NL': 'Netherlands', 'AN': 'Netherlands Antilles', 'NC': 'New Caledonia', 'NZ': 'New Zealand', 'NI': 'Nicaragua', 'NE': 'Niger', 'NG': 'Nigeria', 'NU': 'Niue', 'NF': 'Norfolk Island', 'KP': 'North Korea', 'MP': 'Northern Marianas', 'NO': 'Norway', 'OM': 'Oman', 'PK': 'Pakistan', 'PW': 'Palau', 'PS': 'Palestine', 'PA': 'Panama', 'PG': 'Papua New Guinea', 'PY': 'Paraguay', 'PE': 'Peru', 'PH': 'Philippines', 'PN': 'Pitcairn Islands', 'PL': 'Poland', 'PT': 'Portugal', 'PR': 'Puerto Rico', 'QA': 'Qatar', 'RE': 'Reunion', 'RO': 'Romania', 'RU': 'Russia', 'RW': 'Rwanda', 'ST': 'São Tomé and Príncipe', 'SH': 'Saint Helena', 'PM': 'St. Pierre and Miquelon', 'KN': 'Saint Kitts and Nevis', 'LC': 'Saint Lucia', 'VC': 'Saint Vincent and the Grenadines', 'WS': 'Samoa', 'SM': 'San Marino', 'SA': 'Saudi Arabia', 'SN': 'Senegal', 'RS': 'Serbia', 'SC': 'Seychelles', 'SL': 'Sierra Leone', 'SG': 'Singapore', 'SK': 'Slovakia', 'SI': 'Slovenia', 'SB': 'Solomon Islands', 'SO': 'Somalia', 'ZA': 'South Africa', 'GS': 'South Georgia and the South Sandwich Islands', 'KR': 'South Korea', 'ES': 'Spain', 'LK': 'Sri Lanka', 'SD': 'Sudan', 'SR': 'Suriname', 'SJ': 'Svalbard and Jan Mayen Islands', 'SZ': 'Swaziland', 'SE': 'Sweden', 'CH': 'Switzerland', 'SY': 'Syria', 'TW': 'Taiwan', 'TJ': 'Tajikistan', 'TZ': 'Tanzania', 'TH': 'Thailand', 'BS': 'The Bahamas', 'GM': 'The Gambia', 'TG': 'Togo', 'TK': 'Tokelau', 'TO': 'Tonga', 'TT': 'Trinidad and Tobago', 'TN': 'Tunisia', 'TR': 'Turkey', 'TM': 'Turkmenistan', 'TC': 'Turks and Caicos Islands', 'TV': 'Tuvalu', 'VI': 'US Virgin Islands', 'UG': 'Uganda', 'UA': 'Ukraine', 'AE': 'United Arab Emirates', 'GB': 'United Kingdom', 'US': 'United States', 'UM': 'United States Minor Outlying Islands', 'UY': 'Uruguay', 'UZ': 'Uzbekistan', 'VU': 'Vanuatu', 'VA': 'Vatican City', 'VE': 'Venezuela', 'VN': 'Vietnam', 'WF': 'Wallis and Futuna Islands', 'EH': 'Western Sahara', 'YE': 'Yemen', 'ZM': 'Zambia', 'ZW': 'Zimbabwe' };
Eonic/EonicWeb5
wwwroot/ewcommon/bs3/addons/formHelpers/js/lang/en_US/bootstrap-formhelpers-countries.en_US.js
JavaScript
apache-2.0
6,201
/*before*/"use strict"; /*after*/foo();
zjmiller/babel
packages/babel-plugin-transform-strict-mode/test/fixtures/auxiliary-comment/use-strict-add/expected.js
JavaScript
mit
41
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.xsom.impl.parser; import com.sun.xml.internal.xsom.XSSchemaSet; import com.sun.xml.internal.xsom.impl.ElementDecl; import com.sun.xml.internal.xsom.impl.SchemaImpl; import com.sun.xml.internal.xsom.impl.SchemaSetImpl; import com.sun.xml.internal.xsom.parser.AnnotationParserFactory; import com.sun.xml.internal.xsom.parser.XMLParser; import com.sun.xml.internal.xsom.parser.XSOMParser; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * Provides context information to be used by {@link NGCCRuntimeEx}s. * * <p> * This class does the actual processing for {@link XSOMParser}, * but to hide the details from the public API, this class in * a different package. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class ParserContext { /** SchemaSet to which a newly parsed schema is put in. */ public final SchemaSetImpl schemaSet = new SchemaSetImpl(); private final XSOMParser owner; final XMLParser parser; private final Vector<Patch> patchers = new Vector<Patch>(); private final Vector<Patch> errorCheckers = new Vector<Patch>(); /** * Documents that are parsed already. Used to avoid cyclic inclusion/double * inclusion of schemas. Set of {@link SchemaDocumentImpl}s. * * The actual data structure is map from {@link SchemaDocumentImpl} to itself, * so that we can access the {@link SchemaDocumentImpl} itself. */ public final Map<SchemaDocumentImpl, SchemaDocumentImpl> parsedDocuments = new HashMap<SchemaDocumentImpl, SchemaDocumentImpl>(); public ParserContext( XSOMParser owner, XMLParser parser ) { this.owner = owner; this.parser = parser; try { parse(new InputSource(ParserContext.class.getResource("datatypes.xsd").toExternalForm())); SchemaImpl xs = (SchemaImpl) schemaSet.getSchema("http://www.w3.org/2001/XMLSchema"); xs.addSimpleType(schemaSet.anySimpleType,true); xs.addComplexType(schemaSet.anyType,true); } catch( SAXException e ) { // this must be a bug of XSOM if(e.getException()!=null) e.getException().printStackTrace(); else e.printStackTrace(); throw new InternalError(); } } public EntityResolver getEntityResolver() { return owner.getEntityResolver(); } public AnnotationParserFactory getAnnotationParserFactory() { return owner.getAnnotationParserFactory(); } /** * Parses a new XML Schema document. */ public void parse( InputSource source ) throws SAXException { newNGCCRuntime().parseEntity(source,false,null,null); } public XSSchemaSet getResult() throws SAXException { // run all the patchers for (Patch patcher : patchers) patcher.run(); patchers.clear(); // build the element substitutability map Iterator itr = schemaSet.iterateElementDecls(); while(itr.hasNext()) ((ElementDecl)itr.next()).updateSubstitutabilityMap(); // run all the error checkers for (Patch patcher : errorCheckers) patcher.run(); errorCheckers.clear(); if(hadError) return null; else return schemaSet; } public NGCCRuntimeEx newNGCCRuntime() { return new NGCCRuntimeEx(this); } /** Once an error is detected, this flag is set to true. */ private boolean hadError = false; /** Turns on the error flag. */ void setErrorFlag() { hadError=true; } /** * PatchManager implementation, which is accessible only from * NGCCRuntimEx. */ final PatcherManager patcherManager = new PatcherManager() { public void addPatcher( Patch patch ) { patchers.add(patch); } public void addErrorChecker( Patch patch ) { errorCheckers.add(patch); } public void reportError( String msg, Locator src ) throws SAXException { // set a flag to true to avoid returning a corrupted object. setErrorFlag(); SAXParseException e = new SAXParseException(msg,src); if(errorHandler==null) throw e; else errorHandler.error(e); } }; /** * ErrorHandler proxy to turn on the hadError flag when an error * is found. */ final ErrorHandler errorHandler = new ErrorHandler() { private ErrorHandler getErrorHandler() { if( owner.getErrorHandler()==null ) return noopHandler; else return owner.getErrorHandler(); } public void warning(SAXParseException e) throws SAXException { getErrorHandler().warning(e); } public void error(SAXParseException e) throws SAXException { setErrorFlag(); getErrorHandler().error(e); } public void fatalError(SAXParseException e) throws SAXException { setErrorFlag(); getErrorHandler().fatalError(e); } }; /** * {@link ErrorHandler} that does nothing. */ final ErrorHandler noopHandler = new ErrorHandler() { public void warning(SAXParseException e) { } public void error(SAXParseException e) { } public void fatalError(SAXParseException e) { setErrorFlag(); } }; }
rokn/Count_Words_2015
testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/impl/parser/ParserContext.java
Java
mit
6,989
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class StringInfoGetTextElementEnumerator { public static IEnumerable<object[]> GetTextElementEnumerator_TestData() { yield return new object[] { "", 0, new string[0] }; // Empty string yield return new object[] { "Hello", 5, new string[0] }; // Index = string.Length // Surrogate pair yield return new object[] { "s\uDBFF\uDFFF$", 0, new string[] { "s", "\uDBFF\uDFFF", "$" } }; yield return new object[] { "s\uDBFF\uDFFF$", 1, new string[] { "\uDBFF\uDFFF", "$" } }; // Combining characters yield return new object[] { "13229^a\u20D1a", 6, new string[] { "a\u20D1", "a" } }; yield return new object[] { "13229^a\u20D1a", 0, new string[] { "1", "3", "2", "2", "9", "^", "a\u20D1", "a" } }; // Single base and combining character yield return new object[] { "a\u0300", 0, new string[] { "a\u0300" } }; yield return new object[] { "a\u0300", 1, new string[] { "\u0300" } }; // Lone combining character yield return new object[] { "\u0300\u0300", 0, new string[] { "\u0300", "\u0300" } }; } [Theory] [MemberData(nameof(GetTextElementEnumerator_TestData))] public void GetTextElementEnumerator(string str, int index, string[] expected) { if (index == 0) { TextElementEnumerator basicEnumerator = StringInfo.GetTextElementEnumerator(str); int basicCounter = 0; while (basicEnumerator.MoveNext()) { Assert.Equal(expected[basicCounter], basicEnumerator.Current.ToString()); basicCounter++; } Assert.Equal(expected.Length, basicCounter); } TextElementEnumerator indexedEnumerator = StringInfo.GetTextElementEnumerator(str, index); int indexedCounter = 0; while (indexedEnumerator.MoveNext()) { Assert.Equal(expected[indexedCounter], indexedEnumerator.Current.ToString()); indexedCounter++; } Assert.Equal(expected.Length, indexedCounter); } [Fact] public void GetTextElementEnumerator_Invalid() { Assert.Throws<ArgumentNullException>("str", () => StringInfo.GetTextElementEnumerator(null)); // Str is null Assert.Throws<ArgumentNullException>("str", () => StringInfo.GetTextElementEnumerator(null, 0)); // Str is null Assert.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetTextElementEnumerator("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetTextElementEnumerator("abc", 4)); // Index > str.Length } } }
ellismg/corefx
src/System.Globalization/tests/StringInfo/StringInfoGetTextElementEnumerator.cs
C#
mit
3,157
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /* * Based on the Reverse Engineering work of Christophe Fontanel, * maintainer of the Dungeon Master Encyclopaedia (http://dmweb.free.fr/) */ #include "graphics/surface.h" #include "graphics/thumbnail.h" #include "dm/inventory.h" #include "dm/dungeonman.h" #include "dm/eventman.h" #include "dm/group.h" #include "dm/menus.h" #include "dm/gfx.h" #include "dm/text.h" #include "dm/objectman.h" #include "dm/timeline.h" #include "dm/projexpl.h" #include "dm/sounds.h" namespace DM { void InventoryMan::initConstants() { static const char* skillLevelNamesEN[15] = {"NEOPHYTE", "NOVICE", "APPRENTICE", "JOURNEYMAN", "CRAFTSMAN", "ARTISAN", "ADEPT", "EXPERT", "` MASTER", "a MASTER","b MASTER", "c MASTER", "d MASTER", "e MASTER", "ARCHMASTER"}; static const char* skillLevelNamesDE[15] = {"ANFAENGER", "NEULING", "LEHRLING", "ARBEITER", "GESELLE", "HANDWERKR", "FACHMANN", "EXPERTE", "` MEISTER", "a MEISTER", "b MEISTER", "c MEISTER", "d MEISTER", "e MEISTER", "ERZMEISTR"}; static const char* skillLevelNamesFR[15] = {"NEOPHYTE", "NOVICE", "APPRENTI", "COMPAGNON", "ARTISAN", "PATRON", "ADEPTE", "EXPERT", "MAITRE '", "MAITRE a", "MAITRE b", "MAITRE c", "MAITRE d", "MAITRE e", "SUR-MAITRE"}; const char **translatedSkillLevel; switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: translatedSkillLevel = skillLevelNamesEN; break; case Common::DE_DEU: translatedSkillLevel = skillLevelNamesDE; break; case Common::FR_FRA: translatedSkillLevel = skillLevelNamesFR; break; } for (int i = 0; i < 15; ++i) _skillLevelNames[i] = translatedSkillLevel[i]; _boxPanel = Box(80, 223, 52, 124); // @ G0032_s_Graphic562_Box_Panel } InventoryMan::InventoryMan(DMEngine *vm) : _vm(vm) { _inventoryChampionOrdinal = 0; _panelContent = kDMPanelContentFoodWaterPoisoned; for (uint16 i = 0; i < 8; ++i) _chestSlots[i] = Thing(0); _openChest = _vm->_thingNone; _objDescTextXpos = 0; _objDescTextYpos = 0; for (int i = 0; i < 15; i++) _skillLevelNames[i] = nullptr; initConstants(); } void InventoryMan::toggleInventory(ChampionIndex championIndex) { static Box boxFloppyZzzCross(174, 218, 2, 12); // @ G0041_s_Graphic562_Box_ViewportFloppyZzzCross DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; if ((championIndex != kDMChampionCloseInventory) && !championMan._champions[championIndex]._currHealth) return; if (_vm->_pressingMouth || _vm->_pressingEye) return; _vm->_stopWaitingForPlayerInput = true; uint16 inventoryChampionOrdinal = _inventoryChampionOrdinal; if (_vm->indexToOrdinal(championIndex) == inventoryChampionOrdinal) championIndex = kDMChampionCloseInventory; _vm->_eventMan->showMouse(); if (inventoryChampionOrdinal) { _inventoryChampionOrdinal = _vm->indexToOrdinal(kDMChampionNone); closeChest(); Champion *champion = &championMan._champions[_vm->ordinalToIndex(inventoryChampionOrdinal)]; if (champion->_currHealth && !championMan._candidateChampionOrdinal) { setFlag(champion->_attributes, kDMAttributeStatusBox); championMan.drawChampionState((ChampionIndex)_vm->ordinalToIndex(inventoryChampionOrdinal)); } if (championMan._partyIsSleeping) { _vm->_eventMan->hideMouse(); return; } if (championIndex == kDMChampionCloseInventory) { _vm->_eventMan->_refreshMousePointerInMainLoop = true; _vm->_menuMan->drawMovementArrows(); _vm->_eventMan->hideMouse(); _vm->_eventMan->_secondaryMouseInput = _vm->_eventMan->_secondaryMouseInputMovement; _vm->_eventMan->_secondaryKeyboardInput = _vm->_eventMan->_secondaryKeyboardInputMovement; _vm->_eventMan->discardAllInput(); display.drawFloorAndCeiling(); return; } } display._useByteBoxCoordinates = false; _inventoryChampionOrdinal = _vm->indexToOrdinal(championIndex); if (!inventoryChampionOrdinal) display.shadeScreenBox(&display._boxMovementArrows, kDMColorBlack); Champion *champion = &championMan._champions[championIndex]; display.loadIntoBitmap(kDMGraphicIdxInventory, display._bitmapViewport); if (championMan._candidateChampionOrdinal) display.fillBoxBitmap(display._bitmapViewport, boxFloppyZzzCross, kDMColorDarkestGray, k112_byteWidthViewport, k136_heightViewport); switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "HEALTH"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "STAMINA"); break; case Common::DE_DEU: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "GESUND"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "KRAFT"); break; case Common::FR_FRA: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "SANTE"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "VIGUEUR"); break; } _vm->_textMan->printToViewport(5, 132, kDMColorLightestGray, "MANA"); for (uint16 i = kDMSlotReadyHand; i < kDMSlotChest1; i++) championMan.drawSlot(championIndex, i); setFlag(champion->_attributes, kDMAttributeViewport | kDMAttributeStatusBox | kDMAttributePanel | kDMAttributeLoad | kDMAttributeStatistics | kDMAttributeNameTitle); championMan.drawChampionState(championIndex); _vm->_eventMan->_mousePointerBitmapUpdated = true; _vm->_eventMan->hideMouse(); _vm->_eventMan->_secondaryMouseInput = _vm->_eventMan->_secondaryMouseInputChampionInventory; _vm->_eventMan->_secondaryKeyboardInput = nullptr; _vm->_eventMan->discardAllInput(); } void InventoryMan::drawStatusBoxPortrait(ChampionIndex championIndex) { DisplayMan &dispMan = *_vm->_displayMan; dispMan._useByteBoxCoordinates = false; Box box; box._rect.top = 0; box._rect.bottom = 28; box._rect.left = championIndex * kDMChampionStatusBoxSpacing + 7; box._rect.right = box._rect.left + 31; dispMan.blitToScreen(_vm->_championMan->_champions[championIndex]._portrait, &box, k16_byteWidth, kDMColorNoTransparency, 29); } void InventoryMan::drawPanelHorizontalBar(int16 x, int16 y, int16 pixelWidth, Color color) { DisplayMan &display = *_vm->_displayMan; Box box; box._rect.left = x; box._rect.right = box._rect.left + pixelWidth; box._rect.top = y; box._rect.bottom = box._rect.top + 6; display._useByteBoxCoordinates = false; display.fillBoxBitmap(display._bitmapViewport, box, color, k112_byteWidthViewport, k136_heightViewport); } void InventoryMan::drawPanelFoodOrWaterBar(int16 amount, int16 y, Color color) { if (amount < -512) color = kDMColorRed; else if (amount < 0) color = kDMColorYellow; int16 pixelWidth = amount + 1024; if (pixelWidth == 3072) pixelWidth = 3071; pixelWidth /= 32; drawPanelHorizontalBar(115, y + 2, pixelWidth, kDMColorBlack); drawPanelHorizontalBar(113, y, pixelWidth, color); } void InventoryMan::drawPanelFoodWaterPoisoned() { static Box boxFood(112, 159, 60, 68); // @ G0035_s_Graphic562_Box_Food static Box boxWater(112, 159, 83, 91); // @ G0036_s_Graphic562_Box_Water static Box boxPoisoned(112, 207, 105, 119); // @ G0037_s_Graphic562_Box_Poisoned Champion &champ = _vm->_championMan->_champions[_inventoryChampionOrdinal]; closeChest(); DisplayMan &dispMan = *_vm->_displayMan; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k24_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k24_byteWidth, kDMColorDarkestGray, 9); break; case Common::DE_DEU: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k32_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k32_byteWidth, kDMColorDarkestGray, 9); break; case Common::FR_FRA: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k48_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k24_byteWidth, kDMColorDarkestGray, 9); break; } if (champ._poisonEventCount) dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPoisionedLabel), boxPoisoned, k48_byteWidth, kDMColorDarkestGray, 15); drawPanelFoodOrWaterBar(champ._food, 69, kDMColorLightBrown); drawPanelFoodOrWaterBar(champ._water, 92, kDMColorBlue); } void InventoryMan::drawPanelResurrectReincarnate() { DisplayMan &display = *_vm->_displayMan; _panelContent = kDMPanelContentResurrectReincarnate; display.blitToViewport(display.getNativeBitmapOrGraphic(kDMGraphicIdxPanelResurectReincarnate), _boxPanel, k72_byteWidth, kDMColorDarkGreen, 73); } void InventoryMan::drawPanel() { closeChest(); ChampionMan &cm = *_vm->_championMan; if (cm._candidateChampionOrdinal) { drawPanelResurrectReincarnate(); return; } Thing thing = cm._champions[_vm->ordinalToIndex(_inventoryChampionOrdinal)].getSlot(kDMSlotActionHand); _panelContent = kDMPanelContentFoodWaterPoisoned; switch (thing.getType()) { case kDMThingTypeContainer: _panelContent = kDMPanelContentChest; break; case kDMThingTypeScroll: _panelContent = kDMPanelContentScroll; break; default: thing = _vm->_thingNone; break; } if (thing == _vm->_thingNone) drawPanelFoodWaterPoisoned(); else drawPanelObject(thing, false); } void InventoryMan::closeChest() { DungeonMan &dunMan = *_vm->_dungeonMan; bool processFirstChestSlot = true; if (_openChest == _vm->_thingNone) return; Container *container = (Container *)dunMan.getThingData(_openChest); _openChest = _vm->_thingNone; container->getSlot() = _vm->_thingEndOfList; Thing prevThing; for (int16 chestSlotIndex = 0; chestSlotIndex < 8; ++chestSlotIndex) { Thing thing = _chestSlots[chestSlotIndex]; if (thing != _vm->_thingNone) { _chestSlots[chestSlotIndex] = _vm->_thingNone; // CHANGE8_09_FIX if (processFirstChestSlot) { processFirstChestSlot = false; *dunMan.getThingData(thing) = _vm->_thingEndOfList.toUint16(); container->getSlot() = prevThing = thing; } else { dunMan.linkThingToList(thing, prevThing, kDMMapXNotOnASquare, 0); prevThing = thing; } } } } void InventoryMan::drawPanelScrollTextLine(int16 yPos, char *text) { for (char *iter = text; *iter != '\0'; ++iter) { if ((*iter >= 'A') && (*iter <= 'Z')) *iter -= 64; else if (*iter >= '{') // this branch is CHANGE5_03_IMPROVEMENT *iter -= 96; } _vm->_textMan->printToViewport(162 - (6 * strlen(text) / 2), yPos, kDMColorBlack, text, kDMColorWhite); } void InventoryMan::drawPanelScroll(Scroll *scroll) { DisplayMan &dispMan = *_vm->_displayMan; char stringFirstLine[300]; _vm->_dungeonMan->decodeText(stringFirstLine, Thing(scroll->getTextStringThingIndex()), (TextType)(kDMTextTypeScroll | kDMMaskDecodeEvenIfInvisible)); char *charRed = stringFirstLine; while (*charRed && (*charRed != '\n')) charRed++; *charRed = '\0'; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelOpenScroll), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 lineCount = 1; charRed++; char *charGreen = charRed; // first char of the second line while (*charGreen) { /* BUG0_47 Graphical glitch when you open a scroll. If there is a single line of text in a scroll (with no carriage return) then charGreen points to undefined data. This may result in a graphical glitch and also corrupt other memory. This is not an issue in the original dungeons where all scrolls contain at least one carriage return character */ if (*charGreen == '\n') lineCount++; charGreen++; } if (*(charGreen - 1) != '\n') lineCount++; else if (*(charGreen - 2) == '\n') lineCount--; int16 yPos = 92 - (7 * lineCount) / 2; // center the text vertically drawPanelScrollTextLine(yPos, stringFirstLine); charGreen = charRed; while (*charGreen) { yPos += 7; while (*charRed && (*charRed != '\n')) charRed++; if (!(*charRed)) charRed[1] = '\0'; *charRed++ = '\0'; drawPanelScrollTextLine(yPos, charGreen); charGreen = charRed; } } void InventoryMan::openAndDrawChest(Thing thingToOpen, Container *chest, bool isPressingEye) { DisplayMan &dispMan = *_vm->_displayMan; ObjectMan &objMan = *_vm->_objectMan; if (_openChest == thingToOpen) return; if (_openChest != _vm->_thingNone) closeChest(); // CHANGE8_09_FIX _openChest = thingToOpen; if (!isPressingEye) { objMan.drawIconInSlotBox(kDMSlotBoxInventoryActionHand, kDMIconIndiceContainerChestOpen); } dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelOpenChest), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 chestSlotIndex = 0; Thing thing = chest->getSlot(); int16 thingCount = 0; while (thing != _vm->_thingEndOfList) { if (++thingCount > 8) break; // CHANGE8_08_FIX, make sure that no more than the first 8 objects in a chest are drawn objMan.drawIconInSlotBox(chestSlotIndex + kDMSlotBoxChestFirstSlot, objMan.getIconIndex(thing)); _chestSlots[chestSlotIndex++] = thing; thing = _vm->_dungeonMan->getNextThing(thing); } while (chestSlotIndex < 8) { objMan.drawIconInSlotBox(chestSlotIndex + kDMSlotBoxChestFirstSlot, kDMIconIndiceNone); _chestSlots[chestSlotIndex++] = _vm->_thingNone; } } void InventoryMan::drawIconToViewport(IconIndice iconIndex, int16 xPos, int16 yPos) { static byte iconBitmap[16 * 16]; Box boxIcon(xPos, xPos + 15, yPos, yPos + 15); _vm->_objectMan->extractIconFromBitmap(iconIndex, iconBitmap); _vm->_displayMan->blitToViewport(iconBitmap, boxIcon, k8_byteWidth, kDMColorNoTransparency, 16); } void InventoryMan::buildObjectAttributeString(int16 potentialAttribMask, int16 actualAttribMask, const char **attribStrings, char *destString, const char *prefixString, const char *suffixString) { uint16 identicalBitCount = 0; int16 attribMask = 1; for (uint16 stringIndex = 0; stringIndex < 16; stringIndex++, attribMask <<= 1) { if (attribMask & potentialAttribMask & actualAttribMask) identicalBitCount++; } if (identicalBitCount == 0) { *destString = '\0'; return; } strcpy(destString, prefixString); attribMask = 1; for (uint16 stringIndex = 0; stringIndex < 16; stringIndex++, attribMask <<= 1) { if (attribMask & potentialAttribMask & actualAttribMask) { strcat(destString, attribStrings[stringIndex]); if (identicalBitCount-- > 2) { strcat(destString, ", "); } else if (identicalBitCount == 1) { switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: strcat(destString, " AND "); break; case Common::DE_DEU: strcat(destString, " UND "); break; case Common::FR_FRA: strcat(destString, " ET "); break; } } } } strcat(destString, suffixString); } void InventoryMan::drawPanelObjectDescriptionString(const char *descString) { if (descString[0] == '\f') { // form feed descString++; _objDescTextXpos = 108; _objDescTextYpos = 59; } if (descString[0]) { char stringTmpBuff[128]; strcpy(stringTmpBuff, descString); char *stringLine = stringTmpBuff; bool severalLines = false; char *string = nullptr; while (*stringLine) { if (strlen(stringLine) > 18) { // if string is too long to fit on one line string = &stringLine[17]; while (*string != ' ') // go back to the last space character string--; *string = '\0'; // and split the string there severalLines = true; } _vm->_textMan->printToViewport(_objDescTextXpos, _objDescTextYpos, kDMColorLightestGray, stringLine); _objDescTextYpos += 7; if (severalLines) { severalLines = false; stringLine = ++string; } else { *stringLine = '\0'; } } } } void InventoryMan::drawPanelArrowOrEye(bool pressingEye) { static Box boxArrowOrEye(83, 98, 57, 65); // @ G0033_s_Graphic562_Box_ArrowOrEye DisplayMan &dispMan = *_vm->_displayMan; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(pressingEye ? kDMGraphicIdxEyeForObjectDescription : kDMGraphicIdxArrowForChestContent), boxArrowOrEye, k8_byteWidth, kDMColorRed, 9); } void InventoryMan::drawPanelObject(Thing thingToDraw, bool pressingEye) { static Box boxObjectDescCircle(105, 136, 53, 79); // @ G0034_s_Graphic562_Box_ObjectDescriptionCircle DungeonMan &dungeon = *_vm->_dungeonMan; ObjectMan &objMan = *_vm->_objectMan; DisplayMan &dispMan = *_vm->_displayMan; ChampionMan &champMan = *_vm->_championMan; TextMan &textMan = *_vm->_textMan; if (_vm->_pressingEye || _vm->_pressingMouth) closeChest(); uint16 *rawThingPtr = dungeon.getThingData(thingToDraw); drawPanelObjectDescriptionString("\f"); // form feed ThingType thingType = thingToDraw.getType(); if (thingType == kDMThingTypeScroll) drawPanelScroll((Scroll *)rawThingPtr); else if (thingType == kDMThingTypeContainer) openAndDrawChest(thingToDraw, (Container *)rawThingPtr, pressingEye); else { IconIndice iconIndex = objMan.getIconIndex(thingToDraw); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxObjectDescCircle), boxObjectDescCircle, k16_byteWidth, kDMColorDarkestGray, 27); Common::String descString; Common::String str; if (iconIndex == kDMIconIndiceJunkChampionBones) { switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: // Fix original bug dur to a cut&paste error: string was concatenated then overwritten by the name str = Common::String::format("%s %s", objMan._objectNames[iconIndex], champMan._champions[((Junk *)rawThingPtr)->getChargeCount()]._name); break; default: // German and English versions are the same str = Common::String::format("%s %s", champMan._champions[((Junk *)rawThingPtr)->getChargeCount()]._name, objMan._objectNames[iconIndex]); break; } descString = str; } else if ((thingType == kDMThingTypePotion) && (iconIndex != kDMIconIndicePotionWaterFlask) && (champMan.getSkillLevel((ChampionIndex)_vm->ordinalToIndex(_inventoryChampionOrdinal), kDMSkillPriest) > 1)) { str = ('_' + ((Potion *)rawThingPtr)->getPower() / 40); str += " "; str += objMan._objectNames[iconIndex]; descString = str; } else { descString = objMan._objectNames[iconIndex]; } textMan.printToViewport(134, 68, kDMColorLightestGray, descString.c_str()); drawIconToViewport(iconIndex, 111, 59); _objDescTextYpos = 87; uint16 potentialAttribMask = 0; uint16 actualAttribMask = 0; switch (thingType) { case kDMThingTypeWeapon: { potentialAttribMask = kDMDescriptionMaskCursed | kDMDescriptionMaskPoisoned | kDMDescriptionMaskBroken; Weapon *weapon = (Weapon *)rawThingPtr; actualAttribMask = (weapon->getCursed() << 3) | (weapon->getPoisoned() << 1) | (weapon->getBroken() << 2); if ((iconIndex >= kDMIconIndiceWeaponTorchUnlit) && (iconIndex <= kDMIconIndiceWeaponTorchLit) && (weapon->getChargeCount() == 0)) { switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: drawPanelObjectDescriptionString("(BURNT OUT)"); break; case Common::DE_DEU: drawPanelObjectDescriptionString("(AUSGEBRANNT)"); break; case Common::FR_FRA: drawPanelObjectDescriptionString("(CONSUME)"); break; } } break; } case kDMThingTypeArmour: { potentialAttribMask = kDMDescriptionMaskCursed | kDMDescriptionMaskBroken; Armour *armour = (Armour *)rawThingPtr; actualAttribMask = (armour->getCursed() << 3) | (armour->getBroken() << 2); break; } case kDMThingTypePotion: { potentialAttribMask = kDMDescriptionMaskConsumable; Potion *potion = (Potion *)rawThingPtr; actualAttribMask = dungeon._objectInfos[kDMObjectInfoIndexFirstPotion + potion->getType()].getAllowedSlots(); break; } case kDMThingTypeJunk: { if ((iconIndex >= kDMIconIndiceJunkWater) && (iconIndex <= kDMIconIndiceJunkWaterSkin)) { potentialAttribMask = 0; const char *descStringEN[4] = {"(EMPTY)", "(ALMOST EMPTY)", "(ALMOST FULL)", "(FULL)"}; const char *descStringDE[4] = {"(LEER)", "(FAST LEER)", "(FAST VOLL)", "(VOLL)"}; const char *descStringFR[4] = {"(VIDE)", "(PRESQUE VIDE)", "(PRESQUE PLEINE)", "(PLEINE)"}; Junk *junk = (Junk *)rawThingPtr; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: descString = descStringDE[junk->getChargeCount()]; break; case Common::FR_FRA: descString = descStringFR[junk->getChargeCount()]; break; default: descString = descStringEN[junk->getChargeCount()]; break; } drawPanelObjectDescriptionString(descString.c_str()); } else if ((iconIndex >= kDMIconIndiceJunkCompassNorth) && (iconIndex <= kDMIconIndiceJunkCompassWest)) { const static char *directionNameEN[4] = {"NORTH", "EAST", "SOUTH", "WEST"}; const static char *directionNameDE[4] = {"NORDEN", "OSTEN", "SUEDEN", "WESTEN"}; const static char *directionNameFR[4] = {"AU NORD", "A L'EST", "AU SUD", "A L'OUEST"}; potentialAttribMask = 0; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: str = "GRUPPE BLICKT NACH "; str += directionNameDE[iconIndex]; break; case Common::FR_FRA: str = "GROUPE FACE "; str += directionNameFR[iconIndex]; break; default: str = "PARTY FACING "; str += directionNameEN[iconIndex]; break; } drawPanelObjectDescriptionString(str.c_str()); } else { Junk *junk = (Junk *)rawThingPtr; potentialAttribMask = kDMDescriptionMaskConsumable; actualAttribMask = dungeon._objectInfos[kDMObjectInfoIndexFirstJunk + junk->getType()].getAllowedSlots(); } break; } default: break; } // end of switch if (potentialAttribMask) { static const char *attribStringEN[4] = {"CONSUMABLE", "POISONED", "BROKEN", "CURSED"}; static const char *attribStringDE[4] = {"ESSBAR", "VERGIFTET", "DEFEKT", "VERFLUCHT"}; static const char *attribStringFR[4] = {"COMESTIBLE", "EMPOISONNE", "BRISE", "MAUDIT"}; const char **attribString = nullptr; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: attribString = attribStringDE; break; case Common::FR_FRA: attribString = attribStringFR; break; default: attribString = attribStringEN; break; } char destString[40]; buildObjectAttributeString(potentialAttribMask, actualAttribMask, attribString, destString, "(", ")"); drawPanelObjectDescriptionString(destString); } uint16 weight = dungeon.getObjectWeight(thingToDraw); switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: str = "WIEGT " + champMan.getStringFromInteger(weight / 10, false, 3) + ","; break; case Common::FR_FRA: str = "PESE " + champMan.getStringFromInteger(weight / 10, false, 3) + "KG,"; break; default: str = "WEIGHS " + champMan.getStringFromInteger(weight / 10, false, 3) + "."; break; } weight -= (weight / 10) * 10; str += champMan.getStringFromInteger(weight, false, 1); switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: str += "."; break; default: str += " KG."; break; } drawPanelObjectDescriptionString(str.c_str()); } drawPanelArrowOrEye(pressingEye); } void InventoryMan::setDungeonViewPalette() { static const int16 palIndexToLightAmmount[6] = {99, 75, 50, 25, 1, 0}; // @ G0040_ai_Graphic562_PaletteIndexToLightAmount DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; if (dungeon._currMap->_difficulty == 0) { display._dungeonViewPaletteIndex = 0; /* Brightest color palette index */ } else { /* Get torch light power from both hands of each champion in the party */ int16 counter = 4; /* BUG0_01 Coding error without consequence. The hands of four champions are inspected even if there are less champions in the party. No consequence as the data in unused champions is set to 0 and _vm->_objectMan->f32_getObjectType then returns -1 */ Champion *curChampion = championMan._champions; int16 torchesLightPower[8]; int16 *curTorchLightPower = torchesLightPower; while (counter--) { uint16 slotIndex = kDMSlotActionHand + 1; while (slotIndex--) { Thing slotThing = curChampion->_slots[slotIndex]; if ((_vm->_objectMan->getObjectType(slotThing) >= kDMIconIndiceWeaponTorchUnlit) && (_vm->_objectMan->getObjectType(slotThing) <= kDMIconIndiceWeaponTorchLit)) { Weapon *curWeapon = (Weapon *)dungeon.getThingData(slotThing); *curTorchLightPower = curWeapon->getChargeCount(); } else { *curTorchLightPower = 0; } curTorchLightPower++; } curChampion++; } /* Sort torch light power values so that the four highest values are in the first four entries in the array L1045_ai_TorchesLightPower in decreasing order. The last four entries contain the smallest values but they are not sorted */ curTorchLightPower = torchesLightPower; int16 torchIndex = 0; while (torchIndex != 4) { counter = 7 - torchIndex; int16 *L1041_pi_TorchLightPower = &torchesLightPower[torchIndex + 1]; while (counter--) { if (*L1041_pi_TorchLightPower > *curTorchLightPower) { int16 AL1044_ui_TorchLightPower = *L1041_pi_TorchLightPower; *L1041_pi_TorchLightPower = *curTorchLightPower; *curTorchLightPower = AL1044_ui_TorchLightPower; } L1041_pi_TorchLightPower++; } curTorchLightPower++; torchIndex++; } /* Get total light amount provided by the four torches with the highest light power values and by the fifth torch in the array which may be any one of the four torches with the smallest ligh power values */ uint16 torchLightAmountMultiplier = 6; torchIndex = 5; int16 totalLightAmount = 0; curTorchLightPower = torchesLightPower; while (torchIndex--) { if (*curTorchLightPower) { totalLightAmount += (championMan._lightPowerToLightAmount[*curTorchLightPower] << torchLightAmountMultiplier) >> 6; torchLightAmountMultiplier = MAX(0, torchLightAmountMultiplier - 1); } curTorchLightPower++; } totalLightAmount += championMan._party._magicalLightAmount; /* Select palette corresponding to the total light amount */ const int16 *curLightAmount = palIndexToLightAmmount; int16 paletteIndex; if (totalLightAmount > 0) { paletteIndex = 0; /* Brightest color palette index */ while (*curLightAmount++ > totalLightAmount) paletteIndex++; } else { paletteIndex = 5; /* Darkest color palette index */ } display._dungeonViewPaletteIndex = paletteIndex; } display._refreshDungeonViewPaleteRequested = true; } void InventoryMan::decreaseTorchesLightPower() { ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; bool torchChargeCountChanged = false; int16 championCount = championMan._partyChampionCount; if (championMan._candidateChampionOrdinal) championCount--; Champion *curChampion = championMan._champions; while (championCount--) { int16 slotIndex = kDMSlotActionHand + 1; while (slotIndex--) { int16 iconIndex = _vm->_objectMan->getIconIndex(curChampion->_slots[slotIndex]); if ((iconIndex >= kDMIconIndiceWeaponTorchUnlit) && (iconIndex <= kDMIconIndiceWeaponTorchLit)) { Weapon *curWeapon = (Weapon *)dungeon.getThingData(curChampion->_slots[slotIndex]); if (curWeapon->getChargeCount()) { if (curWeapon->setChargeCount(curWeapon->getChargeCount() - 1) == 0) { curWeapon->setDoNotDiscard(false); } torchChargeCountChanged = true; } } } curChampion++; } if (torchChargeCountChanged) { setDungeonViewPalette(); championMan.drawChangedObjectIcons(); } } void InventoryMan::drawChampionSkillsAndStatistics() { static const char *statisticNamesEN[7] = {"L", "STRENGTH", "DEXTERITY", "WISDOM", "VITALITY", "ANTI-MAGIC", "ANTI-FIRE"}; static const char *statisticNamesDE[7] = {"L", "STAERKE", "FLINKHEIT", "WEISHEIT", "VITALITAET", "ANTI-MAGIE", "ANTI-FEUER"}; static const char *statisticNamesFR[7] = {"L", "FORCE", "DEXTERITE", "SAGESSE", "VITALITE", "ANTI-MAGIE", "ANTI-FEU"}; DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; const char **statisticNames; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: statisticNames = statisticNamesDE; break; case Common::FR_FRA: statisticNames = statisticNamesFR; break; default: statisticNames = statisticNamesEN; break; } closeChest(); uint16 championIndex = _vm->ordinalToIndex(_inventoryChampionOrdinal); Champion *curChampion = &championMan._champions[championIndex]; display.blitToViewport(display.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 textPosY = 58; for (uint16 idx = kDMSkillFighter; idx <= kDMSkillWizard; idx++) { int16 skillLevel = MIN((uint16)16, championMan.getSkillLevel(championIndex, idx | kDMIgnoreTemporaryExperience)); if (skillLevel == 1) continue; Common::String displayString; switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: // Fix original bug: Due to a copy&paste error, the string was concatenate then overwritten be the last part displayString = Common::String::format("%s %s", championMan._baseSkillName[idx], _skillLevelNames[skillLevel - 2]); break; default: // English and German versions are built the same way displayString = Common::String::format("%s %s", _skillLevelNames[skillLevel - 2], championMan._baseSkillName[idx]); break; } _vm->_textMan->printToViewport(108, textPosY, kDMColorLightestGray, displayString.c_str()); textPosY += 7; } textPosY = 86; for (uint16 idx = kDMStatStrength; idx <= kDMStatAntifire; idx++) { _vm->_textMan->printToViewport(108, textPosY, kDMColorLightestGray, statisticNames[idx]); int16 statisticCurrentValue = curChampion->_statistics[idx][kDMStatCurrent]; uint16 statisticMaximumValue = curChampion->_statistics[idx][kDMStatMaximum]; int16 statisticColor; if (statisticCurrentValue < statisticMaximumValue) statisticColor = kDMColorRed; else if (statisticCurrentValue > statisticMaximumValue) statisticColor = kDMColorLightGreen; else statisticColor = kDMColorLightestGray; _vm->_textMan->printToViewport(174, textPosY, (Color)statisticColor, championMan.getStringFromInteger(statisticCurrentValue, true, 3).c_str()); Common::String displayString = "/" + championMan.getStringFromInteger(statisticMaximumValue, true, 3); _vm->_textMan->printToViewport(192, textPosY, kDMColorLightestGray, displayString.c_str()); textPosY += 7; } } void InventoryMan::drawStopPressingMouth() { drawPanel(); _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); _vm->_eventMan->_hideMousePointerRequestCount = 1; _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); } void InventoryMan::drawStopPressingEye() { drawIconToViewport(kDMIconIndiceEyeNotLooking, 12, 13); drawPanel(); _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); Thing leaderHandObject = _vm->_championMan->_leaderHandObject; if (leaderHandObject != _vm->_thingNone) _vm->_objectMan->drawLeaderObjectName(leaderHandObject); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); } void InventoryMan::clickOnMouth() { static int16 foodAmounts[8] = { 500, /* Apple */ 600, /* Corn */ 650, /* Bread */ 820, /* Cheese */ 550, /* Screamer Slice */ 350, /* Worm round */ 990, /* Drumstick / Shank */ 1400 /* Dragon steak */ }; DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; if (championMan._leaderEmptyHanded) { if (_panelContent == kDMPanelContentFoodWaterPoisoned) return; _vm->_eventMan->_ignoreMouseMovements = true; _vm->_pressingMouth = true; if (!_vm->_eventMan->isMouseButtonDown(kDMMouseButtonLeft)) { _vm->_eventMan->_ignoreMouseMovements = false; _vm->_pressingMouth = false; _vm->_stopPressingMouth = false; } else { _vm->_eventMan->showMouse(); _vm->_eventMan->_hideMousePointerRequestCount = 1; drawPanelFoodWaterPoisoned(); display.drawViewport(k0_viewportNotDungeonView); } return; } if (championMan._candidateChampionOrdinal) return; Thing handThing = championMan._leaderHandObject; if (!getFlag(dungeon._objectInfos[dungeon.getObjectInfoIndex(handThing)]._allowedSlots, kDMMaskMouth)) return; uint16 iconIndex = _vm->_objectMan->getIconIndex(handThing); uint16 handThingType = handThing.getType(); uint16 handThingWeight = dungeon.getObjectWeight(handThing); uint16 championIndex = _vm->ordinalToIndex(_inventoryChampionOrdinal); Champion *curChampion = &championMan._champions[championIndex]; Junk *junkData = (Junk *)dungeon.getThingData(handThing); bool removeObjectFromLeaderHand; if ((iconIndex >= kDMIconIndiceJunkWater) && (iconIndex <= kDMIconIndiceJunkWaterSkin)) { if (!(junkData->getChargeCount())) return; curChampion->_water = MIN(curChampion->_water + 800, 2048); junkData->setChargeCount(junkData->getChargeCount() - 1); removeObjectFromLeaderHand = false; } else if (handThingType == kDMThingTypePotion) removeObjectFromLeaderHand = false; else { junkData->setNextThing(_vm->_thingNone); removeObjectFromLeaderHand = true; } _vm->_eventMan->showMouse(); if (removeObjectFromLeaderHand) championMan.getObjectRemovedFromLeaderHand(); if (handThingType == kDMThingTypePotion) { uint16 potionPower = ((Potion *)junkData)->getPower(); uint16 counter = ((511 - potionPower) / (32 + (potionPower + 1) / 8)) >> 1; uint16 adjustedPotionPower = (potionPower / 25) + 8; /* Value between 8 and 18 */ switch (((Potion *)junkData)->getType()) { case kDMPotionTypeRos: adjustStatisticCurrentValue(curChampion, kDMStatDexterity, adjustedPotionPower); break; case kDMPotionTypeKu: adjustStatisticCurrentValue(curChampion, kDMStatStrength, (((Potion *)junkData)->getPower() / 35) + 5); /* Value between 5 and 12 */ break; case kDMPotionTypeDane: adjustStatisticCurrentValue(curChampion, kDMStatWisdom, adjustedPotionPower); break; case kDMPotionTypeNeta: adjustStatisticCurrentValue(curChampion, kDMStatVitality, adjustedPotionPower); break; case kDMPotionTypeAntivenin: championMan.unpoison(championIndex); break; case kDMPotionTypeMon: curChampion->_currStamina += MIN(curChampion->_maxStamina - curChampion->_currStamina, curChampion->_maxStamina / counter); break; case kDMPotionTypeYa: { adjustedPotionPower += adjustedPotionPower >> 1; if (curChampion->_shieldDefense > 50) adjustedPotionPower >>= 2; curChampion->_shieldDefense += adjustedPotionPower; TimelineEvent newEvent; newEvent._type = kDMEventTypeChampionShield; newEvent._mapTime = _vm->setMapAndTime(dungeon._partyMapIndex, _vm->_gameTime + (adjustedPotionPower * adjustedPotionPower)); newEvent._priority = championIndex; newEvent._Bu._defense = adjustedPotionPower; _vm->_timeline->addEventGetEventIndex(&newEvent); setFlag(curChampion->_attributes, kDMAttributeStatusBox); } break; case kDMPotionTypeEe: { uint16 mana = MIN(900, (curChampion->_currMana + adjustedPotionPower) + (adjustedPotionPower - 8)); if (mana > curChampion->_maxMana) mana -= (mana - MAX(curChampion->_currMana, curChampion->_maxMana)) >> 1; curChampion->_currMana = mana; } break; case kDMPotionTypeVi: { uint16 healWoundIterationCount = MAX(1, (((Potion *)junkData)->getPower() / 42)); curChampion->_currHealth += curChampion->_maxHealth / counter; int16 wounds = curChampion->_wounds; if (wounds) { /* If the champion is wounded */ counter = 10; do { for (uint16 i = 0; i < healWoundIterationCount; i++) curChampion->_wounds &= _vm->getRandomNumber(65536); healWoundIterationCount = 1; } while ((wounds == curChampion->_wounds) && --counter); /* Loop until at least one wound is healed or there are no more heal iterations */ } setFlag(curChampion->_attributes, kDMAttributeLoad | kDMAttributeWounds); } break; case kDMPotionTypeWaterFlask: curChampion->_water = MIN(curChampion->_water + 1600, 2048); break; default: break; } ((Potion *)junkData)->setType(kDMPotionTypeEmptyFlask); } else if ((iconIndex >= kDMIconIndiceJunkApple) && (iconIndex < kDMIconIndiceJunkIronKey)) curChampion->_food = MIN(curChampion->_food + foodAmounts[iconIndex - kDMIconIndiceJunkApple], 2048); if (curChampion->_currStamina > curChampion->_maxStamina) curChampion->_currStamina = curChampion->_maxStamina; if (curChampion->_currHealth > curChampion->_maxHealth) curChampion->_currHealth = curChampion->_maxHealth; if (removeObjectFromLeaderHand) { for (uint16 i = 5; --i; _vm->delay(8)) { /* Animate mouth icon */ _vm->_objectMan->drawIconToScreen(kDMIconIndiceMouthOpen + !(i & 0x0001), 56, 46); _vm->_eventMan->discardAllInput(); if (_vm->_engineShouldQuit) return; display.updateScreen(); } } else { championMan.drawChangedObjectIcons(); championMan._champions[championMan._leaderIndex]._load += dungeon.getObjectWeight(handThing) - handThingWeight; setFlag(championMan._champions[championMan._leaderIndex]._attributes, kDMAttributeLoad); } _vm->_sound->requestPlay(kDMSoundIndexSwallow, dungeon._partyMapX, dungeon._partyMapY, kDMSoundModePlayImmediately); setFlag(curChampion->_attributes, kDMAttributeStatistics); if (_panelContent == kDMPanelContentFoodWaterPoisoned) setFlag(curChampion->_attributes, kDMAttributePanel); championMan.drawChampionState((ChampionIndex)championIndex); _vm->_eventMan->hideMouse(); } void InventoryMan::adjustStatisticCurrentValue(Champion *champ, uint16 statIndex, int16 valueDelta) { int16 delta; if (valueDelta >= 0) { int16 currentValue = champ->_statistics[statIndex][kDMStatCurrent]; if (currentValue > 120) { valueDelta >>= 1; if (currentValue > 150) { valueDelta >>= 1; } valueDelta++; } delta = MIN(valueDelta, (int16)(170 - currentValue)); } else { /* BUG0_00 Useless code. The function is always called with valueDelta having a positive value */ delta = MAX(valueDelta, int16(champ->_statistics[statIndex][kDMStatMinimum] - champ->_statistics[statIndex][kDMStatCurrent])); } champ->_statistics[statIndex][kDMStatCurrent] += delta; } void InventoryMan::clickOnEye() { ChampionMan &championMan = *_vm->_championMan; _vm->_eventMan->_ignoreMouseMovements = true; _vm->_pressingEye = true; if (!_vm->_eventMan->isMouseButtonDown(kDMMouseButtonLeft)) { _vm->_eventMan->_ignoreMouseMovements = false; _vm->_pressingEye = false; _vm->_stopPressingEye = false; return; } _vm->_eventMan->discardAllInput(); _vm->_eventMan->hideMouse(); _vm->_eventMan->hideMouse(); _vm->_eventMan->hideMouse(); _vm->delay(8); drawIconToViewport(kDMIconIndiceEyeLooking, 12, 13); if (championMan._leaderEmptyHanded) drawChampionSkillsAndStatistics(); else { _vm->_objectMan->clearLeaderObjectName(); drawPanelObject(championMan._leaderHandObject, true); } _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); } }
alexbevi/scummvm
engines/dm/inventory.cpp
C++
gpl-2.0
40,443
"""generated file, don't modify or your data will be lost""" try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: pass
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/logilab/__init__.py
Python
agpl-3.0
155
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package volume import ( "fmt" "net" "strings" "sync" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/io" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/validation" ) // VolumeOptions contains option information about a volume. type VolumeOptions struct { // The attributes below are required by volume.Provisioner // TODO: refactor all of this out of volumes when an admin can configure // many kinds of provisioners. // Capacity is the size of a volume. Capacity resource.Quantity // AccessModes of a volume AccessModes []api.PersistentVolumeAccessMode // Reclamation policy for a persistent volume PersistentVolumeReclaimPolicy api.PersistentVolumeReclaimPolicy // PV.Name of the appropriate PersistentVolume. Used to generate cloud // volume name. PVName string // PVC.Name of the PersistentVolumeClaim; only set during dynamic provisioning. PVCName string // Unique name of Kubernetes cluster. ClusterName string // Tags to attach to the real volume in the cloud provider - e.g. AWS EBS CloudTags *map[string]string // Volume provisioning parameters from StorageClass Parameters map[string]string // Volume selector from PersistentVolumeClaim Selector *unversioned.LabelSelector } // VolumePlugin is an interface to volume plugins that can be used on a // kubernetes node (e.g. by kubelet) to instantiate and manage volumes. type VolumePlugin interface { // Init initializes the plugin. This will be called exactly once // before any New* calls are made - implementations of plugins may // depend on this. Init(host VolumeHost) error // Name returns the plugin's name. Plugins should use namespaced names // such as "example.com/volume". The "kubernetes.io" namespace is // reserved for plugins which are bundled with kubernetes. GetPluginName() string // GetVolumeName returns the name/ID to uniquely identifying the actual // backing device, directory, path, etc. referenced by the specified volume // spec. // For Attachable volumes, this value must be able to be passed back to // volume Detach methods to identify the device to act on. // If the plugin does not support the given spec, this returns an error. GetVolumeName(spec *Spec) (string, error) // CanSupport tests whether the plugin supports a given volume // specification from the API. The spec pointer should be considered // const. CanSupport(spec *Spec) bool // RequiresRemount returns true if this plugin requires mount calls to be // reexecuted. Atomically updating volumes, like Downward API, depend on // this to update the contents of the volume. RequiresRemount() bool // NewMounter creates a new volume.Mounter from an API specification. // Ownership of the spec pointer in *not* transferred. // - spec: The api.Volume spec // - pod: The enclosing pod NewMounter(spec *Spec, podRef *api.Pod, opts VolumeOptions) (Mounter, error) // NewUnmounter creates a new volume.Unmounter from recoverable state. // - name: The volume name, as per the api.Volume spec. // - podUID: The UID of the enclosing pod NewUnmounter(name string, podUID types.UID) (Unmounter, error) // ConstructVolumeSpec constructs a volume spec based on the given volume name // and mountPath. The spec may have incomplete information due to limited // information from input. This function is used by volume manager to reconstruct // volume spec by reading the volume directories from disk ConstructVolumeSpec(volumeName, mountPath string) (*Spec, error) } // PersistentVolumePlugin is an extended interface of VolumePlugin and is used // by volumes that want to provide long term persistence of data type PersistentVolumePlugin interface { VolumePlugin // GetAccessModes describes the ways a given volume can be accessed/mounted. GetAccessModes() []api.PersistentVolumeAccessMode } // RecyclableVolumePlugin is an extended interface of VolumePlugin and is used // by persistent volumes that want to be recycled before being made available // again to new claims type RecyclableVolumePlugin interface { VolumePlugin // NewRecycler creates a new volume.Recycler which knows how to reclaim // this resource after the volume's release from a PersistentVolumeClaim NewRecycler(pvName string, spec *Spec) (Recycler, error) } // DeletableVolumePlugin is an extended interface of VolumePlugin and is used // by persistent volumes that want to be deleted from the cluster after their // release from a PersistentVolumeClaim. type DeletableVolumePlugin interface { VolumePlugin // NewDeleter creates a new volume.Deleter which knows how to delete this // resource in accordance with the underlying storage provider after the // volume's release from a claim NewDeleter(spec *Spec) (Deleter, error) } const ( // Name of a volume in external cloud that is being provisioned and thus // should be ignored by rest of Kubernetes. ProvisionedVolumeName = "placeholder-for-provisioning" ) // ProvisionableVolumePlugin is an extended interface of VolumePlugin and is // used to create volumes for the cluster. type ProvisionableVolumePlugin interface { VolumePlugin // NewProvisioner creates a new volume.Provisioner which knows how to // create PersistentVolumes in accordance with the plugin's underlying // storage provider NewProvisioner(options VolumeOptions) (Provisioner, error) } // AttachableVolumePlugin is an extended interface of VolumePlugin and is used for volumes that require attachment // to a node before mounting. type AttachableVolumePlugin interface { VolumePlugin NewAttacher() (Attacher, error) NewDetacher() (Detacher, error) GetDeviceMountRefs(deviceMountPath string) ([]string, error) } // VolumeHost is an interface that plugins can use to access the kubelet. type VolumeHost interface { // GetPluginDir returns the absolute path to a directory under which // a given plugin may store data. This directory might not actually // exist on disk yet. For plugin data that is per-pod, see // GetPodPluginDir(). GetPluginDir(pluginName string) string // GetPodVolumeDir returns the absolute path a directory which // represents the named volume under the named plugin for the given // pod. If the specified pod does not exist, the result of this call // might not exist. GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string // GetPodPluginDir returns the absolute path to a directory under which // a given plugin may store data for a given pod. If the specified pod // does not exist, the result of this call might not exist. This // directory might not actually exist on disk yet. GetPodPluginDir(podUID types.UID, pluginName string) string // GetKubeClient returns a client interface GetKubeClient() clientset.Interface // NewWrapperMounter finds an appropriate plugin with which to handle // the provided spec. This is used to implement volume plugins which // "wrap" other plugins. For example, the "secret" volume is // implemented in terms of the "emptyDir" volume. NewWrapperMounter(volName string, spec Spec, pod *api.Pod, opts VolumeOptions) (Mounter, error) // NewWrapperUnmounter finds an appropriate plugin with which to handle // the provided spec. See comments on NewWrapperMounter for more // context. NewWrapperUnmounter(volName string, spec Spec, podUID types.UID) (Unmounter, error) // Get cloud provider from kubelet. GetCloudProvider() cloudprovider.Interface // Get mounter interface. GetMounter() mount.Interface // Get writer interface for writing data to disk. GetWriter() io.Writer // Returns the hostname of the host kubelet is running on GetHostName() string // Returns host IP or nil in the case of error. GetHostIP() (net.IP, error) // Returns the rootcontext to use when performing mounts for a volume. // This is a temporary measure in order to set the rootContext of tmpfs // mounts correctly. It will be replaced and expanded on by future // SecurityContext work. GetRootContext() string // Returns node allocatable GetNodeAllocatable() (api.ResourceList, error) } // VolumePluginMgr tracks registered plugins. type VolumePluginMgr struct { mutex sync.Mutex plugins map[string]VolumePlugin } // Spec is an internal representation of a volume. All API volume types translate to Spec. type Spec struct { Volume *api.Volume PersistentVolume *api.PersistentVolume ReadOnly bool } // Name returns the name of either Volume or PersistentVolume, one of which must not be nil. func (spec *Spec) Name() string { switch { case spec.Volume != nil: return spec.Volume.Name case spec.PersistentVolume != nil: return spec.PersistentVolume.Name default: return "" } } // VolumeConfig is how volume plugins receive configuration. An instance // specific to the plugin will be passed to the plugin's // ProbeVolumePlugins(config) func. Reasonable defaults will be provided by // the binary hosting the plugins while allowing override of those default // values. Those config values are then set to an instance of VolumeConfig // and passed to the plugin. // // Values in VolumeConfig are intended to be relevant to several plugins, but // not necessarily all plugins. The preference is to leverage strong typing // in this struct. All config items must have a descriptive but non-specific // name (i.e, RecyclerMinimumTimeout is OK but RecyclerMinimumTimeoutForNFS is // !OK). An instance of config will be given directly to the plugin, so // config names specific to plugins are unneeded and wrongly expose plugins in // this VolumeConfig struct. // // OtherAttributes is a map of string values intended for one-off // configuration of a plugin or config that is only relevant to a single // plugin. All values are passed by string and require interpretation by the // plugin. Passing config as strings is the least desirable option but can be // used for truly one-off configuration. The binary should still use strong // typing for this value when binding CLI values before they are passed as // strings in OtherAttributes. type VolumeConfig struct { // RecyclerPodTemplate is pod template that understands how to scrub clean // a persistent volume after its release. The template is used by plugins // which override specific properties of the pod in accordance with that // plugin. See NewPersistentVolumeRecyclerPodTemplate for the properties // that are expected to be overridden. RecyclerPodTemplate *api.Pod // RecyclerMinimumTimeout is the minimum amount of time in seconds for the // recycler pod's ActiveDeadlineSeconds attribute. Added to the minimum // timeout is the increment per Gi of capacity. RecyclerMinimumTimeout int // RecyclerTimeoutIncrement is the number of seconds added to the recycler // pod's ActiveDeadlineSeconds for each Gi of capacity in the persistent // volume. Example: 5Gi volume x 30s increment = 150s + 30s minimum = 180s // ActiveDeadlineSeconds for recycler pod RecyclerTimeoutIncrement int // PVName is name of the PersistentVolume instance that is being recycled. // It is used to generate unique recycler pod name. PVName string // OtherAttributes stores config as strings. These strings are opaque to // the system and only understood by the binary hosting the plugin and the // plugin itself. OtherAttributes map[string]string // ProvisioningEnabled configures whether provisioning of this plugin is // enabled or not. Currently used only in host_path plugin. ProvisioningEnabled bool } // NewSpecFromVolume creates an Spec from an api.Volume func NewSpecFromVolume(vs *api.Volume) *Spec { return &Spec{ Volume: vs, } } // NewSpecFromPersistentVolume creates an Spec from an api.PersistentVolume func NewSpecFromPersistentVolume(pv *api.PersistentVolume, readOnly bool) *Spec { return &Spec{ PersistentVolume: pv, ReadOnly: readOnly, } } // InitPlugins initializes each plugin. All plugins must have unique names. // This must be called exactly once before any New* methods are called on any // plugins. func (pm *VolumePluginMgr) InitPlugins(plugins []VolumePlugin, host VolumeHost) error { pm.mutex.Lock() defer pm.mutex.Unlock() if pm.plugins == nil { pm.plugins = map[string]VolumePlugin{} } allErrs := []error{} for _, plugin := range plugins { name := plugin.GetPluginName() if errs := validation.IsQualifiedName(name); len(errs) != 0 { allErrs = append(allErrs, fmt.Errorf("volume plugin has invalid name: %q: %s", name, strings.Join(errs, ";"))) continue } if _, found := pm.plugins[name]; found { allErrs = append(allErrs, fmt.Errorf("volume plugin %q was registered more than once", name)) continue } err := plugin.Init(host) if err != nil { glog.Errorf("Failed to load volume plugin %s, error: %s", plugin, err.Error()) allErrs = append(allErrs, err) continue } pm.plugins[name] = plugin glog.V(1).Infof("Loaded volume plugin %q", name) } return utilerrors.NewAggregate(allErrs) } // FindPluginBySpec looks for a plugin that can support a given volume // specification. If no plugins can support or more than one plugin can // support it, return error. func (pm *VolumePluginMgr) FindPluginBySpec(spec *Spec) (VolumePlugin, error) { pm.mutex.Lock() defer pm.mutex.Unlock() matches := []string{} for k, v := range pm.plugins { if v.CanSupport(spec) { matches = append(matches, k) } } if len(matches) == 0 { return nil, fmt.Errorf("no volume plugin matched") } if len(matches) > 1 { return nil, fmt.Errorf("multiple volume plugins matched: %s", strings.Join(matches, ",")) } return pm.plugins[matches[0]], nil } // FindPluginByName fetches a plugin by name or by legacy name. If no plugin // is found, returns error. func (pm *VolumePluginMgr) FindPluginByName(name string) (VolumePlugin, error) { pm.mutex.Lock() defer pm.mutex.Unlock() // Once we can get rid of legacy names we can reduce this to a map lookup. matches := []string{} for k, v := range pm.plugins { if v.GetPluginName() == name { matches = append(matches, k) } } if len(matches) == 0 { return nil, fmt.Errorf("no volume plugin matched") } if len(matches) > 1 { return nil, fmt.Errorf("multiple volume plugins matched: %s", strings.Join(matches, ",")) } return pm.plugins[matches[0]], nil } // FindPersistentPluginBySpec looks for a persistent volume plugin that can // support a given volume specification. If no plugin is found, return an // error func (pm *VolumePluginMgr) FindPersistentPluginBySpec(spec *Spec) (PersistentVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, fmt.Errorf("Could not find volume plugin for spec: %#v", spec) } if persistentVolumePlugin, ok := volumePlugin.(PersistentVolumePlugin); ok { return persistentVolumePlugin, nil } return nil, fmt.Errorf("no persistent volume plugin matched") } // FindPersistentPluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindPersistentPluginByName(name string) (PersistentVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if persistentVolumePlugin, ok := volumePlugin.(PersistentVolumePlugin); ok { return persistentVolumePlugin, nil } return nil, fmt.Errorf("no persistent volume plugin matched") } // FindRecyclablePluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindRecyclablePluginBySpec(spec *Spec) (RecyclableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if recyclableVolumePlugin, ok := volumePlugin.(RecyclableVolumePlugin); ok { return recyclableVolumePlugin, nil } return nil, fmt.Errorf("no recyclable volume plugin matched") } // FindProvisionablePluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindProvisionablePluginByName(name string) (ProvisionableVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if provisionableVolumePlugin, ok := volumePlugin.(ProvisionableVolumePlugin); ok { return provisionableVolumePlugin, nil } return nil, fmt.Errorf("no provisionable volume plugin matched") } // FindDeletablePluginBySppec fetches a persistent volume plugin by spec. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindDeletablePluginBySpec(spec *Spec) (DeletableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if deletableVolumePlugin, ok := volumePlugin.(DeletableVolumePlugin); ok { return deletableVolumePlugin, nil } return nil, fmt.Errorf("no deletable volume plugin matched") } // FindDeletablePluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindDeletablePluginByName(name string) (DeletableVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if deletableVolumePlugin, ok := volumePlugin.(DeletableVolumePlugin); ok { return deletableVolumePlugin, nil } return nil, fmt.Errorf("no deletable volume plugin matched") } // FindCreatablePluginBySpec fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindCreatablePluginBySpec(spec *Spec) (ProvisionableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if provisionableVolumePlugin, ok := volumePlugin.(ProvisionableVolumePlugin); ok { return provisionableVolumePlugin, nil } return nil, fmt.Errorf("no creatable volume plugin matched") } // FindAttachablePluginBySpec fetches a persistent volume plugin by name. // Unlike the other "FindPlugin" methods, this does not return error if no // plugin is found. All volumes require a mounter and unmounter, but not // every volume will have an attacher/detacher. func (pm *VolumePluginMgr) FindAttachablePluginBySpec(spec *Spec) (AttachableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if attachableVolumePlugin, ok := volumePlugin.(AttachableVolumePlugin); ok { return attachableVolumePlugin, nil } return nil, nil } // FindAttachablePluginByName fetches an attachable volume plugin by name. // Unlike the other "FindPlugin" methods, this does not return error if no // plugin is found. All volumes require a mounter and unmounter, but not // every volume will have an attacher/detacher. func (pm *VolumePluginMgr) FindAttachablePluginByName(name string) (AttachableVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if attachablePlugin, ok := volumePlugin.(AttachableVolumePlugin); ok { return attachablePlugin, nil } return nil, nil } // NewPersistentVolumeRecyclerPodTemplate creates a template for a recycler // pod. By default, a recycler pod simply runs "rm -rf" on a volume and tests // for emptiness. Most attributes of the template will be correct for most // plugin implementations. The following attributes can be overridden per // plugin via configuration: // // 1. pod.Spec.Volumes[0].VolumeSource must be overridden. Recycler // implementations without a valid VolumeSource will fail. // 2. pod.GenerateName helps distinguish recycler pods by name. Recommended. // Default is "pv-recycler-". // 3. pod.Spec.ActiveDeadlineSeconds gives the recycler pod a maximum timeout // before failing. Recommended. Default is 60 seconds. // // See HostPath and NFS for working recycler examples func NewPersistentVolumeRecyclerPodTemplate() *api.Pod { timeout := int64(60) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ GenerateName: "pv-recycler-", Namespace: api.NamespaceDefault, }, Spec: api.PodSpec{ ActiveDeadlineSeconds: &timeout, RestartPolicy: api.RestartPolicyNever, Volumes: []api.Volume{ { Name: "vol", // IMPORTANT! All plugins using this template MUST // override pod.Spec.Volumes[0].VolumeSource Recycler // implementations without a valid VolumeSource will fail. VolumeSource: api.VolumeSource{}, }, }, Containers: []api.Container{ { Name: "pv-recycler", Image: "gcr.io/google_containers/busybox", Command: []string{"/bin/sh"}, Args: []string{"-c", "test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z \"$(ls -A /scrub)\" || exit 1"}, VolumeMounts: []api.VolumeMount{ { Name: "vol", MountPath: "/scrub", }, }, }, }, }, } return pod }
jprukner/origin
vendor/k8s.io/kubernetes/pkg/volume/plugins.go
GO
apache-2.0
21,701
/** * Update: 15-5-11 * Editor: qihongye */ var fs = require('fs'); var path = require('path'); var fis = require('../lib/fis.js'); var _ = fis.file; var defaultSettings = (require('../lib/config.js')).DEFALUT_SETTINGS; var expect = require('chai').expect; var u = fis.util; var config = null; describe('config: config',function(){ beforeEach(function(){ fis.project.setProjectRoot(__dirname); fis.config.init(defaultSettings); process.env.NODE_ENV = 'dev'; }); it('set / get', function () { fis.set('namespace', 'common'); expect(fis.get('namespace')).to.equal('common'); fis.set('obj', {a:'a'}); fis.set('obj.b', 'b'); expect(fis.get('obj')).to.deep.equal({a:'a', b:'b'}); expect(fis.get('obj.c', {c: 'c'})).to.deep.equal({c:'c'}); expect(fis.get('obj.a')).to.equal('a'); expect(fis.get('obj.b')).to.equal('b'); }); it('media', function () { fis.set('a', 'a'); fis.set('b', 'b'); fis.media('prod').set('a', 'aa'); expect(fis.get('a')).to.equal('a'); expect(fis.media('prod').get('a')).to.equal('aa'); expect(fis.media('prod').get('b')).to.equal('b'); expect(fis.media('prod').get('project.charset')).to.equal('utf8'); }); it('fis.match',function(){ fis.match('**', { release: 'static/$&' }); // fis.config.match fis.match('**/js.js', { domain: 'www.baidu.com', useHash: false }, 1); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline'); //without domain // useDomain 已经去除,所以应该不收其影响了 fis.match('**/js.js', { useDomain: false }, 2); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline'); fis.match('**/js.js', { release: null }, 3); //without path path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline'); // with () fis.match('**/v1.0-(*)/(*).html', { release: '/$1/$2' }); path = __dirname+'/file/ext/v1.0-layout/test.html?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/layout/test.html?__inline'); fis.match('!**/js.js', { release: '/static/$&', useHash: true, domain: 'www.baidu.com' }); //with ! path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline'); // with ! but not match path = __dirname+'/file/ext/modular/js.less?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js_'+ f.getHash() +'.less?__inline'); }); it('match ${}', function() { fis.match('**/*.js', { release: null, useHash: false }) fis.set('coffee', 'js'); fis.match('**/js.js', { release: '/static/$&' }); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/file/ext/modular/js.js?__inline'); path = __dirname+'/file/ext/modular/j.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/file/ext/modular/j.js?__inline'); }); it('match 混合用法', function() { fis.set('ROOT', 'js'); fis.match('**', { useHash: false }); fis.match('(**/${ROOT}.js)', { release: '/static/js/$1' }); fis.match('(**/${ROOT}.less)', { release: '/static/js/$1' }); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/js/file/ext/modular/js.js?__inline'); path = __dirname+'/file/ext/modular/js.less?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/js/file/ext/modular/js.less?__inline'); }); it('del', function(){ fis.config.del(); var origin = fis.config.get(); fis.set('a.b', 'b'); fis.media('pro').set('a.b', 'b'); fis.config.del('a.b'); expect(fis.get('a')).to.deep.equal({}); expect(fis.media('pro').get('a.b')).to.equal('b'); fis.config.del('a'); expect(fis.get()).to.deep.equal(origin); fis.media('pro').del('a'); expect(fis.media('pro').get()).to.deep.equal({}); }); it('getSortedMatches', function() { fis.media('prod').match('a', { name: '' }); var matches = fis.media('prod')._matches.concat(); var initIndex = matches[matches.length - 1].index; fis.match('b', { name: '' }, 1) fis.match('c', { name: '' }, 2) fis.media('prod').match('b', { name: 'prod' }, 1) fis.media('prod').match('c', { name: 'prod' }, 2); var result_gl = [ { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 1, index: initIndex + 1 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 2, index: initIndex + 2 } ], result_prod = [ { raw: 'a', reg: u.glob('a'), negate: false, properties: {name: ''}, media: 'prod', weight: 0, index: initIndex + 0 }, { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 1, index: initIndex + 1 }, { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: 'prod'}, media: 'prod', weight: 1, index: initIndex + 3 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 2, index: initIndex + 2 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: 'prod'}, media: 'prod', weight: 2, index: initIndex + 4 }, ]; var xp = fis.config.getSortedMatches(); expect(xp).to.deep.equal(result_gl); var xp2 = fis.media('prod').getSortedMatches(); expect(xp2).to.deep.equal(result_prod); }); it("hook",function(){ fis.config.hook("module"); expect(fis.env().parent.data.modules.hook[1]['__plugin']).to.equal('module'); }); it("unhook",function(){ fis.config.unhook("module"); expect(fis.env().parent.data.modules.hook.length).to.equal(1); }); });
richard-chen-1985/fis3
test/config.js
JavaScript
bsd-2-clause
6,959
(function() { var add, crispedges, feature, flexbox, fullscreen, gradients, logicalProps, prefix, readOnly, resolution, result, sort, writingMode, slice = [].slice; sort = function(array) { return array.sort(function(a, b) { var d; a = a.split(' '); b = b.split(' '); if (a[0] > b[0]) { return 1; } else if (a[0] < b[0]) { return -1; } else { d = parseFloat(a[1]) - parseFloat(b[1]); if (d > 0) { return 1; } else if (d < 0) { return -1; } else { return 0; } } }); }; feature = function(data, opts, callback) { var browser, match, need, ref, ref1, support, version, versions; if (!callback) { ref = [opts, {}], callback = ref[0], opts = ref[1]; } match = opts.match || /\sx($|\s)/; need = []; ref1 = data.stats; for (browser in ref1) { versions = ref1[browser]; for (version in versions) { support = versions[version]; if (support.match(match)) { need.push(browser + ' ' + version); } } } return callback(sort(need)); }; result = {}; prefix = function() { var data, i, j, k, len, name, names, results; names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++]; results = []; for (k = 0, len = names.length; k < len; k++) { name = names[k]; result[name] = {}; results.push((function() { var results1; results1 = []; for (i in data) { results1.push(result[name][i] = data[i]); } return results1; })()); } return results; }; add = function() { var data, j, k, len, name, names, results; names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++]; results = []; for (k = 0, len = names.length; k < len; k++) { name = names[k]; results.push(result[name].browsers = sort(result[name].browsers.concat(data.browsers))); } return results; }; module.exports = result; feature(require('caniuse-db/features-json/border-radius'), function(browsers) { return prefix('border-radius', 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius', { mistakes: ['-khtml-', '-ms-', '-o-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-boxshadow'), function(browsers) { return prefix('box-shadow', { mistakes: ['-khtml-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-animation'), function(browsers) { return prefix('animation', 'animation-name', 'animation-duration', 'animation-delay', 'animation-direction', 'animation-fill-mode', 'animation-iteration-count', 'animation-play-state', 'animation-timing-function', '@keyframes', { mistakes: ['-khtml-', '-ms-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-transitions'), function(browsers) { return prefix('transition', 'transition-property', 'transition-duration', 'transition-delay', 'transition-timing-function', { mistakes: ['-khtml-', '-ms-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/transforms2d'), function(browsers) { return prefix('transform', 'transform-origin', { browsers: browsers }); }); feature(require('caniuse-db/features-json/transforms3d'), function(browsers) { prefix('perspective', 'perspective-origin', { browsers: browsers }); return prefix('transform-style', 'backface-visibility', { mistakes: ['-ms-', '-o-'], browsers: browsers }); }); gradients = require('caniuse-db/features-json/css-gradients'); feature(gradients, { match: /y\sx/ }, function(browsers) { return prefix('linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], mistakes: ['-ms-'], browsers: browsers }); }); feature(gradients, { match: /a\sx/ }, function(browsers) { browsers = browsers.map(function(i) { if (/op/.test(i)) { return i; } else { return i + " old"; } }); return add('linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-boxsizing'), function(browsers) { return prefix('box-sizing', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-filters'), function(browsers) { return prefix('filter', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-filter-function'), function(browsers) { return prefix('filter-function', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-backdrop-filter'), function(browsers) { return prefix('backdrop-filter', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-element-function'), function(browsers) { return prefix('element', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); feature(require('caniuse-db/features-json/multicolumn'), function(browsers) { prefix('columns', 'column-width', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', { browsers: browsers }); return prefix('column-count', 'column-rule-style', 'column-span', 'column-fill', 'break-before', 'break-after', 'break-inside', { browsers: browsers }); }); feature(require('caniuse-db/features-json/user-select-none'), function(browsers) { return prefix('user-select', { mistakes: ['-khtml-'], browsers: browsers }); }); flexbox = require('caniuse-db/features-json/flexbox'); feature(flexbox, { match: /a\sx/ }, function(browsers) { browsers = browsers.map(function(i) { if (/ie|firefox/.test(i)) { return i; } else { return i + " 2009"; } }); prefix('display-flex', 'inline-flex', { props: ['display'], browsers: browsers }); prefix('flex', 'flex-grow', 'flex-shrink', 'flex-basis', { browsers: browsers }); return prefix('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', { browsers: browsers }); }); feature(flexbox, { match: /y\sx/ }, function(browsers) { add('display-flex', 'inline-flex', { browsers: browsers }); add('flex', 'flex-grow', 'flex-shrink', 'flex-basis', { browsers: browsers }); return add('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', { browsers: browsers }); }); feature(require('caniuse-db/features-json/calc'), function(browsers) { return prefix('calc', { props: ['*'], browsers: browsers }); }); feature(require('caniuse-db/features-json/background-img-opts'), function(browsers) { return prefix('background-clip', 'background-origin', 'background-size', { browsers: browsers }); }); feature(require('caniuse-db/features-json/font-feature'), function(browsers) { return prefix('font-feature-settings', 'font-variant-ligatures', 'font-language-override', 'font-kerning', { browsers: browsers }); }); feature(require('caniuse-db/features-json/border-image'), function(browsers) { return prefix('border-image', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-selection'), function(browsers) { return prefix('::selection', { selector: true, browsers: browsers }); }); feature(require('caniuse-db/features-json/css-placeholder'), function(browsers) { browsers = browsers.map(function(i) { var name, ref, version; ref = i.split(' '), name = ref[0], version = ref[1]; if (name === 'firefox' && parseFloat(version) <= 18) { return i + ' old'; } else { return i; } }); return prefix('::placeholder', { selector: true, browsers: browsers }); }); feature(require('caniuse-db/features-json/css-hyphens'), function(browsers) { return prefix('hyphens', { browsers: browsers }); }); fullscreen = require('caniuse-db/features-json/fullscreen'); feature(fullscreen, function(browsers) { return prefix(':fullscreen', { selector: true, browsers: browsers }); }); feature(fullscreen, { match: /x(\s#2|$)/ }, function(browsers) { return prefix('::backdrop', { selector: true, browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-tabsize'), function(browsers) { return prefix('tab-size', { browsers: browsers }); }); feature(require('caniuse-db/features-json/intrinsic-width'), function(browsers) { return prefix('max-content', 'min-content', 'fit-content', 'fill-available', { props: ['width', 'min-width', 'max-width', 'height', 'min-height', 'max-height'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-cursors-newer'), function(browsers) { return prefix('zoom-in', 'zoom-out', { props: ['cursor'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-cursors-grab'), function(browsers) { return prefix('grab', 'grabbing', { props: ['cursor'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-sticky'), function(browsers) { return prefix('sticky', { props: ['position'], browsers: browsers }); }); feature(require('caniuse-db/features-json/pointer'), function(browsers) { return prefix('touch-action', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-decoration'), function(browsers) { return prefix('text-decoration-style', 'text-decoration-line', 'text-decoration-color', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-size-adjust'), function(browsers) { return prefix('text-size-adjust', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-masks'), function(browsers) { prefix('mask-clip', 'mask-composite', 'mask-image', 'mask-origin', 'mask-repeat', 'mask-border-repeat', 'mask-border-source', { browsers: browsers }); return prefix('clip-path', 'mask', 'mask-position', 'mask-size', 'mask-border', 'mask-border-outset', 'mask-border-width', 'mask-border-slice', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-boxdecorationbreak'), function(brwsrs) { return prefix('box-decoration-break', { browsers: brwsrs }); }); feature(require('caniuse-db/features-json/object-fit'), function(browsers) { return prefix('object-fit', 'object-position', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-shapes'), function(browsers) { return prefix('shape-margin', 'shape-outside', 'shape-image-threshold', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-overflow'), function(browsers) { return prefix('text-overflow', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-emphasis'), function(browsers) { return prefix('text-emphasis', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-deviceadaptation'), function(browsers) { return prefix('@viewport', { browsers: browsers }); }); resolution = require('caniuse-db/features-json/css-media-resolution'); feature(resolution, { match: /( x($| )|a #3)/ }, function(browsers) { return prefix('@resolution', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-text-align-last'), function(browsers) { return prefix('text-align-last', { browsers: browsers }); }); crispedges = require('caniuse-db/features-json/css-crisp-edges'); feature(crispedges, { match: /y x/ }, function(browsers) { return prefix('pixelated', { props: ['image-rendering'], browsers: browsers }); }); feature(crispedges, { match: /a x #2/ }, function(browsers) { return prefix('image-rendering', { browsers: browsers }); }); logicalProps = require('caniuse-db/features-json/css-logical-props'); feature(logicalProps, function(browsers) { return prefix('border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end', { browsers: browsers }); }); feature(logicalProps, { match: /x\s#2/ }, function(browsers) { return prefix('border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-appearance'), function(browsers) { return prefix('appearance', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-snappoints'), function(browsers) { return prefix('scroll-snap-type', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scroll-snap-points-x', 'scroll-snap-points-y', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-regions'), function(browsers) { return prefix('flow-into', 'flow-from', 'region-fragment', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-image-set'), function(browsers) { return prefix('image-set', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); writingMode = require('caniuse-db/features-json/css-writing-mode'); feature(writingMode, { match: /a|x/ }, function(browsers) { return prefix('writing-mode', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-cross-fade.json'), function(browsers) { return prefix('cross-fade', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); readOnly = require('caniuse-db/features-json/css-read-only-write.json'); feature(readOnly, function(browsers) { return prefix(':read-only', ':read-write', { selector: true, browsers: browsers }); }); }).call(this);
yuyang545262477/AfterWork
webpack/LittleTwo/node_modules/autoprefixer/data/prefixes.js
JavaScript
mit
15,271
export interface IGridItem { name: string; } export class Tests { public items: KnockoutObservableArray<IGridItem>; public selectedItems: KnockoutObservableArray<IGridItem>; public gridOptionsAlarms: kg.GridOptions<IGridItem>; constructor() { this.items = ko.observableArray<IGridItem>(); this.selectedItems = ko.observableArray<IGridItem>(); this.gridOptionsAlarms = this.createDefaultGridOptions(this.items, this.selectedItems); } public createDefaultGridOptions<Type>(dataArray: KnockoutObservableArray<Type>, selectedItems: KnockoutObservableArray<Type>): kg.GridOptions<Type> { return { data: dataArray, displaySelectionCheckbox: false, footerVisible: false, multiSelect: false, showColumnMenu: false, plugins: null, selectedItems: selectedItems }; } }
markogresak/DefinitelyTyped
types/knockout.kogrid/knockout.kogrid-tests.ts
TypeScript
mit
917
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Serializer\Mapping; /** * Knows how to get the class discriminator mapping for classes and objects. * * @author Samuel Roze <samuel.roze@gmail.com> */ interface ClassDiscriminatorResolverInterface { /** * @param string $class * * @return ClassDiscriminatorMapping|null */ public function getMappingForClass(string $class): ?ClassDiscriminatorMapping; /** * @param object|string $object * * @return ClassDiscriminatorMapping|null */ public function getMappingForMappedObject($object): ?ClassDiscriminatorMapping; /** * @param object|string $object * * @return string|null */ public function getTypeForMappedObject($object): ?string; }
hacfi/symfony
src/Symfony/Component/Serializer/Mapping/ClassDiscriminatorResolverInterface.php
PHP
mit
991
/* * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * COPYRIGHT AND PERMISSION NOTICE * * Copyright (C) 1991-2007 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in http://www.unicode.org/copyright.html. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of the Unicode data files and any associated documentation (the "Data * Files") or Unicode software and any associated documentation (the * "Software") to deal in the Data Files or Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Data Files or Software, and * to permit persons to whom the Data Files or Software are furnished to do * so, provided that (a) the above copyright notice(s) and this permission * notice appear with all copies of the Data Files or Software, (b) both the * above copyright notice(s) and this permission notice appear in associated * documentation, and (c) there is clear notice in each modified Data File or * in the Software as well as in the documentation associated with the Data * File(s) or Software that the data or software has been modified. * * THE DATA FILES AND SOFTWARE ARE 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR * CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall not * be used in advertising or otherwise to promote the sale, use or other * dealings in these Data Files or Software without prior written * authorization of the copyright holder. */ package sun.text.resources.sr; import sun.util.resources.ParallelListResourceBundle; public class FormatData_sr_ME extends ParallelListResourceBundle { protected final Object[][] getContents() { return new Object[][] { }; } }
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/sun/text/resources/sr/FormatData_sr_ME.java
Java
mit
3,546
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @summary Test SoftAudioSynthesizer getFormat method */ import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Patch; import javax.sound.sampled.*; import com.sun.media.sound.*; public class GetFormat { private static void assertEquals(Object a, Object b) throws Exception { if(!a.equals(b)) throw new RuntimeException("assertEquals fails!"); } private static void assertTrue(boolean value) throws Exception { if(!value) throw new RuntimeException("assertTrue fails!"); } public static void main(String[] args) throws Exception { AudioSynthesizer synth = new SoftSynthesizer(); AudioFormat defformat = synth.getFormat(); assertTrue(defformat != null); synth.openStream(null, null); assertTrue(synth.getFormat().toString().equals(defformat.toString())); synth.close(); AudioFormat custformat = new AudioFormat(8000, 16, 1, true, false); synth.openStream(custformat, null); assertTrue(synth.getFormat().toString().equals(custformat.toString())); synth.close(); } }
rokn/Count_Words_2015
testing/openjdk/jdk/test/javax/sound/midi/Gervill/SoftAudioSynthesizer/GetFormat.java
Java
mit
2,359
/* * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang; import java.io.DataInputStream; import java.io.InputStream; import java.lang.ref.SoftReference; import java.util.Arrays; import java.util.zip.InflaterInputStream; import java.security.AccessController; import java.security.PrivilegedAction; class CharacterName { private static SoftReference<byte[]> refStrPool; private static int[][] lookup; private static synchronized byte[] initNamePool() { byte[] strPool = null; if (refStrPool != null && (strPool = refStrPool.get()) != null) return strPool; DataInputStream dis = null; try { dis = new DataInputStream(new InflaterInputStream( AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run() { return getClass().getResourceAsStream("uniName.dat"); } }))); lookup = new int[(Character.MAX_CODE_POINT + 1) >> 8][]; int total = dis.readInt(); int cpEnd = dis.readInt(); byte ba[] = new byte[cpEnd]; dis.readFully(ba); int nameOff = 0; int cpOff = 0; int cp = 0; do { int len = ba[cpOff++] & 0xff; if (len == 0) { len = ba[cpOff++] & 0xff; // always big-endian cp = ((ba[cpOff++] & 0xff) << 16) | ((ba[cpOff++] & 0xff) << 8) | ((ba[cpOff++] & 0xff)); } else { cp++; } int hi = cp >> 8; if (lookup[hi] == null) { lookup[hi] = new int[0x100]; } lookup[hi][cp&0xff] = (nameOff << 8) | len; nameOff += len; } while (cpOff < cpEnd); strPool = new byte[total - cpEnd]; dis.readFully(strPool); refStrPool = new SoftReference<>(strPool); } catch (Exception x) { throw new InternalError(x.getMessage(), x); } finally { try { if (dis != null) dis.close(); } catch (Exception xx) {} } return strPool; } public static String get(int cp) { byte[] strPool = null; if (refStrPool == null || (strPool = refStrPool.get()) == null) strPool = initNamePool(); int off = 0; if (lookup[cp>>8] == null || (off = lookup[cp>>8][cp&0xff]) == 0) return null; @SuppressWarnings("deprecation") String result = new String(strPool, 0, off >>> 8, off & 0xff); // ASCII return result; } }
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/java/lang/CharacterName.java
Java
mit
4,017
/* * grunt-contrib-compress * http://gruntjs.com/ * * Copyright (c) 2016 Chris Talkington, contributors * Licensed under the MIT license. */ 'use strict'; var fs = require('fs'); var path = require('path'); var prettyBytes = require('pretty-bytes'); var chalk = require('chalk'); var zlib = require('zlib'); var archiver = require('archiver'); var streamBuffers = require('stream-buffers'); var _ = require('lodash'); module.exports = function(grunt) { var exports = { options: {} }; var fileStatSync = function() { var filepath = path.join.apply(path, arguments); if (grunt.file.exists(filepath)) { return fs.statSync(filepath); } return false; }; // 1 to 1 gziping of files exports.gzip = function(files, done) { exports.singleFile(files, zlib.createGzip, 'gz', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 deflate of files exports.deflate = function(files, done) { exports.singleFile(files, zlib.createDeflate, 'deflate', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 deflateRaw of files exports.deflateRaw = function(files, done) { exports.singleFile(files, zlib.createDeflateRaw, 'deflate', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 compression of files, expects a compatible zlib method to be passed in, see above exports.singleFile = function(files, algorithm, extension, done) { grunt.util.async.forEachSeries(files, function(filePair, nextPair) { grunt.util.async.forEachSeries(filePair.src, function(src, nextFile) { // Must be a file if (grunt.file.isDir(src)) { return nextFile(); } // Ensure the dest folder exists grunt.file.mkdir(path.dirname(filePair.dest)); var srcStream = fs.createReadStream(src); var originalSize = exports.getSize(src); var destStream; function initDestStream() { destStream = fs.createWriteStream(filePair.dest); destStream.on('close', function() { var compressedSize = exports.getSize(filePair.dest); var ratio = Math.round(parseInt(compressedSize, 10) / parseInt(originalSize, 10) * 100) + '%'; grunt.verbose.writeln('Created ' + chalk.cyan(filePair.dest) + ' (' + compressedSize + ') - ' + chalk.cyan(ratio) + ' of the original size'); nextFile(); }); } // write to memory stream if source and destination are the same var tmpStream; if (src === filePair.dest) { tmpStream = new streamBuffers.WritableStreamBuffer(); tmpStream.on('close', function() { initDestStream(); destStream.write(this.getContents()); destStream.end(); }); } else { initDestStream(); } var compressor = algorithm.call(zlib, exports.options); compressor.on('error', function(err) { grunt.log.error(err); grunt.fail.warn(algorithm + ' failed.'); nextFile(); }); srcStream.pipe(compressor).pipe(tmpStream || destStream); }, nextPair); }, done); }; // Compress with tar, tgz and zip exports.tar = function(files, done) { if (typeof exports.options.archive !== 'string' || exports.options.archive.length === 0) { grunt.fail.warn('Unable to compress; no valid archive file was specified.'); return; } var mode = exports.options.mode; if (mode === 'tgz') { mode = 'tar'; exports.options.gzip = true; } var archive = archiver.create(mode, exports.options); var dest = exports.options.archive; var dataWhitelist = ['comment', 'date', 'mode', 'store', 'gid', 'uid']; var sourcePaths = {}; // Ensure dest folder exists grunt.file.mkdir(path.dirname(dest)); // Where to write the file var destStream = fs.createWriteStream(dest); archive.on('error', function(err) { grunt.log.error(err); grunt.fail.warn('Archiving failed.'); }); archive.on('entry', function(file) { var sp = sourcePaths[file.name] || 'unknown'; grunt.verbose.writeln('Archived ' + chalk.cyan(sp) + ' -> ' + chalk.cyan(dest + '/' + file.name)); }); destStream.on('error', function(err) { grunt.log.error(err); grunt.fail.warn('WriteStream failed.'); }); destStream.on('close', function() { var size = archive.pointer(); grunt.verbose.writeln('Created ' + chalk.cyan(dest) + ' (' + exports.getSize(size) + ')'); done(); }); archive.pipe(destStream); files.forEach(function(file) { var isExpandedPair = file.orig.expand || false; file.src.forEach(function(srcFile) { var fstat = fileStatSync(srcFile); if (!fstat) { grunt.fail.warn('unable to stat srcFile (' + srcFile + ')'); return; } var internalFileName = isExpandedPair ? file.dest : exports.unixifyPath(path.join(file.dest || '', srcFile)); // check if internal file name is not a dot, should not be present in an archive if (internalFileName === '.' || internalFileName === './') { return; } if (fstat.isDirectory() && internalFileName.slice(-1) !== '/') { srcFile += '/'; internalFileName += '/'; } var fileData = { name: internalFileName, stats: fstat }; for (var i = 0; i < dataWhitelist.length; i++) { if (typeof file[dataWhitelist[i]] === 'undefined') { continue; } if (typeof file[dataWhitelist[i]] === 'function') { fileData[dataWhitelist[i]] = file[dataWhitelist[i]](srcFile); } else { fileData[dataWhitelist[i]] = file[dataWhitelist[i]]; } } if (fstat.isFile()) { archive.file(srcFile, fileData); } else if (fstat.isDirectory()) { archive.append(null, fileData); } else { grunt.fail.warn('srcFile (' + srcFile + ') should be a valid file or directory'); return; } sourcePaths[internalFileName] = srcFile; }); }); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); archive.finalize(); }; exports.getSize = function(filename, pretty) { var size = 0; if (typeof filename === 'string') { try { size = fs.statSync(filename).size; } catch (e) {} } else { size = filename; } if (pretty !== false) { if (!exports.options.pretty) { return size + ' bytes'; } return prettyBytes(size); } return Number(size); }; exports.autoDetectMode = function(dest) { if (exports.options.mode) { return exports.options.mode; } if (!dest) { return 'gzip'; } if (_.endsWith(dest, '.tar.gz')) { return 'tgz'; } var ext = path.extname(dest).replace('.', ''); if (ext === 'gz') { return 'gzip'; } return ext; }; exports.unixifyPath = function(filepath) { return process.platform === 'win32' ? filepath.replace(/\\/g, '/') : filepath; }; return exports; };
ph3l1x/realestate
sites/all/themes/default/bootstrap/node_modules/grunt-contrib-compress/tasks/lib/compress.js
JavaScript
gpl-2.0
7,527
#-- # $Id: text.rb,v 1.7 2009/02/28 23:52:28 rmagick Exp $ # Copyright (C) 2009 Timothy P. Hunter #++ # Text-related classes module Magick class RVG # Base class for Tspan, Tref and Text. class TextBase include Stylable include Duplicatable private def initialize(text, &block) #:nodoc: super() @text = text.to_s if text @dx = @dy = 0 @rotation = 0 @tspans = Content.new yield(self) if block_given? end public # Create a new text chunk. Each chunk can have its own initial position and styles. # If <tt>x</tt> and <tt>y</tt> are omitted the text starts at the current text # position. def tspan(text, x=nil, y=nil) tspan = Tspan.new(text, x, y) tspan.parent = self @tspans << tspan return tspan end # Add <tt>x</tt> and <tt>y</tt> to the current text position. def d(x, y=0) @dx, @dy = Magick::RVG.convert_to_float(x, y) yield(self) if block_given? self end # Rotate the text about the current text position. def rotate(degrees) @rotation = Magick::RVG.convert_to_float(degrees)[0] yield(self) if block_given? self end # We do our own transformations. def add_primitives(gc) #:nodoc: if @text || @tspans.length > 0 gc.push x = self.cx + @dx y = self.cy + @dy if @rotation != 0 gc.translate(x, y) gc.rotate(@rotation) gc.translate(-x, -y) end add_style_primitives(gc) if @text x2, y2 = gc.text(x, y, @text) self.cx = x + x2 self.cy = y + y2 end @tspans.each do |tspan| tspan.add_primitives(gc) end gc.pop end end end # class TextBase # Tspan and Tref shared methods - read/update @cx, @cy in parent Text object. module TextLink #:nodoc: def add_primitives(gc) @parent.cx = @x if @x @parent.cy = @y if @y super end def cx() @parent.cx end def cy() @parent.cy end def cx=(x) @parent.cx = x end def cy=(y) @parent.cy = y end end # module TextLink class Tref < TextBase #:nodoc: include TextLink def initialize(obj, x, y, parent) @x, @y = Magick::RVG.convert_to_float(x, y, :allow_nil) super(nil) @tspans << obj @parent = parent end end # class Tref class Tspan < TextBase #:nodoc: include TextLink attr_accessor :parent # Define a text segment starting at (<tt>x</tt>, <tt>y</tt>). # If <tt>x</tt> and <tt>y</tt> are omitted the segment starts # at the current text position. # # Tspan objects can contain Tspan objects. def initialize(text=nil, x=nil, y=nil, &block) @x, @y = Magick::RVG.convert_to_float(x, y, :allow_nil) super(text, &block) end end # class Tspan class Text < TextBase attr_accessor :cx, :cy #:nodoc: # Define a text string starting at [<tt>x</tt>, <tt>y</tt>]. # Use the RVG::TextConstructors#text method to create Text objects in a container. # # container.text(100, 100, "Simple text").styles(:font=>'Arial') # # Text objects can contain Tspan objects. # # container.text(100, 100).styles(:font=>'Arial') do |t| # t.tspan("Red text").styles(:fill=>'red') # t.tspan("Blue text").styles(:fill=>'blue') # end def initialize(x=0, y=0, text=nil, &block) @cx, @cy = Magick::RVG.convert_to_float(x, y) super(text, &block) end # Reference a Tspan object. <tt>x</tt> and <tt>y</tt> are just # like <tt>x</tt> and <tt>y</tt> in RVG::TextBase#tspan def tref(obj, x=nil, y=nil) if ! obj.kind_of?(Tspan) raise ArgumentError, "wrong argument type #{obj.class} (expected Tspan)" end obj = obj.deep_copy obj.parent = self tref = Tref.new(obj, x, y, self) @tspans << tref return tref end end # class Text # Methods that construct text objects within a container module TextConstructors # Draw a text string at (<tt>x</tt>,<tt>y</tt>). The string can # be omitted. Optionally, define text chunks within the associated # block. def text(x=0, y=0, text=nil, &block) t = Text.new(x, y, text, &block) @content << t return t end end # module TextConstructors end # class RVG end # module Magick
mzemel/kpsu.org
vendor/gems/ruby/1.8/gems/rmagick-2.13.1/lib/rvg/text.rb
Ruby
gpl-3.0
5,772
tinyMCE.addI18n('th.advimage_dlg',{ tab_general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B", tab_appearance:"\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30", tab_advanced:"\u0E02\u0E31\u0E49\u0E19\u0E2A\u0E39\u0E07", general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B", title:"\u0E0A\u0E37\u0E48\u0E2D", preview:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07", constrain_proportions:"\u0E04\u0E07\u0E2A\u0E31\u0E14\u0E2A\u0E48\u0E27\u0E19", langdir:"\u0E17\u0E34\u0E28\u0E17\u0E32\u0E07\u0E01\u0E32\u0E23\u0E2D\u0E48\u0E32\u0E19", langcode:"\u0E42\u0E04\u0E49\u0E14\u0E20\u0E32\u0E29\u0E32", long_desc:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E25\u0E34\u0E49\u0E07\u0E04\u0E4C", style:"\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A", classes:"\u0E04\u0E25\u0E32\u0E2A", ltr:"\u0E0B\u0E49\u0E32\u0E22\u0E44\u0E1B\u0E02\u0E27\u0E32", rtl:"\u0E02\u0E27\u0E32\u0E44\u0E1B\u0E0B\u0E49\u0E32\u0E22", id:"Id", map:"Image map", swap_image:"Swap image", alt_image:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E23\u0E39\u0E1B", mouseover:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E0A\u0E35\u0E49", mouseout:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E2D\u0E2D\u0E01", misc:"\u0E40\u0E1A\u0E47\u0E14\u0E40\u0E15\u0E25\u0E47\u0E14", example_img:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30\u0E02\u0E2D\u0E07\u0E23\u0E39\u0E1B", missing_alt:"\u0E04\u0E38\u0E13\u0E41\u0E19\u0E48\u0E43\u0E08\u0E2B\u0E23\u0E37\u0E2D\u0E44\u0E21\u0E48\u0E27\u0E48\u0E32\u0E15\u0E49\u0E2D\u0E07\u0E01\u0E32\u0E23\u0E14\u0E33\u0E40\u0E19\u0E34\u0E19\u0E01\u0E32\u0E23\u0E15\u0E48\u0E2D\u0E42\u0E14\u0E22\u0E44\u0E21\u0E48\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E20\u0E32\u0E1E ? \u0E01\u0E32\u0E23\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E17\u0E33\u0E43\u0E2B\u0E49\u0E1C\u0E39\u0E49\u0E1E\u0E34\u0E01\u0E32\u0E23\u0E17\u0E32\u0E07\u0E2A\u0E32\u0E22\u0E15\u0E32\u0E2A\u0E32\u0E21\u0E32\u0E23\u0E16\u0E23\u0E39\u0E49\u0E44\u0E14\u0E49\u0E27\u0E48\u0E32\u0E23\u0E39\u0E1B\u0E04\u0E38\u0E13\u0E04\u0E37\u0E2D\u0E23\u0E39\u0E1B\u0E2D\u0E30\u0E44\u0E23", dialog_title:"\u0E40\u0E1E\u0E34\u0E48\u0E21/\u0E41\u0E01\u0E49\u0E44\u0E02 image", src:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E23\u0E39\u0E1B", alt:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E23\u0E39\u0E1B", list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B", border:"\u0E01\u0E23\u0E2D\u0E1A", dimensions:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07", vspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E15\u0E31\u0E49\u0E07", hspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E19\u0E2D\u0E19", align:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07\u0E08\u0E31\u0E14\u0E27\u0E32\u0E07", align_baseline:"\u0E40\u0E2A\u0E49\u0E19\u0E1E\u0E37\u0E49\u0E19", align_top:"\u0E1A\u0E19", align_middle:"\u0E01\u0E25\u0E32\u0E07", align_bottom:"\u0E25\u0E48\u0E32\u0E07", align_texttop:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E1A\u0E19", align_textbottom:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E25\u0E48\u0E32\u0E07", align_left:"\u0E0B\u0E49\u0E32\u0E22", align_right:"\u0E02\u0E27\u0E32", image_list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B" });
numericube/twistranet
twistranet/themes/twistheme/static/js/tiny_mce/plugins/advimage/langs/th_dlg.js
JavaScript
agpl-3.0
3,520
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.discovery.zen.fd; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ProcessedClusterStateNonMasterUpdateTask; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.discovery.zen.NotMasterException; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; import java.io.IOException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import static org.elasticsearch.transport.TransportRequestOptions.options; /** * A fault detection that pings the master periodically to see if its alive. */ public class MasterFaultDetection extends FaultDetection { public static final String MASTER_PING_ACTION_NAME = "internal:discovery/zen/fd/master_ping"; public static interface Listener { /** called when pinging the master failed, like a timeout, transport disconnects etc */ void onMasterFailure(DiscoveryNode masterNode, String reason); } private final ClusterService clusterService; private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>(); private volatile MasterPinger masterPinger; private final Object masterNodeMutex = new Object(); private volatile DiscoveryNode masterNode; private volatile int retryCount; private final AtomicBoolean notifiedMasterFailure = new AtomicBoolean(); public MasterFaultDetection(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterName clusterName, ClusterService clusterService) { super(settings, threadPool, transportService, clusterName); this.clusterService = clusterService; logger.debug("[master] uses ping_interval [{}], ping_timeout [{}], ping_retries [{}]", pingInterval, pingRetryTimeout, pingRetryCount); transportService.registerRequestHandler(MASTER_PING_ACTION_NAME, MasterPingRequest::new, ThreadPool.Names.SAME, new MasterPingRequestHandler()); } public DiscoveryNode masterNode() { return this.masterNode; } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public void restart(DiscoveryNode masterNode, String reason) { synchronized (masterNodeMutex) { if (logger.isDebugEnabled()) { logger.debug("[master] restarting fault detection against master [{}], reason [{}]", masterNode, reason); } innerStop(); innerStart(masterNode); } } public void start(final DiscoveryNode masterNode, String reason) { synchronized (masterNodeMutex) { if (logger.isDebugEnabled()) { logger.debug("[master] starting fault detection against master [{}], reason [{}]", masterNode, reason); } innerStart(masterNode); } } private void innerStart(final DiscoveryNode masterNode) { this.masterNode = masterNode; this.retryCount = 0; this.notifiedMasterFailure.set(false); // try and connect to make sure we are connected try { transportService.connectToNode(masterNode); } catch (final Exception e) { // notify master failure (which stops also) and bail.. notifyMasterFailure(masterNode, "failed to perform initial connect [" + e.getMessage() + "]"); return; } if (masterPinger != null) { masterPinger.stop(); } this.masterPinger = new MasterPinger(); // we start pinging slightly later to allow the chosen master to complete it's own master election threadPool.schedule(pingInterval, ThreadPool.Names.SAME, masterPinger); } public void stop(String reason) { synchronized (masterNodeMutex) { if (masterNode != null) { if (logger.isDebugEnabled()) { logger.debug("[master] stopping fault detection against master [{}], reason [{}]", masterNode, reason); } } innerStop(); } } private void innerStop() { // also will stop the next ping schedule this.retryCount = 0; if (masterPinger != null) { masterPinger.stop(); masterPinger = null; } this.masterNode = null; } @Override public void close() { super.close(); stop("closing"); this.listeners.clear(); transportService.removeHandler(MASTER_PING_ACTION_NAME); } @Override protected void handleTransportDisconnect(DiscoveryNode node) { synchronized (masterNodeMutex) { if (!node.equals(this.masterNode)) { return; } if (connectOnNetworkDisconnect) { try { transportService.connectToNode(node); // if all is well, make sure we restart the pinger if (masterPinger != null) { masterPinger.stop(); } this.masterPinger = new MasterPinger(); // we use schedule with a 0 time value to run the pinger on the pool as it will run on later threadPool.schedule(TimeValue.timeValueMillis(0), ThreadPool.Names.SAME, masterPinger); } catch (Exception e) { logger.trace("[master] [{}] transport disconnected (with verified connect)", masterNode); notifyMasterFailure(masterNode, "transport disconnected (with verified connect)"); } } else { logger.trace("[master] [{}] transport disconnected", node); notifyMasterFailure(node, "transport disconnected"); } } } private void notifyMasterFailure(final DiscoveryNode masterNode, final String reason) { if (notifiedMasterFailure.compareAndSet(false, true)) { threadPool.generic().execute(new Runnable() { @Override public void run() { for (Listener listener : listeners) { listener.onMasterFailure(masterNode, reason); } } }); stop("master failure, " + reason); } } private class MasterPinger implements Runnable { private volatile boolean running = true; public void stop() { this.running = false; } @Override public void run() { if (!running) { // return and don't spawn... return; } final DiscoveryNode masterToPing = masterNode; if (masterToPing == null) { // master is null, should not happen, but we are still running, so reschedule threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this); return; } final MasterPingRequest request = new MasterPingRequest(clusterService.localNode().id(), masterToPing.id(), clusterName); final TransportRequestOptions options = options().withType(TransportRequestOptions.Type.PING).withTimeout(pingRetryTimeout); transportService.sendRequest(masterToPing, MASTER_PING_ACTION_NAME, request, options, new BaseTransportResponseHandler<MasterPingResponseResponse>() { @Override public MasterPingResponseResponse newInstance() { return new MasterPingResponseResponse(); } @Override public void handleResponse(MasterPingResponseResponse response) { if (!running) { return; } // reset the counter, we got a good result MasterFaultDetection.this.retryCount = 0; // check if the master node did not get switched on us..., if it did, we simply return with no reschedule if (masterToPing.equals(MasterFaultDetection.this.masterNode())) { // we don't stop on disconnection from master, we keep pinging it threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this); } } @Override public void handleException(TransportException exp) { if (!running) { return; } synchronized (masterNodeMutex) { // check if the master node did not get switched on us... if (masterToPing.equals(MasterFaultDetection.this.masterNode())) { if (exp instanceof ConnectTransportException || exp.getCause() instanceof ConnectTransportException) { handleTransportDisconnect(masterToPing); return; } else if (exp.getCause() instanceof NotMasterException) { logger.debug("[master] pinging a master {} that is no longer a master", masterNode); notifyMasterFailure(masterToPing, "no longer master"); return; } else if (exp.getCause() instanceof ThisIsNotTheMasterYouAreLookingForException) { logger.debug("[master] pinging a master {} that is not the master", masterNode); notifyMasterFailure(masterToPing, "not master"); return; } else if (exp.getCause() instanceof NodeDoesNotExistOnMasterException) { logger.debug("[master] pinging a master {} but we do not exists on it, act as if its master failure", masterNode); notifyMasterFailure(masterToPing, "do not exists on master, act as master failure"); return; } int retryCount = ++MasterFaultDetection.this.retryCount; logger.trace("[master] failed to ping [{}], retry [{}] out of [{}]", exp, masterNode, retryCount, pingRetryCount); if (retryCount >= pingRetryCount) { logger.debug("[master] failed to ping [{}], tried [{}] times, each with maximum [{}] timeout", masterNode, pingRetryCount, pingRetryTimeout); // not good, failure notifyMasterFailure(masterToPing, "failed to ping, tried [" + pingRetryCount + "] times, each with maximum [" + pingRetryTimeout + "] timeout"); } else { // resend the request, not reschedule, rely on send timeout transportService.sendRequest(masterToPing, MASTER_PING_ACTION_NAME, request, options, this); } } } } @Override public String executor() { return ThreadPool.Names.SAME; } } ); } } /** Thrown when a ping reaches the wrong node */ static class ThisIsNotTheMasterYouAreLookingForException extends IllegalStateException { ThisIsNotTheMasterYouAreLookingForException(String msg) { super(msg); } ThisIsNotTheMasterYouAreLookingForException() { } @Override public Throwable fillInStackTrace() { return null; } } static class NodeDoesNotExistOnMasterException extends IllegalStateException { @Override public Throwable fillInStackTrace() { return null; } } private class MasterPingRequestHandler implements TransportRequestHandler<MasterPingRequest> { @Override public void messageReceived(final MasterPingRequest request, final TransportChannel channel) throws Exception { final DiscoveryNodes nodes = clusterService.state().nodes(); // check if we are really the same master as the one we seemed to be think we are // this can happen if the master got "kill -9" and then another node started using the same port if (!request.masterNodeId.equals(nodes.localNodeId())) { throw new ThisIsNotTheMasterYouAreLookingForException(); } // ping from nodes of version < 1.4.0 will have the clustername set to null if (request.clusterName != null && !request.clusterName.equals(clusterName)) { logger.trace("master fault detection ping request is targeted for a different [{}] cluster then us [{}]", request.clusterName, clusterName); throw new ThisIsNotTheMasterYouAreLookingForException("master fault detection ping request is targeted for a different [" + request.clusterName + "] cluster then us [" + clusterName + "]"); } // when we are elected as master or when a node joins, we use a cluster state update thread // to incorporate that information in the cluster state. That cluster state is published // before we make it available locally. This means that a master ping can come from a node // that has already processed the new CS but it is not known locally. // Therefore, if we fail we have to check again under a cluster state thread to make sure // all processing is finished. // if (!nodes.localNodeMaster() || !nodes.nodeExists(request.nodeId)) { logger.trace("checking ping from [{}] under a cluster state thread", request.nodeId); clusterService.submitStateUpdateTask("master ping (from: [" + request.nodeId + "])", new ProcessedClusterStateNonMasterUpdateTask() { @Override public ClusterState execute(ClusterState currentState) throws Exception { // if we are no longer master, fail... DiscoveryNodes nodes = currentState.nodes(); if (!nodes.localNodeMaster()) { throw new NotMasterException("local node is not master"); } if (!nodes.nodeExists(request.nodeId)) { throw new NodeDoesNotExistOnMasterException(); } return currentState; } @Override public void onFailure(String source, @Nullable Throwable t) { if (t == null) { t = new ElasticsearchException("unknown error while processing ping"); } try { channel.sendResponse(t); } catch (IOException e) { logger.warn("error while sending ping response", e); } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { try { channel.sendResponse(new MasterPingResponseResponse()); } catch (IOException e) { logger.warn("error while sending ping response", e); } } }); } else { // send a response, and note if we are connected to the master or not channel.sendResponse(new MasterPingResponseResponse()); } } } public static class MasterPingRequest extends TransportRequest { private String nodeId; private String masterNodeId; private ClusterName clusterName; public MasterPingRequest() { } private MasterPingRequest(String nodeId, String masterNodeId, ClusterName clusterName) { this.nodeId = nodeId; this.masterNodeId = masterNodeId; this.clusterName = clusterName; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); nodeId = in.readString(); masterNodeId = in.readString(); clusterName = ClusterName.readClusterName(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(nodeId); out.writeString(masterNodeId); clusterName.writeTo(out); } } private static class MasterPingResponseResponse extends TransportResponse { private MasterPingResponseResponse() { } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); } } }
himanshuag/elasticsearch
core/src/main/java/org/elasticsearch/discovery/zen/fd/MasterFaultDetection.java
Java
apache-2.0
19,229
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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. * * ***** END LICENSE BLOCK ***** */ /* THIS FILE WAS AUTOGENERATED BY mode.tmpl.js */ define(function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var NSISHighlightRules = require("./nsis_highlight_rules").NSISHighlightRules; var FoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = NSISHighlightRules; this.foldingRules = new FoldMode(); this.$behaviour = this.$defaultBehaviour; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = [";", "#"]; this.blockComment = {start: "/*", end: "*/"}; this.$id = "ace/mode/nsis"; }).call(Mode.prototype); exports.Mode = Mode; });
jecelyin/920-text-editor-v2
tools/assets/ace/lib/ace/mode/nsis.js
JavaScript
apache-2.0
2,369
(function( $ ) { /** * Activity reply object for the activity index screen * * @since 1.6 */ var activityReply = { /** * Attach event handler functions to the relevant elements. * * @since 1.6 */ init : function() { $(document).on( 'click', '.row-actions a.reply', activityReply.open ); $(document).on( 'click', '#bp-activities-container a.cancel', activityReply.close ); $(document).on( 'click', '#bp-activities-container a.save', activityReply.send ); // Close textarea on escape $(document).on( 'keyup', '#bp-activities:visible', function( e ) { if ( 27 == e.which ) { activityReply.close(); } }); }, /** * Reveals the entire row when "reply" is pressed. * * @since 1.6 */ open : function( e ) { // Hide the container row, and move it to the new location var box = $( '#bp-activities-container' ).hide(); $( this ).parents( 'tr' ).after( box ); // Fade the whole row in, and set focus on the text area. box.fadeIn( '300' ); $( '#bp-activities' ).focus(); return false; }, /** * Hide and reset the entire row when "cancel", or escape, are pressed. * * @since 1.6 */ close : function( e ) { // Hide the container row $('#bp-activities-container').fadeOut( '200', function () { // Empty and unfocus the text area $( '#bp-activities' ).val( '' ).blur(); // Remove any error message and disable the spinner $( '#bp-replysubmit .error' ).html( '' ).hide(); $( '#bp-replysubmit .waiting' ).hide(); }); return false; }, /** * Submits "form" via AJAX back to WordPress. * * @since 1.6 */ send : function( e ) { // Hide any existing error message, and show the loading spinner $( '#bp-replysubmit .error' ).hide(); $( '#bp-replysubmit .waiting' ).show(); // Grab the nonce var reply = {}; reply['_ajax_nonce-bp-activity-admin-reply'] = $( '#bp-activities-container input[name="_ajax_nonce-bp-activity-admin-reply"]' ).val(); // Get the rest of the data reply.action = 'bp-activity-admin-reply'; reply.content = $( '#bp-activities' ).val(); reply.parent_id = $( '#bp-activities-container' ).prev().data( 'parent_id' ); reply.root_id = $( '#bp-activities-container' ).prev().data( 'root_id' ); // Make the AJAX call $.ajax({ data : reply, type : 'POST', url : ajaxurl, // Callbacks error : function( r ) { activityReply.error( r ); }, success : function( r ) { activityReply.show( r ); } }); return false; }, /** * send() error message handler * * @since 1.6 */ error : function( r ) { var er = r.statusText; $('#bp-replysubmit .waiting').hide(); if ( r.responseText ) { er = r.responseText.replace( /<.[^<>]*?>/g, '' ); } if ( er ) { $('#bp-replysubmit .error').html( er ).show(); } }, /** * send() success handler * * @since 1.6 */ show : function ( xml ) { var bg, id, response; // Handle any errors in the response if ( typeof( xml ) == 'string' ) { activityReply.error( { 'responseText': xml } ); return false; } response = wpAjax.parseAjaxResponse( xml ); if ( response.errors ) { activityReply.error( { 'responseText': wpAjax.broken } ); return false; } response = response.responses[0]; // Close and reset the reply row, and add the new Activity item into the list. $('#bp-activities-container').fadeOut( '200', function () { // Empty and unfocus the text area $( '#bp-activities' ).val( '' ).blur(); // Remove any error message and disable the spinner $( '#bp-replysubmit .error' ).html( '' ).hide(); $( '#bp-replysubmit .waiting' ).hide(); // Insert new activity item $( '#bp-activities-container' ).before( response.data ); // Get background colour and animate the flash id = $( '#activity-' + response.id ); bg = id.closest( '.widefat' ).css( 'backgroundColor' ); id.animate( { 'backgroundColor': '#CEB' }, 300 ).animate( { 'backgroundColor': bg }, 300 ); }); } }; $(document).ready( function () { // Create the Activity reply object after domready event activityReply.init(); // On the edit screen, unload the close/open toggle js for the action & content metaboxes $( '#bp_activity_action h3, #bp_activity_content h3' ).unbind( 'click' ); }); })(jQuery);
jnishiyama/PebblesWP
wp-content/plugins/buddypress/bp-activity/admin/js/admin.dev.js
JavaScript
gpl-2.0
4,291
/** * @preserve SelectNav.js (v. 0.1) * Converts your <ul>/<ol> navigation into a dropdown list for small screens * https://github.com/lukaszfiszer/selectnav.js */ window.selectnav = (function(){ "use strict"; var selectnav = function(element,options){ element = document.getElementById(element); // return immediately if element doesn't exist if( ! element){ return; } // return immediately if element is not a list if( ! islist(element) ){ return; } // return immediately if no support for insertAdjacentHTML (Firefox 7 and under) if( ! ('insertAdjacentHTML' in window.document.documentElement) ){ return; } // add a js class to <html> tag document.documentElement.className += " js"; // retreive options and set defaults var o = options || {}, activeclass = o.activeclass || 'active', autoselect = typeof(o.autoselect) === "boolean" ? o.autoselect : true, nested = typeof(o.nested) === "boolean" ? o.nested : true, indent = o.indent || "→", label = o.label || "- Navigation -", // helper variables level = 0, selected = " selected "; // insert the freshly created dropdown navigation after the existing navigation element.insertAdjacentHTML('afterend', parselist(element) ); var nav = document.getElementById(id()); // autoforward on click if (nav.addEventListener) { nav.addEventListener('change',goTo); } if (nav.attachEvent) { nav.attachEvent('onchange', goTo); } return nav; function goTo(e){ // Crossbrowser issues - http://www.quirksmode.org/js/events_properties.html var targ; if (!e) e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType === 3) // defeat Safari bug targ = targ.parentNode; if(targ.value) window.location.href = targ.value; } function islist(list){ var n = list.nodeName.toLowerCase(); return (n === 'ul' || n === 'ol'); } function id(nextId){ for(var j=1; document.getElementById('selectnav'+j);j++); return (nextId) ? 'selectnav'+j : 'selectnav'+(j-1); } function parselist(list){ // go one level down level++; var length = list.children.length, html = '', prefix = '', k = level-1 ; // return immediately if has no children if (!length) { return; } if(k) { while(k--){ prefix += indent; } prefix += " "; } for(var i=0; i < length; i++){ var link = list.children[i].children[0]; if(typeof(link) !== 'undefined'){ var text = link.innerText || link.textContent; var isselected = ''; if(activeclass){ isselected = link.className.search(activeclass) !== -1 || link.parentNode.className.search(activeclass) !== -1 ? selected : ''; } if(autoselect && !isselected){ isselected = link.href === document.URL ? selected : ''; } html += '<option value="' + link.href + '" ' + isselected + '>' + prefix + text +'</option>'; if(nested){ var subElement = list.children[i].children[1]; if( subElement && islist(subElement) ){ html += parselist(subElement); } } } } // adds label if(level === 1 && label) { html = '<option value="">' + label + '</option>' + html; } // add <select> tag to the top level of the list if(level === 1) { html = '<select class="selectnav" id="'+id(true)+'">' + html + '</select>'; } // go 1 level up level--; return html; } }; return function (element,options) { selectnav(element,options); }; })();
rtdean93/drupalengage
store.drupalengage.com/profiles/commerce_kickstart/libraries/selectnav.js/selectnav.js
JavaScript
gpl-2.0
3,924
/*============================================================================= Copyright (c) 2002-2015 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // // A complex number micro parser. // // [ JDG May 10, 2002 ] spirit1 // [ JDG May 9, 2007 ] spirit2 // [ JDG May 12, 2015 ] spirit X3 // /////////////////////////////////////////////////////////////////////////////// #include <boost/config/warning_disable.hpp> #include <boost/spirit/home/x3.hpp> #include <iostream> #include <string> #include <complex> /////////////////////////////////////////////////////////////////////////////// // Our complex number parser/compiler /////////////////////////////////////////////////////////////////////////////// namespace client { template <typename Iterator> bool parse_complex(Iterator first, Iterator last, std::complex<double>& c) { using boost::spirit::x3::double_; using boost::spirit::x3::_attr; using boost::spirit::x3::phrase_parse; using boost::spirit::x3::ascii::space; double rN = 0.0; double iN = 0.0; auto fr = [&](auto& ctx){ rN = _attr(ctx); }; auto fi = [&](auto& ctx){ iN = _attr(ctx); }; bool r = phrase_parse(first, last, // Begin grammar ( '(' >> double_[fr] >> -(',' >> double_[fi]) >> ')' | double_[fr] ), // End grammar space); if (!r || first != last) // fail if we did not get a full match return false; c = std::complex<double>(rN, iN); return r; } } //////////////////////////////////////////////////////////////////////////// // Main program //////////////////////////////////////////////////////////////////////////// int main() { std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "\t\tA complex number micro parser for Spirit...\n\n"; std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "Give me a complex number of the form r or (r) or (r,i) \n"; std::cout << "Type [q or Q] to quit\n\n"; std::string str; while (getline(std::cin, str)) { if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; std::complex<double> c; if (client::parse_complex(str.begin(), str.end(), c)) { std::cout << "-------------------------\n"; std::cout << "Parsing succeeded\n"; std::cout << "got: " << c << std::endl; std::cout << "\n-------------------------\n"; } else { std::cout << "-------------------------\n"; std::cout << "Parsing failed\n"; std::cout << "-------------------------\n"; } } std::cout << "Bye... :-) \n\n"; return 0; }
gwq5210/litlib
thirdparty/sources/boost_1_60_0/libs/spirit/example/x3/complex_number.cpp
C++
gpl-3.0
3,196
# -*- coding: utf-8 -*- # # Copyright (C) 2013-2017 Vinay Sajip. # Licensed to the Python Software Foundation under a contributor agreement. # See LICENSE.txt and CONTRIBUTORS.txt. # from __future__ import absolute_import import os import re import sys try: import ssl except ImportError: # pragma: no cover ssl = None if sys.version_info[0] < 3: # pragma: no cover from StringIO import StringIO string_types = basestring, text_type = unicode from types import FileType as file_type import __builtin__ as builtins import ConfigParser as configparser from ._backport import shutil from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit from urllib import (urlretrieve, quote as _quote, unquote, url2pathname, pathname2url, ContentTooShortError, splittype) def quote(s): if isinstance(s, unicode): s = s.encode('utf-8') return _quote(s) import urllib2 from urllib2 import (Request, urlopen, URLError, HTTPError, HTTPBasicAuthHandler, HTTPPasswordMgr, HTTPHandler, HTTPRedirectHandler, build_opener) if ssl: from urllib2 import HTTPSHandler import httplib import xmlrpclib import Queue as queue from HTMLParser import HTMLParser import htmlentitydefs raw_input = raw_input from itertools import ifilter as filter from itertools import ifilterfalse as filterfalse _userprog = None def splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" global _userprog if _userprog is None: import re _userprog = re.compile('^(.*)@(.*)$') match = _userprog.match(host) if match: return match.group(1, 2) return None, host else: # pragma: no cover from io import StringIO string_types = str, text_type = str from io import TextIOWrapper as file_type import builtins import configparser import shutil from urllib.parse import (urlparse, urlunparse, urljoin, splituser, quote, unquote, urlsplit, urlunsplit, splittype) from urllib.request import (urlopen, urlretrieve, Request, url2pathname, pathname2url, HTTPBasicAuthHandler, HTTPPasswordMgr, HTTPHandler, HTTPRedirectHandler, build_opener) if ssl: from urllib.request import HTTPSHandler from urllib.error import HTTPError, URLError, ContentTooShortError import http.client as httplib import urllib.request as urllib2 import xmlrpc.client as xmlrpclib import queue from html.parser import HTMLParser import html.entities as htmlentitydefs raw_input = input from itertools import filterfalse filter = filter try: from ssl import match_hostname, CertificateError except ImportError: # pragma: no cover class CertificateError(ValueError): pass def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False parts = dn.split('.') leftmost, remainder = parts[0], parts[1:] wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn)) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == '*': # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append('[^.]+') elif leftmost.startswith('xn--') or hostname.startswith('xn--'): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) return pat.match(hostname) def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED") dnsnames = [] san = cert.get('subjectAltName', ()) for key, value in san: if key == 'DNS': if _dnsname_match(value, hostname): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get('subject', ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == 'commonName': if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError("hostname %r " "doesn't match either of %s" % (hostname, ', '.join(map(repr, dnsnames)))) elif len(dnsnames) == 1: raise CertificateError("hostname %r " "doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError("no appropriate commonName or " "subjectAltName fields were found") try: from types import SimpleNamespace as Container except ImportError: # pragma: no cover class Container(object): """ A generic container for when multiple values need to be returned """ def __init__(self, **kwargs): self.__dict__.update(kwargs) try: from shutil import which except ImportError: # pragma: no cover # Implementation from Python 3.3 def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. """ # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_check(fn, mode): return (os.path.exists(fn) and os.access(fn, mode) and not os.path.isdir(fn)) # If we're given a path with a directory part, look it up directly rather # than referring to PATH directories. This includes checking relative to the # current directory, e.g. ./script if os.path.dirname(cmd): if _access_check(cmd, mode): return cmd return None if path is None: path = os.environ.get("PATH", os.defpath) if not path: return None path = path.split(os.pathsep) if sys.platform == "win32": # The current directory takes precedence on Windows. if not os.curdir in path: path.insert(0, os.curdir) # PATHEXT is necessary to check on Windows. pathext = os.environ.get("PATHEXT", "").split(os.pathsep) # See if the given file matches any of the expected path extensions. # This will allow us to short circuit when given "python.exe". # If it does match, only test that one, otherwise we have to try # others. if any(cmd.lower().endswith(ext.lower()) for ext in pathext): files = [cmd] else: files = [cmd + ext for ext in pathext] else: # On other platforms you don't have things like PATHEXT to tell you # what file suffixes are executable, so just pass on cmd as-is. files = [cmd] seen = set() for dir in path: normdir = os.path.normcase(dir) if not normdir in seen: seen.add(normdir) for thefile in files: name = os.path.join(dir, thefile) if _access_check(name, mode): return name return None # ZipFile is a context manager in 2.7, but not in 2.6 from zipfile import ZipFile as BaseZipFile if hasattr(BaseZipFile, '__enter__'): # pragma: no cover ZipFile = BaseZipFile else: # pragma: no cover from zipfile import ZipExtFile as BaseZipExtFile class ZipExtFile(BaseZipExtFile): def __init__(self, base): self.__dict__.update(base.__dict__) def __enter__(self): return self def __exit__(self, *exc_info): self.close() # return None, so if an exception occurred, it will propagate class ZipFile(BaseZipFile): def __enter__(self): return self def __exit__(self, *exc_info): self.close() # return None, so if an exception occurred, it will propagate def open(self, *args, **kwargs): base = BaseZipFile.open(self, *args, **kwargs) return ZipExtFile(base) try: from platform import python_implementation except ImportError: # pragma: no cover def python_implementation(): """Return a string identifying the Python implementation.""" if 'PyPy' in sys.version: return 'PyPy' if os.name == 'java': return 'Jython' if sys.version.startswith('IronPython'): return 'IronPython' return 'CPython' try: import sysconfig except ImportError: # pragma: no cover from ._backport import sysconfig try: callable = callable except NameError: # pragma: no cover from collections.abc import Callable def callable(obj): return isinstance(obj, Callable) try: fsencode = os.fsencode fsdecode = os.fsdecode except AttributeError: # pragma: no cover # Issue #99: on some systems (e.g. containerised), # sys.getfilesystemencoding() returns None, and we need a real value, # so fall back to utf-8. From the CPython 2.7 docs relating to Unix and # sys.getfilesystemencoding(): the return value is "the user’s preference # according to the result of nl_langinfo(CODESET), or None if the # nl_langinfo(CODESET) failed." _fsencoding = sys.getfilesystemencoding() or 'utf-8' if _fsencoding == 'mbcs': _fserrors = 'strict' else: _fserrors = 'surrogateescape' def fsencode(filename): if isinstance(filename, bytes): return filename elif isinstance(filename, text_type): return filename.encode(_fsencoding, _fserrors) else: raise TypeError("expect bytes or str, not %s" % type(filename).__name__) def fsdecode(filename): if isinstance(filename, text_type): return filename elif isinstance(filename, bytes): return filename.decode(_fsencoding, _fserrors) else: raise TypeError("expect bytes or str, not %s" % type(filename).__name__) try: from tokenize import detect_encoding except ImportError: # pragma: no cover from codecs import BOM_UTF8, lookup import re cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)") def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): return "iso-8859-1" return orig_enc def detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. """ try: filename = readline.__self__.name except AttributeError: filename = None bom_found = False encoding = None default = 'utf-8' def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: # Decode as UTF-8. Either the line is an encoding declaration, # in which case it should be pure ASCII, or it must be UTF-8 # per default encoding. line_string = line.decode('utf-8') except UnicodeDecodeError: msg = "invalid or missing encoding declaration" if filename is not None: msg = '{} for {!r}'.format(msg, filename) raise SyntaxError(msg) matches = cookie_re.findall(line_string) if not matches: return None encoding = _get_normal_name(matches[0]) try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter if filename is None: msg = "unknown encoding: " + encoding else: msg = "unknown encoding for {!r}: {}".format(filename, encoding) raise SyntaxError(msg) if bom_found: if codec.name != 'utf-8': # This behaviour mimics the Python interpreter if filename is None: msg = 'encoding problem: utf-8' else: msg = 'encoding problem for {!r}: utf-8'.format(filename) raise SyntaxError(msg) encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second] # For converting & <-> &amp; etc. try: from html import escape except ImportError: from cgi import escape if sys.version_info[:2] < (3, 4): unescape = HTMLParser().unescape else: from html import unescape try: from collections import ChainMap except ImportError: # pragma: no cover from collections import MutableMapping try: from reprlib import recursive_repr as _recursive_repr except ImportError: def _recursive_repr(fillvalue='...'): ''' Decorator to make a repr function return fillvalue for a recursive call ''' def decorating_function(user_function): repr_running = set() def wrapper(self): key = id(self), get_ident() if key in repr_running: return fillvalue repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result # Can't use functools.wraps() here because of bootstrap issues wrapper.__module__ = getattr(user_function, '__module__') wrapper.__doc__ = getattr(user_function, '__doc__') wrapper.__name__ = getattr(user_function, '__name__') wrapper.__annotations__ = getattr(user_function, '__annotations__', {}) return wrapper return decorating_function class ChainMap(MutableMapping): ''' A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view. The underlying mappings are stored in a list. That list is public and can accessed or updated using the *maps* attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping. ''' def __init__(self, *maps): '''Initialize a ChainMap by setting *maps* to the given mappings. If no mappings are provided, a single empty dictionary is used. ''' self.maps = list(maps) or [{}] # always at least one map def __missing__(self, key): raise KeyError(key) def __getitem__(self, key): for mapping in self.maps: try: return mapping[key] # can't use 'key in mapping' with defaultdict except KeyError: pass return self.__missing__(key) # support subclasses that define __missing__ def get(self, key, default=None): return self[key] if key in self else default def __len__(self): return len(set().union(*self.maps)) # reuses stored hash values if possible def __iter__(self): return iter(set().union(*self.maps)) def __contains__(self, key): return any(key in m for m in self.maps) def __bool__(self): return any(self.maps) @_recursive_repr() def __repr__(self): return '{0.__class__.__name__}({1})'.format( self, ', '.join(map(repr, self.maps))) @classmethod def fromkeys(cls, iterable, *args): 'Create a ChainMap with a single dict created from the iterable.' return cls(dict.fromkeys(iterable, *args)) def copy(self): 'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]' return self.__class__(self.maps[0].copy(), *self.maps[1:]) __copy__ = copy def new_child(self): # like Django's Context.push() 'New ChainMap with a new dict followed by all previous maps.' return self.__class__({}, *self.maps) @property def parents(self): # like Django's Context.pop() 'New ChainMap from maps[1:].' return self.__class__(*self.maps[1:]) def __setitem__(self, key, value): self.maps[0][key] = value def __delitem__(self, key): try: del self.maps[0][key] except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def popitem(self): 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' try: return self.maps[0].popitem() except KeyError: raise KeyError('No keys found in the first mapping.') def pop(self, key, *args): 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' try: return self.maps[0].pop(key, *args) except KeyError: raise KeyError('Key not found in the first mapping: {!r}'.format(key)) def clear(self): 'Clear maps[0], leaving maps[1:] intact.' self.maps[0].clear() try: from importlib.util import cache_from_source # Python >= 3.4 except ImportError: # pragma: no cover try: from imp import cache_from_source except ImportError: # pragma: no cover def cache_from_source(path, debug_override=None): assert path.endswith('.py') if debug_override is None: debug_override = __debug__ if debug_override: suffix = 'c' else: suffix = 'o' return path + suffix try: from collections import OrderedDict except ImportError: # pragma: no cover ## {{{ http://code.activestate.com/recipes/576693/ (r9) # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy. # Passes Python2.7's test suite and incorporates all the latest updates. try: from thread import get_ident as _get_ident except ImportError: from dummy_thread import get_ident as _get_ident try: from _abcoll import KeysView, ValuesView, ItemsView except ImportError: pass class OrderedDict(dict): 'Dictionary that remembers insertion order' # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. # The remaining methods are order-aware. # Big-O running times for all methods are the same as for regular dictionaries. # The internal self.__map dictionary maps keys to links in a doubly linked list. # The circular doubly linked list starts and ends with a sentinel element. # The sentinel element never gets deleted (this simplifies the algorithm). # Each link is stored as a list of length three: [PREV, NEXT, KEY]. def __init__(self, *args, **kwds): '''Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. ''' if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__root except AttributeError: self.__root = root = [] # sentinel node root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link which goes at the end of the linked # list, and the inherited dictionary is updated with the new key/value pair. if key not in self: root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which is # then removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link_prev, link_next, key = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev def __iter__(self): 'od.__iter__() <==> iter(od)' root = self.__root curr = root[1] while curr is not root: yield curr[2] curr = curr[1] def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0] def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self) def popitem(self, last=True): '''od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next[0] = root key = link[2] del self.__map[key] value = dict.pop(self, key) return key, value # -- the following methods do not depend on the internal structure -- def keys(self): 'od.keys() -> list of keys in od' return list(self) def values(self): 'od.values() -> list of values in od' return [self[key] for key in self] def items(self): 'od.items() -> list of (key, value) pairs in od' return [(key, self[key]) for key in self] def iterkeys(self): 'od.iterkeys() -> an iterator over the keys in od' return iter(self) def itervalues(self): 'od.itervalues -> an iterator over the values in od' for k in self: yield self[k] def iteritems(self): 'od.iteritems -> an iterator over the (key, value) items in od' for k in self: yield (k, self[k]) def update(*args, **kwds): '''od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v ''' if len(args) > 2: raise TypeError('update() takes at most 2 positional ' 'arguments (%d given)' % (len(args),)) elif not args: raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] # Make progressively weaker assumptions about "other" other = () if len(args) == 2: other = args[1] if isinstance(other, dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): for key in other.keys(): self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwds.items(): self[key] = value __update = update # let subclasses override update without breaking __init__ __marker = object() def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default def setdefault(self, key, default=None): 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' if key in self: return self[key] self[key] = default return default def __repr__(self, _repr_running=None): 'od.__repr__() <==> repr(od)' if not _repr_running: _repr_running = {} call_key = id(self), _get_ident() if call_key in _repr_running: return '...' _repr_running[call_key] = 1 try: if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key] def __reduce__(self): 'Return state information for pickling' items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None). ''' d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return len(self)==len(other) and self.items() == other.items() return dict.__eq__(self, other) def __ne__(self, other): return not self == other # -- the following methods are only used in Python 2.7 -- def viewkeys(self): "od.viewkeys() -> a set-like object providing a view on od's keys" return KeysView(self) def viewvalues(self): "od.viewvalues() -> an object providing a view on od's values" return ValuesView(self) def viewitems(self): "od.viewitems() -> a set-like object providing a view on od's items" return ItemsView(self) try: from logging.config import BaseConfigurator, valid_ident except ImportError: # pragma: no cover IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) def valid_ident(s): m = IDENTIFIER.match(s) if not m: raise ValueError('Not a valid Python identifier: %r' % s) return True # The ConvertingXXX classes are wrappers around standard Python containers, # and they serve to convert any suitable values in the container. The # conversion converts base dicts, lists and tuples to their wrapped # equivalents, whereas strings which match a conversion format are converted # appropriately. # # Each wrapper should have a configurator attribute holding the actual # configurator to use for conversion. class ConvertingDict(dict): """A converting dictionary wrapper.""" def __getitem__(self, key): value = dict.__getitem__(self, key) result = self.configurator.convert(value) #If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def get(self, key, default=None): value = dict.get(self, key, default) result = self.configurator.convert(value) #If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, key, default=None): value = dict.pop(self, key, default) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class ConvertingList(list): """A converting list wrapper.""" def __getitem__(self, key): value = list.__getitem__(self, key) result = self.configurator.convert(value) #If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, idx=-1): value = list.pop(self, idx) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self return result class ConvertingTuple(tuple): """A converting tuple wrapper.""" def __getitem__(self, key): value = tuple.__getitem__(self, key) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class BaseConfigurator(object): """ The configurator base class which defines some useful defaults. """ CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$') WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') DIGIT_PATTERN = re.compile(r'^\d+$') value_converters = { 'ext' : 'ext_convert', 'cfg' : 'cfg_convert', } # We might want to use a different one, e.g. importlib importer = staticmethod(__import__) def __init__(self, config): self.config = ConvertingDict(config) self.config.configurator = self def resolve(self, s): """ Resolve strings to objects using standard import and attribute syntax. """ name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) except AttributeError: self.importer(used) found = getattr(found, frag) return found except ImportError: e, tb = sys.exc_info()[1:] v = ValueError('Cannot resolve %r: %s' % (s, e)) v.__cause__, v.__traceback__ = e, tb raise v def ext_convert(self, value): """Default converter for the ext:// protocol.""" return self.resolve(value) def cfg_convert(self, value): """Default converter for the cfg:// protocol.""" rest = value m = self.WORD_PATTERN.match(rest) if m is None: raise ValueError("Unable to convert %r" % value) else: rest = rest[m.end():] d = self.config[m.groups()[0]] #print d, rest while rest: m = self.DOT_PATTERN.match(rest) if m: d = d[m.groups()[0]] else: m = self.INDEX_PATTERN.match(rest) if m: idx = m.groups()[0] if not self.DIGIT_PATTERN.match(idx): d = d[idx] else: try: n = int(idx) # try as number first (most likely) d = d[n] except TypeError: d = d[idx] if m: rest = rest[m.end():] else: raise ValueError('Unable to convert ' '%r at %r' % (value, rest)) #rest should be empty return d def convert(self, value): """ Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ if not isinstance(value, ConvertingDict) and isinstance(value, dict): value = ConvertingDict(value) value.configurator = self elif not isinstance(value, ConvertingList) and isinstance(value, list): value = ConvertingList(value) value.configurator = self elif not isinstance(value, ConvertingTuple) and\ isinstance(value, tuple): value = ConvertingTuple(value) value.configurator = self elif isinstance(value, string_types): m = self.CONVERT_PATTERN.match(value) if m: d = m.groupdict() prefix = d['prefix'] converter = self.value_converters.get(prefix, None) if converter: suffix = d['suffix'] converter = getattr(self, converter) value = converter(suffix) return value def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') if not callable(c): c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) result = c(**kwargs) if props: for name, value in props.items(): setattr(result, name, value) return result def as_tuple(self, value): """Utility function which converts lists to tuples.""" if isinstance(value, list): value = tuple(value) return value
RalfBarkow/Zettelkasten
venv/lib/python3.9/site-packages/pip/_vendor/distlib/compat.py
Python
gpl-3.0
41,408
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package profilefield * @subpackage checkbox * @copyright 2008 onwards Shane Elliot {@link http://pukunui.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2013110500; // The current plugin version (Date: YYYYMMDDXX) $plugin->requires = 2013110500; // Requires this Moodle version $plugin->component = 'profilefield_checkbox'; // Full name of the plugin (used for diagnostics)
jethac/moodle
user/profile/field/checkbox/version.php
PHP
gpl-3.0
1,186
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ namespace Shopware\Bundle\PluginInstallerBundle\Struct; /** * Class CommentStruct * @package Shopware\Bundle\PluginInstallerBundle\Struct */ class CommentStruct implements \JsonSerializable { /** * @var string */ private $author; /** * @var string */ private $text; /** * @var string */ private $headline; /** * @var int */ private $rating; /** * @var \DateTime */ private $creationDate = null; /** * @inheritdoc */ public function jsonSerialize() { return get_object_vars($this); } /** * @return string */ public function getAuthor() { return $this->author; } /** * @param string $author */ public function setAuthor($author) { $this->author = $author; } /** * @return string */ public function getText() { return $this->text; } /** * @param string $text */ public function setText($text) { $this->text = $text; } /** * @return string */ public function getHeadline() { return $this->headline; } /** * @param string $headline */ public function setHeadline($headline) { $this->headline = $headline; } /** * @return int */ public function getRating() { return $this->rating; } /** * @param int $rating */ public function setRating($rating) { $this->rating = $rating; } /** * @return \DateTime */ public function getCreationDate() { return $this->creationDate; } /** * @param \DateTime $creationDate */ public function setCreationDate(\DateTime $creationDate) { $this->creationDate = $creationDate; } }
jenalgit/shopware
engine/Shopware/Bundle/PluginInstallerBundle/Struct/CommentStruct.php
PHP
agpl-3.0
2,823
#include "PresetMerge.hpp" #include <iostream> void PresetMerger::MergePresets(PresetOutputs & A, PresetOutputs & B, mathtype ratio, int gx, int gy) { mathtype invratio = mathval(1.0f) - ratio; //Merge Simple Waveforms // // All the mess is because of Waveform 7, which is two lines. // A.wave_rot = mathmul(A.wave_rot ,invratio) + mathmul(B.wave_rot,ratio); A.wave_scale = mathmul(A.wave_scale, invratio) + mathmul(B.wave_scale,ratio); if (!B.draw_wave_as_loop) A.draw_wave_as_loop = false; if (A.two_waves && B.two_waves) { for (int x = 0; x<A.wave_samples;x++) { A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio); A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio); A.wavearray2[x][0] = mathmul(A.wavearray2[x][0], invratio) + mathmul(B.wavearray2[x][0], ratio); A.wavearray2[x][1] = mathmul(A.wavearray2[x][1], invratio) + mathmul(B.wavearray2[x][1], ratio); } } else if (A.two_waves) { for (int x = 0; x<A.wave_samples;x++) { A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio); A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio); A.wavearray2[x][0] = mathmul(A.wavearray2[x][0], invratio) + mathmul(B.wavearray[x][0], ratio); A.wavearray2[x][1] = mathmul(A.wavearray2[x][1], invratio) + mathmul(B.wavearray[x][1], ratio); } } else if (B.two_waves) { A.two_waves=true; for (int x = 0; x<A.wave_samples;x++) { A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio); A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio); A.wavearray2[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio); A.wavearray2[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio); } } else { for (int x = 0; x<A.wave_samples;x++) { A.wavearray[x][0] = mathmul(A.wavearray[x][0], invratio) + mathmul(B.wavearray[x][0], ratio); A.wavearray[x][1] = mathmul(A.wavearray[x][1], invratio) + mathmul(B.wavearray[x][1], ratio); } } //Merge Custom Shapes and Custom Waves for (PresetOutputs::cshape_container::iterator pos = A.customShapes.begin(); pos != A.customShapes.end(); ++pos) { (*pos)->a = mathmul((*pos)->a, invratio); (*pos)->a2 = mathmul((*pos)->a2, invratio); (*pos)->border_a = mathmul((*pos)->border_a, invratio); } for (PresetOutputs::cshape_container::iterator pos = B.customShapes.begin(); pos != B.customShapes.end(); ++pos) { (*pos)->a = mathmul((*pos)->a, ratio); (*pos)->a2 = mathmul((*pos)->a2, ratio); (*pos)->border_a = mathmul((*pos)->border_a, ratio); A.customShapes.push_back(*pos); } for (PresetOutputs::cwave_container::iterator pos = A.customWaves.begin(); pos != A.customWaves.end(); ++pos) { (*pos)->a = mathmul((*pos)->a, invratio); for (int x=0; x < (*pos)->samples; x++) { (*pos)->a_mesh[x]= mathmul((*pos)->a_mesh[x],invratio); } } for (PresetOutputs::cwave_container::iterator pos = B.customWaves.begin(); pos != B.customWaves.end(); ++pos) { (*pos)->a = mathmul((*pos)->a,ratio); for (int x=0; x < (*pos)->samples; x++) { (*pos)->a_mesh[x]= mathmul((*pos)->a_mesh[x], ratio); } A.customWaves.push_back(*pos); } //Interpolate Per-Pixel mesh for (int x=0;x<gx;x++) { for(int y=0;y<gy;y++) { A.x_mesh[x][y] = mathmul(A.x_mesh[x][y], invratio) + mathmul(B.x_mesh[x][y], ratio); } } for (int x=0;x<gx;x++) { for(int y=0;y<gy;y++) { A.y_mesh[x][y] = mathmul(A.y_mesh[x][y], invratio) + mathmul(B.y_mesh[x][y], ratio); } } //Interpolate PerFrame mathtypes A.decay = mathmul(A.decay , invratio) + mathmul(B.decay, ratio); A.wave_r = mathmul(A.wave_r, invratio) + mathmul(B.wave_r, ratio); A.wave_g = mathmul(A.wave_g, invratio) + mathmul(B.wave_g, ratio); A.wave_b = mathmul(A.wave_b, invratio) + mathmul(B.wave_b, ratio); A.wave_o = mathmul(A.wave_o, invratio) + mathmul(B.wave_o, ratio); A.wave_x = mathmul(A.wave_x, invratio) + mathmul(B.wave_x, ratio); A.wave_y = mathmul(A.wave_y, invratio) + mathmul(B.wave_y, ratio); A.wave_mystery = mathmul(A.wave_mystery, invratio) + mathmul(B.wave_mystery, ratio); A.ob_size = mathmul(A.ob_size, invratio) + mathmul(B.ob_size, ratio); A.ob_r = mathmul(A.ob_r, invratio) + mathmul(B.ob_r, ratio); A.ob_g = mathmul(A.ob_g, invratio) + mathmul(B.ob_g, ratio); A.ob_b = mathmul(A.ob_b, invratio) + mathmul(B.ob_b, ratio); A.ob_a = mathmul(A.ob_a, invratio) + mathmul(B.ob_a, ratio); A.ib_size = mathmul(A.ib_size, invratio) + mathmul(B.ib_size, ratio); A.ib_r = mathmul(A.ib_r, invratio) + mathmul(B.ib_r, ratio); A.ib_g = mathmul(A.ib_g, invratio) + mathmul(B.ib_g, ratio); A.ib_b = mathmul(A.ib_b, invratio) + mathmul(B.ib_b, ratio); A.ib_a = mathmul(A.ib_a, invratio) + mathmul(B.ib_a, ratio); A.mv_a = mathmul(A.mv_a, invratio) + mathmul(B.mv_a, ratio); A.mv_r = mathmul(A.mv_r, invratio) + mathmul(B.mv_r, ratio); A.mv_g = mathmul(A.mv_g, invratio) + mathmul(B.mv_g, ratio); A.mv_b = mathmul(A.mv_b, invratio) + mathmul(B.mv_b, ratio); A.mv_l = mathmul(A.mv_l, invratio) + mathmul(B.mv_l, ratio); A.mv_x = mathmul(A.mv_x, invratio) + mathmul(B.mv_x, ratio); A.mv_y = mathmul(A.mv_y, invratio) + mathmul(B.mv_y, ratio); A.mv_dy = mathmul(A.mv_dy, invratio) + mathmul(B.mv_dy, ratio); A.mv_dx = mathmul(A.mv_dx, invratio) + mathmul(B.mv_dx, ratio); A.fRating = mathmul(A.fRating, invratio) + mathmul(B.fRating, ratio); A.fGammaAdj = mathmul(A.fGammaAdj, invratio) + mathmul(B.fGammaAdj, ratio); A.fVideoEchoZoom = mathmul(A.fVideoEchoZoom, invratio) + mathmul(B.fVideoEchoZoom, ratio); A.fVideoEchoAlpha = mathmul(A.fVideoEchoAlpha, invratio) + mathmul(B.fVideoEchoAlpha, ratio); A.fWaveAlpha = mathmul(A.fWaveAlpha, invratio) + mathmul(B.fWaveAlpha, ratio); A.fWaveScale = mathmul(A.fWaveScale, invratio) + mathmul(B.fWaveScale, ratio); A.fWaveSmoothing = mathmul(A.fWaveSmoothing, invratio) + mathmul(B.fWaveSmoothing, ratio); A.fWaveParam = mathmul(A.fWaveParam, invratio) + mathmul(B.fWaveParam, ratio); A.fModWaveAlphaStart = mathmul(A.fModWaveAlphaStart, invratio) + mathmul(B.fModWaveAlphaStart, ratio); A.fModWaveAlphaEnd = mathmul(A.fModWaveAlphaEnd , invratio) + mathmul(B.fModWaveAlphaEnd , ratio); A.fWarpAnimSpeed = mathmul(A.fWarpAnimSpeed, invratio) + mathmul(B.fWarpAnimSpeed, ratio); A.fWarpScale = mathmul(A.fWarpScale, invratio) + mathmul(B.fWarpScale, ratio); A.fShader = mathmul(A.fShader, invratio) + mathmul(B.fShader, ratio); //Switch bools and discrete values halfway. Maybe we should do some interesting stuff here. if (ratio > 0.5) { A.nVideoEchoOrientation = B.nVideoEchoOrientation; A.nWaveMode = B.nWaveMode; A.bAdditiveWaves = B.bAdditiveWaves; A.bWaveDots = B.bWaveDots; A.bWaveThick = B.bWaveThick; A.bModWaveAlphaByVolume = B.bModWaveAlphaByVolume; A.bMaximizeWaveColor = B.bMaximizeWaveColor; A.bTexWrap = B.bTexWrap; A.bDarkenCenter = B.bDarkenCenter; A.bRedBlueStereo = B.bRedBlueStereo; A.bBrighten = B.bBrighten; A.bDarken = B.bDarken; A.bSolarize = B.bSolarize; A.bInvert = B.bInvert; A.bMotionVectorsOn = B.bMotionVectorsOn; } return; }
neurocis/sagetv
third_party/VisEngine/PresetMerge.cpp
C++
apache-2.0
7,592
function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "index"; this.args = arguments[0] || {}; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } { __processArg(arguments[0], "$model"); } { __processArg(arguments[0], "__itemTemplate"); } } var $ = this; var exports = {}; $.__views.index = Ti.UI.createWindow({ backgroundColor: "#fff", fullscreen: false, exitOnClose: true, id: "index" }); $.__views.index && $.addTopLevelView($.__views.index); $.__views.__alloyId0 = Ti.UI.createLabel({ text: "This app is supported only on iOS", id: "__alloyId0" }); $.__views.index.add($.__views.__alloyId0); exports.destroy = function() {}; _.extend($, $.__views); $.index.open(); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
jvkops/alloy
test/apps/testing/ALOY-262/_generated/mobileweb/alloy/controllers/index.js
JavaScript
apache-2.0
1,252
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package app import ( "github.com/golang/glog" // HACK to ensure that rest mapper from pkg/api is registered for groupName="". // This is required because both pkg/api/install and federation/apis/core/install // are installing their respective groupMeta at the same groupName. // federation/apis/core/install has only a subset of resources and hence if it gets registered first, then installation of v1 API fails in pkg/master. // TODO(nikhiljindal): Fix this by ensuring that pkg/api/install and federation/apis/core/install do not conflict with each other. _ "k8s.io/kubernetes/pkg/api/install" "k8s.io/kubernetes/federation/apis/core" _ "k8s.io/kubernetes/federation/apis/core/install" "k8s.io/kubernetes/federation/apis/core/v1" "k8s.io/kubernetes/federation/cmd/federation-apiserver/app/options" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/rest" "k8s.io/kubernetes/pkg/apimachinery/registered" "k8s.io/kubernetes/pkg/genericapiserver" configmapetcd "k8s.io/kubernetes/pkg/registry/core/configmap/etcd" eventetcd "k8s.io/kubernetes/pkg/registry/core/event/etcd" namespaceetcd "k8s.io/kubernetes/pkg/registry/core/namespace/etcd" secretetcd "k8s.io/kubernetes/pkg/registry/core/secret/etcd" serviceetcd "k8s.io/kubernetes/pkg/registry/core/service/etcd" ) func installCoreAPIs(s *options.ServerRunOptions, g *genericapiserver.GenericAPIServer, restOptionsFactory restOptionsFactory) { serviceStore, serviceStatusStore := serviceetcd.NewREST(restOptionsFactory.NewFor(api.Resource("service"))) namespaceStore, namespaceStatusStore, namespaceFinalizeStore := namespaceetcd.NewREST(restOptionsFactory.NewFor(api.Resource("namespaces"))) secretStore := secretetcd.NewREST(restOptionsFactory.NewFor(api.Resource("secrets"))) configMapStore := configmapetcd.NewREST(restOptionsFactory.NewFor(api.Resource("configmaps"))) eventStore := eventetcd.NewREST(restOptionsFactory.NewFor(api.Resource("events")), uint64(s.EventTTL.Seconds())) coreResources := map[string]rest.Storage{ "secrets": secretStore, "services": serviceStore, "services/status": serviceStatusStore, "namespaces": namespaceStore, "namespaces/status": namespaceStatusStore, "namespaces/finalize": namespaceFinalizeStore, "events": eventStore, "configmaps": configMapStore, } coreGroupMeta := registered.GroupOrDie(core.GroupName) apiGroupInfo := genericapiserver.APIGroupInfo{ GroupMeta: *coreGroupMeta, VersionedResourcesStorageMap: map[string]map[string]rest.Storage{ v1.SchemeGroupVersion.Version: coreResources, }, OptionsExternalVersion: &registered.GroupOrDie(core.GroupName).GroupVersion, Scheme: core.Scheme, ParameterCodec: core.ParameterCodec, NegotiatedSerializer: core.Codecs, } if err := g.InstallLegacyAPIGroup(genericapiserver.DefaultLegacyAPIPrefix, &apiGroupInfo); err != nil { glog.Fatalf("Error in registering group version: %+v.\n Error: %v\n", apiGroupInfo, err) } }
rawlingsj/gofabric8
vendor/k8s.io/kubernetes/federation/cmd/federation-apiserver/app/core.go
GO
apache-2.0
3,587
<?php final class PhabricatorPolicyConfigOptions extends PhabricatorApplicationConfigOptions { public function getName() { return pht('Policy'); } public function getDescription() { return pht('Options relating to object visibility.'); } public function getFontIcon() { return 'fa-lock'; } public function getGroup() { return 'apps'; } public function getOptions() { $policy_locked_type = 'custom:PolicyLockOptionType'; $policy_locked_example = array( 'people.create.users' => 'admin', ); $json = new PhutilJSON(); $policy_locked_example = $json->encodeFormatted($policy_locked_example); return array( $this->newOption('policy.allow-public', 'bool', false) ->setBoolOptions( array( pht('Allow Public Visibility'), pht('Require Login'), )) ->setSummary(pht('Allow users to set object visibility to public.')) ->setDescription( pht( "Phabricator allows you to set the visibility of objects (like ". "repositories and tasks) to 'Public', which means **anyone ". "on the internet can see them, without needing to log in or ". "have an account**.". "\n\n". "This is intended for open source projects. Many installs will ". "never want to make anything public, so this policy is disabled ". "by default. You can enable it here, which will let you set the ". "policy for objects to 'Public'.". "\n\n". "Enabling this setting will immediately open up some features, ". "like the user directory. Anyone on the internet will be able to ". "access these features.". "\n\n". "With this setting disabled, the 'Public' policy is not ". "available, and the most open policy is 'All Users' (which means ". "users must have accounts and be logged in to view things).")), $this->newOption('policy.locked', $policy_locked_type, array()) ->setLocked(true) ->setSummary(pht( 'Lock specific application policies so they can not be edited.')) ->setDescription(pht( 'Phabricator has application policies which can dictate whether '. 'users can take certain actions, such as creating new users. '."\n\n". 'This setting allows for "locking" these policies such that no '. 'further edits can be made on a per-policy basis.')) ->addExample( $policy_locked_example, pht('Lock Create User Policy To Admins')), ); } }
leolujuyi/phabricator
src/applications/policy/config/PhabricatorPolicyConfigOptions.php
PHP
apache-2.0
2,669
name1_0_1_0_0_4_0 = None name1_0_1_0_0_4_1 = None name1_0_1_0_0_4_2 = None name1_0_1_0_0_4_3 = None name1_0_1_0_0_4_4 = None
asedunov/intellij-community
python/testData/completion/heavyStarPropagation/lib/_pkg1/_pkg1_0/_pkg1_0_1/_pkg1_0_1_0/_pkg1_0_1_0_0/_mod1_0_1_0_0_4.py
Python
apache-2.0
128
import datetime from decimal import Decimal import types import six def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_unicode(strings_only=True). """ return isinstance(obj, ( six.integer_types + (types.NoneType, datetime.datetime, datetime.date, datetime.time, float, Decimal)) ) def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first, saves 30-40% when s is an instance of # six.text_type. This function gets called often in that setting. if isinstance(s, six.text_type): return s if strings_only and is_protected_type(s): return s try: if not isinstance(s, six.string_types): if hasattr(s, '__unicode__'): s = s.__unicode__() else: if six.PY3: if isinstance(s, bytes): s = six.text_type(s, encoding, errors) else: s = six.text_type(s) else: s = six.text_type(bytes(s), encoding, errors) else: # Note: We use .decode() here, instead of six.text_type(s, # encoding, errors), so that if s is a SafeBytes, it ends up being # a SafeText at the end. s = s.decode(encoding, errors) except UnicodeDecodeError as e: if not isinstance(s, Exception): raise UnicodeDecodeError(*e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = ' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) return s
unnikrishnankgs/va
venv/lib/python3.5/site-packages/external/org_mozilla_bleach/bleach/encoding.py
Python
bsd-2-clause
2,277
#include "cpu_profile.h" #include "cpu_profile_node.h" namespace nodex { using v8::Array; using v8::CpuProfile; using v8::CpuProfileNode; using v8::Handle; using v8::Number; using v8::Integer; using v8::Local; using v8::Object; using v8::ObjectTemplate; using v8::FunctionTemplate; using v8::String; using v8::Function; using v8::Value; Nan::Persistent<ObjectTemplate> Profile::profile_template_; Nan::Persistent<Object> Profile::profiles; uint32_t Profile::uid_counter = 0; NAN_METHOD(Profile_EmptyMethod) { } void Profile::Initialize () { Nan::HandleScope scope; Local<FunctionTemplate> f = Nan::New<FunctionTemplate>(Profile_EmptyMethod); Local<ObjectTemplate> o = f->InstanceTemplate(); o->SetInternalFieldCount(1); Nan::SetMethod(o, "delete", Profile::Delete); profile_template_.Reset(o); } NAN_METHOD(Profile::Delete) { Local<Object> self = info.This(); void* ptr = Nan::GetInternalFieldPointer(self, 0); Local<Object> profiles = Nan::New<Object>(Profile::profiles); Local<Value> _uid = info.This()->Get(Nan::New<String>("uid").ToLocalChecked()); Local<String> uid = Nan::To<String>(_uid).ToLocalChecked(); profiles->Delete(uid); static_cast<CpuProfile*>(ptr)->Delete(); } Local<Value> Profile::New (const CpuProfile* node) { Nan::EscapableHandleScope scope; if (profile_template_.IsEmpty()) { Profile::Initialize(); } uid_counter++; Local<Object> profile = Nan::New(profile_template_)->NewInstance(); Nan::SetInternalFieldPointer(profile, 0, const_cast<CpuProfile*>(node)); const uint32_t uid_length = (((sizeof uid_counter) * 8) + 2)/3 + 2; char _uid[uid_length]; sprintf(_uid, "%d", uid_counter); Local<Value> CPU = Nan::New<String>("CPU").ToLocalChecked(); Local<Value> uid = Nan::New<String>(_uid).ToLocalChecked(); #if (NODE_MODULE_VERSION >= 45) Local<String> title = node->GetTitle(); #else Local<String> title = Nan::New(node->GetTitle()); #endif if (!title->Length()) { char _title[8 + uid_length]; sprintf(_title, "Profile %i", uid_counter); title = Nan::New<String>(_title).ToLocalChecked(); } Local<Value> head = ProfileNode::New(node->GetTopDownRoot()); profile->Set(Nan::New<String>("typeId").ToLocalChecked(), CPU); profile->Set(Nan::New<String>("uid").ToLocalChecked(), uid); profile->Set(Nan::New<String>("title").ToLocalChecked(), title); profile->Set(Nan::New<String>("head").ToLocalChecked(), head); #if (NODE_MODULE_VERSION > 0x000B) Local<Value> start_time = Nan::New<Number>(node->GetStartTime()/1000000); Local<Value> end_time = Nan::New<Number>(node->GetEndTime()/1000000); Local<Array> samples = Nan::New<Array>(); Local<Array> timestamps = Nan::New<Array>(); uint32_t count = node->GetSamplesCount(); for (uint32_t index = 0; index < count; ++index) { samples->Set(index, Nan::New<Integer>(node->GetSample(index)->GetNodeId())); timestamps->Set(index, Nan::New<Number>(static_cast<double>(node->GetSampleTimestamp(index)))); } profile->Set(Nan::New<String>("startTime").ToLocalChecked(), start_time); profile->Set(Nan::New<String>("endTime").ToLocalChecked(), end_time); profile->Set(Nan::New<String>("samples").ToLocalChecked(), samples); profile->Set(Nan::New<String>("timestamps").ToLocalChecked(), timestamps); #endif Local<Object> profiles = Nan::New<Object>(Profile::profiles); profiles->Set(uid, profile); return scope.Escape(profile); } }
node-inspector/v8-profiler
src/cpu_profile.cc
C++
bsd-2-clause
3,600
/* * Copyright (c) 2014, 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. * */ #include <sstream> #include <fnmatch.h> #include <linux/limits.h> #include <boost/filesystem.hpp> #include <osquery/filesystem.h> #include <osquery/logger.h> #include "osquery/events/linux/inotify.h" namespace fs = boost::filesystem; namespace osquery { int kINotifyMLatency = 200; static const uint32_t BUFFER_SIZE = (10 * ((sizeof(struct inotify_event)) + NAME_MAX + 1)); std::map<int, std::string> kMaskActions = { {IN_ACCESS, "ACCESSED"}, {IN_ATTRIB, "ATTRIBUTES_MODIFIED"}, {IN_CLOSE_WRITE, "UPDATED"}, {IN_CREATE, "CREATED"}, {IN_DELETE, "DELETED"}, {IN_MODIFY, "UPDATED"}, {IN_MOVED_FROM, "MOVED_FROM"}, {IN_MOVED_TO, "MOVED_TO"}, {IN_OPEN, "OPENED"}, }; REGISTER(INotifyEventPublisher, "event_publisher", "inotify"); Status INotifyEventPublisher::setUp() { inotify_handle_ = ::inotify_init(); // If this does not work throw an exception. if (inotify_handle_ == -1) { return Status(1, "Could not start inotify: inotify_init failed"); } return Status(0, "OK"); } void INotifyEventPublisher::configure() { for (auto& sub : subscriptions_) { // Anytime a configure is called, try to monitor all subscriptions. // Configure is called as a response to removing/adding subscriptions. // This means recalculating all monitored paths. auto sc = getSubscriptionContext(sub->context); if (sc->discovered_.size() > 0) { continue; } sc->discovered_ = sc->path; if (sc->path.find("**") != std::string::npos) { sc->recursive = true; sc->discovered_ = sc->path.substr(0, sc->path.find("**")); sc->path = sc->discovered_; } if (sc->path.find('*') != std::string::npos) { // If the wildcard exists within the file (leaf), remove and monitor the // directory instead. Apply a fnmatch on fired events to filter leafs. auto fullpath = fs::path(sc->path); if (fullpath.filename().string().find('*') != std::string::npos) { sc->discovered_ = fullpath.parent_path().string(); } if (sc->discovered_.find('*') != std::string::npos) { // If a wildcard exists within the tree (stem), resolve at configure // time and monitor each path. std::vector<std::string> paths; resolveFilePattern(sc->discovered_, paths); for (const auto& _path : paths) { addMonitor(_path, sc->recursive); } sc->recursive_match = sc->recursive; continue; } } addMonitor(sc->discovered_, sc->recursive); } } void INotifyEventPublisher::tearDown() { ::close(inotify_handle_); inotify_handle_ = -1; } Status INotifyEventPublisher::restartMonitoring(){ if (last_restart_ != 0 && getUnixTime() - last_restart_ < 10) { return Status(1, "Overflow"); } last_restart_ = getUnixTime(); VLOG(1) << "inotify was overflown, attempting to restart handle"; for(const auto& desc : descriptors_){ removeMonitor(desc, 1); } path_descriptors_.clear(); descriptor_paths_.clear(); configure(); return Status(0, "OK"); } Status INotifyEventPublisher::run() { // Get a while wrapper for free. char buffer[BUFFER_SIZE]; fd_set set; FD_ZERO(&set); FD_SET(getHandle(), &set); struct timeval timeout = {3, 3000}; int selector = ::select(getHandle() + 1, &set, nullptr, nullptr, &timeout); if (selector == -1) { LOG(ERROR) << "Could not read inotify handle"; return Status(1, "INotify handle failed"); } if (selector == 0) { // Read timeout. return Status(0, "Continue"); } ssize_t record_num = ::read(getHandle(), buffer, BUFFER_SIZE); if (record_num == 0 || record_num == -1) { return Status(1, "INotify read failed"); } for (char* p = buffer; p < buffer + record_num;) { // Cast the inotify struct, make shared pointer, and append to contexts. auto event = reinterpret_cast<struct inotify_event*>(p); if (event->mask & IN_Q_OVERFLOW) { // The inotify queue was overflown (remove all paths). Status stat = restartMonitoring(); if(!stat.ok()){ return stat; } } if (event->mask & IN_IGNORED) { // This inotify watch was removed. removeMonitor(event->wd, false); } else if (event->mask & IN_MOVE_SELF) { // This inotify path was moved, but is still watched. removeMonitor(event->wd, true); } else if (event->mask & IN_DELETE_SELF) { // A file was moved to replace the watched path. removeMonitor(event->wd, false); } else { auto ec = createEventContextFrom(event); fire(ec); } // Continue to iterate p += (sizeof(struct inotify_event)) + event->len; } osquery::publisherSleep(kINotifyMLatency); return Status(0, "Continue"); } INotifyEventContextRef INotifyEventPublisher::createEventContextFrom( struct inotify_event* event) { auto shared_event = std::make_shared<struct inotify_event>(*event); auto ec = createEventContext(); ec->event = shared_event; // Get the pathname the watch fired on. ec->path = descriptor_paths_[event->wd]; if (event->len > 1) { ec->path += event->name; } for (const auto& action : kMaskActions) { if (event->mask & action.first) { ec->action = action.second; break; } } return ec; } bool INotifyEventPublisher::shouldFire(const INotifySubscriptionContextRef& sc, const INotifyEventContextRef& ec) const { if (sc->recursive && !sc->recursive_match) { ssize_t found = ec->path.find(sc->path); if (found != 0) { return false; } } else if (fnmatch((sc->path + "*").c_str(), ec->path.c_str(), FNM_PATHNAME | FNM_CASEFOLD | ((sc->recursive_match) ? FNM_LEADING_DIR : 0)) != 0) { // Only apply a leading-dir match if this is a recursive watch with a // match requirement (an inline wildcard with ending recursive wildcard). return false; } // The subscription may supply a required event mask. if (sc->mask != 0 && !(ec->event->mask & sc->mask)) { return false; } // inotify will not monitor recursively, new directories need watches. if(sc->recursive && ec->action == "CREATED" && isDirectory(ec->path)){ const_cast<INotifyEventPublisher*>(this)->addMonitor(ec->path + '/', true); } return true; } bool INotifyEventPublisher::addMonitor(const std::string& path, bool recursive) { if (!isPathMonitored(path)) { int watch = ::inotify_add_watch(getHandle(), path.c_str(), IN_ALL_EVENTS); if (watch == -1) { LOG(ERROR) << "Could not add inotify watch on: " << path; return false; } // Keep a list of the watch descriptors descriptors_.push_back(watch); // Keep a map of the path -> watch descriptor path_descriptors_[path] = watch; // Keep a map of the opposite (descriptor -> path) descriptor_paths_[watch] = path; } if (recursive && isDirectory(path).ok()) { std::vector<std::string> children; // Get a list of children of this directory (requested recursive watches). listDirectoriesInDirectory(path, children); for (const auto& child : children) { addMonitor(child, recursive); } } return true; } bool INotifyEventPublisher::removeMonitor(const std::string& path, bool force) { // If force then remove from INotify, otherwise cleanup file descriptors. if (path_descriptors_.find(path) == path_descriptors_.end()) { return false; } int watch = path_descriptors_[path]; path_descriptors_.erase(path); descriptor_paths_.erase(watch); auto position = std::find(descriptors_.begin(), descriptors_.end(), watch); descriptors_.erase(position); if (force) { ::inotify_rm_watch(getHandle(), watch); } return true; } bool INotifyEventPublisher::removeMonitor(int watch, bool force) { if (descriptor_paths_.find(watch) == descriptor_paths_.end()) { return false; } auto path = descriptor_paths_[watch]; return removeMonitor(path, force); } bool INotifyEventPublisher::isPathMonitored(const std::string& path) { boost::filesystem::path parent_path; if (!isDirectory(path).ok()) { if (path_descriptors_.find(path) != path_descriptors_.end()) { // Path is a file, and is directly monitored. return true; } if (!getDirectory(path, parent_path).ok()) { // Could not get parent of unmonitored file. return false; } } else { parent_path = path; } // Directory or parent of file monitoring auto path_iterator = path_descriptors_.find(parent_path.string()); return (path_iterator != path_descriptors_.end()); } }
honestme/osquery
osquery/events/linux/inotify.cpp
C++
bsd-3-clause
8,994
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/common/gpu/grcontext_for_webgraphicscontext3d.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/skia/include/gpu/GrContext.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" namespace webkit { namespace gpu { static void BindWebGraphicsContext3DGLContextCallback( const GrGLInterface* interface) { reinterpret_cast<WebKit::WebGraphicsContext3D*>( interface->fCallbackData)->makeContextCurrent(); } GrContextForWebGraphicsContext3D::GrContextForWebGraphicsContext3D( WebKit::WebGraphicsContext3D* context3d) { if (!context3d) return; skia::RefPtr<GrGLInterface> interface = skia::AdoptRef( context3d->createGrGLInterface()); if (!interface) return; interface->fCallback = BindWebGraphicsContext3DGLContextCallback; interface->fCallbackData = reinterpret_cast<GrGLInterfaceCallbackData>(context3d); gr_context_ = skia::AdoptRef(GrContext::Create( kOpenGL_GrBackend, reinterpret_cast<GrBackendContext>(interface.get()))); if (!gr_context_) return; bool nonzero_allocation = true; SetMemoryLimit(nonzero_allocation); } GrContextForWebGraphicsContext3D::~GrContextForWebGraphicsContext3D() { if (gr_context_) gr_context_->contextDestroyed(); } void GrContextForWebGraphicsContext3D::SetMemoryLimit(bool nonzero_allocation) { if (!gr_context_) return; if (nonzero_allocation) { // The limit of the number of textures we hold in the GrContext's // bitmap->texture cache. static const int kMaxGaneshTextureCacheCount = 2048; // The limit of the bytes allocated toward textures in the GrContext's // bitmap->texture cache. static const size_t kMaxGaneshTextureCacheBytes = 96 * 1024 * 1024; gr_context_->setTextureCacheLimits( kMaxGaneshTextureCacheCount, kMaxGaneshTextureCacheBytes); } else { gr_context_->freeGpuResources(); gr_context_->setTextureCacheLimits(0, 0); } } } // namespace gpu } // namespace webkit
aospx-kitkat/platform_external_chromium_org
webkit/common/gpu/grcontext_for_webgraphicscontext3d.cc
C++
bsd-3-clause
2,195
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("placeholder","sv",{title:"Innehållsrutans egenskaper",toolbar:"Skapa innehållsruta",name:"Innehållsrutans namn",invalidName:"Innehållsrutan får inte vara tom och får inte innehålla någon av följande tecken: [, ], \x3c, \x3e",pathName:"innehållsruta"});
Laravel-Backpack/crud
src/public/packages/ckeditor/plugins/placeholder/lang/sv.js
JavaScript
mit
456
# encoding: utf-8 require 'ffaker/address' module Faker module AddressDE include Faker::Address extend ModuleUtils extend self def zip_code Faker.numerify ZIP_FORMATS.rand end def state STATE.rand end def city CITY.rand end def street_name case rand(2) when 0 then "#{NameDE.last_name}" when 1 then "#{NameDE.first_name}" end << case rand(20) when 0 then "weg" when 1 then "gasse" when 3 then "hain" else "str." end end def street_address "#{street_name} #{1+rand(192)}" end ZIP_FORMATS = k ['#####'] end end
hyfn/ffaker
lib/ffaker/address_de.rb
Ruby
mit
656
<?php namespace Pagekit\Event; interface EventSubscriberInterface { /** * Returns an array of event names this subscriber wants to listen to. * * @return array */ public function subscribe(); }
yaelduckwen/entretelas
web/app/modules/application/src/Event/EventSubscriberInterface.php
PHP
mit
224
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, call_back) { frappe.dom.freeze(); if($.isPlainObject(arg)) arg = JSON.stringify(arg); return $c('runserverobj', args={'method': method, 'docs': JSON.stringify(doc), 'arg': arg }, function(r, rt) { frappe.dom.unfreeze(); if (r.message) { var d = locals[dt][dn]; var field_dict = r.message; for(var key in field_dict) { d[key] = field_dict[key]; if (table_field) refresh_field(key, d.name, table_field); else refresh_field(key); } } if(call_back){ doc = locals[doc.doctype][doc.name]; call_back(doc, dt, dn); } } ); } set_multiple = function (dt, dn, dict, table_field) { var d = locals[dt][dn]; for(var key in dict) { d[key] = dict[key]; if (table_field) refresh_field(key, d.name, table_field); else refresh_field(key); } } refresh_many = function (flist, dn, table_field) { for(var i in flist) { if (table_field) refresh_field(flist[i], dn, table_field); else refresh_field(flist[i]); } } set_field_tip = function(n,txt) { var df = frappe.meta.get_docfield(cur_frm.doctype, n, cur_frm.docname); if(df)df.description = txt; if(cur_frm && cur_frm.fields_dict) { if(cur_frm.fields_dict[n]) cur_frm.fields_dict[n].comment_area.innerHTML = replace_newlines(txt); else console.log('[set_field_tip] Unable to set field tip: ' + n); } } refresh_field = function(n, docname, table_field) { // multiple if(typeof n==typeof []) refresh_many(n, docname, table_field); if(table_field && cur_frm.fields_dict[table_field].grid.grid_rows_by_docname) { // for table cur_frm.fields_dict[table_field].grid.grid_rows_by_docname[docname].refresh_field(n); } else if(cur_frm) { cur_frm.refresh_field(n) } } set_field_options = function(n, txt) { cur_frm.set_df_property(n, 'options', txt) } set_field_permlevel = function(n, level) { cur_frm.set_df_property(n, 'permlevel', level) } toggle_field = function(n, hidden) { var df = frappe.meta.get_docfield(cur_frm.doctype, n, cur_frm.docname); if(df) { df.hidden = hidden; refresh_field(n); } else { console.log((hidden ? "hide_field" : "unhide_field") + " cannot find field " + n); } } hide_field = function(n) { if(cur_frm) { if(n.substr) toggle_field(n, 1); else { for(var i in n) toggle_field(n[i], 1) } } } unhide_field = function(n) { if(cur_frm) { if(n.substr) toggle_field(n, 0); else { for(var i in n) toggle_field(n[i], 0) } } } get_field_obj = function(fn) { return cur_frm.fields_dict[fn]; } // set missing values in given doc set_missing_values = function(doc, dict) { // dict contains fieldname as key and "default value" as value var fields_to_set = {}; $.each(dict, function(i, v) { if (!doc[i]) { fields_to_set[i] = v; } }); if (fields_to_set) { set_multiple(doc.doctype, doc.name, fields_to_set); } } _f.Frm.prototype.get_doc = function() { return locals[this.doctype][this.docname]; } _f.Frm.prototype.field_map = function(fnames, fn) { if(typeof fnames==='string') { if(fnames == '*') { fnames = keys(this.fields_dict); } else { fnames = [fnames]; } } $.each(fnames, function(i,fieldname) { //var field = cur_frm.fields_dict[f]; - much better design var field = frappe.meta.get_docfield(cur_frm.doctype, fieldname, cur_frm.docname); if(field) { fn(field); cur_frm.refresh_field(fieldname); }; }) } _f.Frm.prototype.set_df_property = function(fieldname, property, value) { var field = frappe.meta.get_docfield(cur_frm.doctype, fieldname, cur_frm.docname) if(field) { field[property] = value; cur_frm.refresh_field(fieldname); }; } _f.Frm.prototype.toggle_enable = function(fnames, enable) { cur_frm.field_map(fnames, function(field) { field.read_only = enable ? 0 : 1; }); } _f.Frm.prototype.toggle_reqd = function(fnames, mandatory) { cur_frm.field_map(fnames, function(field) { field.reqd = mandatory ? true : false; }); } _f.Frm.prototype.toggle_display = function(fnames, show) { cur_frm.field_map(fnames, function(field) { field.hidden = show ? 0 : 1; }); } _f.Frm.prototype.call_server = function(method, args, callback) { return $c_obj(cur_frm.doc, method, args, callback); } _f.Frm.prototype.get_files = function() { return cur_frm.attachments ? frappe.utils.sort(cur_frm.attachments.get_attachments(), "file_name", "string") : [] ; } _f.Frm.prototype.set_query = function(fieldname, opt1, opt2) { var func = (typeof opt1=="function") ? opt1 : opt2; if(opt2) { this.fields_dict[opt1].grid.get_field(fieldname).get_query = func; } else { this.fields_dict[fieldname].get_query = func; } } _f.Frm.prototype.set_value_if_missing = function(field, value) { this.set_value(field, value, true); } _f.Frm.prototype.set_value = function(field, value, if_missing) { var me = this; var _set = function(f, v) { var fieldobj = me.fields_dict[f]; if(fieldobj) { if(!if_missing || !frappe.model.has_value(me.doctype, me.doc.name, f)) { if(fieldobj.df.fieldtype==="Table" && $.isArray(v)) { frappe.model.clear_table(me.doc, fieldobj.df.fieldname); $.each(v, function(i, d) { var child = frappe.model.add_child(me.doc, fieldobj.df.options, fieldobj.df.fieldname, i+1); $.extend(child, d); }); me.refresh_field(f); } else { frappe.model.set_value(me.doctype, me.doc.name, f, v); } } } } if(typeof field=="string") { _set(field, value) } else if($.isPlainObject(field)) { $.each(field, function(f, v) { _set(f, v); }) } } _f.Frm.prototype.call = function(opts) { var me = this; if(!opts.doc) { if(opts.method.indexOf(".")===-1) opts.method = frappe.model.get_server_module_name(me.doctype) + "." + opts.method; opts.original_callback = opts.callback; opts.callback = function(r) { if($.isPlainObject(r.message)) { if(opts.child) { // update child doc opts.child = locals[opts.child.doctype][opts.child.name]; $.extend(opts.child, r.message); me.fields_dict[opts.child.parentfield].refresh(); } else { // update parent doc me.set_value(r.message); } } opts.original_callback && opts.original_callback(r); } } else { opts.original_callback = opts.callback; opts.callback = function(r) { if(!r.exc) me.refresh_fields(); opts.original_callback && opts.original_callback(r); } } return frappe.call(opts); } _f.Frm.prototype.get_field = function(field) { return cur_frm.fields_dict[field]; }; _f.Frm.prototype.new_doc = function(doctype, field) { frappe._from_link = field; frappe._from_link_scrollY = scrollY; new_doc(doctype); } _f.Frm.prototype.set_read_only = function() { var perm = []; $.each(frappe.perm.get_perm(cur_frm.doc.doctype), function(i, p) { perm[p.permlevel || 0] = {read:1}; }); cur_frm.perm = perm; } _f.Frm.prototype.get_formatted = function(fieldname) { return frappe.format(this.doc[fieldname], frappe.meta.get_docfield(this.doctype, fieldname, this.docname), {no_icon:true}, this.doc); }
pawaranand/phr_frappe
frappe/public/js/legacy/clientscriptAPI.js
JavaScript
mit
7,148
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionThumbDown = (props) => ( <SvgIcon {...props}> <path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v1.91l.01.01L1 14c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z"/> </SvgIcon> ); ActionThumbDown = pure(ActionThumbDown); ActionThumbDown.displayName = 'ActionThumbDown'; ActionThumbDown.muiName = 'SvgIcon'; export default ActionThumbDown;
mmrtnz/material-ui
src/svg-icons/action/thumb-down.js
JavaScript
mit
562
class TagGroupSerializer < ApplicationSerializer attributes :id, :name, :tag_names, :parent_tag_name, :one_per_topic def tag_names object.tags.map(&:name).sort end def parent_tag_name [object.parent_tag.try(:name)].compact end end
shirishgoyal/daemo-forum
app/serializers/tag_group_serializer.rb
Ruby
gpl-2.0
251
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/non_thread_safe.h" #include "content/common/gpu/gpu_channel.h" #include "content/common/gpu/media/vaapi_video_decode_accelerator.h" #include "media/base/bind_to_current_loop.h" #include "media/video/picture.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/scoped_binders.h" static void ReportToUMA( content::VaapiH264Decoder::VAVDAH264DecoderFailure failure) { UMA_HISTOGRAM_ENUMERATION( "Media.VAVDAH264.DecoderFailure", failure, content::VaapiH264Decoder::VAVDA_H264_DECODER_FAILURES_MAX); } namespace content { #define RETURN_AND_NOTIFY_ON_FAILURE(result, log, error_code, ret) \ do { \ if (!(result)) { \ DVLOG(1) << log; \ NotifyError(error_code); \ return ret; \ } \ } while (0) VaapiVideoDecodeAccelerator::InputBuffer::InputBuffer() : id(0), size(0) { } VaapiVideoDecodeAccelerator::InputBuffer::~InputBuffer() { } void VaapiVideoDecodeAccelerator::NotifyError(Error error) { if (message_loop_ != base::MessageLoop::current()) { DCHECK(decoder_thread_proxy_->BelongsToCurrentThread()); message_loop_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::NotifyError, weak_this_, error)); return; } // Post Cleanup() as a task so we don't recursively acquire lock_. message_loop_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::Cleanup, weak_this_)); DVLOG(1) << "Notifying of error " << error; if (client_) { client_->NotifyError(error); client_ptr_factory_.reset(); } } // TFPPicture allocates X Pixmaps and binds them to textures passed // in PictureBuffers from clients to them. TFPPictures are created as // a consequence of receiving a set of PictureBuffers from clients and released // at the end of decode (or when a new set of PictureBuffers is required). // // TFPPictures are used for output, contents of VASurfaces passed from decoder // are put into the associated pixmap memory and sent to client. class VaapiVideoDecodeAccelerator::TFPPicture : public base::NonThreadSafe { public: ~TFPPicture(); static linked_ptr<TFPPicture> Create( const base::Callback<bool(void)>& make_context_current, const GLXFBConfig& fb_config, Display* x_display, int32 picture_buffer_id, uint32 texture_id, gfx::Size size); int32 picture_buffer_id() { return picture_buffer_id_; } gfx::Size size() { return size_; } int x_pixmap() { return x_pixmap_; } // Bind texture to pixmap. Needs to be called every frame. bool Bind(); private: TFPPicture(const base::Callback<bool(void)>& make_context_current, Display* x_display, int32 picture_buffer_id, uint32 texture_id, gfx::Size size); bool Initialize(const GLXFBConfig& fb_config); base::Callback<bool(void)> make_context_current_; Display* x_display_; // Output id for the client. int32 picture_buffer_id_; uint32 texture_id_; gfx::Size size_; // Pixmaps bound to this texture. Pixmap x_pixmap_; GLXPixmap glx_pixmap_; DISALLOW_COPY_AND_ASSIGN(TFPPicture); }; VaapiVideoDecodeAccelerator::TFPPicture::TFPPicture( const base::Callback<bool(void)>& make_context_current, Display* x_display, int32 picture_buffer_id, uint32 texture_id, gfx::Size size) : make_context_current_(make_context_current), x_display_(x_display), picture_buffer_id_(picture_buffer_id), texture_id_(texture_id), size_(size), x_pixmap_(0), glx_pixmap_(0) { DCHECK(!make_context_current_.is_null()); }; linked_ptr<VaapiVideoDecodeAccelerator::TFPPicture> VaapiVideoDecodeAccelerator::TFPPicture::Create( const base::Callback<bool(void)>& make_context_current, const GLXFBConfig& fb_config, Display* x_display, int32 picture_buffer_id, uint32 texture_id, gfx::Size size) { linked_ptr<TFPPicture> tfp_picture( new TFPPicture(make_context_current, x_display, picture_buffer_id, texture_id, size)); if (!tfp_picture->Initialize(fb_config)) tfp_picture.reset(); return tfp_picture; } bool VaapiVideoDecodeAccelerator::TFPPicture::Initialize( const GLXFBConfig& fb_config) { DCHECK(CalledOnValidThread()); if (!make_context_current_.Run()) return false; XWindowAttributes win_attr; int screen = DefaultScreen(x_display_); XGetWindowAttributes(x_display_, RootWindow(x_display_, screen), &win_attr); //TODO(posciak): pass the depth required by libva, not the RootWindow's depth x_pixmap_ = XCreatePixmap(x_display_, RootWindow(x_display_, screen), size_.width(), size_.height(), win_attr.depth); if (!x_pixmap_) { DVLOG(1) << "Failed creating an X Pixmap for TFP"; return false; } static const int pixmap_attr[] = { GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT, GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGB_EXT, GL_NONE, }; glx_pixmap_ = glXCreatePixmap(x_display_, fb_config, x_pixmap_, pixmap_attr); if (!glx_pixmap_) { // x_pixmap_ will be freed in the destructor. DVLOG(1) << "Failed creating a GLX Pixmap for TFP"; return false; } return true; } VaapiVideoDecodeAccelerator::TFPPicture::~TFPPicture() { DCHECK(CalledOnValidThread()); // Unbind surface from texture and deallocate resources. if (glx_pixmap_ && make_context_current_.Run()) { glXReleaseTexImageEXT(x_display_, glx_pixmap_, GLX_FRONT_LEFT_EXT); glXDestroyPixmap(x_display_, glx_pixmap_); } if (x_pixmap_) XFreePixmap(x_display_, x_pixmap_); XSync(x_display_, False); // Needed to work around buggy vdpau-driver. } bool VaapiVideoDecodeAccelerator::TFPPicture::Bind() { DCHECK(CalledOnValidThread()); DCHECK(x_pixmap_); DCHECK(glx_pixmap_); if (!make_context_current_.Run()) return false; gfx::ScopedTextureBinder texture_binder(GL_TEXTURE_2D, texture_id_); glXBindTexImageEXT(x_display_, glx_pixmap_, GLX_FRONT_LEFT_EXT, NULL); return true; } VaapiVideoDecodeAccelerator::TFPPicture* VaapiVideoDecodeAccelerator::TFPPictureById(int32 picture_buffer_id) { TFPPictures::iterator it = tfp_pictures_.find(picture_buffer_id); if (it == tfp_pictures_.end()) { DVLOG(1) << "Picture id " << picture_buffer_id << " does not exist"; return NULL; } return it->second.get(); } VaapiVideoDecodeAccelerator::VaapiVideoDecodeAccelerator( Display* x_display, const base::Callback<bool(void)>& make_context_current) : x_display_(x_display), make_context_current_(make_context_current), state_(kUninitialized), input_ready_(&lock_), surfaces_available_(&lock_), message_loop_(base::MessageLoop::current()), decoder_thread_("VaapiDecoderThread"), num_frames_at_client_(0), num_stream_bufs_at_decoder_(0), finish_flush_pending_(false), awaiting_va_surfaces_recycle_(false), requested_num_pics_(0), weak_this_factory_(this) { weak_this_ = weak_this_factory_.GetWeakPtr(); va_surface_release_cb_ = media::BindToCurrentLoop( base::Bind(&VaapiVideoDecodeAccelerator::RecycleVASurfaceID, weak_this_)); } VaapiVideoDecodeAccelerator::~VaapiVideoDecodeAccelerator() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); } class XFreeDeleter { public: void operator()(void* x) const { ::XFree(x); } }; bool VaapiVideoDecodeAccelerator::InitializeFBConfig() { const int fbconfig_attr[] = { GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT, GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT, GLX_BIND_TO_TEXTURE_RGB_EXT, GL_TRUE, GLX_Y_INVERTED_EXT, GL_TRUE, GL_NONE, }; int num_fbconfigs; scoped_ptr<GLXFBConfig, XFreeDeleter> glx_fb_configs( glXChooseFBConfig(x_display_, DefaultScreen(x_display_), fbconfig_attr, &num_fbconfigs)); if (!glx_fb_configs) return false; if (!num_fbconfigs) return false; fb_config_ = glx_fb_configs.get()[0]; return true; } bool VaapiVideoDecodeAccelerator::Initialize(media::VideoCodecProfile profile, Client* client) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); client_ptr_factory_.reset(new base::WeakPtrFactory<Client>(client)); client_ = client_ptr_factory_->GetWeakPtr(); base::AutoLock auto_lock(lock_); DCHECK_EQ(state_, kUninitialized); DVLOG(2) << "Initializing VAVDA, profile: " << profile; if (!make_context_current_.Run()) return false; if (!InitializeFBConfig()) { DVLOG(1) << "Could not get a usable FBConfig"; return false; } vaapi_wrapper_ = VaapiWrapper::Create( VaapiWrapper::kDecode, profile, x_display_, base::Bind(&ReportToUMA, content::VaapiH264Decoder::VAAPI_ERROR)); if (!vaapi_wrapper_.get()) { DVLOG(1) << "Failed initializing VAAPI"; return false; } decoder_.reset( new VaapiH264Decoder( vaapi_wrapper_.get(), media::BindToCurrentLoop(base::Bind( &VaapiVideoDecodeAccelerator::SurfaceReady, weak_this_)), base::Bind(&ReportToUMA))); CHECK(decoder_thread_.Start()); decoder_thread_proxy_ = decoder_thread_.message_loop_proxy(); state_ = kIdle; return true; } void VaapiVideoDecodeAccelerator::SurfaceReady( int32 input_id, const scoped_refptr<VASurface>& va_surface) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); DCHECK(!awaiting_va_surfaces_recycle_); // Drop any requests to output if we are resetting or being destroyed. if (state_ == kResetting || state_ == kDestroying) return; pending_output_cbs_.push( base::Bind(&VaapiVideoDecodeAccelerator::OutputPicture, weak_this_, va_surface, input_id)); TryOutputSurface(); } void VaapiVideoDecodeAccelerator::OutputPicture( const scoped_refptr<VASurface>& va_surface, int32 input_id, TFPPicture* tfp_picture) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); int32 output_id = tfp_picture->picture_buffer_id(); TRACE_EVENT2("Video Decoder", "VAVDA::OutputSurface", "input_id", input_id, "output_id", output_id); DVLOG(3) << "Outputting VASurface " << va_surface->id() << " into pixmap bound to picture buffer id " << output_id; RETURN_AND_NOTIFY_ON_FAILURE(tfp_picture->Bind(), "Failed binding texture to pixmap", PLATFORM_FAILURE, ); RETURN_AND_NOTIFY_ON_FAILURE( vaapi_wrapper_->PutSurfaceIntoPixmap(va_surface->id(), tfp_picture->x_pixmap(), tfp_picture->size()), "Failed putting surface into pixmap", PLATFORM_FAILURE, ); // Notify the client a picture is ready to be displayed. ++num_frames_at_client_; TRACE_COUNTER1("Video Decoder", "Textures at client", num_frames_at_client_); DVLOG(4) << "Notifying output picture id " << output_id << " for input "<< input_id << " is ready"; // TODO(posciak): Use visible size from decoder here instead // (crbug.com/402760). if (client_) client_->PictureReady( media::Picture(output_id, input_id, gfx::Rect(tfp_picture->size()))); } void VaapiVideoDecodeAccelerator::TryOutputSurface() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); // Handle Destroy() arriving while pictures are queued for output. if (!client_) return; if (pending_output_cbs_.empty() || output_buffers_.empty()) return; OutputCB output_cb = pending_output_cbs_.front(); pending_output_cbs_.pop(); TFPPicture* tfp_picture = TFPPictureById(output_buffers_.front()); DCHECK(tfp_picture); output_buffers_.pop(); output_cb.Run(tfp_picture); if (finish_flush_pending_ && pending_output_cbs_.empty()) FinishFlush(); } void VaapiVideoDecodeAccelerator::MapAndQueueNewInputBuffer( const media::BitstreamBuffer& bitstream_buffer) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); TRACE_EVENT1("Video Decoder", "MapAndQueueNewInputBuffer", "input_id", bitstream_buffer.id()); DVLOG(4) << "Mapping new input buffer id: " << bitstream_buffer.id() << " size: " << (int)bitstream_buffer.size(); scoped_ptr<base::SharedMemory> shm( new base::SharedMemory(bitstream_buffer.handle(), true)); RETURN_AND_NOTIFY_ON_FAILURE(shm->Map(bitstream_buffer.size()), "Failed to map input buffer", UNREADABLE_INPUT,); base::AutoLock auto_lock(lock_); // Set up a new input buffer and queue it for later. linked_ptr<InputBuffer> input_buffer(new InputBuffer()); input_buffer->shm.reset(shm.release()); input_buffer->id = bitstream_buffer.id(); input_buffer->size = bitstream_buffer.size(); ++num_stream_bufs_at_decoder_; TRACE_COUNTER1("Video Decoder", "Stream buffers at decoder", num_stream_bufs_at_decoder_); input_buffers_.push(input_buffer); input_ready_.Signal(); } bool VaapiVideoDecodeAccelerator::GetInputBuffer_Locked() { DCHECK(decoder_thread_proxy_->BelongsToCurrentThread()); lock_.AssertAcquired(); if (curr_input_buffer_.get()) return true; // Will only wait if it is expected that in current state new buffers will // be queued from the client via Decode(). The state can change during wait. while (input_buffers_.empty() && (state_ == kDecoding || state_ == kIdle)) { input_ready_.Wait(); } // We could have got woken up in a different state or never got to sleep // due to current state; check for that. switch (state_) { case kFlushing: // Here we are only interested in finishing up decoding buffers that are // already queued up. Otherwise will stop decoding. if (input_buffers_.empty()) return false; // else fallthrough case kDecoding: case kIdle: DCHECK(!input_buffers_.empty()); curr_input_buffer_ = input_buffers_.front(); input_buffers_.pop(); DVLOG(4) << "New current bitstream buffer, id: " << curr_input_buffer_->id << " size: " << curr_input_buffer_->size; decoder_->SetStream( static_cast<uint8*>(curr_input_buffer_->shm->memory()), curr_input_buffer_->size, curr_input_buffer_->id); return true; default: // We got woken up due to being destroyed/reset, ignore any already // queued inputs. return false; } } void VaapiVideoDecodeAccelerator::ReturnCurrInputBuffer_Locked() { lock_.AssertAcquired(); DCHECK(decoder_thread_proxy_->BelongsToCurrentThread()); DCHECK(curr_input_buffer_.get()); int32 id = curr_input_buffer_->id; curr_input_buffer_.reset(); DVLOG(4) << "End of input buffer " << id; message_loop_->PostTask(FROM_HERE, base::Bind( &Client::NotifyEndOfBitstreamBuffer, client_, id)); --num_stream_bufs_at_decoder_; TRACE_COUNTER1("Video Decoder", "Stream buffers at decoder", num_stream_bufs_at_decoder_); } bool VaapiVideoDecodeAccelerator::FeedDecoderWithOutputSurfaces_Locked() { lock_.AssertAcquired(); DCHECK(decoder_thread_proxy_->BelongsToCurrentThread()); while (available_va_surfaces_.empty() && (state_ == kDecoding || state_ == kFlushing || state_ == kIdle)) { surfaces_available_.Wait(); } if (state_ != kDecoding && state_ != kFlushing && state_ != kIdle) return false; while (!available_va_surfaces_.empty()) { scoped_refptr<VASurface> va_surface( new VASurface(available_va_surfaces_.front(), va_surface_release_cb_)); available_va_surfaces_.pop_front(); decoder_->ReuseSurface(va_surface); } return true; } void VaapiVideoDecodeAccelerator::DecodeTask() { DCHECK(decoder_thread_proxy_->BelongsToCurrentThread()); TRACE_EVENT0("Video Decoder", "VAVDA::DecodeTask"); base::AutoLock auto_lock(lock_); if (state_ != kDecoding) return; // Main decode task. DVLOG(4) << "Decode task"; // Try to decode what stream data is (still) in the decoder until we run out // of it. while (GetInputBuffer_Locked()) { DCHECK(curr_input_buffer_.get()); VaapiH264Decoder::DecResult res; { // We are OK releasing the lock here, as decoder never calls our methods // directly and we will reacquire the lock before looking at state again. // This is the main decode function of the decoder and while keeping // the lock for its duration would be fine, it would defeat the purpose // of having a separate decoder thread. base::AutoUnlock auto_unlock(lock_); res = decoder_->Decode(); } switch (res) { case VaapiH264Decoder::kAllocateNewSurfaces: DVLOG(1) << "Decoder requesting a new set of surfaces"; message_loop_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::InitiateSurfaceSetChange, weak_this_, decoder_->GetRequiredNumOfPictures(), decoder_->GetPicSize())); // We'll get rescheduled once ProvidePictureBuffers() finishes. return; case VaapiH264Decoder::kRanOutOfStreamData: ReturnCurrInputBuffer_Locked(); break; case VaapiH264Decoder::kRanOutOfSurfaces: // No more output buffers in the decoder, try getting more or go to // sleep waiting for them. if (!FeedDecoderWithOutputSurfaces_Locked()) return; break; case VaapiH264Decoder::kDecodeError: RETURN_AND_NOTIFY_ON_FAILURE(false, "Error decoding stream", PLATFORM_FAILURE, ); return; } } } void VaapiVideoDecodeAccelerator::InitiateSurfaceSetChange(size_t num_pics, gfx::Size size) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); DCHECK(!awaiting_va_surfaces_recycle_); // At this point decoder has stopped running and has already posted onto our // loop any remaining output request callbacks, which executed before we got // here. Some of them might have been pended though, because we might not // have had enough TFPictures to output surfaces to. Initiate a wait cycle, // which will wait for client to return enough PictureBuffers to us, so that // we can finish all pending output callbacks, releasing associated surfaces. DVLOG(1) << "Initiating surface set change"; awaiting_va_surfaces_recycle_ = true; requested_num_pics_ = num_pics; requested_pic_size_ = size; TryFinishSurfaceSetChange(); } void VaapiVideoDecodeAccelerator::TryFinishSurfaceSetChange() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); if (!awaiting_va_surfaces_recycle_) return; if (!pending_output_cbs_.empty() || tfp_pictures_.size() != available_va_surfaces_.size()) { // Either: // 1. Not all pending pending output callbacks have been executed yet. // Wait for the client to return enough pictures and retry later. // 2. The above happened and all surface release callbacks have been posted // as the result, but not all have executed yet. Post ourselves after them // to let them release surfaces. DVLOG(2) << "Awaiting pending output/surface release callbacks to finish"; message_loop_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::TryFinishSurfaceSetChange, weak_this_)); return; } // All surfaces released, destroy them and dismiss all PictureBuffers. awaiting_va_surfaces_recycle_ = false; available_va_surfaces_.clear(); vaapi_wrapper_->DestroySurfaces(); for (TFPPictures::iterator iter = tfp_pictures_.begin(); iter != tfp_pictures_.end(); ++iter) { DVLOG(2) << "Dismissing picture id: " << iter->first; if (client_) client_->DismissPictureBuffer(iter->first); } tfp_pictures_.clear(); // And ask for a new set as requested. DVLOG(1) << "Requesting " << requested_num_pics_ << " pictures of size: " << requested_pic_size_.ToString(); message_loop_->PostTask(FROM_HERE, base::Bind( &Client::ProvidePictureBuffers, client_, requested_num_pics_, requested_pic_size_, GL_TEXTURE_2D)); } void VaapiVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); TRACE_EVENT1("Video Decoder", "VAVDA::Decode", "Buffer id", bitstream_buffer.id()); // We got a new input buffer from the client, map it and queue for later use. MapAndQueueNewInputBuffer(bitstream_buffer); base::AutoLock auto_lock(lock_); switch (state_) { case kIdle: state_ = kDecoding; decoder_thread_proxy_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::DecodeTask, base::Unretained(this))); break; case kDecoding: // Decoder already running, fallthrough. case kResetting: // When resetting, allow accumulating bitstream buffers, so that // the client can queue after-seek-buffers while we are finishing with // the before-seek one. break; default: RETURN_AND_NOTIFY_ON_FAILURE(false, "Decode request from client in invalid state: " << state_, PLATFORM_FAILURE, ); break; } } void VaapiVideoDecodeAccelerator::RecycleVASurfaceID( VASurfaceID va_surface_id) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); base::AutoLock auto_lock(lock_); available_va_surfaces_.push_back(va_surface_id); surfaces_available_.Signal(); } void VaapiVideoDecodeAccelerator::AssignPictureBuffers( const std::vector<media::PictureBuffer>& buffers) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); base::AutoLock auto_lock(lock_); DCHECK(tfp_pictures_.empty()); while (!output_buffers_.empty()) output_buffers_.pop(); RETURN_AND_NOTIFY_ON_FAILURE( buffers.size() == requested_num_pics_, "Got an invalid number of picture buffers. (Got " << buffers.size() << ", requested " << requested_num_pics_ << ")", INVALID_ARGUMENT, ); DCHECK(requested_pic_size_ == buffers[0].size()); std::vector<VASurfaceID> va_surface_ids; RETURN_AND_NOTIFY_ON_FAILURE( vaapi_wrapper_->CreateSurfaces(requested_pic_size_, buffers.size(), &va_surface_ids), "Failed creating VA Surfaces", PLATFORM_FAILURE, ); DCHECK_EQ(va_surface_ids.size(), buffers.size()); for (size_t i = 0; i < buffers.size(); ++i) { DVLOG(2) << "Assigning picture id: " << buffers[i].id() << " to texture id: " << buffers[i].texture_id() << " VASurfaceID: " << va_surface_ids[i]; linked_ptr<TFPPicture> tfp_picture( TFPPicture::Create(make_context_current_, fb_config_, x_display_, buffers[i].id(), buffers[i].texture_id(), requested_pic_size_)); RETURN_AND_NOTIFY_ON_FAILURE( tfp_picture.get(), "Failed assigning picture buffer to a texture.", PLATFORM_FAILURE, ); bool inserted = tfp_pictures_.insert(std::make_pair( buffers[i].id(), tfp_picture)).second; DCHECK(inserted); output_buffers_.push(buffers[i].id()); available_va_surfaces_.push_back(va_surface_ids[i]); surfaces_available_.Signal(); } state_ = kDecoding; decoder_thread_proxy_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::DecodeTask, base::Unretained(this))); } void VaapiVideoDecodeAccelerator::ReusePictureBuffer(int32 picture_buffer_id) { DCHECK_EQ(message_loop_, base::MessageLoop::current()); TRACE_EVENT1("Video Decoder", "VAVDA::ReusePictureBuffer", "Picture id", picture_buffer_id); --num_frames_at_client_; TRACE_COUNTER1("Video Decoder", "Textures at client", num_frames_at_client_); output_buffers_.push(picture_buffer_id); TryOutputSurface(); } void VaapiVideoDecodeAccelerator::FlushTask() { DCHECK(decoder_thread_proxy_->BelongsToCurrentThread()); DVLOG(1) << "Flush task"; // First flush all the pictures that haven't been outputted, notifying the // client to output them. bool res = decoder_->Flush(); RETURN_AND_NOTIFY_ON_FAILURE(res, "Failed flushing the decoder.", PLATFORM_FAILURE, ); // Put the decoder in idle state, ready to resume. decoder_->Reset(); message_loop_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::FinishFlush, weak_this_)); } void VaapiVideoDecodeAccelerator::Flush() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); DVLOG(1) << "Got flush request"; base::AutoLock auto_lock(lock_); state_ = kFlushing; // Queue a flush task after all existing decoding tasks to clean up. decoder_thread_proxy_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::FlushTask, base::Unretained(this))); input_ready_.Signal(); surfaces_available_.Signal(); } void VaapiVideoDecodeAccelerator::FinishFlush() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); finish_flush_pending_ = false; base::AutoLock auto_lock(lock_); if (state_ != kFlushing) { DCHECK_EQ(state_, kDestroying); return; // We could've gotten destroyed already. } // Still waiting for textures from client to finish outputting all pending // frames. Try again later. if (!pending_output_cbs_.empty()) { finish_flush_pending_ = true; return; } state_ = kIdle; message_loop_->PostTask(FROM_HERE, base::Bind( &Client::NotifyFlushDone, client_)); DVLOG(1) << "Flush finished"; } void VaapiVideoDecodeAccelerator::ResetTask() { DCHECK(decoder_thread_proxy_->BelongsToCurrentThread()); DVLOG(1) << "ResetTask"; // All the decoding tasks from before the reset request from client are done // by now, as this task was scheduled after them and client is expected not // to call Decode() after Reset() and before NotifyResetDone. decoder_->Reset(); base::AutoLock auto_lock(lock_); // Return current input buffer, if present. if (curr_input_buffer_.get()) ReturnCurrInputBuffer_Locked(); // And let client know that we are done with reset. message_loop_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::FinishReset, weak_this_)); } void VaapiVideoDecodeAccelerator::Reset() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); DVLOG(1) << "Got reset request"; // This will make any new decode tasks exit early. base::AutoLock auto_lock(lock_); state_ = kResetting; finish_flush_pending_ = false; // Drop all remaining input buffers, if present. while (!input_buffers_.empty()) { message_loop_->PostTask(FROM_HERE, base::Bind( &Client::NotifyEndOfBitstreamBuffer, client_, input_buffers_.front()->id)); input_buffers_.pop(); } decoder_thread_proxy_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::ResetTask, base::Unretained(this))); input_ready_.Signal(); surfaces_available_.Signal(); } void VaapiVideoDecodeAccelerator::FinishReset() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); DVLOG(1) << "FinishReset"; base::AutoLock auto_lock(lock_); if (state_ != kResetting) { DCHECK(state_ == kDestroying || state_ == kUninitialized) << state_; return; // We could've gotten destroyed already. } // Drop pending outputs. while (!pending_output_cbs_.empty()) pending_output_cbs_.pop(); if (awaiting_va_surfaces_recycle_) { // Decoder requested a new surface set while we were waiting for it to // finish the last DecodeTask, running at the time of Reset(). // Let the surface set change finish first before resetting. message_loop_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::FinishReset, weak_this_)); return; } num_stream_bufs_at_decoder_ = 0; state_ = kIdle; message_loop_->PostTask(FROM_HERE, base::Bind( &Client::NotifyResetDone, client_)); // The client might have given us new buffers via Decode() while we were // resetting and might be waiting for our move, and not call Decode() anymore // until we return something. Post a DecodeTask() so that we won't // sleep forever waiting for Decode() in that case. Having two of them // in the pipe is harmless, the additional one will return as soon as it sees // that we are back in kDecoding state. if (!input_buffers_.empty()) { state_ = kDecoding; decoder_thread_proxy_->PostTask(FROM_HERE, base::Bind( &VaapiVideoDecodeAccelerator::DecodeTask, base::Unretained(this))); } DVLOG(1) << "Reset finished"; } void VaapiVideoDecodeAccelerator::Cleanup() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); if (state_ == kUninitialized || state_ == kDestroying) return; DVLOG(1) << "Destroying VAVDA"; base::AutoLock auto_lock(lock_); state_ = kDestroying; client_ptr_factory_.reset(); weak_this_factory_.InvalidateWeakPtrs(); // Signal all potential waiters on the decoder_thread_, let them early-exit, // as we've just moved to the kDestroying state, and wait for all tasks // to finish. input_ready_.Signal(); surfaces_available_.Signal(); { base::AutoUnlock auto_unlock(lock_); decoder_thread_.Stop(); } state_ = kUninitialized; } void VaapiVideoDecodeAccelerator::Destroy() { DCHECK_EQ(message_loop_, base::MessageLoop::current()); Cleanup(); delete this; } bool VaapiVideoDecodeAccelerator::CanDecodeOnIOThread() { return false; } } // namespace content
s20121035/rk3288_android5.1_repo
external/chromium_org/content/common/gpu/media/vaapi_video_decode_accelerator.cc
C++
gpl-3.0
30,302
package org.jsoup.parser; import org.jsoup.helper.Validate; import java.util.Arrays; import java.util.Locale; /** CharacterReader consumes tokens off a string. To replace the old TokenQueue. */ final class CharacterReader { static final char EOF = (char) -1; private static final int maxCacheLen = 12; private final char[] input; private final int length; private int pos = 0; private int mark = 0; private final String[] stringCache = new String[512]; // holds reused strings in this doc, to lessen garbage CharacterReader(String input) { Validate.notNull(input); this.input = input.toCharArray(); this.length = this.input.length; } int pos() { return pos; } boolean isEmpty() { return pos >= length; } char current() { return pos >= length ? EOF : input[pos]; } char consume() { char val = pos >= length ? EOF : input[pos]; pos++; return val; } void unconsume() { pos--; } void advance() { pos++; } void mark() { mark = pos; } void rewindToMark() { pos = mark; } String consumeAsString() { return new String(input, pos++, 1); } /** * Returns the number of characters between the current position and the next instance of the input char * @param c scan target * @return offset between current position and next instance of target. -1 if not found. */ int nextIndexOf(char c) { // doesn't handle scanning for surrogates for (int i = pos; i < length; i++) { if (c == input[i]) return i - pos; } return -1; } /** * Returns the number of characters between the current position and the next instance of the input sequence * * @param seq scan target * @return offset between current position and next instance of target. -1 if not found. */ int nextIndexOf(CharSequence seq) { // doesn't handle scanning for surrogates char startChar = seq.charAt(0); for (int offset = pos; offset < length; offset++) { // scan to first instance of startchar: if (startChar != input[offset]) while(++offset < length && startChar != input[offset]) { /* empty */ } int i = offset + 1; int last = i + seq.length()-1; if (offset < length && last <= length) { for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++) { /* empty */ } if (i == last) // found full sequence return offset - pos; } } return -1; } String consumeTo(char c) { int offset = nextIndexOf(c); if (offset != -1) { String consumed = cacheString(pos, offset); pos += offset; return consumed; } else { return consumeToEnd(); } } String consumeTo(String seq) { int offset = nextIndexOf(seq); if (offset != -1) { String consumed = cacheString(pos, offset); pos += offset; return consumed; } else { return consumeToEnd(); } } String consumeToAny(final char... chars) { final int start = pos; final int remaining = length; OUTER: while (pos < remaining) { for (char c : chars) { if (input[pos] == c) break OUTER; } pos++; } return pos > start ? cacheString(start, pos-start) : ""; } String consumeToAnySorted(final char... chars) { final int start = pos; final int remaining = length; final char[] val = input; while (pos < remaining) { if (Arrays.binarySearch(chars, val[pos]) >= 0) break; pos++; } return pos > start ? cacheString(start, pos-start) : ""; } String consumeData() { // &, <, null final int start = pos; final int remaining = length; final char[] val = input; while (pos < remaining) { final char c = val[pos]; if (c == '&'|| c == '<' || c == TokeniserState.nullChar) break; pos++; } return pos > start ? cacheString(start, pos-start) : ""; } String consumeTagName() { // '\t', '\n', '\r', '\f', ' ', '/', '>', nullChar final int start = pos; final int remaining = length; final char[] val = input; while (pos < remaining) { final char c = val[pos]; if (c == '\t'|| c == '\n'|| c == '\r'|| c == '\f'|| c == ' '|| c == '/'|| c == '>'|| c == TokeniserState.nullChar) break; pos++; } return pos > start ? cacheString(start, pos-start) : ""; } String consumeToEnd() { String data = cacheString(pos, length-pos); pos = length; return data; } String consumeLetterSequence() { int start = pos; while (pos < length) { char c = input[pos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) pos++; else break; } return cacheString(start, pos - start); } String consumeLetterThenDigitSequence() { int start = pos; while (pos < length) { char c = input[pos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) pos++; else break; } while (!isEmpty()) { char c = input[pos]; if (c >= '0' && c <= '9') pos++; else break; } return cacheString(start, pos - start); } String consumeHexSequence() { int start = pos; while (pos < length) { char c = input[pos]; if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) pos++; else break; } return cacheString(start, pos - start); } String consumeDigitSequence() { int start = pos; while (pos < length) { char c = input[pos]; if (c >= '0' && c <= '9') pos++; else break; } return cacheString(start, pos - start); } boolean matches(char c) { return !isEmpty() && input[pos] == c; } boolean matches(String seq) { int scanLength = seq.length(); if (scanLength > length - pos) return false; for (int offset = 0; offset < scanLength; offset++) if (seq.charAt(offset) != input[pos+offset]) return false; return true; } boolean matchesIgnoreCase(String seq) { int scanLength = seq.length(); if (scanLength > length - pos) return false; for (int offset = 0; offset < scanLength; offset++) { char upScan = Character.toUpperCase(seq.charAt(offset)); char upTarget = Character.toUpperCase(input[pos + offset]); if (upScan != upTarget) return false; } return true; } boolean matchesAny(char... seq) { if (isEmpty()) return false; char c = input[pos]; for (char seek : seq) { if (seek == c) return true; } return false; } boolean matchesAnySorted(char[] seq) { return !isEmpty() && Arrays.binarySearch(seq, input[pos]) >= 0; } boolean matchesLetter() { if (isEmpty()) return false; char c = input[pos]; return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } boolean matchesDigit() { if (isEmpty()) return false; char c = input[pos]; return (c >= '0' && c <= '9'); } boolean matchConsume(String seq) { if (matches(seq)) { pos += seq.length(); return true; } else { return false; } } boolean matchConsumeIgnoreCase(String seq) { if (matchesIgnoreCase(seq)) { pos += seq.length(); return true; } else { return false; } } boolean containsIgnoreCase(String seq) { // used to check presence of </title>, </style>. only finds consistent case. String loScan = seq.toLowerCase(Locale.ENGLISH); String hiScan = seq.toUpperCase(Locale.ENGLISH); return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1); } @Override public String toString() { return new String(input, pos, length - pos); } /** * Caches short strings, as a flywheel pattern, to reduce GC load. Just for this doc, to prevent leaks. * <p /> * Simplistic, and on hash collisions just falls back to creating a new string, vs a full HashMap with Entry list. * That saves both having to create objects as hash keys, and running through the entry list, at the expense of * some more duplicates. */ private String cacheString(final int start, final int count) { final char[] val = input; final String[] cache = stringCache; // limit (no cache): if (count > maxCacheLen) return new String(val, start, count); // calculate hash: int hash = 0; int offset = start; for (int i = 0; i < count; i++) { hash = 31 * hash + val[offset++]; } // get from cache final int index = hash & cache.length - 1; String cached = cache[index]; if (cached == null) { // miss, add cached = new String(val, start, count); cache[index] = cached; } else { // hashcode hit, check equality if (rangeEquals(start, count, cached)) { // hit return cached; } else { // hashcode conflict cached = new String(val, start, count); } } return cached; } /** * Check if the value of the provided range equals the string. */ boolean rangeEquals(final int start, int count, final String cached) { if (count == cached.length()) { char one[] = input; int i = start; int j = 0; while (count-- != 0) { if (one[i++] != cached.charAt(j++)) return false; } return true; } return false; } }
rogerxaic/gestock
src/org/jsoup/parser/CharacterReader.java
Java
unlicense
10,826
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # 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. # """Fake HP client exceptions to use when mocking HP clients.""" class UnsupportedVersion(Exception): """Unsupported version of the client.""" pass class ClientException(Exception): """The base exception class for these fake exceptions.""" _error_code = None _error_desc = None _error_ref = None _debug1 = None _debug2 = None def __init__(self, error=None): if error: if 'code' in error: self._error_code = error['code'] if 'desc' in error: self._error_desc = error['desc'] if 'ref' in error: self._error_ref = error['ref'] if 'debug1' in error: self._debug1 = error['debug1'] if 'debug2' in error: self._debug2 = error['debug2'] def get_code(self): return self._error_code def get_description(self): return self._error_desc def get_ref(self): return self._error_ref def __str__(self): formatted_string = self.message if self.http_status: formatted_string += " (HTTP %s)" % self.http_status if self._error_code: formatted_string += " %s" % self._error_code if self._error_desc: formatted_string += " - %s" % self._error_desc if self._error_ref: formatted_string += " - %s" % self._error_ref if self._debug1: formatted_string += " (1: '%s')" % self._debug1 if self._debug2: formatted_string += " (2: '%s')" % self._debug2 return formatted_string class HTTPConflict(Exception): http_status = 409 message = "Conflict" def __init__(self, error=None): if error and 'message' in error: self._error_desc = error['message'] def get_description(self): return self._error_desc class HTTPNotFound(Exception): http_status = 404 message = "Not found" class HTTPForbidden(ClientException): http_status = 403 message = "Forbidden" class HTTPBadRequest(Exception): http_status = 400 message = "Bad request" class HTTPServerError(Exception): http_status = 500 message = "Error" def __init__(self, error=None): if error and 'message' in error: self._error_desc = error['message'] def get_description(self): return self._error_desc
nikesh-mahalka/cinder
cinder/tests/unit/fake_hp_client_exceptions.py
Python
apache-2.0
3,077
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job.entries.evaluatetablecontent; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import org.mockito.stubbing.Answer; public class MockDriver implements Driver { private static final List<MockDriver> drivers = new ArrayList<MockDriver>(); public static synchronized void registerInstance() throws SQLException { MockDriver driver = new MockDriver(); DriverManager.registerDriver( driver ); drivers.add( driver ); } public static synchronized void deregeisterInstances() throws SQLException { for ( Driver driver : drivers ) { DriverManager.deregisterDriver( driver ); } drivers.clear(); } public MockDriver() { } @Override public boolean acceptsURL( String url ) throws SQLException { return true; } @Override public Connection connect( String url, Properties info ) throws SQLException { Connection conn = mock( Connection.class ); Statement stmt = mock( Statement.class ); ResultSet rs = mock( ResultSet.class ); ResultSetMetaData md = mock( ResultSetMetaData.class ); when( stmt.getMaxRows() ).thenReturn( 5 ); when( stmt.getResultSet() ).thenReturn( rs ); when( stmt.executeQuery( anyString() ) ).thenReturn( rs ); when( rs.getMetaData() ).thenReturn( md ); when( rs.getLong( anyInt() ) ).thenReturn( 5L ); when( rs.next() ).thenAnswer( new Answer<Boolean>() { private int count = 0; public Boolean answer( org.mockito.invocation.InvocationOnMock invocation ) throws Throwable { return count++ == 0; } } ); when( md.getColumnCount() ).thenReturn( 1 ); when( md.getColumnName( anyInt() ) ).thenReturn( "count" ); when( md.getColumnType( anyInt() ) ).thenReturn( java.sql.Types.INTEGER ); when( conn.createStatement() ).thenReturn( stmt ); return conn; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } @Override public DriverPropertyInfo[] getPropertyInfo( String url, Properties info ) throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean jdbcCompliant() { // TODO Auto-generated method stub return false; } }
tkafalas/pentaho-kettle
engine/src/test/java/org/pentaho/di/job/entries/evaluatetablecontent/MockDriver.java
Java
apache-2.0
3,801
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.core; public interface KettleAttributeInterface { /** * @return the key for this attribute, usually the repository code. */ public String getKey(); /** * @return the xmlCode */ public String getXmlCode(); /** * @return the repCode */ public String getRepCode(); /** * @return the description */ public String getDescription(); /** * @return the tooltip */ public String getTooltip(); /** * @return the type */ public int getType(); /** * @return The parent interface. */ public KettleAttributeInterface getParent(); }
wseyler/pentaho-kettle
core/src/main/java/org/pentaho/di/core/KettleAttributeInterface.java
Java
apache-2.0
1,533
/* * Copyright 2016 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel; import io.netty.util.IntSupplier; /** * Default select strategy. */ final class DefaultSelectStrategy implements SelectStrategy { static final SelectStrategy INSTANCE = new DefaultSelectStrategy(); private DefaultSelectStrategy() { } @Override public int calculateStrategy(IntSupplier selectSupplier, boolean hasTasks) throws Exception { return hasTasks ? selectSupplier.get() : SelectStrategy.SELECT; } }
bryce-anderson/netty
transport/src/main/java/io/netty/channel/DefaultSelectStrategy.java
Java
apache-2.0
1,101
/** * Module dependencies. */ var Connection = require('../../connection') , mongo = require('mongodb') , Server = mongo.Server , ReplSetServers = mongo.ReplSetServers; /** * Connection for mongodb-native driver * * @api private */ function NativeConnection() { Connection.apply(this, arguments); }; /** * Inherits from Connection. */ NativeConnection.prototype.__proto__ = Connection.prototype; /** * Opens the connection. * * Example server options: * auto_reconnect (default: false) * poolSize (default: 1) * * Example db options: * pk - custom primary key factory to generate `_id` values * * Some of these may break Mongoose. Use at your own risk. You have been warned. * * @param {Function} callback * @api private */ NativeConnection.prototype.doOpen = function (fn) { var server; if (!this.db) { server = new mongo.Server(this.host, Number(this.port), this.options.server); this.db = new mongo.Db(this.name, server, this.options.db); } this.db.open(fn); return this; }; /** * Opens a set connection * * See description of doOpen for server options. In this case options.replset * is also passed to ReplSetServers. Some additional options there are * * reconnectWait (default: 1000) * retries (default: 30) * rs_name (default: false) * read_secondary (default: false) Are reads allowed from secondaries? * * @param {Function} fn * @api private */ NativeConnection.prototype.doOpenSet = function (fn) { if (!this.db) { var servers = [] , ports = this.port , self = this this.host.forEach(function (host, i) { servers.push(new mongo.Server(host, Number(ports[i]), self.options.server)); }); var server = new ReplSetServers(servers, this.options.replset); this.db = new mongo.Db(this.name, server, this.options.db); } this.db.open(fn); return this; }; /** * Closes the connection * * @param {Function} callback * @api private */ NativeConnection.prototype.doClose = function (fn) { this.db.close(); if (fn) fn(); return this; } /** * Module exports. */ module.exports = NativeConnection;
f14c0/rb-sensor
webapp/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js
JavaScript
mit
2,154
<?php // autoload_namespaces.php generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Twig_Extensions_' => $vendorDir . '/twig/extensions/lib/', 'Twig_' => $vendorDir . '/twig/twig/lib/', 'Symfony\\Bundle\\SwiftmailerBundle' => $vendorDir . '/symfony/swiftmailer-bundle/', 'Symfony\\Bundle\\MonologBundle' => $vendorDir . '/symfony/monolog-bundle/', 'Symfony\\Bundle\\AsseticBundle' => $vendorDir . '/symfony/assetic-bundle/', 'Symfony\\' => $vendorDir . '/symfony/symfony/src/', 'Sensio\\Bundle\\GeneratorBundle' => $vendorDir . '/sensio/generator-bundle/', 'Sensio\\Bundle\\FrameworkExtraBundle' => $vendorDir . '/sensio/framework-extra-bundle/', 'Sensio\\Bundle\\DistributionBundle' => $vendorDir . '/sensio/distribution-bundle/', 'Psr\\Log\\' => $vendorDir . '/psr/log/', 'PhpOption\\' => $vendorDir . '/phpoption/phpoption/src/', 'Monolog' => $vendorDir . '/monolog/monolog/src/', 'Metadata\\' => $vendorDir . '/jms/metadata/src/', 'JMS\\SecurityExtraBundle' => $vendorDir . '/jms/security-extra-bundle/', 'JMS\\DiExtraBundle' => $vendorDir . '/jms/di-extra-bundle/', 'JMS\\AopBundle' => $vendorDir . '/jms/aop-bundle/', 'JMS\\' => $vendorDir . '/jms/parser-lib/src/', 'Doctrine\\ORM' => $vendorDir . '/doctrine/orm/lib/', 'Doctrine\\DBAL' => $vendorDir . '/doctrine/dbal/lib/', 'Doctrine\\Common' => $vendorDir . '/doctrine/common/lib/', 'Doctrine\\Bundle\\DoctrineBundle' => $vendorDir . '/doctrine/doctrine-bundle/', 'CG\\' => $vendorDir . '/jms/cg/src/', 'Assetic' => $vendorDir . '/kriswallsmith/assetic/src/', '' => $baseDir . '/src/', );
KammounHatem/projetgl
vendor/composer/autoload_namespaces.php
PHP
mit
1,696
// $Id: ajax.js,v 1.26.2.2 2009/11/30 22:47:05 merlinofchaos Exp $ /** * @file ajax_admin.js * * Handles AJAX submission and response in Views UI. */ Drupal.Views.Ajax = Drupal.Views.Ajax || {}; /** * Handles the simple process of setting the ajax form area with new data. */ Drupal.Views.Ajax.setForm = function(title, output) { $(Drupal.settings.views.ajax.title).html(title); $(Drupal.settings.views.ajax.id).html(output); } /** * An ajax responder that accepts a packet of JSON data and acts appropriately. * * The following fields control behavior. * - 'display': Display the associated data in the form area; bind the new * form to 'url' if appropriate. The 'title' field may also be used. * - 'add': This is a keyed array of HTML output to add via append. The key is * the id to append via $(key).append(value) * - 'replace': This is a keyed array of HTML output to add via replace. The key is * the id to append via $(key).html(value) * */ Drupal.Views.Ajax.ajaxResponse = function(data) { $('a.views-throbbing').removeClass('views-throbbing'); $('span.views-throbbing').remove(); if (data.debug) { alert(data.debug); } // See if we have any settings to extend. Do this first so that behaviors // can access the new settings easily. if (Drupal.settings.viewsAjax) { Drupal.settings.viewsAjax = {}; } if (data.js) { $.extend(Drupal.settings, data.js); } // Check the 'display' for data. if (data.display) { Drupal.Views.Ajax.setForm(data.title, data.display); // if a URL was supplied, bind the form to it. if (data.url) { var ajax_area = Drupal.settings.views.ajax.id; var ajax_title = Drupal.settings.views.ajax.title; // Bind a click to the button to set the value for the button. $('input[type=submit], button', ajax_area).unbind('click'); $('input[type=submit], button', ajax_area).click(function() { $('form', ajax_area).append('<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).val() + '">'); $(this).after('<span class="views-throbbing">&nbsp</span>'); }); // Bind forms to ajax submit. $('form', ajax_area).unbind('submit'); // be safe here. $('form', ajax_area).submit(function(arg) { $(this).ajaxSubmit({ url: data.url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.ajaxResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': data.url})); }, dataType: 'json' }); return false; }); } Drupal.attachBehaviors(ajax_area); } else { // If no display, reset the form. Drupal.Views.Ajax.setForm('', Drupal.settings.views.ajax.defaultForm); //Enable the save button. $('#edit-save').removeAttr('disabled'); // Trigger an update for the live preview when we reach this state: $('#views-ui-preview-form').trigger('submit'); } // Go through the 'add' array and add any new content we're instructed to add. if (data.add) { for (id in data.add) { var newContent = $(id).append(data.add[id]); Drupal.attachBehaviors(newContent); } } // Go through the 'replace' array and replace any content we're instructed to. if (data.replace) { for (id in data.replace) { $(id).html(data.replace[id]); Drupal.attachBehaviors(id); } } // Go through and add any requested tabs if (data.tab) { for (id in data.tab) { $('#views-tabset').addTab(id, data.tab[id]['title'], 0); $(id).html(data.tab[id]['body']); $(id).addClass('views-tab'); Drupal.attachBehaviors(id); // This is kind of annoying, but we have to actually to find where the new // tab is. var instance = $.ui.tabs.instances[$('#views-tabset').get(0).UI_TABS_UUID]; $('#views-tabset').clickTab(instance.$tabs.length); } } if (data.hilite) { $('.hilited').removeClass('hilited'); $(data.hilite).addClass('hilited'); } if (data.changed) { $('div.views-basic-info').addClass('changed'); } } /** * An ajax responder that accepts a packet of JSON data and acts appropriately. * This one specifically responds to the Views live preview area, so it's * hardcoded and specialized. */ Drupal.Views.Ajax.previewResponse = function(data) { $('a.views-throbbing').removeClass('views-throbbing'); $('span.views-throbbing').remove(); if (data.debug) { alert(data.debug); } // See if we have any settings to extend. Do this first so that behaviors // can access the new settings easily. // Clear any previous viewsAjax settings. if (Drupal.settings.viewsAjax) { Drupal.settings.viewsAjax = {}; } if (data.js) { $.extend(Drupal.settings, data.js); } // Check the 'display' for data. if (data.display) { var ajax_area = 'div#views-live-preview'; $(ajax_area).html(data.display); var url = $(ajax_area, 'form').attr('action'); // if a URL was supplied, bind the form to it. if (url) { // Bind a click to the button to set the value for the button. $('input[type=submit], button', ajax_area).unbind('click'); $('input[type=submit], button', ajax_area).click(function() { $('form', ajax_area).append('<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).val() + '">'); $(this).after('<span class="views-throbbing">&nbsp</span>'); }); // Bind forms to ajax submit. $('form', ajax_area).unbind('submit'); // be safe here. $('form', ajax_area).submit(function() { $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.previewResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; }); } Drupal.attachBehaviors(ajax_area); } } Drupal.Views.updatePreviewForm = function() { var url = $(this).attr('action'); url = url.replace('nojs', 'ajax'); $('input[type=submit], button', this).after('<span class="views-throbbing">&nbsp</span>'); $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.previewResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; } Drupal.Views.updatePreviewFilterForm = function() { var url = $(this).attr('action'); url = url.replace('nojs', 'ajax'); $('input[type=submit], button', this).after('<span class="views-throbbing">&nbsp</span>'); $('input[name=q]', this).remove(); // remove 'q' for live preview. $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'GET', success: Drupal.Views.Ajax.previewResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; } Drupal.Views.updatePreviewLink = function() { var url = $(this).attr('href'); url = url.replace('nojs', 'ajax'); if (url.substring(0, 18) != '/admin/build/views') { return true; } $(this).addClass('views-throbbing'); $.ajax({ url: url, data: 'js=1', type: 'POST', success: Drupal.Views.Ajax.previewResponse, error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; } Drupal.behaviors.ViewsAjaxLinks = function() { // Make specified links ajaxy. $('a.views-ajax-link:not(.views-processed)').addClass('views-processed').click(function() { // Translate the href on the link to the ajax href. That way this degrades // into a nice, normal link. var url = $(this).attr('href'); url = url.replace('nojs', 'ajax'); // Turn on the hilite to indicate this is in use. $(this).addClass('hilite'); // Disable the save button. $('#edit-save').attr('disabled', 'true'); $(this).addClass('views-throbbing'); $.ajax({ type: "POST", url: url, data: 'js=1', success: Drupal.Views.Ajax.ajaxResponse, error: function() { $(this).removeClass('views-throbbing'); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; }); $('form.views-ajax-form:not(.views-processed)').addClass('views-processed').submit(function(arg) { // Translate the href on the link to the ajax href. That way this degrades // into a nice, normal link. var url = $(this).attr('action'); url = url.replace('nojs', 'ajax'); // $('input[@type=submit]', this).after('<span class="views-throbbing">&nbsp</span>'); $(this).ajaxSubmit({ url: url, data: { 'js': 1 }, type: 'POST', success: Drupal.Views.Ajax.ajaxResponse, error: function() { $('span.views-throbbing').remove(); alert(Drupal.t("An error occurred at @path.", {'@path': url})); }, dataType: 'json' }); return false; }); // Bind the live preview to where it's supposed to go. $('form#views-ui-preview-form:not(.views-processed)') .addClass('views-processed') .submit(Drupal.Views.updatePreviewForm); $('div#views-live-preview form:not(.views-processed)') .addClass('views-processed') .submit(Drupal.Views.updatePreviewFilterForm); $('div#views-live-preview a:not(.views-processed)') .addClass('views-processed') .click(Drupal.Views.updatePreviewLink); } /** * Get rid of irritating tabledrag messages */ Drupal.theme.tableDragChangedWarning = function () { return '<div></div>'; }
hugowetterberg/goodold_drupal
sites/all/modules/views/js/ajax.js
JavaScript
gpl-2.0
9,897
esprima.tokenize(null);
supriyantomaftuh/esprima
test/fixtures/api/migrated_0010.run.js
JavaScript
bsd-2-clause
24