code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<a href="/change-log.html" class="btn btn-success btn-full"><svg width="28" height="30" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M448 1472q0-26-19-45t-45-19-45 19-19 45 19 45 45 19 45-19 19-45zm644-420l-682 682q-37 37-90 37-52 0-91-37l-106-108q-38-36-38-90 0-53 38-91l681-681q39 98 114.5 173.5t173.5 114.5zm634-435q0 39-23 106-47 134-164.5 217.5t-258.5 83.5q-185 0-316.5-131.5t-131.5-316.5 131.5-316.5 316.5-131.5q58 0 121.5 16.5t107.5 46.5q16 11 16 28t-16 28l-293 169v224l193 107q5-3 79-48.5t135.5-81 70.5-35.5q15 0 23.5 10t8.5 25z" fill="#fff"/></svg></a>
<p class="under-btn">What's new on Full Stack Python?</p>
| mattmakai/fullstackpython.com | theme/templates/choices/buttons/change-log.html | HTML | mit | 643 |
var browserify = require('../');
var path = require('path');
var spawn = require('child_process').spawn;
var parseShell = require('shell-quote').parse;
var duplexer = require('duplexer');
module.exports = function (args) {
var argv = require('optimist')(args)
.boolean(['deps','pack','ig','dg', 'im', 'd','list'])
.string(['s'])
.alias('insert-globals', 'ig')
.alias('detect-globals', 'dg')
.alias('ignore-missing', 'im')
.alias('debug', 'd')
.alias('standalone', 's')
.alias('ig', 'fast')
.alias('noparse', 'noParse')
.default('ig', false)
.default('im', false)
.default('dg', true)
.default('d', false)
.argv
;
var entries = argv._.concat(argv.e).concat(argv.entry)
.filter(Boolean).map(function(entry) {
return path.resolve(process.cwd(), entry);
});
if (argv.s && entries.length === 0
&& [].concat(argv.r, argv.require).filter(Boolean).length === 1) {
entries.push([].concat(argv.r, argv.require).filter(Boolean)[0]);
argv.r = argv.require = [];
}
var b = browserify({
noParse: [].concat(argv.noparse).filter(Boolean),
extensions: [].concat(argv.extension).filter(Boolean),
entries: entries
});
b.argv = argv;
[].concat(argv.i).concat(argv.ignore).filter(Boolean)
.forEach(function (i) { b.ignore(i) })
;
[].concat(argv.r).concat(argv.require).filter(Boolean)
.forEach(function (r) {
var xs = r.split(':');
b.require(xs[0], { expose: xs.length === 1 ? xs[0] : xs[1] })
})
;
// resolve any external files and add them to the bundle as externals
[].concat(argv.x).concat(argv.external).filter(Boolean)
.forEach(function (x) {
if (/^[\/.]/.test(x)) b.external(path.resolve(process.cwd(), x))
else b.external(x)
})
;
[].concat(argv.t).concat(argv.transform).filter(Boolean)
.forEach(function (t) { b.transform(t) })
;
[].concat(argv.c).concat(argv.command).filter(Boolean)
.forEach(function (c) {
var cmd = parseShell(c);
b.transform(function (file) {
var env = Object.keys(process.env).reduce(function (acc, key) {
acc[key] = process.env[key];
return acc;
}, {});
env.FILENAME = file;
var ps = spawn(cmd[0], cmd.slice(1), { env: env });
var error = '';
ps.stderr.on('data', function (buf) { error += buf });
ps.on('exit', function (code) {
if (code === 0) return;
console.error([
'error running source transform command: ' + c,
error.split('\n').join('\n '),
''
].join('\n'));
process.exit(1);
});
return duplexer(ps.stdin, ps.stdout);
});
})
;
if (argv.standalone === true) {
process.nextTick(function () {
b.emit('error', '--standalone requires an export name argument');
});
return b;
}
var bundleOpts = {
detectGlobals: argv['detect-globals'] !== false && argv.dg !== false,
insertGlobals: argv['insert-globals'] || argv.ig,
ignoreMissing: argv['ignore-missing'] || argv.im,
debug: argv['debug'] || argv.d,
standalone: argv['standalone'] || argv.s
};
var bundle = b.bundle;
b.bundle = function (opts, cb) {
if (!opts) opts = {};
if (typeof opts === 'function') { cb = opts; opts = {} };
var bopts = copy(bundleOpts);
Object.keys(opts).forEach(function (key) {
bopts[key] = opts[key];
});
return bundle.call(b, bopts, cb);
};
return b;
};
function copy (obj) {
return Object.keys(obj).reduce(function (acc, key) {
acc[key] = obj[key];
return acc;
}, {});
}
| uublive/ZenBot | node_modules/simple-xmpp/node_modules/node-xmpp/node_modules/browserify/bin/args.js | JavaScript | mit | 4,162 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.7
*/
goog.provide('ng.material.components.subheader');
goog.require('ng.material.components.sticky');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.subheader
* @description
* SubHeader module
*
* Subheaders are special list tiles that delineate distinct sections of a
* list or grid list and are typically related to the current filtering or
* sorting criteria. Subheader tiles are either displayed inline with tiles or
* can be associated with content, for example, in an adjacent column.
*
* Upon scrolling, subheaders remain pinned to the top of the screen and remain
* pinned until pushed on or off screen by the next subheader. @see [Material
* Design Specifications](https://www.google.com/design/spec/components/subheaders.html)
*
* > To improve the visual grouping of content, use the system color for your subheaders.
*
*/
angular
.module('material.components.subheader', [
'material.core',
'material.components.sticky'
])
.directive('mdSubheader', MdSubheaderDirective);
/**
* @ngdoc directive
* @name mdSubheader
* @module material.components.subheader
*
* @restrict E
*
* @description
* The `<md-subheader>` directive is a subheader for a section. By default it is sticky.
* You can make it not sticky by applying the `md-no-sticky` class to the subheader.
*
*
* @usage
* <hljs lang="html">
* <md-subheader>Online Friends</md-subheader>
* </hljs>
*/
function MdSubheaderDirective($mdSticky, $compile, $mdTheming, $mdUtil) {
return {
restrict: 'E',
replace: true,
transclude: true,
template: (
'<div class="md-subheader">' +
' <div class="md-subheader-inner">' +
' <span class="md-subheader-content"></span>' +
' </div>' +
'</div>'
),
link: function postLink(scope, element, attr, controllers, transclude) {
$mdTheming(element);
var outerHTML = element[0].outerHTML;
function getContent(el) {
return angular.element(el[0].querySelector('.md-subheader-content'));
}
// Transclude the user-given contents of the subheader
// the conventional way.
transclude(scope, function(clone) {
getContent(element).append(clone);
});
// Create another clone, that uses the outer and inner contents
// of the element, that will be 'stickied' as the user scrolls.
if (!element.hasClass('md-no-sticky')) {
transclude(scope, function(clone) {
// If the user adds an ng-if or ng-repeat directly to the md-subheader element, the
// compiled clone below will only be a comment tag (since they replace their elements with
// a comment) which cannot be properly passed to the $mdSticky; so we wrap it in our own
// DIV to ensure we have something $mdSticky can use
var wrapperHtml = '<div class="md-subheader-wrapper">' + outerHTML + '</div>';
var stickyClone = $compile(wrapperHtml)(scope);
// Append the sticky
$mdSticky(scope, element, stickyClone);
// Delay initialization until after any `ng-if`/`ng-repeat`/etc has finished before
// attempting to create the clone
$mdUtil.nextTick(function() {
getContent(stickyClone).append(clone);
});
});
}
}
}
}
MdSubheaderDirective.$inject = ["$mdSticky", "$compile", "$mdTheming", "$mdUtil"];
ng.material.components.subheader = angular.module("material.components.subheader"); | valentin7/shazam-datascience | webapp/public/lib/angular-material/modules/closure/subheader/subheader.js | JavaScript | mit | 3,597 |
//------------------------------------------------------------------------------
// <copyright file="SymbolEqualComparer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Util {
using System.Collections;
using System.Globalization;
/// <devdoc>
/// <para>
/// For internal use only. This implements a comparison that only
/// checks for equalilty, so this should only be used in un-sorted data
/// structures like Hastable and ListDictionary. This is a little faster
/// than using CaseInsensitiveComparer because it does a strict character by
/// character equality chech rather than a sorted comparison.
/// </para>
/// </devdoc>
internal class SymbolEqualComparer: IComparer {
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal static readonly IComparer Default = new SymbolEqualComparer();
internal SymbolEqualComparer() {
}
int IComparer.Compare(object keyLeft, object keyRight) {
string sLeft = keyLeft as string;
string sRight = keyRight as string;
if (sLeft == null) {
throw new ArgumentNullException("keyLeft");
}
if (sRight == null) {
throw new ArgumentNullException("keyRight");
}
int lLeft = sLeft.Length;
int lRight = sRight.Length;
if (lLeft != lRight) {
return 1;
}
for (int i = 0; i < lLeft; i++) {
char charLeft = sLeft[i];
char charRight = sRight[i];
if (charLeft == charRight) {
continue;
}
UnicodeCategory catLeft = Char.GetUnicodeCategory(charLeft);
UnicodeCategory catRight = Char.GetUnicodeCategory(charRight);
if (catLeft == UnicodeCategory.UppercaseLetter
&& catRight == UnicodeCategory.LowercaseLetter) {
if (Char.ToLower(charLeft, CultureInfo.InvariantCulture) == charRight) {
continue;
}
} else if (catRight == UnicodeCategory.UppercaseLetter
&& catLeft == UnicodeCategory.LowercaseLetter){
if (Char.ToLower(charRight, CultureInfo.InvariantCulture) == charLeft) {
continue;
}
}
return 1;
}
return 0;
}
}
}
| sekcheong/referencesource | System.Web/Util/SymbolEqualComparer.cs | C# | mit | 2,788 |
using Umbraco.Core.Models;
namespace Umbraco.Core.Events
{
public class NewEventArgs<TEntity> : CancellableObjectEventArgs<TEntity>
{
public NewEventArgs(TEntity eventObject, bool canCancel, string @alias, int parentId) : base(eventObject, canCancel)
{
Alias = alias;
ParentId = parentId;
}
public NewEventArgs(TEntity eventObject, bool canCancel, string @alias, TEntity parent)
: base(eventObject, canCancel)
{
Alias = alias;
Parent = parent;
}
public NewEventArgs(TEntity eventObject, string @alias, int parentId) : base(eventObject)
{
Alias = alias;
ParentId = parentId;
}
public NewEventArgs(TEntity eventObject, string @alias, TEntity parent)
: base(eventObject)
{
Alias = alias;
Parent = parent;
}
/// <summary>
/// The entity being created
/// </summary>
public TEntity Entity
{
get { return EventObject; }
}
/// <summary>
/// Gets or Sets the Alias.
/// </summary>
public string Alias { get; private set; }
/// <summary>
/// Gets or Sets the Id of the parent.
/// </summary>
public int ParentId { get; private set; }
/// <summary>
/// Gets or Sets the parent IContent object.
/// </summary>
public TEntity Parent { get; private set; }
}
} | Shazwazza/Umbraco-CMS | src/Umbraco.Core/Events/NewEventArgs.cs | C# | mit | 1,419 |
# Deploy an Azure Databricks Workspace with a Custom Virtual Network Address Range
<a href="https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F101-databricks-workspace-with-custom-vnet-address%2Fazuredeploy.json" target="_blank">
<img src="http://azuredeploy.net/deploybutton.png"/>
</a>
<a href="http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F101-databricks-workspace-with-custom-vnet-address%2Fazuredeploy.json" target="_blank">
<img src="http://armviz.io/visualizebutton.png"/>
</a>
This template allows you to create a Azure Databricks workspace with a custom virtual network address range.
For more information, see the <a href="https://docs.microsoft.com/en-us/azure/azure-databricks/">Azure Databricks Documentation</a>.
| SunBuild/azure-quickstart-templates | 101-databricks-workspace-with-custom-vnet-address/README.md | Markdown | mit | 897 |
<?php
/*
* This file is part of the FOSUserBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\UserBundle\Tests\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use FOS\UserBundle\DependencyInjection\FOSUserExtension;
use Symfony\Component\Yaml\Parser;
class FOSUserExtensionTest extends \PHPUnit_Framework_TestCase
{
/** @var ContainerBuilder */
protected $configuration;
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testUserLoadThrowsExceptionUnlessDatabaseDriverSet()
{
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
unset($config['db_driver']);
$loader->load(array($config), new ContainerBuilder());
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testUserLoadThrowsExceptionUnlessDatabaseDriverIsValid()
{
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$config['db_driver'] = 'foo';
$loader->load(array($config), new ContainerBuilder());
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testUserLoadThrowsExceptionUnlessFirewallNameSet()
{
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
unset($config['firewall_name']);
$loader->load(array($config), new ContainerBuilder());
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testUserLoadThrowsExceptionUnlessGroupModelClassSet()
{
$loader = new FOSUserExtension();
$config = $this->getFullConfig();
unset($config['group']['group_class']);
$loader->load(array($config), new ContainerBuilder());
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testUserLoadThrowsExceptionUnlessUserModelClassSet()
{
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
unset($config['user_class']);
$loader->load(array($config), new ContainerBuilder());
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testCustomDriverWithoutManager()
{
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$config['db_driver'] = 'custom';
$loader->load(array($config), new ContainerBuilder());
}
public function testCustomDriver()
{
$this->configuration = new ContainerBuilder();
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$config['db_driver'] = 'custom';
$config['service']['user_manager'] = 'acme.user_manager';
$loader->load(array($config), $this->configuration);
$this->assertNotHasDefinition('fos_user.user_manager.default');
$this->assertAlias('acme.user_manager', 'fos_user.user_manager');
$this->assertParameter('custom', 'fos_user.storage');
}
public function testDisableRegistration()
{
$this->configuration = new ContainerBuilder();
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$config['registration'] = false;
$loader->load(array($config), $this->configuration);
$this->assertNotHasDefinition('fos_user.registration.form.factory');
}
public function testDisableResetting()
{
$this->configuration = new ContainerBuilder();
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$config['resetting'] = false;
$loader->load(array($config), $this->configuration);
$this->assertNotHasDefinition('fos_user.resetting.form.factory');
}
public function testDisableProfile()
{
$this->configuration = new ContainerBuilder();
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$config['profile'] = false;
$loader->load(array($config), $this->configuration);
$this->assertNotHasDefinition('fos_user.profile.form.factory');
}
public function testDisableChangePassword()
{
$this->configuration = new ContainerBuilder();
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$config['change_password'] = false;
$loader->load(array($config), $this->configuration);
$this->assertNotHasDefinition('fos_user.change_password.form.factory');
}
public function testUserLoadModelClassWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertParameter('Acme\MyBundle\Document\User', 'fos_user.model.user.class');
}
public function testUserLoadModelClass()
{
$this->createFullConfiguration();
$this->assertParameter('Acme\MyBundle\Entity\User', 'fos_user.model.user.class');
}
public function testUserLoadManagerClassWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertParameter('mongodb', 'fos_user.storage');
$this->assertParameter(null, 'fos_user.model_manager_name');
$this->assertAlias('fos_user.user_manager.default', 'fos_user.user_manager');
$this->assertNotHasDefinition('fos_user.group_manager');
}
public function testUserLoadManagerClass()
{
$this->createFullConfiguration();
$this->assertParameter('orm', 'fos_user.storage');
$this->assertParameter('custom', 'fos_user.model_manager_name');
$this->assertAlias('acme_my.user_manager', 'fos_user.user_manager');
$this->assertAlias('fos_user.group_manager.default', 'fos_user.group_manager');
}
public function testUserLoadFormClassWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertParameter('fos_user_profile', 'fos_user.profile.form.type');
$this->assertParameter('fos_user_registration', 'fos_user.registration.form.type');
$this->assertParameter('fos_user_change_password', 'fos_user.change_password.form.type');
$this->assertParameter('fos_user_resetting', 'fos_user.resetting.form.type');
}
public function testUserLoadFormClass()
{
$this->createFullConfiguration();
$this->assertParameter('acme_my_profile', 'fos_user.profile.form.type');
$this->assertParameter('acme_my_registration', 'fos_user.registration.form.type');
$this->assertParameter('acme_my_group', 'fos_user.group.form.type');
$this->assertParameter('acme_my_change_password', 'fos_user.change_password.form.type');
$this->assertParameter('acme_my_resetting', 'fos_user.resetting.form.type');
}
public function testUserLoadFormNameWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertParameter('fos_user_profile_form', 'fos_user.profile.form.name');
$this->assertParameter('fos_user_registration_form', 'fos_user.registration.form.name');
$this->assertParameter('fos_user_change_password_form', 'fos_user.change_password.form.name');
$this->assertParameter('fos_user_resetting_form', 'fos_user.resetting.form.name');
}
public function testUserLoadFormName()
{
$this->createFullConfiguration();
$this->assertParameter('acme_profile_form', 'fos_user.profile.form.name');
$this->assertParameter('acme_registration_form', 'fos_user.registration.form.name');
$this->assertParameter('acme_group_form', 'fos_user.group.form.name');
$this->assertParameter('acme_change_password_form', 'fos_user.change_password.form.name');
$this->assertParameter('acme_resetting_form', 'fos_user.resetting.form.name');
}
public function testUserLoadFormServiceWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertHasDefinition('fos_user.profile.form.factory');
$this->assertHasDefinition('fos_user.registration.form.factory');
$this->assertNotHasDefinition('fos_user.group.form.factory');
$this->assertHasDefinition('fos_user.change_password.form.factory');
$this->assertHasDefinition('fos_user.resetting.form.factory');
}
public function testUserLoadFormService()
{
$this->createFullConfiguration();
$this->assertHasDefinition('fos_user.profile.form.factory');
$this->assertHasDefinition('fos_user.registration.form.factory');
$this->assertHasDefinition('fos_user.group.form.factory');
$this->assertHasDefinition('fos_user.change_password.form.factory');
$this->assertHasDefinition('fos_user.resetting.form.factory');
}
public function testUserLoadConfirmationEmailWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertParameter(false, 'fos_user.registration.confirmation.enabled');
$this->assertParameter(array('[email protected]' => 'webmaster'), 'fos_user.registration.confirmation.from_email');
$this->assertParameter('FOSUserBundle:Registration:email.txt.twig', 'fos_user.registration.confirmation.template');
$this->assertParameter('FOSUserBundle:Resetting:email.txt.twig', 'fos_user.resetting.email.template');
$this->assertParameter(array('[email protected]' => 'webmaster'), 'fos_user.resetting.email.from_email');
$this->assertParameter(86400, 'fos_user.resetting.token_ttl');
}
public function testUserLoadConfirmationEmail()
{
$this->createFullConfiguration();
$this->assertParameter(true, 'fos_user.registration.confirmation.enabled');
$this->assertParameter(array('[email protected]' => 'Acme Corp'), 'fos_user.registration.confirmation.from_email');
$this->assertParameter('AcmeMyBundle:Registration:mail.txt.twig', 'fos_user.registration.confirmation.template');
$this->assertParameter('AcmeMyBundle:Resetting:mail.txt.twig', 'fos_user.resetting.email.template');
$this->assertParameter(array('[email protected]' => 'Acme Corp'), 'fos_user.resetting.email.from_email');
$this->assertParameter(1800, 'fos_user.resetting.token_ttl');
}
public function testUserLoadTemplateConfigWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertParameter('twig', 'fos_user.template.engine');
}
public function testUserLoadTemplateConfig()
{
$this->createFullConfiguration();
$this->assertParameter('php', 'fos_user.template.engine');
}
public function testUserLoadUtilServiceWithDefaults()
{
$this->createEmptyConfiguration();
$this->assertAlias('fos_user.mailer.default', 'fos_user.mailer');
$this->assertAlias('fos_user.util.canonicalizer.default', 'fos_user.util.email_canonicalizer');
$this->assertAlias('fos_user.util.canonicalizer.default', 'fos_user.util.username_canonicalizer');
}
public function testUserLoadUtilService()
{
$this->createFullConfiguration();
$this->assertAlias('acme_my.mailer', 'fos_user.mailer');
$this->assertAlias('acme_my.email_canonicalizer', 'fos_user.util.email_canonicalizer');
$this->assertAlias('acme_my.username_canonicalizer', 'fos_user.util.username_canonicalizer');
}
protected function createEmptyConfiguration()
{
$this->configuration = new ContainerBuilder();
$loader = new FOSUserExtension();
$config = $this->getEmptyConfig();
$loader->load(array($config), $this->configuration);
$this->assertTrue($this->configuration instanceof ContainerBuilder);
}
protected function createFullConfiguration()
{
$this->configuration = new ContainerBuilder();
$loader = new FOSUserExtension();
$config = $this->getFullConfig();
$loader->load(array($config), $this->configuration);
$this->assertTrue($this->configuration instanceof ContainerBuilder);
}
/**
* getEmptyConfig
*
* @return array
*/
protected function getEmptyConfig()
{
$yaml = <<<EOF
db_driver: mongodb
firewall_name: fos_user
user_class: Acme\MyBundle\Document\User
EOF;
$parser = new Parser();
return $parser->parse($yaml);
}
protected function getFullConfig()
{
$yaml = <<<EOF
db_driver: orm
firewall_name: fos_user
use_listener: true
user_class: Acme\MyBundle\Entity\User
model_manager_name: custom
from_email:
address: [email protected]
sender_name: Acme Corp
profile:
form:
type: acme_my_profile
name: acme_profile_form
validation_groups: [acme_profile]
change_password:
form:
type: acme_my_change_password
name: acme_change_password_form
validation_groups: [acme_change_password]
registration:
confirmation:
from_email:
address: [email protected]
sender_name: Acme Corp
enabled: true
template: AcmeMyBundle:Registration:mail.txt.twig
form:
type: acme_my_registration
name: acme_registration_form
validation_groups: [acme_registration]
resetting:
token_ttl: 1800
email:
from_email:
address: [email protected]
sender_name: Acme Corp
template: AcmeMyBundle:Resetting:mail.txt.twig
form:
type: acme_my_resetting
name: acme_resetting_form
validation_groups: [acme_resetting]
service:
mailer: acme_my.mailer
email_canonicalizer: acme_my.email_canonicalizer
username_canonicalizer: acme_my.username_canonicalizer
user_manager: acme_my.user_manager
template:
engine: php
group:
group_class: Acme\MyBundle\Entity\Group
form:
type: acme_my_group
name: acme_group_form
validation_groups: [acme_group]
EOF;
$parser = new Parser();
return $parser->parse($yaml);
}
/**
* @param string $value
* @param string $key
*/
private function assertAlias($value, $key)
{
$this->assertEquals($value, (string) $this->configuration->getAlias($key), sprintf('%s alias is correct', $key));
}
/**
* @param mixed $value
* @param string $key
*/
private function assertParameter($value, $key)
{
$this->assertEquals($value, $this->configuration->getParameter($key), sprintf('%s parameter is correct', $key));
}
/**
* @param string $id
*/
private function assertHasDefinition($id)
{
$this->assertTrue(($this->configuration->hasDefinition($id) ?: $this->configuration->hasAlias($id)));
}
/**
* @param string $id
*/
private function assertNotHasDefinition($id)
{
$this->assertFalse(($this->configuration->hasDefinition($id) ?: $this->configuration->hasAlias($id)));
}
protected function tearDown()
{
unset($this->configuration);
}
}
| Gerome54520/ProjetWebSujet2 | vendor/symfony/symfony/src/Symfony/Bundle/FOSUserBundle-master/Tests/DependencyInjection/FOSUserExtensionTest.php | PHP | mit | 15,408 |
/* ----------------------------------------------------------------------
* Copyright (C) 2010-2013 ARM Limited. All rights reserved.
*
* $Date: 17. January 2013
* $Revision: V1.4.1
*
* Project: CMSIS DSP Library
* Title: arm_min_q7.c
*
* Description: Minimum value of a Q7 vector.
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* 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 ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ---------------------------------------------------------------------------- */
#include "arm_math.h"
/**
* @ingroup groupStats
*/
/**
* @addtogroup Min
* @{
*/
/**
* @brief Minimum value of a Q7 vector.
* @param[in] *pSrc points to the input vector
* @param[in] blockSize length of the input vector
* @param[out] *pResult minimum value returned here
* @param[out] *pIndex index of minimum value returned here
* @return none.
*
*/
void arm_min_q7(
q7_t * pSrc,
uint32_t blockSize,
q7_t * pResult,
uint32_t * pIndex)
{
#ifndef ARM_MATH_CM0_FAMILY
/* Run the below code for Cortex-M4 and Cortex-M3 */
q7_t minVal1, minVal2, out; /* Temporary variables to store the output value. */
uint32_t blkCnt, outIndex, count; /* loop counter */
/* Initialise the count value. */
count = 0u;
/* Initialise the index value to zero. */
outIndex = 0u;
/* Load first input value that act as reference value for comparision */
out = *pSrc++;
/* Loop unrolling */
blkCnt = (blockSize - 1u) >> 2u;
while(blkCnt > 0)
{
/* Initialize minVal to the next consecutive values one by one */
minVal1 = *pSrc++;
minVal2 = *pSrc++;
/* compare for the minimum value */
if(out > minVal1)
{
/* Update the minimum value and its index */
out = minVal1;
outIndex = count + 1u;
}
minVal1 = *pSrc++;
/* compare for the minimum value */
if(out > minVal2)
{
/* Update the minimum value and its index */
out = minVal2;
outIndex = count + 2u;
}
minVal2 = *pSrc++;
/* compare for the minimum value */
if(out > minVal1)
{
/* Update the minimum value and its index */
out = minVal1;
outIndex = count + 3u;
}
/* compare for the minimum value */
if(out > minVal2)
{
/* Update the minimum value and its index */
out = minVal2;
outIndex = count + 4u;
}
count += 4u;
blkCnt--;
}
/* if (blockSize - 1u ) is not multiple of 4 */
blkCnt = (blockSize - 1u) % 4u;
#else
/* Run the below code for Cortex-M0 */
q7_t minVal1, out; /* Temporary variables to store the output value. */
uint32_t blkCnt, outIndex; /* loop counter */
/* Initialise the index value to zero. */
outIndex = 0u;
/* Load first input value that act as reference value for comparision */
out = *pSrc++;
blkCnt = (blockSize - 1u);
#endif // #ifndef ARM_MATH_CM0_FAMILY
while(blkCnt > 0)
{
/* Initialize minVal to the next consecutive values one by one */
minVal1 = *pSrc++;
/* compare for the minimum value */
if(out > minVal1)
{
/* Update the minimum value and it's index */
out = minVal1;
outIndex = blockSize - blkCnt;
}
blkCnt--;
}
/* Store the minimum value and its index into destination pointers */
*pResult = out;
*pIndex = outIndex;
}
/**
* @} end of Min group
*/
| james54068/stm32f429_learning | stm32f429_SDCard/Libraries/CMSIS/DSP_Lib/Source/StatisticsFunctions/arm_min_q7.c | C | mit | 5,149 |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: IFormatterConverter
**
**
** Purpose: The interface provides the connection between an
** instance of SerializationInfo and the formatter-provided
** class which knows how to parse the data inside the
** SerializationInfo.
**
**
============================================================*/
namespace System.Runtime.Serialization {
using System;
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatterConverter {
Object Convert(Object value, Type type);
Object Convert(Object value, TypeCode typeCode);
bool ToBoolean(Object value);
char ToChar(Object value);
sbyte ToSByte(Object value);
byte ToByte(Object value);
short ToInt16(Object value);
ushort ToUInt16(Object value);
int ToInt32(Object value);
uint ToUInt32(Object value);
long ToInt64(Object value);
ulong ToUInt64(Object value);
float ToSingle(Object value);
double ToDouble(Object value);
Decimal ToDecimal(Object value);
DateTime ToDateTime(Object value);
String ToString(Object value);
}
}
| sekcheong/referencesource | mscorlib/system/runtime/serialization/iformatterconverter.cs | C# | mit | 1,340 |
# FrameAccessor
Easy way to access view's frame in iOS and OSX.
## Compatibility
* iOS 4.3 or higher
* OSX 10.6 or higher
## Installation
### CocoaPods
The recommended approach for installating `FrameAccessor` is via the [CocoaPods](http://cocoapods.org/) package manager, as it provides flexible dependency management and dead simple installation.
For best results, it is recommended that you install via CocoaPods >= **0.27.0** using Git >= **1.8.0** installed via Homebrew.
Install CocoaPods if not already available:
``` bash
$ [sudo] gem install cocoapods
$ pod setup
```
Change to the directory of your Xcode project:
``` bash
$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
```
Edit your Podfile and add `FrameAccessor`:
``` bash
pod 'FrameAccessor'
```
Install into your Xcode project:
``` bash
$ pod install
```
Open your project in Xcode from the .xcworkspace file (not the usual project file)
``` bash
$ open MyProject.xcworkspace
```
Please note that if your installation fails, it may be because you are installing with a version of Git lower than CocoaPods is expecting. Please ensure that you are running Git >= **1.8.0** by executing `git --version`. You can get a full picture of the installation details by executing `pod install --verbose`.
### Manual Install
All you need to do is drop `FrameAccessor` files into your project, and add `#include "FrameAccessor.h"` to the top of files that will use it.
## Example Usage
```objective-c
view.x = 15.;
view.width = 167.;
```
instead of
```objective-c
CGRect newFrame = view.frame;
newFrame.origin.x = 15.;
newFrame.size.width = 167.;
view.frame = newFrame;
```
## Available Properties
`UIView/NSView` properties:
Property | Type | Аvailability
--- | --- | ---
`origin` | `CGPoint` | *readwrite*
`size` | `CGSize` | *readwrite*
`x`, `y` | `CGFloat` | *readwrite*
`width`, `height` | `CGFloat` | *readwrite*
`top`, `left`, `bottom`, `right` | `CGFloat` | *readwrite*
`centerX`, `centerY` | `CGFloat` | *readwrite*
`middlePoint` | `CGPoint` | **readonly**
`middleX`, `middleY` | `CGFloat` | **readonly**
`UIScrollView` properties:
Property | Type | Аvailability
--- | --- | ---
`contentOffsetX`, `contentOffsetY` | `CGFloat` | *readwrite*
`contentSizeWidth`, `contentSizeHeight` | `CGFloat` | *readwrite*
`contentInsetTop`, `contentInsetLeft`, <br>`contentInsetBottom`, `contentInsetRight` | `CGFloat` | *readwrite*
## License
FrameAccessor is available under the MIT license.
Copyright (c) 2012 Alexey Denisov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| Wicowyn/SoundFi | Versionning projet/SoundFi.26.05.KO/Pods/FrameAccessor/README.md | Markdown | mit | 3,538 |
'use strict';
/* global JQLitePrototype: true,
addEventListenerFn: true,
removeEventListenerFn: true,
BOOLEAN_ATTR: true,
ALIASED_ATTR: true,
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @module ng
* @kind function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*
* <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
* commonly needed functionality with the goal of having a very small footprint.</div>
*
* To use jQuery, simply load it before `DOMContentLoaded` event fired.
*
* <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
* jqLite; they are never raw DOM references.</div>
*
* ## Angular's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/)
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/)
* - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
* - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`
* - [`data()`](http://api.jquery.com/data/)
* - [`detach()`](http://api.jquery.com/detach/)
* - [`empty()`](http://api.jquery.com/empty/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/)
* - [`removeClass()`](http://api.jquery.com/removeClass/)
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/)
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
* - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* Angular also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
* element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
* be enabled.
* - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
JQLite.expando = 'ng339';
var jqCache = JQLite.cache = {},
jqId = 1,
addEventListenerFn = function(element, type, fn) {
element.addEventListener(type, fn, false);
},
removeEventListenerFn = function(element, type, fn) {
element.removeEventListener(type, fn, false);
};
/*
* !!! This is an undocumented "private" function !!!
*/
JQLite._data = function(node) {
//jQuery always returns an object on cache miss
return this.cache[node[this.expando]] || {};
};
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|&#?\w+;/;
var TAG_NAME_REGEXP = /<([\w:]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, '<select multiple="multiple">', '</select>'],
'thead': [1, '<table>', '</table>'],
'col': [2, '<table><colgroup>', '</colgroup></table>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
'_default': [0, "", ""]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}
function jqLiteAcceptsData(node) {
// The window object can accept data but has no nodeType
// Otherwise we are only interested in elements (1) and documents (9)
var nodeType = node.nodeType;
return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}
function jqLiteBuildFragment(html, context) {
var tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i;
if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
// Convert html into DOM nodes
tmp = tmp || fragment.appendChild(context.createElement("div"));
tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}
nodes = concat(nodes, tmp.childNodes);
tmp = fragment.firstChild;
tmp.textContent = "";
}
// Remove wrapper from fragment
fragment.textContent = "";
fragment.innerHTML = ""; // Clear inner HTML
forEach(nodes, function(node) {
fragment.appendChild(node);
});
return fragment;
}
function jqLiteParseHTML(html, context) {
context = context || document;
var parsed;
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}
if ((parsed = jqLiteBuildFragment(html, context))) {
return parsed.childNodes;
}
return [];
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
var argIsString;
if (isString(element)) {
element = trim(element);
argIsString = true;
}
if (!(this instanceof JQLite)) {
if (argIsString && element.charAt(0) != '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (argIsString) {
jqLiteAddNodes(this, jqLiteParseHTML(element));
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element, onlyDescendants) {
if (!onlyDescendants) jqLiteRemoveData(element);
if (element.querySelectorAll) {
var descendants = element.querySelectorAll('*');
for (var i = 0, l = descendants.length; i < l; i++) {
jqLiteRemoveData(descendants[i]);
}
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var handle = expandoStore && expandoStore.handle;
if (!handle) return; //no listeners registered
if (!type) {
for (type in events) {
if (type !== '$destroy') {
removeEventListenerFn(element, type, handle);
}
delete events[type];
}
} else {
forEach(type.split(' '), function(type) {
if (isDefined(fn)) {
var listenerFns = events[type];
arrayRemove(listenerFns || [], fn);
if (listenerFns && listenerFns.length > 0) {
return;
}
}
removeEventListenerFn(element, type, handle);
delete events[type];
});
}
}
function jqLiteRemoveData(element, name) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
if (expandoStore) {
if (name) {
delete expandoStore.data[name];
return;
}
if (expandoStore.handle) {
if (expandoStore.events.$destroy) {
expandoStore.handle({}, '$destroy');
}
jqLiteOff(element);
}
delete jqCache[expandoId];
element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteExpandoStore(element, createIfNecessary) {
var expandoId = element.ng339,
expandoStore = expandoId && jqCache[expandoId];
if (createIfNecessary && !expandoStore) {
element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
}
return expandoStore;
}
function jqLiteData(element, key, value) {
if (jqLiteAcceptsData(element)) {
var isSimpleSetter = isDefined(value);
var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
var massGetter = !key;
var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
var data = expandoStore && expandoStore.data;
if (isSimpleSetter) { // data('key', value)
data[key] = value;
} else {
if (massGetter) { // data()
return data;
} else {
if (isSimpleGetter) { // data('key')
// don't force creation of expandoStore if it doesn't exist yet
return data && data[key];
} else { // mass-setter: data({key1: val1, key2: val2})
extend(data, key);
}
}
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
indexOf(" " + selector + " ") > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', trim(existingClasses));
}
}
function jqLiteAddNodes(root, elements) {
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
if (elements) {
// if a Node (the most common case)
if (elements.nodeType) {
root[root.length++] = elements;
} else {
var length = elements.length;
// if an Array or NodeList and not a Window
if (typeof length === 'number' && elements.window !== elements) {
if (length) {
for (var i = 0; i < length; i++) {
root[root.length++] = elements[i];
}
}
} else {
root[root.length++] = elements;
}
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element.nodeType == NODE_TYPE_DOCUMENT) {
element = element.documentElement;
}
var names = isArray(name) ? name : [name];
while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
if ((value = jqLite.data(element, names[i])) !== undefined) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
}
}
function jqLiteEmpty(element) {
jqLiteDealoc(element, true);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function jqLiteRemove(element, keepData) {
if (!keepData) jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
}
function jqLiteDocumentLoaded(action, win) {
win = win || window;
if (win.document.readyState === 'complete') {
// Force the action to be run async for consistent behaviour
// from the action's point of view
// i.e. it will definitely not be in a $apply
win.setTimeout(action);
} else {
// No need to unbind this handler as load is only ever called once
jqLite(win).on('load', action);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
// check if document is already loaded
if (document.readyState === 'complete') {
setTimeout(trigger);
} else {
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
// jshint -W064
JQLite(window).on('load', trigger); // fallback to window.onload for others
// jshint +W064
}
},
toString: function() {
var value = [];
forEach(this, function(e) { value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[value] = true;
});
var ALIASED_ATTR = {
'ngMinlength': 'minlength',
'ngMaxlength': 'maxlength',
'ngMin': 'min',
'ngMax': 'max',
'ngPattern': 'pattern'
};
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
}
function getAliasedAttrName(element, name) {
var nodeName = element.nodeName;
return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
}
forEach({
data: jqLiteData,
removeData: jqLiteRemoveData
}, function(fn, name) {
JQLite[name] = fn;
});
forEach({
data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
},
controller: jqLiteController,
injector: function(element) {
return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element, name) {
element.removeAttribute(name);
},
hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
return element.style[name];
}
},
attr: function(element, name, value) {
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name) || noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
getText.$dv = '';
return getText;
function getText(element, value) {
if (isUndefined(value)) {
var nodeType = element.nodeType;
return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
}
element.textContent = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (element.multiple && nodeName_(element) === 'select') {
var result = [];
forEach(element.options, function(option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result.length === 0 ? null : result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
jqLiteDealoc(element, true);
element.innerHTML = value;
},
empty: jqLiteEmpty
}, function(fn, name) {
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
var nodeCount = this.length;
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
// jqLiteEmpty takes no arguments but is a setter.
if (fn !== jqLiteEmpty &&
(((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for (i = 0; i < nodeCount; i++) {
if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
// TODO: do we still need this?
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for (i = 0; i < nodeCount; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function(event, type) {
// jQuery specific api
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
var eventFns = events[type || event.type];
var eventFnsLength = eventFns ? eventFns.length : 0;
if (!eventFnsLength) return;
if (isUndefined(event.immediatePropagationStopped)) {
var originalStopImmediatePropagation = event.stopImmediatePropagation;
event.stopImmediatePropagation = function() {
event.immediatePropagationStopped = true;
if (event.stopPropagation) {
event.stopPropagation();
}
if (originalStopImmediatePropagation) {
originalStopImmediatePropagation.call(event);
}
};
}
event.isImmediatePropagationStopped = function() {
return event.immediatePropagationStopped === true;
};
// Copy event handlers in case event handlers array is modified during execution.
if ((eventFnsLength > 1)) {
eventFns = shallowCopy(eventFns);
}
for (var i = 0; i < eventFnsLength; i++) {
if (!event.isImmediatePropagationStopped()) {
eventFns[i].call(element, event);
}
}
};
// TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
// events on `element`
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: jqLiteRemoveData,
on: function jqLiteOn(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
// Do not add event handlers to non-elements because they will not be cleaned up.
if (!jqLiteAcceptsData(element)) {
return;
}
var expandoStore = jqLiteExpandoStore(element, true);
var events = expandoStore.events;
var handle = expandoStore.handle;
if (!handle) {
handle = expandoStore.handle = createEventHandler(element, events);
}
// http://jsperf.com/string-indexof-vs-split
var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
var i = types.length;
while (i--) {
type = types[i];
var eventFns = events[type];
if (!eventFns) {
events[type] = [];
if (type === 'mouseenter' || type === 'mouseleave') {
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
var target = this, related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !target.contains(related))) {
handle(event, type);
}
});
} else {
if (type !== '$destroy') {
addEventListenerFn(element, type, handle);
}
}
eventFns = events[type];
}
eventFns.push(fn);
}
},
off: jqLiteOff,
one: function(element, type, fn) {
element = jqLite(element);
//add the listener twice so that when it is called
//you can remove the original function and still be
//able to call element.off(ev, fn) normally
element.on(type, function onFn() {
element.off(type, fn);
element.off(type, onFn);
});
element.on(type, fn);
},
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node) {
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element) {
if (element.nodeType === NODE_TYPE_ELEMENT)
children.push(element);
});
return children;
},
contents: function(element) {
return element.contentDocument || element.childNodes || [];
},
append: function(element, node) {
var nodeType = element.nodeType;
if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
node = new JQLite(node);
for (var i = 0, ii = node.length; i < ii; i++) {
var child = node[i];
element.appendChild(child);
}
},
prepend: function(element, node) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
var index = element.firstChild;
forEach(new JQLite(node), function(child) {
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode).eq(0).clone()[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: jqLiteRemove,
detach: function(element) {
jqLiteRemove(element, true);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
newElement = new JQLite(newElement);
for (var i = 0, ii = newElement.length; i < ii; i++) {
var node = newElement[i];
parent.insertBefore(node, index.nextSibling);
index = node;
}
},
addClass: jqLiteAddClass,
removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (selector) {
forEach(selector.split(' '), function(className) {
var classCondition = condition;
if (isUndefined(classCondition)) {
classCondition = !jqLiteHasClass(element, className);
}
(classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
});
}
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
},
next: function(element) {
return element.nextElementSibling;
},
find: function(element, selector) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(selector);
} else {
return [];
}
},
clone: jqLiteClone,
triggerHandler: function(element, event, extraParameters) {
var dummyEvent, eventFnsCopy, handlerArgs;
var eventName = event.type || event;
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var eventFns = events && events[eventName];
if (eventFns) {
// Create a dummy event to pass to the handlers
dummyEvent = {
preventDefault: function() { this.defaultPrevented = true; },
isDefaultPrevented: function() { return this.defaultPrevented === true; },
stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
stopPropagation: noop,
type: eventName,
target: element
};
// If a custom event was provided then extend our dummy event with it
if (event.type) {
dummyEvent = extend(dummyEvent, event);
}
// Copy event handlers in case event handlers array is modified during execution.
eventFnsCopy = shallowCopy(eventFns);
handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
forEach(eventFnsCopy, function(fn) {
if (!dummyEvent.isImmediatePropagationStopped()) {
fn.apply(element, handlerArgs);
}
});
}
}
}, function(fn, name) {
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for (var i = 0, ii = this.length; i < ii; i++) {
if (isUndefined(value)) {
value = fn(this[i], arg1, arg2, arg3);
if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return isDefined(value) ? value : this;
};
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
});
// Provider for private $$jqLite service
function $$jqLiteProvider() {
this.$get = function $$jqLite() {
return extend(JQLite, {
hasClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteHasClass(node, classes);
},
addClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteAddClass(node, classes);
},
removeClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteRemoveClass(node, classes);
}
});
};
}
| binaysahoo/angular.js | src/jqLite.js | JavaScript | mit | 31,867 |
var gulp = require('gulp');
var chokidar = require('chokidar');
var tarsConfig = require('../../../tars-config');
var watcherLog = require('../../helpers/watcher-log');
/**
* Watcher for data-files of modules
* @param {Object} watchOptions
*/
module.exports = function (watchOptions) {
return chokidar.watch('markup/modules/**/data/data.js', {
ignored: '',
persistent: true,
ignoreInitial: true
}).on('all', function (event, path) {
watcherLog(event, path);
gulp.start('compile-templates-with-data-reloading');
});
}; | extiser/familyclinic | tars/watchers/templates/data-files.js | JavaScript | mit | 574 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.TWEEN = global.TWEEN || {})));
}(this, (function (exports) { 'use strict';
/* global global */
var root = typeof (window) !== 'undefined' ? window : typeof (global) !== 'undefined' ? global : this;
if (!Object.assign) {
Object.assign = function (source) {
var args = [], len$1 = arguments.length - 1;
while ( len$1-- > 0 ) args[ len$1 ] = arguments[ len$1 + 1 ];
for (var i = 0, len = args.length; i < len; i++) {
var arg = args[i];
for (var p in arg) {
source[p] = arg[p];
}
}
return source
};
}
if (!Object.create) {
Object.create = function (source) {
return Object.assign({}, source || {})
};
}
if (!Array.isArray) {
Array.isArray = function (source) { return source && source.push && source.splice; };
}
if (typeof (requestAnimationFrame) === 'undefined') {
root.requestAnimationFrame = function (fn) { return root.setTimeout(fn, 16); };
}
if (typeof (cancelAnimationFrame) === 'undefined') {
root.cancelAnimationFrame = function (id) { return root.clearTimeout(id); };
}
/* global process */
var _tweens = [];
var isStarted = false;
var _autoPlay = false;
var _tick;
var _ticker = root.requestAnimationFrame;
var _stopTicker = root.cancelAnimationFrame;
var add = function (tween) {
_tweens.push(tween);
if (_autoPlay && !isStarted) {
_tick = _ticker(update);
isStarted = true;
}
};
var getAll = function () { return _tweens; };
var autoPlay = function (state) {
_autoPlay = state;
};
var removeAll = function () {
_tweens.length = 0;
};
var get = function (tween) {
for (var i = 0; i < _tweens.length; i++) {
if (tween === _tweens[i]) {
return _tweens[i]
}
}
return null
};
var has = function (tween) {
return get(tween) !== null
};
var remove = function (tween) {
var i = _tweens.indexOf(tween);
if (i !== -1) {
_tweens.splice(i, 1);
}
};
var now = (function () {
if (typeof (process) !== 'undefined' && process.hrtime !== undefined) {
return function () {
var time = process.hrtime();
// Convert [seconds, nanoseconds] to milliseconds.
return time[0] * 1000 + time[1] / 1000000
}
// In a browser, use window.performance.now if it is available.
} else if (root.performance !== undefined &&
root.performance.now !== undefined) {
// This must be bound, because directly assigning this function
// leads to an invocation exception in Chrome.
return root.performance.now.bind(root.performance)
// Use Date.now if it is available.
} else {
var offset = root.performance && root.performance.timing && root.performance.timing.navigationStart ? root.performance.timing.navigationStart : Date.now();
return function () {
return Date.now() - offset
}
}
}());
var update = function (time, preserve) {
time = time !== undefined ? time : now();
_tick = _ticker(update);
if (_tweens.length === 0) {
_stopTicker(_tick);
isStarted = false;
return false
}
var i = 0;
while (i < _tweens.length) {
_tweens[i].update(time, preserve);
i++;
}
return true
};
var isRunning = function () { return isStarted; };
var Plugins = {};
// Normalise time when visiblity is changed (if available) ...
if (root.document && root.document.addEventListener) {
var doc = root.document;
var timeDiff = 0;
var timePause = 0;
doc.addEventListener('visibilitychange', function () {
if (document.hidden) {
timePause = now();
_stopTicker(_tick);
isStarted = false;
} else {
timeDiff = now() - timePause;
for (var i = 0, length = _tweens.length; i < length; i++) {
_tweens[i]._startTime += timeDiff;
}
_tick = _ticker(update);
isStarted = true;
}
return true
});
}
var Easing = {
Linear: {
None: function None (k) {
return k
}
},
Quadratic: {
In: function In (k) {
return k * k
},
Out: function Out (k) {
return k * (2 - k)
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k
}
return -0.5 * (--k * (k - 2) - 1)
}
},
Cubic: {
In: function In (k) {
return k * k * k
},
Out: function Out (k) {
return --k * k * k + 1
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k
}
return 0.5 * ((k -= 2) * k * k + 2)
}
},
Quartic: {
In: function In (k) {
return k * k * k * k
},
Out: function Out (k) {
return 1 - (--k * k * k * k)
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k
}
return -0.5 * ((k -= 2) * k * k * k - 2)
}
},
Quintic: {
In: function In (k) {
return k * k * k * k * k
},
Out: function Out (k) {
return --k * k * k * k * k + 1
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k * k
}
return 0.5 * ((k -= 2) * k * k * k * k + 2)
}
},
Sinusoidal: {
In: function In (k) {
return 1 - Math.cos(k * Math.PI / 2)
},
Out: function Out (k) {
return Math.sin(k * Math.PI / 2)
},
InOut: function InOut (k) {
return 0.5 * (1 - Math.cos(Math.PI * k))
}
},
Exponential: {
In: function In (k) {
return k === 0 ? 0 : Math.pow(1024, k - 1)
},
Out: function Out (k) {
return k === 1 ? 1 : 1 - Math.pow(2, -10 * k)
},
InOut: function InOut (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
if ((k *= 2) < 1) {
return 0.5 * Math.pow(1024, k - 1)
}
return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2)
}
},
Circular: {
In: function In (k) {
return 1 - Math.sqrt(1 - k * k)
},
Out: function Out (k) {
return Math.sqrt(1 - (--k * k))
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - k * k) - 1)
}
return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1)
}
},
Elastic: {
In: function In (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI)
},
Out: function Out (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1
},
InOut: function InOut (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
k *= 2;
if (k < 1) {
return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI)
}
return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1
}
},
Back: {
In: function In (k) {
var s = 1.70158;
return k * k * ((s + 1) * k - s)
},
Out: function Out (k) {
var s = 1.70158;
return --k * k * ((s + 1) * k + s) + 1
},
InOut: function InOut (k) {
var s = 1.70158 * 1.525;
if ((k *= 2) < 1) {
return 0.5 * (k * k * ((s + 1) * k - s))
}
return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2)
}
},
Bounce: {
In: function In (k) {
return 1 - Easing.Bounce.Out(1 - k)
},
Out: function Out (k) {
if (k < (1 / 2.75)) {
return 7.5625 * k * k
} else if (k < (2 / 2.75)) {
return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75
} else if (k < (2.5 / 2.75)) {
return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375
} else {
return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375
}
},
InOut: function InOut (k) {
if (k < 0.5) {
return Easing.Bounce.In(k * 2) * 0.5
}
return Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5
}
}
};
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var intertween = createCommonjsModule(function (module) {
/**
* @name InterTween
* @description The lightweight, fastest, smartest, effecient value interpolator with no-dependecy, zero-configuration and relative interpolation
* @author dalisoft (https://github.com/dalisoft)
* @license MIT-License
* First Release at 20 August 2017, by @dalisoft
*/
(function (root, factory) {
if (typeof undefined === 'function' && undefined.amd) {
undefined([], factory);
} else if ('object' !== 'undefined' && module.exports) {
module.exports = factory();
} else {
root.InterTween = factory();
}
}
(typeof(window) !== 'undefined' ? window : commonjsGlobal, function () {
// RegExp variables
var colorMatch = /rgb/g;
var isIncrementReqForColor = /argb/g;
// This RegExp (numRegExp) is original from @jkroso string tweening and optimized by @dalisoft
var numRegExp =
/\s+|([A-Za-z?().,{}:""[\]#]+)|([-+/*%]+=)?([-+*/%]+)?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var hexColor = /^#([0-9a-f]{6}|[0-9a-f]{3})$/i;
var trimRegExp = /\n|\r|\t/g;
var rgbMax = 255;
// Helpers
function s2f(val) {
var floatedVal = parseFloat(val);
return typeof floatedVal === "number" && !isNaN(floatedVal) ? floatedVal : val;
}
var isArray = Array.isArray;
function h2r_f(all, hex) {
var r;
var g;
var b;
if (hex.length === 3) {
r = hex[0];
g = hex[1];
b = hex[2];
hex = r + r + g + g + b + b;
}
var color = parseInt(hex, 16);
r = color >> 16 & rgbMax;
g = color >> 8 & rgbMax;
b = color & rgbMax;
return "rgb(" + r + "," + g + "," + b + ")";
}
function trim(str) {
return typeof str === "string" ? str.replace(trimRegExp, "") : str;
}
var relativeModes = {
'+=': 1,
'-=': 1,
'*=': 2,
'/=': 3,
'%=': 4
};
function r2n(s, e) {
if (typeof e === 'number') {
return e;
} else {
var rv = relativeModes[e.substr(0, 2)],
v = e.substr(2);
if (rv === 1) {
var e2 = e[0] + v;
return s + parseFloat(e2);
} else if (rv === 2) {
return s * +v;
} else if (rv === 3) {
return s / +v;
} else if (rv === 4) {
return s * (+v / 100);
}
}
return e;
}
var h2r = function (hex) {
return typeof hex !== 'string' ? hex : trim(hex)
.replace(hexColor, h2r_f);
};
function s2n(str) {
return h2r(str).match(numRegExp).map(s2f);
}
// Splitted functions
function stringTween(s, e, d) {
d = d !== undefined ? d : 10000;
if (!numRegExp.test(e))
{ return e; }
var sv = s2n(s);
var ev = s2n(e);
var uv = unitTween(sv, ev, d);
if (uv) {
return uv;
}
uv = null;
var cm = null;
var cmls = null;
var rv = [];
for (var i = 0, len = ev.length; i < len; i++) {
var ve = ev[i],
vs = sv[i];
rv[i] = typeof ve === 'string' && ve.indexOf('=') === 1 ? e : null;
if (isIncrementReqForColor.test(ve)) {
cm = i + 2;
cmls = i + 11;
} else if (colorMatch.test(ve)) {
cm = i;
cmls = i + 9;
}
ev[i] = vs === ve ? null : rv[i] !== null ? r2n(vs, ve) : typeof ve === 'number' ? ve - vs : ve;
}
return function (t) {
var str = '';
for (var i = 0, len = ev.length; i < len; i++) {
var a = sv[i],
b = ev[i],
r = rv[i];
str += typeof b === 'number' ? cm !== null && i > cm &&
i < cmls ? (a + b * t) | 0 : (((a + b * t) * d) |
0) / d : a;
if (t === 1 && r !== null) {
sv[i] += b;
ev[i] = r2n(sv[i], r);
}
}
return str;
}
}
function tweenThemTo(sv, ev) {
var vs = [];
for (var i = 0, len = sv.length; i < len; i++) {
var s = sv[i];
vs[i] = isArray(s) ? arrayTween(s, ev) : typeof s === 'object' ? objectTween(s, ev) : typeof s === 'string' ? stringTween(s, ev) : s;
}
return function (t) {
for (var i = 0, len = vs.length; i < len; i++) {
sv[i] = vs[i](t);
}
return sv;
}
}
function parseInterpolatables(sv, ev) {
var vs = [];
for (var i = 0, len = ev.length; i < len; i++) {
var e = ev[i];
vs[i] = mainTween(i === 0 ? sv : ev[i - 1], e);
}
var lastItem = ev[ev.length - 1];
vs.push(mainTween(lastItem, lastItem));
var endLength = vs.length - 1;
return function (t) {
var totalTime = t * endLength;
var roundedTime = Math.floor(totalTime);
var elapsed = totalTime - roundedTime;
var item = vs[roundedTime];
var interpolated = item(elapsed);
return interpolated;
};
}
function arrayTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
var s = sv.slice();
var rv = [];
var minLength = Math.min(sv.length, ev.length);
for (var i = 0; i < minLength; i++) {
var vs = s[i],
ve = ev[i];
rv[i] = typeof ve === 'string' && ve.indexOf('=') === 1 ? ve : null;
s[i] = ve.nodeType ? ve : ve.update ? ve : vs === ve ? null : isArray(ve) ?
isArray(vs) && ve.length === vs.length ? arrayTween(vs, ve, d) : parseInterpolatables(vs, ve) : isArray(vs) ? tweenThemTo(vs, ve) : typeof vs === 'object' ?
objectTween(vs, ve, d) : typeof vs === 'string' ?
stringTween(vs, ve, d) : vs !== undefined ? vs : ve;
ev[i] = rv[i] !== null ? r2n(
vs, ve) : ve;
}
return function (t) {
for (var i = 0; i < minLength; i++) {
var a = s[i],
b = ev[i],
r = rv[i];
if (a === null || a === undefined)
{ continue; }
sv[i] = typeof a === 'number' ? (((a + (b - a) * t) * d) | 0) /
d : typeof a === 'function' ? a(t) : a.update ? a.update(t) : b && b.update ? b.update(t) : b;
if (r && t === 1) {
s[i] = b;
ev[i] = r2n(s[i], r);
}
}
return sv;
}
}
var units = ["px", "pt", "pc", "deg", "rad", "turn", "em", "ex", "cm", "mm", "dm", "inch", "in", "rem", "vw", "vh", "vmin", "vmax", "%"];
function unitTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
if (ev.length === 2 && sv.length === 2) {
var unidx = units.indexOf(ev[1]);
if (unidx !== -1) {
var s = +sv[0],
e = +ev[0],
u = ev[1],
r = typeof ev[0] === 'string' && ev[0].indexOf('=') === 1 ? ev[0] : null;
if (r) {
e = r2n(s, e);
}
return function (t) {
var v = ((((s + (e - s) * t) * d) | 0) / d) + u;
if (r && t === 1) {
s = e;
e = r2n(s, r);
}
return v;
}
}
}
return false;
}
function objectTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
var rv = {};
var s = {};
for (var i in sv) {
s[i] = sv[i];
var vs = s[i],
ve = ev[i];
rv[i] = typeof ve === 'string' && ve.indexOf('=') === 1 ? ve : null;
if (ve === undefined) { continue; }
s[i] = ve.nodeType || ve.update ? ve : vs === ve ? null : isArray(ve) ?
isArray(vs) && ve.length === vs.length ? arrayTween(vs, ve, d) : parseInterpolatables(vs, ve) : isArray(vs) ? tweenThemTo(vs, ve) : typeof vs === 'object' ?
objectTween(vs, ve, d) : typeof vs === 'string' ?
stringTween(vs, ve, d) : vs !== undefined ? vs : ve;
ev[i] = rv[i] !== null ? r2n(vs, ve) : ve;
}
return function (t) {
for (var i in ev) {
var a = s[i],
b = ev[i],
r = rv[i];
if (a === null || a === undefined)
{ continue; }
sv[i] = typeof a === 'number' ? (((a + (b - a) * t) * d) | 0) /
d : typeof a === 'function' ? a(t) : a.update ? a.update(t) : b.update ? b.update(t) : b;
if (r && t === 1) {
s[i] = b;
ev[i] = r2n(s[i], r);
}
}
return sv;
}
}
function mainTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
var rv = typeof(ev) === 'string' && typeof sv === 'number' && ev.indexOf('=') === 1 ? ev : null;
if (rv) {
ev = r2n(sv, rv);
}
return ev.nodeType ? ev : sv.nodeType ? sv : isArray(ev) ? isArray(sv) && sv.length === ev.length ? arrayTween(sv, ev, d) : parseInterpolatables(sv, ev) : isArray(sv) ? tweenThemTo(sv, ev) : typeof ev === 'object' ?
objectTween(sv, ev, d) : typeof ev === 'string' ? stringTween(sv, ev, d) :
typeof ev === 'function' ? ev : function (t) {
var vv = typeof ev === 'number' ? (((sv + (ev - sv) * t) *
d) | 0) / d : sv;
if (rv && t === 1) {
sv += ev;
ev = r2n(sv, rv);
}
return vv;
}
}
return mainTween;
}));
});
var Store = {};
var NodeCache = function (node, tween) {
if (!node || !node.nodeType) { return tween }
var ID = node.queueID || 'queue_' + Math.round(Math.random() * 1000 + Date.now());
if (!node.queueID) {
node.queueID = ID;
}
if (Store[ID]) {
if (tween) {
Store[ID] = Object.assign(Store[ID], tween);
}
return Store[ID]
}
Store[ID] = tween;
return Store[ID]
};
var EventClass = function EventClass () {
this._events = {};
};
EventClass.prototype.on = function on (event, callback) {
if (!this._events[event]) {
this._events[event] = [];
}
this._events[event].push(callback);
return this
};
EventClass.prototype.once = function once (event, callback) {
var this$1 = this;
if (!this._events[event]) {
this._events[event] = [];
}
var ref = this;
var _events = ref._events;
var spliceIndex = _events[event].length;
this._events[event].push(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
callback.apply(this$1, args);
_events[event].splice(spliceIndex, 1);
});
return this
};
EventClass.prototype.off = function off (event, callback) {
var ref = this;
var _events = ref._events;
if (event === undefined || !_events[event]) {
return this
}
if (callback) {
this._events[event] = this._events[event].filter(function (cb) { return cb !== callback; });
} else {
this._events[event].length = 0;
}
return this
};
EventClass.prototype.emit = function emit (event, arg1, arg2, arg3, arg4) {
var ref = this;
var _events = ref._events;
var _event = _events[event];
if (!_event || !_event.length) {
return this
}
var i = 0;
var len = _event.length;
for (; i < len; i++) {
_event[i](arg1, arg2, arg3, arg4);
}
};
// Events list
var EVENT_UPDATE = 'update';
var EVENT_COMPLETE = 'complete';
var EVENT_START = 'start';
var EVENT_REPEAT = 'repeat';
var EVENT_REVERSE = 'reverse';
var EVENT_PAUSE = 'pause';
var EVENT_PLAY = 'play';
var EVENT_RS = 'restart';
var EVENT_STOP = 'stop';
var EVENT_SEEK = 'seek';
var _id = 0; // Unique ID
var Tween = (function (EventClass$$1) {
function Tween (node, object) {
EventClass$$1.call(this);
this.id = _id++;
if (typeof node !== 'undefined' && !object && !node.nodeType) {
object = this.object = node;
node = null;
} else if (typeof node !== 'undefined') {
this.node = node;
if (typeof object === 'object') {
object = this.object = NodeCache(node, object);
} else {
this.object = object;
}
}
var isArr = this.isArr = Array.isArray(object);
this._valuesStart = isArr ? [] : {};
this._valuesEnd = null;
this._duration = 1000;
this._easingFunction = Easing.Linear.None;
this._startTime = 0;
this._delayTime = 0;
this._repeat = 0;
this._r = 0;
this._isPlaying = false;
this._yoyo = false;
this._reversed = false;
this._onStartCallbackFired = false;
this._pausedTime = null;
this._isFinite = true;
return this
}
if ( EventClass$$1 ) Tween.__proto__ = EventClass$$1;
Tween.prototype = Object.create( EventClass$$1 && EventClass$$1.prototype );
Tween.prototype.constructor = Tween;
Tween.prototype.isPlaying = function isPlaying () {
return this._isPlaying
};
Tween.prototype.isStarted = function isStarted () {
return this._onStartCallbackFired
};
Tween.prototype.reverse = function reverse () {
var ref = this;
var _reversed = ref._reversed;
this._reversed = !_reversed;
return this
};
Tween.prototype.reversed = function reversed () {
return this._reversed
};
Tween.prototype.pause = function pause () {
if (!this._isPlaying) {
return this
}
this._isPlaying = false;
remove(this);
this._pausedTime = now();
return this.emit(EVENT_PAUSE, this.object)
};
Tween.prototype.play = function play () {
if (this._isPlaying) {
return this
}
this._isPlaying = true;
this._startTime += now() - this._pausedTime;
add(this);
this._pausedTime = now();
return this.emit(EVENT_PLAY, this.object)
};
Tween.prototype.restart = function restart (noDelay) {
this._repeat = this._r;
this._startTime = now() + (noDelay ? 0 : this._delayTime);
if (!this._isPlaying) {
add(this);
}
return this.emit(EVENT_RS, this._object)
};
Tween.prototype.seek = function seek (time, keepPlaying) {
this._startTime = now() + Math.max(0, Math.min(
time, this._duration));
this.emit(EVENT_SEEK, time, this._object);
return keepPlaying ? this : this.pause()
};
Tween.prototype.duration = function duration (amount) {
this._duration = typeof (amount) === 'function' ? amount(this._duration) : amount;
return this
};
Tween.prototype.to = function to (properties, duration) {
var this$1 = this;
if ( duration === void 0 ) duration = 1000;
this._valuesEnd = properties;
if (typeof duration === 'number' || typeof (duration) === 'function') {
this._duration = typeof (duration) === 'function' ? duration(this._duration) : duration;
} else if (typeof duration === 'object') {
for (var prop in duration) {
if (this$1[prop]) {
(ref = this$1)[prop].apply(ref, (Array.isArray(duration) ? duration : [duration]));
}
}
}
return this
var ref;
};
Tween.prototype.render = function render () {
var this$1 = this;
if (this._rendered) {
return this
}
var ref = this;
var _valuesEnd = ref._valuesEnd;
var _valuesStart = ref._valuesStart;
var object = ref.object;
var Renderer = ref.Renderer;
for (var property in _valuesEnd) {
var start = object[property];
var end = _valuesEnd[property];
if (Plugins[property]) {
_valuesEnd[property] = new Plugins[property](this$1, start, end);
continue
}
if (object[property] === undefined) {
continue
}
if (typeof start === 'number' && typeof end === 'number') {
_valuesStart[property] = start;
_valuesEnd[property] = end;
} else {
_valuesEnd[property] = intertween(start, end);
}
}
if (Renderer && this.node) {
this.__render = new Renderer(this, object, _valuesEnd);
}
return this
};
Tween.prototype.start = function start (time) {
this._startTime = time !== undefined ? time : now();
this._startTime += this._delayTime;
add(this);
this._isPlaying = true;
return this
};
Tween.prototype.stop = function stop () {
var ref = this;
var _isPlaying = ref._isPlaying;
var object = ref.object;
if (!_isPlaying) {
return this
}
remove(this);
this._isPlaying = false;
return this.emit(EVENT_STOP, object)
};
Tween.prototype.end = function end () {
var ref = this;
var _startTime = ref._startTime;
var _duration = ref._duration;
return this.update(_startTime + _duration)
};
Tween.prototype.delay = function delay (amount) {
this._delayTime = typeof (amount) === 'function' ? amount(this._delayTime) : amount;
this._startTime += this._delayTime;
return this
};
Tween.prototype.repeat = function repeat (amount) {
this._repeat = typeof (amount) === 'function' ? amount(this._repeat) : amount;
this._r = this._repeat;
this._isFinite = isFinite(amount);
return this
};
Tween.prototype.repeatDelay = function repeatDelay (amount) {
this._repeatDelayTime = typeof (amount) === 'function' ? amount(this._repeatDelayTime) : amount;
return this
};
Tween.prototype.reverseDelay = function reverseDelay (amount) {
this._reverseDelayTime = typeof (amount) === 'function' ? amount(this._reverseDelayTime) : amount;
return this
};
Tween.prototype.yoyo = function yoyo (state) {
this._yoyo = typeof (state) === 'function' ? state(this._yoyo) : state;
return this
};
Tween.prototype.easing = function easing (fn) {
this._easingFunction = fn;
return this
};
Tween.prototype.reassignValues = function reassignValues () {
var ref = this;
var _valuesStart = ref._valuesStart;
var _valuesEnd = ref._valuesEnd;
var object = ref.object;
var isArr = ref.isArr;
for (var property in _valuesEnd) {
if (isArr) {
property *= 1;
}
var start = _valuesStart[property];
var end = _valuesEnd[property];
object[property] = typeof end === 'function' ? end(0) : start;
}
return this
};
Tween.prototype.get = function get$$1 (time) {
this.update(time);
return this.object
};
Tween.prototype.update = function update$$1 (time, preserve) {
var ref = this;
var _onStartCallbackFired = ref._onStartCallbackFired;
var _easingFunction = ref._easingFunction;
var _repeat = ref._repeat;
var _repeatDelayTime = ref._repeatDelayTime;
var _reverseDelayTime = ref._reverseDelayTime;
var _yoyo = ref._yoyo;
var _reversed = ref._reversed;
var _startTime = ref._startTime;
var _duration = ref._duration;
var _valuesStart = ref._valuesStart;
var _valuesEnd = ref._valuesEnd;
var object = ref.object;
var _isFinite = ref._isFinite;
var __render = ref.__render;
var elapsed;
var value;
var property;
time = time !== undefined ? time : now();
if (time < _startTime) {
return true
}
if (!_onStartCallbackFired) {
if (!this._rendered) {
this.render();
this._rendered = true;
}
this.emit(EVENT_START, object);
this._onStartCallbackFired = true;
}
elapsed = (time - _startTime) / _duration;
elapsed = elapsed > 1 ? 1 : elapsed;
elapsed = _reversed ? 1 - elapsed : elapsed;
for (property in _valuesEnd) {
value = _easingFunction[property] ? _easingFunction[property](elapsed) : _easingFunction(elapsed);
var start = _valuesStart[property];
var end = _valuesEnd[property];
if (typeof end === 'number') {
object[property] = start + (end - start) * value;
} else if (typeof end === 'function') {
object[property] = end(value);
}
}
if (__render) {
__render.update(object, elapsed);
}
this.emit(EVENT_UPDATE, object, elapsed);
if (elapsed === 1 || (_reversed && elapsed === 0)) {
if (_repeat) {
if (_isFinite) {
this._repeat--;
}
if (_yoyo) {
this._reversed = !_reversed;
}
this.emit(_yoyo && !_reversed ? EVENT_REVERSE : EVENT_REPEAT, object);
if (!_reversed && _repeatDelayTime) {
this._startTime = time + _repeatDelayTime;
} else if (_reversed && _reverseDelayTime) {
this._startTime = time + _reverseDelayTime;
} else {
this._startTime = time;
}
return true
} else {
if (!preserve) {
remove(this);
}
this.emit(EVENT_COMPLETE, object);
this._repeat = this._r;
return false
}
}
return true
};
return Tween;
}(EventClass));
var PlaybackPosition = function PlaybackPosition () {
this.totalTime = 0;
this.labels = [];
this.offsets = [];
};
PlaybackPosition.prototype.parseLabel = function parseLabel (name, offset) {
var ref = this;
var offsets = ref.offsets;
var labels = ref.labels;
var i = labels.indexOf(name);
if (typeof name === 'string' && name.indexOf('=') !== -1 && !offset && i === -1) {
var rty = name.substr(name.indexOf('=') - 1, 2);
var rt = name.split(rty);
offset = rt.length === 2 ? rty + rt[1] : null;
name = rt[0];
i = labels.indexOf(name);
}
if (i !== -1 && name) {
var currOffset = offsets[i] || 0;
if (typeof offset === 'number') {
currOffset = offset;
} else if (typeof offset === 'string') {
if (offset.indexOf('=') !== -1) {
var type = offset.charAt(0);
offset = Number(offset.substr(2));
if (type === '+' || type === '-') {
currOffset += parseFloat(type + offset);
} else if (type === '*') {
currOffset *= offset;
} else if (type === '/') {
currOffset /= offset;
} else if (type === '%') {
currOffset *= offset / 100;
}
}
}
return currOffset
}
return typeof offset === 'number' ? offset : 0
};
PlaybackPosition.prototype.addLabel = function addLabel (name, offset) {
this.labels.push(name);
this.offsets.push(this.parseLabel(name, offset));
return this
};
PlaybackPosition.prototype.setLabel = function setLabel (name, offset) {
var i = this.labels.indexOf(name);
if (i !== -1) {
this.offsets.splice(i, 1, this.parseLabel(name, offset));
}
return this
};
PlaybackPosition.prototype.eraseLabel = function eraseLabel (name) {
var i = this.labels.indexOf(name);
if (i !== -1) {
this.labels.splice(i, 1);
this.offsets.splice(i, 1);
}
return this
};
var _id$1 = 0;
var Timeline = (function (Tween$$1) {
function Timeline (params) {
Tween$$1.call(this);
this._totalDuration = 0;
this._startTime = now();
this._tweens = {};
this._elapsed = 0;
this._id = _id$1++;
this._defaultParams = params;
this.position = new PlaybackPosition();
this.position.addLabel('afterLast', this._totalDuration);
this.position.addLabel('afterInit', this._startTime);
return this
}
if ( Tween$$1 ) Timeline.__proto__ = Tween$$1;
Timeline.prototype = Object.create( Tween$$1 && Tween$$1.prototype );
Timeline.prototype.constructor = Timeline;
Timeline.prototype.addLabel = function addLabel (name, offset) {
this.position.addLabel(name, offset);
return this
};
Timeline.prototype.map = function map (fn) {
var this$1 = this;
for (var tween in this$1._tweens) {
var _tween = this$1._tweens[tween];
fn(_tween, +tween);
this$1._totalDuration = Math.max(this$1._totalDuration, _tween._duration + _tween._startTime);
}
return this
};
Timeline.prototype.add = function add$$1 (tween, position) {
var this$1 = this;
if (Array.isArray(tween)) {
tween.map(function (_tween) {
this$1.add(_tween, position);
});
return this
} else if (typeof tween === 'object' && !(tween instanceof Tween$$1)) {
tween = new Tween$$1(tween.from).to(tween.to, tween);
}
var ref = this;
var _defaultParams = ref._defaultParams;
var _totalDuration = ref._totalDuration;
if (_defaultParams) {
for (var method in _defaultParams) {
tween[method](_defaultParams[method]);
}
}
var offset = typeof position === 'number' ? position : this.position.parseLabel(typeof position !== 'undefined' ? position : 'afterLast', null);
tween._startTime = this._startTime;
tween._startTime += offset;
this._totalDuration = Math.max(_totalDuration, tween._startTime + tween._delayTime + tween._duration);
this._tweens[tween.id] = tween;
this.position.setLabel('afterLast', this._totalDuration);
return this
};
Timeline.prototype.restart = function restart () {
this._startTime += now();
add(this);
return this.emit(EVENT_RS)
};
Timeline.prototype.easing = function easing (easing$1) {
return this.map(function (tween) { return tween.easing(easing$1); })
};
Timeline.prototype.interpolation = function interpolation (interpolation$1) {
return this.map(function (tween) { return tween.interpolation(interpolation$1); })
};
Timeline.prototype.reverse = function reverse () {
this._reversed = !this._reversed;
return this.emit(EVENT_REVERSE)
};
Timeline.prototype.update = function update$$1 (time) {
var ref = this;
var _tweens = ref._tweens;
var _totalDuration = ref._totalDuration;
var _repeatDelayTime = ref._repeatDelayTime;
var _reverseDelayTime = ref._reverseDelayTime;
var _startTime = ref._startTime;
var _reversed = ref._reversed;
var _yoyo = ref._yoyo;
var _repeat = ref._repeat;
var _isFinite = ref._isFinite;
if (time < _startTime) {
return true
}
var elapsed = Math.min(1, Math.max(0, (time - _startTime) / _totalDuration));
elapsed = _reversed ? 1 - elapsed : elapsed;
this._elapsed = elapsed;
var timing = time - _startTime;
var _timing = _reversed ? _totalDuration - timing : timing;
for (var tween in _tweens) {
var _tween = _tweens[tween];
if (_tween.skip) {
_tween.skip = false;
} else if (_tween.update(_timing)) {
continue
} else {
_tween.skip = true;
}
}
this.emit(EVENT_UPDATE, elapsed, timing);
if (elapsed === 1 || (_reversed && elapsed === 0)) {
if (_repeat) {
if (_isFinite) {
this._repeat--;
}
this.emit(_reversed ? EVENT_REVERSE : EVENT_REPEAT);
if (_yoyo) {
this.reverse();
}
if (!_reversed && _repeatDelayTime) {
this._startTime += _totalDuration + _repeatDelayTime;
} else if (_reversed && _reverseDelayTime) {
this._startTime += _totalDuration + _reverseDelayTime;
} else {
this._startTime += _totalDuration;
}
for (var tween$1 in _tweens) {
var _tween$1 = _tweens[tween$1];
if (_tween$1.skip) {
_tween$1.skip = false;
}
_tween$1.reassignValues();
}
return true
} else {
this.emit(EVENT_COMPLETE);
this._repeat = this._r;
for (var tween$2 in _tweens) {
var _tween$2 = _tweens[tween$2];
if (_tween$2.skip) {
_tween$2.skip = false;
}
}
return false
}
}
return true
};
Timeline.prototype.elapsed = function elapsed (value) {
return value !== undefined ? this.update(value * this._totalDuration) : this._elapsed
};
Timeline.prototype.seek = function seek (value) {
return this.update(value < 1.1 ? value * this._totalDuration : value)
};
return Timeline;
}(Tween));
exports.Plugins = Plugins;
exports.Interpolator = intertween;
exports.has = has;
exports.get = get;
exports.getAll = getAll;
exports.removeAll = removeAll;
exports.remove = remove;
exports.add = add;
exports.now = now;
exports.update = update;
exports.autoPlay = autoPlay;
exports.isRunning = isRunning;
exports.Tween = Tween;
exports.Easing = Easing;
exports.Timeline = Timeline;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=Tween.js.map
| sufuf3/cdnjs | ajax/libs/es6-tween/3.5.3/Tween.js | JavaScript | mit | 38,424 |
from . import cli
__all__ = ['cli']
| danking/hail | hail/python/hailtop/hailctl/dev/query/__init__.py | Python | mit | 37 |
// 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.
// ---------------------------------------------------------------------------
// SString.cpp
//
// ---------------------------------------------------------------------------
#include "stdafx.h"
#include "sstring.h"
#include "ex.h"
#include "holder.h"
#if defined(_MSC_VER)
#pragma inline_depth (25)
#endif
//-----------------------------------------------------------------------------
// Static variables
//-----------------------------------------------------------------------------
// Have one internal, well-known, literal for the empty string.
const BYTE SString::s_EmptyBuffer[2] = { 0 };
// @todo: these need to be initialized by calling GetACP()
UINT SString::s_ACP = 0;
#ifndef DACCESS_COMPILE
static BYTE s_EmptySpace[sizeof(SString)] = { 0 };
#endif // DACCESS_COMPILE
SPTR_IMPL(SString,SString,s_Empty);
void SString::Startup()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
if (s_ACP == 0)
{
UINT ACP = GetACP();
#ifndef DACCESS_COMPILE
s_Empty = PTR_SString(new (s_EmptySpace) SString());
s_Empty->SetNormalized();
#endif // DACCESS_COMPILE
MemoryBarrier();
s_ACP = ACP;
}
}
CHECK SString::CheckStartup()
{
WRAPPER_NO_CONTRACT;
CHECK(s_Empty != NULL);
CHECK_OK;
}
//-----------------------------------------------------------------------------
// Case insensitive helpers.
//-----------------------------------------------------------------------------
static WCHAR MapChar(WCHAR wc, DWORD dwFlags)
{
WRAPPER_NO_CONTRACT;
WCHAR wTmp;
#ifndef FEATURE_PAL
int iRet = ::LCMapStringEx(LOCALE_NAME_INVARIANT, dwFlags, &wc, 1, &wTmp, 1, NULL, NULL, 0);
if (!iRet) {
// This can fail in non-exceptional cases becauseof unknown unicode characters.
wTmp = wc;
}
#else // !FEATURE_PAL
// For PAL, no locale specific processing is done
if (dwFlags == LCMAP_UPPERCASE)
{
wTmp =
#ifdef SELF_NO_HOST
toupper(wc);
#else
PAL_ToUpperInvariant(wc);
#endif
}
else
{
_ASSERTE(dwFlags == LCMAP_LOWERCASE);
wTmp =
#ifdef SELF_NO_HOST
tolower(wc);
#else
PAL_ToLowerInvariant(wc);
#endif
}
#endif // !FEATURE_PAL
return wTmp;
}
#define IS_UPPER_A_TO_Z(x) (((x) >= W('A')) && ((x) <= W('Z')))
#define IS_LOWER_A_TO_Z(x) (((x) >= W('a')) && ((x) <= W('z')))
#define CAN_SIMPLE_UPCASE(x) (((x)&~0x7f) == 0)
#define CAN_SIMPLE_DOWNCASE(x) (((x)&~0x7f) == 0)
#define SIMPLE_UPCASE(x) (IS_LOWER_A_TO_Z(x) ? ((x) - W('a') + W('A')) : (x))
#define SIMPLE_DOWNCASE(x) (IS_UPPER_A_TO_Z(x) ? ((x) - W('A') + W('a')) : (x))
/* static */
int SString::CaseCompareHelper(const WCHAR *buffer1, const WCHAR *buffer2, COUNT_T count, BOOL stopOnNull, BOOL stopOnCount)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(stopOnNull || stopOnCount);
const WCHAR *buffer1End = buffer1 + count;
int diff = 0;
while (!stopOnCount || (buffer1 < buffer1End))
{
WCHAR ch1 = *buffer1++;
WCHAR ch2 = *buffer2++;
diff = ch1 - ch2;
if ((ch1 == 0) || (ch2 == 0))
{
if (diff != 0 || stopOnNull)
{
break;
}
}
else
{
if (diff != 0)
{
diff = ((CAN_SIMPLE_UPCASE(ch1) ? SIMPLE_UPCASE(ch1) : MapChar(ch1, LCMAP_UPPERCASE))
- (CAN_SIMPLE_UPCASE(ch2) ? SIMPLE_UPCASE(ch2) : MapChar(ch2, LCMAP_UPPERCASE)));
}
if (diff != 0)
{
break;
}
}
}
return diff;
}
#define IS_LOWER_A_TO_Z_ANSI(x) (((x) >= 'a') && ((x) <= 'z'))
#define CAN_SIMPLE_UPCASE_ANSI(x) (((x) >= 0x20) && ((x) <= 0x7f))
#define SIMPLE_UPCASE_ANSI(x) (IS_LOWER_A_TO_Z(x) ? ((x) - 'a' + 'A') : (x))
int GetCaseInsensitiveValueA(const CHAR *buffer, int length) {
LIMITED_METHOD_CONTRACT;
_ASSERTE(buffer != NULL);
_ASSERTE(length == 1 || ((length == 2) && IsDBCSLeadByte(*buffer)));
WCHAR wideCh;
int sortValue;
int conversionReturn = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, buffer, length, &wideCh, 1);
if (conversionReturn == 0)
{
// An invalid sequence should only compare equal to itself, so use a negative mapping.
if (length == 1)
{
sortValue = -((int)((unsigned char)(*buffer)));
}
else
{
sortValue = -(((((int)((unsigned char)(*buffer))) << 8) | ((int)((unsigned char)(*(buffer + 1))))));
}
}
else
{
_ASSERTE(conversionReturn == 1);
sortValue = MapChar(wideCh, LCMAP_UPPERCASE);
}
return sortValue;
}
/* static */
int SString::CaseCompareHelperA(const CHAR *buffer1, const CHAR *buffer2, COUNT_T count, BOOL stopOnNull, BOOL stopOnCount)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(stopOnNull || stopOnCount);
const CHAR *buffer1End = buffer1 + count;
int diff = 0;
while (!stopOnCount || (buffer1 < buffer1End))
{
CHAR ch1 = *buffer1;
CHAR ch2 = *buffer2;
if ((ch1 == 0) || (ch2 == 0))
{
diff = ch1 - ch2;
if (diff != 0 || stopOnNull)
{
break;
}
buffer1++;
buffer2++;
}
else if (CAN_SIMPLE_UPCASE_ANSI(ch1) && CAN_SIMPLE_UPCASE_ANSI(ch2))
{
diff = ch1 - ch2;
if (diff != 0)
{
diff = (SIMPLE_UPCASE_ANSI(ch1) - SIMPLE_UPCASE_ANSI(ch2));
if (diff != 0)
{
break;
}
}
buffer1++;
buffer2++;
}
else
{
int length = 1;
if (IsDBCSLeadByte(ch1)
&& IsDBCSLeadByte(ch2)
&& (!stopOnCount || ((buffer1 + 1) < buffer1End)))
{
length = 2;
}
int sortValue1 = GetCaseInsensitiveValueA(buffer1, length);
int sortValue2 = GetCaseInsensitiveValueA(buffer2, length);
diff = sortValue1 - sortValue2;
if (diff != 0)
{
break;
}
buffer1 += length;
buffer2 += length;
}
}
return diff;
}
int CaseHashHelper(const WCHAR *buffer, COUNT_T count)
{
LIMITED_METHOD_CONTRACT;
const WCHAR *bufferEnd = buffer + count;
ULONG hash = 5381;
while (buffer < bufferEnd)
{
WCHAR ch = *buffer++;
ch = CAN_SIMPLE_UPCASE(ch) ? SIMPLE_UPCASE(ch) : MapChar(ch, LCMAP_UPPERCASE);
hash = (((hash << 5) + hash) ^ ch);
}
return hash;
}
static int CaseHashHelperA(const CHAR *buffer, COUNT_T count)
{
LIMITED_METHOD_CONTRACT;
const CHAR *bufferEnd = buffer + count;
ULONG hash = 5381;
while (buffer < bufferEnd)
{
CHAR ch = *buffer++;
ch = SIMPLE_UPCASE_ANSI(ch);
hash = (((hash << 5) + hash) ^ ch);
}
return hash;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the unicode string
//-----------------------------------------------------------------------------
void SString::Set(const WCHAR *string)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
if (string == NULL || *string == 0)
Clear();
else
{
Resize((COUNT_T) wcslen(string), REPRESENTATION_UNICODE);
wcscpy_s(GetRawUnicode(), GetBufferSizeInCharIncludeNullChar(), string);
}
RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the first count characters of the given
// unicode string.
//-----------------------------------------------------------------------------
void SString::Set(const WCHAR *string, COUNT_T count)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
PRECONDITION(CheckCount(count));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (count == 0)
Clear();
else
{
Resize(count, REPRESENTATION_UNICODE);
wcsncpy_s(GetRawUnicode(), GetBufferSizeInCharIncludeNullChar(), string, count);
GetRawUnicode()[count] = 0;
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a point to the first count characters of the given
// preallocated unicode string (shallow copy).
//-----------------------------------------------------------------------------
void SString::SetPreallocated(const WCHAR *string, COUNT_T count)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
PRECONDITION(CheckCount(count));
SS_POSTCONDITION(IsEmpty());
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC_HOST_ONLY;
}
SS_CONTRACT_END;
SetImmutable();
SetImmutable((BYTE*) string, count*2);
ClearAllocated();
SetRepresentation(REPRESENTATION_UNICODE);
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the given ansi string
//-----------------------------------------------------------------------------
void SString::SetASCII(const ASCII *string)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
PRECONDITION(CheckASCIIString(string));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (string == NULL || *string == 0)
Clear();
else
{
Resize((COUNT_T) strlen(string), REPRESENTATION_ASCII);
strcpy_s(GetRawUTF8(), GetBufferSizeInCharIncludeNullChar(), string);
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the first count characters of the given
// ascii string
//-----------------------------------------------------------------------------
void SString::SetASCII(const ASCII *string, COUNT_T count)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
PRECONDITION(CheckASCIIString(string, count));
PRECONDITION(CheckCount(count));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (count == 0)
Clear();
else
{
Resize(count, REPRESENTATION_ASCII);
strncpy_s(GetRawASCII(), GetBufferSizeInCharIncludeNullChar(), string, count);
GetRawASCII()[count] = 0;
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the given UTF8 string
//-----------------------------------------------------------------------------
void SString::SetUTF8(const UTF8 *string)
{
SS_CONTRACT_VOID
{
// !!! Check for illegal UTF8 encoding?
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
SS_CONTRACT_END;
if (string == NULL || *string == 0)
Clear();
else
{
Resize((COUNT_T) strlen(string), REPRESENTATION_UTF8);
strcpy_s(GetRawUTF8(), GetBufferSizeInCharIncludeNullChar(), string);
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the first count characters of the given
// UTF8 string.
//-----------------------------------------------------------------------------
void SString::SetUTF8(const UTF8 *string, COUNT_T count)
{
SS_CONTRACT_VOID
{
// !!! Check for illegal UTF8 encoding?
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
PRECONDITION(CheckCount(count));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (count == 0)
Clear();
else
{
Resize(count, REPRESENTATION_UTF8);
strncpy_s(GetRawUTF8(), GetBufferSizeInCharIncludeNullChar(), string, count);
GetRawUTF8()[count] = 0;
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the given ANSI string
//-----------------------------------------------------------------------------
void SString::SetANSI(const ANSI *string)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (string == NULL || *string == 0)
Clear();
else
{
Resize((COUNT_T) strlen(string), REPRESENTATION_ANSI);
strcpy_s(GetRawANSI(), GetBufferSizeInCharIncludeNullChar(), string);
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to a copy of the first count characters of the given
// ANSI string.
//-----------------------------------------------------------------------------
void SString::SetANSI(const ANSI *string, COUNT_T count)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(string, NULL_OK));
PRECONDITION(CheckCount(count));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (count == 0)
Clear();
else
{
Resize(count, REPRESENTATION_ANSI);
strncpy_s(GetRawANSI(), GetBufferSizeInCharIncludeNullChar(), string, count);
GetRawANSI()[count] = 0;
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to the given unicode character
//-----------------------------------------------------------------------------
void SString::Set(WCHAR character)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
SS_CONTRACT_END;
if (character == 0)
Clear();
else
{
Resize(1, REPRESENTATION_UNICODE);
GetRawUnicode()[0] = character;
GetRawUnicode()[1] = 0;
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to the given UTF8 character
//-----------------------------------------------------------------------------
void SString::SetUTF8(CHAR character)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (character == 0)
Clear();
else
{
Resize(1, REPRESENTATION_UTF8);
GetRawUTF8()[0] = character;
GetRawUTF8()[1] = 0;
}
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to the given ansi literal.
// This will share the memory and not make a copy.
//-----------------------------------------------------------------------------
void SString::SetLiteral(const ASCII *literal)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(literal));
PRECONDITION(CheckASCIIString(literal));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
SString s(Literal, literal);
Set(s);
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Set this string to the given unicode literal.
// This will share the memory and not make a copy.
//-----------------------------------------------------------------------------
void SString::SetLiteral(const WCHAR *literal)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(literal));
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
SString s(Literal, literal);
Set(s);
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Hash the string contents
//-----------------------------------------------------------------------------
ULONG SString::Hash() const
{
SS_CONTRACT(ULONG)
{
INSTANCE_CHECK;
THROWS_UNLESS_NORMALIZED;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
ConvertToUnicode();
SS_RETURN HashString(GetRawUnicode());
}
//-----------------------------------------------------------------------------
// Hash the string contents
//-----------------------------------------------------------------------------
ULONG SString::HashCaseInsensitive() const
{
SS_CONTRACT(ULONG)
{
INSTANCE_CHECK;
THROWS_UNLESS_NORMALIZED;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
ConvertToIteratable();
ULONG result;
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
case REPRESENTATION_EMPTY:
result = CaseHashHelper(GetRawUnicode(), GetRawCount());
break;
case REPRESENTATION_ASCII:
result = CaseHashHelperA(GetRawASCII(), GetRawCount());
break;
default:
UNREACHABLE();
}
SS_RETURN result;
}
//-----------------------------------------------------------------------------
// Truncate this string to count characters.
//-----------------------------------------------------------------------------
void SString::Truncate(const Iterator &i)
{
SS_CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
SS_POSTCONDITION(GetRawCount() == i - Begin());
THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
SS_CONTRACT_END;
CONSISTENCY_CHECK(IsFixedSize());
COUNT_T size = i - Begin();
Resize(size, GetRepresentation(), PRESERVE);
i.Resync(this, (BYTE *) (GetRawUnicode() + size));
SS_RETURN;
}
//-----------------------------------------------------------------------------
// Convert the ASCII representation for this String to Unicode. We can do this
// quickly and in-place (if this == &dest), which is why it is optimized.
//-----------------------------------------------------------------------------
void SString::ConvertASCIIToUnicode(SString &dest) const
{
CONTRACT_VOID
{
PRECONDITION(IsRepresentation(REPRESENTATION_ASCII));
POSTCONDITION(dest.IsRepresentation(REPRESENTATION_UNICODE));
THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
// Handle the empty case.
if (IsEmpty())
{
dest.Clear();
RETURN;
}
CONSISTENCY_CHECK(CheckPointer(GetRawASCII()));
CONSISTENCY_CHECK(GetRawCount() > 0);
// If dest is the same as this, then we need to preserve on resize.
dest.Resize(GetRawCount(), REPRESENTATION_UNICODE,
this == &dest ? PRESERVE : DONT_PRESERVE);
// Make sure the buffer is big enough.
CONSISTENCY_CHECK(dest.GetAllocation() > (GetRawCount() * sizeof(WCHAR)));
// This is a poor man's widen. Since we know that the representation is ASCII,
// we can just pad the string with a bunch of zero-value bytes. Of course,
// we move from the end of the string to the start so that we can convert in
// place (in the case that &dest == this).
WCHAR *outBuf = dest.GetRawUnicode() + dest.GetRawCount();
ASCII *inBuf = GetRawASCII() + GetRawCount();
while (GetRawASCII() <= inBuf)
{
CONSISTENCY_CHECK(dest.GetRawUnicode() <= outBuf);
// The casting zero-extends the value, thus giving us the zero-valued byte.
*outBuf = (WCHAR) *inBuf;
outBuf--;
inBuf--;
}
RETURN;
}
//-----------------------------------------------------------------------------
// Convert the internal representation for this String to Unicode.
//-----------------------------------------------------------------------------
void SString::ConvertToUnicode() const
{
CONTRACT_VOID
{
POSTCONDITION(IsRepresentation(REPRESENTATION_UNICODE));
if (IsRepresentation(REPRESENTATION_UNICODE)) NOTHROW; else THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
if (!IsRepresentation(REPRESENTATION_UNICODE))
{
if (IsRepresentation(REPRESENTATION_ASCII))
{
ConvertASCIIToUnicode(*(const_cast<SString *>(this)));
}
else
{
StackSString s;
ConvertToUnicode(s);
PREFIX_ASSUME(!s.IsImmutable());
(const_cast<SString*>(this))->Set(s);
}
}
RETURN;
}
//-----------------------------------------------------------------------------
// Convert the internal representation for this String to Unicode, while
// preserving the iterator if the conversion is done.
//-----------------------------------------------------------------------------
void SString::ConvertToUnicode(const CIterator &i) const
{
CONTRACT_VOID
{
PRECONDITION(i.Check());
POSTCONDITION(IsRepresentation(REPRESENTATION_UNICODE));
if (IsRepresentation(REPRESENTATION_UNICODE)) NOTHROW; else THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
if (!IsRepresentation(REPRESENTATION_UNICODE))
{
CONSISTENCY_CHECK(IsFixedSize());
COUNT_T index = 0;
// Get the current index of the iterator
if (i.m_ptr != NULL)
{
CONSISTENCY_CHECK(GetCharacterSizeShift() == 0);
index = (COUNT_T) (i.m_ptr - m_buffer);
}
if (IsRepresentation(REPRESENTATION_ASCII))
{
ConvertASCIIToUnicode(*(const_cast<SString *>(this)));
}
else
{
StackSString s;
ConvertToUnicode(s);
(const_cast<SString*>(this))->Set(s);
}
// Move the iterator to the new location.
if (i.m_ptr != NULL)
{
i.Resync(this, (BYTE *) (GetRawUnicode() + index));
}
}
RETURN;
}
//-----------------------------------------------------------------------------
// Set s to be a copy of this string's contents, but in the unicode format.
//-----------------------------------------------------------------------------
void SString::ConvertToUnicode(SString &s) const
{
CONTRACT_VOID
{
PRECONDITION(s.Check());
POSTCONDITION(s.IsRepresentation(REPRESENTATION_UNICODE));
THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
int page = 0;
switch (GetRepresentation())
{
case REPRESENTATION_EMPTY:
s.Clear();
RETURN;
case REPRESENTATION_UNICODE:
s.Set(*this);
RETURN;
case REPRESENTATION_UTF8:
page = CP_UTF8;
break;
case REPRESENTATION_ASCII:
ConvertASCIIToUnicode(s);
RETURN;
case REPRESENTATION_ANSI:
page = CP_ACP;
break;
default:
UNREACHABLE();
}
COUNT_T length = WszMultiByteToWideChar(page, 0, GetRawANSI(), GetRawCount()+1, 0, 0);
if (length == 0)
ThrowLastError();
s.Resize(length-1, REPRESENTATION_UNICODE);
length = WszMultiByteToWideChar(page, 0, GetRawANSI(), GetRawCount()+1, s.GetRawUnicode(), length);
if (length == 0)
ThrowLastError();
RETURN;
}
//-----------------------------------------------------------------------------
// Set s to be a copy of this string's contents, but in the ANSI format.
//-----------------------------------------------------------------------------
void SString::ConvertToANSI(SString &s) const
{
CONTRACT_VOID
{
PRECONDITION(s.Check());
POSTCONDITION(s.IsRepresentation(REPRESENTATION_ANSI));
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
switch (GetRepresentation())
{
case REPRESENTATION_EMPTY:
s.Clear();
RETURN;
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
s.Set(*this);
RETURN;
case REPRESENTATION_UTF8:
// No direct conversion to ANSI
ConvertToUnicode();
// fall through
case REPRESENTATION_UNICODE:
break;
default:
UNREACHABLE();
}
// @todo: use WC_NO_BEST_FIT_CHARS
COUNT_T length = WszWideCharToMultiByte(CP_ACP, 0, GetRawUnicode(), GetRawCount()+1,
NULL, 0, NULL, NULL);
s.Resize(length-1, REPRESENTATION_ANSI);
// @todo: use WC_NO_BEST_FIT_CHARS
length = WszWideCharToMultiByte(CP_ACP, 0, GetRawUnicode(), GetRawCount()+1,
s.GetRawANSI(), length, NULL, NULL);
if (length == 0)
ThrowLastError();
RETURN;
}
//-----------------------------------------------------------------------------
// Set s to be a copy of this string's contents, but in the utf8 format.
//-----------------------------------------------------------------------------
COUNT_T SString::ConvertToUTF8(SString &s) const
{
CONTRACT(COUNT_T)
{
PRECONDITION(s.Check());
POSTCONDITION(s.IsRepresentation(REPRESENTATION_UTF8));
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
switch (GetRepresentation())
{
case REPRESENTATION_EMPTY:
s.Clear();
RETURN 1;
case REPRESENTATION_ASCII:
case REPRESENTATION_UTF8:
s.Set(*this);
RETURN s.GetRawCount()+1;
case REPRESENTATION_ANSI:
// No direct conversion from ANSI to UTF8
ConvertToUnicode();
// fall through
case REPRESENTATION_UNICODE:
break;
default:
UNREACHABLE();
}
// <TODO> @todo: use WC_NO_BEST_FIT_CHARS </TODO>
bool allAscii;
DWORD length;
HRESULT hr = FString::Unicode_Utf8_Length(GetRawUnicode(), & allAscii, & length);
if (SUCCEEDED(hr))
{
s.Resize(length, REPRESENTATION_UTF8);
//FString::Unicode_Utf8 expects an array all the time
//we optimize the empty string by replacing it with null for SString above in Resize
if (length > 0)
{
hr = FString::Unicode_Utf8(GetRawUnicode(), allAscii, (LPSTR) s.GetRawUTF8(), length);
}
}
IfFailThrow(hr);
RETURN length + 1;
}
//-----------------------------------------------------------------------------
// Replace a single character with another character.
//-----------------------------------------------------------------------------
void SString::Replace(const Iterator &i, WCHAR c)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i, 1));
POSTCONDITION(Match(i, c));
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
if (IsRepresentation(REPRESENTATION_ASCII) && ((c&~0x7f) == 0))
{
*(BYTE*)i.m_ptr = (BYTE) c;
}
else
{
ConvertToUnicode(i);
*(USHORT*)i.m_ptr = c;
}
RETURN;
}
//-----------------------------------------------------------------------------
// Replace the substring specified by position, length with the given string s.
//-----------------------------------------------------------------------------
void SString::Replace(const Iterator &i, COUNT_T length, const SString &s)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i, length));
PRECONDITION(s.Check());
POSTCONDITION(Match(i, s));
THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
Representation representation = GetRepresentation();
if (representation == REPRESENTATION_EMPTY)
{
// This special case contains some optimizations (like literal sharing).
Set(s);
ConvertToIteratable();
i.Resync(this, m_buffer);
}
else
{
StackSString temp;
const SString &source = GetCompatibleString(s, temp, i);
COUNT_T deleteSize = length<<GetCharacterSizeShift();
COUNT_T insertSize = source.GetRawCount()<<source.GetCharacterSizeShift();
SBuffer::Replace(i, deleteSize, insertSize);
SBuffer::Copy(i, source.m_buffer, insertSize);
}
RETURN;
}
//-----------------------------------------------------------------------------
// Find s in this string starting at i. Return TRUE & update iterator if found.
//-----------------------------------------------------------------------------
BOOL SString::Find(CIterator &i, const SString &s) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
PRECONDITION(s.Check());
POSTCONDITION(RETVAL == Match(i, s));
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
}
CONTRACT_END;
// Get a compatible string from s
StackSString temp;
const SString &source = GetCompatibleString(s, temp, i);
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
{
COUNT_T count = source.GetRawCount();
const WCHAR *start = i.GetUnicode();
const WCHAR *end = GetUnicode() + GetRawCount() - count;
while (start <= end)
{
if (wcsncmp(start, source.GetRawUnicode(), count) == 0)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start++;
}
}
break;
case REPRESENTATION_ANSI:
case REPRESENTATION_ASCII:
{
COUNT_T count = source.GetRawCount();
const CHAR *start = i.GetASCII();
const CHAR *end = GetRawASCII() + GetRawCount() - count;
while (start <= end)
{
if (strncmp(start, source.GetRawASCII(), count) == 0)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start++;
}
}
break;
case REPRESENTATION_EMPTY:
{
if (source.GetRawCount() == 0)
RETURN TRUE;
}
break;
case REPRESENTATION_UTF8:
default:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Find s in this string starting at i. Return TRUE & update iterator if found.
//-----------------------------------------------------------------------------
BOOL SString::Find(CIterator &i, WCHAR c) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
POSTCONDITION(RETVAL == Match(i, c));
THROWS_UNLESS_NORMALIZED;
GC_NOTRIGGER;
}
CONTRACT_END;
// Get a compatible string
if (c & ~0x7f)
ConvertToUnicode(i);
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
{
const WCHAR *start = i.GetUnicode();
const WCHAR *end = GetUnicode() + GetRawCount() - 1;
while (start <= end)
{
if (*start == c)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start++;
}
}
break;
case REPRESENTATION_ANSI:
case REPRESENTATION_ASCII:
{
const CHAR *start = i.GetASCII();
const CHAR *end = GetRawASCII() + GetRawCount() - 1;
while (start <= end)
{
if (*start == c)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start++;
}
}
break;
case REPRESENTATION_EMPTY:
break;
case REPRESENTATION_UTF8:
default:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Find s in this string, working backwards staring at i.
// Return TRUE and update iterator if found.
//-----------------------------------------------------------------------------
BOOL SString::FindBack(CIterator &i, const SString &s) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
PRECONDITION(s.Check());
POSTCONDITION(RETVAL == Match(i, s));
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
}
CONTRACT_END;
// Get a compatible string from s
StackSString temp;
const SString &source = GetCompatibleString(s, temp, i);
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
{
COUNT_T count = source.GetRawCount();
const WCHAR *start = GetRawUnicode() + GetRawCount() - count;
if (start > i.GetUnicode())
start = i.GetUnicode();
const WCHAR *end = GetRawUnicode();
while (start >= end)
{
if (wcsncmp(start, source.GetRawUnicode(), count) == 0)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start--;
}
}
break;
case REPRESENTATION_ANSI:
case REPRESENTATION_ASCII:
{
COUNT_T count = source.GetRawCount();
const CHAR *start = GetRawASCII() + GetRawCount() - count;
if (start > i.GetASCII())
start = i.GetASCII();
const CHAR *end = GetRawASCII();
while (start >= end)
{
if (strncmp(start, source.GetRawASCII(), count) == 0)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start--;
}
}
break;
case REPRESENTATION_EMPTY:
{
if (source.GetRawCount() == 0)
RETURN TRUE;
}
break;
case REPRESENTATION_UTF8:
default:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Find s in this string, working backwards staring at i.
// Return TRUE and update iterator if found.
//-----------------------------------------------------------------------------
BOOL SString::FindBack(CIterator &i, WCHAR c) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
POSTCONDITION(RETVAL == Match(i, c));
THROWS_UNLESS_NORMALIZED;
GC_NOTRIGGER;
}
CONTRACT_END;
// Get a compatible string from s
if (c & ~0x7f)
ConvertToUnicode(i);
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
{
const WCHAR *start = GetRawUnicode() + GetRawCount() - 1;
if (start > i.GetUnicode())
start = i.GetUnicode();
const WCHAR *end = GetRawUnicode();
while (start >= end)
{
if (*start == c)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start--;
}
}
break;
case REPRESENTATION_ANSI:
case REPRESENTATION_ASCII:
{
const CHAR *start = GetRawASCII() + GetRawCount() - 1;
if (start > i.GetASCII())
start = i.GetASCII();
const CHAR *end = GetRawASCII();
while (start >= end)
{
if (*start == c)
{
i.Resync(this, (BYTE*) start);
RETURN TRUE;
}
start--;
}
}
break;
case REPRESENTATION_EMPTY:
break;
case REPRESENTATION_UTF8:
default:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Returns TRUE if this string begins with the contents of s
//-----------------------------------------------------------------------------
BOOL SString::BeginsWith(const SString &s) const
{
WRAPPER_NO_CONTRACT;
return Match(Begin(), s);
}
//-----------------------------------------------------------------------------
// Returns TRUE if this string begins with the contents of s
//-----------------------------------------------------------------------------
BOOL SString::BeginsWithCaseInsensitive(const SString &s) const
{
WRAPPER_NO_CONTRACT;
return MatchCaseInsensitive(Begin(), s);
}
//-----------------------------------------------------------------------------
// Returns TRUE if this string ends with the contents of s
//-----------------------------------------------------------------------------
BOOL SString::EndsWith(const SString &s) const
{
WRAPPER_NO_CONTRACT;
// Need this check due to iterator arithmetic below.
if (GetCount() < s.GetCount())
{
return FALSE;
}
return Match(End() - s.GetCount(), s);
}
//-----------------------------------------------------------------------------
// Returns TRUE if this string ends with the contents of s
//-----------------------------------------------------------------------------
BOOL SString::EndsWithCaseInsensitive(const SString &s) const
{
WRAPPER_NO_CONTRACT;
// Need this check due to iterator arithmetic below.
if (GetCount() < s.GetCount())
{
return FALSE;
}
return MatchCaseInsensitive(End() - s.GetCount(), s);
}
//-----------------------------------------------------------------------------
// Compare this string's contents to s's contents.
// The comparison does not take into account localization issues like case folding.
// Return 0 if equal, <0 if this < s, >0 is this > s. (same as strcmp).
//-----------------------------------------------------------------------------
int SString::Compare(const SString &s) const
{
CONTRACT(int)
{
INSTANCE_CHECK;
PRECONDITION(s.Check());
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
}
CONTRACT_END;
StackSString temp;
const SString &source = GetCompatibleString(s, temp);
COUNT_T smaller;
int equals = 0;
int result = 0;
if (GetRawCount() < source.GetRawCount())
{
smaller = GetRawCount();
equals = -1;
}
else if (GetRawCount() > source.GetRawCount())
{
smaller = source.GetRawCount();
equals = 1;
}
else
{
smaller = GetRawCount();
equals = 0;
}
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
result = wcsncmp(GetRawUnicode(), source.GetRawUnicode(), smaller);
break;
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
result = strncmp(GetRawASCII(), source.GetRawASCII(), smaller);
break;
case REPRESENTATION_EMPTY:
result = 0;
break;
default:
case REPRESENTATION_UTF8:
UNREACHABLE();
}
if (result == 0)
RETURN equals;
else
RETURN result;
}
//-----------------------------------------------------------------------------
// Compare this string's contents to s's contents.
// Return 0 if equal, <0 if this < s, >0 is this > s. (same as strcmp).
//-----------------------------------------------------------------------------
int SString::CompareCaseInsensitive(const SString &s) const
{
CONTRACT(int)
{
INSTANCE_CHECK;
PRECONDITION(s.Check());
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
}
CONTRACT_END;
StackSString temp;
const SString &source = GetCompatibleString(s, temp);
COUNT_T smaller;
int equals = 0;
int result = 0;
if (GetRawCount() < source.GetRawCount())
{
smaller = GetRawCount();
equals = -1;
}
else if (GetRawCount() > source.GetRawCount())
{
smaller = source.GetRawCount();
equals = 1;
}
else
{
smaller = GetRawCount();
equals = 0;
}
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
result = CaseCompareHelper(GetRawUnicode(), source.GetRawUnicode(), smaller, FALSE, TRUE);
break;
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
result = CaseCompareHelperA(GetRawASCII(), source.GetRawASCII(), smaller, FALSE, TRUE);
break;
case REPRESENTATION_EMPTY:
result = 0;
break;
default:
case REPRESENTATION_UTF8:
UNREACHABLE();
}
if (result == 0)
RETURN equals;
else
RETURN result;
}
//-----------------------------------------------------------------------------
// Compare this string's contents to s's contents.
// The comparison does not take into account localization issues like case folding.
// Return 1 if equal, 0 if not.
//-----------------------------------------------------------------------------
BOOL SString::Equals(const SString &s) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(s.Check());
THROWS_UNLESS_BOTH_NORMALIZED(s);
FAULTS_UNLESS_BOTH_NORMALIZED(s, ThrowOutOfMemory());
GC_NOTRIGGER;
}
CONTRACT_END;
StackSString temp;
const SString &source = GetCompatibleString(s, temp);
COUNT_T count = GetRawCount();
if (count != source.GetRawCount())
RETURN FALSE;
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
RETURN (wcsncmp(GetRawUnicode(), source.GetRawUnicode(), count) == 0);
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
RETURN (strncmp(GetRawASCII(), source.GetRawASCII(), count) == 0);
case REPRESENTATION_EMPTY:
RETURN TRUE;
default:
case REPRESENTATION_UTF8:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Compare this string's contents case insensitively to s's contents.
// Return 1 if equal, 0 if not.
//-----------------------------------------------------------------------------
BOOL SString::EqualsCaseInsensitive(const SString &s) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(s.Check());
THROWS_UNLESS_BOTH_NORMALIZED(s);
FAULTS_UNLESS_BOTH_NORMALIZED(s, ThrowOutOfMemory());
GC_NOTRIGGER;
}
CONTRACT_END;
StackSString temp;
const SString &source = GetCompatibleString(s, temp);
COUNT_T count = GetRawCount();
if (count != source.GetRawCount())
RETURN FALSE;
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
RETURN (CaseCompareHelper(GetRawUnicode(), source.GetRawUnicode(), count, FALSE, TRUE) == 0);
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
RETURN (CaseCompareHelperA(GetRawASCII(), source.GetRawASCII(), count, FALSE, TRUE) == 0);
case REPRESENTATION_EMPTY:
RETURN TRUE;
default:
case REPRESENTATION_UTF8:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Compare s's contents to the substring starting at position
// The comparison does not take into account localization issues like case folding.
// Return TRUE if equal, FALSE if not
//-----------------------------------------------------------------------------
BOOL SString::Match(const CIterator &i, const SString &s) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
PRECONDITION(s.Check());
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
}
CONTRACT_END;
StackSString temp;
const SString &source = GetCompatibleString(s, temp, i);
COUNT_T remaining = End() - i;
COUNT_T count = source.GetRawCount();
if (remaining < count)
RETURN FALSE;
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
RETURN (wcsncmp(i.GetUnicode(), source.GetRawUnicode(), count) == 0);
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
RETURN (strncmp(i.GetASCII(), source.GetRawASCII(), count) == 0);
case REPRESENTATION_EMPTY:
RETURN TRUE;
default:
case REPRESENTATION_UTF8:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Compare s's contents case insensitively to the substring starting at position
// Return TRUE if equal, FALSE if not
//-----------------------------------------------------------------------------
BOOL SString::MatchCaseInsensitive(const CIterator &i, const SString &s) const
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
PRECONDITION(s.Check());
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
}
CONTRACT_END;
StackSString temp;
const SString &source = GetCompatibleString(s, temp, i);
COUNT_T remaining = End() - i;
COUNT_T count = source.GetRawCount();
if (remaining < count)
RETURN FALSE;
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
case REPRESENTATION_ANSI:
RETURN (CaseCompareHelper(i.GetUnicode(), source.GetRawUnicode(), count, FALSE, TRUE) == 0);
case REPRESENTATION_ASCII:
RETURN (CaseCompareHelperA(i.GetASCII(), source.GetRawASCII(), count, FALSE, TRUE) == 0);
case REPRESENTATION_EMPTY:
RETURN TRUE;
default:
case REPRESENTATION_UTF8:
UNREACHABLE();
}
RETURN FALSE;
}
//-----------------------------------------------------------------------------
// Compare c case insensitively to the character at position
// Return TRUE if equal, FALSE if not
//-----------------------------------------------------------------------------
BOOL SString::MatchCaseInsensitive(const CIterator &i, WCHAR c) const
{
SS_CONTRACT(BOOL)
{
GC_NOTRIGGER;
INSTANCE_CHECK;
PRECONDITION(CheckIteratorRange(i));
NOTHROW;
}
SS_CONTRACT_END;
// End() will not throw here
CONTRACT_VIOLATION(ThrowsViolation);
if (i >= End())
SS_RETURN FALSE;
WCHAR test = i[0];
SS_RETURN (test == c
|| ((CAN_SIMPLE_UPCASE(test) ? SIMPLE_UPCASE(test) : MapChar(test, LCMAP_UPPERCASE))
== (CAN_SIMPLE_UPCASE(c) ? SIMPLE_UPCASE(c) : MapChar(c, LCMAP_UPPERCASE))));
}
//-----------------------------------------------------------------------------
// Convert string to unicode lowercase using the invariant culture
// Note: Please don't use it in PATH as multiple character can map to the same
// lower case symbol
//-----------------------------------------------------------------------------
void SString::LowerCase()
{
SS_CONTRACT_VOID
{
GC_NOTRIGGER;
PRECONDITION(CheckPointer(this));
SS_POSTCONDITION(CheckPointer(RETVAL));
if (IsRepresentation(REPRESENTATION_UNICODE)) NOTHROW; else THROWS;
SUPPORTS_DAC;
}
SS_CONTRACT_END;
ConvertToUnicode();
for (WCHAR *pwch = GetRawUnicode(); pwch < GetRawUnicode() + GetRawCount(); ++pwch)
{
*pwch = (CAN_SIMPLE_DOWNCASE(*pwch) ? SIMPLE_DOWNCASE(*pwch) : MapChar(*pwch, LCMAP_LOWERCASE));
}
}
//-----------------------------------------------------------------------------
// Convert null-terminated string to lowercase using the invariant culture
//-----------------------------------------------------------------------------
//static
void SString::LowerCase(__inout_z LPWSTR wszString)
{
SS_CONTRACT_VOID
{
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC;
}
SS_CONTRACT_END;
if (wszString == NULL)
{
return;
}
for (WCHAR * pwch = wszString; *pwch != '\0'; ++pwch)
{
*pwch = (CAN_SIMPLE_DOWNCASE(*pwch) ? SIMPLE_DOWNCASE(*pwch) : MapChar(*pwch, LCMAP_LOWERCASE));
}
}
//-----------------------------------------------------------------------------
// Convert string to unicode uppercase using the invariant culture
// Note: Please don't use it in PATH as multiple character can map to the same
// upper case symbol
//-----------------------------------------------------------------------------
void SString::UpperCase()
{
SS_CONTRACT_VOID
{
GC_NOTRIGGER;
PRECONDITION(CheckPointer(this));
SS_POSTCONDITION(CheckPointer(RETVAL));
if (IsRepresentation(REPRESENTATION_UNICODE)) NOTHROW; else THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
SS_CONTRACT_END;
ConvertToUnicode();
for (WCHAR *pwch = GetRawUnicode(); pwch < GetRawUnicode() + GetRawCount(); ++pwch)
{
*pwch = (CAN_SIMPLE_UPCASE(*pwch) ? SIMPLE_UPCASE(*pwch) : MapChar(*pwch, LCMAP_UPPERCASE));
}
}
//-----------------------------------------------------------------------------
// Get a const pointer to the internal buffer as an ANSI string.
//-----------------------------------------------------------------------------
const CHAR *SString::GetANSI(AbstractScratchBuffer &scratch) const
{
SS_CONTRACT(const CHAR *)
{
INSTANCE_CHECK_NULL;
THROWS;
GC_NOTRIGGER;
}
SS_CONTRACT_END;
if (IsRepresentation(REPRESENTATION_ANSI))
SS_RETURN GetRawANSI();
ConvertToANSI((SString&)scratch);
SS_RETURN ((SString&)scratch).GetRawANSI();
}
//-----------------------------------------------------------------------------
// Get a const pointer to the internal buffer as a UTF8 string.
//-----------------------------------------------------------------------------
const UTF8 *SString::GetUTF8(AbstractScratchBuffer &scratch) const
{
CONTRACT(const UTF8 *)
{
INSTANCE_CHECK_NULL;
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
if (IsRepresentation(REPRESENTATION_UTF8))
RETURN GetRawUTF8();
ConvertToUTF8((SString&)scratch);
RETURN ((SString&)scratch).GetRawUTF8();
}
const UTF8 *SString::GetUTF8(AbstractScratchBuffer &scratch, COUNT_T *pcbUtf8) const
{
CONTRACT(const UTF8 *)
{
INSTANCE_CHECK_NULL;
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
if (IsRepresentation(REPRESENTATION_UTF8))
{
*pcbUtf8 = GetRawCount() + 1;
RETURN GetRawUTF8();
}
*pcbUtf8 = ConvertToUTF8((SString&)scratch);
RETURN ((SString&)scratch).GetRawUTF8();
}
//-----------------------------------------------------------------------------
// Get a const pointer to the internal buffer which must already be a UTF8 string.
// This avoids the need to create a scratch buffer we know will never be used.
//-----------------------------------------------------------------------------
const UTF8 *SString::GetUTF8NoConvert() const
{
CONTRACT(const UTF8 *)
{
INSTANCE_CHECK_NULL;
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
if (IsRepresentation(REPRESENTATION_UTF8))
RETURN GetRawUTF8();
ThrowHR(E_INVALIDARG);
}
//-----------------------------------------------------------------------------
// Safe version of sprintf.
// Prints formatted ansi text w/ var args to this buffer.
//-----------------------------------------------------------------------------
void SString::Printf(const CHAR *format, ...)
{
WRAPPER_NO_CONTRACT;
va_list args;
va_start(args, format);
VPrintf(format, args);
va_end(args);
}
#ifdef _DEBUG
//
// Check the Printf use for potential globalization bugs. %S formatting
// specifier does Unicode->Ansi or Ansi->Unicode conversion using current
// C-locale. This almost always means globalization bug in the CLR codebase.
//
// Ideally, we would elimitate %S from all format strings. Unfortunately,
// %S is too widespread in non-shipping code that such cleanup is not feasible.
//
static void CheckForFormatStringGlobalizationIssues(const SString &format, const SString &result)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
DEBUG_ONLY;
}
CONTRACTL_END;
BOOL fDangerousFormat = FALSE;
// Check whether the format string contains the %S formatting specifier
SString::CIterator itrFormat = format.Begin();
while (*itrFormat)
{
if (*itrFormat++ == '%')
{
// <TODO>Handle the complex format strings like %blahS</TODO>
if (*itrFormat++ == 'S')
{
fDangerousFormat = TRUE;
break;
}
}
}
if (fDangerousFormat)
{
BOOL fNonAsciiUsed = FALSE;
// Now check whether there are any non-ASCII characters in the output.
// Check whether the result contains non-Ascii characters
SString::CIterator itrResult = format.Begin();
while (*itrResult)
{
if (*itrResult++ > 127)
{
fNonAsciiUsed = TRUE;
break;
}
}
CONSISTENCY_CHECK_MSGF(!fNonAsciiUsed,
("Non-ASCII string was produced by %%S format specifier. This is likely globalization bug."
"To fix this, change the format string to %%s and do the correct encoding at the Printf callsite"));
}
}
#endif
#ifndef EBADF
#define EBADF 9
#endif
#ifndef ENOMEM
#define ENOMEM 12
#endif
#ifndef ERANGE
#define ERANGE 34
#endif
#if defined(_MSC_VER)
#undef va_copy
#define va_copy(dest,src) (dest = src)
#endif
void SString::VPrintf(const CHAR *format, va_list args)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(format));
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
va_list ap;
// sprintf gives us no means to know how many characters are written
// other than guessing and trying
if (GetRawCount() > 0)
{
// First, try to use the existing buffer
va_copy(ap, args);
int result = _vsnprintf_s(GetRawANSI(), GetRawCount()+1, _TRUNCATE, format, ap);
va_end(ap);
if (result >=0)
{
// Succeeded in writing. Now resize -
Resize(result, REPRESENTATION_ANSI, PRESERVE);
SString sss(Ansi, format);
INDEBUG(CheckForFormatStringGlobalizationIssues(sss, *this));
RETURN;
}
}
// Make a guess how long the result will be (note this will be doubled)
COUNT_T guess = (COUNT_T) strlen(format)+1;
if (guess < GetRawCount())
guess = GetRawCount();
if (guess < MINIMUM_GUESS)
guess = MINIMUM_GUESS;
while (TRUE)
{
// Double the previous guess - eventually we will get enough space
guess *= 2;
Resize(guess, REPRESENTATION_ANSI);
// Clear errno to avoid false alarms
errno = 0;
va_copy(ap, args);
int result = _vsnprintf_s(GetRawANSI(), GetRawCount()+1, _TRUNCATE, format, ap);
va_end(ap);
if (result >= 0)
{
// Succeed in writing. Shrink the buffer to fit exactly.
Resize(result, REPRESENTATION_ANSI, PRESERVE);
SString sss(Ansi, format);
INDEBUG(CheckForFormatStringGlobalizationIssues(sss, *this));
RETURN;
}
if (errno==ENOMEM)
{
ThrowOutOfMemory();
}
else
if (errno!=0 && errno!=EBADF && errno!=ERANGE)
{
CONSISTENCY_CHECK_MSG(FALSE, "_vsnprintf_s failed. Potential globalization bug.");
ThrowHR(HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION));
}
}
RETURN;
}
void SString::Printf(const WCHAR *format, ...)
{
WRAPPER_NO_CONTRACT;
va_list args;
va_start(args, format);
VPrintf(format, args);
va_end(args);
}
void SString::PPrintf(const WCHAR *format, ...)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(format));
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
va_list argItr;
va_start(argItr, format);
PVPrintf(format, argItr);
va_end(argItr);
RETURN;
}
void SString::VPrintf(const WCHAR *format, va_list args)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(format));
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
va_list ap;
// sprintf gives us no means to know how many characters are written
// other than guessing and trying
if (GetRawCount() > 0)
{
// First, try to use the existing buffer
va_copy(ap, args);
int result = _vsnwprintf_s(GetRawUnicode(), GetRawCount()+1, _TRUNCATE, format, ap);
va_end(ap);
if (result >= 0)
{
// succeeded
Resize(result, REPRESENTATION_UNICODE, PRESERVE);
SString sss(format);
INDEBUG(CheckForFormatStringGlobalizationIssues(sss, *this));
RETURN;
}
}
// Make a guess how long the result will be (note this will be doubled)
COUNT_T guess = (COUNT_T) wcslen(format)+1;
if (guess < GetRawCount())
guess = GetRawCount();
if (guess < MINIMUM_GUESS)
guess = MINIMUM_GUESS;
while (TRUE)
{
// Double the previous guess - eventually we will get enough space
guess *= 2;
Resize(guess, REPRESENTATION_UNICODE);
// Clear errno to avoid false alarms
errno = 0;
va_copy(ap, args);
int result = _vsnwprintf_s(GetRawUnicode(), GetRawCount()+1, _TRUNCATE, format, ap);
va_end(ap);
if (result >= 0)
{
Resize(result, REPRESENTATION_UNICODE, PRESERVE);
SString sss(format);
INDEBUG(CheckForFormatStringGlobalizationIssues(sss, *this));
RETURN;
}
if (errno==ENOMEM)
{
ThrowOutOfMemory();
}
else
if (errno!=0 && errno!=EBADF && errno!=ERANGE)
{
CONSISTENCY_CHECK_MSG(FALSE, "_vsnwprintf_s failed. Potential globalization bug.");
ThrowHR(HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION));
}
}
RETURN;
}
void SString::PVPrintf(const WCHAR *format, va_list args)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(format));
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
va_list ap;
// sprintf gives us no means to know how many characters are written
// other than guessing and trying
if (GetRawCount() > 0)
{
// First, try to use the existing buffer
va_copy(ap, args);
#if defined(FEATURE_CORESYSTEM)
int result = _vsnwprintf_s(GetRawUnicode(), GetRawCount()+1, _TRUNCATE, format, ap);
#else
int result = _vswprintf_p(GetRawUnicode(), GetRawCount()+1, format, ap);
#endif
va_end(ap);
if (result >= 0)
{
// succeeded
Resize(result, REPRESENTATION_UNICODE, PRESERVE);
SString sss(format);
INDEBUG(CheckForFormatStringGlobalizationIssues(sss, *this));
RETURN;
}
}
// Make a guess how long the result will be (note this will be doubled)
COUNT_T guess = (COUNT_T) wcslen(format)+1;
if (guess < GetRawCount())
guess = GetRawCount();
if (guess < MINIMUM_GUESS)
guess = MINIMUM_GUESS;
while (TRUE)
{
// Double the previous guess - eventually we will get enough space
guess *= 2;
Resize(guess, REPRESENTATION_UNICODE, DONT_PRESERVE);
// Clear errno to avoid false alarms
errno = 0;
va_copy(ap, args);
#if defined(FEATURE_CORESYSTEM)
int result = _vsnwprintf_s(GetRawUnicode(), GetRawCount()+1, _TRUNCATE, format, ap);
#else
int result = _vswprintf_p(GetRawUnicode(), GetRawCount()+1, format, ap);
#endif
va_end(ap);
if (result >= 0)
{
Resize(result, REPRESENTATION_UNICODE, PRESERVE);
SString sss(format);
INDEBUG(CheckForFormatStringGlobalizationIssues(sss, *this));
RETURN;
}
if (errno==ENOMEM)
{
ThrowOutOfMemory();
}
else
if (errno!=0 && errno!=EBADF && errno!=ERANGE)
{
CONSISTENCY_CHECK_MSG(FALSE, "_vsnwprintf_s failed. Potential globalization bug.");
ThrowHR(HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION));
}
}
RETURN;
}
void SString::AppendPrintf(const CHAR *format, ...)
{
WRAPPER_NO_CONTRACT;
va_list args;
va_start(args, format);
AppendVPrintf(format, args);
va_end(args);
}
void SString::AppendVPrintf(const CHAR *format, va_list args)
{
WRAPPER_NO_CONTRACT;
StackSString s;
s.VPrintf(format, args);
Append(s);
}
void SString::AppendPrintf(const WCHAR *format, ...)
{
WRAPPER_NO_CONTRACT;
va_list args;
va_start(args, format);
AppendVPrintf(format, args);
va_end(args);
}
void SString::AppendVPrintf(const WCHAR *format, va_list args)
{
WRAPPER_NO_CONTRACT;
StackSString s;
s.VPrintf(format, args);
Append(s);
}
//----------------------------------------------------------------------------
// LoadResource - moved to sstring_com.cpp
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Format the message and put the contents in this string
//----------------------------------------------------------------------------
BOOL SString::FormatMessage(DWORD dwFlags, LPCVOID lpSource, DWORD dwMessageId, DWORD dwLanguageId,
const SString &arg1, const SString &arg2,
const SString &arg3, const SString &arg4,
const SString &arg5, const SString &arg6,
const SString &arg7, const SString &arg8,
const SString &arg9, const SString &arg10)
{
CONTRACT(BOOL)
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
const WCHAR *args[] = {arg1.GetUnicode(), arg2.GetUnicode(), arg3.GetUnicode(), arg4.GetUnicode(),
arg5.GetUnicode(), arg6.GetUnicode(), arg7.GetUnicode(), arg8.GetUnicode(),
arg9.GetUnicode(), arg10.GetUnicode()};
if (GetRawCount() > 0)
{
// First, try to use our existing buffer to hold the result.
Resize(GetRawCount(), REPRESENTATION_UNICODE);
DWORD result = ::WszFormatMessage(dwFlags | FORMAT_MESSAGE_ARGUMENT_ARRAY,
lpSource, dwMessageId, dwLanguageId,
GetRawUnicode(), GetRawCount()+1, (va_list*)args);
// Although we cannot directly detect truncation, we can tell if we
// used up all the space (in which case we will assume truncation.)
if (result != 0 && result < GetRawCount())
{
if (GetRawUnicode()[result-1] == W(' '))
{
GetRawUnicode()[result-1] = W('\0');
result -= 1;
}
Resize(result, REPRESENTATION_UNICODE, PRESERVE);
RETURN TRUE;
}
}
// We don't have enough space in our buffer, do dynamic allocation.
LocalAllocHolder<WCHAR> string;
DWORD result = ::WszFormatMessage(dwFlags | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY,
lpSource, dwMessageId, dwLanguageId,
(LPWSTR)(LPWSTR*)&string, 0, (va_list*)args);
if (result == 0)
RETURN FALSE;
else
{
if (string[result-1] == W(' '))
string[result-1] = W('\0');
Set(string);
RETURN TRUE;
}
}
#if 1
//----------------------------------------------------------------------------
// Helper
//----------------------------------------------------------------------------
// @todo -this should be removed and placed outside of SString
void SString::MakeFullNamespacePath(const SString &nameSpace, const SString &name)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
if (nameSpace.GetRepresentation() == REPRESENTATION_UTF8
&& name.GetRepresentation() == REPRESENTATION_UTF8)
{
const UTF8 *ns = nameSpace.GetRawUTF8();
const UTF8 *n = name.GetRawUTF8();
COUNT_T count = ns::GetFullLength(ns, n)-1;
Resize(count, REPRESENTATION_UTF8);
if (count > 0)
ns::MakePath(GetRawUTF8(), count+1, ns, n);
}
else
{
const WCHAR *ns = nameSpace;
const WCHAR *n = name;
COUNT_T count = ns::GetFullLength(ns, n)-1;
Resize(count, REPRESENTATION_UNICODE);
if (count > 0)
ns::MakePath(GetRawUnicode(), count+1, ns, n);
}
RETURN;
}
#endif
//----------------------------------------------------------------------------
// Private helper.
// Check to see if the string fits the suggested representation
//----------------------------------------------------------------------------
BOOL SString::IsRepresentation(Representation representation) const
{
CONTRACT(BOOL)
{
PRECONDITION(CheckRepresentation(representation));
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACT_END;
Representation currentRepresentation = GetRepresentation();
// If representations are the same, cool.
if (currentRepresentation == representation)
RETURN TRUE;
// If we have an empty representation, we match everything
if (currentRepresentation == REPRESENTATION_EMPTY)
RETURN TRUE;
// If we're a 1 byte charset, there are some more chances to match
if (currentRepresentation != REPRESENTATION_UNICODE
&& representation != REPRESENTATION_UNICODE)
{
// If we're ASCII, we can be any 1 byte rep
if (currentRepresentation == REPRESENTATION_ASCII)
RETURN TRUE;
// We really want to be ASCII - scan to see if we qualify
if (ScanASCII())
RETURN TRUE;
}
// Sorry, must convert.
RETURN FALSE;
}
//----------------------------------------------------------------------------
// Private helper.
// Get the contents of the given string in a form which is compatible with our
// string (and is in a fixed character set.) Updates the given iterator
// if necessary to keep it in sync.
//----------------------------------------------------------------------------
const SString &SString::GetCompatibleString(const SString &s, SString &scratch, const CIterator &i) const
{
CONTRACTL
{
PRECONDITION(s.Check());
PRECONDITION(scratch.Check());
PRECONDITION(scratch.CheckEmpty());
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END;
// Since we have an iterator, we should be fixed size already
CONSISTENCY_CHECK(IsFixedSize());
switch (GetRepresentation())
{
case REPRESENTATION_EMPTY:
return s;
case REPRESENTATION_ASCII:
if (s.IsRepresentation(REPRESENTATION_ASCII))
return s;
// We can't in general convert to ASCII, so try unicode.
ConvertToUnicode(i);
// fall through
case REPRESENTATION_UNICODE:
if (s.IsRepresentation(REPRESENTATION_UNICODE))
return s;
// @todo: we could convert s to unicode - is that a good policy????
s.ConvertToUnicode(scratch);
return scratch;
case REPRESENTATION_UTF8:
case REPRESENTATION_ANSI:
// These should all be impossible since we have an CIterator on us.
default:
UNREACHABLE_MSG("Unexpected string representation");
}
return s;
}
//----------------------------------------------------------------------------
// Private helper.
// Get the contents of the given string in a form which is compatible with our
// string (and is in a fixed character set.)
// May convert our string to unicode.
//----------------------------------------------------------------------------
const SString &SString::GetCompatibleString(const SString &s, SString &scratch) const
{
CONTRACTL
{
PRECONDITION(s.Check());
PRECONDITION(scratch.Check());
PRECONDITION(scratch.CheckEmpty());
THROWS_UNLESS_BOTH_NORMALIZED(s);
GC_NOTRIGGER;
}
CONTRACTL_END;
// First, make sure we have a fixed size.
ConvertToFixed();
switch (GetRepresentation())
{
case REPRESENTATION_EMPTY:
return s;
case REPRESENTATION_ANSI:
if (s.IsRepresentation(REPRESENTATION_ANSI))
return s;
s.ConvertToANSI(scratch);
return scratch;
case REPRESENTATION_ASCII:
if (s.IsRepresentation(REPRESENTATION_ASCII))
return s;
// We can't in general convert to ASCII, so try unicode.
ConvertToUnicode();
// fall through
case REPRESENTATION_UNICODE:
if (s.IsRepresentation(REPRESENTATION_UNICODE))
return s;
// @todo: we could convert s to unicode in place - is that a good policy????
s.ConvertToUnicode(scratch);
return scratch;
case REPRESENTATION_UTF8:
default:
UNREACHABLE();
}
return s;
}
//----------------------------------------------------------------------------
// Private helper.
// If we have a 1 byte representation, scan the buffer to see if we can gain
// some conversion flexibility by labelling it ASCII
//----------------------------------------------------------------------------
BOOL SString::ScanASCII() const
{
CONTRACT(BOOL)
{
POSTCONDITION(IsRepresentation(REPRESENTATION_ASCII) || IsASCIIScanned());
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACT_END;
if (!IsASCIIScanned())
{
const CHAR *c = GetRawANSI();
const CHAR *cEnd = c + GetRawCount();
while (c < cEnd)
{
if (*c & 0x80)
break;
c++;
}
if (c == cEnd)
{
const_cast<SString *>(this)->SetRepresentation(REPRESENTATION_ASCII);
RETURN TRUE;
}
else
const_cast<SString *>(this)->SetASCIIScanned();
}
RETURN FALSE;
}
//----------------------------------------------------------------------------
// Private helper.
// Resize updates the geometry of the string and ensures that
// the space can be written to.
// count - number of characters (not including null) to hold
// preserve - if we realloc, do we copy data from old to new?
//----------------------------------------------------------------------------
void SString::Resize(COUNT_T count, SString::Representation representation, Preserve preserve)
{
CONTRACT_VOID
{
PRECONDITION(CountToSize(count) >= count);
POSTCONDITION(IsRepresentation(representation));
POSTCONDITION(GetRawCount() == count);
if (count == 0) NOTHROW; else THROWS;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
// If we are resizing to zero, Clear is more efficient
if (count == 0)
{
Clear();
}
else
{
SetRepresentation(representation);
COUNT_T size = CountToSize(count);
// detect overflow
if (size < count)
ThrowOutOfMemory();
ClearNormalized();
SBuffer::Resize(size, preserve);
if (IsImmutable())
EnsureMutable();
NullTerminate();
}
RETURN;
}
//-----------------------------------------------------------------------------
// This is essentially a specialized version of the above for size 0
//-----------------------------------------------------------------------------
void SString::Clear()
{
CONTRACT_VOID
{
INSTANCE_CHECK;
POSTCONDITION(IsEmpty());
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACT_END;
SetRepresentation(REPRESENTATION_EMPTY);
if (IsImmutable())
{
// Use shared empty string rather than allocating a new buffer
SBuffer::SetImmutable(s_EmptyBuffer, sizeof(s_EmptyBuffer));
}
else
{
// Leave allocated buffer for future growth
SBuffer::TweakSize(sizeof(WCHAR));
GetRawUnicode()[0] = 0;
}
RETURN;
}
#ifdef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
// Return a pointer to the raw buffer
//
// Returns:
// A pointer to the raw string buffer.
//
void * SString::DacGetRawContent() const
{
if (IsEmpty())
{
return NULL;
}
switch (GetRepresentation())
{
case REPRESENTATION_EMPTY:
return NULL;
case REPRESENTATION_UNICODE:
case REPRESENTATION_UTF8:
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
// Note: no need to call DacInstantiateString because we know the exact length already.
return SBuffer::DacGetRawContent();
default:
DacNotImpl();
return NULL;
}
}
//---------------------------------------------------------------------------------------
//
// Return a pointer to the raw buffer as a pointer to a unicode string. Does not
// do conversion, and thus requires that the representation already be in unicode.
//
// Returns:
// A pointer to the raw string buffer as a unicode string.
//
const WCHAR * SString::DacGetRawUnicode() const
{
if (IsEmpty() || (GetRepresentation() == REPRESENTATION_EMPTY))
{
return W("");
}
if (GetRepresentation() != REPRESENTATION_UNICODE)
{
DacError(E_UNEXPECTED);
}
HRESULT status = S_OK;
WCHAR* wszBuf = NULL;
EX_TRY
{
wszBuf = static_cast<WCHAR*>(SBuffer::DacGetRawContent());
}
EX_CATCH_HRESULT(status);
if (SUCCEEDED(status))
{
return wszBuf;
}
else
{
return NULL;
}
}
//---------------------------------------------------------------------------------------
//
// Copy the string from the target into the provided buffer, converting to unicode if necessary
//
// Arguments:
// cBufChars - size of pBuffer in count of unicode characters.
// pBuffer - a buffer of cBufChars unicode chars.
// pcNeedChars - space to store the number of unicode chars in the SString.
//
// Returns:
// true if successful - and buffer is filled with the unicode representation of
// the string.
// false if unsuccessful.
//
bool SString::DacGetUnicode(COUNT_T cBufChars,
__out_z __inout_ecount(cBufChars) WCHAR * pBuffer,
COUNT_T * pcNeedChars) const
{
SUPPORTS_DAC;
PVOID pContent = NULL;
int iPage = CP_ACP;
if (IsEmpty() || (GetRepresentation() == REPRESENTATION_EMPTY))
{
if (pcNeedChars)
{
*pcNeedChars = 1;
}
if (pBuffer && cBufChars)
{
pBuffer[0] = 0;
}
return true;
}
HRESULT status = S_OK;
EX_TRY
{
pContent = SBuffer::DacGetRawContent();
}
EX_CATCH_HRESULT(status);
if (SUCCEEDED(status) && pContent != NULL)
{
switch (GetRepresentation())
{
case REPRESENTATION_UNICODE:
if (pcNeedChars)
{
*pcNeedChars = GetCount() + 1;
}
if (pBuffer && cBufChars)
{
if (cBufChars > GetCount() + 1)
{
cBufChars = GetCount() + 1;
}
memcpy(pBuffer, pContent, cBufChars * sizeof(*pBuffer));
pBuffer[cBufChars - 1] = 0;
}
return true;
case REPRESENTATION_UTF8:
iPage = CP_UTF8;
case REPRESENTATION_ASCII:
case REPRESENTATION_ANSI:
// iPage defaults to CP_ACP.
if (pcNeedChars)
{
*pcNeedChars = WszMultiByteToWideChar(iPage, 0, reinterpret_cast<PSTR>(pContent), -1, NULL, 0);
}
if (pBuffer && cBufChars)
{
if (!WszMultiByteToWideChar(iPage, 0, reinterpret_cast<PSTR>(pContent), -1, pBuffer, cBufChars))
{
return false;
}
}
return true;
default:
DacNotImpl();
return false;
}
}
return false;
}
#endif //DACCESS_COMPILE
| poizan42/coreclr | src/utilcode/sstring.cpp | C++ | mit | 77,108 |
/**!
* @fileOverview Kickass library to create and place poppers near their reference elements.
* @version 1.11.1
* @license
* Copyright (c) 2016 Federico Zivolo and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
var nativeHints = ['native code', '[object MutationObserverConstructor]'];
/**
* Determine if a function is implemented natively (as opposed to a polyfill).
* @method
* @memberof Popper.Utils
* @argument {Function | undefined} fn the function to check
* @returns {Boolean}
*/
var isNative = (function (fn) {
return nativeHints.some(function (hint) {
return (fn || '').toString().indexOf(hint) > -1;
});
});
var isBrowser = typeof window !== 'undefined';
var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
var timeoutDuration = 0;
for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
timeoutDuration = 1;
break;
}
}
function microtaskDebounce(fn) {
var scheduled = false;
var i = 0;
var elem = document.createElement('span');
// MutationObserver provides a mechanism for scheduling microtasks, which
// are scheduled *before* the next task. This gives us a way to debounce
// a function but ensure it's called *before* the next paint.
var observer = new MutationObserver(function () {
fn();
scheduled = false;
});
observer.observe(elem, { attributes: true });
return function () {
if (!scheduled) {
scheduled = true;
elem.setAttribute('x-index', i);
i = i + 1; // don't use compund (+=) because it doesn't get optimized in V8
}
};
}
function taskDebounce(fn) {
var scheduled = false;
return function () {
if (!scheduled) {
scheduled = true;
setTimeout(function () {
scheduled = false;
fn();
}, timeoutDuration);
}
};
}
// It's common for MutationObserver polyfills to be seen in the wild, however
// these rely on Mutation Events which only occur when an element is connected
// to the DOM. The algorithm used in this module does not use a connected element,
// and so we must ensure that a *native* MutationObserver is available.
var supportsNativeMutationObserver = isBrowser && isNative(window.MutationObserver);
/**
* Create a debounced version of a method, that's asynchronously deferred
* but called in the minimum time possible.
*
* @method
* @memberof Popper.Utils
* @argument {Function} fn
* @returns {Function}
*/
var debounce = supportsNativeMutationObserver ? microtaskDebounce : taskDebounce;
/**
* Check if the given variable is a function
* @method
* @memberof Popper.Utils
* @argument {Any} functionToCheck - variable to check
* @returns {Boolean} answer to: is a function?
*/
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/**
* Get CSS computed property of the given element
* @method
* @memberof Popper.Utils
* @argument {Eement} element
* @argument {String} property
*/
function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
}
// NOTE: 1 DOM access here
var css = window.getComputedStyle(element, null);
return property ? css[property] : css;
}
/**
* Returns the parentNode or the host of the element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} parent
*/
function getParentNode(element) {
if (element.nodeName === 'HTML') {
return element;
}
return element.parentNode || element.host;
}
/**
* Returns the scrolling parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} scroll parent
*/
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element || ['HTML', 'BODY', '#document'].indexOf(element.nodeName) !== -1) {
return window.document.body;
}
// Firefox want us to check `-x` and `-y` variations as well
var _getStyleComputedProp = getStyleComputedProperty(element),
overflow = _getStyleComputedProp.overflow,
overflowX = _getStyleComputedProp.overflowX,
overflowY = _getStyleComputedProp.overflowY;
if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
/**
* Returns the offset parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} offset parent
*/
function getOffsetParent(element) {
// NOTE: 1 DOM access here
var offsetParent = element && element.offsetParent;
var nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
return window.document.documentElement;
}
// .offsetParent will return the closest TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
function isOffsetContainer(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY') {
return false;
}
return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
}
/**
* Finds the root node (document, shadowDOM root) of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} node
* @returns {Element} root node
*/
function getRoot(node) {
if (node.parentNode !== null) {
return getRoot(node.parentNode);
}
return node;
}
/**
* Finds the offset parent common to the two provided nodes
* @method
* @memberof Popper.Utils
* @argument {Element} element1
* @argument {Element} element2
* @returns {Element} common offset parent
*/
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return window.document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
var start = order ? element1 : element2;
var end = order ? element2 : element1;
// Get common ancestor container
var range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
var commonAncestorContainer = range.commonAncestorContainer;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
var element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
/**
* Gets the scroll value of the given element in the given side (top and left)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {String} side `top` or `left`
* @returns {number} amount of scrolled pixels
*/
function getScroll(element) {
var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';
var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
var html = window.document.documentElement;
var scrollingElement = window.document.scrollingElement || html;
return scrollingElement[upperSide];
}
return element[upperSide];
}
/*
* Sum or subtract the element scroll values (left and top) from a given rect object
* @method
* @memberof Popper.Utils
* @param {Object} rect - Rect object you want to change
* @param {HTMLElement} element - The element from the function reads the scroll values
* @param {Boolean} subtract - set to true if you want to subtract the scroll values
* @return {Object} rect - The modifier rect object
*/
function includeScroll(rect, element) {
var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
var modifier = subtract ? -1 : 1;
rect.top += scrollTop * modifier;
rect.bottom += scrollTop * modifier;
rect.left += scrollLeft * modifier;
rect.right += scrollLeft * modifier;
return rect;
}
/*
* Helper to detect borders of a given element
* @method
* @memberof Popper.Utils
* @param {CSSStyleDeclaration} styles
* Result of `getStyleComputedProperty` on the given element
* @param {String} axis - `x` or `y`
* @return {number} borders - The borders size of the given axis
*/
function getBordersSize(styles, axis) {
var sideA = axis === 'x' ? 'Left' : 'Top';
var sideB = sideA === 'Left' ? 'Right' : 'Bottom';
return +styles['border' + sideA + 'Width'].split('px')[0] + +styles['border' + sideB + 'Width'].split('px')[0];
}
/**
* Tells if you are running Internet Explorer 10
* @method
* @memberof Popper.Utils
* @returns {Boolean} isIE10
*/
var isIE10 = undefined;
var isIE10$1 = function () {
if (isIE10 === undefined) {
isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1;
}
return isIE10;
};
function getSize(axis, body, html, computedStyle) {
return Math.max(body['offset' + axis], html['client' + axis], html['offset' + axis], isIE10$1() ? html['offset' + axis] + computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')] + computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')] : 0);
}
function getWindowSizes() {
var body = window.document.body;
var html = window.document.documentElement;
var computedStyle = isIE10$1() && window.getComputedStyle(html);
return {
height: getSize('Height', body, html, computedStyle),
width: getSize('Width', body, html, computedStyle)
};
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/**
* Given element offsets, generate an output similar to getBoundingClientRect
* @method
* @memberof Popper.Utils
* @argument {Object} offsets
* @returns {Object} ClientRect like output
*/
function getClientRect(offsets) {
return _extends({}, offsets, {
right: offsets.left + offsets.width,
bottom: offsets.top + offsets.height
});
}
/**
* Get bounding client rect of given element
* @method
* @memberof Popper.Utils
* @param {HTMLElement} element
* @return {Object} client rect
*/
function getBoundingClientRect(element) {
var rect = {};
// IE10 10 FIX: Please, don't ask, the element isn't
// considered in DOM in some circumstances...
// This isn't reproducible in IE10 compatibility mode of IE11
if (isIE10$1()) {
try {
rect = element.getBoundingClientRect();
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
rect.top += scrollTop;
rect.left += scrollLeft;
rect.bottom += scrollTop;
rect.right += scrollLeft;
} catch (err) {}
} else {
rect = element.getBoundingClientRect();
}
var result = {
left: rect.left,
top: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
// subtract scrollbar size from sizes
var sizes = element.nodeName === 'HTML' ? getWindowSizes() : {};
var width = sizes.width || element.clientWidth || result.right - result.left;
var height = sizes.height || element.clientHeight || result.bottom - result.top;
var horizScrollbar = element.offsetWidth - width;
var vertScrollbar = element.offsetHeight - height;
// if an hypothetical scrollbar is detected, we must be sure it's not a `border`
// we make this check conditional for performance reasons
if (horizScrollbar || vertScrollbar) {
var styles = getStyleComputedProperty(element);
horizScrollbar -= getBordersSize(styles, 'x');
vertScrollbar -= getBordersSize(styles, 'y');
result.width -= horizScrollbar;
result.height -= vertScrollbar;
}
return getClientRect(result);
}
function getOffsetRectRelativeToArbitraryNode(children, parent) {
var isIE10 = isIE10$1();
var isHTML = parent.nodeName === 'HTML';
var childrenRect = getBoundingClientRect(children);
var parentRect = getBoundingClientRect(parent);
var scrollParent = getScrollParent(children);
var styles = getStyleComputedProperty(parent);
var borderTopWidth = +styles.borderTopWidth.split('px')[0];
var borderLeftWidth = +styles.borderLeftWidth.split('px')[0];
var offsets = getClientRect({
top: childrenRect.top - parentRect.top - borderTopWidth,
left: childrenRect.left - parentRect.left - borderLeftWidth,
width: childrenRect.width,
height: childrenRect.height
});
offsets.marginTop = 0;
offsets.marginLeft = 0;
// Subtract margins of documentElement in case it's being used as parent
// we do this only on HTML because it's the only element that behaves
// differently when margins are applied to it. The margins are included in
// the box of the documentElement, in the other cases not.
if (!isIE10 && isHTML) {
var marginTop = +styles.marginTop.split('px')[0];
var marginLeft = +styles.marginLeft.split('px')[0];
offsets.top -= borderTopWidth - marginTop;
offsets.bottom -= borderTopWidth - marginTop;
offsets.left -= borderLeftWidth - marginLeft;
offsets.right -= borderLeftWidth - marginLeft;
// Attach marginTop and marginLeft because in some circumstances we may need them
offsets.marginTop = marginTop;
offsets.marginLeft = marginLeft;
}
if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
offsets = includeScroll(offsets, parent);
}
return offsets;
}
function getViewportOffsetRectRelativeToArtbitraryNode(element) {
var html = window.document.documentElement;
var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
var width = Math.max(html.clientWidth, window.innerWidth || 0);
var height = Math.max(html.clientHeight, window.innerHeight || 0);
var scrollTop = getScroll(html);
var scrollLeft = getScroll(html, 'left');
var offset = {
top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
width: width,
height: height
};
return getClientRect(offset);
}
/**
* Check if the given element is fixed or is inside a fixed parent
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {Element} customContainer
* @returns {Boolean} answer to "isFixed?"
*/
function isFixed(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
return false;
}
if (getStyleComputedProperty(element, 'position') === 'fixed') {
return true;
}
return isFixed(getParentNode(element));
}
/**
* Computed the boundaries limits and return them
* @method
* @memberof Popper.Utils
* @param {HTMLElement} popper
* @param {HTMLElement} reference
* @param {number} padding
* @param {HTMLElement} boundariesElement - Element used to define the boundaries
* @returns {Object} Coordinates of the boundaries
*/
function getBoundaries(popper, reference, padding, boundariesElement) {
// NOTE: 1 DOM access here
var boundaries = { top: 0, left: 0 };
var offsetParent = findCommonOffsetParent(popper, reference);
// Handle viewport case
if (boundariesElement === 'viewport') {
boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent);
} else {
// Handle other cases based on DOM element used as boundaries
var boundariesNode = void 0;
if (boundariesElement === 'scrollParent') {
boundariesNode = getScrollParent(getParentNode(popper));
if (boundariesNode.nodeName === 'BODY') {
boundariesNode = window.document.documentElement;
}
} else if (boundariesElement === 'window') {
boundariesNode = window.document.documentElement;
} else {
boundariesNode = boundariesElement;
}
var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent);
// In case of HTML, we need a different computation
if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
var _getWindowSizes = getWindowSizes(),
height = _getWindowSizes.height,
width = _getWindowSizes.width;
boundaries.top += offsets.top - offsets.marginTop;
boundaries.bottom = height + offsets.top;
boundaries.left += offsets.left - offsets.marginLeft;
boundaries.right = width + offsets.left;
} else {
// for all the other DOM elements, this one is good
boundaries = offsets;
}
}
// Add paddings
boundaries.left += padding;
boundaries.top += padding;
boundaries.right -= padding;
boundaries.bottom -= padding;
return boundaries;
}
function getArea(_ref) {
var width = _ref.width,
height = _ref.height;
return width * height;
}
/**
* Utility used to transform the `auto` placement to the placement with more
* available space.
* @method
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
if (placement.indexOf('auto') === -1) {
return placement;
}
var boundaries = getBoundaries(popper, reference, padding, boundariesElement);
var rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
var sortedAreas = Object.keys(rects).map(function (key) {
return _extends({
key: key
}, rects[key], {
area: getArea(rects[key])
});
}).sort(function (a, b) {
return b.area - a.area;
});
var filteredAreas = sortedAreas.filter(function (_ref2) {
var width = _ref2.width,
height = _ref2.height;
return width >= popper.clientWidth && height >= popper.clientHeight;
});
var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
var variation = placement.split('-')[1];
return computedPlacement + (variation ? '-' + variation : '');
}
/**
* Get offsets to the reference element
* @method
* @memberof Popper.Utils
* @param {Object} state
* @param {Element} popper - the popper element
* @param {Element} reference - the reference element (the popper will be relative to this)
* @returns {Object} An object containing the offsets which will be applied to the popper
*/
function getReferenceOffsets(state, popper, reference) {
var commonOffsetParent = findCommonOffsetParent(popper, reference);
return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent);
}
/**
* Get the outer sizes of the given element (offset size + margins)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Object} object containing width and height properties
*/
function getOuterSizes(element) {
var styles = window.getComputedStyle(element);
var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom);
var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight);
var result = {
width: element.offsetWidth + y,
height: element.offsetHeight + x
};
return result;
}
/**
* Get the opposite placement of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement
* @returns {String} flipped placement
*/
function getOppositePlacement(placement) {
var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash[matched];
});
}
/**
* Get offsets to the popper
* @method
* @memberof Popper.Utils
* @param {Object} position - CSS position the Popper will get applied
* @param {HTMLElement} popper - the popper element
* @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
* @param {String} placement - one of the valid placement options
* @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
*/
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
var popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
var popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
var mainSide = isHoriz ? 'top' : 'left';
var secondarySide = isHoriz ? 'left' : 'top';
var measurement = isHoriz ? 'height' : 'width';
var secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
/**
* Mimics the `find` method of Array
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function find(arr, check) {
// use native find if supported
if (Array.prototype.find) {
return arr.find(check);
}
// use `filter` to obtain the same behavior of `find`
return arr.filter(check)[0];
}
/**
* Return the index of the matching object
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function findIndex(arr, prop, value) {
// use native findIndex if supported
if (Array.prototype.findIndex) {
return arr.findIndex(function (cur) {
return cur[prop] === value;
});
}
// use `find` + `indexOf` if `findIndex` isn't supported
var match = find(arr, function (obj) {
return obj[prop] === value;
});
return arr.indexOf(match);
}
/**
* Loop trough the list of modifiers and run them in order,
* each of them will then edit the data object.
* @method
* @memberof Popper.Utils
* @param {dataObject} data
* @param {Array} modifiers
* @param {String} ends - Optional modifier name used as stopper
* @returns {dataObject}
*/
function runModifiers(modifiers, data, ends) {
var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
modifiersToRun.forEach(function (modifier) {
if (modifier.function) {
console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
}
var fn = modifier.function || modifier.fn;
if (modifier.enabled && isFunction(fn)) {
// Add properties to offsets to make them a complete clientRect object
// we do this before each modifier to make sure the previous one doesn't
// mess with these values
data.offsets.popper = getClientRect(data.offsets.popper);
data.offsets.reference = getClientRect(data.offsets.reference);
data = fn(data, modifier);
}
});
return data;
}
/**
* Updates the position of the popper, computing the new offsets and applying
* the new style.<br />
* Prefer `scheduleUpdate` over `update` because of performance reasons.
* @method
* @memberof Popper
*/
function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
}
/**
* Helper used to know if the given modifier is enabled.
* @method
* @memberof Popper.Utils
* @returns {Boolean}
*/
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(function (_ref) {
var name = _ref.name,
enabled = _ref.enabled;
return enabled && name === modifierName;
});
}
/**
* Get the prefixed supported property name
* @method
* @memberof Popper.Utils
* @argument {String} property (camelCase)
* @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
*/
function getSupportedPropertyName(property) {
var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
var upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (var i = 0; i < prefixes.length - 1; i++) {
var prefix = prefixes[i];
var toCheck = prefix ? '' + prefix + upperProp : property;
if (typeof window.document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
/**
* Destroy the popper
* @method
* @memberof Popper
*/
function destroy() {
this.state.isDestroyed = true;
// touch DOM only if `applyStyle` modifier is enabled
if (isModifierEnabled(this.modifiers, 'applyStyle')) {
this.popper.removeAttribute('x-placement');
this.popper.style.left = '';
this.popper.style.position = '';
this.popper.style.top = '';
this.popper.style[getSupportedPropertyName('transform')] = '';
}
this.disableEventListeners();
// remove the popper if user explicity asked for the deletion on destroy
// do not use `remove` because IE11 doesn't support it
if (this.options.removeOnDestroy) {
this.popper.parentNode.removeChild(this.popper);
}
return this;
}
function attachToScrollParents(scrollParent, event, callback, scrollParents) {
var isBody = scrollParent.nodeName === 'BODY';
var target = isBody ? window : scrollParent;
target.addEventListener(event, callback, { passive: true });
if (!isBody) {
attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
}
scrollParents.push(target);
}
/**
* Setup needed event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function setupEventListeners(reference, options, state, updateBound) {
// Resize event listener on window
state.updateBound = updateBound;
window.addEventListener('resize', state.updateBound, { passive: true });
// Scroll event listener on scroll parents
var scrollElement = getScrollParent(reference);
attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
state.scrollElement = scrollElement;
state.eventsEnabled = true;
return state;
}
/**
* It will add resize/scroll events and start recalculating
* position of the popper element when they are triggered.
* @method
* @memberof Popper
*/
function enableEventListeners() {
if (!this.state.eventsEnabled) {
this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
}
}
/**
* Remove event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function removeEventListeners(reference, state) {
// Remove resize event listener on window
window.removeEventListener('resize', state.updateBound);
// Remove scroll event listener on scroll parents
state.scrollParents.forEach(function (target) {
target.removeEventListener('scroll', state.updateBound);
});
// Reset state
state.updateBound = null;
state.scrollParents = [];
state.scrollElement = null;
state.eventsEnabled = false;
return state;
}
/**
* It will remove resize/scroll events and won't recalculate popper position
* when they are triggered. It also won't trigger onUpdate callback anymore,
* unless you call `update` method manually.
* @method
* @memberof Popper
*/
function disableEventListeners() {
if (this.state.eventsEnabled) {
window.cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
}
/**
* Tells if a given input is a number
* @method
* @memberof Popper.Utils
* @param {*} input to check
* @return {Boolean}
*/
function isNumeric(n) {
return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Set the style to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the style to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setStyles(element, styles) {
Object.keys(styles).forEach(function (prop) {
var unit = '';
// add unit if the value is numeric and is one of the following
if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
unit = 'px';
}
element.style[prop] = styles[prop] + unit;
});
}
/**
* Set the attributes to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the attributes to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setAttributes(element, attributes) {
Object.keys(attributes).forEach(function (prop) {
var value = attributes[prop];
if (value !== false) {
element.setAttribute(prop, attributes[prop]);
} else {
element.removeAttribute(prop);
}
});
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} data.styles - List of style properties - values to apply to popper element
* @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The same data object
*/
function applyStyle(data) {
// any property present in `data.styles` will be applied to the popper,
// in this way we can make the 3rd party modifiers add custom styles to it
// Be aware, modifiers could override the properties defined in the previous
// lines of this modifier!
setStyles(data.instance.popper, data.styles);
// any property present in `data.attributes` will be applied to the popper,
// they will be set as HTML attributes of the element
setAttributes(data.instance.popper, data.attributes);
// if the arrow style has been computed, apply the arrow style
if (data.offsets.arrow) {
setStyles(data.arrowElement, data.offsets.arrow);
}
return data;
}
/**
* Set the x-placement attribute before everything else because it could be used
* to add margins to the popper margins needs to be calculated to get the
* correct popper offsets.
* @method
* @memberof Popper.modifiers
* @param {HTMLElement} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper.
* @param {Object} options - Popper.js options
*/
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: 'absolute' });
return options;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeStyle(data, options) {
var x = options.x,
y = options.y;
var popper = data.offsets.popper;
// Remove this legacy support in Popper.js v2
var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'applyStyle';
}).gpuAcceleration;
if (legacyGpuAccelerationOption !== undefined) {
console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
}
var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
var offsetParent = getOffsetParent(data.instance.popper);
var offsetParentRect = getBoundingClientRect(offsetParent);
// Styles
var styles = {
position: popper.position
};
// floor sides to avoid blurry text
var offsets = {
left: Math.floor(popper.left),
top: Math.floor(popper.top),
bottom: Math.floor(popper.bottom),
right: Math.floor(popper.right)
};
var sideA = x === 'bottom' ? 'top' : 'bottom';
var sideB = y === 'right' ? 'left' : 'right';
// if gpuAcceleration is set to `true` and transform is supported,
// we use `translate3d` to apply the position to the popper we
// automatically use the supported prefixed version if needed
var prefixedProperty = getSupportedPropertyName('transform');
// now, let's make a step back and look at this code closely (wtf?)
// If the content of the popper grows once it's been positioned, it
// may happen that the popper gets misplaced because of the new content
// overflowing its reference element
// To avoid this problem, we provide two options (x and y), which allow
// the consumer to define the offset origin.
// If we position a popper on top of a reference element, we can set
// `x` to `top` to make the popper grow towards its top instead of
// its bottom.
var left = void 0,
top = void 0;
if (sideA === 'bottom') {
top = -offsetParentRect.height + offsets.bottom;
} else {
top = offsets.top;
}
if (sideB === 'right') {
left = -offsetParentRect.width + offsets.right;
} else {
left = offsets.left;
}
if (gpuAcceleration && prefixedProperty) {
styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
styles[sideA] = 0;
styles[sideB] = 0;
styles.willChange = 'transform';
} else {
// othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
var invertTop = sideA === 'bottom' ? -1 : 1;
var invertLeft = sideB === 'right' ? -1 : 1;
styles[sideA] = top * invertTop;
styles[sideB] = left * invertLeft;
styles.willChange = sideA + ', ' + sideB;
}
// Attributes
var attributes = {
'x-placement': data.placement
};
// Update attributes and styles of `data`
data.attributes = _extends({}, attributes, data.attributes);
data.styles = _extends({}, styles, data.styles);
return data;
}
/**
* Helper used to know if the given modifier depends from another one.<br />
* It checks if the needed modifier is listed and enabled.
* @method
* @memberof Popper.Utils
* @param {Array} modifiers - list of modifiers
* @param {String} requestingName - name of requesting modifier
* @param {String} requestedName - name of requested modifier
* @returns {Boolean}
*/
function isModifierRequired(modifiers, requestingName, requestedName) {
var requesting = find(modifiers, function (_ref) {
var name = _ref.name;
return name === requestingName;
});
var isRequired = !!requesting && modifiers.some(function (modifier) {
return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
});
if (!isRequired) {
var _requesting = '`' + requestingName + '`';
var requested = '`' + requestedName + '`';
console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
}
return isRequired;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function arrow(data, options) {
// arrow depends on keepTogether in order to work
if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
return data;
}
var arrowElement = options.element;
// if arrowElement is a string, suppose it's a CSS selector
if (typeof arrowElement === 'string') {
arrowElement = data.instance.popper.querySelector(arrowElement);
// if arrowElement is not found, don't run the modifier
if (!arrowElement) {
return data;
}
} else {
// if the arrowElement isn't a query selector we must check that the
// provided DOM node is child of its popper node
if (!data.instance.popper.contains(arrowElement)) {
console.warn('WARNING: `arrow.element` must be child of its popper element!');
return data;
}
}
var placement = data.placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isVertical = ['left', 'right'].indexOf(placement) !== -1;
var len = isVertical ? 'height' : 'width';
var side = isVertical ? 'top' : 'left';
var altSide = isVertical ? 'left' : 'top';
var opSide = isVertical ? 'bottom' : 'right';
var arrowElementSize = getOuterSizes(arrowElement)[len];
//
// extends keepTogether behavior making sure the popper and its reference have enough pixels in conjuction
//
// top/left side
if (reference[opSide] - arrowElementSize < popper[side]) {
data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
}
// bottom/right side
if (reference[side] + arrowElementSize > popper[opSide]) {
data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
}
// compute center of the popper
var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
// Compute the sideValue using the updated popper offsets
var sideValue = center - getClientRect(data.offsets.popper)[side];
// prevent arrowElement from being placed not contiguously to its popper
sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
data.arrowElement = arrowElement;
data.offsets.arrow = {};
data.offsets.arrow[side] = Math.round(sideValue);
data.offsets.arrow[altSide] = ''; // make sure to unset any eventual altSide value from the DOM node
return data;
}
/**
* Get the opposite placement variation of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement variation
* @returns {String} flipped placement variation
*/
function getOppositeVariation(variation) {
if (variation === 'end') {
return 'start';
} else if (variation === 'start') {
return 'end';
}
return variation;
}
/**
* List of accepted placements to use as values of the `placement` option.<br />
* Valid placements are:
* - `auto`
* - `top`
* - `right`
* - `bottom`
* - `left`
*
* Each placement can have a variation from this list:
* - `-start`
* - `-end`
*
* Variations are interpreted easily if you think of them as the left to right
* written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
* is right.<br />
* Vertically (`left` and `right`), `start` is top and `end` is bottom.
*
* Some valid examples are:
* - `top-end` (on top of reference, right aligned)
* - `right-start` (on right of reference, top aligned)
* - `bottom` (on bottom, centered)
* - `auto-right` (on the side with more space available, alignment depends by placement)
*
* @static
* @type {Array}
* @enum {String}
* @readonly
* @method placements
* @memberof Popper
*/
var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
// Get rid of `auto` `auto-start` and `auto-end`
var validPlacements = placements.slice(3);
/**
* Given an initial placement, returns all the subsequent placements
* clockwise (or counter-clockwise).
*
* @method
* @memberof Popper.Utils
* @argument {String} placement - A valid placement (it accepts variations)
* @argument {Boolean} counter - Set to true to walk the placements counterclockwise
* @returns {Array} placements including their variations
*/
function clockwise(placement) {
var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var index = validPlacements.indexOf(placement);
var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
return counter ? arr.reverse() : arr;
}
var BEHAVIORS = {
FLIP: 'flip',
CLOCKWISE: 'clockwise',
COUNTERCLOCKWISE: 'counterclockwise'
};
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function flip(data, options) {
// if `inner` modifier is enabled, we can't use the `flip` modifier
if (isModifierEnabled(data.instance.modifiers, 'inner')) {
return data;
}
if (data.flipped && data.placement === data.originalPlacement) {
// seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
return data;
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement);
var placement = data.placement.split('-')[0];
var placementOpposite = getOppositePlacement(placement);
var variation = data.placement.split('-')[1] || '';
var flipOrder = [];
switch (options.behavior) {
case BEHAVIORS.FLIP:
flipOrder = [placement, placementOpposite];
break;
case BEHAVIORS.CLOCKWISE:
flipOrder = clockwise(placement);
break;
case BEHAVIORS.COUNTERCLOCKWISE:
flipOrder = clockwise(placement, true);
break;
default:
flipOrder = options.behavior;
}
flipOrder.forEach(function (step, index) {
if (placement !== step || flipOrder.length === index + 1) {
return data;
}
placement = data.placement.split('-')[0];
placementOpposite = getOppositePlacement(placement);
var popperOffsets = data.offsets.popper;
var refOffsets = data.offsets.reference;
// using floor because the reference offsets may contain decimals we are not going to consider here
var floor = Math.floor;
var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
// flip the variation if required
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
if (overlapsRef || overflowsBoundaries || flippedVariation) {
// this boolean to detect any flip loop
data.flipped = true;
if (overlapsRef || overflowsBoundaries) {
placement = flipOrder[index + 1];
}
if (flippedVariation) {
variation = getOppositeVariation(variation);
}
data.placement = placement + (variation ? '-' + variation : '');
// this object contains `position`, we want to preserve it along with
// any additional property we may add in the future
data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
data = runModifiers(data.instance.modifiers, data, 'flip');
}
});
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function keepTogether(data) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var placement = data.placement.split('-')[0];
var floor = Math.floor;
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var side = isVertical ? 'right' : 'bottom';
var opSide = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
if (popper[side] < floor(reference[opSide])) {
data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
}
if (popper[opSide] > floor(reference[side])) {
data.offsets.popper[opSide] = floor(reference[side]);
}
return data;
}
/**
* Converts a string containing value + unit into a px value number
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} str - Value + unit string
* @argument {String} measurement - `height` or `width`
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @returns {Number|String}
* Value in pixels, or original string if no values were extracted
*/
function toValue(str, measurement, popperOffsets, referenceOffsets) {
// separate value from unit
var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
var value = +split[1];
var unit = split[2];
// If it's not a number it's an operator, I guess
if (!value) {
return str;
}
if (unit.indexOf('%') === 0) {
var element = void 0;
switch (unit) {
case '%p':
element = popperOffsets;
break;
case '%':
case '%r':
default:
element = referenceOffsets;
}
var rect = getClientRect(element);
return rect[measurement] / 100 * value;
} else if (unit === 'vh' || unit === 'vw') {
// if is a vh or vw, we calculate the size based on the viewport
var size = void 0;
if (unit === 'vh') {
size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
} else {
size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
return size / 100 * value;
} else {
// if is an explicit pixel unit, we get rid of the unit and keep the value
// if is an implicit unit, it's px, and we return just the value
return value;
}
}
/**
* Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} offset
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @argument {String} basePlacement
* @returns {Array} a two cells array with x and y offsets in numbers
*/
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
var offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
var fragments = offset.split(/(\+|\-)/).map(function (frag) {
return frag.trim();
});
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
var divider = fragments.indexOf(find(fragments, function (frag) {
return frag.search(/,|\s/) !== -1;
}));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
var splitRegex = /\s*,\s*|\s+/;
var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map(function (op, index) {
// Most of the units rely on the orientation of the popper
var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
var mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce(function (a, b) {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(function (str) {
return toValue(str, measurement, popperOffsets, referenceOffsets);
});
});
// Loop trough the offsets arrays and execute the operations
ops.forEach(function (op, index) {
op.forEach(function (frag, index2) {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @argument {Number|String} options.offset=0
* The offset value as described in the modifier description
* @returns {Object} The data object, properly modified
*/
function offset(data, _ref) {
var offset = _ref.offset;
var placement = data.placement,
_data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var basePlacement = placement.split('-')[0];
var offsets = void 0;
if (isNumeric(+offset)) {
offsets = [+offset, 0];
} else {
offsets = parseOffset(offset, popper, reference, basePlacement);
}
if (basePlacement === 'left') {
popper.top += offsets[0];
popper.left -= offsets[1];
} else if (basePlacement === 'right') {
popper.top += offsets[0];
popper.left += offsets[1];
} else if (basePlacement === 'top') {
popper.left += offsets[0];
popper.top -= offsets[1];
} else if (basePlacement === 'bottom') {
popper.left += offsets[0];
popper.top += offsets[1];
}
data.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function preventOverflow(data, options) {
var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
// If offsetParent is the reference element, we really want to
// go one step up and use the next offsetParent as reference to
// avoid to make this modifier completely useless and look like broken
if (data.instance.reference === boundariesElement) {
boundariesElement = getOffsetParent(boundariesElement);
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement);
options.boundaries = boundaries;
var order = options.priority;
var popper = data.offsets.popper;
var check = {
primary: function primary(placement) {
var value = popper[placement];
if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
value = Math.max(popper[placement], boundaries[placement]);
}
return defineProperty({}, placement, value);
},
secondary: function secondary(placement) {
var mainSide = placement === 'right' ? 'left' : 'top';
var value = popper[mainSide];
if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
}
return defineProperty({}, mainSide, value);
}
};
order.forEach(function (placement) {
var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
popper = _extends({}, popper, check[side](placement));
});
data.offsets.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function shift(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var shiftvariation = placement.split('-')[1];
// if shift shiftvariation is specified, run the modifier
if (shiftvariation) {
var _data$offsets = data.offsets,
reference = _data$offsets.reference,
popper = _data$offsets.popper;
var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
var side = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
var shiftOffsets = {
start: defineProperty({}, side, reference[side]),
end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement])
};
data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]);
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function hide(data) {
if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
return data;
}
var refRect = data.offsets.reference;
var bound = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'preventOverflow';
}).boundaries;
if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === true) {
return data;
}
data.hide = true;
data.attributes['x-out-of-boundaries'] = '';
} else {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === false) {
return data;
}
data.hide = false;
data.attributes['x-out-of-boundaries'] = false;
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function inner(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
popper[isHoriz ? 'left' : 'top'] = reference[placement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
data.placement = getOppositePlacement(placement);
data.offsets.popper = getClientRect(popper);
return data;
}
/**
* Modifier function, each modifier can have a function of this type assigned
* to its `fn` property.<br />
* These functions will be called on each update, this means that you must
* make sure they are performant enough to avoid performance bottlenecks.
*
* @function ModifierFn
* @argument {dataObject} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {dataObject} The data object, properly modified
*/
/**
* Modifiers are plugins used to alter the behavior of your poppers.<br />
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities
* needed by the library.
*
* Usually you don't want to override the `order`, `fn` and `onLoad` props.
* All the other properties are configurations that could be tweaked.
* @namespace modifiers
*/
var modifiers = {
/**
* Modifier used to shift the popper on the start or end of its reference
* element.<br />
* It will read the variation of the `placement` property.<br />
* It can be one either `-end` or `-start`.
* @memberof modifiers
* @inner
*/
shift: {
/** @prop {number} order=100 - Index used to define the order of execution */
order: 100,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: shift
},
/**
* The `offset` modifier can shift your popper on both its axis.
*
* It accepts the following units:
* - `px` or unitless, interpreted as pixels
* - `%` or `%r`, percentage relative to the length of the reference element
* - `%p`, percentage relative to the length of the popper element
* - `vw`, CSS viewport width unit
* - `vh`, CSS viewport height unit
*
* For length is intended the main axis relative to the placement of the popper.<br />
* This means that if the placement is `top` or `bottom`, the length will be the
* `width`. In case of `left` or `right`, it will be the height.
*
* You can provide a single value (as `Number` or `String`), or a pair of values
* as `String` divided by a comma or one (or more) white spaces.<br />
* The latter is a deprecated method because it leads to confusion and will be
* removed in v2.<br />
* Additionally, it accepts additions and subtractions between different units.
* Note that multiplications and divisions aren't supported.
*
* Valid examples are:
* ```
* 10
* '10%'
* '10, 10'
* '10%, 10'
* '10 + 10%'
* '10 - 5vh + 3%'
* '-10px + 5vh, 5px - 6%'
* ```
*
* @memberof modifiers
* @inner
*/
offset: {
/** @prop {number} order=200 - Index used to define the order of execution */
order: 200,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: offset,
/** @prop {Number|String} offset=0
* The offset value as described in the modifier description
*/
offset: 0
},
/**
* Modifier used to prevent the popper from being positioned outside the boundary.
*
* An scenario exists where the reference itself is not within the boundaries.<br />
* We can say it has "escaped the boundaries" — or just "escaped".<br />
* In this case we need to decide whether the popper should either:
*
* - detach from the reference and remain "trapped" in the boundaries, or
* - if it should ignore the boundary and "escape with its reference"
*
* When `escapeWithReference` is set to`true` and reference is completely
* outside its boundaries, the popper will overflow (or completely leave)
* the boundaries in order to remain attached to the edge of the reference.
*
* @memberof modifiers
* @inner
*/
preventOverflow: {
/** @prop {number} order=300 - Index used to define the order of execution */
order: 300,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: preventOverflow,
/**
* @prop {Array} [priority=['left','right','top','bottom']]
* Popper will try to prevent overflow following these priorities by default,
* then, it could overflow on the left and on top of the `boundariesElement`
*/
priority: ['left', 'right', 'top', 'bottom'],
/**
* @prop {number} padding=5
* Amount of pixel used to define a minimum distance between the boundaries
* and the popper this makes sure the popper has always a little padding
* between the edges of its container
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='scrollParent'
* Boundaries used by the modifier, can be `scrollParent`, `window`,
* `viewport` or any DOM element.
*/
boundariesElement: 'scrollParent'
},
/**
* Modifier used to make sure the reference and its popper stay near eachothers
* without leaving any gap between the two. Expecially useful when the arrow is
* enabled and you want to assure it to point to its reference element.
* It cares only about the first axis, you can still have poppers with margin
* between the popper and its reference element.
* @memberof modifiers
* @inner
*/
keepTogether: {
/** @prop {number} order=400 - Index used to define the order of execution */
order: 400,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: keepTogether
},
/**
* This modifier is used to move the `arrowElement` of the popper to make
* sure it is positioned between the reference element and its popper element.
* It will read the outer size of the `arrowElement` node to detect how many
* pixels of conjuction are needed.
*
* It has no effect if no `arrowElement` is provided.
* @memberof modifiers
* @inner
*/
arrow: {
/** @prop {number} order=500 - Index used to define the order of execution */
order: 500,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: arrow,
/** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
element: '[x-arrow]'
},
/**
* Modifier used to flip the popper's placement when it starts to overlap its
* reference element.
*
* Requires the `preventOverflow` modifier before it in order to work.
*
* **NOTE:** this modifier will interrupt the current update cycle and will
* restart it if it detects the need to flip the placement.
* @memberof modifiers
* @inner
*/
flip: {
/** @prop {number} order=600 - Index used to define the order of execution */
order: 600,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: flip,
/**
* @prop {String|Array} behavior='flip'
* The behavior used to change the popper's placement. It can be one of
* `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
* placements (with optional variations).
*/
behavior: 'flip',
/**
* @prop {number} padding=5
* The popper will flip if it hits the edges of the `boundariesElement`
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='viewport'
* The element which will define the boundaries of the popper position,
* the popper will never be placed outside of the defined boundaries
* (except if keepTogether is enabled)
*/
boundariesElement: 'viewport'
},
/**
* Modifier used to make the popper flow toward the inner of the reference element.
* By default, when this modifier is disabled, the popper will be placed outside
* the reference element.
* @memberof modifiers
* @inner
*/
inner: {
/** @prop {number} order=700 - Index used to define the order of execution */
order: 700,
/** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
enabled: false,
/** @prop {ModifierFn} */
fn: inner
},
/**
* Modifier used to hide the popper when its reference element is outside of the
* popper boundaries. It will set a `x-out-of-boundaries` attribute which can
* be used to hide with a CSS selector the popper when its reference is
* out of boundaries.
*
* Requires the `preventOverflow` modifier before it in order to work.
* @memberof modifiers
* @inner
*/
hide: {
/** @prop {number} order=800 - Index used to define the order of execution */
order: 800,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: hide
},
/**
* Computes the style that will be applied to the popper element to gets
* properly positioned.
*
* Note that this modifier will not touch the DOM, it just prepares the styles
* so that `applyStyle` modifier can apply it. This separation is useful
* in case you need to replace `applyStyle` with a custom implementation.
*
* This modifier has `850` as `order` value to maintain backward compatibility
* with previous versions of Popper.js. Expect the modifiers ordering method
* to change in future major versions of the library.
*
* @memberof modifiers
* @inner
*/
computeStyle: {
/** @prop {number} order=850 - Index used to define the order of execution */
order: 850,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: computeStyle,
/**
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3d transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties.
*/
gpuAcceleration: true,
/**
* @prop {string} [x='bottom']
* Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
* Change this if your popper should grow in a direction different from `bottom`
*/
x: 'bottom',
/**
* @prop {string} [x='left']
* Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
* Change this if your popper should grow in a direction different from `right`
*/
y: 'right'
},
/**
* Applies the computed styles to the popper element.
*
* All the DOM manipulations are limited to this modifier. This is useful in case
* you want to integrate Popper.js inside a framework or view library and you
* want to delegate all the DOM manipulations to it.
*
* Note that if you disable this modifier, you must make sure the popper element
* has its position set to `absolute` before Popper.js can do its work!
*
* Just disable this modifier and define you own to achieve the desired effect.
*
* @memberof modifiers
* @inner
*/
applyStyle: {
/** @prop {number} order=900 - Index used to define the order of execution */
order: 900,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: applyStyle,
/** @prop {Function} */
onLoad: applyStyleOnLoad,
/**
* @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3d transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties.
*/
gpuAcceleration: undefined
}
};
/**
* The `dataObject` is an object containing all the informations used by Popper.js
* this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
* @name dataObject
* @property {Object} data.instance The Popper.js instance
* @property {String} data.placement Placement applied to popper
* @property {String} data.originalPlacement Placement originally defined on init
* @property {Boolean} data.flipped True if popper has been flipped by flip modifier
* @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper.
* @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
* @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.boundaries Offsets of the popper boundaries
* @property {Object} data.offsets The measurements of popper, reference and arrow elements.
* @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
*/
/**
* Default options provided to Popper.js constructor.<br />
* These can be overriden using the `options` argument of Popper.js.<br />
* To override an option, simply pass as 3rd argument an object with the same
* structure of this object, example:
* ```
* new Popper(ref, pop, {
* modifiers: {
* preventOverflow: { enabled: false }
* }
* })
* ```
* @type {Object}
* @static
* @memberof Popper
*/
var Defaults = {
/**
* Popper's placement
* @prop {Popper.placements} placement='bottom'
*/
placement: 'bottom',
/**
* Whether events (resize, scroll) are initially enabled
* @prop {Boolean} eventsEnabled=true
*/
eventsEnabled: true,
/**
* Set to true if you want to automatically remove the popper when
* you call the `destroy` method.
* @prop {Boolean} removeOnDestroy=false
*/
removeOnDestroy: false,
/**
* Callback called when the popper is created.<br />
* By default, is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onCreate}
*/
onCreate: function onCreate() {},
/**
* Callback called when the popper is updated, this callback is not called
* on the initialization/creation of the popper, but only on subsequent
* updates.<br />
* By default, is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onUpdate}
*/
onUpdate: function onUpdate() {},
/**
* List of modifiers used to modify the offsets before they are applied to the popper.
* They provide most of the functionalities of Popper.js
* @prop {modifiers}
*/
modifiers: modifiers
};
/**
* @callback onCreate
* @param {dataObject} data
*/
/**
* @callback onUpdate
* @param {dataObject} data
*/
// Utils
// Methods
var Popper = function () {
/**
* Create a new Popper.js instance
* @class Popper
* @param {HTMLElement|referenceObject} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper.
* @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
* @return {Object} instance - The generated Popper.js instance
*/
function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimationFrame(_this.update);
};
// make update() debounced, so that it only runs at most once-per-tick
this.update = debounce(this.update.bind(this));
// with {} we create a new object with the options inside it
this.options = _extends({}, Popper.Defaults, options);
// init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
};
// get reference and popper elements (allow jQuery wrappers)
this.reference = reference.jquery ? reference[0] : reference;
this.popper = popper.jquery ? popper[0] : popper;
// Deep merge modifiers options
this.options.modifiers = {};
Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
});
// Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends({
name: name
}, _this.options.modifiers[name]);
})
// sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
});
// modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
});
// fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
}
// We can't use class properties because they don't get listed in the
// class prototype and break stuff like Sinon stubs
createClass(Popper, [{
key: 'update',
value: function update$$1() {
return update.call(this);
}
}, {
key: 'destroy',
value: function destroy$$1() {
return destroy.call(this);
}
}, {
key: 'enableEventListeners',
value: function enableEventListeners$$1() {
return enableEventListeners.call(this);
}
}, {
key: 'disableEventListeners',
value: function disableEventListeners$$1() {
return disableEventListeners.call(this);
}
/**
* Schedule an update, it will run on the next UI update available
* @method scheduleUpdate
* @memberof Popper
*/
/**
* Collection of utilities useful when writing custom modifiers.
* Starting from version 1.7, this method is available only if you
* include `popper-utils.js` before `popper.js`.
*
* **DEPRECATION**: This way to access PopperUtils is deprecated
* and will be removed in v2! Use the PopperUtils module directly instead.
* Due to the high instability of the methods contained in Utils, we can't
* guarantee them to follow semver. Use them at your own risk!
* @static
* @private
* @type {Object}
* @deprecated since version 1.8
* @member Utils
* @memberof Popper
*/
}]);
return Popper;
}();
/**
* The `referenceObject` is an object that provides an interface compatible with Popper.js
* and lets you use it as replacement of a real DOM node.<br />
* You can use this method to position a popper relatively to a set of coordinates
* in case you don't have a DOM node to use as reference.
*
* ```
* new Popper(referenceObject, popperNode);
* ```
*
* NB: This feature isn't supported in Internet Explorer 10
* @name referenceObject
* @property {Function} data.getBoundingClientRect
* A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
* @property {number} data.clientWidth
* An ES6 getter that will return the width of the virtual reference element.
* @property {number} data.clientHeight
* An ES6 getter that will return the height of the virtual reference element.
*/
Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
Popper.placements = placements;
Popper.Defaults = Defaults;
export default Popper;
//# sourceMappingURL=popper.js.map
| cdnjs/cdnjs | ajax/libs/popper.js/1.11.1/esm/popper.js | JavaScript | mit | 80,493 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.TWEEN = global.TWEEN || {})));
}(this, (function (exports) { 'use strict';
/* global global */
var root = typeof (window) !== 'undefined' ? window : typeof (global) !== 'undefined' ? global : this;
if (!Object.assign) {
Object.assign = function (source) {
var args = [], len$1 = arguments.length - 1;
while ( len$1-- > 0 ) args[ len$1 ] = arguments[ len$1 + 1 ];
for (var i = 0, len = args.length; i < len; i++) {
var arg = args[i];
for (var p in arg) {
source[p] = arg[p];
}
}
return source
};
}
if (!Object.create) {
Object.create = function (source) {
return Object.assign({}, source || {})
};
}
if (!Array.isArray) {
Array.isArray = function (source) { return source && source.push && source.splice; };
}
if (typeof (requestAnimationFrame) === 'undefined') {
root.requestAnimationFrame = function (fn) { return root.setTimeout(fn, 16); };
}
if (typeof (cancelAnimationFrame) === 'undefined') {
root.cancelAnimationFrame = function (id) { return root.clearTimeout(id); };
}
/* global process */
var _tweens = [];
var isStarted = false;
var _autoPlay = false;
var _tick;
var _ticker = root.requestAnimationFrame;
var _stopTicker = root.cancelAnimationFrame;
var add = function (tween) {
_tweens.push(tween);
if (_autoPlay && !isStarted) {
_tick = _ticker(update);
isStarted = true;
}
};
var getAll = function () { return _tweens; };
var autoPlay = function (state) {
_autoPlay = state;
};
var removeAll = function () {
_tweens.length = 0;
_stopTicker(_tick);
};
var get = function (tween) {
for (var i = 0; i < _tweens.length; i++) {
if (tween === _tweens[i]) {
return _tweens[i]
}
}
return null
};
var has = function (tween) {
return get(tween) !== null
};
var remove = function (tween) {
var i = _tweens.indexOf(tween);
if (i !== -1) {
_tweens.splice(i, 1);
}
if (!_tweens.length) {
_stopTicker(_tick);
}
};
var now = (function () {
if (typeof (process) !== 'undefined' && process.hrtime !== undefined) {
return function () {
var time = process.hrtime();
// Convert [seconds, nanoseconds] to milliseconds.
return time[0] * 1000 + time[1] / 1000000
}
// In a browser, use window.performance.now if it is available.
} else if (root.performance !== undefined &&
root.performance.now !== undefined) {
// This must be bound, because directly assigning this function
// leads to an invocation exception in Chrome.
return root.performance.now.bind(root.performance)
// Use Date.now if it is available.
} else {
var offset = root.performance && root.performance.timing && root.performance.timing.navigationStart ? root.performance.timing.navigationStart : Date.now();
return function () {
return Date.now() - offset
}
}
}());
var update = function (time, preserve) {
time = time !== undefined ? time : now();
_tick = _ticker(update);
var len = _tweens.length;
if (!len) {
isStarted = false;
_stopTicker(_tick);
return false
}
var i = 0;
for (; i < len; i++) {
_tweens[i].update(time, preserve);
}
return true
};
var isRunning = function () { return isStarted; };
var Plugins = {};
// Normalise time when visiblity is changed (if available) ...
if (root.document && root.document.addEventListener) {
var doc = root.document;
var timeDiff = 0;
var timePause = 0;
doc.addEventListener('visibilitychange', function () {
if (document.hidden) {
timePause = now();
_stopTicker(_tick);
isStarted = false;
} else {
timeDiff = now() - timePause;
for (var i = 0, length = _tweens.length; i < length; i++) {
_tweens[i]._startTime += timeDiff;
}
_tick = _ticker(update);
isStarted = true;
}
return true
});
}
var Easing = {
Linear: {
None: function None (k) {
return k
}
},
Quadratic: {
In: function In (k) {
return k * k
},
Out: function Out (k) {
return k * (2 - k)
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k
}
return -0.5 * (--k * (k - 2) - 1)
}
},
Cubic: {
In: function In (k) {
return k * k * k
},
Out: function Out (k) {
return --k * k * k + 1
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k
}
return 0.5 * ((k -= 2) * k * k + 2)
}
},
Quartic: {
In: function In (k) {
return k * k * k * k
},
Out: function Out (k) {
return 1 - (--k * k * k * k)
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k
}
return -0.5 * ((k -= 2) * k * k * k - 2)
}
},
Quintic: {
In: function In (k) {
return k * k * k * k * k
},
Out: function Out (k) {
return --k * k * k * k * k + 1
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k * k
}
return 0.5 * ((k -= 2) * k * k * k * k + 2)
}
},
Sinusoidal: {
In: function In (k) {
return 1 - Math.cos(k * Math.PI / 2)
},
Out: function Out (k) {
return Math.sin(k * Math.PI / 2)
},
InOut: function InOut (k) {
return 0.5 * (1 - Math.cos(Math.PI * k))
}
},
Exponential: {
In: function In (k) {
return k === 0 ? 0 : Math.pow(1024, k - 1)
},
Out: function Out (k) {
return k === 1 ? 1 : 1 - Math.pow(2, -10 * k)
},
InOut: function InOut (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
if ((k *= 2) < 1) {
return 0.5 * Math.pow(1024, k - 1)
}
return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2)
}
},
Circular: {
In: function In (k) {
return 1 - Math.sqrt(1 - k * k)
},
Out: function Out (k) {
return Math.sqrt(1 - (--k * k))
},
InOut: function InOut (k) {
if ((k *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - k * k) - 1)
}
return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1)
}
},
Elastic: {
In: function In (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI)
},
Out: function Out (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1
},
InOut: function InOut (k) {
if (k === 0) {
return 0
}
if (k === 1) {
return 1
}
k *= 2;
if (k < 1) {
return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI)
}
return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1
}
},
Back: {
In: function In (k) {
var s = 1.70158;
return k * k * ((s + 1) * k - s)
},
Out: function Out (k) {
var s = 1.70158;
return --k * k * ((s + 1) * k + s) + 1
},
InOut: function InOut (k) {
var s = 1.70158 * 1.525;
if ((k *= 2) < 1) {
return 0.5 * (k * k * ((s + 1) * k - s))
}
return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2)
}
},
Bounce: {
In: function In (k) {
return 1 - Easing.Bounce.Out(1 - k)
},
Out: function Out (k) {
if (k < (1 / 2.75)) {
return 7.5625 * k * k
} else if (k < (2 / 2.75)) {
return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75
} else if (k < (2.5 / 2.75)) {
return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375
} else {
return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375
}
},
InOut: function InOut (k) {
if (k < 0.5) {
return Easing.Bounce.In(k * 2) * 0.5
}
return Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5
}
}
};
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var intertween = createCommonjsModule(function (module) {
/**
* @name InterTween
* @description The lightweight, fastest, smartest, effecient value interpolator with no-dependecy, zero-configuration and relative interpolation
* @author dalisoft (https://github.com/dalisoft)
* @license MIT-License
* First Release at 20 August 2017, by @dalisoft
*/
(function (root, factory) {
if (typeof undefined === 'function' && undefined.amd) {
undefined([], factory);
} else if ('object' !== 'undefined' && module.exports) {
module.exports = factory();
} else {
root.InterTween = factory();
}
}
(typeof(window) !== 'undefined' ? window : commonjsGlobal, function () {
// RegExp variables
var colorMatch = /rgb/g;
var isIncrementReqForColor = /argb/g;
// This RegExp (numRegExp) is original from @jkroso string tweening and optimized by @dalisoft
var numRegExp =
/\s+|([A-Za-z?().,{}:""[\]#]+)|([-+/*%]+=)?([-+*/%]+)?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var hexColor = /^#([0-9a-f]{6}|[0-9a-f]{3})$/i;
var trimRegExp = /\n|\r|\t/g;
var rgbMax = 255;
// Helpers
function s2f(val) {
var floatedVal = parseFloat(val);
return typeof floatedVal === "number" && !isNaN(floatedVal) ? floatedVal : val;
}
var isArray = Array.isArray;
function h2r_f(all, hex) {
var r;
var g;
var b;
if (hex.length === 3) {
r = hex[0];
g = hex[1];
b = hex[2];
hex = r + r + g + g + b + b;
}
var color = parseInt(hex, 16);
r = color >> 16 & rgbMax;
g = color >> 8 & rgbMax;
b = color & rgbMax;
return "rgb(" + r + "," + g + "," + b + ")";
}
function trim(str) {
return typeof str === "string" ? str.replace(trimRegExp, "") : str;
}
var relativeModes = {
'+=': 1,
'-=': 1,
'*=': 2,
'/=': 3,
'%=': 4
};
function r2n(s, e) {
if (typeof e === 'number') {
return e;
} else {
var rv = relativeModes[e.substr(0, 2)],
v = e.substr(2);
if (rv === 1) {
var e2 = e[0] + v;
return s + parseFloat(e2);
} else if (rv === 2) {
return s * +v;
} else if (rv === 3) {
return s / +v;
} else if (rv === 4) {
return s * (+v / 100);
}
}
return e;
}
var h2r = function (hex) {
return typeof hex !== 'string' ? hex : trim(hex)
.replace(hexColor, h2r_f);
};
function s2n(str) {
return h2r(str).match(numRegExp).map(s2f);
}
// Splitted functions
function stringTween(s, e, d) {
d = d !== undefined ? d : 10000;
if (!numRegExp.test(e))
{ return e; }
var sv = s2n(s);
var ev = s2n(e);
var uv = unitTween(sv, ev, d);
if (uv) {
return uv;
}
uv = null;
var cm = null;
var cmls = null;
var rv = [];
for (var i = 0, len = ev.length; i < len; i++) {
var ve = ev[i],
vs = sv[i];
rv[i] = typeof ve === 'string' && ve.indexOf('=') === 1 ? e : null;
if (isIncrementReqForColor.test(ve)) {
cm = i + 2;
cmls = i + 11;
} else if (colorMatch.test(ve)) {
cm = i;
cmls = i + 9;
}
ev[i] = vs === ve ? null : rv[i] !== null ? r2n(vs, ve) : typeof ve === 'number' ? ve - vs : ve;
}
return function (t) {
var str = '';
for (var i = 0, len = ev.length; i < len; i++) {
var a = sv[i],
b = ev[i],
r = rv[i];
str += typeof b === 'number' ? cm !== null && i > cm &&
i < cmls ? (a + b * t) | 0 : (((a + b * t) * d) |
0) / d : a;
if (t === 1 && r !== null) {
sv[i] += b;
ev[i] = r2n(sv[i], r);
}
}
return str;
}
}
function tweenThemTo(sv, ev) {
var vs = [];
for (var i = 0, len = sv.length; i < len; i++) {
var s = sv[i];
vs[i] = isArray(s) ? arrayTween(s, ev) : typeof s === 'object' ? objectTween(s, ev) : typeof s === 'string' ? stringTween(s, ev) : s;
}
return function (t) {
for (var i = 0, len = vs.length; i < len; i++) {
sv[i] = vs[i](t);
}
return sv;
}
}
function parseInterpolatables(sv, ev) {
var vs = [];
for (var i = 0, len = ev.length; i < len; i++) {
var e = ev[i];
vs[i] = mainTween(i === 0 ? sv : ev[i - 1], e);
}
var lastItem = ev[ev.length - 1];
vs.push(mainTween(lastItem, lastItem));
var endLength = vs.length - 1;
return function (t) {
var totalTime = t * endLength;
var roundedTime = Math.floor(totalTime);
var elapsed = totalTime - roundedTime;
var item = vs[roundedTime];
var interpolated = item(elapsed);
return interpolated;
};
}
function arrayTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
var s = sv.slice();
var rv = [];
for (var i = 0, len = ev.length; i < len; i++) {
var vs = s && s[i],
ve = ev[i];
rv[i] = typeof ve === 'string' && ve.indexOf('=') === 1 ? ve : null;
s[i] = ve.nodeType ? ve : ve.update ? ve : vs === ve ? null : isArray(ve) ?
isArray(vs) && ve.length === vs.length ? arrayTween(vs, ve, d) : parseInterpolatables(vs, ve) : isArray(vs) ? tweenThemTo(vs, ve) : typeof vs === 'object' ?
objectTween(vs, ve, d) : typeof vs === 'string' ?
stringTween(vs, ve, d) : vs !== undefined ? vs : ve;
ev[i] = rv[i] !== null ? r2n(
vs, ve) : ve;
}
var minLength = Math.min(sv.length, ev.length);
return function (t) {
for (var i = 0; i < minLength; i++) {
var a = s[i],
b = ev[i],
r = rv[i];
if (a === null || a === undefined)
{ continue; }
sv[i] = typeof a === 'number' ? (((a + (b - a) * t) * d) | 0) /
d : typeof a === 'function' ? a(t) : a && a.update ? a.update(t) : b && b.update ? b.update(t) : b;
if (r && t === 1) {
s[i] = b;
ev[i] = r2n(s[i], r);
}
}
return sv;
}
}
var units = ["px", "pt", "pc", "deg", "rad", "turn", "em", "ex", "cm", "mm", "dm", "inch", "in", "rem", "vw", "vh", "vmin", "vmax", "%"];
function unitTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
if (ev.length === 2 && sv.length === 2) {
var unidx = units.indexOf(ev[1]);
if (unidx !== -1) {
var s = +sv[0],
e = +ev[0],
u = ev[1],
r = typeof ev[0] === 'string' && ev[0].indexOf('=') === 1 ? ev[0] : null;
if (r) {
e = r2n(s, e);
}
return function (t) {
var v = ((((s + (e - s) * t) * d) | 0) / d) + u;
if (r && t === 1) {
s = e;
e = r2n(s, r);
}
return v;
}
}
}
return false;
}
function objectTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
var rv = {};
var s = {};
for (var i in ev) {
s[i] = sv && sv[i];
var vs = s[i],
ve = ev[i];
rv[i] = typeof ve === 'string' && ve.indexOf('=') === 1 ? ve : null;
s[i] = ve.nodeType ? ve : ve.update ? ve : vs === ve ? null : isArray(ve) ?
isArray(vs) && ve.length === vs.length ? arrayTween(vs, ve, d) : parseInterpolatables(vs, ve) : isArray(vs) ? tweenThemTo(vs, ve) : typeof vs === 'object' ?
objectTween(vs, ve, d) : typeof vs === 'string' ?
stringTween(vs, ve, d) : vs !== undefined ? vs : ve;
ev[i] = rv[i] !== null ? r2n(vs, ve) : ve;
}
return function (t) {
for (var i in ev) {
var a = s[i],
b = ev[i],
r = rv[i];
if (a === null || a === undefined)
{ continue; }
sv[i] = typeof a === 'number' ? (((a + (b - a) * t) * d) | 0) /
d : typeof a === 'function' ? a(t) : a && a.update ? a.update(t) : b && b.update ? b.update(t) : b;
if (r && t === 1) {
s[i] = b;
ev[i] = r2n(s[i], r);
}
}
return sv;
}
}
function mainTween(sv, ev, d) {
d = d !== undefined ? d : 10000;
var rv = typeof(ev) === 'string' && typeof sv === 'number' && ev.indexOf('=') === 1 ? ev : null;
if (rv) {
ev = r2n(sv, rv);
}
return ev.nodeType ? ev : sv.nodeType ? sv : isArray(ev) ? isArray(sv) && sv.length === ev.length ? arrayTween(sv, ev, d) : parseInterpolatables(sv, ev) : isArray(sv) ? tweenThemTo(sv, ev) : typeof ev === 'object' ?
objectTween(sv, ev, d) : typeof ev === 'string' ? stringTween(sv, ev, d) :
typeof ev === 'function' ? ev : function (t) {
var vv = typeof ev === 'number' ? (((sv + (ev - sv) * t) *
d) | 0) / d : sv;
if (rv && t === 1) {
sv += ev;
ev = r2n(sv, rv);
}
return vv;
}
}
return mainTween;
}));
});
var Store = {};
var NodeCache = function (node, tween) {
if (!node) { return tween }
if (Store[node]) {
if (tween) {
return Object.assign(Store[node], tween)
}
return Store[node]
}
Store[node] = tween;
return Store[node]
};
var EventClass = function EventClass () {
this._events = {};
};
EventClass.prototype.on = function on (event, callback) {
if (!this._events[event]) {
this._events[event] = [];
}
this._events[event].push(callback);
return this
};
EventClass.prototype.once = function once (event, callback) {
var this$1 = this;
if (!this._events[event]) {
this._events[event] = [];
}
var ref = this;
var _events = ref._events;
var spliceIndex = _events[event].length;
this._events[event].push(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
callback.apply(this$1, args);
_events[event].splice(spliceIndex, 1);
});
return this
};
EventClass.prototype.off = function off (event, callback) {
var ref = this;
var _events = ref._events;
if (event === undefined || !_events[event]) {
return this
}
if (callback) {
this._events[event] = this._events[event].filter(function (cb) { return cb !== callback; });
} else {
this._events[event].length = 0;
}
return this
};
EventClass.prototype.emit = function emit (event, arg1, arg2, arg3, arg4) {
var ref = this;
var _events = ref._events;
var _event = _events[event];
if (!_event || !_event.length) {
return this
}
var i = 0;
var len = _event.length;
for (; i < len; i++) {
_event[i](arg1, arg2, arg3, arg4);
}
};
// Events list
var EVENT_UPDATE = 'update';
var EVENT_COMPLETE = 'complete';
var EVENT_START = 'start';
var EVENT_REPEAT = 'repeat';
var EVENT_REVERSE = 'reverse';
var EVENT_PAUSE = 'pause';
var EVENT_PLAY = 'play';
var EVENT_RS = 'restart';
var EVENT_STOP = 'stop';
var EVENT_SEEK = 'seek';
var _id = 0; // Unique ID
var Tween = (function (EventClass$$1) {
function Tween (node, object) {
EventClass$$1.call(this);
this.id = _id++;
if (typeof node !== 'undefined' && !object && !node.nodeType) {
object = this.object = node;
node = null;
} else if (typeof node !== 'undefined') {
this.node = node;
if (typeof object === 'object') {
object = this.object = NodeCache(node, object);
} else {
this.object = object;
}
}
this._valuesEnd = null;
this._duration = 1000;
this._easingFunction = Easing.Linear.None;
this._startTime = 0;
this._delayTime = 0;
this._repeat = 0;
this._r = 0;
this._isPlaying = false;
this._yoyo = false;
this._reversed = false;
this._onStartCallbackFired = false;
this._pausedTime = null;
this._isFinite = true;
return this
}
if ( EventClass$$1 ) Tween.__proto__ = EventClass$$1;
Tween.prototype = Object.create( EventClass$$1 && EventClass$$1.prototype );
Tween.prototype.constructor = Tween;
Tween.prototype.isPlaying = function isPlaying () {
return this._isPlaying
};
Tween.prototype.isStarted = function isStarted () {
return this._onStartCallbackFired
};
Tween.prototype.reverse = function reverse () {
var ref = this;
var _reversed = ref._reversed;
this._reversed = !_reversed;
return this
};
Tween.prototype.reversed = function reversed () {
return this._reversed
};
Tween.prototype.pause = function pause () {
if (!this._isPlaying) {
return this
}
this._isPlaying = false;
remove(this);
this._pausedTime = now();
return this.emit(EVENT_PAUSE, this.object)
};
Tween.prototype.play = function play () {
if (this._isPlaying) {
return this
}
this._isPlaying = true;
this._startTime += now() - this._pausedTime;
add(this);
this._pausedTime = now();
return this.emit(EVENT_PLAY, this.object)
};
Tween.prototype.restart = function restart (noDelay) {
this._repeat = this._r;
this._startTime = now() + (noDelay ? 0 : this._delayTime);
if (!this._isPlaying) {
add(this);
}
return this.emit(EVENT_RS, this._object)
};
Tween.prototype.seek = function seek (time, keepPlaying) {
this._startTime = now() + Math.max(0, Math.min(
time, this._duration));
this.emit(EVENT_SEEK, time, this._object);
return keepPlaying ? this : this.pause()
};
Tween.prototype.duration = function duration (amount) {
this._duration = typeof (amount) === 'function' ? amount(this._duration) : amount;
return this
};
Tween.prototype.to = function to (properties, duration) {
var this$1 = this;
if ( duration === void 0 ) duration = 1000;
this._valuesEnd = properties;
if (typeof duration === 'number' || typeof (duration) === 'function') {
this._duration = typeof (duration) === 'function' ? duration(this._duration) : duration;
} else if (typeof duration === 'object') {
for (var prop in duration) {
if (this$1[prop]) {
(ref = this$1)[prop].apply(ref, (Array.isArray(duration) ? duration : [duration]));
}
}
}
return this
var ref;
};
Tween.prototype.render = function render () {
var this$1 = this;
if (this._rendered) {
return this
}
var ref = this;
var _valuesEnd = ref._valuesEnd;
var object = ref.object;
var Renderer = ref.Renderer;
if (typeof _valuesEnd === 'object') {
for (var property in _valuesEnd) {
if (Plugins[property]) {
_valuesEnd[property] = new Plugins[property](this$1, object[property], _valuesEnd[property]);
}
}
}
if (Renderer && this.node) {
this.__render = new Renderer(this, object, _valuesEnd);
}
return this
};
Tween.prototype.start = function start (time) {
this._startTime = time !== undefined ? time : now();
this._startTime += this._delayTime;
add(this);
this._isPlaying = true;
return this
};
Tween.prototype.stop = function stop () {
var ref = this;
var _isPlaying = ref._isPlaying;
var object = ref.object;
if (!_isPlaying) {
return this
}
remove(this);
this._isPlaying = false;
return this.emit(EVENT_STOP, object)
};
Tween.prototype.end = function end () {
var ref = this;
var _startTime = ref._startTime;
var _duration = ref._duration;
return this.update(_startTime + _duration)
};
Tween.prototype.delay = function delay (amount) {
this._delayTime = typeof (amount) === 'function' ? amount(this._delayTime) : amount;
this._startTime += this._delayTime;
return this
};
Tween.prototype.repeat = function repeat (amount) {
this._repeat = typeof (amount) === 'function' ? amount(this._repeat) : amount;
this._r = this._repeat;
this._isFinite = isFinite(amount);
return this
};
Tween.prototype.repeatDelay = function repeatDelay (amount) {
this._repeatDelayTime = typeof (amount) === 'function' ? amount(this._repeatDelayTime) : amount;
return this
};
Tween.prototype.reverseDelay = function reverseDelay (amount) {
this._reverseDelayTime = typeof (amount) === 'function' ? amount(this._reverseDelayTime) : amount;
return this
};
Tween.prototype.yoyo = function yoyo (state) {
this._yoyo = typeof (state) === 'function' ? state(this._yoyo) : state;
return this
};
Tween.prototype.easing = function easing (fn) {
this._easingFunction = fn;
return this
};
Tween.prototype.reassignValues = function reassignValues () {
var ref = this;
var _valuesEnd = ref._valuesEnd;
var object = ref.object;
var v0 = _valuesEnd(0);
if (typeof v0 === 'object') {
var isArr = Array.isArray(v0);
for (var property in v0) {
if (isArr) { property *= 1; }
object[property] = v0[property];
}
}
return this
};
Tween.prototype.get = function get$$1 (time) {
this.update(time);
return this.object
};
Tween.prototype.update = function update$$1 (time, preserve) {
var ref = this;
var _onStartCallbackFired = ref._onStartCallbackFired;
var _easingFunction = ref._easingFunction;
var _repeat = ref._repeat;
var _repeatDelayTime = ref._repeatDelayTime;
var _reverseDelayTime = ref._reverseDelayTime;
var _yoyo = ref._yoyo;
var _reversed = ref._reversed;
var _startTime = ref._startTime;
var _duration = ref._duration;
var _valuesEnd = ref._valuesEnd;
var object = ref.object;
var _isFinite = ref._isFinite;
var __render = ref.__render;
var elapsed;
var value;
time = time !== undefined ? time : now();
if (time < _startTime) {
return true
}
if (!_onStartCallbackFired) {
if (!this._rendered) {
this.render();
this._rendered = true;
if (typeof _valuesEnd !== 'function') {
this._valuesEnd = _valuesEnd = intertween(object, _valuesEnd);
}
}
this.emit(EVENT_START, object);
this._onStartCallbackFired = true;
}
elapsed = (time - _startTime) / _duration;
elapsed = elapsed > 1 ? 1 : elapsed;
elapsed = _reversed ? 1 - elapsed : elapsed;
value = _easingFunction(elapsed);
object = _valuesEnd(value);
if (__render) {
__render.update(object, elapsed);
}
this.emit(EVENT_UPDATE, object, value, elapsed);
if (elapsed === 1 || (_reversed && elapsed === 0)) {
if (_repeat) {
if (_isFinite) {
this._repeat--;
}
if (_yoyo) {
this._reversed = !_reversed;
}
if (!_reversed && _repeatDelayTime) {
this._startTime = time + _repeatDelayTime;
} else if (_reversed && _reverseDelayTime) {
this._startTime = time + _reverseDelayTime;
} else {
this._startTime = time;
}
return true
} else {
if (!preserve) {
remove(this);
}
this.emit(EVENT_COMPLETE, object);
this._repeat = this._r;
return false
}
}
return true
};
return Tween;
}(EventClass));
var PlaybackPosition = function PlaybackPosition () {
this.totalTime = 0;
this.labels = [];
this.offsets = [];
};
PlaybackPosition.prototype.parseLabel = function parseLabel (name, offset) {
var ref = this;
var offsets = ref.offsets;
var labels = ref.labels;
var i = labels.indexOf(name);
if (typeof name === 'string' && name.indexOf('=') !== -1 && !offset && i === -1) {
var rty = name.substr(name.indexOf('=') - 1, 2);
var rt = name.split(rty);
offset = rt.length === 2 ? rty + rt[1] : null;
name = rt[0];
i = labels.indexOf(name);
}
if (i !== -1 && name) {
var currOffset = offsets[i] || 0;
if (typeof offset === 'number') {
currOffset = offset;
} else if (typeof offset === 'string') {
if (offset.indexOf('=') !== -1) {
var type = offset.charAt(0);
offset = Number(offset.substr(2));
if (type === '+' || type === '-') {
currOffset += parseFloat(type + offset);
} else if (type === '*') {
currOffset *= offset;
} else if (type === '/') {
currOffset /= offset;
} else if (type === '%') {
currOffset *= offset / 100;
}
}
}
return currOffset
}
return typeof offset === 'number' ? offset : 0
};
PlaybackPosition.prototype.addLabel = function addLabel (name, offset) {
this.labels.push(name);
this.offsets.push(this.parseLabel(name, offset));
return this
};
PlaybackPosition.prototype.setLabel = function setLabel (name, offset) {
var i = this.labels.indexOf(name);
if (i !== -1) {
this.offsets.splice(i, 1, this.parseLabel(name, offset));
}
return this
};
PlaybackPosition.prototype.eraseLabel = function eraseLabel (name) {
var i = this.labels.indexOf(name);
if (i !== -1) {
this.labels.splice(i, 1);
this.offsets.splice(i, 1);
}
return this
};
var _id$1 = 0;
var Timeline = (function (Tween$$1) {
function Timeline (params) {
Tween$$1.call(this);
this._totalDuration = 0;
this._startTime = now();
this._tweens = {};
this._elapsed = 0;
this._id = _id$1++;
this._defaultParams = params;
this.position = new PlaybackPosition();
this.position.addLabel('afterLast', this._totalDuration);
this.position.addLabel('afterInit', this._startTime);
return this
}
if ( Tween$$1 ) Timeline.__proto__ = Tween$$1;
Timeline.prototype = Object.create( Tween$$1 && Tween$$1.prototype );
Timeline.prototype.constructor = Timeline;
Timeline.prototype.addLabel = function addLabel (name, offset) {
this.position.addLabel(name, offset);
return this
};
Timeline.prototype.map = function map (fn) {
var this$1 = this;
for (var tween in this$1._tweens) {
var _tween = this$1._tweens[tween];
fn(_tween, +tween);
this$1._totalDuration = Math.max(this$1._totalDuration, _tween._duration + _tween._startTime);
}
return this
};
Timeline.prototype.add = function add$$1 (tween, position) {
var this$1 = this;
if (Array.isArray(tween)) {
tween.map(function (_tween) {
this$1.add(_tween, position);
});
return this
} else if (typeof tween === 'object' && !(tween instanceof Tween$$1)) {
tween = new Tween$$1(tween.from).to(tween.to, tween);
}
var ref = this;
var _defaultParams = ref._defaultParams;
var _totalDuration = ref._totalDuration;
if (_defaultParams) {
for (var method in _defaultParams) {
tween[method](_defaultParams[method]);
}
}
var offset = typeof position === 'number' ? position : this.position.parseLabel(typeof position !== 'undefined' ? position : 'afterLast', null);
tween._startTime = this._startTime;
tween._startTime += offset;
this._totalDuration = Math.max(_totalDuration, tween._startTime + tween._delayTime + tween._duration);
this._tweens[tween.id] = tween;
this.position.setLabel('afterLast', this._totalDuration);
return this
};
Timeline.prototype.restart = function restart () {
this._startTime += now();
add(this);
return this.emit(EVENT_RS)
};
Timeline.prototype.easing = function easing (easing$1) {
return this.map(function (tween) { return tween.easing(easing$1); })
};
Timeline.prototype.interpolation = function interpolation (interpolation$1) {
return this.map(function (tween) { return tween.interpolation(interpolation$1); })
};
Timeline.prototype.reverse = function reverse () {
this._reversed = !this._reversed;
return this.emit(EVENT_REVERSE)
};
Timeline.prototype.update = function update$$1 (time) {
var ref = this;
var _tweens = ref._tweens;
var _totalDuration = ref._totalDuration;
var _repeatDelayTime = ref._repeatDelayTime;
var _reverseDelayTime = ref._reverseDelayTime;
var _startTime = ref._startTime;
var _reversed = ref._reversed;
var _yoyo = ref._yoyo;
var _repeat = ref._repeat;
var _isFinite = ref._isFinite;
if (time < _startTime) {
return true
}
var elapsed = Math.min(1, Math.max(0, (time - _startTime) / _totalDuration));
elapsed = _reversed ? 1 - elapsed : elapsed;
this._elapsed = elapsed;
var timing = time - _startTime;
var _timing = _reversed ? _totalDuration - timing : timing;
for (var tween in _tweens) {
var _tween = _tweens[tween];
if (_tween.skip) {
_tween.skip = false;
} else if (_tween.update(_timing)) {
continue
} else {
_tween.skip = true;
}
}
this.emit(EVENT_UPDATE, elapsed, timing);
if (elapsed === 1 || (_reversed && elapsed === 0)) {
if (_repeat) {
if (_isFinite) {
this._repeat--;
}
this.emit(_reversed ? EVENT_REVERSE : EVENT_REPEAT);
if (_yoyo) {
this.reverse();
}
if (!_reversed && _repeatDelayTime) {
this._startTime += _totalDuration + _repeatDelayTime;
} else if (_reversed && _reverseDelayTime) {
this._startTime += _totalDuration + _reverseDelayTime;
} else {
this._startTime += _totalDuration;
}
for (var tween$1 in _tweens) {
var _tween$1 = _tweens[tween$1];
if (_tween$1.skip) {
_tween$1.skip = false;
}
_tween$1.reassignValues();
}
return true
} else {
this.emit(EVENT_COMPLETE);
this._repeat = this._r;
for (var tween$2 in _tweens) {
var _tween$2 = _tweens[tween$2];
if (_tween$2.skip) {
_tween$2.skip = false;
}
}
return false
}
}
return true
};
Timeline.prototype.elapsed = function elapsed (value) {
return value !== undefined ? this.update(value * this._totalDuration) : this._elapsed
};
Timeline.prototype.seek = function seek (value) {
return this.update(value < 1.1 ? value * this._totalDuration : value)
};
return Timeline;
}(Tween));
exports.Plugins = Plugins;
exports.Interpolator = intertween;
exports.has = has;
exports.get = get;
exports.getAll = getAll;
exports.removeAll = removeAll;
exports.remove = remove;
exports.add = add;
exports.now = now;
exports.update = update;
exports.autoPlay = autoPlay;
exports.isRunning = isRunning;
exports.Tween = Tween;
exports.Easing = Easing;
exports.Timeline = Timeline;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=Tween.js.map
| cdnjs/cdnjs | ajax/libs/es6-tween/3.5.0/Tween.js | JavaScript | mit | 37,480 |
/* arch/arm/mach-msm/qdsp6/q6audio_devices.h
*
* Copyright (C) 2009 Google, Inc.
* Author: Brian Swetland <[email protected]>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
struct q6_device_info {
uint32_t id;
uint32_t cad_id;
uint32_t path;
uint32_t rate;
uint8_t dir;
uint8_t codec;
uint8_t hw;
};
#define Q6_ICODEC_RX 0
#define Q6_ICODEC_TX 1
#define Q6_ECODEC_RX 2
#define Q6_ECODEC_TX 3
#define Q6_SDAC_RX 6
#define Q6_SDAC_TX 7
#define Q6_CODEC_NONE 255
#define Q6_TX 1
#define Q6_RX 2
#define Q6_TX_RX 3
#define Q6_HW_HANDSET 0
#define Q6_HW_HEADSET 1
#define Q6_HW_SPEAKER 2
#define Q6_HW_TTY 3
#define Q6_HW_BT_SCO 4
#define Q6_HW_BT_A2DP 5
#define Q6_HW_COUNT 6
#define CAD_HW_DEVICE_ID_HANDSET_MIC 0x01
#define CAD_HW_DEVICE_ID_HANDSET_SPKR 0x02
#define CAD_HW_DEVICE_ID_HEADSET_MIC 0x03
#define CAD_HW_DEVICE_ID_HEADSET_SPKR_MONO 0x04
#define CAD_HW_DEVICE_ID_HEADSET_SPKR_STEREO 0x05
#define CAD_HW_DEVICE_ID_SPKR_PHONE_MIC 0x06
#define CAD_HW_DEVICE_ID_SPKR_PHONE_MONO 0x07
#define CAD_HW_DEVICE_ID_SPKR_PHONE_STEREO 0x08
#define CAD_HW_DEVICE_ID_BT_SCO_MIC 0x09
#define CAD_HW_DEVICE_ID_BT_SCO_SPKR 0x0A
#define CAD_HW_DEVICE_ID_BT_A2DP_SPKR 0x0B
#define CAD_HW_DEVICE_ID_TTY_HEADSET_MIC 0x0C
#define CAD_HW_DEVICE_ID_TTY_HEADSET_SPKR 0x0D
#define CAD_HW_DEVICE_ID_DEFAULT_TX 0x0E
#define CAD_HW_DEVICE_ID_DEFAULT_RX 0x0F
#define CAD_HW_DEVICE_ID_BTDSP_SCO_MIC 0x16
#define CAD_HW_DEVICE_ID_BTDSP_SCO_SPKR 0x17
#define CAD_HW_DEVICE_ID_BTC_SCO_MIC 0x18
#define CAD_HW_DEVICE_ID_BTC_SCO_SPKR 0x19
#define CAD_HW_DEVICE_ID_BTCDSP_SCO_MIC 0x1A
#define CAD_HW_DEVICE_ID_BTCDSP_SCO_SPKR 0x1B
#define CAD_HW_DEVICE_ID_VREC_SPKR_MIC 0x1C
#define CAD_HW_DEVICE_ID_SPKR_PHONE_DUAL_MIC_BROADSIDE 0x2B
#define CAD_HW_DEVICE_ID_SPKR_PHONE_DUAL_MIC_ENDFIRE 0x2D
#define CAD_HW_DEVICE_ID_HANDSET_DUAL_MIC_BROADSIDE 0x2C
#define CAD_HW_DEVICE_ID_HANDSET_DUAL_MIC_ENDFIRE 0x2E
/* Logical Device to indicate A2DP routing */
#define CAD_HW_DEVICE_ID_BT_A2DP_TX 0x10
#define CAD_HW_DEVICE_ID_HEADSET_MONO_PLUS_SPKR_MONO_RX 0x11
#define CAD_HW_DEVICE_ID_HEADSET_MONO_PLUS_SPKR_STEREO_RX 0x12
#define CAD_HW_DEVICE_ID_HEADSET_STEREO_PLUS_SPKR_MONO_RX 0x13
#define CAD_HW_DEVICE_ID_HEADSET_STEREO_PLUS_SPKR_STEREO_RX 0x14
#define CAD_HW_DEVICE_ID_VOICE 0x15
#define CAD_HW_DEVICE_ID_I2S_RX 0x20
#define CAD_HW_DEVICE_ID_I2S_TX 0x21
/* AUXPGA */
#define CAD_HW_DEVICE_ID_HEADSET_SPKR_STEREO_LB 0x22
#define CAD_HW_DEVICE_ID_HEADSET_SPKR_MONO_LB 0x23
#define CAD_HW_DEVICE_ID_SPEAKER_SPKR_STEREO_LB 0x24
#define CAD_HW_DEVICE_ID_SPEAKER_SPKR_MONO_LB 0x25
#define CAD_HW_DEVICE_ID_NULL_RX 0x2A
#define CAD_HW_DEVICE_ID_MAX_NUM 0x2F
#define CAD_HW_DEVICE_ID_INVALID 0xFF
#define CAD_RX_DEVICE 0x00
#define CAD_TX_DEVICE 0x01
static struct q6_device_info q6_audio_devices[] = {
{
.id = ADSP_AUDIO_DEVICE_ID_HANDSET_SPKR,
.cad_id = CAD_HW_DEVICE_ID_HANDSET_SPKR,
.path = ADIE_PATH_HANDSET_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_HANDSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_HEADSET_SPKR_MONO,
.cad_id = CAD_HW_DEVICE_ID_HEADSET_SPKR_MONO,
.path = ADIE_PATH_HEADSET_MONO_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_HEADSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_HEADSET_SPKR_STEREO,
.cad_id = CAD_HW_DEVICE_ID_HEADSET_SPKR_STEREO,
.path = ADIE_PATH_HEADSET_STEREO_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_HEADSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_MONO,
.cad_id = CAD_HW_DEVICE_ID_SPKR_PHONE_MONO,
.path = ADIE_PATH_SPEAKER_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_STEREO,
.cad_id = CAD_HW_DEVICE_ID_SPKR_PHONE_STEREO,
.path = ADIE_PATH_SPEAKER_STEREO_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_MONO_W_MONO_HEADSET,
.cad_id = CAD_HW_DEVICE_ID_HEADSET_MONO_PLUS_SPKR_MONO_RX,
.path = ADIE_PATH_SPKR_MONO_HDPH_MONO_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_MONO_W_STEREO_HEADSET,
.cad_id = CAD_HW_DEVICE_ID_HEADSET_STEREO_PLUS_SPKR_MONO_RX,
.path = ADIE_PATH_SPKR_MONO_HDPH_STEREO_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_STEREO_W_MONO_HEADSET,
.cad_id = CAD_HW_DEVICE_ID_HEADSET_MONO_PLUS_SPKR_STEREO_RX,
.path = ADIE_PATH_SPKR_STEREO_HDPH_MONO_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_STEREO_W_STEREO_HEADSET,
.cad_id = CAD_HW_DEVICE_ID_HEADSET_STEREO_PLUS_SPKR_STEREO_RX,
.path = ADIE_PATH_SPKR_STEREO_HDPH_STEREO_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_TTY_HEADSET_SPKR,
.cad_id = CAD_HW_DEVICE_ID_TTY_HEADSET_SPKR,
.path = ADIE_PATH_TTY_HEADSET_RX,
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ICODEC_RX,
.hw = Q6_HW_TTY,
},
{
.id = ADSP_AUDIO_DEVICE_ID_HANDSET_MIC,
.cad_id = CAD_HW_DEVICE_ID_HANDSET_MIC,
.path = ADIE_PATH_HANDSET_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_HANDSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_HEADSET_MIC,
.cad_id = CAD_HW_DEVICE_ID_HEADSET_MIC,
.path = ADIE_PATH_HEADSET_MONO_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_HEADSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_MIC,
.cad_id = CAD_HW_DEVICE_ID_SPKR_PHONE_MIC,
.path = ADIE_PATH_SPEAKER_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_MIC,
.cad_id = CAD_HW_DEVICE_ID_VREC_SPKR_MIC,
.path = ADIE_PATH_SPEAKER_TX,
.rate = 16000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_HANDSET_DUAL_MIC,
.cad_id = CAD_HW_DEVICE_ID_HANDSET_DUAL_MIC_ENDFIRE,
.path = ADIE_CODEC_HANDSET_SPKR_EF_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_HANDSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_HANDSET_DUAL_MIC,
.cad_id = CAD_HW_DEVICE_ID_HANDSET_DUAL_MIC_BROADSIDE,
.path = ADIE_CODEC_HANDSET_SPKR_BS_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_HANDSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_DUAL_MIC,
.cad_id = CAD_HW_DEVICE_ID_SPKR_PHONE_DUAL_MIC_ENDFIRE,
.path = ADIE_CODEC_HANDSET_SPKR_EF_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_SPKR_PHONE_DUAL_MIC,
.cad_id = CAD_HW_DEVICE_ID_SPKR_PHONE_DUAL_MIC_BROADSIDE,
.path = ADIE_CODEC_HANDSET_SPKR_BS_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_TTY_HEADSET_MIC,
.cad_id = CAD_HW_DEVICE_ID_TTY_HEADSET_MIC,
.path = ADIE_PATH_TTY_HEADSET_TX,
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ICODEC_TX,
.hw = Q6_HW_HEADSET,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_SPKR,
.cad_id = CAD_HW_DEVICE_ID_BT_SCO_SPKR,
.path = 0, /* No need to set ADIE path for Bluetooth. */
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ECODEC_RX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_A2DP_SPKR,
.cad_id = CAD_HW_DEVICE_ID_BT_A2DP_SPKR,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ECODEC_RX,
.hw = Q6_HW_BT_A2DP,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_MIC,
.cad_id = CAD_HW_DEVICE_ID_BT_SCO_MIC,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ECODEC_TX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_SPKR,
.cad_id = CAD_HW_DEVICE_ID_BTDSP_SCO_SPKR,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ECODEC_RX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_SPKR,
.cad_id = CAD_HW_DEVICE_ID_BTC_SCO_SPKR,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ECODEC_RX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_SPKR,
.cad_id = CAD_HW_DEVICE_ID_BTCDSP_SCO_SPKR,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_ECODEC_RX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_MIC,
.cad_id = CAD_HW_DEVICE_ID_BTDSP_SCO_MIC,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ECODEC_TX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_MIC,
.cad_id = CAD_HW_DEVICE_ID_BTC_SCO_MIC,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ECODEC_TX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_BT_SCO_MIC,
.cad_id = CAD_HW_DEVICE_ID_BTCDSP_SCO_MIC,
.path = 0, /* No need to set ADIE path for Bluetooth */
.rate = 8000,
.dir = Q6_TX,
.codec = Q6_ECODEC_TX,
.hw = Q6_HW_BT_SCO,
},
{
.id = ADSP_AUDIO_DEVICE_ID_I2S_SPKR,
.cad_id = CAD_HW_DEVICE_ID_I2S_RX,
.path = 0, /* No need to set ADIE path for I2S. */
.rate = 48000,
.dir = Q6_RX,
.codec = Q6_SDAC_RX,
.hw = Q6_HW_SPEAKER,
},
{
.id = ADSP_AUDIO_DEVICE_ID_I2S_MIC,
.cad_id = CAD_HW_DEVICE_ID_I2S_TX,
.path = 0, /* No need to set ADIE path for I2S. */
.rate = 16000,
.dir = Q6_TX,
.codec = Q6_SDAC_TX,
.hw = Q6_HW_SPEAKER,
},
{
.id = 0,
.cad_id = 0,
.path = 0,
.rate = 8000,
.dir = 0,
.codec = Q6_CODEC_NONE,
.hw = 0,
},
};
| nobodyAtall/nAa-kernel-ics | arch/arm/mach-msm/qdsp6/q6audio_devices.h | C | gpl-2.0 | 10,481 |
<?php
return array(
/**
* Menu items and titles
*/
'messages' => "Wiadomości",
'messages:unreadcount' => "%s nieprzeczytanych",
'messages:back' => "wróć do wiadomości",
'messages:user' => "Skrzynka odbiorcza użytkownika %s",
'messages:posttitle' => "Wiadomości użytkownika %s: %s",
'messages:inbox' => "Skrzynka odbiorcza",
'messages:sent' => "Wysłane",
'messages:message' => "Wiadomość",
'messages:title' => "Tytuł",
'messages:to:help' => "Wpisz nazwę adresata.",
'messages:replying' => "Wiadomość w odpowiedzi na",
'messages:inbox' => "Skrzynka odbiorcza",
'messages:sendmessage' => "Wyślij wiadomość",
'messages:add' => "Utwórz wiadomość",
'messages:sentmessages' => "Wysłane wiadomości",
'messages:recent' => "Najnowsze wiadomości",
'messages:original' => "Oryginalna wiadomość",
'messages:yours' => "Twoja wiadomość",
'messages:toggle' => 'Przełącz wszystkie',
'messages:markread' => 'Oznacz jako przeczytane',
'messages:recipient' => 'Wybierz adresata…',
'messages:to_user' => 'Do: %s',
'messages:new' => 'Nowa wiadomość',
'notification:method:site' => 'Strona',
'messages:error' => 'Wystąpił problem w trakcie zapisu wiadomości. Proszę spróbować ponownie.',
'item:object:messages' => 'Wiadomości',
/**
* Status messages
*/
'messages:posted' => "Twoja wiadomość została wysłana.",
'messages:success:delete:single' => 'Usunięto wiadomość',
'messages:success:delete' => 'Usunięto wiadomości',
'messages:success:read' => 'Oznaczono wiadomości jako przeczytane',
'messages:error:messages_not_selected' => 'Nie zaznaczono wiadomości',
'messages:error:delete:single' => 'Nie można usunąć tej wiadomości',
/**
* Email messages
*/
'messages:email:subject' => 'Masz nową wiadomość!',
'messages:email:body' => "Masz nową wiadomość od %s. Oto ona:
%s
Aby zobaczyć twoje wiadomości, kliknij tutaj:
%s
Aby wysłać wiadomość do %s, kliknij tutaj:
%s
Nie możesz odpowiedzieć na ten e-mail.",
/**
* Error messages
*/
'messages:blank' => "Przykro nam, ale musisz jednak coś wpisać w treści wiadomości zanim ją zapiszesz.",
'messages:notfound' => "Przykro nam, nie można znaleźć określonej wiadomości.",
'messages:notdeleted' => "Przykro nam, nie można usunąć tej wiadomości.",
'messages:nopermission' => "Nie masz uprawnień, aby modyfikować tą wiadomość.",
'messages:nomessages' => "Brak wiadomości.",
'messages:user:nonexist' => "Nie odnaleziono adresata w bazie danych użytkowników.",
'messages:user:blank' => "Musisz wybrać adresata wiadomości.",
'messages:user:self' => "Nie można wysłać wiadomości do samego siebie.",
'messages:deleted_sender' => 'Usunięty użytkownik',
); | gnumdk/Elgg | mod/messages/languages/pl.php | PHP | gpl-2.0 | 2,751 |
/* Fetch the version that defines glob64 as an alias. */
#include <sysdeps/wordsize-64/glob.c>
| VincentS/glibc | sysdeps/nacl/glob.c | C | gpl-2.0 | 96 |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* GRE over IPv6 protocol decoder.
*
* Authors: Dmitry Kozlov ([email protected])
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/in.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/if_arp.h>
#include <linux/init.h>
#include <linux/in6.h>
#include <linux/inetdevice.h>
#include <linux/igmp.h>
#include <linux/netfilter_ipv4.h>
#include <linux/etherdevice.h>
#include <linux/if_ether.h>
#include <linux/hash.h>
#include <linux/if_tunnel.h>
#include <linux/ip6_tunnel.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/ip_tunnels.h>
#include <net/icmp.h>
#include <net/protocol.h>
#include <net/addrconf.h>
#include <net/arp.h>
#include <net/checksum.h>
#include <net/dsfield.h>
#include <net/inet_ecn.h>
#include <net/xfrm.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/rtnetlink.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
#include <net/ip6_tunnel.h>
#include <net/gre.h>
#include <net/erspan.h>
#include <net/dst_metadata.h>
static bool log_ecn_error = true;
module_param(log_ecn_error, bool, 0644);
MODULE_PARM_DESC(log_ecn_error, "Log packets received with corrupted ECN");
#define IP6_GRE_HASH_SIZE_SHIFT 5
#define IP6_GRE_HASH_SIZE (1 << IP6_GRE_HASH_SIZE_SHIFT)
static unsigned int ip6gre_net_id __read_mostly;
struct ip6gre_net {
struct ip6_tnl __rcu *tunnels[4][IP6_GRE_HASH_SIZE];
struct ip6_tnl __rcu *collect_md_tun;
struct ip6_tnl __rcu *collect_md_tun_erspan;
struct net_device *fb_tunnel_dev;
};
static struct rtnl_link_ops ip6gre_link_ops __read_mostly;
static struct rtnl_link_ops ip6gre_tap_ops __read_mostly;
static struct rtnl_link_ops ip6erspan_tap_ops __read_mostly;
static int ip6gre_tunnel_init(struct net_device *dev);
static void ip6gre_tunnel_setup(struct net_device *dev);
static void ip6gre_tunnel_link(struct ip6gre_net *ign, struct ip6_tnl *t);
static void ip6gre_tnl_link_config(struct ip6_tnl *t, int set_mtu);
static void ip6erspan_tnl_link_config(struct ip6_tnl *t, int set_mtu);
/* Tunnel hash table */
/*
4 hash tables:
3: (remote,local)
2: (remote,*)
1: (*,local)
0: (*,*)
We require exact key match i.e. if a key is present in packet
it will match only tunnel with the same key; if it is not present,
it will match only keyless tunnel.
All keysless packets, if not matched configured keyless tunnels
will match fallback tunnel.
*/
#define HASH_KEY(key) (((__force u32)key^((__force u32)key>>4))&(IP6_GRE_HASH_SIZE - 1))
static u32 HASH_ADDR(const struct in6_addr *addr)
{
u32 hash = ipv6_addr_hash(addr);
return hash_32(hash, IP6_GRE_HASH_SIZE_SHIFT);
}
#define tunnels_r_l tunnels[3]
#define tunnels_r tunnels[2]
#define tunnels_l tunnels[1]
#define tunnels_wc tunnels[0]
/* Given src, dst and key, find appropriate for input tunnel. */
static struct ip6_tnl *ip6gre_tunnel_lookup(struct net_device *dev,
const struct in6_addr *remote, const struct in6_addr *local,
__be32 key, __be16 gre_proto)
{
struct net *net = dev_net(dev);
int link = dev->ifindex;
unsigned int h0 = HASH_ADDR(remote);
unsigned int h1 = HASH_KEY(key);
struct ip6_tnl *t, *cand = NULL;
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
int dev_type = (gre_proto == htons(ETH_P_TEB) ||
gre_proto == htons(ETH_P_ERSPAN) ||
gre_proto == htons(ETH_P_ERSPAN2)) ?
ARPHRD_ETHER : ARPHRD_IP6GRE;
int score, cand_score = 4;
struct net_device *ndev;
for_each_ip_tunnel_rcu(t, ign->tunnels_r_l[h0 ^ h1]) {
if (!ipv6_addr_equal(local, &t->parms.laddr) ||
!ipv6_addr_equal(remote, &t->parms.raddr) ||
key != t->parms.i_key ||
!(t->dev->flags & IFF_UP))
continue;
if (t->dev->type != ARPHRD_IP6GRE &&
t->dev->type != dev_type)
continue;
score = 0;
if (t->parms.link != link)
score |= 1;
if (t->dev->type != dev_type)
score |= 2;
if (score == 0)
return t;
if (score < cand_score) {
cand = t;
cand_score = score;
}
}
for_each_ip_tunnel_rcu(t, ign->tunnels_r[h0 ^ h1]) {
if (!ipv6_addr_equal(remote, &t->parms.raddr) ||
key != t->parms.i_key ||
!(t->dev->flags & IFF_UP))
continue;
if (t->dev->type != ARPHRD_IP6GRE &&
t->dev->type != dev_type)
continue;
score = 0;
if (t->parms.link != link)
score |= 1;
if (t->dev->type != dev_type)
score |= 2;
if (score == 0)
return t;
if (score < cand_score) {
cand = t;
cand_score = score;
}
}
for_each_ip_tunnel_rcu(t, ign->tunnels_l[h1]) {
if ((!ipv6_addr_equal(local, &t->parms.laddr) &&
(!ipv6_addr_equal(local, &t->parms.raddr) ||
!ipv6_addr_is_multicast(local))) ||
key != t->parms.i_key ||
!(t->dev->flags & IFF_UP))
continue;
if (t->dev->type != ARPHRD_IP6GRE &&
t->dev->type != dev_type)
continue;
score = 0;
if (t->parms.link != link)
score |= 1;
if (t->dev->type != dev_type)
score |= 2;
if (score == 0)
return t;
if (score < cand_score) {
cand = t;
cand_score = score;
}
}
for_each_ip_tunnel_rcu(t, ign->tunnels_wc[h1]) {
if (t->parms.i_key != key ||
!(t->dev->flags & IFF_UP))
continue;
if (t->dev->type != ARPHRD_IP6GRE &&
t->dev->type != dev_type)
continue;
score = 0;
if (t->parms.link != link)
score |= 1;
if (t->dev->type != dev_type)
score |= 2;
if (score == 0)
return t;
if (score < cand_score) {
cand = t;
cand_score = score;
}
}
if (cand)
return cand;
if (gre_proto == htons(ETH_P_ERSPAN) ||
gre_proto == htons(ETH_P_ERSPAN2))
t = rcu_dereference(ign->collect_md_tun_erspan);
else
t = rcu_dereference(ign->collect_md_tun);
if (t && t->dev->flags & IFF_UP)
return t;
ndev = READ_ONCE(ign->fb_tunnel_dev);
if (ndev && ndev->flags & IFF_UP)
return netdev_priv(ndev);
return NULL;
}
static struct ip6_tnl __rcu **__ip6gre_bucket(struct ip6gre_net *ign,
const struct __ip6_tnl_parm *p)
{
const struct in6_addr *remote = &p->raddr;
const struct in6_addr *local = &p->laddr;
unsigned int h = HASH_KEY(p->i_key);
int prio = 0;
if (!ipv6_addr_any(local))
prio |= 1;
if (!ipv6_addr_any(remote) && !ipv6_addr_is_multicast(remote)) {
prio |= 2;
h ^= HASH_ADDR(remote);
}
return &ign->tunnels[prio][h];
}
static void ip6gre_tunnel_link_md(struct ip6gre_net *ign, struct ip6_tnl *t)
{
if (t->parms.collect_md)
rcu_assign_pointer(ign->collect_md_tun, t);
}
static void ip6erspan_tunnel_link_md(struct ip6gre_net *ign, struct ip6_tnl *t)
{
if (t->parms.collect_md)
rcu_assign_pointer(ign->collect_md_tun_erspan, t);
}
static void ip6gre_tunnel_unlink_md(struct ip6gre_net *ign, struct ip6_tnl *t)
{
if (t->parms.collect_md)
rcu_assign_pointer(ign->collect_md_tun, NULL);
}
static void ip6erspan_tunnel_unlink_md(struct ip6gre_net *ign,
struct ip6_tnl *t)
{
if (t->parms.collect_md)
rcu_assign_pointer(ign->collect_md_tun_erspan, NULL);
}
static inline struct ip6_tnl __rcu **ip6gre_bucket(struct ip6gre_net *ign,
const struct ip6_tnl *t)
{
return __ip6gre_bucket(ign, &t->parms);
}
static void ip6gre_tunnel_link(struct ip6gre_net *ign, struct ip6_tnl *t)
{
struct ip6_tnl __rcu **tp = ip6gre_bucket(ign, t);
rcu_assign_pointer(t->next, rtnl_dereference(*tp));
rcu_assign_pointer(*tp, t);
}
static void ip6gre_tunnel_unlink(struct ip6gre_net *ign, struct ip6_tnl *t)
{
struct ip6_tnl __rcu **tp;
struct ip6_tnl *iter;
for (tp = ip6gre_bucket(ign, t);
(iter = rtnl_dereference(*tp)) != NULL;
tp = &iter->next) {
if (t == iter) {
rcu_assign_pointer(*tp, t->next);
break;
}
}
}
static struct ip6_tnl *ip6gre_tunnel_find(struct net *net,
const struct __ip6_tnl_parm *parms,
int type)
{
const struct in6_addr *remote = &parms->raddr;
const struct in6_addr *local = &parms->laddr;
__be32 key = parms->i_key;
int link = parms->link;
struct ip6_tnl *t;
struct ip6_tnl __rcu **tp;
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
for (tp = __ip6gre_bucket(ign, parms);
(t = rtnl_dereference(*tp)) != NULL;
tp = &t->next)
if (ipv6_addr_equal(local, &t->parms.laddr) &&
ipv6_addr_equal(remote, &t->parms.raddr) &&
key == t->parms.i_key &&
link == t->parms.link &&
type == t->dev->type)
break;
return t;
}
static struct ip6_tnl *ip6gre_tunnel_locate(struct net *net,
const struct __ip6_tnl_parm *parms, int create)
{
struct ip6_tnl *t, *nt;
struct net_device *dev;
char name[IFNAMSIZ];
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
t = ip6gre_tunnel_find(net, parms, ARPHRD_IP6GRE);
if (t && create)
return NULL;
if (t || !create)
return t;
if (parms->name[0]) {
if (!dev_valid_name(parms->name))
return NULL;
strlcpy(name, parms->name, IFNAMSIZ);
} else {
strcpy(name, "ip6gre%d");
}
dev = alloc_netdev(sizeof(*t), name, NET_NAME_UNKNOWN,
ip6gre_tunnel_setup);
if (!dev)
return NULL;
dev_net_set(dev, net);
nt = netdev_priv(dev);
nt->parms = *parms;
dev->rtnl_link_ops = &ip6gre_link_ops;
nt->dev = dev;
nt->net = dev_net(dev);
if (register_netdevice(dev) < 0)
goto failed_free;
ip6gre_tnl_link_config(nt, 1);
/* Can use a lockless transmit, unless we generate output sequences */
if (!(nt->parms.o_flags & TUNNEL_SEQ))
dev->features |= NETIF_F_LLTX;
dev_hold(dev);
ip6gre_tunnel_link(ign, nt);
return nt;
failed_free:
free_netdev(dev);
return NULL;
}
static void ip6erspan_tunnel_uninit(struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
struct ip6gre_net *ign = net_generic(t->net, ip6gre_net_id);
ip6erspan_tunnel_unlink_md(ign, t);
ip6gre_tunnel_unlink(ign, t);
dst_cache_reset(&t->dst_cache);
dev_put(dev);
}
static void ip6gre_tunnel_uninit(struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
struct ip6gre_net *ign = net_generic(t->net, ip6gre_net_id);
ip6gre_tunnel_unlink_md(ign, t);
ip6gre_tunnel_unlink(ign, t);
if (ign->fb_tunnel_dev == dev)
WRITE_ONCE(ign->fb_tunnel_dev, NULL);
dst_cache_reset(&t->dst_cache);
dev_put(dev);
}
static int ip6gre_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct net *net = dev_net(skb->dev);
const struct ipv6hdr *ipv6h;
struct tnl_ptk_info tpi;
struct ip6_tnl *t;
if (gre_parse_header(skb, &tpi, NULL, htons(ETH_P_IPV6),
offset) < 0)
return -EINVAL;
ipv6h = (const struct ipv6hdr *)skb->data;
t = ip6gre_tunnel_lookup(skb->dev, &ipv6h->daddr, &ipv6h->saddr,
tpi.key, tpi.proto);
if (!t)
return -ENOENT;
switch (type) {
case ICMPV6_DEST_UNREACH:
net_dbg_ratelimited("%s: Path to destination invalid or inactive!\n",
t->parms.name);
if (code != ICMPV6_PORT_UNREACH)
break;
return 0;
case ICMPV6_TIME_EXCEED:
if (code == ICMPV6_EXC_HOPLIMIT) {
net_dbg_ratelimited("%s: Too small hop limit or routing loop in tunnel!\n",
t->parms.name);
break;
}
return 0;
case ICMPV6_PARAMPROB: {
struct ipv6_tlv_tnl_enc_lim *tel;
__u32 teli;
teli = 0;
if (code == ICMPV6_HDR_FIELD)
teli = ip6_tnl_parse_tlv_enc_lim(skb, skb->data);
if (teli && teli == be32_to_cpu(info) - 2) {
tel = (struct ipv6_tlv_tnl_enc_lim *) &skb->data[teli];
if (tel->encap_limit == 0) {
net_dbg_ratelimited("%s: Too small encapsulation limit or routing loop in tunnel!\n",
t->parms.name);
}
} else {
net_dbg_ratelimited("%s: Recipient unable to parse tunneled packet!\n",
t->parms.name);
}
return 0;
}
case ICMPV6_PKT_TOOBIG:
ip6_update_pmtu(skb, net, info, 0, 0, sock_net_uid(net, NULL));
return 0;
case NDISC_REDIRECT:
ip6_redirect(skb, net, skb->dev->ifindex, 0,
sock_net_uid(net, NULL));
return 0;
}
if (time_before(jiffies, t->err_time + IP6TUNNEL_ERR_TIMEO))
t->err_count++;
else
t->err_count = 1;
t->err_time = jiffies;
return 0;
}
static int ip6gre_rcv(struct sk_buff *skb, const struct tnl_ptk_info *tpi)
{
const struct ipv6hdr *ipv6h;
struct ip6_tnl *tunnel;
ipv6h = ipv6_hdr(skb);
tunnel = ip6gre_tunnel_lookup(skb->dev,
&ipv6h->saddr, &ipv6h->daddr, tpi->key,
tpi->proto);
if (tunnel) {
if (tunnel->parms.collect_md) {
struct metadata_dst *tun_dst;
__be64 tun_id;
__be16 flags;
flags = tpi->flags;
tun_id = key32_to_tunnel_id(tpi->key);
tun_dst = ipv6_tun_rx_dst(skb, flags, tun_id, 0);
if (!tun_dst)
return PACKET_REJECT;
ip6_tnl_rcv(tunnel, skb, tpi, tun_dst, log_ecn_error);
} else {
ip6_tnl_rcv(tunnel, skb, tpi, NULL, log_ecn_error);
}
return PACKET_RCVD;
}
return PACKET_REJECT;
}
static int ip6erspan_rcv(struct sk_buff *skb,
struct tnl_ptk_info *tpi,
int gre_hdr_len)
{
struct erspan_base_hdr *ershdr;
const struct ipv6hdr *ipv6h;
struct erspan_md2 *md2;
struct ip6_tnl *tunnel;
u8 ver;
ipv6h = ipv6_hdr(skb);
ershdr = (struct erspan_base_hdr *)skb->data;
ver = ershdr->ver;
tunnel = ip6gre_tunnel_lookup(skb->dev,
&ipv6h->saddr, &ipv6h->daddr, tpi->key,
tpi->proto);
if (tunnel) {
int len = erspan_hdr_len(ver);
if (unlikely(!pskb_may_pull(skb, len)))
return PACKET_REJECT;
if (__iptunnel_pull_header(skb, len,
htons(ETH_P_TEB),
false, false) < 0)
return PACKET_REJECT;
if (tunnel->parms.collect_md) {
struct erspan_metadata *pkt_md, *md;
struct metadata_dst *tun_dst;
struct ip_tunnel_info *info;
unsigned char *gh;
__be64 tun_id;
__be16 flags;
tpi->flags |= TUNNEL_KEY;
flags = tpi->flags;
tun_id = key32_to_tunnel_id(tpi->key);
tun_dst = ipv6_tun_rx_dst(skb, flags, tun_id,
sizeof(*md));
if (!tun_dst)
return PACKET_REJECT;
/* skb can be uncloned in __iptunnel_pull_header, so
* old pkt_md is no longer valid and we need to reset
* it
*/
gh = skb_network_header(skb) +
skb_network_header_len(skb);
pkt_md = (struct erspan_metadata *)(gh + gre_hdr_len +
sizeof(*ershdr));
info = &tun_dst->u.tun_info;
md = ip_tunnel_info_opts(info);
md->version = ver;
md2 = &md->u.md2;
memcpy(md2, pkt_md, ver == 1 ? ERSPAN_V1_MDSIZE :
ERSPAN_V2_MDSIZE);
info->key.tun_flags |= TUNNEL_ERSPAN_OPT;
info->options_len = sizeof(*md);
ip6_tnl_rcv(tunnel, skb, tpi, tun_dst, log_ecn_error);
} else {
ip6_tnl_rcv(tunnel, skb, tpi, NULL, log_ecn_error);
}
return PACKET_RCVD;
}
return PACKET_REJECT;
}
static int gre_rcv(struct sk_buff *skb)
{
struct tnl_ptk_info tpi;
bool csum_err = false;
int hdr_len;
hdr_len = gre_parse_header(skb, &tpi, &csum_err, htons(ETH_P_IPV6), 0);
if (hdr_len < 0)
goto drop;
if (iptunnel_pull_header(skb, hdr_len, tpi.proto, false))
goto drop;
if (unlikely(tpi.proto == htons(ETH_P_ERSPAN) ||
tpi.proto == htons(ETH_P_ERSPAN2))) {
if (ip6erspan_rcv(skb, &tpi, hdr_len) == PACKET_RCVD)
return 0;
goto out;
}
if (ip6gre_rcv(skb, &tpi) == PACKET_RCVD)
return 0;
out:
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
drop:
kfree_skb(skb);
return 0;
}
static int gre_handle_offloads(struct sk_buff *skb, bool csum)
{
return iptunnel_handle_offloads(skb,
csum ? SKB_GSO_GRE_CSUM : SKB_GSO_GRE);
}
static void prepare_ip6gre_xmit_ipv4(struct sk_buff *skb,
struct net_device *dev,
struct flowi6 *fl6, __u8 *dsfield,
int *encap_limit)
{
const struct iphdr *iph = ip_hdr(skb);
struct ip6_tnl *t = netdev_priv(dev);
if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
*encap_limit = t->parms.encap_limit;
memcpy(fl6, &t->fl.u.ip6, sizeof(*fl6));
if (t->parms.flags & IP6_TNL_F_USE_ORIG_TCLASS)
*dsfield = ipv4_get_dsfield(iph);
else
*dsfield = ip6_tclass(t->parms.flowinfo);
if (t->parms.flags & IP6_TNL_F_USE_ORIG_FWMARK)
fl6->flowi6_mark = skb->mark;
else
fl6->flowi6_mark = t->parms.fwmark;
fl6->flowi6_uid = sock_net_uid(dev_net(dev), NULL);
}
static int prepare_ip6gre_xmit_ipv6(struct sk_buff *skb,
struct net_device *dev,
struct flowi6 *fl6, __u8 *dsfield,
int *encap_limit)
{
struct ipv6hdr *ipv6h;
struct ip6_tnl *t = netdev_priv(dev);
__u16 offset;
offset = ip6_tnl_parse_tlv_enc_lim(skb, skb_network_header(skb));
/* ip6_tnl_parse_tlv_enc_lim() might have reallocated skb->head */
ipv6h = ipv6_hdr(skb);
if (offset > 0) {
struct ipv6_tlv_tnl_enc_lim *tel;
tel = (struct ipv6_tlv_tnl_enc_lim *)&skb_network_header(skb)[offset];
if (tel->encap_limit == 0) {
icmpv6_ndo_send(skb, ICMPV6_PARAMPROB,
ICMPV6_HDR_FIELD, offset + 2);
return -1;
}
*encap_limit = tel->encap_limit - 1;
} else if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT)) {
*encap_limit = t->parms.encap_limit;
}
memcpy(fl6, &t->fl.u.ip6, sizeof(*fl6));
if (t->parms.flags & IP6_TNL_F_USE_ORIG_TCLASS)
*dsfield = ipv6_get_dsfield(ipv6h);
else
*dsfield = ip6_tclass(t->parms.flowinfo);
if (t->parms.flags & IP6_TNL_F_USE_ORIG_FLOWLABEL)
fl6->flowlabel |= ip6_flowlabel(ipv6h);
if (t->parms.flags & IP6_TNL_F_USE_ORIG_FWMARK)
fl6->flowi6_mark = skb->mark;
else
fl6->flowi6_mark = t->parms.fwmark;
fl6->flowi6_uid = sock_net_uid(dev_net(dev), NULL);
return 0;
}
static struct ip_tunnel_info *skb_tunnel_info_txcheck(struct sk_buff *skb)
{
struct ip_tunnel_info *tun_info;
tun_info = skb_tunnel_info(skb);
if (unlikely(!tun_info || !(tun_info->mode & IP_TUNNEL_INFO_TX)))
return ERR_PTR(-EINVAL);
return tun_info;
}
static netdev_tx_t __gre6_xmit(struct sk_buff *skb,
struct net_device *dev, __u8 dsfield,
struct flowi6 *fl6, int encap_limit,
__u32 *pmtu, __be16 proto)
{
struct ip6_tnl *tunnel = netdev_priv(dev);
__be16 protocol;
if (dev->type == ARPHRD_ETHER)
IPCB(skb)->flags = 0;
if (dev->header_ops && dev->type == ARPHRD_IP6GRE)
fl6->daddr = ((struct ipv6hdr *)skb->data)->daddr;
else
fl6->daddr = tunnel->parms.raddr;
if (skb_cow_head(skb, dev->needed_headroom ?: tunnel->hlen))
return -ENOMEM;
/* Push GRE header. */
protocol = (dev->type == ARPHRD_ETHER) ? htons(ETH_P_TEB) : proto;
if (tunnel->parms.collect_md) {
struct ip_tunnel_info *tun_info;
const struct ip_tunnel_key *key;
__be16 flags;
tun_info = skb_tunnel_info_txcheck(skb);
if (IS_ERR(tun_info) ||
unlikely(ip_tunnel_info_af(tun_info) != AF_INET6))
return -EINVAL;
key = &tun_info->key;
memset(fl6, 0, sizeof(*fl6));
fl6->flowi6_proto = IPPROTO_GRE;
fl6->daddr = key->u.ipv6.dst;
fl6->flowlabel = key->label;
fl6->flowi6_uid = sock_net_uid(dev_net(dev), NULL);
dsfield = key->tos;
flags = key->tun_flags &
(TUNNEL_CSUM | TUNNEL_KEY | TUNNEL_SEQ);
tunnel->tun_hlen = gre_calc_hlen(flags);
gre_build_header(skb, tunnel->tun_hlen,
flags, protocol,
tunnel_id_to_key32(tun_info->key.tun_id),
(flags & TUNNEL_SEQ) ? htonl(tunnel->o_seqno++)
: 0);
} else {
if (tunnel->parms.o_flags & TUNNEL_SEQ)
tunnel->o_seqno++;
gre_build_header(skb, tunnel->tun_hlen, tunnel->parms.o_flags,
protocol, tunnel->parms.o_key,
htonl(tunnel->o_seqno));
}
return ip6_tnl_xmit(skb, dev, dsfield, fl6, encap_limit, pmtu,
NEXTHDR_GRE);
}
static inline int ip6gre_xmit_ipv4(struct sk_buff *skb, struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
int encap_limit = -1;
struct flowi6 fl6;
__u8 dsfield = 0;
__u32 mtu;
int err;
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
if (!t->parms.collect_md)
prepare_ip6gre_xmit_ipv4(skb, dev, &fl6,
&dsfield, &encap_limit);
err = gre_handle_offloads(skb, !!(t->parms.o_flags & TUNNEL_CSUM));
if (err)
return -1;
err = __gre6_xmit(skb, dev, dsfield, &fl6, encap_limit, &mtu,
skb->protocol);
if (err != 0) {
/* XXX: send ICMP error even if DF is not set. */
if (err == -EMSGSIZE)
icmp_ndo_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
htonl(mtu));
return -1;
}
return 0;
}
static inline int ip6gre_xmit_ipv6(struct sk_buff *skb, struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
struct ipv6hdr *ipv6h = ipv6_hdr(skb);
int encap_limit = -1;
struct flowi6 fl6;
__u8 dsfield = 0;
__u32 mtu;
int err;
if (ipv6_addr_equal(&t->parms.raddr, &ipv6h->saddr))
return -1;
if (!t->parms.collect_md &&
prepare_ip6gre_xmit_ipv6(skb, dev, &fl6, &dsfield, &encap_limit))
return -1;
if (gre_handle_offloads(skb, !!(t->parms.o_flags & TUNNEL_CSUM)))
return -1;
err = __gre6_xmit(skb, dev, dsfield, &fl6, encap_limit,
&mtu, skb->protocol);
if (err != 0) {
if (err == -EMSGSIZE)
icmpv6_ndo_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
return -1;
}
return 0;
}
/**
* ip6gre_tnl_addr_conflict - compare packet addresses to tunnel's own
* @t: the outgoing tunnel device
* @hdr: IPv6 header from the incoming packet
*
* Description:
* Avoid trivial tunneling loop by checking that tunnel exit-point
* doesn't match source of incoming packet.
*
* Return:
* 1 if conflict,
* 0 else
**/
static inline bool ip6gre_tnl_addr_conflict(const struct ip6_tnl *t,
const struct ipv6hdr *hdr)
{
return ipv6_addr_equal(&t->parms.raddr, &hdr->saddr);
}
static int ip6gre_xmit_other(struct sk_buff *skb, struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
int encap_limit = -1;
struct flowi6 fl6;
__u32 mtu;
int err;
if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
encap_limit = t->parms.encap_limit;
if (!t->parms.collect_md)
memcpy(&fl6, &t->fl.u.ip6, sizeof(fl6));
err = gre_handle_offloads(skb, !!(t->parms.o_flags & TUNNEL_CSUM));
if (err)
return err;
err = __gre6_xmit(skb, dev, 0, &fl6, encap_limit, &mtu, skb->protocol);
return err;
}
static netdev_tx_t ip6gre_tunnel_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
struct net_device_stats *stats = &t->dev->stats;
int ret;
if (!pskb_inet_may_pull(skb))
goto tx_err;
if (!ip6_tnl_xmit_ctl(t, &t->parms.laddr, &t->parms.raddr))
goto tx_err;
switch (skb->protocol) {
case htons(ETH_P_IP):
ret = ip6gre_xmit_ipv4(skb, dev);
break;
case htons(ETH_P_IPV6):
ret = ip6gre_xmit_ipv6(skb, dev);
break;
default:
ret = ip6gre_xmit_other(skb, dev);
break;
}
if (ret < 0)
goto tx_err;
return NETDEV_TX_OK;
tx_err:
if (!t->parms.collect_md || !IS_ERR(skb_tunnel_info_txcheck(skb)))
stats->tx_errors++;
stats->tx_dropped++;
kfree_skb(skb);
return NETDEV_TX_OK;
}
static netdev_tx_t ip6erspan_tunnel_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ip_tunnel_info *tun_info = NULL;
struct ip6_tnl *t = netdev_priv(dev);
struct dst_entry *dst = skb_dst(skb);
struct net_device_stats *stats;
bool truncate = false;
int encap_limit = -1;
__u8 dsfield = false;
struct flowi6 fl6;
int err = -EINVAL;
__be16 proto;
__u32 mtu;
int nhoff;
int thoff;
if (!pskb_inet_may_pull(skb))
goto tx_err;
if (!ip6_tnl_xmit_ctl(t, &t->parms.laddr, &t->parms.raddr))
goto tx_err;
if (gre_handle_offloads(skb, false))
goto tx_err;
if (skb->len > dev->mtu + dev->hard_header_len) {
pskb_trim(skb, dev->mtu + dev->hard_header_len);
truncate = true;
}
nhoff = skb_network_header(skb) - skb_mac_header(skb);
if (skb->protocol == htons(ETH_P_IP) &&
(ntohs(ip_hdr(skb)->tot_len) > skb->len - nhoff))
truncate = true;
thoff = skb_transport_header(skb) - skb_mac_header(skb);
if (skb->protocol == htons(ETH_P_IPV6) &&
(ntohs(ipv6_hdr(skb)->payload_len) > skb->len - thoff))
truncate = true;
if (skb_cow_head(skb, dev->needed_headroom ?: t->hlen))
goto tx_err;
t->parms.o_flags &= ~TUNNEL_KEY;
IPCB(skb)->flags = 0;
/* For collect_md mode, derive fl6 from the tunnel key,
* for native mode, call prepare_ip6gre_xmit_{ipv4,ipv6}.
*/
if (t->parms.collect_md) {
const struct ip_tunnel_key *key;
struct erspan_metadata *md;
__be32 tun_id;
tun_info = skb_tunnel_info_txcheck(skb);
if (IS_ERR(tun_info) ||
unlikely(ip_tunnel_info_af(tun_info) != AF_INET6))
goto tx_err;
key = &tun_info->key;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_GRE;
fl6.daddr = key->u.ipv6.dst;
fl6.flowlabel = key->label;
fl6.flowi6_uid = sock_net_uid(dev_net(dev), NULL);
dsfield = key->tos;
if (!(tun_info->key.tun_flags & TUNNEL_ERSPAN_OPT))
goto tx_err;
if (tun_info->options_len < sizeof(*md))
goto tx_err;
md = ip_tunnel_info_opts(tun_info);
tun_id = tunnel_id_to_key32(key->tun_id);
if (md->version == 1) {
erspan_build_header(skb,
ntohl(tun_id),
ntohl(md->u.index), truncate,
false);
} else if (md->version == 2) {
erspan_build_header_v2(skb,
ntohl(tun_id),
md->u.md2.dir,
get_hwid(&md->u.md2),
truncate, false);
} else {
goto tx_err;
}
} else {
switch (skb->protocol) {
case htons(ETH_P_IP):
memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
prepare_ip6gre_xmit_ipv4(skb, dev, &fl6,
&dsfield, &encap_limit);
break;
case htons(ETH_P_IPV6):
if (ipv6_addr_equal(&t->parms.raddr, &ipv6_hdr(skb)->saddr))
goto tx_err;
if (prepare_ip6gre_xmit_ipv6(skb, dev, &fl6,
&dsfield, &encap_limit))
goto tx_err;
break;
default:
memcpy(&fl6, &t->fl.u.ip6, sizeof(fl6));
break;
}
if (t->parms.erspan_ver == 1)
erspan_build_header(skb, ntohl(t->parms.o_key),
t->parms.index,
truncate, false);
else if (t->parms.erspan_ver == 2)
erspan_build_header_v2(skb, ntohl(t->parms.o_key),
t->parms.dir,
t->parms.hwid,
truncate, false);
else
goto tx_err;
fl6.daddr = t->parms.raddr;
}
/* Push GRE header. */
proto = (t->parms.erspan_ver == 1) ? htons(ETH_P_ERSPAN)
: htons(ETH_P_ERSPAN2);
gre_build_header(skb, 8, TUNNEL_SEQ, proto, 0, htonl(t->o_seqno++));
/* TooBig packet may have updated dst->dev's mtu */
if (!t->parms.collect_md && dst && dst_mtu(dst) > dst->dev->mtu)
dst->ops->update_pmtu(dst, NULL, skb, dst->dev->mtu, false);
err = ip6_tnl_xmit(skb, dev, dsfield, &fl6, encap_limit, &mtu,
NEXTHDR_GRE);
if (err != 0) {
/* XXX: send ICMP error even if DF is not set. */
if (err == -EMSGSIZE) {
if (skb->protocol == htons(ETH_P_IP))
icmp_ndo_send(skb, ICMP_DEST_UNREACH,
ICMP_FRAG_NEEDED, htonl(mtu));
else
icmpv6_ndo_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
}
goto tx_err;
}
return NETDEV_TX_OK;
tx_err:
stats = &t->dev->stats;
if (!IS_ERR(tun_info))
stats->tx_errors++;
stats->tx_dropped++;
kfree_skb(skb);
return NETDEV_TX_OK;
}
static void ip6gre_tnl_link_config_common(struct ip6_tnl *t)
{
struct net_device *dev = t->dev;
struct __ip6_tnl_parm *p = &t->parms;
struct flowi6 *fl6 = &t->fl.u.ip6;
if (dev->type != ARPHRD_ETHER) {
memcpy(dev->dev_addr, &p->laddr, sizeof(struct in6_addr));
memcpy(dev->broadcast, &p->raddr, sizeof(struct in6_addr));
}
/* Set up flowi template */
fl6->saddr = p->laddr;
fl6->daddr = p->raddr;
fl6->flowi6_oif = p->link;
fl6->flowlabel = 0;
fl6->flowi6_proto = IPPROTO_GRE;
if (!(p->flags&IP6_TNL_F_USE_ORIG_TCLASS))
fl6->flowlabel |= IPV6_TCLASS_MASK & p->flowinfo;
if (!(p->flags&IP6_TNL_F_USE_ORIG_FLOWLABEL))
fl6->flowlabel |= IPV6_FLOWLABEL_MASK & p->flowinfo;
p->flags &= ~(IP6_TNL_F_CAP_XMIT|IP6_TNL_F_CAP_RCV|IP6_TNL_F_CAP_PER_PACKET);
p->flags |= ip6_tnl_get_cap(t, &p->laddr, &p->raddr);
if (p->flags&IP6_TNL_F_CAP_XMIT &&
p->flags&IP6_TNL_F_CAP_RCV && dev->type != ARPHRD_ETHER)
dev->flags |= IFF_POINTOPOINT;
else
dev->flags &= ~IFF_POINTOPOINT;
}
static void ip6gre_tnl_link_config_route(struct ip6_tnl *t, int set_mtu,
int t_hlen)
{
const struct __ip6_tnl_parm *p = &t->parms;
struct net_device *dev = t->dev;
if (p->flags & IP6_TNL_F_CAP_XMIT) {
int strict = (ipv6_addr_type(&p->raddr) &
(IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL));
struct rt6_info *rt = rt6_lookup(t->net,
&p->raddr, &p->laddr,
p->link, NULL, strict);
if (!rt)
return;
if (rt->dst.dev) {
unsigned short dst_len = rt->dst.dev->hard_header_len +
t_hlen;
if (t->dev->header_ops)
dev->hard_header_len = dst_len;
else
dev->needed_headroom = dst_len;
if (set_mtu) {
dev->mtu = rt->dst.dev->mtu - t_hlen;
if (!(t->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
dev->mtu -= 8;
if (dev->type == ARPHRD_ETHER)
dev->mtu -= ETH_HLEN;
if (dev->mtu < IPV6_MIN_MTU)
dev->mtu = IPV6_MIN_MTU;
}
}
ip6_rt_put(rt);
}
}
static int ip6gre_calc_hlen(struct ip6_tnl *tunnel)
{
int t_hlen;
tunnel->tun_hlen = gre_calc_hlen(tunnel->parms.o_flags);
tunnel->hlen = tunnel->tun_hlen + tunnel->encap_hlen;
t_hlen = tunnel->hlen + sizeof(struct ipv6hdr);
if (tunnel->dev->header_ops)
tunnel->dev->hard_header_len = LL_MAX_HEADER + t_hlen;
else
tunnel->dev->needed_headroom = LL_MAX_HEADER + t_hlen;
return t_hlen;
}
static void ip6gre_tnl_link_config(struct ip6_tnl *t, int set_mtu)
{
ip6gre_tnl_link_config_common(t);
ip6gre_tnl_link_config_route(t, set_mtu, ip6gre_calc_hlen(t));
}
static void ip6gre_tnl_copy_tnl_parm(struct ip6_tnl *t,
const struct __ip6_tnl_parm *p)
{
t->parms.laddr = p->laddr;
t->parms.raddr = p->raddr;
t->parms.flags = p->flags;
t->parms.hop_limit = p->hop_limit;
t->parms.encap_limit = p->encap_limit;
t->parms.flowinfo = p->flowinfo;
t->parms.link = p->link;
t->parms.proto = p->proto;
t->parms.i_key = p->i_key;
t->parms.o_key = p->o_key;
t->parms.i_flags = p->i_flags;
t->parms.o_flags = p->o_flags;
t->parms.fwmark = p->fwmark;
t->parms.erspan_ver = p->erspan_ver;
t->parms.index = p->index;
t->parms.dir = p->dir;
t->parms.hwid = p->hwid;
dst_cache_reset(&t->dst_cache);
}
static int ip6gre_tnl_change(struct ip6_tnl *t, const struct __ip6_tnl_parm *p,
int set_mtu)
{
ip6gre_tnl_copy_tnl_parm(t, p);
ip6gre_tnl_link_config(t, set_mtu);
return 0;
}
static void ip6gre_tnl_parm_from_user(struct __ip6_tnl_parm *p,
const struct ip6_tnl_parm2 *u)
{
p->laddr = u->laddr;
p->raddr = u->raddr;
p->flags = u->flags;
p->hop_limit = u->hop_limit;
p->encap_limit = u->encap_limit;
p->flowinfo = u->flowinfo;
p->link = u->link;
p->i_key = u->i_key;
p->o_key = u->o_key;
p->i_flags = gre_flags_to_tnl_flags(u->i_flags);
p->o_flags = gre_flags_to_tnl_flags(u->o_flags);
memcpy(p->name, u->name, sizeof(u->name));
}
static void ip6gre_tnl_parm_to_user(struct ip6_tnl_parm2 *u,
const struct __ip6_tnl_parm *p)
{
u->proto = IPPROTO_GRE;
u->laddr = p->laddr;
u->raddr = p->raddr;
u->flags = p->flags;
u->hop_limit = p->hop_limit;
u->encap_limit = p->encap_limit;
u->flowinfo = p->flowinfo;
u->link = p->link;
u->i_key = p->i_key;
u->o_key = p->o_key;
u->i_flags = gre_tnl_flags_to_gre_flags(p->i_flags);
u->o_flags = gre_tnl_flags_to_gre_flags(p->o_flags);
memcpy(u->name, p->name, sizeof(u->name));
}
static int ip6gre_tunnel_ioctl(struct net_device *dev,
struct ifreq *ifr, int cmd)
{
int err = 0;
struct ip6_tnl_parm2 p;
struct __ip6_tnl_parm p1;
struct ip6_tnl *t = netdev_priv(dev);
struct net *net = t->net;
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
memset(&p1, 0, sizeof(p1));
switch (cmd) {
case SIOCGETTUNNEL:
if (dev == ign->fb_tunnel_dev) {
if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p))) {
err = -EFAULT;
break;
}
ip6gre_tnl_parm_from_user(&p1, &p);
t = ip6gre_tunnel_locate(net, &p1, 0);
if (!t)
t = netdev_priv(dev);
}
memset(&p, 0, sizeof(p));
ip6gre_tnl_parm_to_user(&p, &t->parms);
if (copy_to_user(ifr->ifr_ifru.ifru_data, &p, sizeof(p)))
err = -EFAULT;
break;
case SIOCADDTUNNEL:
case SIOCCHGTUNNEL:
err = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
goto done;
err = -EFAULT;
if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p)))
goto done;
err = -EINVAL;
if ((p.i_flags|p.o_flags)&(GRE_VERSION|GRE_ROUTING))
goto done;
if (!(p.i_flags&GRE_KEY))
p.i_key = 0;
if (!(p.o_flags&GRE_KEY))
p.o_key = 0;
ip6gre_tnl_parm_from_user(&p1, &p);
t = ip6gre_tunnel_locate(net, &p1, cmd == SIOCADDTUNNEL);
if (dev != ign->fb_tunnel_dev && cmd == SIOCCHGTUNNEL) {
if (t) {
if (t->dev != dev) {
err = -EEXIST;
break;
}
} else {
t = netdev_priv(dev);
ip6gre_tunnel_unlink(ign, t);
synchronize_net();
ip6gre_tnl_change(t, &p1, 1);
ip6gre_tunnel_link(ign, t);
netdev_state_change(dev);
}
}
if (t) {
err = 0;
memset(&p, 0, sizeof(p));
ip6gre_tnl_parm_to_user(&p, &t->parms);
if (copy_to_user(ifr->ifr_ifru.ifru_data, &p, sizeof(p)))
err = -EFAULT;
} else
err = (cmd == SIOCADDTUNNEL ? -ENOBUFS : -ENOENT);
break;
case SIOCDELTUNNEL:
err = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
goto done;
if (dev == ign->fb_tunnel_dev) {
err = -EFAULT;
if (copy_from_user(&p, ifr->ifr_ifru.ifru_data, sizeof(p)))
goto done;
err = -ENOENT;
ip6gre_tnl_parm_from_user(&p1, &p);
t = ip6gre_tunnel_locate(net, &p1, 0);
if (!t)
goto done;
err = -EPERM;
if (t == netdev_priv(ign->fb_tunnel_dev))
goto done;
dev = t->dev;
}
unregister_netdevice(dev);
err = 0;
break;
default:
err = -EINVAL;
}
done:
return err;
}
static int ip6gre_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type, const void *daddr,
const void *saddr, unsigned int len)
{
struct ip6_tnl *t = netdev_priv(dev);
struct ipv6hdr *ipv6h;
__be16 *p;
ipv6h = skb_push(skb, t->hlen + sizeof(*ipv6h));
ip6_flow_hdr(ipv6h, 0, ip6_make_flowlabel(dev_net(dev), skb,
t->fl.u.ip6.flowlabel,
true, &t->fl.u.ip6));
ipv6h->hop_limit = t->parms.hop_limit;
ipv6h->nexthdr = NEXTHDR_GRE;
ipv6h->saddr = t->parms.laddr;
ipv6h->daddr = t->parms.raddr;
p = (__be16 *)(ipv6h + 1);
p[0] = t->parms.o_flags;
p[1] = htons(type);
/*
* Set the source hardware address.
*/
if (saddr)
memcpy(&ipv6h->saddr, saddr, sizeof(struct in6_addr));
if (daddr)
memcpy(&ipv6h->daddr, daddr, sizeof(struct in6_addr));
if (!ipv6_addr_any(&ipv6h->daddr))
return t->hlen;
return -t->hlen;
}
static const struct header_ops ip6gre_header_ops = {
.create = ip6gre_header,
};
static const struct net_device_ops ip6gre_netdev_ops = {
.ndo_init = ip6gre_tunnel_init,
.ndo_uninit = ip6gre_tunnel_uninit,
.ndo_start_xmit = ip6gre_tunnel_xmit,
.ndo_do_ioctl = ip6gre_tunnel_ioctl,
.ndo_change_mtu = ip6_tnl_change_mtu,
.ndo_get_stats64 = dev_get_tstats64,
.ndo_get_iflink = ip6_tnl_get_iflink,
};
static void ip6gre_dev_free(struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
gro_cells_destroy(&t->gro_cells);
dst_cache_destroy(&t->dst_cache);
free_percpu(dev->tstats);
}
static void ip6gre_tunnel_setup(struct net_device *dev)
{
dev->netdev_ops = &ip6gre_netdev_ops;
dev->needs_free_netdev = true;
dev->priv_destructor = ip6gre_dev_free;
dev->type = ARPHRD_IP6GRE;
dev->flags |= IFF_NOARP;
dev->addr_len = sizeof(struct in6_addr);
netif_keep_dst(dev);
/* This perm addr will be used as interface identifier by IPv6 */
dev->addr_assign_type = NET_ADDR_RANDOM;
eth_random_addr(dev->perm_addr);
}
#define GRE6_FEATURES (NETIF_F_SG | \
NETIF_F_FRAGLIST | \
NETIF_F_HIGHDMA | \
NETIF_F_HW_CSUM)
static void ip6gre_tnl_init_features(struct net_device *dev)
{
struct ip6_tnl *nt = netdev_priv(dev);
dev->features |= GRE6_FEATURES;
dev->hw_features |= GRE6_FEATURES;
if (!(nt->parms.o_flags & TUNNEL_SEQ)) {
/* TCP offload with GRE SEQ is not supported, nor
* can we support 2 levels of outer headers requiring
* an update.
*/
if (!(nt->parms.o_flags & TUNNEL_CSUM) ||
nt->encap.type == TUNNEL_ENCAP_NONE) {
dev->features |= NETIF_F_GSO_SOFTWARE;
dev->hw_features |= NETIF_F_GSO_SOFTWARE;
}
/* Can use a lockless transmit, unless we generate
* output sequences
*/
dev->features |= NETIF_F_LLTX;
}
}
static int ip6gre_tunnel_init_common(struct net_device *dev)
{
struct ip6_tnl *tunnel;
int ret;
int t_hlen;
tunnel = netdev_priv(dev);
tunnel->dev = dev;
tunnel->net = dev_net(dev);
strcpy(tunnel->parms.name, dev->name);
dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
if (!dev->tstats)
return -ENOMEM;
ret = dst_cache_init(&tunnel->dst_cache, GFP_KERNEL);
if (ret)
goto cleanup_alloc_pcpu_stats;
ret = gro_cells_init(&tunnel->gro_cells, dev);
if (ret)
goto cleanup_dst_cache_init;
t_hlen = ip6gre_calc_hlen(tunnel);
dev->mtu = ETH_DATA_LEN - t_hlen;
if (dev->type == ARPHRD_ETHER)
dev->mtu -= ETH_HLEN;
if (!(tunnel->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
dev->mtu -= 8;
if (tunnel->parms.collect_md) {
netif_keep_dst(dev);
}
ip6gre_tnl_init_features(dev);
return 0;
cleanup_dst_cache_init:
dst_cache_destroy(&tunnel->dst_cache);
cleanup_alloc_pcpu_stats:
free_percpu(dev->tstats);
dev->tstats = NULL;
return ret;
}
static int ip6gre_tunnel_init(struct net_device *dev)
{
struct ip6_tnl *tunnel;
int ret;
ret = ip6gre_tunnel_init_common(dev);
if (ret)
return ret;
tunnel = netdev_priv(dev);
if (tunnel->parms.collect_md)
return 0;
memcpy(dev->dev_addr, &tunnel->parms.laddr, sizeof(struct in6_addr));
memcpy(dev->broadcast, &tunnel->parms.raddr, sizeof(struct in6_addr));
if (ipv6_addr_any(&tunnel->parms.raddr))
dev->header_ops = &ip6gre_header_ops;
return 0;
}
static void ip6gre_fb_tunnel_init(struct net_device *dev)
{
struct ip6_tnl *tunnel = netdev_priv(dev);
tunnel->dev = dev;
tunnel->net = dev_net(dev);
strcpy(tunnel->parms.name, dev->name);
tunnel->hlen = sizeof(struct ipv6hdr) + 4;
dev_hold(dev);
}
static struct inet6_protocol ip6gre_protocol __read_mostly = {
.handler = gre_rcv,
.err_handler = ip6gre_err,
.flags = INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL,
};
static void ip6gre_destroy_tunnels(struct net *net, struct list_head *head)
{
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
struct net_device *dev, *aux;
int prio;
for_each_netdev_safe(net, dev, aux)
if (dev->rtnl_link_ops == &ip6gre_link_ops ||
dev->rtnl_link_ops == &ip6gre_tap_ops ||
dev->rtnl_link_ops == &ip6erspan_tap_ops)
unregister_netdevice_queue(dev, head);
for (prio = 0; prio < 4; prio++) {
int h;
for (h = 0; h < IP6_GRE_HASH_SIZE; h++) {
struct ip6_tnl *t;
t = rtnl_dereference(ign->tunnels[prio][h]);
while (t) {
/* If dev is in the same netns, it has already
* been added to the list by the previous loop.
*/
if (!net_eq(dev_net(t->dev), net))
unregister_netdevice_queue(t->dev,
head);
t = rtnl_dereference(t->next);
}
}
}
}
static int __net_init ip6gre_init_net(struct net *net)
{
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
struct net_device *ndev;
int err;
if (!net_has_fallback_tunnels(net))
return 0;
ndev = alloc_netdev(sizeof(struct ip6_tnl), "ip6gre0",
NET_NAME_UNKNOWN, ip6gre_tunnel_setup);
if (!ndev) {
err = -ENOMEM;
goto err_alloc_dev;
}
ign->fb_tunnel_dev = ndev;
dev_net_set(ign->fb_tunnel_dev, net);
/* FB netdevice is special: we have one, and only one per netns.
* Allowing to move it to another netns is clearly unsafe.
*/
ign->fb_tunnel_dev->features |= NETIF_F_NETNS_LOCAL;
ip6gre_fb_tunnel_init(ign->fb_tunnel_dev);
ign->fb_tunnel_dev->rtnl_link_ops = &ip6gre_link_ops;
err = register_netdev(ign->fb_tunnel_dev);
if (err)
goto err_reg_dev;
rcu_assign_pointer(ign->tunnels_wc[0],
netdev_priv(ign->fb_tunnel_dev));
return 0;
err_reg_dev:
free_netdev(ndev);
err_alloc_dev:
return err;
}
static void __net_exit ip6gre_exit_batch_net(struct list_head *net_list)
{
struct net *net;
LIST_HEAD(list);
rtnl_lock();
list_for_each_entry(net, net_list, exit_list)
ip6gre_destroy_tunnels(net, &list);
unregister_netdevice_many(&list);
rtnl_unlock();
}
static struct pernet_operations ip6gre_net_ops = {
.init = ip6gre_init_net,
.exit_batch = ip6gre_exit_batch_net,
.id = &ip6gre_net_id,
.size = sizeof(struct ip6gre_net),
};
static int ip6gre_tunnel_validate(struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
__be16 flags;
if (!data)
return 0;
flags = 0;
if (data[IFLA_GRE_IFLAGS])
flags |= nla_get_be16(data[IFLA_GRE_IFLAGS]);
if (data[IFLA_GRE_OFLAGS])
flags |= nla_get_be16(data[IFLA_GRE_OFLAGS]);
if (flags & (GRE_VERSION|GRE_ROUTING))
return -EINVAL;
return 0;
}
static int ip6gre_tap_validate(struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct in6_addr daddr;
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
if (!data)
goto out;
if (data[IFLA_GRE_REMOTE]) {
daddr = nla_get_in6_addr(data[IFLA_GRE_REMOTE]);
if (ipv6_addr_any(&daddr))
return -EINVAL;
}
out:
return ip6gre_tunnel_validate(tb, data, extack);
}
static int ip6erspan_tap_validate(struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
__be16 flags = 0;
int ret, ver = 0;
if (!data)
return 0;
ret = ip6gre_tap_validate(tb, data, extack);
if (ret)
return ret;
/* ERSPAN should only have GRE sequence and key flag */
if (data[IFLA_GRE_OFLAGS])
flags |= nla_get_be16(data[IFLA_GRE_OFLAGS]);
if (data[IFLA_GRE_IFLAGS])
flags |= nla_get_be16(data[IFLA_GRE_IFLAGS]);
if (!data[IFLA_GRE_COLLECT_METADATA] &&
flags != (GRE_SEQ | GRE_KEY))
return -EINVAL;
/* ERSPAN Session ID only has 10-bit. Since we reuse
* 32-bit key field as ID, check it's range.
*/
if (data[IFLA_GRE_IKEY] &&
(ntohl(nla_get_be32(data[IFLA_GRE_IKEY])) & ~ID_MASK))
return -EINVAL;
if (data[IFLA_GRE_OKEY] &&
(ntohl(nla_get_be32(data[IFLA_GRE_OKEY])) & ~ID_MASK))
return -EINVAL;
if (data[IFLA_GRE_ERSPAN_VER]) {
ver = nla_get_u8(data[IFLA_GRE_ERSPAN_VER]);
if (ver != 1 && ver != 2)
return -EINVAL;
}
if (ver == 1) {
if (data[IFLA_GRE_ERSPAN_INDEX]) {
u32 index = nla_get_u32(data[IFLA_GRE_ERSPAN_INDEX]);
if (index & ~INDEX_MASK)
return -EINVAL;
}
} else if (ver == 2) {
if (data[IFLA_GRE_ERSPAN_DIR]) {
u16 dir = nla_get_u8(data[IFLA_GRE_ERSPAN_DIR]);
if (dir & ~(DIR_MASK >> DIR_OFFSET))
return -EINVAL;
}
if (data[IFLA_GRE_ERSPAN_HWID]) {
u16 hwid = nla_get_u16(data[IFLA_GRE_ERSPAN_HWID]);
if (hwid & ~(HWID_MASK >> HWID_OFFSET))
return -EINVAL;
}
}
return 0;
}
static void ip6erspan_set_version(struct nlattr *data[],
struct __ip6_tnl_parm *parms)
{
if (!data)
return;
parms->erspan_ver = 1;
if (data[IFLA_GRE_ERSPAN_VER])
parms->erspan_ver = nla_get_u8(data[IFLA_GRE_ERSPAN_VER]);
if (parms->erspan_ver == 1) {
if (data[IFLA_GRE_ERSPAN_INDEX])
parms->index = nla_get_u32(data[IFLA_GRE_ERSPAN_INDEX]);
} else if (parms->erspan_ver == 2) {
if (data[IFLA_GRE_ERSPAN_DIR])
parms->dir = nla_get_u8(data[IFLA_GRE_ERSPAN_DIR]);
if (data[IFLA_GRE_ERSPAN_HWID])
parms->hwid = nla_get_u16(data[IFLA_GRE_ERSPAN_HWID]);
}
}
static void ip6gre_netlink_parms(struct nlattr *data[],
struct __ip6_tnl_parm *parms)
{
memset(parms, 0, sizeof(*parms));
if (!data)
return;
if (data[IFLA_GRE_LINK])
parms->link = nla_get_u32(data[IFLA_GRE_LINK]);
if (data[IFLA_GRE_IFLAGS])
parms->i_flags = gre_flags_to_tnl_flags(
nla_get_be16(data[IFLA_GRE_IFLAGS]));
if (data[IFLA_GRE_OFLAGS])
parms->o_flags = gre_flags_to_tnl_flags(
nla_get_be16(data[IFLA_GRE_OFLAGS]));
if (data[IFLA_GRE_IKEY])
parms->i_key = nla_get_be32(data[IFLA_GRE_IKEY]);
if (data[IFLA_GRE_OKEY])
parms->o_key = nla_get_be32(data[IFLA_GRE_OKEY]);
if (data[IFLA_GRE_LOCAL])
parms->laddr = nla_get_in6_addr(data[IFLA_GRE_LOCAL]);
if (data[IFLA_GRE_REMOTE])
parms->raddr = nla_get_in6_addr(data[IFLA_GRE_REMOTE]);
if (data[IFLA_GRE_TTL])
parms->hop_limit = nla_get_u8(data[IFLA_GRE_TTL]);
if (data[IFLA_GRE_ENCAP_LIMIT])
parms->encap_limit = nla_get_u8(data[IFLA_GRE_ENCAP_LIMIT]);
if (data[IFLA_GRE_FLOWINFO])
parms->flowinfo = nla_get_be32(data[IFLA_GRE_FLOWINFO]);
if (data[IFLA_GRE_FLAGS])
parms->flags = nla_get_u32(data[IFLA_GRE_FLAGS]);
if (data[IFLA_GRE_FWMARK])
parms->fwmark = nla_get_u32(data[IFLA_GRE_FWMARK]);
if (data[IFLA_GRE_COLLECT_METADATA])
parms->collect_md = true;
}
static int ip6gre_tap_init(struct net_device *dev)
{
int ret;
ret = ip6gre_tunnel_init_common(dev);
if (ret)
return ret;
dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
return 0;
}
static const struct net_device_ops ip6gre_tap_netdev_ops = {
.ndo_init = ip6gre_tap_init,
.ndo_uninit = ip6gre_tunnel_uninit,
.ndo_start_xmit = ip6gre_tunnel_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = ip6_tnl_change_mtu,
.ndo_get_stats64 = dev_get_tstats64,
.ndo_get_iflink = ip6_tnl_get_iflink,
};
static int ip6erspan_calc_hlen(struct ip6_tnl *tunnel)
{
int t_hlen;
tunnel->tun_hlen = 8;
tunnel->hlen = tunnel->tun_hlen + tunnel->encap_hlen +
erspan_hdr_len(tunnel->parms.erspan_ver);
t_hlen = tunnel->hlen + sizeof(struct ipv6hdr);
tunnel->dev->needed_headroom = LL_MAX_HEADER + t_hlen;
return t_hlen;
}
static int ip6erspan_tap_init(struct net_device *dev)
{
struct ip6_tnl *tunnel;
int t_hlen;
int ret;
tunnel = netdev_priv(dev);
tunnel->dev = dev;
tunnel->net = dev_net(dev);
strcpy(tunnel->parms.name, dev->name);
dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
if (!dev->tstats)
return -ENOMEM;
ret = dst_cache_init(&tunnel->dst_cache, GFP_KERNEL);
if (ret)
goto cleanup_alloc_pcpu_stats;
ret = gro_cells_init(&tunnel->gro_cells, dev);
if (ret)
goto cleanup_dst_cache_init;
t_hlen = ip6erspan_calc_hlen(tunnel);
dev->mtu = ETH_DATA_LEN - t_hlen;
if (dev->type == ARPHRD_ETHER)
dev->mtu -= ETH_HLEN;
if (!(tunnel->parms.flags & IP6_TNL_F_IGN_ENCAP_LIMIT))
dev->mtu -= 8;
dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
ip6erspan_tnl_link_config(tunnel, 1);
return 0;
cleanup_dst_cache_init:
dst_cache_destroy(&tunnel->dst_cache);
cleanup_alloc_pcpu_stats:
free_percpu(dev->tstats);
dev->tstats = NULL;
return ret;
}
static const struct net_device_ops ip6erspan_netdev_ops = {
.ndo_init = ip6erspan_tap_init,
.ndo_uninit = ip6erspan_tunnel_uninit,
.ndo_start_xmit = ip6erspan_tunnel_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_change_mtu = ip6_tnl_change_mtu,
.ndo_get_stats64 = dev_get_tstats64,
.ndo_get_iflink = ip6_tnl_get_iflink,
};
static void ip6gre_tap_setup(struct net_device *dev)
{
ether_setup(dev);
dev->max_mtu = 0;
dev->netdev_ops = &ip6gre_tap_netdev_ops;
dev->needs_free_netdev = true;
dev->priv_destructor = ip6gre_dev_free;
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
netif_keep_dst(dev);
}
static bool ip6gre_netlink_encap_parms(struct nlattr *data[],
struct ip_tunnel_encap *ipencap)
{
bool ret = false;
memset(ipencap, 0, sizeof(*ipencap));
if (!data)
return ret;
if (data[IFLA_GRE_ENCAP_TYPE]) {
ret = true;
ipencap->type = nla_get_u16(data[IFLA_GRE_ENCAP_TYPE]);
}
if (data[IFLA_GRE_ENCAP_FLAGS]) {
ret = true;
ipencap->flags = nla_get_u16(data[IFLA_GRE_ENCAP_FLAGS]);
}
if (data[IFLA_GRE_ENCAP_SPORT]) {
ret = true;
ipencap->sport = nla_get_be16(data[IFLA_GRE_ENCAP_SPORT]);
}
if (data[IFLA_GRE_ENCAP_DPORT]) {
ret = true;
ipencap->dport = nla_get_be16(data[IFLA_GRE_ENCAP_DPORT]);
}
return ret;
}
static int ip6gre_newlink_common(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct ip6_tnl *nt;
struct ip_tunnel_encap ipencap;
int err;
nt = netdev_priv(dev);
if (ip6gre_netlink_encap_parms(data, &ipencap)) {
int err = ip6_tnl_encap_setup(nt, &ipencap);
if (err < 0)
return err;
}
if (dev->type == ARPHRD_ETHER && !tb[IFLA_ADDRESS])
eth_hw_addr_random(dev);
nt->dev = dev;
nt->net = dev_net(dev);
err = register_netdevice(dev);
if (err)
goto out;
if (tb[IFLA_MTU])
ip6_tnl_change_mtu(dev, nla_get_u32(tb[IFLA_MTU]));
dev_hold(dev);
out:
return err;
}
static int ip6gre_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct ip6_tnl *nt = netdev_priv(dev);
struct net *net = dev_net(dev);
struct ip6gre_net *ign;
int err;
ip6gre_netlink_parms(data, &nt->parms);
ign = net_generic(net, ip6gre_net_id);
if (nt->parms.collect_md) {
if (rtnl_dereference(ign->collect_md_tun))
return -EEXIST;
} else {
if (ip6gre_tunnel_find(net, &nt->parms, dev->type))
return -EEXIST;
}
err = ip6gre_newlink_common(src_net, dev, tb, data, extack);
if (!err) {
ip6gre_tnl_link_config(nt, !tb[IFLA_MTU]);
ip6gre_tunnel_link_md(ign, nt);
ip6gre_tunnel_link(net_generic(net, ip6gre_net_id), nt);
}
return err;
}
static struct ip6_tnl *
ip6gre_changelink_common(struct net_device *dev, struct nlattr *tb[],
struct nlattr *data[], struct __ip6_tnl_parm *p_p,
struct netlink_ext_ack *extack)
{
struct ip6_tnl *t, *nt = netdev_priv(dev);
struct net *net = nt->net;
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
struct ip_tunnel_encap ipencap;
if (dev == ign->fb_tunnel_dev)
return ERR_PTR(-EINVAL);
if (ip6gre_netlink_encap_parms(data, &ipencap)) {
int err = ip6_tnl_encap_setup(nt, &ipencap);
if (err < 0)
return ERR_PTR(err);
}
ip6gre_netlink_parms(data, p_p);
t = ip6gre_tunnel_locate(net, p_p, 0);
if (t) {
if (t->dev != dev)
return ERR_PTR(-EEXIST);
} else {
t = nt;
}
return t;
}
static int ip6gre_changelink(struct net_device *dev, struct nlattr *tb[],
struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct ip6_tnl *t = netdev_priv(dev);
struct ip6gre_net *ign = net_generic(t->net, ip6gre_net_id);
struct __ip6_tnl_parm p;
t = ip6gre_changelink_common(dev, tb, data, &p, extack);
if (IS_ERR(t))
return PTR_ERR(t);
ip6gre_tunnel_unlink_md(ign, t);
ip6gre_tunnel_unlink(ign, t);
ip6gre_tnl_change(t, &p, !tb[IFLA_MTU]);
ip6gre_tunnel_link_md(ign, t);
ip6gre_tunnel_link(ign, t);
return 0;
}
static void ip6gre_dellink(struct net_device *dev, struct list_head *head)
{
struct net *net = dev_net(dev);
struct ip6gre_net *ign = net_generic(net, ip6gre_net_id);
if (dev != ign->fb_tunnel_dev)
unregister_netdevice_queue(dev, head);
}
static size_t ip6gre_get_size(const struct net_device *dev)
{
return
/* IFLA_GRE_LINK */
nla_total_size(4) +
/* IFLA_GRE_IFLAGS */
nla_total_size(2) +
/* IFLA_GRE_OFLAGS */
nla_total_size(2) +
/* IFLA_GRE_IKEY */
nla_total_size(4) +
/* IFLA_GRE_OKEY */
nla_total_size(4) +
/* IFLA_GRE_LOCAL */
nla_total_size(sizeof(struct in6_addr)) +
/* IFLA_GRE_REMOTE */
nla_total_size(sizeof(struct in6_addr)) +
/* IFLA_GRE_TTL */
nla_total_size(1) +
/* IFLA_GRE_ENCAP_LIMIT */
nla_total_size(1) +
/* IFLA_GRE_FLOWINFO */
nla_total_size(4) +
/* IFLA_GRE_FLAGS */
nla_total_size(4) +
/* IFLA_GRE_ENCAP_TYPE */
nla_total_size(2) +
/* IFLA_GRE_ENCAP_FLAGS */
nla_total_size(2) +
/* IFLA_GRE_ENCAP_SPORT */
nla_total_size(2) +
/* IFLA_GRE_ENCAP_DPORT */
nla_total_size(2) +
/* IFLA_GRE_COLLECT_METADATA */
nla_total_size(0) +
/* IFLA_GRE_FWMARK */
nla_total_size(4) +
/* IFLA_GRE_ERSPAN_INDEX */
nla_total_size(4) +
0;
}
static int ip6gre_fill_info(struct sk_buff *skb, const struct net_device *dev)
{
struct ip6_tnl *t = netdev_priv(dev);
struct __ip6_tnl_parm *p = &t->parms;
__be16 o_flags = p->o_flags;
if (p->erspan_ver == 1 || p->erspan_ver == 2) {
if (!p->collect_md)
o_flags |= TUNNEL_KEY;
if (nla_put_u8(skb, IFLA_GRE_ERSPAN_VER, p->erspan_ver))
goto nla_put_failure;
if (p->erspan_ver == 1) {
if (nla_put_u32(skb, IFLA_GRE_ERSPAN_INDEX, p->index))
goto nla_put_failure;
} else {
if (nla_put_u8(skb, IFLA_GRE_ERSPAN_DIR, p->dir))
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_GRE_ERSPAN_HWID, p->hwid))
goto nla_put_failure;
}
}
if (nla_put_u32(skb, IFLA_GRE_LINK, p->link) ||
nla_put_be16(skb, IFLA_GRE_IFLAGS,
gre_tnl_flags_to_gre_flags(p->i_flags)) ||
nla_put_be16(skb, IFLA_GRE_OFLAGS,
gre_tnl_flags_to_gre_flags(o_flags)) ||
nla_put_be32(skb, IFLA_GRE_IKEY, p->i_key) ||
nla_put_be32(skb, IFLA_GRE_OKEY, p->o_key) ||
nla_put_in6_addr(skb, IFLA_GRE_LOCAL, &p->laddr) ||
nla_put_in6_addr(skb, IFLA_GRE_REMOTE, &p->raddr) ||
nla_put_u8(skb, IFLA_GRE_TTL, p->hop_limit) ||
nla_put_u8(skb, IFLA_GRE_ENCAP_LIMIT, p->encap_limit) ||
nla_put_be32(skb, IFLA_GRE_FLOWINFO, p->flowinfo) ||
nla_put_u32(skb, IFLA_GRE_FLAGS, p->flags) ||
nla_put_u32(skb, IFLA_GRE_FWMARK, p->fwmark))
goto nla_put_failure;
if (nla_put_u16(skb, IFLA_GRE_ENCAP_TYPE,
t->encap.type) ||
nla_put_be16(skb, IFLA_GRE_ENCAP_SPORT,
t->encap.sport) ||
nla_put_be16(skb, IFLA_GRE_ENCAP_DPORT,
t->encap.dport) ||
nla_put_u16(skb, IFLA_GRE_ENCAP_FLAGS,
t->encap.flags))
goto nla_put_failure;
if (p->collect_md) {
if (nla_put_flag(skb, IFLA_GRE_COLLECT_METADATA))
goto nla_put_failure;
}
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static const struct nla_policy ip6gre_policy[IFLA_GRE_MAX + 1] = {
[IFLA_GRE_LINK] = { .type = NLA_U32 },
[IFLA_GRE_IFLAGS] = { .type = NLA_U16 },
[IFLA_GRE_OFLAGS] = { .type = NLA_U16 },
[IFLA_GRE_IKEY] = { .type = NLA_U32 },
[IFLA_GRE_OKEY] = { .type = NLA_U32 },
[IFLA_GRE_LOCAL] = { .len = sizeof_field(struct ipv6hdr, saddr) },
[IFLA_GRE_REMOTE] = { .len = sizeof_field(struct ipv6hdr, daddr) },
[IFLA_GRE_TTL] = { .type = NLA_U8 },
[IFLA_GRE_ENCAP_LIMIT] = { .type = NLA_U8 },
[IFLA_GRE_FLOWINFO] = { .type = NLA_U32 },
[IFLA_GRE_FLAGS] = { .type = NLA_U32 },
[IFLA_GRE_ENCAP_TYPE] = { .type = NLA_U16 },
[IFLA_GRE_ENCAP_FLAGS] = { .type = NLA_U16 },
[IFLA_GRE_ENCAP_SPORT] = { .type = NLA_U16 },
[IFLA_GRE_ENCAP_DPORT] = { .type = NLA_U16 },
[IFLA_GRE_COLLECT_METADATA] = { .type = NLA_FLAG },
[IFLA_GRE_FWMARK] = { .type = NLA_U32 },
[IFLA_GRE_ERSPAN_INDEX] = { .type = NLA_U32 },
[IFLA_GRE_ERSPAN_VER] = { .type = NLA_U8 },
[IFLA_GRE_ERSPAN_DIR] = { .type = NLA_U8 },
[IFLA_GRE_ERSPAN_HWID] = { .type = NLA_U16 },
};
static void ip6erspan_tap_setup(struct net_device *dev)
{
ether_setup(dev);
dev->max_mtu = 0;
dev->netdev_ops = &ip6erspan_netdev_ops;
dev->needs_free_netdev = true;
dev->priv_destructor = ip6gre_dev_free;
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
netif_keep_dst(dev);
}
static int ip6erspan_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct ip6_tnl *nt = netdev_priv(dev);
struct net *net = dev_net(dev);
struct ip6gre_net *ign;
int err;
ip6gre_netlink_parms(data, &nt->parms);
ip6erspan_set_version(data, &nt->parms);
ign = net_generic(net, ip6gre_net_id);
if (nt->parms.collect_md) {
if (rtnl_dereference(ign->collect_md_tun_erspan))
return -EEXIST;
} else {
if (ip6gre_tunnel_find(net, &nt->parms, dev->type))
return -EEXIST;
}
err = ip6gre_newlink_common(src_net, dev, tb, data, extack);
if (!err) {
ip6erspan_tnl_link_config(nt, !tb[IFLA_MTU]);
ip6erspan_tunnel_link_md(ign, nt);
ip6gre_tunnel_link(net_generic(net, ip6gre_net_id), nt);
}
return err;
}
static void ip6erspan_tnl_link_config(struct ip6_tnl *t, int set_mtu)
{
ip6gre_tnl_link_config_common(t);
ip6gre_tnl_link_config_route(t, set_mtu, ip6erspan_calc_hlen(t));
}
static int ip6erspan_tnl_change(struct ip6_tnl *t,
const struct __ip6_tnl_parm *p, int set_mtu)
{
ip6gre_tnl_copy_tnl_parm(t, p);
ip6erspan_tnl_link_config(t, set_mtu);
return 0;
}
static int ip6erspan_changelink(struct net_device *dev, struct nlattr *tb[],
struct nlattr *data[],
struct netlink_ext_ack *extack)
{
struct ip6gre_net *ign = net_generic(dev_net(dev), ip6gre_net_id);
struct __ip6_tnl_parm p;
struct ip6_tnl *t;
t = ip6gre_changelink_common(dev, tb, data, &p, extack);
if (IS_ERR(t))
return PTR_ERR(t);
ip6erspan_set_version(data, &p);
ip6gre_tunnel_unlink_md(ign, t);
ip6gre_tunnel_unlink(ign, t);
ip6erspan_tnl_change(t, &p, !tb[IFLA_MTU]);
ip6erspan_tunnel_link_md(ign, t);
ip6gre_tunnel_link(ign, t);
return 0;
}
static struct rtnl_link_ops ip6gre_link_ops __read_mostly = {
.kind = "ip6gre",
.maxtype = IFLA_GRE_MAX,
.policy = ip6gre_policy,
.priv_size = sizeof(struct ip6_tnl),
.setup = ip6gre_tunnel_setup,
.validate = ip6gre_tunnel_validate,
.newlink = ip6gre_newlink,
.changelink = ip6gre_changelink,
.dellink = ip6gre_dellink,
.get_size = ip6gre_get_size,
.fill_info = ip6gre_fill_info,
.get_link_net = ip6_tnl_get_link_net,
};
static struct rtnl_link_ops ip6gre_tap_ops __read_mostly = {
.kind = "ip6gretap",
.maxtype = IFLA_GRE_MAX,
.policy = ip6gre_policy,
.priv_size = sizeof(struct ip6_tnl),
.setup = ip6gre_tap_setup,
.validate = ip6gre_tap_validate,
.newlink = ip6gre_newlink,
.changelink = ip6gre_changelink,
.get_size = ip6gre_get_size,
.fill_info = ip6gre_fill_info,
.get_link_net = ip6_tnl_get_link_net,
};
static struct rtnl_link_ops ip6erspan_tap_ops __read_mostly = {
.kind = "ip6erspan",
.maxtype = IFLA_GRE_MAX,
.policy = ip6gre_policy,
.priv_size = sizeof(struct ip6_tnl),
.setup = ip6erspan_tap_setup,
.validate = ip6erspan_tap_validate,
.newlink = ip6erspan_newlink,
.changelink = ip6erspan_changelink,
.get_size = ip6gre_get_size,
.fill_info = ip6gre_fill_info,
.get_link_net = ip6_tnl_get_link_net,
};
/*
* And now the modules code and kernel interface.
*/
static int __init ip6gre_init(void)
{
int err;
pr_info("GRE over IPv6 tunneling driver\n");
err = register_pernet_device(&ip6gre_net_ops);
if (err < 0)
return err;
err = inet6_add_protocol(&ip6gre_protocol, IPPROTO_GRE);
if (err < 0) {
pr_info("%s: can't add protocol\n", __func__);
goto add_proto_failed;
}
err = rtnl_link_register(&ip6gre_link_ops);
if (err < 0)
goto rtnl_link_failed;
err = rtnl_link_register(&ip6gre_tap_ops);
if (err < 0)
goto tap_ops_failed;
err = rtnl_link_register(&ip6erspan_tap_ops);
if (err < 0)
goto erspan_link_failed;
out:
return err;
erspan_link_failed:
rtnl_link_unregister(&ip6gre_tap_ops);
tap_ops_failed:
rtnl_link_unregister(&ip6gre_link_ops);
rtnl_link_failed:
inet6_del_protocol(&ip6gre_protocol, IPPROTO_GRE);
add_proto_failed:
unregister_pernet_device(&ip6gre_net_ops);
goto out;
}
static void __exit ip6gre_fini(void)
{
rtnl_link_unregister(&ip6gre_tap_ops);
rtnl_link_unregister(&ip6gre_link_ops);
rtnl_link_unregister(&ip6erspan_tap_ops);
inet6_del_protocol(&ip6gre_protocol, IPPROTO_GRE);
unregister_pernet_device(&ip6gre_net_ops);
}
module_init(ip6gre_init);
module_exit(ip6gre_fini);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("D. Kozlov ([email protected])");
MODULE_DESCRIPTION("GRE over IPv6 tunneling device");
MODULE_ALIAS_RTNL_LINK("ip6gre");
MODULE_ALIAS_RTNL_LINK("ip6gretap");
MODULE_ALIAS_RTNL_LINK("ip6erspan");
MODULE_ALIAS_NETDEV("ip6gre0");
| openwrt-es/linux | net/ipv6/ip6_gre.c | C | gpl-2.0 | 59,568 |
#include_next <internaltypes.h>
#ifndef _INTERNAL_TYPES_H_HPPA_
#define _INTERNAL_TYPES_H_HPPA_ 1
#include <atomic.h>
/* In GLIBC 2.10 HPPA switched from Linuxthreads to NPTL, and in order
to maintain ABI compatibility with pthread_cond_t, some care had to be
taken.
The NPTL pthread_cond_t grew in size. When HPPA switched to NPTL, we
dropped the use of ldcw, and switched to the kernel helper routine for
compare-and-swap. This allowed HPPA to use the 4-word 16-byte aligned
lock words, and alignment words to store the additional pthread_cond_t
data. Once organized properly the new NPTL pthread_cond_t was 1 word
smaller than the Linuxthreads version.
However, we were faced with the case that users may have initialized the
pthread_cond_t with PTHREAD_COND_INITIALIZER. In this case, the first
four words were set to one, and must be cleared before any NPTL code
used these words.
We didn't want to use LDCW, because it continues to be a source of bugs
when applications memset pthread_cond_t to all zeroes by accident. This
works on all other architectures where lock words are unlocked at zero.
Remember that because of the semantics of LDCW, a locked word is set to
zero, and an unlocked word is set to 1.
Instead we used atomic_compare_and_exchange_val_acq, but we couldn't use
this on any of the pthread_cond_t words, otherwise it might interfere
with the current operation of the structure. To solve this problem we
used the left over word.
If the stucture was initialized by a legacy Linuxthread
PTHREAD_COND_INITIALIZER it contained a 1, and this indicates that the
structure requires zeroing for NPTL. The first thread to come upon a
pthread_cond_t with a 1 in the __initializer field, will
compare-and-swap the value, placing a 2 there which will cause all other
threads using the same pthread_cond_t to wait for the completion of the
initialization. Lastly, we use a store (with memory barrier) to change
__initializer from 2 to 0. Note that the store is strongly ordered, but
we use the PA 1.1 compatible form which is ",ma" with zero offset.
In the future, when the application is recompiled with NPTL
PTHREAD_COND_INITIALIZER it will be a quick compare-and-swap, which
fails because __initializer is zero, and the structure will be used as
is correctly. */
#define cond_compat_clear(var) \
({ \
int tmp = 0; \
var->__data.__lock = 0; \
var->__data.__futex = 0; \
var->__data.__mutex = NULL; \
/* Clear __initializer last, to indicate initialization is done. */ \
__asm__ __volatile__ ("stw,ma %1,0(%0)" \
: : "r" (&var->__data.__initializer), "r" (tmp) : "memory"); \
})
#define cond_compat_check_and_clear(var) \
({ \
int ret; \
volatile int *value = &var->__data.__initializer; \
if ((ret = atomic_compare_and_exchange_val_acq(value, 2, 1))) \
{ \
if (ret == 1) \
{ \
/* Initialize structure. */ \
cond_compat_clear (var); \
} \
else \
{ \
/* Yield until structure is initialized. */ \
while (*value == 2) sched_yield (); \
} \
} \
})
#endif
| SanDisk-Open-Source/SSD_Dashboard | uefi/userspace/glibc/ports/sysdeps/unix/sysv/linux/hppa/internaltypes.h | C | gpl-2.0 | 3,169 |
/*
* linux/drivers/mmc/core/mmc_ops.h
*
* Copyright 2006-2007 Pierre Ossman
*
* 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.
*/
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/types.h>
#include <linux/scatterlist.h>
#include <linux/mmc/host.h>
#include <linux/mmc/card.h>
#include <linux/mmc/mmc.h>
#include "core.h"
#include "mmc_ops.h"
#define MMC_OPS_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */
static int _mmc_select_card(struct mmc_host *host, struct mmc_card *card)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!host);
cmd.opcode = MMC_SELECT_CARD;
if (card) {
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
} else {
cmd.arg = 0;
cmd.flags = MMC_RSP_NONE | MMC_CMD_AC;
}
err = mmc_wait_for_cmd(host, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
return 0;
}
int mmc_select_card(struct mmc_card *card)
{
BUG_ON(!card);
return _mmc_select_card(card->host, card);
}
int mmc_deselect_cards(struct mmc_host *host)
{
return _mmc_select_card(host, NULL);
}
int mmc_card_sleepawake(struct mmc_host *host, int sleep)
{
struct mmc_command cmd = {0};
struct mmc_card *card = host->card;
int err;
if (sleep)
mmc_deselect_cards(host);
cmd.opcode = MMC_SLEEP_AWAKE;
cmd.arg = card->rca << 16;
if (sleep)
cmd.arg |= 1 << 15;
cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
err = mmc_wait_for_cmd(host, &cmd, 0);
if (err)
return err;
/*
* If the host does not wait while the card signals busy, then we will
* will have to wait the sleep/awake timeout. Note, we cannot use the
* SEND_STATUS command to poll the status because that command (and most
* others) is invalid while the card sleeps.
*/
if (!(host->caps & MMC_CAP_WAIT_WHILE_BUSY))
mmc_delay(DIV_ROUND_UP(card->ext_csd.sa_timeout, 10000));
if (!sleep)
err = mmc_select_card(card);
return err;
}
int mmc_go_idle(struct mmc_host *host)
{
int err;
struct mmc_command cmd = {0};
/*
* Non-SPI hosts need to prevent chipselect going active during
* GO_IDLE; that would put chips into SPI mode. Remind them of
* that in case of hardware that won't pull up DAT3/nCS otherwise.
*
* SPI hosts ignore ios.chip_select; it's managed according to
* rules that must accommodate non-MMC slaves which this layer
* won't even know about.
*/
if (!mmc_host_is_spi(host)) {
mmc_set_chip_select(host, MMC_CS_HIGH);
mmc_delay(1);
}
cmd.opcode = MMC_GO_IDLE_STATE;
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_NONE | MMC_CMD_BC;
err = mmc_wait_for_cmd(host, &cmd, 0);
mmc_delay(1);
if (!mmc_host_is_spi(host)) {
mmc_set_chip_select(host, MMC_CS_DONTCARE);
mmc_delay(1);
}
host->use_spi_crc = 0;
return err;
}
int mmc_send_op_cond(struct mmc_host *host, u32 ocr, u32 *rocr)
{
struct mmc_command cmd = {0};
int i, err = 0;
BUG_ON(!host);
cmd.opcode = MMC_SEND_OP_COND;
cmd.arg = mmc_host_is_spi(host) ? 0 : ocr;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R3 | MMC_CMD_BCR;
for (i = 100; i; i--) {
err = mmc_wait_for_cmd(host, &cmd, 0);
if (err)
break;
/* if we're just probing, do a single pass */
if (ocr == 0)
break;
/* otherwise wait until reset completes */
if (mmc_host_is_spi(host)) {
if (!(cmd.resp[0] & R1_SPI_IDLE))
break;
} else {
if (cmd.resp[0] & MMC_CARD_BUSY)
break;
}
err = -ETIMEDOUT;
mmc_delay(10);
}
if (rocr && !mmc_host_is_spi(host))
*rocr = cmd.resp[0];
return err;
}
int mmc_all_send_cid(struct mmc_host *host, u32 *cid)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!host);
BUG_ON(!cid);
cmd.opcode = MMC_ALL_SEND_CID;
cmd.arg = 0;
cmd.flags = MMC_RSP_R2 | MMC_CMD_BCR;
err = mmc_wait_for_cmd(host, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
memcpy(cid, cmd.resp, sizeof(u32) * 4);
return 0;
}
int mmc_set_relative_addr(struct mmc_card *card)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!card);
BUG_ON(!card->host);
cmd.opcode = MMC_SET_RELATIVE_ADDR;
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
return 0;
}
static int
mmc_send_cxd_native(struct mmc_host *host, u32 arg, u32 *cxd, int opcode)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!host);
BUG_ON(!cxd);
cmd.opcode = opcode;
cmd.arg = arg;
cmd.flags = MMC_RSP_R2 | MMC_CMD_AC;
err = mmc_wait_for_cmd(host, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
memcpy(cxd, cmd.resp, sizeof(u32) * 4);
return 0;
}
static int
mmc_send_cxd_data(struct mmc_card *card, struct mmc_host *host,
u32 opcode, void *buf, unsigned len)
{
struct mmc_request mrq = {NULL};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
void *data_buf;
/* dma onto stack is unsafe/nonportable, but callers to this
* routine normally provide temporary on-stack buffers ...
*/
data_buf = kmalloc(len, GFP_KERNEL);
if (data_buf == NULL)
return -ENOMEM;
mrq.cmd = &cmd;
mrq.data = &data;
cmd.opcode = opcode;
cmd.arg = 0;
/* NOTE HACK: the MMC_RSP_SPI_R1 is always correct here, but we
* rely on callers to never use this with "native" calls for reading
* CSD or CID. Native versions of those commands use the R2 type,
* not R1 plus a data block.
*/
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = len;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
sg_init_one(&sg, data_buf, len);
if (opcode == MMC_SEND_CSD || opcode == MMC_SEND_CID) {
/*
* The spec states that CSR and CID accesses have a timeout
* of 64 clock cycles.
*/
data.timeout_ns = 0;
data.timeout_clks = 64;
} else
mmc_set_data_timeout(&data, card);
mmc_wait_for_req(host, &mrq);
memcpy(buf, data_buf, len);
kfree(data_buf);
if (cmd.error)
return cmd.error;
if (data.error)
return data.error;
return 0;
}
int mmc_send_csd(struct mmc_card *card, u32 *csd)
{
int ret, i;
if (!mmc_host_is_spi(card->host))
return mmc_send_cxd_native(card->host, card->rca << 16,
csd, MMC_SEND_CSD);
ret = mmc_send_cxd_data(card, card->host, MMC_SEND_CSD, csd, 16);
if (ret)
return ret;
for (i = 0;i < 4;i++)
csd[i] = be32_to_cpu(csd[i]);
return 0;
}
int mmc_send_cid(struct mmc_host *host, u32 *cid)
{
int ret, i;
if (!mmc_host_is_spi(host)) {
if (!host->card)
return -EINVAL;
return mmc_send_cxd_native(host, host->card->rca << 16,
cid, MMC_SEND_CID);
}
ret = mmc_send_cxd_data(NULL, host, MMC_SEND_CID, cid, 16);
if (ret)
return ret;
for (i = 0;i < 4;i++)
cid[i] = be32_to_cpu(cid[i]);
return 0;
}
int mmc_send_ext_csd(struct mmc_card *card, u8 *ext_csd)
{
return mmc_send_cxd_data(card, card->host, MMC_SEND_EXT_CSD,
ext_csd, 512);
}
EXPORT_SYMBOL_GPL(mmc_send_ext_csd);
int mmc_spi_read_ocr(struct mmc_host *host, int highcap, u32 *ocrp)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_SPI_READ_OCR;
cmd.arg = highcap ? (1 << 30) : 0;
cmd.flags = MMC_RSP_SPI_R3;
err = mmc_wait_for_cmd(host, &cmd, 0);
*ocrp = cmd.resp[1];
return err;
}
int mmc_spi_set_crc(struct mmc_host *host, int use_crc)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_SPI_CRC_ON_OFF;
cmd.flags = MMC_RSP_SPI_R1;
cmd.arg = use_crc;
err = mmc_wait_for_cmd(host, &cmd, 0);
if (!err)
host->use_spi_crc = use_crc;
return err;
}
/**
* mmc_switch - modify EXT_CSD register
* @card: the MMC card associated with the data transfer
* @set: cmd set values
* @index: EXT_CSD register index
* @value: value to program into EXT_CSD register
* @timeout_ms: timeout (ms) for operation performed by register write,
* timeout of zero implies maximum possible timeout
*
* Modifies the EXT_CSD register for selected card.
*/
int mmc_switch(struct mmc_card *card, u8 set, u8 index, u8 value,
unsigned int timeout_ms)
{
int err;
struct mmc_command cmd = {0};
unsigned int ignore;
unsigned long timeout;
u32 status;
BUG_ON(!card);
BUG_ON(!card->host);
cmd.opcode = MMC_SWITCH;
cmd.arg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) |
(index << 16) |
(value << 8) |
set;
cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
cmd.cmd_timeout_ms = timeout_ms;
err = mmc_wait_for_cmd(card->host, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
/* Must check status to be sure of no errors */
timeout = jiffies + msecs_to_jiffies(MMC_OPS_TIMEOUT_MS);
ignore = (index == EXT_CSD_HS_TIMING) ? MMC_RSP_CRC : 0;
do {
err = mmc_send_status(card, &status, ignore);
if (err)
return err;
if (card->host->caps & MMC_CAP_WAIT_WHILE_BUSY)
break;
if (mmc_host_is_spi(card->host))
break;
/* Timeout if the device never leaves the program state. */
if (time_after(jiffies, timeout)) {
pr_err("%s: Card stuck in programming state! %s\n",
mmc_hostname(card->host), __func__);
return -ETIMEDOUT;
}
} while (R1_CURRENT_STATE(status) == R1_STATE_PRG);
if (mmc_host_is_spi(card->host)) {
if (status & R1_SPI_ILLEGAL_COMMAND)
return -EBADMSG;
} else {
if (status & 0xFDFFA000)
pr_warning("%s: unexpected status %#x after "
"switch", mmc_hostname(card->host), status);
if (status & R1_SWITCH_ERROR)
return -EBADMSG;
}
return 0;
}
EXPORT_SYMBOL_GPL(mmc_switch);
int mmc_send_status(struct mmc_card *card, u32 *status, unsigned int ignore)
{
int err;
struct mmc_command cmd = {0};
BUG_ON(!card);
BUG_ON(!card->host);
cmd.opcode = MMC_SEND_STATUS;
if (!mmc_host_is_spi(card->host))
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
cmd.flags &= ~ignore;
err = mmc_wait_for_cmd(card->host, &cmd, MMC_CMD_RETRIES);
if (err)
return err;
/* NOTE: callers are required to understand the difference
* between "native" and SPI format status words!
*/
if (status)
*status = cmd.resp[0];
return 0;
}
static int
mmc_send_bus_test(struct mmc_card *card, struct mmc_host *host, u8 opcode,
u8 len)
{
struct mmc_request mrq = {NULL};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
u8 *data_buf;
u8 *test_buf;
int i, err;
static u8 testdata_8bit[8] = { 0x55, 0xaa, 0, 0, 0, 0, 0, 0 };
static u8 testdata_4bit[4] = { 0x5a, 0, 0, 0 };
/* dma onto stack is unsafe/nonportable, but callers to this
* routine normally provide temporary on-stack buffers ...
*/
data_buf = kmalloc(len, GFP_KERNEL);
if (!data_buf)
return -ENOMEM;
if (len == 8)
test_buf = testdata_8bit;
else if (len == 4)
test_buf = testdata_4bit;
else {
pr_err("%s: Invalid bus_width %d\n",
mmc_hostname(host), len);
kfree(data_buf);
return -EINVAL;
}
if (opcode == MMC_BUS_TEST_W)
memcpy(data_buf, test_buf, len);
mrq.cmd = &cmd;
mrq.data = &data;
cmd.opcode = opcode;
cmd.arg = 0;
/* NOTE HACK: the MMC_RSP_SPI_R1 is always correct here, but we
* rely on callers to never use this with "native" calls for reading
* CSD or CID. Native versions of those commands use the R2 type,
* not R1 plus a data block.
*/
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = len;
data.blocks = 1;
if (opcode == MMC_BUS_TEST_R)
data.flags = MMC_DATA_READ;
else
data.flags = MMC_DATA_WRITE;
data.sg = &sg;
data.sg_len = 1;
sg_init_one(&sg, data_buf, len);
mmc_wait_for_req(host, &mrq);
err = 0;
if (opcode == MMC_BUS_TEST_R) {
for (i = 0; i < len / 4; i++)
if ((test_buf[i] ^ data_buf[i]) != 0xff) {
err = -EIO;
break;
}
}
kfree(data_buf);
if (cmd.error)
return cmd.error;
if (data.error)
return data.error;
return err;
}
int mmc_bus_test(struct mmc_card *card, u8 bus_width)
{
int err, width;
if (bus_width == MMC_BUS_WIDTH_8)
width = 8;
else if (bus_width == MMC_BUS_WIDTH_4)
width = 4;
else if (bus_width == MMC_BUS_WIDTH_1)
return 0; /* no need for test */
else
return -EINVAL;
/*
* Ignore errors from BUS_TEST_W. BUS_TEST_R will fail if there
* is a problem. This improves chances that the test will work.
*/
mmc_send_bus_test(card, card->host, MMC_BUS_TEST_W, width);
err = mmc_send_bus_test(card, card->host, MMC_BUS_TEST_R, width);
return err;
}
int mmc_send_hpi_cmd(struct mmc_card *card, u32 *status)
{
struct mmc_command cmd = {0};
unsigned int opcode;
int err;
if (!card->ext_csd.hpi) {
pr_warning("%s: Card didn't support HPI command\n",
mmc_hostname(card->host));
return -EINVAL;
}
opcode = card->ext_csd.hpi_cmd;
if (opcode == MMC_STOP_TRANSMISSION)
cmd.flags = MMC_RSP_R1B | MMC_CMD_AC;
else if (opcode == MMC_SEND_STATUS)
cmd.flags = MMC_RSP_R1 | MMC_CMD_AC;
cmd.opcode = opcode;
cmd.arg = card->rca << 16 | 1;
cmd.cmd_timeout_ms = card->ext_csd.out_of_int_time;
err = mmc_wait_for_cmd(card->host, &cmd, 0);
if (err) {
pr_warn("%s: error %d interrupting operation. "
"HPI command response %#x\n", mmc_hostname(card->host),
err, cmd.resp[0]);
return err;
}
if (status)
*status = cmd.resp[0];
return 0;
}
| nbars/Custom-Kernel-SM-P600 | kernel-src/drivers/mmc/core/mmc_ops.c | C | gpl-2.0 | 13,165 |
/*
* Support for PCI bridges found on Power Macintoshes.
* At present the "bandit" and "chaos" bridges are supported.
* Fortunately you access configuration space in the same
* way with either bridge.
*
* Copyright (C) 1997 Paul Mackerras ([email protected])
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <asm/sections.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#undef DEBUG
static void add_bridges(struct device_node *dev);
/* XXX Could be per-controller, but I don't think we risk anything by
* assuming we won't have both UniNorth and Bandit */
static int has_uninorth;
/*
* Magic constants for enabling cache coherency in the bandit/PSX bridge.
*/
#define BANDIT_DEVID_2 8
#define BANDIT_REVID 3
#define BANDIT_DEVNUM 11
#define BANDIT_MAGIC 0x50
#define BANDIT_COHERENT 0x40
static int __init
fixup_one_level_bus_range(struct device_node *node, int higher)
{
for (; node != 0;node = node->sibling) {
int * bus_range;
unsigned int *class_code;
int len;
/* For PCI<->PCI bridges or CardBus bridges, we go down */
class_code = (unsigned int *) get_property(node, "class-code", 0);
if (!class_code || ((*class_code >> 8) != PCI_CLASS_BRIDGE_PCI &&
(*class_code >> 8) != PCI_CLASS_BRIDGE_CARDBUS))
continue;
bus_range = (int *) get_property(node, "bus-range", &len);
if (bus_range != NULL && len > 2 * sizeof(int)) {
if (bus_range[1] > higher)
higher = bus_range[1];
}
higher = fixup_one_level_bus_range(node->child, higher);
}
return higher;
}
/* This routine fixes the "bus-range" property of all bridges in the
* system since they tend to have their "last" member wrong on macs
*
* Note that the bus numbers manipulated here are OF bus numbers, they
* are not Linux bus numbers.
*/
static void __init
fixup_bus_range(struct device_node *bridge)
{
int * bus_range;
int len;
/* Lookup the "bus-range" property for the hose */
bus_range = (int *) get_property(bridge, "bus-range", &len);
if (bus_range == NULL || len < 2 * sizeof(int)) {
printk(KERN_WARNING "Can't get bus-range for %s\n",
bridge->full_name);
return;
}
bus_range[1] = fixup_one_level_bus_range(bridge->child, bus_range[1]);
}
/*
* Apple MacRISC (UniNorth, Bandit, Chaos) PCI controllers.
*
* The "Bandit" version is present in all early PCI PowerMacs,
* and up to the first ones using Grackle. Some machines may
* have 2 bandit controllers (2 PCI busses).
*
* "Chaos" is used in some "Bandit"-type machines as a bridge
* for the separate display bus. It is accessed the same
* way as bandit, but cannot be probed for devices. It therefore
* has its own config access functions.
*
* The "UniNorth" version is present in all Core99 machines
* (iBook, G4, new IMacs, and all the recent Apple machines).
* It contains 3 controllers in one ASIC.
*/
#define MACRISC_CFA0(devfn, off) \
((1 << (unsigned long)PCI_SLOT(dev_fn)) \
| (((unsigned long)PCI_FUNC(dev_fn)) << 8) \
| (((unsigned long)(off)) & 0xFCUL))
#define MACRISC_CFA1(bus, devfn, off) \
((((unsigned long)(bus)) << 16) \
|(((unsigned long)(devfn)) << 8) \
|(((unsigned long)(off)) & 0xFCUL) \
|1UL)
static unsigned int __pmac
macrisc_cfg_access(struct pci_controller* hose, u8 bus, u8 dev_fn, u8 offset)
{
unsigned int caddr;
if (bus == hose->first_busno) {
if (dev_fn < (11 << 3))
return 0;
caddr = MACRISC_CFA0(dev_fn, offset);
} else
caddr = MACRISC_CFA1(bus, dev_fn, offset);
/* Uninorth will return garbage if we don't read back the value ! */
do {
out_le32(hose->cfg_addr, caddr);
} while(in_le32(hose->cfg_addr) != caddr);
offset &= has_uninorth ? 0x07 : 0x03;
return (unsigned int)(hose->cfg_data) + (unsigned int)offset;
}
#define cfg_read(val, addr, type, op, op2) \
*val = op((type)(addr))
#define cfg_write(val, addr, type, op, op2) \
op((type *)(addr), (val)); (void) op2((type *)(addr))
#define cfg_read_bad(val, size) *val = bad_##size;
#define cfg_write_bad(val, size)
#define bad_byte 0xff
#define bad_word 0xffff
#define bad_dword 0xffffffffU
#define MACRISC_PCI_OP(rw, size, type, op, op2) \
static int __pmac \
macrisc_##rw##_config_##size(struct pci_dev *dev, int off, type val) \
{ \
struct pci_controller *hose = dev->sysdata; \
unsigned int addr; \
\
addr = macrisc_cfg_access(hose, dev->bus->number, dev->devfn, off); \
if (!addr) { \
cfg_##rw##_bad(val, size) \
return PCIBIOS_DEVICE_NOT_FOUND; \
} \
cfg_##rw(val, addr, type, op, op2); \
return PCIBIOS_SUCCESSFUL; \
}
MACRISC_PCI_OP(read, byte, u8 *, in_8, x)
MACRISC_PCI_OP(read, word, u16 *, in_le16, x)
MACRISC_PCI_OP(read, dword, u32 *, in_le32, x)
MACRISC_PCI_OP(write, byte, u8, out_8, in_8)
MACRISC_PCI_OP(write, word, u16, out_le16, in_le16)
MACRISC_PCI_OP(write, dword, u32, out_le32, in_le32)
static struct pci_ops macrisc_pci_ops =
{
macrisc_read_config_byte,
macrisc_read_config_word,
macrisc_read_config_dword,
macrisc_write_config_byte,
macrisc_write_config_word,
macrisc_write_config_dword
};
/*
* Verifiy that a specific (bus, dev_fn) exists on chaos
*/
static int __pmac
chaos_validate_dev(struct pci_dev *dev, int offset)
{
if(pci_device_to_OF_node(dev) == 0)
return PCIBIOS_DEVICE_NOT_FOUND;
if((dev->vendor == 0x106b) && (dev->device == 3) && (offset >= 0x10) &&
(offset != 0x14) && (offset != 0x18) && (offset <= 0x24)) {
return PCIBIOS_BAD_REGISTER_NUMBER;
}
return PCIBIOS_SUCCESSFUL;
}
#define CHAOS_PCI_OP(rw, size, type) \
static int __pmac \
chaos_##rw##_config_##size(struct pci_dev *dev, int off, type val) \
{ \
int result = chaos_validate_dev(dev, off); \
if(result == PCIBIOS_BAD_REGISTER_NUMBER) { \
cfg_##rw##_bad(val, size) \
return PCIBIOS_BAD_REGISTER_NUMBER; \
} \
if(result == PCIBIOS_SUCCESSFUL) \
return macrisc_##rw##_config_##size(dev, off, val); \
return result; \
}
CHAOS_PCI_OP(read, byte, u8 *)
CHAOS_PCI_OP(read, word, u16 *)
CHAOS_PCI_OP(read, dword, u32 *)
CHAOS_PCI_OP(write, byte, u8)
CHAOS_PCI_OP(write, word, u16)
CHAOS_PCI_OP(write, dword, u32)
static struct pci_ops chaos_pci_ops =
{
chaos_read_config_byte,
chaos_read_config_word,
chaos_read_config_dword,
chaos_write_config_byte,
chaos_write_config_word,
chaos_write_config_dword
};
/*
* For a bandit bridge, turn on cache coherency if necessary.
* N.B. we could clean this up using the hose ops directly.
*/
static void __init
init_bandit(struct pci_controller *bp)
{
unsigned int vendev, magic;
int rev;
/* read the word at offset 0 in config space for device 11 */
out_le32(bp->cfg_addr, (1UL << BANDIT_DEVNUM) + PCI_VENDOR_ID);
udelay(2);
vendev = in_le32((volatile unsigned int *)bp->cfg_data);
if (vendev == (PCI_DEVICE_ID_APPLE_BANDIT << 16) +
PCI_VENDOR_ID_APPLE) {
/* read the revision id */
out_le32(bp->cfg_addr,
(1UL << BANDIT_DEVNUM) + PCI_REVISION_ID);
udelay(2);
rev = in_8(bp->cfg_data);
if (rev != BANDIT_REVID)
printk(KERN_WARNING
"Unknown revision %d for bandit\n", rev);
} else if (vendev != (BANDIT_DEVID_2 << 16) + PCI_VENDOR_ID_APPLE) {
printk(KERN_WARNING "bandit isn't? (%x)\n", vendev);
return;
}
/* read the word at offset 0x50 */
out_le32(bp->cfg_addr, (1UL << BANDIT_DEVNUM) + BANDIT_MAGIC);
udelay(2);
magic = in_le32((volatile unsigned int *)bp->cfg_data);
if ((magic & BANDIT_COHERENT) != 0)
return;
magic |= BANDIT_COHERENT;
udelay(2);
out_le32((volatile unsigned int *)bp->cfg_data, magic);
printk(KERN_INFO "Cache coherency enabled for bandit/PSX\n");
}
/*
* Tweak the PCI-PCI bridge chip on the blue & white G3s.
*/
static void __init
init_p2pbridge(void)
{
struct device_node *p2pbridge;
struct pci_controller* hose;
u8 bus, devfn;
u16 val;
/* XXX it would be better here to identify the specific
PCI-PCI bridge chip we have. */
if ((p2pbridge = find_devices("pci-bridge")) == 0
|| p2pbridge->parent == NULL
|| strcmp(p2pbridge->parent->name, "pci") != 0)
return;
if (pci_device_from_OF_node(p2pbridge, &bus, &devfn) < 0) {
#ifdef DEBUG
printk("Can't find PCI infos for PCI<->PCI bridge\n");
#endif
return;
}
/* Warning: At this point, we have not yet renumbered all busses.
* So we must use OF walking to find out hose
*/
hose = pci_find_hose_for_OF_device(p2pbridge);
if (!hose) {
#ifdef DEBUG
printk("Can't find hose for PCI<->PCI bridge\n");
#endif
return;
}
if (early_read_config_word(hose, bus, devfn,
PCI_BRIDGE_CONTROL, &val) < 0) {
printk(KERN_ERR "init_p2pbridge: couldn't read bridge control\n");
return;
}
val &= ~PCI_BRIDGE_CTL_MASTER_ABORT;
early_write_config_word(hose, bus, devfn, PCI_BRIDGE_CONTROL, val);
}
/*
* Some Apple desktop machines have a NEC PD720100A USB2 controller
* on the motherboard. Open Firmware, on these, will disable the
* EHCI part of it so it behaves like a pair of OHCI's. This fixup
* code re-enables it ;)
*/
static void __init
fixup_nec_usb2(void)
{
struct device_node *nec;
for (nec = find_devices("usb"); nec != NULL; nec = nec->next) {
struct pci_controller *hose;
u32 data, *prop;
u8 bus, devfn;
prop = (u32 *)get_property(nec, "vendor-id", NULL);
if (prop == NULL)
continue;
if (0x1033 != *prop)
continue;
prop = (u32 *)get_property(nec, "device-id", NULL);
if (prop == NULL)
continue;
if (0x0035 != *prop)
continue;
prop = (u32 *)get_property(nec, "reg", 0);
if (prop == NULL)
continue;
devfn = (prop[0] >> 8) & 0xff;
bus = (prop[0] >> 16) & 0xff;
if (PCI_FUNC(devfn) != 0)
continue;
hose = pci_find_hose_for_OF_device(nec);
if (!hose)
continue;
printk("Found NEC PD720100A USB2 chip, enabling EHCI...\n");
early_read_config_dword(hose, bus, devfn, 0xe4, &data);
data &= ~1UL;
early_write_config_dword(hose, bus, devfn, 0xe4, data);
early_write_config_byte(hose, bus, devfn | 2, PCI_INTERRUPT_LINE,
nec->intrs[0].line);
}
}
void __init
pmac_find_bridges(void)
{
add_bridges(find_devices("bandit"));
add_bridges(find_devices("chaos"));
add_bridges(find_devices("pci"));
init_p2pbridge();
fixup_nec_usb2();
}
#define GRACKLE_CFA(b, d, o) (0x80 | ((b) << 8) | ((d) << 16) \
| (((o) & ~3) << 24))
#define GRACKLE_PICR1_STG 0x00000040
#define GRACKLE_PICR1_LOOPSNOOP 0x00000010
/* N.B. this is called before bridges is initialized, so we can't
use grackle_pcibios_{read,write}_config_dword. */
static inline void grackle_set_stg(struct pci_controller* bp, int enable)
{
unsigned int val;
out_be32(bp->cfg_addr, GRACKLE_CFA(0, 0, 0xa8));
val = in_le32((volatile unsigned int *)bp->cfg_data);
val = enable? (val | GRACKLE_PICR1_STG) :
(val & ~GRACKLE_PICR1_STG);
out_be32(bp->cfg_addr, GRACKLE_CFA(0, 0, 0xa8));
out_le32((volatile unsigned int *)bp->cfg_data, val);
(void)in_le32((volatile unsigned int *)bp->cfg_data);
}
static inline void grackle_set_loop_snoop(struct pci_controller *bp, int enable)
{
unsigned int val;
out_be32(bp->cfg_addr, GRACKLE_CFA(0, 0, 0xa8));
val = in_le32((volatile unsigned int *)bp->cfg_data);
val = enable? (val | GRACKLE_PICR1_LOOPSNOOP) :
(val & ~GRACKLE_PICR1_LOOPSNOOP);
out_be32(bp->cfg_addr, GRACKLE_CFA(0, 0, 0xa8));
out_le32((volatile unsigned int *)bp->cfg_data, val);
(void)in_le32((volatile unsigned int *)bp->cfg_data);
}
static int __init
setup_uninorth(struct pci_controller* hose, struct reg_property* addr)
{
pci_assign_all_busses = 1;
has_uninorth = 1;
hose->ops = ¯isc_pci_ops;
hose->cfg_addr = ioremap(addr->address + 0x800000, 0x1000);
hose->cfg_data = ioremap(addr->address + 0xc00000, 0x1000);
/* We "know" that the bridge at f2000000 has the PCI slots. */
return addr->address == 0xf2000000;
}
static void __init
setup_bandit(struct pci_controller* hose, struct reg_property* addr)
{
hose->ops = ¯isc_pci_ops;
hose->cfg_addr = (volatile unsigned int *)
ioremap(addr->address + 0x800000, 0x1000);
hose->cfg_data = (volatile unsigned char *)
ioremap(addr->address + 0xc00000, 0x1000);
init_bandit(hose);
}
static void __init
setup_chaos(struct pci_controller* hose, struct reg_property* addr)
{
/* assume a `chaos' bridge */
hose->ops = &chaos_pci_ops;
hose->cfg_addr = (volatile unsigned int *)
ioremap(addr->address + 0x800000, 0x1000);
hose->cfg_data = (volatile unsigned char *)
ioremap(addr->address + 0xc00000, 0x1000);
}
void __init
setup_grackle(struct pci_controller *hose)
{
setup_indirect_pci(hose, 0xfec00000, 0xfee00000);
if (machine_is_compatible("AAPL,PowerBook1998"))
grackle_set_loop_snoop(hose, 1);
#if 0 /* Disabled for now, HW problems ??? */
grackle_set_stg(hose, 1);
#endif
}
/*
* We assume that if we have a G3 powermac, we have one bridge called
* "pci" (a MPC106) and no bandit or chaos bridges, and contrariwise,
* if we have one or more bandit or chaos bridges, we don't have a MPC106.
*/
static void __init
add_bridges(struct device_node *dev)
{
int len;
struct pci_controller *hose;
struct reg_property *addr;
char* disp_name;
int *bus_range;
int first = 1, primary;
for (; dev != NULL; dev = dev->next) {
addr = (struct reg_property *) get_property(dev, "reg", &len);
if (addr == NULL || len < sizeof(*addr)) {
printk(KERN_WARNING "Can't use %s: no address\n",
dev->full_name);
continue;
}
bus_range = (int *) get_property(dev, "bus-range", &len);
if (bus_range == NULL || len < 2 * sizeof(int)) {
printk(KERN_WARNING "Can't get bus-range for %s, assume bus 0\n",
dev->full_name);
}
hose = pcibios_alloc_controller();
if (!hose)
continue;
hose->arch_data = dev;
hose->first_busno = bus_range ? bus_range[0] : 0;
hose->last_busno = bus_range ? bus_range[1] : 0xff;
disp_name = NULL;
primary = first;
if (device_is_compatible(dev, "uni-north")) {
primary = setup_uninorth(hose, addr);
disp_name = "UniNorth";
} else if (strcmp(dev->name, "pci") == 0) {
/* XXX assume this is a mpc106 (grackle) */
setup_grackle(hose);
disp_name = "Grackle (MPC106)";
} else if (strcmp(dev->name, "bandit") == 0) {
setup_bandit(hose, addr);
disp_name = "Bandit";
} else if (strcmp(dev->name, "chaos") == 0) {
setup_chaos(hose, addr);
disp_name = "Chaos";
primary = 0;
}
printk(KERN_INFO "Found %s PCI host bridge at 0x%08x. Firmware bus number: %d->%d\n",
disp_name, addr->address, hose->first_busno, hose->last_busno);
#ifdef DEBUG
printk(" ->Hose at 0x%08lx, cfg_addr=0x%08lx,cfg_data=0x%08lx\n",
hose, hose->cfg_addr, hose->cfg_data);
#endif
/* Interpret the "ranges" property */
/* This also maps the I/O region and sets isa_io/mem_base */
pci_process_bridge_OF_ranges(hose, dev, primary);
/* Fixup "bus-range" OF property */
fixup_bus_range(dev);
first &= !primary;
}
}
static void __init
pcibios_fixup_OF_interrupts(void)
{
struct pci_dev* dev;
/*
* Open Firmware often doesn't initialize the
* PCI_INTERRUPT_LINE config register properly, so we
* should find the device node and apply the interrupt
* obtained from the OF device-tree
*/
pci_for_each_dev(dev) {
struct device_node* node = pci_device_to_OF_node(dev);
/* this is the node, see if it has interrupts */
if (node && node->n_intrs > 0)
dev->irq = node->intrs[0].line;
pci_write_config_byte(dev, PCI_INTERRUPT_LINE, dev->irq);
}
}
void __init
pmac_pcibios_fixup(void)
{
/* Fixup interrupts according to OF tree */
pcibios_fixup_OF_interrupts();
}
int __pmac
pmac_pci_enable_device_hook(struct pci_dev *dev, int initial)
{
struct device_node* node;
int updatecfg = 0;
int uninorth_child;
node = pci_device_to_OF_node(dev);
/* We don't want to enable USB controllers absent from the OF tree
* (iBook second controller)
*/
if (dev->vendor == PCI_VENDOR_ID_APPLE
&& dev->device == PCI_DEVICE_ID_APPLE_KL_USB && !node)
return -EINVAL;
if (!node)
return 0;
uninorth_child = node->parent &&
device_is_compatible(node->parent, "uni-north");
/* Firewire & GMAC were disabled after PCI probe, the driver is
* claiming them, we must re-enable them now.
*/
if (uninorth_child && !strcmp(node->name, "firewire") &&
(device_is_compatible(node, "pci106b,18") ||
device_is_compatible(node, "pci106b,30") ||
device_is_compatible(node, "pci11c1,5811"))) {
pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, node, 0, 1);
pmac_call_feature(PMAC_FTR_1394_ENABLE, node, 0, 1);
updatecfg = 1;
}
if (uninorth_child && !strcmp(node->name, "ethernet") &&
device_is_compatible(node, "gmac")) {
pmac_call_feature(PMAC_FTR_GMAC_ENABLE, node, 0, 1);
updatecfg = 1;
}
if (updatecfg) {
u16 cmd;
/*
* Make sure PCI is correctly configured
*
* We use old pci_bios versions of the function since, by
* default, gmac is not powered up, and so will be absent
* from the kernel initial PCI lookup.
*
* Should be replaced by 2.4 new PCI mecanisms and really
* regiser the device.
*/
pci_read_config_word(dev, PCI_COMMAND, &cmd);
cmd |= PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_INVALIDATE;
pci_write_config_word(dev, PCI_COMMAND, cmd);
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 16);
pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, 8);
}
return 0;
}
/* We power down some devices after they have been probed. They'll
* be powered back on later on
*/
void __init
pmac_pcibios_after_init(void)
{
struct device_node* nd;
#ifdef CONFIG_BLK_DEV_IDE
struct pci_dev *dev;
/* OF fails to initialize IDE controllers on macs
* (and maybe other machines)
*
* Ideally, this should be moved to the IDE layer, but we need
* to check specifically with Andre Hedrick how to do it cleanly
* since the common IDE code seem to care about the fact that the
* BIOS may have disabled a controller.
*
* -- BenH
*/
pci_for_each_dev(dev) {
if ((dev->class >> 16) == PCI_BASE_CLASS_STORAGE)
pci_enable_device(dev);
}
#endif /* CONFIG_BLK_DEV_IDE */
nd = find_devices("firewire");
while (nd) {
if (nd->parent && (device_is_compatible(nd, "pci106b,18") ||
device_is_compatible(nd, "pci106b,30") ||
device_is_compatible(nd, "pci11c1,5811"))
&& device_is_compatible(nd->parent, "uni-north")) {
pmac_call_feature(PMAC_FTR_1394_ENABLE, nd, 0, 0);
pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, nd, 0, 0);
}
nd = nd->next;
}
nd = find_devices("ethernet");
while (nd) {
if (nd->parent && device_is_compatible(nd, "gmac")
&& device_is_compatible(nd->parent, "uni-north"))
pmac_call_feature(PMAC_FTR_GMAC_ENABLE, nd, 0, 0);
nd = nd->next;
}
}
| sensysnetworks/uClinux | linux-2.4.x/arch/ppc/platforms/pmac_pci.c | C | gpl-2.0 | 19,065 |
/**
* @private
*
* Translates the element by setting the scroll position of its parent node.
*/
Ext.define('Ext.util.translatable.ScrollParent', {
extend: 'Ext.util.translatable.Dom',
isScrollParent: true,
applyElement: function(element) {
var el = Ext.get(element);
if (el) {
this.parent = el.parent();
}
return el;
},
doTranslate: function(x, y) {
var parent = this.parent;
parent.setScrollLeft(Math.round(-x));
parent.setScrollTop(Math.round(-y));
this.callParent([x, y]);
},
getPosition: function() {
var me = this,
position = me.position,
parent = me.parent;
position.x = parent.getScrollLeft();
position.y = parent.getScrollTop();
return position;
}
});
| ebouda33/torrent | www/ext/packages/core/src/util/translatable/ScrollParent.js | JavaScript | gpl-3.0 | 838 |
require 'facts/facts_plugin'
| dLobatog/smart-proxy | modules/facts/facts.rb | Ruby | gpl-3.0 | 29 |
/*
Unix SMB/CIFS implementation.
kerberos utility library
Copyright (C) Andrew Tridgell 2001
Copyright (C) Remus Koos 2001
Copyright (C) Luke Howard 2003
Copyright (C) Guenther Deschner 2003, 2005
Copyright (C) Jim McDonough ([email protected]) 2003
Copyright (C) Andrew Bartlett <[email protected]> 2004-2005
Copyright (C) Jeremy Allison 2007
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/>.
*/
#include "includes.h"
#include "smb_krb5.h"
#include "libads/kerberos_proto.h"
#include "secrets.h"
#include "../librpc/gen_ndr/krb5pac.h"
#ifdef HAVE_KRB5
#if !defined(HAVE_KRB5_PRINC_COMPONENT)
const krb5_data *krb5_princ_component(krb5_context, krb5_principal, int );
#endif
static bool ads_dedicated_keytab_verify_ticket(krb5_context context,
krb5_auth_context auth_context,
const DATA_BLOB *ticket,
krb5_ticket **pp_tkt,
krb5_keyblock **keyblock,
krb5_error_code *perr)
{
krb5_error_code ret = 0;
bool auth_ok = false;
krb5_keytab keytab = NULL;
krb5_keytab_entry kt_entry;
krb5_ticket *dec_ticket = NULL;
krb5_data packet;
krb5_kvno kvno = 0;
krb5_enctype enctype;
*pp_tkt = NULL;
*keyblock = NULL;
*perr = 0;
ZERO_STRUCT(kt_entry);
ret = smb_krb5_open_keytab(context, lp_dedicated_keytab_file(), true,
&keytab);
if (ret) {
DEBUG(1, ("smb_krb5_open_keytab failed (%s)\n",
error_message(ret)));
goto out;
}
packet.length = ticket->length;
packet.data = (char *)ticket->data;
ret = krb5_rd_req(context, &auth_context, &packet, NULL, keytab,
NULL, &dec_ticket);
if (ret) {
DEBUG(0, ("krb5_rd_req failed (%s)\n", error_message(ret)));
goto out;
}
#ifdef HAVE_ETYPE_IN_ENCRYPTEDDATA /* Heimdal */
enctype = dec_ticket->ticket.key.keytype;
#else /* MIT */
enctype = dec_ticket->enc_part.enctype;
kvno = dec_ticket->enc_part.kvno;
#endif
/* Get the key for checking the pac signature */
ret = krb5_kt_get_entry(context, keytab, dec_ticket->server,
kvno, enctype, &kt_entry);
if (ret) {
DEBUG(0, ("krb5_kt_get_entry failed (%s)\n",
error_message(ret)));
goto out;
}
ret = krb5_copy_keyblock(context, KRB5_KT_KEY(&kt_entry), keyblock);
smb_krb5_kt_free_entry(context, &kt_entry);
if (ret) {
DEBUG(0, ("failed to copy key: %s\n",
error_message(ret)));
goto out;
}
auth_ok = true;
*pp_tkt = dec_ticket;
dec_ticket = NULL;
out:
if (dec_ticket)
krb5_free_ticket(context, dec_ticket);
if (keytab)
krb5_kt_close(context, keytab);
*perr = ret;
return auth_ok;
}
/******************************************************************************
Try to verify a ticket using the system keytab... the system keytab has
kvno -1 entries, so it's more like what microsoft does... see comment in
utils/net_ads.c in the ads_keytab_add_entry function for details.
******************************************************************************/
static bool ads_keytab_verify_ticket(krb5_context context,
krb5_auth_context auth_context,
const DATA_BLOB *ticket,
krb5_ticket **pp_tkt,
krb5_keyblock **keyblock,
krb5_error_code *perr)
{
krb5_error_code ret = 0;
bool auth_ok = False;
krb5_keytab keytab = NULL;
krb5_kt_cursor kt_cursor;
krb5_keytab_entry kt_entry;
char *valid_princ_formats[7] = { NULL, NULL, NULL,
NULL, NULL, NULL, NULL };
char *entry_princ_s = NULL;
fstring my_name, my_fqdn;
int i;
int number_matched_principals = 0;
krb5_data packet;
int err;
*pp_tkt = NULL;
*keyblock = NULL;
*perr = 0;
/* Generate the list of principal names which we expect
* clients might want to use for authenticating to the file
* service. We allow name$,{host,cifs}/{name,fqdn,name.REALM}. */
fstrcpy(my_name, global_myname());
my_fqdn[0] = '\0';
name_to_fqdn(my_fqdn, global_myname());
err = asprintf(&valid_princ_formats[0],
"%s$@%s", my_name, lp_realm());
if (err == -1) {
goto out;
}
err = asprintf(&valid_princ_formats[1],
"host/%s@%s", my_name, lp_realm());
if (err == -1) {
goto out;
}
err = asprintf(&valid_princ_formats[2],
"host/%s@%s", my_fqdn, lp_realm());
if (err == -1) {
goto out;
}
err = asprintf(&valid_princ_formats[3],
"host/%s.%s@%s", my_name, lp_realm(), lp_realm());
if (err == -1) {
goto out;
}
err = asprintf(&valid_princ_formats[4],
"cifs/%s@%s", my_name, lp_realm());
if (err == -1) {
goto out;
}
err = asprintf(&valid_princ_formats[5],
"cifs/%s@%s", my_fqdn, lp_realm());
if (err == -1) {
goto out;
}
err = asprintf(&valid_princ_formats[6],
"cifs/%s.%s@%s", my_name, lp_realm(), lp_realm());
if (err == -1) {
goto out;
}
ZERO_STRUCT(kt_entry);
ZERO_STRUCT(kt_cursor);
ret = smb_krb5_open_keytab(context, NULL, False, &keytab);
if (ret) {
DEBUG(1, (__location__ ": smb_krb5_open_keytab failed (%s)\n",
error_message(ret)));
goto out;
}
/* Iterate through the keytab. For each key, if the principal
* name case-insensitively matches one of the allowed formats,
* try verifying the ticket using that principal. */
ret = krb5_kt_start_seq_get(context, keytab, &kt_cursor);
if (ret) {
DEBUG(1, (__location__ ": krb5_kt_start_seq_get failed (%s)\n",
error_message(ret)));
goto out;
}
while (!auth_ok &&
(krb5_kt_next_entry(context, keytab,
&kt_entry, &kt_cursor) == 0)) {
ret = smb_krb5_unparse_name(talloc_tos(), context,
kt_entry.principal,
&entry_princ_s);
if (ret) {
DEBUG(1, (__location__ ": smb_krb5_unparse_name "
"failed (%s)\n", error_message(ret)));
goto out;
}
for (i = 0; i < ARRAY_SIZE(valid_princ_formats); i++) {
if (!strequal(entry_princ_s, valid_princ_formats[i])) {
continue;
}
number_matched_principals++;
packet.length = ticket->length;
packet.data = (char *)ticket->data;
*pp_tkt = NULL;
ret = krb5_rd_req_return_keyblock_from_keytab(context,
&auth_context, &packet,
kt_entry.principal, keytab,
NULL, pp_tkt, keyblock);
if (ret) {
DEBUG(10, (__location__ ": krb5_rd_req_return"
"_keyblock_from_keytab(%s) "
"failed: %s\n", entry_princ_s,
error_message(ret)));
/* workaround for MIT:
* as krb5_ktfile_get_entry will explicitly
* close the krb5_keytab as soon as krb5_rd_req
* has successfully decrypted the ticket but the
* ticket is not valid yet (due to clockskew)
* there is no point in querying more keytab
* entries - Guenther */
if (ret == KRB5KRB_AP_ERR_TKT_NYV ||
ret == KRB5KRB_AP_ERR_TKT_EXPIRED ||
ret == KRB5KRB_AP_ERR_SKEW) {
break;
}
} else {
DEBUG(3, (__location__ ": krb5_rd_req_return"
"_keyblock_from_keytab succeeded "
"for principal %s\n",
entry_princ_s));
auth_ok = True;
break;
}
}
/* Free the name we parsed. */
TALLOC_FREE(entry_princ_s);
/* Free the entry we just read. */
smb_krb5_kt_free_entry(context, &kt_entry);
ZERO_STRUCT(kt_entry);
}
krb5_kt_end_seq_get(context, keytab, &kt_cursor);
ZERO_STRUCT(kt_cursor);
out:
for (i = 0; i < ARRAY_SIZE(valid_princ_formats); i++) {
SAFE_FREE(valid_princ_formats[i]);
}
if (!auth_ok) {
if (!number_matched_principals) {
DEBUG(3, (__location__ ": no keytab principals "
"matched expected file service name.\n"));
} else {
DEBUG(3, (__location__ ": krb5_rd_req failed for "
"all %d matched keytab principals\n",
number_matched_principals));
}
}
TALLOC_FREE(entry_princ_s);
{
krb5_keytab_entry zero_kt_entry;
ZERO_STRUCT(zero_kt_entry);
if (memcmp(&zero_kt_entry, &kt_entry,
sizeof(krb5_keytab_entry))) {
smb_krb5_kt_free_entry(context, &kt_entry);
}
}
{
krb5_kt_cursor zero_csr;
ZERO_STRUCT(zero_csr);
if ((memcmp(&kt_cursor, &zero_csr,
sizeof(krb5_kt_cursor)) != 0) && keytab) {
krb5_kt_end_seq_get(context, keytab, &kt_cursor);
}
}
if (keytab) {
krb5_kt_close(context, keytab);
}
*perr = ret;
return auth_ok;
}
/*****************************************************************************
Try to verify a ticket using the secrets.tdb.
******************************************************************************/
static krb5_error_code ads_secrets_verify_ticket(krb5_context context,
krb5_auth_context auth_context,
krb5_principal host_princ,
const DATA_BLOB *ticket,
krb5_ticket **pp_tkt,
krb5_keyblock **keyblock,
krb5_error_code *perr)
{
krb5_error_code ret = 0;
bool auth_ok = False;
bool cont = true;
char *password_s = NULL;
/* Let's make some room for 2 password (old and new)*/
krb5_data passwords[2];
krb5_enctype enctypes[] = {
#ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
ENCTYPE_AES256_CTS_HMAC_SHA1_96,
#endif
#ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
ENCTYPE_AES128_CTS_HMAC_SHA1_96,
#endif
ENCTYPE_ARCFOUR_HMAC,
ENCTYPE_DES_CBC_CRC,
ENCTYPE_DES_CBC_MD5,
ENCTYPE_NULL
};
krb5_data packet;
int i, j;
*pp_tkt = NULL;
*keyblock = NULL;
*perr = 0;
ZERO_STRUCT(passwords);
if (!secrets_init()) {
DEBUG(1,("ads_secrets_verify_ticket: secrets_init failed\n"));
*perr = KRB5_CONFIG_CANTOPEN;
return False;
}
password_s = secrets_fetch_machine_password(lp_workgroup(),
NULL, NULL);
if (!password_s) {
DEBUG(1,(__location__ ": failed to fetch machine password\n"));
*perr = KRB5_LIBOS_CANTREADPWD;
return False;
}
passwords[0].data = password_s;
passwords[0].length = strlen(password_s);
password_s = secrets_fetch_prev_machine_password(lp_workgroup());
if (password_s) {
DEBUG(10, (__location__ ": found previous password\n"));
passwords[1].data = password_s;
passwords[1].length = strlen(password_s);
}
/* CIFS doesn't use addresses in tickets. This would break NAT. JRA */
packet.length = ticket->length;
packet.data = (char *)ticket->data;
/* We need to setup a auth context with each possible encoding type
* in turn. */
for (j=0; j<2 && passwords[j].length; j++) {
for (i=0;enctypes[i];i++) {
krb5_keyblock *key = NULL;
if (!(key = SMB_MALLOC_P(krb5_keyblock))) {
ret = ENOMEM;
goto out;
}
if (create_kerberos_key_from_string(context,
host_princ, &passwords[j],
key, enctypes[i], false)) {
SAFE_FREE(key);
continue;
}
krb5_auth_con_setuseruserkey(context,
auth_context, key);
if (!(ret = krb5_rd_req(context, &auth_context,
&packet, NULL, NULL,
NULL, pp_tkt))) {
DEBUG(10, (__location__ ": enc type [%u] "
"decrypted message !\n",
(unsigned int)enctypes[i]));
auth_ok = True;
cont = false;
krb5_copy_keyblock(context, key, keyblock);
krb5_free_keyblock(context, key);
break;
}
DEBUG((ret != KRB5_BAD_ENCTYPE) ? 3 : 10,
(__location__ ": enc type [%u] failed to "
"decrypt with error %s\n",
(unsigned int)enctypes[i],
error_message(ret)));
/* successfully decrypted but ticket is just not
* valid at the moment */
if (ret == KRB5KRB_AP_ERR_TKT_NYV ||
ret == KRB5KRB_AP_ERR_TKT_EXPIRED ||
ret == KRB5KRB_AP_ERR_SKEW) {
krb5_free_keyblock(context, key);
cont = false;
break;
}
krb5_free_keyblock(context, key);
}
if (!cont) {
/* If we found a valid pass then no need to try
* the next one or we have invalid ticket so no need
* to try next password*/
break;
}
}
out:
SAFE_FREE(passwords[0].data);
SAFE_FREE(passwords[1].data);
*perr = ret;
return auth_ok;
}
/*****************************************************************************
Verify an incoming ticket and parse out the principal name and
authorization_data if available.
******************************************************************************/
NTSTATUS ads_verify_ticket(TALLOC_CTX *mem_ctx,
const char *realm,
time_t time_offset,
const DATA_BLOB *ticket,
char **principal,
struct PAC_LOGON_INFO **logon_info,
DATA_BLOB *ap_rep,
DATA_BLOB *session_key,
bool use_replay_cache)
{
NTSTATUS sret = NT_STATUS_LOGON_FAILURE;
NTSTATUS pac_ret;
DATA_BLOB auth_data;
krb5_context context = NULL;
krb5_auth_context auth_context = NULL;
krb5_data packet;
krb5_ticket *tkt = NULL;
krb5_rcache rcache = NULL;
krb5_keyblock *keyblock = NULL;
time_t authtime;
krb5_error_code ret = 0;
int flags = 0;
krb5_principal host_princ = NULL;
krb5_const_principal client_principal = NULL;
char *host_princ_s = NULL;
bool auth_ok = False;
bool got_auth_data = False;
struct named_mutex *mutex = NULL;
ZERO_STRUCT(packet);
ZERO_STRUCT(auth_data);
*principal = NULL;
*logon_info = NULL;
*ap_rep = data_blob_null;
*session_key = data_blob_null;
initialize_krb5_error_table();
ret = krb5_init_context(&context);
if (ret) {
DEBUG(1, (__location__ ": krb5_init_context failed (%s)\n",
error_message(ret)));
return NT_STATUS_LOGON_FAILURE;
}
if (time_offset != 0) {
krb5_set_real_time(context, time(NULL) + time_offset, 0);
}
ret = krb5_set_default_realm(context, realm);
if (ret) {
DEBUG(1, (__location__ ": krb5_set_default_realm "
"failed (%s)\n", error_message(ret)));
goto out;
}
/* This whole process is far more complex than I would
like. We have to go through all this to allow us to store
the secret internally, instead of using /etc/krb5.keytab */
ret = krb5_auth_con_init(context, &auth_context);
if (ret) {
DEBUG(1, (__location__ ": krb5_auth_con_init failed (%s)\n",
error_message(ret)));
goto out;
}
krb5_auth_con_getflags( context, auth_context, &flags );
if ( !use_replay_cache ) {
/* Disable default use of a replay cache */
flags &= ~KRB5_AUTH_CONTEXT_DO_TIME;
krb5_auth_con_setflags( context, auth_context, flags );
}
if (asprintf(&host_princ_s, "%s$", global_myname()) == -1) {
goto out;
}
strlower_m(host_princ_s);
ret = smb_krb5_parse_name(context, host_princ_s, &host_princ);
if (ret) {
DEBUG(1, (__location__ ": smb_krb5_parse_name(%s) "
"failed (%s)\n", host_princ_s, error_message(ret)));
goto out;
}
if (use_replay_cache) {
/* Lock a mutex surrounding the replay as there is no
locking in the MIT krb5 code surrounding the replay
cache... */
mutex = grab_named_mutex(talloc_tos(),
"replay cache mutex", 10);
if (mutex == NULL) {
DEBUG(1, (__location__ ": unable to protect replay "
"cache with mutex.\n"));
ret = KRB5_CC_IO;
goto out;
}
/* JRA. We must set the rcache here. This will prevent
replay attacks. */
ret = krb5_get_server_rcache(
context,
krb5_princ_component(context, host_princ, 0),
&rcache);
if (ret) {
DEBUG(1, (__location__ ": krb5_get_server_rcache "
"failed (%s)\n", error_message(ret)));
goto out;
}
ret = krb5_auth_con_setrcache(context, auth_context, rcache);
if (ret) {
DEBUG(1, (__location__ ": krb5_auth_con_setrcache "
"failed (%s)\n", error_message(ret)));
goto out;
}
}
switch (lp_kerberos_method()) {
default:
case KERBEROS_VERIFY_SECRETS:
auth_ok = ads_secrets_verify_ticket(context, auth_context,
host_princ, ticket, &tkt, &keyblock, &ret);
break;
case KERBEROS_VERIFY_SYSTEM_KEYTAB:
auth_ok = ads_keytab_verify_ticket(context, auth_context,
ticket, &tkt, &keyblock, &ret);
break;
case KERBEROS_VERIFY_DEDICATED_KEYTAB:
auth_ok = ads_dedicated_keytab_verify_ticket(context,
auth_context, ticket, &tkt, &keyblock, &ret);
break;
case KERBEROS_VERIFY_SECRETS_AND_KEYTAB:
/* First try secrets.tdb and fallback to the krb5.keytab if
necessary. This is the pre 3.4 behavior when
"use kerberos keytab" was true.*/
auth_ok = ads_secrets_verify_ticket(context, auth_context,
host_princ, ticket, &tkt, &keyblock, &ret);
if (!auth_ok) {
/* Only fallback if we failed to decrypt the ticket */
if (ret != KRB5KRB_AP_ERR_TKT_NYV &&
ret != KRB5KRB_AP_ERR_TKT_EXPIRED &&
ret != KRB5KRB_AP_ERR_SKEW) {
auth_ok = ads_keytab_verify_ticket(context,
auth_context, ticket, &tkt, &keyblock,
&ret);
}
}
break;
}
if (use_replay_cache) {
TALLOC_FREE(mutex);
#if 0
/* Heimdal leaks here, if we fix the leak, MIT crashes */
if (rcache) {
krb5_rc_close(context, rcache);
}
#endif
}
if (!auth_ok) {
DEBUG(3, (__location__ ": krb5_rd_req with auth "
"failed (%s)\n", error_message(ret)));
/* Try map the error return in case it's something like
* a clock skew error.
*/
sret = krb5_to_nt_status(ret);
if (NT_STATUS_IS_OK(sret) ||
NT_STATUS_EQUAL(sret,NT_STATUS_UNSUCCESSFUL)) {
sret = NT_STATUS_LOGON_FAILURE;
}
DEBUG(10, (__location__ ": returning error %s\n",
nt_errstr(sret) ));
goto out;
}
authtime = get_authtime_from_tkt(tkt);
client_principal = get_principal_from_tkt(tkt);
ret = krb5_mk_rep(context, auth_context, &packet);
if (ret) {
DEBUG(3, (__location__ ": Failed to generate mutual "
"authentication reply (%s)\n", error_message(ret)));
goto out;
}
*ap_rep = data_blob(packet.data, packet.length);
if (packet.data) {
kerberos_free_data_contents(context, &packet);
ZERO_STRUCT(packet);
}
get_krb5_smb_session_key(mem_ctx, context,
auth_context, session_key, true);
dump_data_pw("SMB session key (from ticket)\n",
session_key->data, session_key->length);
#if 0
file_save("/tmp/ticket.dat", ticket->data, ticket->length);
#endif
/* continue when no PAC is retrieved or we couldn't decode the PAC
(like accounts that have the UF_NO_AUTH_DATA_REQUIRED flag set, or
Kerberos tickets encrypted using a DES key) - Guenther */
got_auth_data = get_auth_data_from_tkt(mem_ctx, &auth_data, tkt);
if (!got_auth_data) {
DEBUG(3, (__location__ ": did not retrieve auth data. "
"continuing without PAC\n"));
}
if (got_auth_data) {
struct PAC_DATA *pac_data;
pac_ret = decode_pac_data(mem_ctx, &auth_data, context,
keyblock, client_principal,
authtime, &pac_data);
data_blob_free(&auth_data);
if (!NT_STATUS_IS_OK(pac_ret)) {
DEBUG(3, (__location__ ": failed to decode "
"PAC_DATA: %s\n", nt_errstr(pac_ret)));
} else {
uint32_t i;
for (i = 0; i < pac_data->num_buffers; i++) {
if (pac_data->buffers[i].type != PAC_TYPE_LOGON_INFO) {
continue;
}
*logon_info = pac_data->buffers[i].info->logon_info.info;
}
if (!*logon_info) {
DEBUG(1, ("correctly decoded PAC but found "
"no logon_info! "
"This should not happen\n"));
return NT_STATUS_INVALID_USER_BUFFER;
}
}
}
#if 0
#if defined(HAVE_KRB5_TKT_ENC_PART2)
/* MIT */
if (tkt->enc_part2) {
file_save("/tmp/authdata.dat",
tkt->enc_part2->authorization_data[0]->contents,
tkt->enc_part2->authorization_data[0]->length);
}
#else
/* Heimdal */
if (tkt->ticket.authorization_data) {
file_save("/tmp/authdata.dat",
tkt->ticket.authorization_data->val->ad_data.data,
tkt->ticket.authorization_data->val->ad_data.length);
}
#endif
#endif
ret = smb_krb5_unparse_name(mem_ctx, context,
client_principal, principal);
if (ret) {
DEBUG(3, (__location__ ": smb_krb5_unparse_name "
"failed (%s)\n", error_message(ret)));
sret = NT_STATUS_LOGON_FAILURE;
goto out;
}
sret = NT_STATUS_OK;
out:
TALLOC_FREE(mutex);
if (!NT_STATUS_IS_OK(sret)) {
data_blob_free(&auth_data);
}
if (!NT_STATUS_IS_OK(sret)) {
data_blob_free(ap_rep);
}
if (host_princ) {
krb5_free_principal(context, host_princ);
}
if (keyblock) {
krb5_free_keyblock(context, keyblock);
}
if (tkt != NULL) {
krb5_free_ticket(context, tkt);
}
SAFE_FREE(host_princ_s);
if (auth_context) {
krb5_auth_con_free(context, auth_context);
}
if (context) {
krb5_free_context(context);
}
return sret;
}
#endif /* HAVE_KRB5 */
| Distrotech/samba | source3/libads/kerberos_verify.c | C | gpl-3.0 | 20,345 |
#ifndef INCLUDED_volk_16i_s32f_convert_32f_u_H
#define INCLUDED_volk_16i_s32f_convert_32f_u_H
#include <inttypes.h>
#include <stdio.h>
#ifdef LV_HAVE_SSE4_1
#include <smmintrin.h>
/*!
\brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value
\param inputVector The 16 bit input data buffer
\param outputVector The floating point output data buffer
\param scalar The value divided against each point in the output buffer
\param num_points The number of data values to be converted
\note Output buffer does NOT need to be properly aligned
*/
static inline void volk_16i_s32f_convert_32f_u_sse4_1(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){
unsigned int number = 0;
const unsigned int eighthPoints = num_points / 8;
float* outputVectorPtr = outputVector;
__m128 invScalar = _mm_set_ps1(1.0/scalar);
int16_t* inputPtr = (int16_t*)inputVector;
__m128i inputVal;
__m128i inputVal2;
__m128 ret;
for(;number < eighthPoints; number++){
// Load the 8 values
inputVal = _mm_loadu_si128((__m128i*)inputPtr);
// Shift the input data to the right by 64 bits ( 8 bytes )
inputVal2 = _mm_srli_si128(inputVal, 8);
// Convert the lower 4 values into 32 bit words
inputVal = _mm_cvtepi16_epi32(inputVal);
inputVal2 = _mm_cvtepi16_epi32(inputVal2);
ret = _mm_cvtepi32_ps(inputVal);
ret = _mm_mul_ps(ret, invScalar);
_mm_storeu_ps(outputVectorPtr, ret);
outputVectorPtr += 4;
ret = _mm_cvtepi32_ps(inputVal2);
ret = _mm_mul_ps(ret, invScalar);
_mm_storeu_ps(outputVectorPtr, ret);
outputVectorPtr += 4;
inputPtr += 8;
}
number = eighthPoints * 8;
for(; number < num_points; number++){
outputVector[number] =((float)(inputVector[number])) / scalar;
}
}
#endif /* LV_HAVE_SSE4_1 */
#ifdef LV_HAVE_SSE
#include <xmmintrin.h>
/*!
\brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value
\param inputVector The 16 bit input data buffer
\param outputVector The floating point output data buffer
\param scalar The value divided against each point in the output buffer
\param num_points The number of data values to be converted
\note Output buffer does NOT need to be properly aligned
*/
static inline void volk_16i_s32f_convert_32f_u_sse(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){
unsigned int number = 0;
const unsigned int quarterPoints = num_points / 4;
float* outputVectorPtr = outputVector;
__m128 invScalar = _mm_set_ps1(1.0/scalar);
int16_t* inputPtr = (int16_t*)inputVector;
__m128 ret;
for(;number < quarterPoints; number++){
ret = _mm_set_ps((float)(inputPtr[3]), (float)(inputPtr[2]), (float)(inputPtr[1]), (float)(inputPtr[0]));
ret = _mm_mul_ps(ret, invScalar);
_mm_storeu_ps(outputVectorPtr, ret);
inputPtr += 4;
outputVectorPtr += 4;
}
number = quarterPoints * 4;
for(; number < num_points; number++){
outputVector[number] = (float)(inputVector[number]) / scalar;
}
}
#endif /* LV_HAVE_SSE */
#ifdef LV_HAVE_GENERIC
/*!
\brief Converts the input 16 bit integer data into floating point data, and divides the each floating point output data point by the scalar value
\param inputVector The 16 bit input data buffer
\param outputVector The floating point output data buffer
\param scalar The value divided against each point in the output buffer
\param num_points The number of data values to be converted
\note Output buffer does NOT need to be properly aligned
*/
static inline void volk_16i_s32f_convert_32f_u_generic(float* outputVector, const int16_t* inputVector, const float scalar, unsigned int num_points){
float* outputVectorPtr = outputVector;
const int16_t* inputVectorPtr = inputVector;
unsigned int number = 0;
for(number = 0; number < num_points; number++){
*outputVectorPtr++ = ((float)(*inputVectorPtr++)) / scalar;
}
}
#endif /* LV_HAVE_GENERIC */
#endif /* INCLUDED_volk_16i_s32f_convert_32f_u_H */
| tyc85/nwsdr-3.6.3-dsc | volk/include/volk/volk_16i_s32f_convert_32f_u.h | C | gpl-3.0 | 4,343 |
/**
* Abstract base class for filter implementations.
*/
Ext.define('Ext.grid.filters.filter.Base', {
mixins: [
'Ext.mixin.Factoryable'
],
factoryConfig: {
type: 'grid.filter'
},
$configPrefixed: false,
$configStrict: false,
config: {
/**
* @cfg {Object} [itemDefaults]
* The default configuration options for any menu items created by this filter.
*
* Example usage:
*
* itemDefaults: {
* width: 150
* },
*/
itemDefaults: null,
menuDefaults: {
xtype: 'menu'
}
},
/**
* @property {Boolean} active
* True if this filter is active. Use setActive() to alter after configuration.
*/
/**
* @cfg {Boolean} active
* Indicates the initial status of the filter (defaults to false).
*/
active: false,
/**
* @property {String} type
* The filter type. Used by the filters.Feature class when adding filters and applying state.
*/
type: 'string',
/**
* @cfg {String} dataIndex
* The {@link Ext.data.Store} dataIndex of the field this filter represents.
* The dataIndex does not actually have to exist in the store.
*/
dataIndex: null,
/**
* @property {Ext.menu.Menu} menu
* The filter configuration menu that will be installed into the filter submenu of a column menu.
*/
menu: null,
/**
* @cfg {Number} updateBuffer
* Number of milliseconds to wait after user interaction to fire an update. Only supported
* by filters: 'list', 'numeric', and 'string'.
*/
updateBuffer: 500,
isGridFilter: true,
defaultRoot: 'data',
/**
* The prefix for id's used to track stateful Store filters.
* @private
*/
filterIdPrefix: 'x-gridfilter',
/**
* @event activate
* Fires when an inactive filter becomes active
* @param {Ext.grid.filters.filter.Filter} this
*/
/**
* @event deactivate
* Fires when an active filter becomes inactive
* @param {Ext.grid.filters.filter.Filter} this
*/
/**
* @event update
* Fires when a filter configuration has changed
* @param {Ext.grid.filters.filter.Filter} this The filter object.
*/
/**
* Initializes the filter given its configuration.
* @param {Object} config
*/
constructor: function (config) {
var me = this;
me.initConfig(config);
me.store = me.grid.store;
},
/**
* Destroys this filter by purging any event listeners, and removing any menus.
*/
destroy: function(){
if (this.menu){
this.menu.destroy();
}
},
addStoreFilter: function (filter) {
this.store.getFilters().add(filter);
},
createFilter: function (config, key) {
config.id = this.getBaseIdPrefix();
if (!config.property) {
config.property = this.column.dataIndex;
}
if (!config.root) {
config.root = this.defaultRoot;
}
if (key) {
config.id += '-' + key;
}
return new Ext.util.Filter(config);
},
/**
* @private
* Creates the Menu for this filter.
* @param {Object} config Filter configuration
* @return {Ext.menu.Menu}
*/
createMenu: function () {
var config = this.getMenuConfig();
this.menu = Ext.widget(config);
},
getBaseIdPrefix: function () {
return this.filterIdPrefix + '-' + this.column.dataIndex;
},
getMenuConfig: function () {
return Ext.apply({}, this.getMenuDefaults());
},
getStoreFilter: function (key) {
var id = this.getBaseIdPrefix();
if (key) {
id += '-' + key;
}
return this.store.getFilters().get(id);
},
removeStoreFilter: function (filter) {
this.store.getFilters().remove(filter);
},
/**
* @private
* @method getValue
* Template method to be implemented by all subclasses that is to
* get and return the value of the filter.
* @return {Object} The 'serialized' form of this filter
* @template
*/
/**
* @private
* @method setValue
* Template method to be implemented by all subclasses that is to
* set the value of the filter and fire the 'update' event.
* @param {Object} data The value to set the filter
* @template
*/
/**
* @method
* Template method to be implemented by all subclasses that is to
* return true if the filter has enough configuration information to be activated.
* Defaults to always returning true.
* @return {Boolean}
*/
/**
* Sets the status of the filter and fires the appropriate events.
* @param {Boolean} active The new filter state.
* @param {String} key The filter key for columns that support multiple filters.
*/
setActive: function (active) {
var me = this,
owner = me.owner,
menuItem = owner.activeFilterMenuItem,
filterCollection;
if (me.active !== active) {
me.active = active;
filterCollection = me.store.getFilters();
filterCollection.beginUpdate();
if (active) {
me.activate();
} else {
me.deactivate();
}
filterCollection.endUpdate();
// Make sure we update the 'Filters' menu item.
if (menuItem && menuItem.activeFilter === me) {
menuItem.setChecked(active);
}
me.column[active ? 'addCls' : 'removeCls'](owner.filterCls);
// TODO: fire activate/deactivate
}
},
showMenu: function (menuItem) {
if (!this.menu) {
this.createMenu();
}
menuItem.activeFilter = this;
menuItem.setMenu(this.menu, false);
menuItem.setChecked(this.active);
// Disable the menu if filter.disabled explicitly set to true.
menuItem.setDisabled(this.disabled === true);
if (this.active) {
this.activate(/*showingMenu*/ true);
}
},
updateStoreFilter: function (filter) {
this.store.getFilters().notify('endupdate');
}
});
| applifireAlgo/ZenClubApp | zenws/src/main/webapp/ext/src/grid/filters/filter/Base.js | JavaScript | gpl-3.0 | 6,413 |
<?php
/**
* PHPExcel
*
* Copyright (C) 2006 - 2009 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Shared_OLE
* @copyright Copyright (c) 2006 - 2007 Christian Schmidt
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
require_once 'PHPExcel/Shared/OLE.php';
/**
* PHPExcel_Shared_OLE_ChainedBlockStream
*
* Stream wrapper for reading data stored in an OLE file. Implements methods
* for PHP's stream_wrapper_register(). For creating streams using this
* wrapper, use PHPExcel_Shared_OLE_PPS_File::getStream().
*
* @category PHPExcel
* @package PHPExcel_Shared_OLE
*/
class PHPExcel_Shared_OLE_ChainedBlockStream
{
/**
* The OLE container of the file that is being read.
* @var OLE
*/
public $ole;
/**
* Parameters specified by fopen().
* @var array
*/
public $params;
/**
* The binary data of the file.
* @var string
*/
public $data;
/**
* The file pointer.
* @var int byte offset
*/
public $pos;
/**
* Implements support for fopen().
* For creating streams using this wrapper, use OLE_PPS_File::getStream().
* @param string resource name including scheme, e.g.
* ole-chainedblockstream://oleInstanceId=1
* @param string only "r" is supported
* @param int mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH
* @param string absolute path of the opened stream (out parameter)
* @return bool true on success
*/
public function stream_open($path, $mode, $options, &$openedPath)
{
if ($mode != 'r') {
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('Only reading is supported', E_USER_WARNING);
}
return false;
}
// 25 is length of "ole-chainedblockstream://"
parse_str(substr($path, 25), $this->params);
if (!isset($this->params['oleInstanceId'],
$this->params['blockId'],
$GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) {
if ($options & STREAM_REPORT_ERRORS) {
trigger_error('OLE stream not found', E_USER_WARNING);
}
return false;
}
$this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']];
$blockId = $this->params['blockId'];
$this->data = '';
if (isset($this->params['size']) &&
$this->params['size'] < $this->ole->bigBlockThreshold &&
$blockId != $this->ole->root->_StartBlock) {
// Block id refers to small blocks
$rootPos = $this->ole->_getBlockOffset($this->ole->root->_StartBlock);
while ($blockId != -2) {
$pos = $rootPos + $blockId * $this->ole->bigBlockSize;
$blockId = $this->ole->sbat[$blockId];
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
}
} else {
// Block id refers to big blocks
while ($blockId != -2) {
$pos = $this->ole->_getBlockOffset($blockId);
fseek($this->ole->_file_handle, $pos);
$this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize);
$blockId = $this->ole->bbat[$blockId];
}
}
if (isset($this->params['size'])) {
$this->data = substr($this->data, 0, $this->params['size']);
}
if ($options & STREAM_USE_PATH) {
$openedPath = $path;
}
return true;
}
/**
* Implements support for fclose().
* @return string
*/
public function stream_close()
{
$this->ole = null;
unset($GLOBALS['_OLE_INSTANCES']);
}
/**
* Implements support for fread(), fgets() etc.
* @param int maximum number of bytes to read
* @return string
*/
public function stream_read($count)
{
if ($this->stream_eof()) {
return false;
}
$s = substr($this->data, $this->pos, $count);
$this->pos += $count;
return $s;
}
/**
* Implements support for feof().
* @return bool TRUE if the file pointer is at EOF; otherwise FALSE
*/
public function stream_eof()
{
$eof = $this->pos >= strlen($this->data);
// Workaround for bug in PHP 5.0.x: http://bugs.php.net/27508
if (version_compare(PHP_VERSION, '5.0', '>=') &&
version_compare(PHP_VERSION, '5.1', '<')) {
$eof = !$eof;
}
return $eof;
}
/**
* Returns the position of the file pointer, i.e. its offset into the file
* stream. Implements support for ftell().
* @return int
*/
public function stream_tell()
{
return $this->pos;
}
/**
* Implements support for fseek().
* @param int byte offset
* @param int SEEK_SET, SEEK_CUR or SEEK_END
* @return bool
*/
public function stream_seek($offset, $whence)
{
if ($whence == SEEK_SET && $offset >= 0) {
$this->pos = $offset;
} elseif ($whence == SEEK_CUR && -$offset <= $this->pos) {
$this->pos += $offset;
} elseif ($whence == SEEK_END && -$offset <= sizeof($this->data)) {
$this->pos = strlen($this->data) + $offset;
} else {
return false;
}
return true;
}
/**
* Implements support for fstat(). Currently the only supported field is
* "size".
* @return array
*/
public function stream_stat()
{
return array(
'size' => strlen($this->data),
);
}
// Methods used by stream_wrapper_register() that are not implemented:
// bool stream_flush ( void )
// int stream_write ( string data )
// bool rename ( string path_from, string path_to )
// bool mkdir ( string path, int mode, int options )
// bool rmdir ( string path, int options )
// bool dir_opendir ( string path, int options )
// array url_stat ( string path, int flags )
// string dir_readdir ( void )
// bool dir_rewinddir ( void )
// bool dir_closedir ( void )
}
| mwveliz/siglas-mppp | plugins/sfPhpExcelPlugin/lib/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php | PHP | gpl-3.0 | 6,257 |
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2004 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
/******************************************************************************
* *
* THIS IS A LIBRARY READ-ONLY SOURCE FILE. DO NOT EDIT IT DIRECTLY. *
* *
* Overriding HAL Functions *
* *
* To provide your own implementation of a HAL function, include the file in *
* your Nios II IDE application project. When building the executable, the *
* Nios II IDE finds your function first, and uses it in place of the HAL *
* version. *
* *
******************************************************************************/
/*
*
*/
typedef void (*constructor) (void);
extern constructor __CTOR_LIST__[];
extern constructor __CTOR_END__[];
/*
* Run the C++ static constructors.
*/
void _do_ctors(void)
{
constructor* ctor;
for (ctor = &__CTOR_END__[-1]; ctor >= __CTOR_LIST__; ctor--)
(*ctor) ();
}
| mzakharo/usb-de2-fpga | support/DE2_NIOS_DEVICE_LED/SW/isp_bsp/HAL/src/alt_do_ctors.c | C | gpl-3.0 | 3,802 |
<?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 [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @version $Id: Container.php 18951 2009-11-12 16:26:19Z alexander $
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_View_Helper_Placeholder_Container_Abstract */
require_once 'Zend/View/Helper/Placeholder/Container/Abstract.php';
/**
* Container for placeholder values
*
* @package Zend_View
* @subpackage Helper
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_View_Helper_Placeholder_Container extends Zend_View_Helper_Placeholder_Container_Abstract
{
}
| ivesbai/server | vendor/ZendFramework/library/Zend/View/Helper/Placeholder/Container.php | PHP | agpl-3.0 | 1,261 |
<?php
/**
*
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
* Copyright (C) 2011 - 2018 SalesAgility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
*/
if (!defined('sugarEntry') || !sugarEntry) {
die('Not A Valid Entry Point');
}
$module_name = 'OAuth2Tokens';
$metafiles[$module_name] = array(
'detailviewdefs' => 'modules/' . $module_name . '/metadata/detailviewdefs.php',
'editviewdefs' => 'modules/' . $module_name . '/metadata/editviewdefs.php',
'listviewdefs' => 'modules/' . $module_name . '/metadata/listviewdefs.php',
'searchdefs' => 'modules/' . $module_name . '/metadata/searchdefs.php',
'popupdefs' => 'modules/' . $module_name . '/metadata/popupdefs.php',
'searchfields' => 'modules/' . $module_name . '/metadata/SearchFields.php',
);
| ChangezKhan/SuiteCRM | modules/OAuth2Tokens/metadata/metafiles.php | PHP | agpl-3.0 | 2,693 |
ALTER TABLE `items` ADD COLUMN `ScaledStatsDistributionId` INT(32) UNSIGNED DEFAULT '0' NOT NULL AFTER `stat_value10`;
ALTER TABLE `items` ADD COLUMN `ScaledStatsDistributionFlags` INT(32) UNSIGNED DEFAULT '0' NOT NULL AFTER `ScaledStatsDistributionId`;
ALTER TABLE `items` ADD COLUMN `ItemLimitCategoryId` INT(32) UNSIGNED DEFAULT '0' NOT NULL AFTER `unk2`; | satanail/ArcTic-d | sql/world_updates/1564_items.sql | SQL | agpl-3.0 | 358 |
/*
* Copyright (C) 2013 Freie Universität Berlin
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @{
* @file
* @brief Providing implementation for POSIX socket wrapper.
* @author Martine Lenders <[email protected]>
* @todo
*/
#include "sys/socket.h"
int flagless_send(int fd, const void *buf, size_t len)
{
(void)fd;
(void)buf;
(void)len;
return -1;
}
int flagless_recv(int fd, void *buf, size_t len)
{
return (int)socket_base_recv(fd, buf, (uint32_t)len, 0);
}
int socket(int domain, int type, int protocol)
{
(void)domain;
(void)type;
(void)protocol;
return -1;
}
int accept(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len)
{
(void)socket;
(void)address;
(void)address_len;
return -1;
}
int bind(int socket, const struct sockaddr *address, socklen_t address_len)
{
(void)socket;
(void)address;
(void)address_len;
return -1;
}
int connect(int socket, const struct sockaddr *address, socklen_t address_len)
{
(void)socket;
(void)address;
(void)address_len;
return -1;
}
int getsockopt(int socket, int level, int option_name,
void *restrict option_value, socklen_t *restrict option_len)
{
// TODO
(void) socket;
(void) level;
(void) option_name;
(void) option_value;
(void) option_len;
return -1;
}
int listen(int socket, int backlog)
{
(void)socket;
(void)backlog;
return -1;
}
ssize_t recv(int socket, void *buffer, size_t length, int flags)
{
(void)socket;
(void)buffer;
(void)length;
(void)flags;
return -1;
}
ssize_t recvfrom(int socket, void *restrict buffer, size_t length, int flags,
struct sockaddr *restrict address,
socklen_t *restrict address_len)
{
(void)socket;
(void)buffer;
(void)length;
(void)flags;
(void)address;
(void)address_len;
return -1;
}
ssize_t send(int socket, const void *buffer, size_t length, int flags)
{
(void)socket;
(void)buffer;
(void)length;
(void)flags;
return -1;
}
ssize_t sendto(int socket, const void *message, size_t length, int flags,
const struct sockaddr *dest_addr, socklen_t dest_len)
{
// TODO
(void)socket;
(void)message;
(void)length;
(void)flags;
(void)dest_addr;
(void)dest_len;
return -1;
}
int setsockopt(int socket, int level, int option_name, const void *option_value,
socklen_t option_len)
{
// TODO
(void) socket;
(void) level;
(void) option_name;
(void) option_value;
(void) option_len;
return -1;
}
/**
* @}
*/
| luciotorre/RIOT | sys/posix/pnet/sys_socket.c | C | lgpl-2.1 | 2,828 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2009 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// Test DoFTools::make_cell_patches with parallel::distributed::Triangulation
#include "block_list.h"
template <int dim>
void
test_block_list(const parallel::distributed::Triangulation<dim> &tr, const FiniteElement<dim> &fe)
{
deallog << fe.get_name() << std::endl;
DoFHandler<dim> dof;
dof.initialize(tr, fe);
dof.distribute_mg_dofs (fe);
for (unsigned int level=0; level<tr.n_global_levels(); ++level)
{
SparsityPattern bl;
DoFTools::make_cell_patches(bl, dof, level);
bl.compress();
for (unsigned int i=0; i<bl.n_rows(); ++i)
{
deallog << "Level " << level << " Block " << std::setw(3) << i;
std::vector<unsigned int> entries;
for (SparsityPattern::iterator b = bl.begin(i); b != bl.end(i); ++b)
entries.push_back(b->column());
std::sort(entries.begin(), entries.end());
for (unsigned int i=0; i<entries.size(); ++i)
deallog << ' ' << std::setw(4) << entries[i];
deallog << std::endl;
}
}
}
int main(int argc, char **argv)
{
Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
MPILogInitAll all;
deallog.push("2D");
test_global_refinement_parallel<2>(&test_block_list<2>);
deallog.pop();
deallog.push("3D");
test_global_refinement_parallel<3>(&test_block_list<3>);
deallog.pop();
}
| pesser/dealii | tests/dofs/block_list_parallel_01.cc | C++ | lgpl-2.1 | 2,018 |
/* radare - LGPL - Copyright 2015-2016 - pancake, condret, riq, qnix */
#include <r_asm.h>
#include <r_lib.h>
#include <string.h>
#include "../snes/snesdis.c"
static struct {
ut8 op;
char *name;
size_t len;
} ops[] = {
{0x00, "brk", 1},
{0x0b, "anc #0x%02x", 2},
{0x2b, "anc #0x%02x", 2},
{0x8b, "ane #0x%02x", 2},
{0x6b, "arr #0x%02x", 2},
{0x4b, "asr #0x%02x", 2},
{0xc7, "dcp 0x%02x", 2},
{0xd7, "dcp 0x%02x,x", 2},
{0xcf, "dcp 0x%04x", 3},
{0xdf, "dcp 0x%04x,x", 3},
{0xdb, "dcp 0x%04x,y", 3},
{0xc3, "dcp (0x%02x,x)", 2},
{0xd3, "dcp (0x%02x),y", 2},
{0xe7, "isb 0x%02x", 2},
{0xf7, "isb 0x%02x,x", 2},
{0xef, "isb 0x%04x", 3},
{0xff, "isb 0x%04x,x", 3},
{0xfb, "isb 0x%04x,y", 3},
{0xe3, "isb (0x%02x,x)", 2},
{0xf3, "isb (0x%02x),y", 2},
{0x02, "hlt", 1},
{0x12, "hlt", 1},
{0x22, "hlt", 1},
{0x32, "hlt", 1},
{0x42, "hlt", 1},
{0x52, "hlt", 1},
{0x62, "hlt", 1},
{0x72, "hlt", 1},
{0x92, "hlt", 1},
{0xb2, "hlt", 1},
{0xd2, "hlt", 1},
{0xf2, "hlt", 1},
{0xbb, "lae 0x%04x,y", 3},
{0xa7, "lax 0x%02x", 2},
{0xb7, "lax 0x%02x,y", 2},
{0xaf, "lax 0x%04x", 3},
{0xbf, "lax 0x%04x,y", 3},
{0xa3, "lax (0x%02x,x)", 2},
{0xb3, "lax (0x%02x),y", 2},
{0xab, "lxa #0x%02x", 2},
{0xea, "nop", 1},
{0x1a, "nop", 1},
{0x3a, "nop", 1},
{0x5a, "nop", 1},
{0x7a, "nop", 1},
{0xda, "nop", 1},
{0xfa, "nop", 1},
{0x80, "nop #0x%02x", 2},
{0x82, "nop #0x%02x", 2},
{0x89, "nop #0x%02x", 2},
{0xc2, "nop #0x%02x", 2},
{0xe2, "nop #0x%02x", 2},
{0x04, "nop 0x%02x", 2},
{0x44, "nop 0x%02x", 2},
{0x64, "nop 0x%02x", 2},
{0x14, "nop 0x%02x,x", 2},
{0x34, "nop 0x%02x,x", 2},
{0x54, "nop 0x%02x,x", 2},
{0x74, "nop 0x%02x,x", 2},
{0xd4, "nop 0x%02x,x", 2},
{0xf4, "nop 0x%02x,x", 2},
{0x0c, "nop 0x%04x", 3},
{0x1c, "nop 0x%04x,x", 3},
{0x3c, "nop 0x%04x,x", 3},
{0x5c, "nop 0x%04x,x", 3},
{0x7c, "nop 0x%04x,x", 3},
{0xdc, "nop 0x%04x,x", 3},
{0xfc, "nop 0x%04x,x", 3},
{0x27, "rla 0x%02x", 2},
{0x37, "rla 0x%02x,x", 2},
{0x2f, "rla 0x%04x", 3},
{0x3f, "rla 0x%04x,x", 3},
{0x3b, "rla 0x%04x,y", 3},
{0x23, "rla (0x%02x,x)", 2},
{0x33, "rla (0x%02x),y", 2},
{0x67, "rra 0x%02x", 2},
{0x77, "rra 0x%02x,x", 2},
{0x6f, "rra 0x%04x", 3},
{0x7f, "rra 0x%04x,x", 3},
{0x7b, "rra 0x%04x,y", 3},
{0x63, "rra (0x%02x,x)", 2},
{0x73, "rra (0x%02x),y", 2},
{0x87, "sax 0x%02x", 2},
{0x97, "sax 0x%02x,y", 2},
{0x8f, "sax 0x%04x", 3},
{0x83, "sax (0x%02x,x)", 2},
{0xe9, "sbc #0x%02x", 2},
{0xe5, "sbc 0x%02x", 2},
{0xf5, "sbc 0x%02x,x", 2},
{0xed, "sbc 0x%04x", 3},
{0xfd, "sbc 0x%04x,x", 3},
{0xf9, "sbc 0x%04x,y", 3},
{0xe1, "sbc (0x%02x,x)", 2},
{0xf1, "sbc (0x%02x),y", 2},
{0xeb, "sbc #0x%02x", 2},
//{0xef, "sbc 0x%06x", 4},
//{0xff, "sbc 0x%06x,x", 4},
//{0xf2, "sbc (0x%02x)", 2},
//{0xe7, "sbc [0x%02x]", 2},
//{0xf7, "sbc [0x%02x],y", 2},
//{0xe3, "sbc 0x%02x,s", 2},
//{0xf3, "sbc (0x%02x,s),y", 2},
{0xcb, "sbx 0x%02x", 2},
{0x93, "sha 0x%04x,x", 3},
{0x9f, "sha 0x%04x,y", 3},
{0x9b, "shs 0x%04x,y", 3},
{0x9e, "shx 0x%04x,y", 3},
{0x9c, "shy 0x%04x,x", 3},
{0x07, "slo 0x%02x", 2},
{0x17, "slo 0x%02x,x", 2},
{0x0f, "slo 0x%04x", 3},
{0x1f, "slo 0x%04x,x", 3},
{0x1b, "slo 0x%04x,y", 3},
{0x03, "slo (0x%02x,x)", 2},
{0x13, "slo (0x%02x),y", 2},
{0x47, "sre 0x%02x", 2},
{0x57, "sre 0x%02x,x", 2},
{0x4f, "sre 0x%04x", 3},
{0x5f, "sre 0x%04x,x", 3},
{0x5b, "sre 0x%04x,y", 3},
{0x43, "sre (0x%02x,x)", 2},
{0x53, "sre (0x%02x),y", 2},
{-1, NULL, 0}};
static int _6502Disass (ut64 pc, RAsmOp *op, const ut8 *buf, ut64 len) {
int i;
for (i=0; ops[i].name != NULL; i++) {
if (ops[i].op == buf[0]) {
const char *buf_asm = "invalid";
int len = ops[i].len;
switch (ops[i].len) {
case 1:
buf_asm = sdb_fmt ("%s", ops[i].name);
break;
case 2:
if (len > 1) {
buf_asm = sdb_fmt (ops[i].name, buf[1]);
} else {
buf_asm = "truncated";
len = -1;
}
break;
case 3:
if (len > 2) {
buf_asm = sdb_fmt (ops[i].name, buf[1] + 0x100 * buf[2]);
} else {
buf_asm = "truncated";
len = -1;
}
break;
case 4:
if (len > 3) {
buf_asm = sdb_fmt (ops[i].name, buf[1]+0x100*buf[2]+0x10000*buf[3]);
} else {
buf_asm = "truncated";
len = -1;
}
break;
default:
goto beach;
}
r_strbuf_set (&op->buf_asm, buf_asm);
return len;
}
}
beach:
return snesDisass (1, 1, pc, op, buf, len);
}
| bigendiansmalls/radare2 | libr/asm/arch/6502/6502dis.c | C | lgpl-3.0 | 4,413 |
/*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.registry.webdav;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavCompliance;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavResource;
import org.apache.jackrabbit.webdav.DavResourceFactory;
import org.apache.jackrabbit.webdav.DavResourceIterator;
import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
import org.apache.jackrabbit.webdav.DavResourceLocator;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.DavSession;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.io.InputContext;
import org.apache.jackrabbit.webdav.io.OutputContext;
import org.apache.jackrabbit.webdav.lock.ActiveLock;
import org.apache.jackrabbit.webdav.lock.LockInfo;
import org.apache.jackrabbit.webdav.lock.LockManager;
import org.apache.jackrabbit.webdav.lock.Scope;
import org.apache.jackrabbit.webdav.lock.Type;
import org.apache.jackrabbit.webdav.property.DavProperty;
import org.apache.jackrabbit.webdav.property.DavPropertyName;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
import org.apache.jackrabbit.webdav.property.ResourceType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.CollectionImpl;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
public class RegistryResource implements DavResource {
private Resource underLineResource;
private Registry registry;
private RegistryWebDavContext resourceCache;
private DavResourceLocator locator;
private String path;
private boolean doesNotExists = false;
private Map<DavPropertyName,DavProperty> properties = new HashMap<DavPropertyName,DavProperty>();
private boolean lockable = false;
private LockManager lockManager;
private DavSession session;
private static final String COMPLIANCE_CLASSES = DavCompliance.concatComplianceClasses( new String[] {DavCompliance._1_});
public RegistryResource(RegistryWebDavContext webdavContext,
DavResourceLocator locator) throws DavException {
this.registry = webdavContext.getRegistry();
if(registry == null){
throw new DavException(DavServletResponse.SC_FORBIDDEN, "Registry Not Found");
}
this.locator = locator;
this.resourceCache = webdavContext;
String path = locator.getResourcePath();
if(path.startsWith("/registry/resourcewebdav")){
path = path.substring("/registry/resourcewebdav".length());
}
if(path.trim().length() == 0){
path = "/";
}
this.path = path.trim();
//this.session = session;
}
private Resource getUnderlineResource(){
try {
this.underLineResource = registry.get(path);
// adding the properties requested from the webDAV client
addRequiredProperties();
return underLineResource;
} catch (RegistryException e) {
doesNotExists = true;
throw new RuntimeException(e);
}
}
// add the properties required by the webDAV client
private void addRequiredProperties() {
if (underLineResource instanceof Collection) {
addDavProperty(DavPropertyName.RESOURCETYPE, new ResourceType(ResourceType.COLLECTION));
// Windows XP support
addDavProperty(DavPropertyName.ISCOLLECTION, "1");
} else {
addDavProperty(DavPropertyName.RESOURCETYPE, new ResourceType(ResourceType.DEFAULT_RESOURCE));
// Windows XP support
addDavProperty(DavPropertyName.ISCOLLECTION, "0");
addDavProperty(DavPropertyName.GETCONTENTLENGTH, getContentLength());
addDavProperty(DavPropertyName.GETCONTENTTYPE, underLineResource.getMediaType());
}
addDavProperty(DavPropertyName.create("author"), underLineResource.getAuthorUserName());
addDavProperty(DavPropertyName.GETETAG, getETag());
addDavProperty(DavPropertyName.DISPLAYNAME, getDisplayName());
addDavProperty(DavPropertyName.CREATIONDATE, DavConstants.creationDateFormat.format(
underLineResource.getCreatedTime()));
addDavProperty(DavPropertyName.GETLASTMODIFIED, DavConstants.modificationDateFormat.format(
underLineResource.getLastModified()));
}
//TODO: fix ETag
// the proper ETag implementation should be applied in the future.
private String getETag() {
return path;
}
// returns the size -the number of bytes - of the content
private int getContentLength() {
int bytesRead = 0;
try {
Object o = this.underLineResource.getContent();
if (null != o && o instanceof byte[]) {
bytesRead = ((byte[]) o).length;
}
} catch (RegistryException e) {
bytesRead = 0;
}
return bytesRead;
}
// creates and adds a dav property
private void addDavProperty(DavPropertyName dName, Object value) {
DavProperty<Object> davProp = new DefaultDavProperty<Object>(dName, value);
properties.put(davProp.getName(), davProp);
}
public void addMember(DavResource resource, InputContext inputContext)
throws DavException {
// if (isLocked(this) || isLocked(member)) {
// throw new DavException(DavServletResponse.SC_LOCKED);
// }
try {
if (resource instanceof RegistryResource) {
if (getUnderlineResource() instanceof Collection) {
if (resource.getResourcePath().contains(path)) {
Resource resourceImpl = ((RegistryResource) resource).getUnderLineResource();
boolean isCollection = resourceImpl instanceof Collection;
// 'resourceImpl == null' indicates it's a new non-collection resource created by the client
// @see: org.wso2.carbon.registry.webdav.RegistryServlet.doMkCol()
if (null == resourceImpl) {
resourceImpl = isCollection ? new CollectionImpl() : new ResourceImpl();
//setting path and underline resource only for newly created resources
((ResourceImpl) resourceImpl).setPath(resource.getResourcePath());
((RegistryResource) resource).setUnderLineResource(resourceImpl);
//if (!isCollection) {
resourceCache.updateDavResourceMimeType((RegistryResource) resource);
// setting the media type to text/plain as the default for newly created resources with
// no extensions.
if( null == resourceImpl.getMediaType() && resourceImpl.getPath().indexOf('.') == -1) {
resourceImpl.setMediaType("text/plain");
}
//}
}
if (!isCollection) {
resourceImpl.setContentStream(inputContext.getInputStream());
}
resourceCache.getRegistry().put(resource.getResourcePath(), resourceImpl);
} else {
throw new DavException(DavServletResponse.SC_BAD_REQUEST,
"Internal Error, Parent and target path does not match");
}
} else {
throw new DavException(DavServletResponse.SC_BAD_REQUEST,
"Only add resources to Collections");
}
} else {
throw new DavException(DavServletResponse.SC_BAD_REQUEST,
"Only support " + RegistryResource.class + " as members");
}
} catch (RegistryException e) {
e.printStackTrace();
throw new DavException(DavServletResponse.SC_BAD_REQUEST,e);
}
}
public boolean exists() {
if(doesNotExists){
return false;
}else{
try{
getUnderlineResource();
return true;
} catch (RuntimeException e) {
return false;
}
}
}
public boolean isCollection() {
return exists() && getUnderlineResource() instanceof Collection;
}
public DavResource getCollection() {
try {
int index = path.lastIndexOf("/");
if(index >= 0){
String parentPath = path.substring(0,index+1);
return resourceCache.getRegistryResource(parentPath);
}else{
throw new RuntimeException("Illegal Path "+ path);
}
} catch (DavException e) {
throw new RuntimeException(e);
}
}
public String getComplianceClass() {
return COMPLIANCE_CLASSES;
}
public String getDisplayName() {
String fullpath = path;
if(fullpath.equals("/")){
return "/";
}
String[] tokens = fullpath.split("/");
return tokens[tokens.length-1]+"_";
}
// We do not do lock, at least not for now.
public ActiveLock getLock(Type type, Scope scope) {
if(lockable){
ActiveLock lock = null;
if (exists() && Type.WRITE.equals(type) && Scope.EXCLUSIVE.equals(scope)) {
lock = lockManager.getLock(type, scope, this);
}
return lock;
}else{
throw new UnsupportedOperationException();
}
}
public ActiveLock[] getLocks() {
if(lockable){
ActiveLock writeLock = getLock(Type.WRITE, Scope.EXCLUSIVE);
return (writeLock != null) ? new ActiveLock[]{writeLock} : new ActiveLock[0];
}else{
throw new UnsupportedOperationException();
}
}
public boolean hasLock(Type type, Scope scope) {
if(lockable){
return getLock(type, scope) != null;
}else{
throw new UnsupportedOperationException();
}
}
public boolean isLockable(Type type, Scope scope) {
return lockable;
}
public void addLockManager(LockManager lockmgr) {
this.lockManager = lockmgr;
}
public void unlock(String lockToken) throws DavException {
if(lockable){
ActiveLock lock = getLock(Type.WRITE, Scope.EXCLUSIVE);
if (lock == null) {
throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED);
} else if (lock.isLockedByToken(lockToken)) {
lockManager.releaseLock(lockToken, this);
} else {
throw new DavException(DavServletResponse.SC_LOCKED);
}
}else{
throw new UnsupportedOperationException();
}
}
public ActiveLock lock(LockInfo lockInfo) throws DavException {
if(lockable){
if (isLockable(lockInfo.getType(), lockInfo.getScope())) {
return lockManager.createLock(lockInfo, this);
} else {
throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "Unsupported lock type or scope.");
}
}else{
throw new UnsupportedOperationException();
}
}
public ActiveLock refreshLock(LockInfo lockInfo, String lockToken) throws DavException{
if(lockable){
if (!exists()) {
throw new DavException(DavServletResponse.SC_NOT_FOUND);
}
ActiveLock lock = getLock(lockInfo.getType(), lockInfo.getScope());
if (lock == null) {
throw new DavException(DavServletResponse.SC_PRECONDITION_FAILED, "No lock with the given type/scope present on resource " + getResourcePath());
}
lock = lockManager.refreshLock(lockInfo, lockToken, this);
/* since lock has infinite lock (simple) or undefined timeout (jcr)
return the lock as retrieved from getLock. */
return lock;
}else{
throw new UnsupportedOperationException();
}
}
public void removeMember(DavResource member) throws DavException {
try {
String path = member.getResourcePath();
resourceCache.saveDavResourceMimeType((RegistryResource) member);
resourceCache.removeRegistryResource(path);
registry.delete(path);
} catch (RegistryException e) {
throw new DavException(DavServletResponse.SC_BAD_REQUEST);
}
}
public void removeProperty(DavPropertyName propertyName)
throws DavException {
getUnderlineResource().removeProperty(propertyName.getName());
}
public void setProperty(DavProperty property) throws DavException {
getUnderlineResource().setProperty(property.getName().getName(),
(String) property.getValue());
}
public String getResourcePath() {
return path;
}
public void move(DavResource destination) throws DavException {
try {
registry.move(path, destination
.getResourcePath());
resourceCache.saveDavResourceMimeType(this);
} catch (RegistryException e) {
throw new DavException(DavServletResponse.SC_BAD_REQUEST);
}
}
public void copy(DavResource destination, boolean shallow)
throws DavException {
try {
if(shallow){
throw new DavException(DavServletResponse.SC_BAD_REQUEST,"Shallow copy/move not supported");
}
registry.copy(path, destination
.getResourcePath());
} catch (RegistryException e) {
throw new DavException(DavServletResponse.SC_BAD_REQUEST,e);
}
}
public MultiStatusResponse alterProperties(List changeList)
throws DavException {
if (!exists()) {
throw new DavException(DavServletResponse.SC_NOT_FOUND);
}
MultiStatusResponse msr = new MultiStatusResponse(getHref(), null);
Iterator it = changeList.iterator();
while(it.hasNext()){
DavProperty property = (DavProperty)it.next();
try{
getUnderlineResource().setProperty(property.getName().getName(), (String)property.getValue());
msr.add(property, DavServletResponse.SC_OK);
}catch (Exception e) {
e.printStackTrace();
msr.add(property, DavServletResponse.SC_BAD_REQUEST);
}
}
return msr;
}
public MultiStatusResponse alterProperties(DavPropertySet setProperties,
DavPropertyNameSet removePropertyNames) throws DavException {
if (!exists()) {
throw new DavException(DavServletResponse.SC_NOT_FOUND);
}
MultiStatusResponse msr = new MultiStatusResponse(getHref(), null);
Iterator it = setProperties.iterator();
while(it.hasNext()){
DavProperty property = (DavProperty)it.next();
try{
getUnderlineResource().setProperty(property.getName().getName(), (String)property.getValue());
msr.add(property, DavServletResponse.SC_OK);
}catch (Exception e) {
e.printStackTrace();
msr.add(property, DavServletResponse.SC_BAD_REQUEST);
}
}
it = setProperties.iterator();
while(it.hasNext()){
DavProperty property = (DavProperty)it.next();
try{
getUnderlineResource().setProperty(property.getName().getName(), (String)property.getValue());
msr.add(property, DavServletResponse.SC_OK);
}catch (Exception e) {
e.printStackTrace();
msr.add(property, DavServletResponse.SC_BAD_REQUEST);
}
}
return msr;
}
public DavResourceFactory getFactory() {
return resourceCache.getEnviorment().getResourceFactory();
}
// white spaces are replaced by '%20' to avoid href space issue with resource names.
public String getHref() {
return new StringBuffer(resourceCache.getContextPath()).append("/registry/resourcewebdav").append(path).toString().replace(" ","%20");
}
public DavResourceLocator getLocator() {
return locator;
}
public DavResourceIterator getMembers() {
try {
String[] childrenNames = ((CollectionImpl)getUnderlineResource()).getChildren();
List childrenList = new ArrayList();
for(String name:childrenNames){
RegistryResource registryResource = resourceCache.getRegistryResource(name);
if(!"true".equals(registryResource.getUnderlineResource().getProperty("registry.link"))) {
childrenList.add(registryResource);
}
}
return new DavResourceIteratorImpl(childrenList);
} catch (RegistryException e) {
throw new RuntimeException(e);
} catch (DavException e) {
throw new RuntimeException(e);
}
}
public long getModificationTime() {
return getUnderlineResource().getLastModified().getTime();
}
public DavPropertySet getProperties() {
final Properties properties = getUnderlineResource().getProperties();
DavPropertySet davproperties = new DavPropertySet();
Iterator it = properties.keySet().iterator();
while(it.hasNext()){
final Object key = it.next();
davproperties.add(new DavProperty() {
public Element toXml(Document document) {
return null;
}
public boolean isInvisibleInAllprop() {
return false;
}
public Object getValue() {
return properties.get(key);
}
public DavPropertyName getName() {
return DavPropertyName.create((String)key);
}
});
}
for (DavProperty p : this.properties.values()) {
davproperties.add(p);
}
return davproperties;
}
public DavProperty getProperty(final DavPropertyName name) {
DavProperty property = properties.get(name);
if(property != null){
return property;
}else{
return new DavProperty() {
public Element toXml(Document document) {
return null;
}
public boolean isInvisibleInAllprop() {
return false;
}
public Object getValue() {
return getUnderlineResource().getProperty(name.getName());
}
public DavPropertyName getName() {
return name;
}
};
}
}
public DavPropertyName[] getPropertyNames() {
List<DavPropertyName> list = new ArrayList<DavPropertyName>();
Iterator it = getUnderlineResource().getProperties().keySet().iterator();
while(it.hasNext()){
list.add(DavPropertyName.create((String)it.next()));
}
Iterator it2 = properties.keySet().iterator();
while(it2.hasNext()){
list.add(((DavPropertyName)it2.next()));
}
return list.toArray(new DavPropertyName[0]);
}
public DavSession getSession() {
return resourceCache.getSession();
}
public String getSupportedMethods() {
return "OPTIONS, GET, HEAD, POST, TRACE, PROPFIND, PROPPATCH, MKCOL, COPY,PUT, DELETE, MOVE, LOCK, UNLOCK, BIND, REBIND, UNBIND";
}
public void spool(OutputContext outputContext) throws IOException {
try {
if (exists()) {
if (!isCollection()) {
final InputStream in = getUnderLineResource().getContentStream();
final OutputStream out = outputContext.getOutputStream();
if (null != out) {
byte[] buf = new byte[1024];
int read;
while ((read = in.read(buf)) >= 0) {
out.write(buf, 0, read);
}
}
}
} else {
throw new IOException("Resource " + path + " does not exists");
}
} catch (RegistryException e) {
throw new IOException("Error writing resource " + path + ":" + e.getMessage());
}
}
public Resource getUnderLineResource() {
return underLineResource;
}
public void setUnderLineResource(Resource underLineResource) {
this.underLineResource = underLineResource;
}
/**
* Return true if this resource cannot be modified due to a write lock
* that is not owned by the given session.
*
* @return true if this resource cannot be modified due to a write lock
*/
private boolean isLocked(DavResource res) {
ActiveLock lock = res.getLock(Type.WRITE, Scope.EXCLUSIVE);
if (lock == null) {
return false;
} else {
String[] sLockTokens = session.getLockTokens();
for (int i = 0; i < sLockTokens.length; i++) {
if (sLockTokens[i].equals(lock.getToken())) {
return false;
}
}
return true;
}
}
}
| arunasujith/carbon-registry | components/registry/org.wso2.carbon.registry.webdav/src/main/java/org/wso2/carbon/registry/webdav/RegistryResource.java | Java | apache-2.0 | 21,191 |
// +build experimental
package client
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
"golang.org/x/net/context"
)
func TestPluginRemoveError(t *testing.T) {
client := &Client{
transport: newMockClient(nil, errorMock(http.StatusInternalServerError, "Server error")),
}
err := client.PluginRemove(context.Background(), "plugin_name")
if err == nil || err.Error() != "Error response from daemon: Server error" {
t.Fatalf("expected a Server Error, got %v", err)
}
}
func TestPluginRemove(t *testing.T) {
expectedURL := "/plugins/plugin_name"
client := &Client{
transport: newMockClient(nil, func(req *http.Request) (*http.Response, error) {
if !strings.HasPrefix(req.URL.Path, expectedURL) {
return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL)
}
if req.Method != "DELETE" {
return nil, fmt.Errorf("expected POST method, got %s", req.Method)
}
return &http.Response{
StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
}, nil
}),
}
err := client.PluginRemove(context.Background(), "plugin_name")
if err != nil {
t.Fatal(err)
}
}
| venilnoronha/docker-volume-vsphere | vendor/github.com/docker/engine-api/client/plugin_remove_test.go | GO | apache-2.0 | 1,171 |
var _curry2 = require('./internal/_curry2');
var _dispatchable = require('./internal/_dispatchable');
var _xfindIndex = require('./internal/_xfindIndex');
/**
* Returns the index of the first element of the list which matches the
* predicate, or `-1` if no element matches.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.1
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Number} The index of the element found, or `-1`.
* @see R.transduce
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.findIndex(R.propEq('a', 2))(xs); //=> 1
* R.findIndex(R.propEq('a', 4))(xs); //=> -1
*/
module.exports = _curry2(_dispatchable([], _xfindIndex, function findIndex(fn, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
if (fn(list[idx])) {
return idx;
}
idx += 1;
}
return -1;
}));
| BigBoss424/portfolio | v7/development/node_modules/ramda/src/findIndex.js | JavaScript | apache-2.0 | 1,078 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>DataTables example - Flexible table width</title>
<link rel="stylesheet" type="text/css" href="../../media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="../resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../resources/demo.css">
<style type="text/css" class="init">
div.container {
width: 80%;
}
</style>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.11.3.min.js">
</script>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.dataTables.js">
</script>
<script type="text/javascript" language="javascript" src="../resources/syntax/shCore.js">
</script>
<script type="text/javascript" language="javascript" src="../resources/demo.js">
</script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>DataTables example <span>Flexible table width</span></h1>
<div class="info">
<p>Often you may want to have your table resize dynamically with the page. Typically this is done by assigning <code>width:100%</code> in your CSS, but this
presents a problem for Javascript since it can be very hard to get that relative size rather than the absolute pixels. As such, if you apply the <code>width</code>
attribute to the HTML table tag or inline width style (<code>style="width:100%"</code>), it will be used as the width for the table (overruling any CSS
styles).</p>
<p>This example shows a table with <code>width="100%"</code> and the container is also flexible width, so as the window is resized, the table will also resize
dynamically.</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
</tr>
<tr>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
</tr>
<tr>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
</tr>
<tr>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
</tr>
<tr>
<td>Quinn Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
</tr>
<tr>
<td>Charde Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
</tr>
<tr>
<td>Tatyana Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
</tr>
<tr>
<td>Michael Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
</tr>
<tr>
<td>Paul Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
</tr>
<tr>
<td>Gloria Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
</tr>
<tr>
<td>Bradley Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
</tr>
<tr>
<td>Dai Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
</tr>
<tr>
<td>Jenette Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
</tr>
<tr>
<td>Yuri Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
</tr>
<tr>
<td>Caesar Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
</tr>
<tr>
<td>Doris Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
</tr>
<tr>
<td>Angelica Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
</tr>
<tr>
<td>Gavin Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
</tr>
<tr>
<td>Jennifer Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
</tr>
<tr>
<td>Brenden Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
</tr>
<tr>
<td>Fiona Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
</tr>
<tr>
<td>Shou Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
</tr>
<tr>
<td>Michelle House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
</tr>
<tr>
<td>Suki Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
</tr>
<tr>
<td>Prescott Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
</tr>
<tr>
<td>Gavin Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
</tr>
<tr>
<td>Martena Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
</tr>
<tr>
<td>Unity Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
</tr>
<tr>
<td>Howard Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
</tr>
<tr>
<td>Hope Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
</tr>
<tr>
<td>Vivian Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
</tr>
<tr>
<td>Timothy Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
</tr>
<tr>
<td>Jackson Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
</tr>
<tr>
<td>Olivia Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
</tr>
<tr>
<td>Bruno Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
</tr>
<tr>
<td>Sakura Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
</tr>
<tr>
<td>Thor Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
</tr>
<tr>
<td>Finn Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
</tr>
<tr>
<td>Serge Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
</tr>
<tr>
<td>Zenaida Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
</tr>
<tr>
<td>Zorita Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
</tr>
<tr>
<td>Jennifer Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
</tr>
<tr>
<td>Cara Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
</tr>
<tr>
<td>Hermione Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
</tr>
<tr>
<td>Lael Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
</tr>
<tr>
<td>Jonas Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
</tr>
<tr>
<td>Shad Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
</tr>
<tr>
<td>Michael Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() {
$('#example').DataTable();
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p>
<ul>
<li>
<a href="//code.jquery.com/jquery-1.11.3.min.js">//code.jquery.com/jquery-1.11.3.min.js</a>
</li>
<li>
<a href="../../media/js/jquery.dataTables.js">../../media/js/jquery.dataTables.js</a>
</li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The
additional CSS used is shown below:</p><code class="multiline language-css">div.container {
width: 80%;
}</code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p>
<ul>
<li>
<a href="../../media/css/jquery.dataTables.css">../../media/css/jquery.dataTables.css</a>
</li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is
loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side
processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables
documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="./index.html">Basic initialisation</a></h3>
<ul class="toc active">
<li>
<a href="./zero_configuration.html">Zero configuration</a>
</li>
<li>
<a href="./filter_only.html">Feature enable / disable</a>
</li>
<li>
<a href="./table_sorting.html">Default ordering (sorting)</a>
</li>
<li>
<a href="./multi_col_sort.html">Multi-column ordering</a>
</li>
<li>
<a href="./multiple_tables.html">Multiple tables</a>
</li>
<li>
<a href="./hidden_columns.html">Hidden columns</a>
</li>
<li>
<a href="./complex_header.html">Complex headers (rowspan and colspan)</a>
</li>
<li>
<a href="./dom.html">DOM positioning</a>
</li>
<li class="active">
<a href="./flexible_width.html">Flexible table width</a>
</li>
<li>
<a href="./state_save.html">State saving</a>
</li>
<li>
<a href="./alt_pagination.html">Alternative pagination</a>
</li>
<li>
<a href="./scroll_y.html">Scroll - vertical</a>
</li>
<li>
<a href="./scroll_y_dynamic.html">Scroll - vertical, dynamic height</a>
</li>
<li>
<a href="./scroll_x.html">Scroll - horizontal</a>
</li>
<li>
<a href="./scroll_xy.html">Scroll - horizontal and vertical</a>
</li>
<li>
<a href="./comma-decimal.html">Language - Comma decimal place</a>
</li>
<li>
<a href="./language.html">Language options</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../advanced_init/index.html">Advanced initialisation</a></h3>
<ul class="toc">
<li>
<a href="../advanced_init/events_live.html">DOM / jQuery events</a>
</li>
<li>
<a href="../advanced_init/dt_events.html">DataTables events</a>
</li>
<li>
<a href="../advanced_init/column_render.html">Column rendering</a>
</li>
<li>
<a href="../advanced_init/length_menu.html">Page length options</a>
</li>
<li>
<a href="../advanced_init/dom_multiple_elements.html">Multiple table control elements</a>
</li>
<li>
<a href="../advanced_init/complex_header.html">Complex headers with column visibility</a>
</li>
<li>
<a href="../advanced_init/object_dom_read.html">Read HTML to data objects</a>
</li>
<li>
<a href="../advanced_init/html5-data-options.html">HTML5 data-* attributes - table options</a>
</li>
<li>
<a href="../advanced_init/html5-data-attributes.html">HTML5 data-* attributes - cell data</a>
</li>
<li>
<a href="../advanced_init/language_file.html">Language file</a>
</li>
<li>
<a href="../advanced_init/defaults.html">Setting defaults</a>
</li>
<li>
<a href="../advanced_init/row_callback.html">Row created callback</a>
</li>
<li>
<a href="../advanced_init/row_grouping.html">Row grouping</a>
</li>
<li>
<a href="../advanced_init/footer_callback.html">Footer callback</a>
</li>
<li>
<a href="../advanced_init/dom_toolbar.html">Custom toolbar elements</a>
</li>
<li>
<a href="../advanced_init/sort_direction_control.html">Order direction sequence control</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../styling/index.html">Styling</a></h3>
<ul class="toc">
<li>
<a href="../styling/display.html">Base style</a>
</li>
<li>
<a href="../styling/no-classes.html">Base style - no styling classes</a>
</li>
<li>
<a href="../styling/cell-border.html">Base style - cell borders</a>
</li>
<li>
<a href="../styling/compact.html">Base style - compact</a>
</li>
<li>
<a href="../styling/hover.html">Base style - hover</a>
</li>
<li>
<a href="../styling/order-column.html">Base style - order-column</a>
</li>
<li>
<a href="../styling/row-border.html">Base style - row borders</a>
</li>
<li>
<a href="../styling/stripe.html">Base style - stripe</a>
</li>
<li>
<a href="../styling/bootstrap.html">Bootstrap</a>
</li>
<li>
<a href="../styling/foundation.html">Foundation</a>
</li>
<li>
<a href="../styling/jqueryUI.html">jQuery UI ThemeRoller</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../data_sources/index.html">Data sources</a></h3>
<ul class="toc">
<li>
<a href="../data_sources/dom.html">HTML (DOM) sourced data</a>
</li>
<li>
<a href="../data_sources/ajax.html">Ajax sourced data</a>
</li>
<li>
<a href="../data_sources/js_array.html">Javascript sourced data</a>
</li>
<li>
<a href="../data_sources/server_side.html">Server-side processing</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../api/index.html">API</a></h3>
<ul class="toc">
<li>
<a href="../api/add_row.html">Add rows</a>
</li>
<li>
<a href="../api/multi_filter.html">Individual column searching (text inputs)</a>
</li>
<li>
<a href="../api/multi_filter_select.html">Individual column searching (select inputs)</a>
</li>
<li>
<a href="../api/highlight.html">Highlighting rows and columns</a>
</li>
<li>
<a href="../api/row_details.html">Child rows (show extra / detailed information)</a>
</li>
<li>
<a href="../api/select_row.html">Row selection (multiple rows)</a>
</li>
<li>
<a href="../api/select_single_row.html">Row selection and deletion (single row)</a>
</li>
<li>
<a href="../api/form.html">Form inputs</a>
</li>
<li>
<a href="../api/counter_columns.html">Index column</a>
</li>
<li>
<a href="../api/show_hide.html">Show / hide columns dynamically</a>
</li>
<li>
<a href="../api/api_in_init.html">Using API in callbacks</a>
</li>
<li>
<a href="../api/tabs_and_scrolling.html">Scrolling and Bootstrap tabs</a>
</li>
<li>
<a href="../api/regex.html">Search API (regular expressions)</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../ajax/index.html">Ajax</a></h3>
<ul class="toc">
<li>
<a href="../ajax/simple.html">Ajax data source (arrays)</a>
</li>
<li>
<a href="../ajax/objects.html">Ajax data source (objects)</a>
</li>
<li>
<a href="../ajax/deep.html">Nested object data (objects)</a>
</li>
<li>
<a href="../ajax/objects_subarrays.html">Nested object data (arrays)</a>
</li>
<li>
<a href="../ajax/orthogonal-data.html">Orthogonal data</a>
</li>
<li>
<a href="../ajax/null_data_source.html">Generated content for a column</a>
</li>
<li>
<a href="../ajax/custom_data_property.html">Custom data source property</a>
</li>
<li>
<a href="../ajax/custom_data_flat.html">Flat array data source</a>
</li>
<li>
<a href="../ajax/defer_render.html">Deferred rendering for speed</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../server_side/index.html">Server-side</a></h3>
<ul class="toc">
<li>
<a href="../server_side/simple.html">Server-side processing</a>
</li>
<li>
<a href="../server_side/custom_vars.html">Custom HTTP variables</a>
</li>
<li>
<a href="../server_side/post.html">POST data</a>
</li>
<li>
<a href="../server_side/ids.html">Automatic addition of row ID attributes</a>
</li>
<li>
<a href="../server_side/object_data.html">Object data source</a>
</li>
<li>
<a href="../server_side/row_details.html">Row details</a>
</li>
<li>
<a href="../server_side/select_rows.html">Row selection</a>
</li>
<li>
<a href="../server_side/jsonp.html">JSONP data source for remote domains</a>
</li>
<li>
<a href="../server_side/defer_loading.html">Deferred loading of data</a>
</li>
<li>
<a href="../server_side/pipeline.html">Pipelining data to reduce Ajax calls for paging</a>
</li>
</ul>
</div>
<div class="toc-group">
<h3><a href="../plug-ins/index.html">Plug-ins</a></h3>
<ul class="toc">
<li>
<a href="../plug-ins/api.html">API plug-in methods</a>
</li>
<li>
<a href="../plug-ins/sorting_auto.html">Ordering plug-ins (with type detection)</a>
</li>
<li>
<a href="../plug-ins/sorting_manual.html">Ordering plug-ins (no type detection)</a>
</li>
<li>
<a href="../plug-ins/range_filtering.html">Custom filtering - range search</a>
</li>
<li>
<a href="../plug-ins/dom_sort.html">Live DOM ordering</a>
</li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extensions">extensions</a> and <a href=
"http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of DataTables.</p>
<p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2015<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | zhanglei13/zeppelin | zeppelin-client/src/asserts/DataTables-1.10.10/examples/basic_init/flexible_width.html | HTML | apache-2.0 | 25,012 |
/* Copyright 2018 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/core/grappler/optimizers/data/fusion_utils.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/mutable_graph_view.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h"
#include "tensorflow/core/grappler/optimizers/data/function_utils.h"
#include "tensorflow/core/grappler/optimizers/data/graph_utils.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/lib/gtl/flatmap.h"
#include "tensorflow/core/lib/gtl/flatset.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/protobuf.h"
namespace tensorflow {
namespace grappler {
namespace fusion_utils {
namespace {
string ParseNodeConnection(const string& name) {
// If input/output node name has semicolon, take the prefix. Otherwise take
// the whole string.
return name.substr(0, name.find(':'));
}
string ParseOutputNode(const string& name) {
if (name.find(':') == string::npos) return {};
return name.substr(name.find(':'), string::npos);
}
string GetOutputNode(const FunctionDef& function, int output_idx) {
const auto& ret_output_name =
function.signature().output_arg(output_idx).name();
return function.ret().at(ret_output_name);
}
string& GetMutableOutputNode(FunctionDef* function, int output_idx) {
const auto& ret_output_name =
function->signature().output_arg(output_idx).name();
return function->mutable_ret()->at(ret_output_name);
}
template <typename Iterable>
StringCollection GetNames(const Iterable& iterable, int allocate_size) {
StringCollection names;
names.reserve(allocate_size);
for (auto& arg : iterable) names.push_back(arg.name());
return names;
}
template <typename Iterable>
gtl::FlatSet<string> GetNodeNamesSet(const Iterable& nodes) {
// NOTE(prazek): Cases where the set is not modified after construction
// could use sorted vector with binary_search instead, to make it faster.
gtl::FlatSet<string> names;
for (const auto& node : nodes) {
CHECK(gtl::InsertIfNotPresent(&names, node.name()))
<< "Functions should have unique node names. Node with name "
<< node.name() << " already exists";
}
return names;
}
template <typename Iterable>
gtl::FlatMap<string, string> GetUniqueNames(const Iterable& first_iterable,
const Iterable& second_iterable) {
gtl::FlatMap<string, string> changed_node_names;
const auto first_names = GetNodeNamesSet(first_iterable);
auto second_names = GetNodeNamesSet(first_iterable);
int id = second_iterable.size();
for (const auto& node : second_iterable) {
string name_before = node.name();
string name = name_before;
bool changed_name = false;
while (first_names.count(name) ||
(changed_name && second_names.count(name))) {
name = strings::StrCat(name_before, "/_", id);
changed_name = true;
++id;
}
if (changed_name) {
changed_node_names[name_before] = name;
// We don't want to pick a new name that would collide with another new
// name.
second_names.insert(std::move(name));
}
}
return changed_node_names;
}
// We need to rename them and the connections of the inputs that refer to them.
// Nodes that will be added to the function can have the same name as the nodes
// from parent function.
void RenameFunctionNodes(const FunctionDef& first_function,
protobuf::RepeatedPtrField<NodeDef>* nodes_to_fuse,
protobuf::Map<string, string>* rets_to_fuse) {
const gtl::FlatMap<string, string> changed_node_names =
GetUniqueNames(first_function.node_def(), *nodes_to_fuse);
auto update_name = [&changed_node_names](string* input) {
string input_node = ParseNodeConnection(*input);
auto iter = changed_node_names.find(input_node);
if (iter != changed_node_names.end()) {
*input = iter->second + ParseOutputNode(*input);
}
};
for (NodeDef& function_node : *nodes_to_fuse) {
if (const string* new_name =
gtl::FindOrNull(changed_node_names, function_node.name())) {
function_node.set_name(*new_name);
}
for (string& input : *function_node.mutable_input()) {
update_name(&input);
}
}
for (auto& ret : *rets_to_fuse) update_name(&ret.second);
}
StringCollection GetFunctionInputs(const FunctionDef& function) {
return GetNames(function.signature().input_arg(),
function.signature().input_arg_size());
}
// This function produces signature having names that do not conflict with
// `first_signature`. The input of returns and nodes that will be fused are
// updated to use new names.
OpDef GetUniqueSignature(const OpDef& first_signature,
const OpDef& second_signature,
protobuf::Map<string, string>* rets_to_fuse,
protobuf::RepeatedPtrField<NodeDef>* nodes_to_fuse) {
const gtl::FlatMap<string, string> changed_input_names =
GetUniqueNames(first_signature.input_arg(), second_signature.input_arg());
OpDef signature;
signature.set_name(second_signature.name());
for (const auto& input_arg : second_signature.input_arg()) {
auto& input = *signature.add_input_arg();
input = input_arg;
if (const string* new_name =
gtl::FindOrNull(changed_input_names, input.name())) {
input.set_name(*new_name);
}
}
const gtl::FlatMap<string, string> changed_output_names = GetUniqueNames(
first_signature.output_arg(), second_signature.output_arg());
for (const auto& output_arg : second_signature.output_arg()) {
auto& output = *signature.add_output_arg();
output = output_arg;
if (const string* new_name =
gtl::FindOrNull(changed_output_names, output.name())) {
output.set_name(*new_name);
}
}
protobuf::Map<string, string> new_rets;
for (const auto& ret : *rets_to_fuse) {
const auto& key = changed_output_names.count(ret.first)
? changed_output_names.at(ret.first)
: ret.first;
const auto& input = ParseNodeConnection(ret.second);
const auto& value =
changed_input_names.count(input)
? changed_input_names.at(input) + ParseOutputNode(ret.second)
: ret.second;
new_rets[key] = value;
}
*rets_to_fuse = std::move(new_rets);
for (NodeDef& function_node : *nodes_to_fuse) {
for (auto& node_input : *function_node.mutable_input()) {
const auto& input = ParseNodeConnection(node_input);
if (const string* new_name =
gtl::FindOrNull(changed_input_names, input)) {
node_input = *new_name + ParseOutputNode(node_input);
}
}
}
return signature;
}
// This function adds new nodes and changes their input to the output nodes
// of parent function. It assumes that the name of nodes to fuse are not
// conflicting.
void FuseFunctionNodes(const StringCollection& first_inputs,
const StringCollection& second_inputs,
const StringCollection& first_outputs,
const SetInputFn& set_input,
protobuf::RepeatedPtrField<NodeDef>* nodes_to_fuse) {
for (NodeDef& function_node : *nodes_to_fuse) {
for (auto& node_input : *function_node.mutable_input()) {
auto parsed_name = ParseNodeConnection(node_input);
auto input_it =
std::find(second_inputs.begin(), second_inputs.end(), parsed_name);
if (input_it == second_inputs.end()) continue;
auto arg_num = std::distance(second_inputs.begin(), input_it);
node_input =
set_input(first_inputs, second_inputs, first_outputs, arg_num);
}
}
}
// This function looks for direct edges from input to return and rewrites
// them to the corresponding input of the return of `first_function`.
void FuseReturns(const StringCollection& first_inputs,
const StringCollection& second_inputs,
const StringCollection& first_outputs,
const SetInputFn& set_input,
protobuf::Map<string, string>* fused_ret) {
for (auto& ret : *fused_ret) {
auto return_input = ParseNodeConnection(ret.second);
auto input_it =
std::find(second_inputs.begin(), second_inputs.end(), return_input);
if (input_it == second_inputs.end()) continue;
auto input_idx = std::distance(second_inputs.begin(), input_it);
ret.second =
set_input(first_inputs, second_inputs, first_outputs, input_idx);
}
}
// Returns collection of node names that are used as a return from function.
StringCollection GetFunctionOutputs(const FunctionDef& function) {
const auto number_of_outputs = function.signature().output_arg_size();
StringCollection outputs;
outputs.reserve(number_of_outputs);
for (int output_idx = 0; output_idx < number_of_outputs; output_idx++)
outputs.push_back(GetOutputNode(function, output_idx));
return outputs;
}
FunctionDef* CreateFalsePredicate(
const protobuf::RepeatedPtrField<OpDef_ArgDef>& fake_args,
FunctionDefLibrary* library) {
GraphDef graph;
MutableGraphView graph_view(&graph);
auto* node = graph_utils::AddScalarConstNode(false, &graph_view);
auto* false_predicate = library->add_function();
graph_utils::SetUniqueGraphFunctionName("false_predicate", library,
false_predicate);
int num = 0;
for (const auto& fake_arg : fake_args) {
auto* arg = false_predicate->mutable_signature()->add_input_arg();
arg->set_type(fake_arg.type());
arg->set_name(strings::StrCat("fake_arg", num));
num++;
}
auto* output = false_predicate->mutable_signature()->add_output_arg();
output->set_name("false_out");
output->set_type(DT_BOOL);
(*false_predicate->mutable_ret())["false_out"] = node->name() + ":output:0";
*false_predicate->mutable_node_def() = std::move(*graph.mutable_node());
return false_predicate;
}
void CheckIfCanCompose(const OpDef& first_signature,
const OpDef& second_signature) {
CHECK(CanCompose(first_signature, second_signature))
<< "The number of input arguments of function " << second_signature.name()
<< " should be the same as the number of output arguments of function "
<< first_signature.name() << ".";
}
} // namespace
void MergeNodes(const FunctionDef& first_function,
const FunctionDef& second_function, FunctionDef* fused_function,
FunctionDefLibrary* library) {
// Copy all nodes from first_function.
fused_function->mutable_node_def()->CopyFrom(first_function.node_def());
// Copy transformed nodes from the second function.
fused_function->mutable_node_def()->MergeFrom(second_function.node_def());
}
bool CanCompose(const OpDef& first_signature, const OpDef& second_signature) {
// TODO(prazek): Functions can have additional inputs being placeholders
// for a values used in function. We should be able to also fuse these
// functions.
return first_signature.output_arg_size() == second_signature.input_arg_size();
}
string ComposeInput(const StringCollection& first_inputs,
const StringCollection& second_inputs,
const StringCollection& first_outputs, int arg_num) {
// Take corresponding parent output.
return first_outputs.at(arg_num);
}
void ComposeSignature(const OpDef& first_signature,
const OpDef& second_signature, OpDef* fused_signature) {
CheckIfCanCompose(first_signature, second_signature);
// Copy input signature from parent function.
*fused_signature->mutable_input_arg() = first_signature.input_arg();
// Copy output signature from second function.
*fused_signature->mutable_output_arg() = second_signature.output_arg();
}
void ComposeOutput(const protobuf::Map<string, string>& first_ret,
const protobuf::Map<string, string>& second_ret,
protobuf::Map<string, string>* fused_ret) {
*fused_ret = second_ret;
}
void CombineSignature(const OpDef& first_signature,
const OpDef& second_signature, OpDef* fused_signature) {
CheckIfCanCompose(first_signature, second_signature);
// Copy input and output signature from parent function.
*fused_signature = first_signature;
// Add new output parameter.
fused_signature->mutable_output_arg()->MergeFrom(
second_signature.output_arg());
}
void CombineOutput(const protobuf::Map<string, string>& first_ret,
const protobuf::Map<string, string>& second_ret,
protobuf::Map<string, string>* fused_ret) {
*fused_ret = first_ret;
fused_ret->insert(second_ret.begin(), second_ret.end());
}
string SameInput(const StringCollection& first_inputs,
const StringCollection& second_inputs,
const StringCollection& first_outputs, int arg_num) {
return first_inputs.at(arg_num);
}
bool HasSameSignature(const OpDef& first_signature,
const OpDef& second_signature) {
return first_signature.input_arg_size() ==
second_signature.input_arg_size() &&
first_signature.output_arg_size() ==
second_signature.output_arg_size();
}
void SameSignature(const OpDef& first_signature, const OpDef& second_signature,
OpDef* fused_signature) {
CHECK(HasSameSignature(first_signature, second_signature))
<< "Functions do not have the same signature";
// Copy signature from first function.
*fused_signature = first_signature;
}
void LazyConjunctionNodes(const FunctionDef& first_function,
const FunctionDef& second_function,
FunctionDef* fused_function,
FunctionDefLibrary* library) {
fused_function->mutable_node_def()->CopyFrom(first_function.node_def());
NodeDefBuilder if_builder("", "If");
if_builder.Input(GetOutputNode(first_function, 0), 0, DT_BOOL);
DataTypeVector in_arg_types;
std::vector<NodeDefBuilder::NodeOut> inputs;
for (const auto& input_arg : first_function.signature().input_arg()) {
inputs.push_back({input_arg.name(), 0, input_arg.type()});
in_arg_types.push_back(input_arg.type());
}
if_builder.Attr("Tin", in_arg_types);
if_builder.Attr("Tcond", DT_BOOL);
if_builder.Attr("Tout", DataTypeVector{DT_BOOL});
if_builder.Attr("_lower_using_switch_merge", true);
NameAttrList then_branch;
then_branch.set_name(second_function.signature().name());
if_builder.Attr("then_branch", then_branch);
auto* false_predicate =
CreateFalsePredicate(first_function.signature().input_arg(), library);
NameAttrList else_branch;
else_branch.set_name(false_predicate->signature().name());
if_builder.Attr("else_branch", else_branch);
if_builder.Input(inputs);
auto* if_node = fused_function->add_node_def();
// This is guaranteed to succeed.
TF_CHECK_OK(if_builder.Finalize(if_node));
function_utils::SetUniqueFunctionNodeName("cond", fused_function, if_node);
GetMutableOutputNode(fused_function, 0) = if_node->name() + ":output:0";
}
void LazyConjunctionOutput(const protobuf::Map<string, string>& first_ret,
const protobuf::Map<string, string>& second_ret,
protobuf::Map<string, string>* fused_ret) {
CHECK_EQ(first_ret.size(), 1);
CHECK_EQ(second_ret.size(), 1);
// Temporarily copy returns from first_ret. We are going to change the
// output node after creating it.
*fused_ret = first_ret;
}
FunctionDef* FuseFunctions(
const FunctionDef& first_function, const FunctionDef& second_function,
StringPiece fused_name_prefix, const SetFunctionSignatureFn& set_signature,
const SetInputFn& set_input, const SetOutputFn& set_output,
const SetNodesFn& set_nodes, FunctionDefLibrary* library) {
if (first_function.attr_size() != 0 || second_function.attr_size() != 0)
return nullptr; // Functions with attributes are currently not supported
// This function will be used as a clone of second function, having unique
// names.
FunctionDef setup_function = second_function;
*setup_function.mutable_signature() = GetUniqueSignature(
first_function.signature(), setup_function.signature(),
setup_function.mutable_ret(), setup_function.mutable_node_def());
FunctionDef* fused_function = library->add_function();
set_signature(first_function.signature(), setup_function.signature(),
fused_function->mutable_signature());
graph_utils::SetUniqueGraphFunctionName(fused_name_prefix, library,
fused_function);
RenameFunctionNodes(first_function, setup_function.mutable_node_def(),
setup_function.mutable_ret());
set_output(first_function.ret(), setup_function.ret(),
fused_function->mutable_ret());
CHECK(fused_function->signature().output_arg_size() ==
fused_function->ret_size())
<< "Fused function must have the same number of returns as output "
"args. Output size: "
<< fused_function->signature().output_arg_size()
<< ", ret size: " << fused_function->ret_size();
const auto first_inputs = GetFunctionInputs(first_function);
const auto second_inputs = GetFunctionInputs(setup_function);
const auto first_outputs = GetFunctionOutputs(first_function);
FuseFunctionNodes(first_inputs, second_inputs, first_outputs, set_input,
setup_function.mutable_node_def());
FuseReturns(first_inputs, second_inputs, first_outputs, set_input,
fused_function->mutable_ret());
set_nodes(first_function, setup_function, fused_function, library);
return fused_function;
}
} // namespace fusion_utils
} // namespace grappler
} // namespace tensorflow
| ghchinoy/tensorflow | tensorflow/core/grappler/optimizers/data/fusion_utils.cc | C++ | apache-2.0 | 18,800 |
################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF 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.
################################################################################
"""
Important classes of Flink Batch API:
- :class:`ExecutionEnvironment`:
The ExecutionEnvironment is the context in which a batch program is executed.
"""
from pyflink.dataset.execution_environment import ExecutionEnvironment
__all__ = ['ExecutionEnvironment']
| hequn8128/flink | flink-python/pyflink/dataset/__init__.py | Python | apache-2.0 | 1,234 |
/*
* Copyright 2000-2009 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.intellij.psi.filters.getters;
import com.intellij.psi.*;
import com.intellij.psi.filters.FilterUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
public class InstanceOfLeftPartTypeGetter {
@NotNull
public static PsiType[] getLeftTypes(PsiElement context) {
if((context = FilterUtil.getPreviousElement(context, true)) == null) return PsiType.EMPTY_ARRAY;
if(!PsiKeyword.INSTANCEOF.equals(context.getText())) return PsiType.EMPTY_ARRAY;
if((context = FilterUtil.getPreviousElement(context, false)) == null) return PsiType.EMPTY_ARRAY;
final PsiExpression contextOfType = PsiTreeUtil.getContextOfType(context, PsiExpression.class, false);
if (contextOfType == null) return PsiType.EMPTY_ARRAY;
PsiType type = contextOfType.getType();
if (type == null) return PsiType.EMPTY_ARRAY;
if (type instanceof PsiClassType) {
final PsiClass psiClass = ((PsiClassType)type).resolve();
if (psiClass instanceof PsiTypeParameter) {
return psiClass.getExtendsListTypes();
}
}
return new PsiType[]{type};
}
}
| asedunov/intellij-community | java/java-impl/src/com/intellij/psi/filters/getters/InstanceOfLeftPartTypeGetter.java | Java | apache-2.0 | 1,721 |
"use strict";
module.exports = function (t, a) {
a(t.call(new Date(2000, 0, 15, 13, 32, 34, 234)).valueOf(), new Date(2000, 0, 1).valueOf());
};
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/es5-ext/test/date/#/floor-month.js | JavaScript | apache-2.0 | 147 |
/*
* jQuery One Page Nav Plugin
* http://github.com/davist11/jQuery-One-Page-Nav
*
* Copyright (c) 2010 Trevor Davis (http://trevordavis.net)
* Dual licensed under the MIT and GPL licenses.
* Uses the same license as jQuery, see:
* http://jquery.org/license
*
* @version 3.0.0
*
* Example usage:
* $('#nav').onePageNav({
* currentClass: 'current',
* changeHash: false,
* scrollSpeed: 750
* });
*/
; (function ($, window, document, undefined) {
// our plugin constructor
var OnePageNav = function (elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$win = $(window);
this.sections = {};
this.didScroll = false;
this.$doc = $(document);
this.docHeight = this.$doc.height();
};
// the plugin prototype
OnePageNav.prototype = {
defaults: {
navItems: 'a',
currentClass: 'current',
changeHash: false,
easing: 'swing',
filter: '',
navHeight: 70,
scrollSpeed: 750,
scrollThreshold: 0.5,
begin: false,
end: false,
scrollChange: false
},
init: function () {
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.$nav = this.$elem.find(this.config.navItems);
//Filter any links out of the nav
if (this.config.filter !== '') {
this.$nav = this.$nav.filter(this.config.filter);
}
//Handle clicks on the nav
this.$nav.on('click.onePageNav', $.proxy(this.handleClick, this));
//Get the section positions
this.getPositions();
//Handle scroll changes
this.bindInterval();
//Update the positions on resize too
this.$win.on('resize.onePageNav', $.proxy(this.getPositions, this));
return this;
},
adjustNav: function (self, $parent) {
self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
$parent.addClass(self.config.currentClass);
},
bindInterval: function () {
var self = this;
var docHeight;
self.$win.on('scroll.onePageNav', function () {
self.didScroll = true;
});
self.t = setInterval(function () {
docHeight = self.$doc.height();
//If it was scrolled
if (self.didScroll) {
self.didScroll = false;
self.scrollChange();
}
//If the document height changes
if (docHeight !== self.docHeight) {
self.docHeight = docHeight;
self.getPositions();
}
}, 250);
},
getHash: function ($link) {
return $link.attr('href').split('#')[1];
},
getPositions: function () {
var self = this;
var linkHref;
var topPos;
var $target;
self.$nav.each(function () {
linkHref = self.getHash($(this));
$target = $('#' + linkHref);
if ($target.length) {
topPos = $target.offset().top;
self.sections[linkHref] = Math.round(topPos);
}
});
},
getSection: function (windowPos) {
var returnValue = null;
var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
for (var section in this.sections) {
if ((this.sections[section] - windowHeight) < windowPos) {
returnValue = section;
}
}
return returnValue;
},
handleClick: function (e) {
var self = this;
var $link = $(e.currentTarget);
var $parent = $link.parent();
var newLoc = '#' + self.getHash($link);
if (!$parent.hasClass(self.config.currentClass)) {
//Start callback
if (self.config.begin) {
self.config.begin();
}
//Change the highlighted nav item
self.adjustNav(self, $parent);
//Removing the auto-adjust on scroll
self.unbindInterval();
//Scroll to the correct position
self.scrollTo(newLoc, function () {
//Do we need to change the hash?
if (self.config.changeHash) {
window.location.hash = newLoc;
}
// $('#aboutUs').offset({'top':'60'});
//Add the auto-adjust on scroll back in
self.bindInterval();
//End callback
if (self.config.end) {
self.config.end();
}
});
}
e.preventDefault();
},
scrollChange: function () {
var windowTop = this.$win.scrollTop();
var position = this.getSection(windowTop);
var $parent;
//If the position is set
if (position !== null) {
$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
//If it's not already the current section
if (!$parent.hasClass(this.config.currentClass)) {
//Change the highlighted nav item
this.adjustNav(this, $parent);
//If there is a scrollChange callback
if (this.config.scrollChange) {
this.config.scrollChange($parent);
}
}
}
},
scrollTo: function (target, callback) {
var offset = $(target).offset().top - this.config.navHeight;
$('html, body').animate({
scrollTop: offset
}, this.config.scrollSpeed, this.config.easing, callback);
},
unbindInterval: function () {
clearInterval(this.t);
this.$win.unbind('scroll.onePageNav');
}
};
OnePageNav.defaults = OnePageNav.prototype.defaults;
$.fn.onePageNav = function (options) {
return this.each(function () {
new OnePageNav(this, options).init();
});
};
})(jQuery, window, document); | arthuralee/tether | website/js/jquery.nav.js | JavaScript | apache-2.0 | 7,028 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class MethodKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeInsideClass()
{
await VerifyKeywordAsync(
@"class C {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeAfterAttributeInsideClass()
{
await VerifyKeywordAsync(
@"class C {
[Goo]
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
}
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int Goo {
get;
}
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeAfterField()
{
await VerifyKeywordAsync(
@"class C {
int Goo;
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInAttributeAfterEvent()
{
await VerifyKeywordAsync(
@"class C {
event Action<int> Goo;
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInOuterAttribute()
{
await VerifyAbsenceAsync(
@"[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInParameterAttribute()
{
await VerifyAbsenceAsync(
@"class C {
void Goo([$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPropertyAttribute1()
{
await VerifyKeywordAsync(
@"class C {
int Goo { [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInPropertyAttribute2()
{
await VerifyKeywordAsync(
@"class C {
int Goo { get { } [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEventAttribute1()
{
await VerifyKeywordAsync(
@"class C {
event Action<int> Goo { [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEventAttribute2()
{
await VerifyKeywordAsync(
@"class C {
event Action<int> Goo { add { } [$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInTypeParameters()
{
await VerifyAbsenceAsync(
@"class C<[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInInterface()
{
await VerifyKeywordAsync(
@"interface I {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInStruct()
{
await VerifyKeywordAsync(
@"struct S {
[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnum()
{
await VerifyAbsenceAsync(
@"enum E {
[$$");
}
}
}
| MichalStrehovsky/roslyn | src/EditorFeatures/CSharpTest2/Recommendations/MethodKeywordRecommenderTests.cs | C# | apache-2.0 | 5,325 |
"""The tests for the Ring light platform."""
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from .common import setup_platform
from tests.common import load_fixture
async def test_entity_registry(hass, requests_mock):
"""Tests that the devices are registered in the entity registry."""
await setup_platform(hass, LIGHT_DOMAIN)
entity_registry = await hass.helpers.entity_registry.async_get_registry()
entry = entity_registry.async_get("light.front_light")
assert entry.unique_id == 765432
entry = entity_registry.async_get("light.internal_light")
assert entry.unique_id == 345678
async def test_light_off_reports_correctly(hass, requests_mock):
"""Tests that the initial state of a device that should be off is correct."""
await setup_platform(hass, LIGHT_DOMAIN)
state = hass.states.get("light.front_light")
assert state.state == "off"
assert state.attributes.get("friendly_name") == "Front light"
async def test_light_on_reports_correctly(hass, requests_mock):
"""Tests that the initial state of a device that should be on is correct."""
await setup_platform(hass, LIGHT_DOMAIN)
state = hass.states.get("light.internal_light")
assert state.state == "on"
assert state.attributes.get("friendly_name") == "Internal light"
async def test_light_can_be_turned_on(hass, requests_mock):
"""Tests the light turns on correctly."""
await setup_platform(hass, LIGHT_DOMAIN)
# Mocks the response for turning a light on
requests_mock.put(
"https://api.ring.com/clients_api/doorbots/765432/floodlight_light_on",
text=load_fixture("ring_doorbot_siren_on_response.json"),
)
state = hass.states.get("light.front_light")
assert state.state == "off"
await hass.services.async_call(
"light", "turn_on", {"entity_id": "light.front_light"}, blocking=True
)
await hass.async_block_till_done()
state = hass.states.get("light.front_light")
assert state.state == "on"
async def test_updates_work(hass, requests_mock):
"""Tests the update service works correctly."""
await setup_platform(hass, LIGHT_DOMAIN)
state = hass.states.get("light.front_light")
assert state.state == "off"
# Changes the return to indicate that the light is now on.
requests_mock.get(
"https://api.ring.com/clients_api/ring_devices",
text=load_fixture("ring_devices_updated.json"),
)
await hass.services.async_call("ring", "update", {}, blocking=True)
await hass.async_block_till_done()
state = hass.states.get("light.front_light")
assert state.state == "on"
| nkgilley/home-assistant | tests/components/ring/test_light.py | Python | apache-2.0 | 2,649 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents an event.
/// </summary>
internal abstract partial class EventSymbol : Symbol, IEventSymbol
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Changes to the public interface of this class should remain synchronized with the VB version.
// Do not make any changes to the public interface without making the corresponding change
// to the VB version.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal EventSymbol()
{
}
/// <summary>
/// The original definition of this symbol. If this symbol is constructed from another
/// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in
/// source or metadata.
/// </summary>
public new virtual EventSymbol OriginalDefinition
{
get
{
return this;
}
}
protected override sealed Symbol OriginalSymbolDefinition
{
get
{
return this.OriginalDefinition;
}
}
/// <summary>
/// The type of the event.
/// </summary>
public abstract TypeSymbol Type { get; }
/// <summary>
/// The 'add' accessor of the event. Null only in error scenarios.
/// </summary>
public abstract MethodSymbol AddMethod { get; }
/// <summary>
/// The 'remove' accessor of the event. Null only in error scenarios.
/// </summary>
public abstract MethodSymbol RemoveMethod { get; }
internal bool HasAssociatedField
{
get
{
return (object)this.AssociatedField != null;
}
}
/// <summary>
/// True if this is a Windows Runtime-style event.
///
/// A normal C# event, "event D E", has accessors
/// void add_E(D d)
/// void remove_E(D d)
///
/// A Windows Runtime event, "event D E", has accessors
/// EventRegistrationToken add_E(D d)
/// void remove_E(EventRegistrationToken t)
/// </summary>
public abstract bool IsWindowsRuntimeEvent { get; }
/// <summary>
/// True if this symbol has a special name (metadata flag SpecialName is set).
/// </summary>
internal abstract bool HasSpecialName { get; }
/// <summary>
/// Gets the attributes on event's associated field, if any.
/// Returns an empty <see cref="ImmutableArray<AttributeData>"/> if
/// there are no attributes.
/// </summary>
/// <remarks>
/// This publicly exposes the attributes of the internal backing field.
/// </remarks>
public ImmutableArray<CSharpAttributeData> GetFieldAttributes()
{
return (object)this.AssociatedField == null ?
ImmutableArray<CSharpAttributeData>.Empty :
this.AssociatedField.GetAttributes();
}
internal virtual FieldSymbol AssociatedField
{
get
{
return null;
}
}
/// <summary>
/// Returns the overridden event, or null.
/// </summary>
public EventSymbol OverriddenEvent
{
get
{
if (this.IsOverride)
{
if (IsDefinition)
{
return (EventSymbol)OverriddenOrHiddenMembers.GetOverriddenMember();
}
return (EventSymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenEvent);
}
return null;
}
}
internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers
{
get
{
return this.MakeOverriddenOrHiddenMembers();
}
}
internal bool HidesBaseEventsByName
{
get
{
MethodSymbol accessor = AddMethod ?? RemoveMethod;
return (object)accessor != null && accessor.HidesBaseMethodsByName;
}
}
internal EventSymbol GetLeastOverriddenEvent(NamedTypeSymbol accessingTypeOpt)
{
var accessingType = ((object)accessingTypeOpt == null ? this.ContainingType : accessingTypeOpt).OriginalDefinition;
EventSymbol e = this;
while (e.IsOverride && !e.HidesBaseEventsByName)
{
// NOTE: We might not be able to access the overridden event. For example,
//
// .assembly A
// {
// InternalsVisibleTo("B")
// public class A { internal virtual event Action E { add; remove; } }
// }
//
// .assembly B
// {
// InternalsVisibleTo("C")
// public class B : A { internal override event Action E { add; remove; } }
// }
//
// .assembly C
// {
// public class C : B { ... new B().E += null ... } // A.E is not accessible from here
// }
//
// See InternalsVisibleToAndStrongNameTests: IvtVirtualCall1, IvtVirtualCall2, IvtVirtual_ParamsAndDynamic.
EventSymbol overridden = e.OverriddenEvent;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if ((object)overridden == null || !AccessCheck.IsSymbolAccessible(overridden, accessingType, ref useSiteDiagnostics))
{
break;
}
e = overridden;
}
return e;
}
/// <summary>
/// Source: Was the member name qualified with a type name?
/// Metadata: Is the member an explicit implementation?
/// </summary>
/// <remarks>
/// Will not always agree with ExplicitInterfaceImplementations.Any()
/// (e.g. if binding of the type part of the name fails).
/// </remarks>
internal virtual bool IsExplicitInterfaceImplementation
{
get
{
return ExplicitInterfaceImplementations.Any();
}
}
/// <summary>
/// Returns interface events explicitly implemented by this event.
/// </summary>
/// <remarks>
/// Events imported from metadata can explicitly implement more than one event.
/// </remarks>
public abstract ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get; }
/// <summary>
/// Gets the kind of this symbol.
/// </summary>
public sealed override SymbolKind Kind
{
get
{
return SymbolKind.Event;
}
}
/// <summary>
/// Implements visitor pattern.
/// </summary>
internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
{
return visitor.VisitEvent(this, argument);
}
public override void Accept(CSharpSymbolVisitor visitor)
{
visitor.VisitEvent(this);
}
public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
{
return visitor.VisitEvent(this);
}
internal EventSymbol AsMember(NamedTypeSymbol newOwner)
{
Debug.Assert(this.IsDefinition);
Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition));
return (newOwner == this.ContainingSymbol) ? this : new SubstitutedEventSymbol(newOwner as SubstitutedNamedTypeSymbol, this);
}
internal abstract bool MustCallMethodsDirectly { get; }
#region Use-Site Diagnostics
internal override DiagnosticInfo GetUseSiteDiagnostic()
{
if (this.IsDefinition)
{
return base.GetUseSiteDiagnostic();
}
return this.OriginalDefinition.GetUseSiteDiagnostic();
}
internal bool CalculateUseSiteDiagnostic(ref DiagnosticInfo result)
{
Debug.Assert(this.IsDefinition);
// Check event type.
if (DeriveUseSiteDiagnosticFromType(ref result, this.Type))
{
return true;
}
if (this.ContainingModule.HasUnifiedReferences)
{
// If the member is in an assembly with unified references,
// we check if its definition depends on a type from a unified reference.
HashSet<TypeSymbol> unificationCheckedTypes = null;
if (this.Type.GetUnificationUseSiteDiagnosticRecursive(ref result, this, ref unificationCheckedTypes))
{
return true;
}
}
return false;
}
protected override int HighestPriorityUseSiteError
{
get
{
return (int)ErrorCode.ERR_BindToBogus;
}
}
public sealed override bool HasUnsupportedMetadata
{
get
{
DiagnosticInfo info = GetUseSiteDiagnostic();
return (object)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus;
}
}
#endregion
#region IEventSymbol Members
ITypeSymbol IEventSymbol.Type
{
get
{
return this.Type;
}
}
IMethodSymbol IEventSymbol.AddMethod
{
get
{
return this.AddMethod;
}
}
IMethodSymbol IEventSymbol.RemoveMethod
{
get
{
return this.RemoveMethod;
}
}
IMethodSymbol IEventSymbol.RaiseMethod
{
get
{
// C# doesn't have raise methods for events.
return null;
}
}
IEventSymbol IEventSymbol.OriginalDefinition
{
get
{
return this.OriginalDefinition;
}
}
IEventSymbol IEventSymbol.OverriddenEvent
{
get
{
return this.OverriddenEvent;
}
}
ImmutableArray<IEventSymbol> IEventSymbol.ExplicitInterfaceImplementations
{
get
{
return this.ExplicitInterfaceImplementations.Cast<EventSymbol, IEventSymbol>();
}
}
#endregion
#region ISymbol Members
public override void Accept(SymbolVisitor visitor)
{
visitor.VisitEvent(this);
}
public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
{
return visitor.VisitEvent(this);
}
#endregion
#region Equality
public sealed override bool Equals(object obj)
{
EventSymbol other = obj as EventSymbol;
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
// This checks if the events have the same definition and the type parameters on the containing types have been
// substituted in the same way.
return this.ContainingType == other.ContainingType && ReferenceEquals(this.OriginalDefinition, other.OriginalDefinition);
}
public override int GetHashCode()
{
int hash = 1;
hash = Hash.Combine(this.ContainingType, hash);
hash = Hash.Combine(this.Name, hash);
return hash;
}
#endregion Equality
}
}
| VPashkov/roslyn | src/Compilers/CSharp/Portable/Symbols/EventSymbol.cs | C# | apache-2.0 | 12,671 |
/* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_KERNELS_TENSOR_MAP_H_
#define TENSORFLOW_CORE_KERNELS_TENSOR_MAP_H_
#include <utility>
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_key.h"
#include "tensorflow/core/framework/variant.h"
#include "tensorflow/core/framework/variant_tensor_data.h"
#include "tensorflow/core/lib/core/refcount.h"
namespace tensorflow {
// Variant compatible type for a map of tensors. This is mutable but instances
// should never be mutated after stored in a variant tensor.
//
// **NOTE**: TensorMap stores a refcounted container of tf::Tensor objects,
// which are accessible via TensorMap::tensors(). Because it is refcounted,
// straight copies of the form:
//
// TensorMap b = a;
// b.tensors().insert(k,v); // WARNING: This modifies a.tensors().
//
// Do not create a true copy of the underlying container - but instead increment
// a reference count. Modifying b.tensors() modifies a.tensors(). In this way,
// TensorMap should be considered similar to the tf::Tensor object.
//
// In order to get a copy of the underlying map, use the Copy method:
//
// TensorMap b = a.Copy();
// b.tensors().insert(k, v); // This does not modify a.tensors().
//
// Note that this is not a deep copy: the memory locations of the underlying
// tensors will still point to the same locations of the corresponding tensors
// in the original. To truly perform a deep copy, Device and Type-specific
// code needs to be applied to the underlying tensors as usual.
//
// The most important implication of RefCounted TensorMaps is that OpKernels
// wishing to reuse TensorMap inputs as outputs via context->forward_input()
// need to perform an additional check on the refcount of the TensorList,
// to ensure aliasing can be performed safely. For example:
//
// bool can_alias = false;
// auto fw = c->forward_input(..., DT_VARIANT, {}, ...);
// if (fw && fw->dtype() == DT_VARIANT && fw->NumElements() == 1) {
// auto* tl = fw->scalar<Variant>()().get<TensorMap>();
// if (tl && tl->RefCountIsOne()) {
// can_alias = true;
// }
// }
//
class TensorMap {
public:
TensorMap() : tensors_(new Tensors) {}
~TensorMap();
TensorMap(const TensorMap& other) : tensors_(other.tensors_) {
tensors_->Ref();
}
TensorMap(TensorMap&& rhs) : tensors_(rhs.tensors_) {
rhs.tensors_ = nullptr;
}
TensorMap& operator=(const TensorMap& rhs) {
if (this == &rhs) return *this;
tensors_->Unref();
tensors_ = rhs.tensors_;
tensors_->Ref();
return *this;
}
TensorMap& operator=(TensorMap&& rhs) {
if (this == &rhs) return *this;
std::swap(tensors_, rhs.tensors_);
return *this;
}
static const char kTypeName[];
string TypeName() const { return kTypeName; }
void Encode(VariantTensorData* data) const;
bool Decode(const VariantTensorData& data);
// TODO(apassos) fill this out
string DebugString() const { return "TensorMap"; }
// Access to the underlying tensor container.
absl::flat_hash_map<TensorKey, Tensor>& tensors() {
return tensors_->values_;
}
const absl::flat_hash_map<TensorKey, Tensor>& tensors() const {
return tensors_->values_;
}
// Get a new TensorMap containing a copy of the underlying tensor container.
TensorMap Copy() const {
TensorMap out;
// This performs a copy of the absl::hashmap.
out.tensors_->values_ = tensors_->values_;
return out;
}
// Insert key and value if the key does not already exist.
// Returns true if the insertion happens.
bool insert(const TensorKey& key, const Tensor& value) {
auto r = tensors_->values_.try_emplace(key, value);
return r.second;
}
// Lookup given key. Returns iterator to found key or end.
absl::flat_hash_map<TensorKey, Tensor>::iterator find(TensorKey key) {
return tensors_->values_.find(key);
}
Tensor& lookup(TensorKey key) { return tensors_->values_.find(key)->second; }
Tensor& operator[](TensorKey& k) { return tensors_->values_[k]; }
bool replace(const TensorKey& k, const Tensor& v) {
tensors_->values_[k] = v;
return true;
}
// Removes element with given key. Return size of removed element.
size_t erase(TensorKey key) { return tensors_->values_.erase(key); }
// Size returns the number of elements in the map
size_t size() const { return tensors_->values_.size(); }
std::vector<Tensor> keys() const {
std::vector<Tensor> keys;
keys.reserve(tensors_->values_.size());
absl::flat_hash_map<TensorKey, Tensor>::iterator it =
tensors_->values_.begin();
while (it != tensors_->values_.end()) {
keys.push_back(it->first);
it++;
}
return keys;
}
// Is this TensorMap the only one with a reference to the underlying
// container?
bool RefCountIsOne() const { return tensors_->RefCountIsOne(); }
private:
class Tensors : public core::RefCounted {
public:
absl::flat_hash_map<TensorKey, Tensor> values_;
};
Tensors* tensors_;
};
#if defined(PLATFORM_GOOGLE)
// TODO(ebrevdo): Identify why Variant inline size is smaller on mobile devices.
// For 32-bit devices, it's acceptable not to inline.
static_assert(Variant::CanInlineType<TensorMap>() || sizeof(void*) < 8,
"Must be able to inline TensorMap into a Variant");
#endif
} // namespace tensorflow
#endif // TENSORFLOW_CORE_KERNELS_TENSOR_MAP_H_
| frreiss/tensorflow-fred | tensorflow/core/kernels/tensor_map.h | C | apache-2.0 | 6,118 |
curl -sH 'Accept-encoding: gzip' http://www.piste.io/info/all.json | gunzip - > resorts.json
| cylgom/zeroclickinfo-spice | share/spice/ski_resorts/get_resorts.sh | Shell | apache-2.0 | 93 |
/*
* Copyright (c) 1983, 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)ftp.h 8.1 (Berkeley) 6/2/93
*
* $FreeBSD$
*/
#ifndef _ARPA_FTP_H_
#define _ARPA_FTP_H_
/* Definitions for FTP; see RFC-765. */
/*
* Reply codes.
*/
#define PRELIM 1 /* positive preliminary */
#define COMPLETE 2 /* positive completion */
#define CONTINUE 3 /* positive intermediate */
#define TRANSIENT 4 /* transient negative completion */
#define ERROR 5 /* permanent negative completion */
/*
* Type codes
*/
#define TYPE_A 1 /* ASCII */
#define TYPE_E 2 /* EBCDIC */
#define TYPE_I 3 /* image */
#define TYPE_L 4 /* local byte size */
#ifdef FTP_NAMES
char *typenames[] = {"0", "ASCII", "EBCDIC", "Image", "Local" };
#endif
/*
* Form codes
*/
#define FORM_N 1 /* non-print */
#define FORM_T 2 /* telnet format effectors */
#define FORM_C 3 /* carriage control (ASA) */
#ifdef FTP_NAMES
char *formnames[] = {"0", "Nonprint", "Telnet", "Carriage-control" };
#endif
/*
* Structure codes
*/
#define STRU_F 1 /* file (no record structure) */
#define STRU_R 2 /* record structure */
#define STRU_P 3 /* page structure */
#ifdef FTP_NAMES
char *strunames[] = {"0", "File", "Record", "Page" };
#endif
/*
* Mode types
*/
#define MODE_S 1 /* stream */
#define MODE_B 2 /* block */
#define MODE_C 3 /* compressed */
#ifdef FTP_NAMES
char *modenames[] = {"0", "Stream", "Block", "Compressed" };
#endif
/*
* Record Tokens
*/
#define REC_ESC '\377' /* Record-mode Escape */
#define REC_EOR '\001' /* Record-mode End-of-Record */
#define REC_EOF '\002' /* Record-mode End-of-File */
/*
* Block Header
*/
#define BLK_EOR 0x80 /* Block is End-of-Record */
#define BLK_EOF 0x40 /* Block is End-of-File */
#define BLK_ERRORS 0x20 /* Block is suspected of containing errors */
#define BLK_RESTART 0x10 /* Block is Restart Marker */
#define BLK_BYTECOUNT 2 /* Bytes in this block */
#endif /* !_FTP_H_ */
| webos21/xbionic | platform_bionic-android-vts-12.0_r2/libc/include/arpa/ftp.h | C | apache-2.0 | 3,446 |
"use strict";
var isImplemented = require("../../../../array/#/entries/is-implemented");
module.exports = function (a) { a(isImplemented(), true); };
| GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/es5-ext/test/array/#/entries/implement.js | JavaScript | apache-2.0 | 152 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include "base/logging.h"
#include "media/formats/mp4/box_definitions.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
media::mp4::AVCDecoderConfigurationRecord().Parse(data, size);
return 0;
}
// For disabling noisy logging.
struct Environment {
Environment() { logging::SetMinLogLevel(logging::LOG_FATAL); }
};
Environment* env = new Environment();
| youtube/cobalt | third_party/chromium/media/formats/mp4/mp4_avcc_parser_fuzzer.cc | C++ | bsd-3-clause | 595 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBKIT_PLUGINS_PPAPI_PPB_BROKER_IMPL_H_
#define WEBKIT_PLUGINS_PPAPI_PPB_BROKER_IMPL_H_
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/memory/weak_ptr.h"
#include "ppapi/c/pp_completion_callback.h"
#include "ppapi/c/trusted/ppb_broker_trusted.h"
#include "ppapi/shared_impl/resource.h"
#include "ppapi/shared_impl/tracked_callback.h"
#include "ppapi/thunk/ppb_broker_api.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/webkit_plugins_export.h"
namespace webkit {
namespace ppapi {
class WEBKIT_PLUGINS_EXPORT PPB_Broker_Impl
: public ::ppapi::Resource,
NON_EXPORTED_BASE(public ::ppapi::thunk::PPB_Broker_API),
public base::SupportsWeakPtr<PPB_Broker_Impl> {
public:
explicit PPB_Broker_Impl(PP_Instance instance);
virtual ~PPB_Broker_Impl();
// Resource override.
virtual ::ppapi::thunk::PPB_Broker_API* AsPPB_Broker_API() OVERRIDE;
// PPB_BrokerTrusted implementation.
virtual int32_t Connect(
scoped_refptr< ::ppapi::TrackedCallback> connect_callback) OVERRIDE;
virtual int32_t GetHandle(int32_t* handle) OVERRIDE;
// Returns the URL of the document this plug-in runs in. This is necessary to
// decide whether to grant access to the PPAPI broker.
GURL GetDocumentUrl();
void BrokerConnected(int32_t handle, int32_t result);
private:
// PluginDelegate ppapi broker object.
// We don't own this pointer but are responsible for calling Disconnect on it.
PluginDelegate::Broker* broker_;
// Callback invoked from BrokerConnected.
scoped_refptr< ::ppapi::TrackedCallback> connect_callback_;
// Pipe handle for the plugin instance to use to communicate with the broker.
// Never owned by this object.
int32_t pipe_handle_;
DISALLOW_COPY_AND_ASSIGN(PPB_Broker_Impl);
};
} // namespace ppapi
} // namespace webkit
#endif // WEBKIT_PLUGINS_PPAPI_PPB_BROKER_IMPL_H_
| timopulkkinen/BubbleFish | webkit/plugins/ppapi/ppb_broker_impl.h | C | bsd-3-clause | 2,137 |
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// Draw pt corrections for debugging
// author: Eulogio Serradilla <[email protected]>
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TStyle.h>
#include <TFile.h>
#include <TH1D.h>
#include <TString.h>
#include <TCanvas.h>
#include <TF1.h>
#endif
#include "B2.h"
void DrawPair(TH1* hX, TH1* hY, Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, const TString& title="", const char* option="E", Int_t xMarker=kFullCircle, Int_t yMarker=kFullCircle, Int_t xColor=kBlue, Int_t yColor=kRed);
void DrawCorr(const TString& species="Deuteron", const TString& inputFile="corrections.root", const TString& tag="")
{
//
// Draw pt corrections for debugging
//
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
gStyle->SetPadGridX(1);
gStyle->SetPadGridY(1);
gStyle->SetOptTitle(0);
gStyle->SetOptStat(0);
Double_t xmin = 0;
Double_t xmax = 3.5;
const Int_t kNpart = 2;
TFile* finput = new TFile(inputFile.Data());
if (finput->IsZombie()) exit(1);
const TString kPrefix[] = {"", "Anti"};
// Reconstruction efficiency
TCanvas* c2 = new TCanvas(Form("%s.Efficiency",species.Data()), Form("Reconstruction Efficiency for (Anti)%ss",species.Data()));
c2->Divide(2,2);
TH1D* hEffTrigPt[kNpart];
TH1D* hEffVtxPt[kNpart];
TH1D* hEffAccPt[kNpart];
TH1D* hEffAccTrkPt[kNpart];
for(Int_t i=0; i<kNpart; ++i)
{
hEffTrigPt[i] = FindObj<TH1D>(finput, tag, kPrefix[i] + species + "_Eff_Trig_Pt");
hEffVtxPt[i] = FindObj<TH1D>(finput, tag, kPrefix[i] + species + "_Eff_Vtx_Pt");
hEffAccPt[i] = FindObj<TH1D>(finput, tag, kPrefix[i] + species + "_Eff_Acc_Pt");
hEffAccTrkPt[i] = FindObj<TH1D>(finput, tag, kPrefix[i] + species + "_Eff_AccTrk_Pt");
}
c2->cd(1);
DrawPair(hEffTrigPt[0], hEffTrigPt[1], xmin, xmax, 0, 1.1);
c2->cd(2);
DrawPair(hEffVtxPt[0], hEffVtxPt[1], xmin, xmax, 0, 1.1);
c2->cd(3);
DrawPair(hEffAccPt[0], hEffAccPt[1], xmin, xmax, 0, 1.1);
c2->cd(4);
DrawPair(hEffAccTrkPt[0], hEffAccTrkPt[1], xmin, xmax, 0, 1.1);
// Secondaries
TCanvas* c3 = new TCanvas(Form("%s.Secondaries",species.Data()), Form("Fraction of secondaries for (Anti)%ss",species.Data()));
c3->Divide(2,2);
for(Int_t i=0; i<kNpart; ++i)
{
TH1D* hFracFdwnPt = FindObj<TH1D>(finput, tag, kPrefix[i] + species + "_Frac_Fdwn_Pt");
TH1D* hFracMatPt = FindObj<TH1D>(finput, tag, kPrefix[i] + species + "_Frac_Mat_Pt");
TF1* fncFracFdwnPt = FindObj<TF1>(finput, tag, kPrefix[i] + species + "_Frac_Fdwn_Fit_Pt");
TF1* fncFracMatPt = FindObj<TF1>(finput, tag, kPrefix[i] + species + "_Frac_Mat_Fit_Pt");
c3->cd(2*i+1);
hFracFdwnPt->SetAxisRange(xmin, xmax, "X");
hFracFdwnPt->SetAxisRange(0., 0.6, "Y");
hFracFdwnPt->GetYaxis()->SetTitleOffset(1.4);
hFracFdwnPt->SetMarkerColor(kBlue);
hFracFdwnPt->SetLineColor(kBlue);
hFracFdwnPt->SetMarkerStyle(kFullCircle);
hFracFdwnPt->DrawCopy("E");
fncFracFdwnPt->SetLineColor(kRed);
fncFracFdwnPt->SetLineWidth(1);
fncFracFdwnPt->Draw("same");
c3->cd(2*i+2);
hFracMatPt->SetAxisRange(xmin, xmax, "X");
hFracMatPt->SetAxisRange(0.,0.6, "Y");
hFracMatPt->GetYaxis()->SetTitleOffset(1.4);
hFracMatPt->SetMarkerColor(kBlue);
hFracMatPt->SetLineColor(kBlue);
hFracMatPt->SetMarkerStyle(kFullCircle);
hFracMatPt->DrawCopy("E");
fncFracMatPt->SetLineColor(kRed);
fncFracMatPt->SetLineWidth(1);
fncFracMatPt->Draw("same");
}
}
void DrawPair(TH1* hX, TH1* hY, Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, const TString& title, const char* option, Int_t xMarker, Int_t yMarker, Int_t xColor, Int_t yColor)
{
//
// Draw a pair of histograms in the current pad
//
hX->SetTitle(title.Data());
hX->SetAxisRange(xmin, xmax, "X");
hX->SetAxisRange(ymin, ymax, "Y");
hX->SetMarkerColor(xColor);
hX->SetLineColor(xColor);
hX->SetMarkerStyle(xMarker);
hY->SetMarkerColor(yColor);
hY->SetLineColor(yColor);
hY->SetMarkerStyle(yMarker);
hX->DrawCopy(option);
hY->DrawCopy(Form("same%s",option));
}
| dlodato/AliPhysics | PWGLF/NUCLEX/Nuclei/Nucleipp/macros/DrawCorr.C | C++ | bsd-3-clause | 5,049 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/test/weburl_loader_mock_factory.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "content/test/weburl_loader_mock.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLError.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebCache.h"
using blink::WebCache;
using blink::WebData;
using blink::WebString;
using blink::WebURL;
using blink::WebURLError;
using blink::WebURLLoader;
using blink::WebURLRequest;
using blink::WebURLResponse;
WebURLLoaderMockFactory::WebURLLoaderMockFactory() {}
WebURLLoaderMockFactory::~WebURLLoaderMockFactory() {}
void WebURLLoaderMockFactory::RegisterURL(const WebURL& url,
const WebURLResponse& response,
const WebString& file_path) {
ResponseInfo response_info;
response_info.response = response;
if (!file_path.isNull() && !file_path.isEmpty()) {
#if defined(OS_POSIX)
// TODO(jcivelli): On Linux, UTF8 might not be correct.
response_info.file_path =
base::FilePath(static_cast<std::string>(file_path.utf8()));
#elif defined(OS_WIN)
base::string16 file_path_16 = file_path;
response_info.file_path = base::FilePath(std::wstring(
file_path_16.data(), file_path_16.length()));
#endif
DCHECK(base::PathExists(response_info.file_path))
<< response_info.file_path.MaybeAsASCII() << " does not exist.";
}
DCHECK(url_to_reponse_info_.find(url) == url_to_reponse_info_.end());
url_to_reponse_info_[url] = response_info;
}
void WebURLLoaderMockFactory::RegisterErrorURL(const WebURL& url,
const WebURLResponse& response,
const WebURLError& error) {
DCHECK(url_to_reponse_info_.find(url) == url_to_reponse_info_.end());
RegisterURL(url, response, WebString());
url_to_error_info_[url] = error;
}
void WebURLLoaderMockFactory::UnregisterURL(const blink::WebURL& url) {
URLToResponseMap::iterator iter = url_to_reponse_info_.find(url);
DCHECK(iter != url_to_reponse_info_.end());
url_to_reponse_info_.erase(iter);
URLToErrorMap::iterator error_iter = url_to_error_info_.find(url);
if (error_iter != url_to_error_info_.end())
url_to_error_info_.erase(error_iter);
}
void WebURLLoaderMockFactory::UnregisterAllURLs() {
url_to_reponse_info_.clear();
url_to_error_info_.clear();
WebCache::clear();
}
void WebURLLoaderMockFactory::ServeAsynchronousRequests() {
last_handled_asynchronous_request_.reset();
// Serving a request might trigger more requests, so we cannot iterate on
// pending_loaders_ as it might get modified.
while (!pending_loaders_.empty()) {
LoaderToRequestMap::iterator iter = pending_loaders_.begin();
WebURLLoaderMock* loader = iter->first;
const WebURLRequest& request = iter->second;
WebURLResponse response;
WebURLError error;
WebData data;
last_handled_asynchronous_request_ = request;
LoadRequest(request, &response, &error, &data);
// Follow any redirects while the loader is still active.
while (response.httpStatusCode() >= 300 &&
response.httpStatusCode() < 400) {
WebURLRequest newRequest = loader->ServeRedirect(response);
if (!IsPending(loader) || loader->isDeferred())
break;
last_handled_asynchronous_request_ = newRequest;
LoadRequest(newRequest, &response, &error, &data);
}
// Serve the request if the loader is still active.
if (IsPending(loader) && !loader->isDeferred())
loader->ServeAsynchronousRequest(response, data, error);
// The loader might have already been removed.
pending_loaders_.erase(loader);
}
base::RunLoop().RunUntilIdle();
}
blink::WebURLRequest
WebURLLoaderMockFactory::GetLastHandledAsynchronousRequest() {
return last_handled_asynchronous_request_;
}
bool WebURLLoaderMockFactory::IsMockedURL(const blink::WebURL& url) {
return url_to_reponse_info_.find(url) != url_to_reponse_info_.end();
}
void WebURLLoaderMockFactory::CancelLoad(WebURLLoaderMock* loader) {
LoaderToRequestMap::iterator iter = pending_loaders_.find(loader);
DCHECK(iter != pending_loaders_.end());
pending_loaders_.erase(iter);
}
WebURLLoader* WebURLLoaderMockFactory::CreateURLLoader(
WebURLLoader* default_loader) {
DCHECK(default_loader);
return new WebURLLoaderMock(this, default_loader);
}
void WebURLLoaderMockFactory::LoadSynchronously(const WebURLRequest& request,
WebURLResponse* response,
WebURLError* error,
WebData* data) {
LoadRequest(request, response, error, data);
}
void WebURLLoaderMockFactory::LoadAsynchronouly(const WebURLRequest& request,
WebURLLoaderMock* loader) {
LoaderToRequestMap::iterator iter = pending_loaders_.find(loader);
DCHECK(iter == pending_loaders_.end());
pending_loaders_[loader] = request;
}
void WebURLLoaderMockFactory::LoadRequest(const WebURLRequest& request,
WebURLResponse* response,
WebURLError* error,
WebData* data) {
URLToErrorMap::const_iterator error_iter =
url_to_error_info_.find(request.url());
if (error_iter != url_to_error_info_.end())
*error = error_iter->second;
URLToResponseMap::const_iterator iter =
url_to_reponse_info_.find(request.url());
if (iter == url_to_reponse_info_.end()) {
// Non mocked URLs should not have been passed to the default URLLoader.
NOTREACHED();
return;
}
if (!error->reason && !ReadFile(iter->second.file_path, data)) {
NOTREACHED();
return;
}
*response = iter->second.response;
}
bool WebURLLoaderMockFactory::IsPending(WebURLLoaderMock* loader) {
LoaderToRequestMap::iterator iter = pending_loaders_.find(loader);
return iter != pending_loaders_.end();
}
// static
bool WebURLLoaderMockFactory::ReadFile(const base::FilePath& file_path,
WebData* data) {
int64 file_size = 0;
if (!base::GetFileSize(file_path, &file_size))
return false;
int size = static_cast<int>(file_size);
scoped_ptr<char[]> buffer(new char[size]);
data->reset();
int read_count = base::ReadFile(file_path, buffer.get(), size);
if (read_count == -1)
return false;
DCHECK(read_count == size);
data->assign(buffer.get(), size);
return true;
}
| 7kbird/chrome | content/test/weburl_loader_mock_factory.cc | C++ | bsd-3-clause | 6,933 |
/*
* Fushicai USBTV007 Audio-Video Grabber Driver
*
* Product web site:
* http://www.fushicai.com/products_detail/&productId=d05449ee-b690-42f9-a661-aa7353894bed.html
*
* Following LWN articles were very useful in construction of this driver:
* Video4Linux2 API series: http://lwn.net/Articles/203924/
* videobuf2 API explanation: http://lwn.net/Articles/447435/
* Thanks go to Jonathan Corbet for providing this quality documentation.
* He is awesome.
*
* Copyright (c) 2013 Lubomir Rintel
* All rights reserved.
* No physical hardware was harmed running Windows during the
* reverse-engineering activity
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL").
*/
#include <media/v4l2-ioctl.h>
#include <media/videobuf2-core.h>
#include "usbtv.h"
static struct usbtv_norm_params norm_params[] = {
{
.norm = V4L2_STD_525_60,
.cap_width = 720,
.cap_height = 480,
},
{
.norm = V4L2_STD_PAL,
.cap_width = 720,
.cap_height = 576,
}
};
static int usbtv_configure_for_norm(struct usbtv *usbtv, v4l2_std_id norm)
{
int i, ret = 0;
struct usbtv_norm_params *params = NULL;
for (i = 0; i < ARRAY_SIZE(norm_params); i++) {
if (norm_params[i].norm & norm) {
params = &norm_params[i];
break;
}
}
if (params) {
usbtv->width = params->cap_width;
usbtv->height = params->cap_height;
usbtv->n_chunks = usbtv->width * usbtv->height
/ 4 / USBTV_CHUNK;
usbtv->norm = params->norm;
} else
ret = -EINVAL;
return ret;
}
static int usbtv_select_input(struct usbtv *usbtv, int input)
{
int ret;
static const u16 composite[][2] = {
{ USBTV_BASE + 0x0105, 0x0060 },
{ USBTV_BASE + 0x011f, 0x00f2 },
{ USBTV_BASE + 0x0127, 0x0060 },
{ USBTV_BASE + 0x00ae, 0x0010 },
{ USBTV_BASE + 0x0239, 0x0060 },
};
static const u16 svideo[][2] = {
{ USBTV_BASE + 0x0105, 0x0010 },
{ USBTV_BASE + 0x011f, 0x00ff },
{ USBTV_BASE + 0x0127, 0x0060 },
{ USBTV_BASE + 0x00ae, 0x0030 },
{ USBTV_BASE + 0x0239, 0x0060 },
};
switch (input) {
case USBTV_COMPOSITE_INPUT:
ret = usbtv_set_regs(usbtv, composite, ARRAY_SIZE(composite));
break;
case USBTV_SVIDEO_INPUT:
ret = usbtv_set_regs(usbtv, svideo, ARRAY_SIZE(svideo));
break;
default:
ret = -EINVAL;
}
if (!ret)
usbtv->input = input;
return ret;
}
static int usbtv_select_norm(struct usbtv *usbtv, v4l2_std_id norm)
{
int ret;
static const u16 pal[][2] = {
{ USBTV_BASE + 0x001a, 0x0068 },
{ USBTV_BASE + 0x010e, 0x0072 },
{ USBTV_BASE + 0x010f, 0x00a2 },
{ USBTV_BASE + 0x0112, 0x00b0 },
{ USBTV_BASE + 0x0117, 0x0001 },
{ USBTV_BASE + 0x0118, 0x002c },
{ USBTV_BASE + 0x012d, 0x0010 },
{ USBTV_BASE + 0x012f, 0x0020 },
{ USBTV_BASE + 0x024f, 0x0002 },
{ USBTV_BASE + 0x0254, 0x0059 },
{ USBTV_BASE + 0x025a, 0x0016 },
{ USBTV_BASE + 0x025b, 0x0035 },
{ USBTV_BASE + 0x0263, 0x0017 },
{ USBTV_BASE + 0x0266, 0x0016 },
{ USBTV_BASE + 0x0267, 0x0036 }
};
static const u16 ntsc[][2] = {
{ USBTV_BASE + 0x001a, 0x0079 },
{ USBTV_BASE + 0x010e, 0x0068 },
{ USBTV_BASE + 0x010f, 0x009c },
{ USBTV_BASE + 0x0112, 0x00f0 },
{ USBTV_BASE + 0x0117, 0x0000 },
{ USBTV_BASE + 0x0118, 0x00fc },
{ USBTV_BASE + 0x012d, 0x0004 },
{ USBTV_BASE + 0x012f, 0x0008 },
{ USBTV_BASE + 0x024f, 0x0001 },
{ USBTV_BASE + 0x0254, 0x005f },
{ USBTV_BASE + 0x025a, 0x0012 },
{ USBTV_BASE + 0x025b, 0x0001 },
{ USBTV_BASE + 0x0263, 0x001c },
{ USBTV_BASE + 0x0266, 0x0011 },
{ USBTV_BASE + 0x0267, 0x0005 }
};
ret = usbtv_configure_for_norm(usbtv, norm);
if (!ret) {
if (norm & V4L2_STD_525_60)
ret = usbtv_set_regs(usbtv, ntsc, ARRAY_SIZE(ntsc));
else if (norm & V4L2_STD_PAL)
ret = usbtv_set_regs(usbtv, pal, ARRAY_SIZE(pal));
}
return ret;
}
static int usbtv_setup_capture(struct usbtv *usbtv)
{
int ret;
static const u16 setup[][2] = {
/* These seem to enable the device. */
{ USBTV_BASE + 0x0008, 0x0001 },
{ USBTV_BASE + 0x01d0, 0x00ff },
{ USBTV_BASE + 0x01d9, 0x0002 },
/* These seem to influence color parameters, such as
* brightness, etc. */
{ USBTV_BASE + 0x0239, 0x0040 },
{ USBTV_BASE + 0x0240, 0x0000 },
{ USBTV_BASE + 0x0241, 0x0000 },
{ USBTV_BASE + 0x0242, 0x0002 },
{ USBTV_BASE + 0x0243, 0x0080 },
{ USBTV_BASE + 0x0244, 0x0012 },
{ USBTV_BASE + 0x0245, 0x0090 },
{ USBTV_BASE + 0x0246, 0x0000 },
{ USBTV_BASE + 0x0278, 0x002d },
{ USBTV_BASE + 0x0279, 0x000a },
{ USBTV_BASE + 0x027a, 0x0032 },
{ 0xf890, 0x000c },
{ 0xf894, 0x0086 },
{ USBTV_BASE + 0x00ac, 0x00c0 },
{ USBTV_BASE + 0x00ad, 0x0000 },
{ USBTV_BASE + 0x00a2, 0x0012 },
{ USBTV_BASE + 0x00a3, 0x00e0 },
{ USBTV_BASE + 0x00a4, 0x0028 },
{ USBTV_BASE + 0x00a5, 0x0082 },
{ USBTV_BASE + 0x00a7, 0x0080 },
{ USBTV_BASE + 0x0000, 0x0014 },
{ USBTV_BASE + 0x0006, 0x0003 },
{ USBTV_BASE + 0x0090, 0x0099 },
{ USBTV_BASE + 0x0091, 0x0090 },
{ USBTV_BASE + 0x0094, 0x0068 },
{ USBTV_BASE + 0x0095, 0x0070 },
{ USBTV_BASE + 0x009c, 0x0030 },
{ USBTV_BASE + 0x009d, 0x00c0 },
{ USBTV_BASE + 0x009e, 0x00e0 },
{ USBTV_BASE + 0x0019, 0x0006 },
{ USBTV_BASE + 0x008c, 0x00ba },
{ USBTV_BASE + 0x0101, 0x00ff },
{ USBTV_BASE + 0x010c, 0x00b3 },
{ USBTV_BASE + 0x01b2, 0x0080 },
{ USBTV_BASE + 0x01b4, 0x00a0 },
{ USBTV_BASE + 0x014c, 0x00ff },
{ USBTV_BASE + 0x014d, 0x00ca },
{ USBTV_BASE + 0x0113, 0x0053 },
{ USBTV_BASE + 0x0119, 0x008a },
{ USBTV_BASE + 0x013c, 0x0003 },
{ USBTV_BASE + 0x0150, 0x009c },
{ USBTV_BASE + 0x0151, 0x0071 },
{ USBTV_BASE + 0x0152, 0x00c6 },
{ USBTV_BASE + 0x0153, 0x0084 },
{ USBTV_BASE + 0x0154, 0x00bc },
{ USBTV_BASE + 0x0155, 0x00a0 },
{ USBTV_BASE + 0x0156, 0x00a0 },
{ USBTV_BASE + 0x0157, 0x009c },
{ USBTV_BASE + 0x0158, 0x001f },
{ USBTV_BASE + 0x0159, 0x0006 },
{ USBTV_BASE + 0x015d, 0x0000 },
{ USBTV_BASE + 0x0003, 0x0004 },
{ USBTV_BASE + 0x0100, 0x00d3 },
{ USBTV_BASE + 0x0115, 0x0015 },
{ USBTV_BASE + 0x0220, 0x002e },
{ USBTV_BASE + 0x0225, 0x0008 },
{ USBTV_BASE + 0x024e, 0x0002 },
{ USBTV_BASE + 0x024e, 0x0002 },
{ USBTV_BASE + 0x024f, 0x0002 },
};
ret = usbtv_set_regs(usbtv, setup, ARRAY_SIZE(setup));
if (ret)
return ret;
ret = usbtv_select_norm(usbtv, usbtv->norm);
if (ret)
return ret;
ret = usbtv_select_input(usbtv, usbtv->input);
if (ret)
return ret;
return 0;
}
/* Copy data from chunk into a frame buffer, deinterlacing the data
* into every second line. Unfortunately, they don't align nicely into
* 720 pixel lines, as the chunk is 240 words long, which is 480 pixels.
* Therefore, we break down the chunk into two halves before copyting,
* so that we can interleave a line if needed. */
static void usbtv_chunk_to_vbuf(u32 *frame, __be32 *src, int chunk_no, int odd)
{
int half;
for (half = 0; half < 2; half++) {
int part_no = chunk_no * 2 + half;
int line = part_no / 3;
int part_index = (line * 2 + !odd) * 3 + (part_no % 3);
u32 *dst = &frame[part_index * USBTV_CHUNK/2];
memcpy(dst, src, USBTV_CHUNK/2 * sizeof(*src));
src += USBTV_CHUNK/2;
}
}
/* Called for each 256-byte image chunk.
* First word identifies the chunk, followed by 240 words of image
* data and padding. */
static void usbtv_image_chunk(struct usbtv *usbtv, __be32 *chunk)
{
int frame_id, odd, chunk_no;
u32 *frame;
struct usbtv_buf *buf;
unsigned long flags;
/* Ignore corrupted lines. */
if (!USBTV_MAGIC_OK(chunk))
return;
frame_id = USBTV_FRAME_ID(chunk);
odd = USBTV_ODD(chunk);
chunk_no = USBTV_CHUNK_NO(chunk);
if (chunk_no >= usbtv->n_chunks)
return;
/* Beginning of a frame. */
if (chunk_no == 0) {
usbtv->frame_id = frame_id;
usbtv->chunks_done = 0;
}
if (usbtv->frame_id != frame_id)
return;
spin_lock_irqsave(&usbtv->buflock, flags);
if (list_empty(&usbtv->bufs)) {
/* No free buffers. Userspace likely too slow. */
spin_unlock_irqrestore(&usbtv->buflock, flags);
return;
}
/* First available buffer. */
buf = list_first_entry(&usbtv->bufs, struct usbtv_buf, list);
frame = vb2_plane_vaddr(&buf->vb, 0);
/* Copy the chunk data. */
usbtv_chunk_to_vbuf(frame, &chunk[1], chunk_no, odd);
usbtv->chunks_done++;
/* Last chunk in a frame, signalling an end */
if (odd && chunk_no == usbtv->n_chunks-1) {
int size = vb2_plane_size(&buf->vb, 0);
enum vb2_buffer_state state = usbtv->chunks_done ==
usbtv->n_chunks ?
VB2_BUF_STATE_DONE :
VB2_BUF_STATE_ERROR;
buf->vb.v4l2_buf.field = V4L2_FIELD_INTERLACED;
buf->vb.v4l2_buf.sequence = usbtv->sequence++;
v4l2_get_timestamp(&buf->vb.v4l2_buf.timestamp);
vb2_set_plane_payload(&buf->vb, 0, size);
vb2_buffer_done(&buf->vb, state);
list_del(&buf->list);
}
spin_unlock_irqrestore(&usbtv->buflock, flags);
}
/* Got image data. Each packet contains a number of 256-word chunks we
* compose the image from. */
static void usbtv_iso_cb(struct urb *ip)
{
int ret;
int i;
struct usbtv *usbtv = (struct usbtv *)ip->context;
switch (ip->status) {
/* All fine. */
case 0:
break;
/* Device disconnected or capture stopped? */
case -ENODEV:
case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
return;
/* Unknown error. Retry. */
default:
dev_warn(usbtv->dev, "Bad response for ISO request.\n");
goto resubmit;
}
for (i = 0; i < ip->number_of_packets; i++) {
int size = ip->iso_frame_desc[i].actual_length;
unsigned char *data = ip->transfer_buffer +
ip->iso_frame_desc[i].offset;
int offset;
for (offset = 0; USBTV_CHUNK_SIZE * offset < size; offset++)
usbtv_image_chunk(usbtv,
(__be32 *)&data[USBTV_CHUNK_SIZE * offset]);
}
resubmit:
ret = usb_submit_urb(ip, GFP_ATOMIC);
if (ret < 0)
dev_warn(usbtv->dev, "Could not resubmit ISO URB\n");
}
static struct urb *usbtv_setup_iso_transfer(struct usbtv *usbtv)
{
struct urb *ip;
int size = usbtv->iso_size;
int i;
ip = usb_alloc_urb(USBTV_ISOC_PACKETS, GFP_KERNEL);
if (ip == NULL)
return NULL;
ip->dev = usbtv->udev;
ip->context = usbtv;
ip->pipe = usb_rcvisocpipe(usbtv->udev, USBTV_VIDEO_ENDP);
ip->interval = 1;
ip->transfer_flags = URB_ISO_ASAP;
ip->transfer_buffer = kzalloc(size * USBTV_ISOC_PACKETS,
GFP_KERNEL);
ip->complete = usbtv_iso_cb;
ip->number_of_packets = USBTV_ISOC_PACKETS;
ip->transfer_buffer_length = size * USBTV_ISOC_PACKETS;
for (i = 0; i < USBTV_ISOC_PACKETS; i++) {
ip->iso_frame_desc[i].offset = size * i;
ip->iso_frame_desc[i].length = size;
}
return ip;
}
static void usbtv_stop(struct usbtv *usbtv)
{
int i;
unsigned long flags;
/* Cancel running transfers. */
for (i = 0; i < USBTV_ISOC_TRANSFERS; i++) {
struct urb *ip = usbtv->isoc_urbs[i];
if (ip == NULL)
continue;
usb_kill_urb(ip);
kfree(ip->transfer_buffer);
usb_free_urb(ip);
usbtv->isoc_urbs[i] = NULL;
}
/* Return buffers to userspace. */
spin_lock_irqsave(&usbtv->buflock, flags);
while (!list_empty(&usbtv->bufs)) {
struct usbtv_buf *buf = list_first_entry(&usbtv->bufs,
struct usbtv_buf, list);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
list_del(&buf->list);
}
spin_unlock_irqrestore(&usbtv->buflock, flags);
}
static int usbtv_start(struct usbtv *usbtv)
{
int i;
int ret;
usbtv_audio_suspend(usbtv);
ret = usb_set_interface(usbtv->udev, 0, 0);
if (ret < 0)
return ret;
ret = usbtv_setup_capture(usbtv);
if (ret < 0)
return ret;
ret = usb_set_interface(usbtv->udev, 0, 1);
if (ret < 0)
return ret;
usbtv_audio_resume(usbtv);
for (i = 0; i < USBTV_ISOC_TRANSFERS; i++) {
struct urb *ip;
ip = usbtv_setup_iso_transfer(usbtv);
if (ip == NULL) {
ret = -ENOMEM;
goto start_fail;
}
usbtv->isoc_urbs[i] = ip;
ret = usb_submit_urb(ip, GFP_KERNEL);
if (ret < 0)
goto start_fail;
}
return 0;
start_fail:
usbtv_stop(usbtv);
return ret;
}
static int usbtv_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct usbtv *dev = video_drvdata(file);
strlcpy(cap->driver, "usbtv", sizeof(cap->driver));
strlcpy(cap->card, "usbtv", sizeof(cap->card));
usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info));
cap->device_caps = V4L2_CAP_VIDEO_CAPTURE;
cap->device_caps |= V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int usbtv_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct usbtv *dev = video_drvdata(file);
switch (i->index) {
case USBTV_COMPOSITE_INPUT:
strlcpy(i->name, "Composite", sizeof(i->name));
break;
case USBTV_SVIDEO_INPUT:
strlcpy(i->name, "S-Video", sizeof(i->name));
break;
default:
return -EINVAL;
}
i->type = V4L2_INPUT_TYPE_CAMERA;
i->std = dev->vdev.tvnorms;
return 0;
}
static int usbtv_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (f->index > 0)
return -EINVAL;
strlcpy(f->description, "16 bpp YUY2, 4:2:2, packed",
sizeof(f->description));
f->pixelformat = V4L2_PIX_FMT_YUYV;
return 0;
}
static int usbtv_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct usbtv *usbtv = video_drvdata(file);
f->fmt.pix.width = usbtv->width;
f->fmt.pix.height = usbtv->height;
f->fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
f->fmt.pix.field = V4L2_FIELD_INTERLACED;
f->fmt.pix.bytesperline = usbtv->width * 2;
f->fmt.pix.sizeimage = (f->fmt.pix.bytesperline * f->fmt.pix.height);
f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
return 0;
}
static int usbtv_g_std(struct file *file, void *priv, v4l2_std_id *norm)
{
struct usbtv *usbtv = video_drvdata(file);
*norm = usbtv->norm;
return 0;
}
static int usbtv_s_std(struct file *file, void *priv, v4l2_std_id norm)
{
int ret = -EINVAL;
struct usbtv *usbtv = video_drvdata(file);
if ((norm & V4L2_STD_525_60) || (norm & V4L2_STD_PAL))
ret = usbtv_select_norm(usbtv, norm);
return ret;
}
static int usbtv_g_input(struct file *file, void *priv, unsigned int *i)
{
struct usbtv *usbtv = video_drvdata(file);
*i = usbtv->input;
return 0;
}
static int usbtv_s_input(struct file *file, void *priv, unsigned int i)
{
struct usbtv *usbtv = video_drvdata(file);
return usbtv_select_input(usbtv, i);
}
static struct v4l2_ioctl_ops usbtv_ioctl_ops = {
.vidioc_querycap = usbtv_querycap,
.vidioc_enum_input = usbtv_enum_input,
.vidioc_enum_fmt_vid_cap = usbtv_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = usbtv_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = usbtv_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = usbtv_fmt_vid_cap,
.vidioc_g_std = usbtv_g_std,
.vidioc_s_std = usbtv_s_std,
.vidioc_g_input = usbtv_g_input,
.vidioc_s_input = usbtv_s_input,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_prepare_buf = vb2_ioctl_prepare_buf,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_create_bufs = vb2_ioctl_create_bufs,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
};
static struct v4l2_file_operations usbtv_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
.mmap = vb2_fop_mmap,
.open = v4l2_fh_open,
.release = vb2_fop_release,
.read = vb2_fop_read,
.poll = vb2_fop_poll,
};
static int usbtv_queue_setup(struct vb2_queue *vq,
const struct v4l2_format *v4l_fmt, unsigned int *nbuffers,
unsigned int *nplanes, unsigned int sizes[], void *alloc_ctxs[])
{
struct usbtv *usbtv = vb2_get_drv_priv(vq);
if (*nbuffers < 2)
*nbuffers = 2;
*nplanes = 1;
sizes[0] = USBTV_CHUNK * usbtv->n_chunks * 2 * sizeof(u32);
return 0;
}
static void usbtv_buf_queue(struct vb2_buffer *vb)
{
struct usbtv *usbtv = vb2_get_drv_priv(vb->vb2_queue);
struct usbtv_buf *buf = container_of(vb, struct usbtv_buf, vb);
unsigned long flags;
if (usbtv->udev == NULL) {
vb2_buffer_done(vb, VB2_BUF_STATE_ERROR);
return;
}
spin_lock_irqsave(&usbtv->buflock, flags);
list_add_tail(&buf->list, &usbtv->bufs);
spin_unlock_irqrestore(&usbtv->buflock, flags);
}
static int usbtv_start_streaming(struct vb2_queue *vq, unsigned int count)
{
struct usbtv *usbtv = vb2_get_drv_priv(vq);
if (usbtv->udev == NULL)
return -ENODEV;
return usbtv_start(usbtv);
}
static void usbtv_stop_streaming(struct vb2_queue *vq)
{
struct usbtv *usbtv = vb2_get_drv_priv(vq);
if (usbtv->udev)
usbtv_stop(usbtv);
}
static struct vb2_ops usbtv_vb2_ops = {
.queue_setup = usbtv_queue_setup,
.buf_queue = usbtv_buf_queue,
.start_streaming = usbtv_start_streaming,
.stop_streaming = usbtv_stop_streaming,
};
static void usbtv_release(struct v4l2_device *v4l2_dev)
{
struct usbtv *usbtv = container_of(v4l2_dev, struct usbtv, v4l2_dev);
v4l2_device_unregister(&usbtv->v4l2_dev);
vb2_queue_release(&usbtv->vb2q);
kfree(usbtv);
}
int usbtv_video_init(struct usbtv *usbtv)
{
int ret;
(void)usbtv_configure_for_norm(usbtv, V4L2_STD_525_60);
spin_lock_init(&usbtv->buflock);
mutex_init(&usbtv->v4l2_lock);
mutex_init(&usbtv->vb2q_lock);
INIT_LIST_HEAD(&usbtv->bufs);
/* videobuf2 structure */
usbtv->vb2q.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
usbtv->vb2q.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
usbtv->vb2q.drv_priv = usbtv;
usbtv->vb2q.buf_struct_size = sizeof(struct usbtv_buf);
usbtv->vb2q.ops = &usbtv_vb2_ops;
usbtv->vb2q.mem_ops = &vb2_vmalloc_memops;
usbtv->vb2q.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
usbtv->vb2q.lock = &usbtv->vb2q_lock;
ret = vb2_queue_init(&usbtv->vb2q);
if (ret < 0) {
dev_warn(usbtv->dev, "Could not initialize videobuf2 queue\n");
return ret;
}
/* v4l2 structure */
usbtv->v4l2_dev.release = usbtv_release;
ret = v4l2_device_register(usbtv->dev, &usbtv->v4l2_dev);
if (ret < 0) {
dev_warn(usbtv->dev, "Could not register v4l2 device\n");
goto v4l2_fail;
}
/* Video structure */
strlcpy(usbtv->vdev.name, "usbtv", sizeof(usbtv->vdev.name));
usbtv->vdev.v4l2_dev = &usbtv->v4l2_dev;
usbtv->vdev.release = video_device_release_empty;
usbtv->vdev.fops = &usbtv_fops;
usbtv->vdev.ioctl_ops = &usbtv_ioctl_ops;
usbtv->vdev.tvnorms = USBTV_TV_STD;
usbtv->vdev.queue = &usbtv->vb2q;
usbtv->vdev.lock = &usbtv->v4l2_lock;
video_set_drvdata(&usbtv->vdev, usbtv);
ret = video_register_device(&usbtv->vdev, VFL_TYPE_GRABBER, -1);
if (ret < 0) {
dev_warn(usbtv->dev, "Could not register video device\n");
goto vdev_fail;
}
return 0;
vdev_fail:
v4l2_device_unregister(&usbtv->v4l2_dev);
v4l2_fail:
vb2_queue_release(&usbtv->vb2q);
return ret;
}
void usbtv_video_free(struct usbtv *usbtv)
{
mutex_lock(&usbtv->vb2q_lock);
mutex_lock(&usbtv->v4l2_lock);
usbtv_stop(usbtv);
video_unregister_device(&usbtv->vdev);
v4l2_device_disconnect(&usbtv->v4l2_dev);
mutex_unlock(&usbtv->v4l2_lock);
mutex_unlock(&usbtv->vb2q_lock);
v4l2_device_put(&usbtv->v4l2_dev);
}
| mericon/Xp_Kernel_LGH850 | virt/drivers/media/usb/usbtv/usbtv-video.c | C | gpl-2.0 | 19,231 |
/* ----------------------------------------------------------------------
* Copyright (C) 2010-2013 ARM Limited. All rights reserved.
*
* $Date: 17. January 2013
* $Revision: V1.4.1
*
* Project: CMSIS DSP Library
* Title: arm_scale_q15.c
*
* Description: Multiplies a Q15 vector by a scalar.
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* 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 ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* -------------------------------------------------------------------- */
#include "arm_math.h"
/**
* @ingroup groupMath
*/
/**
* @addtogroup scale
* @{
*/
/**
* @brief Multiplies a Q15 vector by a scalar.
* @param[in] *pSrc points to the input vector
* @param[in] scaleFract fractional portion of the scale value
* @param[in] shift number of bits to shift the result by
* @param[out] *pDst points to the output vector
* @param[in] blockSize number of samples in the vector
* @return none.
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The input data <code>*pSrc</code> and <code>scaleFract</code> are in 1.15 format.
* These are multiplied to yield a 2.30 intermediate result and this is shifted with saturation to 1.15 format.
*/
void arm_scale_q15(
q15_t * pSrc,
q15_t scaleFract,
int8_t shift,
q15_t * pDst,
uint32_t blockSize)
{
int8_t kShift = 15 - shift; /* shift to apply after scaling */
uint32_t blkCnt; /* loop counter */
#ifndef ARM_MATH_CM0_FAMILY
/* Run the below code for Cortex-M4 and Cortex-M3 */
q15_t in1, in2, in3, in4;
q31_t inA1, inA2; /* Temporary variables */
q31_t out1, out2, out3, out4;
/*loop Unrolling */
blkCnt = blockSize >> 2u;
/* First part of the processing with loop unrolling. Compute 4 outputs at a time.
** a second loop below computes the remaining 1 to 3 samples. */
while(blkCnt > 0u)
{
/* Reading 2 inputs from memory */
inA1 = *__SIMD32(pSrc)++;
inA2 = *__SIMD32(pSrc)++;
/* C = A * scale */
/* Scale the inputs and then store the 2 results in the destination buffer
* in single cycle by packing the outputs */
out1 = (q31_t) ((q15_t) (inA1 >> 16) * scaleFract);
out2 = (q31_t) ((q15_t) inA1 * scaleFract);
out3 = (q31_t) ((q15_t) (inA2 >> 16) * scaleFract);
out4 = (q31_t) ((q15_t) inA2 * scaleFract);
/* apply shifting */
out1 = out1 >> kShift;
out2 = out2 >> kShift;
out3 = out3 >> kShift;
out4 = out4 >> kShift;
/* saturate the output */
in1 = (q15_t) (__SSAT(out1, 16));
in2 = (q15_t) (__SSAT(out2, 16));
in3 = (q15_t) (__SSAT(out3, 16));
in4 = (q15_t) (__SSAT(out4, 16));
/* store the result to destination */
*__SIMD32(pDst)++ = __PKHBT(in2, in1, 16);
*__SIMD32(pDst)++ = __PKHBT(in4, in3, 16);
/* Decrement the loop counter */
blkCnt--;
}
/* If the blockSize is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = blockSize % 0x4u;
while(blkCnt > 0u)
{
/* C = A * scale */
/* Scale the input and then store the result in the destination buffer. */
*pDst++ = (q15_t) (__SSAT(((*pSrc++) * scaleFract) >> kShift, 16));
/* Decrement the loop counter */
blkCnt--;
}
#else
/* Run the below code for Cortex-M0 */
/* Initialize blkCnt with number of samples */
blkCnt = blockSize;
while(blkCnt > 0u)
{
/* C = A * scale */
/* Scale the input and then store the result in the destination buffer. */
*pDst++ = (q15_t) (__SSAT(((q31_t) * pSrc++ * scaleFract) >> kShift, 16));
/* Decrement the loop counter */
blkCnt--;
}
#endif /* #ifndef ARM_MATH_CM0_FAMILY */
}
/**
* @} end of scale group
*/
| james54068/stm32f429_learning | stm32f429_SDCard/Libraries/CMSIS/DSP_Lib/Source/BasicMathFunctions/arm_scale_q15.c | C | mit | 5,506 |
/* contrib/lo/lo--1.0--1.1.sql */
-- complain if script is sourced in psql, rather than via ALTER EXTENSION
\echo Use "ALTER EXTENSION lo UPDATE TO '1.1'" to load this file. \quit
ALTER FUNCTION lo_oid(lo) PARALLEL SAFE;
| unsupo/ogame | ogamebotserver/src/main/resources/databases/postgres_windows/App/PgSQL/share/extension/lo--1.0--1.1.sql | SQL | mit | 223 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DependencyInjection\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
class ContainerTest extends TestCase
{
public function testConstructor()
{
$sc = new Container();
$this->assertSame($sc, $sc->get('service_container'), '__construct() automatically registers itself as a service');
$sc = new Container(new ParameterBag(array('foo' => 'bar')));
$this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '__construct() takes an array of parameters as its first argument');
}
/**
* @dataProvider dataForTestCamelize
*/
public function testCamelize($id, $expected)
{
$this->assertEquals($expected, Container::camelize($id), sprintf('Container::camelize("%s")', $id));
}
public function dataForTestCamelize()
{
return array(
array('foo_bar', 'FooBar'),
array('foo.bar', 'Foo_Bar'),
array('foo.bar_baz', 'Foo_BarBaz'),
array('foo._bar', 'Foo_Bar'),
array('foo_.bar', 'Foo_Bar'),
array('_foo', 'Foo'),
array('.foo', '_Foo'),
array('foo_', 'Foo'),
array('foo.', 'Foo_'),
array('foo\bar', 'Foo_Bar'),
);
}
/**
* @dataProvider dataForTestUnderscore
*/
public function testUnderscore($id, $expected)
{
$this->assertEquals($expected, Container::underscore($id), sprintf('Container::underscore("%s")', $id));
}
public function dataForTestUnderscore()
{
return array(
array('FooBar', 'foo_bar'),
array('Foo_Bar', 'foo.bar'),
array('Foo_BarBaz', 'foo.bar_baz'),
array('FooBar_BazQux', 'foo_bar.baz_qux'),
array('_Foo', '.foo'),
array('Foo_', 'foo.'),
);
}
public function testCompile()
{
$sc = new Container(new ParameterBag(array('foo' => 'bar')));
$this->assertFalse($sc->getParameterBag()->isResolved(), '->compile() resolves the parameter bag');
$sc->compile();
$this->assertTrue($sc->getParameterBag()->isResolved(), '->compile() resolves the parameter bag');
$this->assertInstanceOf('Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag', $sc->getParameterBag(), '->compile() changes the parameter bag to a FrozenParameterBag instance');
$this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '->compile() copies the current parameters to the new parameter bag');
}
public function testIsFrozen()
{
$sc = new Container(new ParameterBag(array('foo' => 'bar')));
$this->assertFalse($sc->isFrozen(), '->isFrozen() returns false if the parameters are not frozen');
$sc->compile();
$this->assertTrue($sc->isFrozen(), '->isFrozen() returns true if the parameters are frozen');
}
public function testGetParameterBag()
{
$sc = new Container();
$this->assertEquals(array(), $sc->getParameterBag()->all(), '->getParameterBag() returns an empty array if no parameter has been defined');
}
public function testGetSetParameter()
{
$sc = new Container(new ParameterBag(array('foo' => 'bar')));
$sc->setParameter('bar', 'foo');
$this->assertEquals('foo', $sc->getParameter('bar'), '->setParameter() sets the value of a new parameter');
$sc->setParameter('foo', 'baz');
$this->assertEquals('baz', $sc->getParameter('foo'), '->setParameter() overrides previously set parameter');
$sc->setParameter('Foo', 'baz1');
$this->assertEquals('baz1', $sc->getParameter('foo'), '->setParameter() converts the key to lowercase');
$this->assertEquals('baz1', $sc->getParameter('FOO'), '->getParameter() converts the key to lowercase');
try {
$sc->getParameter('baba');
$this->fail('->getParameter() thrown an \InvalidArgumentException if the key does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\InvalidArgumentException', $e, '->getParameter() thrown an \InvalidArgumentException if the key does not exist');
$this->assertEquals('You have requested a non-existent parameter "baba".', $e->getMessage(), '->getParameter() thrown an \InvalidArgumentException if the key does not exist');
}
}
public function testGetServiceIds()
{
$sc = new Container();
$sc->set('foo', $obj = new \stdClass());
$sc->set('bar', $obj = new \stdClass());
$this->assertEquals(array('service_container', 'foo', 'bar'), $sc->getServiceIds(), '->getServiceIds() returns all defined service ids');
$sc = new ProjectServiceContainer();
$sc->set('foo', $obj = new \stdClass());
$this->assertEquals(array('scoped', 'scoped_foo', 'scoped_synchronized_foo', 'inactive', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'service_container', 'foo'), $sc->getServiceIds(), '->getServiceIds() returns defined service ids by getXXXService() methods, followed by service ids defined by set()');
}
public function testSet()
{
$sc = new Container();
$sc->set('._. \\o/', $foo = new \stdClass());
$this->assertSame($foo, $sc->get('._. \\o/'), '->set() sets a service');
}
public function testSetWithNullResetTheService()
{
$sc = new Container();
$sc->set('foo', null);
$this->assertFalse($sc->has('foo'), '->set() with null service resets the service');
}
/**
* @expectedException \InvalidArgumentException
* @group legacy
*/
public function testSetDoesNotAllowPrototypeScope()
{
$c = new Container();
$c->set('foo', new \stdClass(), Container::SCOPE_PROTOTYPE);
}
/**
* @expectedException \RuntimeException
* @group legacy
*/
public function testSetDoesNotAllowInactiveScope()
{
$c = new Container();
$c->addScope(new Scope('foo'));
$c->set('foo', new \stdClass(), 'foo');
}
/**
* @group legacy
*/
public function testSetAlsoSetsScopedService()
{
$c = new Container();
$c->addScope(new Scope('foo'));
$c->enterScope('foo');
$c->set('foo', $foo = new \stdClass(), 'foo');
$scoped = $this->getField($c, 'scopedServices');
$this->assertTrue(isset($scoped['foo']['foo']), '->set() sets a scoped service');
$this->assertSame($foo, $scoped['foo']['foo'], '->set() sets a scoped service');
}
/**
* @group legacy
*/
public function testSetAlsoCallsSynchronizeService()
{
$c = new ProjectServiceContainer();
$c->addScope(new Scope('foo'));
$c->enterScope('foo');
$c->set('scoped_synchronized_foo', $bar = new \stdClass(), 'foo');
$this->assertTrue($c->synchronized, '->set() calls synchronize*Service() if it is defined for the service');
}
public function testSetReplacesAlias()
{
$c = new ProjectServiceContainer();
$c->set('alias', $foo = new \stdClass());
$this->assertSame($foo, $c->get('alias'), '->set() replaces an existing alias');
}
public function testGet()
{
$sc = new ProjectServiceContainer();
$sc->set('foo', $foo = new \stdClass());
$this->assertSame($foo, $sc->get('foo'), '->get() returns the service for the given id');
$this->assertSame($foo, $sc->get('Foo'), '->get() returns the service for the given id, and converts id to lowercase');
$this->assertSame($sc->__bar, $sc->get('bar'), '->get() returns the service for the given id');
$this->assertSame($sc->__foo_bar, $sc->get('foo_bar'), '->get() returns the service if a get*Method() is defined');
$this->assertSame($sc->__foo_baz, $sc->get('foo.baz'), '->get() returns the service if a get*Method() is defined');
$this->assertSame($sc->__foo_baz, $sc->get('foo\\baz'), '->get() returns the service if a get*Method() is defined');
$sc->set('bar', $bar = new \stdClass());
$this->assertSame($bar, $sc->get('bar'), '->get() prefers to return a service defined with set() than one defined with a getXXXMethod()');
try {
$sc->get('');
$this->fail('->get() throws a \InvalidArgumentException exception if the service is empty');
} catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws a ServiceNotFoundException exception if the service is empty');
}
$this->assertNull($sc->get('', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service is empty');
}
public function testGetThrowServiceNotFoundException()
{
$sc = new ProjectServiceContainer();
$sc->set('foo', $foo = new \stdClass());
$sc->set('baz', $foo = new \stdClass());
try {
$sc->get('foo1');
$this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
$this->assertEquals('You have requested a non-existent service "foo1". Did you mean this: "foo"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices');
}
try {
$sc->get('bag');
$this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
$this->assertEquals('You have requested a non-existent service "bag". Did you mean one of these: "bar", "baz"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices');
}
}
public function testGetCircularReference()
{
$sc = new ProjectServiceContainer();
try {
$sc->get('circular');
$this->fail('->get() throws a ServiceCircularReferenceException if it contains circular reference');
} catch (\Exception $e) {
$this->assertInstanceOf('\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException', $e, '->get() throws a ServiceCircularReferenceException if it contains circular reference');
$this->assertStringStartsWith('Circular reference detected for service "circular"', $e->getMessage(), '->get() throws a \LogicException if it contains circular reference');
}
}
/**
* @group legacy
*/
public function testGetReturnsNullOnInactiveScope()
{
$sc = new ProjectServiceContainer();
$this->assertNull($sc->get('inactive', ContainerInterface::NULL_ON_INVALID_REFERENCE));
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage You have requested a synthetic service ("request"). The DIC does not know how to construct this service.
*/
public function testGetSyntheticServiceAlwaysThrows()
{
require_once __DIR__.'/Fixtures/php/services9.php';
$container = new \ProjectServiceContainer();
$container->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE);
}
public function testHas()
{
$sc = new ProjectServiceContainer();
$sc->set('foo', new \stdClass());
$this->assertFalse($sc->has('foo1'), '->has() returns false if the service does not exist');
$this->assertTrue($sc->has('foo'), '->has() returns true if the service exists');
$this->assertTrue($sc->has('bar'), '->has() returns true if a get*Method() is defined');
$this->assertTrue($sc->has('foo_bar'), '->has() returns true if a get*Method() is defined');
$this->assertTrue($sc->has('foo.baz'), '->has() returns true if a get*Method() is defined');
$this->assertTrue($sc->has('foo\\baz'), '->has() returns true if a get*Method() is defined');
}
public function testInitialized()
{
$sc = new ProjectServiceContainer();
$sc->set('foo', new \stdClass());
$this->assertTrue($sc->initialized('foo'), '->initialized() returns true if service is loaded');
$this->assertFalse($sc->initialized('foo1'), '->initialized() returns false if service is not loaded');
$this->assertFalse($sc->initialized('bar'), '->initialized() returns false if a service is defined, but not currently loaded');
$this->assertFalse($sc->initialized('alias'), '->initialized() returns false if an aliased service is not initialized');
$sc->set('bar', new \stdClass());
$this->assertTrue($sc->initialized('alias'), '->initialized() returns true for alias if aliased service is initialized');
}
public function testReset()
{
$c = new Container();
$c->set('bar', new \stdClass());
$c->reset();
$this->assertNull($c->get('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE));
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException
* @expectedExceptionMessage Resetting the container is not allowed when a scope is active.
* @group legacy
*/
public function testCannotResetInActiveScope()
{
$c = new Container();
$c->addScope(new Scope('foo'));
$c->set('bar', new \stdClass());
$c->enterScope('foo');
$c->reset();
}
/**
* @group legacy
*/
public function testResetAfterLeavingScope()
{
$c = new Container();
$c->addScope(new Scope('foo'));
$c->set('bar', new \stdClass());
$c->enterScope('foo');
$c->leaveScope('foo');
$c->reset();
$this->assertNull($c->get('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE));
}
/**
* @group legacy
*/
public function testEnterLeaveCurrentScope()
{
$container = new ProjectServiceContainer();
$container->addScope(new Scope('foo'));
$container->enterScope('foo');
$container->set('foo', new \stdClass(), 'foo');
$scoped1 = $container->get('scoped');
$scopedFoo1 = $container->get('scoped_foo');
$container->enterScope('foo');
$container->set('foo', new \stdClass(), 'foo');
$scoped2 = $container->get('scoped');
$scoped3 = $container->get('SCOPED');
$scopedFoo2 = $container->get('scoped_foo');
$container->set('foo', null, 'foo');
$container->leaveScope('foo');
$scoped4 = $container->get('scoped');
$scopedFoo3 = $container->get('scoped_foo');
$this->assertNotSame($scoped1, $scoped2);
$this->assertSame($scoped2, $scoped3);
$this->assertSame($scoped1, $scoped4);
$this->assertNotSame($scopedFoo1, $scopedFoo2);
$this->assertSame($scopedFoo1, $scopedFoo3);
}
/**
* @group legacy
*/
public function testEnterLeaveScopeWithChildScopes()
{
$container = new Container();
$container->addScope(new Scope('foo'));
$container->addScope(new Scope('bar', 'foo'));
$this->assertFalse($container->isScopeActive('foo'));
$container->enterScope('foo');
$container->enterScope('bar');
$this->assertTrue($container->isScopeActive('foo'));
$this->assertFalse($container->has('a'));
$a = new \stdClass();
$container->set('a', $a, 'bar');
$scoped = $this->getField($container, 'scopedServices');
$this->assertTrue(isset($scoped['bar']['a']));
$this->assertSame($a, $scoped['bar']['a']);
$this->assertTrue($container->has('a'));
$container->leaveScope('foo');
$scoped = $this->getField($container, 'scopedServices');
$this->assertFalse(isset($scoped['bar']));
$this->assertFalse($container->isScopeActive('foo'));
$this->assertFalse($container->has('a'));
}
/**
* @group legacy
*/
public function testEnterScopeRecursivelyWithInactiveChildScopes()
{
$container = new Container();
$container->addScope(new Scope('foo'));
$container->addScope(new Scope('bar', 'foo'));
$this->assertFalse($container->isScopeActive('foo'));
$container->enterScope('foo');
$this->assertTrue($container->isScopeActive('foo'));
$this->assertFalse($container->isScopeActive('bar'));
$this->assertFalse($container->has('a'));
$a = new \stdClass();
$container->set('a', $a, 'foo');
$scoped = $this->getField($container, 'scopedServices');
$this->assertTrue(isset($scoped['foo']['a']));
$this->assertSame($a, $scoped['foo']['a']);
$this->assertTrue($container->has('a'));
$container->enterScope('foo');
$scoped = $this->getField($container, 'scopedServices');
$this->assertFalse(isset($scoped['a']));
$this->assertTrue($container->isScopeActive('foo'));
$this->assertFalse($container->isScopeActive('bar'));
$this->assertFalse($container->has('a'));
$container->enterScope('bar');
$this->assertTrue($container->isScopeActive('bar'));
$container->leaveScope('foo');
$this->assertTrue($container->isScopeActive('foo'));
$this->assertFalse($container->isScopeActive('bar'));
$this->assertTrue($container->has('a'));
}
/**
* @group legacy
*/
public function testEnterChildScopeRecursively()
{
$container = new Container();
$container->addScope(new Scope('foo'));
$container->addScope(new Scope('bar', 'foo'));
$container->enterScope('foo');
$container->enterScope('bar');
$this->assertTrue($container->isScopeActive('bar'));
$this->assertFalse($container->has('a'));
$a = new \stdClass();
$container->set('a', $a, 'bar');
$scoped = $this->getField($container, 'scopedServices');
$this->assertTrue(isset($scoped['bar']['a']));
$this->assertSame($a, $scoped['bar']['a']);
$this->assertTrue($container->has('a'));
$container->enterScope('bar');
$scoped = $this->getField($container, 'scopedServices');
$this->assertFalse(isset($scoped['a']));
$this->assertTrue($container->isScopeActive('foo'));
$this->assertTrue($container->isScopeActive('bar'));
$this->assertFalse($container->has('a'));
$container->leaveScope('bar');
$this->assertTrue($container->isScopeActive('foo'));
$this->assertTrue($container->isScopeActive('bar'));
$this->assertTrue($container->has('a'));
}
/**
* @expectedException \InvalidArgumentException
* @group legacy
*/
public function testEnterScopeNotAdded()
{
$container = new Container();
$container->enterScope('foo');
}
/**
* @expectedException \RuntimeException
* @group legacy
*/
public function testEnterScopeDoesNotAllowInactiveParentScope()
{
$container = new Container();
$container->addScope(new Scope('foo'));
$container->addScope(new Scope('bar', 'foo'));
$container->enterScope('bar');
}
/**
* @group legacy
*/
public function testLeaveScopeNotActive()
{
$container = new Container();
$container->addScope(new Scope('foo'));
try {
$container->leaveScope('foo');
$this->fail('->leaveScope() throws a \LogicException if the scope is not active yet');
} catch (\Exception $e) {
$this->assertInstanceOf('\LogicException', $e, '->leaveScope() throws a \LogicException if the scope is not active yet');
$this->assertEquals('The scope "foo" is not active.', $e->getMessage(), '->leaveScope() throws a \LogicException if the scope is not active yet');
}
try {
$container->leaveScope('bar');
$this->fail('->leaveScope() throws a \LogicException if the scope does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('\LogicException', $e, '->leaveScope() throws a \LogicException if the scope does not exist');
$this->assertEquals('The scope "bar" is not active.', $e->getMessage(), '->leaveScope() throws a \LogicException if the scope does not exist');
}
}
/**
* @expectedException \InvalidArgumentException
* @dataProvider getLegacyBuiltInScopes
* @group legacy
*/
public function testAddScopeDoesNotAllowBuiltInScopes($scope)
{
$container = new Container();
$container->addScope(new Scope($scope));
}
/**
* @expectedException \InvalidArgumentException
* @group legacy
*/
public function testAddScopeDoesNotAllowExistingScope()
{
$container = new Container();
$container->addScope(new Scope('foo'));
$container->addScope(new Scope('foo'));
}
/**
* @expectedException \InvalidArgumentException
* @dataProvider getLegacyInvalidParentScopes
* @group legacy
*/
public function testAddScopeDoesNotAllowInvalidParentScope($scope)
{
$c = new Container();
$c->addScope(new Scope('foo', $scope));
}
/**
* @group legacy
*/
public function testAddScope()
{
$c = new Container();
$c->addScope(new Scope('foo'));
$c->addScope(new Scope('bar', 'foo'));
$this->assertSame(array('foo' => 'container', 'bar' => 'foo'), $this->getField($c, 'scopes'));
$this->assertSame(array('foo' => array('bar'), 'bar' => array()), $this->getField($c, 'scopeChildren'));
$c->addScope(new Scope('baz', 'bar'));
$this->assertSame(array('foo' => 'container', 'bar' => 'foo', 'baz' => 'bar'), $this->getField($c, 'scopes'));
$this->assertSame(array('foo' => array('bar', 'baz'), 'bar' => array('baz'), 'baz' => array()), $this->getField($c, 'scopeChildren'));
}
/**
* @group legacy
*/
public function testHasScope()
{
$c = new Container();
$this->assertFalse($c->hasScope('foo'));
$c->addScope(new Scope('foo'));
$this->assertTrue($c->hasScope('foo'));
}
/**
* @expectedException \Exception
* @expectedExceptionMessage Something went terribly wrong!
*/
public function testGetThrowsException()
{
$c = new ProjectServiceContainer();
try {
$c->get('throw_exception');
} catch (\Exception $e) {
// Do nothing.
}
// Retry, to make sure that get*Service() will be called.
$c->get('throw_exception');
}
public function testGetThrowsExceptionOnServiceConfiguration()
{
$c = new ProjectServiceContainer();
try {
$c->get('throws_exception_on_service_configuration');
} catch (\Exception $e) {
// Do nothing.
}
$this->assertFalse($c->initialized('throws_exception_on_service_configuration'));
// Retry, to make sure that get*Service() will be called.
try {
$c->get('throws_exception_on_service_configuration');
} catch (\Exception $e) {
// Do nothing.
}
$this->assertFalse($c->initialized('throws_exception_on_service_configuration'));
}
/**
* @group legacy
*/
public function testIsScopeActive()
{
$c = new Container();
$this->assertFalse($c->isScopeActive('foo'));
$c->addScope(new Scope('foo'));
$this->assertFalse($c->isScopeActive('foo'));
$c->enterScope('foo');
$this->assertTrue($c->isScopeActive('foo'));
$c->leaveScope('foo');
$this->assertFalse($c->isScopeActive('foo'));
}
public function getLegacyInvalidParentScopes()
{
return array(
array(ContainerInterface::SCOPE_PROTOTYPE),
array('bar'),
);
}
public function getLegacyBuiltInScopes()
{
return array(
array(ContainerInterface::SCOPE_CONTAINER),
array(ContainerInterface::SCOPE_PROTOTYPE),
);
}
protected function getField($obj, $field)
{
$reflection = new \ReflectionProperty($obj, $field);
$reflection->setAccessible(true);
return $reflection->getValue($obj);
}
public function testAlias()
{
$c = new ProjectServiceContainer();
$this->assertTrue($c->has('alias'));
$this->assertSame($c->get('alias'), $c->get('bar'));
}
public function testThatCloningIsNotSupported()
{
$class = new \ReflectionClass('Symfony\Component\DependencyInjection\Container');
$clone = $class->getMethod('__clone');
if (\PHP_VERSION_ID >= 50400) {
$this->assertFalse($class->isCloneable());
}
$this->assertTrue($clone->isPrivate());
}
}
class ProjectServiceContainer extends Container
{
public $__bar;
public $__foo_bar;
public $__foo_baz;
public $synchronized;
public function __construct()
{
parent::__construct();
$this->__bar = new \stdClass();
$this->__foo_bar = new \stdClass();
$this->__foo_baz = new \stdClass();
$this->synchronized = false;
$this->aliases = array('alias' => 'bar');
}
protected function getScopedService()
{
if (!$this->isScopeActive('foo')) {
throw new \RuntimeException('Invalid call');
}
return $this->services['scoped'] = $this->scopedServices['foo']['scoped'] = new \stdClass();
}
protected function getScopedFooService()
{
if (!$this->isScopeActive('foo')) {
throw new \RuntimeException('invalid call');
}
return $this->services['scoped_foo'] = $this->scopedServices['foo']['scoped_foo'] = new \stdClass();
}
protected function getScopedSynchronizedFooService()
{
if (!$this->isScopeActive('foo')) {
throw new \RuntimeException('invalid call');
}
return $this->services['scoped_bar'] = $this->scopedServices['foo']['scoped_bar'] = new \stdClass();
}
protected function synchronizeFooService()
{
// Typically get the service to pass it to a setter
$this->get('foo');
}
protected function synchronizeScopedSynchronizedFooService()
{
$this->synchronized = true;
}
protected function getInactiveService()
{
throw new InactiveScopeException('request', 'request');
}
protected function getBarService()
{
return $this->__bar;
}
protected function getFooBarService()
{
return $this->__foo_bar;
}
protected function getFoo_BazService()
{
return $this->__foo_baz;
}
protected function getCircularService()
{
return $this->get('circular');
}
protected function getThrowExceptionService()
{
throw new \Exception('Something went terribly wrong!');
}
protected function getThrowsExceptionOnServiceConfigurationService()
{
$this->services['throws_exception_on_service_configuration'] = $instance = new \stdClass();
throw new \Exception('Something was terribly wrong while trying to configure the service!');
}
}
| robhaverkort/belasting | vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php | PHP | mit | 28,728 |
---
layout: tutorial_frame
title: Video Overlay Tutorial
---
<script>
var map = L.map('map');
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.satellite'
}).addTo(map);
var videoUrls = [
'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
'https://www.mapbox.com/bites/00188/patricia_nasa.mp4'
],
bounds = L.latLngBounds([[ 32, -130], [ 13, -100]]);
map.fitBounds(bounds);
var overlay = L.videoOverlay(videoUrls, bounds, {
opacity: 0.8,
interactive: false,
autoplay: false
});
map.addLayer(overlay);
overlay.on('load', function () {
var MyPauseControl = L.Control.extend({
onAdd: function() {
var button = L.DomUtil.create('button');
button.innerHTML = '⏸';
L.DomEvent.on(button, 'click', function () {
overlay.getElement().pause();
});
return button;
}
});
var MyPlayControl = L.Control.extend({
onAdd: function() {
var button = L.DomUtil.create('button');
button.innerHTML = '⏵';
L.DomEvent.on(button, 'click', function () {
overlay.getElement().play();
});
return button;
}
});
var pauseControl = (new MyPauseControl()).addTo(map);
var playControl = (new MyPlayControl()).addTo(map);
});
</script>
| watari53/HighWayStampRally | www/components/Leaflet/docs/examples/video-overlay/example.md | Markdown | mit | 1,604 |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventProperty
**
** Purpose:
** This public class defines the methods / properties for the
** individual Data Values of an EventRecord. Instances of this
** class are obtained from EventRecord.
**
============================================================*/
using System;
namespace System.Diagnostics.Eventing.Reader {
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class EventProperty {
private object value;
internal EventProperty(object value) {
this.value = value;
}
public object Value {
get {
return value;
}
}
}
}
| sekcheong/referencesource | System.Core/System/Diagnostics/Eventing/Reader/EventProperty.cs | C# | mit | 837 |
/*! jQuery UI - v1.10.4 - 2014-01-19
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.pt={closeText:"Fechar",prevText:"Anterior",nextText:"Seguinte",currentText:"Hoje",monthNames:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],monthNamesShort:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],dayNames:["Domingo","Segunda-feira","Terça-feira","Quarta-feira","Quinta-feira","Sexta-feira","Sábado"],dayNamesShort:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],dayNamesMin:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],weekHeader:"Sem",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.pt)}); | soney/interstate | src/_vendor/jquery-ui-1.10.4.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-pt.min.js | JavaScript | mit | 846 |
using System;
using System.Linq;
using JabbR.Models;
using Microsoft.AspNet.SignalR;
namespace JabbR.Commands
{
[Command("list", "List_CommandInfo", "[room]", "room")]
public class ListCommand : UserCommand
{
public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args)
{
string roomName = args.Length > 0 ? args[0] : callerContext.RoomName;
if (String.IsNullOrEmpty(roomName))
{
throw new HubException(LanguageResources.List_RoomRequired);
}
ChatRoom room = context.Repository.VerifyRoom(roomName);
// ensure the user could join the room if they wanted to
callingUser.EnsureAllowed(room);
var names = context.Repository.GetOnlineUsers(room).Select(s => s.Name);
context.NotificationService.ListUsers(room, names);
}
}
} | fuzeman/vox | Vox/Commands/ListCommand.cs | C# | mit | 951 |
## Node.js
These settings apply only when `--nodejs` is specified on the command line.
Please also specify `--node-sdks-folder=<path to root folder of your azure-sdk-for-node clone>`.
``` yaml $(nodejs)
nodejs:
azure-arm: true
package-name: azure-arm-sql
output-folder: $(node-sdks-folder)/lib/services/sqlManagement2
generate-license-txt: true
generate-package-json: true
generate-readme-md: true
```
| yugangw-msft/azure-rest-api-specs | specification/sql/resource-manager/readme.nodejs.md | Markdown | mit | 416 |
/*
* Copyright (c) 2006-2009 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <[email protected]>
*
* S3C24XX CPU Frequency scaling - IO timing for S3C2410/S3C2440/S3C2442
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/cpufreq.h>
#include <linux/seq_file.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <plat/cpu-freq-core.h>
#include "regs-mem.h"
#define print_ns(x) ((x) / 10), ((x) % 10)
/**
* s3c2410_print_timing - print bank timing data for debug purposes
* @pfx: The prefix to put on the output
* @timings: The timing inforamtion to print.
*/
static void s3c2410_print_timing(const char *pfx,
struct s3c_iotimings *timings)
{
struct s3c2410_iobank_timing *bt;
int bank;
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = timings->bank[bank].io_2410;
if (!bt)
continue;
printk(KERN_DEBUG "%s %d: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, "
"Tcoh=%d.%d, Tcah=%d.%d\n", pfx, bank,
print_ns(bt->tacs),
print_ns(bt->tcos),
print_ns(bt->tacc),
print_ns(bt->tcoh),
print_ns(bt->tcah));
}
}
/**
* bank_reg - convert bank number to pointer to the control register.
* @bank: The IO bank number.
*/
static inline void __iomem *bank_reg(unsigned int bank)
{
return S3C2410_BANKCON0 + (bank << 2);
}
/**
* bank_is_io - test whether bank is used for IO
* @bankcon: The bank control register.
*
* This is a simplistic test to see if any BANKCON[x] is not an IO
* bank. It currently does not take into account whether BWSCON has
* an illegal width-setting in it, or if the pin connected to nCS[x]
* is actually being handled as a chip-select.
*/
static inline int bank_is_io(unsigned long bankcon)
{
return !(bankcon & S3C2410_BANKCON_SDRAM);
}
/**
* to_div - convert cycle time to divisor
* @cyc: The cycle time, in 10ths of nanoseconds.
* @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds.
*
* Convert the given cycle time into the divisor to use to obtain it from
* HCLK.
*/
static inline unsigned int to_div(unsigned int cyc, unsigned int hclk_tns)
{
if (cyc == 0)
return 0;
return DIV_ROUND_UP(cyc, hclk_tns);
}
/**
* calc_0124 - calculate divisor control for divisors that do /0, /1. /2 and /4
* @cyc: The cycle time, in 10ths of nanoseconds.
* @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds.
* @v: Pointer to register to alter.
* @shift: The shift to get to the control bits.
*
* Calculate the divisor, and turn it into the correct control bits to
* set in the result, @v.
*/
static unsigned int calc_0124(unsigned int cyc, unsigned long hclk_tns,
unsigned long *v, int shift)
{
unsigned int div = to_div(cyc, hclk_tns);
unsigned long val;
s3c_freq_iodbg("%s: cyc=%d, hclk=%lu, shift=%d => div %d\n",
__func__, cyc, hclk_tns, shift, div);
switch (div) {
case 0:
val = 0;
break;
case 1:
val = 1;
break;
case 2:
val = 2;
break;
case 3:
case 4:
val = 3;
break;
default:
return -1;
}
*v |= val << shift;
return 0;
}
int calc_tacp(unsigned int cyc, unsigned long hclk, unsigned long *v)
{
/* Currently no support for Tacp calculations. */
return 0;
}
/**
* calc_tacc - calculate divisor control for tacc.
* @cyc: The cycle time, in 10ths of nanoseconds.
* @nwait_en: IS nWAIT enabled for this bank.
* @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds.
* @v: Pointer to register to alter.
*
* Calculate the divisor control for tACC, taking into account whether
* the bank has nWAIT enabled. The result is used to modify the value
* pointed to by @v.
*/
static int calc_tacc(unsigned int cyc, int nwait_en,
unsigned long hclk_tns, unsigned long *v)
{
unsigned int div = to_div(cyc, hclk_tns);
unsigned long val;
s3c_freq_iodbg("%s: cyc=%u, nwait=%d, hclk=%lu => div=%u\n",
__func__, cyc, nwait_en, hclk_tns, div);
/* if nWait enabled on an bank, Tacc must be at-least 4 cycles. */
if (nwait_en && div < 4)
div = 4;
switch (div) {
case 0:
val = 0;
break;
case 1:
case 2:
case 3:
case 4:
val = div - 1;
break;
case 5:
case 6:
val = 4;
break;
case 7:
case 8:
val = 5;
break;
case 9:
case 10:
val = 6;
break;
case 11:
case 12:
case 13:
case 14:
val = 7;
break;
default:
return -1;
}
*v |= val << 8;
return 0;
}
/**
* s3c2410_calc_bank - calculate bank timing information
* @cfg: The configuration we need to calculate for.
* @bt: The bank timing information.
*
* Given the cycle timine for a bank @bt, calculate the new BANKCON
* setting for the @cfg timing. This updates the timing information
* ready for the cpu frequency change.
*/
static int s3c2410_calc_bank(struct s3c_cpufreq_config *cfg,
struct s3c2410_iobank_timing *bt)
{
unsigned long hclk = cfg->freq.hclk_tns;
unsigned long res;
int ret;
res = bt->bankcon;
res &= (S3C2410_BANKCON_SDRAM | S3C2410_BANKCON_PMC16);
/* tacp: 2,3,4,5 */
/* tcah: 0,1,2,4 */
/* tcoh: 0,1,2,4 */
/* tacc: 1,2,3,4,6,7,10,14 (>4 for nwait) */
/* tcos: 0,1,2,4 */
/* tacs: 0,1,2,4 */
ret = calc_0124(bt->tacs, hclk, &res, S3C2410_BANKCON_Tacs_SHIFT);
ret |= calc_0124(bt->tcos, hclk, &res, S3C2410_BANKCON_Tcos_SHIFT);
ret |= calc_0124(bt->tcah, hclk, &res, S3C2410_BANKCON_Tcah_SHIFT);
ret |= calc_0124(bt->tcoh, hclk, &res, S3C2410_BANKCON_Tcoh_SHIFT);
if (ret)
return -EINVAL;
ret |= calc_tacp(bt->tacp, hclk, &res);
ret |= calc_tacc(bt->tacc, bt->nwait_en, hclk, &res);
if (ret)
return -EINVAL;
bt->bankcon = res;
return 0;
}
static const unsigned int tacc_tab[] = {
[0] = 1,
[1] = 2,
[2] = 3,
[3] = 4,
[4] = 6,
[5] = 9,
[6] = 10,
[7] = 14,
};
/**
* get_tacc - turn tACC value into cycle time
* @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds.
* @val: The bank timing register value, shifed down.
*/
static unsigned int get_tacc(unsigned long hclk_tns,
unsigned long val)
{
val &= 7;
return hclk_tns * tacc_tab[val];
}
/**
* get_0124 - turn 0/1/2/4 divider into cycle time
* @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds.
* @val: The bank timing register value, shifed down.
*/
static unsigned int get_0124(unsigned long hclk_tns,
unsigned long val)
{
val &= 3;
return hclk_tns * ((val == 3) ? 4 : val);
}
/**
* s3c2410_iotiming_getbank - turn BANKCON into cycle time information
* @cfg: The frequency configuration
* @bt: The bank timing to fill in (uses cached BANKCON)
*
* Given the BANKCON setting in @bt and the current frequency settings
* in @cfg, update the cycle timing information.
*/
void s3c2410_iotiming_getbank(struct s3c_cpufreq_config *cfg,
struct s3c2410_iobank_timing *bt)
{
unsigned long bankcon = bt->bankcon;
unsigned long hclk = cfg->freq.hclk_tns;
bt->tcah = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcah_SHIFT);
bt->tcoh = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcoh_SHIFT);
bt->tcos = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcos_SHIFT);
bt->tacs = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tacs_SHIFT);
bt->tacc = get_tacc(hclk, bankcon >> S3C2410_BANKCON_Tacc_SHIFT);
}
/**
* s3c2410_iotiming_debugfs - debugfs show io bank timing information
* @seq: The seq_file to write output to using seq_printf().
* @cfg: The current configuration.
* @iob: The IO bank information to decode.
*/
void s3c2410_iotiming_debugfs(struct seq_file *seq,
struct s3c_cpufreq_config *cfg,
union s3c_iobank *iob)
{
struct s3c2410_iobank_timing *bt = iob->io_2410;
unsigned long bankcon = bt->bankcon;
unsigned long hclk = cfg->freq.hclk_tns;
unsigned int tacs;
unsigned int tcos;
unsigned int tacc;
unsigned int tcoh;
unsigned int tcah;
seq_printf(seq, "BANKCON=0x%08lx\n", bankcon);
tcah = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcah_SHIFT);
tcoh = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcoh_SHIFT);
tcos = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcos_SHIFT);
tacs = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tacs_SHIFT);
tacc = get_tacc(hclk, bankcon >> S3C2410_BANKCON_Tacc_SHIFT);
seq_printf(seq,
"\tRead: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, Tcoh=%d.%d, Tcah=%d.%d\n",
print_ns(bt->tacs),
print_ns(bt->tcos),
print_ns(bt->tacc),
print_ns(bt->tcoh),
print_ns(bt->tcah));
seq_printf(seq,
"\t Set: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, Tcoh=%d.%d, Tcah=%d.%d\n",
print_ns(tacs),
print_ns(tcos),
print_ns(tacc),
print_ns(tcoh),
print_ns(tcah));
}
/**
* s3c2410_iotiming_calc - Calculate bank timing for frequency change.
* @cfg: The frequency configuration
* @iot: The IO timing information to fill out.
*
* Calculate the new values for the banks in @iot based on the new
* frequency information in @cfg. This is then used by s3c2410_iotiming_set()
* to update the timing when necessary.
*/
int s3c2410_iotiming_calc(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *iot)
{
struct s3c2410_iobank_timing *bt;
unsigned long bankcon;
int bank;
int ret;
for (bank = 0; bank < MAX_BANKS; bank++) {
bankcon = __raw_readl(bank_reg(bank));
bt = iot->bank[bank].io_2410;
if (!bt)
continue;
bt->bankcon = bankcon;
ret = s3c2410_calc_bank(cfg, bt);
if (ret) {
printk(KERN_ERR "%s: cannot calculate bank %d io\n",
__func__, bank);
goto err;
}
s3c_freq_iodbg("%s: bank %d: con=%08lx\n",
__func__, bank, bt->bankcon);
}
return 0;
err:
return ret;
}
/**
* s3c2410_iotiming_set - set the IO timings from the given setup.
* @cfg: The frequency configuration
* @iot: The IO timing information to use.
*
* Set all the currently used IO bank timing information generated
* by s3c2410_iotiming_calc() once the core has validated that all
* the new values are within permitted bounds.
*/
void s3c2410_iotiming_set(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *iot)
{
struct s3c2410_iobank_timing *bt;
int bank;
/* set the io timings from the specifier */
for (bank = 0; bank < MAX_BANKS; bank++) {
bt = iot->bank[bank].io_2410;
if (!bt)
continue;
__raw_writel(bt->bankcon, bank_reg(bank));
}
}
/**
* s3c2410_iotiming_get - Get the timing information from current registers.
* @cfg: The frequency configuration
* @timings: The IO timing information to fill out.
*
* Calculate the @timings timing information from the current frequency
* information in @cfg, and the new frequency configuration
* through all the IO banks, reading the state and then updating @iot
* as necessary.
*
* This is used at the moment on initialisation to get the current
* configuration so that boards do not have to carry their own setup
* if the timings are correct on initialisation.
*/
int s3c2410_iotiming_get(struct s3c_cpufreq_config *cfg,
struct s3c_iotimings *timings)
{
struct s3c2410_iobank_timing *bt;
unsigned long bankcon;
unsigned long bwscon;
int bank;
bwscon = __raw_readl(S3C2410_BWSCON);
/* look through all banks to see what is currently set. */
for (bank = 0; bank < MAX_BANKS; bank++) {
bankcon = __raw_readl(bank_reg(bank));
if (!bank_is_io(bankcon))
continue;
s3c_freq_iodbg("%s: bank %d: con %08lx\n",
__func__, bank, bankcon);
bt = kzalloc(sizeof(*bt), GFP_KERNEL);
if (!bt)
return -ENOMEM;
/* find out in nWait is enabled for bank. */
if (bank != 0) {
unsigned long tmp = S3C2410_BWSCON_GET(bwscon, bank);
if (tmp & S3C2410_BWSCON_WS)
bt->nwait_en = 1;
}
timings->bank[bank].io_2410 = bt;
bt->bankcon = bankcon;
s3c2410_iotiming_getbank(cfg, bt);
}
s3c2410_print_timing("get", timings);
return 0;
}
| hannes/linux | arch/arm/mach-s3c24xx/iotiming-s3c2410.c | C | gpl-2.0 | 11,881 |
/*
*
*
* Copyright (C) 2009 SonyEricsson AB
* License terms: GNU General Public License (GPL) version 2
* Author: Aleksej Makarov <[email protected]>
*
*/
/****************** INCLUDE FILES SECTION *************************************/
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/workqueue.h>
#include <mach/msm_rpcrouter.h>
#include <mach/pmic.h>
#include <mach/misc_modem_api.h>
#include <linux/miscdevice.h>
#include <linux/semcclass.h>
#include <linux/fs.h>
#include <mach/vreg.h>
/****************** CONSTANT AND MACRO SECTION ********************************/
#define DEBUG_LEVEL 0
#define TIMEOUT_IMMEDIATELY (1 * HZ)
#define TIMEOUT_INFINITE -1
#define PMIC_APISPROG 0x30000061
#define PMIC_APISVERS 0x00010001
#define ADC_RPC_TIMEOUT (5 * HZ)
#define ONCRPC_ADC_READ_PROC 100
#define ONCRPC_VREG_CONTROL_PROC 101
#define ONCRPC_ENABLE_CAMERA_FLASH_PROC 102
#define ONCRPC_UNSECURE_CONFIG_DIGITAL_OUT_PROC 103
#define QC_ONCRPC_ADC_READ_PROC 2
#define QC_ADC_READ_APISPROG 0x30000071
#define QC_ADC_READ_APISVERS 0x00010001
/****************** TYPE DEFINITION SECTION ***********************************/
struct misc_api_rpc_t {
u32 prog;
u32 vers;
u32 proc;
u32 timeout;
};
/****************** DATA DEFINITION SECTION ***********************************/
static const struct misc_api_rpc_t proc_adc_read = {
QC_ADC_READ_APISPROG,
QC_ADC_READ_APISVERS,
QC_ONCRPC_ADC_READ_PROC,
TIMEOUT_IMMEDIATELY,
};
static const struct misc_api_rpc_t proc_vreg_control = {
PMIC_APISPROG,
PMIC_APISVERS,
ONCRPC_VREG_CONTROL_PROC,
TIMEOUT_IMMEDIATELY,
};
static const struct misc_api_rpc_t proc_enable_camera_flash = {
PMIC_APISPROG,
PMIC_APISVERS,
ONCRPC_ENABLE_CAMERA_FLASH_PROC,
TIMEOUT_IMMEDIATELY,
};
static int misc_rpc_call_reply(const struct misc_api_rpc_t *remote,
void *in, int in_size,
void *out, int out_size)
{
struct msm_rpc_endpoint *endpoint;
int rc = -ENODEV;
endpoint = msm_rpc_connect_compatible(remote->prog,
remote->vers, 0);
if (NULL == endpoint) {
printk(KERN_ERR "%s: msm_rpc_connect_compatible failed\n", __func__);
return rc;
}
if (IS_ERR(endpoint)) {
printk(KERN_ERR "%s: msm_rpc_connect_compatible failed (%ld returned)\n",
__func__, IS_ERR(endpoint));
goto exit_func;
}
#if DEBUG_LEVEL
printk(KERN_DEBUG "%s: msm_rpc_connect_compatible OK: (0x%08x:v.%08x)\n",
__func__, remote->prog, remote->vers);
#endif
rc = msm_rpc_call_reply(endpoint,
remote->proc,
in, in_size,
out, out_size,
remote->timeout);
if (rc < 0)
printk(KERN_ERR"%s: failed err=%d\n", __func__, rc);
#if DEBUG_LEVEL
printk(KERN_DEBUG "%s (0x%08x:v.%08x proc=%d insize=%d outsize=%d):"
" rc = %d\n",
__func__, remote->prog, remote->vers,
remote->proc, in_size, out_size, rc);
#endif
exit_func:
msm_rpc_close(endpoint);
return rc > 0 ? 0 : rc;
}
int msm_adc_read(enum adc_logical_channel_t channel, u16 *return_value)
{
int rc;
struct {
struct rpc_request_hdr hdr;
u32 data;
} request;
struct {
struct rpc_reply_hdr hdr;
u32 data;
} reply;
request.data = cpu_to_be32(channel);
rc = misc_rpc_call_reply(&proc_adc_read, &request,
sizeof(request), &reply, sizeof(reply));
if (!rc)
*return_value = (u16) be32_to_cpu(reply.data);
return rc;
}
EXPORT_SYMBOL_GPL(msm_adc_read);
int pmic_boost_control(int enable)
{
int rc;
struct {
struct rpc_request_hdr hdr;
u32 data;
} request;
struct {
struct rpc_reply_hdr hdr;
u32 data;
} reply;
request.data = cpu_to_be32(enable);
rc = misc_rpc_call_reply(&proc_vreg_control,
&request, sizeof(request), &reply, sizeof(reply));
if (rc)
printk(KERN_ERR"%s: failed (pmic_lib_err=%d)\n",
__func__, be32_to_cpu(reply.data));
return rc;
}
EXPORT_SYMBOL_GPL(pmic_boost_control);
int pmic_enable_camera_flash(u16 current_mamp)
{
int rc;
struct {
struct rpc_request_hdr hdr;
u32 data;
} request;
struct {
struct rpc_reply_hdr hdr;
u32 data;
} reply;
request.data = cpu_to_be32(current_mamp);
rc = misc_rpc_call_reply(&proc_enable_camera_flash,
&request, sizeof(request), &reply, sizeof(reply));
if (rc)
printk(KERN_ERR"%s: failed (pmic_lib_err=%d)\n",
__func__, be32_to_cpu(reply.data));
return rc;
}
EXPORT_SYMBOL_GPL(pmic_enable_camera_flash);
MODULE_AUTHOR("Aleksej Makarov");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Misc modem API");
| skritchz/semc-kernel-qsd8k-ics | arch/arm/mach-msm/misc_modem_api.c | C | gpl-2.0 | 4,424 |
// Copyright 2017 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "DolphinQt/Config/LogConfigWidget.h"
#include <QCheckBox>
#include <QGroupBox>
#include <QListWidget>
#include <QPushButton>
#include <QRadioButton>
#include <QVBoxLayout>
#include "Common/FileUtil.h"
#include "Common/Logging/LogManager.h"
#include "Core/ConfigManager.h"
#include "DolphinQt/Settings.h"
LogConfigWidget::LogConfigWidget(QWidget* parent) : QDockWidget(parent)
{
setWindowTitle(tr("Log Configuration"));
setObjectName(QStringLiteral("logconfig"));
setHidden(!Settings::Instance().IsLogConfigVisible());
setAllowedAreas(Qt::AllDockWidgetAreas);
CreateWidgets();
LoadSettings();
ConnectWidgets();
}
LogConfigWidget::~LogConfigWidget()
{
SaveSettings();
}
void LogConfigWidget::CreateWidgets()
{
auto* layout = new QVBoxLayout;
auto* verbosity = new QGroupBox(tr("Verbosity"));
auto* verbosity_layout = new QVBoxLayout;
verbosity->setLayout(verbosity_layout);
m_verbosity_notice = new QRadioButton(tr("Notice"));
m_verbosity_error = new QRadioButton(tr("Error"));
m_verbosity_warning = new QRadioButton(tr("Warning"));
m_verbosity_info = new QRadioButton(tr("Info"));
m_verbosity_debug = new QRadioButton(tr("Debug"));
auto* outputs = new QGroupBox(tr("Logger Outputs"));
auto* outputs_layout = new QVBoxLayout;
outputs->setLayout(outputs_layout);
m_out_file = new QCheckBox(tr("Write to File"));
m_out_console = new QCheckBox(tr("Write to Console"));
m_out_window = new QCheckBox(tr("Write to Window"));
auto* types = new QGroupBox(tr("Log Types"));
auto* types_layout = new QVBoxLayout;
types->setLayout(types_layout);
m_types_toggle = new QPushButton(tr("Toggle All Log Types"));
m_types_list = new QListWidget;
const auto* const log_manager = Common::Log::LogManager::GetInstance();
for (int i = 0; i < Common::Log::NUMBER_OF_LOGS; i++)
{
const auto log_type = static_cast<Common::Log::LOG_TYPE>(i);
const QString full_name = QString::fromUtf8(log_manager->GetFullName(log_type));
const QString short_name = QString::fromUtf8(log_manager->GetShortName(log_type));
auto* widget = new QListWidgetItem(QStringLiteral("%1 (%2)").arg(full_name, short_name));
widget->setCheckState(Qt::Unchecked);
m_types_list->addItem(widget);
}
layout->addWidget(verbosity);
verbosity_layout->addWidget(m_verbosity_notice);
verbosity_layout->addWidget(m_verbosity_error);
verbosity_layout->addWidget(m_verbosity_warning);
verbosity_layout->addWidget(m_verbosity_info);
if constexpr (MAX_LOGLEVEL == Common::Log::LOG_LEVELS::LDEBUG)
{
verbosity_layout->addWidget(m_verbosity_debug);
}
layout->addWidget(outputs);
outputs_layout->addWidget(m_out_file);
outputs_layout->addWidget(m_out_console);
outputs_layout->addWidget(m_out_window);
layout->addWidget(types);
types_layout->addWidget(m_types_toggle);
types_layout->addWidget(m_types_list);
QWidget* widget = new QWidget;
widget->setLayout(layout);
setWidget(widget);
}
void LogConfigWidget::ConnectWidgets()
{
// Configuration
connect(m_verbosity_notice, &QRadioButton::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_verbosity_error, &QRadioButton::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_verbosity_warning, &QRadioButton::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_verbosity_info, &QRadioButton::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_verbosity_debug, &QRadioButton::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_out_file, &QCheckBox::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_out_console, &QCheckBox::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_out_window, &QCheckBox::toggled, this, &LogConfigWidget::SaveSettings);
connect(m_types_toggle, &QPushButton::clicked, [this] {
m_all_enabled = !m_all_enabled;
// Don't save every time we change an item
m_block_save = true;
for (int i = 0; i < m_types_list->count(); i++)
m_types_list->item(i)->setCheckState(m_all_enabled ? Qt::Checked : Qt::Unchecked);
m_block_save = false;
SaveSettings();
});
connect(m_types_list, &QListWidget::itemChanged, this, &LogConfigWidget::SaveSettings);
connect(&Settings::Instance(), &Settings::LogConfigVisibilityChanged, this,
[this](bool visible) { setHidden(!visible); });
}
void LogConfigWidget::LoadSettings()
{
const auto* const log_manager = Common::Log::LogManager::GetInstance();
const auto& settings = Settings::GetQSettings();
restoreGeometry(settings.value(QStringLiteral("logconfigwidget/geometry")).toByteArray());
setFloating(settings.value(QStringLiteral("logconfigwidget/floating")).toBool());
// Config - Verbosity
const Common::Log::LOG_LEVELS verbosity = log_manager->GetLogLevel();
m_verbosity_notice->setChecked(verbosity == Common::Log::LOG_LEVELS::LNOTICE);
m_verbosity_error->setChecked(verbosity == Common::Log::LOG_LEVELS::LERROR);
m_verbosity_warning->setChecked(verbosity == Common::Log::LOG_LEVELS::LWARNING);
m_verbosity_info->setChecked(verbosity == Common::Log::LOG_LEVELS::LINFO);
m_verbosity_debug->setChecked(verbosity == Common::Log::LOG_LEVELS::LDEBUG);
// Config - Outputs
m_out_file->setChecked(log_manager->IsListenerEnabled(Common::Log::LogListener::FILE_LISTENER));
m_out_console->setChecked(
log_manager->IsListenerEnabled(Common::Log::LogListener::CONSOLE_LISTENER));
m_out_window->setChecked(
log_manager->IsListenerEnabled(Common::Log::LogListener::LOG_WINDOW_LISTENER));
// Config - Log Types
for (int i = 0; i < Common::Log::NUMBER_OF_LOGS; ++i)
{
const auto log_type = static_cast<Common::Log::LOG_TYPE>(i);
const bool log_enabled = log_manager->IsEnabled(log_type);
if (!log_enabled)
m_all_enabled = false;
m_types_list->item(i)->setCheckState(log_enabled ? Qt::Checked : Qt::Unchecked);
}
}
void LogConfigWidget::SaveSettings()
{
if (m_block_save)
return;
auto& settings = Settings::GetQSettings();
settings.setValue(QStringLiteral("logconfigwidget/geometry"), saveGeometry());
settings.setValue(QStringLiteral("logconfigwidget/floating"), isFloating());
// Config - Verbosity
auto verbosity = Common::Log::LOG_LEVELS::LNOTICE;
if (m_verbosity_notice->isChecked())
verbosity = Common::Log::LOG_LEVELS::LNOTICE;
if (m_verbosity_error->isChecked())
verbosity = Common::Log::LOG_LEVELS::LERROR;
if (m_verbosity_warning->isChecked())
verbosity = Common::Log::LOG_LEVELS::LWARNING;
if (m_verbosity_info->isChecked())
verbosity = Common::Log::LOG_LEVELS::LINFO;
if (m_verbosity_debug->isChecked())
verbosity = Common::Log::LOG_LEVELS::LDEBUG;
auto* const log_manager = Common::Log::LogManager::GetInstance();
// Config - Verbosity
log_manager->SetLogLevel(verbosity);
// Config - Outputs
log_manager->EnableListener(Common::Log::LogListener::FILE_LISTENER, m_out_file->isChecked());
log_manager->EnableListener(Common::Log::LogListener::CONSOLE_LISTENER,
m_out_console->isChecked());
log_manager->EnableListener(Common::Log::LogListener::LOG_WINDOW_LISTENER,
m_out_window->isChecked());
// Config - Log Types
for (int i = 0; i < Common::Log::NUMBER_OF_LOGS; ++i)
{
const auto type = static_cast<Common::Log::LOG_TYPE>(i);
const bool enabled = m_types_list->item(i)->checkState() == Qt::Checked;
const bool was_enabled = log_manager->IsEnabled(type);
if (enabled != was_enabled)
log_manager->SetEnable(type, enabled);
}
}
void LogConfigWidget::closeEvent(QCloseEvent*)
{
Settings::Instance().SetLogConfigVisible(false);
}
| TwitchPlaysPokemon/dolphinWatch | Source/Core/DolphinQt/Config/LogConfigWidget.cpp | C++ | gpl-2.0 | 7,785 |
. inc/common.sh
start_server
function check_partitioning()
{
$MYSQL $MYSQL_ARGS -Ns -e "show variables like 'have_partitioning'"
}
PARTITION_CHECK=`check_partitioning`
if [ -z "$PARTITION_CHECK" ]; then
echo "Requires Partitioning." > $SKIPPED_REASON
stop_server
exit $SKIPPED_EXIT_CODE
fi
run_cmd $MYSQL $MYSQL_ARGS test <<EOF
CREATE TABLE test (
a int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
PARTITION BY RANGE (a)
(PARTITION p0 VALUES LESS THAN (100) ENGINE = InnoDB,
PARTITION P1 VALUES LESS THAN (200) ENGINE = InnoDB,
PARTITION p2 VALUES LESS THAN (300) ENGINE = InnoDB,
PARTITION p3 VALUES LESS THAN (400) ENGINE = InnoDB,
PARTITION p4 VALUES LESS THAN MAXVALUE ENGINE = InnoDB);
EOF
# Adding 10k rows
vlog "Adding initial rows to database..."
numrow=500
count=0
while [ "$numrow" -gt "$count" ]
do
${MYSQL} ${MYSQL_ARGS} -e "insert into test values ($count);" test
let "count=count+1"
done
vlog "Initial rows added"
# Full backup
# Full backup folder
mkdir -p $topdir/data/full
# Incremental data
mkdir -p $topdir/data/delta
vlog "Starting backup"
xtrabackup --no-defaults --datadir=$mysql_datadir --backup \
--target-dir=$topdir/data/full
vlog "Full backup done"
# Changing data in sakila
vlog "Making changes to database"
numrow=500
count=0
while [ "$numrow" -gt "$count" ]
do
${MYSQL} ${MYSQL_ARGS} -e "insert into test values ($count);" test
let "count=count+1"
done
vlog "Changes done"
# Saving the checksum of original table
checksum_a=`checksum_table test test`
vlog "Table checksum is $checksum_a - before backup"
vlog "Making incremental backup"
# Incremental backup
xtrabackup --no-defaults --datadir=$mysql_datadir --backup \
--target-dir=$topdir/data/delta --incremental-basedir=$topdir/data/full
vlog "Incremental backup done"
vlog "Preparing backup"
# Prepare backup
xtrabackup --no-defaults --datadir=$mysql_datadir --prepare --apply-log-only \
--target-dir=$topdir/data/full
vlog "Log applied to backup"
xtrabackup --no-defaults --datadir=$mysql_datadir --prepare --apply-log-only \
--target-dir=$topdir/data/full --incremental-dir=$topdir/data/delta
vlog "Delta applied to backup"
xtrabackup --no-defaults --datadir=$mysql_datadir --prepare \
--target-dir=$topdir/data/full
vlog "Data prepared for restore"
# removing rows
vlog "Table cleared"
${MYSQL} ${MYSQL_ARGS} -e "delete from test" test
# Restore backup
stop_server
vlog "Copying files"
cd $topdir/data/full/
cp -r * $mysql_datadir
cd $topdir
vlog "Data restored"
start_server
vlog "Cheking checksums"
checksum_b=`checksum_table test test`
if [ "$checksum_a" != "$checksum_b" ]
then
vlog "Checksums are not equal"
exit -1
fi
vlog "Checksums are OK"
| kraziegent/mysql-5.6 | xtrabackup/test/t/xb_part_range.sh | Shell | gpl-2.0 | 2,731 |
/*
* Copyright (C) 2013 Red Hat
* Author: Rob Clark <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* 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/>.
*/
#ifndef __MSM_MMU_H__
#define __MSM_MMU_H__
#include <linux/iommu.h>
#include <linux/dma-buf.h>
struct msm_mmu;
struct msm_gpu;
struct msm_gem_object;
struct msm_mmu_dev;
/* range of mmu */
#define MSM_MMU_GLOBAL_MEM_SIZE SZ_64M
#define MSM_MMU_GLOBAL_MEM_BASE 0xf8000000
#define MSM_MMU_SECURE_SIZE SZ_256M
#define MSM_MMU_SECURE_END MSM_MMU_GLOBAL_MEM_BASE
#define MSM_MMU_SECURE_BASE \
(MSM_MMU_GLOBAL_MEM_BASE - MSM_MMU_SECURE_SIZE)
#define MSM_MMU_VA_BASE32 0x300000
#define MSM_MMU_VA_END32 (0xC0000000 - SZ_16M)
#define MSM_MMU_VA_SIZE32 (MSM_MMU_VA_END32 - MSM_MMU_VA_BASE32)
#define MSM_MMU_VA_BASE64 0x500000000ULL
#define MSM_MMU_VA_END64 0x600000000ULL
#define MSM_MMU_VA_SIZE64 (MSM_MMU_VA_END64 - MSM_MMU_VA_BASE64)
enum msm_mmu_domain_type {
MSM_SMMU_DOMAIN_UNSECURE = 0,
MSM_SMMU_DOMAIN_NRT_UNSECURE,
MSM_SMMU_DOMAIN_SECURE,
MSM_SMMU_DOMAIN_NRT_SECURE,
MSM_SMMU_DOMAIN_GPU_UNSECURE,
MSM_SMMU_DOMAIN_GPU_SECURE,
MSM_SMMU_DOMAIN_MAX,
};
/* mmu name */
#define MSM_MMU_UNSECURE 0xFFFF0001
#define MSM_MMU_NRT_UNSECURE 0xFFFF0002
#define MSM_MMU_SECURE 0xFFFF0003
#define MSM_MMU_NRT_SECURE 0xFFFF0004
#define MSM_MMU_GPU_UNSECURE 0xFFFF0005
#define MSM_MMU_GPU_SECURE 0xFFFF0006
/* MMU has register retention */
#define MSM_MMU_RETENTION BIT(1)
/* MMU requires the TLB to be flushed on map */
#define MSM_MMU_FLUSH_TLB_ON_MAP BIT(2)
/* MMU uses global pagetable */
#define MSM_MMU_GLOBAL_PAGETABLE BIT(3)
/* MMU uses hypervisor for content protection */
#define MSM_MMU_HYP_SECURE_ALLOC BIT(4)
/* Force 32 bit, even if the MMU can do 64 bit */
#define MSM_MMU_FORCE_32BIT BIT(5)
/* 64 bit address is live */
#define MSM_MMU_64BIT BIT(6)
/* MMU can do coherent hardware table walks */
#define MSM_MMU_COHERENT_HTW BIT(7)
/* The MMU supports non-contigious pages */
#define MSM_MMU_PAGED BIT(8)
/* The device requires a guard page */
#define MSM_MMU_NEED_GUARD_PAGE BIT(9)
struct msm_mmu_funcs {
int (*attach)(struct msm_mmu *mmu, const char **names, int cnt);
void (*detach)(struct msm_mmu *mmu, const char **names, int cnt);
int (*map)(struct msm_mmu *mmu, dma_addr_t iova,
struct sg_table *sgt, int prot);
int (*unmap)(struct msm_mmu *mmu, dma_addr_t iova,
struct sg_table *sgt);
int (*bo_map)(struct msm_mmu *mmu, struct msm_gem_object *bo);
int (*bo_unmap)(struct msm_mmu *mmu, struct msm_gem_object *bo);
/* For switching in multi-context */
u64 (*get_ttbr0)(struct msm_mmu *mmu);
u32 (*get_contextidr)(struct msm_mmu *mmu);
u32 (*get_cb_num)(struct msm_mmu *mmu);
/* iova management. */
int (*get_iovaddr)(struct msm_mmu *mmu, struct msm_gem_object *bo,
uint64_t *iova);
int (*put_iovaddr)(struct msm_mmu *mmu, struct msm_gem_object *bo);
bool (*addr_in_range)(struct msm_mmu *mmu, uint64_t);
int (*map_sg)(struct msm_mmu *mmu, struct sg_table *sgt,
enum dma_data_direction dir);
void (*unmap_sg)(struct msm_mmu *mmu, struct sg_table *sgt,
enum dma_data_direction dir);
int (*map_dma_buf)(struct msm_mmu *mmu, struct sg_table *sgt,
struct dma_buf *dma_buf, int dir);
void (*unmap_dma_buf)(struct msm_mmu *mmu, struct sg_table *sgt,
struct dma_buf *dma_buf, int dir);
void (*destroy)(struct msm_mmu *mmu);
};
struct msm_mmu {
struct kref refcount;
const struct msm_mmu_funcs *funcs;
struct device *dev;
struct drm_device *drm_dev;
uint32_t name;
int id;
};
#define MMU_OP_VALID(_mmu, _field) \
(((_mmu) != NULL) && \
((_mmu)->funcs != NULL) && \
((_mmu)->funcs->_field != NULL))
struct msm_mmu_dev_funcs {
int (*get_cb_num)(struct msm_mmu_dev *mmu_dev);
void (*set_cb_num)(struct msm_mmu_dev *mmu_dev, uint32_t cb_num);
int (*cpu_set_pt)(struct msm_mmu_dev *mmu_dev, struct msm_mmu *mmu);
};
struct msm_mmu_dev {
struct device *dev;
const struct msm_mmu_dev_funcs *funcs;
};
#define MMU_DEV_OP_VALID(_mmu, _field) \
(((_mmu) != NULL) && \
((_mmu)->funcs != NULL) && \
((_mmu)->funcs->_field != NULL))
static inline void msm_mmu_init(struct msm_mmu *mmu, struct drm_device *drm_dev,
struct device *dev, uint32_t name, const struct msm_mmu_funcs *funcs)
{
mmu->drm_dev = drm_dev;
mmu->dev = dev;
mmu->name = name;
mmu->funcs = funcs;
mmu->id = -1;
kref_init(&mmu->refcount);
}
static inline void msm_mmu_dev_init(struct msm_mmu_dev *mdev,
struct device *dev, const struct msm_mmu_dev_funcs *funcs)
{
mdev->dev = dev;
mdev->funcs = funcs;
}
struct msm_mmu *msm_smmu_new(struct drm_device *drm_dev, struct device *dev,
enum msm_mmu_domain_type domain);
struct msm_mmu *msm_iommu_new(struct drm_device *dev,
struct msm_mmu_dev *mmu_dev, uint32_t name);
#endif /* __MSM_MMU_H__ */
| shminer/kernel-msm-3.18 | drivers/gpu/drm/msm/msm_mmu.h | C | gpl-2.0 | 5,376 |
/*****************************************************************************
* filesystem.c: POSIX file system helpers
*****************************************************************************
* Copyright (C) 2005-2006 VLC authors and VideoLAN
* Copyright © 2005-2008 Rémi Denis-Courmont
*
* Authors: Rémi Denis-Courmont <rem # videolan.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <assert.h>
#include <stdio.h>
#include <limits.h> /* NAME_MAX */
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#ifndef HAVE_LSTAT
# define lstat(a, b) stat(a, b)
#endif
#include <dirent.h>
#include <sys/socket.h>
#ifndef O_TMPFILE
# define O_TMPFILE 0
#endif
#include <vlc_common.h>
#include <vlc_fs.h>
int vlc_open (const char *filename, int flags, ...)
{
unsigned int mode = 0;
va_list ap;
va_start (ap, flags);
if (flags & (O_CREAT|O_TMPFILE))
mode = va_arg (ap, unsigned int);
va_end (ap);
#ifdef O_CLOEXEC
flags |= O_CLOEXEC;
#endif
int fd = open (filename, flags, mode);
if (fd != -1)
fcntl (fd, F_SETFD, FD_CLOEXEC);
return fd;
}
int vlc_openat (int dir, const char *filename, int flags, ...)
{
unsigned int mode = 0;
va_list ap;
va_start (ap, flags);
if (flags & (O_CREAT|O_TMPFILE))
mode = va_arg (ap, unsigned int);
va_end (ap);
#ifdef O_CLOEXEC
flags |= O_CLOEXEC;
#endif
#ifdef HAVE_OPENAT
int fd = openat (dir, filename, flags, mode);
if (fd != -1)
fcntl (fd, F_SETFD, FD_CLOEXEC);
#else
VLC_UNUSED (dir);
VLC_UNUSED (filename);
VLC_UNUSED (mode);
int fd = -1;
errno = ENOSYS;
#endif
return fd;
}
int vlc_mkstemp (char *template)
{
int fd;
#ifdef HAVE_MKOSTEMP
fd = mkostemp (template, O_CLOEXEC);
#else
fd = mkstemp (template);
#endif
if (fd != -1)
fcntl (fd, F_SETFD, FD_CLOEXEC);
return fd;
}
int vlc_memfd (void)
{
int fd;
#ifdef O_TMPFILE
fd = vlc_open ("/tmp", O_RDWR|O_TMPFILE, S_IRUSR|S_IWUSR);
if (fd != -1)
return fd;
/* ENOENT means either /tmp is missing (!) or the kernel does not support
* O_TMPFILE. EISDIR means /tmp exists but the kernel does not support
* O_TMPFILE. EOPNOTSUPP means the kernel supports O_TMPFILE but the /tmp
* filesystem does not. Do not fallback on other errors. */
if (errno != ENOENT && errno != EISDIR && errno != EOPNOTSUPP)
return -1;
#endif
char bufpath[] = "/tmp/"PACKAGE_NAME"XXXXXX";
fd = vlc_mkstemp (bufpath);
if (fd != -1)
unlink (bufpath);
return fd;
}
int vlc_mkdir (const char *dirname, mode_t mode)
{
return mkdir (dirname, mode);
}
DIR *vlc_opendir (const char *dirname)
{
return opendir (dirname);
}
const char *vlc_readdir(DIR *dir)
{
struct dirent *ent = readdir (dir);
return (ent != NULL) ? ent->d_name : NULL;
}
int vlc_stat (const char *filename, struct stat *buf)
{
return stat (filename, buf);
}
int vlc_lstat (const char *filename, struct stat *buf)
{
return lstat (filename, buf);
}
int vlc_unlink (const char *filename)
{
return unlink (filename);
}
int vlc_rename (const char *oldpath, const char *newpath)
{
return rename (oldpath, newpath);
}
char *vlc_getcwd (void)
{
long path_max = pathconf (".", _PC_PATH_MAX);
size_t size = (path_max == -1 || path_max > 4096) ? 4096 : path_max;
for (;; size *= 2)
{
char *buf = malloc (size);
if (unlikely(buf == NULL))
break;
if (getcwd (buf, size) != NULL)
return buf;
free (buf);
if (errno != ERANGE)
break;
}
return NULL;
}
int vlc_dup (int oldfd)
{
int newfd;
#ifdef F_DUPFD_CLOEXEC
newfd = fcntl (oldfd, F_DUPFD_CLOEXEC, 0);
if (unlikely(newfd == -1 && errno == EINVAL))
#endif
{
newfd = dup (oldfd);
if (likely(newfd != -1))
fcntl (newfd, F_SETFD, FD_CLOEXEC);
}
return newfd;
}
int vlc_pipe (int fds[2])
{
#ifdef HAVE_PIPE2
if (pipe2 (fds, O_CLOEXEC) == 0)
return 0;
if (errno != ENOSYS)
return -1;
#endif
if (pipe (fds))
return -1;
fcntl (fds[0], F_SETFD, FD_CLOEXEC);
fcntl (fds[1], F_SETFD, FD_CLOEXEC);
return 0;
}
ssize_t vlc_write(int fd, const void *buf, size_t len)
{
struct iovec iov = { .iov_base = (void *)buf, .iov_len = len };
return vlc_writev(fd, &iov, 1);
}
ssize_t vlc_writev(int fd, const struct iovec *iov, int count)
{
sigset_t set, oset;
sigemptyset(&set);
sigaddset(&set, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &set, &oset);
ssize_t val = writev(fd, iov, count);
if (val < 0 && errno == EPIPE)
{
#if (_POSIX_REALTIME_SIGNALS > 0)
siginfo_t info;
struct timespec ts = { 0, 0 };
while (sigtimedwait(&set, &info, &ts) >= 0 || errno != EAGAIN);
#else
for (;;)
{
sigset_t s;
int num;
sigpending(&s);
if (!sigismember(&s, SIGPIPE))
break;
sigwait(&set, &num);
assert(num == SIGPIPE);
}
#endif
}
if (!sigismember(&oset, SIGPIPE)) /* Restore the signal mask if changed */
pthread_sigmask(SIG_SETMASK, &oset, NULL);
return val;
}
#include <vlc_network.h>
/**
* Creates a socket file descriptor. The new file descriptor has the
* close-on-exec flag set.
* @param pf protocol family
* @param type socket type
* @param proto network protocol
* @param nonblock true to create a non-blocking socket
* @return a new file descriptor or -1
*/
int vlc_socket (int pf, int type, int proto, bool nonblock)
{
int fd;
#ifdef SOCK_CLOEXEC
type |= SOCK_CLOEXEC;
if (nonblock)
type |= SOCK_NONBLOCK;
fd = socket (pf, type, proto);
if (fd != -1 || errno != EINVAL)
return fd;
type &= ~(SOCK_CLOEXEC|SOCK_NONBLOCK);
#endif
fd = socket (pf, type, proto);
if (fd == -1)
return -1;
fcntl (fd, F_SETFD, FD_CLOEXEC);
if (nonblock)
fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
#ifdef SO_NOSIGPIPE
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &(int){ 1 }, sizeof (int));
#endif
return fd;
}
/**
* Accepts an inbound connection request on a listening socket.
* The new file descriptor has the close-on-exec flag set.
* @param lfd listening socket file descriptor
* @param addr pointer to the peer address or NULL [OUT]
* @param alen pointer to the length of the peer address or NULL [OUT]
* @param nonblock whether to put the new socket in non-blocking mode
* @return a new file descriptor, or -1 on error.
*/
int vlc_accept (int lfd, struct sockaddr *addr, socklen_t *alen, bool nonblock)
{
int fd;
#ifdef HAVE_ACCEPT4
int flags = SOCK_CLOEXEC;
if (nonblock)
flags |= SOCK_NONBLOCK;
do
fd = accept4 (lfd, addr, alen, flags);
while (fd == -1 && errno == EINTR);
# ifdef SO_NOSIGPIPE
if (fd != -1)
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &(int){ 1 }, sizeof (int));
# endif
if (fd != -1 || errno != ENOSYS)
return fd;
#endif
do
fd = accept (lfd, addr, alen);
while (fd == -1 && errno == EINTR);
if (fd != -1)
{
fcntl (fd, F_SETFD, FD_CLOEXEC);
if (nonblock)
fcntl (fd, F_SETFL, fcntl (fd, F_GETFL, 0) | O_NONBLOCK);
#ifdef SO_NOSIGPIPE
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &(int){ 1 }, sizeof (int));
#endif
}
return fd;
}
| platux/vlc | src/posix/filesystem.c | C | gpl-2.0 | 8,407 |
/*
* linux/arch/arm/mach-omap2/usb-musb.c
*
* This file will contain the board specific details for the
* MENTOR USB OTG controller on OMAP3430
*
* Copyright (C) 2007-2008 Texas Instruments
* Copyright (C) 2008 Nokia Corporation
* Author: Vikram Pandita
*
* Generalization by:
* Felipe Balbi <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <linux/usb/musb.h>
#include <mach/hardware.h>
#include <mach/irqs.h>
#include <mach/am35xx.h>
#include <plat/usb.h>
#include <plat/omap_device.h>
#include "mux.h"
static struct musb_hdrc_config musb_config = {
.multipoint = 1,
.dyn_fifo = 1,
.num_eps = 16,
.ram_bits = 12,
};
static struct musb_hdrc_platform_data musb_plat = {
#ifdef CONFIG_USB_MUSB_OTG
.mode = MUSB_OTG,
#elif defined(CONFIG_USB_MUSB_HDRC_HCD)
.mode = MUSB_HOST,
#elif defined(CONFIG_USB_GADGET_MUSB_HDRC)
.mode = MUSB_PERIPHERAL,
#endif
/* .clock is set dynamically */
.config = &musb_config,
/* REVISIT charge pump on TWL4030 can supply up to
* 100 mA ... but this value is board-specific, like
* "mode", and should be passed to usb_musb_init().
*/
.power = 50, /* up to 100 mA */
};
static u64 musb_dmamask = DMA_BIT_MASK(32);
static struct omap_musb_board_data musb_default_board_data = {
.interface_type = MUSB_INTERFACE_ULPI,
.mode = MUSB_OTG,
.power = 100,
};
void __init usb_musb_init(struct omap_musb_board_data *musb_board_data)
{
struct omap_hwmod *oh;
struct platform_device *pdev;
struct device *dev;
int bus_id = -1;
const char *oh_name, *name;
struct omap_musb_board_data *board_data;
if (musb_board_data)
board_data = musb_board_data;
else
board_data = &musb_default_board_data;
/*
* REVISIT: This line can be removed once all the platforms using
* musb_core.c have been converted to use use clkdev.
*/
musb_plat.clock = "ick";
musb_plat.board_data = board_data;
musb_plat.power = board_data->power >> 1;
musb_plat.mode = board_data->mode;
musb_plat.extvbus = board_data->extvbus;
if (cpu_is_omap3517() || cpu_is_omap3505()) {
oh_name = "am35x_otg_hs";
name = "musb-am35x";
} else if (cpu_is_ti81xx()) {
oh_name = "usb_otg_hs";
name = "musb-ti81xx";
} else {
oh_name = "usb_otg_hs";
name = "musb-omap2430";
}
oh = omap_hwmod_lookup(oh_name);
if (WARN(!oh, "%s: could not find omap_hwmod for %s\n",
__func__, oh_name))
return;
pdev = omap_device_build(name, bus_id, oh, &musb_plat,
sizeof(musb_plat), NULL, 0, false);
if (IS_ERR(pdev)) {
pr_err("Could not build omap_device for %s %s\n",
name, oh_name);
return;
}
dev = &pdev->dev;
get_device(dev);
dev->dma_mask = &musb_dmamask;
dev->coherent_dma_mask = musb_dmamask;
put_device(dev);
}
| bsmitty83/kernel_omap | arch/arm/mach-omap2/usb-musb.c | C | gpl-2.0 | 3,112 |
/*
* Handle incoming frames
* Linux ethernet bridge
*
* Authors:
* Lennert Buytenhek <[email protected]>
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/netfilter_bridge.h>
#include "br_private.h"
static int br_pass_frame_up(struct sk_buff *skb)
{
struct net_device *indev, *brdev = BR_INPUT_SKB_CB(skb)->brdev;
brdev->stats.rx_packets++;
brdev->stats.rx_bytes += skb->len;
indev = skb->dev;
skb->dev = brdev;
return NF_HOOK(PF_BRIDGE, NF_BR_LOCAL_IN, skb, indev, NULL,
netif_receive_skb);
}
/* note: already called with rcu_read_lock (preempt_disabled) */
int br_handle_frame_finish(struct sk_buff *skb)
{
const unsigned char *dest = eth_hdr(skb)->h_dest;
struct net_bridge_port *p = rcu_dereference(skb->dev->br_port);
struct net_bridge *br;
struct net_bridge_fdb_entry *dst;
struct net_bridge_mdb_entry *mdst;
struct sk_buff *skb2;
if (!p || p->state == BR_STATE_DISABLED)
goto drop;
/* insert into forwarding database after filtering to avoid spoofing */
br = p->br;
br_fdb_update(br, p, eth_hdr(skb)->h_source);
if (!is_broadcast_ether_addr(dest) && is_multicast_ether_addr(dest) &&
br_multicast_rcv(br, p, skb))
goto drop;
if (p->state == BR_STATE_LEARNING)
goto drop;
BR_INPUT_SKB_CB(skb)->brdev = br->dev;
/* The packet skb2 goes to the local host (NULL to skip). */
skb2 = NULL;
if (br->dev->flags & IFF_PROMISC)
skb2 = skb;
dst = NULL;
if (is_broadcast_ether_addr(dest))
skb2 = skb;
else if (is_multicast_ether_addr(dest)) {
mdst = br_mdb_get(br, skb);
if (mdst || BR_INPUT_SKB_CB(skb)->mrouters_only) {
if ((mdst && mdst->mglist) ||
br_multicast_is_router(br))
skb2 = skb;
br_multicast_forward(mdst, skb, skb2);
skb = NULL;
if (!skb2)
goto out;
} else
skb2 = skb;
br->dev->stats.multicast++;
} else if ((dst = __br_fdb_get(br, dest)) && dst->is_local) {
skb2 = skb;
/* Do not forward the packet since it's local. */
skb = NULL;
}
if (skb) {
if (dst)
br_forward(dst->dst, skb, skb2);
else
br_flood_forward(br, skb, skb2);
}
if (skb2)
return br_pass_frame_up(skb2);
out:
return 0;
drop:
kfree_skb(skb);
goto out;
}
/* note: already called with rcu_read_lock (preempt_disabled) */
static int br_handle_local_finish(struct sk_buff *skb)
{
struct net_bridge_port *p = rcu_dereference(skb->dev->br_port);
if (p)
br_fdb_update(p->br, p, eth_hdr(skb)->h_source);
return 0; /* process further */
}
/*
* Called via br_handle_frame_hook.
* Return NULL if skb is handled
* note: already called with rcu_read_lock (preempt_disabled)
*/
struct sk_buff *br_handle_frame(struct net_bridge_port *p, struct sk_buff *skb)
{
const unsigned char *dest = eth_hdr(skb)->h_dest;
int (*rhook)(struct sk_buff *skb);
if (!is_valid_ether_addr(eth_hdr(skb)->h_source))
goto drop;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
return NULL;
if (unlikely(is_link_local_ether_addr(dest))) {
/* Pause frames shouldn't be passed up by driver anyway */
if (skb->protocol == htons(ETH_P_PAUSE))
goto drop;
/* If STP is turned off, then forward */
if (p->br->stp_enabled == BR_NO_STP && dest[5] == 0)
goto forward;
if (NF_HOOK(PF_BRIDGE, NF_BR_LOCAL_IN, skb, skb->dev,
NULL, br_handle_local_finish))
return NULL; /* frame consumed by filter */
else
return skb; /* continue processing */
}
forward:
switch (p->state) {
case BR_STATE_FORWARDING:
rhook = rcu_dereference(br_should_route_hook);
if (rhook != NULL) {
if (rhook(skb))
return skb;
dest = eth_hdr(skb)->h_dest;
}
/* fall through */
case BR_STATE_LEARNING:
if (!compare_ether_addr(p->br->dev->dev_addr, dest))
skb->pkt_type = PACKET_HOST;
NF_HOOK(PF_BRIDGE, NF_BR_PRE_ROUTING, skb, skb->dev, NULL,
br_handle_frame_finish);
break;
default:
drop:
kfree_skb(skb);
}
return NULL;
}
| is00hcw/fastsocket | kernel/net/bridge/br_input.c | C | gpl-2.0 | 4,161 |
/* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* 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.
*/
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/slimbus/slimbus.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/clk.h>
#include <linux/pm_runtime.h>
#include <linux/of.h>
#include <linux/of_slimbus.h>
#include <linux/timer.h>
#include <linux/msm-sps.h>
#include "slim-msm.h"
#define NGD_SLIM_NAME "ngd_msm_ctrl"
#define SLIM_LA_MGR 0xFF
#define SLIM_ROOT_FREQ 24576000
#define LADDR_RETRY 5
#define NGD_BASE_V1(r) (((r) % 2) ? 0x800 : 0xA00)
#define NGD_BASE_V2(r) (((r) % 2) ? 0x1000 : 0x2000)
#define NGD_BASE(r, v) ((v) ? NGD_BASE_V2(r) : NGD_BASE_V1(r))
/* NGD (Non-ported Generic Device) registers */
enum ngd_reg {
NGD_CFG = 0x0,
NGD_STATUS = 0x4,
NGD_RX_MSGQ_CFG = 0x8,
NGD_INT_EN = 0x10,
NGD_INT_STAT = 0x14,
NGD_INT_CLR = 0x18,
NGD_TX_MSG = 0x30,
NGD_RX_MSG = 0x70,
NGD_IE_STAT = 0xF0,
NGD_VE_STAT = 0x100,
};
enum ngd_msg_cfg {
NGD_CFG_ENABLE = 1,
NGD_CFG_RX_MSGQ_EN = 1 << 1,
NGD_CFG_TX_MSGQ_EN = 1 << 2,
};
enum ngd_intr {
NGD_INT_RECFG_DONE = 1 << 24,
NGD_INT_TX_NACKED_2 = 1 << 25,
NGD_INT_MSG_BUF_CONTE = 1 << 26,
NGD_INT_MSG_TX_INVAL = 1 << 27,
NGD_INT_IE_VE_CHG = 1 << 28,
NGD_INT_DEV_ERR = 1 << 29,
NGD_INT_RX_MSG_RCVD = 1 << 30,
NGD_INT_TX_MSG_SENT = 1 << 31,
};
enum ngd_offsets {
NGD_NACKED_MC = 0x7F00000,
NGD_ACKED_MC = 0xFE000,
NGD_ERROR = 0x1800,
NGD_MSGQ_SUPPORT = 0x400,
NGD_RX_MSGQ_TIME_OUT = 0x16,
NGD_ENUMERATED = 0x1,
NGD_TX_BUSY = 0x0,
};
enum ngd_status {
NGD_LADDR = 1 << 1,
};
static int ngd_slim_runtime_resume(struct device *device);
static int ngd_slim_power_up(struct msm_slim_ctrl *dev, bool mdm_restart);
static irqreturn_t ngd_slim_interrupt(int irq, void *d)
{
struct msm_slim_ctrl *dev = (struct msm_slim_ctrl *)d;
void __iomem *ngd = dev->base + NGD_BASE(dev->ctrl.nr, dev->ver);
u32 stat = readl_relaxed(ngd + NGD_INT_STAT);
u32 pstat;
if ((stat & NGD_INT_MSG_BUF_CONTE) ||
(stat & NGD_INT_MSG_TX_INVAL) || (stat & NGD_INT_DEV_ERR) ||
(stat & NGD_INT_TX_NACKED_2)) {
writel_relaxed(stat, ngd + NGD_INT_CLR);
dev->err = -EIO;
SLIM_WARN(dev, "NGD interrupt error:0x%x, err:%d\n", stat,
dev->err);
/* Guarantee that error interrupts are cleared */
mb();
if (dev->wr_comp)
complete(dev->wr_comp);
} else if (stat & NGD_INT_TX_MSG_SENT) {
writel_relaxed(NGD_INT_TX_MSG_SENT, ngd + NGD_INT_CLR);
/* Make sure interrupt is cleared */
mb();
if (dev->wr_comp)
complete(dev->wr_comp);
}
if (stat & NGD_INT_RX_MSG_RCVD) {
u32 rx_buf[10];
u8 len, i;
rx_buf[0] = readl_relaxed(ngd + NGD_RX_MSG);
len = rx_buf[0] & 0x1F;
for (i = 1; i < ((len + 3) >> 2); i++) {
rx_buf[i] = readl_relaxed(ngd + NGD_RX_MSG +
(4 * i));
SLIM_DBG(dev, "REG-RX data: %x\n", rx_buf[i]);
}
msm_slim_rx_enqueue(dev, rx_buf, len);
writel_relaxed(NGD_INT_RX_MSG_RCVD,
ngd + NGD_INT_CLR);
/*
* Guarantee that CLR bit write goes through before
* queuing work
*/
mb();
if (dev->use_rx_msgqs == MSM_MSGQ_ENABLED)
SLIM_WARN(dev, "direct msg rcvd with RX MSGQs\n");
else
complete(&dev->rx_msgq_notify);
}
if (stat & NGD_INT_RECFG_DONE) {
writel_relaxed(NGD_INT_RECFG_DONE, ngd + NGD_INT_CLR);
/* Guarantee RECONFIG DONE interrupt is cleared */
mb();
/* In satellite mode, just log the reconfig done IRQ */
SLIM_DBG(dev, "reconfig done IRQ for NGD\n");
}
if (stat & NGD_INT_IE_VE_CHG) {
writel_relaxed(NGD_INT_IE_VE_CHG, ngd + NGD_INT_CLR);
/* Guarantee IE VE change interrupt is cleared */
mb();
SLIM_DBG(dev, "NGD IE VE change\n");
}
pstat = readl_relaxed(PGD_THIS_EE(PGD_PORT_INT_ST_EEn, dev->ver));
if (pstat != 0)
return msm_slim_port_irq_handler(dev, pstat);
return IRQ_HANDLED;
}
static int ngd_qmi_available(struct notifier_block *n, unsigned long code,
void *_cmd)
{
struct msm_slim_qmi *qmi = container_of(n, struct msm_slim_qmi, nb);
struct msm_slim_ctrl *dev =
container_of(qmi, struct msm_slim_ctrl, qmi);
SLIM_INFO(dev, "Slimbus QMI NGD CB received event:%ld\n", code);
switch (code) {
case QMI_SERVER_ARRIVE:
schedule_work(&qmi->ssr_up);
break;
case QMI_SERVER_EXIT:
dev->state = MSM_CTRL_DOWN;
/* make sure autosuspend is not called until ADSP comes up*/
pm_runtime_get_noresume(dev->dev);
/* Reset ctrl_up completion */
init_completion(&dev->ctrl_up);
schedule_work(&qmi->ssr_down);
break;
default:
break;
}
return 0;
}
static int mdm_ssr_notify_cb(struct notifier_block *n, unsigned long code,
void *_cmd)
{
void __iomem *ngd;
struct msm_slim_mdm *mdm = container_of(n, struct msm_slim_mdm, nb);
struct msm_slim_ctrl *dev = container_of(mdm, struct msm_slim_ctrl,
mdm);
struct slim_controller *ctrl = &dev->ctrl;
u32 laddr;
struct slim_device *sbdev;
switch (code) {
case SUBSYS_BEFORE_SHUTDOWN:
SLIM_INFO(dev, "SLIM %lu external_modem SSR notify cb\n", code);
/* vote for runtime-pm so that ADSP doesn't go down */
msm_slim_get_ctrl(dev);
/*
* checking framer here will wake-up ADSP and may avoid framer
* handover later
*/
msm_slim_qmi_check_framer_request(dev);
dev->mdm.state = MSM_CTRL_DOWN;
msm_slim_put_ctrl(dev);
break;
case SUBSYS_AFTER_POWERUP:
if (dev->mdm.state != MSM_CTRL_DOWN)
return NOTIFY_DONE;
SLIM_INFO(dev,
"SLIM %lu external_modem SSR notify cb\n", code);
/* vote for runtime-pm so that ADSP doesn't go down */
msm_slim_get_ctrl(dev);
msm_slim_qmi_check_framer_request(dev);
/* If NGD enumeration is lost, we will need to power us up */
ngd = dev->base + NGD_BASE(dev->ctrl.nr, dev->ver);
laddr = readl_relaxed(ngd + NGD_STATUS);
if (!(laddr & NGD_LADDR)) {
/* runtime-pm state should be consistent with HW */
pm_runtime_disable(dev->dev);
pm_runtime_set_suspended(dev->dev);
dev->state = MSM_CTRL_DOWN;
SLIM_INFO(dev,
"SLIM MDM SSR (active framer on MDM) dev-down\n");
list_for_each_entry(sbdev, &ctrl->devs, dev_list)
slim_report_absent(sbdev);
ngd_slim_power_up(dev, true);
pm_runtime_set_active(dev->dev);
pm_runtime_enable(dev->dev);
}
dev->mdm.state = MSM_CTRL_AWAKE;
msm_slim_put_ctrl(dev);
break;
default:
break;
}
return NOTIFY_DONE;
}
static int ngd_get_tid(struct slim_controller *ctrl, struct slim_msg_txn *txn,
u8 *tid, struct completion *done)
{
struct msm_slim_ctrl *dev = slim_get_ctrldata(ctrl);
mutex_lock(&ctrl->m_ctrl);
if (ctrl->last_tid <= 255) {
ctrl->txnt = krealloc(ctrl->txnt,
(ctrl->last_tid + 1) *
sizeof(struct slim_msg_txn *),
GFP_KERNEL);
if (!ctrl->txnt) {
mutex_unlock(&ctrl->m_ctrl);
return -ENOMEM;
}
dev->msg_cnt = ctrl->last_tid;
ctrl->last_tid++;
} else {
int i;
for (i = 0; i < 256; i++) {
dev->msg_cnt = ((dev->msg_cnt + 1) & 0xFF);
if (ctrl->txnt[dev->msg_cnt] == NULL)
break;
}
if (i >= 256) {
dev_err(&ctrl->dev, "out of TID");
mutex_unlock(&ctrl->m_ctrl);
return -ENOMEM;
}
}
ctrl->txnt[dev->msg_cnt] = txn;
txn->tid = dev->msg_cnt;
txn->comp = done;
*tid = dev->msg_cnt;
mutex_unlock(&ctrl->m_ctrl);
return 0;
}
static int ngd_xfer_msg(struct slim_controller *ctrl, struct slim_msg_txn *txn)
{
DECLARE_COMPLETION_ONSTACK(done);
DECLARE_COMPLETION_ONSTACK(tx_sent);
struct msm_slim_ctrl *dev = slim_get_ctrldata(ctrl);
u32 *pbuf;
u8 *puc;
int ret = 0;
u8 la = txn->la;
u8 txn_mt;
u16 txn_mc = txn->mc;
u8 wbuf[SLIM_MSGQ_BUF_LEN];
bool report_sat = false;
if (txn->mc == SLIM_USR_MC_REPORT_SATELLITE &&
txn->mt == SLIM_MSG_MT_SRC_REFERRED_USER)
report_sat = true;
if (!pm_runtime_enabled(dev->dev) && dev->state == MSM_CTRL_ASLEEP &&
report_sat == false) {
/*
* Counter-part of system-suspend when runtime-pm is not enabled
* This way, resume can be left empty and device will be put in
* active mode only if client requests anything on the bus
* If the state was DOWN, SSR UP notification will take
* care of putting the device in active state.
*/
ret = ngd_slim_runtime_resume(dev->dev);
if (ret) {
SLIM_ERR(dev, "slim resume failed ret:%d, state:%d",
ret, dev->state);
return -EREMOTEIO;
}
}
else if (txn->mc & SLIM_MSG_CLK_PAUSE_SEQ_FLG)
return -EPROTONOSUPPORT;
if (txn->mt == SLIM_MSG_MT_CORE &&
(txn->mc >= SLIM_MSG_MC_BEGIN_RECONFIGURATION &&
txn->mc <= SLIM_MSG_MC_RECONFIGURE_NOW)) {
return 0;
}
/* If txn is tried when controller is down, wait for ADSP to boot */
if (!report_sat) {
if (dev->state == MSM_CTRL_DOWN) {
u8 mc = (u8)txn->mc;
int timeout;
SLIM_INFO(dev, "ADSP slimbus not up yet\n");
/*
* Messages related to data channel management can't
* wait since they are holding reconfiguration lock.
* clk_pause in resume (which can change state back to
* MSM_CTRL_AWAKE), will need that lock.
* Port disconnection, channel removal calls should pass
* through since there is no activity on the bus and
* those calls are triggered by clients due to
* device_down callback in that situation.
* Returning 0 on the disconnections and
* removals will ensure consistent state of channels,
* ports with the HW
* Remote requests to remove channel/port will be
* returned from the path where they wait on
* acknowledgement from ADSP
*/
if ((txn->mt == SLIM_MSG_MT_DEST_REFERRED_USER) &&
((mc == SLIM_USR_MC_CHAN_CTRL ||
mc == SLIM_USR_MC_DISCONNECT_PORT ||
mc == SLIM_USR_MC_RECONFIG_NOW)))
return -EREMOTEIO;
if ((txn->mt == SLIM_MSG_MT_CORE) &&
((mc == SLIM_MSG_MC_DISCONNECT_PORT ||
mc == SLIM_MSG_MC_NEXT_REMOVE_CHANNEL ||
mc == SLIM_USR_MC_RECONFIG_NOW)))
return 0;
if ((txn->mt == SLIM_MSG_MT_CORE) &&
((mc >= SLIM_MSG_MC_CONNECT_SOURCE &&
mc <= SLIM_MSG_MC_CHANGE_CONTENT) ||
(mc >= SLIM_MSG_MC_BEGIN_RECONFIGURATION &&
mc <= SLIM_MSG_MC_RECONFIGURE_NOW)))
return -EREMOTEIO;
if ((txn->mt == SLIM_MSG_MT_DEST_REFERRED_USER) &&
((mc >= SLIM_USR_MC_DEFINE_CHAN &&
mc < SLIM_USR_MC_DISCONNECT_PORT)))
return -EREMOTEIO;
timeout = wait_for_completion_timeout(&dev->ctrl_up,
HZ);
if (!timeout && dev->state == MSM_CTRL_DOWN)
return -ETIMEDOUT;
}
ret = msm_slim_get_ctrl(dev);
/*
* Runtime-pm's callbacks are not called until runtime-pm's
* error status is cleared
* Setting runtime status to suspended clears the error
* It also makes HW status cosistent with what SW has it here
*/
if (ret < 0) {
SLIM_ERR(dev, "slim ctrl vote failed ret:%d, state:%d",
ret, dev->state);
pm_runtime_set_suspended(dev->dev);
msm_slim_put_ctrl(dev);
return -EREMOTEIO;
} else {
dev->state = MSM_CTRL_AWAKE;
}
}
mutex_lock(&dev->tx_lock);
if (txn->mt == SLIM_MSG_MT_CORE &&
(txn->mc == SLIM_MSG_MC_CONNECT_SOURCE ||
txn->mc == SLIM_MSG_MC_CONNECT_SINK ||
txn->mc == SLIM_MSG_MC_DISCONNECT_PORT)) {
int i = 0;
if (txn->mc != SLIM_MSG_MC_DISCONNECT_PORT)
SLIM_INFO(dev,
"Connect port: laddr 0x%x port_num %d chan_num %d\n",
txn->la, txn->wbuf[0], txn->wbuf[1]);
else
SLIM_INFO(dev,
"Disconnect port: laddr 0x%x port_num %d\n",
txn->la, txn->wbuf[0]);
txn->mt = SLIM_MSG_MT_DEST_REFERRED_USER;
if (txn->mc == SLIM_MSG_MC_CONNECT_SOURCE)
txn->mc = SLIM_USR_MC_CONNECT_SRC;
else if (txn->mc == SLIM_MSG_MC_CONNECT_SINK)
txn->mc = SLIM_USR_MC_CONNECT_SINK;
else if (txn->mc == SLIM_MSG_MC_DISCONNECT_PORT)
txn->mc = SLIM_USR_MC_DISCONNECT_PORT;
if (txn->la == SLIM_LA_MGR) {
if (dev->pgdla == SLIM_LA_MGR) {
u8 ea[] = {0, QC_DEVID_PGD, 0, 0, QC_MFGID_MSB,
QC_MFGID_LSB};
ea[2] = (u8)(dev->pdata.eapc & 0xFF);
ea[3] = (u8)((dev->pdata.eapc & 0xFF00) >> 8);
mutex_unlock(&dev->tx_lock);
ret = dev->ctrl.get_laddr(&dev->ctrl, ea, 6,
&dev->pgdla);
SLIM_DBG(dev, "SLIM PGD LA:0x%x, ret:%d\n",
dev->pgdla, ret);
if (ret) {
SLIM_ERR(dev,
"Incorrect SLIM-PGD EAPC:0x%x\n",
dev->pdata.eapc);
return ret;
}
mutex_lock(&dev->tx_lock);
}
txn->la = dev->pgdla;
}
wbuf[i++] = txn->la;
la = SLIM_LA_MGR;
wbuf[i++] = txn->wbuf[0];
if (txn->mc != SLIM_USR_MC_DISCONNECT_PORT)
wbuf[i++] = txn->wbuf[1];
ret = ngd_get_tid(ctrl, txn, &wbuf[i++], &done);
if (ret) {
SLIM_ERR(dev, "TID for connect/disconnect fail:%d\n",
ret);
goto ngd_xfer_err;
}
txn->len = i;
txn->wbuf = wbuf;
txn->rl = txn->len + 4;
}
txn->rl--;
pbuf = msm_get_msg_buf(dev, txn->rl);
if (!pbuf) {
SLIM_ERR(dev, "Message buffer unavailable\n");
ret = -ENOMEM;
goto ngd_xfer_err;
}
dev->err = 0;
if (txn->dt == SLIM_MSG_DEST_ENUMADDR) {
ret = -EPROTONOSUPPORT;
goto ngd_xfer_err;
}
if (txn->dt == SLIM_MSG_DEST_LOGICALADDR)
*pbuf = SLIM_MSG_ASM_FIRST_WORD(txn->rl, txn->mt, txn->mc, 0,
la);
else
*pbuf = SLIM_MSG_ASM_FIRST_WORD(txn->rl, txn->mt, txn->mc, 1,
la);
if (txn->dt == SLIM_MSG_DEST_LOGICALADDR)
puc = ((u8 *)pbuf) + 3;
else
puc = ((u8 *)pbuf) + 2;
if (txn->rbuf)
*(puc++) = txn->tid;
if (((txn->mt == SLIM_MSG_MT_CORE) &&
((txn->mc >= SLIM_MSG_MC_REQUEST_INFORMATION &&
txn->mc <= SLIM_MSG_MC_REPORT_INFORMATION) ||
(txn->mc >= SLIM_MSG_MC_REQUEST_VALUE &&
txn->mc <= SLIM_MSG_MC_CHANGE_VALUE))) ||
(txn->mc == SLIM_USR_MC_REPEAT_CHANGE_VALUE &&
txn->mt == SLIM_MSG_MT_DEST_REFERRED_USER)) {
*(puc++) = (txn->ec & 0xFF);
*(puc++) = (txn->ec >> 8)&0xFF;
}
if (txn->wbuf)
memcpy(puc, txn->wbuf, txn->len);
if (txn->mt == SLIM_MSG_MT_DEST_REFERRED_USER &&
(txn->mc == SLIM_USR_MC_CONNECT_SRC ||
txn->mc == SLIM_USR_MC_CONNECT_SINK ||
txn->mc == SLIM_USR_MC_DISCONNECT_PORT) && txn->wbuf &&
wbuf[0] == dev->pgdla) {
if (txn->mc != SLIM_USR_MC_DISCONNECT_PORT)
dev->err = msm_slim_connect_pipe_port(dev, wbuf[1]);
else {
/*
* Remove channel disconnects master-side ports from
* channel. No need to send that again on the bus
* Only disable port
*/
writel_relaxed(0, PGD_PORT(PGD_PORT_CFGn,
(wbuf[1] + dev->port_b), dev->ver));
mutex_unlock(&dev->tx_lock);
msm_slim_put_ctrl(dev);
return 0;
}
if (dev->err) {
SLIM_ERR(dev, "pipe-port connect err:%d\n", dev->err);
goto ngd_xfer_err;
}
/* Add port-base to port number if this is manager side port */
puc[1] += dev->port_b;
}
dev->err = 0;
/*
* If it's a read txn, it may be freed if a response is received by
* received thread before reaching end of this function.
* mc, mt may have changed to convert standard slimbus code/type to
* satellite user-defined message. Reinitialize again
*/
txn_mc = txn->mc;
txn_mt = txn->mt;
dev->wr_comp = &tx_sent;
ret = msm_send_msg_buf(dev, pbuf, txn->rl,
NGD_BASE(dev->ctrl.nr, dev->ver) + NGD_TX_MSG);
if (!ret) {
int timeout = wait_for_completion_timeout(&tx_sent, HZ);
if (!timeout) {
ret = -ETIMEDOUT;
/*
* disconnect/recoonect pipe so that subsequent
* transactions don't timeout due to unavailable
* descriptors
*/
msm_slim_disconnect_endp(dev, &dev->tx_msgq,
&dev->use_tx_msgqs);
msm_slim_connect_endp(dev, &dev->tx_msgq, NULL);
} else {
ret = dev->err;
}
}
dev->wr_comp = NULL;
if (ret) {
u32 conf, stat, rx_msgq, int_stat, int_en, int_clr;
void __iomem *ngd = dev->base + NGD_BASE(dev->ctrl.nr,
dev->ver);
SLIM_WARN(dev, "TX failed :MC:0x%x,mt:0x%x, ret:%d, ver:%d\n",
txn_mc, txn_mt, ret, dev->ver);
conf = readl_relaxed(ngd);
stat = readl_relaxed(ngd + NGD_STATUS);
rx_msgq = readl_relaxed(ngd + NGD_RX_MSGQ_CFG);
int_stat = readl_relaxed(ngd + NGD_INT_STAT);
int_en = readl_relaxed(ngd + NGD_INT_EN);
int_clr = readl_relaxed(ngd + NGD_INT_CLR);
SLIM_WARN(dev, "conf:0x%x,stat:0x%x,rxmsgq:0x%x\n",
conf, stat, rx_msgq);
SLIM_WARN(dev, "int_stat:0x%x,int_en:0x%x,int_cll:0x%x\n",
int_stat, int_en, int_clr);
} else if (txn_mt == SLIM_MSG_MT_DEST_REFERRED_USER &&
(txn_mc == SLIM_USR_MC_CONNECT_SRC ||
txn_mc == SLIM_USR_MC_CONNECT_SINK ||
txn_mc == SLIM_USR_MC_DISCONNECT_PORT)) {
int timeout;
mutex_unlock(&dev->tx_lock);
msm_slim_put_ctrl(dev);
timeout = wait_for_completion_timeout(txn->comp, HZ);
if (!timeout)
ret = -ETIMEDOUT;
else
ret = txn->ec;
if (ret) {
SLIM_INFO(dev,
"connect/disconnect:0x%x,tid:%d err:%d\n",
txn->mc, txn->tid, ret);
mutex_lock(&ctrl->m_ctrl);
ctrl->txnt[txn->tid] = NULL;
mutex_unlock(&ctrl->m_ctrl);
}
return ret ? ret : dev->err;
}
ngd_xfer_err:
mutex_unlock(&dev->tx_lock);
if (!report_sat)
msm_slim_put_ctrl(dev);
return ret ? ret : dev->err;
}
static int ngd_user_msg(struct slim_controller *ctrl, u8 la, u8 mt, u8 mc,
struct slim_ele_access *msg, u8 *buf, u8 len)
{
struct slim_msg_txn txn;
if (mt != SLIM_MSG_MT_DEST_REFERRED_USER ||
mc != SLIM_USR_MC_REPEAT_CHANGE_VALUE) {
return -EPROTONOSUPPORT;
}
if (len > SLIM_MAX_VE_SLC_BYTES ||
msg->start_offset > MSM_SLIM_VE_MAX_MAP_ADDR)
return -EINVAL;
if (len <= 4) {
txn.ec = len - 1;
} else if (len <= 8) {
if (len & 0x1)
return -EINVAL;
txn.ec = ((len >> 1) + 1);
} else {
if (len & 0x3)
return -EINVAL;
txn.ec = ((len >> 2) + 3);
}
txn.ec |= (0x8 | ((msg->start_offset & 0xF) << 4));
txn.ec |= ((msg->start_offset & 0xFF0) << 4);
txn.la = la;
txn.mt = mt;
txn.mc = mc;
txn.dt = SLIM_MSG_DEST_LOGICALADDR;
txn.len = len;
txn.rl = len + 6;
txn.wbuf = buf;
txn.rbuf = NULL;
txn.comp = msg->comp;
return ngd_xfer_msg(ctrl, &txn);
}
static int ngd_xferandwait_ack(struct slim_controller *ctrl,
struct slim_msg_txn *txn)
{
struct msm_slim_ctrl *dev = slim_get_ctrldata(ctrl);
int ret = ngd_xfer_msg(ctrl, txn);
if (!ret) {
int timeout;
timeout = wait_for_completion_timeout(txn->comp, HZ);
if (!timeout)
ret = -ETIMEDOUT;
else
ret = txn->ec;
}
if (ret) {
if (ret != -EREMOTEIO || txn->mc != SLIM_USR_MC_CHAN_CTRL)
SLIM_ERR(dev, "master msg:0x%x,tid:%d ret:%d\n",
txn->mc, txn->tid, ret);
mutex_lock(&ctrl->m_ctrl);
ctrl->txnt[txn->tid] = NULL;
mutex_unlock(&ctrl->m_ctrl);
}
return ret;
}
static int ngd_allocbw(struct slim_device *sb, int *subfrmc, int *clkgear)
{
int ret = 0, num_chan = 0;
struct slim_pending_ch *pch;
struct slim_msg_txn txn;
struct slim_controller *ctrl = sb->ctrl;
DECLARE_COMPLETION_ONSTACK(done);
u8 wbuf[SLIM_MSGQ_BUF_LEN];
struct msm_slim_ctrl *dev = slim_get_ctrldata(ctrl);
*clkgear = ctrl->clkgear;
*subfrmc = 0;
txn.mt = SLIM_MSG_MT_DEST_REFERRED_USER;
txn.dt = SLIM_MSG_DEST_LOGICALADDR;
txn.la = SLIM_LA_MGR;
txn.len = 0;
txn.ec = 0;
txn.wbuf = wbuf;
txn.rbuf = NULL;
if (ctrl->sched.msgsl != ctrl->sched.pending_msgsl) {
SLIM_DBG(dev, "slim reserve BW for messaging: req: %d\n",
ctrl->sched.pending_msgsl);
txn.mc = SLIM_USR_MC_REQ_BW;
wbuf[txn.len++] = ((sb->laddr & 0x1f) |
((u8)(ctrl->sched.pending_msgsl & 0x7) << 5));
wbuf[txn.len++] = (u8)(ctrl->sched.pending_msgsl >> 3);
ret = ngd_get_tid(ctrl, &txn, &wbuf[txn.len++], &done);
if (ret)
return ret;
txn.rl = txn.len + 4;
ret = ngd_xferandwait_ack(ctrl, &txn);
if (ret)
return ret;
txn.mc = SLIM_USR_MC_RECONFIG_NOW;
txn.len = 2;
wbuf[1] = sb->laddr;
txn.rl = txn.len + 4;
ret = ngd_get_tid(ctrl, &txn, &wbuf[0], &done);
if (ret)
return ret;
ret = ngd_xferandwait_ack(ctrl, &txn);
if (ret)
return ret;
txn.len = 0;
}
list_for_each_entry(pch, &sb->mark_define, pending) {
struct slim_ich *slc;
slc = &ctrl->chans[pch->chan];
if (!slc) {
SLIM_WARN(dev, "no channel in define?\n");
return -ENXIO;
}
if (txn.len == 0) {
/* Per protocol, only last 5 bits for client no. */
wbuf[txn.len++] = (u8) (slc->prop.dataf << 5) |
(sb->laddr & 0x1f);
wbuf[txn.len] = slc->seglen;
if (slc->coeff == SLIM_COEFF_3)
wbuf[txn.len] |= 1 << 5;
wbuf[txn.len++] |= slc->prop.auxf << 6;
wbuf[txn.len++] = slc->rootexp << 4 | slc->prop.prot;
wbuf[txn.len++] = slc->prrate;
ret = ngd_get_tid(ctrl, &txn, &wbuf[txn.len++], &done);
if (ret) {
SLIM_WARN(dev, "no tid for channel define?\n");
return -ENXIO;
}
}
num_chan++;
wbuf[txn.len++] = slc->chan;
SLIM_INFO(dev, "slim activate chan:%d, laddr: 0x%x\n",
slc->chan, sb->laddr);
}
if (txn.len) {
txn.mc = SLIM_USR_MC_DEF_ACT_CHAN;
txn.rl = txn.len + 4;
ret = ngd_xferandwait_ack(ctrl, &txn);
if (ret)
return ret;
txn.mc = SLIM_USR_MC_RECONFIG_NOW;
txn.len = 2;
wbuf[1] = sb->laddr;
txn.rl = txn.len + 4;
ret = ngd_get_tid(ctrl, &txn, &wbuf[0], &done);
if (ret)
return ret;
ret = ngd_xferandwait_ack(ctrl, &txn);
if (ret)
return ret;
}
txn.len = 0;
list_for_each_entry(pch, &sb->mark_removal, pending) {
struct slim_ich *slc;
slc = &ctrl->chans[pch->chan];
if (!slc) {
SLIM_WARN(dev, "no channel in removal?\n");
return -ENXIO;
}
if (txn.len == 0) {
/* Per protocol, only last 5 bits for client no. */
wbuf[txn.len++] = (u8) (SLIM_CH_REMOVE << 6) |
(sb->laddr & 0x1f);
ret = ngd_get_tid(ctrl, &txn, &wbuf[txn.len++], &done);
if (ret) {
SLIM_WARN(dev, "no tid for channel define?\n");
return -ENXIO;
}
}
wbuf[txn.len++] = slc->chan;
SLIM_INFO(dev, "slim remove chan:%d, laddr: 0x%x\n",
slc->chan, sb->laddr);
}
if (txn.len) {
txn.mc = SLIM_USR_MC_CHAN_CTRL;
txn.rl = txn.len + 4;
ret = ngd_xferandwait_ack(ctrl, &txn);
/* HW restarting, channel removal should succeed */
if (ret == -EREMOTEIO)
return 0;
else if (ret)
return ret;
txn.mc = SLIM_USR_MC_RECONFIG_NOW;
txn.len = 2;
wbuf[1] = sb->laddr;
txn.rl = txn.len + 4;
ret = ngd_get_tid(ctrl, &txn, &wbuf[0], &done);
if (ret)
return ret;
ret = ngd_xferandwait_ack(ctrl, &txn);
if (ret)
return ret;
txn.len = 0;
}
return 0;
}
static int ngd_set_laddr(struct slim_controller *ctrl, const u8 *ea,
u8 elen, u8 laddr)
{
return 0;
}
static int ngd_get_laddr(struct slim_controller *ctrl, const u8 *ea,
u8 elen, u8 *laddr)
{
int ret;
u8 wbuf[10];
struct slim_msg_txn txn;
DECLARE_COMPLETION_ONSTACK(done);
txn.mt = SLIM_MSG_MT_DEST_REFERRED_USER;
txn.dt = SLIM_MSG_DEST_LOGICALADDR;
txn.la = SLIM_LA_MGR;
txn.ec = 0;
ret = ngd_get_tid(ctrl, &txn, &wbuf[0], &done);
if (ret) {
return ret;
}
memcpy(&wbuf[1], ea, elen);
txn.mc = SLIM_USR_MC_ADDR_QUERY;
txn.rl = 11;
txn.len = 7;
txn.wbuf = wbuf;
txn.rbuf = NULL;
ret = ngd_xferandwait_ack(ctrl, &txn);
if (!ret && txn.la == 0xFF)
ret = -ENXIO;
else if (!ret)
*laddr = txn.la;
return ret;
}
static void ngd_slim_setup_msg_path(struct msm_slim_ctrl *dev)
{
if (dev->state == MSM_CTRL_DOWN) {
msm_slim_sps_init(dev, dev->bam_mem,
NGD_BASE(dev->ctrl.nr,
dev->ver) + NGD_STATUS, true);
} else {
if (dev->use_rx_msgqs == MSM_MSGQ_DISABLED)
goto setup_tx_msg_path;
msm_slim_connect_endp(dev, &dev->rx_msgq,
&dev->rx_msgq_notify);
setup_tx_msg_path:
if (dev->use_tx_msgqs == MSM_MSGQ_DISABLED)
return;
msm_slim_connect_endp(dev, &dev->tx_msgq,
NULL);
}
}
static void ngd_slim_rx(struct msm_slim_ctrl *dev, u8 *buf)
{
u8 mc, mt, len;
int ret;
u32 msgq_en = 1;
len = buf[0] & 0x1F;
mt = (buf[0] >> 5) & 0x7;
mc = buf[1];
if (mc == SLIM_USR_MC_MASTER_CAPABILITY &&
mt == SLIM_MSG_MT_SRC_REFERRED_USER) {
struct slim_msg_txn txn;
int retries = 0;
u8 wbuf[8];
txn.dt = SLIM_MSG_DEST_LOGICALADDR;
txn.ec = 0;
txn.rbuf = NULL;
txn.mc = SLIM_USR_MC_REPORT_SATELLITE;
txn.mt = SLIM_MSG_MT_SRC_REFERRED_USER;
txn.la = SLIM_LA_MGR;
wbuf[0] = SAT_MAGIC_LSB;
wbuf[1] = SAT_MAGIC_MSB;
wbuf[2] = SAT_MSG_VER;
wbuf[3] = SAT_MSG_PROT;
txn.wbuf = wbuf;
txn.len = 4;
SLIM_INFO(dev, "SLIM SAT: Rcvd master capability\n");
if (dev->state >= MSM_CTRL_ASLEEP) {
ngd_slim_setup_msg_path(dev);
if (dev->use_rx_msgqs == MSM_MSGQ_ENABLED)
msgq_en |= NGD_CFG_RX_MSGQ_EN;
if (dev->use_tx_msgqs == MSM_MSGQ_ENABLED)
msgq_en |= NGD_CFG_TX_MSGQ_EN;
writel_relaxed(msgq_en, dev->base +
NGD_BASE(dev->ctrl.nr, dev->ver));
/* make sure NGD MSG-Q config goes through */
mb();
}
capability_retry:
txn.rl = 8;
ret = ngd_xfer_msg(&dev->ctrl, &txn);
if (!ret) {
enum msm_ctrl_state prev_state = dev->state;
SLIM_INFO(dev,
"SLIM SAT: capability exchange successful\n");
dev->state = MSM_CTRL_AWAKE;
if (prev_state >= MSM_CTRL_ASLEEP)
complete(&dev->reconf);
else
SLIM_ERR(dev,
"SLIM: unexpected capability, state:%d\n",
prev_state);
/* ADSP SSR, send device_up notifications */
if (prev_state == MSM_CTRL_DOWN)
complete(&dev->qmi.slave_notify);
} else if (ret == -EIO) {
SLIM_WARN(dev, "capability message NACKed, retrying\n");
if (retries < INIT_MX_RETRIES) {
msleep(DEF_RETRY_MS);
retries++;
goto capability_retry;
}
}
}
if (mc == SLIM_MSG_MC_REPLY_INFORMATION ||
mc == SLIM_MSG_MC_REPLY_VALUE) {
u8 tid = buf[3];
dev_dbg(dev->dev, "tid:%d, len:%d\n", tid, len);
slim_msg_response(&dev->ctrl, &buf[4], tid,
len - 4);
pm_runtime_mark_last_busy(dev->dev);
}
if (mc == SLIM_USR_MC_ADDR_REPLY &&
mt == SLIM_MSG_MT_SRC_REFERRED_USER) {
struct slim_msg_txn *txn;
u8 failed_ea[6] = {0, 0, 0, 0, 0, 0};
mutex_lock(&dev->ctrl.m_ctrl);
txn = dev->ctrl.txnt[buf[3]];
if (!txn) {
SLIM_WARN(dev,
"LADDR response after timeout, tid:0x%x\n",
buf[3]);
mutex_unlock(&dev->ctrl.m_ctrl);
return;
}
if (memcmp(&buf[4], failed_ea, 6))
txn->la = buf[10];
dev->ctrl.txnt[buf[3]] = NULL;
mutex_unlock(&dev->ctrl.m_ctrl);
complete(txn->comp);
}
if (mc == SLIM_USR_MC_GENERIC_ACK &&
mt == SLIM_MSG_MT_SRC_REFERRED_USER) {
struct slim_msg_txn *txn;
mutex_lock(&dev->ctrl.m_ctrl);
txn = dev->ctrl.txnt[buf[3]];
if (!txn) {
SLIM_WARN(dev, "ACK received after timeout, tid:0x%x\n",
buf[3]);
mutex_unlock(&dev->ctrl.m_ctrl);
return;
}
dev_dbg(dev->dev, "got response:tid:%d, response:0x%x",
(int)buf[3], buf[4]);
if (!(buf[4] & MSM_SAT_SUCCSS)) {
SLIM_WARN(dev, "TID:%d, NACK code:0x%x\n", (int)buf[3],
buf[4]);
txn->ec = -EIO;
}
dev->ctrl.txnt[buf[3]] = NULL;
mutex_unlock(&dev->ctrl.m_ctrl);
complete(txn->comp);
}
}
static int ngd_slim_power_up(struct msm_slim_ctrl *dev, bool mdm_restart)
{
void __iomem *ngd;
int timeout, ret = 0;
enum msm_ctrl_state cur_state = dev->state;
u32 laddr;
u32 ngd_int = (NGD_INT_TX_NACKED_2 |
NGD_INT_MSG_BUF_CONTE | NGD_INT_MSG_TX_INVAL |
NGD_INT_IE_VE_CHG | NGD_INT_DEV_ERR |
NGD_INT_TX_MSG_SENT | NGD_INT_RX_MSG_RCVD);
if (!mdm_restart && cur_state == MSM_CTRL_DOWN) {
int timeout = wait_for_completion_timeout(&dev->qmi.qmi_comp,
HZ);
if (!timeout)
SLIM_ERR(dev, "slimbus QMI init timed out\n");
}
/* No need to vote if contorller is not in low power mode */
if (!mdm_restart &&
(cur_state == MSM_CTRL_DOWN || cur_state == MSM_CTRL_ASLEEP)) {
ret = msm_slim_qmi_power_request(dev, true);
if (ret) {
SLIM_ERR(dev, "SLIM QMI power request failed:%d\n",
ret);
return ret;
}
}
if (!dev->ver) {
dev->ver = readl_relaxed(dev->base);
/* Version info in 16 MSbits */
dev->ver >>= 16;
}
ngd = dev->base + NGD_BASE(dev->ctrl.nr, dev->ver);
laddr = readl_relaxed(ngd + NGD_STATUS);
if (laddr & NGD_LADDR) {
/*
* external MDM restart case where ADSP itself was active framer
* For example, modem restarted when playback was active
*/
if (cur_state == MSM_CTRL_AWAKE) {
SLIM_INFO(dev, "Subsys restart: ADSP active framer\n");
return 0;
}
/*
* ADSP power collapse case, where HW wasn't reset.
* Reconnect BAM pipes if disconnected
*/
ngd_slim_setup_msg_path(dev);
return 0;
}
if (mdm_restart) {
/*
* external MDM SSR when MDM is active framer
* ADSP will reset slimbus HW. disconnect BAM pipes so that
* they can be connected after capability message is received.
* Set device state to ASLEEP to be synchronous with the HW
*/
/* make current state as DOWN */
cur_state = MSM_CTRL_DOWN;
SLIM_INFO(dev,
"SLIM MDM restart: MDM active framer: reinit HW\n");
/* disconnect BAM pipes */
if (dev->use_rx_msgqs == MSM_MSGQ_ENABLED)
dev->use_rx_msgqs = MSM_MSGQ_DOWN;
if (dev->use_tx_msgqs == MSM_MSGQ_ENABLED)
dev->use_tx_msgqs = MSM_MSGQ_DOWN;
dev->state = MSM_CTRL_DOWN;
}
/* SSR scenario, need to disconnect pipe before connecting */
if (dev->use_rx_msgqs == MSM_MSGQ_DOWN) {
struct msm_slim_endp *endpoint = &dev->rx_msgq;
sps_disconnect(endpoint->sps);
sps_free_endpoint(endpoint->sps);
dev->use_rx_msgqs = MSM_MSGQ_RESET;
}
if (dev->use_tx_msgqs == MSM_MSGQ_DOWN) {
struct msm_slim_endp *endpoint = &dev->tx_msgq;
sps_disconnect(endpoint->sps);
sps_free_endpoint(endpoint->sps);
dev->use_tx_msgqs = MSM_MSGQ_RESET;
}
/*
* ADSP power collapse case (OR SSR), where HW was reset
* BAM programming will happen when capability message is received
*/
writel_relaxed(ngd_int, dev->base + NGD_INT_EN +
NGD_BASE(dev->ctrl.nr, dev->ver));
/*
* Enable NGD. Configure NGD in register acc. mode until master
* announcement is received
*/
writel_relaxed(1, dev->base + NGD_BASE(dev->ctrl.nr, dev->ver));
/* make sure NGD enabling goes through */
mb();
timeout = wait_for_completion_timeout(&dev->reconf, HZ);
if (!timeout) {
SLIM_ERR(dev, "Failed to receive master capability\n");
return -ETIMEDOUT;
}
if (cur_state == MSM_CTRL_DOWN) {
complete(&dev->ctrl_up);
/* Resetting the log level */
SLIM_RST_LOGLVL(dev);
}
return 0;
}
static int ngd_slim_enable(struct msm_slim_ctrl *dev, bool enable)
{
int ret = 0;
if (enable) {
ret = msm_slim_qmi_init(dev, false);
/* controller state should be in sync with framework state */
if (!ret) {
complete(&dev->qmi.qmi_comp);
if (!pm_runtime_enabled(dev->dev) ||
!pm_runtime_suspended(dev->dev))
ngd_slim_runtime_resume(dev->dev);
else
pm_runtime_resume(dev->dev);
pm_runtime_mark_last_busy(dev->dev);
pm_runtime_put(dev->dev);
} else
SLIM_ERR(dev, "qmi init fail, ret:%d, state:%d\n",
ret, dev->state);
} else {
msm_slim_qmi_exit(dev);
}
return ret;
}
static int ngd_slim_power_down(struct msm_slim_ctrl *dev)
{
int i;
struct slim_controller *ctrl = &dev->ctrl;
mutex_lock(&ctrl->m_ctrl);
/* Pending response for a message */
for (i = 0; i < ctrl->last_tid; i++) {
if (ctrl->txnt[i]) {
SLIM_INFO(dev, "NGD down:txn-rsp for %d pending", i);
mutex_unlock(&ctrl->m_ctrl);
return -EBUSY;
}
}
mutex_unlock(&ctrl->m_ctrl);
msm_slim_disconnect_endp(dev, &dev->rx_msgq,
&dev->use_rx_msgqs);
msm_slim_disconnect_endp(dev, &dev->tx_msgq,
&dev->use_tx_msgqs);
return msm_slim_qmi_power_request(dev, false);
}
static int ngd_slim_rx_msgq_thread(void *data)
{
struct msm_slim_ctrl *dev = (struct msm_slim_ctrl *)data;
struct completion *notify = &dev->rx_msgq_notify;
int ret = 0, index = 0;
u32 mc = 0;
u32 mt = 0;
u32 buffer[10];
u8 msg_len = 0;
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
wait_for_completion(notify);
/* 1 irq notification per message */
if (dev->use_rx_msgqs != MSM_MSGQ_ENABLED) {
msm_slim_rx_dequeue(dev, (u8 *)buffer);
ngd_slim_rx(dev, (u8 *)buffer);
continue;
}
ret = msm_slim_rx_msgq_get(dev, buffer, index);
if (ret) {
SLIM_ERR(dev, "rx_msgq_get() failed 0x%x\n", ret);
continue;
}
/* Wait for complete message */
if (index++ == 0) {
msg_len = *buffer & 0x1F;
mt = (buffer[0] >> 5) & 0x7;
mc = (buffer[0] >> 8) & 0xff;
dev_dbg(dev->dev, "MC: %x, MT: %x\n", mc, mt);
}
if ((index * 4) >= msg_len) {
index = 0;
ngd_slim_rx(dev, (u8 *)buffer);
} else
continue;
}
return 0;
}
static int ngd_notify_slaves(void *data)
{
struct msm_slim_ctrl *dev = (struct msm_slim_ctrl *)data;
struct slim_controller *ctrl = &dev->ctrl;
struct slim_device *sbdev;
struct list_head *pos, *next;
int ret, i = 0;
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
wait_for_completion(&dev->qmi.slave_notify);
/* Probe devices for first notification */
if (!i) {
i++;
dev->err = 0;
if (dev->dev->of_node)
of_register_slim_devices(&dev->ctrl);
/*
* Add devices registered with board-info now that
* controller is up
*/
slim_ctrl_add_boarddevs(&dev->ctrl);
} else {
slim_framer_booted(ctrl);
}
mutex_lock(&ctrl->m_ctrl);
list_for_each_safe(pos, next, &ctrl->devs) {
int j;
sbdev = list_entry(pos, struct slim_device, dev_list);
mutex_unlock(&ctrl->m_ctrl);
for (j = 0; j < LADDR_RETRY; j++) {
ret = slim_get_logical_addr(sbdev,
sbdev->e_addr,
6, &sbdev->laddr);
if (!ret)
break;
else /* time for ADSP to assign LA */
msleep(20);
}
mutex_lock(&ctrl->m_ctrl);
}
mutex_unlock(&ctrl->m_ctrl);
}
return 0;
}
static void ngd_adsp_down(struct work_struct *work)
{
struct msm_slim_qmi *qmi =
container_of(work, struct msm_slim_qmi, ssr_down);
struct msm_slim_ctrl *dev =
container_of(qmi, struct msm_slim_ctrl, qmi);
struct slim_controller *ctrl = &dev->ctrl;
struct slim_device *sbdev;
mutex_lock(&dev->ssr_lock);
ngd_slim_enable(dev, false);
/* disconnect BAM pipes */
if (dev->use_rx_msgqs == MSM_MSGQ_ENABLED)
dev->use_rx_msgqs = MSM_MSGQ_DOWN;
if (dev->use_tx_msgqs == MSM_MSGQ_ENABLED)
dev->use_tx_msgqs = MSM_MSGQ_DOWN;
msm_slim_sps_exit(dev, false);
/* device up should be called again after SSR */
list_for_each_entry(sbdev, &ctrl->devs, dev_list)
slim_report_absent(sbdev);
SLIM_INFO(dev, "SLIM ADSP SSR (DOWN) done\n");
mutex_unlock(&dev->ssr_lock);
}
static void ngd_adsp_up(struct work_struct *work)
{
struct msm_slim_qmi *qmi =
container_of(work, struct msm_slim_qmi, ssr_up);
struct msm_slim_ctrl *dev =
container_of(qmi, struct msm_slim_ctrl, qmi);
mutex_lock(&dev->ssr_lock);
ngd_slim_enable(dev, true);
mutex_unlock(&dev->ssr_lock);
}
static ssize_t show_mask(struct device *device, struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(device);
struct msm_slim_ctrl *dev = platform_get_drvdata(pdev);
return snprintf(buf, sizeof(int), "%u\n", dev->ipc_log_mask);
}
static ssize_t set_mask(struct device *device, struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(device);
struct msm_slim_ctrl *dev = platform_get_drvdata(pdev);
dev->ipc_log_mask = buf[0] - '0';
if (dev->ipc_log_mask > DBG_LEV)
dev->ipc_log_mask = DBG_LEV;
return count;
}
static DEVICE_ATTR(debug_mask, S_IRUGO | S_IWUSR, show_mask, set_mask);
static int ngd_slim_probe(struct platform_device *pdev)
{
struct msm_slim_ctrl *dev;
int ret;
struct resource *bam_mem;
struct resource *slim_mem;
struct resource *irq, *bam_irq;
bool rxreg_access = false;
bool slim_mdm = false;
const char *ext_modem_id = NULL;
slim_mem = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"slimbus_physical");
if (!slim_mem) {
dev_err(&pdev->dev, "no slimbus physical memory resource\n");
return -ENODEV;
}
bam_mem = platform_get_resource_byname(pdev, IORESOURCE_MEM,
"slimbus_bam_physical");
if (!bam_mem) {
dev_err(&pdev->dev, "no slimbus BAM memory resource\n");
return -ENODEV;
}
irq = platform_get_resource_byname(pdev, IORESOURCE_IRQ,
"slimbus_irq");
if (!irq) {
dev_err(&pdev->dev, "no slimbus IRQ resource\n");
return -ENODEV;
}
bam_irq = platform_get_resource_byname(pdev, IORESOURCE_IRQ,
"slimbus_bam_irq");
if (!bam_irq) {
dev_err(&pdev->dev, "no slimbus BAM IRQ resource\n");
return -ENODEV;
}
dev = kzalloc(sizeof(struct msm_slim_ctrl), GFP_KERNEL);
if (IS_ERR_OR_NULL(dev)) {
dev_err(&pdev->dev, "no memory for MSM slimbus controller\n");
return PTR_ERR(dev);
}
dev->dev = &pdev->dev;
platform_set_drvdata(pdev, dev);
slim_set_ctrldata(&dev->ctrl, dev);
/* Create IPC log context */
dev->ipc_slimbus_log = ipc_log_context_create(IPC_SLIMBUS_LOG_PAGES,
dev_name(dev->dev));
if (!dev->ipc_slimbus_log)
dev_err(&pdev->dev, "error creating ipc_logging context\n");
else {
/* Initialize the log mask */
dev->ipc_log_mask = INFO_LEV;
dev->default_ipc_log_mask = INFO_LEV;
SLIM_INFO(dev, "start logging for slim dev %s\n",
dev_name(dev->dev));
}
ret = sysfs_create_file(&dev->dev->kobj, &dev_attr_debug_mask.attr);
if (ret) {
dev_err(&pdev->dev, "Failed to create dev. attr\n");
dev->sysfs_created = false;
} else
dev->sysfs_created = true;
dev->base = ioremap(slim_mem->start, resource_size(slim_mem));
if (!dev->base) {
dev_err(&pdev->dev, "IOremap failed\n");
ret = -ENOMEM;
goto err_ioremap_failed;
}
dev->bam.base = ioremap(bam_mem->start, resource_size(bam_mem));
if (!dev->bam.base) {
dev_err(&pdev->dev, "BAM IOremap failed\n");
ret = -ENOMEM;
goto err_ioremap_bam_failed;
}
if (pdev->dev.of_node) {
ret = of_property_read_u32(pdev->dev.of_node, "cell-index",
&dev->ctrl.nr);
if (ret) {
dev_err(&pdev->dev, "Cell index not specified:%d", ret);
goto err_ctrl_failed;
}
rxreg_access = of_property_read_bool(pdev->dev.of_node,
"qcom,rxreg-access");
of_property_read_u32(pdev->dev.of_node, "qcom,apps-ch-pipes",
&dev->pdata.apps_pipes);
of_property_read_u32(pdev->dev.of_node, "qcom,ea-pc",
&dev->pdata.eapc);
ret = of_property_read_string(pdev->dev.of_node,
"qcom,slim-mdm", &ext_modem_id);
if (!ret)
slim_mdm = true;
} else {
dev->ctrl.nr = pdev->id;
}
/*
* Keep PGD's logical address as manager's. Query it when first data
* channel request comes in
*/
dev->pgdla = SLIM_LA_MGR;
dev->ctrl.nchans = MSM_SLIM_NCHANS;
dev->ctrl.nports = MSM_SLIM_NPORTS;
dev->framer.rootfreq = SLIM_ROOT_FREQ >> 3;
dev->framer.superfreq =
dev->framer.rootfreq / SLIM_CL_PER_SUPERFRAME_DIV8;
dev->ctrl.a_framer = &dev->framer;
dev->ctrl.clkgear = SLIM_MAX_CLK_GEAR;
dev->ctrl.set_laddr = ngd_set_laddr;
dev->ctrl.get_laddr = ngd_get_laddr;
dev->ctrl.allocbw = ngd_allocbw;
dev->ctrl.xfer_msg = ngd_xfer_msg;
dev->ctrl.xfer_user_msg = ngd_user_msg;
dev->ctrl.wakeup = NULL;
dev->ctrl.alloc_port = msm_alloc_port;
dev->ctrl.dealloc_port = msm_dealloc_port;
dev->ctrl.port_xfer = msm_slim_port_xfer;
dev->ctrl.port_xfer_status = msm_slim_port_xfer_status;
dev->bam_mem = bam_mem;
init_completion(&dev->reconf);
init_completion(&dev->ctrl_up);
mutex_init(&dev->tx_lock);
mutex_init(&dev->ssr_lock);
spin_lock_init(&dev->rx_lock);
dev->ee = 1;
dev->irq = irq->start;
dev->bam.irq = bam_irq->start;
if (rxreg_access)
dev->use_rx_msgqs = MSM_MSGQ_DISABLED;
else
dev->use_rx_msgqs = MSM_MSGQ_RESET;
/* Enable TX message queues by default as recommended by HW */
dev->use_tx_msgqs = MSM_MSGQ_RESET;
init_completion(&dev->rx_msgq_notify);
init_completion(&dev->qmi.slave_notify);
/* Register with framework */
ret = slim_add_numbered_controller(&dev->ctrl);
if (ret) {
dev_err(dev->dev, "error adding controller\n");
goto err_ctrl_failed;
}
dev->ctrl.dev.parent = &pdev->dev;
dev->ctrl.dev.of_node = pdev->dev.of_node;
dev->state = MSM_CTRL_DOWN;
ret = request_irq(dev->irq, ngd_slim_interrupt,
IRQF_TRIGGER_HIGH, "ngd_slim_irq", dev);
if (ret) {
dev_err(&pdev->dev, "request IRQ failed\n");
goto err_request_irq_failed;
}
init_completion(&dev->qmi.qmi_comp);
dev->err = -EPROBE_DEFER;
pm_runtime_use_autosuspend(dev->dev);
pm_runtime_set_autosuspend_delay(dev->dev, MSM_SLIM_AUTOSUSPEND);
pm_runtime_set_suspended(dev->dev);
pm_runtime_enable(dev->dev);
if (slim_mdm) {
dev->mdm.nb.notifier_call = mdm_ssr_notify_cb;
dev->mdm.ssr = subsys_notif_register_notifier(ext_modem_id,
&dev->mdm.nb);
if (IS_ERR_OR_NULL(dev->mdm.ssr))
dev_err(dev->dev,
"subsys_notif_register_notifier failed %p",
dev->mdm.ssr);
}
INIT_WORK(&dev->qmi.ssr_down, ngd_adsp_down);
INIT_WORK(&dev->qmi.ssr_up, ngd_adsp_up);
dev->qmi.nb.notifier_call = ngd_qmi_available;
pm_runtime_get_noresume(dev->dev);
ret = qmi_svc_event_notifier_register(SLIMBUS_QMI_SVC_ID,
SLIMBUS_QMI_SVC_V1,
SLIMBUS_QMI_INS_ID, &dev->qmi.nb);
if (ret) {
pr_err("Slimbus QMI service registration failed:%d", ret);
goto qmi_register_failed;
}
/* Fire up the Rx message queue thread */
dev->rx_msgq_thread = kthread_run(ngd_slim_rx_msgq_thread, dev,
"ngd_rx_thread%d", dev->ctrl.nr);
if (IS_ERR(dev->rx_msgq_thread)) {
ret = PTR_ERR(dev->rx_msgq_thread);
dev_err(dev->dev, "Failed to start Rx thread:%d\n", ret);
goto err_rx_thread_create_failed;
}
/* Start thread to probe, and notify slaves */
dev->qmi.slave_thread = kthread_run(ngd_notify_slaves, dev,
"ngd_notify_sl%d", dev->ctrl.nr);
if (IS_ERR(dev->qmi.slave_thread)) {
ret = PTR_ERR(dev->qmi.slave_thread);
dev_err(dev->dev, "Failed to start notifier thread:%d\n", ret);
goto err_notify_thread_create_failed;
}
SLIM_INFO(dev, "NGD SB controller is up!\n");
return 0;
err_notify_thread_create_failed:
kthread_stop(dev->rx_msgq_thread);
err_rx_thread_create_failed:
qmi_svc_event_notifier_unregister(SLIMBUS_QMI_SVC_ID,
SLIMBUS_QMI_SVC_V1,
SLIMBUS_QMI_INS_ID, &dev->qmi.nb);
qmi_register_failed:
free_irq(dev->irq, dev);
err_request_irq_failed:
slim_del_controller(&dev->ctrl);
err_ctrl_failed:
iounmap(dev->bam.base);
err_ioremap_bam_failed:
iounmap(dev->base);
err_ioremap_failed:
if (dev->sysfs_created)
sysfs_remove_file(&dev->dev->kobj,
&dev_attr_debug_mask.attr);
kfree(dev);
return ret;
}
static int ngd_slim_remove(struct platform_device *pdev)
{
struct msm_slim_ctrl *dev = platform_get_drvdata(pdev);
ngd_slim_enable(dev, false);
if (dev->sysfs_created)
sysfs_remove_file(&dev->dev->kobj,
&dev_attr_debug_mask.attr);
qmi_svc_event_notifier_unregister(SLIMBUS_QMI_SVC_ID,
SLIMBUS_QMI_SVC_V1,
SLIMBUS_QMI_INS_ID, &dev->qmi.nb);
pm_runtime_disable(&pdev->dev);
if (!IS_ERR_OR_NULL(dev->mdm.ssr))
subsys_notif_unregister_notifier(dev->mdm.ssr, &dev->mdm.nb);
free_irq(dev->irq, dev);
slim_del_controller(&dev->ctrl);
kthread_stop(dev->rx_msgq_thread);
iounmap(dev->bam.base);
iounmap(dev->base);
kfree(dev);
return 0;
}
#ifdef CONFIG_PM_RUNTIME
static int ngd_slim_runtime_idle(struct device *device)
{
struct platform_device *pdev = to_platform_device(device);
struct msm_slim_ctrl *dev = platform_get_drvdata(pdev);
if (dev->state == MSM_CTRL_AWAKE)
dev->state = MSM_CTRL_IDLE;
dev_dbg(device, "pm_runtime: idle...\n");
pm_request_autosuspend(device);
return -EAGAIN;
}
#endif
/*
* If PM_RUNTIME is not defined, these 2 functions become helper
* functions to be called from system suspend/resume. So they are not
* inside ifdef CONFIG_PM_RUNTIME
*/
static int ngd_slim_runtime_resume(struct device *device)
{
struct platform_device *pdev = to_platform_device(device);
struct msm_slim_ctrl *dev = platform_get_drvdata(pdev);
int ret = 0;
if (dev->state >= MSM_CTRL_ASLEEP)
ret = ngd_slim_power_up(dev, false);
if (ret) {
/* Did SSR cause this power up failure */
if (dev->state != MSM_CTRL_DOWN)
dev->state = MSM_CTRL_ASLEEP;
else
SLIM_WARN(dev, "HW wakeup attempt during SSR\n");
} else {
dev->state = MSM_CTRL_AWAKE;
}
SLIM_INFO(dev, "Slim runtime resume: ret %d\n", ret);
return ret;
}
#ifdef CONFIG_PM_SLEEP
static int ngd_slim_runtime_suspend(struct device *device)
{
struct platform_device *pdev = to_platform_device(device);
struct msm_slim_ctrl *dev = platform_get_drvdata(pdev);
int ret = 0;
ret = ngd_slim_power_down(dev);
if (ret) {
if (ret != -EBUSY)
SLIM_INFO(dev, "slim resource not idle:%d\n", ret);
dev->state = MSM_CTRL_AWAKE;
} else {
dev->state = MSM_CTRL_ASLEEP;
}
SLIM_INFO(dev, "Slim runtime suspend: ret %d\n", ret);
return ret;
}
static int ngd_slim_suspend(struct device *dev)
{
int ret = -EBUSY;
struct platform_device *pdev = to_platform_device(dev);
struct msm_slim_ctrl *cdev = platform_get_drvdata(pdev);
if (!pm_runtime_enabled(dev) ||
(!pm_runtime_suspended(dev) &&
cdev->state == MSM_CTRL_IDLE)) {
ret = ngd_slim_runtime_suspend(dev);
/*
* If runtime-PM still thinks it's active, then make sure its
* status is in sync with HW status.
* Since this suspend calls QMI api, it results in holding a
* wakelock. That results in failure of first suspend.
* Subsequent suspend should not call low-power transition
* again since the HW is already in suspended state.
*/
if (!ret) {
pm_runtime_disable(dev);
pm_runtime_set_suspended(dev);
pm_runtime_enable(dev);
}
}
if (ret == -EBUSY) {
/*
* There is a possibility that some audio stream is active
* during suspend. We dont want to return suspend failure in
* that case so that display and relevant components can still
* go to suspend.
* If there is some other error, then it should be passed-on
* to system level suspend
*/
ret = 0;
}
SLIM_INFO(cdev, "system suspend\n");
return ret;
}
static int ngd_slim_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct msm_slim_ctrl *cdev = platform_get_drvdata(pdev);
/*
* Rely on runtime-PM to call resume in case it is enabled.
* Even if it's not enabled, rely on 1st client transaction to do
* clock/power on
*/
SLIM_INFO(cdev, "system resume\n");
return 0;
}
#endif /* CONFIG_PM_SLEEP */
static const struct dev_pm_ops ngd_slim_dev_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(
ngd_slim_suspend,
ngd_slim_resume
)
SET_RUNTIME_PM_OPS(
ngd_slim_runtime_suspend,
ngd_slim_runtime_resume,
ngd_slim_runtime_idle
)
};
static struct of_device_id ngd_slim_dt_match[] = {
{
.compatible = "qcom,slim-ngd",
},
{}
};
static struct platform_driver ngd_slim_driver = {
.probe = ngd_slim_probe,
.remove = ngd_slim_remove,
.driver = {
.name = NGD_SLIM_NAME,
.owner = THIS_MODULE,
.pm = &ngd_slim_dev_pm_ops,
.of_match_table = ngd_slim_dt_match,
},
};
static int ngd_slim_init(void)
{
return platform_driver_register(&ngd_slim_driver);
}
late_initcall(ngd_slim_init);
static void ngd_slim_exit(void)
{
platform_driver_unregister(&ngd_slim_driver);
}
module_exit(ngd_slim_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("MSM Slimbus controller");
MODULE_ALIAS("platform:msm-slim-ngd");
| bhb27/android_kernel_motorola_apq8084 | drivers/slimbus/slim-msm-ngd.c | C | gpl-2.0 | 46,863 |
#!/usr/bin/php
<?php
/*
Copyright (C) 2011-2012 Hewlett-Packard Development Company, L.P.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
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.
*/
/**
* \file pkgConfig.php
* \brief prepare a system for install testing.
*
* pkgConfig prepares a system for the installation of fossology packages and
* installs the fossology packages.
*
* @param string $fossVersion the version of fossology to install?
* @todo what should the api for this really be?
*
* @version "$Id $"
* Created on Jul 19, 2011 by Mark Donohoe
* Updated on Nov 15, 2012 by Vincent Ma
*/
require_once '../lib/TestRun.php';
global $Debian;
global $RedHat;
$debian = NULL;
$redHat = NULL;
$fedora = NULL;
$ubuntu = NULL;
/*
* determine what os and version:
* configure yum or apt for fossology
* install fossology
* stop scheduler (if install is good).
* do the steps below.
* 1. tune kernel
* 2. postgres files
* 3. php ini files
* 4. fossology.org apache file (No needec)
* 5. checkout fossology
* 6. run fo-installdeps
* 7. for RHEL what else?
*/
// Check for Super User
$euid = posix_getuid();
if($euid != 0) {
print "Error, this script must be run as root\n";
exit(1);
}
// determine os flavor
$distros = array();
$f = exec('cat /etc/issue', $dist, $dRtn);
$distros = explode(' ', $dist[0]);
//echo "DB: distros[0] is:{$distros[0]}\n";
// configure for fossology and install fossology packages.
// Note that after this point, you could just stop if one could rely on the install
// process to give a valid exit code... Another script will run the agent unit
// and functional tests.
// create this class which can be used by any release/os
$testUtils = new TestRun();
// distro can be Debian, Red, Fedora, Ubuntu
switch ($distros[0]) {
case 'Debian':
$debian = TRUE; // is this needed?
$debianVersion = $distros[2];
echo "debian version is:$debianVersion\n";
try
{
$Debian = new ConfigSys($distros[0], $debianVersion);
}
catch (Exception $e)
{
echo "FATAL! could not process ini file for Debian $debianVersion system\n";
exit(1);
}
if(insertDeb($Debian) === FALSE)
{
echo "FATAL! cannot insert deb line into /etc/apt/sources.list\n";
exit(1);
}
echo "*** Installing fossology ***\n";
if(!installFossology($Debian))
{
echo "FATAL! Could not install fossology on {$distros[0]} version $debianVersion\n";
exit(1);
}
echo "*** stopping scheduler ***\n";
// Stop scheduler so system files can be configured.
$testUtils->stopScheduler();
echo "*** Tuning kernel ***\n";
tuneKernel();
echo "*** Setting up config files ***\n";
if(configDebian($distros[0], $debianVersion) === FALSE)
{
echo "FATAL! could not configure postgres or php config files\n";
exit(1);
}
/*
echo "*** Checking apache config ***\n";
if(!configApache2($distros[0]))
{
echo "Fatal, could not configure apache2 to use fossology\n";
}
*/
if(!restart('apache2'))
{
echo "Erorr! Could not restart apache2, please restart by hand\n";
exit(1);
}
echo "*** Starting FOSSology ***\n";
if(!start('fossology'))
{
echo "Erorr! Could not start FOSSology, please restart by hand\n";
exit(1);
}
break;
case 'Red':
$redHat = 'RedHat';
$rhVersion = $distros[6];
//echo "rh version is:$rhVersion\n";
try
{
$RedHat = new ConfigSys($redHat, $rhVersion);
}
catch (Exception $e)
{
echo "FATAL! could not process ini file for RedHat $rhVersion system\n";
echo $e;
exit(1);
}
if(!configYum($RedHat))
{
echo "FATAL! could not install fossology.conf yum configuration file\n";
exit(1);
}
echo "*** Tuning kernel ***\n";
tuneKernel();
echo "*** Installing fossology ***\n";
if(!installFossology($RedHat))
{
echo "FATAL! Could not install fossology on $redHat version $rhVersion\n";
exit(1);
}
echo "*** stopping scheduler ***\n";
// Stop scheduler so system files can be configured.
//$testUtils->stopScheduler();
echo "*** Setting up config files ***\n";
if(!configRhel($redHat, $rhVersion))
{
echo "FATAL! could not install php and postgress configuration files\n";
exit(1);
}
/*
echo "*** Checking apache config ***\n";
if(!configApache2($distros[0]))
{
echo "Fatal, could not configure apache2 to use fossology\n";
}
*/
if(!restart('httpd'))
{
echo "Erorr! Could not restart httpd, please restart by hand\n";
exit(1);
}
if(!stop('iptables'))
{
echo "Erorr! Could not stop Firewall, please stop by hand\n";
exit(1);
}
break;
case 'CentOS':
$redHat = 'RedHat';
$rhVersion = $distros[2];
echo "rh version is:$rhVersion\n";
try
{
$RedHat = new ConfigSys($redHat, $rhVersion);
}
catch (Exception $e)
{
echo "FATAL! could not process ini file for RedHat $rhVersion system\n";
echo $e;
exit(1);
}
if(!configYum($RedHat))
{
echo "FATAL! could not install fossology.conf yum configuration file\n";
exit(1);
}
echo "*** Tuning kernel ***\n";
tuneKernel();
echo "*** Installing fossology ***\n";
if(!installFossology($RedHat))
{
echo "FATAL! Could not install fossology on $redHat version $rhVersion\n";
exit(1);
}
echo "*** stopping scheduler ***\n";
// Stop scheduler so system files can be configured.
//$testUtils->stopScheduler();
echo "*** Setting up config files ***\n";
if(!configRhel($redHat, $rhVersion))
{
echo "FATAL! could not install php and postgress configuration files\n";
exit(1);
}
/*
echo "*** Checking apache config ***\n";
if(!configApache2($distros[0]))
{
echo "Fatal, could not configure apache2 to use fossology\n";
}
*/
if(!stop('httpd'))
{
echo "Erorr! Could not restart httpd, please restart by hand\n";
exit(1);
}
if(!start('httpd'))
{
echo "Erorr! Could not restart httpd, please restart by hand\n";
exit(1);
}
if(!stop('iptables'))
{
echo "Erorr! Could not stop Firewall, please stop by hand\n";
exit(1);
}
echo "*** Starting fossology ***\n";
if(!start('fossology'))
{
echo "Erorr! Could not start fossology, please restart by hand\n";
exit(1);
}
break;
case 'Fedora':
$fedora = 'Fedora';
$fedVersion = $distros[2];
try
{
$Fedora = new ConfigSys($fedora, $fedVersion);
}
catch (Exception $e)
{
echo "FATAL! could not process ini file for Fedora $fedVersion system\n";
echo $e;
exit(1);
}
if(!configYum($Fedora))
{
echo "FATAL! could not install fossology.repo yum configuration file\n";
exit(1);
break;
}
echo "*** Installing fossology ***\n";
if(!installFossology($Fedora))
{
echo "FATAL! Could not install fossology on $fedora version $fedVersion\n";
exit(1);
}
echo "*** stopping scheduler ***\n";
// Stop scheduler so system files can be configured.
//$testUtils->stopScheduler();
echo "*** Tuning kernel ***\n";
tuneKernel();
echo "*** Setting up config files ***\n";
if(!configRhel($fedora, $fedVersion))
{
echo "FATAL! could not install php and postgress configuration files\n";
exit(1);
}
/*
echo "*** Checking apache config ***\n";
if(!configApache2($distros[0]))
{
echo "Fatal, could not configure apache2 to use fossology\n";
}
*/
$last = exec("systemctl restart httpd.service", $out, $rtn);
if($rtn != 0)
{
echo "Erorr! Could not restart httpd, please restart by hand\n";
exit(1);
}
$last = exec("systemctl stop iptables.service", $out, $rtn);
if($rtn != 0)
{
echo "Erorr! Could not stop Firewall, please stop by hand\n";
exit(1);
}
echo "*** Starting fossology ***\n";
$last = exec("systemctl restart fossology.service", $out, $rtn);
if($rtn != 0)
{
echo "Erorr! Could not start FOSSology, please stop by hand\n";
exit(1);
}
break;
case 'Ubuntu':
$distro = 'Ubuntu';
$ubunVersion = $distros[1];
echo "Ubuntu version is:$ubunVersion\n";
try
{
$Ubuntu = new ConfigSys($distros[0], $ubunVersion);
}
catch (Exception $e)
{
echo "FATAL! could not process ini file for Ubuntu $ubunVersion system\n";
echo $e . "\n";
exit(1);
}
if(insertDeb($Ubuntu) === FALSE)
{
echo "FATAL! cannot insert deb line into /etc/apt/sources.list\n";
exit(1);
}
echo "*** Tuning kernel ***\n";
tuneKernel();
echo "*** Installing fossology ***\n";
if(!installFossology($Ubuntu))
{
echo "FATAL! Could not install fossology on {$distros[0]} version $ubunVersion\n";
exit(1);
}
echo "*** stopping scheduler ***\n";
// Stop scheduler so system files can be configured.
$testUtils->stopScheduler();
echo "*** Setting up config files ***\n";
if(configDebian($distros[0], $ubunVersion) === FALSE)
{
echo "FATAL! could not configure postgres or php config files\n";
exit(1);
}
/*
echo "*** Checking apache config ***\n";
if(!configApache2($distros[0]))
{
echo "Fatal, could not configure apache2 to use fossology\n";
}
*/
if(!restart('apache2'))
{
echo "Erorr! Could not restart apache2, please restart by hand\n";
exit(1);
}
echo "*** Starting FOSSology ***\n";
if(!start('fossology'))
{
echo "Erorr! Could not start FOSSology, please restart by hand\n";
exit(1);
}
break;
default:
echo "Fatal! unrecognized distribution! {$distros[0]}\n" ;
exit(1);
break;
}
class ConfigSys {
public $osFlavor;
public $osVersion = 0;
private $fossVersion;
private $osCodeName;
public $deb;
public $comment = '';
public $yum;
function __construct($osFlavor, $osVersion)
{
if(empty($osFlavor))
{
throw new Exception("No Os Flavor supplied\n");
}
if(empty($osVersion))
{
throw new Exception("No Os Version Supplied\n");
}
$dataFile = '../dataFiles/pkginstall/' . strtolower($osFlavor) . '.ini';
$releases = parse_ini_file($dataFile, 1);
//echo "DB: the parsed ini file is:\n";
//print_r($releases) . "\n";
foreach($releases as $release => $values)
{
if($values['osversion'] == $osVersion)
{
// found the correct os, gather attributes
$this->osFlavor = $values['osflavor'];
$this->osVersion = $values['osversion'];
$this->fossVersion = $values['fossversion'];
$this->osCodeName = $values['codename'];
// code below is needed to avoid php notice
switch (strtolower($this->osFlavor)) {
case 'ubuntu':
case 'debian':
$this->deb = $values['deb'];
break;
case 'fedora':
case 'redhat':
$this->yum = $values['yum'];
break;
default:
;
break;
}
$this->comment = $values['comment'];
}
}
if($this->osVersion == 0)
{
throw new Exception("FATAL! no matching os flavor or version found\n");
}
return;
} // __construct
/**
* prints all the classes attributes (properties)
*
* @return void
*/
public function printAttr()
{
echo "Attributes of ConfigSys:\n";
echo "\tosFlavor:$this->osFlavor\n";
echo "\tosVersion:$this->osVersion\n";
echo "\tfossVersion:$this->fossVersion\n";
echo "\tosCodeName:$this->osCodeName\n";
echo "\tdeb:$this->deb\n";
echo "\tcomment:$this->comment\n";
echo "\tyum:$this->yum\n";
return;
} //printAttr
} // ConfigSys
/**
* \brief insert the fossology debian line in /etc/apt/sources.list
*
* @param object $objRef the object with the deb attribute
*
* @return boolean
*/
function insertDeb($objRef)
{
if(!is_object($objRef))
{
return(FALSE);
}
// open file for append
$APT = fopen('/etc/apt/sources.list', 'a+');
if(!is_resource($APT))
{
echo "FATAL! could not open /etc/apt/sources.list for modification\n";
return(FALSE);
}
$written = fwrite($APT, "\n");
fflush($APT);
if(empty($objRef->comment))
{
$comment = '# Automatically inserted by pkgConfig.php';
}
$com = fwrite($APT, $objRef->comment . "\n");
if(!$written = fwrite($APT, $objRef->deb))
{
echo "FATAL! could not write deb line to /etc/apt/sources.list\n";
return(FALSE);
}
fclose($APT);
return(TRUE);
} // insertDeb
/**
* \brief Install fossology using either apt or yum
*
* installFossology assumes that the correct configuration for yum and the
* correct fossology version has been configured into the system.
*
* @param object $objRef an object reference (should be to ConfigSys)
*
* @return boolean
*/
function installFossology($objRef)
{
if(!is_object($objRef))
{
return(FALSE);
}
$aptUpdate = 'apt-get update 2>&1';
$aptInstall = 'apt-get -y --force-yes install fossology 2>&1';
$yumUpdate = 'yum -y update 2>&1';
$yumInstall = 'yum -y install fossology > fossinstall.log 2>&1';
$debLog = NULL;
$installLog = NULL;
//echo "DB: IFOSS: osFlavor is:$objRef->osFlavor\n";
switch ($objRef->osFlavor) {
case 'Ubuntu':
case 'Debian':
$last = exec($aptUpdate, $out, $rtn);
//echo "last is:$last\nresults of update are:\n";print_r($out) . "\n";
$last = exec($aptInstall, $iOut, $iRtn);
if($iRtn != 0)
{
echo "Failed to install fossology!\nTranscript is:\n";
echo implode("\n",$iOut) . "\n";
return(FALSE);
}
// check for php or other errors that don't make apt return 1
echo "DB: in ubun/deb case, before installLog implode\n";
$debLog = implode("\n",$iOut);
if(!ckInstallLog($debLog))
{
echo "One or more of the phrases:\nPHP Stack trace:\nFATAL\n".
"Could not connect to FOSSology database:\n" .
"Unable to connect to PostgreSQL server:\n" .
"Was found in the install output. This install is suspect and is considered FAILED.\n";
return(FALSE);
}
// if any of the above are non zero, return false
break;
case 'Fedora':
case 'RedHat':
echo "** Running yum update **\n";
$last = exec($yumUpdate, $out, $rtn);
if($rtn != 0)
{
echo "Failed to update yum repositories with fossology!\nTranscript is:\n";
echo implode("\n",$out) . "\n";
return(FALSE);
}
echo "** Running yum install fossology **\n";
$last = exec($yumInstall, $yumOut, $yumRtn);
//echo "install of fossology finished, yumRtn is:$yumRtn\nlast is:$last\n";
//$clast = system('cat fossinstall.log');
if($yumRtn != 0)
{
echo "Failed to install fossology!\nTranscript is:\n";
system('cat fossinstall.log');
return(FALSE);
}
if(!($installLog = file_get_contents('fossinstall.log')))
{
echo "FATAL! could not read 'fossinstall.log\n";
return(FALSE);
}
if(!ckInstallLog($installLog))
{
echo "One or more of the phrases:\nPHP Stack trace:\nFATAL\n".
"Could not connect to FOSSology database:\n" .
"Unable to connect to PostgreSQL server:\n" .
"Was found in the install output. This install is suspect and is considered failed.\n";
return(FALSE);
}
break;
default:
echo "FATAL! Unrecongnized OS/Release, not one of Ubuntu, Debian, RedHat" .
" or Fedora\n";
return(FALSE);
break;
}
return(TRUE);
}
/**
* \brief Check the fossology install output for errors in the install.
*
* These errors do not cause apt to think that the install failed, so the output
* should be checked for typical failures during an install of packages. See
* the code for the specific checks.
*
* @param string $log the output from a fossology install with packages
*/
function ckInstallLog($log) {
if(empty($log))
{
return(FALSE);
}
// check for php or other errors that don't make apt return 1
$traces = $fates = $connects = $postgresFail = 0;
$stack = '/PHP Stack trace:/';
$fatal = '/FATAL/';
$noConnect = '/Could not connect to FOSSology database/';
$noPG = '/Unable to connect to PostgreSQL server:/';
$traces = preg_match_all($stack, $log, $stackMatches);
$fates = preg_match_all($fatal, $log, $fatalMatches);
$connects = preg_match_all($noConnect, $log, $noconMatches);
$postgresFail = preg_match_all($noPG, $log, $noPGMatches);
echo "Number of PHP stack traces found:$traces\n";
echo "Number of FATAL's found:$fates\n";
echo "Number of 'cannot connect' found:$connects\n";
echo "Number of 'cannot connect to postgres server' found:$postgresFail\n";
//print "DB: install log is:\n$log\n";
if($traces ||
$fates ||
$connects ||
$postgresFail)
{
return(FALSE);
}
return(TRUE);
}
/**
* \brief copyFiles, copy one or more files to the destination,
* throws exception if file is not copied.
*
* The method can be used to rename a single file, but not a directory. It
* cannot rename multiple files.
*
* @param mixed $file the file to copy (string), use an array for multiple files.
* @param string $dest the destination path (must exist, must be writable).
*
* @retrun boolean
*
*/
function copyFiles($files, $dest)
{
if(empty($files))
{
throw new Exception('No file to copy', 0);
}
if(empty($dest))
{
throw new Exception('No destination for copy', 0);
}
//echo "DB: copyFiles: we are at:" . getcwd() . "\n";
$login = posix_getlogin();
//echo "DB: copyFiles: running as:$login\n";
//echo "DB: copyFiles: uid is:" . posix_getuid() . "\n";
if(is_array($files))
{
foreach($files as $file)
{
// Get left name and check if dest is a directory, copy cannot copy to a
// dir.
$baseFile = basename($file);
if(is_dir($dest))
{
$to = $dest . "/$baseFile";
}
else
{
$to = $dest;
}
//echo "DB: copyfiles: file copied is:$file\n";
//echo "DB: copyfiles: to is:$to\n";
if(!copy($file, $to))
{
throw new Exception("Could not copy $file to $to");
}
//$lastcp = exec("cp -v $file $to", $cpout, $cprtn);
//echo "DB: copyfiles: cprtn is:$cprtn\n";
//echo "DB: copyfiles: lastcp is:$lastcp\n";
//echo "DB: copyfiles: out is:\n";print_r($cpout) . "\n";
}
}
else
{
$baseFile = basename($files);
if(is_dir($dest))
{
$to = $dest . "/$baseFile";
}
else
{
$to = $dest;
}
//echo "DB: copyfiles-single: file copied is:$files\n";
//echo "DB: copyfiles-single: to is:$to\n";
if(!copy($files,$to))
{
throw new Exception("Could not copy $file to $to");
}
}
return(TRUE);
} // copyFiles
/**
* \brief find the version of postgres and return major release and sub release.
* For example, if postgres is at 8.4.8, this function will return 8.4.
*
* @return boolean
*/
function findVerPsql()
{
$version = NULL;
$last = exec('psql --version', $out, $rtn);
if($rtn != 0)
{
return(FALSE);
}
else
{
// isolate the version number and return it
list( , ,$ver) = explode(' ', $out[0]);
$version = substr($ver, 0, 3);
}
return($version);
}
/**
* \brief tune the kernel for this boot and successive boots
*
* returns void
*/
function tuneKernel()
{
// check to see if we have already done this... so the sysctl.conf file doesn't
// end up with dup entries.
$grepCmd = 'grep shmmax=512000000 /etc/sysctl.conf /dev/null 2>&1';
$last = exec($grepCmd, $out, $rtn);
if($rtn == 0) // kernel already configured
{
echo "NOTE: kernel already configured.\n";
return;
}
$cmd1 = "echo 512000000 > /proc/sys/kernel/shmmax";
$cmd2 = "echo 'kernel.shmmax=512000000' >> /etc/sysctl.conf";
// Tune the kernel
$last1 = exec($cmd1, $cmd1Out, $rtn1);
if ($rtn1 != 0)
{
echo "Fatal! Could not set kernel shmmax in /proc/sys/kernel/shmmax\n";
}
$last2 = exec($cmd2, $cmd2Out, $rtn2);
// make it permanent
if ($rtn2 != 0)
{
echo "Fatal! Could not turn kernel.shmmax in /etc/sysctl.conf\n";
}
return;
} // tuneKernel
/**
* \brief check to see if fossology is configured into apache. If not copy the
* config file and configure it. Restart apache if configured.
*
* @param string $osType type of the os, e.g. Debian, Ubuntu, Red, Fedora
*
* @return boolean
*/
function configApache2($osType)
{
if(empty($osType))
{
return(FALSE);
}
switch ($osType) {
case 'Ubuntu':
case 'Debian':
if(is_link('/etc/apache2/conf.d/fossology'))
{
break;
}
else
{
// copy config file, create sym link
if(!copy('../dataFiles/pkginstall/fo-apache.conf', '/etc/fossology/fo-apache.conf'))
{
echo "FATAL!, Cannot configure fossology into apache2\n";
return(FALSE);
}
if(!symlink('/etc/fossology/fo-apache.conf','/etc/apache2/conf.d/fossology'))
{
echo "FATAL! Could not create symlink in /etc/apache2/conf.d/ for fossology\n";
return(FALSE);
}
// restart apache so changes take effect
if(!restart('apache2'))
{
echo "Erorr! Could not restart apache2, please restart by hand\n";
return(FALSE);
}
}
break;
case 'Red':
// copy config file, no symlink needed for redhat
if(!copy('../dataFiles/pkginstall/fo-apache.conf', '/etc/httpd/conf.d/fossology.conf'))
{
echo "FATAL!, Cannot configure fossology into apache2\n";
return(FALSE);
}
// restart apapche so changes take effect
if(!restart('httpd'))
{
echo "Erorr! Could not restart httpd, please restart by hand\n";
return(FALSE);
}
break;
default:
;
break;
}
return(TRUE);
} // configApache2
/**
* \brief config a debian based system to install fossology.
*
* copy postgres, php config files so that fossology can run.
*
* @param string $osType either Debian or Ubuntu
* @param string $osVersion the particular version to install
*
* @return boolean
*/
function configDebian($osType, $osVersion)
{
if(empty($osType))
{
return(FALSE);
}
if(empty($osVersion))
{
return(FALSE);
}
// based on type read the appropriate ini file.
//echo "DB:configD: osType is:$osType\n";
//echo "DB:configD: osversion is:$osVersion\n";
// can't check in pg_hba.conf as it shows HP's firewall settings, get it
// internally
// No need to update pg_hba.conf file
//getPGhba('../dataFiles/pkginstall/debian/6/pg_hba.conf');
$debPath = '../dataFiles/pkginstall/debian/6/';
$psqlFiles = array(
//$debPath . 'pg_hba.conf',
$debPath . 'postgresql.conf');
switch ($osVersion)
{
case '6.0':
echo "debianConfig got os version 6.0!\n";
// copy config files
/*
* Change the structure of data files:
* e.g. debian/5/pg_hba..., etc, all files that go with this version
* debian/6/pg_hba....
* and use a symlink for the 'codename' squeeze -> debian/6/
*/
try
{
copyFiles($psqlFiles, "/etc/postgresql/8.4/main");
}
catch (Exception $e)
{
echo "Failure: Could not copy postgres 8.4 config file\n";
}
try
{
copyFiles($debPath . 'cli-php.ini', '/etc/php5/cli/php.ini');
} catch (Exception $e)
{
echo "Failure: Could not copy php.ini to /etc/php5/cli/php.ini\n";
return(FALSE);
}
try
{
copyFiles($debPath . 'apache2-php.ini', '/etc/php5/apache2/php.ini');
} catch (Exception $e)
{
echo "Failure: Could not copy php.ini to /etc/php5/apache2/php.ini\n";
return(FALSE);
}
break;
case '10.04.3':
case '11.04':
case '11.10':
try
{
copyFiles($psqlFiles, "/etc/postgresql/8.4/main");
}
catch (Exception $e)
{
echo "Failure: Could not copy postgres 8.4 config file\n";
}
try
{
copyFiles($debPath . 'cli-php.ini', '/etc/php5/cli/php.ini');
} catch (Exception $e)
{
echo "Failure: Could not copy php.ini to /etc/php5/cli/php.ini\n";
return(FALSE);
}
try
{
copyFiles($debPath . 'apache2-php.ini', '/etc/php5/apache2/php.ini');
} catch (Exception $e)
{
echo "Failure: Could not copy php.ini to /etc/php5/apache2/php.ini\n";
return(FALSE);
}
break;
case '12.04.1':
case '12.10':
//postgresql-9.1 can't use 8.4 conf file
/*
try
{
copyFiles($psqlFiles, "/etc/postgresql/9.1/main");
}
catch (Exception $e)
{
echo "Failure: Could not copy postgres 9.1 config file\n";
}
*/
try
{
copyFiles($debPath . 'cli-php.ini', '/etc/php5/cli/php.ini');
} catch (Exception $e)
{
echo "Failure: Could not copy php.ini to /etc/php5/cli/php.ini\n";
return(FALSE);
}
try
{
copyFiles($debPath . 'apache2-php.ini', '/etc/php5/apache2/php.ini');
} catch (Exception $e)
{
echo "Failure: Could not copy php.ini to /etc/php5/apache2/php.ini\n";
return(FALSE);
}
break;
default:
return(FALSE); // unsupported debian version
break;
}
// restart apache and postgres so changes take effect
if(!restart('apache2'))
{
echo "Erorr! Could not restart apache2, please restart by hand\n";
return(FALSE);
}
// Get the postrgres version so the correct file is used.
$pName = 'postgresql';
if($osVersion == '10.04.3')
{
$ver = findVerPsql();
//echo "DB: returned version is:$ver\n";
$pName = 'postgresql-' . $ver;
}
echo "DB pName is:$pName\n";
if(!restart($pName))
{
echo "Erorr! Could not restart $pName, please restart by hand\n";
return(FALSE);
}
return(TRUE);
} // configDebian
/**
* \brief copy configuration files and restart apache and postgres
*
* @param string $osType
* @param string $osVersion
* @return boolean
*/
function configRhel($osType, $osVersion)
{
if(empty($osType))
{
return(FALSE);
}
if(empty($osVersion))
{
return(FALSE);
}
$rpmPath = '../dataFiles/pkginstall/redhat/6.x';
// getPGhba($rpmPath . '/pg_hba.conf');
$psqlFiles = array(
//$rpmPath . '/pg_hba.conf',
$rpmPath . '/postgresql.conf');
// fossology tweaks the postgres files so the packages work.... don't copy
/*
try
{
copyFiles($psqlFiles, "/var/lib/pgsql/data/");
}
catch (Exception $e)
{
echo "Failure: Could not copy postgres 8.4 config files\n";
}
*/
try
{
copyFiles($rpmPath . '/php.ini', '/etc/php.ini');
} catch (Exception $e)
{
echo "Failure: Could not copy php.ini to /etc/php.ini\n";
return(FALSE);
}
// restart postgres, postgresql conf didn't change do not restart
/*
$pName = 'postgresql';
if(!restart($pName))
{
echo "Erorr! Could not restart $pName, please restart by hand\n";
return(FALSE);
}
*/
return(TRUE);
} // configRhel
/**
* \brief config yum on a redhat based system to install fossology.
*
* Copies the Yum configuration file for fossology to
*
* @param object $objRef, a reference to the ConfigSys object
*
* @return boolean
*/
function configYum($objRef)
{
if(!is_object($objRef))
{
return(FALSE);
}
if(empty($objRef->yum))
{
echo "FATAL, no yum install line to install\n";
return(FALSE);
}
$RedFedRepo = 'redfed-fossology.repo'; // name of generic repo file.
// replace the baseurl line with the current one.
$n = "../dataFiles/pkginstall/" . $RedFedRepo;
$fcont = file_get_contents($n);
//if(!$fcont);
//{
//echo "FATAL! could not read repo file $n\n";
//exit(1);
//}
//echo "DB: contents is:\n$fcont\n";
$newRepo = preg_replace("/baseurl=(.*)?/", 'baseurl=' . $objRef->yum, $fcont,-1, $cnt);
// write the file, fix below to copy the correct thing...
if(!($written = file_put_contents("../dataFiles/pkginstall/" . $RedFedRepo, $newRepo)))
{
echo "FATAL! could not write repo file $RedFedRepo\n";
exit(1);
}
// coe plays with yum stuff, check if yum.repos.d exists and if not create it.
if(is_dir('/etc/yum.repos.d'))
{
copyFiles("../dataFiles/pkginstall/" . $RedFedRepo, '/etc/yum.repos.d/fossology.repo');
}
else
{
// create the dir and then copy
if(!mkdir('/etc/yum.repos.d'))
{
echo "FATAL! could not create yum.repos.d\n";
return(FALSE);
}
copyFiles("../dataFiles/pkginstall/" . $RedFedRepo, '/etc/yum.repos.d/fossology.repo');
}
//print_r($objRef);
if ($objRef->osFlavor == 'RedHat')
{
$last = exec("yum -y install wget", $out, $rtn);
if($rtn != 0)
{
echo "FATAL! install EPEL repo fail\n";
echo "transcript is:\n";print_r($out) . "\n";
return(FALSE);
}
$last = exec("wget -e http_proxy=http://lart.usa.hp.com:3128 http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-7.noarch.rpm", $out, $rtn);
if($rtn != 0)
{
echo "FATAL! install EPEL repo fail\n";
echo "transcript is:\n";print_r($out) . "\n";
return(FALSE);
}
$last = exec("rpm -ivh epel-release-6-7.noarch.rpm", $out, $rtn);
if($rtn != 0)
{
echo "FATAL! install EPEL repo fail\n";
echo "transcript is:\n";print_r($out) . "\n";
return(FALSE);
}
}
return(TRUE);
} // configYum
/**
* \brief restart the application passed in, so any config changes will take
* affect. Assumes application is restartable via /etc/init.d/<script>.
* The application passed in should match the script name in /etc/init.d
*
* @param string $application the application to restart. The application passed
* in should match the script name in /etc/init.d
*
* @return boolen
*/
function restart($application)
{
if(empty($application))
{
return(FALSE);
}
$last = exec("/etc/init.d/$application restart 2>&1", $out, $rtn);
if($rtn != 0)
{
echo "FATAL! could not restart $application\n";
echo "transcript is:\n";print_r($out) . "\n";
return(FALSE);
}
return(TRUE);
} // restart
/**
* \brief start the application
* Assumes application is restartable via /etc/init.d/<script>.
* The application passed in should match the script name in /etc/init.d
*
* @param string $application the application to start. The application passed
* in should match the script name in /etc/init.d
*
* @return boolen
*/
function start($application)
{
if(empty($application))
{
return(FALSE);
}
echo "Starting $application ...\n";
$last = exec("/etc/init.d/$application restart 2>&1", $out, $rtn);
if($rtn != 0)
{
echo "FATAL! could not start $application\n";
echo "transcript is:\n";print_r($out) . "\n";
return(FALSE);
}
return(TRUE);
} // start
/**
* \brief stop the application
* Assumes application is restartable via /etc/init.d/<script>.
* The application passed in should match the script name in /etc/init.d
*
* @param string $application the application to stop. The application passed
* in should match the script name in /etc/init.d
*
* @return boolen
*/
function stop($application)
{
if(empty($application))
{
return(FALSE);
}
$last = exec("/etc/init.d/$application stop 2>&1", $out, $rtn);
if($rtn != 0)
{
echo "FATAL! could not stop $application\n";
echo "transcript is:\n";print_r($out) . "\n";
return(FALSE);
}
return(TRUE);
} // stop
/**
* \brief wget the pg_hba.conf file and place it in $destPath
*
* @param string $destPath the full path to the destination
* @return boolean, TRUE on success, FALSE otherwise.
*
*/
function getPGhba($destPath)
{
if(empty($destPath))
{
return(FALSE);
}
$wcmd = "wget -q -O $destPath " .
"http://fonightly.usa.hp.com/testfiles/pg_hba.conf ";
$last = exec($wcmd, $wOut, $wRtn);
if($wRtn != 0)
{
echo "Error, could not download pg_hba.conf file, pleases configure by hand\n";
echo "wget output is:\n" . implode("\n",$wOut) . "\n";
return(FALSE);
}
return(TRUE);
}
?>
| siemens/fossology | src/testing/install/test4packageinstall/testdata.php | PHP | gpl-2.0 | 33,275 |
// PR c++/85761
// { dg-do compile { target c++11 } }
template <typename T>
void out(const T& value);
struct foo {
void bar();
};
void foo::bar()
{
constexpr int COUNT = 10000;
auto run = []() {
out(COUNT); // { dg-error "9:not captured" }
};
run();
}
| Gurgel100/gcc | gcc/testsuite/g++.dg/cpp0x/lambda/lambda-const8.C | C++ | gpl-2.0 | 271 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>ssl::context::set_options (1 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../set_options.html" title="ssl::context::set_options">
<link rel="prev" href="../set_options.html" title="ssl::context::set_options">
<link rel="next" href="overload2.html" title="ssl::context::set_options (2 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../set_options.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../set_options.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.ssl__context.set_options.overload1"></a><a class="link" href="overload1.html" title="ssl::context::set_options (1 of 2 overloads)">ssl::context::set_options
(1 of 2 overloads)</a>
</h5></div></div></div>
<p>
Set options on the context.
</p>
<pre class="programlisting"><span class="keyword">void</span> <span class="identifier">set_options</span><span class="special">(</span>
<span class="identifier">options</span> <span class="identifier">o</span><span class="special">);</span>
</pre>
<p>
This function may be used to configure the SSL options used by the context.
</p>
<h6>
<a name="boost_asio.reference.ssl__context.set_options.overload1.h0"></a>
<span class="phrase"><a name="boost_asio.reference.ssl__context.set_options.overload1.parameters"></a></span><a class="link" href="overload1.html#boost_asio.reference.ssl__context.set_options.overload1.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl class="variablelist">
<dt><span class="term">o</span></dt>
<dd><p>
A bitmask of options. The available option values are defined in
the <a class="link" href="../../ssl__context_base.html" title="ssl::context_base"><code class="computeroutput"><span class="identifier">ssl</span><span class="special">::</span><span class="identifier">context_base</span></code></a> class. The
options are bitwise-ored with any existing value for the options.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.ssl__context.set_options.overload1.h1"></a>
<span class="phrase"><a name="boost_asio.reference.ssl__context.set_options.overload1.exceptions"></a></span><a class="link" href="overload1.html#boost_asio.reference.ssl__context.set_options.overload1.exceptions">Exceptions</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl class="variablelist">
<dt><span class="term">boost::system::system_error</span></dt>
<dd><p>
Thrown on failure.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.ssl__context.set_options.overload1.h2"></a>
<span class="phrase"><a name="boost_asio.reference.ssl__context.set_options.overload1.remarks"></a></span><a class="link" href="overload1.html#boost_asio.reference.ssl__context.set_options.overload1.remarks">Remarks</a>
</h6>
<p>
Calls <code class="computeroutput"><span class="identifier">SSL_CTX_set_options</span></code>.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../set_options.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../set_options.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/doc/html/boost_asio/reference/ssl__context/set_options/overload1.html | HTML | gpl-3.0 | 5,438 |
/* -*- c++ -*- */
/*
* Copyright (C) 2001-2003 William E. Kempf
* Copyright (C) 2007 Anthony Williams
* Copyright 2008,2009 Free Software Foundation, Inc.
*
* 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)
*/
/*
* This was extracted from Boost 1.35.0 and fixed.
*/
#ifndef INCLUDED_GRUEL_THREAD_GROUP_H
#define INCLUDED_GRUEL_THREAD_GROUP_H
#include <gruel/api.h>
#include <gruel/thread.h>
#include <boost/utility.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/function.hpp>
namespace gruel
{
class GRUEL_API thread_group : public boost::noncopyable
{
public:
thread_group();
~thread_group();
boost::thread* create_thread(const boost::function0<void>& threadfunc);
void add_thread(boost::thread* thrd);
void remove_thread(boost::thread* thrd);
void join_all();
void interrupt_all();
size_t size() const;
private:
std::list<boost::thread*> m_threads;
mutable boost::shared_mutex m_mutex;
};
}
#endif /* INCLUDED_GRUEL_THREAD_GROUP_H */
| manojgudi/sandhi | modules/gr36/gruel/src/include/gruel/thread_group.h | C | gpl-3.0 | 1,120 |
dojo.provide("dojox.data.tests.stores.AtomReadStore");
dojo.require("dojox.data.AtomReadStore");
dojo.require("dojo.data.api.Read");
dojox.data.tests.stores.AtomReadStore.getBlog1Store = function(){
return new dojox.data.AtomReadStore({url: require.toUrl("dojox/data/tests/stores/atom1.xml").toString()});
//return new dojox.data.AtomReadStore({url: "/sos/feeds/blog.php"});
};
/*
dojox.data.tests.stores.AtomReadStore.getBlog2Store = function(){
return new dojox.data.AtomReadStore({url: dojo.moduleUrl("dojox.data.tests", "stores/atom2.xml").toString()});
};
*/
dojox.data.tests.stores.AtomReadStore.error = function(t, d, errData){
// summary:
// The error callback function to be used for all of the tests.
//console.log("In here.");
//console.trace();
d.errback(errData);
}
doh.register("dojox.data.tests.stores.AtomReadStore",
[
{
name: "ReadAPI: Fetch_One",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of a basic fetch on AtomReadStore of a single item.
// description:
// Simple test of a basic fetch on AtomReadStore of a single item.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items, request){
t.is(1, items.length);
d.callback(true);
}
atomStore.fetch({
query: {
},
count: 1,
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, doh, d)
});
return d; //Object
}
},
{
name: "ReadAPI: Fetch_5_Streaming",
timeout: 5000, //1 second.
runTest: function(t) {
// summary:
// Simple test of a basic fetch on AtomReadStore.
// description:
// Simple test of a basic fetch on AtomReadStore.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
var count = 0;
function onItem(item, requestObj){
t.assertTrue(atomStore.isItem(item));
count++;
}
function onComplete(items, request){
t.is(5, count);
t.is(null, items);
d.callback(true);
}
//Get everything...
atomStore.fetch({
query: {
},
onBegin: null,
count: 5,
onItem: onItem,
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: Fetch_Paging",
timeout: 5000, //1 second.
runTest: function(t) {
// summary:
// Test of multiple fetches on a single result. Paging, if you will.
// description:
// Test of multiple fetches on a single result. Paging, if you will.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function dumpFirstFetch(items, request){
t.is(5, items.length);
request.start = 3;
request.count = 1;
request.onComplete = dumpSecondFetch;
atomStore.fetch(request);
}
function dumpSecondFetch(items, request){
console.log("dumpSecondFetch: got "+items.length);
t.is(1, items.length);
request.start = 0;
request.count = 5;
request.onComplete = dumpThirdFetch;
atomStore.fetch(request);
}
function dumpThirdFetch(items, request){
console.log("dumpThirdFetch: got "+items.length);
t.is(5, items.length);
request.start = 2;
request.count = 18;
request.onComplete = dumpFourthFetch;
atomStore.fetch(request);
}
function dumpFourthFetch(items, request){
console.log("dumpFourthFetch: got "+items.length);
t.is(18, items.length);
request.start = 5;
request.count = 11;
request.onComplete = dumpFifthFetch;
atomStore.fetch(request);
}
function dumpFifthFetch(items, request){
console.log("dumpFifthFetch: got "+items.length);
t.is(11, items.length);
request.start = 4;
request.count = 16;
request.onComplete = dumpSixthFetch;
atomStore.fetch(request);
}
function dumpSixthFetch(items, request){
console.log("dumpSixthFetch: got "+items.length);
t.is(16, items.length);
d.callback(true);
}
function completed(items, request){
t.is(7, items.length);
request.start = 1;
request.count = 5;
request.onComplete = dumpFirstFetch;
atomStore.fetch(request);
}
atomStore.fetch({
query: {
},
count: 7,
onComplete: completed,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: getLabel",
timeout: 5000, //1 second.
runTest: function(t) {
// summary:
// Simple test of the getLabel function against a store set that has a label defined.
// description:
// Simple test of the getLabel function against a store set that has a label defined.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items, request){
t.assertEqual(items.length, 1);
var label = atomStore.getLabel(items[0]);
t.assertTrue(label !== null);
d.callback(true);
}
atomStore.fetch({
query: {
},
count: 1,
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d;
}
},
{
name: "ReadAPI: getLabelAttributes",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the getLabelAttributes function against a store set that has a label defined.
// description:
// Simple test of the getLabelAttributes function against a store set that has a label defined.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items, request){
t.assertEqual(items.length, 1);
var labelList = atomStore.getLabelAttributes(items[0]);
t.assertTrue(dojo.isArray(labelList));
t.assertEqual("title", labelList[0]);
d.callback(true);
}
atomStore.fetch({
query: {
},
count: 1,
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d;
}
},
{
name: "ReadAPI: getValue",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the getValue function of the store.
// description:
// Simple test of the getValue function of the store.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function completedAll(items){
t.is(1, items.length);
t.assertTrue(atomStore.getValue(items[0], "summary") !== null);
t.assertTrue(atomStore.getValue(items[0], "content") !== null);
t.assertTrue(atomStore.getValue(items[0], "published") !== null);
t.assertTrue(atomStore.getValue(items[0], "updated") !== null);
console.log("typeof updated = "+typeof(atomStore.getValue(items[0], "updated")));
t.assertTrue(atomStore.getValue(items[0], "updated").getFullYear);
d.callback(true);
}
//Get one item and look at it.
atomStore.fetch({
query: {
},
count: 1,
onComplete: completedAll,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)});
return d; //Object
}
},
{
name: "ReadAPI: getValue_Failure",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the getValue function of the store.
// description:
// Simple test of the getValue function of the store.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var passed = false;
try{
var value = atomStore.getValue("NotAnItem", "foo");
}catch(e){
passed = true;
}
t.assertTrue(passed);
}
},
{
name: "ReadAPI: getValues",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the getValue function of the store.
// description:
// Simple test of the getValue function of the store.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function completedAll(items){
t.is(1, items.length);
var summary = atomStore.getValues(items[0], "summary");
t.assertTrue(dojo.isArray(summary));
var content = atomStore.getValues(items[0], "content");
t.assertTrue(dojo.isArray(content));
var published = atomStore.getValues(items[0], "published");
t.assertTrue(dojo.isArray(published));
var updated = atomStore.getValues(items[0], "updated");
t.assertTrue(dojo.isArray(updated));
d.callback(true);
}
//Get one item and look at it.
atomStore.fetch({
query: {
},
count: 1,
onComplete: completedAll,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error,
t,
d)
});
return d; //Object
}
},
{
name: "ReadAPI: getValues_Failure",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the getValue function of the store.
// description:
// Simple test of the getValue function of the store.
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var passed = false;
try{
var value = atomStore.getValues("NotAnItem", "foo");
}catch(e){
passed = true;
}
t.assertTrue(passed);
}
},
{
name: "ReadAPI: isItem",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the isItem function of the store
// description:
// Simple test of the isItem function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function completedAll(items){
t.is(5, items.length);
for(var i=0; i < items.length; i++){
t.assertTrue(atomStore.isItem(items[i]));
}
d.callback(true);
}
//Get everything...
atomStore.fetch({
query: {
},
count: 5,
onComplete: completedAll,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: hasAttribute",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the hasAttribute function of the store
// description:
// Simple test of the hasAttribute function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items){
t.is(1, items.length);
t.assertTrue(items[0] !== null);
var count = 0;
console.log("hasAttribute");
t.assertTrue(atomStore.hasAttribute(items[0], "author"));
t.assertTrue(atomStore.hasAttribute(items[0], "published"));
t.assertTrue(atomStore.hasAttribute(items[0], "updated"));
t.assertTrue(atomStore.hasAttribute(items[0], "category"));
t.assertTrue(atomStore.hasAttribute(items[0], "id"));
t.assertTrue(!atomStore.hasAttribute(items[0], "foo"));
t.assertTrue(!atomStore.hasAttribute(items[0], "bar"));
t.assertTrue(atomStore.hasAttribute(items[0], "summary"));
t.assertTrue(atomStore.hasAttribute(items[0], "content"));
t.assertTrue(atomStore.hasAttribute(items[0], "title"));
var summary = atomStore.getValue(items[0], "summary");
var content = atomStore.getValue(items[0], "content");
var title = atomStore.getValue(items[0], "title");
t.assertTrue(summary && summary.text && summary.type == "html");
t.assertTrue(content && content.text && content.type == "html");
t.assertTrue(title && title.text && title.type == "html");
//Test that null attributes throw an exception
try{
atomStore.hasAttribute(items[0], null);
t.assertTrue(false);
}catch (e){
}
d.callback(true);
}
//Get one item...
atomStore.fetch({
query: {
},
count: 1,
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: containsValue",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the containsValue function of the store
// description:
// Simple test of the containsValue function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items){
t.is(1, items.length);
t.assertTrue(atomStore.containsValue(items[0], "id","http://shaneosullivan.wordpress.com/2008/01/22/using-aol-hosted-dojo-with-your-custom-code/"));
d.callback(true);
}
//Get one item...
atomStore.fetch({
query: {
},
count: 1,
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: getAttributes",
timeout: 5000, //1 second
runTest: function(t) {
// summary:
// Simple test of the getAttributes function of the store
// description:
// Simple test of the getAttributes function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items){
t.is(1, items.length);
t.assertTrue(atomStore.isItem(items[0]));
var attributes = atomStore.getAttributes(items[0]);
console.log("getAttributes 4: "+attributes.length);
t.is(10, attributes.length);
d.callback(true);
}
//Get everything...
atomStore.fetch({
query: {
},
count: 1,
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: fetch_Category",
timeout: 5000, //1 second.
runTest: function(t) {
// summary:
// Retrieve items from the store by category
// description:
// Simple test of the getAttributes function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items){
t.is(2, items.length);
t.assertTrue(atomStore.isItem(items[0]));
t.assertTrue(atomStore.isItem(items[1]));
var categories = atomStore.getValues(items[0], "category");
t.assertTrue(dojo.some(categories, function(category){
return category.term == "aol";
}));
categories = atomStore.getValues(items[1], "category");
t.assertTrue(dojo.some(categories, function(category){
return category.term == "aol";
}));
d.callback(true);
}
//Get everything...
atomStore.fetch({
query: {
category: "aol"
},
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: fetch_byID",
timeout: 5000, //1 second.
runTest: function(t) {
// summary:
// Retrieve items from the store by category
// description:
// Simple test of the getAttributes function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items){
console.log("getById: items.length="+items.length)
t.is(1, items.length);
t.assertTrue(atomStore.isItem(items[0]));
var title = atomStore.getValue(items[0], "title");
console.log("getById: title.text="+title.text)
t.assertTrue(title.text == "Dojo Grid has landed");
d.callback(true);
}
//Get everything...
atomStore.fetch({
query: {
id: "http://shaneosullivan.wordpress.com/2007/10/05/dojo-grid-has-landed/"
},
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
{
name: "ReadAPI: fetch_alternate",
timeout: 5000, //1 second.
runTest: function(t) {
// summary:
// Retrieve items from the store by category
// description:
// Simple test of the getAttributes function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var d = new doh.Deferred();
function onComplete(items){
t.is(1, items.length);
t.assertTrue(atomStore.isItem(items[0]));
var alternate = atomStore.getValue(items[0], "alternate");
t.assertEqual(alternate.href, "http://shaneosullivan.wordpress.com/2007/10/05/dojo-grid-has-landed/");
d.callback(true);
}
//Get everything...
atomStore.fetch({
query: {
id: "http://shaneosullivan.wordpress.com/2007/10/05/dojo-grid-has-landed/"
},
onComplete: onComplete,
onError: dojo.partial(dojox.data.tests.stores.AtomReadStore.error, t, d)
});
return d; //Object
}
},
function testReadAPI_getFeatures(t){
// summary:
// Simple test of the getFeatures function of the store
// description:
// Simple test of the getFeatures function of the store
var atomStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var features = atomStore.getFeatures();
var count = 0;
for(i in features){
t.assertTrue((i === "dojo.data.api.Read"));
count++;
}
t.assertTrue(count === 1);
},
function testReadAPI_functionConformance(t){
// summary:
// Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.
// description:
// Simple test read API conformance. Checks to see all declared functions are actual functions on the instances.
var testStore = dojox.data.tests.stores.AtomReadStore.getBlog1Store();
var readApi = new dojo.data.api.Read();
var passed = true;
for(i in readApi){
if(i.toString().charAt(0) !== '_')
{
var member = readApi[i];
//Check that all the 'Read' defined functions exist on the test store.
if(typeof member === "function"){
console.log("Looking at function: [" + i + "]");
var testStoreMember = testStore[i];
if(!(typeof testStoreMember === "function")){
console.log("Problem with function: [" + i + "]. Got value: " + testStoreMember);
passed = false;
break;
}
}
}
}
t.assertTrue(passed);
}
]
);
| avz-cmf/zaboy-middleware | www/js/dojox/data/tests/stores/AtomReadStore.js | JavaScript | gpl-3.0 | 18,579 |
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code 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.
Doom 3 Source 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 for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
const int BUILD_NUMBER = 1304;
| kphillisjr/DOOM-3-ID | neo/framework/BuildVersion.h | C | gpl-3.0 | 1,521 |
"""
CryptoPK v0.01
Cryptographic Public Key Code Signing/Verification Classes Based on RSASSA-PKCS1-v1_5
Features a complete digital signature/verification implementation
If no RSA key pair exists then one will be created automatically
A signed package is a json dictionary containing:
- RSA public key
- base64 encoded signature (RSA4096 encrypted SHA512 hash of the plain text and package name)
- base64 encoded plain text data (may be zlib compressed)
- MD5 hash of the plain text
- package name
- compression flag
The signature guarantees the origin of the package contents to the owner of the public key
Copyright 2013 Brian Monkaba
This file is part of ga-bitbot.
ga-bitbot 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.
ga-bitbot 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 ga-bitbot. If not, see <http://www.gnu.org/licenses/>.
"""
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512
from Crypto.Hash import MD5
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto import Random
import hashlib
import base64
import json
import zlib
import random
import time
import logging
import sys
import getpass
logger = logging.getLogger(__name__)
class CryptoPKSign:
def __init__(self,key_path=''):
self.key_path = key_path
self.pub = ''
self.prv = ''
self.prv_key_locked = True
try: #load existing priv/pub key pair if available
f = open(self.key_path + 'public.key')
self.pub = f.read()
f.close()
f = open(self.key_path + 'private.key')
self.prv = f.read()
f.close()
except: #if no key pair exists then create one
logger.info("CryptoPKSign:__init__: no existing keys found, generating a new key pair")
self.__gen_key_pair()
return
def __gen_key_pair(self):
import os
#generate a public/private key pair
self.rsa=RSA.generate(4096,os.urandom)
self.pub = self.rsa.publickey().exportKey() #public key
self.prv = self.rsa.exportKey() #private key
#save the key pair
f = open(self.key_path + 'public.key','w')
f.write(self.pub)
f.close()
f = open(self.key_path + 'private.key','w')
f.write(self.prv)
f.close()
def unlock_private_key(self):
if self.prv_key_locked == True:
#decrypts the private key
try: #load the salt file
f = open(self.key_path+'salt.txt','r')
salt = f.read()
f.close()
logger.info("CryptoPKSign:__init__: salt loaded")
except: #salt file not found, generate a new salt
pre_salt = str(time.time() * random.random() * 1000000) + 'H7gfJ8756Jg7HBJGtbnm856gnnblkjiINBMBV734'
salt = hashlib.sha512(pre_salt).digest()
f = open(self.key_path+'salt.txt','w')
f.write(salt)
f.close()
logger.info("CryptoPKSign:__init__: new salt file generated")
if self.prv.find('BEGIN RSA PRIVATE KEY') > -1:#check to see if the private key is encrypted
logger.warning("CryptoPKSign:__init__: non-enrypted private key found")
print "\n\nPrivate key is not encrypted\nEnter a new password to encrypt the private key:"
password = raw_input()
hash_pass = hashlib.sha256(password + salt).digest()
iv = Random.new().read(AES.block_size)
encryptor = AES.new(hash_pass, AES.MODE_CBC,iv)
text = json.dumps(self.prv)
pad_len = 16 - len(text)%16 #pad the text
text += " " * pad_len
ciphertext = iv + encryptor.encrypt(text) #prepend the iv parameter to the encrypted data
f = open(self.key_path + 'private.key','w')
f.write(ciphertext)
f.close()
else:
#request password to decrypt private key
print "\n\nEnter the private key password:"
password = getpass.getpass()
hash_pass = hashlib.sha256(password + salt).digest()
decryptor = AES.new(hash_pass, AES.MODE_CBC,self.prv[:AES.block_size])
text = decryptor.decrypt(self.prv[AES.block_size:])
try:
self.prv = json.loads(text)
except:
logger.error("CryptoPKSign:unlock_private_key: invalid password or corrupted encrypted private key file found")
sys.exit()
self.prv_key_locked = False
return
def sign(self,plain_text,package_name='',compress_package=False):
#returns a public key signed package as a json string
self.unlock_private_key()
#MD5 is intended to be used by receivers who wish to validate that they have the latest package.
md=MD5.new(plain_text).hexdigest()
h=SHA512.new(plain_text + package_name + md + str(compress_package))
key = RSA.importKey(self.prv) #import the private key
signature = base64.b64encode(PKCS1_v1_5.new(key).sign(h)) #sign & convert to base64 encoding
if compress_package == True:
plain_text = zlib.compress(plain_text,9)
str_d = json.dumps({'public_key':self.pub,'signature':signature,'plain_text':base64.b64encode(plain_text),'package_name':package_name,'MD5':md,'compressed':compress_package})
return str_d
def sign_file(self,filename,package_name='',compress_package=False):
try:
f = open(filename)
except:
raise Exception("CryptoPKSign:sign_file:ERROR: file not found")
plain_text = f.read()
f.close()
return self.sign(plain_text,package_name,compress_package)
class CryptoPKVerify:
def __init__(self,package,trusted_keys = []):
#package is the json output created by CryptoPKSign.sign
#if verification fails the plain text will not be made available
#trusted_keys is a list of trusted public keys
self.plain_text = ''
self.verified = False
self.trusted_source = False
self.md5 = ''
try:
package = json.loads(package)
except:
raise Exception("CryptoPKVerify:__init__:ERROR: package json loading failed")
self.package_name = package['package_name']
if package['public_key'] in trusted_keys:
self.trusted_source = True
#check to see if package is compressed
if package['compressed'] == True:
try:
plain_text = zlib.decompress(base64.b64decode(package['plain_text']))
except:
raise Exception("CryptoPKVerify:__init__:ERROR: package decompression failed")
else:
try:
plain_text = base64.b64decode(package['plain_text'])
except:
raise Exception("CryptoPKVerify:__init__:ERROR: package base64 decoding failed")
#verify the MD5 hash sent inside the package
self.md5 = MD5.new(plain_text).hexdigest()
if self.md5 != package['MD5']:
raise Exception("CryptoPKVerify:__init__:ERROR: package MD5 verification failed")
#verify the package
key = RSA.importKey(package['public_key'])
h=SHA512.new(plain_text + self.package_name + package['MD5'] + str(package['compressed']))
self.verified = PKCS1_v1_5.new(key).verify(h,base64.b64decode(package['signature']))
if self.verified:
self.plain_text = plain_text
return
def verify_local_file(self,filename = ''):
if filename == '':
#use the implied filename from the package_name
filename = self.package_name
if self.verified == False:
raise Exception("CryptoPKVerify:verify_local_file:ERROR: package failed verifiction")
if self.trusted_source == False:
raise Exception("CryptoPKVerify:verify_local_file:ERROR: package is from an untrusted source")
try:
f = open(filename)
local_plain_text = f.read()
f.close()
except:
logger.info("CryptoPKVerify:verify_local_file: local file does not exist")
return False
if MD5.new(local_plain_text).hexdigest() == self.md5:
logger.info("CryptoPKVerify:verify_local_file: local file is up to date")
return True
else:
logger.info("CryptoPKVerify:verify_local_file: local file is out of date")
return False
def update_local_file(self,filename = ''):
if self.verify_local_file(filename) == False and self.verified: #verified test is redundant but better safe than sorry :)
#package is valid and local file either does not exist or is out of date
#update the file
if filename == '':
#use the implied filename from the package_name
filename = self.package_name
f = open(filename,'w')
f.write(self.plain_text)
f.close()
logger.info("CryptoPKVerify:update_local_file: local file is now up to date")
else:
logger.info("CryptoPKVerify:update_local_file: local file is already up to date")
return True
if __name__ == '__main__':
print "*"*80
print "Cryptographic public key code signing/verification class library"
print "based on RSASSA-PKCS1-v1_5"
print "Testing module..."
print "*"*80
print "CryptoPK:__main__:INFO: Signing a package"
signer = CryptoPKSign()
trusted_keys = [signer.pub] #in real world use the trusted keys are provided, this is for testing only
package = signer.sign('I am not sure if this is at all correct.')
print "CryptoPK:__main__:INFO: Verifying the package"
receiver = CryptoPKVerify(package,trusted_keys)
if receiver.verified: #should pass
print "CryptoPK:__main__:INFO: Package verified."
print "CryptoPK:__main__:INFO: Plain text: ",receiver.plain_text
else:
print "CryptoPK:__main__:INFO: Package verification failed."
print "CryptoPK:__main__:INFO: Plain text: ",receiver.plain_text
print "CryptoPK:__main__:INFO: Corrupting the public key"
package = package[:64] + 'A' + package[65:]
package = package[:90] + '1' + package[91:]
receiver = CryptoPKVerify(package,trusted_keys)
if receiver.verified: #should fail
print "CryptoPK:__main__:INFO: Package verified."
print "CryptoPK:__main__:INFO: Plain text: ",receiver.plain_text
else:
print "CryptoPK:__main__:INFO: Package verification failed."
#if verification fails plain text will not be available
print "CryptoPK:__main__:INFO: Plain text: ",receiver.plain_text
print "CryptoPK:__main__:INFO: Using an untrusted public key"
trusted_keys2 = []
receiver = CryptoPKVerify(package,trusted_keys2)
if receiver.verified: #should fail
print "CryptoPK:__main__:INFO: Package verified."
print "CryptoPK:__main__:INFO: Plain text: ",receiver.plain_text
else:
print "CryptoPK:__main__:INFO: Package verification failed."
#if verification fails plain text will not be available
print "CryptoPK:__main__:INFO: Plain text: ",receiver.plain_text
#quick visual benchmark
print "CryptoPK:__main__:INFO: Signing 100 messages"
signer = CryptoPKSign()
pkg_lst = []
for i in xrange(100):
pkg_lst.append(signer.sign(str(i)+'kjhsdkfhglksdjghkl'+('*'*1200)+'sdjfghklsdjghklsdjfg'+str(i)))
print "CryptoPK:__main__:INFO: Verifying 100 messages"
pass_count = 0
for pkg in pkg_lst:
receiver = CryptoPKVerify(pkg,trusted_keys)
if receiver.verified:
pass_count += 1
print "CryptoPK:__main__:INFO: Messages verified:",pass_count
print "CryptoPK:__main__:INFO: Signing this module"
package = CryptoPKSign().sign(open('CryptoPK.py').read(),'CryptoPK.py')
receiver = CryptoPKVerify(package,trusted_keys)
if receiver.verified: #should pass
print "CryptoPK:__main__:INFO: Package verified."
#print "Plain text: ",receiver.plain_text
else:
print "CryptoPK:__main__:INFO: Package verification failed."
#print "Plain text: ",receiver.plain_text
print "CryptoPK:__main__:INFO: Uncompressed package length:",len(package)
print "CryptoPK:__main__:INFO: Signing this module - compressed package"
package = CryptoPKSign().sign(open('CryptoPK.py').read(),'CryptoPK.py',compress_package=True)
receiver = CryptoPKVerify(package,trusted_keys)
if receiver.verified: #should pass
print "CryptoPK:__main__:INFO: Package verified."
#print "Plain text: ",receiver.plain_text
else:
print "CryptoPK:__main__:INFO: Package verification failed."
#print "Plain text: ",receiver.plain_text
print "CryptoPK:__main__:INFO: Compressed length:",len(package)
print "CryptoPK:__main__:INFO: Verifying status of local files..."
receiver.verify_local_file('CryptoPK.py') #explicit filename
receiver.verify_local_file() #implied filename from package name
receiver.verify_local_file('asdf') #file not found
#receiver.verify_local_file('sign.py') #file out of date (difference found)
receiver.update_local_file('asdf') #file not found, will create a new one with the package contents
print "CryptoPK:__main__:INFO:"+" -"*20 + ' START OF PACKAGE DUMP ' + "-"*20
print package
print "CryptoPK:__main__:INFO:"+" -"*20 + ' END OF PACKAGE DUMP ' + "-"*20
#print "CryptoPK:__main__:INFO: Saving the test package"
#f = open('test_package.txt','w')
#f.write(package)
#f.close()
| matthusby/ga-bitbot | libs/CryptoPK.py | Python | gpl-3.0 | 14,521 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.apache.commons.math3.analysis.function;
import org.apache.commons.math3.analysis.FunctionUtils;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction;
import org.apache.commons.math3.analysis.ParametricUnivariateFunction;
import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.util.FastMath;
/**
* <a href="http://en.wikipedia.org/wiki/Generalised_logistic_function">
* Generalised logistic</a> function.
*
* @since 3.0
*/
public class Logistic implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction {
/** Lower asymptote. */
private final double a;
/** Upper asymptote. */
private final double k;
/** Growth rate. */
private final double b;
/** Parameter that affects near which asymptote maximum growth occurs. */
private final double oneOverN;
/** Parameter that affects the position of the curve along the ordinate axis. */
private final double q;
/** Abscissa of maximum growth. */
private final double m;
/**
* @param k If {@code b > 0}, value of the function for x going towards +∞.
* If {@code b < 0}, value of the function for x going towards -∞.
* @param m Abscissa of maximum growth.
* @param b Growth rate.
* @param q Parameter that affects the position of the curve along the
* ordinate axis.
* @param a If {@code b > 0}, value of the function for x going towards -∞.
* If {@code b < 0}, value of the function for x going towards +∞.
* @param n Parameter that affects near which asymptote the maximum
* growth occurs.
* @throws NotStrictlyPositiveException if {@code n <= 0}.
*/
public Logistic(double k,
double m,
double b,
double q,
double a,
double n)
throws NotStrictlyPositiveException {
if (n <= 0) {
throw new NotStrictlyPositiveException(n);
}
this.k = k;
this.m = m;
this.b = b;
this.q = q;
this.a = a;
oneOverN = 1 / n;
}
/** {@inheritDoc} */
public double value(double x) {
return value(m - x, k, b, q, a, oneOverN);
}
/** {@inheritDoc}
* @deprecated as of 3.1, replaced by {@link #value(DerivativeStructure)}
*/
@Deprecated
public UnivariateFunction derivative() {
return FunctionUtils.toDifferentiableUnivariateFunction(this).derivative();
}
/**
* Parametric function where the input array contains the parameters of
* the {@link Logistic#Logistic(double,double,double,double,double,double)
* logistic function}, ordered as follows:
* <ul>
* <li>k</li>
* <li>m</li>
* <li>b</li>
* <li>q</li>
* <li>a</li>
* <li>n</li>
* </ul>
*/
public static class Parametric implements ParametricUnivariateFunction {
/**
* Computes the value of the sigmoid at {@code x}.
*
* @param x Value for which the function must be computed.
* @param param Values for {@code k}, {@code m}, {@code b}, {@code q},
* {@code a} and {@code n}.
* @return the value of the function.
* @throws NullArgumentException if {@code param} is {@code null}.
* @throws DimensionMismatchException if the size of {@code param} is
* not 6.
* @throws NotStrictlyPositiveException if {@code param[5] <= 0}.
*/
public double value(double x, double ... param)
throws NullArgumentException,
DimensionMismatchException,
NotStrictlyPositiveException {
validateParameters(param);
return Logistic.value(param[1] - x, param[0],
param[2], param[3],
param[4], 1 / param[5]);
}
/**
* Computes the value of the gradient at {@code x}.
* The components of the gradient vector are the partial
* derivatives of the function with respect to each of the
* <em>parameters</em>.
*
* @param x Value at which the gradient must be computed.
* @param param Values for {@code k}, {@code m}, {@code b}, {@code q},
* {@code a} and {@code n}.
* @return the gradient vector at {@code x}.
* @throws NullArgumentException if {@code param} is {@code null}.
* @throws DimensionMismatchException if the size of {@code param} is
* not 6.
* @throws NotStrictlyPositiveException if {@code param[5] <= 0}.
*/
public double[] gradient(double x, double ... param)
throws NullArgumentException,
DimensionMismatchException,
NotStrictlyPositiveException {
validateParameters(param);
final double b = param[2];
final double q = param[3];
final double mMinusX = param[1] - x;
final double oneOverN = 1 / param[5];
final double exp = FastMath.exp(b * mMinusX);
final double qExp = q * exp;
final double qExp1 = qExp + 1;
final double factor1 = (param[0] - param[4]) * oneOverN / FastMath.pow(qExp1, oneOverN);
final double factor2 = -factor1 / qExp1;
// Components of the gradient.
final double gk = Logistic.value(mMinusX, 1, b, q, 0, oneOverN);
final double gm = factor2 * b * qExp;
final double gb = factor2 * mMinusX * qExp;
final double gq = factor2 * exp;
final double ga = Logistic.value(mMinusX, 0, b, q, 1, oneOverN);
final double gn = factor1 * FastMath.log(qExp1) * oneOverN;
return new double[] { gk, gm, gb, gq, ga, gn };
}
/**
* Validates parameters to ensure they are appropriate for the evaluation of
* the {@link #value(double,double[])} and {@link #gradient(double,double[])}
* methods.
*
* @param param Values for {@code k}, {@code m}, {@code b}, {@code q},
* {@code a} and {@code n}.
* @throws NullArgumentException if {@code param} is {@code null}.
* @throws DimensionMismatchException if the size of {@code param} is
* not 6.
* @throws NotStrictlyPositiveException if {@code param[5] <= 0}.
*/
private void validateParameters(double[] param)
throws NullArgumentException,
DimensionMismatchException,
NotStrictlyPositiveException {
if (param == null) {
throw new NullArgumentException();
}
if (param.length != 6) {
throw new DimensionMismatchException(param.length, 6);
}
if (param[5] <= 0) {
throw new NotStrictlyPositiveException(param[5]);
}
}
}
/**
* @param mMinusX {@code m - x}.
* @param k {@code k}.
* @param b {@code b}.
* @param q {@code q}.
* @param a {@code a}.
* @param oneOverN {@code 1 / n}.
* @return the value of the function.
*/
private static double value(double mMinusX,
double k,
double b,
double q,
double a,
double oneOverN) {
return a + (k - a) / FastMath.pow(1 + q * FastMath.exp(b * mMinusX), oneOverN);
}
/** {@inheritDoc}
* @since 3.1
*/
public DerivativeStructure value(final DerivativeStructure t) {
return t.negate().add(m).multiply(b).exp().multiply(q).add(1).pow(oneOverN).reciprocal().multiply(k - a).add(a);
}
}
| happyjack27/autoredistrict | src/org/apache/commons/math3/analysis/function/Logistic.java | Java | gpl-3.0 | 9,080 |
<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8>
<title>Font family name parsing tests</title>
<link rel="author" title="John Daggett" href="mailto:[email protected]">
<link rel="help" href="http://www.w3.org/TR/css3-fonts/#font-family-prop" />
<link rel="help" href="http://www.w3.org/TR/css3-fonts/#font-prop" />
<meta name="assert" content="tests that valid font family names parse and invalid ones don't" />
<script type="text/javascript" src="/resources/testharness.js"></script>
<script type="text/javascript" src="/resources/testharnessreport.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="log"></div>
<pre id="display"></pre>
<style type="text/css" id="testbox"></style>
<script type="text/javascript">
function fontProp(n, size, s1, s2) { return (s1 ? s1 + " " : "") + (s2 ? s2 + " " : "") + size + " " + n; }
function font(n, size, s1, s2) { return "font: " + fontProp(n, size, s1, s2); }
// testrules
// namelist - font family list
// invalid - true if declarations won't parse in either font-family or font
// fontonly - only test with the 'font' property
// single - namelist includes only a single name (@font-face rules only allow a single name)
var testFontFamilyLists = [
/* basic syntax */
{ namelist: "simple", single: true },
{ namelist: "'simple'", single: true },
{ namelist: '"simple"', single: true },
{ namelist: "-simple", single: true },
{ namelist: "_simple", single: true },
{ namelist: "quite simple", single: true },
{ namelist: "quite _simple", single: true },
{ namelist: "quite -simple", single: true },
{ namelist: "0simple", invalid: true, single: true },
{ namelist: "simple!", invalid: true, single: true },
{ namelist: "simple()", invalid: true, single: true },
{ namelist: "quite@simple", invalid: true, single: true },
{ namelist: "#simple", invalid: true, single: true },
{ namelist: "quite 0simple", invalid: true, single: true },
{ namelist: "納豆嫌い", single: true },
{ namelist: "納豆嫌い, ick, patooey" },
{ namelist: "ick, patooey, 納豆嫌い" },
{ namelist: "納豆嫌い, 納豆大嫌い" },
{ namelist: "納豆嫌い, 納豆大嫌い, 納豆本当に嫌い" },
{ namelist: "納豆嫌い, 納豆大嫌い, 納豆本当に嫌い, 納豆は好みではない" },
{ namelist: "arial, helvetica, sans-serif" },
{ namelist: "arial, helvetica, 'times' new roman, sans-serif", invalid: true },
{ namelist: "arial, helvetica, \"times\" new roman, sans-serif", invalid: true },
{ namelist: "arial, helvetica, \"\\\"times new roman\", sans-serif" },
{ namelist: "arial, helvetica, '\\\"times new roman', sans-serif" },
{ namelist: "arial, helvetica, times 'new' roman, sans-serif", invalid: true },
{ namelist: "arial, helvetica, times \"new\" roman, sans-serif", invalid: true },
{ namelist: "\"simple", single: true },
{ namelist: "\\\"simple", single: true },
{ namelist: "\"\\\"simple\"", single: true },
{ namelist: "İsimple", single: true },
{ namelist: "ßsimple", single: true },
{ namelist: "ẙsimple", single: true },
/* escapes */
{ namelist: "\\s imple", single: true },
{ namelist: "\\073 imple", single: true },
{ namelist: "\\035 simple", single: true },
{ namelist: "sim\\035 ple", single: true },
{ namelist: "simple\\02cinitial", single: true },
{ namelist: "simple, \\02cinitial" },
{ namelist: "sim\\020 \\035 ple", single: true },
{ namelist: "sim\\020 5ple", single: true },
{ namelist: "\\@simple", single: true },
{ namelist: "\\@simple\\;", single: true },
{ namelist: "\\@font-face", single: true },
{ namelist: "\\@font-face\\;", single: true },
{ namelist: "\\031 \\036 px", single: true },
{ namelist: "\\031 \\036 px", single: true },
{ namelist: "\\1f4a9", single: true },
{ namelist: "\\01f4a9", single: true },
{ namelist: "\\0001f4a9", single: true },
{ namelist: "\\AbAb", single: true },
/* keywords */
{ namelist: "italic", single: true },
{ namelist: "bold", single: true },
{ namelist: "bold italic", single: true },
{ namelist: "italic bold", single: true },
{ namelist: "larger", single: true },
{ namelist: "smaller", single: true },
{ namelist: "bolder", single: true },
{ namelist: "lighter", single: true },
{ namelist: "default", invalid: true, fontonly: true, single: true },
{ namelist: "initial", invalid: true, fontonly: true, single: true },
{ namelist: "inherit", invalid: true, fontonly: true, single: true },
{ namelist: "normal", single: true },
{ namelist: "default, simple", invalid: true },
{ namelist: "initial, simple", invalid: true },
{ namelist: "inherit, simple", invalid: true },
{ namelist: "normal, simple" },
{ namelist: "simple, default", invalid: true },
{ namelist: "simple, initial", invalid: true },
{ namelist: "simple, inherit", invalid: true },
{ namelist: "simple, default bongo" },
{ namelist: "simple, initial bongo" },
{ namelist: "simple, inherit bongo" },
{ namelist: "simple, bongo default" },
{ namelist: "simple, bongo initial" },
{ namelist: "simple, bongo inherit" },
{ namelist: "simple, normal" },
{ namelist: "simple default", single: true },
{ namelist: "simple initial", single: true },
{ namelist: "simple inherit", single: true },
{ namelist: "simple normal", single: true },
{ namelist: "default simple", single: true },
{ namelist: "initial simple", single: true },
{ namelist: "inherit simple", single: true },
{ namelist: "normal simple", single: true },
{ namelist: "caption", single: true }, // these are keywords for the 'font' property but only when in the first position
{ namelist: "icon", single: true },
{ namelist: "menu", single: true }
];
if (window.SpecialPowers && SpecialPowers.getBoolPref("layout.css.unset-value.enabled")) {
testFontFamilyLists.push(
{ namelist: "unset", invalid: true, fontonly: true, single: true },
{ namelist: "unset, simple", invalid: true },
{ namelist: "simple, unset", invalid: true },
{ namelist: "simple, unset bongo" },
{ namelist: "simple, bongo unset" },
{ namelist: "simple unset", single: true },
{ namelist: "unset simple", single: true });
}
var gTest = 0;
/* strip out just values */
function extractDecl(rule)
{
var t = rule.replace(/[ \n]+/g, " ");
t = t.replace(/.*{[ \n]*/, "");
t = t.replace(/[ \n]*}.*/, "");
return t;
}
function testStyleRuleParse(decl, invalid) {
var sheet = document.styleSheets[1];
var rule = ".test" + gTest++ + " { " + decl + "; }";
while(sheet.cssRules.length > 0) {
sheet.deleteRule(0);
}
// shouldn't throw but improper handling of punctuation may cause some parsers to throw
try {
sheet.insertRule(rule, 0);
} catch (e) {
assert_unreached("unexpected error with " + decl + " ==> " + e.name);
}
assert_equals(sheet.cssRules.length, 1,
"strange number of rules (" + sheet.cssRules.length + ") with " + decl);
var s = extractDecl(sheet.cssRules[0].cssText);
if (invalid) {
assert_equals(s, "", "rule declaration shouldn't parse - " + rule + " ==> " + s);
} else {
assert_not_equals(s, "", "rule declaration should parse - " + rule);
// check that the serialization also parses
var r = ".test" + gTest++ + " { " + s + " }";
while(sheet.cssRules.length > 0) {
sheet.deleteRule(0);
}
try {
sheet.insertRule(r, 0);
} catch (e) {
assert_unreached("exception occurred parsing serialized form of rule - " + rule + " ==> " + r + " " + e.name);
}
var s2 = extractDecl(sheet.cssRules[0].cssText);
assert_not_equals(s2, "", "serialized form of rule should also parse - " + rule + " ==> " + r);
}
}
var kDefaultFamilySetting = "onelittlepiggywenttomarket";
function testFontFamilySetterParse(namelist, invalid) {
var el = document.getElementById("display");
el.style.fontFamily = kDefaultFamilySetting;
var def = el.style.fontFamily;
el.style.fontFamily = namelist;
if (!invalid) {
assert_not_equals(el.style.fontFamily, def, "fontFamily setter should parse - " + namelist);
var parsed = el.style.fontFamily;
el.style.fontFamily = kDefaultFamilySetting;
el.style.fontFamily = parsed;
assert_equals(el.style.fontFamily, parsed, "fontFamily setter should parse serialized form to identical serialization - " + parsed + " ==> " + el.style.fontFamily);
} else {
assert_equals(el.style.fontFamily, def, "fontFamily setter shouldn't parse - " + namelist);
}
}
var kDefaultFontSetting = "16px onelittlepiggywenttomarket";
function testFontSetterParse(n, size, s1, s2, invalid) {
var el = document.getElementById("display");
el.style.font = kDefaultFontSetting;
var def = el.style.font;
var fp = fontProp(n, size, s1, s2);
el.style.font = fp;
if (!invalid) {
assert_not_equals(el.style.font, def, "font setter should parse - " + fp);
var parsed = el.style.font;
el.style.font = kDefaultFontSetting;
el.style.font = parsed;
assert_equals(el.style.font, parsed, "font setter should parse serialized form to identical serialization - " + parsed + " ==> " + el.style.font);
} else {
assert_equals(el.style.font, def, "font setter shouldn't parse - " + fp);
}
}
var testFontVariations = [
{ size: "16px" },
{ size: "900px" },
{ size: "900em" },
{ size: "35%" },
{ size: "7832.3%" },
{ size: "xx-large" },
{ size: "larger", s1: "lighter" },
{ size: "16px", s1: "italic" },
{ size: "16px", s1: "italic", s2: "bold" },
{ size: "smaller", s1: "normal" },
{ size: "16px", s1: "normal", s2: "normal" },
{ size: "16px", s1: "400", s2: "normal" },
{ size: "16px", s1: "bolder", s2: "oblique" }
];
function testFamilyNameParsing() {
var i;
for (i = 0; i < testFontFamilyLists.length; i++) {
var tst = testFontFamilyLists[i];
var n = tst.namelist;
var t;
if (!tst.fontonly) {
t = "font-family: " + n;
test(function() { testStyleRuleParse(t, tst.invalid); }, t);
test(function() { testFontFamilySetterParse(n, tst.invalid); }, t + " (setter)");
}
var v;
for (v = 0; v < testFontVariations.length; v++) {
var f = testFontVariations[v];
t = font(n, f.size, f.s1, f.s2);
test(function() { testStyleRuleParse(t, tst.invalid); }, t);
test(function() { testFontSetterParse(n, f.size, f.s1, f.s2, tst.invalid); }, t + " (setter)");
}
}
}
testFamilyNameParsing();
</script>
</body>
</html>
| snehasi/servo | tests/wpt/mozilla/tests/css/test_font_family_parsing.html | HTML | mpl-2.0 | 10,479 |
var r = [
(new Array()).toString() == "",
(new Array(2)).toString() == ",",
(new Array(3)).toString() == ",,",
(new Array(3.0)).toString() == ",,",
(new Array(Math.ceil(3.2134567))).toString() == ",,,",
(new Array("3")).toString() == "3",
];
try {
new Array(2.1);
console.log("New array with FP value should have thrown an error");
} catch (e) {
result=r.every(function(s){return s;});
}
| muet/Espruino | tests/test_array_constructor.js | JavaScript | mpl-2.0 | 410 |
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2013 Live Networks, Inc. All rights reserved.
// An object that redirects one or more RTP/RTCP streams - forming a single
// multimedia session - into a 'Darwin Streaming Server' (for subsequent
// reflection to potentially arbitrarily many remote RTSP clients).
// Implementation
#include "DarwinInjector.hh"
#include <GroupsockHelper.hh>
////////// SubstreamDescriptor definition //////////
class SubstreamDescriptor {
public:
SubstreamDescriptor(RTPSink* rtpSink, RTCPInstance* rtcpInstance, unsigned trackId);
~SubstreamDescriptor();
SubstreamDescriptor*& next() { return fNext; }
RTPSink* rtpSink() const { return fRTPSink; }
RTCPInstance* rtcpInstance() const { return fRTCPInstance; }
char const* sdpLines() const { return fSDPLines; }
private:
SubstreamDescriptor* fNext;
RTPSink* fRTPSink;
RTCPInstance* fRTCPInstance;
char* fSDPLines;
};
////////// DarwinInjector implementation //////////
DarwinInjector* DarwinInjector::createNew(UsageEnvironment& env,
char const* applicationName,
int verbosityLevel) {
return new DarwinInjector(env, applicationName, verbosityLevel);
}
Boolean DarwinInjector::lookupByName(UsageEnvironment& env, char const* name,
DarwinInjector*& result) {
result = NULL; // unless we succeed
Medium* medium;
if (!Medium::lookupByName(env, name, medium)) return False;
if (!medium->isDarwinInjector()) {
env.setResultMsg(name, " is not a 'Darwin injector'");
return False;
}
result = (DarwinInjector*)medium;
return True;
}
DarwinInjector::DarwinInjector(UsageEnvironment& env,
char const* applicationName, int verbosityLevel)
: Medium(env),
fApplicationName(strDup(applicationName)), fVerbosityLevel(verbosityLevel),
fRTSPClient(NULL), fSubstreamSDPSizes(0),
fHeadSubstream(NULL), fTailSubstream(NULL), fSession(NULL), fLastTrackId(0), fResultString(NULL) {
}
DarwinInjector::~DarwinInjector() {
if (fSession != NULL) { // close down and delete the session
fRTSPClient->sendTeardownCommand(*fSession, NULL);
Medium::close(fSession);
}
delete fHeadSubstream;
delete[] (char*)fApplicationName;
Medium::close(fRTSPClient);
}
void DarwinInjector::addStream(RTPSink* rtpSink, RTCPInstance* rtcpInstance) {
if (rtpSink == NULL) return; // "rtpSink" should be non-NULL
SubstreamDescriptor* newDescriptor = new SubstreamDescriptor(rtpSink, rtcpInstance, ++fLastTrackId);
if (fHeadSubstream == NULL) {
fHeadSubstream = fTailSubstream = newDescriptor;
} else {
fTailSubstream->next() = newDescriptor;
fTailSubstream = newDescriptor;
}
fSubstreamSDPSizes += strlen(newDescriptor->sdpLines());
}
// Define a special subclass of "RTSPClient" that has a pointer field to a "DarwinInjector". We'll use this to implement RTSP ops:
class RTSPClientForDarwinInjector: public RTSPClient {
public:
RTSPClientForDarwinInjector(UsageEnvironment& env, char const* rtspURL, int verbosityLevel, char const* applicationName,
DarwinInjector* ourDarwinInjector)
: RTSPClient(env, rtspURL, verbosityLevel, applicationName, 0, -1),
fOurDarwinInjector(ourDarwinInjector) {}
virtual ~RTSPClientForDarwinInjector() {}
DarwinInjector* fOurDarwinInjector;
};
Boolean DarwinInjector
::setDestination(char const* remoteRTSPServerNameOrAddress,
char const* remoteFileName,
char const* sessionName,
char const* sessionInfo,
portNumBits remoteRTSPServerPortNumber,
char const* remoteUserName,
char const* remotePassword,
char const* sessionAuthor,
char const* sessionCopyright,
int timeout) {
char* sdp = NULL;
char* url = NULL;
Boolean success = False; // until we learn otherwise
do {
// Construct a RTSP URL for the remote stream:
char const* const urlFmt = "rtsp://%s:%u/%s";
unsigned urlLen
= strlen(urlFmt) + strlen(remoteRTSPServerNameOrAddress) + 5 /* max short len */ + strlen(remoteFileName);
url = new char[urlLen];
sprintf(url, urlFmt, remoteRTSPServerNameOrAddress, remoteRTSPServerPortNumber, remoteFileName);
// Begin by creating our RTSP client object:
fRTSPClient = new RTSPClientForDarwinInjector(envir(), url, fVerbosityLevel, fApplicationName, this);
if (fRTSPClient == NULL) break;
// Get the remote RTSP server's IP address:
struct in_addr addr;
{
NetAddressList addresses(remoteRTSPServerNameOrAddress);
if (addresses.numAddresses() == 0) break;
NetAddress const* address = addresses.firstAddress();
addr.s_addr = *(unsigned*)(address->data());
}
AddressString remoteRTSPServerAddressStr(addr);
// Construct a SDP description for the session that we'll be streaming:
char const* const sdpFmt =
"v=0\r\n"
"o=- %u %u IN IP4 127.0.0.1\r\n"
"s=%s\r\n"
"i=%s\r\n"
"c=IN IP4 %s\r\n"
"t=0 0\r\n"
"a=x-qt-text-nam:%s\r\n"
"a=x-qt-text-inf:%s\r\n"
"a=x-qt-text-cmt:source application:%s\r\n"
"a=x-qt-text-aut:%s\r\n"
"a=x-qt-text-cpy:%s\r\n";
// plus, %s for each substream SDP
unsigned sdpLen = strlen(sdpFmt)
+ 20 /* max int len */ + 20 /* max int len */
+ strlen(sessionName)
+ strlen(sessionInfo)
+ strlen(remoteRTSPServerAddressStr.val())
+ strlen(sessionName)
+ strlen(sessionInfo)
+ strlen(fApplicationName)
+ strlen(sessionAuthor)
+ strlen(sessionCopyright)
+ fSubstreamSDPSizes;
unsigned const sdpSessionId = our_random32();
unsigned const sdpVersion = sdpSessionId;
sdp = new char[sdpLen];
sprintf(sdp, sdpFmt,
sdpSessionId, sdpVersion, // o= line
sessionName, // s= line
sessionInfo, // i= line
remoteRTSPServerAddressStr.val(), // c= line
sessionName, // a=x-qt-text-nam: line
sessionInfo, // a=x-qt-text-inf: line
fApplicationName, // a=x-qt-text-cmt: line
sessionAuthor, // a=x-qt-text-aut: line
sessionCopyright // a=x-qt-text-cpy: line
);
char* p = &sdp[strlen(sdp)];
SubstreamDescriptor* ss;
for (ss = fHeadSubstream; ss != NULL; ss = ss->next()) {
sprintf(p, "%s", ss->sdpLines());
p += strlen(p);
}
// Do a RTSP "ANNOUNCE" with this SDP description:
Authenticator auth;
Authenticator* authToUse = NULL;
if (remoteUserName[0] != '\0' || remotePassword[0] != '\0') {
auth.setUsernameAndPassword(remoteUserName, remotePassword);
authToUse = &auth;
}
fWatchVariable = 0;
(void)fRTSPClient->sendAnnounceCommand(sdp, genericResponseHandler, authToUse);
// Now block (but handling events) until we get a response:
envir().taskScheduler().doEventLoop(&fWatchVariable);
delete[] fResultString;
if (fResultCode != 0) break; // an error occurred with the RTSP "ANNOUNCE" command
// Next, tell the remote server to start receiving the stream from us.
// (To do this, we first create a "MediaSession" object from the SDP description.)
fSession = MediaSession::createNew(envir(), sdp);
if (fSession == NULL) break;
ss = fHeadSubstream;
MediaSubsessionIterator iter(*fSession);
MediaSubsession* subsession;
ss = fHeadSubstream;
unsigned streamChannelId = 0;
while ((subsession = iter.next()) != NULL) {
if (!subsession->initiate()) break;
fWatchVariable = 0;
(void)fRTSPClient->sendSetupCommand(*subsession, genericResponseHandler,
True /*streamOutgoing*/,
True /*streamUsingTCP*/);
// Now block (but handling events) until we get a response:
envir().taskScheduler().doEventLoop(&fWatchVariable);
delete[] fResultString;
if (fResultCode != 0) break; // an error occurred with the RTSP "SETUP" command
// Tell this subsession's RTPSink and RTCPInstance to use
// the RTSP TCP connection:
ss->rtpSink()->setStreamSocket(fRTSPClient->socketNum(), streamChannelId++);
if (ss->rtcpInstance() != NULL) {
ss->rtcpInstance()->setStreamSocket(fRTSPClient->socketNum(),
streamChannelId++);
}
ss = ss->next();
}
if (subsession != NULL) break; // an error occurred above
// Tell the RTSP server to start:
fWatchVariable = 0;
(void)fRTSPClient->sendPlayCommand(*fSession, genericResponseHandler);
// Now block (but handling events) until we get a response:
envir().taskScheduler().doEventLoop(&fWatchVariable);
delete[] fResultString;
if (fResultCode != 0) break; // an error occurred with the RTSP "PLAY" command
// Finally, make sure that the output TCP buffer is a reasonable size:
increaseSendBufferTo(envir(), fRTSPClient->socketNum(), 100*1024);
success = True;
} while (0);
delete[] sdp;
delete[] url;
return success;
}
Boolean DarwinInjector::isDarwinInjector() const {
return True;
}
void DarwinInjector::genericResponseHandler(RTSPClient* rtspClient, int responseCode, char* responseString) {
DarwinInjector* di = ((RTSPClientForDarwinInjector*)rtspClient)-> fOurDarwinInjector;
di->genericResponseHandler1(responseCode, responseString);
}
void DarwinInjector::genericResponseHandler1(int responseCode, char* responseString) {
// Set result values:
fResultCode = responseCode;
fResultString = responseString;
// Signal a break from the event loop (thereby returning from the blocking command):
fWatchVariable = ~0;
}
////////// SubstreamDescriptor implementation //////////
SubstreamDescriptor::SubstreamDescriptor(RTPSink* rtpSink,
RTCPInstance* rtcpInstance, unsigned trackId)
: fNext(NULL), fRTPSink(rtpSink), fRTCPInstance(rtcpInstance) {
// Create the SDP description for this substream
char const* mediaType = fRTPSink->sdpMediaType();
unsigned char rtpPayloadType = fRTPSink->rtpPayloadType();
char const* rtpPayloadFormatName = fRTPSink->rtpPayloadFormatName();
unsigned rtpTimestampFrequency = fRTPSink->rtpTimestampFrequency();
unsigned numChannels = fRTPSink->numChannels();
char* rtpmapLine;
if (rtpPayloadType >= 96) {
char* encodingParamsPart;
if (numChannels != 1) {
encodingParamsPart = new char[1 + 20 /* max int len */];
sprintf(encodingParamsPart, "/%d", numChannels);
} else {
encodingParamsPart = strDup("");
}
char const* const rtpmapFmt = "a=rtpmap:%d %s/%d%s\r\n";
unsigned rtpmapFmtSize = strlen(rtpmapFmt)
+ 3 /* max char len */ + strlen(rtpPayloadFormatName)
+ 20 /* max int len */ + strlen(encodingParamsPart);
rtpmapLine = new char[rtpmapFmtSize];
sprintf(rtpmapLine, rtpmapFmt,
rtpPayloadType, rtpPayloadFormatName,
rtpTimestampFrequency, encodingParamsPart);
delete[] encodingParamsPart;
} else {
// Static payload type => no "a=rtpmap:" line
rtpmapLine = strDup("");
}
unsigned rtpmapLineSize = strlen(rtpmapLine);
char const* auxSDPLine = fRTPSink->auxSDPLine();
if (auxSDPLine == NULL) auxSDPLine = "";
unsigned auxSDPLineSize = strlen(auxSDPLine);
char const* const sdpFmt =
"m=%s 0 RTP/AVP %u\r\n"
"%s" // "a=rtpmap:" line (if present)
"%s" // auxilliary (e.g., "a=fmtp:") line (if present)
"a=control:trackID=%u\r\n";
unsigned sdpFmtSize = strlen(sdpFmt)
+ strlen(mediaType) + 3 /* max char len */
+ rtpmapLineSize
+ auxSDPLineSize
+ 20 /* max int len */;
char* sdpLines = new char[sdpFmtSize];
sprintf(sdpLines, sdpFmt,
mediaType, // m= <media>
rtpPayloadType, // m= <fmt list>
rtpmapLine, // a=rtpmap:... (if present)
auxSDPLine, // optional extra SDP line
trackId); // a=control:<track-id>
fSDPLines = strDup(sdpLines);
delete[] sdpLines;
delete[] rtpmapLine;
}
SubstreamDescriptor::~SubstreamDescriptor() {
delete fSDPLines;
delete fNext;
}
| yuetianle/live555 | liveMedia/src/DarwinInjector.cpp | C++ | lgpl-2.1 | 12,613 |
#!/bin/bash
set -e
. "${GOPATH}"/src/github.com/google/trillian/integration/functions.sh
INTEGRATION_DIR="$( cd "$( dirname "$0" )" && pwd )"
. "${INTEGRATION_DIR}"/ct_functions.sh
# Default to one of everything.
RPC_SERVER_COUNT=${1:-1}
LOG_SIGNER_COUNT=${2:-1}
HTTP_SERVER_COUNT=${3:-1}
ct_prep_test "${RPC_SERVER_COUNT}" "${LOG_SIGNER_COUNT}" "${HTTP_SERVER_COUNT}"
# Cleanup for the Trillian components
TO_DELETE="${TO_DELETE} ${ETCD_DB_DIR}"
TO_KILL+=(${LOG_SIGNER_PIDS[@]})
TO_KILL+=(${RPC_SERVER_PIDS[@]})
TO_KILL+=(${ETCD_PID})
TO_KILL+=(${PROMETHEUS_PID})
TO_KILL+=(${ETCDISCOVER_PID})
# Cleanup for the personality
TO_DELETE="${TO_DELETE} ${CT_CFG}"
TO_KILL+=(${CT_SERVER_PIDS[@]})
echo "Running test(s)"
pushd "${INTEGRATION_DIR}"
set +e
go test -v -run ".*LiveCT.*" --timeout=5m ./ --log_config "${CT_CFG}" --ct_http_servers=${CT_SERVERS} --ct_metrics_servers=${CT_METRICS_SERVERS} --testdata_dir=${GOPATH}/src/github.com/google/certificate-transparency-go/trillian/testdata
RESULT=$?
set -e
popd
ct_stop_test
TO_KILL=()
exit $RESULT
| imcsk8/origin | vendor/github.com/google/certificate-transparency-go/trillian/integration/ct_integration_test.sh | Shell | apache-2.0 | 1,053 |
# Copyright 2016 The TensorFlow Authors. 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
# TODO: #6568 Remove this hack that makes dlopen() not crash.
if hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags'):
import ctypes
sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL)
from tensorflow.contrib.copy_graph.python.util import copy_elements
from tensorflow.contrib.tfprof.python.tools.tfprof import tfprof_logger
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
class TFProfLoggerTest(test.TestCase):
def _BuildSmallPlaceholderlModel(self):
a = array_ops.placeholder(dtypes.int32, [2, 2])
b = array_ops.placeholder(dtypes.int32, [2, 2])
y = math_ops.matmul(a, b)
return a, b, y
def _BuildSmallModel(self):
a = constant_op.constant([[1, 2], [3, 4]])
b = constant_op.constant([[1, 2], [3, 4]])
return math_ops.matmul(a, b)
def testFillMissingShape(self):
a, b, y = self._BuildSmallPlaceholderlModel()
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.FULL_TRACE)
run_metadata = config_pb2.RunMetadata()
sess = session.Session()
sess.run(y,
options=run_options,
run_metadata=run_metadata,
feed_dict={a: [[1, 2], [2, 3]],
b: [[1, 2], [2, 3]]})
graph2 = ops.Graph()
# Use copy_op_to_graph to remove shape information.
y2 = copy_elements.copy_op_to_graph(y, graph2, [])
self.assertEquals('<unknown>', str(y2.get_shape()))
tfprof_logger._fill_missing_graph_shape(graph2, run_metadata)
self.assertEquals('(2, 2)', str(y2.get_shape()))
def testFailedFillMissingShape(self):
y = self._BuildSmallModel()
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.FULL_TRACE)
run_metadata = config_pb2.RunMetadata()
sess = session.Session()
sess.run(y, options=run_options, run_metadata=run_metadata)
graph2 = ops.Graph()
y2 = copy_elements.copy_op_to_graph(y, graph2, [])
self.assertEquals('<unknown>', str(y2.get_shape()))
# run_metadata has special name for MatMul, hence failed to fill shape.
tfprof_logger._fill_missing_graph_shape(graph2, run_metadata)
self.assertEquals('<unknown>', str(y2.get_shape()))
if __name__ == '__main__':
test.main()
| anilmuthineni/tensorflow | tensorflow/contrib/tfprof/python/tools/tfprof/tfprof_logger_test.py | Python | apache-2.0 | 3,357 |
# -*- coding: utf-8 -*-
from nose.tools import * # noqa
import mock
import httplib as http
from tests.factories import AuthUserFactory
from framework.auth.decorators import Auth
from website.util import api_url_for
from website.addons.base.testing import views
from website.addons.dataverse.model import DataverseProvider
from website.addons.dataverse.serializer import DataverseSerializer
from website.addons.dataverse.tests.utils import (
create_mock_connection, DataverseAddonTestCase, create_external_account,
)
class TestAuthViews(DataverseAddonTestCase):
def test_deauthorize(self):
url = api_url_for('dataverse_deauthorize_node',
pid=self.project._primary_key)
self.app.delete(url, auth=self.user.auth)
self.node_settings.reload()
assert_false(self.node_settings.dataverse_alias)
assert_false(self.node_settings.dataverse)
assert_false(self.node_settings.dataset_doi)
assert_false(self.node_settings.dataset)
assert_false(self.node_settings.user_settings)
# Log states that node was deauthorized
self.project.reload()
last_log = self.project.logs[-1]
assert_equal(last_log.action, 'dataverse_node_deauthorized')
log_params = last_log.params
assert_equal(log_params['node'], self.project._primary_key)
assert_equal(log_params['project'], None)
def test_user_config_get(self):
url = api_url_for('dataverse_user_config_get')
new_user = AuthUserFactory.build()
res = self.app.get(url, auth=new_user.auth)
result = res.json.get('result')
assert_false(result['userHasAuth'])
assert_in('hosts', result)
assert_in('create', result['urls'])
# userHasAuth is true with external accounts
new_user.external_accounts.append(create_external_account())
new_user.save()
res = self.app.get(url, auth=self.user.auth)
result = res.json.get('result')
assert_true(result['userHasAuth'])
class TestConfigViews(DataverseAddonTestCase, views.OAuthAddonConfigViewsTestCaseMixin):
connection = create_mock_connection()
Serializer = DataverseSerializer
client = DataverseProvider
def setUp(self):
super(TestConfigViews, self).setUp()
self.mock_ser_api = mock.patch('website.addons.dataverse.serializer.client.connect_from_settings')
self.mock_ser_api.return_value = create_mock_connection()
self.mock_ser_api.start()
def tearDown(self):
self.mock_ser_api.stop()
super(TestConfigViews, self).tearDown()
@mock.patch('website.addons.dataverse.views.client.connect_from_settings')
def test_folder_list(self, mock_connection):
#test_get_datasets
mock_connection.return_value = self.connection
url = api_url_for('dataverse_get_datasets', pid=self.project._primary_key)
params = {'alias': 'ALIAS1'}
res = self.app.post_json(url, params, auth=self.user.auth)
assert_equal(len(res.json['datasets']), 3)
first = res.json['datasets'][0]
assert_equal(first['title'], 'Example (DVN/00001)')
assert_equal(first['doi'], 'doi:12.3456/DVN/00001')
@mock.patch('website.addons.dataverse.views.client.connect_from_settings')
def test_set_config(self, mock_connection):
mock_connection.return_value = self.connection
url = self.project.api_url_for('{0}_set_config'.format(self.ADDON_SHORT_NAME))
res = self.app.post_json(url, {
'dataverse': {'alias': 'ALIAS3'},
'dataset': {'doi': 'doi:12.3456/DVN/00003'},
}, auth=self.user.auth)
assert_equal(res.status_code, http.OK)
self.project.reload()
assert_equal(
self.project.logs[-1].action,
'{0}_dataset_linked'.format(self.ADDON_SHORT_NAME)
)
assert_equal(res.json['dataverse'], self.connection.get_dataverse('ALIAS3').title)
assert_equal(res.json['dataset'],
self.connection.get_dataverse('ALIAS3').get_dataset_by_doi('doi:12.3456/DVN/00003').title)
def test_get_config(self):
url = self.project.api_url_for('{0}_get_config'.format(self.ADDON_SHORT_NAME))
res = self.app.get(url, auth=self.user.auth)
assert_equal(res.status_code, http.OK)
assert_in('result', res.json)
serialized = self.Serializer().serialize_settings(
self.node_settings,
self.user,
)
assert_equal(serialized, res.json['result'])
@mock.patch('website.addons.dataverse.views.client.connect_from_settings')
def test_set_config_no_dataset(self, mock_connection):
mock_connection.return_value = self.connection
num_old_logs = len(self.project.logs)
url = api_url_for('dataverse_set_config',
pid=self.project._primary_key)
params = {
'dataverse': {'alias': 'ALIAS3'},
'dataset': {}, # The dataverse has no datasets
}
# Select a different dataset
res = self.app.post_json(url, params, auth=self.user.auth,
expect_errors=True)
self.node_settings.reload()
# Old settings did not change
assert_equal(res.status_code, http.BAD_REQUEST)
assert_equal(self.node_settings.dataverse_alias, 'ALIAS2')
assert_equal(self.node_settings.dataset, 'Example (DVN/00001)')
assert_equal(self.node_settings.dataset_doi, 'doi:12.3456/DVN/00001')
# Nothing was logged
self.project.reload()
assert_equal(len(self.project.logs), num_old_logs)
class TestHgridViews(DataverseAddonTestCase):
@mock.patch('website.addons.dataverse.views.client.connect_from_settings')
@mock.patch('website.addons.dataverse.views.client.get_files')
def test_dataverse_root_published(self, mock_files, mock_connection):
mock_connection.return_value = create_mock_connection()
mock_files.return_value = ['mock_file']
self.project.set_privacy('public')
self.project.save()
alias = self.node_settings.dataverse_alias
doi = self.node_settings.dataset_doi
external_account = create_external_account()
self.user.external_accounts.append(external_account)
self.user.save()
self.node_settings.set_auth(external_account, self.user)
self.node_settings.dataverse_alias = alias
self.node_settings.dataset_doi = doi
self.node_settings.save()
url = api_url_for('dataverse_root_folder',
pid=self.project._primary_key)
# Contributor can select between states, current state is correct
res = self.app.get(url, auth=self.user.auth)
assert_true(res.json[0]['permissions']['edit'])
assert_true(res.json[0]['hasPublishedFiles'])
assert_equal(res.json[0]['version'], 'latest-published')
# Non-contributor gets published version, no options
user2 = AuthUserFactory()
res = self.app.get(url, auth=user2.auth)
assert_false(res.json[0]['permissions']['edit'])
assert_true(res.json[0]['hasPublishedFiles'])
assert_equal(res.json[0]['version'], 'latest-published')
@mock.patch('website.addons.dataverse.views.client.connect_from_settings')
@mock.patch('website.addons.dataverse.views.client.get_files')
def test_dataverse_root_not_published(self, mock_files, mock_connection):
mock_connection.return_value = create_mock_connection()
mock_files.return_value = []
self.project.set_privacy('public')
self.project.save()
alias = self.node_settings.dataverse_alias
doi = self.node_settings.dataset_doi
external_account = create_external_account()
self.user.external_accounts.append(external_account)
self.user.save()
self.node_settings.set_auth(external_account, self.user)
self.node_settings.dataverse_alias = alias
self.node_settings.dataset_doi = doi
self.node_settings.save()
url = api_url_for('dataverse_root_folder',
pid=self.project._primary_key)
# Contributor gets draft, no options
res = self.app.get(url, auth=self.user.auth)
assert_true(res.json[0]['permissions']['edit'])
assert_false(res.json[0]['hasPublishedFiles'])
assert_equal(res.json[0]['version'], 'latest')
# Non-contributor gets nothing
user2 = AuthUserFactory()
res = self.app.get(url, auth=user2.auth)
assert_equal(res.json, [])
@mock.patch('website.addons.dataverse.views.client.connect_from_settings')
@mock.patch('website.addons.dataverse.views.client.get_files')
def test_dataverse_root_no_connection(self, mock_files, mock_connection):
mock_connection.return_value = create_mock_connection()
mock_files.return_value = ['mock_file']
url = api_url_for('dataverse_root_folder',
pid=self.project._primary_key)
mock_connection.return_value = None
res = self.app.get(url, auth=self.user.auth)
assert_equal(res.json, [])
def test_dataverse_root_incomplete(self):
self.node_settings.dataset_doi = None
self.node_settings.save()
url = api_url_for('dataverse_root_folder',
pid=self.project._primary_key)
res = self.app.get(url, auth=self.user.auth)
assert_equal(res.json, [])
class TestCrudViews(DataverseAddonTestCase):
@mock.patch('website.addons.dataverse.views.client.connect_from_settings_or_401')
@mock.patch('website.addons.dataverse.views.client.publish_dataset')
@mock.patch('website.addons.dataverse.views.client.publish_dataverse')
def test_dataverse_publish_dataset(self, mock_publish_dv, mock_publish_ds, mock_connection):
mock_connection.return_value = create_mock_connection()
url = api_url_for('dataverse_publish_dataset',
pid=self.project._primary_key)
self.app.put_json(url, params={'publish_both': False}, auth=self.user.auth)
# Only dataset was published
assert_false(mock_publish_dv.called)
assert_true(mock_publish_ds.called)
@mock.patch('website.addons.dataverse.views.client.connect_from_settings_or_401')
@mock.patch('website.addons.dataverse.views.client.publish_dataset')
@mock.patch('website.addons.dataverse.views.client.publish_dataverse')
def test_dataverse_publish_both(self, mock_publish_dv, mock_publish_ds, mock_connection):
mock_connection.return_value = create_mock_connection()
url = api_url_for('dataverse_publish_dataset',
pid=self.project._primary_key)
self.app.put_json(url, params={'publish_both': True}, auth=self.user.auth)
# Both Dataverse and dataset were published
assert_true(mock_publish_dv.called)
assert_true(mock_publish_ds.called)
class TestDataverseRestrictions(DataverseAddonTestCase):
def setUp(self):
super(DataverseAddonTestCase, self).setUp()
# Nasty contributor who will try to access content that he shouldn't
# have access to
self.contrib = AuthUserFactory()
self.project.add_contributor(self.contrib, auth=Auth(self.user))
self.project.save()
@mock.patch('website.addons.dataverse.views.client.connect_from_settings')
def test_restricted_set_dataset_not_owner(self, mock_connection):
mock_connection.return_value = create_mock_connection()
# Contributor has dataverse auth, but is not the node authorizer
self.contrib.add_addon('dataverse')
self.contrib.save()
url = api_url_for('dataverse_set_config', pid=self.project._primary_key)
params = {
'dataverse': {'alias': 'ALIAS1'},
'dataset': {'doi': 'doi:12.3456/DVN/00002'},
}
res = self.app.post_json(url, params, auth=self.contrib.auth,
expect_errors=True)
assert_equal(res.status_code, http.FORBIDDEN)
| zachjanicki/osf.io | website/addons/dataverse/tests/test_views.py | Python | apache-2.0 | 12,181 |
/**
* $RCSfile: ServerDialback.java,v $
* $Revision: 3188 $
* $Date: 2005-12-12 00:28:19 -0300 (Mon, 12 Dec 2005) $
*
* Copyright (C) 2005-2008 Jive Software. 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.
*/
package org.jivesoftware.openfire.server;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.XMPPPacketReader;
import org.jivesoftware.openfire.Connection;
import org.jivesoftware.openfire.RemoteConnectionFailedException;
import org.jivesoftware.openfire.RoutingTable;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.StreamID;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.net.DNSUtil;
import org.jivesoftware.openfire.net.MXParser;
import org.jivesoftware.openfire.net.ServerTrafficCounter;
import org.jivesoftware.openfire.net.SocketConnection;
import org.jivesoftware.openfire.session.IncomingServerSession;
import org.jivesoftware.openfire.session.LocalIncomingServerSession;
import org.jivesoftware.openfire.session.LocalOutgoingServerSession;
import org.jivesoftware.openfire.spi.BasicStreamIDFactory;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.StringUtils;
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.StreamError;
/**
* Implementation of the Server Dialback method as defined by the RFC3920.
*
* The dialback method follows the following logic to validate the remote server:
* <ol>
* <li>The Originating Server establishes a connection to the Receiving Server.</li>
* <li>The Originating Server sends a 'key' value over the connection to the Receiving
* Server.</li>
* <li>The Receiving Server establishes a connection to the Authoritative Server.</li>
* <li>The Receiving Server sends the same 'key' value to the Authoritative Server.</li>
* <li>The Authoritative Server replies that key is valid or invalid.</li>
* <li>The Receiving Server informs the Originating Server whether it is authenticated or
* not.</li>
* </ol>
*
* By default a timeout of 20 seconds will be used for reading packets from remote servers. Use
* the property <b>xmpp.server.read.timeout</b> to change that value. The value should be in
* milliseconds.
*
* @author Gaston Dombiak
*/
public class ServerDialback {
private static final Logger Log = LoggerFactory.getLogger(ServerDialback.class);
/**
* The utf-8 charset for decoding and encoding Jabber packet streams.
*/
protected static String CHARSET = "UTF-8";
/**
* Cache (unlimited, never expire) that holds the secret key to be used for
* encoding and decoding keys used for authentication.
* Key: constant hard coded value, Value: random generated string
*/
private static Cache<String, String> secretKeyCache;
private static XmlPullParserFactory FACTORY = null;
static {
try {
FACTORY = XmlPullParserFactory.newInstance(MXParser.class.getName(), null);
}
catch (XmlPullParserException e) {
Log.error("Error creating a parser factory", e);
}
secretKeyCache = CacheFactory.createCache("Secret Keys Cache");
}
private Connection connection;
private String serverName;
private SessionManager sessionManager = SessionManager.getInstance();
private RoutingTable routingTable = XMPPServer.getInstance().getRoutingTable();
/**
* Returns true if server dialback is enabled. When enabled remote servers may connect to this
* server using the server dialback method and this server may try the server dialback method
* to connect to remote servers.<p>
*
* When TLS is enabled between servers and server dialback method is enabled then TLS is going
* to be tried first, when connecting to a remote server, and if TLS fails then server dialback
* is going to be used as a last resort. If enabled and the remote server offered server-dialback
* after TLS and no SASL EXTERNAL then server dialback will be used.
*
* @return true if server dialback is enabled.
*/
public static boolean isEnabled() {
return JiveGlobals.getBooleanProperty("xmpp.server.dialback.enabled", true);
}
/**
* Returns true if server dialback can be used when the remote server presented a self-signed
* certificate. During TLS the remote server can present a self-signed certificate, if this
* setting is enabled then the self-signed certificate will be accepted and if SASL EXTERNAL
* is not offered then server dialback will be used for verifying the remote server.<p>
*
* If self-signed certificates are accepted then server dialback over TLS is enabled.
*
* @return true if server dialback can be used when the remote server presented a self-signed
* certificate.
*/
public static boolean isEnabledForSelfSigned() {
return JiveGlobals.getBooleanProperty("xmpp.server.certificate.accept-selfsigned", false);
}
/**
* Sets if server dialback can be used when the remote server presented a self-signed
* certificate. During TLS the remote server can present a self-signed certificate, if this
* setting is enabled then the self-signed certificate will be accepted and if SASL EXTERNAL
* is not offered then server dialback will be used for verifying the remote server.<p>
*
* If self-signed certificates are accepted then server dialback over TLS is enabled.
*
* @param enabled if server dialback can be used when the remote server presented a self-signed
* certificate.
*/
public static void setEnabledForSelfSigned(boolean enabled) {
JiveGlobals.setProperty("xmpp.server.certificate.accept-selfsigned", Boolean.toString(enabled));
}
/**
* Creates a new instance that will be used for creating {@link IncomingServerSession},
* validating subsequent domains or authenticatig new domains. Use
* {@link #createIncomingSession(org.dom4j.io.XMPPPacketReader)} for creating a new server
* session used for receiving packets from the remote server. Use
* {@link #validateRemoteDomain(org.dom4j.Element, org.jivesoftware.openfire.StreamID)} for
* validating subsequent domains and use
* {@link #authenticateDomain(OutgoingServerSocketReader, String, String, String)} for
* registering new domains that are allowed to send packets to the remote server.<p>
*
* For validating domains a new TCP connection will be established to the Authoritative Server.
* The Authoritative Server may be the same Originating Server or some other machine in the
* Originating Server's network. Once the remote domain gets validated the Originating Server
* will be allowed for sending packets to this server. However, this server will need to
* validate its domain/s with the Originating Server if this server needs to send packets to
* the Originating Server. Another TCP connection will be established for validation this
* server domain/s and for sending packets to the Originating Server.
*
* @param connection the connection created by the remote server.
* @param serverName the name of the local server.
*/
public ServerDialback(Connection connection, String serverName) {
this.connection = connection;
this.serverName = serverName;
}
public ServerDialback() {
}
/**
* Creates a new connection from the Originating Server to the Receiving Server for
* authenticating the specified domain.
*
* @param localDomain domain of the Originating Server to authenticate with the Receiving Server.
* @param remoteDomain IP address or hostname of the Receiving Server.
* @param port port of the Receiving Server.
* @return an OutgoingServerSession if the domain was authenticated or <tt>null</tt> if none.
*/
public LocalOutgoingServerSession createOutgoingSession(String localDomain, String remoteDomain, int port) {
String hostname = null;
int realPort = port;
try {
// Establish a TCP connection to the Receiving Server
Socket socket = new Socket();
// Get a list of real hostnames to connect to using DNS lookup of the specified hostname
List<DNSUtil.HostAddress> hosts = DNSUtil.resolveXMPPDomain(remoteDomain, port);
for (Iterator<DNSUtil.HostAddress> it = hosts.iterator(); it.hasNext();) {
try {
DNSUtil.HostAddress address = it.next();
hostname = address.getHost();
realPort = address.getPort();
Log.debug("ServerDialback: OS - Trying to connect to " + remoteDomain + ":" + port +
"(DNS lookup: " + hostname + ":" + realPort + ")");
// Establish a TCP connection to the Receiving Server
socket.connect(new InetSocketAddress(hostname, realPort),
RemoteServerManager.getSocketTimeout());
Log.debug("ServerDialback: OS - Connection to " + remoteDomain + ":" + port + " successful");
break;
}
catch (Exception e) {
Log.warn("Error trying to connect to remote server: " + remoteDomain +
"(DNS lookup: " + hostname + ":" + realPort + ")", e);
}
}
connection =
new SocketConnection(XMPPServer.getInstance().getPacketDeliverer(), socket,
false);
// Get a writer for sending the open stream tag
// Send to the Receiving Server a stream header
StringBuilder stream = new StringBuilder();
stream.append("<stream:stream");
stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
stream.append(" xmlns=\"jabber:server\"");
stream.append(" to=\"").append(remoteDomain).append("\"");
stream.append(" from=\"").append(localDomain).append("\"");
stream.append(" xmlns:db=\"jabber:server:dialback\"");
stream.append(" version=\"1.0\">");
connection.deliverRawText(stream.toString());
// Set a read timeout (of 5 seconds) so we don't keep waiting forever
int soTimeout = socket.getSoTimeout();
socket.setSoTimeout(RemoteServerManager.getSocketTimeout());
XMPPPacketReader reader = new XMPPPacketReader();
reader.setXPPFactory(FACTORY);
reader.getXPPParser().setInput(new InputStreamReader(
ServerTrafficCounter.wrapInputStream(socket.getInputStream()), CHARSET));
// Get the answer from the Receiving Server
XmlPullParser xpp = reader.getXPPParser();
for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) {
eventType = xpp.next();
}
if ("jabber:server:dialback".equals(xpp.getNamespace("db"))) {
// Restore default timeout
socket.setSoTimeout(soTimeout);
String id = xpp.getAttributeValue("", "id");
OutgoingServerSocketReader socketReader = new OutgoingServerSocketReader(reader);
if (authenticateDomain(socketReader, localDomain, remoteDomain, id)) {
// Domain was validated so create a new OutgoingServerSession
StreamID streamID = new BasicStreamIDFactory().createStreamID(id);
LocalOutgoingServerSession session = new LocalOutgoingServerSession(localDomain, connection, socketReader, streamID);
connection.init(session);
// Set the hostname as the address of the session
session.setAddress(new JID(null, remoteDomain, null));
return session;
}
else {
// Close the connection
connection.close();
}
}
else {
Log.debug("ServerDialback: OS - Invalid namespace in packet: " + xpp.getText());
// Send an invalid-namespace stream error condition in the response
connection.deliverRawText(
new StreamError(StreamError.Condition.invalid_namespace).toXML());
// Close the connection
connection.close();
}
}
catch (IOException e) {
Log.debug("ServerDialback: Error connecting to the remote server: " + remoteDomain + "(DNS lookup: " +
hostname + ":" + realPort + ")", e);
// Close the connection
if (connection != null) {
connection.close();
}
}
catch (Exception e) {
Log.error("Error creating outgoing session to remote server: " + remoteDomain +
"(DNS lookup: " +
hostname +
")",
e);
// Close the connection
if (connection != null) {
connection.close();
}
}
return null;
}
/**
* Authenticates the Originating Server domain with the Receiving Server. Once the domain has
* been authenticated the Receiving Server will start accepting packets from the Originating
* Server.<p>
*
* The Receiving Server will connect to the Authoritative Server to verify the dialback key.
* Most probably the Originating Server machine will be the Authoritative Server too.
*
* @param socketReader the reader to use for reading the answer from the Receiving Server.
* @param domain the domain to authenticate.
* @param hostname the hostname of the remote server (i.e. Receiving Server).
* @param id the stream id to be used for creating the dialback key.
* @return true if the Receiving Server authenticated the domain with the Authoritative Server.
*/
public boolean authenticateDomain(OutgoingServerSocketReader socketReader, String domain,
String hostname, String id) {
String key = AuthFactory.createDigest(id, getSecretkey());
Log.debug("ServerDialback: OS - Sent dialback key to host: " + hostname + " id: " + id + " from domain: " +
domain);
synchronized (socketReader) {
// Send a dialback key to the Receiving Server
StringBuilder sb = new StringBuilder();
sb.append("<db:result");
sb.append(" from=\"").append(domain).append("\"");
sb.append(" to=\"").append(hostname).append("\">");
sb.append(key);
sb.append("</db:result>");
connection.deliverRawText(sb.toString());
// Process the answer from the Receiving Server
try {
while (true) {
Element doc = socketReader.getElement(RemoteServerManager.getSocketTimeout(),
TimeUnit.MILLISECONDS);
if (doc == null) {
Log.debug("ServerDialback: OS - Time out waiting for answer in validation from: " + hostname +
" id: " +
id +
" for domain: " +
domain);
return false;
}
else if ("db".equals(doc.getNamespacePrefix()) && "result".equals(doc.getName())) {
boolean success = "valid".equals(doc.attributeValue("type"));
Log.debug("ServerDialback: OS - Validation " + (success ? "GRANTED" : "FAILED") + " from: " +
hostname +
" id: " +
id +
" for domain: " +
domain);
return success;
}
else {
Log.warn("ServerDialback: OS - Ignoring unexpected answer in validation from: " + hostname + " id: " +
id +
" for domain: " +
domain +
" answer:" +
doc.asXML());
}
}
}
catch (InterruptedException e) {
Log.debug("ServerDialback: OS - Validation FAILED from: " + hostname +
" id: " +
id +
" for domain: " +
domain, e);
return false;
}
}
}
/**
* Returns a new {@link IncomingServerSession} with a domain validated by the Authoritative
* Server. New domains may be added to the returned IncomingServerSession after they have
* been validated. See
* {@link LocalIncomingServerSession#validateSubsequentDomain(org.dom4j.Element)}. The remote
* server will be able to send packets through this session whose domains were previously
* validated.<p>
*
* When acting as an Authoritative Server this method will verify the requested key
* and will return null since the underlying TCP connection will be closed after sending the
* response to the Receiving Server.<p>
*
* @param reader reader of DOM documents on the connection to the remote server.
* @return an IncomingServerSession that was previously validated against the remote server.
* @throws IOException if an I/O error occurs while communicating with the remote server.
* @throws XmlPullParserException if an error occurs while parsing XML packets.
*/
public LocalIncomingServerSession createIncomingSession(XMPPPacketReader reader) throws IOException,
XmlPullParserException {
XmlPullParser xpp = reader.getXPPParser();
StringBuilder sb;
if ("jabber:server:dialback".equals(xpp.getNamespace("db"))) {
Log.debug("ServerDialback: Processing incoming session.");
StreamID streamID = sessionManager.nextStreamID();
sb = new StringBuilder();
sb.append("<stream:stream");
sb.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
sb.append(" xmlns=\"jabber:server\" xmlns:db=\"jabber:server:dialback\"");
sb.append(" id=\"");
sb.append(streamID.toString());
sb.append("\">");
connection.deliverRawText(sb.toString());
try {
Element doc = reader.parseDocument().getRootElement();
if ("db".equals(doc.getNamespacePrefix()) && "result".equals(doc.getName())) {
String hostname = doc.attributeValue("from");
String recipient = doc.attributeValue("to");
Log.debug("ServerDialback: RS - Validating remote domain for incoming session from {} to {}", hostname, recipient);
if (validateRemoteDomain(doc, streamID)) {
Log.debug("ServerDialback: RS - Validation of remote domain for incoming session from {} to {} was successful.", hostname, recipient);
// Create a server Session for the remote server
LocalIncomingServerSession session = sessionManager.
createIncomingServerSession(connection, streamID);
// Add the validated domain as a valid domain
session.addValidatedDomain(hostname);
// Set the domain or subdomain of the local server used when
// validating the session
session.setLocalDomain(recipient);
return session;
} else {
Log.debug("ServerDialback: RS - Validation of remote domain for incoming session from {} to {} was not successful.", hostname, recipient);
return null;
}
}
else if ("db".equals(doc.getNamespacePrefix()) && "verify".equals(doc.getName())) {
// When acting as an Authoritative Server the Receiving Server will send a
// db:verify packet for verifying a key that was previously sent by this
// server when acting as the Originating Server
verifyReceivedKey(doc, connection);
// Close the underlying connection
connection.close();
String verifyFROM = doc.attributeValue("from");
String id = doc.attributeValue("id");
Log.debug("ServerDialback: AS - Connection closed for host: " + verifyFROM + " id: " + id);
return null;
}
else {
Log.debug("ServerDialback: Received an invalid/unknown packet while trying to process an incoming session: {}", doc.asXML());
// The remote server sent an invalid/unknown packet
connection.deliverRawText(
new StreamError(StreamError.Condition.invalid_xml).toXML());
// Close the underlying connection
connection.close();
return null;
}
}
catch (Exception e) {
Log.error("An error occured while creating a server session", e);
// Close the underlying connection
connection.close();
return null;
}
}
else {
Log.debug("ServerDialback: Received a stanza in an invalid namespace while trying to process an incoming session: {}", xpp.getNamespace("db"));
connection.deliverRawText(
new StreamError(StreamError.Condition.invalid_namespace).toXML());
// Close the underlying connection
connection.close();
return null;
}
}
/**
* Returns true if the domain requested by the remote server was validated by the Authoritative
* Server. To validate the domain a new TCP connection will be established to the
* Authoritative Server. The Authoritative Server may be the same Originating Server or
* some other machine in the Originating Server's network.<p>
*
* If the domain was not valid or some error occurred while validating the domain then the
* underlying TCP connection will be closed.
*
* @param doc the request for validating the new domain.
* @param streamID the stream id generated by this server for the Originating Server.
* @return true if the requested domain is valid.
*/
public boolean validateRemoteDomain(Element doc, StreamID streamID) {
StringBuilder sb;
String recipient = doc.attributeValue("to");
String hostname = doc.attributeValue("from");
Log.debug("ServerDialback: RS - Received dialback key from host: " + hostname + " to: " + recipient);
if (!RemoteServerManager.canAccess(hostname)) {
// Remote server is not allowed to establish a connection to this server
connection.deliverRawText(new StreamError(StreamError.Condition.host_unknown).toXML());
// Close the underlying connection
connection.close();
Log.debug("ServerDialback: RS - Error, hostname is not allowed to establish a connection to " +
"this server: " +
recipient);
return false;
}
else if (isHostUnknown(recipient)) {
// address does not match a recognized hostname
connection.deliverRawText(new StreamError(StreamError.Condition.host_unknown).toXML());
// Close the underlying connection
connection.close();
Log.debug("ServerDialback: RS - Error, hostname not recognized: " + recipient);
return false;
}
else {
// Check if the remote server already has a connection to the target domain/subdomain
boolean alreadyExists = false;
for (IncomingServerSession session : sessionManager.getIncomingServerSessions(hostname)) {
if (recipient.equals(session.getLocalDomain())) {
alreadyExists = true;
}
}
if (alreadyExists && !sessionManager.isMultipleServerConnectionsAllowed()) {
// Remote server already has a IncomingServerSession created
connection.deliverRawText(
new StreamError(StreamError.Condition.not_authorized).toXML());
// Close the underlying connection
connection.close();
Log.debug("ServerDialback: RS - Error, incoming connection already exists from: " + hostname);
return false;
}
else {
String key = doc.getTextTrim();
// Get a list of real hostnames and try to connect using DNS lookup of the specified domain
List<DNSUtil.HostAddress> hosts = DNSUtil.resolveXMPPDomain(hostname,
RemoteServerManager.getPortForServer(hostname));
Socket socket = new Socket();
String realHostname = null;
int realPort;
for (Iterator<DNSUtil.HostAddress> it = hosts.iterator(); it.hasNext();) {
try {
DNSUtil.HostAddress address = it.next();
realHostname = address.getHost();
realPort = address.getPort();
Log.debug("ServerDialback: RS - Trying to connect to Authoritative Server: " + hostname +
"(DNS lookup: " + realHostname + ":" + realPort + ")");
// Establish a TCP connection to the Receiving Server
socket.connect(new InetSocketAddress(realHostname, realPort),
RemoteServerManager.getSocketTimeout());
Log.debug("ServerDialback: RS - Connection to AS: " + hostname + " successful");
break;
}
catch (Exception e) {
Log.warn("Error trying to connect to remote server: " + hostname +
"(DNS lookup: " + realHostname + ")", e);
}
}
if (!socket.isConnected()) {
Log.warn("No server available for verifying key of remote server: " + hostname);
return false;
}
try {
boolean valid = verifyKey(key, streamID.toString(), recipient, hostname, socket);
Log.debug("ServerDialback: RS - Sending key verification result to OS: " + hostname);
sb = new StringBuilder();
sb.append("<db:result");
sb.append(" from=\"").append(recipient).append("\"");
sb.append(" to=\"").append(hostname).append("\"");
sb.append(" type=\"");
sb.append(valid ? "valid" : "invalid");
sb.append("\"/>");
connection.deliverRawText(sb.toString());
if (!valid) {
// Close the underlying connection
connection.close();
}
return valid;
}
catch (Exception e) {
Log.warn("Error verifying key of remote server: " + hostname, e);
// Send a <remote-connection-failed/> stream error condition
// and terminate both the XML stream and the underlying
// TCP connection
connection.deliverRawText(new StreamError(
StreamError.Condition.remote_connection_failed).toXML());
// Close the underlying connection
connection.close();
return false;
}
}
}
}
private boolean isHostUnknown(String recipient) {
boolean host_unknown = !serverName.equals(recipient);
// If the recipient does not match the serverName then check if it matches a subdomain. This
// trick is useful when subdomains of this server are registered in the DNS so remote
// servers may establish connections directly to a subdomain of this server
if (host_unknown && recipient.contains(serverName)) {
host_unknown = !routingTable.hasComponentRoute(new JID(recipient));
}
return host_unknown;
}
/**
* Verifies the key with the Authoritative Server.
*/
private boolean verifyKey(String key, String streamID, String recipient, String hostname,
Socket socket) throws IOException, XmlPullParserException,
RemoteConnectionFailedException {
XMPPPacketReader reader;
Writer writer = null;
// Set a read timeout
socket.setSoTimeout(RemoteServerManager.getSocketTimeout());
try {
reader = new XMPPPacketReader();
reader.setXPPFactory(FACTORY);
reader.getXPPParser().setInput(new InputStreamReader(socket.getInputStream(),
CHARSET));
// Get a writer for sending the open stream tag
writer =
new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),
CHARSET));
// Send the Authoritative Server a stream header
StringBuilder stream = new StringBuilder();
stream.append("<stream:stream");
stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
stream.append(" xmlns=\"jabber:server\"");
stream.append(" xmlns:db=\"jabber:server:dialback\">");
writer.write(stream.toString());
writer.flush();
// Get the answer from the Authoritative Server
XmlPullParser xpp = reader.getXPPParser();
for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) {
eventType = xpp.next();
}
if ("jabber:server:dialback".equals(xpp.getNamespace("db"))) {
Log.debug("ServerDialback: RS - Asking AS to verify dialback key for id" + streamID);
// Request for verification of the key
StringBuilder sb = new StringBuilder();
sb.append("<db:verify");
sb.append(" from=\"").append(recipient).append("\"");
sb.append(" to=\"").append(hostname).append("\"");
sb.append(" id=\"").append(streamID).append("\">");
sb.append(key);
sb.append("</db:verify>");
writer.write(sb.toString());
writer.flush();
try {
Element doc = reader.parseDocument().getRootElement();
if ("db".equals(doc.getNamespacePrefix()) && "verify".equals(doc.getName())) {
if (!streamID.equals(doc.attributeValue("id"))) {
// Include the invalid-id stream error condition in the response
writer.write(new StreamError(StreamError.Condition.invalid_id).toXML());
writer.flush();
// Thrown an error so <remote-connection-failed/> stream error
// condition is sent to the Originating Server
throw new RemoteConnectionFailedException("Invalid ID");
}
else if (isHostUnknown(doc.attributeValue("to"))) {
// Include the host-unknown stream error condition in the response
writer.write(
new StreamError(StreamError.Condition.host_unknown).toXML());
writer.flush();
// Thrown an error so <remote-connection-failed/> stream error
// condition is sent to the Originating Server
throw new RemoteConnectionFailedException("Host unknown");
}
else if (!hostname.equals(doc.attributeValue("from"))) {
// Include the invalid-from stream error condition in the response
writer.write(
new StreamError(StreamError.Condition.invalid_from).toXML());
writer.flush();
// Thrown an error so <remote-connection-failed/> stream error
// condition is sent to the Originating Server
throw new RemoteConnectionFailedException("Invalid From");
}
else {
boolean valid = "valid".equals(doc.attributeValue("type"));
Log.debug("ServerDialback: RS - Key was " + (valid ? "" : "NOT ") +
"VERIFIED by the Authoritative Server for: " +
hostname);
return valid;
}
}
else {
Log.debug("ServerDialback: db:verify answer was: " + doc.asXML());
}
}
catch (DocumentException e) {
Log.error("An error occured connecting to the Authoritative Server", e);
// Thrown an error so <remote-connection-failed/> stream error condition is
// sent to the Originating Server
throw new RemoteConnectionFailedException("Error connecting to the Authoritative Server");
}
}
else {
// Include the invalid-namespace stream error condition in the response
writer.write(new StreamError(StreamError.Condition.invalid_namespace).toXML());
writer.flush();
// Thrown an error so <remote-connection-failed/> stream error condition is
// sent to the Originating Server
throw new RemoteConnectionFailedException("Invalid namespace");
}
}
finally {
try {
Log.debug("ServerDialback: RS - Closing connection to Authoritative Server: " + hostname);
// Close the stream
StringBuilder sb = new StringBuilder();
sb.append("</stream:stream>");
writer.write(sb.toString());
writer.flush();
// Close the TCP connection
socket.close();
}
catch (IOException ioe) {
// Do nothing
}
}
return false;
}
/**
* Verifies the key sent by a Receiving Server. This server will be acting as the
* Authoritative Server when executing this method. The remote server may have established
* a new connection to the Authoritative Server (i.e. this server) for verifying the key
* or it may be reusing an existing incoming connection.
*
* @param doc the Element that contains the key to verify.
* @param connection the connection to use for sending the verification result
* @return true if the key was verified.
*/
public static boolean verifyReceivedKey(Element doc, Connection connection) {
String verifyFROM = doc.attributeValue("from");
String verifyTO = doc.attributeValue("to");
String key = doc.getTextTrim();
String id = doc.attributeValue("id");
Log.debug("ServerDialback: AS - Verifying key for host: " + verifyFROM + " id: " + id);
// TODO If the value of the 'to' address does not match a recognized hostname,
// then generate a <host-unknown/> stream error condition
// TODO If the value of the 'from' address does not match the hostname
// represented by the Receiving Server when opening the TCP connection, then
// generate an <invalid-from/> stream error condition
// Verify the received key
// Created the expected key based on the received ID value and the shared secret
String expectedKey = AuthFactory.createDigest(id, getSecretkey());
boolean verified = expectedKey.equals(key);
// Send the result of the key verification
StringBuilder sb = new StringBuilder();
sb.append("<db:verify");
sb.append(" from=\"").append(verifyTO).append("\"");
sb.append(" to=\"").append(verifyFROM).append("\"");
sb.append(" type=\"");
sb.append(verified ? "valid" : "invalid");
sb.append("\" id=\"").append(id).append("\"/>");
connection.deliverRawText(sb.toString());
Log.debug("ServerDialback: AS - Key was: " + (verified ? "VALID" : "INVALID") + " for host: " +
verifyFROM +
" id: " +
id);
return verified;
}
/**
* Returns the secret key that was randomly generated. When running inside of a cluster
* the key will be unique to all cluster nodes.
*
* @return the secret key that was randomly generated.
*/
private static String getSecretkey() {
String key = "secretKey";
Lock lock = CacheFactory.getLock(key, secretKeyCache);
try {
lock.lock();
String secret = secretKeyCache.get(key);
if (secret == null) {
secret = StringUtils.randomString(10);
secretKeyCache.put(key, secret);
}
return secret;
}
finally {
lock.unlock();
}
}
}
| mhd911/openfire | src/java/org/jivesoftware/openfire/server/ServerDialback.java | Java | apache-2.0 | 40,385 |
import { Menu, MenuType } from './menu-interface';
import { Platform } from '../../platform/platform';
/**
* @name MenuController
* @description
* The MenuController is a provider which makes it easy to control a [Menu](../Menu).
* Its methods can be used to display the menu, enable the menu, toggle the menu, and more.
* The controller will grab a reference to the menu by the `side`, `id`, or, if neither
* of these are passed to it, it will grab the first menu it finds.
*
*
* @usage
*
* Add a basic menu component to start with. See the [Menu](../Menu) API docs
* for more information on adding menu components.
*
* ```html
* <ion-menu [content]="mycontent">
* <ion-content>
* <ion-list>
* ...
* </ion-list>
* </ion-content>
* </ion-menu>
*
* <ion-nav #mycontent [root]="rootPage"></ion-nav>
* ```
*
* To call the controller methods, inject the `MenuController` provider
* into the page. Then, create some methods for opening, closing, and
* toggling the menu.
*
* ```ts
* import { Component } from '@angular/core';
* import { MenuController } from 'ionic-angular';
*
* @Component({...})
* export class MyPage {
*
* constructor(public menuCtrl: MenuController) {
*
* }
*
* openMenu() {
* this.menuCtrl.open();
* }
*
* closeMenu() {
* this.menuCtrl.close();
* }
*
* toggleMenu() {
* this.menuCtrl.toggle();
* }
*
* }
* ```
*
* Since only one menu exists, the `MenuController` will grab the
* correct menu and call the correct method for each.
*
*
* ### Multiple Menus on Different Sides
*
* For applications with both a left and right menu, the desired menu can be
* grabbed by passing the `side` of the menu. If nothing is passed, it will
* default to the `"left"` menu.
*
* ```html
* <ion-menu side="left" [content]="mycontent">...</ion-menu>
* <ion-menu side="right" [content]="mycontent">...</ion-menu>
* <ion-nav #mycontent [root]="rootPage"></ion-nav>
* ```
*
* ```ts
* toggleLeftMenu() {
* this.menuCtrl.toggle();
* }
*
* toggleRightMenu() {
* this.menuCtrl.toggle('right');
* }
* ```
*
*
* ### Multiple Menus on the Same Side
*
* An application can have multiple menus on the same side. In order to determine
* the menu to control, an `id` should be passed. In the example below, the menu
* with the `authenticated` id will be enabled, and the menu with the `unauthenticated`
* id will be disabled.
*
* ```html
* <ion-menu id="authenticated" side="left" [content]="mycontent">...</ion-menu>
* <ion-menu id="unauthenticated" side="left" [content]="mycontent">...</ion-menu>
* <ion-nav #mycontent [root]="rootPage"></ion-nav>
* ```
*
* ```ts
* enableAuthenticatedMenu() {
* this.menuCtrl.enable(true, 'authenticated');
* this.menuCtrl.enable(false, 'unauthenticated');
* }
* ```
*
* Note: if an app only has one menu, there is no reason to pass an `id`.
*
*
* @demo /docs/demos/src/menu/
*
* @see {@link /docs/components#menus Menu Component Docs}
* @see {@link ../Menu Menu API Docs}
*
*/
export declare class MenuController {
private _menus;
/**
* Programatically open the Menu.
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {Promise} returns a promise when the menu is fully opened
*/
open(menuId?: string): Promise<boolean>;
/**
* Programatically close the Menu. If no `menuId` is given as the first
* argument then it'll close any menu which is open. If a `menuId`
* is given then it'll close that exact menu.
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {Promise} returns a promise when the menu is fully closed
*/
close(menuId?: string): Promise<boolean>;
/**
* Toggle the menu. If it's closed, it will open, and if opened, it
* will close.
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {Promise} returns a promise when the menu has been toggled
*/
toggle(menuId?: string): Promise<boolean>;
/**
* Used to enable or disable a menu. For example, there could be multiple
* left menus, but only one of them should be able to be opened at the same
* time. If there are multiple menus on the same side, then enabling one menu
* will also automatically disable all the others that are on the same side.
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {Menu} Returns the instance of the menu, which is useful for chaining.
*/
enable(shouldEnable: boolean, menuId?: string): Menu;
/**
* Used to enable or disable the ability to swipe open the menu.
* @param {boolean} shouldEnable True if it should be swipe-able, false if not.
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {Menu} Returns the instance of the menu, which is useful for chaining.
*/
swipeEnable(shouldEnable: boolean, menuId?: string): Menu;
/**
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {boolean} Returns true if the specified menu is currently open, otherwise false.
* If the menuId is not specified, it returns true if ANY menu is currenly open.
*/
isOpen(menuId?: string): boolean;
/**
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {boolean} Returns true if the menu is currently enabled, otherwise false.
*/
isEnabled(menuId?: string): boolean;
/**
* Used to get a menu instance. If a `menuId` is not provided then it'll
* return the first menu found. If a `menuId` is `left` or `right`, then
* it'll return the enabled menu on that side. Otherwise, if a `menuId` is
* provided, then it'll try to find the menu using the menu's `id`
* property. If a menu is not found then it'll return `null`.
* @param {string} [menuId] Optionally get the menu by its id, or side.
* @return {Menu} Returns the instance of the menu if found, otherwise `null`.
*/
get(menuId?: string): Menu;
/**
* @return {Menu} Returns the instance of the menu already opened, otherwise `null`.
*/
getOpen(): Menu;
/**
* @return {Array<Menu>} Returns an array of all menu instances.
*/
getMenus(): Array<Menu>;
/**
* @hidden
* @return {boolean} if any menu is currently animating
*/
isAnimating(): boolean;
/**
* @hidden
*/
_register(menu: Menu): void;
/**
* @hidden
*/
_unregister(menu: Menu): void;
/**
* @hidden
*/
_setActiveMenu(menu: Menu): void;
/**
* @hidden
*/
static registerType(name: string, cls: new (...args: any[]) => MenuType): void;
/**
* @hidden
*/
static create(type: string, menuCmp: Menu, plt: Platform): MenuType;
}
| A-HostMobile/MobileApp | node_modules/ionic-angular/umd/components/app/menu-controller.d.ts | TypeScript | apache-2.0 | 6,931 |
Receive Greenhouse notifications in Zulip!
1. {!create-stream.md!}
1. {!create-bot-construct-url-indented.md!}
1. On your Greenhouse **Dashboard**, click on the
**gear** (<i class="fa fa-cog"></i>) icon in the upper right
corner. Click on **Dev Center**, and click **Web Hooks**.
Click on **Web Hooks** one more time.
1. Set **Name this web hook** to a name of your choice, such as
`Zulip`. Set **When** to the event you'd like to be notified
about. Set **Endpoint URL** to the URL constructed above.
1. Greenhouse requires you to provide a **Secret key**, but Zulip
doesn't expect any particular value. Set **Secret key** to any
random value, and click **Create Web hook**.
{!congrats.md!}

| rht/zulip | zerver/webhooks/greenhouse/doc.md | Markdown | apache-2.0 | 771 |
#pragma once
/*
* Copyright 2000-2017 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.
*/
// Shared file for elevator and launcher
// Author: Ilya Kazakevich
// So called "descriptors". Used as arguments in many macros and can also be used as binary flags
#define ELEV_DESCR_STDOUT 1
#define ELEV_DESCR_STDERR 2
#define ELEV_DESCR_STDIN 4
// Rules to generate pipe name
#define ELEV_GEN_PIPE_NAME(sDest, nPid, nDescriptor) wsprintf(sDest, L"\\\\.\\pipe\\_jetbrains%ld_%d", nPid, nDescriptor)
#define ELEV_BUF_SIZE 1024 //Buf to read/write between processes
// Convert descriptor to Win32API handler
#define ELEV_DESCR_GET_HANDLE(nDescriptor) (nDescriptor == ELEV_DESCR_STDOUT ? STD_OUTPUT_HANDLE : \
(nDescriptor == ELEV_DESCR_STDERR ? STD_ERROR_HANDLE : STD_INPUT_HANDLE))
// Pipe name
typedef wchar_t ELEV_PIPE_NAME[32];
// Separates arguments provided to elevator and user command line
#define ELEV_COMMAND_LINE_SEPARATOR L"--::--"
| asedunov/intellij-community | native/WinElevator/elevShared/elevTools.h | C | apache-2.0 | 1,473 |
describe MiqAeDatastore::XmlExport do
describe ".to_xml" do
let(:custom_button) { double("CustomButton") }
let(:custom_buttons) { [custom_button] }
let(:miq_ae_class1) { double("MiqAeClass", :fqname => "z") }
let(:miq_ae_class2) { double("MiqAeClass", :fqname => "a") }
let(:miq_ae_classes) { [miq_ae_class1, miq_ae_class2] }
let(:expected_xml) do
<<-XML
<?xml version="1.0" encoding="UTF-8"?>
<MiqAeDatastore version="1.0">
<class2/>
<class1/>
<custom_button/>
</MiqAeDatastore>
XML
end
before do
# Populate the doubles *before* we start messing with .all
miq_ae_classes
custom_buttons
allow(MiqAeClass).to receive(:all).and_return(miq_ae_classes)
allow(CustomButton).to receive(:all).and_return(custom_buttons)
end
it "sorts the miq ae classes and returns the correct xml" do
expect(miq_ae_class2).to receive(:to_export_xml) do |options|
expect(options[:builder].target!).to eq <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<MiqAeDatastore version="1.0">
XML
expect(options[:skip_instruct]).to be_truthy
expect(options[:indent]).to eq(2)
options[:builder].class2
end
expect(miq_ae_class1).to receive(:to_export_xml) do |options|
expect(options[:builder].target!).to eq <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<MiqAeDatastore version="1.0">
<class2/>
XML
expect(options[:skip_instruct]).to be_truthy
expect(options[:indent]).to eq(2)
options[:builder].class1
end
expect(custom_button).to receive(:to_export_xml) do |options|
expect(options[:builder].target!).to eq <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<MiqAeDatastore version="1.0">
<class2/>
<class1/>
XML
expect(options[:skip_instruct]).to be_truthy
expect(options[:indent]).to eq(2)
options[:builder].custom_button
end
expect(MiqAeDatastore::XmlExport.to_xml).to eq(expected_xml)
end
end
end
| bdunne/manageiq-automation_engine | spec/models/miq_ae_datastore/xml_export_spec.rb | Ruby | apache-2.0 | 2,032 |
{% extends "base.html" %}
{% block title %}
<title>OSF Admin | Delete banner</title>
{% endblock title %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h4>Confirm Delete Banner</h4>
<form action="" method="post">{% csrf_token %}
<p>
Are you sure you want to delete <b>{{ object.name }}</b>? It is scheduled for {{ object.start_date }} -
{{ object.end_date }}
</p>
<input class="btn btn-primary" type="submit" value="Confirm" />
</form>
</div>
</div>
</div>
{% endblock content %}
| icereval/osf.io | admin/templates/banners/confirm_delete.html | HTML | apache-2.0 | 736 |
/*
*******************************************************************************
* Copyright (C) 1996-2010, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.impl;
import com.ibm.icu.text.Replaceable;
import com.ibm.icu.text.ReplaceableString;
import com.ibm.icu.text.UCharacterIterator;
import com.ibm.icu.text.UTF16;
/**
* DLF docs must define behavior when Replaceable is mutated underneath
* the iterator.
*
* This and ICUCharacterIterator share some code, maybe they should share
* an implementation, or the common state and implementation should be
* moved up into UCharacterIterator.
*
* What are first, last, and getBeginIndex doing here?!?!?!
*/
public class ReplaceableUCharacterIterator extends UCharacterIterator {
// public constructor ------------------------------------------------------
/**
* Public constructor
* @param replaceable text which the iterator will be based on
*/
public ReplaceableUCharacterIterator(Replaceable replaceable){
if(replaceable==null){
throw new IllegalArgumentException();
}
this.replaceable = replaceable;
this.currentIndex = 0;
}
/**
* Public constructor
* @param str text which the iterator will be based on
*/
public ReplaceableUCharacterIterator(String str){
if(str==null){
throw new IllegalArgumentException();
}
this.replaceable = new ReplaceableString(str);
this.currentIndex = 0;
}
/**
* Public constructor
* @param buf buffer of text on which the iterator will be based
*/
public ReplaceableUCharacterIterator(StringBuffer buf){
if(buf==null){
throw new IllegalArgumentException();
}
this.replaceable = new ReplaceableString(buf);
this.currentIndex = 0;
}
// public methods ----------------------------------------------------------
/**
* Creates a copy of this iterator, does not clone the underlying
* <code>Replaceable</code>object
* @return copy of this iterator
*/
public Object clone(){
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null; // never invoked
}
}
/**
* Returns the current UTF16 character.
* @return current UTF16 character
*/
public int current(){
if (currentIndex < replaceable.length()) {
return replaceable.charAt(currentIndex);
}
return DONE;
}
/**
* Returns the current codepoint
* @return current codepoint
*/
public int currentCodePoint(){
// cannot use charAt due to it different
// behaviour when index is pointing at a
// trail surrogate, check for surrogates
int ch = current();
if(UTF16.isLeadSurrogate((char)ch)){
// advance the index to get the next code point
next();
// due to post increment semantics current() after next()
// actually returns the next char which is what we want
int ch2 = current();
// current should never change the current index so back off
previous();
if(UTF16.isTrailSurrogate((char)ch2)){
// we found a surrogate pair
return UCharacterProperty.getRawSupplementary(
(char)ch,(char)ch2
);
}
}
return ch;
}
/**
* Returns the length of the text
* @return length of the text
*/
public int getLength(){
return replaceable.length();
}
/**
* Gets the current currentIndex in text.
* @return current currentIndex in text.
*/
public int getIndex(){
return currentIndex;
}
/**
* Returns next UTF16 character and increments the iterator's currentIndex by 1.
* If the resulting currentIndex is greater or equal to the text length, the
* currentIndex is reset to the text length and a value of DONECODEPOINT is
* returned.
* @return next UTF16 character in text or DONE if the new currentIndex is off the
* end of the text range.
*/
public int next(){
if (currentIndex < replaceable.length()) {
return replaceable.charAt(currentIndex++);
}
return DONE;
}
/**
* Returns previous UTF16 character and decrements the iterator's currentIndex by
* 1.
* If the resulting currentIndex is less than 0, the currentIndex is reset to 0 and a
* value of DONECODEPOINT is returned.
* @return next UTF16 character in text or DONE if the new currentIndex is off the
* start of the text range.
*/
public int previous(){
if (currentIndex > 0) {
return replaceable.charAt(--currentIndex);
}
return DONE;
}
/**
* <p>Sets the currentIndex to the specified currentIndex in the text and returns that
* single UTF16 character at currentIndex.
* This assumes the text is stored as 16-bit code units.</p>
* @param currentIndex the currentIndex within the text.
* @exception IllegalArgumentException is thrown if an invalid currentIndex is
* supplied. i.e. currentIndex is out of bounds.
* @returns the character at the specified currentIndex or DONE if the specified
* currentIndex is equal to the end of the text.
*/
public void setIndex(int currentIndex) throws IndexOutOfBoundsException{
if (currentIndex < 0 || currentIndex > replaceable.length()) {
throw new IndexOutOfBoundsException();
}
this.currentIndex = currentIndex;
}
public int getText(char[] fillIn, int offset){
int length = replaceable.length();
if(offset < 0 || offset + length > fillIn.length){
throw new IndexOutOfBoundsException(Integer.toString(length));
}
replaceable.getChars(0,length,fillIn,offset);
return length;
}
// private data members ----------------------------------------------------
/**
* Replacable object
*/
private Replaceable replaceable;
/**
* Current currentIndex
*/
private int currentIndex;
}
| Miracle121/quickdic-dictionary.dictionary | jars/icu4j-52_1/main/classes/core/src/com/ibm/icu/impl/ReplaceableUCharacterIterator.java | Java | apache-2.0 | 6,713 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.apache.drill.exec.store.hive;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.exec.physical.base.AbstractBase;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.physical.base.PhysicalVisitor;
import org.apache.drill.exec.physical.base.SubScan;
import org.apache.drill.exec.proto.UserBitShared.CoreOperatorType;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.mapred.InputSplit;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
@JsonTypeName("hive-sub-scan")
public class HiveSubScan extends AbstractBase implements SubScan {
private List<String> splits;
private HiveReadEntry hiveReadEntry;
private List<String> splitClasses;
private List<SchemaPath> columns;
@JsonIgnore
private List<InputSplit> inputSplits = Lists.newArrayList();
@JsonIgnore
private Table table;
@JsonIgnore
private List<Partition> partitions;
@JsonCreator
public HiveSubScan(@JsonProperty("userName") String userName,
@JsonProperty("splits") List<String> splits,
@JsonProperty("hiveReadEntry") HiveReadEntry hiveReadEntry,
@JsonProperty("splitClasses") List<String> splitClasses,
@JsonProperty("columns") List<SchemaPath> columns) throws IOException, ReflectiveOperationException {
super(userName);
this.hiveReadEntry = hiveReadEntry;
this.table = hiveReadEntry.getTable();
this.partitions = hiveReadEntry.getPartitions();
this.splits = splits;
this.splitClasses = splitClasses;
this.columns = columns;
for (int i = 0; i < splits.size(); i++) {
inputSplits.add(deserializeInputSplit(splits.get(i), splitClasses.get(i)));
}
}
public List<String> getSplits() {
return splits;
}
public Table getTable() {
return table;
}
public List<Partition> getPartitions() {
return partitions;
}
public List<String> getSplitClasses() {
return splitClasses;
}
public List<SchemaPath> getColumns() {
return columns;
}
public List<InputSplit> getInputSplits() {
return inputSplits;
}
public HiveReadEntry getHiveReadEntry() {
return hiveReadEntry;
}
public static InputSplit deserializeInputSplit(String base64, String className) throws IOException, ReflectiveOperationException{
Constructor<?> constructor = Class.forName(className).getDeclaredConstructor();
if (constructor == null) {
throw new ReflectiveOperationException("Class " + className + " does not implement a default constructor.");
}
constructor.setAccessible(true);
InputSplit split = (InputSplit) constructor.newInstance();
ByteArrayDataInput byteArrayDataInput = ByteStreams.newDataInput(Base64.decodeBase64(base64));
split.readFields(byteArrayDataInput);
return split;
}
@Override
public <T, X, E extends Throwable> T accept(PhysicalVisitor<T, X, E> physicalVisitor, X value) throws E {
return physicalVisitor.visitSubScan(this, value);
}
@Override
public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) throws ExecutionSetupException {
try {
return new HiveSubScan(getUserName(), splits, hiveReadEntry, splitClasses, columns);
} catch (IOException | ReflectiveOperationException e) {
throw new ExecutionSetupException(e);
}
}
@Override
public Iterator<PhysicalOperator> iterator() {
return Iterators.emptyIterator();
}
@Override
public int getOperatorType() {
return CoreOperatorType.HIVE_SUB_SCAN_VALUE;
}
}
| kristinehahn/drill | contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveSubScan.java | Java | apache-2.0 | 5,019 |
# Copyright (C) 2010 Google, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Research in Motion Ltd. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unittest
from model.workitems import WorkItems
class WorkItemsTest(unittest.TestCase):
def test_display_position_for_attachment(self):
items = WorkItems()
items.item_ids = [0, 1, 2]
self.assertEquals(items.display_position_for_attachment(0), 1)
self.assertEquals(items.display_position_for_attachment(1), 2)
self.assertEquals(items.display_position_for_attachment(3), None)
if __name__ == '__main__':
unittest.main()
| mogoweb/webkit_for_android5.1 | webkit/Tools/QueueStatusServer/model/workitems_unittest.py | Python | apache-2.0 | 2,018 |
---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF 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.
---
accelerometerError
==================
onError callback function for acceleration functions.
function() {
// Handle the error
}
| maveriklko9719/Coffee-Spills | docs/en/3.0.0rc1/cordova/accelerometer/parameters/accelerometerError.md | Markdown | apache-2.0 | 1,036 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_TagManager_Tag extends Google_Collection
{
protected $collection_key = 'teardownTag';
public $accountId;
public $blockingRuleId;
public $blockingTriggerId;
public $containerId;
public $fingerprint;
public $firingRuleId;
public $firingTriggerId;
public $liveOnly;
public $name;
public $notes;
protected $parameterType = 'Google_Service_TagManager_Parameter';
protected $parameterDataType = 'array';
public $parentFolderId;
public $path;
public $paused;
protected $priorityType = 'Google_Service_TagManager_Parameter';
protected $priorityDataType = '';
public $scheduleEndMs;
public $scheduleStartMs;
protected $setupTagType = 'Google_Service_TagManager_SetupTag';
protected $setupTagDataType = 'array';
public $tagFiringOption;
public $tagId;
public $tagManagerUrl;
protected $teardownTagType = 'Google_Service_TagManager_TeardownTag';
protected $teardownTagDataType = 'array';
public $type;
public $workspaceId;
public function setAccountId($accountId)
{
$this->accountId = $accountId;
}
public function getAccountId()
{
return $this->accountId;
}
public function setBlockingRuleId($blockingRuleId)
{
$this->blockingRuleId = $blockingRuleId;
}
public function getBlockingRuleId()
{
return $this->blockingRuleId;
}
public function setBlockingTriggerId($blockingTriggerId)
{
$this->blockingTriggerId = $blockingTriggerId;
}
public function getBlockingTriggerId()
{
return $this->blockingTriggerId;
}
public function setContainerId($containerId)
{
$this->containerId = $containerId;
}
public function getContainerId()
{
return $this->containerId;
}
public function setFingerprint($fingerprint)
{
$this->fingerprint = $fingerprint;
}
public function getFingerprint()
{
return $this->fingerprint;
}
public function setFiringRuleId($firingRuleId)
{
$this->firingRuleId = $firingRuleId;
}
public function getFiringRuleId()
{
return $this->firingRuleId;
}
public function setFiringTriggerId($firingTriggerId)
{
$this->firingTriggerId = $firingTriggerId;
}
public function getFiringTriggerId()
{
return $this->firingTriggerId;
}
public function setLiveOnly($liveOnly)
{
$this->liveOnly = $liveOnly;
}
public function getLiveOnly()
{
return $this->liveOnly;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setNotes($notes)
{
$this->notes = $notes;
}
public function getNotes()
{
return $this->notes;
}
/**
* @param Google_Service_TagManager_Parameter
*/
public function setParameter($parameter)
{
$this->parameter = $parameter;
}
/**
* @return Google_Service_TagManager_Parameter
*/
public function getParameter()
{
return $this->parameter;
}
public function setParentFolderId($parentFolderId)
{
$this->parentFolderId = $parentFolderId;
}
public function getParentFolderId()
{
return $this->parentFolderId;
}
public function setPath($path)
{
$this->path = $path;
}
public function getPath()
{
return $this->path;
}
public function setPaused($paused)
{
$this->paused = $paused;
}
public function getPaused()
{
return $this->paused;
}
/**
* @param Google_Service_TagManager_Parameter
*/
public function setPriority(Google_Service_TagManager_Parameter $priority)
{
$this->priority = $priority;
}
/**
* @return Google_Service_TagManager_Parameter
*/
public function getPriority()
{
return $this->priority;
}
public function setScheduleEndMs($scheduleEndMs)
{
$this->scheduleEndMs = $scheduleEndMs;
}
public function getScheduleEndMs()
{
return $this->scheduleEndMs;
}
public function setScheduleStartMs($scheduleStartMs)
{
$this->scheduleStartMs = $scheduleStartMs;
}
public function getScheduleStartMs()
{
return $this->scheduleStartMs;
}
/**
* @param Google_Service_TagManager_SetupTag
*/
public function setSetupTag($setupTag)
{
$this->setupTag = $setupTag;
}
/**
* @return Google_Service_TagManager_SetupTag
*/
public function getSetupTag()
{
return $this->setupTag;
}
public function setTagFiringOption($tagFiringOption)
{
$this->tagFiringOption = $tagFiringOption;
}
public function getTagFiringOption()
{
return $this->tagFiringOption;
}
public function setTagId($tagId)
{
$this->tagId = $tagId;
}
public function getTagId()
{
return $this->tagId;
}
public function setTagManagerUrl($tagManagerUrl)
{
$this->tagManagerUrl = $tagManagerUrl;
}
public function getTagManagerUrl()
{
return $this->tagManagerUrl;
}
/**
* @param Google_Service_TagManager_TeardownTag
*/
public function setTeardownTag($teardownTag)
{
$this->teardownTag = $teardownTag;
}
/**
* @return Google_Service_TagManager_TeardownTag
*/
public function getTeardownTag()
{
return $this->teardownTag;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
public function setWorkspaceId($workspaceId)
{
$this->workspaceId = $workspaceId;
}
public function getWorkspaceId()
{
return $this->workspaceId;
}
}
| drthomas21/WordPress_Tutorial | wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/TagManager/Tag.php | PHP | apache-2.0 | 6,014 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.