code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
// 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. // // This file defines implementation of GoogleChromeSxSDistribution. #include "chrome/installer/util/google_chrome_sxs_distribution.h" #include "base/command_line.h" #include "base/logging.h" #include "installer_util_strings.h" // NOLINT namespace { const wchar_t kChromeSxSGuid[] = L"{4ea16ac7-fd5a-47c3-875b-dbf4a2008c20}"; const wchar_t kChannelName[] = L"canary"; const wchar_t kBrowserAppId[] = L"ChromeCanary"; const int kSxSIconIndex = 4; } // namespace GoogleChromeSxSDistribution::GoogleChromeSxSDistribution() : GoogleChromeDistribution() { GoogleChromeDistribution::set_product_guid(kChromeSxSGuid); } string16 GoogleChromeSxSDistribution::GetApplicationName() { return L"Google Chrome Canary"; } string16 GoogleChromeSxSDistribution::GetAppShortCutName() { const string16& shortcut_name = installer::GetLocalizedString(IDS_SXS_SHORTCUT_NAME_BASE); return shortcut_name; } string16 GoogleChromeSxSDistribution::GetBrowserAppId() { return kBrowserAppId; } string16 GoogleChromeSxSDistribution::GetInstallSubDir() { return GoogleChromeDistribution::GetInstallSubDir().append( installer::kSxSSuffix); } string16 GoogleChromeSxSDistribution::GetUninstallRegPath() { return GoogleChromeDistribution::GetUninstallRegPath().append( installer::kSxSSuffix); } bool GoogleChromeSxSDistribution::CanSetAsDefault() { return false; } int GoogleChromeSxSDistribution::GetIconIndex() { return kSxSIconIndex; } bool GoogleChromeSxSDistribution::GetChromeChannel(string16* channel) { *channel = kChannelName; return true; } bool GoogleChromeSxSDistribution::GetDelegateExecuteHandlerData( string16* handler_class_uuid, string16* type_lib_uuid, string16* type_lib_version, string16* interface_uuid) { return false; } string16 GoogleChromeSxSDistribution::ChannelName() { return kChannelName; }
robclark/chromium
chrome/installer/util/google_chrome_sxs_distribution.cc
C++
bsd-3-clause
2,041
{% extends "users/base.html" %} {% from "users/includes/macros.html" import login_form with context %} {% set title = _('Password successfully reset.') %} {% set classes = 'password' %} {% block content %} <article id="pw-reset" class="main"> <h1>{{ title }}</h1> <p>{{ _('You can now log in.') }}</p> {{ login_form(form) }} </article> {% endblock content %}
mythmon/kitsune
kitsune/users/jinja2/users/pw_reset_complete.html
HTML
bsd-3-clause
376
from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.hasmethod import hasmethod from hamcrest.core.helpers.wrap_matcher import wrap_matcher __author__ = "Jon Reid" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" class IsDictContainingEntries(BaseMatcher): def __init__(self, value_matchers): self.value_matchers = sorted(value_matchers.items()) def _not_a_dictionary(self, dictionary, mismatch_description): if mismatch_description: mismatch_description.append_description_of(dictionary) \ .append_text(' is not a mapping object') return False def matches(self, dictionary, mismatch_description=None): for key, value_matcher in self.value_matchers: try: if not key in dictionary: if mismatch_description: mismatch_description.append_text('no ') \ .append_description_of(key) \ .append_text(' key in ') \ .append_description_of(dictionary) return False except TypeError: return self._not_a_dictionary(dictionary, mismatch_description) try: actual_value = dictionary[key] except TypeError: return self._not_a_dictionary(dictionary, mismatch_description) if not value_matcher.matches(actual_value): if mismatch_description: mismatch_description.append_text('value for ') \ .append_description_of(key) \ .append_text(' ') value_matcher.describe_mismatch(actual_value, mismatch_description) return False return True def describe_mismatch(self, item, mismatch_description): self.matches(item, mismatch_description) def describe_keyvalue(self, index, value, description): """Describes key-value pair at given index.""" description.append_description_of(index) \ .append_text(': ') \ .append_description_of(value) def describe_to(self, description): description.append_text('a dictionary containing {') first = True for key, value in self.value_matchers: if not first: description.append_text(', ') self.describe_keyvalue(key, value, description) first = False description.append_text('}') def has_entries(*keys_valuematchers, **kv_args): """Matches if dictionary contains entries satisfying a dictionary of keys and corresponding value matchers. :param matcher_dict: A dictionary mapping keys to associated value matchers, or to expected values for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Note that the keys must be actual keys, not matchers. Any value argument that is not a matcher is implicitly wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for equality. Examples:: has_entries({'foo':equal_to(1), 'bar':equal_to(2)}) has_entries({'foo':1, 'bar':2}) ``has_entries`` also accepts a list of keyword arguments: .. function:: has_entries(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]]) :param keyword1: A keyword to look up. :param valueMatcher1: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_entries(foo=equal_to(1), bar=equal_to(2)) has_entries(foo=1, bar=2) Finally, ``has_entries`` also accepts a list of alternating keys and their value matchers: .. function:: has_entries(key1, value_matcher1[, ...]) :param key1: A key (not a matcher) to look up. :param valueMatcher1: The matcher to satisfy for the value, or an expected value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching. Examples:: has_entries('foo', equal_to(1), 'bar', equal_to(2)) has_entries('foo', 1, 'bar', 2) """ if len(keys_valuematchers) == 1: try: base_dict = keys_valuematchers[0].copy() for key in base_dict: base_dict[key] = wrap_matcher(base_dict[key]) except AttributeError: raise ValueError('single-argument calls to has_entries must pass a dict as the argument') else: if len(keys_valuematchers) % 2: raise ValueError('has_entries requires key-value pairs') base_dict = {} for index in range(int(len(keys_valuematchers) / 2)): base_dict[keys_valuematchers[2 * index]] = wrap_matcher(keys_valuematchers[2 * index + 1]) for key, value in kv_args.items(): base_dict[key] = wrap_matcher(value) return IsDictContainingEntries(base_dict)
msabramo/PyHamcrest
src/hamcrest/library/collection/isdict_containingentries.py
Python
bsd-3-clause
5,168
/** * @file uartRead.c */ /* Embedded Xinu, Copyright (C) 2009, 2013. All rights reserved. */ #include <uart.h> #include <interrupt.h> /** * @ingroup uartgeneric * * Reads data from a UART. * * @param devptr * Pointer to the device table entry for a UART. * @param buf * Pointer to a buffer into which to place the read data. * @param len * Maximum number of bytes of data to read. * * @return * On success, returns the number of bytes read, which normally is @p len, * but may be less than @p len if the UART has been set to non-blocking * mode. Returns SYSERR on other error (currently, only if uartInit() has * not yet been called). */ devcall uartRead(device *devptr, void *buf, uint len) { irqmask im; struct uart *uartptr; uint count; uchar c; /* Disable interrupts and get a pointer to the UART structure. */ im = disable(); uartptr = &uarttab[devptr->minor]; /* Make sure uartInit() has run. */ if (NULL == uartptr->csr) { restore(im); return SYSERR; } /* Attempt to read each byte requested. */ for (count = 0; count < len; count++) { /* If the UART is in non-blocking mode, ensure there is a byte available * in the input buffer from the lower half (interrupt handler). If not, * return early with a short count. */ if ((uartptr->iflags & UART_IFLAG_NOBLOCK) && uartptr->icount == 0) { break; } /* Wait for there to be at least one byte in the input buffer from the * lower half (interrupt handler), then remove it. */ wait(uartptr->isema); c = uartptr->in[uartptr->istart]; ((uchar*)buf)[count] = c; uartptr->icount--; uartptr->istart = (uartptr->istart + 1) % UART_IBLEN; /* If the UART is in echo mode, echo the byte back to the UART. */ if (uartptr->iflags & UART_IFLAG_ECHO) { uartPutc(uartptr->dev, c); } } /* Restore interrupts and return the number of bytes read. */ restore(im); return count; }
robert-w-gries/xinu
device/uart/uartRead.c
C
bsd-3-clause
2,138
using System.Reflection; using System.Runtime.InteropServices; using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Orchard.ImportExport")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Orchard")] [assembly: AssemblyCopyright("Copyright © Outercurve Foundation 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6568da4-2c1f-408a-b5e1-0469beb60b19")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.7.1")] [assembly: AssemblyFileVersion("1.7.1")]
angeloocana/CampanhasOnline
src/Orchard.Web/Modules/_Backup/Orchard.ImportExport/Properties/AssemblyInfo.cs
C#
bsd-3-clause
1,333
<?php namespace app\models; /** * This is the ActiveQuery class for [[AuthItem]]. * * @see AuthItem */ class AuthItemQuery extends \yii\db\ActiveQuery { /*public function active() { $this->andWhere('[[status]]=1'); return $this; }*/ /** * @inheritdoc * @return AuthItem[]|array */ public function all($db = null) { return parent::all($db); } /** * @inheritdoc * @return AuthItem|array|null */ public function one($db = null) { return parent::one($db); } }
dwisuseno/tiket
models/AuthItemQuery.php
PHP
bsd-3-clause
569
# This migration comes from spree (originally 20150515211137) class FixAdjustmentOrderId < ActiveRecord::Migration[4.2] def change say 'Populate order_id from adjustable_id where appropriate' execute(<<-SQL.squish) UPDATE spree_adjustments SET order_id = adjustable_id WHERE adjustable_type = 'Spree::Order' ; SQL # Submitter of change does not care about MySQL, as it is not officially supported. # Still spree officials decided to provide a working code path for MySQL users, hence # submitter made a AR code path he could validate on PostgreSQL. # # Whoever runs a big enough MySQL installation where the AR solution hurts: # Will have to write a better MySQL specific equivalent. if Spree::Order.connection.adapter_name.eql?('MySQL') Spree::Adjustment.where(adjustable_type: 'Spree::LineItem').find_each do |adjustment| adjustment.update_columns(order_id: Spree::LineItem.find(adjustment.adjustable_id).order_id) end else execute(<<-SQL.squish) UPDATE spree_adjustments SET order_id = (SELECT order_id FROM spree_line_items WHERE spree_line_items.id = spree_adjustments.adjustable_id) WHERE adjustable_type = 'Spree::LineItem' SQL end say 'Fix schema for spree_adjustments order_id column' change_table :spree_adjustments do |t| t.change :order_id, :integer, null: false end # Improved schema for postgresql, uncomment if you like it: # # # Negated Logical implication. # # # # When adjustable_type is 'Spree::Order' (p) the adjustable_id must be order_id (q). # # # # When adjustable_type is NOT 'Spree::Order' the adjustable id allowed to be any value (including of order_id in # # case foreign keys match). XOR does not work here. # # # # Postgresql does not have an operator for logical implication. So we need to build the following truth table # # via AND with OR: # # # # p q | CHECK = !(p -> q) # # ----------- # # t t | t # # t f | f # # f t | t # # f f | t # # # # According to de-morgans law the logical implication q -> p is equivalent to !p || q # # # execute(<<-SQL.squish) # ALTER TABLE ONLY spree_adjustments # ADD CONSTRAINT fk_spree_adjustments FOREIGN KEY (order_id) # REFERENCES spree_orders(id) ON UPDATE RESTRICT ON DELETE RESTRICT, # ADD CONSTRAINT check_spree_adjustments_order_id CHECK # (adjustable_type <> 'Spree::Order' OR order_id = adjustable_id); # SQL end end
andreinabgomezg29/spree_out_stock
spec/dummy/db/migrate/20170904174443_fix_adjustment_order_id.spree.rb
Ruby
bsd-3-clause
2,651
using System; namespace NCalc { public class ParameterArgs : EventArgs { private object _result; public object Result { get { return _result; } set { _result = value; HasResult = true; } } public bool HasResult { get; set; } } }
nhenriques/YAMP
YAMP.Core.Comparison/NCalc/ParameterArgs.cs
C#
bsd-3-clause
366
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; /** * This script tests that React Native end to end installation/bootstrap works for different platforms * Available arguments: * --ios - 'react-native init' and check iOS app doesn't redbox * --tvos - 'react-native init' and check tvOS app doesn't redbox * --android - 'react-native init' and check Android app doesn't redbox * --js - 'react-native init' and only check the packager returns a bundle * --skip-cli-install - to skip react-native-cli global installation (for local debugging) * --retries [num] - how many times to retry possible flaky commands: yarn add and running tests, default 1 */ /*eslint-disable no-undef */ require('shelljs/global'); const spawn = require('child_process').spawn; const argv = require('yargs').argv; const path = require('path'); const SCRIPTS = __dirname; const ROOT = path.normalize(path.join(__dirname, '..')); const tryExecNTimes = require('./try-n-times'); const TEMP = exec('mktemp -d /tmp/react-native-XXXXXXXX').stdout.trim(); // To make sure we actually installed the local version // of react-native, we will create a temp file inside the template // and check that it exists after `react-native init const MARKER_IOS = exec(`mktemp ${ROOT}/local-cli/templates/HelloWorld/ios/HelloWorld/XXXXXXXX`).stdout.trim(); const MARKER_ANDROID = exec(`mktemp ${ROOT}/local-cli/templates/HelloWorld/android/XXXXXXXX`).stdout.trim(); const numberOfRetries = argv.retries || 1; let SERVER_PID; let APPIUM_PID; let exitCode; try { // install CLI cd('react-native-cli'); exec('yarn pack'); const CLI_PACKAGE = path.join(ROOT, 'react-native-cli', 'react-native-cli-*.tgz'); cd('..'); if (!argv['skip-cli-install']) { if (exec(`sudo yarn global add ${CLI_PACKAGE}`).code) { echo('Could not install react-native-cli globally.'); echo('Run with --skip-cli-install to skip this step'); exitCode = 1; throw Error(exitCode); } } if (argv.android) { if (exec('./gradlew :ReactAndroid:installArchives -Pjobs=1 -Dorg.gradle.jvmargs="-Xmx512m -XX:+HeapDumpOnOutOfMemoryError"').code) { echo('Failed to compile Android binaries'); exitCode = 1; throw Error(exitCode); } } if (exec('yarn pack').code) { echo('Failed to pack react-native'); exitCode = 1; throw Error(exitCode); } const PACKAGE = path.join(ROOT, 'react-native-*.tgz'); cd(TEMP); if (tryExecNTimes( () => { exec('sleep 10s'); return exec(`react-native init EndToEndTest --version ${PACKAGE}`).code; }, numberOfRetries, () => rm('-rf', 'EndToEndTest'))) { echo('Failed to execute react-native init'); echo('Most common reason is npm registry connectivity, try again'); exitCode = 1; throw Error(exitCode); } cd('EndToEndTest'); if (argv.android) { echo('Running an Android e2e test'); echo('Installing e2e framework'); if (tryExecNTimes( () => exec('yarn add --dev appium@1.5.1 mocha@2.4.5 wd@0.3.11 colors@1.0.3 pretty-data2@0.40.1', { silent: true }).code, numberOfRetries)) { echo('Failed to install appium'); echo('Most common reason is npm registry connectivity, try again'); exitCode = 1; throw Error(exitCode); } cp(`${SCRIPTS}/android-e2e-test.js`, 'android-e2e-test.js'); cd('android'); echo('Downloading Maven deps'); exec('./gradlew :app:copyDownloadableDepsToLibs'); // Make sure we installed local version of react-native if (!test('-e', path.basename(MARKER_ANDROID))) { echo('Android marker was not found, react native init command failed?'); exitCode = 1; throw Error(exitCode); } cd('..'); exec('keytool -genkey -v -keystore android/keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"'); echo(`Starting appium server, ${APPIUM_PID}`); const appiumProcess = spawn('node', ['./node_modules/.bin/appium']); APPIUM_PID = appiumProcess.pid; echo('Building the app'); if (exec('buck build android/app').code) { echo('could not execute Buck build, is it installed and in PATH?'); exitCode = 1; throw Error(exitCode); } echo(`Starting packager server, ${SERVER_PID}`); // shelljs exec('', {async: true}) does not emit stdout events, so we rely on good old spawn const packagerProcess = spawn('yarn', ['start', '--max-workers 1'], { env: process.env }); SERVER_PID = packagerProcess.pid; // wait a bit to allow packager to startup exec('sleep 15s'); echo('Executing android e2e test'); if (tryExecNTimes( () => { exec('sleep 10s'); return exec('node node_modules/.bin/_mocha android-e2e-test.js').code; }, numberOfRetries)) { echo('Failed to run Android e2e tests'); echo('Most likely the code is broken'); exitCode = 1; throw Error(exitCode); } } if (argv.ios || argv.tvos) { var iosTestType = (argv.tvos ? 'tvOS' : 'iOS'); echo('Running the ' + iosTestType + 'app'); cd('ios'); // Make sure we installed local version of react-native if (!test('-e', path.join('EndToEndTest', path.basename(MARKER_IOS)))) { echo('iOS marker was not found, `react-native init` command failed?'); exitCode = 1; throw Error(exitCode); } // shelljs exec('', {async: true}) does not emit stdout events, so we rely on good old spawn const packagerEnv = Object.create(process.env); packagerEnv.REACT_NATIVE_MAX_WORKERS = 1; const packagerProcess = spawn('yarn', ['start', '--nonPersistent'], { stdio: 'inherit', env: packagerEnv }); SERVER_PID = packagerProcess.pid; exec('sleep 15s'); // prepare cache to reduce chances of possible red screen "Can't fibd variable __fbBatchedBridge..." exec('response=$(curl --write-out %{http_code} --silent --output /dev/null localhost:8081/index.bundle?platform=ios&dev=true)'); echo(`Starting packager server, ${SERVER_PID}`); echo('Executing ' + iosTestType + ' e2e test'); if (tryExecNTimes( () => { exec('sleep 10s'); if (argv.tvos) { return exec('xcodebuild -destination "platform=tvOS Simulator,name=Apple TV 1080p,OS=10.0" -scheme EndToEndTest-tvOS -sdk appletvsimulator test | xcpretty && exit ${PIPESTATUS[0]}').code; } else { return exec('xcodebuild -destination "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1" -scheme EndToEndTest -sdk iphonesimulator test | xcpretty && exit ${PIPESTATUS[0]}').code; } }, numberOfRetries)) { echo('Failed to run ' + iosTestType + ' e2e tests'); echo('Most likely the code is broken'); exitCode = 1; throw Error(exitCode); } cd('..'); } if (argv.js) { // Check the packager produces a bundle (doesn't throw an error) if (exec('react-native bundle --max-workers 1 --platform android --dev true --entry-file index.js --bundle-output android-bundle.js').code) { echo('Could not build Android bundle'); exitCode = 1; throw Error(exitCode); } if (exec('react-native --max-workers 1 bundle --platform ios --dev true --entry-file index.js --bundle-output ios-bundle.js').code) { echo('Could not build iOS bundle'); exitCode = 1; throw Error(exitCode); } if (exec(`${ROOT}/node_modules/.bin/flow check`).code) { echo('Flow check does not pass'); exitCode = 1; throw Error(exitCode); } if (exec('yarn test').code) { echo('Jest test failure'); exitCode = 1; throw Error(exitCode); } } exitCode = 0; } finally { cd(ROOT); rm(MARKER_IOS); rm(MARKER_ANDROID); if (SERVER_PID) { echo(`Killing packager ${SERVER_PID}`); exec(`kill -9 ${SERVER_PID}`); // this is quite drastic but packager starts a daemon that we can't kill by killing the parent process // it will be fixed in April (quote David Aurelio), so until then we will kill the zombie by the port number exec("lsof -i tcp:8081 | awk 'NR!=1 {print $2}' | xargs kill"); } if (APPIUM_PID) { echo(`Killing appium ${APPIUM_PID}`); exec(`kill -9 ${APPIUM_PID}`); } } exit(exitCode); /*eslint-enable no-undef */
hoastoolshop/react-native
scripts/run-ci-e2e-tests.js
JavaScript
bsd-3-clause
8,512
package HTTP::Proxy::Engine::Threaded; use strict; use HTTP::Proxy; use threads; # A massive hack of Engine::Fork to use the threads stuff # Basically created to work under win32 so that the filters # can share global caches among themselves # Angelos Karageorgiou angelos@unix.gr our @ISA = qw( HTTP::Proxy::Engine ); our %defaults = ( max_clients => 60, ); __PACKAGE__->make_accessors( qw( kids select ), keys %defaults ); sub start { my $self = shift; $self->kids( [] ); $self->select( IO::Select->new( $self->proxy->daemon ) ); } sub run { my $self = shift; my $proxy = $self->proxy; my $kids = $self->kids; # check for new connections my @ready = $self->select->can_read(1); for my $fh (@ready) { # there's only one, anyway # single-process proxy (useful for debugging) # accept the new connection my $conn = $fh->accept; my $child=threads->new(\&worker,$proxy,$conn); if ( !defined $child ) { $conn->close; $proxy->log( HTTP::Proxy::ERROR, "PROCESS", "Cannot spawn thread" ); next; } $child->detach(); } } sub stop { my $self = shift; my $kids = $self->kids; # not needed } sub worker { my $proxy=shift; my $conn=shift; $proxy->serve_connections($conn); $conn->close(); return; } 1; __END__ =head1 NAME HTTP::Proxy::Engine::Threaded - A scoreboard-based HTTP::Proxy engine =head1 SYNOPSIS my $proxy = HTTP::Proxy->new( engine => 'Threaded' ); =head1 DESCRIPTION This module provides a threaded engine to HTTP::Proxy. =head1 METHODS The module defines the following methods, used by HTTP::Proxy main loop: =over 4 =item start() Initialize the engine. =item run() Implements the forking logic: a new process is forked for each new incoming TCP connection. =item stop() Reap remaining child processes. =back =head1 SEE ALSO L<HTTP::Proxy>, L<HTTP::Proxy::Engine>. =head1 AUTHOR Angelos Karageorgiou C<< <angelos@unix.gr> >>. (Actual code) Philippe "BooK" Bruhat, C<< <book@cpan.org> >>. (Documentation) =head1 COPYRIGHT Copyright 2010, Philippe Bruhat. =head1 LICENSE This module is free software; you can redistribute it or modify it under the same terms as Perl itself. =cut
btovar/cvmfs
test/mock_services/HTTP/Proxy/Engine/Threaded.pm
Perl
bsd-3-clause
2,285
/* Copyright (c) 2013, Ford Motor Company All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Ford Motor Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_BUTTON_RESPONSE_H_ #define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_BUTTON_RESPONSE_H_ #include "application_manager/commands/command_response_impl.h" #include "utils/macro.h" namespace application_manager { namespace commands { /** * @brief SubscribeButtonResponse command class **/ class SubscribeButtonResponse : public CommandResponseImpl { public: /** * @brief SubscribeButtonResponse class constructor * * @param message Incoming SmartObject message **/ explicit SubscribeButtonResponse(const MessageSharedPtr& message); /** * @brief SubscribeButtonResponse class destructor **/ virtual ~SubscribeButtonResponse(); /** * @brief Execute command **/ virtual void Run(); private: DISALLOW_COPY_AND_ASSIGN(SubscribeButtonResponse); }; } // namespace commands } // namespace application_manager #endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_BUTTON_RESPONSE_H_
smartdevice475/sdl_core
src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_response.h
C
bsd-3-clause
2,628
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/path_service.h" #include "build/build_config.h" #include "chrome/test/remoting/qunit_browser_test_runner.h" #if defined(OS_MACOSX) #include "base/mac/foundation_util.h" #endif // !defined(OS_MACOSX) namespace remoting { // Flakily times out on Win7 Tests (dbg): https://crbug.com/504204. #if defined(OS_WIN) && !defined(NDEBUG) #define MAYBE_Remoting_Webapp_Js_Unittest DISABLED_Remoting_Webapp_Js_Unittest #else #define MAYBE_Remoting_Webapp_Js_Unittest Remoting_Webapp_Js_Unittest #endif IN_PROC_BROWSER_TEST_F(QUnitBrowserTestRunner, MAYBE_Remoting_Webapp_Js_Unittest) { base::FilePath base_dir; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &base_dir)); #if defined(OS_MACOSX) if (base::mac::AmIBundled()) { // If we are inside a mac bundle, navigate up to the output directory base_dir = base::mac::GetAppBundlePath(base_dir).DirName(); } #endif // !defined(OS_MACOSX) RunTest( base_dir.Append(FILE_PATH_LITERAL("remoting/unittests/unittests.html"))); } } // namespace remoting
joone/chromium-crosswalk
chrome/test/remoting/webapp_javascript_unittest.cc
C++
bsd-3-clause
1,215
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef GRPC_INTERNAL_CORE_CENSUS_CONTEXT_H #define GRPC_INTERNAL_CORE_CENSUS_CONTEXT_H #include <grpc/census.h> /* census_context is the in-memory representation of information needed to * maintain tracing, RPC statistics and resource usage information. */ struct census_context { gpr_uint64 op_id; /* Operation identifier - unique per-context */ gpr_uint64 trace_id; /* Globally unique trace identifier */ /* TODO(aveitch) Add census tags: const census_tag_set *tags; */ }; #endif /* GRPC_INTERNAL_CORE_CENSUS_CONTEXT_H */
bjori/grpc
src/core/census/context.h
C
bsd-3-clause
2,179
Android Deps Repository Generator --------------------------------- Tool to generate a gradle-specified repository for Android and Java dependencies. ### Usage fetch_all.py [--help] This script creates a temporary build directory, where it will, for each of the dependencies specified in `build.gradle`, take care of the following: - Download the library - Generate a README.chromium file - Download the LICENSE - Generate a GN target in BUILD.gn - Generate .info files for AAR libraries - Generate 3pp subdirectories describing the CIPD packages - Generate a `deps` entry in DEPS. It will then compare the build directory with your current workspace, and print the differences (i.e. new/updated/deleted packages names). ### Adding a new library or updating existing libraries. Full steps to add a new third party library or update existing libraries: 1. Update `build.gradle` with the new dependency or the new versions. 2. Run `fetch_all.py` to update your current workspace with the changes. This will update, among other things, your top-level DEPS file. If this is a new library, you can skip directly to step 5 since the next step is not going to work for you. 3. Run `gclient sync` to make sure that cipd has access to the versions you are trying to roll. This might fail with a cipd error failing to resolve a tag. 4. If the previous step works, upload your cl and you are done, if not continue with the steps. 5. Add a `overrideLatest` property override to your package in `ChromiumDepGraph.groovy` in the `PROPERTY_OVERRIDES` map, set it to `true`. 6. Run `fetch_all.py` again. 7. `git add` all the 3pp related changes and create a CL for review. Keep the `3pp/`, `.gradle`, `OWNERS`, `.groovy` changes in the CL and revert the other files. The other files should be committed in a follow up CL. Example git commands: * `git add third_party/android_deps{*.gradle,*.groovy,*3pp*,*OWNERS,*README.md}` * `git commit -m commit_message` * `git restore third_party/android_deps DEPS` * `git clean -id` 8. Land the first CL in the previous step and wait for the corresponding 3pp packager to create the new CIPD packages. The 3pp packager runs every 6 hours. You can see the latest runs [here][3pp_bot]. See [`//docs/cipd_and_3pp.md`][cipd_and_3pp_doc] for how it works. Anyone on the Clank build core team and any trooper can trigger the bot on demand for you. 9. If your follow up CL takes more than a day please revert the original CL. Once the bot uploads to cipd there is no need to keep the modified 3pp files. The bot runs 4 times a day. When you are ready to land the follow up CL, you can land everything together since the cipd packages have already been uploaded. 10. Remove your `overrideLatest` property override entry in `ChromiumDepGraph.groovy` so that the 3pp bot goes back to downloading and storing the latest versions of your package so that it is available when you next try to roll. 11. Run `fetch_all.py` again. Create a CL with the changes and land it. If the CL is doing more than upgrading existing packages or adding packages from the same source and license (e.g. gms) follow [`//docs/adding_to_third_party.md`][docs_link] for the review. If you are updating any of the gms dependencies, please ensure that the license file that they use, explained in the [README.chromium][readme_chromium_link] is up-to-date with the one on android's [website][android_sdk_link], last updated date is at the bottom. [3pp_bot]: https://ci.chromium.org/p/chromium/builders/ci/3pp-linux-amd64-packager [cipd_and_3pp_doc]: ../../docs/cipd_and_3pp.md [owners_link]: http://go/android-deps-owners [docs_link]: ../../docs/adding_to_third_party.md [android_sdk_link]: https://developer.android.com/studio/terms [readme_chromium_link]: ./README.chromium ### Implementation notes: The script invokes a Gradle plugin to leverage its dependency resolution features. An alternative way to implement it is to mix gradle to purely fetch dependencies and their pom.xml files, and use Python to process and generate the files. This approach was not as successful, as some information about the dependencies does not seem to be available purely from the POM file, which resulted in expecting dependencies that gradle considered unnecessary. This is especially true nowadays that pom.xml files for many dependencies are no longer maintained by the package authors. #### Groovy Style Guide The groovy code in `//third_party/android_deps/buildSrc/src/main/groovy` loosely follows the [Groovy Style Guide][groovy_style_guide], and can be linted by each dev with [npm-groovy-lint][npm_groovy_lint] via either: - Command Line `npm-groovy-lint -p third_party/android_deps/buildSrc/src/main/groovy/ --config ~/.groovylintrc.json` npm-groovy-lint can be installed via `npm install -g npm-groovy-lint`. - [VS Code extension][vs_code_groovy_lint]. The line length limit for groovy is **120** characters. Here is a sample `.groovylintrc.json` file: ``` { "extends": "recommended", "rules": { "CatchException": "off", "CompileStatic": "off", "DuplicateMapLiteral": "off", "DuplicateNumberLiteral": "off", "DuplicateStringLiteral": "off", "FactoryMethodName": "off", "JUnitPublicProperty": "off", "JavaIoPackageAccess": "off", "MethodCount": "off", "NestedForLoop": "off", "ThrowRuntimeException": "off", "formatting.Indentation": { "spacesPerIndentLevel": 4 } } } ``` This is a list of rule names: [Groovy Rule Index by Name][groovy_rule_index]. [groovy_style_guide]: https://groovy-lang.org/style-guide.html [npm_groovy_lint]: https://github.com/nvuillam/npm-groovy-lint [vs_code_groovy_lint]: https://marketplace.visualstudio.com/items?itemName=NicolasVuillamy.vscode-groovy-lint [groovy_rule_index]: https://codenarc.org/codenarc-rule-index-by-name.html
chromium/chromium
third_party/android_deps/README.md
Markdown
bsd-3-clause
5,998
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2013 Steven Lovegrove * * 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. */ #ifndef PANGOLIN_COMPAT_TYPE_TRAITS_H #define PANGOLIN_COMPAT_TYPE_TRAITS_H #include <pangolin/platform.h> #include <typeinfo> #ifdef CPP11_NO_BOOST #include <type_traits> #else #include <boost/type_traits.hpp> #endif #include <pangolin/compat/boostd.h> // enable_if From Boost namespace pangolin { template <bool B, class T = void> struct enable_if_c { typedef T type; }; template <class T> struct enable_if_c<false, T> {}; template <class Cond, class T = void> struct enable_if : public enable_if_c<Cond::value, T> {}; } #endif // PANGOLIN_COMPAT_TYPE_TRAITS_H
YAMMAY/Autoware
ros/src/computing/perception/localization/packages/orb_localizer/Thirdparty/Pangolin/include/pangolin/compat/type_traits.h
C
bsd-3-clause
1,836
import { Observable } from 'rx'; import { ofType } from 'redux-epic'; import { fetchMessagesComplete, fetchMessagesError } from './'; import { types as app } from '../../redux'; import { getJSON$ } from '../../../utils/ajax-stream.js'; export default function getMessagesEpic(actions) { return actions::ofType(app.appMounted) .flatMap(() => getJSON$('/api/users/get-messages') .map(fetchMessagesComplete) .catch(err => Observable.of(fetchMessagesError(err))) ); }
FreeCodeCampQuito/FreeCodeCamp
common/app/Flash/redux/get-messages-epic.js
JavaScript
bsd-3-clause
492
<!DOCTYPE html> <!-- Copyright (c) 2014 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Authors: Wang, Hongjuan <hongjuanx.wang@intel.com> --> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, width=device-width" /> <link rel="stylesheet" type="text/css" href="../../css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="../../css/main.css"> <script src="../../js/jquery-2.1.3.min.js"></script> <script src="../../js/bootstrap.min.js"></script> <script src="../../js/common.js"></script> <script src="../../js/tests.js"></script> <script src="../../main.js"></script> <script src="../../cordova.js"></script> <script src="js/main.js"></script> <body onload="init();"> <div id="header"> <h3 id="main_page_title"></h3> </div> <div class="content"> <h4>This sample demonstrates the app can play beep, vibrate, confirm dialog and prompt dialog.</h4> <button onclick="beep();" class="btn btn-default btn-lg btn-block">Play Beep</button> <button onclick="vibrate();" class="btn btn-default btn-lg btn-block">Vibrate</button> <button onclick="confirmDialogB('You pressed confirm.', 'Confirm Dialog', ['Yes', 'No', 'Maybe, Not Sure']);" class="btn btn-default btn-lg btn-block">Confirm Dialog</button> <button onclick="promptDialog('You pressed prompt.', 'Prompt Dialog', ['Yes', 'No', 'Maybe, Not Sure']);" class="btn btn-default btn-lg btn-block">Prompt Dialog</div> </button> <div class="footer"> <div id="footer"></div> </div> <div class="modal fade" id="popup_info"> <p>Notification features: beep, vibrate, confirm, prompt method.</p> </div> </body>
kangxu/demo-express
samples-cordova/CordovaNotification/index.html
HTML
bsd-3-clause
3,019
#include "castselection.h" #include "castviewer.h" #include "menubarcommandids.h" #include "toonzqt/icongenerator.h" #include "toonzqt/gutil.h" #include "toonz/toonzscene.h" #include "toonz/txshlevel.h" #include "toonz/txshsimplelevel.h" #include "toonz/txshpalettelevel.h" #include "toonz/txshlevelhandle.h" #include "toonz/tscenehandle.h" #include "toonz/sceneproperties.h" #include "tapp.h" #include "toonz/stage2.h" #include "tsystem.h" #include "toonz/txshsoundlevel.h" #include "toonz/preferences.h" //============================================================================= // // CastSelection // //----------------------------------------------------------------------------- CastSelection::CastSelection() : m_browser(0) {} //----------------------------------------------------------------------------- CastSelection::~CastSelection() {} //----------------------------------------------------------------------------- void CastSelection::getSelectedLevels(std::vector<TXshLevel *> &levels) { assert(m_browser); CastItems const &castItems = m_browser->getCastItems(); for (int i = 0; i < castItems.getItemCount(); i++) { if (!isSelected(i)) continue; TXshLevel *level = castItems.getItem(i)->getSimpleLevel(); if (!level) level = castItems.getItem(i)->getPaletteLevel(); if (!level) level = castItems.getItem(i)->getSoundLevel(); if (level) levels.push_back(level); } } //----------------------------------------------------------------------------- void CastSelection::enableCommands() { DvItemSelection::enableCommands(); assert(m_browser); if (m_browser) { enableCommand(m_browser, MI_ExposeResource, &CastBrowser::expose); enableCommand(m_browser, MI_EditLevel, &CastBrowser::edit); // enableCommand(m_browser, MI_ConvertToVectors, &CastBrowser::vectorize); enableCommand(m_browser, MI_ShowFolderContents, &CastBrowser::showFolderContents); } } // TODO: da qui in avanti: spostare in un altro file //============================================================================= // // CastBrowser::LevelItem // //----------------------------------------------------------------------------- QString LevelCastItem::getName() const { return QString::fromStdWString(m_level->getName()); } //----------------------------------------------------------------------------- QString LevelCastItem::getToolTip() const { TFilePath path = m_level->getPath(); return QString::fromStdWString(path.withoutParentDir().getWideString()); } //----------------------------------------------------------------------------- int LevelCastItem::getFrameCount() const { return m_level->getFrameCount(); } //----------------------------------------------------------------------------- QPixmap LevelCastItem::getPixmap(bool isSelected) const { TXshSimpleLevel *sl = m_level->getSimpleLevel(); if (!sl) return QPixmap(); ToonzScene *scene = sl->getScene(); assert(scene); if (!scene) return QPixmap(); bool onDemand = false; if (Preferences::instance()->getColumnIconLoadingPolicy() == Preferences::LoadOnDemand) onDemand = !isSelected; QPixmap icon = IconGenerator::instance()->getIcon(sl, sl->getFirstFid(), false, onDemand); return scalePixmapKeepingAspectRatio(icon, m_itemPixmapSize, Qt::transparent); } //----------------------------------------------------------------------------- bool LevelCastItem::exists() const { ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); return TSystem::doesExistFileOrLevel( scene->decodeFilePath(m_level->getPath())) || !getPixmap(false).isNull(); } //------------------------------------------------------- TXshSimpleLevel *LevelCastItem::getSimpleLevel() const { return m_level ? m_level->getSimpleLevel() : 0; } //============================================================================= // // CastBrowser::SoundItem // //----------------------------------------------------------------------------- QString SoundCastItem::getName() const { return QString::fromStdWString(m_soundLevel->getName()); } //----------------------------------------------------------------------------- QString SoundCastItem::getToolTip() const { TFilePath path = m_soundLevel->getPath(); return QString::fromStdWString(path.withoutParentDir().getWideString()); } //----------------------------------------------------------------------------- int SoundCastItem::getFrameCount() const { return m_soundLevel->getFrameCount(); } //----------------------------------------------------------------------------- QPixmap SoundCastItem::getPixmap(bool isSelected) const { static QPixmap loudspeaker(svgToPixmap( ":Resources/audio.svg", m_itemPixmapSize, Qt::KeepAspectRatio)); return loudspeaker; } //----------------------------------------------------------------------------- bool SoundCastItem::exists() const { ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); return TSystem::doesExistFileOrLevel( scene->decodeFilePath(m_soundLevel->getPath())); } //============================================================================= // // CastBrowser::PaletteCastItem // //----------------------------------------------------------------------------- QString PaletteCastItem::getName() const { return QString::fromStdWString(m_paletteLevel->getName()); } //----------------------------------------------------------------------------- QString PaletteCastItem::getToolTip() const { TFilePath path = m_paletteLevel->getPath(); return QString::fromStdWString(path.withoutParentDir().getWideString()); } //----------------------------------------------------------------------------- int PaletteCastItem::getFrameCount() const { return m_paletteLevel->getFrameCount(); } //----------------------------------------------------------------------------- QPixmap PaletteCastItem::getPixmap(bool isSelected) const { static QPixmap palette(svgToPixmap(":Resources/paletteicon.svg", m_itemPixmapSize, Qt::KeepAspectRatio)); return palette; } bool PaletteCastItem::exists() const { ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); return TSystem::doesExistFileOrLevel( scene->decodeFilePath(m_paletteLevel->getPath())); } //============================================================================= // // CastItems // //----------------------------------------------------------------------------- CastItems::CastItems() : QMimeData() {} //----------------------------------------------------------------------------- CastItems::~CastItems() { clear(); } //----------------------------------------------------------------------------- void CastItems::clear() { clearPointerContainer(m_items); } //----------------------------------------------------------------------------- void CastItems::addItem(CastItem *item) { m_items.push_back(item); } //----------------------------------------------------------------------------- CastItem *CastItems::getItem(int index) const { assert(0 <= index && index < (int)m_items.size()); return m_items[index]; } //----------------------------------------------------------------------------- bool CastItems::hasFormat(const QString &mimeType) const { return mimeType == getMimeFormat(); } //----------------------------------------------------------------------------- QString CastItems::getMimeFormat() { return "application/vnd.toonz.levels"; } //----------------------------------------------------------------------------- QStringList CastItems::formats() const { return QStringList(QString("application/vnd.toonz.levels")); } //----------------------------------------------------------------------------- CastItems *CastItems::getSelectedItems(const std::set<int> &indices) const { CastItems *c = new CastItems(); std::set<int>::const_iterator it; for (it = indices.begin(); it != indices.end(); ++it) { int index = *it; if (0 <= index && index < getItemCount()) c->addItem(getItem(index)->clone()); } return c; }
damies13/opentoonz
toonz/sources/toonz/castselection.cpp
C++
bsd-3-clause
8,176
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ENTERPRISE_CONNECTORS_FILE_SYSTEM_BROWSERTEST_HELPER_H_ #define CHROME_BROWSER_ENTERPRISE_CONNECTORS_FILE_SYSTEM_BROWSERTEST_HELPER_H_ #include <string> #include <vector> #include "base/memory/raw_ptr.h" #include "base/strings/stringprintf.h" #include "base/task/current_thread.h" #include "base/values.h" #include "chrome/browser/enterprise/connectors/connectors_service.h" #include "chrome/browser/enterprise/connectors/file_system/box_uploader.h" #include "chrome/browser/enterprise/connectors/file_system/rename_handler.h" #include "chrome/browser/enterprise/connectors/file_system/signin_experience.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/chrome_paths.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/ui_test_utils.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/policy_constants.h" #include "components/variations/variations_params_manager.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/download_test_observer.h" #include "google_apis/gaia/gaia_urls.h" #include "net/dns/mock_host_resolver.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace enterprise_connectors { enum DownloadServiceProvider { kLocal, kBox, kUnknown }; std::string GetAllAllowedTestPolicy(const char* enterprise_id); std::string GetTestPolicyWithEnabledFilter(const char* enterprise_id, const char* include_url, const char* include_mime); std::string GetTestPolicyWithDisabledFilter(const char* enterprise_id, const char* exclude_url, const char* exclude_mime); class BoxSignInObserver : public SigninExperienceTestObserver, public content::WebContentsObserver, public views::WidgetObserver { public: enum class Page { kSignin, kAuth, kUnknown }; explicit BoxSignInObserver(FileSystemRenameHandler* rename_handler); ~BoxSignInObserver() override; // Accept the Sign in confirmation dialog to bring up the Box.com // sign in dialog. void AcceptSignInConfirmation(); void CancelSignInConfirmation(); // Bypass Single-Factor-Authentication sign in and authorize // Chrome to access Box.com resources. void AuthorizeWithUserAndPasswordSFA(const std::string& username, const std::string& password); // Bypass 2-Factor-Authentication sign in and authorize // Chrome to access Box.com resources. void AuthorizeWithUserAndPassword2FA(const std::string& username, const std::string& password, const std::string& sms_code, bool manually_submit_sms_code); void SubmitInvalidSignInCredentials(const std::string& username, const std::string& password); bool GetUserNameFromSignInPage(std::string* result); void CloseSignInWidget(); void WaitForPageLoad(); void WaitForSignInConfirmationDialog(); void WaitForSignInDialogToShow(); void WaitForSignInDialogToClose(base::OnceClosure trigger_close_action); // content::WebContentsObserver void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) override; // views::WidgetObserver void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override; // SigninExperienceTestObserver void OnConfirmationDialogCreated( views::DialogDelegate* confirmation_dialog_delegate) override; void OnSignInDialogCreated(content::WebContents* dialog_web_content, FileSystemSigninDialogDelegate* dialog_delegate, views::Widget* dialog_widget) override; void BypassSignInWebsite(const GoogleServiceAuthError& status, const std::string& access_token, const std::string& refresh_token); private: static bool IsBoxSignInURI(const GURL& url); static bool IsBoxAuthorizeURI(const GURL& url); static std::string GetSubmitAccountSignInScript(const std::string& username, const std::string& password); static std::string GetSubmitSmsCodeScript(const std::string& password); static std::string GetClickAuthorizeScript(); Page current_page_ = Page::kUnknown; // This bool variable allows this class to differentiate an expected dialog // closure from unexpected dialog shutdown/crash/exits. Before triggering an // action to close the dialog, the test class will set this variable to true. bool expecting_dialog_shutdown_ = false; raw_ptr<views::DialogDelegate> signin_confirmation_dlg_ = nullptr; raw_ptr<views::Widget> sign_in_widget_ = nullptr; raw_ptr<FileSystemSigninDialogDelegate> sign_in_dlg_ = nullptr; std::unique_ptr<base::RunLoop> run_loop_; base::OnceClosure stop_waiting_for_signin_confirmation_; base::OnceClosure stop_waiting_for_page_load_; base::OnceClosure stop_waiting_for_widget_to_show_; base::OnceClosure stop_waiting_for_dialog_shutdown_; base::OnceClosure stop_waiting_for_authorization_completion_; }; class BoxDownloadItemObserver : public download::DownloadItem::Observer { public: explicit BoxDownloadItemObserver(download::DownloadItem* item); ~BoxDownloadItemObserver() override; void OnDownloadDestroyed(download::DownloadItem* item) override; void OnRenameHandlerCreated(download::DownloadItem* item); void OnDownloadUpdated(download::DownloadItem* item) override; // Wait for when the reroute info on a download::DownloadItem is accurate. // If the DownloadItem downloads to a local file, then this method should // stop when the download completes. // If the DownloadItem will be rerouted, then this method should stop when // the DownloadItem's rename handler kicks off. void WaitForDownloadItemRerouteInfo(); void WaitForRenameHandlerCreation(); void WaitForSignInConfirmationDialog(); DownloadServiceProvider GetServiceProvider(); download::DownloadItem* download_item() { return download_item_; } BoxSignInObserver* sign_in_observer() { return sign_in_observer_.get(); } BoxFetchAccessTokenTestObserver* fetch_access_token_observer() { return fetch_access_token_observer_.get(); } BoxUploader::TestObserver* upload_observer() { return upload_observer_.get(); } private: raw_ptr<download::DownloadItem> download_item_ = nullptr; base::OnceClosure stop_waiting_for_rename_handler_creation_; base::OnceClosure stop_waiting_for_download_near_completion_; bool rename_handler_created_ = false; std::unique_ptr<RenameStartObserver> rename_start_observer_; std::unique_ptr<BoxSignInObserver> sign_in_observer_; std::unique_ptr<BoxFetchAccessTokenTestObserver> fetch_access_token_observer_; std::unique_ptr<BoxUploader::TestObserver> upload_observer_; }; class FileSystemConnectorBrowserTestBase : public InProcessBrowserTest { public: FileSystemConnectorBrowserTestBase() = default; ~FileSystemConnectorBrowserTestBase() override = default; protected: void SetUpOnMainThread() override; void SetUpCommandLine(base::CommandLine* command_line) override; void TearDownOnMainThread() override; void SetCloudFSCPolicy(const std::string& policy_value); bool IsFSCEnabled(); private: base::test::ScopedFeatureList feature_list_; }; } // namespace enterprise_connectors #endif // CHROME_BROWSER_ENTERPRISE_CONNECTORS_FILE_SYSTEM_BROWSERTEST_HELPER_H_
ric2b/Vivaldi-browser
chromium/chrome/browser/enterprise/connectors/file_system/browsertest_helper.h
C
bsd-3-clause
8,600
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_COMMON_CONFLICTS_MODULE_WATCHER_WIN_H_ #define CHROME_COMMON_CONFLICTS_MODULE_WATCHER_WIN_H_ #include <memory> #include "base/callback.h" #include "base/files/file_path.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" class ModuleWatcherTest; union LDR_DLL_NOTIFICATION_DATA; // This class observes modules as they are loaded into a process's address // space. // // This class is safe to be created on any thread. Similarly, it is safe to be // destroyed on any thread, independent of the thread on which the instance was // created. class ModuleWatcher { public: // The types of module events that can occur. enum class ModuleEventType { // A module was already loaded, but its presence is being observed. kModuleAlreadyLoaded, // A module is in the process of being loaded. kModuleLoaded, }; // Houses information about a module event, and some module metadata. struct ModuleEvent { ModuleEvent() = default; ModuleEvent(const ModuleEvent& other) = default; ModuleEvent(ModuleEventType event_type, const base::FilePath& module_path, void* module_load_address, size_t module_size) : event_type(event_type), module_path(module_path), module_load_address(module_load_address), module_size(module_size) {} // The type of module event. ModuleEventType event_type; // The full path to the module on disk. base::FilePath module_path; // The load address of the module. Careful consideration must be made before // accessing memory at this address. See the comment for // OnModuleEventCallback. raw_ptr<void> module_load_address; // The size of the module in memory. size_t module_size; }; // The type of callback that will be invoked for each module event. This // callback may be run from any thread in the process, and may be invoked // during initialization (while iterating over already loaded modules) or in // response to LdrDllNotifications received from the loader. As such, keep the // amount of work performed here to an absolute minimum. // // MODULE_LOADED events are always dispatched directly from the loader while // under the loader's lock, so the module is guaranteed to be loaded in memory // (it is safe to access module_load_address). // // If the event is of type MODULE_ALREADY_LOADED, then the module data comes // from a snapshot and it is possible that its |module_load_address| is // invalid by the time the event is sent. // // Note that it is possible for this callback to be invoked after the // destruction of the watcher. using OnModuleEventCallback = base::RepeatingCallback<void(const ModuleEvent& event)>; // Creates and starts a watcher. This enumerates all loaded modules // synchronously on the current thread during construction, and provides // synchronous notifications as modules are loaded. The callback is invoked in // the context of the thread that is loading a module, and as such may be // invoked on any thread in the process. Note that it is possible to receive // two notifications for some modules as the initial loaded module enumeration // races briefly with the callback mechanism. In this case both a // MODULE_LOADED and a MODULE_ALREADY_LOADED event will be received for the // same module. Since the callback is installed first no modules can be // missed, however. This factory function may be called on any thread. // // Only a single instance of a watcher may exist at any moment. This will // return nullptr when trying to create a second watcher. static std::unique_ptr<ModuleWatcher> Create(OnModuleEventCallback callback); ModuleWatcher(const ModuleWatcher&) = delete; ModuleWatcher& operator=(const ModuleWatcher&) = delete; // This can be called on any thread. After destruction the |callback| // provided to the constructor will no longer be invoked with module events. ~ModuleWatcher(); private: // For unittesting. friend class ModuleWatcherTest; // Private to enforce Singleton semantics. See Create above. ModuleWatcher(); // Initializes the ModuleWatcher instance. void Initialize(OnModuleEventCallback callback); // Registers a DllNotification callback with the OS. Modifies // |dll_notification_cookie_|. Can be called on any thread. void RegisterDllNotificationCallback(); // Removes the installed DllNotification callback. Modifies // |dll_notification_cookie_|. Can be called on any thread. void UnregisterDllNotificationCallback(); // Enumerates all currently loaded modules, synchronously invoking callbacks // on the current thread. Can be called on any thread. static void EnumerateAlreadyLoadedModules( scoped_refptr<base::SequencedTaskRunner> task_runner, OnModuleEventCallback callback); // Helper function for retrieving the callback associated with a given // LdrNotification context. static OnModuleEventCallback GetCallbackForContext(void* context); // The loader notification callback. This is actually // void CALLBACK LoaderNotificationCallback( // DWORD, const LDR_DLL_NOTIFICATION_DATA*, PVOID) // Not using CALLBACK/DWORD/PVOID allows skipping the windows.h header from // this file. static void __stdcall LoaderNotificationCallback( unsigned long notification_reason, const LDR_DLL_NOTIFICATION_DATA* notification_data, void* context); // Used to bind the |callback_| to a WeakPtr. void RunCallback(const ModuleEvent& event); // The current callback. Can end up being invoked on any thread. OnModuleEventCallback callback_; // Used by the DllNotification mechanism. void* dll_notification_cookie_ = nullptr; base::WeakPtrFactory<ModuleWatcher> weak_ptr_factory_{this}; }; #endif // CHROME_COMMON_CONFLICTS_MODULE_WATCHER_WIN_H_
ric2b/Vivaldi-browser
chromium/chrome/common/conflicts/module_watcher_win.h
C
bsd-3-clause
6,126
import { defineProperty, deprecateProperty } from '..'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor( 'defineProperty', class extends AbstractTestCase { ['@test toString'](assert) { let obj = {}; defineProperty(obj, 'toString', undefined, function () { return 'FOO'; }); assert.equal(obj.toString(), 'FOO', 'should replace toString'); } } ); moduleFor( 'Ember.deprecateProperty', class extends AbstractTestCase { ['@test enables access to deprecated property and returns the value of the new property']( assert ) { assert.expect(3); let obj = { foo: 'bar' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); expectDeprecation(); assert.equal(obj.baz, obj.foo, 'baz and foo are equal'); obj.foo = 'blammo'; assert.equal(obj.baz, obj.foo, 'baz and foo are equal'); } ['@test deprecatedKey is not enumerable'](assert) { assert.expect(2); let obj = { foo: 'bar', blammo: 'whammy' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); for (let prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { assert.notEqual(prop, 'baz'); } } } ['@test enables setter to deprecated property and updates the value of the new property']( assert ) { assert.expect(3); let obj = { foo: 'bar' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); expectDeprecation(); obj.baz = 'bloop'; assert.equal(obj.foo, 'bloop', 'updating baz updates foo'); assert.equal(obj.baz, obj.foo, 'baz and foo are equal'); } } );
sly7-7/ember.js
packages/@ember/-internals/metal/tests/properties_test.js
JavaScript
mit
1,800
<!DOCTYPE html> <meta charset="utf-8"> <title>GopherCon 2017 Contribution Dashboard</title> <meta name=viewport content="width=device-width,minimum-scale=1,maximum-scale=1"> <style> * { box-sizing: border-box; margin: 0; padding: 0; } a:link, a:visited { color: #fff; } .Site { background-color: #2a2a2a; color: #fff; display: flex; flex-direction: column; font: 14px 'Helvetica-Neue', Helvetica, sans-serif; height: 100vh; text-rendering: optimizeLegibility; } .Site-body { display: flex; flex: 1; } .Site-content { border-right: 1px solid #3a3939; overflow: hidden; padding: 1.5em; width: 60%; } .Site-activity { background-color: #323232; flex: 1; overflow: scroll; } .Site-logo { height: 60px; margin-right: 2em; } .Site-pointsTitle, .Site-points { text-align: center; } .Site-pointsTitle { font-size: 4vh; letter-spacing: 1px; text-transform: uppercase; } .Site-points { font-size: 30vh; } .u-avatar { border-radius: 50%; } .AvatarGroup { display: flex; flex-wrap: wrap; justify-content: center; } .AvatarGroup-avatar { height: 6vh; margin: 0 .5em .5em 0; width: 6vh; } .Activity { align-items: flex-start; background-color: #323232; border-bottom: 1px solid #2d2d2d; border-top: 1px solid #404040; display: flex; font-size: 2vw; padding: 1em; } .Activity-avatar { height: 2.5em; margin-right: .75em; width: 2.5em; } .Activity-main { flex: 1; margin-right: .15em; } .Activity-points { color: #85ebf9; font-size: .85em; margin-top: .25em; } .Activity-icon { font-size: 2em; } .Site-footer { align-items: center; background: #3a3737; display: flex; justify-content: space-between; padding: 1em 1.5em; } </style> <body class="Site"> <div class="Site-body"> <main class="Site-content"> <div class="Site-pointsTitle">Total points</div> <div class="Site-points js-totalPoints">0</div> <div class="AvatarGroup js-avatarGroup"></div> </main> <aside class="Site-activity js-activityList"></aside> </div> <footer class="Site-footer"> <img class="Site-logo" src="https://github.com/ashleymcnamara/gophers/raw/master/GoCommunity.png" alt="Go Community"> <div> Gopher artwork by <a href="https://github.com/ashleymcnamara/gophers" target="_blank">Ashley McNamara</a> based on the original artwork by the amazing <a href="https://reneefrench.blogspot.com/" target="_blank">Renee French</a>. Licensed under a <a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.</a> </div> </footer> </body> <template class="activityTemplate"> <div class="Activity"> <img class="u-avatar Activity-avatar js-avatar"> <div class="Activity-main"> <div class="Activity-body js-body"></div> <div class="Activity-points js-points"></div> </div> <div class="Activity-icon js-icon"></div> </div> </template> <script> (function() { 'use strict'; const ActivityType = { AMEND_CHANGE: 'AMEND_CHANGE', CREATE_CHANGE: 'CREATE_CHANGE', MERGE_CHANGE: 'MERGE_CHANGE', REGISTER: 'REGISTER', }; const iconMap = {}; iconMap.AMEND_CHANGE = '👍'; iconMap.CREATE_CHANGE = '👏'; iconMap.MERGE_CHANGE = '🤘'; iconMap.REGISTER = '🎉'; let lastUpdateMs = 0; getActivities(lastUpdateMs); startUpdateLoop(); function getActivities(since) { const url = `/_/activities?since=${since}`; fetch(url).then(resp => { resp.json().then(obj => { processAll(obj.activities); updatePoints(obj.totalPoints); }); }).catch(err => { console.error(err); }); } function startUpdateLoop() { window.setInterval(() => { getActivities(lastUpdateMs); }, 5000); } // Username => img element. let avatarMap = {}; function processAll(activities) { const activityListEl = document.querySelector('.js-activityList'); const avatarGroupEl = document.querySelector('.js-avatarGroup'); activities.forEach(activity => { if (!avatarMap[activity.gitHubUser]) { const el = createAvatarEl(activity.gitHubUser); el.classList.add('AvatarGroup-avatar'); avatarMap[activity.gitHubUser] = el; } avatarGroupEl.insertBefore(avatarMap[activity.gitHubUser], avatarGroupEl.firstChild); const activityEl = createActivityEl(activity); activityListEl.insertBefore(activityEl, activityListEl.firstChild); }); if (activities.length > 0) { lastUpdateMs = new Date(activities[activities.length - 1].created).getTime(); } } function updatePoints(points) { document.querySelector('.js-totalPoints').textContent = points; } function createAvatarEl(username) { let img = document.createElement('IMG'); img.classList.add('u-avatar'); img.src = avatarSrc(username); img.alt = avatarAlt(username); return img; } function avatarSrc(username) { return `https://github.com/${encodeURIComponent(username)}.png?size=100`; } function avatarAlt(username) { return `Avatar for ${username}`; } function activityBody(type, username) { switch (type) { case ActivityType.AMEND_CHANGE: return `${username} just amended a change!`; case ActivityType.CREATE_CHANGE: return `${username} just created a change!`; case ActivityType.MERGE_CHANGE: return `${username} just merged a change!`; case ActivityType.REGISTER: return `${username} just registered!`; } } function pointsStr(points) { return `+${points} Point` + (points > 1 ? 's' : ''); } function createActivityEl(activity) { const tmpl = document.querySelector('.activityTemplate'); const imgEl = tmpl.content.querySelector('.js-avatar'); imgEl.src = avatarSrc(activity.gitHubUser); imgEl.alt = avatarAlt(activity.gitHubUser); tmpl.content.querySelector('.js-icon').textContent = iconMap[activity.type]; tmpl.content.querySelector('.js-body').textContent = activityBody(activity.type, activity.gitHubUser); tmpl.content.querySelector('.js-points').textContent = pointsStr(activity.points); return document.importNode(tmpl.content, true); } })(); </script>
xor-gate/cicd
vendor/github.com/golang/build/devapp/static/gophercon/index.html
HTML
mit
6,306
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2014 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using AnimationOrTween; using System.Collections.Generic; /// <summary> /// Mainly an internal script used by UIButtonPlayAnimation, but can also be used to call /// the specified function on the game object after it finishes animating. /// </summary> [AddComponentMenu("NGUI/Internal/Active Animation")] public class ActiveAnimation : MonoBehaviour { /// <summary> /// Active animation that resulted in the event notification. /// </summary> static public ActiveAnimation current; /// <summary> /// Event delegates called when the animation finishes. /// </summary> public List<EventDelegate> onFinished = new List<EventDelegate>(); // Deprecated functionality, kept for backwards compatibility [HideInInspector] public GameObject eventReceiver; [HideInInspector] public string callWhenFinished; Animation mAnim; Direction mLastDirection = Direction.Toggle; Direction mDisableDirection = Direction.Toggle; bool mNotify = false; Animator mAnimator; string mClip = ""; float playbackTime { get { AnimatorStateInfo state = mAnimator.GetCurrentAnimatorStateInfo(0); return Mathf.Clamp01(state.normalizedTime); } } /// <summary> /// Whether the animation is currently playing. /// </summary> public bool isPlaying { get { if (mAnim == null) { if (mAnimator != null) { if (mLastDirection == Direction.Reverse) { if (playbackTime == 0f) return false; } else if (playbackTime == 1f) return false; return true; } return false; } foreach (AnimationState state in mAnim) { if (!mAnim.IsPlaying(state.name)) continue; if (mLastDirection == Direction.Forward) { if (state.time < state.length) return true; } else if (mLastDirection == Direction.Reverse) { if (state.time > 0f) return true; } else return true; } return false; } } /// <summary> /// Immediately finish playing the animation. /// </summary> public void Finish () { if (mAnim != null) { foreach (AnimationState state in mAnim) { if (mLastDirection == Direction.Forward) state.time = state.length; else if (mLastDirection == Direction.Reverse) state.time = 0f; } } else if (mAnimator != null) { mAnimator.Play(mClip, 0, (mLastDirection == Direction.Forward) ? 1f : 0f); } } /// <summary> /// Manually reset the active animation to the beginning. /// </summary> public void Reset () { if (mAnim != null) { foreach (AnimationState state in mAnim) { if (mLastDirection == Direction.Reverse) state.time = state.length; else if (mLastDirection == Direction.Forward) state.time = 0f; } } else if (mAnimator != null) { mAnimator.Play(mClip, 0, (mLastDirection == Direction.Reverse) ? 1f : 0f); } } /// <summary> /// Event receiver is only kept for backwards compatibility purposes. It's removed on start if new functionality is used. /// </summary> void Start () { if (eventReceiver != null && EventDelegate.IsValid(onFinished)) { eventReceiver = null; callWhenFinished = null; } } /// <summary> /// Notify the target when the animation finishes playing. /// </summary> void Update () { float delta = RealTime.deltaTime; if (delta == 0f) return; if (mAnimator != null) { mAnimator.Update((mLastDirection == Direction.Reverse) ? -delta : delta); if (isPlaying) return; mAnimator.enabled = false; enabled = false; } else if (mAnim != null) { bool playing = false; foreach (AnimationState state in mAnim) { if (!mAnim.IsPlaying(state.name)) continue; float movement = state.speed * delta; state.time += movement; if (movement < 0f) { if (state.time > 0f) playing = true; else state.time = 0f; } else { if (state.time < state.length) playing = true; else state.time = state.length; } } mAnim.Sample(); if (playing) return; enabled = false; } else { enabled = false; return; } if (mNotify) { mNotify = false; if (current == null) { current = this; EventDelegate.Execute(onFinished); // Deprecated functionality, kept for backwards compatibility if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished)) eventReceiver.SendMessage(callWhenFinished, SendMessageOptions.DontRequireReceiver); current = null; } if (mDisableDirection != Direction.Toggle && mLastDirection == mDisableDirection) NGUITools.SetActive(gameObject, false); } } /// <summary> /// Play the specified animation. /// </summary> void Play (string clipName, Direction playDirection) { // Determine the play direction if (playDirection == Direction.Toggle) playDirection = (mLastDirection != Direction.Forward) ? Direction.Forward : Direction.Reverse; if (mAnim != null) { // We will sample the animation manually so that it works when the time is paused enabled = true; mAnim.enabled = false; bool noName = string.IsNullOrEmpty(clipName); // Play the animation if it's not playing already if (noName) { if (!mAnim.isPlaying) mAnim.Play(); } else if (!mAnim.IsPlaying(clipName)) { mAnim.Play(clipName); } // Update the animation speed based on direction -- forward or back foreach (AnimationState state in mAnim) { if (string.IsNullOrEmpty(clipName) || state.name == clipName) { float speed = Mathf.Abs(state.speed); state.speed = speed * (int)playDirection; // Automatically start the animation from the end if it's playing in reverse if (playDirection == Direction.Reverse && state.time == 0f) state.time = state.length; else if (playDirection == Direction.Forward && state.time == state.length) state.time = 0f; } } // Remember the direction for disable checks in Update() mLastDirection = playDirection; mNotify = true; mAnim.Sample(); } else if (mAnimator != null) { if (enabled && isPlaying) { if (mClip == clipName) { mLastDirection = playDirection; return; } } enabled = true; mNotify = true; mLastDirection = playDirection; mClip = clipName; mAnimator.Play(mClip, 0, (playDirection == Direction.Forward) ? 0f : 1f); // NOTE: If you are getting a message "Animator.GotoState: State could not be found" // it means that you chose a state name that doesn't exist in the Animator window. } } /// <summary> /// Play the specified animation on the specified object. /// </summary> static public ActiveAnimation Play (Animation anim, string clipName, Direction playDirection, EnableCondition enableBeforePlay, DisableCondition disableCondition) { if (!NGUITools.GetActive(anim.gameObject)) { // If the object is disabled, don't do anything if (enableBeforePlay != EnableCondition.EnableThenPlay) return null; // Enable the game object before animating it NGUITools.SetActive(anim.gameObject, true); // Refresh all panels right away so that there is no one frame delay UIPanel[] panels = anim.gameObject.GetComponentsInChildren<UIPanel>(); for (int i = 0, imax = panels.Length; i < imax; ++i) panels[i].Refresh(); } ActiveAnimation aa = anim.GetComponent<ActiveAnimation>(); if (aa == null) aa = anim.gameObject.AddComponent<ActiveAnimation>(); aa.mAnim = anim; aa.mDisableDirection = (Direction)(int)disableCondition; aa.onFinished.Clear(); aa.Play(clipName, playDirection); if (aa.mAnim != null) aa.mAnim.Sample(); else if (aa.mAnimator != null) aa.mAnimator.Update(0f); return aa; } /// <summary> /// Play the specified animation. /// </summary> static public ActiveAnimation Play (Animation anim, string clipName, Direction playDirection) { return Play(anim, clipName, playDirection, EnableCondition.DoNothing, DisableCondition.DoNotDisable); } /// <summary> /// Play the specified animation. /// </summary> static public ActiveAnimation Play (Animation anim, Direction playDirection) { return Play(anim, null, playDirection, EnableCondition.DoNothing, DisableCondition.DoNotDisable); } /// <summary> /// Play the specified animation on the specified object. /// </summary> static public ActiveAnimation Play (Animator anim, string clipName, Direction playDirection, EnableCondition enableBeforePlay, DisableCondition disableCondition) { if (!NGUITools.GetActive(anim.gameObject)) { // If the object is disabled, don't do anything if (enableBeforePlay != EnableCondition.EnableThenPlay) return null; // Enable the game object before animating it NGUITools.SetActive(anim.gameObject, true); // Refresh all panels right away so that there is no one frame delay UIPanel[] panels = anim.gameObject.GetComponentsInChildren<UIPanel>(); for (int i = 0, imax = panels.Length; i < imax; ++i) panels[i].Refresh(); } ActiveAnimation aa = anim.GetComponent<ActiveAnimation>(); if (aa == null) aa = anim.gameObject.AddComponent<ActiveAnimation>(); aa.mAnimator = anim; aa.mDisableDirection = (Direction)(int)disableCondition; aa.onFinished.Clear(); aa.Play(clipName, playDirection); if (aa.mAnim != null) aa.mAnim.Sample(); else if (aa.mAnimator != null) aa.mAnimator.Update(0f); return aa; } }
xclouder/particlecollect
Assets/NGUI/Scripts/Internal/ActiveAnimation.cs
C#
mit
9,484
<?php defined('C5_EXECUTE') or die("Access Denied."); use \Concrete\Core\File\EditResponse as FileEditResponse; $u = new User(); $form = Loader::helper('form'); $dh = Core::make('helper/date'); /* @var $dh \Concrete\Core\Localization\Service\Date */ $fp = FilePermissions::getGlobal(); if (!$fp->canAccessFileManager()) { die(t("Unable to access the file manager.")); } $token_validator = \Core::make('helper/validation/token'); if ($_POST['task'] == 'delete_files') { $fr = new FileEditResponse(); if ($token_validator->validate('files/delete')) { $files = array(); if (is_array($_POST['fID'])) { foreach ($_POST['fID'] as $fID) { $f = File::getByID($fID); $fp = new Permissions($f); if ($fp->canDeleteFile()) { $files[] = $f; $f->delete(); } else { throw new Exception(t('Unable to delete one or more files.')); } } } $fr->setMessage(t2('%s file deleted successfully.', '%s files deleted successfully.', count($files))); } else { $fr->setError(new \Exception('Invalid Token')); } $fr->outputJSON(); } $form = Loader::helper('form'); $files = array(); if (is_array($_REQUEST['fID'])) { foreach ($_REQUEST['fID'] as $fID) { $files[] = File::getByID($fID); } } else { $files[] = File::getByID($_REQUEST['fID']); } $fcnt = 0; foreach ($files as $f) { $fp = new Permissions($f); if ($fp->canDeleteFile()) { ++$fcnt; } } ?> <div class="ccm-ui"> <br/> <?php if ($fcnt == 0) { ?> <p><?php echo t("You do not have permission to delete any of the selected files."); ?><p> <?php } else { ?> <div class="alert alert-warning"><?php echo t('Are you sure you want to delete the following files?')?></div> <form data-dialog-form="delete-file" method="post" action="<?php echo REL_DIR_FILES_TOOLS_REQUIRED?>/files/delete"> <?php echo $token_validator->output('files/delete') ?> <?php echo $form->hidden('task', 'delete_files')?> <table border="0" cellspacing="0" cellpadding="0" width="100%" class="table table-striped"> <?php foreach ($files as $f) { $fp = new Permissions($f); if ($fp->canDeleteFile()) { $fv = $f->getApprovedVersion(); if (is_object($fv)) { ?> <?php echo $form->hidden('fID[]', $f->getFileID())?> <tr> <td><?php echo $fv->getType()?></td> <td class="ccm-file-list-filename" width="100%"><div style="word-wrap: break-word; width: 150px"><?php echo h($fv->getTitle())?></div></td> <td><?php echo $dh->formatDateTime($f->getDateAdded()->getTimestamp())?></td> <td><?php echo $fv->getSize()?></td> <td><?php echo $fv->getAuthorName()?></td> </tr> <?php } } } ?> </table> </form> <div class="dialog-buttons"> <button class="btn btn-default pull-left" data-dialog-action="cancel"><?php echo t('Cancel')?></button> <button type="button" data-dialog-action="submit" class="btn btn-danger pull-right"><?php echo t('Delete')?></button> </div> </div> <script type="text/javascript"> $(function() { ConcreteEvent.subscribe('AjaxFormSubmitSuccess', function(e, data) { if (data.form == 'delete-file') { ConcreteEvent.publish('FileManagerDeleteFilesComplete', {files: data.response.files}); } }); }); </script> <?php }
noLunch/nolunch
concrete5/concrete/tools/files/delete.php
PHP
mit
3,435
/*************************************************************************/ /* gd_parser.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ /* */ /* 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. */ /*************************************************************************/ #ifndef GD_PARSER_H #define GD_PARSER_H #include "gd_tokenizer.h" #include "gd_functions.h" #include "map.h" #include "object.h" class GDParser { public: struct Node { enum Type { TYPE_CLASS, TYPE_FUNCTION, TYPE_BUILT_IN_FUNCTION, TYPE_BLOCK, TYPE_IDENTIFIER, TYPE_TYPE, TYPE_CONSTANT, TYPE_ARRAY, TYPE_DICTIONARY, TYPE_SELF, TYPE_OPERATOR, TYPE_CONTROL_FLOW, TYPE_LOCAL_VAR, TYPE_ASSERT, TYPE_NEWLINE, }; Node * next; int line; int column; Type type; virtual ~Node() {} }; struct FunctionNode; struct BlockNode; struct ClassNode : public Node { bool tool; StringName name; bool extends_used; StringName extends_file; Vector<StringName> extends_class; struct Member { PropertyInfo _export; #ifdef TOOLS_ENABLED Variant default_value; #endif StringName identifier; StringName setter; StringName getter; int line; Node *expression; }; struct Constant { StringName identifier; Node *expression; }; struct Signal { StringName name; Vector<StringName> arguments; }; Vector<ClassNode*> subclasses; Vector<Member> variables; Vector<Constant> constant_expressions; Vector<FunctionNode*> functions; Vector<FunctionNode*> static_functions; Vector<Signal> _signals; BlockNode *initializer; ClassNode *owner; //Vector<Node*> initializers; int end_line; ClassNode() { tool=false; type=TYPE_CLASS; extends_used=false; end_line=-1; owner=NULL;} }; struct FunctionNode : public Node { bool _static; StringName name; Vector<StringName> arguments; Vector<Node*> default_values; BlockNode *body; FunctionNode() { type=TYPE_FUNCTION; _static=false; } }; struct BlockNode : public Node { ClassNode *parent_class; BlockNode *parent_block; Map<StringName,int> locals; List<Node*> statements; Vector<StringName> variables; Vector<int> variable_lines; //the following is useful for code completion List<BlockNode*> sub_blocks; int end_line; BlockNode() { type=TYPE_BLOCK; end_line=-1; parent_block=NULL; parent_class=NULL; } }; struct TypeNode : public Node { Variant::Type vtype; TypeNode() { type=TYPE_TYPE; } }; struct BuiltInFunctionNode : public Node { GDFunctions::Function function; BuiltInFunctionNode() { type=TYPE_BUILT_IN_FUNCTION; } }; struct IdentifierNode : public Node { StringName name; IdentifierNode() { type=TYPE_IDENTIFIER; } }; struct LocalVarNode : public Node { StringName name; Node *assign; LocalVarNode() { type=TYPE_LOCAL_VAR; assign=NULL;} }; struct ConstantNode : public Node { Variant value; ConstantNode() { type=TYPE_CONSTANT; } }; struct ArrayNode : public Node { Vector<Node*> elements; ArrayNode() { type=TYPE_ARRAY; } }; struct DictionaryNode : public Node { struct Pair { Node *key; Node *value; }; Vector<Pair> elements; DictionaryNode() { type=TYPE_DICTIONARY; } }; struct SelfNode : public Node { SelfNode() { type=TYPE_SELF; } }; struct OperatorNode : public Node { enum Operator { //call/constructor operator OP_CALL, OP_PARENT_CALL, OP_YIELD, OP_EXTENDS, //indexing operator OP_INDEX, OP_INDEX_NAMED, //unary operators OP_NEG, OP_NOT, OP_BIT_INVERT, OP_PREINC, OP_PREDEC, OP_INC, OP_DEC, //binary operators (in precedence order) OP_IN, OP_EQUAL, OP_NOT_EQUAL, OP_LESS, OP_LESS_EQUAL, OP_GREATER, OP_GREATER_EQUAL, OP_AND, OP_OR, OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_MOD, OP_SHIFT_LEFT, OP_SHIFT_RIGHT, OP_INIT_ASSIGN, OP_ASSIGN, OP_ASSIGN_ADD, OP_ASSIGN_SUB, OP_ASSIGN_MUL, OP_ASSIGN_DIV, OP_ASSIGN_MOD, OP_ASSIGN_SHIFT_LEFT, OP_ASSIGN_SHIFT_RIGHT, OP_ASSIGN_BIT_AND, OP_ASSIGN_BIT_OR, OP_ASSIGN_BIT_XOR, OP_BIT_AND, OP_BIT_OR, OP_BIT_XOR, }; Operator op; Vector<Node*> arguments; OperatorNode() { type=TYPE_OPERATOR; } }; struct ControlFlowNode : public Node { enum CFType { CF_IF, CF_FOR, CF_WHILE, CF_SWITCH, CF_BREAK, CF_CONTINUE, CF_RETURN }; CFType cf_type; Vector<Node*> arguments; BlockNode *body; BlockNode *body_else; ControlFlowNode *_else; //used for if ControlFlowNode() { type=TYPE_CONTROL_FLOW; cf_type=CF_IF; body=NULL; body_else=NULL;} }; struct AssertNode : public Node { Node* condition; AssertNode() { type=TYPE_ASSERT; } }; struct NewLineNode : public Node { NewLineNode() { type=TYPE_NEWLINE; } }; struct Expression { bool is_op; union { OperatorNode::Operator op; Node *node; }; }; /* struct OperatorNode : public Node { DataType return_cache; Operator op; Vector<Node*> arguments; virtual DataType get_datatype() const { return return_cache; } OperatorNode() { type=TYPE_OPERATOR; return_cache=TYPE_VOID; } }; struct VariableNode : public Node { DataType datatype_cache; StringName name; virtual DataType get_datatype() const { return datatype_cache; } VariableNode() { type=TYPE_VARIABLE; datatype_cache=TYPE_VOID; } }; struct ConstantNode : public Node { DataType datatype; Variant value; virtual DataType get_datatype() const { return datatype; } ConstantNode() { type=TYPE_CONSTANT; } }; struct BlockNode : public Node { Map<StringName,DataType> variables; List<Node*> statements; BlockNode() { type=TYPE_BLOCK; } }; struct ControlFlowNode : public Node { FlowOperation flow_op; Vector<Node*> statements; ControlFlowNode() { type=TYPE_CONTROL_FLOW; flow_op=FLOW_OP_IF;} }; struct MemberNode : public Node { DataType datatype; StringName name; Node* owner; virtual DataType get_datatype() const { return datatype; } MemberNode() { type=TYPE_MEMBER; } }; struct ProgramNode : public Node { struct Function { StringName name; FunctionNode*function; }; Map<StringName,DataType> builtin_variables; Map<StringName,DataType> preexisting_variables; Vector<Function> functions; BlockNode *body; ProgramNode() { type=TYPE_PROGRAM; } }; */ enum CompletionType { COMPLETION_NONE, COMPLETION_BUILT_IN_TYPE_CONSTANT, COMPLETION_FUNCTION, COMPLETION_IDENTIFIER, COMPLETION_PARENT_FUNCTION, COMPLETION_METHOD, COMPLETION_CALL_ARGUMENTS, COMPLETION_INDEX, COMPLETION_VIRTUAL_FUNC }; private: GDTokenizer *tokenizer; Node *head; Node *list; template<class T> T* alloc_node(); bool validating; bool for_completion; int parenthesis; bool error_set; String error; int error_line; int error_column; int pending_newline; List<int> tab_level; String base_path; String self_path; ClassNode *current_class; FunctionNode *current_function; BlockNode *current_block; bool _get_completable_identifier(CompletionType p_type,StringName& identifier); void _make_completable_call(int p_arg); CompletionType completion_type; StringName completion_cursor; bool completion_static; Variant::Type completion_built_in_constant; Node *completion_node; ClassNode *completion_class; FunctionNode *completion_function; BlockNode *completion_block; int completion_line; int completion_argument; bool completion_found; PropertyInfo current_export; void _set_error(const String& p_error, int p_line=-1, int p_column=-1); bool _recover_from_completion(); bool _parse_arguments(Node* p_parent, Vector<Node*>& p_args, bool p_static, bool p_can_codecomplete=false); bool _enter_indent_block(BlockNode *p_block=NULL); bool _parse_newline(); Node* _parse_expression(Node *p_parent,bool p_static,bool p_allow_assign=false); Node* _reduce_expression(Node *p_node,bool p_to_const=false); Node* _parse_and_reduce_expression(Node *p_parent,bool p_static,bool p_reduce_const=false,bool p_allow_assign=false); void _parse_block(BlockNode *p_block,bool p_static); void _parse_extends(ClassNode *p_class); void _parse_class(ClassNode *p_class); bool _end_statement(); Error _parse(const String& p_base_path); public: String get_error() const; int get_error_line() const; int get_error_column() const; Error parse(const String& p_code, const String& p_base_path="", bool p_just_validate=false,const String& p_self_path="",bool p_for_completion=false); Error parse_bytecode(const Vector<uint8_t> &p_bytecode,const String& p_base_path="",const String& p_self_path=""); const Node *get_parse_tree() const; //completion info CompletionType get_completion_type(); StringName get_completion_cursor(); int get_completion_line(); Variant::Type get_completion_built_in_constant(); Node *get_completion_node(); ClassNode *get_completion_class(); BlockNode *get_completion_block(); FunctionNode *get_completion_function(); int get_completion_argument_index(); void clear(); GDParser(); ~GDParser(); }; #endif // PARSER_H
dreamsxin/godot
modules/gdscript/gd_parser.h
C
mit
10,947
--- title: Telerik.Web.UI.ListViewItemSelectingEventArgs page_title: Client-side API Reference description: Client-side API Reference slug: Telerik.Web.UI.ListViewItemSelectingEventArgs --- # Telerik.Web.UI.ListViewItemSelectingEventArgs : Sys.CancelEventArgs ## Inheritance Hierarchy * Sys.CancelEventArgs * *[Telerik.Web.UI.ListViewItemSelectingEventArgs]({%slug Telerik.Web.UI.ListViewItemSelectingEventArgs%})* ## Methods ### get_itemIndex Returns the index of the item that is about to be selected. #### Parameters #### Returns `Number`
scstauf/ajax-docs
api/client/args/Telerik.Web.UI.ListViewItemSelectingEventArgs.md
Markdown
mit
551
module Fastlane module Actions class PromptAction < Action def self.run(params) if params[:boolean] return params[:ci_input] unless UI.interactive? return UI.confirm(params[:text]) end UI.message(params[:text]) return params[:ci_input] unless UI.interactive? if params[:multi_line_end_keyword] # Multi line end_tag = params[:multi_line_end_keyword] UI.important("Submit inputs using \"#{params[:multi_line_end_keyword]}\"") user_input = STDIN.gets(end_tag).chomp.gsub(end_tag, "").strip else # Standard one line input if params[:secure_text] user_input = STDIN.noecho(&:gets).chomp while (user_input || "").length == 0 else user_input = STDIN.gets.chomp.strip while (user_input || "").length == 0 end end return user_input end ##################################################### # @!group Documentation ##################################################### def self.description "Ask the user for a value or for confirmation" end def self.details [ "You can use `prompt` to ask the user for a value or to just let the user confirm the next step.", "When this is executed on a CI service, the passed `ci_input` value will be returned.", "This action also supports multi-line inputs using the `multi_line_end_keyword` option." ].join("\n") end def self.available_options [ FastlaneCore::ConfigItem.new(key: :text, description: "The text that will be displayed to the user", default_value: "Please enter some text: "), FastlaneCore::ConfigItem.new(key: :ci_input, description: "The default text that will be used when being executed on a CI service", default_value: ''), FastlaneCore::ConfigItem.new(key: :boolean, description: "Is that a boolean question (yes/no)? This will add (y/n) at the end", default_value: false, is_string: false), FastlaneCore::ConfigItem.new(key: :secure_text, description: "Is that a secure text (yes/no)?", default_value: false, is_string: false), FastlaneCore::ConfigItem.new(key: :multi_line_end_keyword, description: "Enable multi-line inputs by providing an end text (e.g. 'END') which will stop the user input", optional: true, is_string: true) ] end def self.output [] end def self.authors ["KrauseFx"] end def self.is_supported?(platform) true end def self.example_code [ 'changelog = prompt(text: "Changelog: ")', 'changelog = prompt( text: "Changelog: ", multi_line_end_keyword: "END" ) crashlytics(notes: changelog)' ] end def self.sample_return_value "User Content\nWithNewline" end def self.return_type :string end def self.category :misc end end end end
daveanderson/fastlane
fastlane/lib/fastlane/actions/prompt.rb
Ruby
mit
3,615
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A NamespaceExtent represents whether a namespace contains types and sub-namespaces from a /// particular module, assembly, or merged across all modules (source and metadata) in a /// particular compilation. /// </summary> internal struct NamespaceExtent : IEquatable<NamespaceExtent> { private readonly NamespaceKind _kind; private readonly object _symbolOrCompilation; /// <summary> /// Returns what kind of extent: Module, Assembly, or Compilation. /// </summary> public NamespaceKind Kind { get { return _kind; } } /// <summary> /// If the Kind is ExtendKind.Module, returns the module symbol that this namespace /// encompasses. Otherwise throws InvalidOperationException. /// </summary> public ModuleSymbol Module { get { if (_kind == NamespaceKind.Module) { return (ModuleSymbol)_symbolOrCompilation; } throw new InvalidOperationException(); } } /// <summary> /// If the Kind is ExtendKind.Assembly, returns the assembly symbol that this namespace /// encompasses. Otherwise throws InvalidOperationException. /// </summary> public AssemblySymbol Assembly { get { if (_kind == NamespaceKind.Assembly) { return (AssemblySymbol)_symbolOrCompilation; } throw new InvalidOperationException(); } } /// <summary> /// If the Kind is ExtendKind.Compilation, returns the compilation symbol that this /// namespace encompasses. Otherwise throws InvalidOperationException. /// </summary> public CSharpCompilation Compilation { get { if (_kind == NamespaceKind.Compilation) { return (CSharpCompilation)_symbolOrCompilation; } throw new InvalidOperationException(); } } public override string ToString() { return $"{_kind}: {_symbolOrCompilation}"; } /// <summary> /// Create a NamespaceExtent that represents a given ModuleSymbol. /// </summary> internal NamespaceExtent(ModuleSymbol module) { _kind = NamespaceKind.Module; _symbolOrCompilation = module; } /// <summary> /// Create a NamespaceExtent that represents a given AssemblySymbol. /// </summary> internal NamespaceExtent(AssemblySymbol assembly) { _kind = NamespaceKind.Assembly; _symbolOrCompilation = assembly; } /// <summary> /// Create a NamespaceExtent that represents a given Compilation. /// </summary> internal NamespaceExtent(CSharpCompilation compilation) { _kind = NamespaceKind.Compilation; _symbolOrCompilation = compilation; } public override bool Equals(object obj) { return obj is NamespaceExtent && Equals((NamespaceExtent)obj); } public bool Equals(NamespaceExtent other) { return object.Equals(_symbolOrCompilation, other._symbolOrCompilation); } public override int GetHashCode() { return (_symbolOrCompilation == null) ? 0 : _symbolOrCompilation.GetHashCode(); } } }
diryboy/roslyn
src/Compilers/CSharp/Portable/Symbols/NamespaceExtent.cs
C#
mit
4,128
--- title: Events page_title: Server-side Events | RadToolBar for ASP.NET AJAX Documentation description: Events slug: toolbar/server-side-programming/events tags: events published: True position: 0 --- # Events ## __RadToolBar__ supports a number of server-side events that let you respond to events with complex actions that can't be performed in client-side code. * [ButtonClick]({%slug toolbar/server-side-programming/buttonclick%}) occurs when a button is clicked. * [ButtonDataBound]({%slug toolbar/server-side-programming/buttondatabound%}) occurs for each button when it is being bound to a data value. * [ItemCreated]({%slug toolbar/server-side-programming/itemcreated%}) occurs when a new item is added to the Items collection. # See Also * [Events]({%slug toolbar/client-side-programming/events%}) * [Working With Items at the Server]({%slug toolbar/radtoolbar-items/working-with-items-at-the-server%})
erikruth/ajax-docs
controls/toolbar/server-side-programming/events.md
Markdown
mit
957
class Admin::MainMenuCell < ::Admin::MenuCell protected def build_list add :contents, :url => admin_pages_url add :settings, :url => edit_admin_current_site_url end end
dickeyxxx/girltalk
app/cells/admin/main_menu_cell.rb
Ruby
mit
186
{% extends "../../head.html" %} {% block page_title %} Create a password for your online account - GOV.UK {% endblock %} {% block content %} <main id="content" role="main"> <!-- beta banner block --> {% include "../../partials/beta-banner.html" %} <div class="big-space"></div> <!-- <div class="small-space"> <a href="signin" class="link-back" onclick="history.go(-1)">Back</a> </div> --> <div class="grid-row"> <div class="column-two-thirds"> <form action="post-confirm" method="get" class="form" id="password_reset" data-parsley-validate="" data-parsley-errors-messages-disabled> <h1 class="heading-large"> Tell us if you want the security code marked for someone’s attention </h1> <!-- input --> <div class="form-group"> <label class="form-label" for="fao"> Enter a name and, or department (optional) </label> <!-- <span class="form-hint"> <p>For example: Michelle Sopp, Account team</p> </span> --> <input type="text" class="form-control" id="fao"/> </div> <input type="submit" value="Continue" class="button" role="button"/> </form> </div> </div> </main> {% endblock %}
christinagyles-ea/water
app/v6/views/v25/ex/registration/fao.html
HTML
mit
1,263
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Describes a virtual machine scale set extension profile. * */ class VirtualMachineScaleSetExtensionProfile { /** * Create a VirtualMachineScaleSetExtensionProfile. * @member {array} [extensions] The virtual machine scale set child extension * resources. */ constructor() { } /** * Defines the metadata of VirtualMachineScaleSetExtensionProfile * * @returns {object} metadata of VirtualMachineScaleSetExtensionProfile * */ mapper() { return { required: false, serializedName: 'VirtualMachineScaleSetExtensionProfile', type: { name: 'Composite', className: 'VirtualMachineScaleSetExtensionProfile', modelProperties: { extensions: { required: false, serializedName: 'extensions', type: { name: 'Sequence', element: { required: false, serializedName: 'VirtualMachineScaleSetExtensionElementType', type: { name: 'Composite', className: 'VirtualMachineScaleSetExtension' } } } } } } }; } } module.exports = VirtualMachineScaleSetExtensionProfile;
lmazuel/azure-sdk-for-node
lib/services/computeManagement2/lib/models/virtualMachineScaleSetExtensionProfile.js
JavaScript
mit
1,647
/* * ========================================================= * ========================================================= * ColorPicker * ========================================================= * ========================================================= * */ .inlet_slider { opacity: 0.85; z-index: 10; width: 24%; display: block; border-radius: 3px; height: 14px; -webkit-box-shadow: inset 0px 0px 5px 0px rgba(4, 4, 4, 0.5); box-shadow: inset 0px 0px 5px 0px rgba(4, 4, 4, 0.5); background-color: #d6d6d6; background-image: -webkit-gradient(linear, left top, left bottom, from(#d6d6d6), to(#ebebeb)); background-image: -webkit-linear-gradient(top, #d6d6d6, #ebebeb); background-image: -moz-linear-gradient(top, #d6d6d6, #ebebeb); background-image: -o-linear-gradient(top, #d6d6d6, #ebebeb); background-image: -ms-linear-gradient(top, #d6d6d6, #ebebeb); background-image: linear-gradient(top, #d6d6d6, #ebebeb); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, StartColorStr='#d6d6d6', EndColorStr='#ebebeb'); } .inlet_slider:hover { opacity: 0.98; } .inlet_slider .range { width: 90%; margin-left: 5%; margin-top: 0px; } .inlet_slider input[type="range"] { -webkit-appearance: none; -moz-appearance: none; } @-moz-document url-prefix() { .inlet_slider input[type="range"] { position: absolute; } } .inlet_slider input::-moz-range-track { background: none; border: none; outline: none; } .inlet_slider input::-webkit-slider-thumb { cursor: col-resize; -webkit-appearance: none; -moz-apperance: none; width: 12px; height: 12px; margin-top: -13px; border-radius: 6px; border: 1px solid black; background-color: red; -webkit-box-shadow: 0px 0px 3px 0px rgba(4, 4, 4, 0.4); box-shadow: 0px 0px 3px 0px rgba(4, 4, 4, 0.4); background-color: #424242; background-image: -webkit-gradient(linear, left top, left bottom, from(#424242), to(#212121)); background-image: -webkit-linear-gradient(top, #424242, #212121); background-image: -moz-linear-gradient(top, #424242, #212121); background-image: -o-linear-gradient(top, #424242, #212121); background-image: -ms-linear-gradient(top, #424242, #212121); background-image: linear-gradient(top, #424242, #212121); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, StartColorStr='#424242', EndColorStr='#212121'); } /* * ========================================================= * ========================================================= * ColorPicker * ========================================================= * ========================================================= * */ .ColorPicker { /* border: 1px solid rgba(0,0,0,0.5); border-radius: 6px; background: #0d0d0d; background: -webkit-gradient(linear, left top, left bottom, from(#333), color-stop(0.1, #111), to(#000000)); box-shadow: 2px 2px 5px 2px rgba(0,0,0,0.35); color:#AAA; */ text-shadow: 1px 1px 1px #000; color: #050505; cursor: default; display: block; font-family: 'arial', helvetica, sans-serif; font-size: 20px; padding: 7px 8px 20px; position: absolute; top: 100px; left: 700px; width: 229px; z-index: 100; border-radius: 3px; -webkit-box-shadow: inset 0px 0px 5px 0px rgba(4, 4, 4, 0.5); box-shadow: inset 0px 0px 5px 0px rgba(4, 4, 4, 0.5); background-color: rgba(214, 214, 215, 0.85); /* background-image: -webkit-gradient(linear, left top, left bottom, from(rgb(214, 214, 214)), to(rgb(235, 235, 235))); background-image: -webkit-linear-gradient(top, rgb(214, 214, 214), rgb(235, 235, 235)); background-image: -moz-linear-gradient(top, rgb(214, 214, 214), rgb(235, 235, 235)); background-image: -o-linear-gradient(top, rgb(214, 214, 214), rgb(235, 235, 235)); background-image: -ms-linear-gradient(top, rgb(214, 214, 214), rgb(235, 235, 235)); background-image: linear-gradient(top, rgb(214, 214, 214), rgb(235, 235, 235)); filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#d6d6d6', EndColorStr='#ebebeb'); */ } .ColorPicker br { clear: both; margin: 0; padding: 0; } .ColorPicker input.hexInput:hover, .ColorPicker input.hexInput:focus { color: #aa1212; } .ColorPicker input.hexInput { -webkit-transition-property: color; -webkit-transition-duration: .5s; background: none; border: 0; margin: 0; font-family: courier,monospace; font-size: 20px; position: relative; top: -2px; float: left; color: #050505; cursor: text; } .ColorPicker div.hexBox { border: 1px solid rgba(255, 255, 255, 0.5); border-radius: 2px; background: #FFF; float: left; font-size: 1px; height: 20px; margin: 0 5px 0 2px; width: 20px; cursor: pointer; } .ColorPicker div.hexBox div { width: inherit; height: inherit; } .ColorPicker div.hexClose { display: none; /* -webkit-transition-property: color, text-shadow; -webkit-transition-duration: .5s; position: relative; top: -1px; left: -1px; color:#FFF; cursor:pointer; float:right; padding: 0 5px; margin:0 4px 3px; user-select:none; -webkit-user-select: none; */ } .ColorPicker div.hexClose:hover { text-shadow: 0 0 20px #fff; color: #FF1100; }
bright-sparks/kodeWeave
libraries/codemirror/inlet.css
CSS
mit
5,202
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_DIRECT3D_9_ #include "CD3D9NormalMapRenderer.h" #include "IVideoDriver.h" #include "IMaterialRendererServices.h" #include "os.h" #include "SLight.h" namespace irr { namespace video { // 1.1 Shaders with two lights and vertex based attenuation // Irrlicht Engine D3D9 render path normal map vertex shader const char D3D9_NORMAL_MAP_VSH[] = ";Irrlicht Engine 0.8 D3D9 render path normal map vertex shader\n"\ "; c0-3: Transposed world matrix \n"\ "; c8-11: Transposed worldViewProj matrix (Projection * View * World) \n"\ "; c12: Light01 position \n"\ "; c13: x,y,z: Light01 color; .w: 1/LightRadius² \n"\ "; c14: Light02 position \n"\ "; c15: x,y,z: Light02 color; .w: 1/LightRadius² \n"\ "vs.1.1\n"\ "dcl_position v0 ; position \n"\ "dcl_normal v1 ; normal \n"\ "dcl_color v2 ; color \n"\ "dcl_texcoord0 v3 ; texture coord \n"\ "dcl_texcoord1 v4 ; tangent \n"\ "dcl_texcoord2 v5 ; binormal \n"\ "\n"\ "def c95, 0.5, 0.5, 0.5, 0.5 ; used for moving light vector to ps \n"\ "\n"\ "m4x4 oPos, v0, c8 ; transform position to clip space with worldViewProj matrix\n"\ "\n"\ "m3x3 r5, v4, c0 ; transform tangent U\n"\ "m3x3 r7, v1, c0 ; transform normal W\n"\ "m3x3 r6, v5, c0 ; transform binormal V\n"\ "\n"\ "m4x4 r4, v0, c0 ; vertex into world position\n"\ "add r2, c12, -r4 ; vtxpos - lightpos1\n"\ "add r3, c14, -r4 ; vtxpos - lightpos2\n"\ "\n"\ "dp3 r8.x, r5, r2 ; transform the light vector 1 with U, V, W\n"\ "dp3 r8.y, r6, r2 \n"\ "dp3 r8.z, r7, r2 \n"\ "dp3 r9.x, r5, r3 ; transform the light vector 2 with U, V, W\n"\ "dp3 r9.y, r6, r3 \n"\ "dp3 r9.z, r7, r3 \n"\ "\n"\ "dp3 r8.w, r8, r8 ; normalize light vector 1 (r8)\n"\ "rsq r8.w, r8.w \n"\ "mul r8, r8, r8.w \n"\ "dp3 r9.w, r9, r9 ; normalize light vector 2 (r9)\n"\ "rsq r9.w, r9.w \n"\ "mul r9, r9, r9.w \n"\ "\n"\ "mad oT2.xyz, r8.xyz, c95, c95 ; move light vector 1 from -1..1 into 0..1 \n"\ "mad oT3.xyz, r9.xyz, c95, c95 ; move light vector 2 from -1..1 into 0..1 \n"\ "\n"\ " ; calculate attenuation of light 1 \n"\ "dp3 r2.x, r2.xyz, r2.xyz ; r2.x = r2.x² + r2.y² + r2.z² \n"\ "mul r2.x, r2.x, c13.w ; r2.x * attenutation \n"\ "rsq r2, r2.x ; r2.xyzw = 1/sqrt(r2.x * attenutation)\n"\ "mul oD0, r2, c13 ; resulting light color = lightcolor * attenuation \n"\ "\n"\ " ; calculate attenuation of light 2 \n"\ "dp3 r3.x, r3.xyz, r3.xyz ; r3.x = r3.x² + r3.y² + r3.z² \n"\ "mul r3.x, r3.x, c15.w ; r2.x * attenutation \n"\ "rsq r3, r3.x ; r2.xyzw = 1/sqrt(r2.x * attenutation)\n"\ "mul oD1, r3, c15 ; resulting light color = lightcolor * attenuation \n"\ "\n"\ "mov oT0.xy, v3.xy ; move out texture coordinates 1\n"\ "mov oT1.xy, v3.xy ; move out texture coordinates 2\n"\ "mov oD0.a, v2.a ; move out original alpha value \n"\ "\n"; // Irrlicht Engine D3D9 render path normal map pixel shader const char D3D9_NORMAL_MAP_PSH_1_1[] = ";Irrlicht Engine 0.8 D3D9 render path normal map pixel shader\n"\ ";Input: \n"\ ";t0: color map texture coord \n"\ ";t1: normal map texture coords \n"\ ";t2: light 1 vector in tangent space \n"\ ";v0: light 1 color \n"\ ";t3: light 2 vector in tangent space \n"\ ";v1: light 2 color \n"\ ";v0.a: vertex alpha value \n"\ "ps.1.1 \n"\ "tex t0 ; sample color map \n"\ "tex t1 ; sample normal map\n"\ "texcoord t2 ; fetch light vector 1\n"\ "texcoord t3 ; fetch light vector 2\n"\ "\n"\ "dp3_sat r0, t1_bx2, t2_bx2 ; normal dot light 1 (_bx2 because moved into 0..1)\n"\ "mul r0, r0, v0 ; luminance1 * light color 1 \n"\ "\n"\ "dp3_sat r1, t1_bx2, t3_bx2 ; normal dot light 2 (_bx2 because moved into 0..1)\n"\ "mad r0, r1, v1, r0 ; (luminance2 * light color 2) + luminance 1 \n"\ "\n"\ "mul r0.xyz, t0, r0 ; total luminance * base color\n"\ "+mov r0.a, v0.a ; write interpolated vertex alpha value \n"\ "\n"\ ""; // Higher-quality normal map pixel shader (requires PS 2.0) // uses per-pixel normalization for improved accuracy const char D3D9_NORMAL_MAP_PSH_2_0[] = ";Irrlicht Engine 0.8 D3D9 render path normal map pixel shader\n"\ ";Input: \n"\ ";t0: color map texture coord \n"\ ";t1: normal map texture coords \n"\ ";t2: light 1 vector in tangent space \n"\ ";v0: light 1 color \n"\ ";t3: light 2 vector in tangent space \n"\ ";v1: light 2 color \n"\ ";v0.a: vertex alpha value \n"\ "ps_2_0 \n"\ "def c0, 0, 0, 0, 0\n"\ "def c1, 1.0, 1.0, 1.0, 1.0\n"\ "def c2, 2.0, 2.0, 2.0, 2.0\n"\ "def c3, -.5, -.5, -.5, -.5\n"\ "dcl t0\n"\ "dcl t1\n"\ "dcl t2\n"\ "dcl t3\n"\ "dcl v1\n"\ "dcl v0\n"\ "dcl_2d s0\n"\ "dcl_2d s1\n"\ "texld r0, t0, s0 ; sample color map into r0 \n"\ "texld r4, t0, s1 ; sample normal map into r4\n"\ "add r4, r4, c3 ; bias the normal vector\n"\ "add r5, t2, c3 ; bias the light 1 vector into r5\n"\ "add r6, t3, c3 ; bias the light 2 vector into r6\n"\ "nrm r1, r4 ; normalize the normal vector into r1\n"\ "nrm r2, r5 ; normalize the light1 vector into r2\n"\ "nrm r3, r6 ; normalize the light2 vector into r3\n"\ "dp3 r2, r2, r1 ; let r2 = normal DOT light 1 vector\n"\ "max r2, r2, c0 ; clamp result to positive numbers\n"\ "mul r2, r2, v0 ; let r2 = luminance1 * light color 1 \n"\ "dp3 r3, r3, r1 ; let r3 = normal DOT light 2 vector\n"\ "max r3, r3, c0 ; clamp result to positive numbers\n"\ "mad r2, r3, v1, r2 ; let r2 = (luminance2 * light color 2) + (luminance2 * light color 1) \n"\ "mul r2, r2, r0 ; let r2 = total luminance * base color\n"\ "mov r2.w, v0.w ; write interpolated vertex alpha value \n"\ "mov oC0, r2 ; copy r2 to the output register \n"\ "\n"\ ""; CD3D9NormalMapRenderer::CD3D9NormalMapRenderer( IDirect3DDevice9* d3ddev, video::IVideoDriver* driver, s32& outMaterialTypeNr, IMaterialRenderer* baseMaterial) : CD3D9ShaderMaterialRenderer(d3ddev, driver, 0, baseMaterial) { #ifdef _DEBUG setDebugName("CD3D9NormalMapRenderer"); #endif // set this as callback. We could have done this in // the initialization list, but some compilers don't like it. CallBack = this; // basically, this thing simply compiles the hardcoded shaders // if the hardware is able to do them, otherwise it maps to the // base material if (!driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) || !driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1)) { // this hardware is not able to do shaders. Fall back to // base material. outMaterialTypeNr = driver->addMaterialRenderer(this); return; } // check if already compiled normal map shaders are there. video::IMaterialRenderer* renderer = driver->getMaterialRenderer(EMT_NORMAL_MAP_SOLID); if (renderer) { // use the already compiled shaders video::CD3D9NormalMapRenderer* nmr = (video::CD3D9NormalMapRenderer*)renderer; VertexShader = nmr->VertexShader; if (VertexShader) VertexShader->AddRef(); PixelShader = nmr->PixelShader; if (PixelShader) PixelShader->AddRef(); outMaterialTypeNr = driver->addMaterialRenderer(this); } else { // compile shaders on our own if (driver->queryFeature(video::EVDF_PIXEL_SHADER_2_0)) { init(outMaterialTypeNr, D3D9_NORMAL_MAP_VSH, D3D9_NORMAL_MAP_PSH_2_0); } else { init(outMaterialTypeNr, D3D9_NORMAL_MAP_VSH, D3D9_NORMAL_MAP_PSH_1_1); } } // something failed, use base material if (-1==outMaterialTypeNr) driver->addMaterialRenderer(this); } CD3D9NormalMapRenderer::~CD3D9NormalMapRenderer() { if (CallBack == this) CallBack = 0; } bool CD3D9NormalMapRenderer::OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) { if (vtxtype != video::EVT_TANGENTS) { os::Printer::log("Error: Normal map renderer only supports vertices of type EVT_TANGENTS", ELL_ERROR); return false; } return CD3D9ShaderMaterialRenderer::OnRender(service, vtxtype); } //! Returns the render capability of the material. s32 CD3D9NormalMapRenderer::getRenderCapability() const { if (Driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) && Driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1)) return 0; return 1; } //! Called by the engine when the vertex and/or pixel shader constants //! for an material renderer should be set. void CD3D9NormalMapRenderer::OnSetConstants(IMaterialRendererServices* services, s32 userData) { video::IVideoDriver* driver = services->getVideoDriver(); // set transposed world matrix services->setVertexShaderConstant(driver->getTransform(video::ETS_WORLD).getTransposed().pointer(), 0, 4); // set transposed worldViewProj matrix core::matrix4 worldViewProj(driver->getTransform(video::ETS_PROJECTION)); worldViewProj *= driver->getTransform(video::ETS_VIEW); worldViewProj *= driver->getTransform(video::ETS_WORLD); services->setVertexShaderConstant(worldViewProj.getTransposed().pointer(), 8, 4); // here we've got to fetch the fixed function lights from the // driver and set them as constants u32 cnt = driver->getDynamicLightCount(); for (u32 i=0; i<2; ++i) { SLight light; if (i<cnt) light = driver->getDynamicLight(i); else { light.DiffuseColor.set(0,0,0); // make light dark light.Radius = 1.0f; } light.DiffuseColor.a = 1.0f/(light.Radius*light.Radius); // set attenuation services->setVertexShaderConstant(reinterpret_cast<const f32*>(&light.Position), 12+(i*2), 1); services->setVertexShaderConstant(reinterpret_cast<const f32*>(&light.DiffuseColor), 13+(i*2), 1); } // this is not really necessary in d3d9 (used a def instruction), but to be sure: f32 c95[] = {0.5f, 0.5f, 0.5f, 0.5f}; services->setVertexShaderConstant(c95, 95, 1); } } // end namespace video } // end namespace irr #endif // _IRR_COMPILE_WITH_DIRECT3D_9_
usernameHed/Worms
library/Irrlicht/source/Irrlicht/CD3D9NormalMapRenderer.cpp
C++
mit
10,890
require File.dirname(__FILE__) + '/../../spec_helper' describe "Process.wait" do before :all do Process.waitall end it "raises a Errno::ECHILD if there are no child processes" do lambda { Process.wait }.should raise_error(Errno::ECHILD) end platform_is_not :windows do it "returns its childs pid" do pid = Process.fork { Process.exit! } Process.wait.should == pid end it "sets $? to a Process::Status" do pid = Process.fork { Process.exit! } Process.wait $?.class.should == Process::Status $?.pid.should == pid end it "waits for any child process if no pid is given" do pid = Process.fork { Process.exit! } Process.wait.should == pid lambda { Process.kill(0, pid) }.should raise_error(Errno::ESRCH) end it "waits for a specific child if a pid is given" do pid1 = Process.fork { Process.exit! } pid2 = Process.fork { Process.exit! } Process.wait(pid2).should == pid2 Process.wait(pid1).should == pid1 lambda { Process.kill(0, pid1) }.should raise_error(Errno::ESRCH) lambda { Process.kill(0, pid2) }.should raise_error(Errno::ESRCH) end # This spec is probably system-dependent. it "waits for a child whose process group ID is that of the calling process" do read, write = IO.pipe pid1 = Process.fork { read.close Process.setpgid(0, 0) write << 1 write.close Process.exit! } Process.setpgid(0, 0) ppid = Process.pid pid2 = Process.fork { read.close Process.setpgid(0, ppid); write << 2 write.close Process.exit! } write.close read.read(1) read.read(1) # to give children a chance to set their process groups read.close Process.wait(0).should == pid2 Process.wait.should == pid1 end # This spec is probably system-dependent. it "doesn't block if no child is available when WNOHANG is used" do pid = Process.fork { 10.times { sleep(1) }; Process.exit! } Process.wait(pid, Process::WNOHANG).should == nil Process.kill("TERM", pid) Process.wait.should == pid end it "always accepts flags=0" do pid = Process.fork { Process.exit! } Process.wait(-1, 0).should == pid lambda { Process.kill(0, pid) }.should raise_error(Errno::ESRCH) end end end
luccastera/rubyspec
core/process/wait_spec.rb
Ruby
mit
2,421
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 1.2.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Test\TestCase\Routing; use Cake\Controller\Controller; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Network\Request; use Cake\Network\Response; use Cake\Network\Session; use Cake\Routing\Dispatcher; use Cake\Routing\Filter\ControllerFactoryFilter; use Cake\TestSuite\TestCase; /** * DispatcherTest class */ class DispatcherTest extends TestCase { /** * setUp method * * @return void */ public function setUp() { parent::setUp(); $_GET = []; Configure::write('App.base', false); Configure::write('App.baseUrl', false); Configure::write('App.dir', 'app'); Configure::write('App.webroot', 'webroot'); Configure::write('App.namespace', 'TestApp'); $this->dispatcher = new Dispatcher(); $this->dispatcher->addFilter(new ControllerFactoryFilter()); } /** * tearDown method * * @return void */ public function tearDown() { parent::tearDown(); Plugin::unload(); } /** * testMissingController method * * @expectedException \Cake\Routing\Exception\MissingControllerException * @expectedExceptionMessage Controller class SomeController could not be found. * @return void */ public function testMissingController() { $request = new Request([ 'url' => 'some_controller/home', 'params' => [ 'controller' => 'SomeController', 'action' => 'home', ] ]); $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); $this->dispatcher->dispatch($request, $response, ['return' => 1]); } /** * testMissingControllerInterface method * * @expectedException \Cake\Routing\Exception\MissingControllerException * @expectedExceptionMessage Controller class Interface could not be found. * @return void */ public function testMissingControllerInterface() { $request = new Request([ 'url' => 'interface/index', 'params' => [ 'controller' => 'Interface', 'action' => 'index', ] ]); $url = new Request('dispatcher_test_interface/index'); $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); $this->dispatcher->dispatch($request, $response, ['return' => 1]); } /** * testMissingControllerInterface method * * @expectedException \Cake\Routing\Exception\MissingControllerException * @expectedExceptionMessage Controller class Abstract could not be found. * @return void */ public function testMissingControllerAbstract() { $request = new Request([ 'url' => 'abstract/index', 'params' => [ 'controller' => 'Abstract', 'action' => 'index', ] ]); $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); $this->dispatcher->dispatch($request, $response, ['return' => 1]); } /** * Test that lowercase controller names result in missing controller errors. * * In case-insensitive file systems, lowercase controller names will kind of work. * This causes annoying deployment issues for lots of folks. * * @expectedException \Cake\Routing\Exception\MissingControllerException * @expectedExceptionMessage Controller class somepages could not be found. * @return void */ public function testMissingControllerLowercase() { $request = new Request([ 'url' => 'pages/home', 'params' => [ 'controller' => 'somepages', 'action' => 'display', 'pass' => ['home'], ] ]); $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); $this->dispatcher->dispatch($request, $response, ['return' => 1]); } /** * testDispatch method * * @return void */ public function testDispatchBasic() { $url = new Request([ 'url' => 'pages/home', 'params' => [ 'controller' => 'Pages', 'action' => 'display', 'pass' => ['extract'], ] ]); $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); $response->expects($this->once()) ->method('send'); $result = $this->dispatcher->dispatch($url, $response); $this->assertNull($result); } /** * Test that Dispatcher handles actions that return response objects. * * @return void */ public function testDispatchActionReturnsResponse() { $request = new Request([ 'url' => 'some_pages/responseGenerator', 'params' => [ 'controller' => 'SomePages', 'action' => 'responseGenerator', 'pass' => [] ] ]); $response = $this->getMockBuilder('Cake\Network\Response') ->setMethods(['_sendHeader']) ->getMock(); ob_start(); $this->dispatcher->dispatch($request, $response); $result = ob_get_clean(); $this->assertEquals('new response', $result); } /** * test forbidden controller names. * * @expectedException \Cake\Routing\Exception\MissingControllerException * @expectedExceptionMessage Controller class TestPlugin.Tests could not be found. * @return void */ public function testDispatchBadPluginName() { Plugin::load('TestPlugin'); $request = new Request([ 'url' => 'TestPlugin.Tests/index', 'params' => [ 'plugin' => '', 'controller' => 'TestPlugin.Tests', 'action' => 'index', 'pass' => [], 'return' => 1 ] ]); $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); $this->dispatcher->dispatch($request, $response); } /** * test forbidden controller names. * * @expectedException \Cake\Routing\Exception\MissingControllerException * @expectedExceptionMessage Controller class TestApp\Controller\PostsController could not be found. * @return void */ public function testDispatchBadName() { $request = new Request([ 'url' => 'TestApp%5CController%5CPostsController/index', 'params' => [ 'plugin' => '', 'controller' => 'TestApp\Controller\PostsController', 'action' => 'index', 'pass' => [], 'return' => 1 ] ]); $response = $this->getMockBuilder('Cake\Network\Response')->getMock(); $this->dispatcher->dispatch($request, $response); } /** * Test dispatcher filters being called. * * @return void */ public function testDispatcherFilter() { $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') ->setMethods(['beforeDispatch', 'afterDispatch']) ->getMock(); $filter->expects($this->at(0)) ->method('beforeDispatch'); $filter->expects($this->at(1)) ->method('afterDispatch'); $this->dispatcher->addFilter($filter); $request = new Request([ 'url' => '/', 'params' => [ 'controller' => 'Pages', 'action' => 'display', 'home', 'pass' => [] ] ]); $response = $this->getMockBuilder('Cake\Network\Response') ->setMethods(['send']) ->getMock(); $this->dispatcher->dispatch($request, $response); } /** * Test dispatcher filters being called and changing the response. * * @return void */ public function testBeforeDispatchAbortDispatch() { $response = $this->getMockBuilder('Cake\Network\Response') ->setMethods(['send']) ->getMock(); $response->expects($this->once()) ->method('send'); $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') ->setMethods(['beforeDispatch', 'afterDispatch']) ->getMock(); $filter->expects($this->once()) ->method('beforeDispatch') ->will($this->returnValue($response)); $filter->expects($this->never()) ->method('afterDispatch'); $request = new Request([ 'url' => '/', 'params' => [ 'controller' => 'Pages', 'action' => 'display', 'home', 'pass' => [] ] ]); $res = new Response(); $this->dispatcher->addFilter($filter); $this->dispatcher->dispatch($request, $res); } /** * Test dispatcher filters being called and changing the response. * * @return void */ public function testAfterDispatchReplaceResponse() { $response = $this->getMockBuilder('Cake\Network\Response') ->setMethods(['_sendHeader', 'send']) ->getMock(); $response->expects($this->once()) ->method('send'); $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter') ->setMethods(['beforeDispatch', 'afterDispatch']) ->getMock(); $filter->expects($this->once()) ->method('afterDispatch') ->will($this->returnValue($response)); $request = new Request([ 'url' => '/posts', 'params' => [ 'plugin' => null, 'controller' => 'Posts', 'action' => 'index', 'pass' => [], ], 'session' => new Session ]); $this->dispatcher->addFilter($filter); $this->dispatcher->dispatch($request, $response); } }
HavokInspiration/cakephp
tests/TestCase/Routing/DispatcherTest.php
PHP
mit
10,659
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.StreamAnalytics.Models { /// <summary> /// Defines values for AuthenticationMode. /// </summary> public static class AuthenticationMode { public const string Msi = "Msi"; public const string UserToken = "UserToken"; public const string ConnectionString = "ConnectionString"; } }
ayeletshpigelman/azure-sdk-for-net
sdk/streamanalytics/Microsoft.Azure.Management.StreamAnalytics/src/Generated/Models/AuthenticationMode.cs
C#
mit
718
--- layout: categories_list cat_name: Writing --- {% for post in site.categories.writing %} {% include catandtag.html %} {% endfor %}
airrayagroupwebdesign/sciblog
category/writing/index.html
HTML
mit
139
/*************************************************************************/ /* register_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "register_types.h" #include "core/engine.h" #include "csharp_script.h" CSharpLanguage *script_language_cs = NULL; ResourceFormatLoaderCSharpScript *resource_loader_cs = NULL; ResourceFormatSaverCSharpScript *resource_saver_cs = NULL; _GodotSharp *_godotsharp = NULL; void register_mono_types() { ClassDB::register_class<CSharpScript>(); _godotsharp = memnew(_GodotSharp); ClassDB::register_class<_GodotSharp>(); Engine::get_singleton()->add_singleton(Engine::Singleton("GodotSharp", _GodotSharp::get_singleton())); script_language_cs = memnew(CSharpLanguage); script_language_cs->set_language_index(ScriptServer::get_language_count()); ScriptServer::register_language(script_language_cs); resource_loader_cs = memnew(ResourceFormatLoaderCSharpScript); ResourceLoader::add_resource_format_loader(resource_loader_cs); resource_saver_cs = memnew(ResourceFormatSaverCSharpScript); ResourceSaver::add_resource_format_saver(resource_saver_cs); } void unregister_mono_types() { ScriptServer::unregister_language(script_language_cs); if (script_language_cs) memdelete(script_language_cs); if (resource_loader_cs) memdelete(resource_loader_cs); if (resource_saver_cs) memdelete(resource_saver_cs); if (_godotsharp) memdelete(_godotsharp); }
mcanders/godot
modules/mono/register_types.cpp
C++
mit
3,482
<?php /** * PHP-DI * * @link http://php-di.org/ * @copyright Matthieu Napoli (http://mnapoli.fr/) * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file) */ namespace DI; use DI\Definition\EntryReference; use DI\Definition\Helper\ArrayDefinitionExtensionHelper; use DI\Definition\Helper\FactoryDefinitionHelper; use DI\Definition\Helper\ObjectDefinitionHelper; use DI\Definition\Helper\EnvironmentVariableDefinitionHelper; use DI\Definition\Helper\ValueDefinitionHelper; use DI\Definition\Helper\StringDefinitionHelper; if (! function_exists('DI\value')) { /** * Helper for defining an object. * * @param mixed $value * * @return ValueDefinitionHelper */ function value($value) { return new ValueDefinitionHelper($value); } } if (! function_exists('DI\object')) { /** * Helper for defining an object. * * @param string|null $className Class name of the object. * If null, the name of the entry (in the container) will be used as class name. * * @return ObjectDefinitionHelper */ function object($className = null) { return new ObjectDefinitionHelper($className); } } if (! function_exists('DI\factory')) { /** * Helper for defining a container entry using a factory function/callable. * * @param callable $factory The factory is a callable that takes the container as parameter * and returns the value to register in the container. * * @return FactoryDefinitionHelper */ function factory($factory) { return new FactoryDefinitionHelper($factory); } } if (! function_exists('DI\decorate')) { /** * Decorate the previous definition using a callable. * * Example: * * 'foo' => decorate(function ($foo, $container) { * return new CachedFoo($foo, $container->get('cache')); * }) * * @param callable $callable The callable takes the decorated object as first parameter and * the container as second. * * @return FactoryDefinitionHelper */ function decorate($callable) { return new FactoryDefinitionHelper($callable, true); } } if (! function_exists('DI\get')) { /** * Helper for referencing another container entry in an object definition. * * @param string $entryName * * @return EntryReference */ function get($entryName) { return new EntryReference($entryName); } } if (! function_exists('DI\link')) { /** * Helper for referencing another container entry in an object definition. * * @deprecated \DI\link() has been replaced by \DI\get() * * @param string $entryName * * @return EntryReference */ function link($entryName) { return new EntryReference($entryName); } } if (! function_exists('DI\env')) { /** * Helper for referencing environment variables. * * @param string $variableName The name of the environment variable. * @param mixed $defaultValue The default value to be used if the environment variable is not defined. * * @return EnvironmentVariableDefinitionHelper */ function env($variableName, $defaultValue = null) { // Only mark as optional if the default value was *explicitly* provided. $isOptional = 2 === func_num_args(); return new EnvironmentVariableDefinitionHelper($variableName, $isOptional, $defaultValue); } } if (! function_exists('DI\add')) { /** * Helper for extending another definition. * * Example: * * 'log.backends' => DI\add(DI\get('My\Custom\LogBackend')) * * or: * * 'log.backends' => DI\add([ * DI\get('My\Custom\LogBackend') * ]) * * @param mixed|array $values A value or an array of values to add to the array. * * @return ArrayDefinitionExtensionHelper * * @since 5.0 */ function add($values) { if (! is_array($values)) { $values = [$values]; } return new ArrayDefinitionExtensionHelper($values); } } if (! function_exists('DI\string')) { /** * Helper for concatenating strings. * * Example: * * 'log.filename' => DI\string('{app.path}/app.log') * * @param string $expression A string expression. Use the `{}` placeholders to reference other container entries. * * @return StringDefinitionHelper * * @since 5.0 */ function string($expression) { return new StringDefinitionHelper((string) $expression); } }
IftekherSunny/Alien
vendor/php-di/php-di/src/DI/functions.php
PHP
mit
4,802
#ifndef __LINUX_JIFFIES_WRAPPER_H #define __LINUX_JIFFIES_WRAPPER_H 1 #include_next <linux/jiffies.h> #include <linux/version.h> /* Same as above, but does so with platform independent 64bit types. * These must be used when utilizing jiffies_64 (i.e. return value of * get_jiffies_64() */ #ifndef time_after64 #define time_after64(a, b) \ (typecheck(__u64, a) && \ typecheck(__u64, b) && \ ((__s64)(b) - (__s64)(a) < 0)) #endif #ifndef time_before64 #define time_before64(a, b) time_after64(b, a) #endif #ifndef time_after_eq64 #define time_after_eq64(a, b) \ (typecheck(__u64, a) && \ typecheck(__u64, b) && \ ((__s64)(a) - (__s64)(b) >= 0)) #endif #ifndef time_before_eq64 #define time_before_eq64(a, b) time_after_eq64(b, a) #endif #endif
kspviswa/dpi-enabled-ovs
ovs/datapath/linux/compat/include/linux/jiffies.h
C
mit
774
/* * Copyright 2012-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.metrics.export; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Test; import org.mockito.Mockito; import org.springframework.boot.actuate.metrics.reader.MetricReader; import org.springframework.boot.actuate.metrics.writer.GaugeWriter; import org.springframework.boot.actuate.metrics.writer.MetricWriter; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Tests for {@link MetricExporters}. * * @author Dave Syer */ public class MetricExportersTests { private MetricExporters exporters; private MetricExportProperties export = new MetricExportProperties(); private Map<String, GaugeWriter> writers = new LinkedHashMap<String, GaugeWriter>(); private MetricReader reader = Mockito.mock(MetricReader.class); private MetricWriter writer = Mockito.mock(MetricWriter.class); @Test public void emptyWriters() { this.exporters = new MetricExporters(this.export); this.exporters.setReader(this.reader); this.exporters.setWriters(this.writers); this.exporters.configureTasks(new ScheduledTaskRegistrar()); assertNotNull(this.exporters.getExporters()); assertEquals(0, this.exporters.getExporters().size()); } @Test public void oneWriter() { this.export.setUpDefaults(); this.writers.put("foo", this.writer); this.exporters = new MetricExporters(this.export); this.exporters.setReader(this.reader); this.exporters.setWriters(this.writers); this.exporters.configureTasks(new ScheduledTaskRegistrar()); assertNotNull(this.exporters.getExporters()); assertEquals(1, this.exporters.getExporters().size()); } @Test public void exporter() { this.export.setUpDefaults(); this.exporters = new MetricExporters(this.export); this.exporters.setExporters(Collections.<String, Exporter>singletonMap("foo", new MetricCopyExporter(this.reader, this.writer))); this.exporters.configureTasks(new ScheduledTaskRegistrar()); assertNotNull(this.exporters.getExporters()); assertEquals(1, this.exporters.getExporters().size()); } }
rokn/Count_Words_2015
testing/spring-boot-master/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/metrics/export/MetricExportersTests.java
Java
mit
2,807
// Copyright (c) 2014 The ShadowCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_STEALTH_H #define BITCOIN_STEALTH_H #include "util.h" #include "serialize.h" #include <stdlib.h> #include <stdio.h> #include <vector> #include <inttypes.h> typedef std::vector<uint8_t> data_chunk; const size_t ec_secret_size = 32; const size_t ec_compressed_size = 33; const size_t ec_uncompressed_size = 65; typedef struct ec_secret { uint8_t e[ec_secret_size]; } ec_secret; typedef data_chunk ec_point; typedef uint32_t stealth_bitfield; struct stealth_prefix { uint8_t number_bits; stealth_bitfield bitfield; }; template <typename T, typename Iterator> T from_big_endian(Iterator in) { //VERIFY_UNSIGNED(T); T out = 0; size_t i = sizeof(T); while (0 < i) out |= static_cast<T>(*in++) << (8 * --i); return out; } template <typename T, typename Iterator> T from_little_endian(Iterator in) { //VERIFY_UNSIGNED(T); T out = 0; size_t i = 0; while (i < sizeof(T)) out |= static_cast<T>(*in++) << (8 * i++); return out; } class CStealthAddress { public: CStealthAddress() { options = 0; } uint8_t options; ec_point scan_pubkey; ec_point spend_pubkey; //std::vector<ec_point> spend_pubkeys; size_t number_signatures; stealth_prefix prefix; mutable std::string label; data_chunk scan_secret; data_chunk spend_secret; bool SetEncoded(const std::string& encodedAddress); std::string Encoded() const; bool operator <(const CStealthAddress& y) const { return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], ec_compressed_size) < 0; } bool operator == (const CStealthAddress& y) const { return (scan_pubkey == y.scan_pubkey) && (spend_pubkey == y.spend_pubkey) && (scan_secret == y.scan_secret) && (spend_secret == y.spend_secret); } IMPLEMENT_SERIALIZE ( READWRITE(this->options); READWRITE(this->scan_pubkey); READWRITE(this->spend_pubkey); READWRITE(this->label); READWRITE(this->scan_secret); READWRITE(this->spend_secret); ); }; void AppendChecksum(data_chunk& data); bool VerifyChecksum(const data_chunk& data); int GenerateRandomSecret(ec_secret& out); int SecretToPublicKey(const ec_secret& secret, ec_point& out); int StealthSecret(ec_secret& secret, ec_point& pubkey, const ec_point& pkSpend, ec_secret& sharedSOut, ec_point& pkOut); int StealthSecretSpend(ec_secret& scanSecret, ec_point& ephemPubkey, ec_secret& spendSecret, ec_secret& secretOut); int StealthSharedToSecretSpend(ec_secret& sharedS, ec_secret& spendSecret, ec_secret& secretOut); bool IsStealthAddress(const std::string& encodedAddress); #endif // BITCOIN_STEALTH_H
cqtenq/feathercoin_core
src/stealth.h
C
mit
2,989
// Copyright 2014 the V8 project authors. All rights reserved. // AUTO-GENERATED BY tools/generate-runtime-tests.py, DO NOT MODIFY // Flags: --allow-natives-syntax --harmony --harmony-proxies var _source = "foo"; var arg1 = false; %CompileString(_source, arg1);
kingland/go-v8
v8-3.28/test/mjsunit/runtime-gen/compilestring.js
JavaScript
mit
262
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['en-ki'] = [ 'en-KI', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'AUD', '$', 'Australian Dollar', {'AUD': ['$'], 'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural, [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
mgechev/angular
packages/common/locales/global/en-KI.js
JavaScript
mit
2,304
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <content> /// Contains nested type Recurrence.RelativeMonthlyPattern. /// </content> public abstract partial class Recurrence { /// <summary> /// Represents a recurrence pattern where each occurrence happens on a relative day a specific number of months /// after the previous one. /// </summary> public sealed class RelativeMonthlyPattern : IntervalPattern { private DayOfTheWeek? dayOfTheWeek; private DayOfTheWeekIndex? dayOfTheWeekIndex; /// <summary> /// Initializes a new instance of the <see cref="RelativeMonthlyPattern"/> class. /// </summary> public RelativeMonthlyPattern() : base() { } /// <summary> /// Initializes a new instance of the <see cref="RelativeMonthlyPattern"/> class. /// </summary> /// <param name="startDate">The date and time when the recurrence starts.</param> /// <param name="interval">The number of months between each occurrence.</param> /// <param name="dayOfTheWeek">The day of the week each occurrence happens.</param> /// <param name="dayOfTheWeekIndex">The relative position of the day within the month.</param> public RelativeMonthlyPattern( DateTime startDate, int interval, DayOfTheWeek dayOfTheWeek, DayOfTheWeekIndex dayOfTheWeekIndex) : base(startDate, interval) { this.DayOfTheWeek = dayOfTheWeek; this.DayOfTheWeekIndex = dayOfTheWeekIndex; } /// <summary> /// Gets the name of the XML element. /// </summary> /// <value>The name of the XML element.</value> internal override string XmlElementName { get { return XmlElementNames.RelativeMonthlyRecurrence; } } /// <summary> /// Write properties to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void InternalWritePropertiesToXml(EwsServiceXmlWriter writer) { base.InternalWritePropertiesToXml(writer); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DaysOfWeek, this.DayOfTheWeek); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DayOfWeekIndex, this.DayOfTheWeekIndex); } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if appropriate element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { if (base.TryReadElementFromXml(reader)) { return true; } else { switch (reader.LocalName) { case XmlElementNames.DaysOfWeek: this.dayOfTheWeek = reader.ReadElementValue<DayOfTheWeek>(); return true; case XmlElementNames.DayOfWeekIndex: this.dayOfTheWeekIndex = reader.ReadElementValue<DayOfTheWeekIndex>(); return true; default: return false; } } } /// <summary> /// Validates this instance. /// </summary> internal override void InternalValidate() { base.InternalValidate(); if (!this.dayOfTheWeek.HasValue) { throw new ServiceValidationException(Strings.DayOfTheWeekMustBeSpecifiedForRecurrencePattern); } if (!this.dayOfTheWeekIndex.HasValue) { throw new ServiceValidationException(Strings.DayOfWeekIndexMustBeSpecifiedForRecurrencePattern); } } /// <summary> /// Checks if two recurrence objects are identical. /// </summary> /// <param name="otherRecurrence">The recurrence to compare this one to.</param> /// <returns>true if the two recurrences are identical, false otherwise.</returns> public override bool IsSame(Recurrence otherRecurrence) { RelativeMonthlyPattern otherRelativeMonthlyPattern = (RelativeMonthlyPattern)otherRecurrence; return base.IsSame(otherRecurrence) && this.dayOfTheWeek == otherRelativeMonthlyPattern.dayOfTheWeek && this.dayOfTheWeekIndex == otherRelativeMonthlyPattern.dayOfTheWeekIndex; } /// <summary> /// Gets or sets the relative position of the day specified in DayOfTheWeek within the month. /// </summary> public DayOfTheWeekIndex DayOfTheWeekIndex { get { return this.GetFieldValueOrThrowIfNull<DayOfTheWeekIndex>(this.dayOfTheWeekIndex, "DayOfTheWeekIndex"); } set { this.SetFieldValue<DayOfTheWeekIndex?>(ref this.dayOfTheWeekIndex, value); } } /// <summary> /// The day of the week when each occurrence happens. /// </summary> public DayOfTheWeek DayOfTheWeek { get { return this.GetFieldValueOrThrowIfNull<DayOfTheWeek>(this.dayOfTheWeek, "DayOfTheWeek"); } set { this.SetFieldValue<DayOfTheWeek?>(ref this.dayOfTheWeek, value); } } } } }
FilipRychnavsky/ews-managed-api
ComplexProperties/Recurrence/Patterns/Recurrence.RelativeMonthlyPattern.cs
C#
mit
7,553
var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); (function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "@angular/core", "../../config/config", "../ion", "../../util/util"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var config_1 = require("../../config/config"); var ion_1 = require("../ion"); var util_1 = require("../../util/util"); /** * \@name Spinner * \@description * The `ion-spinner` component provides a variety of animated SVG spinners. * Spinners enables you to give users feedback that the app is actively * processing/thinking/waiting/chillin’ out, or whatever you’d like it to indicate. * By default, the `ion-refresher` feature uses this spinner component while it's * the refresher is in the `refreshing` state. * * Ionic offers a handful of spinners out of the box, and by default, it will use * the appropriate spinner for the platform on which it’s running. * * <table class="table spinner-table"> * <tr> * <th> * <code>ios</code> * </th> * <td> * <ion-spinner name="ios"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>ios-small</code> * </th> * <td> * <ion-spinner name="ios-small"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>bubbles</code> * </th> * <td> * <ion-spinner name="bubbles"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>circles</code> * </th> * <td> * <ion-spinner name="circles"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>crescent</code> * </th> * <td> * <ion-spinner name="crescent"></ion-spinner> * </td> * </tr> * <tr> * <th> * <code>dots</code> * </th> * <td> * <ion-spinner name="dots"></ion-spinner> * </td> * </tr> * </table> * * \@usage * The following code would use the default spinner for the platform it's * running from. If it's neither iOS or Android, it'll default to use `ios`. * * ```html * <ion-spinner></ion-spinner> * ``` * * By setting the `name` property, you can specify which predefined spinner to * use, no matter what the platform is. * * ```html * <ion-spinner name="bubbles"></ion-spinner> * ``` * * ## Styling SVG with CSS * One cool thing about SVG is its ability to be styled with CSS! One thing to note * is that some of the CSS properties on an SVG element have different names. For * example, SVG uses the term `stroke` instead of `border`, and `fill` instead * of `background-color`. * * ```css * ion-spinner * { * width: 28px; * height: 28px; * stroke: #444; * fill: #222; * } * ``` */ var Spinner = (function (_super) { __extends(Spinner, _super); /** * @param {?} config * @param {?} elementRef * @param {?} renderer */ function Spinner(config, elementRef, renderer) { var _this = _super.call(this, config, elementRef, renderer, 'spinner') || this; _this._dur = null; _this._paused = false; return _this; } Object.defineProperty(Spinner.prototype, "name", { /** * \@input {string} SVG spinner name. * @return {?} */ get: function () { return this._name; }, /** * @param {?} val * @return {?} */ set: function (val) { this._name = val; this.load(); }, enumerable: true, configurable: true }); Object.defineProperty(Spinner.prototype, "duration", { /** * \@input {string} How long it takes it to do one loop. * @return {?} */ get: function () { return this._dur; }, /** * @param {?} val * @return {?} */ set: function (val) { this._dur = val; this.load(); }, enumerable: true, configurable: true }); Object.defineProperty(Spinner.prototype, "paused", { /** * \@input {boolean} If true, pause the animation. * @return {?} */ get: function () { return this._paused; }, /** * @param {?} val * @return {?} */ set: function (val) { this._paused = util_1.isTrueProperty(val); }, enumerable: true, configurable: true }); /** * @hidden * @return {?} */ Spinner.prototype.ngOnInit = function () { this._init = true; this.load(); }; /** * @hidden * @return {?} */ Spinner.prototype.load = function () { if (this._init) { this._l = []; this._c = []; var /** @type {?} */ name = this._name || this._config.get('spinner', 'ios'); var /** @type {?} */ spinner = SPINNERS[name]; if (spinner) { if (spinner.lines) { for (var /** @type {?} */ i = 0, /** @type {?} */ l = spinner.lines; i < l; i++) { this._l.push(this._loadEle(spinner, i, l)); } } else if (spinner.circles) { for (var /** @type {?} */ i = 0, /** @type {?} */ l = spinner.circles; i < l; i++) { this._c.push(this._loadEle(spinner, i, l)); } } this.setElementClass("spinner-" + name, true); this.setElementClass("spinner-" + this._mode + "-" + name, true); } } }; /** * @param {?} spinner * @param {?} index * @param {?} total * @return {?} */ Spinner.prototype._loadEle = function (spinner, index, total) { var /** @type {?} */ duration = this._dur || spinner.dur; var /** @type {?} */ data = spinner.fn(duration, index, total); data.style.animationDuration = duration + 'ms'; return data; }; return Spinner; }(ion_1.Ion)); Spinner.decorators = [ { type: core_1.Component, args: [{ selector: 'ion-spinner', template: '<svg viewBox="0 0 64 64" *ngFor="let i of _c" [ngStyle]="i.style">' + '<circle [attr.r]="i.r" transform="translate(32,32)"></circle>' + '</svg>' + '<svg viewBox="0 0 64 64" *ngFor="let i of _l" [ngStyle]="i.style">' + '<line [attr.y1]="i.y1" [attr.y2]="i.y2" transform="translate(32,32)"></line>' + '</svg>', host: { '[class.spinner-paused]': '_paused' }, changeDetection: core_1.ChangeDetectionStrategy.OnPush, encapsulation: core_1.ViewEncapsulation.None, },] }, ]; /** * @nocollapse */ Spinner.ctorParameters = function () { return [ { type: config_1.Config, }, { type: core_1.ElementRef, }, { type: core_1.Renderer, }, ]; }; Spinner.propDecorators = { 'name': [{ type: core_1.Input },], 'duration': [{ type: core_1.Input },], 'paused': [{ type: core_1.Input },], }; exports.Spinner = Spinner; function Spinner_tsickle_Closure_declarations() { /** @type {?} */ Spinner.decorators; /** * @nocollapse * @type {?} */ Spinner.ctorParameters; /** @type {?} */ Spinner.propDecorators; /** @type {?} */ Spinner.prototype._c; /** @type {?} */ Spinner.prototype._l; /** @type {?} */ Spinner.prototype._name; /** @type {?} */ Spinner.prototype._dur; /** @type {?} */ Spinner.prototype._init; /** @type {?} */ Spinner.prototype._paused; } var /** @type {?} */ SPINNERS = { ios: { dur: 1000, lines: 12, fn: function (dur, index, total) { var /** @type {?} */ transform = 'rotate(' + (30 * index + (index < 6 ? 180 : -180)) + 'deg)'; var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { y1: 17, y2: 29, style: { transform: transform, webkitTransform: transform, animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, 'ios-small': { dur: 1000, lines: 12, fn: function (dur, index, total) { var /** @type {?} */ transform = 'rotate(' + (30 * index + (index < 6 ? 180 : -180)) + 'deg)'; var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { y1: 12, y2: 20, style: { transform: transform, webkitTransform: transform, animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, bubbles: { dur: 1000, circles: 9, fn: function (dur, index, total) { var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { r: 5, style: { top: (9 * Math.sin(2 * Math.PI * index / total)) + 'px', left: (9 * Math.cos(2 * Math.PI * index / total)) + 'px', animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, circles: { dur: 1000, circles: 8, fn: function (dur, index, total) { var /** @type {?} */ animationDelay = -(dur - ((dur / total) * index)) + 'ms'; return { r: 5, style: { top: (9 * Math.sin(2 * Math.PI * index / total)) + 'px', left: (9 * Math.cos(2 * Math.PI * index / total)) + 'px', animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } }, crescent: { dur: 750, circles: 1, fn: function (dur) { return { r: 26, style: {} }; } }, dots: { dur: 750, circles: 3, fn: function (dur, index, total) { var /** @type {?} */ animationDelay = -(110 * index) + 'ms'; return { r: 6, style: { left: (9 - (9 * index)) + 'px', animationDelay: animationDelay, webkitAnimationDelay: animationDelay } }; } } }; }); //# sourceMappingURL=spinner.js.map
fabiencheylac/kolp
node_modules/ionic-angular/umd/components/spinner/spinner.js
JavaScript
mit
13,071
// // Copyright (c) 2020 Advanced Micro Devices, Inc. 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. // /// \file /// \mainpage /// AGS Library Overview /// -------------------- /// This document provides an overview of the AGS (AMD GPU Services) library. The AGS library provides software developers with the ability to query /// AMD GPU software and hardware state information that is not normally available through standard operating systems or graphic APIs. /// /// The latest version of the API is publicly hosted here: https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/. /// It is also worth checking http://gpuopen.com/gaming-product/amd-gpu-services-ags-library/ for any updates and articles on AGS. /// \internal /// Online documentation is publicly hosted here: http://gpuopen-librariesandsdks.github.io/ags/ /// \endinternal /// /// --------------------------------------- /// What's new in AGS 6.0 since version 5.4.2 /// --------------------------------------- /// AGS 6.0 includes the following updates: /// * DX12 ray tracing hit token for RDNA2 hardware. /// * Shader intrinsic that exposes ReadLaneAt in DX12. /// * Shader intrinsics that expose explicit float conversions in DX12. /// * Refactored and revised API to minimize user error. /// * Added agsGetVersionNumber. /// * Detection for external GPUs. /// * Detection of RDNA2 architecture. /// * Grouped the more established intrinsics together into per year support. /// * Function pointer typedefs for the API /// /// --------------------------------------- /// What's new in AGS 5.4.2 since version 5.4.1 /// --------------------------------------- /// AGS 5.4.2 includes the following updates: /// * sharedMemoryInBytes has been reinstated. /// * Clock speed returned for APUs. /// /// --------------------------------------- /// What's new in AGS 5.4.1 since version 5.4.0 /// --------------------------------------- /// AGS 5.4.1 includes the following updates: /// * AsicFamily_Count to help with code maintenance. /// * Visual Studio 2019 support. /// * x86 support /// * BaseInstance and BaseVertex intrinsics along with corresponding caps bits. /// * GetWaveSize intrinsic along with corresponding caps bits. /// /// --------------------------------------- /// What's new in AGS 5.4 since version 5.3 /// --------------------------------------- /// AGS 5.4 includes the following updates: /// * A more detailed description of the GPU architecture, now including RDNA GPUs. /// * Radeon 7 core and memory speeds returned. /// * Draw index and Atomic U64 intrinsics for both DX11 and DX12. /// /// --------------------------------------- /// What's new in AGS 5.3 since version 5.2 /// --------------------------------------- /// AGS 5.3 includes the following updates: /// * DX11 deferred context support for Multi Draw Indirect and UAV Overlap extensions. /// * A Radeon Software Version helper to determine whether the installed driver meets your game's minimum driver version requirements. /// * Freesync HDR Gamma 2.2 mode which uses a 1010102 swapchain and can be considered as an alternative to using the 64 bit swapchain required for Freesync HDR scRGB. /// /// Using the AGS library /// --------------------- /// It is recommended to take a look at the source code for the samples that come with the AGS SDK: /// * AGSSample /// * CrossfireSample /// * EyefinitySample /// The AGSSample application is the simplest of the three examples and demonstrates the code required to initialize AGS and use it to query the GPU and Eyefinity state. /// The CrossfireSample application demonstrates the use of the new API to transfer resources on GPUs in Crossfire mode. Lastly, the EyefinitySample application provides a more /// extensive example of Eyefinity setup than the basic example provided in AGSSample. /// There are other samples on Github that demonstrate the DirectX shader extensions, such as the Barycentrics11 and Barycentrics12 samples. /// /// To add AGS support to an existing project, follow these steps: /// * Link your project against the correct import library. Choose from either the 32 bit or 64 bit version. /// * Copy the AGS dll into the same directory as your game executable. /// * Include the amd_ags.h header file from your source code. /// * Include the AGS hlsl files if you are using the shader intrinsics. /// * Declare a pointer to an AGSContext and make this available for all subsequent calls to AGS. /// * On game initialization, call \ref agsInitialize passing in the address of the context. On success, this function will return a valid context pointer. /// /// Don't forget to cleanup AGS by calling \ref agsDeInitialize when the app exits, after the device has been destroyed. #ifndef AMD_AGS_H #define AMD_AGS_H #define AMD_AGS_VERSION_MAJOR 6 ///< AGS major version #define AMD_AGS_VERSION_MINOR 0 ///< AGS minor version #define AMD_AGS_VERSION_PATCH 1 ///< AGS patch version #ifdef __cplusplus extern "C" { #endif /// \defgroup Defines AGS defines /// @{ #if defined (AGS_GCC) #define AMD_AGS_API #else #define AMD_AGS_API __declspec(dllexport) ///< AGS exported functions #endif #define AGS_MAKE_VERSION( major, minor, patch ) ( ( major << 22 ) | ( minor << 12 ) | patch ) ///< Macro to create the app and engine versions for the fields in \ref AGSDX12ExtensionParams and \ref AGSDX11ExtensionParams and the Radeon Software Version #define AGS_UNSPECIFIED_VERSION 0xFFFFAD00 ///< Use this to specify no version /// @} #if !defined (AGS_DIRECTX_TYPES_INCLUDED) // Forward declaration of D3D and DXGI types struct IDXGIAdapter; struct IDXGISwapChain; struct DXGI_SWAP_CHAIN_DESC; enum D3D_DRIVER_TYPE; enum D3D_FEATURE_LEVEL; enum D3D_PRIMITIVE_TOPOLOGY; // Forward declaration of D3D11 types struct ID3D11Device; struct ID3D11DeviceContext; struct ID3D11Resource; struct ID3D11Buffer; struct ID3D11Texture1D; struct ID3D11Texture2D; struct ID3D11Texture3D; struct D3D11_BUFFER_DESC; struct D3D11_TEXTURE1D_DESC; struct D3D11_TEXTURE2D_DESC; struct D3D11_TEXTURE3D_DESC; struct D3D11_SUBRESOURCE_DATA; struct tagRECT; typedef tagRECT D3D11_RECT; ///< typedef this ourselves so we don't have to drag d3d11.h in // Forward declaration of D3D12 types struct ID3D12Device; struct ID3D12GraphicsCommandList; #endif /// \defgroup enums General enumerations /// @{ /// The return codes typedef enum AGSReturnCode { AGS_SUCCESS, ///< Successful function call AGS_FAILURE, ///< Failed to complete call for some unspecified reason AGS_INVALID_ARGS, ///< Invalid arguments into the function AGS_OUT_OF_MEMORY, ///< Out of memory when allocating space internally AGS_MISSING_D3D_DLL, ///< Returned when a D3D dll fails to load AGS_LEGACY_DRIVER, ///< Returned if a feature is not present in the installed driver AGS_NO_AMD_DRIVER_INSTALLED, ///< Returned if the AMD GPU driver does not appear to be installed AGS_EXTENSION_NOT_SUPPORTED, ///< Returned if the driver does not support the requested driver extension AGS_ADL_FAILURE, ///< Failure in ADL (the AMD Display Library) AGS_DX_FAILURE ///< Failure from DirectX runtime } AGSReturnCode; /// @} struct AGSContext; ///< All function calls in AGS require a pointer to a context. This is generated via \ref agsInitialize /// The rectangle struct used by AGS. typedef struct AGSRect { int offsetX; ///< Offset on X axis int offsetY; ///< Offset on Y axis int width; ///< Width of rectangle int height; ///< Height of rectangle } AGSRect; /// The display info struct used to describe a display enumerated by AGS typedef struct AGSDisplayInfo { char name[ 256 ]; ///< The name of the display char displayDeviceName[ 32 ]; ///< The display device name, i.e. DISPLAY_DEVICE::DeviceName unsigned int isPrimaryDisplay : 1; ///< Whether this display is marked as the primary display unsigned int HDR10 : 1; ///< HDR10 is supported on this display unsigned int dolbyVision : 1; ///< Dolby Vision is supported on this display unsigned int freesync : 1; ///< Freesync is supported on this display unsigned int freesyncHDR : 1; ///< Freesync HDR is supported on this display unsigned int eyefinityInGroup : 1; ///< The display is part of the Eyefinity group unsigned int eyefinityPreferredDisplay : 1; ///< The display is the preferred display in the Eyefinity group for displaying the UI unsigned int eyefinityInPortraitMode : 1; ///< The display is in the Eyefinity group but in portrait mode unsigned int reservedPadding : 24; ///< Reserved for future use int maxResolutionX; ///< The maximum supported resolution of the unrotated display int maxResolutionY; ///< The maximum supported resolution of the unrotated display float maxRefreshRate; ///< The maximum supported refresh rate of the display AGSRect currentResolution; ///< The current resolution and position in the desktop, ignoring Eyefinity bezel compensation AGSRect visibleResolution; ///< The visible resolution and position. When Eyefinity bezel compensation is enabled this will ///< be the sub region in the Eyefinity single large surface (SLS) float currentRefreshRate; ///< The current refresh rate int eyefinityGridCoordX; ///< The X coordinate in the Eyefinity grid. -1 if not in an Eyefinity group int eyefinityGridCoordY; ///< The Y coordinate in the Eyefinity grid. -1 if not in an Eyefinity group double chromaticityRedX; ///< Red display primary X coord double chromaticityRedY; ///< Red display primary Y coord double chromaticityGreenX; ///< Green display primary X coord double chromaticityGreenY; ///< Green display primary Y coord double chromaticityBlueX; ///< Blue display primary X coord double chromaticityBlueY; ///< Blue display primary Y coord double chromaticityWhitePointX; ///< White point X coord double chromaticityWhitePointY; ///< White point Y coord double screenDiffuseReflectance; ///< Percentage expressed between 0 - 1 double screenSpecularReflectance; ///< Percentage expressed between 0 - 1 double minLuminance; ///< The minimum luminance of the display in nits double maxLuminance; ///< The maximum luminance of the display in nits double avgLuminance; ///< The average luminance of the display in nits int logicalDisplayIndex; ///< The internally used index of this display int adlAdapterIndex; ///< The internally used ADL adapter index int reserved; ///< reserved field } AGSDisplayInfo; /// The device info struct used to describe a physical GPU enumerated by AGS typedef struct AGSDeviceInfo { /// The ASIC family typedef enum AsicFamily { AsicFamily_Unknown, ///< Unknown architecture, potentially from another IHV. Check \ref AGSDeviceInfo::vendorId AsicFamily_PreGCN, ///< Pre GCN architecture. AsicFamily_GCN1, ///< AMD GCN 1 architecture: Oland, Cape Verde, Pitcairn & Tahiti. AsicFamily_GCN2, ///< AMD GCN 2 architecture: Hawaii & Bonaire. This also includes APUs Kaveri and Carrizo. AsicFamily_GCN3, ///< AMD GCN 3 architecture: Tonga & Fiji. AsicFamily_GCN4, ///< AMD GCN 4 architecture: Polaris. AsicFamily_Vega, ///< AMD Vega architecture, including Raven Ridge (ie AMD Ryzen CPU + AMD Vega GPU). AsicFamily_RDNA, ///< AMD RDNA architecture AsicFamily_RDNA2, ///< AMD RDNA2 architecture AsicFamily_Count ///< Number of enumerated ASIC families } AsicFamily; const char* adapterString; ///< The adapter name string AsicFamily asicFamily; ///< Set to Unknown if not AMD hardware unsigned int isAPU : 1; ///< Whether this device is an APU unsigned int isPrimaryDevice : 1; ///< Whether this device is marked as the primary device unsigned int isExternal :1; ///< Whether this device is a detachable, external device unsigned int reservedPadding : 29; ///< Reserved for future use int vendorId; ///< The vendor id int deviceId; ///< The device id int revisionId; ///< The revision id int numCUs; ///< Number of compute units int numWGPs; ///< Number of RDNA Work Group Processors. Only valid if ASIC is RDNA onwards. int numROPs; ///< Number of ROPs int coreClock; ///< Core clock speed at 100% power in MHz int memoryClock; ///< Memory clock speed at 100% power in MHz int memoryBandwidth; ///< Memory bandwidth in MB/s float teraFlops; ///< Teraflops of GPU. Zero if not GCN onwards. Calculated from iCoreClock * iNumCUs * 64 Pixels/clk * 2 instructions/MAD unsigned long long localMemoryInBytes; ///< The size of local memory in bytes. 0 for non AMD hardware. unsigned long long sharedMemoryInBytes; ///< The size of system memory available to the GPU in bytes. It is important to factor this into your VRAM budget for APUs ///< as the reported local memory will only be a small fraction of the total memory available to the GPU. int numDisplays; ///< The number of active displays found to be attached to this adapter. AGSDisplayInfo* displays; ///< List of displays allocated by AGS to be numDisplays in length. int eyefinityEnabled; ///< Indicates if Eyefinity is active int eyefinityGridWidth; ///< Contains width of the multi-monitor grid that makes up the Eyefinity Single Large Surface. int eyefinityGridHeight; ///< Contains height of the multi-monitor grid that makes up the Eyefinity Single Large Surface. int eyefinityResolutionX; ///< Contains width in pixels of the multi-monitor Single Large Surface. int eyefinityResolutionY; ///< Contains height in pixels of the multi-monitor Single Large Surface. int eyefinityBezelCompensated; ///< Indicates if bezel compensation is used for the current SLS display area. 1 if enabled, and 0 if disabled. int adlAdapterIndex; ///< Internally used index into the ADL list of adapters int reserved; ///< reserved field } AGSDeviceInfo; /// \defgroup general General API functions /// API for initialization, cleanup, HDR display modes and Crossfire GPU count /// @{ typedef void* (__stdcall *AGS_ALLOC_CALLBACK)( size_t allocationSize ); ///< AGS user defined allocation prototype typedef void (__stdcall *AGS_FREE_CALLBACK)( void* allocationPtr ); ///< AGS user defined free prototype /// The configuration options that can be passed in to \ref agsInitialize typedef struct AGSConfiguration { AGS_ALLOC_CALLBACK allocCallback; ///< Optional memory allocation callback. If not supplied, malloc() is used AGS_FREE_CALLBACK freeCallback; ///< Optional memory freeing callback. If not supplied, free() is used } AGSConfiguration; /// The top level GPU information returned from \ref agsInitialize typedef struct AGSGPUInfo { const char* driverVersion; ///< The AMD driver package version const char* radeonSoftwareVersion; ///< The Radeon Software Version int numDevices; ///< Number of GPUs in the system AGSDeviceInfo* devices; ///< List of GPUs in the system } AGSGPUInfo; /// The struct to specify the display settings to the driver. typedef struct AGSDisplaySettings { /// The display mode typedef enum Mode { Mode_SDR, ///< SDR mode Mode_HDR10_PQ, ///< HDR10 PQ encoding, requiring a 1010102 UNORM swapchain and PQ encoding in the output shader. Mode_HDR10_scRGB, ///< HDR10 scRGB, requiring an FP16 swapchain. Values of 1.0 == 80 nits, 125.0 == 10000 nits. Mode_FreesyncHDR_scRGB, ///< Freesync HDR scRGB, requiring an FP16 swapchain. A value of 1.0 == 80 nits. Mode_FreesyncHDR_Gamma22, ///< Freesync HDR Gamma 2.2, requiring a 1010102 UNORM swapchain. The output needs to be encoded to gamma 2.2. Mode_DolbyVision, ///< Dolby Vision, requiring an 8888 UNORM swapchain Mode_Count ///< Number of enumerated display modes } Mode; Mode mode; ///< The display mode to set the display into double chromaticityRedX; ///< Red display primary X coord double chromaticityRedY; ///< Red display primary Y coord double chromaticityGreenX; ///< Green display primary X coord double chromaticityGreenY; ///< Green display primary Y coord double chromaticityBlueX; ///< Blue display primary X coord double chromaticityBlueY; ///< Blue display primary Y coord double chromaticityWhitePointX; ///< White point X coord double chromaticityWhitePointY; ///< White point Y coord double minLuminance; ///< The minimum scene luminance in nits double maxLuminance; ///< The maximum scene luminance in nits double maxContentLightLevel; ///< The maximum content light level in nits (MaxCLL) double maxFrameAverageLightLevel; ///< The maximum frame average light level in nits (MaxFALL) unsigned int disableLocalDimming : 1; ///< Disables local dimming if possible unsigned int reservedPadding : 31; ///< Reserved } AGSDisplaySettings; /// The result returned from \ref agsCheckDriverVersion typedef enum AGSDriverVersionResult { AGS_SOFTWAREVERSIONCHECK_OK, ///< The reported Radeon Software Version is newer or the same as the required version AGS_SOFTWAREVERSIONCHECK_OLDER, ///< The reported Radeon Software Version is older than the required version AGS_SOFTWAREVERSIONCHECK_UNDEFINED ///< The check could not determine as result. This could be because it is a private or custom driver or just invalid arguments. } AGSDriverVersionResult; /// /// Helper function to check the installed software version against the required software version. /// /// \param [in] radeonSoftwareVersionReported The Radeon Software Version returned from \ref AGSGPUInfo::radeonSoftwareVersion. /// \param [in] radeonSoftwareVersionRequired The Radeon Software Version to check against. This is specificed using \ref AGS_MAKE_VERSION. /// \return The result of the check. /// AMD_AGS_API AGSDriverVersionResult agsCheckDriverVersion( const char* radeonSoftwareVersionReported, unsigned int radeonSoftwareVersionRequired ); /// /// Function to return the AGS version number. /// /// \return The version number made using AGS_MAKE_VERSION( AMD_AGS_VERSION_MAJOR, AMD_AGS_VERSION_MINOR, AMD_AGS_VERSION_PATCH ). /// AMD_AGS_API int agsGetVersionNumber(); /// /// Function used to initialize the AGS library. /// agsVersion must be specified as AGS_MAKE_VERSION( AMD_AGS_VERSION_MAJOR, AMD_AGS_VERSION_MINOR, AMD_AGS_VERSION_PATCH ) or the call will return \ref AGS_INVALID_ARGS. /// Must be called prior to any of the subsequent AGS API calls. /// Must be called prior to ID3D11Device or ID3D12Device creation. /// \note The caller of this function should handle the possibility of the call failing in the cases below. One option is to do a vendor id check and only call \ref agsInitialize if there is an AMD GPU present. /// \note This function will fail with \ref AGS_NO_AMD_DRIVER_INSTALLED if there is no AMD driver found on the system. /// \note This function will fail with \ref AGS_LEGACY_DRIVER in Catalyst versions before 12.20. /// /// \param [in] agsVersion The API version specified using the \ref AGS_MAKE_VERSION macro. If this does not match the version in the binary this initialization call will fail. /// \param [in] config Optional pointer to a AGSConfiguration struct to override the default library configuration. /// \param [out] context Address of a pointer to a context. This function allocates a context on the heap which is then required for all subsequent API calls. /// \param [out] gpuInfo Optional pointer to a AGSGPUInfo struct which will get filled in for all the GPUs in the system. /// AMD_AGS_API AGSReturnCode agsInitialize( int agsVersion, const AGSConfiguration* config, AGSContext** context, AGSGPUInfo* gpuInfo ); /// /// Function used to clean up the AGS library. /// /// \param [in] context Pointer to a context. This function will deallocate the context from the heap. /// AMD_AGS_API AGSReturnCode agsDeInitialize( AGSContext* context ); /// /// Function used to set a specific display into HDR mode /// \note Setting all of the values apart from color space and transfer function to zero will cause the display to use defaults. /// \note Call this function after each mode change (switch to fullscreen, any change in swapchain etc). /// \note HDR10 PQ mode requires a 1010102 swapchain. /// \note HDR10 scRGB mode requires an FP16 swapchain. /// \note Freesync HDR scRGB mode requires an FP16 swapchain. /// \note Freesync HDR Gamma 2.2 mode requires a 1010102 swapchain. /// \note Dolby Vision requires a 8888 UNORM swapchain. /// /// \param [in] context Pointer to a context. This is generated by \ref agsInitialize /// \param [in] deviceIndex The index of the device listed in \ref AGSGPUInfo::devices. /// \param [in] displayIndex The index of the display listed in \ref AGSDeviceInfo::displays. /// \param [in] settings Pointer to the display settings to use. /// AMD_AGS_API AGSReturnCode agsSetDisplayMode( AGSContext* context, int deviceIndex, int displayIndex, const AGSDisplaySettings* settings ); /// @} /// \defgroup dx12 DirectX12 Extensions /// DirectX12 driver extensions /// @{ /// \defgroup dx12init Device and device object creation and cleanup /// It is now mandatory to call \ref agsDriverExtensionsDX12_CreateDevice when creating a device if the user wants to access any future DX12 AMD extensions. /// The corresponding \ref agsDriverExtensionsDX12_DestroyDevice call must be called to release the device and free up the internal resources allocated by the create call. /// @{ /// The struct to specify the DX12 device creation parameters typedef struct AGSDX12DeviceCreationParams { IDXGIAdapter* pAdapter; ///< Pointer to the adapter to use when creating the device. This may be null. IID iid; ///< The interface ID for the type of device to be created. D3D_FEATURE_LEVEL FeatureLevel; ///< The minimum feature level to create the device with. } AGSDX12DeviceCreationParams; /// The struct to specify DX12 additional device creation parameters typedef struct AGSDX12ExtensionParams { const WCHAR* pAppName; ///< Application name const WCHAR* pEngineName; ///< Engine name unsigned int appVersion; ///< Application version unsigned int engineVersion; ///< Engine version unsigned int uavSlot; ///< The UAV slot reserved for intrinsic support. Refer to the \ref agsDriverExtensionsDX12_CreateDevice documentation for more details. } AGSDX12ExtensionParams; /// The struct to hold all the returned parameters from the device creation call typedef struct AGSDX12ReturnedParams { ID3D12Device* pDevice; ///< The newly created device typedef struct ExtensionsSupported /// Extensions for DX12 { unsigned int intrinsics16 : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. ReadFirstLane, ReadLane, LaneID, Swizzle, Ballot, MBCount, Med3, Barycentrics unsigned int intrinsics17 : 1; ///< Supported in Radeon Software Version 17.9.1 onwards. WaveReduce, WaveScan unsigned int userMarkers : 1; ///< Supported in Radeon Software Version 17.9.1 onwards. unsigned int appRegistration : 1; ///< Supported in Radeon Software Version 17.9.1 onwards. unsigned int UAVBindSlot : 1; ///< Supported in Radeon Software Version 19.5.1 onwards. unsigned int intrinsics19 : 1; ///< Supported in Radeon Software Version 19.12.2 onwards. DrawIndex, AtomicU64 unsigned int baseVertex : 1; ///< Supported in Radeon Software Version 20.2.1 onwards. unsigned int baseInstance : 1; ///< Supported in Radeon Software Version 20.2.1 onwards. unsigned int getWaveSize : 1; ///< Supported in Radeon Software Version 20.5.1 onwards. unsigned int floatConversion : 1; ///< Supported in Radeon Software Version 20.5.1 onwards. unsigned int readLaneAt : 1; ///< Supported in Radeon Software Version 20.11.2 onwards. unsigned int rayHitToken : 1; ///< Supported in Radeon Software Version 20.11.2 onwards. unsigned int padding : 20; ///< Reserved } ExtensionsSupported; ExtensionsSupported extensionsSupported; ///< List of supported extensions } AGSDX12ReturnedParams; /// The space id for DirectX12 intrinsic support const unsigned int AGS_DX12_SHADER_INSTRINSICS_SPACE_ID = 0x7FFF0ADE; // 2147420894 /// /// Function used to create a D3D12 device with additional AMD-specific initialization parameters. /// /// When using the HLSL shader extensions please note: /// * The shader compiler should not use the D3DCOMPILE_SKIP_OPTIMIZATION (/Od) option, otherwise it will not work. /// * The shader compiler needs D3DCOMPILE_ENABLE_STRICTNESS (/Ges) enabled. /// * The intrinsic instructions require a 5.1 shader model. /// * The Root Signature will need to reserve an extra UAV resource slot. This is not a real resource that requires allocating, it is just used to encode the intrinsic instructions. /// /// The easiest way to set up the reserved UAV slot is to specify it at u0. The register space id will automatically be assumed to be \ref AGS_DX12_SHADER_INSTRINSICS_SPACE_ID. /// The HLSL expects this as default and the set up code would look similar to this: /// \code{.cpp} /// CD3DX12_DESCRIPTOR_RANGE range[]; /// ... /// range[ 0 ].Init( D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, AGS_DX12_SHADER_INSTRINSICS_SPACE_ID ); // u0 at driver-reserved space id /// \endcode /// /// Newer drivers also support a user-specified slot in which case the register space id is assumed to be 0. It is important that the \ref AGSDX12ReturnedParams::ExtensionsSupported::UAVBindSlot bit is set. /// to ensure the driver can support this. If not, then u0 and \ref AGS_DX12_SHADER_INSTRINSICS_SPACE_ID must be used. /// If the driver does support this feature and a non zero slot is required, then the HLSL must also define AMD_EXT_SHADER_INTRINSIC_UAV_OVERRIDE as the matching slot value. /// /// \param [in] context Pointer to a context. This is generated by \ref agsInitialize /// \param [in] creationParams Pointer to the struct to specify the existing DX12 device creation parameters. /// \param [in] extensionParams Optional pointer to the struct to specify DX12 additional device creation parameters. /// \param [out] returnedParams Pointer to struct to hold all the returned parameters from the call. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX12_CreateDevice( AGSContext* context, const AGSDX12DeviceCreationParams* creationParams, const AGSDX12ExtensionParams* extensionParams, AGSDX12ReturnedParams* returnedParams ); /// /// Function to destroy the D3D12 device. /// This call will also cleanup any AMD-specific driver extensions for D3D12. /// /// \param [in] context Pointer to a context. /// \param [in] device Pointer to the D3D12 device. /// \param [out] deviceReferences Optional pointer to an unsigned int that will be set to the value returned from device->Release(). /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX12_DestroyDevice( AGSContext* context, ID3D12Device* device, unsigned int* deviceReferences ); /// @} /// \defgroup dx12usermarkers User Markers /// @{ /// /// Function used to push an AMD user marker onto the command list. /// This is only has an effect if \ref AGSDX12ReturnedParams::ExtensionsSupported::userMarkers is present. /// Supported in Radeon Software Version 17.9.1 onwards. /// /// \param [in] context Pointer to a context. /// \param [in] commandList Pointer to the command list. /// \param [in] data The marker string. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX12_PushMarker( AGSContext* context, ID3D12GraphicsCommandList* commandList, const char* data ); /// /// Function used to pop an AMD user marker on the command list. /// Supported in Radeon Software Version 17.9.1 onwards. /// /// \param [in] context Pointer to a context. /// \param [in] commandList Pointer to the command list. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX12_PopMarker( AGSContext* context, ID3D12GraphicsCommandList* commandList ); /// /// Function used to insert an single event AMD user marker onto the command list. /// Supported in Radeon Software Version 17.9.1 onwards. /// /// \param [in] context Pointer to a context. /// \param [in] commandList Pointer to the command list. /// \param [in] data The marker string. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX12_SetMarker( AGSContext* context, ID3D12GraphicsCommandList* commandList, const char* data ); /// @} /// @} /// \defgroup dx11 DirectX11 Extensions /// DirectX11 driver extensions /// @{ /// \defgroup dx11init Device creation and cleanup /// It is now mandatory to call \ref agsDriverExtensionsDX11_CreateDevice when creating a device if the user wants to access any DX11 AMD extensions. /// The corresponding \ref agsDriverExtensionsDX11_DestroyDevice call must be called to release the device and free up the internal resources allocated by the create call. /// @{ /// The different modes to control Crossfire behavior. typedef enum AGSCrossfireMode { AGS_CROSSFIRE_MODE_DRIVER_AFR = 0, ///< Use the default driver-based AFR rendering. If this mode is specified, do NOT use the agsDriverExtensionsDX11_Create*() APIs to create resources AGS_CROSSFIRE_MODE_EXPLICIT_AFR, ///< Use the AGS Crossfire API functions to perform explicit AFR rendering without requiring a CF driver profile AGS_CROSSFIRE_MODE_DISABLE ///< Completely disable AFR rendering } AGSCrossfireMode; /// The struct to specify the existing DX11 device creation parameters typedef struct AGSDX11DeviceCreationParams { IDXGIAdapter* pAdapter; ///< Consult the DX documentation on D3D11CreateDevice for this parameter D3D_DRIVER_TYPE DriverType; ///< Consult the DX documentation on D3D11CreateDevice for this parameter HMODULE Software; ///< Consult the DX documentation on D3D11CreateDevice for this parameter UINT Flags; ///< Consult the DX documentation on D3D11CreateDevice for this parameter const D3D_FEATURE_LEVEL* pFeatureLevels; ///< Consult the DX documentation on D3D11CreateDevice for this parameter UINT FeatureLevels; ///< Consult the DX documentation on D3D11CreateDevice for this parameter UINT SDKVersion; ///< Consult the DX documentation on D3D11CreateDevice for this parameter const DXGI_SWAP_CHAIN_DESC* pSwapChainDesc; ///< Optional swapchain description. Specify this to invoke D3D11CreateDeviceAndSwapChain instead of D3D11CreateDevice. } AGSDX11DeviceCreationParams; /// The struct to specify DX11 additional device creation parameters typedef struct AGSDX11ExtensionParams { const WCHAR* pAppName; ///< Application name const WCHAR* pEngineName; ///< Engine name unsigned int appVersion; ///< Application version unsigned int engineVersion; ///< Engine version unsigned int numBreadcrumbMarkers; ///< The number of breadcrumb markers to allocate. Each marker is a uint64 (ie 8 bytes). If 0, the system is disabled. unsigned int uavSlot; ///< The UAV slot reserved for intrinsic support. This must match the slot defined in the HLSL, i.e. "#define AmdDxExtShaderIntrinsicsUAVSlot". /// The default slot is 7, but the caller is free to use an alternative slot. /// If 0 is specified, then the default of 7 will be used. AGSCrossfireMode crossfireMode; ///< Desired Crossfire mode } AGSDX11ExtensionParams; /// The struct to hold all the returned parameters from the device creation call typedef struct AGSDX11ReturnedParams { ID3D11Device* pDevice; ///< The newly created device ID3D11DeviceContext* pImmediateContext; ///< The newly created immediate device context IDXGISwapChain* pSwapChain; ///< The newly created swap chain. This is only created if a valid pSwapChainDesc is supplied in AGSDX11DeviceCreationParams. D3D_FEATURE_LEVEL featureLevel; ///< The feature level supported by the newly created device typedef struct ExtensionsSupported /// Extensions for DX11 { unsigned int quadList : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int screenRectList : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int uavOverlap : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int depthBoundsTest : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int multiDrawIndirect : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int multiDrawIndirectCountIndirect : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int crossfireAPI : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int createShaderControls : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. unsigned int intrinsics16 : 1; ///< Supported in Radeon Software Version 16.9.2 onwards. ReadFirstLane, ReadLane, LaneID, Swizzle, Ballot, MBCount, Med3, Barycentrics unsigned int multiView : 1; ///< Supported in Radeon Software Version 16.12.1 onwards. unsigned int intrinsics17 : 1; ///< Supported in Radeon Software Version 17.9.1 onwards. WaveReduce, WaveScan unsigned int appRegistration : 1; ///< Supported in Radeon Software Version 17.9.1 onwards. unsigned int breadcrumbMarkers : 1; ///< Supported in Radeon Software Version 17.11.1 onwards. unsigned int MDIDeferredContexts : 1; ///< Supported in Radeon Software Version 18.8.1 onwards. unsigned int UAVOverlapDeferredContexts : 1; ///< Supported in Radeon Software Version 18.8.1 onwards. unsigned int depthBoundsDeferredContexts : 1; ///< Supported in Radeon Software Version 18.8.1 onwards. unsigned int intrinsics19 : 1; ///< Supported in Radeon Software Version 19.12.2 onwards. DrawIndex, AtomicU64 unsigned int getWaveSize : 1; ///< Supported in Radeon Software Version 20.2.1 onwards. unsigned int baseVertex : 1; ///< Supported in Radeon Software Version 20.2.1 onwards. unsigned int baseInstance : 1; ///< Supported in Radeon Software Version 20.2.1 onwards. unsigned int padding : 12; ///< Reserved } ExtensionsSupported; ExtensionsSupported extensionsSupported; ///< List of supported extensions unsigned int crossfireGPUCount; ///< The number of GPUs that are active for this app void* breadcrumbBuffer; ///< The CPU buffer returned if the initialization of the breadcrumb was successful } AGSDX11ReturnedParams; /// /// Function used to create a D3D11 device with additional AMD-specific initialization parameters. /// /// When using the HLSL shader extensions please note: /// * The shader compiler should not use the D3DCOMPILE_SKIP_OPTIMIZATION (/Od) option, otherwise it will not work. /// * The shader compiler needs D3DCOMPILE_ENABLE_STRICTNESS (/Ges) enabled. /// /// \param [in] context Pointer to a context. This is generated by \ref agsInitialize /// \param [in] creationParams Pointer to the struct to specify the existing DX11 device creation parameters. /// \param [in] extensionParams Optional pointer to the struct to specify DX11 additional device creation parameters. /// \param [out] returnedParams Pointer to struct to hold all the returned parameters from the call. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_CreateDevice( AGSContext* context, const AGSDX11DeviceCreationParams* creationParams, const AGSDX11ExtensionParams* extensionParams, AGSDX11ReturnedParams* returnedParams ); /// /// Function to destroy the D3D11 device and its immediate context. /// This call will also cleanup any AMD-specific driver extensions for D3D11. /// /// \param [in] context Pointer to a context. /// \param [in] device Pointer to the D3D11 device. /// \param [out] deviceReferences Optional pointer to an unsigned int that will be set to the value returned from device->Release(). /// \param [in] immediateContext Pointer to the D3D11 immediate device context. /// \param [out] immediateContextReferences Optional pointer to an unsigned int that will be set to the value returned from immediateContext->Release(). /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_DestroyDevice( AGSContext* context, ID3D11Device* device, unsigned int* deviceReferences, ID3D11DeviceContext* immediateContext, unsigned int* immediateContextReferences ); /// @} /// \defgroup dx11appreg App Registration /// @{ /// This extension allows an apllication to voluntarily register itself with the driver, providing a more robust app detection solution and avoid the issue of the driver /// relying on exe names to match the app to a driver profile. /// This feature is supported in Radeon Software Version 17.9.2 onwards. /// Rules: /// * AppName or EngineName must be set, but both are not required. Engine profiles will be used only if app specific profiles do not exist. /// * In an engine, the EngineName should be set, so a default profile can be built. If an app modifies the engine, the AppName should be set, to allow a profile for the specific app. /// * Version number is not mandatory, but heavily suggested. The use of which can prevent the use of profiles for incompatible versions (for instance engine versions that introduce or change features), and can help prevent older profiles from being used (and introducing new bugs) before the profile is tested with new app builds. /// * If Version numbers are used and a new version is introduced, a new profile will not be enabled until an AMD engineer has been able to update a previous profile, or make a new one. /// /// The cases for profile selection are as follows: /// /// |Case|Profile Applied| /// |----|---------------| /// | App or Engine Version has profile | The profile is used. | /// | App or Engine Version num < profile version num | The closest profile > the version number is used. | /// | App or Engine Version num > profile version num | No profile selected/The previous method is used. | /// | App and Engine Version have profile | The App's profile is used. | /// | App and Engine Version num < profile version | The closest App profile > the version number is used. | /// | App and Engine Version, no App profile found | The Engine profile will be used. | /// | App/Engine name but no Version, has profile | The latest profile is used. | /// | No name or version, or no profile | The previous app detection method is used. | /// /// As shown above, if an App name is given, and a profile is found for that app, that will be prioritized. The Engine name and profile will be used only if no app name is given, or no viable profile is found for the app name. /// In the case that App nor Engine have a profile, the previous app detection methods will be used. If given a version number that is larger than any profile version number, no profile will be selected. /// This is specifically to prevent cases where an update to an engine or app will cause catastrophic breaks in the profile, allowing an engineer to test the profile before clearing it for public use with the new engine/app update. /// /// @} /// \defgroup breadcrumbs Breadcrumb API /// API for writing top-of-pipe and bottom-of-pipe markers to help track down GPU hangs. /// /// The API is available if the \ref AGSDX11ReturnedParams::ExtensionsSupported::breadcrumbMarkers is present. /// /// To use the API, a non zero value needs to be specificed in \ref AGSDX11ExtensionParams::numBreadcrumbMarkers. This enables the API (if available) and allocates a system memory buffer /// which is returned to the user in \ref AGSDX11ReturnedParams::breadcrumbBuffer. /// /// The user can now write markers before and after draw calls using \ref agsDriverExtensionsDX11_WriteBreadcrumb. /// /// \section background Background /// /// A top-of-pipe (TOP) command is scheduled for execution as soon as the command processor (CP) reaches the command. /// A bottom-of-pipe (BOP) command is scheduled for execution once the previous rendering commands (draw and dispatch) finish execution. /// TOP and BOP commands do not block CP. i.e. the CP schedules the command for execution then proceeds to the next command without waiting. /// To effectively use TOP and BOP commands, it is important to understand how they interact with rendering commands: /// /// When the CP encounters a rendering command it queues it for execution and moves to the next command. The queued rendering commands are issued in order. /// There can be multiple rendering commands running in parallel. When a rendering command is issued we say it is at the top of the pipe. When a rendering command /// finishes execution we say it has reached the bottom of the pipe. /// /// A BOP command remains in a waiting queue and is executed once prior rendering commands finish. The queue of BOP commands is limited to 64 entries in GCN generation 1, 2, 3, 4 and 5. /// If the 64 limit is reached the CP will stop queueing BOP commands and also rendering commands. Developers should limit the number of BOP commands that write markers to avoid contention. /// In general, developers should limit both TOP and BOP commands to avoid stalling the CP. /// /// \subsection eg1 Example 1: /// /// \code{.cpp} /// // Start of a command buffer /// WriteMarker(TopOfPipe, 1) /// WriteMarker(BottomOfPipe, 2) /// WriteMarker(BottomOfPipe, 3) /// DrawX /// WriteMarker(BottomOfPipe, 4) /// WriteMarker(BottomOfPipe, 5) /// WriteMarker(TopOfPipe, 6) /// // End of command buffer /// \endcode /// /// In the above example, the CP writes markers 1, 2 and 3 without waiting: /// Marker 1 is TOP so it's independent from other commands /// There's no wait for marker 2 and 3 because there are no draws preceding the BOP commands /// Marker 4 is only written once DrawX finishes execution /// Marker 5 doesn't wait for additional draws so it is written right after marker 4 /// Marker 6 can be written as soon as the CP reaches the command. For instance, it is very possible that CP writes marker 6 while DrawX /// is running and therefore marker 6 gets written before markers 4 and 5 /// /// \subsection eg2 Example 2: /// /// \code{.cpp} /// WriteMarker(TopOfPipe, 1) /// DrawX /// WriteMarker(BottomOfPipe, 2) /// WriteMarker(TopOfPipe, 3) /// DrawY /// WriteMarker(BottomOfPipe, 4) /// \endcode /// /// In this example marker 1 is written before the start of DrawX /// Marker 2 is written once DrawX finishes execution /// Similarly marker 3 is written before the start of DrawY /// Marker 4 is written once DrawY finishes execution /// In case of a GPU hang, if markers 1 and 3 are written but markers 2 and 4 are missing we can conclude that: /// The CP has reached both DrawX and DrawY commands since marker 1 and 3 are present /// The fact that marker 2 and 4 are missing means that either DrawX is hanging while DrawY is at the top of the pipe or both DrawX and DrawY /// started and both are simultaneously hanging /// /// \subsection eg3 Example 3: /// /// \code{.cpp} /// // Start of a command buffer /// WriteMarker(BottomOfPipe, 1) /// DrawX /// WriteMarker(BottomOfPipe, 2) /// DrawY /// WriteMarker(BottomOfPipe, 3) /// DrawZ /// WriteMarker(BottomOfPipe, 4) /// // End of command buffer /// \endcode /// /// In this example marker 1 is written before the start of DrawX /// Marker 2 is written once DrawX finishes /// Marker 3 is written once DrawY finishes /// Marker 4 is written once DrawZ finishes /// If the GPU hangs and only marker 1 is written we can conclude that the hang is happening in either DrawX, DrawY or DrawZ /// If the GPU hangs and only marker 1 and 2 are written we can conclude that the hang is happening in DrawY or DrawZ /// If the GPU hangs and only marker 4 is missing we can conclude that the hang is happening in DrawZ /// /// \subsection eg4 Example 4: /// /// \code{.cpp} /// Start of a command buffer /// WriteMarker(TopOfPipe, 1) /// DrawX /// WriteMarker(TopOfPipe, 2) /// DrawY /// WriteMarker(TopOfPipe, 3) /// DrawZ /// // End of command buffer /// \endcode /// /// In this example, in case the GPU hangs and only marker 1 is written we can conclude that the hang is happening in DrawX /// In case the GPU hangs and only marker 1 and 2 are written we can conclude that the hang is happening in DrawX or DrawY /// In case the GPU hangs and all 3 markers are written we can conclude that the hang is happening in any of DrawX, DrawY or DrawZ /// /// \subsection eg5 Example 5: /// /// \code{.cpp} /// DrawX /// WriteMarker(TopOfPipe, 1) /// WriteMarker(BottomOfPipe, 2) /// DrawY /// WriteMarker(TopOfPipe, 3) /// WriteMarker(BottomOfPipe, 4) /// \endcode /// /// Marker 1 is written right after DrawX is queued for execution. /// Marker 2 is only written once DrawX finishes execution. /// Marker 3 is written right after DrawY is queued for execution. /// Marker 4 is only written once DrawY finishes execution /// If marker 1 is written we would know that the CP has reached the command DrawX (DrawX at the top of the pipe). /// If marker 2 is written we can say that DrawX has finished execution (DrawX at the bottom of the pipe). /// In case the GPU hangs and only marker 1 and 3 are written we can conclude that the hang is happening in DrawX or DrawY /// In case the GPU hangs and only marker 1 is written we can conclude that the hang is happening in DrawX /// In case the GPU hangs and only marker 4 is missing we can conclude that the hang is happening in DrawY /// /// \section data Retrieving GPU Data /// /// In the event of a GPU hang, the user can inspect the system memory buffer to determine which draw has caused the hang. /// For example: /// \code{.cpp} /// // Force the work to be flushed to prevent CPU ahead of GPU /// g_pImmediateContext->Flush(); /// /// // Present the information rendered to the back buffer to the front buffer (the screen) /// HRESULT hr = g_pSwapChain->Present( 0, 0 ); /// /// // Read the marker data buffer once detect device lost /// if ( hr != S_OK ) /// { /// for (UINT i = 0; i < g_NumMarkerWritten; i++) /// { /// UINT64* pTempData; /// pTempData = static_cast<UINT64*>(pMarkerBuffer); /// /// // Write the marker data to file /// ofs << i << "\r\n"; /// ofs << std::hex << *(pTempData + i * 2) << "\r\n"; /// ofs << std::hex << *(pTempData + (i * 2 + 1)) << "\r\n"; /// /// WCHAR s1[256]; /// setlocale(LC_NUMERIC, "en_US.iso88591"); /// /// // Output the marker data to console /// swprintf(s1, 256, L" The Draw count is %d; The Top maker is % 016llX and the Bottom marker is % 016llX \r\n", i, *(pTempData + i * 2), *(pTempData + (i * 2 + 1))); /// /// OutputDebugStringW(s1); /// } /// } /// \endcode /// /// The console output would resemble something like: /// \code{.cpp} /// D3D11: Removing Device. /// D3D11 ERROR: ID3D11Device::RemoveDevice: Device removal has been triggered for the following reason (DXGI_ERROR_DEVICE_HUNG: The Device took an unreasonable amount of time to execute its commands, or the hardware crashed/hung. As a result, the TDR (Timeout Detection and Recovery) mechanism has been triggered. The current Device Context was executing commands when the hang occurred. The application may want to respawn and fallback to less aggressive use of the display hardware). [ EXECUTION ERROR #378: DEVICE_REMOVAL_PROCESS_AT_FAULT] /// The Draw count is 0; The Top maker is 00000000DEADCAFE and the Bottom marker is 00000000DEADBEEF /// The Draw count is 1; The Top maker is 00000000DEADCAFE and the Bottom marker is 00000000DEADBEEF /// The Draw count is 2; The Top maker is 00000000DEADCAFE and the Bottom marker is 00000000DEADBEEF /// The Draw count is 3; The Top maker is 00000000DEADCAFE and the Bottom marker is 00000000DEADBEEF /// The Draw count is 4; The Top maker is 00000000DEADCAFE and the Bottom marker is 00000000DEADBEEF /// The Draw count is 5; The Top maker is CDCDCDCDCDCDCDCD and the Bottom marker is CDCDCDCDCDCDCDCD /// The Draw count is 6; The Top maker is CDCDCDCDCDCDCDCD and the Bottom marker is CDCDCDCDCDCDCDCD /// The Draw count is 7; The Top maker is CDCDCDCDCDCDCDCD and the Bottom marker is CDCDCDCDCDCDCDCD /// \endcode /// /// @{ /// The breadcrumb marker struct used by \ref agsDriverExtensionsDX11_WriteBreadcrumb typedef struct AGSBreadcrumbMarker { /// The marker type typedef enum Type { TopOfPipe = 0, ///< Top-of-pipe marker BottomOfPipe = 1 ///< Bottom-of-pipe marker } Type; unsigned long long markerData; ///< The user data to write. Type type; ///< Whether this marker is top or bottom of pipe. unsigned int index; ///< The index of the marker. This should be less than the value specified in \ref AGSDX11ExtensionParams::numBreadcrumbMarkers } AGSBreadcrumbMarker; /// /// Function to write a breadcrumb marker. /// /// This method inserts a write marker operation in the GPU command stream. In the case where the GPU is hanging the write /// command will never be reached and the marker will never get written to memory. /// /// In order to use this function, \ref AGSDX11ExtensionParams::numBreadcrumbMarkers must be set to a non zero value. /// /// \param [in] context Pointer to a context. /// \param [in] marker Pointer to a marker. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_WriteBreadcrumb( AGSContext* context, const AGSBreadcrumbMarker* marker ); /// @} /// \defgroup dx11Topology Extended Topology /// API for primitive topologies /// @{ /// Additional topologies supported via extensions typedef enum AGSPrimitiveTopology { AGS_PRIMITIVE_TOPOLOGY_QUADLIST = 7, ///< Quad list AGS_PRIMITIVE_TOPOLOGY_SCREENRECTLIST = 9 ///< Screen rect list } AGSPrimitiveTopology; /// /// Function used to set the primitive topology. If you are using any of the extended topology types, then this function should /// be called to set ALL topology types. /// /// The Quad List extension is a convenient way to submit quads without using an index buffer. Note that this still submits two triangles at the driver level. /// In order to use this function, AGS must already be initialized and agsDriverExtensionsDX11_Init must have been called successfully. /// /// The Screen Rect extension, which is only available on GCN hardware, allows the user to pass in three of the four corners of a rectangle. /// The hardware then uses the bounding box of the vertices to rasterize the rectangle primitive (i.e. as a rectangle rather than two triangles). /// \note Note that this will not return valid interpolated values, only valid SV_Position values. /// \note If either the Quad List or Screen Rect extension are used, then agsDriverExtensionsDX11_IASetPrimitiveTopology should be called in place of the native DirectX11 equivalent all the time. /// /// \param [in] context Pointer to a context. /// \param [in] topology The topology to set on the D3D11 device. This can be either an AGS-defined topology such as AGS_PRIMITIVE_TOPOLOGY_QUADLIST /// or a standard D3D-defined topology such as D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP. /// NB. the AGS-defined types will require casting to a D3D_PRIMITIVE_TOPOLOGY type. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_IASetPrimitiveTopology( AGSContext* context, D3D_PRIMITIVE_TOPOLOGY topology ); /// @} /// \defgroup dx11UAVOverlap UAV Overlap /// API for enabling overlapping UAV writes /// @{ /// /// Function used indicate to the driver that it doesn't need to sync the UAVs bound for the subsequent set of back-to-back dispatches. /// When calling back-to-back draw calls or dispatch calls that write to the same UAV, the AMD DX11 driver will automatically insert a barrier to ensure there are no write after write (WAW) hazards. /// If the app can guarantee there is no overlap between the writes between these calls, then this extension will remove those barriers allowing the work to run in parallel on the GPU. /// /// Usage would be as follows: /// \code{.cpp} /// m_device->Dispatch( ... ); // First call that writes to the UAV /// /// // Disable automatic WAW syncs /// agsDriverExtensionsDX11_BeginUAVOverlap( m_agsContext ); /// /// // Submit other dispatches that write to the same UAV concurrently /// m_device->Dispatch( ... ); /// m_device->Dispatch( ... ); /// m_device->Dispatch( ... ); /// /// // Reenable automatic WAW syncs /// agsDriverExtensionsDX11_EndUAVOverlap( m_agsContext ); /// \endcode /// /// \param [in] context Pointer to a context. /// \param [in] dxContext Pointer to the DirectX device context. If this is to work using the non-immediate context, then you need to check support. If nullptr is specified, then the immediate context is assumed. /// with the AGS_DX11_EXTENSION_DEFERRED_CONTEXTS bit. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_BeginUAVOverlap( AGSContext* context, ID3D11DeviceContext* dxContext ); /// /// Function used indicate to the driver it can no longer overlap the batch of back-to-back dispatches that has been submitted. /// /// \param [in] context Pointer to a context. /// \param [in] dxContext Pointer to the DirectX device context. If this is to work using the non-immediate context, then you need to check support. If nullptr is specified, then the immediate context is assumed. /// with the AGS_DX11_EXTENSION_DEFERRED_CONTEXTS bit. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_EndUAVOverlap( AGSContext* context, ID3D11DeviceContext* dxContext ); /// @} /// \defgroup dx11DepthBoundsTest Depth Bounds Test /// API for enabling depth bounds testing /// @{ /// /// Function used to set the depth bounds test extension /// /// \param [in] context Pointer to a context /// \param [in] dxContext Pointer to the DirectX device context. If this is to work using the non-immediate context, then you need to check support. If nullptr is specified, then the immediate context is assumed. /// \param [in] enabled Whether to enable or disable the depth bounds testing. If disabled, the next two args are ignored. /// \param [in] minDepth The near depth range to clip against. /// \param [in] maxDepth The far depth range to clip against. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_SetDepthBounds( AGSContext* context, ID3D11DeviceContext* dxContext, bool enabled, float minDepth, float maxDepth ); /// @} /// \defgroup mdi Multi Draw Indirect (MDI) /// API for dispatching multiple instanced draw commands. /// The multi draw indirect extensions allow multiple sets of DrawInstancedIndirect to be submitted in one API call. /// The draw calls are issued on the GPU's command processor (CP), potentially saving the significant CPU overheads incurred by submitting the equivalent draw calls on the CPU. /// /// The extension allows the following code: /// \code{.cpp} /// // Submit n batches of DrawIndirect calls /// for ( int i = 0; i < n; i++ ) /// deviceContext->DrawIndexedInstancedIndirect( buffer, i * sizeof( cmd ) ); /// \endcode /// To be replaced by the following call: /// \code{.cpp} /// // Submit all n batches in one call /// agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect( m_agsContext, deviceContext, n, buffer, 0, sizeof( cmd ) ); /// \endcode /// /// The buffer used for the indirect args must be of the following formats: /// \code{.cpp} /// // Buffer layout for agsDriverExtensions_MultiDrawInstancedIndirect /// struct DrawInstancedIndirectArgs /// { /// UINT VertexCountPerInstance; /// UINT InstanceCount; /// UINT StartVertexLocation; /// UINT StartInstanceLocation; /// }; /// /// // Buffer layout for agsDriverExtensions_MultiDrawIndexedInstancedIndirect /// struct DrawIndexedInstancedIndirectArgs /// { /// UINT IndexCountPerInstance; /// UINT InstanceCount; /// UINT StartIndexLocation; /// UINT BaseVertexLocation; /// UINT StartInstanceLocation; /// }; /// \endcode /// /// Example usage can be seen in AMD's GeometryFX (https://github.com/GPUOpen-Effects/GeometryFX). In particular, in this file: https://github.com/GPUOpen-Effects/GeometryFX/blob/master/amd_geometryfx/src/AMD_GeometryFX_Filtering.cpp /// /// @{ /// /// Function used to submit a batch of draws via MultiDrawIndirect /// /// \param [in] context Pointer to a context. /// \param [in] dxContext Pointer to the DirectX device context. If this is to work using the non-immediate context, then you need to check support. If nullptr is specified, then the immediate context is assumed. /// \param [in] drawCount The number of draws. /// \param [in] pBufferForArgs The args buffer. /// \param [in] alignedByteOffsetForArgs The offset into the args buffer. /// \param [in] byteStrideForArgs The per element stride of the args buffer. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_MultiDrawInstancedIndirect( AGSContext* context, ID3D11DeviceContext* dxContext, unsigned int drawCount, ID3D11Buffer* pBufferForArgs, unsigned int alignedByteOffsetForArgs, unsigned int byteStrideForArgs ); /// /// Function used to submit a batch of draws via MultiDrawIndirect /// /// \param [in] context Pointer to a context. /// \param [in] dxContext Pointer to the DirectX device context. If this is to work using the non-immediate context, then you need to check support. If nullptr is specified, then the immediate context is assumed. /// \param [in] drawCount The number of draws. /// \param [in] pBufferForArgs The args buffer. /// \param [in] alignedByteOffsetForArgs The offset into the args buffer. /// \param [in] byteStrideForArgs The per element stride of the args buffer. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect( AGSContext* context, ID3D11DeviceContext* dxContext, unsigned int drawCount, ID3D11Buffer* pBufferForArgs, unsigned int alignedByteOffsetForArgs, unsigned int byteStrideForArgs ); /// /// Function used to submit a batch of draws via MultiDrawIndirect /// /// \param [in] context Pointer to a context. /// \param [in] dxContext Pointer to the DirectX device context. If this is to work using the non-immediate context, then you need to check support. If nullptr is specified, then the immediate context is assumed. /// \param [in] pBufferForDrawCount The draw count buffer. /// \param [in] alignedByteOffsetForDrawCount The offset into the draw count buffer. /// \param [in] pBufferForArgs The args buffer. /// \param [in] alignedByteOffsetForArgs The offset into the args buffer. /// \param [in] byteStrideForArgs The per element stride of the args buffer. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_MultiDrawInstancedIndirectCountIndirect( AGSContext* context, ID3D11DeviceContext* dxContext, ID3D11Buffer* pBufferForDrawCount, unsigned int alignedByteOffsetForDrawCount, ID3D11Buffer* pBufferForArgs, unsigned int alignedByteOffsetForArgs, unsigned int byteStrideForArgs ); /// /// Function used to submit a batch of draws via MultiDrawIndirect /// /// \param [in] context Pointer to a context. /// \param [in] dxContext Pointer to the DirectX device context. If this is to work using the non-immediate context, then you need to check support. If nullptr is specified, then the immediate context is assumed. /// \param [in] pBufferForDrawCount The draw count buffer. /// \param [in] alignedByteOffsetForDrawCount The offset into the draw count buffer. /// \param [in] pBufferForArgs The args buffer. /// \param [in] alignedByteOffsetForArgs The offset into the args buffer. /// \param [in] byteStrideForArgs The per element stride of the args buffer. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirectCountIndirect( AGSContext* context, ID3D11DeviceContext* dxContext, ID3D11Buffer* pBufferForDrawCount, unsigned int alignedByteOffsetForDrawCount, ID3D11Buffer* pBufferForArgs, unsigned int alignedByteOffsetForArgs, unsigned int byteStrideForArgs ); /// @} /// \defgroup shadercompiler Shader Compiler Controls /// API for controlling DirectX11 shader compilation. /// Check support for this feature using the AGS_DX11_EXTENSION_CREATE_SHADER_CONTROLS bit. /// Supported in Radeon Software Version 16.9.2 (driver version 16.40.2311) onwards. /// @{ /// /// This method can be used to limit the maximum number of threads the driver uses for asynchronous shader compilation. /// Setting it to 0 will disable asynchronous compilation completely and force the shaders to be compiled "inline" on the threads that call Create*Shader. /// /// This method can only be called before any shaders are created and being compiled by the driver. /// If this method is called after shaders have been created the function will return AGS_FAILURE. /// This function only sets an upper limit.The driver may create fewer threads than allowed by this function. /// /// \param [in] context Pointer to a context. /// \param [in] numberOfThreads The maximum number of threads to use. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_SetMaxAsyncCompileThreadCount( AGSContext* context, unsigned int numberOfThreads ); /// /// This method can be used to determine the total number of asynchronous shader compile jobs that are either /// queued for waiting for compilation or being compiled by the driver's asynchronous compilation threads. /// This method can be called at any during the lifetime of the driver. /// /// \param [in] context Pointer to a context. /// \param [out] numberOfJobs Pointer to the number of jobs in flight currently. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_NumPendingAsyncCompileJobs( AGSContext* context, unsigned int* numberOfJobs ); /// /// This method can be used to enable or disable the disk based shader cache. /// Enabling/disabling the disk cache is not supported if is it disabled explicitly via Radeon Settings or by an app profile. /// Calling this method under these conditions will result in AGS_FAILURE being returned. /// It is recommended that this method be called before any shaders are created by the application and being compiled by the driver. /// Doing so at any other time may result in the cache being left in an inconsistent state. /// /// \param [in] context Pointer to a context. /// \param [in] enable Whether to enable the disk cache. 0 to disable, 1 to enable. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_SetDiskShaderCacheEnabled( AGSContext* context, int enable ); /// @} /// \defgroup multiview Multiview /// API for multiview broadcasting. /// Check support for this feature using the AGS_DX11_EXTENSION_MULTIVIEW bit. /// Supported in Radeon Software Version 16.12.1 (driver version 16.50.2001) onwards. /// @{ /// /// Function to control draw calls replication to multiple viewports and RT slices. /// Setting any mask to 0 disables draw replication. /// /// \param [in] context Pointer to a context. /// \param [in] vpMask Viewport control bit mask. /// \param [in] rtSliceMask RT slice control bit mask. /// \param [in] vpMaskPerRtSliceEnabled If 0, 16 lower bits of vpMask apply to all RT slices; if 1 each 16 bits of 64-bit mask apply to corresponding 4 RT slices. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_SetViewBroadcastMasks( AGSContext* context, unsigned long long vpMask, unsigned long long rtSliceMask, int vpMaskPerRtSliceEnabled ); /// /// Function returns max number of supported clip rectangles. /// /// \param [in] context Pointer to a context. /// \param [out] maxRectCount Returned max number of clip rectangles. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_GetMaxClipRects( AGSContext* context, unsigned int* maxRectCount ); /// The clip rectangle struct used by \ref agsDriverExtensionsDX11_SetClipRects typedef struct AGSClipRect { /// The inclusion mode for the rect typedef enum Mode { ClipRectIncluded = 0, ///< Include the rect ClipRectExcluded = 1 ///< Exclude the rect } Mode; Mode mode; ///< Include/exclude rect region AGSRect rect; ///< The rect to include/exclude } AGSClipRect; /// /// Function sets clip rectangles. /// /// \param [in] context Pointer to a context. /// \param [in] clipRectCount Number of specified clip rectangles. Use 0 to disable clip rectangles. /// \param [in] clipRects Array of clip rectangles. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_SetClipRects( AGSContext* context, unsigned int clipRectCount, const AGSClipRect* clipRects ); /// @} /// \defgroup cfxapi Explicit Crossfire API /// API for explicit control over Crossfire /// @{ /// The Crossfire API transfer types typedef enum AGSAfrTransferType { AGS_AFR_TRANSFER_DEFAULT = 0, ///< Default Crossfire driver resource tracking AGS_AFR_TRANSFER_DISABLE = 1, ///< Turn off driver resource tracking AGS_AFR_TRANSFER_1STEP_P2P = 2, ///< App controlled GPU to next GPU transfer AGS_AFR_TRANSFER_2STEP_NO_BROADCAST = 3, ///< App controlled GPU to next GPU transfer using intermediate system memory AGS_AFR_TRANSFER_2STEP_WITH_BROADCAST = 4, ///< App controlled GPU to all render GPUs transfer using intermediate system memory } AGSAfrTransferType; /// The Crossfire API transfer engines typedef enum AGSAfrTransferEngine { AGS_AFR_TRANSFERENGINE_DEFAULT = 0, ///< Use default engine for Crossfire API transfers AGS_AFR_TRANSFERENGINE_3D_ENGINE = 1, ///< Use 3D engine for Crossfire API transfers AGS_AFR_TRANSFERENGINE_COPY_ENGINE = 2, ///< Use Copy engine for Crossfire API transfers } AGSAfrTransferEngine; /// /// Function to create a Direct3D11 resource with the specified AFR transfer type and specified transfer engine. /// /// \param [in] context Pointer to a context. /// \param [in] desc Pointer to the D3D11 resource description. /// \param [in] initialData Optional pointer to the initializing data for the resource. /// \param [out] buffer Returned pointer to the resource. /// \param [in] transferType The transfer behavior. /// \param [in] transferEngine The transfer engine to use. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_CreateBuffer( AGSContext* context, const D3D11_BUFFER_DESC* desc, const D3D11_SUBRESOURCE_DATA* initialData, ID3D11Buffer** buffer, AGSAfrTransferType transferType, AGSAfrTransferEngine transferEngine ); /// /// Function to create a Direct3D11 resource with the specified AFR transfer type and specified transfer engine. /// /// \param [in] context Pointer to a context. /// \param [in] desc Pointer to the D3D11 resource description. /// \param [in] initialData Optional pointer to the initializing data for the resource. /// \param [out] texture1D Returned pointer to the resource. /// \param [in] transferType The transfer behavior. /// \param [in] transferEngine The transfer engine to use. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_CreateTexture1D( AGSContext* context, const D3D11_TEXTURE1D_DESC* desc, const D3D11_SUBRESOURCE_DATA* initialData, ID3D11Texture1D** texture1D, AGSAfrTransferType transferType, AGSAfrTransferEngine transferEngine ); /// /// Function to create a Direct3D11 resource with the specified AFR transfer type and specified transfer engine. /// /// \param [in] context Pointer to a context. /// \param [in] desc Pointer to the D3D11 resource description. /// \param [in] initialData Optional pointer to the initializing data for the resource. /// \param [out] texture2D Returned pointer to the resource. /// \param [in] transferType The transfer behavior. /// \param [in] transferEngine The transfer engine to use. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_CreateTexture2D( AGSContext* context, const D3D11_TEXTURE2D_DESC* desc, const D3D11_SUBRESOURCE_DATA* initialData, ID3D11Texture2D** texture2D, AGSAfrTransferType transferType, AGSAfrTransferEngine transferEngine ); /// /// Function to create a Direct3D11 resource with the specified AFR transfer type and specified transfer engine. /// /// \param [in] context Pointer to a context. /// \param [in] desc Pointer to the D3D11 resource description. /// \param [in] initialData Optional pointer to the initializing data for the resource. /// \param [out] texture3D Returned pointer to the resource. /// \param [in] transferType The transfer behavior. /// \param [in] transferEngine The transfer engine to use. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_CreateTexture3D( AGSContext* context, const D3D11_TEXTURE3D_DESC* desc, const D3D11_SUBRESOURCE_DATA* initialData, ID3D11Texture3D** texture3D, AGSAfrTransferType transferType, AGSAfrTransferEngine transferEngine ); /// /// Function to notify the driver that we have finished writing to the resource this frame. /// This will initiate a transfer for AGS_AFR_TRANSFER_1STEP_P2P, /// AGS_AFR_TRANSFER_2STEP_NO_BROADCAST, and AGS_AFR_TRANSFER_2STEP_WITH_BROADCAST. /// /// \param [in] context Pointer to a context. /// \param [in] resource Pointer to the resource. /// \param [in] transferRegions An array of transfer regions (can be null to specify the whole area). /// \param [in] subresourceArray An array of subresource indices (can be null to specify all subresources). /// \param [in] numSubresources The number of subresources in subresourceArray OR number of transferRegions. Use 0 to specify ALL subresources and one transferRegion (which may be null if specifying the whole area). /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_NotifyResourceEndWrites( AGSContext* context, ID3D11Resource* resource, const D3D11_RECT* transferRegions, const unsigned int* subresourceArray, unsigned int numSubresources ); /// /// This will notify the driver that the app will begin read/write access to the resource. /// /// \param [in] context Pointer to a context. /// \param [in] resource Pointer to the resource. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_NotifyResourceBeginAllAccess( AGSContext* context, ID3D11Resource* resource ); /// /// This is used for AGS_AFR_TRANSFER_1STEP_P2P to notify when it is safe to initiate a transfer. /// This call in frame N-(NumGpus-1) allows a 1 step P2P in frame N to start. /// This should be called after agsDriverExtensionsDX11_NotifyResourceEndWrites. /// /// \param [in] context Pointer to a context. /// \param [in] resource Pointer to the resource. /// AMD_AGS_API AGSReturnCode agsDriverExtensionsDX11_NotifyResourceEndAllAccess( AGSContext* context, ID3D11Resource* resource ); /// @} /// @} /// \defgroup typedefs Function pointer typedefs /// List of function pointer typedefs for the API /// @{ typedef AMD_AGS_API AGSDriverVersionResult (*AGS_CHECKDRIVERVERSION)( const char*, unsigned int ); ///< \ref agsCheckDriverVersion typedef AMD_AGS_API int (*AGS_GETVERSIONNUMBER)(); ///< \ref agsGetVersionNumber typedef AMD_AGS_API AGSReturnCode (*AGS_INITIALIZE)( int, const AGSConfiguration*, AGSContext**, AGSGPUInfo* ); ///< \ref agsInitialize typedef AMD_AGS_API AGSReturnCode (*AGS_DEINITIALIZE)( AGSContext* ); ///< \ref agsDeInitialize typedef AMD_AGS_API AGSReturnCode (*AGS_SETDISPLAYMODE)( AGSContext*, int, int, const AGSDisplaySettings* ); ///< \ref agsSetDisplayMode typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX12_CREATEDEVICE)( AGSContext*, const AGSDX12DeviceCreationParams*, const AGSDX12ExtensionParams*, AGSDX12ReturnedParams* ); ///< \ref agsDriverExtensionsDX12_CreateDevice typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX12_DESTROYDEVICE)( AGSContext*, ID3D12Device*, unsigned int* ); ///< \ref agsDriverExtensionsDX12_DestroyDevice typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX12_PUSHMARKER)( AGSContext*, ID3D12GraphicsCommandList*, const char* ); ///< \ref agsDriverExtensionsDX12_PushMarker typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX12_POPMARKER)( AGSContext*, ID3D12GraphicsCommandList* ); ///< \ref agsDriverExtensionsDX12_PopMarker typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX12_SETMARKER)( AGSContext*, ID3D12GraphicsCommandList*, const char* ); ///< \ref agsDriverExtensionsDX12_SetMarker typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_CREATEDEVICE)( AGSContext*, const AGSDX11DeviceCreationParams*, const AGSDX11ExtensionParams*, AGSDX11ReturnedParams* ); ///< \ref agsDriverExtensionsDX11_CreateDevice typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_DESTROYDEVICE)( AGSContext*, ID3D11Device*, unsigned int*, ID3D11DeviceContext*, unsigned int* ); ///< \ref agsDriverExtensionsDX11_DestroyDevice typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_WRITEBREADCRUMB)( AGSContext*, const AGSBreadcrumbMarker* ); ///< \ref agsDriverExtensionsDX11_WriteBreadcrumb typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_IASETPRIMITIVETOPOLOGY)( AGSContext*, enum D3D_PRIMITIVE_TOPOLOGY ); ///< \ref agsDriverExtensionsDX11_IASetPrimitiveTopology typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_BEGINUAVOVERLAP)( AGSContext*, ID3D11DeviceContext* ); ///< \ref agsDriverExtensionsDX11_BeginUAVOverlap typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_ENDUAVOVERLAP)( AGSContext*, ID3D11DeviceContext* ); ///< \ref agsDriverExtensionsDX11_EndUAVOverlap typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_SETDEPTHBOUNDS)( AGSContext*, ID3D11DeviceContext*, bool, float, float ); ///< \ref agsDriverExtensionsDX11_SetDepthBounds typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_MULTIDRAWINSTANCEDINDIRECT)( AGSContext*, ID3D11DeviceContext*, unsigned int, ID3D11Buffer*, unsigned int, unsigned int ); ///< \ref agsDriverExtensionsDX11_MultiDrawInstancedIndirect typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_MULTIDRAWINDEXEDINSTANCEDINDIRECT)( AGSContext*, ID3D11DeviceContext*, unsigned int, ID3D11Buffer*, unsigned int, unsigned int ); ///< \ref agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirect typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_MULTIDRAWINSTANCEDINDIRECTCOUNTINDIRECT)( AGSContext*, ID3D11DeviceContext*, ID3D11Buffer*, unsigned int, ID3D11Buffer*, unsigned int, unsigned int ); ///< \ref agsDriverExtensionsDX11_MultiDrawInstancedIndirectCountIndirect typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_MULTIDRAWINDEXEDINSTANCEDINDIRECTCOUNTINDIRECT)( AGSContext*, ID3D11DeviceContext*, ID3D11Buffer*, unsigned int, ID3D11Buffer*, unsigned int, unsigned int ); ///< \ref agsDriverExtensionsDX11_MultiDrawIndexedInstancedIndirectCountIndirect typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_SETMAXASYNCCOMPILETHREADCOUNT)( AGSContext*, unsigned int ); ///< \ref agsDriverExtensionsDX11_SetMaxAsyncCompileThreadCount typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_NUMPENDINGASYNCOMPILEJOBS)( AGSContext*, unsigned int* ); ///< \ref agsDriverExtensionsDX11_NumPendingAsyncCompileJobs typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_SETDISKSHADERCACHEENABLED)( AGSContext*, int ); ///< \ref agsDriverExtensionsDX11_SetDiskShaderCacheEnabled typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_SETVIEWBROADCASTMASKS)( AGSContext*, unsigned long long, unsigned long long, int ); ///< \ref agsDriverExtensionsDX11_SetViewBroadcastMasks typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_GETMAXCLIPRECTS)( AGSContext*, unsigned int* ); ///< \ref agsDriverExtensionsDX11_GetMaxClipRects typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_SETCLIPRECTS)( AGSContext*, unsigned int, const AGSClipRect* ); ///< \ref agsDriverExtensionsDX11_SetClipRects typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_CREATEBUFFER)( AGSContext*, const D3D11_BUFFER_DESC*, const D3D11_SUBRESOURCE_DATA*, ID3D11Buffer**, AGSAfrTransferType, AGSAfrTransferEngine ); ///< \ref agsDriverExtensionsDX11_CreateBuffer typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_CREATETEXTURE1D)( AGSContext*, const D3D11_TEXTURE1D_DESC*, const D3D11_SUBRESOURCE_DATA*, ID3D11Texture1D**, AGSAfrTransferType, AGSAfrTransferEngine ); ///< \ref agsDriverExtensionsDX11_CreateTexture1D typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_CREATETEXTURE2D)( AGSContext*, const D3D11_TEXTURE2D_DESC*, const D3D11_SUBRESOURCE_DATA*, ID3D11Texture2D**, AGSAfrTransferType, AGSAfrTransferEngine ); ///< \ref agsDriverExtensionsDX11_CreateTexture2D typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_CREATETEXTURE3D)( AGSContext*, const D3D11_TEXTURE3D_DESC*, const D3D11_SUBRESOURCE_DATA*, ID3D11Texture3D**, AGSAfrTransferType, AGSAfrTransferEngine ); ///< \ref agsDriverExtensionsDX11_CreateTexture3D typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_NOTIFYRESOURCEENDWRITES)( AGSContext*, ID3D11Resource*, const D3D11_RECT*, const unsigned int*, unsigned int ); ///< \ref agsDriverExtensionsDX11_NotifyResourceEndWrites typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_NOTIFYRESOURCEBEGINALLACCESS)( AGSContext*, ID3D11Resource* ); ///< \ref agsDriverExtensionsDX11_NotifyResourceBeginAllAccess typedef AMD_AGS_API AGSReturnCode (*AGS_DRIVEREXTENSIONSDX11_NOTIFYRESOURCEENDALLACCESS)( AGSContext*, ID3D11Resource* ); ///< \ref agsDriverExtensionsDX11_NotifyResourceEndAllAccess /// @} #ifdef __cplusplus } // extern "C" #endif #endif // AMD_AGS_H
moradin/renderdoc
util/test/demos/3rdparty/ags/amd_ags.h
C
mit
87,812
<?php /** * This file is part of the Propel package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License */ namespace Propel\Generator\Platform; use Propel\Generator\Exception\EngineException; use Propel\Generator\Model\Column; use Propel\Generator\Model\Database; use Propel\Generator\Model\Diff\TableDiff; use Propel\Generator\Model\Domain; use Propel\Generator\Model\Index; use Propel\Generator\Model\IdMethod; use Propel\Generator\Model\PropelTypes; use Propel\Generator\Model\Table; use Propel\Generator\Model\Unique; use Propel\Generator\Model\Diff\ColumnDiff; /** * Postgresql PlatformInterface implementation. * * @author Hans Lellelid <hans@xmpl.org> (Propel) * @author Martin Poeschl <mpoeschl@marmot.at> (Torque) * @author Niklas Närhinen <niklas@narhinen.net> */ class PgsqlPlatform extends DefaultPlatform { /** * @var string */ protected $createOrDropSequences = ''; /** * Initializes db specific domain mapping. */ protected function initialize() { parent::initialize(); $this->setSchemaDomainMapping(new Domain(PropelTypes::BOOLEAN, 'BOOLEAN')); $this->setSchemaDomainMapping(new Domain(PropelTypes::TINYINT, 'INT2')); $this->setSchemaDomainMapping(new Domain(PropelTypes::SMALLINT, 'INT2')); $this->setSchemaDomainMapping(new Domain(PropelTypes::BIGINT, 'INT8')); //$this->setSchemaDomainMapping(new Domain(PropelTypes::REAL, 'FLOAT')); $this->setSchemaDomainMapping(new Domain(PropelTypes::DOUBLE, 'DOUBLE PRECISION')); $this->setSchemaDomainMapping(new Domain(PropelTypes::FLOAT, 'DOUBLE PRECISION')); $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, 'TEXT')); $this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, 'BYTEA')); $this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, 'BYTEA')); $this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, 'BYTEA')); $this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, 'BYTEA')); $this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, 'TEXT')); $this->setSchemaDomainMapping(new Domain(PropelTypes::OBJECT, 'BYTEA')); $this->setSchemaDomainMapping(new Domain(PropelTypes::PHP_ARRAY, 'TEXT')); $this->setSchemaDomainMapping(new Domain(PropelTypes::ENUM, 'INT2')); $this->setSchemaDomainMapping(new Domain(PropelTypes::DECIMAL, 'NUMERIC')); } public function getNativeIdMethod() { return PlatformInterface::SERIAL; } public function getAutoIncrement() { return ''; } public function getDefaultTypeSizes() { return array( 'char' => 1, 'character' => 1, 'integer' => 32, 'bigint' => 64, 'smallint' => 16, 'double precision' => 54 ); } public function getMaxColumnNameLength() { return 63; } public function getBooleanString($b) { // parent method does the checking for allows string // representations & returns integer $b = parent::getBooleanString($b); return ($b ? "'t'" : "'f'"); } public function supportsNativeDeleteTrigger() { return true; } /** * Override to provide sequence names that conform to postgres' standard when * no id-method-parameter specified. * * @param Table $table * * @return string */ public function getSequenceName(Table $table) { $result = null; if ($table->getIdMethod() == IdMethod::NATIVE) { $idMethodParams = $table->getIdMethodParameters(); if (empty($idMethodParams)) { $result = null; // We're going to ignore a check for max length (mainly // because I'm not sure how Postgres would handle this w/ SERIAL anyway) foreach ($table->getColumns() as $col) { if ($col->isAutoIncrement()) { $result = $table->getName() . '_' . $col->getName() . '_seq'; break; // there's only one auto-increment column allowed } } } else { $result = $idMethodParams[0]->getValue(); } } return $result; } protected function getAddSequenceDDL(Table $table) { if ($table->getIdMethod() == IdMethod::NATIVE && $table->getIdMethodParameters() != null) { $pattern = " CREATE SEQUENCE %s; "; return sprintf($pattern, $this->quoteIdentifier(strtolower($this->getSequenceName($table))) ); } } protected function getDropSequenceDDL(Table $table) { if ($table->getIdMethod() == IdMethod::NATIVE && $table->getIdMethodParameters() != null) { $pattern = " DROP SEQUENCE %s; "; return sprintf($pattern, $this->quoteIdentifier(strtolower($this->getSequenceName($table))) ); } } public function getAddSchemasDDL(Database $database) { $ret = ''; $schemas = array(); foreach ($database->getTables() as $table) { $vi = $table->getVendorInfoForType('pgsql'); if ($vi->hasParameter('schema') && !isset($schemas[$vi->getParameter('schema')])) { $schemas[$vi->getParameter('schema')] = true; $ret .= $this->getAddSchemaDDL($table); } } return $ret; } public function getAddSchemaDDL(Table $table) { $vi = $table->getVendorInfoForType('pgsql'); if ($vi->hasParameter('schema')) { $pattern = " CREATE SCHEMA %s; "; return sprintf($pattern, $this->quoteIdentifier($vi->getParameter('schema'))); }; } public function getUseSchemaDDL(Table $table) { $vi = $table->getVendorInfoForType('pgsql'); if ($vi->hasParameter('schema')) { $pattern = " SET search_path TO %s; "; return sprintf($pattern, $this->quoteIdentifier($vi->getParameter('schema'))); } } public function getResetSchemaDDL(Table $table) { $vi = $table->getVendorInfoForType('pgsql'); if ($vi->hasParameter('schema')) { return " SET search_path TO public; "; } } public function getAddTablesDDL(Database $database) { $ret = $this->getBeginDDL(); $ret .= $this->getAddSchemasDDL($database); foreach ($database->getTablesForSql() as $table) { $this->normalizeTable($table); } foreach ($database->getTablesForSql() as $table) { $ret .= $this->getCommentBlockDDL($table->getName()); $ret .= $this->getDropTableDDL($table); $ret .= $this->getAddTableDDL($table); $ret .= $this->getAddIndicesDDL($table); } foreach ($database->getTablesForSql() as $table) { $ret .= $this->getAddForeignKeysDDL($table); } $ret .= $this->getEndDDL(); return $ret; } /** * {@inheritDoc} */ public function getAddForeignKeysDDL(Table $table) { $ret = ''; foreach ($table->getForeignKeys() as $fk) { $ret .= $this->getAddForeignKeyDDL($fk); } return $ret; } public function getAddTableDDL(Table $table) { $ret = ''; $ret .= $this->getUseSchemaDDL($table); $ret .= $this->getAddSequenceDDL($table); $lines = array(); foreach ($table->getColumns() as $column) { $lines[] = $this->getColumnDDL($column); } if ($table->hasPrimaryKey()) { $lines[] = $this->getPrimaryKeyDDL($table); } foreach ($table->getUnices() as $unique) { $lines[] = $this->getUniqueDDL($unique); } $sep = ", "; $pattern = " CREATE TABLE %s ( %s ); "; $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), implode($sep, $lines) ); if ($table->hasDescription()) { $pattern = " COMMENT ON TABLE %s IS %s; "; $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $this->quote($table->getDescription()) ); } $ret .= $this->getAddColumnsComments($table); $ret .= $this->getResetSchemaDDL($table); return $ret; } protected function getAddColumnsComments(Table $table) { $ret = ''; foreach ($table->getColumns() as $column) { $ret .= $this->getAddColumnComment($column); } return $ret; } protected function getAddColumnComment(Column $column) { $pattern = " COMMENT ON COLUMN %s.%s IS %s; "; if ($description = $column->getDescription()) { return sprintf($pattern, $this->quoteIdentifier($column->getTable()->getName()), $this->quoteIdentifier($column->getName()), $this->quote($description) ); } } public function getDropTableDDL(Table $table) { $ret = ''; $ret .= $this->getUseSchemaDDL($table); $pattern = " DROP TABLE IF EXISTS %s CASCADE; "; $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName())); $ret .= $this->getDropSequenceDDL($table); $ret .= $this->getResetSchemaDDL($table); return $ret; } public function getPrimaryKeyName(Table $table) { $tableName = $table->getCommonName(); return $tableName . '_pkey'; } public function getColumnDDL(Column $col) { $domain = $col->getDomain(); $ddl = array($this->quoteIdentifier($col->getName())); $sqlType = $domain->getSqlType(); $table = $col->getTable(); if ($col->isAutoIncrement() && $table && $table->getIdMethodParameters() == null) { $sqlType = $col->getType() === PropelTypes::BIGINT ? 'bigserial' : 'serial'; } if ($this->hasSize($sqlType) && $col->isDefaultSqlType($this)) { if ($this->isNumber($sqlType)) { if ('NUMERIC' === strtoupper($sqlType)) { $ddl[] = $sqlType . $col->getSizeDefinition(); } else { $ddl[] = $sqlType; } } else { $ddl[] = $sqlType . $col->getSizeDefinition(); } } else { $ddl[] = $sqlType; } if ($default = $this->getColumnDefaultValueDDL($col)) { $ddl[] = $default; } if ($notNull = $this->getNullString($col->isNotNull())) { $ddl[] = $notNull; } if ($autoIncrement = $col->getAutoIncrementString()) { $ddl[] = $autoIncrement; } return implode(' ', $ddl); } public function getUniqueDDL(Unique $unique) { return sprintf('CONSTRAINT %s UNIQUE (%s)', $this->quoteIdentifier($unique->getName()), $this->getColumnListDDL($unique->getColumnObjects()) ); } public function getRenameTableDDL($fromTableName, $toTableName) { if (false !== ($pos = strpos($toTableName, '.'))) { $toTableName = substr($toTableName, $pos + 1); } $pattern = " ALTER TABLE %s RENAME TO %s; "; return sprintf($pattern, $this->quoteIdentifier($fromTableName), $this->quoteIdentifier($toTableName) ); } /** * @see Platform::supportsSchemas() */ public function supportsSchemas() { return true; } public function hasSize($sqlType) { return !in_array($sqlType, array('BYTEA', 'TEXT', 'DOUBLE PRECISION')); } public function hasStreamBlobImpl() { return true; } public function supportsVarcharWithoutSize() { return true; } public function getModifyTableDDL(TableDiff $tableDiff) { $ret = parent::getModifyTableDDL($tableDiff); if ($this->createOrDropSequences) { $ret = $this->createOrDropSequences . $ret; } $this->createOrDropSequences = ''; return $ret; } /** * Overrides the implementation from DefaultPlatform * * @author Niklas Närhinen <niklas@narhinen.net> * @return string * @see DefaultPlatform::getModifyColumnDDL */ public function getModifyColumnDDL(ColumnDiff $columnDiff) { $ret = ''; $changedProperties = $columnDiff->getChangedProperties(); $fromColumn = $columnDiff->getFromColumn(); $toColumn = clone $columnDiff->getToColumn(); $fromTable = $fromColumn->getTable(); $table = $toColumn->getTable(); $colName = $this->quoteIdentifier($toColumn->getName()); $pattern = " ALTER TABLE %s ALTER COLUMN %s; "; if (isset($changedProperties['autoIncrement'])) { $tableName = $table->getName(); $colPlainName = $toColumn->getName(); $seqName = "{$tableName}_{$colPlainName}_seq"; if ($toColumn->isAutoIncrement() && $table && $table->getIdMethodParameters() == null) { $defaultValue = "nextval('$seqName'::regclass)"; $toColumn->setDefaultValue($defaultValue); $changedProperties['defaultValueValue'] = [null, $defaultValue]; //add sequence if (!$fromTable->getDatabase()->hasSequence($seqName)) { $this->createOrDropSequences .= sprintf(" CREATE SEQUENCE %s; ", $seqName ); $fromTable->getDatabase()->addSequence($seqName); } } if (!$toColumn->isAutoIncrement() && $fromColumn->isAutoIncrement()) { $changedProperties['defaultValueValue'] = [$fromColumn->getDefaultValueString(), null]; $toColumn->setDefaultValue(null); //remove sequence if ($fromTable->getDatabase()->hasSequence($seqName)) { $this->createOrDropSequences .= sprintf(" DROP SEQUENCE %s CASCADE; ", $seqName ); $fromTable->getDatabase()->removeSequence($seqName); } } } if (isset($changedProperties['size']) || isset($changedProperties['type']) || isset($changedProperties['scale'])) { $sqlType = $toColumn->getDomain()->getSqlType(); if ($this->hasSize($sqlType) && $toColumn->isDefaultSqlType($this)) { if ($this->isNumber($sqlType)) { if ('NUMERIC' === strtoupper($sqlType)) { $sqlType .= $toColumn->getSizeDefinition(); } } else { $sqlType .= $toColumn->getSizeDefinition(); } } if ($using = $this->getUsingCast($fromColumn, $toColumn)) { $sqlType .= $using; } $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . ' TYPE ' . $sqlType ); } if (isset($changedProperties['defaultValueValue'])) { $property = $changedProperties['defaultValueValue']; if ($property[0] !== null && $property[1] === null) { $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . ' DROP DEFAULT'); } else { $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . ' SET ' . $this->getColumnDefaultValueDDL($toColumn)); } } if (isset($changedProperties['notNull'])) { $property = $changedProperties['notNull']; $notNull = ' DROP NOT NULL'; if ($property[1]) { $notNull = ' SET NOT NULL'; } $ret .= sprintf($pattern, $this->quoteIdentifier($table->getName()), $colName . $notNull); } return $ret; } public function isString($type) { $strings = ['VARCHAR']; return in_array(strtoupper($type), $strings); } public function isNumber($type) { $numbers = ['INTEGER', 'INT4', 'INT2', 'NUMBER', 'NUMERIC', 'SMALLINT', 'BIGINT', 'DECICAML', 'REAL', 'DOUBLE PRECISION', 'SERIAL', 'BIGSERIAL']; return in_array(strtoupper($type), $numbers); } public function getUsingCast(Column $fromColumn, Column $toColumn) { $fromSqlType = strtoupper($fromColumn->getDomain()->getSqlType()); $toSqlType = strtoupper($toColumn->getDomain()->getSqlType()); $name = $fromColumn->getName(); if ($this->isNumber($fromSqlType) && $this->isString($toSqlType)) { //cast from int to string return ' '; } if ($this->isString($fromSqlType) && $this->isNumber($toSqlType)) { //cast from string to int return " USING CASE WHEN trim($name) SIMILAR TO '[0-9]+' THEN CAST(trim($name) AS integer) ELSE NULL END"; } if ($this->isNumber($fromSqlType) && 'BYTEA' === $toSqlType) { return " USING decode(CAST($name as text), 'escape')"; } if ('DATE' === $fromSqlType && 'TIME' === $toSqlType) { return " USING NULL"; } if ($this->isNumber($fromSqlType) && $this->isNumber($toSqlType)) { return ''; } if ($this->isString($fromSqlType) && $this->isString($toSqlType)) { return ''; } return " USING NULL"; } /** * Overrides the implementation from DefaultPlatform * * @author Niklas Närhinen <niklas@narhinen.net> * @return string * @see DefaultPlatform::getModifyColumnsDDL */ public function getModifyColumnsDDL($columnDiffs) { $ret = ''; foreach ($columnDiffs as $columnDiff) { $ret .= $this->getModifyColumnDDL($columnDiff); } return $ret; } /** * Overrides the implementation from DefaultPlatform * * @author Niklas Närhinen <niklas@narhinen.net> * @return string * @see DefaultPlatform::getAddColumnsDLL */ public function getAddColumnsDDL($columns) { $ret = ''; foreach ($columns as $column) { $ret .= $this->getAddColumnDDL($column); } return $ret; } /** * Overrides the implementation from DefaultPlatform * * @author Niklas Närhinen <niklas@narhinen.net> * @return string * @see DefaultPlatform::getDropIndexDDL */ public function getDropIndexDDL(Index $index) { if ($index instanceof Unique) { $pattern = " ALTER TABLE %s DROP CONSTRAINT %s; "; return sprintf($pattern, $this->quoteIdentifier($index->getTable()->getName()), $this->quoteIdentifier($index->getName()) ); } else { return parent::getDropIndexDDL($index); } } /** * Get the PHP snippet for getting a Pk from the database. * Warning: duplicates logic from PgsqlAdapter::getId(). * Any code modification here must be ported there. */ public function getIdentifierPhp($columnValueMutator, $connectionVariableName = '$con', $sequenceName = '', $tab = " ") { if (!$sequenceName) { throw new EngineException('PostgreSQL needs a sequence name to fetch primary keys'); } $snippet = " \$dataFetcher = %s->query(\"SELECT nextval('%s')\"); %s = \$dataFetcher->fetchColumn();"; $script = sprintf($snippet, $connectionVariableName, $sequenceName, $columnValueMutator ); return preg_replace('/^/m', $tab, $script); } }
david0/Propel2
src/Propel/Generator/Platform/PgsqlPlatform.php
PHP
mit
20,351
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """GYP backend that generates Eclipse CDT settings files. This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML files that can be imported into an Eclipse CDT project. The XML file contains a list of include paths and symbols (i.e. defines). Because a full .cproject definition is not created by this generator, it's not possible to properly define the include dirs and symbols for each file individually. Instead, one set of includes/symbols is generated for the entire project. This works fairly well (and is a vast improvement in general), but may still result in a few indexer issues here and there. This generator has no automated tests, so expect it to be broken. """ from xml.sax.saxutils import escape import os.path import subprocess import gyp import gyp.common import gyp.msvs_emulation import shlex import xml.etree.cElementTree as ET generator_wants_static_library_dependencies_adjusted = False generator_default_variables = { } for dirname in ['INTERMEDIATE_DIR', 'PRODUCT_DIR', 'LIB_DIR', 'SHARED_LIB_DIR']: # Some gyp steps fail if these are empty(!), so we convert them to variables generator_default_variables[dirname] = '$' + dirname for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', 'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX', 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX', 'CONFIGURATION_NAME']: generator_default_variables[unused] = '' # Include dirs will occasionally use the SHARED_INTERMEDIATE_DIR variable as # part of the path when dealing with generated headers. This value will be # replaced dynamically for each configuration. generator_default_variables['SHARED_INTERMEDIATE_DIR'] = \ '$SHARED_INTERMEDIATE_DIR' def CalculateVariables(default_variables, params): generator_flags = params.get('generator_flags', {}) for key, val in generator_flags.items(): default_variables.setdefault(key, val) flavor = gyp.common.GetFlavor(params) default_variables.setdefault('OS', flavor) if flavor == 'win': # Copy additional generator configuration data from VS, which is shared # by the Eclipse generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True def GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options. """ gyp_includes_set = set() compiler_includes_list = [] # Find compiler's default include dirs. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-xc++', '-v', '-']) proc = subprocess.Popen(args=command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate()[1] # Extract the list of include dirs from the output, which has this format: # ... # #include "..." search starts here: # #include <...> search starts here: # /usr/include/c++/4.6 # /usr/local/include # End of search list. # ... in_include_list = False for line in output.splitlines(): if line.startswith('#include'): in_include_list = True continue if line.startswith('End of search list.'): break if in_include_list: include_dir = line.strip() if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if config_name in target['configurations']: config = target['configurations'][config_name] # Look for any include dirs that were explicitly added via cflags. This # may be done in gyp files to force certain includes to come at the end. # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and # remove this. if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) cflags = msvs_settings.GetCflags(config_name) else: cflags = config['cflags'] for cflag in cflags: if cflag.startswith('-I'): include_dir = cflag[2:] if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) # Find standard gyp include dirs. if config.has_key('include_dirs'): include_dirs = config['include_dirs'] for shared_intermediate_dir in shared_intermediate_dirs: for include_dir in include_dirs: include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR', shared_intermediate_dir) if not os.path.isabs(include_dir): base_dir = os.path.dirname(target_name) include_dir = base_dir + '/' + include_dir include_dir = os.path.abspath(include_dir) gyp_includes_set.add(include_dir) # Generate a list that has all the include dirs. all_includes_list = list(gyp_includes_set) all_includes_list.sort() for compiler_include in compiler_includes_list: if not compiler_include in gyp_includes_set: all_includes_list.append(compiler_include) # All done. return all_includes_list def GetCompilerPath(target_list, data, options): """Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variable. """ # First, see if the compiler is configured in make's settings. build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_dict = data[build_file].get('make_global_settings', {}) for key, value in make_global_settings_dict: if key in ['CC', 'CXX']: return os.path.join(options.toplevel_dir, value) # Check to see if the compiler was specified as an environment variable. for key in ['CC_target', 'CC', 'CXX']: compiler = os.environ.get(key) if compiler: return compiler return 'gcc' def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path): """Calculate the defines for a project. Returns: A dict that includes explict defines declared in gyp files along with all of the default defines that the compiler uses. """ # Get defines declared in the gyp files. all_defines = {} flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) extra_defines = msvs_settings.GetComputedDefines(config_name) else: extra_defines = [] if config_name in target['configurations']: config = target['configurations'][config_name] target_defines = config['defines'] else: target_defines = [] for define in target_defines + extra_defines: split_define = define.split('=', 1) if len(split_define) == 1: split_define.append('1') if split_define[0].strip() in all_defines: # Already defined continue all_defines[split_define[0].strip()] = split_define[1].strip() # Get default compiler defines (if possible). if flavor == 'win': return all_defines # Default defines already processed in the loop above. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-dM', '-']) cpp_proc = subprocess.Popen(args=command, cwd='.', stdin=subprocess.PIPE, stdout=subprocess.PIPE) cpp_output = cpp_proc.communicate()[0] cpp_lines = cpp_output.split('\n') for cpp_line in cpp_lines: if not cpp_line.strip(): continue cpp_line_parts = cpp_line.split(' ', 2) key = cpp_line_parts[1] if len(cpp_line_parts) >= 3: val = cpp_line_parts[2] else: val = '1' all_defines[key] = val return all_defines def WriteIncludePaths(out, eclipse_langs, include_dirs): """Write the includes section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.IncludePaths">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclipse_langs: out.write(' <language name="%s">\n' % lang) for include_dir in include_dirs: out.write(' <includepath workspace_path="false">%s</includepath>\n' % include_dir) out.write(' </language>\n') out.write(' </section>\n') def WriteMacros(out, eclipse_langs, defines): """Write the macros section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.Macros">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclipse_langs: out.write(' <language name="%s">\n' % lang) for key in sorted(defines.iterkeys()): out.write(' <macro><name>%s</name><value>%s</value></macro>\n' % (escape(key), escape(defines[key]))) out.write(' </language>\n') out.write(' </section>\n') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params['options'] generator_flags = params.get('generator_flags', {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.join(generator_flags.get('output_dir', 'out'), config_name) toplevel_build = os.path.join(options.toplevel_dir, build_dir) # Ninja uses out/Debug/gen while make uses out/Debug/obj/gen as the # SHARED_INTERMEDIATE_DIR. Include both possible locations. shared_intermediate_dirs = [os.path.join(toplevel_build, 'obj', 'gen'), os.path.join(toplevel_build, 'gen')] GenerateCdtSettingsFile(target_list, target_dicts, data, params, config_name, os.path.join(toplevel_build, 'eclipse-cdt-settings.xml'), options, shared_intermediate_dirs) GenerateClasspathFile(target_list, target_dicts, options.toplevel_dir, toplevel_build, os.path.join(toplevel_build, 'eclipse-classpath.xml')) def GenerateCdtSettingsFile(target_list, target_dicts, data, params, config_name, out_name, options, shared_intermediate_dirs): gyp.common.EnsureDirExists(out_name) with open(out_name, 'w') as out: out.write('<?xml version="1.0" encoding="UTF-8"?>\n') out.write('<cdtprojectproperties>\n') eclipse_langs = ['C++ Source File', 'C Source File', 'Assembly Source File', 'GNU C++', 'GNU C', 'Assembly'] compiler_path = GetCompilerPath(target_list, data, options) include_dirs = GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path) WriteIncludePaths(out, eclipse_langs, include_dirs) defines = GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path) WriteMacros(out, eclipse_langs, defines) out.write('</cdtprojectproperties>\n') def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.common.EnsureDirExists(out_name) result = ET.Element('classpath') def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, 'classpathentry') entry_element.set('kind', kind) entry_element.set('path', path) AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER']) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')]) ET.ElementTree(result).write(out_name) def GetJavaJars(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all .jars used as inputs.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if os.path.splitext(input_)[1] == '.jar' and not input_.startswith('$'): if os.path.isabs(input_): yield input_ else: yield os.path.join(os.path.dirname(target_name), input_) def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all likely java package root directories.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if (os.path.splitext(input_)[1] == '.java' and not input_.startswith('$')): dir_ = os.path.dirname(os.path.join(os.path.dirname(target_name), input_)) # If there is a parent 'src' or 'java' folder, navigate up to it - # these are canonical package root names in Chromium. This will # break if 'src' or 'java' exists in the package structure. This # could be further improved by inspecting the java file for the # package name if this proves to be too fragile in practice. parent_search = dir_ while os.path.basename(parent_search) not in ['src', 'java']: parent_search, _ = os.path.split(parent_search) if not parent_search or parent_search == toplevel_dir: # Didn't find a known root, just return the original path yield dir_ break else: yield parent_search def GenerateOutput(target_list, target_dicts, data, params): """Generate an XML settings file that can be imported into a CDT project.""" if params['options'].generator_output: raise NotImplementedError("--generator_output not implemented for eclipse") user_config = params.get('generator_flags', {}).get('config', None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
jamfang/Agora-WebRTC-Live-Broadcasting-Demo
node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py
Python
mit
17,013
//===--- llvm/Support/DataStream.cpp - Lazy streamed data -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements DataStreamer, which fetches bytes of Data from // a stream source. It provides support for streaming (lazy reading) of // bitcode. An example implementation of streaming from a file or stdin // is included. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "Data-stream" #include "llvm/Support/DataStream.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Program.h" #include "llvm/Support/system_error.h" #include <cerrno> #include <cstdio> #include <string> #if !defined(_MSC_VER) && !defined(__MINGW32__) #include <unistd.h> #else #include <io.h> #endif #include <fcntl.h> using namespace llvm; // Interface goals: // * StreamableMemoryObject doesn't care about complexities like using // threads/async callbacks to actually overlap download+compile // * Don't want to duplicate Data in memory // * Don't need to know total Data len in advance // Non-goals: // StreamableMemoryObject already has random access so this interface only does // in-order streaming (no arbitrary seeking, else we'd have to buffer all the // Data here in addition to MemoryObject). This also means that if we want // to be able to to free Data, BitstreamBytes/BitcodeReader will implement it STATISTIC(NumStreamFetches, "Number of calls to Data stream fetch"); namespace llvm { DataStreamer::~DataStreamer() {} } namespace { // Very simple stream backed by a file. Mostly useful for stdin and debugging; // actual file access is probably still best done with mmap. class DataFileStreamer : public DataStreamer { int Fd; public: DataFileStreamer() : Fd(0) {} virtual ~DataFileStreamer() { close(Fd); } virtual size_t GetBytes(unsigned char *buf, size_t len) LLVM_OVERRIDE { NumStreamFetches++; return read(Fd, buf, len); } error_code OpenFile(const std::string &Filename) { if (Filename == "-") { Fd = 0; sys::Program::ChangeStdinToBinary(); return error_code::success(); } int OpenFlags = O_RDONLY; #ifdef O_BINARY OpenFlags |= O_BINARY; // Open input file in binary mode on win32. #endif Fd = ::open(Filename.c_str(), OpenFlags); if (Fd == -1) return error_code(errno, posix_category()); return error_code::success(); } }; } namespace llvm { DataStreamer *getDataFileStreamer(const std::string &Filename, std::string *StrError) { DataFileStreamer *s = new DataFileStreamer(); if (error_code e = s->OpenFile(Filename)) { *StrError = std::string("Could not open ") + Filename + ": " + e.message() + "\n"; return NULL; } return s; } }
dbrumley/recfi
llvm-3.3/lib/Support/DataStream.cpp
C++
mit
2,995
package org.knowm.xchange.bitmarket.dto.trade; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author kfonal */ public class BitMarketHistoryOperation { private final long id; private final BigDecimal amount; private final String currency; private final long time; private final BigDecimal rate; private final BigDecimal commission; private final String type; /** * Constructor * * @param id * @param amount * @param currency * @param time * @param rate * @param commission * @param type */ public BitMarketHistoryOperation(@JsonProperty("id") long id, @JsonProperty("amount") BigDecimal amount, @JsonProperty("currency") String currency, @JsonProperty("time") long time, @JsonProperty("rate") BigDecimal rate, @JsonProperty("commission") BigDecimal commission, @JsonProperty("type") String type) { this.id = id; this.amount = amount; this.currency = currency; this.time = time; this.rate = rate; this.commission = commission; this.type = type; } public long getId() { return id; } public BigDecimal getAmount() { return amount; } public String getCurrency() { return currency; } public long getTime() { return time; } public BigDecimal getRate() { return rate; } public BigDecimal getCommission() { return commission; } public String getType() { return type; } }
dozd/XChange
xchange-bitmarket/src/main/java/org/knowm/xchange/bitmarket/dto/trade/BitMarketHistoryOperation.java
Java
mit
1,467
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.AI.MetricsAdvisor.Models { public partial class TopNGroupScope : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("top"); writer.WriteNumberValue(Top); writer.WritePropertyName("period"); writer.WriteNumberValue(Period); writer.WritePropertyName("minTopCount"); writer.WriteNumberValue(MinimumTopCount); writer.WriteEndObject(); } internal static TopNGroupScope DeserializeTopNGroupScope(JsonElement element) { int top = default; int period = default; int minTopCount = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("top")) { top = property.Value.GetInt32(); continue; } if (property.NameEquals("period")) { period = property.Value.GetInt32(); continue; } if (property.NameEquals("minTopCount")) { minTopCount = property.Value.GetInt32(); continue; } } return new TopNGroupScope(top, period, minTopCount); } } }
jackmagic313/azure-sdk-for-net
sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Generated/Models/TopNGroupScope.Serialization.cs
C#
mit
1,640
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // Import zero symbols from zone.js. This causes the zone ambient type to be // added to the type-checker, without emitting any runtime module load statement import {} from 'zone.js'; // TODO(jteplitz602): Load WorkerGlobalScope from lib.webworker.d.ts file #3492 declare var WorkerGlobalScope: any /** TODO #9100 */; // CommonJS / Node have global context exposed as "global" variable. // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake // the global "global" var for now. declare var global: any /** TODO #9100 */; const __window = typeof window !== 'undefined' && window; const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope && self; const __global = typeof global !== 'undefined' && global; const _global: {[name: string]: any} = __window || __global || __self; /** * Attention: whenever providing a new value, be sure to add an * entry into the corresponding `....externs.js` file, * so that closure won't use that global for its purposes. */ export {_global as global}; // When Symbol.iterator doesn't exist, retrieves the key used in es6-shim declare const Symbol: any; let _symbolIterator: any = null; export function getSymbolIterator(): string|symbol { if (!_symbolIterator) { const Symbol = _global['Symbol']; if (Symbol && Symbol.iterator) { _symbolIterator = Symbol.iterator; } else { // es6-shim specific logic const keys = Object.getOwnPropertyNames(Map.prototype); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (key !== 'entries' && key !== 'size' && (Map as any).prototype[key] === Map.prototype['entries']) { _symbolIterator = key; } } } } return _symbolIterator; } export function scheduleMicroTask(fn: Function) { Zone.current.scheduleMicroTask('scheduleMicrotask', fn); } // JS has NaN !== NaN export function looseIdentical(a: any, b: any): boolean { return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b); } export function stringify(token: any): string { if (typeof token === 'string') { return token; } if (token instanceof Array) { return '[' + token.map(stringify).join(', ') + ']'; } if (token == null) { return '' + token; } if (token.overriddenName) { return `${token.overriddenName}`; } if (token.name) { return `${token.name}`; } const res = token.toString(); if (res == null) { return '' + res; } const newLineIndex = res.indexOf('\n'); return newLineIndex === -1 ? res : res.substring(0, newLineIndex); }
aboveyou00/angular
packages/core/src/util.ts
TypeScript
mit
2,885
export const a = 1; export const b = 2; export default 42;
corneliusweig/rollup
test/form/samples/export-all-from-internal/internal.js
JavaScript
mit
59
#! /usr/bin/env ruby # # check-autoscaling-cpucredits # # DESCRIPTION: # Check AutoScaling CPU Credits through CloudWatch API. # # OUTPUT: # plain-text # # PLATFORMS: # Linux # # DEPENDENCIES: # gem: aws-sdk # gem: sensu-plugin # # USAGE: # ./check-autoscaling-cpucredits.rb -r ${your_region} --warning-under 100 --critical-under 50 # # NOTES: # Based heavily on Yohei Kawahara's check-ec2-network # # LICENSE: # Gavin Hamill <gavin@bashton.com> # Released under the same terms as Sensu (the MIT license); see LICENSE # for details. # require 'sensu-plugin/check/cli' require 'aws-sdk' class CheckEc2CpuCredits < Sensu::Plugin::Check::CLI option :aws_access_key, short: '-a AWS_ACCESS_KEY', long: '--aws-access-key AWS_ACCESS_KEY', description: "AWS Access Key. Either set ENV['AWS_ACCESS_KEY'] or provide it as an option", default: ENV['AWS_ACCESS_KEY'] option :aws_secret_access_key, short: '-k AWS_SECRET_KEY', long: '--aws-secret-access-key AWS_SECRET_KEY', description: "AWS Secret Access Key. Either set ENV['AWS_SECRET_KEY'] or provide it as an option", default: ENV['AWS_SECRET_KEY'] option :aws_region, short: '-r AWS_REGION', long: '--aws-region REGION', description: 'AWS Region (defaults to us-east-1).', default: 'us-east-1' option :group, short: '-g G', long: '--autoscaling-group GROUP', description: 'AutoScaling group to check' option :end_time, short: '-t T', long: '--end-time TIME', default: Time.now, description: 'CloudWatch metric statistics end time' option :period, short: '-p N', long: '--period SECONDS', default: 60, description: 'CloudWatch metric statistics period' option :countmetric, short: '-d M', long: '--countmetric METRIC', default: 'CPUCreditBalance', description: 'Select any CloudWatch _Count_ based metric (Status Checks / CPU Credits)' option :warning_under, short: '-w N', long: '--warning-under VALUE', description: 'Issue a warning if the CloudWatch _Count_ based metric (Status Check / CPU Credits) is below this value' option :critical_under, short: '-c N', long: '--critical-under VALUE', description: 'Issue a critical if the CloudWatch _Count_ based metric (Status Check / CPU Credits) is below this value' def aws_config { access_key_id: config[:aws_access_key], secret_access_key: config[:aws_secret_access_key], region: config[:aws_region] } end def asg @asg ||= Aws::AutoScaling::Client.new aws_config end def cloud_watch @cloud_watch ||= Aws::CloudWatch::Client.new aws_config end def get_count_metric(group) cloud_watch.get_metric_statistics( namespace: 'AWS/EC2', metric_name: config[:countmetric].to_s, dimensions: [ { name: 'AutoScalingGroupName', value: group } ], start_time: config[:end_time] - 600, end_time: config[:end_time], statistics: ['Average'], period: config[:period], unit: 'Count' ) end def latest_value(value) value.datapoints[0][:average].to_f unless value.datapoints[0].nil? end def check_metric(group) metric = get_count_metric group latest_value metric unless metric.nil? end def check_group(group, reportstring, warnflag, critflag) metric_value = check_metric group if !metric_value.nil? && metric_value < config[:critical_under].to_f critflag = 1 reportstring = reportstring + group + ': ' + metric_value.to_s + ' ' elsif !metric_value.nil? && metric_value < config[:warning_under].to_f warnflag = 1 reportstring = reportstring + group + ': ' + metric_value.to_s + ' ' end [reportstring, warnflag, critflag] end def run warnflag = 0 critflag = 0 reportstring = '' if config[:group].nil? asg.describe_auto_scaling_groups.auto_scaling_groups.each do |group| if group.desired_capacity > 0 reportstring, warnflag, critflag = check_group(group.auto_scaling_group_name, reportstring, warnflag, critflag) end end else reportstring, warnflag, critflag = check_group(config[:group], reportstring, warnflag, critflag) end if critflag == 1 critical reportstring elsif warnflag == 1 warning reportstring else ok 'All checked AutoScaling Groups are cool' end end end
nyxcharon/sensu-plugins-aws
bin/check-autoscaling-cpucredits.rb
Ruby
mit
4,743
// 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. #nullable enable namespace Microsoft.CodeAnalysis { /// <summary> /// A class that provides constants for common language names. /// </summary> public static class LanguageNames { /// <summary> /// The common name used for the C# language. /// </summary> public const string CSharp = "C#"; /// <summary> /// The common name used for the Visual Basic language. /// </summary> public const string VisualBasic = "Visual Basic"; /// <summary> /// The common name used for the F# language. /// </summary> /// <remarks> /// F# is not a supported compile target for the Roslyn compiler. /// </remarks> public const string FSharp = "F#"; } }
jmarolf/roslyn
src/Compilers/Core/Portable/Symbols/LanguageNames.cs
C#
mit
988
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; namespace Avalonia.Base.UnitTests.Collections { internal class PropertyChangedTracker { public PropertyChangedTracker(INotifyPropertyChanged obj) { Names = new List<string>(); obj.PropertyChanged += PropertyChanged; } public List<string> Names { get; } public void Reset() { Names.Clear(); } private void PropertyChanged(object sender, PropertyChangedEventArgs e) { Names.Add(e.PropertyName); } } }
susloparovdenis/Avalonia
tests/Avalonia.Base.UnitTests/Collections/PropertyChangedTracker.cs
C#
mit
786
<span class="transition-label"><%= label %></span> <span class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-sort-down"></i> </span> <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu"> <li class="first"> <a class="workflow-step-edit" href="#edit-step"><i class="icon icon-edit" aria-hidden="true"></i><%= _.__('Edit') %></a> </li> <li> <a class="workflow-step-clone" href="#clone-step"><i class="icon icon-copy" aria-hidden="true"></i><%= _.__('Clone') %></a> </li> <li> <a class="workflow-step-delete" href="#delete-step"><i class="icon icon-trash" aria-hidden="true"></i><%= _.__('Delete') %></a> </li> </ul>
devGomgbo/stockvalue
web/bundles/oroworkflow/templates/flowchart/editor/transition.html
HTML
mit
692
class ChangeGlobalIdToInt < ActiveRecord::Migration def change change_column :users, :global_id, :int end end
MusikAnimal/WikiEduDashboard
db/migrate/20150402225521_change_global_id_to_int.rb
Ruby
mit
118
// // STXFeedTableViewDelegate.h // STXDynamicTableView // // Created by Jesse Armand on 27/3/14. // Copyright (c) 2014 2359 Media. All rights reserved. // @import Foundation; @protocol STXFeedPhotoCellDelegate; @protocol STXLikesCellDelegate; @protocol STXCaptionCellDelegate; @protocol STXCommentCellDelegate; @protocol STXUserActionDelegate; @interface STXFeedTableViewDelegate : NSObject <UITableViewDelegate> @property (nonatomic) BOOL insertingRow; - (instancetype)initWithController:(id<STXFeedPhotoCellDelegate, STXLikesCellDelegate, STXCaptionCellDelegate, STXCommentCellDelegate, STXUserActionDelegate>)controller; - (void)reloadAtIndexPath:(NSIndexPath *)indexPath forTableView:(UITableView *)tableView; @end
iulukaya/STXDynamicTableView
STXDynamicTableView/Protocols/STXFeedTableViewDelegate.h
C
mit
731
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/on', 'dojo/topic', 'dijit/popup', 'dijit/TooltipDialog', './IDMappingGrid', './GridContainer' ], function ( declare, lang, on, Topic, popup, TooltipDialog, IDMappingGrid, GridContainer ) { return declare([GridContainer], { gridCtor: IDMappingGrid, containerType: 'feature_data', facetFields: [], enableFilterPanel: false, buildQuery: function () { // prevent further filtering. DO NOT DELETE }, _setQueryAttr: function (query) { // block default query handler for now. }, onSetState: function (state) { // block default behavior }, _setStateAttr: function (state) { this.inherited(arguments); if (!state) { return; } if (this.grid) { this.grid.set('state', state); } else { // console.log("No Grid Yet (IDMappingGridContainer)"); } this._set('state', state); } }); });
dmachi/p3_web
public/js/p3/widget/IDMappingGridContainer.js
JavaScript
mit
976
#!/bin/bash FN="TxDb.Rnorvegicus.BioMart.igis_2.3.2.tar.gz" URLS=( "https://bioconductor.org/packages/3.14/data/annotation/src/contrib/TxDb.Rnorvegicus.BioMart.igis_2.3.2.tar.gz" "https://bioarchive.galaxyproject.org/TxDb.Rnorvegicus.BioMart.igis_2.3.2.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-txdb.rnorvegicus.biomart.igis/bioconductor-txdb.rnorvegicus.biomart.igis_2.3.2_src_all.tar.gz" ) MD5="eaf695f63cd021074d68c76d148cdfb7" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
cokelaer/bioconda-recipes
recipes/bioconductor-txdb.rnorvegicus.biomart.igis/post-link.sh
Shell
mit
1,393
/* * Copyright (c) 2014 ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Universitaetsstrasse 6, CH-8092 Zurich. Attn: Systems Group. */ #include <barrelfish/barrelfish.h> #include <virtio/virtio_guest.h> #include "guest/channel.h" struct virtio_guest_chan_fn *vguest_chan_fn = NULL; /** * */ errval_t virtio_guest_init(enum virtio_guest_channel backend, char *iface) { errval_t err; switch (backend) { case VIRTIO_GUEST_CHAN_FLOUNDER: err = virtio_guest_flounder_init(iface); break; case VIRTIO_GUEST_CHAN_XEON_PHI: err = virtio_guest_xeon_phi_init(); break; default: err = -1; break; } if (err_is_fail(err)) { return err; } assert(vguest_chan_fn); return SYS_ERR_OK; }
kishoredbn/barrelfish
lib/virtio/guest.c
C
mit
961
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "lighting/advanced/hlsl/deferredShadingFeaturesHLSL.h" #include "lighting/advanced/advancedLightBinManager.h" #include "shaderGen/langElement.h" #include "shaderGen/shaderOp.h" #include "shaderGen/conditionerFeature.h" #include "renderInstance/renderPrePassMgr.h" #include "materials/processedMaterial.h" #include "materials/materialFeatureTypes.h" //**************************************************************************** // Deferred Shading Features //**************************************************************************** // Specular Map -> Blue of Material Buffer ( greyscaled ) // Gloss Map (Alpha Channel of Specular Map) -> Alpha ( Spec Power ) of Material Info Buffer. void DeferredSpecMapHLSL::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ) { // Get the texture coord. Var *texCoord = getInTexCoord( "texCoord", "float2", true, componentList ); // search for color var Var *material = (Var*) LangElement::find( getOutputTargetVarName(ShaderFeature::RenderTarget2) ); MultiLine * meta = new MultiLine; if ( !material ) { // create color var material = new Var; material->setType( "fragout" ); material->setName( getOutputTargetVarName(ShaderFeature::RenderTarget2) ); material->setStructName( "OUT" ); } // create texture var Var *specularMap = new Var; specularMap->setType( "sampler2D" ); specularMap->setName( "specularMap" ); specularMap->uniform = true; specularMap->sampler = true; specularMap->constNum = Var::getTexUnitNum(); Var* specularMapTex = NULL; if (mIsDirect3D11) { specularMap->setType("SamplerState"); specularMapTex = new Var; specularMapTex->setName("specularMapTex"); specularMapTex->setType("Texture2D"); specularMapTex->uniform = true; specularMapTex->texture = true; specularMapTex->constNum = specularMap->constNum; } //matinfo.g slot reserved for AO later Var* specColor = new Var; specColor->setName("specColor"); specColor->setType("float4"); LangElement *specColorElem = new DecOp(specColor); meta->addStatement(new GenOp(" @.g = 1.0;\r\n", material)); //sample specular map if (mIsDirect3D11) meta->addStatement(new GenOp(" @ = @.Sample(@, @);\r\n", specColorElem, specularMapTex, specularMap, texCoord)); else meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", specColorElem, specularMap, texCoord)); meta->addStatement(new GenOp(" @.b = dot(@.rgb, float3(0.3, 0.59, 0.11));\r\n", material, specColor)); meta->addStatement(new GenOp(" @.a = @.a;\r\n", material, specColor)); output = meta; } ShaderFeature::Resources DeferredSpecMapHLSL::getResources( const MaterialFeatureData &fd ) { Resources res; res.numTex = 1; res.numTexReg = 1; return res; } void DeferredSpecMapHLSL::setTexData( Material::StageData &stageDat, const MaterialFeatureData &fd, RenderPassData &passData, U32 &texIndex ) { GFXTextureObject *tex = stageDat.getTex( MFT_SpecularMap ); if ( tex ) { passData.mTexType[ texIndex ] = Material::Standard; passData.mSamplerNames[ texIndex ] = "specularMap"; passData.mTexSlot[ texIndex++ ].texObject = tex; } } void DeferredSpecMapHLSL::processVert( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ) { MultiLine *meta = new MultiLine; getOutTexCoord( "texCoord", "float2", true, fd.features[MFT_TexAnim], meta, componentList ); output = meta; } // Material Info Flags -> Red ( Flags ) of Material Info Buffer. void DeferredMatInfoFlagsHLSL::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ) { // search for material var Var *material = (Var*) LangElement::find( getOutputTargetVarName(ShaderFeature::RenderTarget2) ); if ( !material ) { // create material var material = new Var; material->setType( "fragout" ); material->setName( getOutputTargetVarName(ShaderFeature::RenderTarget2) ); material->setStructName( "OUT" ); } Var *matInfoFlags = new Var; matInfoFlags->setType( "float" ); matInfoFlags->setName( "matInfoFlags" ); matInfoFlags->uniform = true; matInfoFlags->constSortPos = cspPotentialPrimitive; output = new GenOp( " @.r = @;\r\n", material, matInfoFlags ); } // Spec Strength -> Blue Channel of Material Info Buffer. // Spec Power -> Alpha Channel ( of Material Info Buffer. void DeferredSpecVarsHLSL::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ) { // search for material var Var *material = (Var*) LangElement::find( getOutputTargetVarName(ShaderFeature::RenderTarget2) ); if ( !material ) { // create material var material = new Var; material->setType( "fragout" ); material->setName( getOutputTargetVarName(ShaderFeature::RenderTarget2) ); material->setStructName( "OUT" ); } Var *specStrength = new Var; specStrength->setType( "float" ); specStrength->setName( "specularStrength" ); specStrength->uniform = true; specStrength->constSortPos = cspPotentialPrimitive; Var *specPower = new Var; specPower->setType( "float" ); specPower->setName( "specularPower" ); specPower->uniform = true; specPower->constSortPos = cspPotentialPrimitive; MultiLine * meta = new MultiLine; //matinfo.g slot reserved for AO later meta->addStatement(new GenOp(" @.g = 1.0;\r\n", material)); meta->addStatement(new GenOp(" @.a = @/128;\r\n", material, specPower)); meta->addStatement(new GenOp(" @.b = @/5;\r\n", material, specStrength)); output = meta; } // Black -> Blue and Alpha of matinfo Buffer (representing no specular), White->G (representing No AO) void DeferredEmptySpecHLSL::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ) { // search for material var Var *material = (Var*)LangElement::find(getOutputTargetVarName(ShaderFeature::RenderTarget2)); if (!material) { // create color var material = new Var; material->setType("fragout"); material->setName(getOutputTargetVarName(ShaderFeature::RenderTarget2)); material->setStructName("OUT"); } MultiLine * meta = new MultiLine; //matinfo.g slot reserved for AO later meta->addStatement(new GenOp(" @.g = 1.0;\r\n", material)); meta->addStatement(new GenOp(" @.ba = 0.0;\r\n", material)); output = meta; }
elfprince13/Torque3D
Engine/source/lighting/advanced/hlsl/deferredShadingFeaturesHLSL.cpp
C++
mit
8,082
(function(){ module('data-method', { setup: function() { $('#qunit-fixture').append($('<a />', { href: '/echo', 'data-method': 'delete', text: 'destroy!' })); }, teardown: function() { $(document).unbind('iframe:loaded'); } }); function submit(fn, options) { $(document).bind('iframe:loaded', function(e, data) { fn(data); start(); }); $('#qunit-fixture').find('a') .trigger('click'); } asyncTest('link with "data-method" set to "delete"', 3, function() { submit(function(data) { equal(data.REQUEST_METHOD, 'DELETE'); strictEqual(data.params.authenticity_token, undefined); strictEqual(data.HTTP_X_CSRF_TOKEN, undefined); }); }); asyncTest('link with "data-method" and CSRF', 1, function() { $('#qunit-fixture') .append('<meta name="csrf-param" content="authenticity_token"/>') .append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae"/>'); submit(function(data) { equal(data.params.authenticity_token, 'cf50faa3fe97702ca1ae'); }); }); asyncTest('link "target" should be carried over to generated form', 1, function() { $('a[data-method]').attr('target', 'super-special-frame'); submit(function(data) { equal(data.params._target, 'super-special-frame'); }); }); })();
star-diopside/jquery-ujs
test/public/test/data-method.js
JavaScript
mit
1,270
--- title: TextChanged page_title: TextChanged | RadComboBox for ASP.NET AJAX Documentation description: TextChanged slug: combobox/server-side-programming/textchanged tags: textchanged published: True position: 5 --- # TextChanged ## The **TextChanged** event occurs when the text in the input area of **RadComboBox** changes. This can be due to the user typing in custom text (if the **AllowCustomText** property is **True**) or to changing the selected item. When the user types in the input area, **TextChanged** does not occur until the user hits Enter or clicks outside the combobox. When the selection changes, **TextChanged** only occurs if a new item is selected. >caution The **TextChanged** event does not fire unless the **AutoPostBack** property is **True** . > The **TextChanged** event handler receives two arguments: 1. The **RadComboBox** that is loading items. This argument is of type object, but can be cast to the **RadComboBox** type. 1. An EventArgs object. This is the standard ASP.NET EventArgs object. Use the **TextChanged** event handler to respond in server-side code when text in the input area changes: ````ASPNET <telerik:radcombobox id="RadComboBox1" runat="server" ontextchanged="RadComboBox1_TextChanged" allowcustomtext="True" autopostback="True"> </telerik:radcombobox> ```` ````C# protected void RadComboBox1_TextChanged(object sender, EventArgs e) { TextBox1.Text = RadComboBox1.Text; } ```` ````VB.NET Protected Sub RadComboBox1_TextChanged(ByVal sender As Object, ByVal e As EventArgs) TextBox1.Text = RadComboBox1.Text End Sub ```` # See Also * [SelectedIndexChanged]({%slug combobox/server-side-programming/selectedindexchanged%}) * [OnClientKeyPressing]({%slug combobox/client-side-programming/events/onclientkeypressing%})
LanceMcCarthy/ajax-docs
controls/combobox/server-side-programming/textchanged.md
Markdown
mit
1,892
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_SEQUENTIAL_IMPULSE_CONSTRAINT_SOLVER_H #define BT_SEQUENTIAL_IMPULSE_CONSTRAINT_SOLVER_H class btIDebugDraw; class btPersistentManifold; class btDispatcher; class btCollisionObject; #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" #include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h" #include "BulletDynamics/ConstraintSolver/btSolverBody.h" #include "BulletDynamics/ConstraintSolver/btSolverConstraint.h" #include "BulletCollision/NarrowPhaseCollision/btManifoldPoint.h" #include "BulletDynamics/ConstraintSolver/btConstraintSolver.h" typedef btScalar (*btSingleConstraintRowSolver)(btSolverBody&, btSolverBody&, const btSolverConstraint&); ///The btSequentialImpulseConstraintSolver is a fast SIMD implementation of the Projected Gauss Seidel (iterative LCP) method. ATTRIBUTE_ALIGNED16(class) btSequentialImpulseConstraintSolver : public btConstraintSolver { protected: btAlignedObjectArray<btSolverBody> m_tmpSolverBodyPool; btConstraintArray m_tmpSolverContactConstraintPool; btConstraintArray m_tmpSolverNonContactConstraintPool; btConstraintArray m_tmpSolverContactFrictionConstraintPool; btConstraintArray m_tmpSolverContactRollingFrictionConstraintPool; btAlignedObjectArray<int> m_orderTmpConstraintPool; btAlignedObjectArray<int> m_orderNonContactConstraintPool; btAlignedObjectArray<int> m_orderFrictionConstraintPool; btAlignedObjectArray<btTypedConstraint::btConstraintInfo1> m_tmpConstraintSizesPool; int m_maxOverrideNumSolverIterations; int m_fixedBodyId; // When running solvers on multiple threads, a race condition exists for Kinematic objects that // participate in more than one solver. // The getOrInitSolverBody() function writes the companionId of each body (storing the index of the solver body // for the current solver). For normal dynamic bodies it isn't an issue because they can only be in one island // (and therefore one thread) at a time. But kinematic bodies can be in multiple islands at once. // To avoid this race condition, this solver does not write the companionId, instead it stores the solver body // index in this solver-local table, indexed by the uniqueId of the body. btAlignedObjectArray<int> m_kinematicBodyUniqueIdToSolverBodyTable; // only used for multithreading btSingleConstraintRowSolver m_resolveSingleConstraintRowGeneric; btSingleConstraintRowSolver m_resolveSingleConstraintRowLowerLimit; btSingleConstraintRowSolver m_resolveSplitPenetrationImpulse; int m_cachedSolverMode; // used to check if SOLVER_SIMD flag has been changed void setupSolverFunctions(bool useSimd); btScalar m_leastSquaresResidual; void setupFrictionConstraint(btSolverConstraint & solverConstraint, const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, btManifoldPoint& cp, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, const btContactSolverInfo& infoGlobal, btScalar desiredVelocity = 0., btScalar cfmSlip = 0.); void setupTorsionalFrictionConstraint(btSolverConstraint & solverConstraint, const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, btManifoldPoint& cp, btScalar combinedTorsionalFriction, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, btScalar desiredVelocity = 0., btScalar cfmSlip = 0.); btSolverConstraint& addFrictionConstraint(const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, int frictionIndex, btManifoldPoint& cp, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, const btContactSolverInfo& infoGlobal, btScalar desiredVelocity = 0., btScalar cfmSlip = 0.); btSolverConstraint& addTorsionalFrictionConstraint(const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, int frictionIndex, btManifoldPoint& cp, btScalar torsionalFriction, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, btScalar desiredVelocity = 0, btScalar cfmSlip = 0.f); void setupContactConstraint(btSolverConstraint & solverConstraint, int solverBodyIdA, int solverBodyIdB, btManifoldPoint& cp, const btContactSolverInfo& infoGlobal, btScalar& relaxation, const btVector3& rel_pos1, const btVector3& rel_pos2); static void applyAnisotropicFriction(btCollisionObject * colObj, btVector3 & frictionDirection, int frictionMode); void setFrictionConstraintImpulse(btSolverConstraint & solverConstraint, int solverBodyIdA, int solverBodyIdB, btManifoldPoint& cp, const btContactSolverInfo& infoGlobal); ///m_btSeed2 is used for re-arranging the constraint rows. improves convergence/quality of friction unsigned long m_btSeed2; btScalar restitutionCurve(btScalar rel_vel, btScalar restitution, btScalar velocityThreshold); virtual void convertContacts(btPersistentManifold * *manifoldPtr, int numManifolds, const btContactSolverInfo& infoGlobal); void convertContact(btPersistentManifold * manifold, const btContactSolverInfo& infoGlobal); virtual void convertJoints(btTypedConstraint * *constraints, int numConstraints, const btContactSolverInfo& infoGlobal); void convertJoint(btSolverConstraint * currentConstraintRow, btTypedConstraint * constraint, const btTypedConstraint::btConstraintInfo1& info1, int solverBodyIdA, int solverBodyIdB, const btContactSolverInfo& infoGlobal); virtual void convertBodies(btCollisionObject * *bodies, int numBodies, const btContactSolverInfo& infoGlobal); btScalar resolveSplitPenetrationSIMD(btSolverBody & bodyA, btSolverBody & bodyB, const btSolverConstraint& contactConstraint) { return m_resolveSplitPenetrationImpulse(bodyA, bodyB, contactConstraint); } btScalar resolveSplitPenetrationImpulseCacheFriendly(btSolverBody & bodyA, btSolverBody & bodyB, const btSolverConstraint& contactConstraint) { return m_resolveSplitPenetrationImpulse(bodyA, bodyB, contactConstraint); } //internal method int getOrInitSolverBody(btCollisionObject & body, btScalar timeStep); void initSolverBody(btSolverBody * solverBody, btCollisionObject * collisionObject, btScalar timeStep); btScalar resolveSingleConstraintRowGeneric(btSolverBody & bodyA, btSolverBody & bodyB, const btSolverConstraint& contactConstraint); btScalar resolveSingleConstraintRowGenericSIMD(btSolverBody & bodyA, btSolverBody & bodyB, const btSolverConstraint& contactConstraint); btScalar resolveSingleConstraintRowLowerLimit(btSolverBody & bodyA, btSolverBody & bodyB, const btSolverConstraint& contactConstraint); btScalar resolveSingleConstraintRowLowerLimitSIMD(btSolverBody & bodyA, btSolverBody & bodyB, const btSolverConstraint& contactConstraint); btScalar resolveSplitPenetrationImpulse(btSolverBody & bodyA, btSolverBody & bodyB, const btSolverConstraint& contactConstraint) { return m_resolveSplitPenetrationImpulse(bodyA, bodyB, contactConstraint); } protected: void writeBackContacts(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal); void writeBackJoints(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal); void writeBackBodies(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal); virtual void solveGroupCacheFriendlySplitImpulseIterations(btCollisionObject * *bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer); virtual btScalar solveGroupCacheFriendlyFinish(btCollisionObject * *bodies, int numBodies, const btContactSolverInfo& infoGlobal); virtual btScalar solveSingleIteration(int iteration, btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer); virtual btScalar solveGroupCacheFriendlySetup(btCollisionObject * *bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer); virtual btScalar solveGroupCacheFriendlyIterations(btCollisionObject * *bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer); public: BT_DECLARE_ALIGNED_ALLOCATOR(); btSequentialImpulseConstraintSolver(); virtual ~btSequentialImpulseConstraintSolver(); virtual btScalar solveGroup(btCollisionObject * *bodies, int numBodies, btPersistentManifold** manifold, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& info, btIDebugDraw* debugDrawer, btDispatcher* dispatcher); ///clear internal cached data and reset random seed virtual void reset(); unsigned long btRand2(); int btRandInt2(int n); void setRandSeed(unsigned long seed) { m_btSeed2 = seed; } unsigned long getRandSeed() const { return m_btSeed2; } virtual btConstraintSolverType getSolverType() const { return BT_SEQUENTIAL_IMPULSE_SOLVER; } btSingleConstraintRowSolver getActiveConstraintRowSolverGeneric() { return m_resolveSingleConstraintRowGeneric; } void setConstraintRowSolverGeneric(btSingleConstraintRowSolver rowSolver) { m_resolveSingleConstraintRowGeneric = rowSolver; } btSingleConstraintRowSolver getActiveConstraintRowSolverLowerLimit() { return m_resolveSingleConstraintRowLowerLimit; } void setConstraintRowSolverLowerLimit(btSingleConstraintRowSolver rowSolver) { m_resolveSingleConstraintRowLowerLimit = rowSolver; } ///Various implementations of solving a single constraint row using a generic equality constraint, using scalar reference, SSE2 or SSE4 btSingleConstraintRowSolver getScalarConstraintRowSolverGeneric(); btSingleConstraintRowSolver getSSE2ConstraintRowSolverGeneric(); btSingleConstraintRowSolver getSSE4_1ConstraintRowSolverGeneric(); ///Various implementations of solving a single constraint row using an inequality (lower limit) constraint, using scalar reference, SSE2 or SSE4 btSingleConstraintRowSolver getScalarConstraintRowSolverLowerLimit(); btSingleConstraintRowSolver getSSE2ConstraintRowSolverLowerLimit(); btSingleConstraintRowSolver getSSE4_1ConstraintRowSolverLowerLimit(); }; #endif //BT_SEQUENTIAL_IMPULSE_CONSTRAINT_SOLVER_H
okamstudio/godot
thirdparty/bullet/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h
C
mit
11,530
console.warn("warn -",`Imports like "const rarible = require('simple-icons/icons/rarible');" have been deprecated in v6.0.0 and will no longer work from v7.0.0, use "const { siRarible } = require('simple-icons/icons');" instead`),module.exports={title:"Rarible",slug:"rarible",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Rarible</title><path d="'+this.path+'"/></svg>'},path:"M4.8 0A4.79 4.79 0 000 4.8v14.4A4.79 4.79 0 004.8 24h14.4a4.79 4.79 0 004.8-4.8V4.8A4.79 4.79 0 0019.2 0zm1.32 7.68h8.202c2.06 0 3.666.44 3.666 2.334 0 1.137-.671 1.702-1.427 1.898.904.268 1.558 1 1.558 2.16v2.131h-3.451V14.18c0-.62-.37-.87-1-.87H9.572v2.893H6.12zm3.452 2.5v.834h4.155c.452 0 .726-.06.726-.416 0-.358-.274-.418-.726-.418z",source:"https://rarible.com/",hex:"FEDA03",guidelines:void 0,license:void 0};
cdnjs/cdnjs
ajax/libs/simple-icons/6.9.0/rarible.js
JavaScript
mit
845
module ActiveShipping # FedEx carrier implementation. # # FedEx module by Jimmy Baker (http://github.com/jimmyebaker) # Documentation can be found here: http://images.fedex.com/us/developer/product/WebServices/MyWebHelp/PropDevGuide.pdf class FedEx < Carrier self.retry_safe = true cattr_reader :name @@name = "FedEx" TEST_URL = 'https://gatewaybeta.fedex.com:443/xml' LIVE_URL = 'https://gateway.fedex.com:443/xml' CARRIER_CODES = { "fedex_ground" => "FDXG", "fedex_express" => "FDXE" } DELIVERY_ADDRESS_NODE_NAMES = %w(DestinationAddress ActualDeliveryAddress) SHIPPER_ADDRESS_NODE_NAMES = %w(ShipperAddress) SERVICE_TYPES = { "PRIORITY_OVERNIGHT" => "FedEx Priority Overnight", "PRIORITY_OVERNIGHT_SATURDAY_DELIVERY" => "FedEx Priority Overnight Saturday Delivery", "FEDEX_2_DAY" => "FedEx 2 Day", "FEDEX_2_DAY_SATURDAY_DELIVERY" => "FedEx 2 Day Saturday Delivery", "STANDARD_OVERNIGHT" => "FedEx Standard Overnight", "FIRST_OVERNIGHT" => "FedEx First Overnight", "FIRST_OVERNIGHT_SATURDAY_DELIVERY" => "FedEx First Overnight Saturday Delivery", "FEDEX_EXPRESS_SAVER" => "FedEx Express Saver", "FEDEX_1_DAY_FREIGHT" => "FedEx 1 Day Freight", "FEDEX_1_DAY_FREIGHT_SATURDAY_DELIVERY" => "FedEx 1 Day Freight Saturday Delivery", "FEDEX_2_DAY_FREIGHT" => "FedEx 2 Day Freight", "FEDEX_2_DAY_FREIGHT_SATURDAY_DELIVERY" => "FedEx 2 Day Freight Saturday Delivery", "FEDEX_3_DAY_FREIGHT" => "FedEx 3 Day Freight", "FEDEX_3_DAY_FREIGHT_SATURDAY_DELIVERY" => "FedEx 3 Day Freight Saturday Delivery", "INTERNATIONAL_PRIORITY" => "FedEx International Priority", "INTERNATIONAL_PRIORITY_SATURDAY_DELIVERY" => "FedEx International Priority Saturday Delivery", "INTERNATIONAL_ECONOMY" => "FedEx International Economy", "INTERNATIONAL_FIRST" => "FedEx International First", "INTERNATIONAL_PRIORITY_FREIGHT" => "FedEx International Priority Freight", "INTERNATIONAL_ECONOMY_FREIGHT" => "FedEx International Economy Freight", "GROUND_HOME_DELIVERY" => "FedEx Ground Home Delivery", "FEDEX_GROUND" => "FedEx Ground", "INTERNATIONAL_GROUND" => "FedEx International Ground", "SMART_POST" => "FedEx SmartPost", "FEDEX_FREIGHT_PRIORITY" => "FedEx Freight Priority", "FEDEX_FREIGHT_ECONOMY" => "FedEx Freight Economy" } PACKAGE_TYPES = { "fedex_envelope" => "FEDEX_ENVELOPE", "fedex_pak" => "FEDEX_PAK", "fedex_box" => "FEDEX_BOX", "fedex_tube" => "FEDEX_TUBE", "fedex_10_kg_box" => "FEDEX_10KG_BOX", "fedex_25_kg_box" => "FEDEX_25KG_BOX", "your_packaging" => "YOUR_PACKAGING" } DROPOFF_TYPES = { 'regular_pickup' => 'REGULAR_PICKUP', 'request_courier' => 'REQUEST_COURIER', 'dropbox' => 'DROP_BOX', 'business_service_center' => 'BUSINESS_SERVICE_CENTER', 'station' => 'STATION' } SIGNATURE_OPTION_CODES = { adult: 'ADULT', # 21 years plus direct: 'DIRECT', # A person at the delivery address indirect: 'INDIRECT', # A person at the delivery address, or a neighbor, or a signed note for fedex on the door none_required: 'NO_SIGNATURE_REQUIRED', default_for_service: 'SERVICE_DEFAULT' } PAYMENT_TYPES = { 'sender' => 'SENDER', 'recipient' => 'RECIPIENT', 'third_party' => 'THIRDPARTY', 'collect' => 'COLLECT' } PACKAGE_IDENTIFIER_TYPES = { 'tracking_number' => 'TRACKING_NUMBER_OR_DOORTAG', 'door_tag' => 'TRACKING_NUMBER_OR_DOORTAG', 'rma' => 'RMA', 'ground_shipment_id' => 'GROUND_SHIPMENT_ID', 'ground_invoice_number' => 'GROUND_INVOICE_NUMBER', 'ground_customer_reference' => 'GROUND_CUSTOMER_REFERENCE', 'ground_po' => 'GROUND_PO', 'express_reference' => 'EXPRESS_REFERENCE', 'express_mps_master' => 'EXPRESS_MPS_MASTER', 'shipper_reference' => 'SHIPPER_REFERENCE', } TRANSIT_TIMES = %w(UNKNOWN ONE_DAY TWO_DAYS THREE_DAYS FOUR_DAYS FIVE_DAYS SIX_DAYS SEVEN_DAYS EIGHT_DAYS NINE_DAYS TEN_DAYS ELEVEN_DAYS TWELVE_DAYS THIRTEEN_DAYS FOURTEEN_DAYS FIFTEEN_DAYS SIXTEEN_DAYS SEVENTEEN_DAYS EIGHTEEN_DAYS) # FedEx tracking codes as described in the FedEx Tracking Service WSDL Guide # All delays also have been marked as exceptions TRACKING_STATUS_CODES = HashWithIndifferentAccess.new( 'AA' => :at_airport, 'AD' => :at_delivery, 'AF' => :at_fedex_facility, 'AR' => :at_fedex_facility, 'AP' => :at_pickup, 'CA' => :canceled, 'CH' => :location_changed, 'DE' => :exception, 'DL' => :delivered, 'DP' => :departed_fedex_location, 'DR' => :vehicle_furnished_not_used, 'DS' => :vehicle_dispatched, 'DY' => :exception, 'EA' => :exception, 'ED' => :enroute_to_delivery, 'EO' => :enroute_to_origin_airport, 'EP' => :enroute_to_pickup, 'FD' => :at_fedex_destination, 'HL' => :held_at_location, 'IT' => :in_transit, 'LO' => :left_origin, 'OC' => :order_created, 'OD' => :out_for_delivery, 'PF' => :plane_in_flight, 'PL' => :plane_landed, 'PU' => :picked_up, 'RS' => :return_to_shipper, 'SE' => :exception, 'SF' => :at_sort_facility, 'SP' => :split_status, 'TR' => :transfer ) def self.service_name_for_code(service_code) SERVICE_TYPES[service_code] || "FedEx #{service_code.titleize.sub(/Fedex /, '')}" end def requirements [:key, :password, :account, :login] end def find_rates(origin, destination, packages, options = {}) options = @options.update(options) packages = Array(packages) rate_request = build_rate_request(origin, destination, packages, options) xml = commit(save_request(rate_request), (options[:test] || false)) parse_rate_response(origin, destination, packages, xml, options) end def find_tracking_info(tracking_number, options = {}) options = @options.update(options) tracking_request = build_tracking_request(tracking_number, options) xml = commit(save_request(tracking_request), (options[:test] || false)) parse_tracking_response(xml, options) end # Get Shipping labels def create_shipment(origin, destination, packages, options = {}) options = @options.update(options) packages = Array(packages) raise Error, "Multiple packages are not supported yet." if packages.length > 1 request = build_shipment_request(origin, destination, packages, options) logger.debug(request) if logger response = commit(save_request(request), (options[:test] || false)) parse_ship_response(response) end def maximum_address_field_length # See Fedex Developper Guide 35 end protected def build_shipment_request(origin, destination, packages, options = {}) imperial = location_uses_imperial(origin) xml_builder = Nokogiri::XML::Builder.new do |xml| xml.ProcessShipmentRequest(xmlns: 'http://fedex.com/ws/ship/v13') do build_request_header(xml) build_version_node(xml, 'ship', 13, 0 ,0) xml.RequestedShipment do xml.ShipTimestamp(ship_timestamp(options[:turn_around_time]).iso8601(0)) xml.DropoffType('REGULAR_PICKUP') xml.ServiceType(options[:service_type] || 'FEDEX_GROUND') xml.PackagingType('YOUR_PACKAGING') xml.Shipper do build_contact_address_nodes(xml, options[:shipper] || origin) end xml.Recipient do build_contact_address_nodes(xml, destination) end xml.Origin do build_contact_address_nodes(xml, origin) end xml.ShippingChargesPayment do xml.PaymentType('SENDER') xml.Payor do build_shipment_responsible_party_node(xml, options[:shipper] || origin) end end xml.LabelSpecification do xml.LabelFormatType('COMMON2D') xml.ImageType('PNG') xml.LabelStockType('PAPER_7X4.75') end xml.RateRequestTypes('ACCOUNT') xml.PackageCount(packages.size) packages.each do |package| xml.RequestedPackageLineItems do xml.GroupPackageCount(1) build_package_weight_node(xml, package, imperial) build_package_dimensions_node(xml, package, imperial) # Reference Numbers reference_numbers = Array(package.options[:reference_numbers]) if reference_numbers.size > 0 xml.CustomerReferences do reference_numbers.each do |reference_number_info| xml.CustomerReferenceType(reference_number_info[:type] || "CUSTOMER_REFERENCE") xml.Value(reference_number_info[:value]) end end end xml.SpecialServicesRequested do xml.SpecialServiceTypes("SIGNATURE_OPTION") xml.SignatureOptionDetail do xml.OptionType(SIGNATURE_OPTION_CODES[package.options[:signature_option] || :default_for_service]) end end end end end end end xml_builder.to_xml end def build_contact_address_nodes(xml, location) xml.Contact do xml.PersonName(location.name) xml.CompanyName(location.company) xml.PhoneNumber(location.phone) end xml.Address do xml.StreetLines(location.address1) if location.address1 xml.StreetLines(location.address2) if location.address2 xml.City(location.city) if location.city xml.StateOrProvinceCode(location.state) xml.PostalCode(location.postal_code) xml.CountryCode(location.country_code(:alpha2)) xml.Residential('true') if location.residential? end end def build_shipment_responsible_party_node(xml, origin) xml.ResponsibleParty do xml.AccountNumber(@options[:account]) xml.Contact do xml.PersonName(origin.name) xml.CompanyName(origin.company) xml.PhoneNumber(origin.phone) end end end def build_rate_request(origin, destination, packages, options = {}) imperial = location_uses_imperial(origin) xml_builder = Nokogiri::XML::Builder.new do |xml| xml.RateRequest(xmlns: 'http://fedex.com/ws/rate/v13') do build_request_header(xml) build_version_node(xml, 'crs', 13, 0 ,0) # Returns delivery dates xml.ReturnTransitAndCommit(true) # Returns saturday delivery shipping options when available xml.VariableOptions('SATURDAY_DELIVERY') xml.RequestedShipment do xml.ShipTimestamp(ship_timestamp(options[:turn_around_time]).iso8601(0)) freight = has_freight?(options) unless freight # fedex api wants this up here otherwise request returns an error xml.DropoffType(options[:dropoff_type] || 'REGULAR_PICKUP') xml.PackagingType(options[:packaging_type] || 'YOUR_PACKAGING') end build_location_node(xml, 'Shipper', options[:shipper] || origin) build_location_node(xml, 'Recipient', destination) if options[:shipper] && options[:shipper] != origin build_location_node(xml, 'Origin', origin) end if freight freight_options = options[:freight] build_shipping_charges_payment_node(xml, freight_options) build_freight_shipment_detail_node(xml, freight_options, packages, imperial) build_rate_request_types_node(xml) else xml.SmartPostDetail do xml.Indicia(options[:smart_post_indicia] || 'PARCEL_SELECT') xml.HubId(options[:smart_post_hub_id] || 5902) # default to LA end build_rate_request_types_node(xml) xml.PackageCount(packages.size) build_packages_nodes(xml, packages, imperial) end end end end xml_builder.to_xml end def build_packages_nodes(xml, packages, imperial) packages.map do |pkg| xml.RequestedPackageLineItems do xml.GroupPackageCount(1) build_package_weight_node(xml, pkg, imperial) build_package_dimensions_node(xml, pkg, imperial) end end end def build_shipping_charges_payment_node(xml, freight_options) xml.ShippingChargesPayment do xml.PaymentType(freight_options[:payment_type]) xml.Payor do xml.ResponsibleParty do # TODO: case of different freight account numbers? xml.AccountNumber(freight_options[:account]) end end end end def build_freight_shipment_detail_node(xml, freight_options, packages, imperial) xml.FreightShipmentDetail do # TODO: case of different freight account numbers? xml.FedExFreightAccountNumber(freight_options[:account]) build_location_node(xml, 'FedExFreightBillingContactAndAddress', freight_options[:billing_location]) xml.Role(freight_options[:role]) packages.each do |pkg| xml.LineItems do xml.FreightClass(freight_options[:freight_class]) xml.Packaging(freight_options[:packaging]) build_package_weight_node(xml, pkg, imperial) build_package_dimensions_node(xml, pkg, imperial) end end end end def has_freight?(options) options[:freight] && options[:freight].present? end def build_package_weight_node(xml, pkg, imperial) xml.Weight do xml.Units(imperial ? 'LB' : 'KG') xml.Value([((imperial ? pkg.lbs : pkg.kgs).to_f * 1000).round / 1000.0, 0.1].max) end end def build_package_dimensions_node(xml, pkg, imperial) xml.Dimensions do [:length, :width, :height].each do |axis| value = ((imperial ? pkg.inches(axis) : pkg.cm(axis)).to_f * 1000).round / 1000.0 # 3 decimals xml.public_send(axis.to_s.capitalize, value.ceil) end xml.Units(imperial ? 'IN' : 'CM') end end def build_rate_request_types_node(xml, type = 'ACCOUNT') xml.RateRequestTypes(type) end def build_tracking_request(tracking_number, options = {}) xml_builder = Nokogiri::XML::Builder.new do |xml| xml.TrackRequest(xmlns: 'http://fedex.com/ws/track/v7') do build_request_header(xml) build_version_node(xml, 'trck', 7, 0, 0) xml.SelectionDetails do xml.PackageIdentifier do xml.Type(PACKAGE_IDENTIFIER_TYPES[options[:package_identifier_type] || 'tracking_number']) xml.Value(tracking_number) end xml.ShipDateRangeBegin(options[:ship_date_range_begin]) if options[:ship_date_range_begin] xml.ShipDateRangeEnd(options[:ship_date_range_end]) if options[:ship_date_range_end] xml.TrackingNumberUniqueIdentifier(options[:unique_identifier]) if options[:unique_identifier] end xml.ProcessingOptions('INCLUDE_DETAILED_SCANS') end end xml_builder.to_xml end def build_request_header(xml) xml.WebAuthenticationDetail do xml.UserCredential do xml.Key(@options[:key]) xml.Password(@options[:password]) end end xml.ClientDetail do xml.AccountNumber(@options[:account]) xml.MeterNumber(@options[:login]) end xml.TransactionDetail do xml.CustomerTransactionId(@options[:transaction_id] || 'ActiveShipping') # TODO: Need to do something better with this... end end def build_version_node(xml, service_id, major, intermediate, minor) xml.Version do xml.ServiceId(service_id) xml.Major(major) xml.Intermediate(intermediate) xml.Minor(minor) end end def build_location_node(xml, name, location) xml.public_send(name) do xml.Address do xml.StreetLines(location.address1) if location.address1 xml.StreetLines(location.address2) if location.address2 xml.City(location.city) if location.city xml.PostalCode(location.postal_code) xml.CountryCode(location.country_code(:alpha2)) xml.Residential(true) unless location.commercial? end end end def parse_rate_response(origin, destination, packages, response, options) xml = build_document(response, 'RateReply') success = response_success?(xml) message = response_message(xml) if success rate_estimates = xml.root.css('> RateReplyDetails').map do |rated_shipment| service_code = rated_shipment.at('ServiceType').text is_saturday_delivery = rated_shipment.at('AppliedOptions').try(:text) == 'SATURDAY_DELIVERY' service_type = is_saturday_delivery ? "#{service_code}_SATURDAY_DELIVERY" : service_code transit_time = rated_shipment.at('TransitTime').text if ["FEDEX_GROUND", "GROUND_HOME_DELIVERY"].include?(service_code) max_transit_time = rated_shipment.at('MaximumTransitTime').try(:text) if service_code == "FEDEX_GROUND" delivery_timestamp = rated_shipment.at('DeliveryTimestamp').try(:text) delivery_range = delivery_range_from(transit_time, max_transit_time, delivery_timestamp, options) currency = rated_shipment.at('RatedShipmentDetails/ShipmentRateDetail/TotalNetCharge/Currency').text RateEstimate.new(origin, destination, @@name, self.class.service_name_for_code(service_type), :service_code => service_code, :total_price => rated_shipment.at('RatedShipmentDetails/ShipmentRateDetail/TotalNetCharge/Amount').text.to_f, :currency => currency, :packages => packages, :delivery_range => delivery_range) end if rate_estimates.empty? success = false message = "No shipping rates could be found for the destination address" if message.blank? end else rate_estimates = [] end RateResponse.new(success, message, Hash.from_xml(response), :rates => rate_estimates, :xml => response, :request => last_request, :log_xml => options[:log_xml]) end def delivery_range_from(transit_time, max_transit_time, delivery_timestamp, options) delivery_range = [delivery_timestamp, delivery_timestamp] # if there's no delivery timestamp but we do have a transit time, use it if delivery_timestamp.blank? && transit_time.present? transit_range = parse_transit_times([transit_time, max_transit_time.presence || transit_time]) delivery_range = transit_range.map { |days| business_days_from(ship_date(options[:turn_around_time]), days) } end delivery_range end def parse_ship_response(response) xml = build_document(response, 'ProcessShipmentReply') success = response_success?(xml) message = response_message(xml) response_info = Hash.from_xml(response) tracking_number = xml.css("CompletedPackageDetails TrackingIds TrackingNumber").text base_64_image = xml.css("Label Image").text labels = [Label.new(tracking_number, Base64.decode64(base_64_image))] LabelResponse.new(success, message, response_info, {labels: labels}) end def business_days_from(date, days) future_date = date count = 0 while count < days future_date += 1.day count += 1 if business_day?(future_date) end future_date end def business_day?(date) (1..5).include?(date.wday) end def parse_tracking_response(response, options) xml = build_document(response, 'TrackReply') success = response_success?(xml) message = response_message(xml) if success origin = nil delivery_signature = nil shipment_events = [] all_tracking_details = xml.root.xpath('CompletedTrackDetails/TrackDetails') tracking_details = case all_tracking_details.length when 1 all_tracking_details.first when 0 raise ActiveShipping::Error, "The response did not contain tracking details" else all_unique_identifiers = xml.root.xpath('CompletedTrackDetails/TrackDetails/TrackingNumberUniqueIdentifier').map(&:text) raise ActiveShipping::Error, "Multiple matches were found. Specify a unqiue identifier: #{all_unique_identifiers.join(', ')}" end first_notification = tracking_details.at('Notification') if first_notification.at('Severity').text == 'ERROR' case first_notification.at('Code').text when '9040' raise ActiveShipping::ShipmentNotFound, first_notification.at('Message').text else raise ActiveShipping::ResponseContentError, StandardError.new(first_notification.at('Message').text) end end tracking_number = tracking_details.at('TrackingNumber').text status_detail = tracking_details.at('StatusDetail') if status_detail.nil? raise ActiveShipping::Error, "Tracking response does not contain status information" end status_code = status_detail.at('Code').try(:text) if status_code.nil? raise ActiveShipping::Error, "Tracking response does not contain status code" end status_description = (status_detail.at('AncillaryDetails/ReasonDescription') || status_detail.at('Description')).text status = TRACKING_STATUS_CODES[status_code] if status_code == 'DL' && tracking_details.at('AvailableImages').try(:text) == 'SIGNATURE_PROOF_OF_DELIVERY' delivery_signature = tracking_details.at('DeliverySignatureName').text end if origin_node = tracking_details.at('OriginLocationAddress') origin = Location.new( :country => origin_node.at('CountryCode').text, :province => origin_node.at('StateOrProvinceCode').text, :city => origin_node.at('City').text ) end destination = extract_address(tracking_details, DELIVERY_ADDRESS_NODE_NAMES) shipper_address = extract_address(tracking_details, SHIPPER_ADDRESS_NODE_NAMES) ship_time = extract_timestamp(tracking_details, 'ShipTimestamp') actual_delivery_time = extract_timestamp(tracking_details, 'ActualDeliveryTimestamp') scheduled_delivery_time = extract_timestamp(tracking_details, 'EstimatedDeliveryTimestamp') tracking_details.xpath('Events').each do |event| address = event.at('Address') next if address.nil? || address.at('CountryCode').nil? city = address.at('City').try(:text) state = address.at('StateOrProvinceCode').try(:text) zip_code = address.at('PostalCode').try(:text) country = address.at('CountryCode').try(:text) location = Location.new(:city => city, :state => state, :postal_code => zip_code, :country => country) description = event.at('EventDescription').text time = Time.parse(event.at('Timestamp').text) zoneless_time = time.utc shipment_events << ShipmentEvent.new(description, zoneless_time, location) end shipment_events = shipment_events.sort_by(&:time) end TrackingResponse.new(success, message, Hash.from_xml(response), :carrier => @@name, :xml => response, :request => last_request, :status => status, :status_code => status_code, :status_description => status_description, :ship_time => ship_time, :scheduled_delivery_date => scheduled_delivery_time, :actual_delivery_date => actual_delivery_time, :delivery_signature => delivery_signature, :shipment_events => shipment_events, :shipper_address => (shipper_address.nil? || shipper_address.unknown?) ? nil : shipper_address, :origin => origin, :destination => destination, :tracking_number => tracking_number ) end def ship_timestamp(delay_in_hours) delay_in_hours ||= 0 Time.now + delay_in_hours.hours end def ship_date(delay_in_hours) delay_in_hours ||= 0 (Time.now + delay_in_hours.hours).to_date end def response_success?(document) highest_severity = document.root.at('HighestSeverity') return false if highest_severity.nil? %w(SUCCESS WARNING NOTE).include?(highest_severity.text) end def response_message(document) notifications = document.root.at('Notifications') return "" if notifications.nil? "#{notifications.at('Severity').text} - #{notifications.at('Code').text}: #{notifications.at('Message').text}" end def commit(request, test = false) ssl_post(test ? TEST_URL : LIVE_URL, request.gsub("\n", '')) end def parse_transit_times(times) results = [] times.each do |day_count| days = TRANSIT_TIMES.index(day_count.to_s.chomp) results << days.to_i end results end def extract_address(document, possible_node_names) node = nil args = {} possible_node_names.each do |name| node = document.at(name) break if node end if node args[:country] = node.at('CountryCode').try(:text) || ActiveUtils::Country.new(:alpha2 => 'ZZ', :name => 'Unknown or Invalid Territory', :alpha3 => 'ZZZ', :numeric => '999') args[:province] = node.at('StateOrProvinceCode').try(:text) || 'unknown' args[:city] = node.at('City').try(:text) || 'unknown' end Location.new(args) end def extract_timestamp(document, node_name) if timestamp_node = document.at(node_name) if timestamp_node.text =~ /\A(\d{4}-\d{2}-\d{2})T00:00:00\Z/ Date.parse($1) else Time.parse(timestamp_node.text) end end end def build_document(xml, expected_root_tag) document = Nokogiri.XML(xml) { |config| config.strict } document.remove_namespaces! if document.root.nil? || document.root.name != expected_root_tag raise ActiveShipping::ResponseContentError.new(StandardError.new('Invalid document'), xml) end document rescue Nokogiri::XML::SyntaxError => e raise ActiveShipping::ResponseContentError.new(e, xml) end def location_uses_imperial(location) %w(US LR MM).include?(location.country_code(:alpha2)) end end end
ipmobiletech/Shopify-active_shipping
lib/active_shipping/carriers/fedex.rb
Ruby
mit
27,510
--- title: Telerik.Web.UI.RadToolBarDropDown page_title: Client-side API Reference description: Client-side API Reference slug: Telerik.Web.UI.RadToolBarDropDown --- # Telerik.Web.UI.RadToolBarDropDown : Telerik.Web.UI.ControlItemContainer ## Inheritance Hierarchy * [Telerik.Web.UI.ControlItemContainer]({%slug Telerik.Web.UI.ControlItemContainer%}) * *[Telerik.Web.UI.RadToolBarDropDown]({%slug Telerik.Web.UI.RadToolBarDropDown%})* ## Methods ### blur Moves focus off the item to the next element in the tab order. #### Parameters #### Returns `None` ### disable disables the toolbar item. #### Parameters #### Returns `None` ### enable Enables the toolbar item. #### Parameters #### Returns `None` ### focus Moves focus to the item. #### Parameters #### Returns `None` ### get_animationContainer Returns the DOM element for the animation container of the item's drop-down list. #### Parameters #### Returns `Element` HTML element ### get_arrowElement Gets the DOM element for the UL element that lists the arrow elements. #### Parameters #### Returns `Element` ### get_buttons Returns the collection of buttons in the RadToolbarButtonCollection #### Parameters #### Returns `Telerik.Web.UI.RadToolBarButtonCollection` RadToolBarButtonCollection ### get_childListElement Gets the DOM element for the UL element that lists the toolbar buttons. #### Parameters #### Returns `Element` HTML element ### get_clicked True if the item is clicked. #### Parameters #### Returns `Boolean` boolean ### get_clickedCssClass Returns the name of the CSS class applied to the button when clicked. #### Parameters #### Returns `String` The value indicating the Css class name ### get_clickedImageUrl Returns the URL of the image when it is clicked. #### Parameters #### Returns `String` ### get_disabledCssClass Gets the CSS class for the item when it is disabled. #### Parameters #### Returns `String` ### get_disabledImageUrl Returns the full path to the image of a disabled item #### Parameters #### Returns `String` The value indicating the image url ### get_dropDownElement Returns the DOM element for the item's drop-down list. #### Parameters #### Returns `Element` HTML element ### get_dropDownVisible Returns true if the drop-down is opened. #### Parameters #### Returns `Boolean` ### get_expandDirection Gets the expand direction of the Toolbar. #### Parameters #### Returns `Telerik.Web.UI.ExpandDirection` ### get_focused True if the item is focused. #### Parameters #### Returns `Boolean` ### get_focusedCssClass Returns the name of the CSS class applied to the button when on focus. #### Parameters #### Returns `String` The value indicating the Css class name ### get_focusedImageUrl Returns the URL of the image when on focus. #### Parameters #### Returns `String` string ### get_hovered True if the item is hovered. #### Parameters #### Returns `Boolean` boolean ### get_hoveredCssClass Returns the name of the CSS class applied to the button when hovered. #### Parameters #### Returns `String` The value indicating the Css class name ### get_hoveredImageUrl Returns the URL of the hovered-state image. #### Parameters #### Returns `String` ### get_imageElement Gets the DOM element for the image of the item. #### Parameters #### Returns `Element` HTML element ### get_imagePosition Gets the image position of the toolbar item. #### Parameters #### Returns `Telerik.Web.UI.ToolBarImagePosition` ### get_imageUrl Returns the URL of the image. #### Parameters #### Returns `String` ### get_innerWrapElement Gets the DOM element for the innermost SPAN that wraps the item. #### Parameters #### Returns `Element` HTML element ### get_linkElement Gets the anchor DOM element of the toolbar button. #### Parameters #### Returns `Element` HTML element ### get_middleWrapElement Gets the DOM element for the middle SPAN that wraps the item. #### Parameters #### Returns `Element` HTML element ### get_outerWrapElement Gets the DOM element for the outermost SPAN that wraps the item. #### Parameters #### Returns `Element` HTML element ### get_text Returns the text of the item. #### Parameters #### Returns `String` string ### get_textElement Gets the DOM element for the text of the item. #### Parameters #### Returns `Element` HTML element ### get_toolBar Returns the toolbar to which the item belongs. #### Parameters #### Returns `Telerik.Web.UI.RadToolBar` RadToolBar ### get_toolTip Returns the text of the item's tool tip. #### Parameters #### Returns `String` ### get_visible True if the item is visible. #### Parameters #### Returns `Boolean` boolean ### hide Hides the toolbar item. #### Parameters #### Returns `None` ### hideDropDown Closes the drop-down list. #### Parameters #### Returns `None` ### set_clickedCssClass Sets the name of the CSS class to be applied to the button when clicked. #### Parameters ##### value `String` value #### Returns `None` ### set_clickedImageUrl Sets the URL of the image when it is clicked. #### Parameters ##### value `String` value #### Returns `None` ### set_disabledCssClass Sets the CSS class for the item when it is disabled. #### Parameters ##### value `String` value #### Returns `None` ### set_disabledImageUrl Sets the DisabledImageUrl property of the item #### Parameters ##### value `String` value #### Returns `None` ### set_enabled Sets whether the item is enabled. #### Parameters ##### value `Boolean` value #### Returns `None` ### set_expandDirection Sets the expand direction of the Toolbar. #### Parameters ##### value `Telerik.Web.UI.ExpandDirection` #### Returns `None` ### set_focused Sets if the item is focused. #### Parameters ##### value `Boolean` value #### Returns `None` ### set_focusedCssClass Sets the name of the CSS class to be applied to the button when on focus. #### Parameters ##### value `String` value #### Returns `None` ### set_focusedImageUrl Sets the URL of the image when on focus. #### Parameters ##### value `String` value #### Returns `None` ### set_hoveredCssClass Sets the name of the CSS class to be applied to the button when hovered. #### Parameters ##### value `String` value #### Returns `None` ### set_hoveredImageUrl Sets the URL for the hovered-state image. #### Parameters ##### value `String` value #### Returns `None` ### set_imagePosition Sets the image position of the toolbar item. #### Parameters ##### value `Telerik.Web.UI.ToolBarImagePosition` #### Returns `None` ### set_imageUrl Sets the URL for the image. #### Parameters ##### value `String` value #### Returns `None` ### set_text Sets the text of the item. #### Parameters ##### text `String` text #### Returns `None` ### set_toolTip Sets the text of the item's tool tip. #### Parameters ##### value `String` value #### Returns `None` ### set_visible Sets if the item is visible. #### Parameters ##### value `Boolean` value #### Returns `None` ### show Shows the toolbar item. #### Parameters #### Returns `None` ### showDropDown Opens the drop-down list. #### Parameters #### Returns `None`
erikruth/ajax-docs
api/client/Telerik.Web.UI.RadToolBarDropDown.md
Markdown
mit
7,353
# you can use tinyint instead of smallint on MySQL ALTER TABLE `spawnpoints` ADD `failures` smallint;
sebast1219/Monocle
sql/add_spawnpoint_failures.sql
SQL
mit
102
package frontend; import templater.PageGenerator; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author v.chibrikov */ public class Frontend extends HttpServlet { private String login = ""; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, Object> pageVariables = new HashMap<>(); pageVariables.put("lastLogin", login == null ? "" : login); response.getWriter().println(PageGenerator.getPage("authform.html", pageVariables)); response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { login = request.getParameter("login"); response.setContentType("text/html;charset=utf-8"); if (login == null || login.isEmpty()) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); } else { response.setStatus(HttpServletResponse.SC_OK); } Map<String, Object> pageVariables = new HashMap<>(); pageVariables.put("lastLogin", login == null ? "" : login); response.getWriter().println(PageGenerator.getPage("authform.html", pageVariables)); } }
KlevtsovStanislav/tp_java_2015_02
L1.1/src/main/java/frontend/Frontend.java
Java
mit
1,582
/****************************************************************************** * Copyright (C) 2006-2012 IFS Institute for Software and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Original authors: * Dennis Hunziker * Ueli Kistler * Reto Schuettel * Robin Stocker * Contributors: * Fabio Zadrozny <fabiofz@gmail.com> - initial implementation ******************************************************************************/ /* * Copyright (C) 2006, 2007 Dennis Hunziker, Ueli Kistler * Copyright (C) 2007 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * */ package org.python.pydev.refactoring.ast.visitors.renamer; import java.util.HashMap; import java.util.Map; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.FunctionDef; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.NameTok; import org.python.pydev.parser.jython.ast.VisitorBase; import org.python.pydev.parser.jython.ast.argumentsType; import org.python.pydev.parser.jython.ast.factory.AdapterPrefs; import org.python.pydev.parser.jython.ast.factory.NodeHelper; public class LocalVarRenameVisitor extends VisitorBase { private Map<String, String> renameMap; private NodeHelper nodeHelper; public LocalVarRenameVisitor(AdapterPrefs adapterPrefs) { this.renameMap = new HashMap<String, String>(); this.nodeHelper = new NodeHelper(adapterPrefs); } public void visit(SimpleNode node) throws Exception { if (node == null) { return; } if (nodeHelper.isFunctionOrClassDef(node)) { return; } node.accept(this); } @Override public void traverse(SimpleNode node) throws Exception { if (node != null) { node.traverse(this); } } @Override public Object visitName(Name node) throws Exception { if (renameMap.containsKey(node.id)) { node.id = renameMap.get(node.id); } return null; } @Override public Object visitNameTok(NameTok node) throws Exception { if (renameMap.containsKey(node.id)) { node.id = renameMap.get(node.id); } return null; } @Override public Object visitFunctionDef(FunctionDef node) throws Exception { // ignore function name visit(node.args); visit(node.body); return null; } private void visit(argumentsType args) throws Exception { visit(args.args); visit(args.vararg); visit(args.kwarg); } @Override public Object visitAttribute(Attribute node) throws Exception { visit(node.value); return null; } private void visit(SimpleNode[] nodes) throws Exception { for (SimpleNode node : nodes) { visit(node); } } @Override protected Object unhandled_node(SimpleNode node) throws Exception { return null; } /** * * @param renameMap * Contains association oldName => newName */ public void setRenameMap(Map<String, String> renameMap) { this.renameMap = renameMap; } }
bobwalker99/Pydev
plugins/org.python.pydev.refactoring/src/org/python/pydev/refactoring/ast/visitors/renamer/LocalVarRenameVisitor.java
Java
epl-1.0
3,520
/* Verify that ftell returns the correct value after a read and a write on a file opened in a+ mode. Copyright (C) 2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <locale.h> #include <wchar.h> /* data points to either char_data or wide_data, depending on whether we're testing regular file mode or wide mode respectively. Similarly, fputs_func points to either fputs or fputws. data_len keeps track of the length of the current data and file_len maintains the current file length. */ #define BUF_LEN 4 static void *buf; static char char_buf[BUF_LEN]; static wchar_t wide_buf[BUF_LEN]; static const void *data; static const char *char_data = "abcdefghijklmnopqrstuvwxyz"; static const wchar_t *wide_data = L"abcdefghijklmnopqrstuvwxyz"; static size_t data_len; static size_t file_len; typedef int (*fputs_func_t) (const void *data, FILE *fp); fputs_func_t fputs_func; typedef void *(*fgets_func_t) (void *s, int size, FILE *stream); fgets_func_t fgets_func; static int do_test (void); #define TEST_FUNCTION do_test () #include "../test-skeleton.c" static FILE * init_file (const char *filename) { FILE *fp = fopen (filename, "w"); if (fp == NULL) { printf ("fopen: %m\n"); return NULL; } int written = fputs_func (data, fp); if (written == EOF) { printf ("fputs failed to write data\n"); fclose (fp); return NULL; } file_len = data_len; fclose (fp); fp = fopen (filename, "a+"); if (fp == NULL) { printf ("fopen(a+): %m\n"); return NULL; } return fp; } static int do_one_test (const char *filename) { FILE *fp = init_file (filename); if (fp == NULL) return 1; void *ret = fgets_func (buf, BUF_LEN, fp); if (ret == NULL) { printf ("read failed: %m\n"); fclose (fp); return 1; } int written = fputs_func (data, fp); if (written == EOF) { printf ("fputs failed to write data\n"); fclose (fp); return 1; } file_len += data_len; long off = ftell (fp); if (off != file_len) { printf ("Incorrect offset %ld, expected %zu\n", off, file_len); fclose (fp); return 1; } else printf ("Correct offset %ld after write.\n", off); return 0; } /* Run the tests for regular files and wide mode files. */ static int do_test (void) { int ret = 0; char *filename; int fd = create_temp_file ("tst-ftell-append-tmp.", &filename); if (fd == -1) { printf ("create_temp_file: %m\n"); return 1; } close (fd); /* Tests for regular files. */ puts ("Regular mode:"); fputs_func = (fputs_func_t) fputs; fgets_func = (fgets_func_t) fgets; data = char_data; buf = char_buf; data_len = strlen (char_data); ret |= do_one_test (filename); /* Tests for wide files. */ puts ("Wide mode:"); if (setlocale (LC_ALL, "en_US.UTF-8") == NULL) { printf ("Cannot set en_US.UTF-8 locale.\n"); return 1; } fputs_func = (fputs_func_t) fputws; fgets_func = (fgets_func_t) fgetws; data = wide_data; buf = wide_buf; data_len = wcslen (wide_data); ret |= do_one_test (filename); return ret; }
rbheromax/src_glibc
libio/tst-ftell-append.c
C
gpl-2.0
3,995
/* * f_bpf.c BPF-based Classifier * * This program is free software; you can distribute 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. * * Authors: Daniel Borkmann <daniel@iogearbox.net> */ #include <stdio.h> #include <stdlib.h> #include <linux/bpf.h> #include "utils.h" #include "tc_util.h" #include "bpf_util.h" static const enum bpf_prog_type bpf_type = BPF_PROG_TYPE_SCHED_CLS; static void explain(void) { fprintf(stderr, "Usage: ... bpf ...\n"); fprintf(stderr, "\n"); fprintf(stderr, "BPF use case:\n"); fprintf(stderr, " bytecode BPF_BYTECODE\n"); fprintf(stderr, " bytecode-file FILE\n"); fprintf(stderr, "\n"); fprintf(stderr, "eBPF use case:\n"); fprintf(stderr, " object-file FILE [ section CLS_NAME ] [ export UDS_FILE ]"); fprintf(stderr, " [ verbose ] [ direct-action ] [ skip_hw | skip_sw ]\n"); fprintf(stderr, " object-pinned FILE [ direct-action ] [ skip_hw | skip_sw ]\n"); fprintf(stderr, "\n"); fprintf(stderr, "Common remaining options:\n"); fprintf(stderr, " [ action ACTION_SPEC ]\n"); fprintf(stderr, " [ classid CLASSID ]\n"); fprintf(stderr, "\n"); fprintf(stderr, "Where BPF_BYTECODE := \'s,c t f k,c t f k,c t f k,...\'\n"); fprintf(stderr, "c,t,f,k and s are decimals; s denotes number of 4-tuples\n"); fprintf(stderr, "\n"); fprintf(stderr, "Where FILE points to a file containing the BPF_BYTECODE string,\n"); fprintf(stderr, "an ELF file containing eBPF map definitions and bytecode, or a\n"); fprintf(stderr, "pinned eBPF program.\n"); fprintf(stderr, "\n"); fprintf(stderr, "Where CLS_NAME refers to the section name containing the\n"); fprintf(stderr, "classifier (default \'%s\').\n", bpf_prog_to_default_section(bpf_type)); fprintf(stderr, "\n"); fprintf(stderr, "Where UDS_FILE points to a unix domain socket file in order\n"); fprintf(stderr, "to hand off control of all created eBPF maps to an agent.\n"); fprintf(stderr, "\n"); fprintf(stderr, "ACTION_SPEC := ... look at individual actions\n"); fprintf(stderr, "NOTE: CLASSID is parsed as hexadecimal input.\n"); } static void bpf_cbpf_cb(void *nl, const struct sock_filter *ops, int ops_len) { addattr16(nl, MAX_MSG, TCA_BPF_OPS_LEN, ops_len); addattr_l(nl, MAX_MSG, TCA_BPF_OPS, ops, ops_len * sizeof(struct sock_filter)); } static void bpf_ebpf_cb(void *nl, int fd, const char *annotation) { addattr32(nl, MAX_MSG, TCA_BPF_FD, fd); addattrstrz(nl, MAX_MSG, TCA_BPF_NAME, annotation); } static const struct bpf_cfg_ops bpf_cb_ops = { .cbpf_cb = bpf_cbpf_cb, .ebpf_cb = bpf_ebpf_cb, }; static int bpf_parse_opt(struct filter_util *qu, char *handle, int argc, char **argv, struct nlmsghdr *n) { const char *bpf_obj = NULL, *bpf_uds_name = NULL; struct tcmsg *t = NLMSG_DATA(n); unsigned int bpf_gen_flags = 0; unsigned int bpf_flags = 0; struct bpf_cfg_in cfg = {}; bool seen_run = false; bool skip_sw = false; struct rtattr *tail; int ret = 0; if (handle) { if (get_u32(&t->tcm_handle, handle, 0)) { fprintf(stderr, "Illegal \"handle\"\n"); return -1; } } if (argc == 0) return 0; tail = (struct rtattr *)(((void *)n) + NLMSG_ALIGN(n->nlmsg_len)); addattr_l(n, MAX_MSG, TCA_OPTIONS, NULL, 0); while (argc > 0) { if (matches(*argv, "run") == 0) { NEXT_ARG(); if (seen_run) duparg("run", *argv); opt_bpf: seen_run = true; cfg.type = bpf_type; cfg.argc = argc; cfg.argv = argv; if (bpf_parse_common(&cfg, &bpf_cb_ops) < 0) { fprintf(stderr, "Unable to parse bpf command line\n"); return -1; } argc = cfg.argc; argv = cfg.argv; bpf_obj = cfg.object; bpf_uds_name = cfg.uds; } else if (matches(*argv, "classid") == 0 || matches(*argv, "flowid") == 0) { unsigned int handle; NEXT_ARG(); if (get_tc_classid(&handle, *argv)) { fprintf(stderr, "Illegal \"classid\"\n"); return -1; } addattr32(n, MAX_MSG, TCA_BPF_CLASSID, handle); } else if (matches(*argv, "direct-action") == 0 || matches(*argv, "da") == 0) { bpf_flags |= TCA_BPF_FLAG_ACT_DIRECT; } else if (matches(*argv, "skip_hw") == 0) { bpf_gen_flags |= TCA_CLS_FLAGS_SKIP_HW; } else if (matches(*argv, "skip_sw") == 0) { bpf_gen_flags |= TCA_CLS_FLAGS_SKIP_SW; skip_sw = true; } else if (matches(*argv, "action") == 0) { NEXT_ARG(); if (parse_action(&argc, &argv, TCA_BPF_ACT, n)) { fprintf(stderr, "Illegal \"action\"\n"); return -1; } continue; } else if (matches(*argv, "police") == 0) { NEXT_ARG(); if (parse_police(&argc, &argv, TCA_BPF_POLICE, n)) { fprintf(stderr, "Illegal \"police\"\n"); return -1; } continue; } else if (matches(*argv, "help") == 0) { explain(); return -1; } else { if (!seen_run) goto opt_bpf; fprintf(stderr, "What is \"%s\"?\n", *argv); explain(); return -1; } NEXT_ARG_FWD(); } if (skip_sw) cfg.ifindex = t->tcm_ifindex; if (bpf_load_common(&cfg, &bpf_cb_ops, n) < 0) { fprintf(stderr, "Unable to load program\n"); return -1; } if (bpf_gen_flags) addattr32(n, MAX_MSG, TCA_BPF_FLAGS_GEN, bpf_gen_flags); if (bpf_flags) addattr32(n, MAX_MSG, TCA_BPF_FLAGS, bpf_flags); tail->rta_len = (((void *)n) + n->nlmsg_len) - (void *)tail; if (bpf_uds_name) ret = bpf_send_map_fds(bpf_uds_name, bpf_obj); return ret; } static int bpf_print_opt(struct filter_util *qu, FILE *f, struct rtattr *opt, __u32 handle) { struct rtattr *tb[TCA_BPF_MAX + 1]; int dump_ok = 0; if (opt == NULL) return 0; parse_rtattr_nested(tb, TCA_BPF_MAX, opt); if (handle) fprintf(f, "handle 0x%x ", handle); if (tb[TCA_BPF_CLASSID]) { SPRINT_BUF(b1); fprintf(f, "flowid %s ", sprint_tc_classid(rta_getattr_u32(tb[TCA_BPF_CLASSID]), b1)); } if (tb[TCA_BPF_NAME]) fprintf(f, "%s ", rta_getattr_str(tb[TCA_BPF_NAME])); if (tb[TCA_BPF_FLAGS]) { unsigned int flags = rta_getattr_u32(tb[TCA_BPF_FLAGS]); if (flags & TCA_BPF_FLAG_ACT_DIRECT) fprintf(f, "direct-action "); } if (tb[TCA_BPF_FLAGS_GEN]) { unsigned int flags = rta_getattr_u32(tb[TCA_BPF_FLAGS_GEN]); if (flags & TCA_CLS_FLAGS_SKIP_HW) fprintf(f, "skip_hw "); if (flags & TCA_CLS_FLAGS_SKIP_SW) fprintf(f, "skip_sw "); if (flags & TCA_CLS_FLAGS_IN_HW) fprintf(f, "in_hw "); else if (flags & TCA_CLS_FLAGS_NOT_IN_HW) fprintf(f, "not_in_hw "); } if (tb[TCA_BPF_OPS] && tb[TCA_BPF_OPS_LEN]) bpf_print_ops(f, tb[TCA_BPF_OPS], rta_getattr_u16(tb[TCA_BPF_OPS_LEN])); if (tb[TCA_BPF_ID]) dump_ok = bpf_dump_prog_info(f, rta_getattr_u32(tb[TCA_BPF_ID])); if (!dump_ok && tb[TCA_BPF_TAG]) { SPRINT_BUF(b); fprintf(f, "tag %s ", hexstring_n2a(RTA_DATA(tb[TCA_BPF_TAG]), RTA_PAYLOAD(tb[TCA_BPF_TAG]), b, sizeof(b))); } if (tb[TCA_BPF_POLICE]) { fprintf(f, "\n"); tc_print_police(f, tb[TCA_BPF_POLICE]); } if (tb[TCA_BPF_ACT]) tc_print_action(f, tb[TCA_BPF_ACT], 0); return 0; } struct filter_util bpf_filter_util = { .id = "bpf", .parse_fopt = bpf_parse_opt, .print_fopt = bpf_print_opt, };
ndev2/iproute2-final
tc/f_bpf.c
C
gpl-2.0
7,174
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing authors: Mark Stevens (SNL), Aidan Thompson (SNL) ------------------------------------------------------------------------- */ #include <cstring> #include <cstdlib> #include <cmath> #include "fix_nh_cuda.h" #include "atom.h" #include "force.h" #include "comm.h" #include "modify.h" #include "fix_deform.h" #include "compute.h" #include "kspace.h" #include "update.h" #include "respa.h" #include "domain.h" #include "memory.h" #include "error.h" #include "math_extra.h" #include "cuda.h" #include "fix_nh_cuda_cu.h" #include "cuda_modify_flags.h" using namespace LAMMPS_NS; using namespace FixConst; using namespace FixConstCuda; enum{NOBIAS,BIAS}; enum{NONE,XYZ,XY,YZ,XZ}; enum{ISO,ANISO,TRICLINIC}; /* ---------------------------------------------------------------------- NVT,NPH,NPT integrators for improved Nose-Hoover equations of motion ---------------------------------------------------------------------- */ FixNHCuda::FixNHCuda(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg) { cuda = lmp->cuda; if(cuda == NULL) error->all(FLERR,"You cannot use a /cuda class, without activating 'cuda' acceleration. Provide '-c on' as command-line argument to LAMMPS.."); if (narg < 4) error->all(FLERR,"Illegal fix nvt/npt/nph command"); restart_global = 1; time_integrate = 1; scalar_flag = 1; vector_flag = 1; global_freq = 1; extscalar = 1; extvector = 0; triggerneighsq = -1; // default values pcouple = NONE; drag = 0.0; allremap = 1; mtchain = mpchain = 3; nc_tchain = nc_pchain = 1; mtk_flag = 1; deviatoric_flag = 0; nreset_h0 = 0; // Used by FixNVTSllod to preserve non-default value mtchain_default_flag = 1; tstat_flag = 0; double t_period = 0.0; double p_period[6]; for (int i = 0; i < 6; i++) { p_start[i] = p_stop[i] = p_period[i] = 0.0; p_flag[i] = 0; } // process keywords dimension = domain->dimension; int iarg = 3; while (iarg < narg) { if (strcmp(arg[iarg],"temp") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); tstat_flag = 1; t_start = force->numeric(FLERR,arg[iarg+1]); t_stop = force->numeric(FLERR,arg[iarg+2]); t_period = force->numeric(FLERR,arg[iarg+3]); if (t_start < 0.0 || t_stop <= 0.0) error->all(FLERR,"Target T for fix nvt/npt/nph cannot be 0.0"); iarg += 4; } else if (strcmp(arg[iarg],"iso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); pcouple = XYZ; p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"aniso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); pcouple = NONE; p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"tri") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); pcouple = NONE; p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; p_start[3] = p_start[4] = p_start[5] = 0.0; p_stop[3] = p_stop[4] = p_stop[5] = 0.0; p_period[3] = p_period[4] = p_period[5] = force->numeric(FLERR,arg[iarg+3]); p_flag[3] = p_flag[4] = p_flag[5] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; p_start[3] = p_stop[3] = p_period[3] = 0.0; p_flag[3] = 0; p_start[4] = p_stop[4] = p_period[4] = 0.0; p_flag[4] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"x") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); p_start[0] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = 1; deviatoric_flag = 1; iarg += 4; } else if (strcmp(arg[iarg],"y") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); p_start[1] = force->numeric(FLERR,arg[iarg+1]); p_stop[1] = force->numeric(FLERR,arg[iarg+2]); p_period[1] = force->numeric(FLERR,arg[iarg+3]); p_flag[1] = 1; deviatoric_flag = 1; iarg += 4; } else if (strcmp(arg[iarg],"z") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[2] = 1; deviatoric_flag = 1; iarg += 4; if (dimension == 2) error->all(FLERR,"Invalid fix nvt/npt/nph command for a 2d simulation"); } else if (strcmp(arg[iarg],"yz") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); p_start[3] = force->numeric(FLERR,arg[iarg+1]); p_stop[3] = force->numeric(FLERR,arg[iarg+2]); p_period[3] = force->numeric(FLERR,arg[iarg+3]); p_flag[3] = 1; deviatoric_flag = 1; iarg += 4; if (dimension == 2) error->all(FLERR,"Invalid fix nvt/npt/nph command for a 2d simulation"); } else if (strcmp(arg[iarg],"xz") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); p_start[4] = force->numeric(FLERR,arg[iarg+1]); p_stop[4] = force->numeric(FLERR,arg[iarg+2]); p_period[4] = force->numeric(FLERR,arg[iarg+3]); p_flag[4] = 1; deviatoric_flag = 1; iarg += 4; if (dimension == 2) error->all(FLERR,"Invalid fix nvt/npt/nph command for a 2d simulation"); } else if (strcmp(arg[iarg],"xy") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); p_start[5] = force->numeric(FLERR,arg[iarg+1]); p_stop[5] = force->numeric(FLERR,arg[iarg+2]); p_period[5] = force->numeric(FLERR,arg[iarg+3]); p_flag[5] = 1; deviatoric_flag = 1; iarg += 4; } else if (strcmp(arg[iarg],"couple") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); if (strcmp(arg[iarg+1],"xyz") == 0) pcouple = XYZ; else if (strcmp(arg[iarg+1],"xy") == 0) pcouple = XY; else if (strcmp(arg[iarg+1],"yz") == 0) pcouple = YZ; else if (strcmp(arg[iarg+1],"xz") == 0) pcouple = XZ; else if (strcmp(arg[iarg+1],"none") == 0) pcouple = NONE; else error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"drag") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); drag = force->numeric(FLERR,arg[iarg+1]); if (drag < 0.0) error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"dilate") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); if (strcmp(arg[iarg+1],"all") == 0) allremap = 1; else if (strcmp(arg[iarg+1],"partial") == 0) allremap = 0; else error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"tchain") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); mtchain = force->inumeric(FLERR,arg[iarg+1]); if (mtchain < 1) error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"pchain") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); mpchain = force->inumeric(FLERR,arg[iarg+1]); if (mpchain < 0) error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"mtk") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); if (strcmp(arg[iarg+1],"yes") == 0) mtk_flag = 1; else if (strcmp(arg[iarg+1],"no") == 0) mtk_flag = 0; else error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"tloop") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); nc_tchain = force->inumeric(FLERR,arg[iarg+1]); if (nc_tchain < 0) error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"ploop") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); nc_pchain = force->inumeric(FLERR,arg[iarg+1]); if (nc_pchain < 0) error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else if (strcmp(arg[iarg],"nreset") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix nvt/npt/nph command"); nreset_h0 = force->inumeric(FLERR,arg[iarg+1]); if (nreset_h0 < 0) error->all(FLERR,"Illegal fix nvt/npt/nph command"); iarg += 2; } else error->all(FLERR,"Illegal fix nvt/npt/nph command"); } // error checks if (dimension == 2 && (p_flag[2] || p_flag[3] || p_flag[4])) error->all(FLERR,"Invalid fix nvt/npt/nph command for a 2d simulation"); if (dimension == 2 && (pcouple == YZ || pcouple == XZ)) error->all(FLERR,"Invalid fix nvt/npt/nph command for a 2d simulation"); if (pcouple == XYZ && (p_flag[0] == 0 || p_flag[1] == 0)) error->all(FLERR,"Invalid fix nvt/npt/nph command pressure settings"); if (pcouple == XYZ && dimension == 3 && p_flag[2] == 0) error->all(FLERR,"Invalid fix nvt/npt/nph command pressure settings"); if (pcouple == XY && (p_flag[0] == 0 || p_flag[1] == 0)) error->all(FLERR,"Invalid fix nvt/npt/nph command pressure settings"); if (pcouple == YZ && (p_flag[1] == 0 || p_flag[2] == 0)) error->all(FLERR,"Invalid fix nvt/npt/nph command pressure settings"); if (pcouple == XZ && (p_flag[0] == 0 || p_flag[2] == 0)) error->all(FLERR,"Invalid fix nvt/npt/nph command pressure settings"); if (p_flag[0] && domain->xperiodic == 0) error->all(FLERR,"Cannot use fix nvt/npt/nph on a non-periodic dimension"); if (p_flag[1] && domain->yperiodic == 0) error->all(FLERR,"Cannot use fix nvt/npt/nph on a non-periodic dimension"); if (p_flag[2] && domain->zperiodic == 0) error->all(FLERR,"Cannot use fix nvt/npt/nph on a non-periodic dimension"); if (p_flag[3] && domain->zperiodic == 0) error->all(FLERR,"Cannot use fix nvt/npt/nph on a 2nd non-periodic dimension"); if (p_flag[4] && domain->zperiodic == 0) error->all(FLERR,"Cannot use fix nvt/npt/nph on a 2nd non-periodic dimension"); if (p_flag[5] && domain->yperiodic == 0) error->all(FLERR,"Cannot use fix nvt/npt/nph on a 2nd non-periodic dimension"); if (!domain->triclinic && (p_flag[3] || p_flag[4] || p_flag[5])) error->all(FLERR,"Can not specify Pxy/Pxz/Pyz in " "fix nvt/npt/nph with non-triclinic box"); if (pcouple == XYZ && dimension == 3 && (p_start[0] != p_start[1] || p_start[0] != p_start[2] || p_stop[0] != p_stop[1] || p_stop[0] != p_stop[2] || p_period[0] != p_period[1] || p_period[0] != p_period[2])) error->all(FLERR,"Invalid fix nvt/npt/nph pressure settings"); if (pcouple == XYZ && dimension == 2 && (p_start[0] != p_start[1] || p_stop[0] != p_stop[1] || p_period[0] != p_period[1])) error->all(FLERR,"Invalid fix nvt/npt/nph pressure settings"); if (pcouple == XY && (p_start[0] != p_start[1] || p_stop[0] != p_stop[1] || p_period[0] != p_period[1])) error->all(FLERR,"Invalid fix nvt/npt/nph pressure settings"); if (pcouple == YZ && (p_start[1] != p_start[2] || p_stop[1] != p_stop[2] || p_period[1] != p_period[2])) error->all(FLERR,"Invalid fix nvt/npt/nph pressure settings"); if (pcouple == XZ && (p_start[0] != p_start[2] || p_stop[0] != p_stop[2] || p_period[0] != p_period[2])) error->all(FLERR,"Invalid fix nvt/npt/nph pressure settings"); if ((tstat_flag && t_period <= 0.0) || (p_flag[0] && p_period[0] <= 0.0) || (p_flag[1] && p_period[1] <= 0.0) || (p_flag[2] && p_period[2] <= 0.0) || (p_flag[3] && p_period[3] <= 0.0) || (p_flag[4] && p_period[4] <= 0.0) || (p_flag[5] && p_period[5] <= 0.0)) error->all(FLERR,"Fix nvt/npt/nph damping parameters must be > 0.0"); // set pstat_flag and box change variables pstat_flag = 0; for (int i = 0; i < 6; i++) if (p_flag[i]) pstat_flag = 1; if (pstat_flag) { if (p_flag[0] || p_flag[1] || p_flag[2]) box_change_size = 1; if (p_flag[3] || p_flag[4] || p_flag[5]) box_change_shape = 1; no_change_box = 1; if (allremap == 0) restart_pbc = 1; } // pstyle = TRICLINIC if any off-diagonal term is controlled -> 6 dof // else pstyle = ISO if XYZ coupling or XY coupling in 2d -> 1 dof // else pstyle = ANISO -> 3 dof if (p_flag[3] || p_flag[4] || p_flag[5]) pstyle = TRICLINIC; else if (pcouple == XYZ || (dimension == 2 && pcouple == XY)) pstyle = ISO; else pstyle = ANISO; // convert input periods to frequencies t_freq = 0.0; p_freq[0] = p_freq[1] = p_freq[2] = p_freq[3] = p_freq[4] = p_freq[5] = 0.0; if (tstat_flag) t_freq = 1.0 / t_period; if (p_flag[0]) p_freq[0] = 1.0 / p_period[0]; if (p_flag[1]) p_freq[1] = 1.0 / p_period[1]; if (p_flag[2]) p_freq[2] = 1.0 / p_period[2]; if (p_flag[3]) p_freq[3] = 1.0 / p_period[3]; if (p_flag[4]) p_freq[4] = 1.0 / p_period[4]; if (p_flag[5]) p_freq[5] = 1.0 / p_period[5]; // Nose/Hoover temp and pressure init size_vector = 0; if (tstat_flag) { int ich; eta = new double[mtchain]; // add one extra dummy thermostat, set to zero eta_dot = new double[mtchain+1]; eta_dot[mtchain] = 0.0; eta_dotdot = new double[mtchain]; for (ich = 0; ich < mtchain; ich++) { eta[ich] = eta_dot[ich] = eta_dotdot[ich] = 0.0; } eta_mass = new double[mtchain]; size_vector += 2*2*mtchain; } if (pstat_flag) { omega[0] = omega[1] = omega[2] = 0.0; omega_dot[0] = omega_dot[1] = omega_dot[2] = 0.0; omega_mass[0] = omega_mass[1] = omega_mass[2] = 0.0; omega[3] = omega[4] = omega[5] = 0.0; omega_dot[3] = omega_dot[4] = omega_dot[5] = 0.0; omega_mass[3] = omega_mass[4] = omega_mass[5] = 0.0; if (pstyle == ISO) size_vector += 2*2*1; else if (pstyle == ANISO) size_vector += 2*2*3; else if (pstyle == TRICLINIC) size_vector += 2*2*6; if (mpchain) { int ich; etap = new double[mpchain]; // add one extra dummy thermostat, set to zero etap_dot = new double[mpchain+1]; etap_dot[mpchain] = 0.0; etap_dotdot = new double[mpchain]; for (ich = 0; ich < mpchain; ich++) { etap[ich] = etap_dot[ich] = etap_dotdot[ich] = 0.0; } etap_mass = new double[mpchain]; size_vector += 2*2*mpchain; } if (deviatoric_flag) size_vector += 1; } nrigid = 0; rfix = NULL; // initialize vol0,t0 to zero to signal uninitialized // values then assigned in init(), if necessary vol0 = t0 = 0.0; } /* ---------------------------------------------------------------------- */ FixNHCuda::~FixNHCuda() { delete [] rfix; // delete temperature and pressure if fix created them if (tflag) modify->delete_compute(id_temp); delete [] id_temp; if (tstat_flag) { delete [] eta; delete [] eta_dot; delete [] eta_dotdot; delete [] eta_mass; } if (pstat_flag) { if (pflag) modify->delete_compute(id_press); delete [] id_press; if (mpchain) { delete [] etap; delete [] etap_dot; delete [] etap_dotdot; delete [] etap_mass; } } } /* ---------------------------------------------------------------------- */ int FixNHCuda::setmask() { int mask = 0; mask |= INITIAL_INTEGRATE_CUDA; mask |= FINAL_INTEGRATE_CUDA; mask |= THERMO_ENERGY_CUDA; //mask |= INITIAL_INTEGRATE_RESPA; //mask |= FINAL_INTEGRATE_RESPA; return mask; } /* ---------------------------------------------------------------------- */ void FixNHCuda::init() { // insure no conflict with fix deform if (pstat_flag) for (int i = 0; i < modify->nfix; i++) if (strcmp(modify->fix[i]->style,"deform") == 0) { int *dimflag = ((FixDeform *) modify->fix[i])->dimflag; if ((p_flag[0] && dimflag[0]) || (p_flag[1] && dimflag[1]) || (p_flag[2] && dimflag[2]) || (p_flag[3] && dimflag[3]) || (p_flag[4] && dimflag[4]) || (p_flag[5] && dimflag[5])) error->all(FLERR,"Cannot use fix npt and fix deform on " "same component of stress tensor"); } // set temperature and pressure ptrs int icompute = modify->find_compute(id_temp); if (icompute < 0) error->all(FLERR,"Temperature ID for fix nvt/nph/npt does not exist"); temperature = modify->compute[icompute]; if (temperature->tempbias) which = BIAS; else which = NOBIAS; if (pstat_flag) { icompute = modify->find_compute(id_press); if (icompute < 0) error->all(FLERR,"Pressure ID for fix npt/nph does not exist"); pressure = modify->compute[icompute]; } // set timesteps and frequencies dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dthalf = 0.5 * update->dt; dt4 = 0.25 * update->dt; dt8 = 0.125 * update->dt; dto = dthalf; p_freq_max = 0.0; if (pstat_flag) { p_freq_max = MAX(p_freq[0],p_freq[1]); p_freq_max = MAX(p_freq_max,p_freq[2]); if (pstyle == TRICLINIC) { p_freq_max = MAX(p_freq_max,p_freq[3]); p_freq_max = MAX(p_freq_max,p_freq[4]); p_freq_max = MAX(p_freq_max,p_freq[5]); } pdrag_factor = 1.0 - (update->dt * p_freq_max * drag / nc_pchain); } if (tstat_flag) tdrag_factor = 1.0 - (update->dt * t_freq * drag / nc_tchain); // tally the number of dimensions that are barostatted // also compute the initial volume and reference cell // set initial volume and reference cell, if not already done if (pstat_flag) { pdim = p_flag[0] + p_flag[1] + p_flag[2]; if (vol0 == 0.0) { if (dimension == 3) vol0 = domain->xprd * domain->yprd * domain->zprd; else vol0 = domain->xprd * domain->yprd; h0_inv[0] = domain->h_inv[0]; h0_inv[1] = domain->h_inv[1]; h0_inv[2] = domain->h_inv[2]; h0_inv[3] = domain->h_inv[3]; h0_inv[4] = domain->h_inv[4]; h0_inv[5] = domain->h_inv[5]; } } boltz = force->boltz; nktv2p = force->nktv2p; if (force->kspace) kspace_flag = 1; else kspace_flag = 0; if (strcmp(update->integrate_style,"respa") == 0) { nlevels_respa = ((Respa *) update->integrate)->nlevels; step_respa = ((Respa *) update->integrate)->step; dto = 0.5*step_respa[0]; } // detect if any rigid fixes exist so rigid bodies move when box is remapped // rfix[] = indices to each fix rigid delete [] rfix; nrigid = 0; rfix = NULL; for (int i = 0; i < modify->nfix; i++) if (modify->fix[i]->rigid_flag) nrigid++; if (nrigid) { rfix = new int[nrigid]; nrigid = 0; for (int i = 0; i < modify->nfix; i++) if (modify->fix[i]->rigid_flag) rfix[nrigid++] = i; } triggerneighsq= cuda->shared_data.atom.triggerneighsq; cuda->neighbor_decide_by_integrator=1; Cuda_FixNHCuda_Init(&cuda->shared_data,dtv,dtf); } /* ---------------------------------------------------------------------- compute T,P before integrator starts ------------------------------------------------------------------------- */ void FixNHCuda::setup(int vflag) { // initialize some quantities that were not available earlier //if (mtk_flag) mtk_factor = 1.0 + 1.0/atom->natoms; //else mtk_factor = 1.0; tdof = temperature->dof; // t_target is used by compute_scalar(), even for NPH if (tstat_flag) t_target = t_start; else if (pstat_flag) { // t0 = initial value for piston mass and energy conservation // cannot be done in init() b/c temperature cannot be called there // is b/c Modify::init() inits computes after fixes due to dof dependence // guesstimate a unit-dependent t0 if actual T = 0.0 // if it was read in from a restart file, leave it be if (t0 == 0.0) { t0 = temperature->compute_scalar(); if (t0 == 0.0) { if (strcmp(update->unit_style,"lj") == 0) t0 = 1.0; else t0 = 300.0; } } t_target = t0; } if (pstat_flag) compute_press_target(); t_current = temperature->compute_scalar(); if (pstat_flag) { if (pstyle == ISO) double tmp = pressure->compute_scalar(); else pressure->compute_vector(); couple(); pressure->addstep(update->ntimestep+1); } // initial forces on thermostat variables if (tstat_flag) { eta_mass[0] = tdof * boltz * t_target / (t_freq*t_freq); for (int ich = 1; ich < mtchain; ich++) eta_mass[ich] = boltz * t_target / (t_freq*t_freq); for (int ich = 1; ich < mtchain; ich++) { eta_dotdot[ich] = (eta_mass[ich-1]*eta_dot[ich-1]*eta_dot[ich-1] - boltz*t_target) / eta_mass[ich]; } } if (pstat_flag) { double kt = boltz * t_target; double nkt = atom->natoms * kt; for (int i = 0; i < 3; i++) if (p_flag[i]) omega_mass[i] = nkt/(p_freq[i]*p_freq[i]); if (pstyle == TRICLINIC) { for (int i = 3; i < 6; i++) if (p_flag[i]) omega_mass[i] = nkt/(p_freq[i]*p_freq[i]); } // initial forces on barostat thermostat variables if (mpchain) { etap_mass[0] = boltz * t_target / (p_freq_max*p_freq_max); for (int ich = 1; ich < mpchain; ich++) etap_mass[ich] = boltz * t_target / (p_freq_max*p_freq_max); for (int ich = 1; ich < mpchain; ich++) etap_dotdot[ich] = (etap_mass[ich-1]*etap_dot[ich-1]*etap_dot[ich-1] - boltz*t_target) / etap_mass[ich]; } // compute appropriately coupled elements of mvv_current //if (mtk_flag) couple_ke(); } } /* ---------------------------------------------------------------------- 1st half of Verlet update ------------------------------------------------------------------------- */ void FixNHCuda::initial_integrate(int vflag) { if(!temperature->cudable) cuda->downloadAll(); if(triggerneighsq!=cuda->shared_data.atom.triggerneighsq) { triggerneighsq= cuda->shared_data.atom.triggerneighsq; Cuda_FixNHCuda_Init(&cuda->shared_data,dtv,dtf); } // update eta_press_dot if (pstat_flag && mpchain) nhc_press_integrate(); // update eta_dot if (tstat_flag) { double delta = update->ntimestep - update->beginstep; delta /= update->endstep - update->beginstep; t_target = t_start + delta * (t_stop-t_start); eta_mass[0] = tdof * boltz * t_target / (t_freq*t_freq); for (int ich = 1; ich < mtchain; ich++) eta_mass[ich] = boltz * t_target / (t_freq*t_freq); nhc_temp_integrate(); } // need to recompute pressure to account for change in KE // t_current is up-to-date, but compute_temperature is not // compute appropriately coupled elements of mvv_current if (pstat_flag) { if (pstyle == ISO) { temperature->compute_scalar(); double tmp = pressure->compute_scalar(); } else { temperature->compute_vector(); pressure->compute_vector(); } couple(); pressure->addstep(update->ntimestep+1); //if (mtk_flag) couple_ke(); } if(which==NOBIAS) { if (pstat_flag) { compute_press_target(); nh_omega_dot(); factor[0] = exp(-dt4*(omega_dot[0]+mtk_term2)); factor[1] = exp(-dt4*(omega_dot[1]+mtk_term2)); factor[2] = exp(-dt4*(omega_dot[2]+mtk_term2)); Cuda_FixNHCuda_nh_v_press_and_nve_v_NoBias(&cuda->shared_data, groupbit, factor,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal,(pstyle == TRICLINIC)?1:0); } else Cuda_FixNHCuda_nve_v(&cuda->shared_data,groupbit,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal); } else if(which==BIAS) { if(pstat_flag) { compute_press_target(); nh_omega_dot(); factor[0] = exp(-dt4*(omega_dot[0]+mtk_term2)); factor[1] = exp(-dt4*(omega_dot[1]+mtk_term2)); factor[2] = exp(-dt4*(omega_dot[2]+mtk_term2)); if(!temperature->cudable) { nh_v_press(); cuda->cu_v->upload(); } else { int groupbit_org=temperature->groupbit; temperature->groupbit=groupbit; temperature->remove_bias_all(); Cuda_FixNHCuda_nh_v_press(&cuda->shared_data, groupbit, factor,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal,(pstyle == TRICLINIC)?1:0); temperature->restore_bias_all(); temperature->groupbit=groupbit_org; } } Cuda_FixNHCuda_nve_v(&cuda->shared_data,groupbit,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal); } // remap simulation box by 1/2 step if (pstat_flag) remap(); Cuda_FixNHCuda_nve_x(&cuda->shared_data,groupbit,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal); // remap simulation box by 1/2 step // redo KSpace coeffs since volume has changed if (pstat_flag) { remap(); if (kspace_flag) force->kspace->setup(); } } /* ---------------------------------------------------------------------- 2nd half of Verlet update ------------------------------------------------------------------------- */ void FixNHCuda::final_integrate() { if(!temperature->cudable) cuda->downloadAll(); if(which==NOBIAS) { if(pstat_flag) { factor[0] = exp(-dt4*(omega_dot[0]+mtk_term2)); factor[1] = exp(-dt4*(omega_dot[1]+mtk_term2)); factor[2] = exp(-dt4*(omega_dot[2]+mtk_term2)); Cuda_FixNHCuda_nve_v_and_nh_v_press_NoBias(&cuda->shared_data, groupbit, factor,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal,(pstyle == TRICLINIC)?1:0); } else Cuda_FixNHCuda_nve_v(&cuda->shared_data,groupbit,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal); } else if(which==BIAS) { Cuda_FixNHCuda_nve_v(&cuda->shared_data,groupbit,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal); if(pstat_flag) { factor[0] = exp(-dt4*(omega_dot[0]+mtk_term2)); factor[1] = exp(-dt4*(omega_dot[1]+mtk_term2)); factor[2] = exp(-dt4*(omega_dot[2]+mtk_term2)); if(!temperature->cudable) { cuda->cu_v->download(); nh_v_press(); cuda->cu_v->upload(); } else { int groupbit_org=temperature->groupbit; temperature->groupbit=groupbit; temperature->remove_bias_all(); Cuda_FixNHCuda_nh_v_press(&cuda->shared_data, groupbit, factor,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal,(pstyle == TRICLINIC)?1:0); temperature->restore_bias_all(); temperature->groupbit=groupbit_org; } } } // compute new T,P // compute appropriately coupled elements of mvv_current if(!temperature->cudable) cuda->cu_v->download(); t_current = temperature->compute_scalar(); if (pstat_flag) { if (pstyle == ISO) double tmp = pressure->compute_scalar(); else pressure->compute_vector(); couple(); pressure->addstep(update->ntimestep+1); } if (pstat_flag) nh_omega_dot(); // update eta_dot // update eta_press_dot if (tstat_flag) nhc_temp_integrate(); if (pstat_flag && mpchain) nhc_press_integrate(); } /* ---------------------------------------------------------------------- */ void FixNHCuda::initial_integrate_respa(int vflag, int ilevel, int iloop) { int i; // set timesteps by level dtv = step_respa[ilevel]; dtf = 0.5 * step_respa[ilevel] * force->ftm2v; dthalf = 0.5 * step_respa[ilevel]; // outermost level - update eta_dot and omega_dot, apply to v, remap box // all other levels - NVE update of v // x,v updates only performed for atoms in group if (ilevel == nlevels_respa-1) { // update eta_press_dot if (pstat_flag && mpchain) nhc_press_integrate(); // update eta_dot if (tstat_flag) { double delta = update->ntimestep - update->beginstep; delta /= update->endstep - update->beginstep; t_target = t_start + delta * (t_stop-t_start); eta_mass[0] = tdof * boltz * t_target / (t_freq*t_freq); for (int ich = 1; ich < mtchain; ich++) eta_mass[ich] = boltz * t_target / (t_freq*t_freq); nhc_temp_integrate(); } // recompute pressure to account for change in KE // t_current is up-to-date, but compute_temperature is not // compute appropriately coupled elements of mvv_current if (pstat_flag) { if (pstyle == ISO) { temperature->compute_scalar(); double tmp = pressure->compute_scalar(); } else { temperature->compute_vector(); pressure->compute_vector(); } couple(); pressure->addstep(update->ntimestep+1); if (mtk_flag) couple_ke(); } if (pstat_flag) { compute_press_target(); nh_omega_dot(); nh_v_press(); } nve_v(); } else nve_v(); // innermost level - also update x only for atoms in group // if barostat, perform 1/2 step remap before and after if (ilevel == 0) { if (pstat_flag) remap(); nve_x(); if (pstat_flag) remap(); } // if barostat, redo KSpace coeffs at outermost level, // since volume has changed if (ilevel == nlevels_respa-1 && kspace_flag && pstat_flag) force->kspace->setup(); } /* ---------------------------------------------------------------------- */ void FixNHCuda::final_integrate_respa(int ilevel, int iloop) { // set timesteps by level dtf = 0.5 * step_respa[ilevel] * force->ftm2v; dthalf = 0.5 * step_respa[ilevel]; // outermost level - update eta_dot and omega_dot, apply via final_integrate // all other levels - NVE update of v if (ilevel == nlevels_respa-1) final_integrate(); else nve_v(); } /* ---------------------------------------------------------------------- */ void FixNHCuda::couple() { double *tensor = pressure->vector; if (pstyle == ISO) p_current[0] = p_current[1] = p_current[2] = pressure->scalar; else if (pcouple == XYZ) { double ave = 1.0/3.0 * (tensor[0] + tensor[1] + tensor[2]); p_current[0] = p_current[1] = p_current[2] = ave; } else if (pcouple == XY) { double ave = 0.5 * (tensor[0] + tensor[1]); p_current[0] = p_current[1] = ave; p_current[2] = tensor[2]; } else if (pcouple == YZ) { double ave = 0.5 * (tensor[1] + tensor[2]); p_current[1] = p_current[2] = ave; p_current[0] = tensor[0]; } else if (pcouple == XZ) { double ave = 0.5 * (tensor[0] + tensor[2]); p_current[0] = p_current[2] = ave; p_current[1] = tensor[1]; } else { p_current[0] = tensor[0]; p_current[1] = tensor[1]; p_current[2] = tensor[2]; } // switch order from xy-xz-yz to Voigt if (pstyle == TRICLINIC) { p_current[3] = tensor[5]; p_current[4] = tensor[4]; p_current[5] = tensor[3]; } } /* ---------------------------------------------------------------------- */ void FixNHCuda::couple_ke() { double *tensor = temperature->vector; if (pstyle == ISO) mvv_current[0] = mvv_current[1] = mvv_current[2] = tdof * boltz * t_current/dimension; else if (pcouple == XYZ) { double ave = 1.0/3.0 * (tensor[0] + tensor[1] + tensor[2]); mvv_current[0] = mvv_current[1] = mvv_current[2] = ave; } else if (pcouple == XY) { double ave = 0.5 * (tensor[0] + tensor[1]); mvv_current[0] = mvv_current[1] = ave; mvv_current[2] = tensor[2]; } else if (pcouple == YZ) { double ave = 0.5 * (tensor[1] + tensor[2]); mvv_current[1] = mvv_current[2] = ave; mvv_current[0] = tensor[0]; } else if (pcouple == XZ) { double ave = 0.5 * (tensor[0] + tensor[2]); mvv_current[0] = mvv_current[2] = ave; mvv_current[1] = tensor[1]; } else { mvv_current[0] = tensor[0]; mvv_current[1] = tensor[1]; mvv_current[2] = tensor[2]; } } /* ---------------------------------------------------------------------- change box size remap all atoms or fix group atoms depending on allremap flag if rigid bodies exist, scale rigid body centers-of-mass ------------------------------------------------------------------------- */ void FixNHCuda::remap() { int i; double oldlo,oldhi,ctr; double **x = atom->x; int *mask = atom->mask; int nlocal = atom->nlocal; double *h = domain->h; // omega is not used, except for book-keeping for (int i = 0; i < 6; i++) omega[i] += dto*omega_dot[i]; // convert pertinent atoms and rigid bodies to lamda coords if (allremap) domain->x2lamda(nlocal); else { for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) domain->x2lamda(x[i],x[i]); } if (nrigid) for (i = 0; i < nrigid; i++) modify->fix[rfix[i]]->deform(0); // reset global and local box to new size/shape // This operation corresponds to applying the // translate and scale operations // corresponding to the solution of the following ODE: // // h_dot = omega_dot * h // // where h_dot, omega_dot and h are all upper-triangular // 3x3 tensors. In Voigt notation, the elements of the // RHS product tensor are: // h_dot = [0*0, 1*1, 2*2, 1*3+3*2, 0*4+5*3+4*2, 0*5+5*1] // // Ordering of operations preserves time symmetry. double dto2 = dto/2.0; double dto4 = dto/4.0; double dto8 = dto/8.0; if (pstyle == TRICLINIC) { h[4] *= exp(dto8*omega_dot[0]); h[4] += dto4*(omega_dot[5]*h[3]+omega_dot[4]*h[2]); h[4] *= exp(dto8*omega_dot[0]); h[3] *= exp(dto4*omega_dot[1]); h[3] += dto2*(omega_dot[3]*h[2]); h[3] *= exp(dto4*omega_dot[1]); h[5] *= exp(dto4*omega_dot[0]); h[5] += dto2*(omega_dot[5]*h[1]); h[5] *= exp(dto4*omega_dot[0]); h[4] *= exp(dto8*omega_dot[0]); h[4] += dto4*(omega_dot[5]*h[3]+omega_dot[4]*h[2]); h[4] *= exp(dto8*omega_dot[0]); } for (i = 0; i < 3; i++) { if (p_flag[i]) { oldlo = domain->boxlo[i]; oldhi = domain->boxhi[i]; ctr = 0.5 * (oldlo + oldhi); domain->boxlo[i] = (oldlo-ctr)*exp(dto*omega_dot[i]) + ctr; domain->boxhi[i] = (oldhi-ctr)*exp(dto*omega_dot[i]) + ctr; } } if (pstyle == TRICLINIC) { h[4] *= exp(dto8*omega_dot[0]); h[4] += dto4*(omega_dot[5]*h[3]+omega_dot[4]*h[2]); h[4] *= exp(dto8*omega_dot[0]); h[3] *= exp(dto4*omega_dot[1]); h[3] += dto2*(omega_dot[3]*h[2]); h[3] *= exp(dto4*omega_dot[1]); h[5] *= exp(dto4*omega_dot[0]); h[5] += dto2*(omega_dot[5]*h[1]); h[5] *= exp(dto4*omega_dot[0]); h[4] *= exp(dto8*omega_dot[0]); h[4] += dto4*(omega_dot[5]*h[3]+omega_dot[4]*h[2]); h[4] *= exp(dto8*omega_dot[0]); domain->yz = h[3]; domain->xz = h[4]; domain->xy = h[5]; if (domain->yz < -0.5*domain->yprd || domain->yz > 0.5*domain->yprd || domain->xz < -0.5*domain->xprd || domain->xz > 0.5*domain->xprd || domain->xy < -0.5*domain->xprd || domain->xy > 0.5*domain->xprd) error->all(FLERR,"Fix npt/nph has tilted box too far - " "box flips are not yet implemented"); } domain->set_global_box(); domain->set_local_box(); // convert pertinent atoms and rigid bodies back to box coords if (allremap) domain->lamda2x(nlocal); else { for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) domain->lamda2x(x[i],x[i]); } if (nrigid) for (i = 0; i < nrigid; i++) modify->fix[rfix[i]]->deform(1); } /* ---------------------------------------------------------------------- pack entire state of Fix into one write ------------------------------------------------------------------------- */ void FixNHCuda::write_restart(FILE *fp) { int nsize = 2; if (tstat_flag) nsize += 1 + 2*mtchain; if (pstat_flag) { nsize += 16 + 2*mpchain; if (deviatoric_flag) nsize += 6; } double* list = (double *) memory->smalloc(nsize*sizeof(double),"nh:list"); int n = 0; list[n++] = tstat_flag; if (tstat_flag) { list[n++] = mtchain; for (int ich = 0; ich < mtchain; ich++) list[n++] = eta[ich]; for (int ich = 0; ich < mtchain; ich++) list[n++] = eta_dot[ich]; } list[n++] = pstat_flag; if (pstat_flag) { list[n++] = omega[0]; list[n++] = omega[1]; list[n++] = omega[2]; list[n++] = omega[3]; list[n++] = omega[4]; list[n++] = omega[5]; list[n++] = omega_dot[0]; list[n++] = omega_dot[1]; list[n++] = omega_dot[2]; list[n++] = omega_dot[3]; list[n++] = omega_dot[4]; list[n++] = omega_dot[5]; list[n++] = vol0; list[n++] = t0; list[n++] = mpchain; if (mpchain) { for (int ich = 0; ich < mpchain; ich++) list[n++] = etap[ich]; for (int ich = 0; ich < mpchain; ich++) list[n++] = etap_dot[ich]; } list[n++] = deviatoric_flag; if (deviatoric_flag) { list[n++] = h0_inv[0]; list[n++] = h0_inv[1]; list[n++] = h0_inv[2]; list[n++] = h0_inv[3]; list[n++] = h0_inv[4]; list[n++] = h0_inv[5]; } } if (comm->me == 0) { int size = nsize * sizeof(double); fwrite(&size,sizeof(int),1,fp); fwrite(list,sizeof(double),nsize,fp); } memory->sfree(list); } /* ---------------------------------------------------------------------- use state info from restart file to restart the Fix ------------------------------------------------------------------------- */ void FixNHCuda::restart(char *buf) { int n = 0; double *list = (double *) buf; int flag = static_cast<int> (list[n++]); if (flag) { int m = static_cast<int> (list[n++]); if (tstat_flag && m == mtchain) { for (int ich = 0; ich < mtchain; ich++) eta[ich] = list[n++]; for (int ich = 0; ich < mtchain; ich++) eta_dot[ich] = list[n++]; } else n += 2*m; } flag = static_cast<int> (list[n++]); if (flag) { omega[0] = list[n++]; omega[1] = list[n++]; omega[2] = list[n++]; omega[3] = list[n++]; omega[4] = list[n++]; omega[5] = list[n++]; omega_dot[0] = list[n++]; omega_dot[1] = list[n++]; omega_dot[2] = list[n++]; omega_dot[3] = list[n++]; omega_dot[4] = list[n++]; omega_dot[5] = list[n++]; vol0 = list[n++]; t0 = list[n++]; int m = static_cast<int> (list[n++]); if (pstat_flag && m == mpchain) { for (int ich = 0; ich < mpchain; ich++) etap[ich] = list[n++]; for (int ich = 0; ich < mpchain; ich++) etap_dot[ich] = list[n++]; } else n+=2*m; flag = static_cast<int> (list[n++]); if (flag) { h0_inv[0] = list[n++]; h0_inv[1] = list[n++]; h0_inv[2] = list[n++]; h0_inv[3] = list[n++]; h0_inv[4] = list[n++]; h0_inv[5] = list[n++]; } } } /* ---------------------------------------------------------------------- */ int FixNHCuda::modify_param(int narg, char **arg) { if (strcmp(arg[0],"temp") == 0) { if (narg < 2) error->all(FLERR,"Illegal fix_modify command"); if (tflag) { modify->delete_compute(id_temp); tflag = 0; } delete [] id_temp; int n = strlen(arg[1]) + 1; id_temp = new char[n]; strcpy(id_temp,arg[1]); int icompute = modify->find_compute(arg[1]); if (icompute < 0) error->all(FLERR,"Could not find fix_modify temperature ID"); temperature = modify->compute[icompute]; if (temperature->tempflag == 0) error->all(FLERR,"Fix_modify temperature ID does not compute temperature"); if (temperature->igroup != 0 && comm->me == 0) error->warning(FLERR,"Temperature for fix modify is not for group all"); // reset id_temp of pressure to new temperature ID if (pstat_flag) { icompute = modify->find_compute(id_press); if (icompute < 0) error->all(FLERR,"Pressure ID for fix modify does not exist"); modify->compute[icompute]->reset_extra_compute_fix(id_temp); } return 2; } else if (strcmp(arg[0],"press") == 0) { if (narg < 2) error->all(FLERR,"Illegal fix_modify command"); if (!pstat_flag) error->all(FLERR,"Illegal fix_modify command"); if (pflag) { modify->delete_compute(id_press); pflag = 0; } delete [] id_press; int n = strlen(arg[1]) + 1; id_press = new char[n]; strcpy(id_press,arg[1]); int icompute = modify->find_compute(arg[1]); if (icompute < 0) error->all(FLERR,"Could not find fix_modify pressure ID"); pressure = modify->compute[icompute]; if (pressure->pressflag == 0) error->all(FLERR,"Fix_modify pressure ID does not compute pressure"); return 2; } return 0; } /* ---------------------------------------------------------------------- */ double FixNHCuda::compute_scalar() { int i; double volume; double energy; double kt = boltz * t_target; double lkt = tdof * kt; double lkt_press = kt; int ich; if (dimension == 3) volume = domain->xprd * domain->yprd * domain->zprd; else volume = domain->xprd * domain->yprd; energy = 0.0; // thermostat chain energy is equivalent to Eq. (2) in // Martyna, Tuckerman, Tobias, Klein, Mol Phys, 87, 1117 // Sum(0.5*p_eta_k^2/Q_k,k=1,M) + L*k*T*eta_1 + Sum(k*T*eta_k,k=2,M), // where L = tdof // M = mtchain // p_eta_k = Q_k*eta_dot[k-1] // Q_1 = L*k*T/t_freq^2 // Q_k = k*T/t_freq^2, k > 1 if (tstat_flag) { energy += lkt * eta[0] + 0.5*eta_mass[0]*eta_dot[0]*eta_dot[0]; for (ich = 1; ich < mtchain; ich++) energy += kt * eta[ich] + 0.5*eta_mass[ich]*eta_dot[ich]*eta_dot[ich]; } // barostat energy is equivalent to Eq. (8) in // Martyna, Tuckerman, Tobias, Klein, Mol Phys, 87, 1117 // Sum(0.5*p_omega^2/W + P*V), // where N = natoms // p_omega = W*omega_dot // W = N*k*T/p_freq^2 // sum is over barostatted dimensions if (pstat_flag) { for (i = 0; i < 3; i++) if (p_flag[i]) energy += 0.5*omega_dot[i]*omega_dot[i]*omega_mass[i] + p_hydro*(volume-vol0) / (pdim*nktv2p); if (pstyle == TRICLINIC) { for (i = 3; i < 6; i++) if (p_flag[i]) energy += 0.5*omega_dot[i]*omega_dot[i]*omega_mass[i]; } // extra contributions from thermostat chain for barostat if (mpchain) { energy += lkt_press * etap[0] + 0.5*etap_mass[0]*etap_dot[0]*etap_dot[0]; for (ich = 1; ich < mpchain; ich++) energy += kt * etap[ich] + 0.5*etap_mass[ich]*etap_dot[ich]*etap_dot[ich]; } // extra contribution from strain energy if (deviatoric_flag) energy += compute_strain_energy(); } return energy; } /* ---------------------------------------------------------------------- return a single element of the following vectors, in this order: eta[tchain], eta_dot[tchain], omega[ndof], omega_dot[ndof] etap[pchain], etap_dot[pchain], PE_eta[tchain], KE_eta_dot[tchain] PE_omega[ndof], KE_omega_dot[ndof], PE_etap[pchain], KE_etap_dot[pchain] PE_strain[1] if no thermostat exists, related quantities are omitted from the list if no barostat exists, related quantities are omitted from the list ndof = 1,3,6 degrees of freedom for pstyle = ISO,ANISO,TRI ------------------------------------------------------------------------- */ double FixNHCuda::compute_vector(int n) { int ilen; if (tstat_flag) { ilen = mtchain; if (n < ilen) return eta[n]; n -= ilen; ilen = mtchain; if (n < ilen) return eta_dot[n]; n -= ilen; } if (pstat_flag) { if (pstyle == ISO) { ilen = 1; if (n < ilen) return omega[n]; n -= ilen; } else if (pstyle == ANISO) { ilen = 3; if (n < ilen) return omega[n]; n -= ilen; } else { ilen = 6; if (n < ilen) return omega[n]; n -= ilen; } if (pstyle == ISO) { ilen = 1; if (n < ilen) return omega_dot[n]; n -= ilen; } else if (pstyle == ANISO) { ilen = 3; if (n < ilen) return omega_dot[n]; n -= ilen; } else { ilen = 6; if (n < ilen) return omega_dot[n]; n -= ilen; } if (mpchain) { ilen = mpchain; if (n < ilen) return etap[n]; n -= ilen; ilen = mpchain; if (n < ilen) return etap_dot[n]; n -= ilen; } } int i; double volume; double kt = boltz * t_target; double lkt = tdof * kt; double lkt_press = kt; int ich; if (dimension == 3) volume = domain->xprd * domain->yprd * domain->zprd; else volume = domain->xprd * domain->yprd; if (tstat_flag) { ilen = mtchain; if (n < ilen) { ich = n; if (ich == 0) return lkt * eta[0]; else return kt * eta[ich]; } n -= ilen; ilen = mtchain; if (n < ilen) { ich = n; if (ich == 0) return 0.5*eta_mass[0]*eta_dot[0]*eta_dot[0]; else return 0.5*eta_mass[ich]*eta_dot[ich]*eta_dot[ich]; } n -= ilen; } if (pstat_flag) { if (pstyle == ISO) { ilen = 1; if (n < ilen) return p_hydro*(volume-vol0) / nktv2p; n -= ilen; } else if (pstyle == ANISO) { ilen = 3; if (n < ilen) if (p_flag[n]) return p_hydro*(volume-vol0) / (pdim*nktv2p); else return 0.0; n -= ilen; } else { ilen = 6; if (n < ilen) if (n > 2) return 0.0; else if (p_flag[n]) return p_hydro*(volume-vol0) / (pdim*nktv2p); else return 0.0; n -= ilen; } if (pstyle == ISO) { ilen = 1; if (n < ilen) return pdim*0.5*omega_dot[n]*omega_dot[n]*omega_mass[n]; n -= ilen; } else if (pstyle == ANISO) { ilen = 3; if (n < ilen) if (p_flag[n]) return 0.5*omega_dot[n]*omega_dot[n]*omega_mass[n]; else return 0.0; n -= ilen; } else { ilen = 6; if (n < ilen) if (p_flag[n]) return 0.5*omega_dot[n]*omega_dot[n]*omega_mass[n]; else return 0.0; n -= ilen; } if (mpchain) { ilen = mpchain; if (n < ilen) { ich = n; if (ich == 0) return lkt_press * etap[0]; else return kt * etap[ich]; } n -= ilen; ilen = mpchain; if (n < ilen) { ich = n; if (ich == 0) return 0.5*etap_mass[0]*etap_dot[0]*etap_dot[0]; else return 0.5*etap_mass[ich]*etap_dot[ich]*etap_dot[ich]; } n -= ilen; } if (deviatoric_flag) { ilen = 1; if (n < ilen) return compute_strain_energy(); n -= ilen; } } return 0.0; } /* ---------------------------------------------------------------------- */ void FixNHCuda::reset_dt() { dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dthalf = 0.5 * update->dt; dt4 = 0.25 * update->dt; dt8 = 0.125 * update->dt; dto = dthalf; // If using respa, then remap is performed in innermost level if (strcmp(update->integrate_style,"respa") == 0) dto = 0.5*step_respa[0]; p_freq_max = 0.0; if (pstat_flag) { p_freq_max = MAX(p_freq[0],p_freq[1]); p_freq_max = MAX(p_freq_max,p_freq[2]); if (pstyle == TRICLINIC) { p_freq_max = MAX(p_freq_max,p_freq[3]); p_freq_max = MAX(p_freq_max,p_freq[4]); p_freq_max = MAX(p_freq_max,p_freq[5]); } pdrag_factor = 1.0 - (update->dt * p_freq_max * drag / nc_pchain); } if (tstat_flag) tdrag_factor = 1.0 - (update->dt * t_freq * drag / nc_tchain); } /* ---------------------------------------------------------------------- perform half-step update of chain thermostat variables ------------------------------------------------------------------------- */ void FixNHCuda::nhc_temp_integrate() { int ich; double expfac; double lkt = tdof * boltz * t_target; double kecurrent = tdof * boltz * t_current; eta_dotdot[0] = (kecurrent - lkt)/eta_mass[0]; double ncfac = 1.0/nc_tchain; for (int iloop = 0; iloop < nc_tchain; iloop++) { for (ich = mtchain-1; ich > 0; ich--) { expfac = exp(-ncfac*dt8*eta_dot[ich+1]); eta_dot[ich] *= expfac; eta_dot[ich] += eta_dotdot[ich] * ncfac*dt4; eta_dot[ich] *= tdrag_factor; eta_dot[ich] *= expfac; } expfac = exp(-ncfac*dt8*eta_dot[1]); eta_dot[0] *= expfac; eta_dot[0] += eta_dotdot[0] * ncfac*dt4; eta_dot[0] *= tdrag_factor; eta_dot[0] *= expfac; factor_eta = exp(-ncfac*dthalf*eta_dot[0]); if(which==NOBIAS) Cuda_FixNHCuda_nh_v_temp(&cuda->shared_data,groupbit,factor_eta,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal); else if(which==BIAS) { if(!temperature->cudable) { cuda->downloadAll(); nh_v_temp(); cuda->cu_v->upload(); } else { int groupbit_org=temperature->groupbit; temperature->groupbit=groupbit; temperature->remove_bias_all(); Cuda_FixNHCuda_nh_v_temp(&cuda->shared_data,groupbit,factor_eta,(igroup == atom->firstgroup)?atom->nfirst:atom->nlocal); temperature->restore_bias_all(); temperature->groupbit=groupbit_org; } } // rescale temperature due to velocity scaling // should not be necessary to explicitly recompute the temperature t_current *= factor_eta*factor_eta; kecurrent = tdof * boltz * t_current; eta_dotdot[0] = (kecurrent - lkt)/eta_mass[0]; for (ich = 0; ich < mtchain; ich++) eta[ich] += ncfac*dthalf*eta_dot[ich]; eta_dot[0] *= expfac; eta_dot[0] += eta_dotdot[0] * ncfac*dt4; eta_dot[0] *= expfac; for (ich = 1; ich < mtchain; ich++) { expfac = exp(-ncfac*dt8*eta_dot[ich+1]); eta_dot[ich] *= expfac; eta_dotdot[ich] = (eta_mass[ich-1]*eta_dot[ich-1]*eta_dot[ich-1] - boltz * t_target)/eta_mass[ich]; eta_dot[ich] += eta_dotdot[ich] * ncfac*dt4; eta_dot[ich] *= expfac; } } } /* ---------------------------------------------------------------------- perform half-step update of chain thermostat variables for barostat scale barostat velocities ------------------------------------------------------------------------- */ void FixNHCuda::nhc_press_integrate() { int ich,i; double expfac,factor_etap,wmass,kecurrent; double kt = boltz * t_target; double lkt_press = kt; kecurrent = 0.0; for (i = 0; i < 3; i++) if (p_flag[i]) kecurrent += omega_mass[i]*omega_dot[i]*omega_dot[i]; if (pstyle == TRICLINIC) { for (i = 3; i < 6; i++) if (p_flag[i]) kecurrent += omega_mass[i]*omega_dot[i]*omega_dot[i]; } etap_dotdot[0] = (kecurrent - lkt_press)/etap_mass[0]; double ncfac = 1.0/nc_pchain; for (int iloop = 0; iloop < nc_pchain; iloop++) { for (ich = mpchain-1; ich > 0; ich--) { expfac = exp(-ncfac*dt8*etap_dot[ich+1]); etap_dot[ich] *= expfac; etap_dot[ich] += etap_dotdot[ich] * ncfac*dt4; etap_dot[ich] *= pdrag_factor; etap_dot[ich] *= expfac; } expfac = exp(-ncfac*dt8*etap_dot[1]); etap_dot[0] *= expfac; etap_dot[0] += etap_dotdot[0] * ncfac*dt4; etap_dot[0] *= pdrag_factor; etap_dot[0] *= expfac; for (ich = 0; ich < mpchain; ich++) etap[ich] += ncfac*dthalf*etap_dot[ich]; factor_etap = exp(-ncfac*dthalf*etap_dot[0]); for (i = 0; i < 3; i++) if (p_flag[i]) omega_dot[i] *= factor_etap; if (pstyle == TRICLINIC) { for (i = 3; i < 6; i++) if (p_flag[i]) omega_dot[i] *= factor_etap; } kecurrent = 0.0; for (i = 0; i < 3; i++) if (p_flag[i]) kecurrent += omega_mass[i]*omega_dot[i]*omega_dot[i]; if (pstyle == TRICLINIC) { for (i = 3; i < 6; i++) if (p_flag[i]) kecurrent += omega_mass[i]*omega_dot[i]*omega_dot[i]; } etap_dotdot[0] = (kecurrent - lkt_press)/etap_mass[0]; etap_dot[0] *= expfac; etap_dot[0] += etap_dotdot[0] * ncfac*dt4; etap_dot[0] *= expfac; for (ich = 1; ich < mpchain; ich++) { expfac = exp(-ncfac*dt8*etap_dot[ich+1]); etap_dot[ich] *= expfac; etap_dotdot[ich] = (etap_mass[ich-1]*etap_dot[ich-1]*etap_dot[ich-1] - boltz*t_target) / etap_mass[ich]; etap_dot[ich] += etap_dotdot[ich] * ncfac*dt4; etap_dot[ich] *= expfac; } } } /* ---------------------------------------------------------------------- perform half-step barostat scaling of velocities -----------------------------------------------------------------------*/ void FixNHCuda::nh_v_press() { double factor[3]; double **v = atom->v; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; factor[0] = exp(-dt4*(omega_dot[0]+mtk_term2)); factor[1] = exp(-dt4*(omega_dot[1]+mtk_term2)); factor[2] = exp(-dt4*(omega_dot[2]+mtk_term2)); if (which == NOBIAS) { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { v[i][0] *= factor[0]; v[i][1] *= factor[1]; v[i][2] *= factor[2]; if (pstyle == TRICLINIC) { v[i][0] += -dthalf*(v[i][1]*omega_dot[5] + v[i][2]*omega_dot[4]); v[i][1] += -dthalf*v[i][2]*omega_dot[3]; } v[i][0] *= factor[0]; v[i][1] *= factor[1]; v[i][2] *= factor[2]; } } } else if (which == BIAS) { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { temperature->remove_bias(i,v[i]); v[i][0] *= factor[0]; v[i][1] *= factor[1]; v[i][2] *= factor[2]; if (pstyle == TRICLINIC) { v[i][0] += -dthalf*(v[i][1]*omega_dot[5] + v[i][2]*omega_dot[4]); v[i][1] += -dthalf*v[i][2]*omega_dot[3]; } v[i][0] *= factor[0]; v[i][1] *= factor[1]; v[i][2] *= factor[2]; temperature->restore_bias(i,v[i]); } } } } /* ---------------------------------------------------------------------- perform half-step update of velocities -----------------------------------------------------------------------*/ void FixNHCuda::nve_v() { double dtfm; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; if (rmass) { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { dtfm = dtf / rmass[i]; v[i][0] += dtfm*f[i][0]; v[i][1] += dtfm*f[i][1]; v[i][2] += dtfm*f[i][2]; } } } else { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { dtfm = dtf / mass[type[i]]; v[i][0] += dtfm*f[i][0]; v[i][1] += dtfm*f[i][1]; v[i][2] += dtfm*f[i][2]; } } } } /* ---------------------------------------------------------------------- perform full-step update of positions -----------------------------------------------------------------------*/ void FixNHCuda::nve_x() { double **x = atom->x; double **v = atom->v; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; // x update by full step only for atoms in group for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { x[i][0] += dtv * v[i][0]; x[i][1] += dtv * v[i][1]; x[i][2] += dtv * v[i][2]; } } } /* ---------------------------------------------------------------------- perform half-step thermostat scaling of velocities -----------------------------------------------------------------------*/ void FixNHCuda::nh_v_temp() { double **v = atom->v; int *mask = atom->mask; int nlocal = atom->nlocal; if (igroup == atom->firstgroup) nlocal = atom->nfirst; if (which == NOBIAS) { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { v[i][0] *= factor_eta; v[i][1] *= factor_eta; v[i][2] *= factor_eta; } } } else if (which == BIAS) { for (int i = 0; i < nlocal; i++) { if (mask[i] & groupbit) { temperature->remove_bias(i,v[i]); v[i][0] *= factor_eta; v[i][1] *= factor_eta; v[i][2] *= factor_eta; temperature->restore_bias(i,v[i]); } } } } /* ---------------------------------------------------------------------- compute sigma tensor needed whenever p_target or h0_inv changes -----------------------------------------------------------------------*/ void FixNHCuda::compute_sigma() { // if nreset_h0 > 0, reset vol0 and h0_inv // every nreset_h0 timesteps if (nreset_h0 > 0) { int delta = update->ntimestep - update->beginstep; if (delta % nreset_h0 == 0) { if (dimension == 3) vol0 = domain->xprd * domain->yprd * domain->zprd; else vol0 = domain->xprd * domain->yprd; h0_inv[0] = domain->h_inv[0]; h0_inv[1] = domain->h_inv[1]; h0_inv[2] = domain->h_inv[2]; h0_inv[3] = domain->h_inv[3]; h0_inv[4] = domain->h_inv[4]; h0_inv[5] = domain->h_inv[5]; } } // generate upper-triangular half of // sigma = vol0*h0inv*(p_target-p_hydro)*h0inv^t // units of sigma are are PV/L^2 e.g. atm.A // // [ 0 5 4 ] [ 0 5 4 ] [ 0 5 4 ] [ 0 - - ] // [ 5 1 3 ] = [ - 1 3 ] [ 5 1 3 ] [ 5 1 - ] // [ 4 3 2 ] [ - - 2 ] [ 4 3 2 ] [ 4 3 2 ] sigma[0] = vol0*(h0_inv[0]*((p_target[0]-p_hydro)*h0_inv[0] + p_target[5]*h0_inv[5]+p_target[4]*h0_inv[4]) + h0_inv[5]*(p_target[5]*h0_inv[0] + (p_target[1]-p_hydro)*h0_inv[5]+p_target[3]*h0_inv[4]) + h0_inv[4]*(p_target[4]*h0_inv[0]+p_target[3]*h0_inv[5] + (p_target[2]-p_hydro)*h0_inv[4])); sigma[1] = vol0*(h0_inv[1]*((p_target[1]-p_hydro)*h0_inv[1] + p_target[3]*h0_inv[3]) + h0_inv[3]*(p_target[3]*h0_inv[1] + (p_target[2]-p_hydro)*h0_inv[3])); sigma[2] = vol0*(h0_inv[2]*((p_target[2]-p_hydro)*h0_inv[2])); sigma[3] = vol0*(h0_inv[1]*(p_target[3]*h0_inv[2]) + h0_inv[3]*((p_target[2]-p_hydro)*h0_inv[2])); sigma[4] = vol0*(h0_inv[0]*(p_target[4]*h0_inv[2]) + h0_inv[5]*(p_target[3]*h0_inv[2]) + h0_inv[4]*((p_target[2]-p_hydro)*h0_inv[2])); sigma[5] = vol0*(h0_inv[0]*(p_target[5]*h0_inv[1]+p_target[4]*h0_inv[3]) + h0_inv[5]*((p_target[1]-p_hydro)*h0_inv[1]+p_target[3]*h0_inv[3]) + h0_inv[4]*(p_target[3]*h0_inv[1]+(p_target[2]-p_hydro)*h0_inv[3])); } /* ---------------------------------------------------------------------- compute strain energy -----------------------------------------------------------------------*/ double FixNHCuda::compute_strain_energy() { // compute strain energy = 0.5*Tr(sigma*h*h^t) in energy units double* h = domain->h; double d0,d1,d2; d0 = sigma[0]*(h[0]*h[0]+h[5]*h[5]+h[4]*h[4]) + sigma[5]*( h[1]*h[5]+h[3]*h[4]) + sigma[4]*( h[2]*h[4]); d1 = sigma[5]*( h[5]*h[1]+h[4]*h[3]) + sigma[1]*( h[1]*h[1]+h[3]*h[3]) + sigma[3]*( h[2]*h[3]); d2 = sigma[4]*( h[4]*h[2]) + sigma[3]*( h[3]*h[2]) + sigma[2]*( h[2]*h[2]); double energy = 0.5*(d0+d1+d2)/nktv2p; return energy; } /* ---------------------------------------------------------------------- compute deviatoric barostat force = h*sigma*h^t -----------------------------------------------------------------------*/ void FixNHCuda::compute_deviatoric() { // generate upper-triangular part of h*sigma*h^t // units of fdev are are PV, e.g. atm*A^3 // [ 0 5 4 ] [ 0 5 4 ] [ 0 5 4 ] [ 0 - - ] // [ 5 1 3 ] = [ - 1 3 ] [ 5 1 3 ] [ 5 1 - ] // [ 4 3 2 ] [ - - 2 ] [ 4 3 2 ] [ 4 3 2 ] double* h = domain->h; fdev[0] = h[0]*(sigma[0]*h[0]+sigma[5]*h[5]+sigma[4]*h[4]) + h[5]*(sigma[5]*h[0]+sigma[1]*h[5]+sigma[3]*h[4]) + h[4]*(sigma[4]*h[0]+sigma[3]*h[5]+sigma[2]*h[4]); fdev[1] = h[1]*( sigma[1]*h[1]+sigma[3]*h[3]) + h[3]*( sigma[3]*h[1]+sigma[2]*h[3]); fdev[2] = h[2]*( sigma[2]*h[2]); fdev[3] = h[1]*( sigma[3]*h[2]) + h[3]*( sigma[2]*h[2]); fdev[4] = h[0]*( sigma[4]*h[2]) + h[5]*( sigma[3]*h[2]) + h[4]*( sigma[2]*h[2]); fdev[5] = h[0]*( sigma[5]*h[1]+sigma[4]*h[3]) + h[5]*( sigma[1]*h[1]+sigma[3]*h[3]) + h[4]*( sigma[3]*h[1]+sigma[2]*h[3]); } /* ---------------------------------------------------------------------- compute hydrostatic target pressure -----------------------------------------------------------------------*/ void FixNHCuda::compute_press_target() { double delta = update->ntimestep - update->beginstep; if (update->endstep > update->beginstep) delta /= update->endstep - update->beginstep; else delta = 0.0; p_hydro = 0.0; for (int i = 0; i < 3; i++) if (p_flag[i]) { p_target[i] = p_start[i] + delta * (p_stop[i]-p_start[i]); p_hydro += p_target[i]; } p_hydro /= pdim; if (pstyle == TRICLINIC) for (int i = 3; i < 6; i++) p_target[i] = p_start[i] + delta * (p_stop[i]-p_start[i]); // if deviatoric, recompute sigma each time p_target changes if (deviatoric_flag) compute_sigma(); } /* ---------------------------------------------------------------------- update omega_dot, omega, dilation -----------------------------------------------------------------------*/ void FixNHCuda::nh_omega_dot() { double f_omega,volume; if (dimension == 3) volume = domain->xprd*domain->yprd*domain->zprd; else volume = domain->xprd*domain->yprd; if (deviatoric_flag) compute_deviatoric(); mtk_term1 = 0.0; if (mtk_flag) if (pstyle == ISO) { mtk_term1 = tdof * boltz * t_current; mtk_term1 /= pdim * atom->natoms; } else { double *mvv_current = temperature->vector; for (int i = 0; i < 3; i++) if (p_flag[i]) mtk_term1 += mvv_current[i]; mtk_term1 /= pdim * atom->natoms; } for (int i = 0; i < 3; i++) if (p_flag[i]) { f_omega = (p_current[i]-p_hydro)*volume / (omega_mass[i] * nktv2p) + mtk_term1 / omega_mass[i]; if (deviatoric_flag) f_omega -= fdev[i]/(omega_mass[i] * nktv2p); omega_dot[i] += f_omega*dthalf; omega_dot[i] *= pdrag_factor; } mtk_term2 = 0.0; if (mtk_flag) { for (int i = 0; i < 3; i++) if (p_flag[i]) mtk_term2 += omega_dot[i]; mtk_term2 /= pdim * atom->natoms; } if (pstyle == TRICLINIC) { for (int i = 3; i < 6; i++) { if (p_flag[i]) { f_omega = p_current[i]*volume/(omega_mass[i] * nktv2p); if (deviatoric_flag) f_omega -= fdev[i]/(omega_mass[i] * nktv2p); omega_dot[i] += f_omega*dthalf; omega_dot[i] *= pdrag_factor; } } } }
slitvinov/lammps-swimmer
src/USER-CUDA/fix_nh_cuda.cpp
C++
gpl-2.0
64,942
#pragma once /* * Copyright (C) 2010-2012 Team XBMC * http://www.xbmc.org * * 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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "Interfaces/AESink.h" #include <stdint.h> #include <dsound.h> #include "../Utils/AEDeviceInfo.h" #include "threads/CriticalSection.h" class CAESinkDirectSound : public IAESink { public: virtual const char *GetName() { return "DirectSound"; } CAESinkDirectSound(); virtual ~CAESinkDirectSound(); virtual bool Initialize (AEAudioFormat &format, std::string &device); virtual void Deinitialize(); virtual bool IsCompatible(const AEAudioFormat format, const std::string device); virtual void Stop (); virtual double GetDelay (); virtual double GetCacheTime (); virtual double GetCacheTotal (); virtual unsigned int AddPackets (uint8_t *data, unsigned int frames, bool hasAudio); virtual bool SoftSuspend (); virtual bool SoftResume (); static std::string GetDefaultDevice (); static void EnumerateDevicesEx (AEDeviceInfoList &deviceInfoList, bool force = false); private: void AEChannelsFromSpeakerMask(DWORD speakers); DWORD SpeakerMaskFromAEChannels(const CAEChannelInfo &channels); void CheckPlayStatus(); bool UpdateCacheStatus(); unsigned int GetSpace(); const char *dserr2str(int err); static const char *WASAPIErrToStr(HRESULT err); LPDIRECTSOUNDBUFFER m_pBuffer; LPDIRECTSOUND8 m_pDSound; AEAudioFormat m_format; enum AEDataFormat m_encodedFormat; CAEChannelInfo m_channelLayout; std::string m_device; unsigned int m_AvgBytesPerSec; unsigned int m_dwChunkSize; unsigned int m_dwFrameSize; unsigned int m_dwBufferLen; unsigned int m_BufferOffset; unsigned int m_CacheLen; unsigned int m_LastCacheCheck; unsigned int m_BufferTimeouts; bool m_running; bool m_initialized; bool m_isDirtyDS; CCriticalSection m_runLock; };
RasPlex/plex-home-theatre
xbmc/cores/AudioEngine/Sinks/AESinkDirectSound.h
C
gpl-2.0
2,762
<?php ///////////////////////////////////////////////////////////////// /// getID3() by James Heinrich <info@getid3.org> // // available at http://getid3.sourceforge.net // // or http://www.getid3.org // ///////////////////////////////////////////////////////////////// // See readme.txt for more details // ///////////////////////////////////////////////////////////////// /// // // module.tag.id3v2.php // // module for analyzing ID3v2 tags // // dependencies: module.tag.id3v1.php // // /// ///////////////////////////////////////////////////////////////// getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v1.php', __FILE__, true); class getid3_id3v2 { function getid3_id3v2(&$fd, &$ThisFileInfo, $StartingOffset=0) { // Overall tag structure: // +-----------------------------+ // | Header (10 bytes) | // +-----------------------------+ // | Extended Header | // | (variable length, OPTIONAL) | // +-----------------------------+ // | Frames (variable length) | // +-----------------------------+ // | Padding | // | (variable length, OPTIONAL) | // +-----------------------------+ // | Footer (10 bytes, OPTIONAL) | // +-----------------------------+ // Header // ID3v2/file identifier "ID3" // ID3v2 version $04 00 // ID3v2 flags (%ab000000 in v2.2, %abc00000 in v2.3, %abcd0000 in v2.4.x) // ID3v2 size 4 * %0xxxxxxx // shortcuts $ThisFileInfo['id3v2']['header'] = true; $thisfile_id3v2 = &$ThisFileInfo['id3v2']; $thisfile_id3v2['flags'] = array(); $thisfile_id3v2_flags = &$thisfile_id3v2['flags']; fseek($fd, $StartingOffset, SEEK_SET); $header = fread($fd, 10); if (substr($header, 0, 3) == 'ID3' && strlen($header) == 10) { $thisfile_id3v2['majorversion'] = ord($header{3}); $thisfile_id3v2['minorversion'] = ord($header{4}); // shortcut $id3v2_majorversion = &$thisfile_id3v2['majorversion']; } else { unset($ThisFileInfo['id3v2']); return false; } if ($id3v2_majorversion > 4) { // this script probably won't correctly parse ID3v2.5.x and above (if it ever exists) $ThisFileInfo['error'][] = 'this script only parses up to ID3v2.4.x - this tag is ID3v2.'.$id3v2_majorversion.'.'.$thisfile_id3v2['minorversion']; return false; } $id3_flags = ord($header{5}); switch ($id3v2_majorversion) { case 2: // %ab000000 in v2.2 $thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation $thisfile_id3v2_flags['compression'] = (bool) ($id3_flags & 0x40); // b - Compression break; case 3: // %abc00000 in v2.3 $thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation $thisfile_id3v2_flags['exthead'] = (bool) ($id3_flags & 0x40); // b - Extended header $thisfile_id3v2_flags['experim'] = (bool) ($id3_flags & 0x20); // c - Experimental indicator break; case 4: // %abcd0000 in v2.4 $thisfile_id3v2_flags['unsynch'] = (bool) ($id3_flags & 0x80); // a - Unsynchronisation $thisfile_id3v2_flags['exthead'] = (bool) ($id3_flags & 0x40); // b - Extended header $thisfile_id3v2_flags['experim'] = (bool) ($id3_flags & 0x20); // c - Experimental indicator $thisfile_id3v2_flags['isfooter'] = (bool) ($id3_flags & 0x10); // d - Footer present break; } $thisfile_id3v2['headerlength'] = getid3_lib::BigEndian2Int(substr($header, 6, 4), 1) + 10; // length of ID3v2 tag in 10-byte header doesn't include 10-byte header length $thisfile_id3v2['tag_offset_start'] = $StartingOffset; $thisfile_id3v2['tag_offset_end'] = $thisfile_id3v2['tag_offset_start'] + $thisfile_id3v2['headerlength']; // create 'encoding' key - used by getid3::HandleAllTags() // in ID3v2 every field can have it's own encoding type // so force everything to UTF-8 so it can be handled consistantly $thisfile_id3v2['encoding'] = 'UTF-8'; // Frames // All ID3v2 frames consists of one frame header followed by one or more // fields containing the actual information. The header is always 10 // bytes and laid out as follows: // // Frame ID $xx xx xx xx (four characters) // Size 4 * %0xxxxxxx // Flags $xx xx $sizeofframes = $thisfile_id3v2['headerlength'] - 10; // not including 10-byte initial header if (@$thisfile_id3v2['exthead']['length']) { $sizeofframes -= ($thisfile_id3v2['exthead']['length'] + 4); } if (@$thisfile_id3v2_flags['isfooter']) { $sizeofframes -= 10; // footer takes last 10 bytes of ID3v2 header, after frame data, before audio } if ($sizeofframes > 0) { $framedata = fread($fd, $sizeofframes); // read all frames from file into $framedata variable // if entire frame data is unsynched, de-unsynch it now (ID3v2.3.x) if (@$thisfile_id3v2_flags['unsynch'] && ($id3v2_majorversion <= 3)) { $framedata = $this->DeUnsynchronise($framedata); } // [in ID3v2.4.0] Unsynchronisation [S:6.1] is done on frame level, instead // of on tag level, making it easier to skip frames, increasing the streamability // of the tag. The unsynchronisation flag in the header [S:3.1] indicates that // there exists an unsynchronised frame, while the new unsynchronisation flag in // the frame header [S:4.1.2] indicates unsynchronisation. //$framedataoffset = 10 + (@$thisfile_id3v2['exthead']['length'] ? $thisfile_id3v2['exthead']['length'] + 4 : 0); // how many bytes into the stream - start from after the 10-byte header (and extended header length+4, if present) $framedataoffset = 10; // how many bytes into the stream - start from after the 10-byte header // Extended Header if (@$thisfile_id3v2_flags['exthead']) { $extended_header_offset = 0; if ($id3v2_majorversion == 3) { // v2.3 definition: //Extended header size $xx xx xx xx // 32-bit integer //Extended Flags $xx xx // %x0000000 %00000000 // v2.3 // x - CRC data present //Size of padding $xx xx xx xx $thisfile_id3v2['exthead']['length'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4), 0); $extended_header_offset += 4; $thisfile_id3v2['exthead']['flag_bytes'] = 2; $thisfile_id3v2['exthead']['flag_raw'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $thisfile_id3v2['exthead']['flag_bytes'])); $extended_header_offset += $thisfile_id3v2['exthead']['flag_bytes']; $thisfile_id3v2['exthead']['flags']['crc'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x8000); $thisfile_id3v2['exthead']['padding_size'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4)); $extended_header_offset += 4; if ($thisfile_id3v2['exthead']['flags']['crc']) { $thisfile_id3v2['exthead']['flag_data']['crc'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4)); $extended_header_offset += 4; } $extended_header_offset += $thisfile_id3v2['exthead']['padding_size']; } elseif ($id3v2_majorversion == 4) { // v2.4 definition: //Extended header size 4 * %0xxxxxxx // 28-bit synchsafe integer //Number of flag bytes $01 //Extended Flags $xx // %0bcd0000 // v2.4 // b - Tag is an update // Flag data length $00 // c - CRC data present // Flag data length $05 // Total frame CRC 5 * %0xxxxxxx // d - Tag restrictions // Flag data length $01 $thisfile_id3v2['exthead']['length'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 4), 1); $extended_header_offset += 4; $thisfile_id3v2['exthead']['flag_bytes'] = 1; $thisfile_id3v2['exthead']['flag_raw'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, $thisfile_id3v2['exthead']['flag_bytes'])); $extended_header_offset += $thisfile_id3v2['exthead']['flag_bytes']; $thisfile_id3v2['exthead']['flags']['update'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x4000); $thisfile_id3v2['exthead']['flags']['crc'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x2000); $thisfile_id3v2['exthead']['flags']['restrictions'] = (bool) ($thisfile_id3v2['exthead']['flag_raw'] & 0x1000); if ($thisfile_id3v2['exthead']['flags']['crc']) { $thisfile_id3v2['exthead']['flag_data']['crc'] = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 5), 1); $extended_header_offset += 5; } if ($thisfile_id3v2['exthead']['flags']['restrictions']) { // %ppqrrstt $restrictions_raw = getid3_lib::BigEndian2Int(substr($framedata, $extended_header_offset, 1)); $extended_header_offset += 1; $thisfile_id3v2['exthead']['flags']['restrictions']['tagsize'] = ($restrictions_raw && 0xC0) >> 6; // p - Tag size restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['textenc'] = ($restrictions_raw && 0x20) >> 5; // q - Text encoding restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['textsize'] = ($restrictions_raw && 0x18) >> 3; // r - Text fields size restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['imgenc'] = ($restrictions_raw && 0x04) >> 2; // s - Image encoding restrictions $thisfile_id3v2['exthead']['flags']['restrictions']['imgsize'] = ($restrictions_raw && 0x03) >> 0; // t - Image size restrictions } } $framedataoffset += $extended_header_offset; $framedata = substr($framedata, $extended_header_offset); } // end extended header while (isset($framedata) && (strlen($framedata) > 0)) { // cycle through until no more frame data is left to parse if (strlen($framedata) <= $this->ID3v2HeaderLength($id3v2_majorversion)) { // insufficient room left in ID3v2 header for actual data - must be padding $thisfile_id3v2['padding']['start'] = $framedataoffset; $thisfile_id3v2['padding']['length'] = strlen($framedata); $thisfile_id3v2['padding']['valid'] = true; for ($i = 0; $i < $thisfile_id3v2['padding']['length']; $i++) { if ($framedata{$i} != "\x00") { $thisfile_id3v2['padding']['valid'] = false; $thisfile_id3v2['padding']['errorpos'] = $thisfile_id3v2['padding']['start'] + $i; $ThisFileInfo['warning'][] = 'Invalid ID3v2 padding found at offset '.$thisfile_id3v2['padding']['errorpos'].' (the remaining '.($thisfile_id3v2['padding']['length'] - $i).' bytes are considered invalid)'; break; } } break; // skip rest of ID3v2 header } if ($id3v2_majorversion == 2) { // Frame ID $xx xx xx (three characters) // Size $xx xx xx (24-bit integer) // Flags $xx xx $frame_header = substr($framedata, 0, 6); // take next 6 bytes for header $framedata = substr($framedata, 6); // and leave the rest in $framedata $frame_name = substr($frame_header, 0, 3); $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 3, 3), 0); $frame_flags = 0; // not used for anything in ID3v2.2, just set to avoid E_NOTICEs } elseif ($id3v2_majorversion > 2) { // Frame ID $xx xx xx xx (four characters) // Size $xx xx xx xx (32-bit integer in v2.3, 28-bit synchsafe in v2.4+) // Flags $xx xx $frame_header = substr($framedata, 0, 10); // take next 10 bytes for header $framedata = substr($framedata, 10); // and leave the rest in $framedata $frame_name = substr($frame_header, 0, 4); if ($id3v2_majorversion == 3) { $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0); // 32-bit integer } else { // ID3v2.4+ $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 1); // 32-bit synchsafe integer (28-bit value) } if ($frame_size < (strlen($framedata) + 4)) { $nextFrameID = substr($framedata, $frame_size, 4); if ($this->IsValidID3v2FrameName($nextFrameID, $id3v2_majorversion)) { // next frame is OK } elseif (($frame_name == "\x00".'MP3') || ($frame_name == "\x00\x00".'MP') || ($frame_name == ' MP3') || ($frame_name == 'MP3e')) { // MP3ext known broken frames - "ok" for the purposes of this test } elseif (($id3v2_majorversion == 4) && ($this->IsValidID3v2FrameName(substr($framedata, getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0), 4), 3))) { $ThisFileInfo['warning'][] = 'ID3v2 tag written as ID3v2.4, but with non-synchsafe integers (ID3v2.3 style). Older versions of (Helium2; iTunes) are known culprits of this. Tag has been parsed as ID3v2.3'; $id3v2_majorversion = 3; $frame_size = getid3_lib::BigEndian2Int(substr($frame_header, 4, 4), 0); // 32-bit integer } } $frame_flags = getid3_lib::BigEndian2Int(substr($frame_header, 8, 2)); } if ((($id3v2_majorversion == 2) && ($frame_name == "\x00\x00\x00")) || ($frame_name == "\x00\x00\x00\x00")) { // padding encountered $thisfile_id3v2['padding']['start'] = $framedataoffset; $thisfile_id3v2['padding']['length'] = strlen($frame_header) + strlen($framedata); $thisfile_id3v2['padding']['valid'] = true; $len = strlen($framedata); for ($i = 0; $i < $len; $i++) { if ($framedata{$i} != "\x00") { $thisfile_id3v2['padding']['valid'] = false; $thisfile_id3v2['padding']['errorpos'] = $thisfile_id3v2['padding']['start'] + $i; $ThisFileInfo['warning'][] = 'Invalid ID3v2 padding found at offset '.$thisfile_id3v2['padding']['errorpos'].' (the remaining '.($thisfile_id3v2['padding']['length'] - $i).' bytes are considered invalid)'; break; } } break; // skip rest of ID3v2 header } if ($frame_name == 'COM ') { $ThisFileInfo['warning'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))). [Note: this particular error has been known to happen with tags edited by iTunes (versions "X v2.0.3", "v3.0.1" are known-guilty, probably others too)]'; $frame_name = 'COMM'; } if (($frame_size <= strlen($framedata)) && ($this->IsValidID3v2FrameName($frame_name, $id3v2_majorversion))) { unset($parsedFrame); $parsedFrame['frame_name'] = $frame_name; $parsedFrame['frame_flags_raw'] = $frame_flags; $parsedFrame['data'] = substr($framedata, 0, $frame_size); $parsedFrame['datalength'] = getid3_lib::CastAsInt($frame_size); $parsedFrame['dataoffset'] = $framedataoffset; $this->ParseID3v2Frame($parsedFrame, $ThisFileInfo); $thisfile_id3v2[$frame_name][] = $parsedFrame; $framedata = substr($framedata, $frame_size); } else { // invalid frame length or FrameID if ($frame_size <= strlen($framedata)) { if ($this->IsValidID3v2FrameName(substr($framedata, $frame_size, 4), $id3v2_majorversion)) { // next frame is valid, just skip the current frame $framedata = substr($framedata, $frame_size); $ThisFileInfo['warning'][] = 'Next ID3v2 frame is valid, skipping current frame.'; } else { // next frame is invalid too, abort processing //unset($framedata); $framedata = null; $ThisFileInfo['error'][] = 'Next ID3v2 frame is also invalid, aborting processing.'; } } elseif ($frame_size == strlen($framedata)) { // this is the last frame, just skip $ThisFileInfo['warning'][] = 'This was the last ID3v2 frame.'; } else { // next frame is invalid too, abort processing //unset($framedata); $framedata = null; $ThisFileInfo['warning'][] = 'Invalid ID3v2 frame size, aborting.'; } if (!$this->IsValidID3v2FrameName($frame_name, $id3v2_majorversion)) { switch ($frame_name) { case "\x00\x00".'MP': case "\x00".'MP3': case ' MP3': case 'MP3e': case "\x00".'MP': case ' MP': case 'MP3': $ThisFileInfo['warning'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: !IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))). [Note: this particular error has been known to happen with tags edited by "MP3ext (www.mutschler.de/mp3ext/)"]'; break; default: $ThisFileInfo['warning'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: !IsValidID3v2FrameName("'.str_replace("\x00", ' ', $frame_name).'", '.$id3v2_majorversion.'))).'; break; } } elseif ($frame_size > strlen(@$framedata)){ $ThisFileInfo['error'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag). (ERROR: $frame_size ('.$frame_size.') > strlen($framedata) ('.strlen($framedata).')).'; } else { $ThisFileInfo['error'][] = 'error parsing "'.$frame_name.'" ('.$framedataoffset.' bytes into the ID3v2.'.$id3v2_majorversion.' tag).'; } } $framedataoffset += ($frame_size + $this->ID3v2HeaderLength($id3v2_majorversion)); } } // Footer // The footer is a copy of the header, but with a different identifier. // ID3v2 identifier "3DI" // ID3v2 version $04 00 // ID3v2 flags %abcd0000 // ID3v2 size 4 * %0xxxxxxx if (isset($thisfile_id3v2_flags['isfooter']) && $thisfile_id3v2_flags['isfooter']) { $footer = fread($fd, 10); if (substr($footer, 0, 3) == '3DI') { $thisfile_id3v2['footer'] = true; $thisfile_id3v2['majorversion_footer'] = ord($footer{3}); $thisfile_id3v2['minorversion_footer'] = ord($footer{4}); } if ($thisfile_id3v2['majorversion_footer'] <= 4) { $id3_flags = ord(substr($footer{5})); $thisfile_id3v2_flags['unsynch_footer'] = (bool) ($id3_flags & 0x80); $thisfile_id3v2_flags['extfoot_footer'] = (bool) ($id3_flags & 0x40); $thisfile_id3v2_flags['experim_footer'] = (bool) ($id3_flags & 0x20); $thisfile_id3v2_flags['isfooter_footer'] = (bool) ($id3_flags & 0x10); $thisfile_id3v2['footerlength'] = getid3_lib::BigEndian2Int(substr($footer, 6, 4), 1); } } // end footer if (isset($thisfile_id3v2['comments']['genre'])) { foreach ($thisfile_id3v2['comments']['genre'] as $key => $value) { unset($thisfile_id3v2['comments']['genre'][$key]); $thisfile_id3v2['comments'] = getid3_lib::array_merge_noclobber($thisfile_id3v2['comments'], $this->ParseID3v2GenreString($value)); } } if (isset($thisfile_id3v2['comments']['track'])) { foreach ($thisfile_id3v2['comments']['track'] as $key => $value) { if (strstr($value, '/')) { list($thisfile_id3v2['comments']['tracknum'][$key], $thisfile_id3v2['comments']['totaltracks'][$key]) = explode('/', $thisfile_id3v2['comments']['track'][$key]); } } } if (!isset($thisfile_id3v2['comments']['year']) && preg_match('/^([0-9]{4})/', trim(@$thisfile_id3v2['comments']['recording_time'][0]), $matches)) { $thisfile_id3v2['comments']['year'] = array($matches[1]); } // Set avdataoffset $ThisFileInfo['avdataoffset'] = $thisfile_id3v2['headerlength']; if (isset($thisfile_id3v2['footer'])) { $ThisFileInfo['avdataoffset'] += 10; } return true; } function ParseID3v2GenreString($genrestring) { // Parse genres into arrays of genreName and genreID // ID3v2.2.x, ID3v2.3.x: '(21)' or '(4)Eurodisco' or '(51)(39)' or '(55)((I think...)' // ID3v2.4.x: '21' $00 'Eurodisco' $00 $genrestring = trim($genrestring); $returnarray = array(); if (strpos($genrestring, "\x00") !== false) { $unprocessed = trim($genrestring); // trailing nulls will cause an infinite loop. $genrestring = ''; while (strpos($unprocessed, "\x00") !== false) { // convert null-seperated v2.4-format into v2.3 ()-seperated format $endpos = strpos($unprocessed, "\x00"); $genrestring .= '('.substr($unprocessed, 0, $endpos).')'; $unprocessed = substr($unprocessed, $endpos + 1); } unset($unprocessed); } elseif (preg_match('/^([0-9]+|CR|RX)$/i', $genrestring)) { // some tagging program (including some that use TagLib) fail to include null byte after numeric genre $genrestring = '('.$genrestring.')'; } if (getid3_id3v1::LookupGenreID($genrestring)) { $returnarray['genre'][] = $genrestring; } else { while (strpos($genrestring, '(') !== false) { $startpos = strpos($genrestring, '('); $endpos = strpos($genrestring, ')'); if (substr($genrestring, $startpos + 1, 1) == '(') { $genrestring = substr($genrestring, 0, $startpos).substr($genrestring, $startpos + 1); $endpos--; } $element = substr($genrestring, $startpos + 1, $endpos - ($startpos + 1)); $genrestring = substr($genrestring, 0, $startpos).substr($genrestring, $endpos + 1); if (getid3_id3v1::LookupGenreName($element)) { // $element is a valid genre id/abbreviation if (empty($returnarray['genre']) || !in_array(getid3_id3v1::LookupGenreName($element), $returnarray['genre'])) { // avoid duplicate entires $returnarray['genre'][] = getid3_id3v1::LookupGenreName($element); } } else { if (empty($returnarray['genre']) || !in_array($element, $returnarray['genre'])) { // avoid duplicate entires $returnarray['genre'][] = $element; } } } } if ($genrestring) { if (empty($returnarray['genre']) || !in_array($genrestring, $returnarray['genre'])) { // avoid duplicate entires $returnarray['genre'][] = $genrestring; } } return $returnarray; } function ParseID3v2Frame(&$parsedFrame, &$ThisFileInfo) { // shortcuts $id3v2_majorversion = $ThisFileInfo['id3v2']['majorversion']; $parsedFrame['framenamelong'] = $this->FrameNameLongLookup($parsedFrame['frame_name']); if (empty($parsedFrame['framenamelong'])) { unset($parsedFrame['framenamelong']); } $parsedFrame['framenameshort'] = $this->FrameNameShortLookup($parsedFrame['frame_name']); if (empty($parsedFrame['framenameshort'])) { unset($parsedFrame['framenameshort']); } if ($id3v2_majorversion >= 3) { // frame flags are not part of the ID3v2.2 standard if ($id3v2_majorversion == 3) { // Frame Header Flags // %abc00000 %ijk00000 $parsedFrame['flags']['TagAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x8000); // a - Tag alter preservation $parsedFrame['flags']['FileAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x4000); // b - File alter preservation $parsedFrame['flags']['ReadOnly'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x2000); // c - Read only $parsedFrame['flags']['compression'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0080); // i - Compression $parsedFrame['flags']['Encryption'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0040); // j - Encryption $parsedFrame['flags']['GroupingIdentity'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0020); // k - Grouping identity } elseif ($id3v2_majorversion == 4) { // Frame Header Flags // %0abc0000 %0h00kmnp $parsedFrame['flags']['TagAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x4000); // a - Tag alter preservation $parsedFrame['flags']['FileAlterPreservation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x2000); // b - File alter preservation $parsedFrame['flags']['ReadOnly'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x1000); // c - Read only $parsedFrame['flags']['GroupingIdentity'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0040); // h - Grouping identity $parsedFrame['flags']['compression'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0008); // k - Compression $parsedFrame['flags']['Encryption'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0004); // m - Encryption $parsedFrame['flags']['Unsynchronisation'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0002); // n - Unsynchronisation $parsedFrame['flags']['DataLengthIndicator'] = (bool) ($parsedFrame['frame_flags_raw'] & 0x0001); // p - Data length indicator // Frame-level de-unsynchronisation - ID3v2.4 if ($parsedFrame['flags']['Unsynchronisation']) { $parsedFrame['data'] = $this->DeUnsynchronise($parsedFrame['data']); } } // Frame-level de-compression if ($parsedFrame['flags']['compression']) { $parsedFrame['decompressed_size'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 4)); if (!function_exists('gzuncompress')) { $ThisFileInfo['warning'][] = 'gzuncompress() support required to decompress ID3v2 frame "'.$parsedFrame['frame_name'].'"'; } elseif ($decompresseddata = @gzuncompress(substr($parsedFrame['data'], 4))) { $parsedFrame['data'] = $decompresseddata; } else { $ThisFileInfo['warning'][] = 'gzuncompress() failed on compressed contents of ID3v2 frame "'.$parsedFrame['frame_name'].'"'; } } } if (isset($parsedFrame['datalength']) && ($parsedFrame['datalength'] == 0)) { $warning = 'Frame "'.$parsedFrame['frame_name'].'" at offset '.$parsedFrame['dataoffset'].' has no data portion'; switch ($parsedFrame['frame_name']) { case 'WCOM': $warning .= ' (this is known to happen with files tagged by RioPort)'; break; default: break; } $ThisFileInfo['warning'][] = $warning; } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'UFID')) || // 4.1 UFID Unique file identifier (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'UFI'))) { // 4.1 UFI Unique file identifier // There may be more than one 'UFID' frame in a tag, // but only one with the same 'Owner identifier'. // <Header for 'Unique file identifier', ID: 'UFID'> // Owner identifier <text string> $00 // Identifier <up to 64 bytes binary data> $frame_terminatorpos = strpos($parsedFrame['data'], "\x00"); $frame_idstring = substr($parsedFrame['data'], 0, $frame_terminatorpos); $parsedFrame['ownerid'] = $frame_idstring; $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen("\x00")); unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'TXXX')) || // 4.2.2 TXXX User defined text information frame (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'TXX'))) { // 4.2.2 TXX User defined text information frame // There may be more than one 'TXXX' frame in each tag, // but only one with the same description. // <Header for 'User defined text information frame', ID: 'TXXX'> // Text encoding $xx // Description <text string according to encoding> $00 (00) // Value <text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['description'] = $frame_description; $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding))); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = trim(getid3_lib::iconv_fallback($parsedFrame['encoding'], $ThisFileInfo['id3v2']['encoding'], $parsedFrame['data'])); } unset($parsedFrame['data']); } elseif ($parsedFrame['frame_name']{0} == 'T') { // 4.2. T??[?] Text information frame // There may only be one text information frame of its kind in an tag. // <Header for 'Text information frame', ID: 'T000' - 'TZZZ', // excluding 'TXXX' described in 4.2.6.> // Text encoding $xx // Information <text string(s) according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { // remove possible terminating \x00 (put by encoding id or software bug) $string = getid3_lib::iconv_fallback($parsedFrame['encoding'], $ThisFileInfo['id3v2']['encoding'], $parsedFrame['data']); if ($string[strlen($string) - 1] == "\x00") { $string = substr($string, 0, strlen($string) - 1); } $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = $string; unset($string); } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'WXXX')) || // 4.3.2 WXXX User defined URL link frame (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'WXX'))) { // 4.3.2 WXX User defined URL link frame // There may be more than one 'WXXX' frame in each tag, // but only one with the same description // <Header for 'User defined URL link frame', ID: 'WXXX'> // Text encoding $xx // Description <text string according to encoding> $00 (00) // URL <text string> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding))); $frame_terminatorpos = strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding)); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } if ($frame_terminatorpos) { // there are null bytes after the data - this is not according to spec // only use data up to first null byte $frame_urldata = (string) substr($parsedFrame['data'], 0, $frame_terminatorpos); } else { // no null bytes following data, just use all data $frame_urldata = (string) $parsedFrame['data']; } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['url'] = $frame_urldata; $parsedFrame['description'] = $frame_description; if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $ThisFileInfo['id3v2']['encoding'], $parsedFrame['url']); } unset($parsedFrame['data']); } elseif ($parsedFrame['frame_name']{0} == 'W') { // 4.3. W??? URL link frames // There may only be one URL link frame of its kind in a tag, // except when stated otherwise in the frame description // <Header for 'URL link frame', ID: 'W000' - 'WZZZ', excluding 'WXXX' // described in 4.3.2.> // URL <text string> $parsedFrame['url'] = trim($parsedFrame['data']); if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = $parsedFrame['url']; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'IPLS')) || // 4.4 IPLS Involved people list (ID3v2.3 only) (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'IPL'))) { // 4.4 IPL Involved people list (ID3v2.2 only) // There may only be one 'IPL' frame in each tag // <Header for 'User defined URL link frame', ID: 'IPL'> // Text encoding $xx // People list strings <textstrings> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($parsedFrame['encodingid']); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $ThisFileInfo['id3v2']['encoding'], $parsedFrame['data']); } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'MCDI')) || // 4.4 MCDI Music CD identifier (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'MCI'))) { // 4.5 MCI Music CD identifier // There may only be one 'MCDI' frame in each tag // <Header for 'Music CD identifier', ID: 'MCDI'> // CD TOC <binary data> if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = $parsedFrame['data']; } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'ETCO')) || // 4.5 ETCO Event timing codes (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'ETC'))) { // 4.6 ETC Event timing codes // There may only be one 'ETCO' frame in each tag // <Header for 'Event timing codes', ID: 'ETCO'> // Time stamp format $xx // Where time stamp format is: // $01 (32-bit value) MPEG frames from beginning of file // $02 (32-bit value) milliseconds from beginning of file // Followed by a list of key events in the following format: // Type of event $xx // Time stamp $xx (xx ...) // The 'Time stamp' is set to zero if directly at the beginning of the sound // or after the previous event. All events MUST be sorted in chronological order. $frame_offset = 0; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); while ($frame_offset < strlen($parsedFrame['data'])) { $parsedFrame['typeid'] = substr($parsedFrame['data'], $frame_offset++, 1); $parsedFrame['type'] = $this->ETCOEventLookup($parsedFrame['typeid']); $parsedFrame['timestamp'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'MLLT')) || // 4.6 MLLT MPEG location lookup table (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'MLL'))) { // 4.7 MLL MPEG location lookup table // There may only be one 'MLLT' frame in each tag // <Header for 'Location lookup table', ID: 'MLLT'> // MPEG frames between reference $xx xx // Bytes between reference $xx xx xx // Milliseconds between reference $xx xx xx // Bits for bytes deviation $xx // Bits for milliseconds dev. $xx // Then for every reference the following data is included; // Deviation in bytes %xxx.... // Deviation in milliseconds %xxx.... $frame_offset = 0; $parsedFrame['framesbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 0, 2)); $parsedFrame['bytesbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 2, 3)); $parsedFrame['msbetweenreferences'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 5, 3)); $parsedFrame['bitsforbytesdeviation'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 8, 1)); $parsedFrame['bitsformsdeviation'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], 9, 1)); $parsedFrame['data'] = substr($parsedFrame['data'], 10); while ($frame_offset < strlen($parsedFrame['data'])) { $deviationbitstream .= getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1)); } $reference_counter = 0; while (strlen($deviationbitstream) > 0) { $parsedFrame[$reference_counter]['bytedeviation'] = bindec(substr($deviationbitstream, 0, $parsedFrame['bitsforbytesdeviation'])); $parsedFrame[$reference_counter]['msdeviation'] = bindec(substr($deviationbitstream, $parsedFrame['bitsforbytesdeviation'], $parsedFrame['bitsformsdeviation'])); $deviationbitstream = substr($deviationbitstream, $parsedFrame['bitsforbytesdeviation'] + $parsedFrame['bitsformsdeviation']); $reference_counter++; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'SYTC')) || // 4.7 SYTC Synchronised tempo codes (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'STC'))) { // 4.8 STC Synchronised tempo codes // There may only be one 'SYTC' frame in each tag // <Header for 'Synchronised tempo codes', ID: 'SYTC'> // Time stamp format $xx // Tempo data <binary data> // Where time stamp format is: // $01 (32-bit value) MPEG frames from beginning of file // $02 (32-bit value) milliseconds from beginning of file $frame_offset = 0; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $timestamp_counter = 0; while ($frame_offset < strlen($parsedFrame['data'])) { $parsedFrame[$timestamp_counter]['tempo'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ($parsedFrame[$timestamp_counter]['tempo'] == 255) { $parsedFrame[$timestamp_counter]['tempo'] += ord(substr($parsedFrame['data'], $frame_offset++, 1)); } $parsedFrame[$timestamp_counter]['timestamp'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $timestamp_counter++; } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'USLT')) || // 4.8 USLT Unsynchronised lyric/text transcription (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'ULT'))) { // 4.9 ULT Unsynchronised lyric/text transcription // There may be more than one 'Unsynchronised lyrics/text transcription' frame // in each tag, but only one with the same language and content descriptor. // <Header for 'Unsynchronised lyrics/text transcription', ID: 'USLT'> // Text encoding $xx // Language $xx xx xx // Content descriptor <text string according to encoding> $00 (00) // Lyrics/text <full text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding))); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['data'] = $parsedFrame['data']; $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); $parsedFrame['description'] = $frame_description; if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $ThisFileInfo['id3v2']['encoding'], $parsedFrame['data']); } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'SYLT')) || // 4.9 SYLT Synchronised lyric/text (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'SLT'))) { // 4.10 SLT Synchronised lyric/text // There may be more than one 'SYLT' frame in each tag, // but only one with the same language and content descriptor. // <Header for 'Synchronised lyrics/text', ID: 'SYLT'> // Text encoding $xx // Language $xx xx xx // Time stamp format $xx // $01 (32-bit value) MPEG frames from beginning of file // $02 (32-bit value) milliseconds from beginning of file // Content type $xx // Content descriptor <text string according to encoding> $00 (00) // Terminated text to be synced (typically a syllable) // Sync identifier (terminator to above string) $00 (00) // Time stamp $xx (xx ...) $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['contenttypeid'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['contenttype'] = $this->SYTLContentTypeLookup($parsedFrame['contenttypeid']); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); $timestampindex = 0; $frame_remainingdata = substr($parsedFrame['data'], $frame_offset); while (strlen($frame_remainingdata)) { $frame_offset = 0; $frame_terminatorpos = strpos($frame_remainingdata, $this->TextEncodingTerminatorLookup($frame_textencoding)); if ($frame_terminatorpos === false) { $frame_remainingdata = ''; } else { if (ord(substr($frame_remainingdata, $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $parsedFrame['lyrics'][$timestampindex]['data'] = substr($frame_remainingdata, $frame_offset, $frame_terminatorpos - $frame_offset); $frame_remainingdata = substr($frame_remainingdata, $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding))); if (($timestampindex == 0) && (ord($frame_remainingdata{0}) != 0)) { // timestamp probably omitted for first data item } else { $parsedFrame['lyrics'][$timestampindex]['timestamp'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 0, 4)); $frame_remainingdata = substr($frame_remainingdata, 4); } $timestampindex++; } } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'COMM')) || // 4.10 COMM Comments (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'COM'))) { // 4.11 COM Comments // There may be more than one comment frame in each tag, // but only one with the same language and content descriptor. // <Header for 'Comment', ID: 'COMM'> // Text encoding $xx // Language $xx xx xx // Short content descrip. <text string according to encoding> $00 (00) // The actual text <full text string according to encoding> if (strlen($parsedFrame['data']) < 5) { $ThisFileInfo['warning'][] = 'Invalid data (too short) for "'.$parsedFrame['frame_name'].'" frame at offset '.$parsedFrame['dataoffset']; } else { $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $frame_text = (string) substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding))); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); $parsedFrame['description'] = $frame_description; $parsedFrame['data'] = $frame_text; if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $ThisFileInfo['id3v2']['encoding'], $parsedFrame['data']); } } } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'RVA2')) { // 4.11 RVA2 Relative volume adjustment (2) (ID3v2.4+ only) // There may be more than one 'RVA2' frame in each tag, // but only one with the same identification string // <Header for 'Relative volume adjustment (2)', ID: 'RVA2'> // Identification <text string> $00 // The 'identification' string is used to identify the situation and/or // device where this adjustment should apply. The following is then // repeated for every channel: // Type of channel $xx // Volume adjustment $xx xx // Bits representing peak $xx // Peak volume $xx (xx ...) $frame_terminatorpos = strpos($parsedFrame['data'], "\x00"); $frame_idstring = substr($parsedFrame['data'], 0, $frame_terminatorpos); if (ord($frame_idstring) === 0) { $frame_idstring = ''; } $frame_remainingdata = substr($parsedFrame['data'], $frame_terminatorpos + strlen("\x00")); $parsedFrame['description'] = $frame_idstring; while (strlen($frame_remainingdata)) { $frame_offset = 0; $frame_channeltypeid = ord(substr($frame_remainingdata, $frame_offset++, 1)); $parsedFrame[$frame_channeltypeid]['channeltypeid'] = $frame_channeltypeid; $parsedFrame[$frame_channeltypeid]['channeltype'] = $this->RVA2ChannelTypeLookup($frame_channeltypeid); $parsedFrame[$frame_channeltypeid]['volumeadjust'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, $frame_offset, 2), false, true); // 16-bit signed $frame_offset += 2; $parsedFrame[$frame_channeltypeid]['bitspeakvolume'] = ord(substr($frame_remainingdata, $frame_offset++, 1)); $frame_bytespeakvolume = ceil($parsedFrame[$frame_channeltypeid]['bitspeakvolume'] / 8); $parsedFrame[$frame_channeltypeid]['peakvolume'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, $frame_offset, $frame_bytespeakvolume)); $frame_remainingdata = substr($frame_remainingdata, $frame_offset + $frame_bytespeakvolume); } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'RVAD')) || // 4.12 RVAD Relative volume adjustment (ID3v2.3 only) (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'RVA'))) { // 4.12 RVA Relative volume adjustment (ID3v2.2 only) // There may only be one 'RVA' frame in each tag // <Header for 'Relative volume adjustment', ID: 'RVA'> // ID3v2.2 => Increment/decrement %000000ba // ID3v2.3 => Increment/decrement %00fedcba // Bits used for volume descr. $xx // Relative volume change, right $xx xx (xx ...) // a // Relative volume change, left $xx xx (xx ...) // b // Peak volume right $xx xx (xx ...) // Peak volume left $xx xx (xx ...) // ID3v2.3 only, optional (not present in ID3v2.2): // Relative volume change, right back $xx xx (xx ...) // c // Relative volume change, left back $xx xx (xx ...) // d // Peak volume right back $xx xx (xx ...) // Peak volume left back $xx xx (xx ...) // ID3v2.3 only, optional (not present in ID3v2.2): // Relative volume change, center $xx xx (xx ...) // e // Peak volume center $xx xx (xx ...) // ID3v2.3 only, optional (not present in ID3v2.2): // Relative volume change, bass $xx xx (xx ...) // f // Peak volume bass $xx xx (xx ...) $frame_offset = 0; $frame_incrdecrflags = getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['incdec']['right'] = (bool) substr($frame_incrdecrflags, 6, 1); $parsedFrame['incdec']['left'] = (bool) substr($frame_incrdecrflags, 7, 1); $parsedFrame['bitsvolume'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_bytesvolume = ceil($parsedFrame['bitsvolume'] / 8); $parsedFrame['volumechange']['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['right'] === false) { $parsedFrame['volumechange']['right'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['volumechange']['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['left'] === false) { $parsedFrame['volumechange']['left'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; if ($id3v2_majorversion == 3) { $parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset); if (strlen($parsedFrame['data']) > 0) { $parsedFrame['incdec']['rightrear'] = (bool) substr($frame_incrdecrflags, 4, 1); $parsedFrame['incdec']['leftrear'] = (bool) substr($frame_incrdecrflags, 5, 1); $parsedFrame['volumechange']['rightrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['rightrear'] === false) { $parsedFrame['volumechange']['rightrear'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['volumechange']['leftrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['leftrear'] === false) { $parsedFrame['volumechange']['leftrear'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['rightrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['leftrear'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; } $parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset); if (strlen($parsedFrame['data']) > 0) { $parsedFrame['incdec']['center'] = (bool) substr($frame_incrdecrflags, 3, 1); $parsedFrame['volumechange']['center'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['center'] === false) { $parsedFrame['volumechange']['center'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['center'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; } $parsedFrame['data'] = substr($parsedFrame['data'], $frame_offset); if (strlen($parsedFrame['data']) > 0) { $parsedFrame['incdec']['bass'] = (bool) substr($frame_incrdecrflags, 2, 1); $parsedFrame['volumechange']['bass'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); if ($parsedFrame['incdec']['bass'] === false) { $parsedFrame['volumechange']['bass'] *= -1; } $frame_offset += $frame_bytesvolume; $parsedFrame['peakvolume']['bass'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesvolume)); $frame_offset += $frame_bytesvolume; } } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'EQU2')) { // 4.12 EQU2 Equalisation (2) (ID3v2.4+ only) // There may be more than one 'EQU2' frame in each tag, // but only one with the same identification string // <Header of 'Equalisation (2)', ID: 'EQU2'> // Interpolation method $xx // $00 Band // $01 Linear // Identification <text string> $00 // The following is then repeated for every adjustment point // Frequency $xx xx // Volume adjustment $xx xx $frame_offset = 0; $frame_interpolationmethod = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_idstring = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_idstring) === 0) { $frame_idstring = ''; } $parsedFrame['description'] = $frame_idstring; $frame_remainingdata = substr($parsedFrame['data'], $frame_terminatorpos + strlen("\x00")); while (strlen($frame_remainingdata)) { $frame_frequency = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 0, 2)) / 2; $parsedFrame['data'][$frame_frequency] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 2, 2), false, true); $frame_remainingdata = substr($frame_remainingdata, 4); } $parsedFrame['interpolationmethod'] = $frame_interpolationmethod; unset($parsedFrame['data']); } elseif ((($id3v2_majorversion == 3) && ($parsedFrame['frame_name'] == 'EQUA')) || // 4.12 EQUA Equalisation (ID3v2.3 only) (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'EQU'))) { // 4.13 EQU Equalisation (ID3v2.2 only) // There may only be one 'EQUA' frame in each tag // <Header for 'Relative volume adjustment', ID: 'EQU'> // Adjustment bits $xx // This is followed by 2 bytes + ('adjustment bits' rounded up to the // nearest byte) for every equalisation band in the following format, // giving a frequency range of 0 - 32767Hz: // Increment/decrement %x (MSB of the Frequency) // Frequency (lower 15 bits) // Adjustment $xx (xx ...) $frame_offset = 0; $parsedFrame['adjustmentbits'] = substr($parsedFrame['data'], $frame_offset++, 1); $frame_adjustmentbytes = ceil($parsedFrame['adjustmentbits'] / 8); $frame_remainingdata = (string) substr($parsedFrame['data'], $frame_offset); while (strlen($frame_remainingdata) > 0) { $frame_frequencystr = getid3_lib::BigEndian2Bin(substr($frame_remainingdata, 0, 2)); $frame_incdec = (bool) substr($frame_frequencystr, 0, 1); $frame_frequency = bindec(substr($frame_frequencystr, 1, 15)); $parsedFrame[$frame_frequency]['incdec'] = $frame_incdec; $parsedFrame[$frame_frequency]['adjustment'] = getid3_lib::BigEndian2Int(substr($frame_remainingdata, 2, $frame_adjustmentbytes)); if ($parsedFrame[$frame_frequency]['incdec'] === false) { $parsedFrame[$frame_frequency]['adjustment'] *= -1; } $frame_remainingdata = substr($frame_remainingdata, 2 + $frame_adjustmentbytes); } unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RVRB')) || // 4.13 RVRB Reverb (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'REV'))) { // 4.14 REV Reverb // There may only be one 'RVRB' frame in each tag. // <Header for 'Reverb', ID: 'RVRB'> // Reverb left (ms) $xx xx // Reverb right (ms) $xx xx // Reverb bounces, left $xx // Reverb bounces, right $xx // Reverb feedback, left to left $xx // Reverb feedback, left to right $xx // Reverb feedback, right to right $xx // Reverb feedback, right to left $xx // Premix left to right $xx // Premix right to left $xx $frame_offset = 0; $parsedFrame['left'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['right'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['bouncesL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['bouncesR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackLL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackLR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackRR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['feedbackRL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['premixLR'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['premixRL'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'APIC')) || // 4.14 APIC Attached picture (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'PIC'))) { // 4.15 PIC Attached picture // There may be several pictures attached to one file, // each in their individual 'APIC' frame, but only one // with the same content descriptor // <Header for 'Attached picture', ID: 'APIC'> // Text encoding $xx // ID3v2.3+ => MIME type <text string> $00 // ID3v2.2 => Image format $xx xx xx // Picture type $xx // Description <text string according to encoding> $00 (00) // Picture data <binary data> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } if ($id3v2_majorversion == 2 && strlen($parsedFrame['data']) > $frame_offset) { $frame_imagetype = substr($parsedFrame['data'], $frame_offset, 3); if (strtolower($frame_imagetype) == 'ima') { // complete hack for mp3Rage (www.chaoticsoftware.com) that puts ID3v2.3-formatted // MIME type instead of 3-char ID3v2.2-format image type (thanks xbhoffØpacbell*net) $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_mimetype) === 0) { $frame_mimetype = ''; } $frame_imagetype = strtoupper(str_replace('image/', '', strtolower($frame_mimetype))); if ($frame_imagetype == 'JPEG') { $frame_imagetype = 'JPG'; } $frame_offset = $frame_terminatorpos + strlen("\x00"); } else { $frame_offset += 3; } } if ($id3v2_majorversion > 2 && strlen($parsedFrame['data']) > $frame_offset) { $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_mimetype) === 0) { $frame_mimetype = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); } $frame_picturetype = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); if ($id3v2_majorversion == 2) { $parsedFrame['imagetype'] = $frame_imagetype; } else { $parsedFrame['mime'] = $frame_mimetype; } $parsedFrame['picturetypeid'] = $frame_picturetype; $parsedFrame['picturetype'] = $this->APICPictureTypeLookup($frame_picturetype); $parsedFrame['description'] = $frame_description; $parsedFrame['data'] = substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding))); $imageinfo = array(); $imagechunkcheck = getid3_lib::GetDataImageSize($parsedFrame['data'], $imageinfo); if (($imagechunkcheck[2] >= 1) && ($imagechunkcheck[2] <= 3)) { $parsedFrame['image_mime'] = 'image/'.getid3_lib::ImageTypesLookup($imagechunkcheck[2]); if ($imagechunkcheck[0]) { $parsedFrame['image_width'] = $imagechunkcheck[0]; } if ($imagechunkcheck[1]) { $parsedFrame['image_height'] = $imagechunkcheck[1]; } $parsedFrame['image_bytes'] = strlen($parsedFrame['data']); } } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'GEOB')) || // 4.15 GEOB General encapsulated object (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'GEO'))) { // 4.16 GEO General encapsulated object // There may be more than one 'GEOB' frame in each tag, // but only one with the same content descriptor // <Header for 'General encapsulated object', ID: 'GEOB'> // Text encoding $xx // MIME type <text string> $00 // Filename <text string according to encoding> $00 (00) // Content description <text string according to encoding> $00 (00) // Encapsulated object <binary data> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_mimetype) === 0) { $frame_mimetype = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_filename = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_filename) === 0) { $frame_filename = ''; } $frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)); $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)); $parsedFrame['objectdata'] = (string) substr($parsedFrame['data'], $frame_offset); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['mime'] = $frame_mimetype; $parsedFrame['filename'] = $frame_filename; $parsedFrame['description'] = $frame_description; unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'PCNT')) || // 4.16 PCNT Play counter (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CNT'))) { // 4.17 CNT Play counter // There may only be one 'PCNT' frame in each tag. // When the counter reaches all one's, one byte is inserted in // front of the counter thus making the counter eight bits bigger // <Header for 'Play counter', ID: 'PCNT'> // Counter $xx xx xx xx (xx ...) $parsedFrame['data'] = getid3_lib::BigEndian2Int($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'POPM')) || // 4.17 POPM Popularimeter (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'POP'))) { // 4.18 POP Popularimeter // There may be more than one 'POPM' frame in each tag, // but only one with the same email address // <Header for 'Popularimeter', ID: 'POPM'> // Email to user <text string> $00 // Rating $xx // Counter $xx xx xx xx (xx ...) $frame_offset = 0; $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_emailaddress = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_emailaddress) === 0) { $frame_emailaddress = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_rating = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['data'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset)); $parsedFrame['email'] = $frame_emailaddress; $parsedFrame['rating'] = $frame_rating; unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RBUF')) || // 4.18 RBUF Recommended buffer size (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'BUF'))) { // 4.19 BUF Recommended buffer size // There may only be one 'RBUF' frame in each tag // <Header for 'Recommended buffer size', ID: 'RBUF'> // Buffer size $xx xx xx // Embedded info flag %0000000x // Offset to next tag $xx xx xx xx $frame_offset = 0; $parsedFrame['buffersize'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 3)); $frame_offset += 3; $frame_embeddedinfoflags = getid3_lib::BigEndian2Bin(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['flags']['embededinfo'] = (bool) substr($frame_embeddedinfoflags, 7, 1); $parsedFrame['nexttagoffset'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); unset($parsedFrame['data']); } elseif (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CRM')) { // 4.20 Encrypted meta frame (ID3v2.2 only) // There may be more than one 'CRM' frame in a tag, // but only one with the same 'owner identifier' // <Header for 'Encrypted meta frame', ID: 'CRM'> // Owner identifier <textstring> $00 (00) // Content/explanation <textstring> $00 (00) // Encrypted datablock <binary data> $frame_offset = 0; $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); $parsedFrame['description'] = $frame_description; unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'AENC')) || // 4.19 AENC Audio encryption (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'CRA'))) { // 4.21 CRA Audio encryption // There may be more than one 'AENC' frames in a tag, // but only one with the same 'Owner identifier' // <Header for 'Audio encryption', ID: 'AENC'> // Owner identifier <text string> $00 // Preview start $xx xx // Preview length $xx xx // Encryption info <binary data> $frame_offset = 0; $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid == ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['previewstart'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['previewlength'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['encryptioninfo'] = (string) substr($parsedFrame['data'], $frame_offset); unset($parsedFrame['data']); } elseif ((($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'LINK')) || // 4.20 LINK Linked information (($id3v2_majorversion == 2) && ($parsedFrame['frame_name'] == 'LNK'))) { // 4.22 LNK Linked information // There may be more than one 'LINK' frame in a tag, // but only one with the same contents // <Header for 'Linked information', ID: 'LINK'> // ID3v2.3+ => Frame identifier $xx xx xx xx // ID3v2.2 => Frame identifier $xx xx xx // URL <text string> $00 // ID and additional data <text string(s)> $frame_offset = 0; if ($id3v2_majorversion == 2) { $parsedFrame['frameid'] = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; } else { $parsedFrame['frameid'] = substr($parsedFrame['data'], $frame_offset, 4); $frame_offset += 4; } $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_url = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_url) === 0) { $frame_url = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['url'] = $frame_url; $parsedFrame['additionaldata'] = (string) substr($parsedFrame['data'], $frame_offset); if (!empty($parsedFrame['framenameshort']) && $parsedFrame['url']) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = utf8_encode($parsedFrame['url']); } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'POSS')) { // 4.21 POSS Position synchronisation frame (ID3v2.3+ only) // There may only be one 'POSS' frame in each tag // <Head for 'Position synchronisation', ID: 'POSS'> // Time stamp format $xx // Position $xx (xx ...) $frame_offset = 0; $parsedFrame['timestampformat'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['position'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset)); unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'USER')) { // 4.22 USER Terms of use (ID3v2.3+ only) // There may be more than one 'Terms of use' frame in a tag, // but only one with the same 'Language' // <Header for 'Terms of use frame', ID: 'USER'> // Text encoding $xx // Language $xx xx xx // The actual text <text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_language = substr($parsedFrame['data'], $frame_offset, 3); $frame_offset += 3; $parsedFrame['language'] = $frame_language; $parsedFrame['languagename'] = $this->LanguageLookup($frame_language, false); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); if (!empty($parsedFrame['framenameshort']) && !empty($parsedFrame['data'])) { $ThisFileInfo['id3v2']['comments'][$parsedFrame['framenameshort']][] = getid3_lib::iconv_fallback($parsedFrame['encoding'], $ThisFileInfo['id3v2']['encoding'], $parsedFrame['data']); } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'OWNE')) { // 4.23 OWNE Ownership frame (ID3v2.3+ only) // There may only be one 'OWNE' frame in a tag // <Header for 'Ownership frame', ID: 'OWNE'> // Text encoding $xx // Price paid <text string> $00 // Date of purch. <text string> // Seller <text string according to encoding> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_pricepaid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['pricepaid']['currencyid'] = substr($frame_pricepaid, 0, 3); $parsedFrame['pricepaid']['currency'] = $this->LookupCurrencyUnits($parsedFrame['pricepaid']['currencyid']); $parsedFrame['pricepaid']['value'] = substr($frame_pricepaid, 3); $parsedFrame['purchasedate'] = substr($parsedFrame['data'], $frame_offset, 8); if (!$this->IsValidDateStampString($parsedFrame['purchasedate'])) { $parsedFrame['purchasedateunix'] = mktime (0, 0, 0, substr($parsedFrame['purchasedate'], 4, 2), substr($parsedFrame['purchasedate'], 6, 2), substr($parsedFrame['purchasedate'], 0, 4)); } $frame_offset += 8; $parsedFrame['seller'] = (string) substr($parsedFrame['data'], $frame_offset); unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'COMR')) { // 4.24 COMR Commercial frame (ID3v2.3+ only) // There may be more than one 'commercial frame' in a tag, // but no two may be identical // <Header for 'Commercial frame', ID: 'COMR'> // Text encoding $xx // Price string <text string> $00 // Valid until <text string> // Contact URL <text string> $00 // Received as $xx // Name of seller <text string according to encoding> $00 (00) // Description <text string according to encoding> $00 (00) // Picture MIME type <string> $00 // Seller logo <binary data> $frame_offset = 0; $frame_textencoding = ord(substr($parsedFrame['data'], $frame_offset++, 1)); if ((($id3v2_majorversion <= 3) && ($frame_textencoding > 1)) || (($id3v2_majorversion == 4) && ($frame_textencoding > 3))) { $ThisFileInfo['warning'][] = 'Invalid text encoding byte ('.$frame_textencoding.') in frame "'.$parsedFrame['frame_name'].'" - defaulting to ISO-8859-1 encoding'; } $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_pricestring = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_rawpricearray = explode('/', $frame_pricestring); foreach ($frame_rawpricearray as $key => $val) { $frame_currencyid = substr($val, 0, 3); $parsedFrame['price'][$frame_currencyid]['currency'] = $this->LookupCurrencyUnits($frame_currencyid); $parsedFrame['price'][$frame_currencyid]['value'] = substr($val, 3); } $frame_datestring = substr($parsedFrame['data'], $frame_offset, 8); $frame_offset += 8; $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_contacturl = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_receivedasid = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_sellername = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_sellername) === 0) { $frame_sellername = ''; } $frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)); $frame_terminatorpos = @strpos($parsedFrame['data'], $this->TextEncodingTerminatorLookup($frame_textencoding), $frame_offset); if (ord(substr($parsedFrame['data'], $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)), 1)) === 0) { $frame_terminatorpos++; // @strpos() fooled because 2nd byte of Unicode chars are often 0x00 } $frame_description = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_description) === 0) { $frame_description = ''; } $frame_offset = $frame_terminatorpos + strlen($this->TextEncodingTerminatorLookup($frame_textencoding)); $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_mimetype = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); $frame_offset = $frame_terminatorpos + strlen("\x00"); $frame_sellerlogo = substr($parsedFrame['data'], $frame_offset); $parsedFrame['encodingid'] = $frame_textencoding; $parsedFrame['encoding'] = $this->TextEncodingNameLookup($frame_textencoding); $parsedFrame['pricevaliduntil'] = $frame_datestring; $parsedFrame['contacturl'] = $frame_contacturl; $parsedFrame['receivedasid'] = $frame_receivedasid; $parsedFrame['receivedas'] = $this->COMRReceivedAsLookup($frame_receivedasid); $parsedFrame['sellername'] = $frame_sellername; $parsedFrame['description'] = $frame_description; $parsedFrame['mime'] = $frame_mimetype; $parsedFrame['logo'] = $frame_sellerlogo; unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'ENCR')) { // 4.25 ENCR Encryption method registration (ID3v2.3+ only) // There may be several 'ENCR' frames in a tag, // but only one containing the same symbol // and only one containing the same owner identifier // <Header for 'Encryption method registration', ID: 'ENCR'> // Owner identifier <text string> $00 // Method symbol $xx // Encryption data <binary data> $frame_offset = 0; $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['methodsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'GRID')) { // 4.26 GRID Group identification registration (ID3v2.3+ only) // There may be several 'GRID' frames in a tag, // but only one containing the same symbol // and only one containing the same owner identifier // <Header for 'Group ID registration', ID: 'GRID'> // Owner identifier <text string> $00 // Group symbol $xx // Group dependent data <binary data> $frame_offset = 0; $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['groupsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'PRIV')) { // 4.27 PRIV Private frame (ID3v2.3+ only) // The tag may contain more than one 'PRIV' frame // but only with different contents // <Header for 'Private frame', ID: 'PRIV'> // Owner identifier <text string> $00 // The private data <binary data> $frame_offset = 0; $frame_terminatorpos = @strpos($parsedFrame['data'], "\x00", $frame_offset); $frame_ownerid = substr($parsedFrame['data'], $frame_offset, $frame_terminatorpos - $frame_offset); if (ord($frame_ownerid) === 0) { $frame_ownerid = ''; } $frame_offset = $frame_terminatorpos + strlen("\x00"); $parsedFrame['ownerid'] = $frame_ownerid; $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'SIGN')) { // 4.28 SIGN Signature frame (ID3v2.4+ only) // There may be more than one 'signature frame' in a tag, // but no two may be identical // <Header for 'Signature frame', ID: 'SIGN'> // Group symbol $xx // Signature <binary data> $frame_offset = 0; $parsedFrame['groupsymbol'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $parsedFrame['data'] = (string) substr($parsedFrame['data'], $frame_offset); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'SEEK')) { // 4.29 SEEK Seek frame (ID3v2.4+ only) // There may only be one 'seek frame' in a tag // <Header for 'Seek frame', ID: 'SEEK'> // Minimum offset to next tag $xx xx xx xx $frame_offset = 0; $parsedFrame['data'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); } elseif (($id3v2_majorversion >= 4) && ($parsedFrame['frame_name'] == 'ASPI')) { // 4.30 ASPI Audio seek point index (ID3v2.4+ only) // There may only be one 'audio seek point index' frame in a tag // <Header for 'Seek Point Index', ID: 'ASPI'> // Indexed data start (S) $xx xx xx xx // Indexed data length (L) $xx xx xx xx // Number of index points (N) $xx xx // Bits per index point (b) $xx // Then for every index point the following data is included: // Fraction at index (Fi) $xx (xx) $frame_offset = 0; $parsedFrame['datastart'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $parsedFrame['indexeddatalength'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $parsedFrame['indexpoints'] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['bitsperpoint'] = ord(substr($parsedFrame['data'], $frame_offset++, 1)); $frame_bytesperpoint = ceil($parsedFrame['bitsperpoint'] / 8); for ($i = 0; $i < $frame_indexpoints; $i++) { $parsedFrame['indexes'][$i] = getid3_lib::BigEndian2Int(substr($parsedFrame['data'], $frame_offset, $frame_bytesperpoint)); $frame_offset += $frame_bytesperpoint; } unset($parsedFrame['data']); } elseif (($id3v2_majorversion >= 3) && ($parsedFrame['frame_name'] == 'RGAD')) { // Replay Gain Adjustment // http://privatewww.essex.ac.uk/~djmrob/replaygain/file_format_id3v2.html // There may only be one 'RGAD' frame in a tag // <Header for 'Replay Gain Adjustment', ID: 'RGAD'> // Peak Amplitude $xx $xx $xx $xx // Radio Replay Gain Adjustment %aaabbbcd %dddddddd // Audiophile Replay Gain Adjustment %aaabbbcd %dddddddd // a - name code // b - originator code // c - sign bit // d - replay gain adjustment $frame_offset = 0; $parsedFrame['peakamplitude'] = getid3_lib::BigEndian2Float(substr($parsedFrame['data'], $frame_offset, 4)); $frame_offset += 4; $rg_track_adjustment = getid3_lib::Dec2Bin(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $rg_album_adjustment = getid3_lib::Dec2Bin(substr($parsedFrame['data'], $frame_offset, 2)); $frame_offset += 2; $parsedFrame['raw']['track']['name'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 0, 3)); $parsedFrame['raw']['track']['originator'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 3, 3)); $parsedFrame['raw']['track']['signbit'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 6, 1)); $parsedFrame['raw']['track']['adjustment'] = getid3_lib::Bin2Dec(substr($rg_track_adjustment, 7, 9)); $parsedFrame['raw']['album']['name'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 0, 3)); $parsedFrame['raw']['album']['originator'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 3, 3)); $parsedFrame['raw']['album']['signbit'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 6, 1)); $parsedFrame['raw']['album']['adjustment'] = getid3_lib::Bin2Dec(substr($rg_album_adjustment, 7, 9)); $parsedFrame['track']['name'] = getid3_lib::RGADnameLookup($parsedFrame['raw']['track']['name']); $parsedFrame['track']['originator'] = getid3_lib::RGADoriginatorLookup($parsedFrame['raw']['track']['originator']); $parsedFrame['track']['adjustment'] = getid3_lib::RGADadjustmentLookup($parsedFrame['raw']['track']['adjustment'], $parsedFrame['raw']['track']['signbit']); $parsedFrame['album']['name'] = getid3_lib::RGADnameLookup($parsedFrame['raw']['album']['name']); $parsedFrame['album']['originator'] = getid3_lib::RGADoriginatorLookup($parsedFrame['raw']['album']['originator']); $parsedFrame['album']['adjustment'] = getid3_lib::RGADadjustmentLookup($parsedFrame['raw']['album']['adjustment'], $parsedFrame['raw']['album']['signbit']); $ThisFileInfo['replay_gain']['track']['peak'] = $parsedFrame['peakamplitude']; $ThisFileInfo['replay_gain']['track']['originator'] = $parsedFrame['track']['originator']; $ThisFileInfo['replay_gain']['track']['adjustment'] = $parsedFrame['track']['adjustment']; $ThisFileInfo['replay_gain']['album']['originator'] = $parsedFrame['album']['originator']; $ThisFileInfo['replay_gain']['album']['adjustment'] = $parsedFrame['album']['adjustment']; unset($parsedFrame['data']); } return true; } function DeUnsynchronise($data) { return str_replace("\xFF\x00", "\xFF", $data); } function LookupCurrencyUnits($currencyid) { $begin = __LINE__; /** This is not a comment! AED Dirhams AFA Afghanis ALL Leke AMD Drams ANG Guilders AOA Kwanza ARS Pesos ATS Schillings AUD Dollars AWG Guilders AZM Manats BAM Convertible Marka BBD Dollars BDT Taka BEF Francs BGL Leva BHD Dinars BIF Francs BMD Dollars BND Dollars BOB Bolivianos BRL Brazil Real BSD Dollars BTN Ngultrum BWP Pulas BYR Rubles BZD Dollars CAD Dollars CDF Congolese Francs CHF Francs CLP Pesos CNY Yuan Renminbi COP Pesos CRC Colones CUP Pesos CVE Escudos CYP Pounds CZK Koruny DEM Deutsche Marks DJF Francs DKK Kroner DOP Pesos DZD Algeria Dinars EEK Krooni EGP Pounds ERN Nakfa ESP Pesetas ETB Birr EUR Euro FIM Markkaa FJD Dollars FKP Pounds FRF Francs GBP Pounds GEL Lari GGP Pounds GHC Cedis GIP Pounds GMD Dalasi GNF Francs GRD Drachmae GTQ Quetzales GYD Dollars HKD Dollars HNL Lempiras HRK Kuna HTG Gourdes HUF Forints IDR Rupiahs IEP Pounds ILS New Shekels IMP Pounds INR Rupees IQD Dinars IRR Rials ISK Kronur ITL Lire JEP Pounds JMD Dollars JOD Dinars JPY Yen KES Shillings KGS Soms KHR Riels KMF Francs KPW Won KWD Dinars KYD Dollars KZT Tenge LAK Kips LBP Pounds LKR Rupees LRD Dollars LSL Maloti LTL Litai LUF Francs LVL Lati LYD Dinars MAD Dirhams MDL Lei MGF Malagasy Francs MKD Denars MMK Kyats MNT Tugriks MOP Patacas MRO Ouguiyas MTL Liri MUR Rupees MVR Rufiyaa MWK Kwachas MXN Pesos MYR Ringgits MZM Meticais NAD Dollars NGN Nairas NIO Gold Cordobas NLG Guilders NOK Krone NPR Nepal Rupees NZD Dollars OMR Rials PAB Balboa PEN Nuevos Soles PGK Kina PHP Pesos PKR Rupees PLN Zlotych PTE Escudos PYG Guarani QAR Rials ROL Lei RUR Rubles RWF Rwanda Francs SAR Riyals SBD Dollars SCR Rupees SDD Dinars SEK Kronor SGD Dollars SHP Pounds SIT Tolars SKK Koruny SLL Leones SOS Shillings SPL Luigini SRG Guilders STD Dobras SVC Colones SYP Pounds SZL Emalangeni THB Baht TJR Rubles TMM Manats TND Dinars TOP Pa'anga TRL Liras TTD Dollars TVD Tuvalu Dollars TWD New Dollars TZS Shillings UAH Hryvnia UGX Shillings USD Dollars UYU Pesos UZS Sums VAL Lire VEB Bolivares VND Dong VUV Vatu WST Tala XAF Francs XAG Ounces XAU Ounces XCD Dollars XDR Special Drawing Rights XPD Ounces XPF Francs XPT Ounces YER Rials YUM New Dinars ZAR Rand ZMK Kwacha ZWD Zimbabwe Dollars */ return getid3_lib::EmbeddedLookup($currencyid, $begin, __LINE__, __FILE__, 'id3v2-currency-units'); } function LookupCurrencyCountry($currencyid) { $begin = __LINE__; /** This is not a comment! AED United Arab Emirates AFA Afghanistan ALL Albania AMD Armenia ANG Netherlands Antilles AOA Angola ARS Argentina ATS Austria AUD Australia AWG Aruba AZM Azerbaijan BAM Bosnia and Herzegovina BBD Barbados BDT Bangladesh BEF Belgium BGL Bulgaria BHD Bahrain BIF Burundi BMD Bermuda BND Brunei Darussalam BOB Bolivia BRL Brazil BSD Bahamas BTN Bhutan BWP Botswana BYR Belarus BZD Belize CAD Canada CDF Congo/Kinshasa CHF Switzerland CLP Chile CNY China COP Colombia CRC Costa Rica CUP Cuba CVE Cape Verde CYP Cyprus CZK Czech Republic DEM Germany DJF Djibouti DKK Denmark DOP Dominican Republic DZD Algeria EEK Estonia EGP Egypt ERN Eritrea ESP Spain ETB Ethiopia EUR Euro Member Countries FIM Finland FJD Fiji FKP Falkland Islands (Malvinas) FRF France GBP United Kingdom GEL Georgia GGP Guernsey GHC Ghana GIP Gibraltar GMD Gambia GNF Guinea GRD Greece GTQ Guatemala GYD Guyana HKD Hong Kong HNL Honduras HRK Croatia HTG Haiti HUF Hungary IDR Indonesia IEP Ireland (Eire) ILS Israel IMP Isle of Man INR India IQD Iraq IRR Iran ISK Iceland ITL Italy JEP Jersey JMD Jamaica JOD Jordan JPY Japan KES Kenya KGS Kyrgyzstan KHR Cambodia KMF Comoros KPW Korea KWD Kuwait KYD Cayman Islands KZT Kazakstan LAK Laos LBP Lebanon LKR Sri Lanka LRD Liberia LSL Lesotho LTL Lithuania LUF Luxembourg LVL Latvia LYD Libya MAD Morocco MDL Moldova MGF Madagascar MKD Macedonia MMK Myanmar (Burma) MNT Mongolia MOP Macau MRO Mauritania MTL Malta MUR Mauritius MVR Maldives (Maldive Islands) MWK Malawi MXN Mexico MYR Malaysia MZM Mozambique NAD Namibia NGN Nigeria NIO Nicaragua NLG Netherlands (Holland) NOK Norway NPR Nepal NZD New Zealand OMR Oman PAB Panama PEN Peru PGK Papua New Guinea PHP Philippines PKR Pakistan PLN Poland PTE Portugal PYG Paraguay QAR Qatar ROL Romania RUR Russia RWF Rwanda SAR Saudi Arabia SBD Solomon Islands SCR Seychelles SDD Sudan SEK Sweden SGD Singapore SHP Saint Helena SIT Slovenia SKK Slovakia SLL Sierra Leone SOS Somalia SPL Seborga SRG Suriname STD São Tome and Principe SVC El Salvador SYP Syria SZL Swaziland THB Thailand TJR Tajikistan TMM Turkmenistan TND Tunisia TOP Tonga TRL Turkey TTD Trinidad and Tobago TVD Tuvalu TWD Taiwan TZS Tanzania UAH Ukraine UGX Uganda USD United States of America UYU Uruguay UZS Uzbekistan VAL Vatican City VEB Venezuela VND Viet Nam VUV Vanuatu WST Samoa XAF Communauté Financière Africaine XAG Silver XAU Gold XCD East Caribbean XDR International Monetary Fund XPD Palladium XPF Comptoirs Français du Pacifique XPT Platinum YER Yemen YUM Yugoslavia ZAR South Africa ZMK Zambia ZWD Zimbabwe */ return getid3_lib::EmbeddedLookup($currencyid, $begin, __LINE__, __FILE__, 'id3v2-currency-country'); } function LanguageLookup($languagecode, $casesensitive=false) { if (!$casesensitive) { $languagecode = strtolower($languagecode); } // http://www.id3.org/id3v2.4.0-structure.txt // [4. ID3v2 frame overview] // The three byte language field, present in several frames, is used to // describe the language of the frame's content, according to ISO-639-2 // [ISO-639-2]. The language should be represented in lower case. If the // language is not known the string "XXX" should be used. // ISO 639-2 - http://www.id3.org/iso639-2.html $begin = __LINE__; /** This is not a comment! XXX unknown xxx unknown aar Afar abk Abkhazian ace Achinese ach Acoli ada Adangme afa Afro-Asiatic (Other) afh Afrihili afr Afrikaans aka Akan akk Akkadian alb Albanian ale Aleut alg Algonquian Languages amh Amharic ang English, Old (ca. 450-1100) apa Apache Languages ara Arabic arc Aramaic arm Armenian arn Araucanian arp Arapaho art Artificial (Other) arw Arawak asm Assamese ath Athapascan Languages ava Avaric ave Avestan awa Awadhi aym Aymara aze Azerbaijani bad Banda bai Bamileke Languages bak Bashkir bal Baluchi bam Bambara ban Balinese baq Basque bas Basa bat Baltic (Other) bej Beja bel Byelorussian bem Bemba ben Bengali ber Berber (Other) bho Bhojpuri bih Bihari bik Bikol bin Bini bis Bislama bla Siksika bnt Bantu (Other) bod Tibetan bra Braj bre Breton bua Buriat bug Buginese bul Bulgarian bur Burmese cad Caddo cai Central American Indian (Other) car Carib cat Catalan cau Caucasian (Other) ceb Cebuano cel Celtic (Other) ces Czech cha Chamorro chb Chibcha che Chechen chg Chagatai chi Chinese chm Mari chn Chinook jargon cho Choctaw chr Cherokee chu Church Slavic chv Chuvash chy Cheyenne cop Coptic cor Cornish cos Corsican cpe Creoles and Pidgins, English-based (Other) cpf Creoles and Pidgins, French-based (Other) cpp Creoles and Pidgins, Portuguese-based (Other) cre Cree crp Creoles and Pidgins (Other) cus Cushitic (Other) cym Welsh cze Czech dak Dakota dan Danish del Delaware deu German din Dinka div Divehi doi Dogri dra Dravidian (Other) dua Duala dum Dutch, Middle (ca. 1050-1350) dut Dutch dyu Dyula dzo Dzongkha efi Efik egy Egyptian (Ancient) eka Ekajuk ell Greek, Modern (1453-) elx Elamite eng English enm English, Middle (ca. 1100-1500) epo Esperanto esk Eskimo (Other) esl Spanish est Estonian eus Basque ewe Ewe ewo Ewondo fan Fang fao Faroese fas Persian fat Fanti fij Fijian fin Finnish fiu Finno-Ugrian (Other) fon Fon fra French fre French frm French, Middle (ca. 1400-1600) fro French, Old (842- ca. 1400) fry Frisian ful Fulah gaa Ga gae Gaelic (Scots) gai Irish gay Gayo gdh Gaelic (Scots) gem Germanic (Other) geo Georgian ger German gez Geez gil Gilbertese glg Gallegan gmh German, Middle High (ca. 1050-1500) goh German, Old High (ca. 750-1050) gon Gondi got Gothic grb Grebo grc Greek, Ancient (to 1453) gre Greek, Modern (1453-) grn Guarani guj Gujarati hai Haida hau Hausa haw Hawaiian heb Hebrew her Herero hil Hiligaynon him Himachali hin Hindi hmo Hiri Motu hun Hungarian hup Hupa hye Armenian iba Iban ibo Igbo ice Icelandic ijo Ijo iku Inuktitut ilo Iloko ina Interlingua (International Auxiliary language Association) inc Indic (Other) ind Indonesian ine Indo-European (Other) ine Interlingue ipk Inupiak ira Iranian (Other) iri Irish iro Iroquoian uages isl Icelandic ita Italian jav Javanese jaw Javanese jpn Japanese jpr Judeo-Persian jrb Judeo-Arabic kaa Kara-Kalpak kab Kabyle kac Kachin kal Greenlandic kam Kamba kan Kannada kar Karen kas Kashmiri kat Georgian kau Kanuri kaw Kawi kaz Kazakh kha Khasi khi Khoisan (Other) khm Khmer kho Khotanese kik Kikuyu kin Kinyarwanda kir Kirghiz kok Konkani kom Komi kon Kongo kor Korean kpe Kpelle kro Kru kru Kurukh kua Kuanyama kum Kumyk kur Kurdish kus Kusaie kut Kutenai lad Ladino lah Lahnda lam Lamba lao Lao lat Latin lav Latvian lez Lezghian lin Lingala lit Lithuanian lol Mongo loz Lozi ltz Letzeburgesch lub Luba-Katanga lug Ganda lui Luiseno lun Lunda luo Luo (Kenya and Tanzania) mac Macedonian mad Madurese mag Magahi mah Marshall mai Maithili mak Macedonian mak Makasar mal Malayalam man Mandingo mao Maori map Austronesian (Other) mar Marathi mas Masai max Manx may Malay men Mende mga Irish, Middle (900 - 1200) mic Micmac min Minangkabau mis Miscellaneous (Other) mkh Mon-Kmer (Other) mlg Malagasy mlt Maltese mni Manipuri mno Manobo Languages moh Mohawk mol Moldavian mon Mongolian mos Mossi mri Maori msa Malay mul Multiple Languages mun Munda Languages mus Creek mwr Marwari mya Burmese myn Mayan Languages nah Aztec nai North American Indian (Other) nau Nauru nav Navajo nbl Ndebele, South nde Ndebele, North ndo Ndongo nep Nepali new Newari nic Niger-Kordofanian (Other) niu Niuean nla Dutch nno Norwegian (Nynorsk) non Norse, Old nor Norwegian nso Sotho, Northern nub Nubian Languages nya Nyanja nym Nyamwezi nyn Nyankole nyo Nyoro nzi Nzima oci Langue d'Oc (post 1500) oji Ojibwa ori Oriya orm Oromo osa Osage oss Ossetic ota Turkish, Ottoman (1500 - 1928) oto Otomian Languages paa Papuan-Australian (Other) pag Pangasinan pal Pahlavi pam Pampanga pan Panjabi pap Papiamento pau Palauan peo Persian, Old (ca 600 - 400 B.C.) per Persian phn Phoenician pli Pali pol Polish pon Ponape por Portuguese pra Prakrit uages pro Provencal, Old (to 1500) pus Pushto que Quechua raj Rajasthani rar Rarotongan roa Romance (Other) roh Rhaeto-Romance rom Romany ron Romanian rum Romanian run Rundi rus Russian sad Sandawe sag Sango sah Yakut sai South American Indian (Other) sal Salishan Languages sam Samaritan Aramaic san Sanskrit sco Scots scr Serbo-Croatian sel Selkup sem Semitic (Other) sga Irish, Old (to 900) shn Shan sid Sidamo sin Singhalese sio Siouan Languages sit Sino-Tibetan (Other) sla Slavic (Other) slk Slovak slo Slovak slv Slovenian smi Sami Languages smo Samoan sna Shona snd Sindhi sog Sogdian som Somali son Songhai sot Sotho, Southern spa Spanish sqi Albanian srd Sardinian srr Serer ssa Nilo-Saharan (Other) ssw Siswant ssw Swazi suk Sukuma sun Sudanese sus Susu sux Sumerian sve Swedish swa Swahili swe Swedish syr Syriac tah Tahitian tam Tamil tat Tatar tel Telugu tem Timne ter Tereno tgk Tajik tgl Tagalog tha Thai tib Tibetan tig Tigre tir Tigrinya tiv Tivi tli Tlingit tmh Tamashek tog Tonga (Nyasa) ton Tonga (Tonga Islands) tru Truk tsi Tsimshian tsn Tswana tso Tsonga tuk Turkmen tum Tumbuka tur Turkish tut Altaic (Other) twi Twi tyv Tuvinian uga Ugaritic uig Uighur ukr Ukrainian umb Umbundu und Undetermined urd Urdu uzb Uzbek vai Vai ven Venda vie Vietnamese vol Volapük vot Votic wak Wakashan Languages wal Walamo war Waray was Washo wel Welsh wen Sorbian Languages wol Wolof xho Xhosa yao Yao yap Yap yid Yiddish yor Yoruba zap Zapotec zen Zenaga zha Zhuang zho Chinese zul Zulu zun Zuni */ return getid3_lib::EmbeddedLookup($languagecode, $begin, __LINE__, __FILE__, 'id3v2-languagecode'); } function ETCOEventLookup($index) { if (($index >= 0x17) && ($index <= 0xDF)) { return 'reserved for future use'; } if (($index >= 0xE0) && ($index <= 0xEF)) { return 'not predefined synch 0-F'; } if (($index >= 0xF0) && ($index <= 0xFC)) { return 'reserved for future use'; } static $EventLookup = array( 0x00 => 'padding (has no meaning)', 0x01 => 'end of initial silence', 0x02 => 'intro start', 0x03 => 'main part start', 0x04 => 'outro start', 0x05 => 'outro end', 0x06 => 'verse start', 0x07 => 'refrain start', 0x08 => 'interlude start', 0x09 => 'theme start', 0x0A => 'variation start', 0x0B => 'key change', 0x0C => 'time change', 0x0D => 'momentary unwanted noise (Snap, Crackle & Pop)', 0x0E => 'sustained noise', 0x0F => 'sustained noise end', 0x10 => 'intro end', 0x11 => 'main part end', 0x12 => 'verse end', 0x13 => 'refrain end', 0x14 => 'theme end', 0x15 => 'profanity', 0x16 => 'profanity end', 0xFD => 'audio end (start of silence)', 0xFE => 'audio file ends', 0xFF => 'one more byte of events follows' ); return (isset($EventLookup[$index]) ? $EventLookup[$index] : ''); } function SYTLContentTypeLookup($index) { static $SYTLContentTypeLookup = array( 0x00 => 'other', 0x01 => 'lyrics', 0x02 => 'text transcription', 0x03 => 'movement/part name', // (e.g. 'Adagio') 0x04 => 'events', // (e.g. 'Don Quijote enters the stage') 0x05 => 'chord', // (e.g. 'Bb F Fsus') 0x06 => 'trivia/\'pop up\' information', 0x07 => 'URLs to webpages', 0x08 => 'URLs to images' ); return (isset($SYTLContentTypeLookup[$index]) ? $SYTLContentTypeLookup[$index] : ''); } function APICPictureTypeLookup($index, $returnarray=false) { static $APICPictureTypeLookup = array( 0x00 => 'Other', 0x01 => '32x32 pixels \'file icon\' (PNG only)', 0x02 => 'Other file icon', 0x03 => 'Cover (front)', 0x04 => 'Cover (back)', 0x05 => 'Leaflet page', 0x06 => 'Media (e.g. label side of CD)', 0x07 => 'Lead artist/lead performer/soloist', 0x08 => 'Artist/performer', 0x09 => 'Conductor', 0x0A => 'Band/Orchestra', 0x0B => 'Composer', 0x0C => 'Lyricist/text writer', 0x0D => 'Recording Location', 0x0E => 'During recording', 0x0F => 'During performance', 0x10 => 'Movie/video screen capture', 0x11 => 'A bright coloured fish', 0x12 => 'Illustration', 0x13 => 'Band/artist logotype', 0x14 => 'Publisher/Studio logotype' ); if ($returnarray) { return $APICPictureTypeLookup; } return (isset($APICPictureTypeLookup[$index]) ? $APICPictureTypeLookup[$index] : ''); } function COMRReceivedAsLookup($index) { static $COMRReceivedAsLookup = array( 0x00 => 'Other', 0x01 => 'Standard CD album with other songs', 0x02 => 'Compressed audio on CD', 0x03 => 'File over the Internet', 0x04 => 'Stream over the Internet', 0x05 => 'As note sheets', 0x06 => 'As note sheets in a book with other sheets', 0x07 => 'Music on other media', 0x08 => 'Non-musical merchandise' ); return (isset($COMRReceivedAsLookup[$index]) ? $COMRReceivedAsLookup[$index] : ''); } function RVA2ChannelTypeLookup($index) { static $RVA2ChannelTypeLookup = array( 0x00 => 'Other', 0x01 => 'Master volume', 0x02 => 'Front right', 0x03 => 'Front left', 0x04 => 'Back right', 0x05 => 'Back left', 0x06 => 'Front centre', 0x07 => 'Back centre', 0x08 => 'Subwoofer' ); return (isset($RVA2ChannelTypeLookup[$index]) ? $RVA2ChannelTypeLookup[$index] : ''); } function FrameNameLongLookup($framename) { $begin = __LINE__; /** This is not a comment! AENC Audio encryption APIC Attached picture ASPI Audio seek point index BUF Recommended buffer size CNT Play counter COM Comments COMM Comments COMR Commercial frame CRA Audio encryption CRM Encrypted meta frame ENCR Encryption method registration EQU Equalisation EQU2 Equalisation (2) EQUA Equalisation ETC Event timing codes ETCO Event timing codes GEO General encapsulated object GEOB General encapsulated object GRID Group identification registration IPL Involved people list IPLS Involved people list LINK Linked information LNK Linked information MCDI Music CD identifier MCI Music CD Identifier MLL MPEG location lookup table MLLT MPEG location lookup table OWNE Ownership frame PCNT Play counter PIC Attached picture POP Popularimeter POPM Popularimeter POSS Position synchronisation frame PRIV Private frame RBUF Recommended buffer size REV Reverb RVA Relative volume adjustment RVA2 Relative volume adjustment (2) RVAD Relative volume adjustment RVRB Reverb SEEK Seek frame SIGN Signature frame SLT Synchronised lyric/text STC Synced tempo codes SYLT Synchronised lyric/text SYTC Synchronised tempo codes TAL Album/Movie/Show title TALB Album/Movie/Show title TBP BPM (Beats Per Minute) TBPM BPM (beats per minute) TCM Composer TCMP Part of a compilation TCO Content type TCOM Composer TCON Content type TCOP Copyright message TCP Part of a compilation TCR Copyright message TDA Date TDAT Date TDEN Encoding time TDLY Playlist delay TDOR Original release time TDRC Recording time TDRL Release time TDTG Tagging time TDY Playlist delay TEN Encoded by TENC Encoded by TEXT Lyricist/Text writer TFLT File type TFT File type TIM Time TIME Time TIPL Involved people list TIT1 Content group description TIT2 Title/songname/content description TIT3 Subtitle/Description refinement TKE Initial key TKEY Initial key TLA Language(s) TLAN Language(s) TLE Length TLEN Length TMCL Musician credits list TMED Media type TMOO Mood TMT Media type TOA Original artist(s)/performer(s) TOAL Original album/movie/show title TOF Original filename TOFN Original filename TOL Original Lyricist(s)/text writer(s) TOLY Original lyricist(s)/text writer(s) TOPE Original artist(s)/performer(s) TOR Original release year TORY Original release year TOT Original album/Movie/Show title TOWN File owner/licensee TP1 Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group TP2 Band/Orchestra/Accompaniment TP3 Conductor/Performer refinement TP4 Interpreted, remixed, or otherwise modified by TPA Part of a set TPB Publisher TPE1 Lead performer(s)/Soloist(s) TPE2 Band/orchestra/accompaniment TPE3 Conductor/performer refinement TPE4 Interpreted, remixed, or otherwise modified by TPOS Part of a set TPRO Produced notice TPUB Publisher TRC ISRC (International Standard Recording Code) TRCK Track number/Position in set TRD Recording dates TRDA Recording dates TRK Track number/Position in set TRSN Internet radio station name TRSO Internet radio station owner TS2 Album-Artist sort order TSA Album sort order TSC Composer sort order TSI Size TSIZ Size TSO2 Album-Artist sort order TSOA Album sort order TSOC Composer sort order TSOP Performer sort order TSOT Title sort order TSP Performer sort order TSRC ISRC (international standard recording code) TSS Software/hardware and settings used for encoding TSSE Software/Hardware and settings used for encoding TSST Set subtitle TST Title sort order TT1 Content group description TT2 Title/Songname/Content description TT3 Subtitle/Description refinement TXT Lyricist/text writer TXX User defined text information frame TXXX User defined text information frame TYE Year TYER Year UFI Unique file identifier UFID Unique file identifier ULT Unsychronised lyric/text transcription USER Terms of use USLT Unsynchronised lyric/text transcription WAF Official audio file webpage WAR Official artist/performer webpage WAS Official audio source webpage WCM Commercial information WCOM Commercial information WCOP Copyright/Legal information WCP Copyright/Legal information WOAF Official audio file webpage WOAR Official artist/performer webpage WOAS Official audio source webpage WORS Official Internet radio station homepage WPAY Payment WPB Publishers official webpage WPUB Publishers official webpage WXX User defined URL link frame WXXX User defined URL link frame TFEA Featured Artist TSTU Recording Studio rgad Replay Gain Adjustment */ return getid3_lib::EmbeddedLookup($framename, $begin, __LINE__, __FILE__, 'id3v2-framename_long'); // Last three: // from Helium2 [www.helium2.com] // from http://privatewww.essex.ac.uk/~djmrob/replaygain/file_format_id3v2.html } function FrameNameShortLookup($framename) { $begin = __LINE__; /** This is not a comment! AENC audio_encryption APIC attached_picture ASPI audio_seek_point_index BUF recommended_buffer_size CNT play_counter COM comments COMM comments COMR commercial_frame CRA audio_encryption CRM encrypted_meta_frame ENCR encryption_method_registration EQU equalisation EQU2 equalisation EQUA equalisation ETC event_timing_codes ETCO event_timing_codes GEO general_encapsulated_object GEOB general_encapsulated_object GRID group_identification_registration IPL involved_people_list IPLS involved_people_list LINK linked_information LNK linked_information MCDI music_cd_identifier MCI music_cd_identifier MLL mpeg_location_lookup_table MLLT mpeg_location_lookup_table OWNE ownership_frame PCNT play_counter PIC attached_picture POP popularimeter POPM popularimeter POSS position_synchronisation_frame PRIV private_frame RBUF recommended_buffer_size REV reverb RVA relative_volume_adjustment RVA2 relative_volume_adjustment RVAD relative_volume_adjustment RVRB reverb SEEK seek_frame SIGN signature_frame SLT synchronised_lyric STC synced_tempo_codes SYLT synchronised_lyric SYTC synchronised_tempo_codes TAL album TALB album TBP bpm TBPM bpm TCM composer TCMP part_of_a_compilation TCO genre TCOM composer TCON genre TCOP copyright_message TCP part_of_a_compilation TCR copyright_message TDA date TDAT date TDEN encoding_time TDLY playlist_delay TDOR original_release_time TDRC recording_time TDRL release_time TDTG tagging_time TDY playlist_delay TEN encoded_by TENC encoded_by TEXT lyricist TFLT file_type TFT file_type TIM time TIME time TIPL involved_people_list TIT1 content_group_description TIT2 title TIT3 subtitle TKE initial_key TKEY initial_key TLA language TLAN language TLE length TLEN length TMCL musician_credits_list TMED media_type TMOO mood TMT media_type TOA original_artist TOAL original_album TOF original_filename TOFN original_filename TOL original_lyricist TOLY original_lyricist TOPE original_artist TOR original_year TORY original_year TOT original_album TOWN file_owner TP1 artist TP2 band TP3 conductor TP4 remixer TPA part_of_a_set TPB publisher TPE1 artist TPE2 band TPE3 conductor TPE4 remixer TPOS part_of_a_set TPRO produced_notice TPUB publisher TRC isrc TRCK track_number TRD recording_dates TRDA recording_dates TRK track_number TRSN internet_radio_station_name TRSO internet_radio_station_owner TS2 album_artist_sort_order TSA album_sort_order TSC composer_sort_order TSI size TSIZ size TSO2 album_artist_sort_order TSOA album_sort_order TSOC composer_sort_order TSOP performer_sort_order TSOT title_sort_order TSP performer_sort_order TSRC isrc TSS encoder_settings TSSE encoder_settings TSST set_subtitle TST title_sort_order TT1 description TT2 title TT3 subtitle TXT lyricist TXX text TXXX text TYE year TYER year UFI unique_file_identifier UFID unique_file_identifier ULT unsychronised_lyric USER terms_of_use USLT unsynchronised_lyric WAF url_file WAR url_artist WAS url_source WCM commercial_information WCOM commercial_information WCOP copyright WCP copyright WOAF url_file WOAR url_artist WOAS url_source WORS url_station WPAY url_payment WPB url_publisher WPUB url_publisher WXX url_user WXXX url_user TFEA featured_artist TSTU recording_studio rgad replay_gain_adjustment */ return getid3_lib::EmbeddedLookup($framename, $begin, __LINE__, __FILE__, 'id3v2-framename_short'); } function TextEncodingTerminatorLookup($encoding) { // http://www.id3.org/id3v2.4.0-structure.txt // Frames that allow different types of text encoding contains a text encoding description byte. Possible encodings: // $00 ISO-8859-1. Terminated with $00. // $01 UTF-16 encoded Unicode with BOM. All strings in the same frame SHALL have the same byteorder. Terminated with $00 00. // $02 UTF-16BE encoded Unicode without BOM. Terminated with $00 00. // $03 UTF-8 encoded Unicode. Terminated with $00. static $TextEncodingTerminatorLookup = array(0=>"\x00", 1=>"\x00\x00", 2=>"\x00\x00", 3=>"\x00", 255=>"\x00\x00"); return @$TextEncodingTerminatorLookup[$encoding]; } function TextEncodingNameLookup($encoding) { // http://www.id3.org/id3v2.4.0-structure.txt static $TextEncodingNameLookup = array(0=>'ISO-8859-1', 1=>'UTF-16', 2=>'UTF-16BE', 3=>'UTF-8', 255=>'UTF-16BE'); return (isset($TextEncodingNameLookup[$encoding]) ? $TextEncodingNameLookup[$encoding] : 'ISO-8859-1'); } function IsValidID3v2FrameName($framename, $id3v2majorversion) { switch ($id3v2majorversion) { case 2: return preg_match('/[A-Z][A-Z0-9]{2}/i', $framename); break; case 3: case 4: return preg_match('/[A-Z][A-Z0-9]{3}/i', $framename); break; } return false; } function IsANumber($numberstring, $allowdecimal=false, $allownegative=false) { for ($i = 0; $i < strlen($numberstring); $i++) { if ((chr($numberstring{$i}) < chr('0')) || (chr($numberstring{$i}) > chr('9'))) { if (($numberstring{$i} == '.') && $allowdecimal) { // allowed } elseif (($numberstring{$i} == '-') && $allownegative && ($i == 0)) { // allowed } else { return false; } } } return true; } function IsValidDateStampString($datestamp) { if (strlen($datestamp) != 8) { return false; } if (!$this->IsANumber($datestamp, false)) { return false; } $year = substr($datestamp, 0, 4); $month = substr($datestamp, 4, 2); $day = substr($datestamp, 6, 2); if (($year == 0) || ($month == 0) || ($day == 0)) { return false; } if ($month > 12) { return false; } if ($day > 31) { return false; } if (($day > 30) && (($month == 4) || ($month == 6) || ($month == 9) || ($month == 11))) { return false; } if (($day > 29) && ($month == 2)) { return false; } return true; } function ID3v2HeaderLength($majorversion) { return (($majorversion == 2) ? 6 : 10); } } ?>
stormeus/Kusaba-Z
lib/getid3/module.tag.id3v2.php
PHP
gpl-2.0
123,419
using System; using Server; using Server.Engines.MLQuests; using Server.Mobiles; using Server.Network; namespace Server.Engines.MLQuests.Items { public class BedlamTeleporter : Item { public override int LabelNumber { get { return 1074161; } } // Access to Bedlam by invitation only private static readonly Point3D PointDest = new Point3D( 120, 1682, 0 ); private static readonly Map MapDest = Map.Malas; public BedlamTeleporter() : base( 0x124D ) { Movable = false; } public override void OnDoubleClick( Mobile from ) { if ( !from.InRange( GetWorldLocation(), 2 ) ) { from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that. return; } MLQuestContext context; if ( from is PlayerMobile && ( context = MLQuestSystem.GetContext( (PlayerMobile)from ) ) != null && context.BedlamAccess ) { BaseCreature.TeleportPets( from, PointDest, MapDest ); from.MoveToWorld( PointDest, MapDest ); } else { from.SendLocalizedMessage( 1074276 ); // You press and push on the iron maiden, but nothing happens. } } public BedlamTeleporter( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
nmcgill/UOReturns
Scripts/Engines/MLQuests/Items/BedlamTeleporter.cs
C#
gpl-2.0
1,458
/* libFLAC - Free Lossless Audio Codec library * Copyright (C) 2004-2009 Josh Coalson * Copyright (C) 2011-2013 Xiph.Org Foundation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Xiph.org Foundation 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 FOUNDATION OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FLAC__PRIVATE__FLOAT_H #define FLAC__PRIVATE__FLOAT_H #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "../../../ordinals.h" /* * These typedefs make it easier to ensure that integer versions of * the library really only contain integer operations. All the code * in libFLAC should use FLAC__float and FLAC__double in place of * float and double, and be protected by checks of the macro * FLAC__INTEGER_ONLY_LIBRARY. * * FLAC__real is the basic floating point type used in LPC analysis. */ #ifndef FLAC__INTEGER_ONLY_LIBRARY typedef double FLAC__double; typedef float FLAC__float; /* * WATCHOUT: changing FLAC__real will change the signatures of many * functions that have assembly language equivalents and break them. */ typedef float FLAC__real; #else /* * The convention for FLAC__fixedpoint is to use the upper 16 bits * for the integer part and lower 16 bits for the fractional part. */ typedef FLAC__int32 FLAC__fixedpoint; extern const FLAC__fixedpoint FLAC__FP_ZERO; extern const FLAC__fixedpoint FLAC__FP_ONE_HALF; extern const FLAC__fixedpoint FLAC__FP_ONE; extern const FLAC__fixedpoint FLAC__FP_LN2; extern const FLAC__fixedpoint FLAC__FP_E; #define FLAC__fixedpoint_trunc(x) ((x)>>16) #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) ) #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) ) /* * FLAC__fixedpoint_log2() * -------------------------------------------------------------------- * Returns the base-2 logarithm of the fixed-point number 'x' using an * algorithm by Knuth for x >= 1.0 * * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must * be < 32 and evenly divisible by 4 (0 is OK but not very precise). * * 'precision' roughly limits the number of iterations that are done; * use (unsigned)(-1) for maximum precision. * * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this * function will punt and return 0. * * The return value will also have 'fracbits' fractional bits. */ FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision); #endif #endif
aneeshvartakavi/VSTPlugins
stereoEnhancer/JuceLibraryCode/modules/juce_audio_formats/codecs/flac/libFLAC/include/private/float.h
C
gpl-2.0
3,853
/* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 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. * * MZmine 2 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 * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin * St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.visualization.peaklisttable; import java.util.Arrays; import net.sf.mzmine.parameters.parametertypes.MultiChoiceParameter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class ColumnSettingParameter<ValueType> extends MultiChoiceParameter<ValueType> { private int columnWidths[]; public ColumnSettingParameter(String name, String description, ValueType choices[]) { super(name, description, choices, choices, 0); columnWidths = new int[choices.length]; Arrays.fill(columnWidths, 100); } public int getColumnWidth(int index) { return columnWidths[index]; } public void setColumnWidth(int index, int width) { columnWidths[index] = width; } @Override public ColumnSettingParameter<ValueType> cloneParameter() { ColumnSettingParameter<ValueType> copy = new ColumnSettingParameter<ValueType>( getName(), getDescription(), getChoices()); copy.setValue(getValue()); copy.columnWidths = columnWidths.clone(); return copy; } @Override public void loadValueFromXML(Element xmlElement) { super.loadValueFromXML(xmlElement); // If loading of the parameters caused all columns to be hidden, ignore // the loaded value and set all to visible ValueType newValues[] = getValue(); if (newValues.length == 0) setValue(getChoices()); NodeList items = xmlElement.getElementsByTagName("widths"); if (items.getLength() != 1) return; String widthsString = items.item(0).getTextContent(); String widthsArray[] = widthsString.split(":"); if (widthsArray.length != getChoices().length) return; int newColumnWidths[] = new int[widthsArray.length]; for (int i = 0; i < newColumnWidths.length; i++) { newColumnWidths[i] = Integer.parseInt(widthsArray[i]); } columnWidths = newColumnWidths; } @Override public void saveValueToXML(Element xmlElement) { super.saveValueToXML(xmlElement); Document parentDocument = xmlElement.getOwnerDocument(); Element widthsElement = parentDocument.createElement("widths"); StringBuilder widthsString = new StringBuilder(); for (int i = 0; i < columnWidths.length; i++) { widthsString.append(String.valueOf(columnWidths[i])); if (i < columnWidths.length - 1) widthsString.append(":"); } widthsElement.setTextContent(widthsString.toString()); xmlElement.appendChild(widthsElement); } }
DrewG/mzmine2
src/main/java/net/sf/mzmine/modules/visualization/peaklisttable/ColumnSettingParameter.java
Java
gpl-2.0
3,215
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Acl * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Acl_Resource_Interface */ #require_once 'Zend/Acl/Resource/Interface.php'; /** * @category Zend * @package Zend_Acl * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Acl_Resource implements Zend_Acl_Resource_Interface { /** * Unique id of Resource * * @var string */ protected $_resourceId; /** * Sets the Resource identifier * * @param string $resourceId * @return void */ public function __construct($resourceId) { $this->_resourceId = (string) $resourceId; } /** * Defined by Zend_Acl_Resource_Interface; returns the Resource identifier * * @return string */ public function getResourceId() { return $this->_resourceId; } /** * Defined by Zend_Acl_Resource_Interface; returns the Resource identifier * Proxies to getResourceId() * * @return string */ public function __toString() { return $this->getResourceId(); } }
T0MM0R/magento
web/lib/Zend/Acl/Resource.php
PHP
gpl-2.0
1,849
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License 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., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for ASP_Process_Para * @author Adempiere (generated) * @version Release 3.8.0 - $Id$ */ public class X_ASP_Process_Para extends PO implements I_ASP_Process_Para, I_Persistent { /** * */ private static final long serialVersionUID = 20150223L; /** Standard Constructor */ public X_ASP_Process_Para (Properties ctx, int ASP_Process_Para_ID, String trxName) { super (ctx, ASP_Process_Para_ID, trxName); /** if (ASP_Process_Para_ID == 0) { setASP_Status (null); // U } */ } /** Load Constructor */ public X_ASP_Process_Para (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 4 - System */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_ASP_Process_Para[") .append(get_ID()).append("]"); return sb.toString(); } public org.compiere.model.I_AD_Process_Para getAD_Process_Para() throws RuntimeException { return (org.compiere.model.I_AD_Process_Para)MTable.get(getCtx(), org.compiere.model.I_AD_Process_Para.Table_Name) .getPO(getAD_Process_Para_ID(), get_TrxName()); } /** Set Process Parameter. @param AD_Process_Para_ID Process Parameter */ public void setAD_Process_Para_ID (int AD_Process_Para_ID) { if (AD_Process_Para_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Process_Para_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Process_Para_ID, Integer.valueOf(AD_Process_Para_ID)); } /** Get Process Parameter. @return Process Parameter */ public int getAD_Process_Para_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Para_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_ASP_Process getASP_Process() throws RuntimeException { return (org.compiere.model.I_ASP_Process)MTable.get(getCtx(), org.compiere.model.I_ASP_Process.Table_Name) .getPO(getASP_Process_ID(), get_TrxName()); } /** Set ASP Process. @param ASP_Process_ID ASP Process */ public void setASP_Process_ID (int ASP_Process_ID) { if (ASP_Process_ID < 1) set_ValueNoCheck (COLUMNNAME_ASP_Process_ID, null); else set_ValueNoCheck (COLUMNNAME_ASP_Process_ID, Integer.valueOf(ASP_Process_ID)); } /** Get ASP Process. @return ASP Process */ public int getASP_Process_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ASP_Process_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ASP Process Parameter. @param ASP_Process_Para_ID ASP Process Parameter */ public void setASP_Process_Para_ID (int ASP_Process_Para_ID) { if (ASP_Process_Para_ID < 1) set_ValueNoCheck (COLUMNNAME_ASP_Process_Para_ID, null); else set_ValueNoCheck (COLUMNNAME_ASP_Process_Para_ID, Integer.valueOf(ASP_Process_Para_ID)); } /** Get ASP Process Parameter. @return ASP Process Parameter */ public int getASP_Process_Para_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ASP_Process_Para_ID); if (ii == null) return 0; return ii.intValue(); } /** ASP_Status AD_Reference_ID=53234 */ public static final int ASP_STATUS_AD_Reference_ID=53234; /** Hide = H */ public static final String ASP_STATUS_Hide = "H"; /** Show = S */ public static final String ASP_STATUS_Show = "S"; /** Undefined = U */ public static final String ASP_STATUS_Undefined = "U"; /** Set ASP Status. @param ASP_Status ASP Status */ public void setASP_Status (String ASP_Status) { set_Value (COLUMNNAME_ASP_Status, ASP_Status); } /** Get ASP Status. @return ASP Status */ public String getASP_Status () { return (String)get_Value(COLUMNNAME_ASP_Status); } }
pplatek/adempiere
base/src/org/compiere/model/X_ASP_Process_Para.java
Java
gpl-2.0
5,371
<li class="dropdown messages-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-tasks"></i> <span class="label label-danger">#_count_#</span> </a> <ul class="dropdown-menu"> <li class="header">#_header_#</li> <li> <!-- inner menu: contains the actual data --> <ul class="menu"> #_notifications_# </ul> </li> <li class="footer"> <!-- <a href="#">See All Messages</a> --> </li> </ul> </li>
jpbalderas17/hris
templates/notifications/notifications.html
HTML
gpl-2.0
512
/* vim: set sts=4 sw=4 cindent nowrap: This modeline was added by Daniel Mentz */ /* * IPFIX Concentrator Module Library * Copyright (C) 2004 Christoph Sommer <http://www.deltadevelopment.de/users/christoph/ipfix/> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef _IPFIX_SSL_CTX_WRAPPER_H_ #define _IPFIX_SSL_CTX_WRAPPER_H_ #ifdef SUPPORT_DTLS #include <string> #include <openssl/ssl.h> #ifndef HEADER_DH_H #include <openssl/dh.h> #endif class SSL_CTX_wrapper { public: SSL_CTX_wrapper( const std::string &certificateChainFile, const std::string &privateKeyFile, const std::string &caFile, const std::string &caPath, bool requirePeerAuthentication ); ~SSL_CTX_wrapper(); SSL *SSL_new(); void SSL_free(SSL *ssl); bool get_verify_peers(); private: SSL_CTX *ctx; bool verify_peers; /* Do we authenticate our peer by verifying its certificate? */ static DH *get_dh2048(); void setDHParams(); bool loadVerifyLocations( const std::string &caFile, const std::string &caPath ); bool loadCert( const std::string &certificateChainFile, const std::string &privateKeyFile ); void setCipherList(); }; #endif // SUPPORT_DTLS #endif
tumi8/vermont
src/common/openssl/SSLCTXWrapper.hpp
C++
gpl-2.0
1,895
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <base href="../../" /> <script src="list.js"></script> <script src="page.js"></script> <link type="text/css" rel="stylesheet" href="page.css" /> </head> <body> [page:Texture] &rarr; <h1>[name]</h1> <div class="desc">Creates a texture directly from raw data, width and height.</div> <h2>Constructor</h2> <h3>[name]( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy )</h3> <div> The data argument must be an ArrayBuffer or a typed array view. Further parameters correspond to the properties inherited from [page:Texture], where both magFilter and minFilter default to THREE.NearestFilter. The properties flipY and generateMipmaps are intially set to false. </div> <div> The interpretation of the data depends on type and format: If the type is THREE.UnsignedByteType, a Uint8Array will be useful for addressing the texel data. If the format is THREE.RGBAFormat, data needs four values for one texel; Red, Green, Blue and Alpha (typically the opacity). Similarly, THREE.RGBFormat specifies a format where only three values are used for each texel.<br /> For the packed types, THREE.UnsignedShort4444Type, THREE.UnsignedShort5551Type or THREE.UnsignedShort565Type, all color components of one texel can be addressed as bitfields within an integer element of a Uint16Array.<br /> In order to use the types THREE.FloatType and THREE.HalfFloatType, the WebGL implementation must support the respective extensions OES_texture_float and OES_texture_half_float. In order to use THREE.LinearFilter for component-wise, bilinear interpolation of the texels based on these types, the WebGL extensions OES_texture_float_linear or OES_texture_half_float_linear must also be present. </div> <h2>Properties</h2> <h3>[property:Image image]</h3> <div> Overridden with a record type holding data, width and height. </div> <h2>Methods</h2> <h2>Source</h2> [link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js] </body> </html>
ChainedLupine/ludum-dare-24-jam-entry
web/three.js/docs/api/textures/DataTexture.html
HTML
gpl-2.0
2,121
/* * Copyright (c) 2016 Vittorio Giovara <vittorio.giovara@gmail.com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Spherical video */ #ifndef AVUTIL_SPHERICAL_H #define AVUTIL_SPHERICAL_H #include <stddef.h> #include <stdint.h> /** * @addtogroup lavu_video * @{ * * @defgroup lavu_video_spherical Spherical video mapping * @{ */ /** * @addtogroup lavu_video_spherical * A spherical video file contains surfaces that need to be mapped onto a * sphere. Depending on how the frame was converted, a different distortion * transformation or surface recomposition function needs to be applied before * the video should be mapped and displayed. */ /** * Projection of the video surface(s) on a sphere. */ enum AVSphericalProjection { /** * Video represents a sphere mapped on a flat surface using * equirectangular projection. */ AV_SPHERICAL_EQUIRECTANGULAR, /** * Video frame is split into 6 faces of a cube, and arranged on a * 3x2 layout. Faces are oriented upwards for the front, left, right, * and back faces. The up face is oriented so the top of the face is * forwards and the down face is oriented so the top of the face is * to the back. */ AV_SPHERICAL_CUBEMAP, }; /** * This structure describes how to handle spherical videos, outlining * information about projection, initial layout, and any other view modifier. * * @note The struct must be allocated with av_spherical_alloc() and * its size is not a part of the public ABI. */ typedef struct AVSphericalMapping { /** * Projection type. */ enum AVSphericalProjection projection; /** * @name Initial orientation * @{ * There fields describe additional rotations applied to the sphere after * the video frame is mapped onto it. The sphere is rotated around the * viewer, who remains stationary. The order of transformation is always * yaw, followed by pitch, and finally by roll. * * The coordinate system matches the one defined in OpenGL, where the * forward vector (z) is coming out of screen, and it is equivalent to * a rotation matrix of R = r_y(yaw) * r_x(pitch) * r_z(roll). * * A positive yaw rotates the portion of the sphere in front of the viewer * toward their right. A positive pitch rotates the portion of the sphere * in front of the viewer upwards. A positive roll tilts the portion of * the sphere in front of the viewer to the viewer's right. * * These values are exported as 16.16 fixed point. * * See this equirectangular projection as example: * * @code{.unparsed} * Yaw * -180 0 180 * 90 +-------------+-------------+ 180 * | | | up * P | | | y| forward * i | ^ | | /z * t 0 +-------------X-------------+ 0 Roll | / * c | | | | / * h | | | 0|/_____right * | | | x * -90 +-------------+-------------+ -180 * * X - the default camera center * ^ - the default up vector * @endcode */ int32_t yaw; ///< Rotation around the up vector [-180, 180]. int32_t pitch; ///< Rotation around the right vector [-90, 90]. int32_t roll; ///< Rotation around the forward vector [-180, 180]. /** * @} */ } AVSphericalMapping; /** * Allocate a AVSphericalVideo structure and initialize its fields to default * values. * * @return the newly allocated struct or NULL on failure */ AVSphericalMapping *av_spherical_alloc(size_t *size); /** * @} * @} */ #endif /* AVUTIL_SPHERICAL_H */
ztwireless/obs-studio
win_deps_vs2015/win64/include/libavutil/spherical.h
C
gpl-2.0
4,654
<?php $locale['name'] = 'French'; $locale['native'] = 'le français'; // You can write native name of language here $locale['xml_lang'] = 'fr'; $locale['lang'] = 'fr'; $locale['charset'] = 'utf-8'; $locale['locale'] = 'fr_FR.UTF-8'; // You can enumerate different possible locale names separated by comma $locale['timezone'] = 'Europe/Paris'; // Default timezone. See http://php.net/manual/en/timezones.php // EOF
ieasyweb/altocms
engine/libs/UserLocale/i18n/fr.php
PHP
gpl-2.0
448
/* This file is part of Cyclos (www.cyclos.org). A project of the Social Trade Organisation (www.socialtrade.org). Cyclos 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. Cyclos 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 Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package nl.strohalm.cyclos.dao.access; import java.util.HashMap; import java.util.List; import java.util.Map; import nl.strohalm.cyclos.dao.BaseDAOImpl; import nl.strohalm.cyclos.entities.access.PasswordHistoryLog; import nl.strohalm.cyclos.entities.access.PasswordHistoryLog.PasswordType; import nl.strohalm.cyclos.entities.access.User; import nl.strohalm.cyclos.utils.hibernate.HibernateHelper; import nl.strohalm.cyclos.utils.query.PageHelper; import nl.strohalm.cyclos.utils.query.PageParameters; import nl.strohalm.cyclos.utils.query.QueryParameters.ResultType; import org.apache.commons.lang.StringUtils; public class PasswordHistoryLogDAOImpl extends BaseDAOImpl<PasswordHistoryLog> implements PasswordHistoryLogDAO { public PasswordHistoryLogDAOImpl() { super(PasswordHistoryLog.class); } public boolean wasAlreadyUsed(final User user, final PasswordType type, final String password) { final Map<String, Object> namedParameters = new HashMap<String, Object>(); final StringBuilder hql = HibernateHelper.getInitialQuery(getEntityType(), "h"); HibernateHelper.addParameterToQuery(hql, namedParameters, "h.user", user); HibernateHelper.addParameterToQuery(hql, namedParameters, "h.type", type); HibernateHelper.addParameterToQuery(hql, namedParameters, "upper(h.password)", StringUtils.trimToEmpty(password).toUpperCase()); final List<Object> list = list(ResultType.PAGE, hql.toString(), namedParameters, PageParameters.count()); return PageHelper.getTotalCount(list) > 0; } }
robertoandrade/cyclos
src/nl/strohalm/cyclos/dao/access/PasswordHistoryLogDAOImpl.java
Java
gpl-2.0
2,401
/* * Copyright (C) 2012 Fusion-io All rights reserved. * Copyright (C) 2012 Intel Corp. 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 v2 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., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/sched.h> #include <linux/wait.h> #include <linux/bio.h> #include <linux/slab.h> #include <linux/buffer_head.h> #include <linux/blkdev.h> #include <linux/random.h> #include <linux/iocontext.h> #include <linux/capability.h> #include <linux/ratelimit.h> #include <linux/kthread.h> #include <linux/raid/pq.h> #include <linux/hash.h> #include <linux/list_sort.h> #include <linux/raid/xor.h> #include <linux/mm.h> #include <asm/div64.h> #include "ctree.h" #include "extent_map.h" #include "disk-io.h" #include "transaction.h" #include "print-tree.h" #include "volumes.h" #include "raid56.h" #include "async-thread.h" #include "check-integrity.h" #include "rcu-string.h" /* set when additional merges to this rbio are not allowed */ #define RBIO_RMW_LOCKED_BIT 1 /* * set when this rbio is sitting in the hash, but it is just a cache * of past RMW */ #define RBIO_CACHE_BIT 2 /* * set when it is safe to trust the stripe_pages for caching */ #define RBIO_CACHE_READY_BIT 3 #define RBIO_CACHE_SIZE 1024 enum btrfs_rbio_ops { BTRFS_RBIO_WRITE, BTRFS_RBIO_READ_REBUILD, BTRFS_RBIO_PARITY_SCRUB, BTRFS_RBIO_REBUILD_MISSING, }; struct btrfs_raid_bio { struct btrfs_fs_info *fs_info; struct btrfs_bio *bbio; /* while we're doing rmw on a stripe * we put it into a hash table so we can * lock the stripe and merge more rbios * into it. */ struct list_head hash_list; /* * LRU list for the stripe cache */ struct list_head stripe_cache; /* * for scheduling work in the helper threads */ struct btrfs_work work; /* * bio list and bio_list_lock are used * to add more bios into the stripe * in hopes of avoiding the full rmw */ struct bio_list bio_list; spinlock_t bio_list_lock; /* also protected by the bio_list_lock, the * plug list is used by the plugging code * to collect partial bios while plugged. The * stripe locking code also uses it to hand off * the stripe lock to the next pending IO */ struct list_head plug_list; /* * flags that tell us if it is safe to * merge with this bio */ unsigned long flags; /* size of each individual stripe on disk */ int stripe_len; /* number of data stripes (no p/q) */ int nr_data; int real_stripes; int stripe_npages; /* * set if we're doing a parity rebuild * for a read from higher up, which is handled * differently from a parity rebuild as part of * rmw */ enum btrfs_rbio_ops operation; /* first bad stripe */ int faila; /* second bad stripe (for raid6 use) */ int failb; int scrubp; /* * number of pages needed to represent the full * stripe */ int nr_pages; /* * size of all the bios in the bio_list. This * helps us decide if the rbio maps to a full * stripe or not */ int bio_list_bytes; int generic_bio_cnt; refcount_t refs; atomic_t stripes_pending; atomic_t error; /* * these are two arrays of pointers. We allocate the * rbio big enough to hold them both and setup their * locations when the rbio is allocated */ /* pointers to pages that we allocated for * reading/writing stripes directly from the disk (including P/Q) */ struct page **stripe_pages; /* * pointers to the pages in the bio_list. Stored * here for faster lookup */ struct page **bio_pages; /* * bitmap to record which horizontal stripe has data */ unsigned long *dbitmap; }; static int __raid56_parity_recover(struct btrfs_raid_bio *rbio); static noinline void finish_rmw(struct btrfs_raid_bio *rbio); static void rmw_work(struct btrfs_work *work); static void read_rebuild_work(struct btrfs_work *work); static void async_rmw_stripe(struct btrfs_raid_bio *rbio); static void async_read_rebuild(struct btrfs_raid_bio *rbio); static int fail_bio_stripe(struct btrfs_raid_bio *rbio, struct bio *bio); static int fail_rbio_index(struct btrfs_raid_bio *rbio, int failed); static void __free_raid_bio(struct btrfs_raid_bio *rbio); static void index_rbio_pages(struct btrfs_raid_bio *rbio); static int alloc_rbio_pages(struct btrfs_raid_bio *rbio); static noinline void finish_parity_scrub(struct btrfs_raid_bio *rbio, int need_check); static void async_scrub_parity(struct btrfs_raid_bio *rbio); /* * the stripe hash table is used for locking, and to collect * bios in hopes of making a full stripe */ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info) { struct btrfs_stripe_hash_table *table; struct btrfs_stripe_hash_table *x; struct btrfs_stripe_hash *cur; struct btrfs_stripe_hash *h; int num_entries = 1 << BTRFS_STRIPE_HASH_TABLE_BITS; int i; int table_size; if (info->stripe_hash_table) return 0; /* * The table is large, starting with order 4 and can go as high as * order 7 in case lock debugging is turned on. * * Try harder to allocate and fallback to vmalloc to lower the chance * of a failing mount. */ table_size = sizeof(*table) + sizeof(*h) * num_entries; table = kvzalloc(table_size, GFP_KERNEL); if (!table) return -ENOMEM; spin_lock_init(&table->cache_lock); INIT_LIST_HEAD(&table->stripe_cache); h = table->table; for (i = 0; i < num_entries; i++) { cur = h + i; INIT_LIST_HEAD(&cur->hash_list); spin_lock_init(&cur->lock); init_waitqueue_head(&cur->wait); } x = cmpxchg(&info->stripe_hash_table, NULL, table); if (x) kvfree(x); return 0; } /* * caching an rbio means to copy anything from the * bio_pages array into the stripe_pages array. We * use the page uptodate bit in the stripe cache array * to indicate if it has valid data * * once the caching is done, we set the cache ready * bit. */ static void cache_rbio_pages(struct btrfs_raid_bio *rbio) { int i; char *s; char *d; int ret; ret = alloc_rbio_pages(rbio); if (ret) return; for (i = 0; i < rbio->nr_pages; i++) { if (!rbio->bio_pages[i]) continue; s = kmap(rbio->bio_pages[i]); d = kmap(rbio->stripe_pages[i]); memcpy(d, s, PAGE_SIZE); kunmap(rbio->bio_pages[i]); kunmap(rbio->stripe_pages[i]); SetPageUptodate(rbio->stripe_pages[i]); } set_bit(RBIO_CACHE_READY_BIT, &rbio->flags); } /* * we hash on the first logical address of the stripe */ static int rbio_bucket(struct btrfs_raid_bio *rbio) { u64 num = rbio->bbio->raid_map[0]; /* * we shift down quite a bit. We're using byte * addressing, and most of the lower bits are zeros. * This tends to upset hash_64, and it consistently * returns just one or two different values. * * shifting off the lower bits fixes things. */ return hash_64(num >> 16, BTRFS_STRIPE_HASH_TABLE_BITS); } /* * stealing an rbio means taking all the uptodate pages from the stripe * array in the source rbio and putting them into the destination rbio */ static void steal_rbio(struct btrfs_raid_bio *src, struct btrfs_raid_bio *dest) { int i; struct page *s; struct page *d; if (!test_bit(RBIO_CACHE_READY_BIT, &src->flags)) return; for (i = 0; i < dest->nr_pages; i++) { s = src->stripe_pages[i]; if (!s || !PageUptodate(s)) { continue; } d = dest->stripe_pages[i]; if (d) __free_page(d); dest->stripe_pages[i] = s; src->stripe_pages[i] = NULL; } } /* * merging means we take the bio_list from the victim and * splice it into the destination. The victim should * be discarded afterwards. * * must be called with dest->rbio_list_lock held */ static void merge_rbio(struct btrfs_raid_bio *dest, struct btrfs_raid_bio *victim) { bio_list_merge(&dest->bio_list, &victim->bio_list); dest->bio_list_bytes += victim->bio_list_bytes; dest->generic_bio_cnt += victim->generic_bio_cnt; bio_list_init(&victim->bio_list); } /* * used to prune items that are in the cache. The caller * must hold the hash table lock. */ static void __remove_rbio_from_cache(struct btrfs_raid_bio *rbio) { int bucket = rbio_bucket(rbio); struct btrfs_stripe_hash_table *table; struct btrfs_stripe_hash *h; int freeit = 0; /* * check the bit again under the hash table lock. */ if (!test_bit(RBIO_CACHE_BIT, &rbio->flags)) return; table = rbio->fs_info->stripe_hash_table; h = table->table + bucket; /* hold the lock for the bucket because we may be * removing it from the hash table */ spin_lock(&h->lock); /* * hold the lock for the bio list because we need * to make sure the bio list is empty */ spin_lock(&rbio->bio_list_lock); if (test_and_clear_bit(RBIO_CACHE_BIT, &rbio->flags)) { list_del_init(&rbio->stripe_cache); table->cache_size -= 1; freeit = 1; /* if the bio list isn't empty, this rbio is * still involved in an IO. We take it out * of the cache list, and drop the ref that * was held for the list. * * If the bio_list was empty, we also remove * the rbio from the hash_table, and drop * the corresponding ref */ if (bio_list_empty(&rbio->bio_list)) { if (!list_empty(&rbio->hash_list)) { list_del_init(&rbio->hash_list); refcount_dec(&rbio->refs); BUG_ON(!list_empty(&rbio->plug_list)); } } } spin_unlock(&rbio->bio_list_lock); spin_unlock(&h->lock); if (freeit) __free_raid_bio(rbio); } /* * prune a given rbio from the cache */ static void remove_rbio_from_cache(struct btrfs_raid_bio *rbio) { struct btrfs_stripe_hash_table *table; unsigned long flags; if (!test_bit(RBIO_CACHE_BIT, &rbio->flags)) return; table = rbio->fs_info->stripe_hash_table; spin_lock_irqsave(&table->cache_lock, flags); __remove_rbio_from_cache(rbio); spin_unlock_irqrestore(&table->cache_lock, flags); } /* * remove everything in the cache */ static void btrfs_clear_rbio_cache(struct btrfs_fs_info *info) { struct btrfs_stripe_hash_table *table; unsigned long flags; struct btrfs_raid_bio *rbio; table = info->stripe_hash_table; spin_lock_irqsave(&table->cache_lock, flags); while (!list_empty(&table->stripe_cache)) { rbio = list_entry(table->stripe_cache.next, struct btrfs_raid_bio, stripe_cache); __remove_rbio_from_cache(rbio); } spin_unlock_irqrestore(&table->cache_lock, flags); } /* * remove all cached entries and free the hash table * used by unmount */ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info) { if (!info->stripe_hash_table) return; btrfs_clear_rbio_cache(info); kvfree(info->stripe_hash_table); info->stripe_hash_table = NULL; } /* * insert an rbio into the stripe cache. It * must have already been prepared by calling * cache_rbio_pages * * If this rbio was already cached, it gets * moved to the front of the lru. * * If the size of the rbio cache is too big, we * prune an item. */ static void cache_rbio(struct btrfs_raid_bio *rbio) { struct btrfs_stripe_hash_table *table; unsigned long flags; if (!test_bit(RBIO_CACHE_READY_BIT, &rbio->flags)) return; table = rbio->fs_info->stripe_hash_table; spin_lock_irqsave(&table->cache_lock, flags); spin_lock(&rbio->bio_list_lock); /* bump our ref if we were not in the list before */ if (!test_and_set_bit(RBIO_CACHE_BIT, &rbio->flags)) refcount_inc(&rbio->refs); if (!list_empty(&rbio->stripe_cache)){ list_move(&rbio->stripe_cache, &table->stripe_cache); } else { list_add(&rbio->stripe_cache, &table->stripe_cache); table->cache_size += 1; } spin_unlock(&rbio->bio_list_lock); if (table->cache_size > RBIO_CACHE_SIZE) { struct btrfs_raid_bio *found; found = list_entry(table->stripe_cache.prev, struct btrfs_raid_bio, stripe_cache); if (found != rbio) __remove_rbio_from_cache(found); } spin_unlock_irqrestore(&table->cache_lock, flags); } /* * helper function to run the xor_blocks api. It is only * able to do MAX_XOR_BLOCKS at a time, so we need to * loop through. */ static void run_xor(void **pages, int src_cnt, ssize_t len) { int src_off = 0; int xor_src_cnt = 0; void *dest = pages[src_cnt]; while(src_cnt > 0) { xor_src_cnt = min(src_cnt, MAX_XOR_BLOCKS); xor_blocks(xor_src_cnt, len, dest, pages + src_off); src_cnt -= xor_src_cnt; src_off += xor_src_cnt; } } /* * returns true if the bio list inside this rbio * covers an entire stripe (no rmw required). * Must be called with the bio list lock held, or * at a time when you know it is impossible to add * new bios into the list */ static int __rbio_is_full(struct btrfs_raid_bio *rbio) { unsigned long size = rbio->bio_list_bytes; int ret = 1; if (size != rbio->nr_data * rbio->stripe_len) ret = 0; BUG_ON(size > rbio->nr_data * rbio->stripe_len); return ret; } static int rbio_is_full(struct btrfs_raid_bio *rbio) { unsigned long flags; int ret; spin_lock_irqsave(&rbio->bio_list_lock, flags); ret = __rbio_is_full(rbio); spin_unlock_irqrestore(&rbio->bio_list_lock, flags); return ret; } /* * returns 1 if it is safe to merge two rbios together. * The merging is safe if the two rbios correspond to * the same stripe and if they are both going in the same * direction (read vs write), and if neither one is * locked for final IO * * The caller is responsible for locking such that * rmw_locked is safe to test */ static int rbio_can_merge(struct btrfs_raid_bio *last, struct btrfs_raid_bio *cur) { if (test_bit(RBIO_RMW_LOCKED_BIT, &last->flags) || test_bit(RBIO_RMW_LOCKED_BIT, &cur->flags)) return 0; /* * we can't merge with cached rbios, since the * idea is that when we merge the destination * rbio is going to run our IO for us. We can * steal from cached rbios though, other functions * handle that. */ if (test_bit(RBIO_CACHE_BIT, &last->flags) || test_bit(RBIO_CACHE_BIT, &cur->flags)) return 0; if (last->bbio->raid_map[0] != cur->bbio->raid_map[0]) return 0; /* we can't merge with different operations */ if (last->operation != cur->operation) return 0; /* * We've need read the full stripe from the drive. * check and repair the parity and write the new results. * * We're not allowed to add any new bios to the * bio list here, anyone else that wants to * change this stripe needs to do their own rmw. */ if (last->operation == BTRFS_RBIO_PARITY_SCRUB || cur->operation == BTRFS_RBIO_PARITY_SCRUB) return 0; if (last->operation == BTRFS_RBIO_REBUILD_MISSING || cur->operation == BTRFS_RBIO_REBUILD_MISSING) return 0; return 1; } static int rbio_stripe_page_index(struct btrfs_raid_bio *rbio, int stripe, int index) { return stripe * rbio->stripe_npages + index; } /* * these are just the pages from the rbio array, not from anything * the FS sent down to us */ static struct page *rbio_stripe_page(struct btrfs_raid_bio *rbio, int stripe, int index) { return rbio->stripe_pages[rbio_stripe_page_index(rbio, stripe, index)]; } /* * helper to index into the pstripe */ static struct page *rbio_pstripe_page(struct btrfs_raid_bio *rbio, int index) { return rbio_stripe_page(rbio, rbio->nr_data, index); } /* * helper to index into the qstripe, returns null * if there is no qstripe */ static struct page *rbio_qstripe_page(struct btrfs_raid_bio *rbio, int index) { if (rbio->nr_data + 1 == rbio->real_stripes) return NULL; return rbio_stripe_page(rbio, rbio->nr_data + 1, index); } /* * The first stripe in the table for a logical address * has the lock. rbios are added in one of three ways: * * 1) Nobody has the stripe locked yet. The rbio is given * the lock and 0 is returned. The caller must start the IO * themselves. * * 2) Someone has the stripe locked, but we're able to merge * with the lock owner. The rbio is freed and the IO will * start automatically along with the existing rbio. 1 is returned. * * 3) Someone has the stripe locked, but we're not able to merge. * The rbio is added to the lock owner's plug list, or merged into * an rbio already on the plug list. When the lock owner unlocks, * the next rbio on the list is run and the IO is started automatically. * 1 is returned * * If we return 0, the caller still owns the rbio and must continue with * IO submission. If we return 1, the caller must assume the rbio has * already been freed. */ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio) { int bucket = rbio_bucket(rbio); struct btrfs_stripe_hash *h = rbio->fs_info->stripe_hash_table->table + bucket; struct btrfs_raid_bio *cur; struct btrfs_raid_bio *pending; unsigned long flags; DEFINE_WAIT(wait); struct btrfs_raid_bio *freeit = NULL; struct btrfs_raid_bio *cache_drop = NULL; int ret = 0; spin_lock_irqsave(&h->lock, flags); list_for_each_entry(cur, &h->hash_list, hash_list) { if (cur->bbio->raid_map[0] == rbio->bbio->raid_map[0]) { spin_lock(&cur->bio_list_lock); /* can we steal this cached rbio's pages? */ if (bio_list_empty(&cur->bio_list) && list_empty(&cur->plug_list) && test_bit(RBIO_CACHE_BIT, &cur->flags) && !test_bit(RBIO_RMW_LOCKED_BIT, &cur->flags)) { list_del_init(&cur->hash_list); refcount_dec(&cur->refs); steal_rbio(cur, rbio); cache_drop = cur; spin_unlock(&cur->bio_list_lock); goto lockit; } /* can we merge into the lock owner? */ if (rbio_can_merge(cur, rbio)) { merge_rbio(cur, rbio); spin_unlock(&cur->bio_list_lock); freeit = rbio; ret = 1; goto out; } /* * we couldn't merge with the running * rbio, see if we can merge with the * pending ones. We don't have to * check for rmw_locked because there * is no way they are inside finish_rmw * right now */ list_for_each_entry(pending, &cur->plug_list, plug_list) { if (rbio_can_merge(pending, rbio)) { merge_rbio(pending, rbio); spin_unlock(&cur->bio_list_lock); freeit = rbio; ret = 1; goto out; } } /* no merging, put us on the tail of the plug list, * our rbio will be started with the currently * running rbio unlocks */ list_add_tail(&rbio->plug_list, &cur->plug_list); spin_unlock(&cur->bio_list_lock); ret = 1; goto out; } } lockit: refcount_inc(&rbio->refs); list_add(&rbio->hash_list, &h->hash_list); out: spin_unlock_irqrestore(&h->lock, flags); if (cache_drop) remove_rbio_from_cache(cache_drop); if (freeit) __free_raid_bio(freeit); return ret; } /* * called as rmw or parity rebuild is completed. If the plug list has more * rbios waiting for this stripe, the next one on the list will be started */ static noinline void unlock_stripe(struct btrfs_raid_bio *rbio) { int bucket; struct btrfs_stripe_hash *h; unsigned long flags; int keep_cache = 0; bucket = rbio_bucket(rbio); h = rbio->fs_info->stripe_hash_table->table + bucket; if (list_empty(&rbio->plug_list)) cache_rbio(rbio); spin_lock_irqsave(&h->lock, flags); spin_lock(&rbio->bio_list_lock); if (!list_empty(&rbio->hash_list)) { /* * if we're still cached and there is no other IO * to perform, just leave this rbio here for others * to steal from later */ if (list_empty(&rbio->plug_list) && test_bit(RBIO_CACHE_BIT, &rbio->flags)) { keep_cache = 1; clear_bit(RBIO_RMW_LOCKED_BIT, &rbio->flags); BUG_ON(!bio_list_empty(&rbio->bio_list)); goto done; } list_del_init(&rbio->hash_list); refcount_dec(&rbio->refs); /* * we use the plug list to hold all the rbios * waiting for the chance to lock this stripe. * hand the lock over to one of them. */ if (!list_empty(&rbio->plug_list)) { struct btrfs_raid_bio *next; struct list_head *head = rbio->plug_list.next; next = list_entry(head, struct btrfs_raid_bio, plug_list); list_del_init(&rbio->plug_list); list_add(&next->hash_list, &h->hash_list); refcount_inc(&next->refs); spin_unlock(&rbio->bio_list_lock); spin_unlock_irqrestore(&h->lock, flags); if (next->operation == BTRFS_RBIO_READ_REBUILD) async_read_rebuild(next); else if (next->operation == BTRFS_RBIO_REBUILD_MISSING) { steal_rbio(rbio, next); async_read_rebuild(next); } else if (next->operation == BTRFS_RBIO_WRITE) { steal_rbio(rbio, next); async_rmw_stripe(next); } else if (next->operation == BTRFS_RBIO_PARITY_SCRUB) { steal_rbio(rbio, next); async_scrub_parity(next); } goto done_nolock; /* * The barrier for this waitqueue_active is not needed, * we're protected by h->lock and can't miss a wakeup. */ } else if (waitqueue_active(&h->wait)) { spin_unlock(&rbio->bio_list_lock); spin_unlock_irqrestore(&h->lock, flags); wake_up(&h->wait); goto done_nolock; } } done: spin_unlock(&rbio->bio_list_lock); spin_unlock_irqrestore(&h->lock, flags); done_nolock: if (!keep_cache) remove_rbio_from_cache(rbio); } static void __free_raid_bio(struct btrfs_raid_bio *rbio) { int i; if (!refcount_dec_and_test(&rbio->refs)) return; WARN_ON(!list_empty(&rbio->stripe_cache)); WARN_ON(!list_empty(&rbio->hash_list)); WARN_ON(!bio_list_empty(&rbio->bio_list)); for (i = 0; i < rbio->nr_pages; i++) { if (rbio->stripe_pages[i]) { __free_page(rbio->stripe_pages[i]); rbio->stripe_pages[i] = NULL; } } btrfs_put_bbio(rbio->bbio); kfree(rbio); } static void free_raid_bio(struct btrfs_raid_bio *rbio) { unlock_stripe(rbio); __free_raid_bio(rbio); } /* * this frees the rbio and runs through all the bios in the * bio_list and calls end_io on them */ static void rbio_orig_end_io(struct btrfs_raid_bio *rbio, blk_status_t err) { struct bio *cur = bio_list_get(&rbio->bio_list); struct bio *next; if (rbio->generic_bio_cnt) btrfs_bio_counter_sub(rbio->fs_info, rbio->generic_bio_cnt); free_raid_bio(rbio); while (cur) { next = cur->bi_next; cur->bi_next = NULL; cur->bi_status = err; bio_endio(cur); cur = next; } } /* * end io function used by finish_rmw. When we finally * get here, we've written a full stripe */ static void raid_write_end_io(struct bio *bio) { struct btrfs_raid_bio *rbio = bio->bi_private; blk_status_t err = bio->bi_status; int max_errors; if (err) fail_bio_stripe(rbio, bio); bio_put(bio); if (!atomic_dec_and_test(&rbio->stripes_pending)) return; err = BLK_STS_OK; /* OK, we have read all the stripes we need to. */ max_errors = (rbio->operation == BTRFS_RBIO_PARITY_SCRUB) ? 0 : rbio->bbio->max_errors; if (atomic_read(&rbio->error) > max_errors) err = BLK_STS_IOERR; rbio_orig_end_io(rbio, err); } /* * the read/modify/write code wants to use the original bio for * any pages it included, and then use the rbio for everything * else. This function decides if a given index (stripe number) * and page number in that stripe fall inside the original bio * or the rbio. * * if you set bio_list_only, you'll get a NULL back for any ranges * that are outside the bio_list * * This doesn't take any refs on anything, you get a bare page pointer * and the caller must bump refs as required. * * You must call index_rbio_pages once before you can trust * the answers from this function. */ static struct page *page_in_rbio(struct btrfs_raid_bio *rbio, int index, int pagenr, int bio_list_only) { int chunk_page; struct page *p = NULL; chunk_page = index * (rbio->stripe_len >> PAGE_SHIFT) + pagenr; spin_lock_irq(&rbio->bio_list_lock); p = rbio->bio_pages[chunk_page]; spin_unlock_irq(&rbio->bio_list_lock); if (p || bio_list_only) return p; return rbio->stripe_pages[chunk_page]; } /* * number of pages we need for the entire stripe across all the * drives */ static unsigned long rbio_nr_pages(unsigned long stripe_len, int nr_stripes) { return DIV_ROUND_UP(stripe_len, PAGE_SIZE) * nr_stripes; } /* * allocation and initial setup for the btrfs_raid_bio. Not * this does not allocate any pages for rbio->pages. */ static struct btrfs_raid_bio *alloc_rbio(struct btrfs_fs_info *fs_info, struct btrfs_bio *bbio, u64 stripe_len) { struct btrfs_raid_bio *rbio; int nr_data = 0; int real_stripes = bbio->num_stripes - bbio->num_tgtdevs; int num_pages = rbio_nr_pages(stripe_len, real_stripes); int stripe_npages = DIV_ROUND_UP(stripe_len, PAGE_SIZE); void *p; rbio = kzalloc(sizeof(*rbio) + num_pages * sizeof(struct page *) * 2 + DIV_ROUND_UP(stripe_npages, BITS_PER_LONG) * sizeof(long), GFP_NOFS); if (!rbio) return ERR_PTR(-ENOMEM); bio_list_init(&rbio->bio_list); INIT_LIST_HEAD(&rbio->plug_list); spin_lock_init(&rbio->bio_list_lock); INIT_LIST_HEAD(&rbio->stripe_cache); INIT_LIST_HEAD(&rbio->hash_list); rbio->bbio = bbio; rbio->fs_info = fs_info; rbio->stripe_len = stripe_len; rbio->nr_pages = num_pages; rbio->real_stripes = real_stripes; rbio->stripe_npages = stripe_npages; rbio->faila = -1; rbio->failb = -1; refcount_set(&rbio->refs, 1); atomic_set(&rbio->error, 0); atomic_set(&rbio->stripes_pending, 0); /* * the stripe_pages and bio_pages array point to the extra * memory we allocated past the end of the rbio */ p = rbio + 1; rbio->stripe_pages = p; rbio->bio_pages = p + sizeof(struct page *) * num_pages; rbio->dbitmap = p + sizeof(struct page *) * num_pages * 2; if (bbio->map_type & BTRFS_BLOCK_GROUP_RAID5) nr_data = real_stripes - 1; else if (bbio->map_type & BTRFS_BLOCK_GROUP_RAID6) nr_data = real_stripes - 2; else BUG(); rbio->nr_data = nr_data; return rbio; } /* allocate pages for all the stripes in the bio, including parity */ static int alloc_rbio_pages(struct btrfs_raid_bio *rbio) { int i; struct page *page; for (i = 0; i < rbio->nr_pages; i++) { if (rbio->stripe_pages[i]) continue; page = alloc_page(GFP_NOFS | __GFP_HIGHMEM); if (!page) return -ENOMEM; rbio->stripe_pages[i] = page; } return 0; } /* only allocate pages for p/q stripes */ static int alloc_rbio_parity_pages(struct btrfs_raid_bio *rbio) { int i; struct page *page; i = rbio_stripe_page_index(rbio, rbio->nr_data, 0); for (; i < rbio->nr_pages; i++) { if (rbio->stripe_pages[i]) continue; page = alloc_page(GFP_NOFS | __GFP_HIGHMEM); if (!page) return -ENOMEM; rbio->stripe_pages[i] = page; } return 0; } /* * add a single page from a specific stripe into our list of bios for IO * this will try to merge into existing bios if possible, and returns * zero if all went well. */ static int rbio_add_io_page(struct btrfs_raid_bio *rbio, struct bio_list *bio_list, struct page *page, int stripe_nr, unsigned long page_index, unsigned long bio_max_len) { struct bio *last = bio_list->tail; u64 last_end = 0; int ret; struct bio *bio; struct btrfs_bio_stripe *stripe; u64 disk_start; stripe = &rbio->bbio->stripes[stripe_nr]; disk_start = stripe->physical + (page_index << PAGE_SHIFT); /* if the device is missing, just fail this stripe */ if (!stripe->dev->bdev) return fail_rbio_index(rbio, stripe_nr); /* see if we can add this page onto our existing bio */ if (last) { last_end = (u64)last->bi_iter.bi_sector << 9; last_end += last->bi_iter.bi_size; /* * we can't merge these if they are from different * devices or if they are not contiguous */ if (last_end == disk_start && stripe->dev->bdev && !last->bi_status && last->bi_bdev == stripe->dev->bdev) { ret = bio_add_page(last, page, PAGE_SIZE, 0); if (ret == PAGE_SIZE) return 0; } } /* put a new bio on the list */ bio = btrfs_io_bio_alloc(bio_max_len >> PAGE_SHIFT ?: 1); bio->bi_iter.bi_size = 0; bio->bi_bdev = stripe->dev->bdev; bio->bi_iter.bi_sector = disk_start >> 9; bio_add_page(bio, page, PAGE_SIZE, 0); bio_list_add(bio_list, bio); return 0; } /* * while we're doing the read/modify/write cycle, we could * have errors in reading pages off the disk. This checks * for errors and if we're not able to read the page it'll * trigger parity reconstruction. The rmw will be finished * after we've reconstructed the failed stripes */ static void validate_rbio_for_rmw(struct btrfs_raid_bio *rbio) { if (rbio->faila >= 0 || rbio->failb >= 0) { BUG_ON(rbio->faila == rbio->real_stripes - 1); __raid56_parity_recover(rbio); } else { finish_rmw(rbio); } } /* * helper function to walk our bio list and populate the bio_pages array with * the result. This seems expensive, but it is faster than constantly * searching through the bio list as we setup the IO in finish_rmw or stripe * reconstruction. * * This must be called before you trust the answers from page_in_rbio */ static void index_rbio_pages(struct btrfs_raid_bio *rbio) { struct bio *bio; u64 start; unsigned long stripe_offset; unsigned long page_index; spin_lock_irq(&rbio->bio_list_lock); bio_list_for_each(bio, &rbio->bio_list) { struct bio_vec bvec; struct bvec_iter iter; int i = 0; start = (u64)bio->bi_iter.bi_sector << 9; stripe_offset = start - rbio->bbio->raid_map[0]; page_index = stripe_offset >> PAGE_SHIFT; if (bio_flagged(bio, BIO_CLONED)) bio->bi_iter = btrfs_io_bio(bio)->iter; bio_for_each_segment(bvec, bio, iter) { rbio->bio_pages[page_index + i] = bvec.bv_page; i++; } } spin_unlock_irq(&rbio->bio_list_lock); } /* * this is called from one of two situations. We either * have a full stripe from the higher layers, or we've read all * the missing bits off disk. * * This will calculate the parity and then send down any * changed blocks. */ static noinline void finish_rmw(struct btrfs_raid_bio *rbio) { struct btrfs_bio *bbio = rbio->bbio; void *pointers[rbio->real_stripes]; int nr_data = rbio->nr_data; int stripe; int pagenr; int p_stripe = -1; int q_stripe = -1; struct bio_list bio_list; struct bio *bio; int ret; bio_list_init(&bio_list); if (rbio->real_stripes - rbio->nr_data == 1) { p_stripe = rbio->real_stripes - 1; } else if (rbio->real_stripes - rbio->nr_data == 2) { p_stripe = rbio->real_stripes - 2; q_stripe = rbio->real_stripes - 1; } else { BUG(); } /* at this point we either have a full stripe, * or we've read the full stripe from the drive. * recalculate the parity and write the new results. * * We're not allowed to add any new bios to the * bio list here, anyone else that wants to * change this stripe needs to do their own rmw. */ spin_lock_irq(&rbio->bio_list_lock); set_bit(RBIO_RMW_LOCKED_BIT, &rbio->flags); spin_unlock_irq(&rbio->bio_list_lock); atomic_set(&rbio->error, 0); /* * now that we've set rmw_locked, run through the * bio list one last time and map the page pointers * * We don't cache full rbios because we're assuming * the higher layers are unlikely to use this area of * the disk again soon. If they do use it again, * hopefully they will send another full bio. */ index_rbio_pages(rbio); if (!rbio_is_full(rbio)) cache_rbio_pages(rbio); else clear_bit(RBIO_CACHE_READY_BIT, &rbio->flags); for (pagenr = 0; pagenr < rbio->stripe_npages; pagenr++) { struct page *p; /* first collect one page from each data stripe */ for (stripe = 0; stripe < nr_data; stripe++) { p = page_in_rbio(rbio, stripe, pagenr, 0); pointers[stripe] = kmap(p); } /* then add the parity stripe */ p = rbio_pstripe_page(rbio, pagenr); SetPageUptodate(p); pointers[stripe++] = kmap(p); if (q_stripe != -1) { /* * raid6, add the qstripe and call the * library function to fill in our p/q */ p = rbio_qstripe_page(rbio, pagenr); SetPageUptodate(p); pointers[stripe++] = kmap(p); raid6_call.gen_syndrome(rbio->real_stripes, PAGE_SIZE, pointers); } else { /* raid5 */ memcpy(pointers[nr_data], pointers[0], PAGE_SIZE); run_xor(pointers + 1, nr_data - 1, PAGE_SIZE); } for (stripe = 0; stripe < rbio->real_stripes; stripe++) kunmap(page_in_rbio(rbio, stripe, pagenr, 0)); } /* * time to start writing. Make bios for everything from the * higher layers (the bio_list in our rbio) and our p/q. Ignore * everything else. */ for (stripe = 0; stripe < rbio->real_stripes; stripe++) { for (pagenr = 0; pagenr < rbio->stripe_npages; pagenr++) { struct page *page; if (stripe < rbio->nr_data) { page = page_in_rbio(rbio, stripe, pagenr, 1); if (!page) continue; } else { page = rbio_stripe_page(rbio, stripe, pagenr); } ret = rbio_add_io_page(rbio, &bio_list, page, stripe, pagenr, rbio->stripe_len); if (ret) goto cleanup; } } if (likely(!bbio->num_tgtdevs)) goto write_data; for (stripe = 0; stripe < rbio->real_stripes; stripe++) { if (!bbio->tgtdev_map[stripe]) continue; for (pagenr = 0; pagenr < rbio->stripe_npages; pagenr++) { struct page *page; if (stripe < rbio->nr_data) { page = page_in_rbio(rbio, stripe, pagenr, 1); if (!page) continue; } else { page = rbio_stripe_page(rbio, stripe, pagenr); } ret = rbio_add_io_page(rbio, &bio_list, page, rbio->bbio->tgtdev_map[stripe], pagenr, rbio->stripe_len); if (ret) goto cleanup; } } write_data: atomic_set(&rbio->stripes_pending, bio_list_size(&bio_list)); BUG_ON(atomic_read(&rbio->stripes_pending) == 0); while (1) { bio = bio_list_pop(&bio_list); if (!bio) break; bio->bi_private = rbio; bio->bi_end_io = raid_write_end_io; bio_set_op_attrs(bio, REQ_OP_WRITE, 0); submit_bio(bio); } return; cleanup: rbio_orig_end_io(rbio, BLK_STS_IOERR); } /* * helper to find the stripe number for a given bio. Used to figure out which * stripe has failed. This expects the bio to correspond to a physical disk, * so it looks up based on physical sector numbers. */ static int find_bio_stripe(struct btrfs_raid_bio *rbio, struct bio *bio) { u64 physical = bio->bi_iter.bi_sector; u64 stripe_start; int i; struct btrfs_bio_stripe *stripe; physical <<= 9; for (i = 0; i < rbio->bbio->num_stripes; i++) { stripe = &rbio->bbio->stripes[i]; stripe_start = stripe->physical; if (physical >= stripe_start && physical < stripe_start + rbio->stripe_len && bio->bi_bdev == stripe->dev->bdev) { return i; } } return -1; } /* * helper to find the stripe number for a given * bio (before mapping). Used to figure out which stripe has * failed. This looks up based on logical block numbers. */ static int find_logical_bio_stripe(struct btrfs_raid_bio *rbio, struct bio *bio) { u64 logical = bio->bi_iter.bi_sector; u64 stripe_start; int i; logical <<= 9; for (i = 0; i < rbio->nr_data; i++) { stripe_start = rbio->bbio->raid_map[i]; if (logical >= stripe_start && logical < stripe_start + rbio->stripe_len) { return i; } } return -1; } /* * returns -EIO if we had too many failures */ static int fail_rbio_index(struct btrfs_raid_bio *rbio, int failed) { unsigned long flags; int ret = 0; spin_lock_irqsave(&rbio->bio_list_lock, flags); /* we already know this stripe is bad, move on */ if (rbio->faila == failed || rbio->failb == failed) goto out; if (rbio->faila == -1) { /* first failure on this rbio */ rbio->faila = failed; atomic_inc(&rbio->error); } else if (rbio->failb == -1) { /* second failure on this rbio */ rbio->failb = failed; atomic_inc(&rbio->error); } else { ret = -EIO; } out: spin_unlock_irqrestore(&rbio->bio_list_lock, flags); return ret; } /* * helper to fail a stripe based on a physical disk * bio. */ static int fail_bio_stripe(struct btrfs_raid_bio *rbio, struct bio *bio) { int failed = find_bio_stripe(rbio, bio); if (failed < 0) return -EIO; return fail_rbio_index(rbio, failed); } /* * this sets each page in the bio uptodate. It should only be used on private * rbio pages, nothing that comes in from the higher layers */ static void set_bio_pages_uptodate(struct bio *bio) { struct bio_vec bvec; struct bvec_iter iter; if (bio_flagged(bio, BIO_CLONED)) bio->bi_iter = btrfs_io_bio(bio)->iter; bio_for_each_segment(bvec, bio, iter) SetPageUptodate(bvec.bv_page); } /* * end io for the read phase of the rmw cycle. All the bios here are physical * stripe bios we've read from the disk so we can recalculate the parity of the * stripe. * * This will usually kick off finish_rmw once all the bios are read in, but it * may trigger parity reconstruction if we had any errors along the way */ static void raid_rmw_end_io(struct bio *bio) { struct btrfs_raid_bio *rbio = bio->bi_private; if (bio->bi_status) fail_bio_stripe(rbio, bio); else set_bio_pages_uptodate(bio); bio_put(bio); if (!atomic_dec_and_test(&rbio->stripes_pending)) return; if (atomic_read(&rbio->error) > rbio->bbio->max_errors) goto cleanup; /* * this will normally call finish_rmw to start our write * but if there are any failed stripes we'll reconstruct * from parity first */ validate_rbio_for_rmw(rbio); return; cleanup: rbio_orig_end_io(rbio, BLK_STS_IOERR); } static void async_rmw_stripe(struct btrfs_raid_bio *rbio) { btrfs_init_work(&rbio->work, btrfs_rmw_helper, rmw_work, NULL, NULL); btrfs_queue_work(rbio->fs_info->rmw_workers, &rbio->work); } static void async_read_rebuild(struct btrfs_raid_bio *rbio) { btrfs_init_work(&rbio->work, btrfs_rmw_helper, read_rebuild_work, NULL, NULL); btrfs_queue_work(rbio->fs_info->rmw_workers, &rbio->work); } /* * the stripe must be locked by the caller. It will * unlock after all the writes are done */ static int raid56_rmw_stripe(struct btrfs_raid_bio *rbio) { int bios_to_read = 0; struct bio_list bio_list; int ret; int pagenr; int stripe; struct bio *bio; bio_list_init(&bio_list); ret = alloc_rbio_pages(rbio); if (ret) goto cleanup; index_rbio_pages(rbio); atomic_set(&rbio->error, 0); /* * build a list of bios to read all the missing parts of this * stripe */ for (stripe = 0; stripe < rbio->nr_data; stripe++) { for (pagenr = 0; pagenr < rbio->stripe_npages; pagenr++) { struct page *page; /* * we want to find all the pages missing from * the rbio and read them from the disk. If * page_in_rbio finds a page in the bio list * we don't need to read it off the stripe. */ page = page_in_rbio(rbio, stripe, pagenr, 1); if (page) continue; page = rbio_stripe_page(rbio, stripe, pagenr); /* * the bio cache may have handed us an uptodate * page. If so, be happy and use it */ if (PageUptodate(page)) continue; ret = rbio_add_io_page(rbio, &bio_list, page, stripe, pagenr, rbio->stripe_len); if (ret) goto cleanup; } } bios_to_read = bio_list_size(&bio_list); if (!bios_to_read) { /* * this can happen if others have merged with * us, it means there is nothing left to read. * But if there are missing devices it may not be * safe to do the full stripe write yet. */ goto finish; } /* * the bbio may be freed once we submit the last bio. Make sure * not to touch it after that */ atomic_set(&rbio->stripes_pending, bios_to_read); while (1) { bio = bio_list_pop(&bio_list); if (!bio) break; bio->bi_private = rbio; bio->bi_end_io = raid_rmw_end_io; bio_set_op_attrs(bio, REQ_OP_READ, 0); btrfs_bio_wq_end_io(rbio->fs_info, bio, BTRFS_WQ_ENDIO_RAID56); submit_bio(bio); } /* the actual write will happen once the reads are done */ return 0; cleanup: rbio_orig_end_io(rbio, BLK_STS_IOERR); return -EIO; finish: validate_rbio_for_rmw(rbio); return 0; } /* * if the upper layers pass in a full stripe, we thank them by only allocating * enough pages to hold the parity, and sending it all down quickly. */ static int full_stripe_write(struct btrfs_raid_bio *rbio) { int ret; ret = alloc_rbio_parity_pages(rbio); if (ret) { __free_raid_bio(rbio); return ret; } ret = lock_stripe_add(rbio); if (ret == 0) finish_rmw(rbio); return 0; } /* * partial stripe writes get handed over to async helpers. * We're really hoping to merge a few more writes into this * rbio before calculating new parity */ static int partial_stripe_write(struct btrfs_raid_bio *rbio) { int ret; ret = lock_stripe_add(rbio); if (ret == 0) async_rmw_stripe(rbio); return 0; } /* * sometimes while we were reading from the drive to * recalculate parity, enough new bios come into create * a full stripe. So we do a check here to see if we can * go directly to finish_rmw */ static int __raid56_parity_write(struct btrfs_raid_bio *rbio) { /* head off into rmw land if we don't have a full stripe */ if (!rbio_is_full(rbio)) return partial_stripe_write(rbio); return full_stripe_write(rbio); } /* * We use plugging call backs to collect full stripes. * Any time we get a partial stripe write while plugged * we collect it into a list. When the unplug comes down, * we sort the list by logical block number and merge * everything we can into the same rbios */ struct btrfs_plug_cb { struct blk_plug_cb cb; struct btrfs_fs_info *info; struct list_head rbio_list; struct btrfs_work work; }; /* * rbios on the plug list are sorted for easier merging. */ static int plug_cmp(void *priv, struct list_head *a, struct list_head *b) { struct btrfs_raid_bio *ra = container_of(a, struct btrfs_raid_bio, plug_list); struct btrfs_raid_bio *rb = container_of(b, struct btrfs_raid_bio, plug_list); u64 a_sector = ra->bio_list.head->bi_iter.bi_sector; u64 b_sector = rb->bio_list.head->bi_iter.bi_sector; if (a_sector < b_sector) return -1; if (a_sector > b_sector) return 1; return 0; } static void run_plug(struct btrfs_plug_cb *plug) { struct btrfs_raid_bio *cur; struct btrfs_raid_bio *last = NULL; /* * sort our plug list then try to merge * everything we can in hopes of creating full * stripes. */ list_sort(NULL, &plug->rbio_list, plug_cmp); while (!list_empty(&plug->rbio_list)) { cur = list_entry(plug->rbio_list.next, struct btrfs_raid_bio, plug_list); list_del_init(&cur->plug_list); if (rbio_is_full(cur)) { /* we have a full stripe, send it down */ full_stripe_write(cur); continue; } if (last) { if (rbio_can_merge(last, cur)) { merge_rbio(last, cur); __free_raid_bio(cur); continue; } __raid56_parity_write(last); } last = cur; } if (last) { __raid56_parity_write(last); } kfree(plug); } /* * if the unplug comes from schedule, we have to push the * work off to a helper thread */ static void unplug_work(struct btrfs_work *work) { struct btrfs_plug_cb *plug; plug = container_of(work, struct btrfs_plug_cb, work); run_plug(plug); } static void btrfs_raid_unplug(struct blk_plug_cb *cb, bool from_schedule) { struct btrfs_plug_cb *plug; plug = container_of(cb, struct btrfs_plug_cb, cb); if (from_schedule) { btrfs_init_work(&plug->work, btrfs_rmw_helper, unplug_work, NULL, NULL); btrfs_queue_work(plug->info->rmw_workers, &plug->work); return; } run_plug(plug); } /* * our main entry point for writes from the rest of the FS. */ int raid56_parity_write(struct btrfs_fs_info *fs_info, struct bio *bio, struct btrfs_bio *bbio, u64 stripe_len) { struct btrfs_raid_bio *rbio; struct btrfs_plug_cb *plug = NULL; struct blk_plug_cb *cb; int ret; rbio = alloc_rbio(fs_info, bbio, stripe_len); if (IS_ERR(rbio)) { btrfs_put_bbio(bbio); return PTR_ERR(rbio); } bio_list_add(&rbio->bio_list, bio); rbio->bio_list_bytes = bio->bi_iter.bi_size; rbio->operation = BTRFS_RBIO_WRITE; btrfs_bio_counter_inc_noblocked(fs_info); rbio->generic_bio_cnt = 1; /* * don't plug on full rbios, just get them out the door * as quickly as we can */ if (rbio_is_full(rbio)) { ret = full_stripe_write(rbio); if (ret) btrfs_bio_counter_dec(fs_info); return ret; } cb = blk_check_plugged(btrfs_raid_unplug, fs_info, sizeof(*plug)); if (cb) { plug = container_of(cb, struct btrfs_plug_cb, cb); if (!plug->info) { plug->info = fs_info; INIT_LIST_HEAD(&plug->rbio_list); } list_add_tail(&rbio->plug_list, &plug->rbio_list); ret = 0; } else { ret = __raid56_parity_write(rbio); if (ret) btrfs_bio_counter_dec(fs_info); } return ret; } /* * all parity reconstruction happens here. We've read in everything * we can find from the drives and this does the heavy lifting of * sorting the good from the bad. */ static void __raid_recover_end_io(struct btrfs_raid_bio *rbio) { int pagenr, stripe; void **pointers; int faila = -1, failb = -1; struct page *page; blk_status_t err; int i; pointers = kcalloc(rbio->real_stripes, sizeof(void *), GFP_NOFS); if (!pointers) { err = BLK_STS_RESOURCE; goto cleanup_io; } faila = rbio->faila; failb = rbio->failb; if (rbio->operation == BTRFS_RBIO_READ_REBUILD || rbio->operation == BTRFS_RBIO_REBUILD_MISSING) { spin_lock_irq(&rbio->bio_list_lock); set_bit(RBIO_RMW_LOCKED_BIT, &rbio->flags); spin_unlock_irq(&rbio->bio_list_lock); } index_rbio_pages(rbio); for (pagenr = 0; pagenr < rbio->stripe_npages; pagenr++) { /* * Now we just use bitmap to mark the horizontal stripes in * which we have data when doing parity scrub. */ if (rbio->operation == BTRFS_RBIO_PARITY_SCRUB && !test_bit(pagenr, rbio->dbitmap)) continue; /* setup our array of pointers with pages * from each stripe */ for (stripe = 0; stripe < rbio->real_stripes; stripe++) { /* * if we're rebuilding a read, we have to use * pages from the bio list */ if ((rbio->operation == BTRFS_RBIO_READ_REBUILD || rbio->operation == BTRFS_RBIO_REBUILD_MISSING) && (stripe == faila || stripe == failb)) { page = page_in_rbio(rbio, stripe, pagenr, 0); } else { page = rbio_stripe_page(rbio, stripe, pagenr); } pointers[stripe] = kmap(page); } /* all raid6 handling here */ if (rbio->bbio->map_type & BTRFS_BLOCK_GROUP_RAID6) { /* * single failure, rebuild from parity raid5 * style */ if (failb < 0) { if (faila == rbio->nr_data) { /* * Just the P stripe has failed, without * a bad data or Q stripe. * TODO, we should redo the xor here. */ err = BLK_STS_IOERR; goto cleanup; } /* * a single failure in raid6 is rebuilt * in the pstripe code below */ goto pstripe; } /* make sure our ps and qs are in order */ if (faila > failb) { int tmp = failb; failb = faila; faila = tmp; } /* if the q stripe is failed, do a pstripe reconstruction * from the xors. * If both the q stripe and the P stripe are failed, we're * here due to a crc mismatch and we can't give them the * data they want */ if (rbio->bbio->raid_map[failb] == RAID6_Q_STRIPE) { if (rbio->bbio->raid_map[faila] == RAID5_P_STRIPE) { err = BLK_STS_IOERR; goto cleanup; } /* * otherwise we have one bad data stripe and * a good P stripe. raid5! */ goto pstripe; } if (rbio->bbio->raid_map[failb] == RAID5_P_STRIPE) { raid6_datap_recov(rbio->real_stripes, PAGE_SIZE, faila, pointers); } else { raid6_2data_recov(rbio->real_stripes, PAGE_SIZE, faila, failb, pointers); } } else { void *p; /* rebuild from P stripe here (raid5 or raid6) */ BUG_ON(failb != -1); pstripe: /* Copy parity block into failed block to start with */ memcpy(pointers[faila], pointers[rbio->nr_data], PAGE_SIZE); /* rearrange the pointer array */ p = pointers[faila]; for (stripe = faila; stripe < rbio->nr_data - 1; stripe++) pointers[stripe] = pointers[stripe + 1]; pointers[rbio->nr_data - 1] = p; /* xor in the rest */ run_xor(pointers, rbio->nr_data - 1, PAGE_SIZE); } /* if we're doing this rebuild as part of an rmw, go through * and set all of our private rbio pages in the * failed stripes as uptodate. This way finish_rmw will * know they can be trusted. If this was a read reconstruction, * other endio functions will fiddle the uptodate bits */ if (rbio->operation == BTRFS_RBIO_WRITE) { for (i = 0; i < rbio->stripe_npages; i++) { if (faila != -1) { page = rbio_stripe_page(rbio, faila, i); SetPageUptodate(page); } if (failb != -1) { page = rbio_stripe_page(rbio, failb, i); SetPageUptodate(page); } } } for (stripe = 0; stripe < rbio->real_stripes; stripe++) { /* * if we're rebuilding a read, we have to use * pages from the bio list */ if ((rbio->operation == BTRFS_RBIO_READ_REBUILD || rbio->operation == BTRFS_RBIO_REBUILD_MISSING) && (stripe == faila || stripe == failb)) { page = page_in_rbio(rbio, stripe, pagenr, 0); } else { page = rbio_stripe_page(rbio, stripe, pagenr); } kunmap(page); } } err = BLK_STS_OK; cleanup: kfree(pointers); cleanup_io: if (rbio->operation == BTRFS_RBIO_READ_REBUILD) { if (err == BLK_STS_OK) cache_rbio_pages(rbio); else clear_bit(RBIO_CACHE_READY_BIT, &rbio->flags); rbio_orig_end_io(rbio, err); } else if (rbio->operation == BTRFS_RBIO_REBUILD_MISSING) { rbio_orig_end_io(rbio, err); } else if (err == BLK_STS_OK) { rbio->faila = -1; rbio->failb = -1; if (rbio->operation == BTRFS_RBIO_WRITE) finish_rmw(rbio); else if (rbio->operation == BTRFS_RBIO_PARITY_SCRUB) finish_parity_scrub(rbio, 0); else BUG(); } else { rbio_orig_end_io(rbio, err); } } /* * This is called only for stripes we've read from disk to * reconstruct the parity. */ static void raid_recover_end_io(struct bio *bio) { struct btrfs_raid_bio *rbio = bio->bi_private; /* * we only read stripe pages off the disk, set them * up to date if there were no errors */ if (bio->bi_status) fail_bio_stripe(rbio, bio); else set_bio_pages_uptodate(bio); bio_put(bio); if (!atomic_dec_and_test(&rbio->stripes_pending)) return; if (atomic_read(&rbio->error) > rbio->bbio->max_errors) rbio_orig_end_io(rbio, BLK_STS_IOERR); else __raid_recover_end_io(rbio); } /* * reads everything we need off the disk to reconstruct * the parity. endio handlers trigger final reconstruction * when the IO is done. * * This is used both for reads from the higher layers and for * parity construction required to finish a rmw cycle. */ static int __raid56_parity_recover(struct btrfs_raid_bio *rbio) { int bios_to_read = 0; struct bio_list bio_list; int ret; int pagenr; int stripe; struct bio *bio; bio_list_init(&bio_list); ret = alloc_rbio_pages(rbio); if (ret) goto cleanup; atomic_set(&rbio->error, 0); /* * read everything that hasn't failed. Thanks to the * stripe cache, it is possible that some or all of these * pages are going to be uptodate. */ for (stripe = 0; stripe < rbio->real_stripes; stripe++) { if (rbio->faila == stripe || rbio->failb == stripe) { atomic_inc(&rbio->error); continue; } for (pagenr = 0; pagenr < rbio->stripe_npages; pagenr++) { struct page *p; /* * the rmw code may have already read this * page in */ p = rbio_stripe_page(rbio, stripe, pagenr); if (PageUptodate(p)) continue; ret = rbio_add_io_page(rbio, &bio_list, rbio_stripe_page(rbio, stripe, pagenr), stripe, pagenr, rbio->stripe_len); if (ret < 0) goto cleanup; } } bios_to_read = bio_list_size(&bio_list); if (!bios_to_read) { /* * we might have no bios to read just because the pages * were up to date, or we might have no bios to read because * the devices were gone. */ if (atomic_read(&rbio->error) <= rbio->bbio->max_errors) { __raid_recover_end_io(rbio); goto out; } else { goto cleanup; } } /* * the bbio may be freed once we submit the last bio. Make sure * not to touch it after that */ atomic_set(&rbio->stripes_pending, bios_to_read); while (1) { bio = bio_list_pop(&bio_list); if (!bio) break; bio->bi_private = rbio; bio->bi_end_io = raid_recover_end_io; bio_set_op_attrs(bio, REQ_OP_READ, 0); btrfs_bio_wq_end_io(rbio->fs_info, bio, BTRFS_WQ_ENDIO_RAID56); submit_bio(bio); } out: return 0; cleanup: if (rbio->operation == BTRFS_RBIO_READ_REBUILD || rbio->operation == BTRFS_RBIO_REBUILD_MISSING) rbio_orig_end_io(rbio, BLK_STS_IOERR); return -EIO; } /* * the main entry point for reads from the higher layers. This * is really only called when the normal read path had a failure, * so we assume the bio they send down corresponds to a failed part * of the drive. */ int raid56_parity_recover(struct btrfs_fs_info *fs_info, struct bio *bio, struct btrfs_bio *bbio, u64 stripe_len, int mirror_num, int generic_io) { struct btrfs_raid_bio *rbio; int ret; if (generic_io) { ASSERT(bbio->mirror_num == mirror_num); btrfs_io_bio(bio)->mirror_num = mirror_num; } rbio = alloc_rbio(fs_info, bbio, stripe_len); if (IS_ERR(rbio)) { if (generic_io) btrfs_put_bbio(bbio); return PTR_ERR(rbio); } rbio->operation = BTRFS_RBIO_READ_REBUILD; bio_list_add(&rbio->bio_list, bio); rbio->bio_list_bytes = bio->bi_iter.bi_size; rbio->faila = find_logical_bio_stripe(rbio, bio); if (rbio->faila == -1) { btrfs_warn(fs_info, "%s could not find the bad stripe in raid56 so that we cannot recover any more (bio has logical %llu len %llu, bbio has map_type %llu)", __func__, (u64)bio->bi_iter.bi_sector << 9, (u64)bio->bi_iter.bi_size, bbio->map_type); if (generic_io) btrfs_put_bbio(bbio); kfree(rbio); return -EIO; } if (generic_io) { btrfs_bio_counter_inc_noblocked(fs_info); rbio->generic_bio_cnt = 1; } else { btrfs_get_bbio(bbio); } /* * reconstruct from the q stripe if they are * asking for mirror 3 */ if (mirror_num == 3) rbio->failb = rbio->real_stripes - 2; ret = lock_stripe_add(rbio); /* * __raid56_parity_recover will end the bio with * any errors it hits. We don't want to return * its error value up the stack because our caller * will end up calling bio_endio with any nonzero * return */ if (ret == 0) __raid56_parity_recover(rbio); /* * our rbio has been added to the list of * rbios that will be handled after the * currently lock owner is done */ return 0; } static void rmw_work(struct btrfs_work *work) { struct btrfs_raid_bio *rbio; rbio = container_of(work, struct btrfs_raid_bio, work); raid56_rmw_stripe(rbio); } static void read_rebuild_work(struct btrfs_work *work) { struct btrfs_raid_bio *rbio; rbio = container_of(work, struct btrfs_raid_bio, work); __raid56_parity_recover(rbio); } /* * The following code is used to scrub/replace the parity stripe * * Caller must have already increased bio_counter for getting @bbio. * * Note: We need make sure all the pages that add into the scrub/replace * raid bio are correct and not be changed during the scrub/replace. That * is those pages just hold metadata or file data with checksum. */ struct btrfs_raid_bio * raid56_parity_alloc_scrub_rbio(struct btrfs_fs_info *fs_info, struct bio *bio, struct btrfs_bio *bbio, u64 stripe_len, struct btrfs_device *scrub_dev, unsigned long *dbitmap, int stripe_nsectors) { struct btrfs_raid_bio *rbio; int i; rbio = alloc_rbio(fs_info, bbio, stripe_len); if (IS_ERR(rbio)) return NULL; bio_list_add(&rbio->bio_list, bio); /* * This is a special bio which is used to hold the completion handler * and make the scrub rbio is similar to the other types */ ASSERT(!bio->bi_iter.bi_size); rbio->operation = BTRFS_RBIO_PARITY_SCRUB; for (i = 0; i < rbio->real_stripes; i++) { if (bbio->stripes[i].dev == scrub_dev) { rbio->scrubp = i; break; } } /* Now we just support the sectorsize equals to page size */ ASSERT(fs_info->sectorsize == PAGE_SIZE); ASSERT(rbio->stripe_npages == stripe_nsectors); bitmap_copy(rbio->dbitmap, dbitmap, stripe_nsectors); /* * We have already increased bio_counter when getting bbio, record it * so we can free it at rbio_orig_end_io(). */ rbio->generic_bio_cnt = 1; return rbio; } /* Used for both parity scrub and missing. */ void raid56_add_scrub_pages(struct btrfs_raid_bio *rbio, struct page *page, u64 logical) { int stripe_offset; int index; ASSERT(logical >= rbio->bbio->raid_map[0]); ASSERT(logical + PAGE_SIZE <= rbio->bbio->raid_map[0] + rbio->stripe_len * rbio->nr_data); stripe_offset = (int)(logical - rbio->bbio->raid_map[0]); index = stripe_offset >> PAGE_SHIFT; rbio->bio_pages[index] = page; } /* * We just scrub the parity that we have correct data on the same horizontal, * so we needn't allocate all pages for all the stripes. */ static int alloc_rbio_essential_pages(struct btrfs_raid_bio *rbio) { int i; int bit; int index; struct page *page; for_each_set_bit(bit, rbio->dbitmap, rbio->stripe_npages) { for (i = 0; i < rbio->real_stripes; i++) { index = i * rbio->stripe_npages + bit; if (rbio->stripe_pages[index]) continue; page = alloc_page(GFP_NOFS | __GFP_HIGHMEM); if (!page) return -ENOMEM; rbio->stripe_pages[index] = page; } } return 0; } static noinline void finish_parity_scrub(struct btrfs_raid_bio *rbio, int need_check) { struct btrfs_bio *bbio = rbio->bbio; void *pointers[rbio->real_stripes]; DECLARE_BITMAP(pbitmap, rbio->stripe_npages); int nr_data = rbio->nr_data; int stripe; int pagenr; int p_stripe = -1; int q_stripe = -1; struct page *p_page = NULL; struct page *q_page = NULL; struct bio_list bio_list; struct bio *bio; int is_replace = 0; int ret; bio_list_init(&bio_list); if (rbio->real_stripes - rbio->nr_data == 1) { p_stripe = rbio->real_stripes - 1; } else if (rbio->real_stripes - rbio->nr_data == 2) { p_stripe = rbio->real_stripes - 2; q_stripe = rbio->real_stripes - 1; } else { BUG(); } if (bbio->num_tgtdevs && bbio->tgtdev_map[rbio->scrubp]) { is_replace = 1; bitmap_copy(pbitmap, rbio->dbitmap, rbio->stripe_npages); } /* * Because the higher layers(scrubber) are unlikely to * use this area of the disk again soon, so don't cache * it. */ clear_bit(RBIO_CACHE_READY_BIT, &rbio->flags); if (!need_check) goto writeback; p_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM); if (!p_page) goto cleanup; SetPageUptodate(p_page); if (q_stripe != -1) { q_page = alloc_page(GFP_NOFS | __GFP_HIGHMEM); if (!q_page) { __free_page(p_page); goto cleanup; } SetPageUptodate(q_page); } atomic_set(&rbio->error, 0); for_each_set_bit(pagenr, rbio->dbitmap, rbio->stripe_npages) { struct page *p; void *parity; /* first collect one page from each data stripe */ for (stripe = 0; stripe < nr_data; stripe++) { p = page_in_rbio(rbio, stripe, pagenr, 0); pointers[stripe] = kmap(p); } /* then add the parity stripe */ pointers[stripe++] = kmap(p_page); if (q_stripe != -1) { /* * raid6, add the qstripe and call the * library function to fill in our p/q */ pointers[stripe++] = kmap(q_page); raid6_call.gen_syndrome(rbio->real_stripes, PAGE_SIZE, pointers); } else { /* raid5 */ memcpy(pointers[nr_data], pointers[0], PAGE_SIZE); run_xor(pointers + 1, nr_data - 1, PAGE_SIZE); } /* Check scrubbing parity and repair it */ p = rbio_stripe_page(rbio, rbio->scrubp, pagenr); parity = kmap(p); if (memcmp(parity, pointers[rbio->scrubp], PAGE_SIZE)) memcpy(parity, pointers[rbio->scrubp], PAGE_SIZE); else /* Parity is right, needn't writeback */ bitmap_clear(rbio->dbitmap, pagenr, 1); kunmap(p); for (stripe = 0; stripe < rbio->real_stripes; stripe++) kunmap(page_in_rbio(rbio, stripe, pagenr, 0)); } __free_page(p_page); if (q_page) __free_page(q_page); writeback: /* * time to start writing. Make bios for everything from the * higher layers (the bio_list in our rbio) and our p/q. Ignore * everything else. */ for_each_set_bit(pagenr, rbio->dbitmap, rbio->stripe_npages) { struct page *page; page = rbio_stripe_page(rbio, rbio->scrubp, pagenr); ret = rbio_add_io_page(rbio, &bio_list, page, rbio->scrubp, pagenr, rbio->stripe_len); if (ret) goto cleanup; } if (!is_replace) goto submit_write; for_each_set_bit(pagenr, pbitmap, rbio->stripe_npages) { struct page *page; page = rbio_stripe_page(rbio, rbio->scrubp, pagenr); ret = rbio_add_io_page(rbio, &bio_list, page, bbio->tgtdev_map[rbio->scrubp], pagenr, rbio->stripe_len); if (ret) goto cleanup; } submit_write: nr_data = bio_list_size(&bio_list); if (!nr_data) { /* Every parity is right */ rbio_orig_end_io(rbio, BLK_STS_OK); return; } atomic_set(&rbio->stripes_pending, nr_data); while (1) { bio = bio_list_pop(&bio_list); if (!bio) break; bio->bi_private = rbio; bio->bi_end_io = raid_write_end_io; bio_set_op_attrs(bio, REQ_OP_WRITE, 0); submit_bio(bio); } return; cleanup: rbio_orig_end_io(rbio, BLK_STS_IOERR); } static inline int is_data_stripe(struct btrfs_raid_bio *rbio, int stripe) { if (stripe >= 0 && stripe < rbio->nr_data) return 1; return 0; } /* * While we're doing the parity check and repair, we could have errors * in reading pages off the disk. This checks for errors and if we're * not able to read the page it'll trigger parity reconstruction. The * parity scrub will be finished after we've reconstructed the failed * stripes */ static void validate_rbio_for_parity_scrub(struct btrfs_raid_bio *rbio) { if (atomic_read(&rbio->error) > rbio->bbio->max_errors) goto cleanup; if (rbio->faila >= 0 || rbio->failb >= 0) { int dfail = 0, failp = -1; if (is_data_stripe(rbio, rbio->faila)) dfail++; else if (is_parity_stripe(rbio->faila)) failp = rbio->faila; if (is_data_stripe(rbio, rbio->failb)) dfail++; else if (is_parity_stripe(rbio->failb)) failp = rbio->failb; /* * Because we can not use a scrubbing parity to repair * the data, so the capability of the repair is declined. * (In the case of RAID5, we can not repair anything) */ if (dfail > rbio->bbio->max_errors - 1) goto cleanup; /* * If all data is good, only parity is correctly, just * repair the parity. */ if (dfail == 0) { finish_parity_scrub(rbio, 0); return; } /* * Here means we got one corrupted data stripe and one * corrupted parity on RAID6, if the corrupted parity * is scrubbing parity, luckily, use the other one to repair * the data, or we can not repair the data stripe. */ if (failp != rbio->scrubp) goto cleanup; __raid_recover_end_io(rbio); } else { finish_parity_scrub(rbio, 1); } return; cleanup: rbio_orig_end_io(rbio, BLK_STS_IOERR); } /* * end io for the read phase of the rmw cycle. All the bios here are physical * stripe bios we've read from the disk so we can recalculate the parity of the * stripe. * * This will usually kick off finish_rmw once all the bios are read in, but it * may trigger parity reconstruction if we had any errors along the way */ static void raid56_parity_scrub_end_io(struct bio *bio) { struct btrfs_raid_bio *rbio = bio->bi_private; if (bio->bi_status) fail_bio_stripe(rbio, bio); else set_bio_pages_uptodate(bio); bio_put(bio); if (!atomic_dec_and_test(&rbio->stripes_pending)) return; /* * this will normally call finish_rmw to start our write * but if there are any failed stripes we'll reconstruct * from parity first */ validate_rbio_for_parity_scrub(rbio); } static void raid56_parity_scrub_stripe(struct btrfs_raid_bio *rbio) { int bios_to_read = 0; struct bio_list bio_list; int ret; int pagenr; int stripe; struct bio *bio; ret = alloc_rbio_essential_pages(rbio); if (ret) goto cleanup; bio_list_init(&bio_list); atomic_set(&rbio->error, 0); /* * build a list of bios to read all the missing parts of this * stripe */ for (stripe = 0; stripe < rbio->real_stripes; stripe++) { for_each_set_bit(pagenr, rbio->dbitmap, rbio->stripe_npages) { struct page *page; /* * we want to find all the pages missing from * the rbio and read them from the disk. If * page_in_rbio finds a page in the bio list * we don't need to read it off the stripe. */ page = page_in_rbio(rbio, stripe, pagenr, 1); if (page) continue; page = rbio_stripe_page(rbio, stripe, pagenr); /* * the bio cache may have handed us an uptodate * page. If so, be happy and use it */ if (PageUptodate(page)) continue; ret = rbio_add_io_page(rbio, &bio_list, page, stripe, pagenr, rbio->stripe_len); if (ret) goto cleanup; } } bios_to_read = bio_list_size(&bio_list); if (!bios_to_read) { /* * this can happen if others have merged with * us, it means there is nothing left to read. * But if there are missing devices it may not be * safe to do the full stripe write yet. */ goto finish; } /* * the bbio may be freed once we submit the last bio. Make sure * not to touch it after that */ atomic_set(&rbio->stripes_pending, bios_to_read); while (1) { bio = bio_list_pop(&bio_list); if (!bio) break; bio->bi_private = rbio; bio->bi_end_io = raid56_parity_scrub_end_io; bio_set_op_attrs(bio, REQ_OP_READ, 0); btrfs_bio_wq_end_io(rbio->fs_info, bio, BTRFS_WQ_ENDIO_RAID56); submit_bio(bio); } /* the actual write will happen once the reads are done */ return; cleanup: rbio_orig_end_io(rbio, BLK_STS_IOERR); return; finish: validate_rbio_for_parity_scrub(rbio); } static void scrub_parity_work(struct btrfs_work *work) { struct btrfs_raid_bio *rbio; rbio = container_of(work, struct btrfs_raid_bio, work); raid56_parity_scrub_stripe(rbio); } static void async_scrub_parity(struct btrfs_raid_bio *rbio) { btrfs_init_work(&rbio->work, btrfs_rmw_helper, scrub_parity_work, NULL, NULL); btrfs_queue_work(rbio->fs_info->rmw_workers, &rbio->work); } void raid56_parity_submit_scrub_rbio(struct btrfs_raid_bio *rbio) { if (!lock_stripe_add(rbio)) async_scrub_parity(rbio); } /* The following code is used for dev replace of a missing RAID 5/6 device. */ struct btrfs_raid_bio * raid56_alloc_missing_rbio(struct btrfs_fs_info *fs_info, struct bio *bio, struct btrfs_bio *bbio, u64 length) { struct btrfs_raid_bio *rbio; rbio = alloc_rbio(fs_info, bbio, length); if (IS_ERR(rbio)) return NULL; rbio->operation = BTRFS_RBIO_REBUILD_MISSING; bio_list_add(&rbio->bio_list, bio); /* * This is a special bio which is used to hold the completion handler * and make the scrub rbio is similar to the other types */ ASSERT(!bio->bi_iter.bi_size); rbio->faila = find_logical_bio_stripe(rbio, bio); if (rbio->faila == -1) { BUG(); kfree(rbio); return NULL; } /* * When we get bbio, we have already increased bio_counter, record it * so we can free it at rbio_orig_end_io() */ rbio->generic_bio_cnt = 1; return rbio; } static void missing_raid56_work(struct btrfs_work *work) { struct btrfs_raid_bio *rbio; rbio = container_of(work, struct btrfs_raid_bio, work); __raid56_parity_recover(rbio); } static void async_missing_raid56(struct btrfs_raid_bio *rbio) { btrfs_init_work(&rbio->work, btrfs_rmw_helper, missing_raid56_work, NULL, NULL); btrfs_queue_work(rbio->fs_info->rmw_workers, &rbio->work); } void raid56_submit_missing_rbio(struct btrfs_raid_bio *rbio) { if (!lock_stripe_add(rbio)) async_missing_raid56(rbio); }
pratyushanand/linux
fs/btrfs/raid56.c
C
gpl-2.0
67,975
/* Measure STRCHR functions. Copyright (C) 2013-2015 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #define TEST_MAIN #ifndef WIDE # ifdef USE_FOR_STRCHRNUL # define TEST_NAME "strchrnul" # else # define TEST_NAME "strchr" # endif /* !USE_FOR_STRCHRNUL */ #else # ifdef USE_FOR_STRCHRNUL # define TEST_NAME "wcschrnul" # else # define TEST_NAME "wcschr" # endif /* !USE_FOR_STRCHRNUL */ #endif /* WIDE */ #include "bench-string.h" #ifndef WIDE # ifdef USE_FOR_STRCHRNUL # define STRCHR strchrnul # define stupid_STRCHR stupid_STRCHRNUL # define simple_STRCHR simple_STRCHRNUL # else # define STRCHR strchr # endif /* !USE_FOR_STRCHRNUL */ # define STRLEN strlen # define CHAR char # define BIG_CHAR CHAR_MAX # define MIDDLE_CHAR 127 # define SMALL_CHAR 23 # define UCHAR unsigned char #else # include <wchar.h> # ifdef USE_FOR_STRCHRNUL # define STRCHR wcschrnul # define stupid_STRCHR stupid_WCSCHRNUL # define simple_STRCHR simple_WCSCHRNUL # else # define STRCHR wcschr # endif /* !USE_FOR_STRCHRNUL */ # define STRLEN wcslen # define CHAR wchar_t # define BIG_CHAR WCHAR_MAX # define MIDDLE_CHAR 1121 # define SMALL_CHAR 851 # define UCHAR wchar_t #endif /* WIDE */ #ifdef USE_FOR_STRCHRNUL # define NULLRET(endptr) endptr #else # define NULLRET(endptr) NULL #endif /* !USE_FOR_STRCHRNUL */ typedef CHAR *(*proto_t) (const CHAR *, int); CHAR * simple_STRCHR (const CHAR *s, int c) { for (; *s != (CHAR) c; ++s) if (*s == '\0') return NULLRET ((CHAR *) s); return (CHAR *) s; } CHAR * stupid_STRCHR (const CHAR *s, int c) { size_t n = STRLEN (s) + 1; while (n--) if (*s++ == (CHAR) c) return (CHAR *) s - 1; return NULLRET ((CHAR *) s - 1); } IMPL (stupid_STRCHR, 0) IMPL (simple_STRCHR, 0) IMPL (STRCHR, 1) static void do_one_test (impl_t *impl, const CHAR *s, int c, const CHAR *exp_res) { size_t i, iters = INNER_LOOP_ITERS; timing_t start, stop, cur; TIMING_NOW (start); for (i = 0; i < iters; ++i) { CALL (impl, s, c); } TIMING_NOW (stop); TIMING_DIFF (cur, start, stop); TIMING_PRINT_MEAN ((double) cur, (double) iters); } static void do_test (size_t align, size_t pos, size_t len, int seek_char, int max_char) /* For wcschr: align here means align not in bytes, but in wchar_ts, in bytes it will equal to align * (sizeof (wchar_t)) len for wcschr here isn't in bytes but it's number of wchar_t symbols. */ { size_t i; CHAR *result; CHAR *buf = (CHAR *) buf1; align &= 15; if ((align + len) * sizeof (CHAR) >= page_size) return; for (i = 0; i < len; ++i) { buf[align + i] = 32 + 23 * i % max_char; if (buf[align + i] == seek_char) buf[align + i] = seek_char + 1; else if (buf[align + i] == 0) buf[align + i] = 1; } buf[align + len] = 0; if (pos < len) { buf[align + pos] = seek_char; result = buf + align + pos; } else if (seek_char == 0) result = buf + align + len; else result = NULLRET (buf + align + len); printf ("Length %4zd, alignment in bytes %2zd:", pos, align * sizeof (CHAR)); FOR_EACH_IMPL (impl, 0) do_one_test (impl, buf + align, seek_char, result); putchar ('\n'); } int test_main (void) { size_t i; test_init (); printf ("%20s", ""); FOR_EACH_IMPL (impl, 0) printf ("\t%s", impl->name); putchar ('\n'); for (i = 1; i < 8; ++i) { do_test (0, 16 << i, 2048, SMALL_CHAR, MIDDLE_CHAR); do_test (i, 16 << i, 2048, SMALL_CHAR, MIDDLE_CHAR); } for (i = 1; i < 8; ++i) { do_test (i, 64, 256, SMALL_CHAR, MIDDLE_CHAR); do_test (i, 64, 256, SMALL_CHAR, BIG_CHAR); } for (i = 0; i < 32; ++i) { do_test (0, i, i + 1, SMALL_CHAR, MIDDLE_CHAR); do_test (0, i, i + 1, SMALL_CHAR, BIG_CHAR); } for (i = 1; i < 8; ++i) { do_test (0, 16 << i, 2048, 0, MIDDLE_CHAR); do_test (i, 16 << i, 2048, 0, MIDDLE_CHAR); } for (i = 1; i < 8; ++i) { do_test (i, 64, 256, 0, MIDDLE_CHAR); do_test (i, 64, 256, 0, BIG_CHAR); } for (i = 0; i < 32; ++i) { do_test (0, i, i + 1, 0, MIDDLE_CHAR); do_test (0, i, i + 1, 0, BIG_CHAR); } return ret; } #include "../test-skeleton.c"
VincentS/glibc
benchtests/bench-strchr.c
C
gpl-2.0
4,933
#ifndef __MAC80211_DRIVER_OPS #define __MAC80211_DRIVER_OPS #include <net/mac80211.h> #include "ieee80211_i.h" #include "driver-trace.h" static inline void check_sdata_in_driver(struct ieee80211_sub_if_data *sdata) { WARN_ON(!(sdata->flags & IEEE80211_SDATA_IN_DRIVER)); } static inline struct ieee80211_sub_if_data * get_bss_sdata(struct ieee80211_sub_if_data *sdata) { if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) sdata = container_of(sdata->bss, struct ieee80211_sub_if_data, u.ap); return sdata; } static inline void drv_tx(struct ieee80211_local *local, struct sk_buff *skb) { local->ops->tx(&local->hw, skb); } static inline void drv_tx_frags(struct ieee80211_local *local, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct sk_buff_head *skbs) { local->ops->tx_frags(&local->hw, vif, sta, skbs); } static inline int drv_start(struct ieee80211_local *local) { int ret; might_sleep(); trace_drv_start(local); local->started = true; smp_mb(); ret = local->ops->start(&local->hw); trace_drv_return_int(local, ret); return ret; } static inline void drv_stop(struct ieee80211_local *local) { might_sleep(); trace_drv_stop(local); local->ops->stop(&local->hw); trace_drv_return_void(local); /* */ tasklet_disable(&local->tasklet); tasklet_enable(&local->tasklet); barrier(); local->started = false; } #ifdef CONFIG_PM static inline int drv_suspend(struct ieee80211_local *local, struct cfg80211_wowlan *wowlan) { int ret; might_sleep(); trace_drv_suspend(local); ret = local->ops->suspend(&local->hw, wowlan); trace_drv_return_int(local, ret); return ret; } static inline int drv_resume(struct ieee80211_local *local) { int ret; might_sleep(); trace_drv_resume(local); ret = local->ops->resume(&local->hw); trace_drv_return_int(local, ret); return ret; } #endif static inline int drv_add_interface(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { int ret; might_sleep(); if (WARN_ON(sdata->vif.type == NL80211_IFTYPE_AP_VLAN || sdata->vif.type == NL80211_IFTYPE_MONITOR)) return -EINVAL; trace_drv_add_interface(local, sdata); ret = local->ops->add_interface(&local->hw, &sdata->vif); trace_drv_return_int(local, ret); if (ret == 0) sdata->flags |= IEEE80211_SDATA_IN_DRIVER; return ret; } static inline int drv_change_interface(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, enum nl80211_iftype type, bool p2p) { int ret; might_sleep(); check_sdata_in_driver(sdata); trace_drv_change_interface(local, sdata, type, p2p); ret = local->ops->change_interface(&local->hw, &sdata->vif, type, p2p); trace_drv_return_int(local, ret); return ret; } static inline void drv_remove_interface(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { might_sleep(); check_sdata_in_driver(sdata); trace_drv_remove_interface(local, sdata); local->ops->remove_interface(&local->hw, &sdata->vif); sdata->flags &= ~IEEE80211_SDATA_IN_DRIVER; trace_drv_return_void(local); } static inline int drv_config(struct ieee80211_local *local, u32 changed) { int ret; might_sleep(); trace_drv_config(local, changed); ret = local->ops->config(&local->hw, changed); trace_drv_return_int(local, ret); return ret; } static inline void drv_bss_info_changed(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_bss_conf *info, u32 changed) { might_sleep(); check_sdata_in_driver(sdata); trace_drv_bss_info_changed(local, sdata, info, changed); if (local->ops->bss_info_changed) local->ops->bss_info_changed(&local->hw, &sdata->vif, info, changed); trace_drv_return_void(local); } static inline u64 drv_prepare_multicast(struct ieee80211_local *local, struct netdev_hw_addr_list *mc_list) { u64 ret = 0; trace_drv_prepare_multicast(local, mc_list->count); if (local->ops->prepare_multicast) ret = local->ops->prepare_multicast(&local->hw, mc_list); trace_drv_return_u64(local, ret); return ret; } static inline void drv_configure_filter(struct ieee80211_local *local, unsigned int changed_flags, unsigned int *total_flags, u64 multicast) { might_sleep(); trace_drv_configure_filter(local, changed_flags, total_flags, multicast); local->ops->configure_filter(&local->hw, changed_flags, total_flags, multicast); trace_drv_return_void(local); } static inline int drv_set_tim(struct ieee80211_local *local, struct ieee80211_sta *sta, bool set) { int ret = 0; trace_drv_set_tim(local, sta, set); if (local->ops->set_tim) ret = local->ops->set_tim(&local->hw, sta, set); trace_drv_return_int(local, ret); return ret; } static inline int drv_set_key(struct ieee80211_local *local, enum set_key_cmd cmd, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta, struct ieee80211_key_conf *key) { int ret; might_sleep(); sdata = get_bss_sdata(sdata); check_sdata_in_driver(sdata); trace_drv_set_key(local, cmd, sdata, sta, key); ret = local->ops->set_key(&local->hw, cmd, &sdata->vif, sta, key); trace_drv_return_int(local, ret); return ret; } static inline void drv_update_tkip_key(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_key_conf *conf, struct sta_info *sta, u32 iv32, u16 *phase1key) { struct ieee80211_sta *ista = NULL; if (sta) ista = &sta->sta; sdata = get_bss_sdata(sdata); check_sdata_in_driver(sdata); trace_drv_update_tkip_key(local, sdata, conf, ista, iv32); if (local->ops->update_tkip_key) local->ops->update_tkip_key(&local->hw, &sdata->vif, conf, ista, iv32, phase1key); trace_drv_return_void(local); } static inline int drv_hw_scan(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct cfg80211_scan_request *req) { int ret; might_sleep(); check_sdata_in_driver(sdata); trace_drv_hw_scan(local, sdata); ret = local->ops->hw_scan(&local->hw, &sdata->vif, req); trace_drv_return_int(local, ret); return ret; } static inline void drv_cancel_hw_scan(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { might_sleep(); check_sdata_in_driver(sdata); trace_drv_cancel_hw_scan(local, sdata); local->ops->cancel_hw_scan(&local->hw, &sdata->vif); trace_drv_return_void(local); } static inline int drv_sched_scan_start(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct cfg80211_sched_scan_request *req, struct ieee80211_sched_scan_ies *ies) { int ret; might_sleep(); check_sdata_in_driver(sdata); trace_drv_sched_scan_start(local, sdata); ret = local->ops->sched_scan_start(&local->hw, &sdata->vif, req, ies); trace_drv_return_int(local, ret); return ret; } static inline void drv_sched_scan_stop(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { might_sleep(); check_sdata_in_driver(sdata); trace_drv_sched_scan_stop(local, sdata); local->ops->sched_scan_stop(&local->hw, &sdata->vif); trace_drv_return_void(local); } static inline void drv_sw_scan_start(struct ieee80211_local *local) { might_sleep(); trace_drv_sw_scan_start(local); if (local->ops->sw_scan_start) local->ops->sw_scan_start(&local->hw); trace_drv_return_void(local); } static inline void drv_sw_scan_complete(struct ieee80211_local *local) { might_sleep(); trace_drv_sw_scan_complete(local); if (local->ops->sw_scan_complete) local->ops->sw_scan_complete(&local->hw); trace_drv_return_void(local); } static inline int drv_get_stats(struct ieee80211_local *local, struct ieee80211_low_level_stats *stats) { int ret = -EOPNOTSUPP; might_sleep(); if (local->ops->get_stats) ret = local->ops->get_stats(&local->hw, stats); trace_drv_get_stats(local, stats, ret); return ret; } static inline void drv_get_tkip_seq(struct ieee80211_local *local, u8 hw_key_idx, u32 *iv32, u16 *iv16) { if (local->ops->get_tkip_seq) local->ops->get_tkip_seq(&local->hw, hw_key_idx, iv32, iv16); trace_drv_get_tkip_seq(local, hw_key_idx, iv32, iv16); } static inline int drv_set_frag_threshold(struct ieee80211_local *local, u32 value) { int ret = 0; might_sleep(); trace_drv_set_frag_threshold(local, value); if (local->ops->set_frag_threshold) ret = local->ops->set_frag_threshold(&local->hw, value); trace_drv_return_int(local, ret); return ret; } static inline int drv_set_rts_threshold(struct ieee80211_local *local, u32 value) { int ret = 0; might_sleep(); trace_drv_set_rts_threshold(local, value); if (local->ops->set_rts_threshold) ret = local->ops->set_rts_threshold(&local->hw, value); trace_drv_return_int(local, ret); return ret; } static inline int drv_set_coverage_class(struct ieee80211_local *local, u8 value) { int ret = 0; might_sleep(); trace_drv_set_coverage_class(local, value); if (local->ops->set_coverage_class) local->ops->set_coverage_class(&local->hw, value); else ret = -EOPNOTSUPP; trace_drv_return_int(local, ret); return ret; } static inline void drv_sta_notify(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, enum sta_notify_cmd cmd, struct ieee80211_sta *sta) { sdata = get_bss_sdata(sdata); check_sdata_in_driver(sdata); trace_drv_sta_notify(local, sdata, cmd, sta); if (local->ops->sta_notify) local->ops->sta_notify(&local->hw, &sdata->vif, cmd, sta); trace_drv_return_void(local); } static inline int drv_sta_add(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta) { int ret = 0; might_sleep(); sdata = get_bss_sdata(sdata); check_sdata_in_driver(sdata); trace_drv_sta_add(local, sdata, sta); if (local->ops->sta_add) ret = local->ops->sta_add(&local->hw, &sdata->vif, sta); trace_drv_return_int(local, ret); return ret; } static inline void drv_sta_remove(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct ieee80211_sta *sta) { might_sleep(); sdata = get_bss_sdata(sdata); check_sdata_in_driver(sdata); trace_drv_sta_remove(local, sdata, sta); if (local->ops->sta_remove) local->ops->sta_remove(&local->hw, &sdata->vif, sta); trace_drv_return_void(local); } static inline __must_check int drv_sta_state(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct sta_info *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state) { int ret = 0; might_sleep(); sdata = get_bss_sdata(sdata); check_sdata_in_driver(sdata); trace_drv_sta_state(local, sdata, &sta->sta, old_state, new_state); if (local->ops->sta_state) { ret = local->ops->sta_state(&local->hw, &sdata->vif, &sta->sta, old_state, new_state); } else if (old_state == IEEE80211_STA_AUTH && new_state == IEEE80211_STA_ASSOC) { ret = drv_sta_add(local, sdata, &sta->sta); if (ret == 0) sta->uploaded = true; } else if (old_state == IEEE80211_STA_ASSOC && new_state == IEEE80211_STA_AUTH) { drv_sta_remove(local, sdata, &sta->sta); } trace_drv_return_int(local, ret); return ret; } static inline int drv_conf_tx(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, u16 queue, const struct ieee80211_tx_queue_params *params) { int ret = -EOPNOTSUPP; might_sleep(); check_sdata_in_driver(sdata); trace_drv_conf_tx(local, sdata, queue, params); if (local->ops->conf_tx) ret = local->ops->conf_tx(&local->hw, &sdata->vif, queue, params); trace_drv_return_int(local, ret); return ret; } static inline u64 drv_get_tsf(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { u64 ret = -1ULL; might_sleep(); check_sdata_in_driver(sdata); trace_drv_get_tsf(local, sdata); if (local->ops->get_tsf) ret = local->ops->get_tsf(&local->hw, &sdata->vif); trace_drv_return_u64(local, ret); return ret; } static inline void drv_set_tsf(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, u64 tsf) { might_sleep(); check_sdata_in_driver(sdata); trace_drv_set_tsf(local, sdata, tsf); if (local->ops->set_tsf) local->ops->set_tsf(&local->hw, &sdata->vif, tsf); trace_drv_return_void(local); } static inline void drv_reset_tsf(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata) { might_sleep(); check_sdata_in_driver(sdata); trace_drv_reset_tsf(local, sdata); if (local->ops->reset_tsf) local->ops->reset_tsf(&local->hw, &sdata->vif); trace_drv_return_void(local); } static inline int drv_tx_last_beacon(struct ieee80211_local *local) { int ret = 0; /* */ might_sleep(); trace_drv_tx_last_beacon(local); if (local->ops->tx_last_beacon) ret = local->ops->tx_last_beacon(&local->hw); trace_drv_return_int(local, ret); return ret; } static inline int drv_ampdu_action(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, enum ieee80211_ampdu_mlme_action action, struct ieee80211_sta *sta, u16 tid, u16 *ssn, u8 buf_size) { int ret = -EOPNOTSUPP; might_sleep(); sdata = get_bss_sdata(sdata); check_sdata_in_driver(sdata); trace_drv_ampdu_action(local, sdata, action, sta, tid, ssn, buf_size); if (local->ops->ampdu_action) ret = local->ops->ampdu_action(&local->hw, &sdata->vif, action, sta, tid, ssn, buf_size); trace_drv_return_int(local, ret); return ret; } static inline int drv_get_survey(struct ieee80211_local *local, int idx, struct survey_info *survey) { int ret = -EOPNOTSUPP; trace_drv_get_survey(local, idx, survey); if (local->ops->get_survey) ret = local->ops->get_survey(&local->hw, idx, survey); trace_drv_return_int(local, ret); return ret; } static inline void drv_rfkill_poll(struct ieee80211_local *local) { might_sleep(); if (local->ops->rfkill_poll) local->ops->rfkill_poll(&local->hw); } static inline void drv_flush(struct ieee80211_local *local, bool drop) { might_sleep(); trace_drv_flush(local, drop); if (local->ops->flush) local->ops->flush(&local->hw, drop); trace_drv_return_void(local); } static inline void drv_channel_switch(struct ieee80211_local *local, struct ieee80211_channel_switch *ch_switch) { might_sleep(); trace_drv_channel_switch(local, ch_switch); local->ops->channel_switch(&local->hw, ch_switch); trace_drv_return_void(local); } static inline int drv_set_antenna(struct ieee80211_local *local, u32 tx_ant, u32 rx_ant) { int ret = -EOPNOTSUPP; might_sleep(); if (local->ops->set_antenna) ret = local->ops->set_antenna(&local->hw, tx_ant, rx_ant); trace_drv_set_antenna(local, tx_ant, rx_ant, ret); return ret; } static inline int drv_get_antenna(struct ieee80211_local *local, u32 *tx_ant, u32 *rx_ant) { int ret = -EOPNOTSUPP; might_sleep(); if (local->ops->get_antenna) ret = local->ops->get_antenna(&local->hw, tx_ant, rx_ant); trace_drv_get_antenna(local, *tx_ant, *rx_ant, ret); return ret; } static inline int drv_remain_on_channel(struct ieee80211_local *local, struct ieee80211_channel *chan, enum nl80211_channel_type chantype, unsigned int duration) { int ret; might_sleep(); trace_drv_remain_on_channel(local, chan, chantype, duration); ret = local->ops->remain_on_channel(&local->hw, chan, chantype, duration); trace_drv_return_int(local, ret); return ret; } static inline int drv_cancel_remain_on_channel(struct ieee80211_local *local) { int ret; might_sleep(); trace_drv_cancel_remain_on_channel(local); ret = local->ops->cancel_remain_on_channel(&local->hw); trace_drv_return_int(local, ret); return ret; } static inline int drv_set_ringparam(struct ieee80211_local *local, u32 tx, u32 rx) { int ret = -ENOTSUPP; might_sleep(); trace_drv_set_ringparam(local, tx, rx); if (local->ops->set_ringparam) ret = local->ops->set_ringparam(&local->hw, tx, rx); trace_drv_return_int(local, ret); return ret; } static inline void drv_get_ringparam(struct ieee80211_local *local, u32 *tx, u32 *tx_max, u32 *rx, u32 *rx_max) { might_sleep(); trace_drv_get_ringparam(local, tx, tx_max, rx, rx_max); if (local->ops->get_ringparam) local->ops->get_ringparam(&local->hw, tx, tx_max, rx, rx_max); trace_drv_return_void(local); } static inline bool drv_tx_frames_pending(struct ieee80211_local *local) { bool ret = false; might_sleep(); trace_drv_tx_frames_pending(local); if (local->ops->tx_frames_pending) ret = local->ops->tx_frames_pending(&local->hw); trace_drv_return_bool(local, ret); return ret; } static inline int drv_set_bitrate_mask(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, const struct cfg80211_bitrate_mask *mask) { int ret = -EOPNOTSUPP; might_sleep(); check_sdata_in_driver(sdata); trace_drv_set_bitrate_mask(local, sdata, mask); if (local->ops->set_bitrate_mask) ret = local->ops->set_bitrate_mask(&local->hw, &sdata->vif, mask); trace_drv_return_int(local, ret); return ret; } static inline void drv_set_rekey_data(struct ieee80211_local *local, struct ieee80211_sub_if_data *sdata, struct cfg80211_gtk_rekey_data *data) { check_sdata_in_driver(sdata); trace_drv_set_rekey_data(local, sdata, data); if (local->ops->set_rekey_data) local->ops->set_rekey_data(&local->hw, &sdata->vif, data); trace_drv_return_void(local); } static inline void drv_rssi_callback(struct ieee80211_local *local, const enum ieee80211_rssi_event event) { trace_drv_rssi_callback(local, event); if (local->ops->rssi_callback) local->ops->rssi_callback(&local->hw, event); trace_drv_return_void(local); } static inline void drv_release_buffered_frames(struct ieee80211_local *local, struct sta_info *sta, u16 tids, int num_frames, enum ieee80211_frame_release_type reason, bool more_data) { trace_drv_release_buffered_frames(local, &sta->sta, tids, num_frames, reason, more_data); if (local->ops->release_buffered_frames) local->ops->release_buffered_frames(&local->hw, &sta->sta, tids, num_frames, reason, more_data); trace_drv_return_void(local); } static inline void drv_allow_buffered_frames(struct ieee80211_local *local, struct sta_info *sta, u16 tids, int num_frames, enum ieee80211_frame_release_type reason, bool more_data) { trace_drv_allow_buffered_frames(local, &sta->sta, tids, num_frames, reason, more_data); if (local->ops->allow_buffered_frames) local->ops->allow_buffered_frames(&local->hw, &sta->sta, tids, num_frames, reason, more_data); trace_drv_return_void(local); } #endif /* */
holyangel/LGE_G3
net/mac80211/driver-ops.h
C
gpl-2.0
18,957
module.exports={A:{A:{"2":"J C G E B A UB"},B:{"2":"D Y g H L"},C:{"1":"3 m n o p q r s x","2":"0 1 4 5 SB y F I J C G E z u t QB PB","132":"L M N O P Q R S T U V W X v Z a b c d e f K h i j k l","164":"B A D Y g H"},D:{"1":"0 1 3 4 5 8 h i j k l m n o p q r s x z u t EB BB TB CB","2":"F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f","66":"K"},E:{"2":"9 F I J C G E B A DB FB GB HB IB JB KB"},F:{"1":"U V W X v Z a b c d e f K h i j k l m n o p q r s","2":"6 7 E A D H L M N O P Q R S T LB MB NB OB RB w"},G:{"2":"2 9 G A AB VB WB XB YB ZB aB bB cB"},H:{"2":"dB"},I:{"1":"t","2":"2 y F eB fB gB hB iB jB"},J:{"2":"C B"},K:{"1":"K","2":"6 7 B A D w"},L:{"1":"8"},M:{"1":"u"},N:{"2":"B A"},O:{"132":"kB"},P:{"1":"F I"},Q:{"2":"lB"},R:{"1":"mB"}},B:4,C:"Battery Status API"};
secatoriuris/vista-theme
themes/vista/node_modules/caniuse-lite/data/features/battery-status.js
JavaScript
gpl-2.0
793
/* * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.mirror.declaration; import com.sun.mirror.type.TypeMirror; import com.sun.mirror.type.VoidType; /** * Represents a method of a class or interface. * Note that an * {@linkplain AnnotationTypeElementDeclaration annotation type element} * is a kind of method. * * @author Joseph D. Darcy * @author Scott Seligman * @since 1.5 */ public interface MethodDeclaration extends ExecutableDeclaration { /** * Returns the formal return type of this method. * Returns {@link VoidType} if this method does not return a value. * * @return the formal return type of this method */ TypeMirror getReturnType(); }
lucasicf/metricgenerator-jdk-compiler
src/share/classes/com/sun/mirror/declaration/MethodDeclaration.java
Java
gpl-2.0
1,868
<?php /** * Get the resource groups as nodes * * @param string $id The ID of the parent node * * @package modx * @subpackage processors.security.documentgroup */ if (!$modx->hasPermission('access_permissions')) return $modx->error->failure($modx->lexicon('permission_denied')); $modx->lexicon->load('access'); /* setup default properties */ $isLimit = !empty($scriptProperties['limit']); $start = $modx->getOption('start',$scriptProperties,0); $limit = $modx->getOption('limit',$scriptProperties,10); $sort = $modx->getOption('sort',$scriptProperties,'name'); $dir = $modx->getOption('dir',$scriptProperties,'ASC'); /* get parent */ $scriptProperties['id'] = !isset($scriptProperties['id']) ? 0 : str_replace('n_dg_','',$scriptProperties['id']); $resourceGroup = $modx->getObject('modResourceGroup',$scriptProperties['id']); $c = $modx->newQuery('modResourceGroup'); $c->sortby($sort,$dir); if ($isLimit) $c->limit($limit,$start); $groups = $modx->getCollection('modResourceGroup',$c); $list = array(); if ($resourceGroup == null) { foreach ($groups as $group) { $menu = array(); $menu[] = array( 'text' => $modx->lexicon('resource_group_create'), 'handler' => 'function(itm,e) { this.create(itm,e); }', ); $menu[] = '-'; $menu[] = array( 'text' => $modx->lexicon('resource_group_remove'), 'handler' => 'function(itm,e) { this.remove(itm,e); }', ); $list[] = array( 'text' => $group->get('name'), 'id' => 'n_dg_'.$group->get('id'), 'leaf' => 0, 'type' => 'modResourceGroup', 'cls' => 'icon-resourcegroup', 'menu' => array('items' => $menu), ); } } else { $resources = $resourceGroup->getResources(); foreach ($resources as $resource) { $menu = array(); $menu[] = array( 'text' => $modx->lexicon('resource_group_access_remove'), 'handler' => 'function(itm,e) { this.removeResource(itm,e); }', ); $list[] = array( 'text' => $resource->get('pagetitle'), 'id' => 'n_'.$resource->get('id'), 'leaf' => 1, 'type' => 'modResource', 'cls' => 'icon-'.$resource->get('class_key'), 'menu' => array('items' => $menu), ); } } return $this->toJSON($list);
cameronscott137/rustbuilt
wp-content/themes/rustbuilt/core/model/modx/processors/security/documentgroup/getnodes.php
PHP
gpl-2.0
2,349
/* Copyright (c) 2008-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. * */ #ifndef MDSS_FB_H #define MDSS_FB_H #include <linux/msm_ion.h> #include <linux/list.h> #include <linux/msm_mdp.h> #include <linux/types.h> #include <linux/notifier.h> #include "mdss_panel.h" #define MSM_FB_DEFAULT_PAGE_SIZE 2 #define MFD_KEY 0x11161126 #define MSM_FB_MAX_DEV_LIST 32 #define MSM_FB_ENABLE_DBGFS #define WAIT_FENCE_FIRST_TIMEOUT (3 * MSEC_PER_SEC) #define WAIT_FENCE_FINAL_TIMEOUT (10 * MSEC_PER_SEC) /* Display op timeout should be greater than total timeout */ #define WAIT_DISP_OP_TIMEOUT ((WAIT_FENCE_FIRST_TIMEOUT + \ WAIT_FENCE_FINAL_TIMEOUT) * MDP_MAX_FENCE_FD) #define SPLASH_THREAD_WAIT_TIMEOUT 3 #ifndef MAX #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #endif #ifndef MIN #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #endif /** * enum mdp_notify_event - Different frame events to indicate frame update state * * @MDP_NOTIFY_FRAME_BEGIN: Frame update has started, the frame is about to * be programmed into hardware. * @MDP_NOTIFY_FRAME_READY: Frame ready to be kicked off, this can be used * as the last point in time to synchronized with * source buffers before kickoff. * @MDP_NOTIFY_FRAME_FLUSHED: Configuration of frame has been flushed and * DMA transfer has started. * @MDP_NOTIFY_FRAME_DONE: Frame DMA transfer has completed. * - For video mode panels this will indicate that * previous frame has been replaced by new one. * - For command mode/writeback frame done happens * as soon as the DMA of the frame is done. * @MDP_NOTIFY_FRAME_TIMEOUT: Frame DMA transfer has failed to complete within * a fair amount of time. */ enum mdp_notify_event { MDP_NOTIFY_FRAME_BEGIN = 1, MDP_NOTIFY_FRAME_READY, MDP_NOTIFY_FRAME_FLUSHED, MDP_NOTIFY_FRAME_DONE, MDP_NOTIFY_FRAME_TIMEOUT, }; enum mdp_splash_event { MDP_CREATE_SPLASH_OV = 0, MDP_REMOVE_SPLASH_OV, }; struct disp_info_type_suspend { int op_enable; int panel_power_on; }; struct disp_info_notify { int type; struct timer_list timer; struct completion comp; struct mutex lock; int value; int is_suspend; }; struct msm_sync_pt_data { char *fence_name; u32 acq_fen_cnt; struct sync_fence *acq_fen[MDP_MAX_FENCE_FD]; struct sw_sync_timeline *timeline; int timeline_value; u32 threshold; u32 retire_threshold; atomic_t commit_cnt; bool flushed; bool async_wait_fences; struct mutex sync_mutex; struct notifier_block notifier; struct sync_fence *(*get_retire_fence) (struct msm_sync_pt_data *sync_pt_data); }; struct msm_fb_data_type; struct msm_mdp_interface { int (*fb_mem_alloc_fnc)(struct msm_fb_data_type *mfd); int (*fb_mem_get_iommu_domain)(void); int (*init_fnc)(struct msm_fb_data_type *mfd); int (*on_fnc)(struct msm_fb_data_type *mfd); int (*off_fnc)(struct msm_fb_data_type *mfd); /* called to release resources associated to the process */ int (*release_fnc)(struct msm_fb_data_type *mfd, bool release_all); int (*kickoff_fnc)(struct msm_fb_data_type *mfd, struct mdp_display_commit *data); int (*ioctl_handler)(struct msm_fb_data_type *mfd, u32 cmd, void *arg); void (*dma_fnc)(struct msm_fb_data_type *mfd, struct mdp_overlay *req, int image_len, int *pipe_ndx); int (*cursor_update)(struct msm_fb_data_type *mfd, struct fb_cursor *cursor); #ifdef CONFIG_LCD_KCAL int (*lut_update)(struct msm_fb_data_type *mfd, struct fb_cmap *cmap, bool setup_hw); #else int (*lut_update)(struct msm_fb_data_type *mfd, struct fb_cmap *cmap); #endif int (*do_histogram)(struct msm_fb_data_type *mfd, struct mdp_histogram *hist); int (*update_ad_input)(struct msm_fb_data_type *mfd); int (*panel_register_done)(struct mdss_panel_data *pdata); u32 (*fb_stride)(u32 fb_index, u32 xres, int bpp); int (*splash_fnc) (struct msm_fb_data_type *mfd, int *index, int req); struct msm_sync_pt_data *(*get_sync_fnc)(struct msm_fb_data_type *mfd, const struct mdp_buf_sync *buf_sync); void (*check_dsi_status)(struct work_struct *work, uint32_t interval); void *private1; }; #define IS_CALIB_MODE_BL(mfd) (((mfd)->calib_mode) & MDSS_CALIB_MODE_BL) #define MDSS_BRIGHT_TO_BL(out, v, bl_max, max_bright) do {\ out = (2 * (v) * (bl_max) + max_bright)\ / (2 * max_bright);\ } while (0) struct mdss_fb_proc_info { int pid; u32 ref_cnt; struct list_head list; }; struct msm_fb_backup_type { struct fb_info info; struct mdp_display_commit disp_commit; }; struct msm_fb_data_type { u32 key; u32 index; u32 ref_cnt; u32 fb_page; struct panel_id panel; struct mdss_panel_info *panel_info; int split_display; int split_fb_left; int split_fb_right; u32 dest; struct fb_info *fbi; int idle_time; struct delayed_work idle_notify_work; int op_enable; u32 fb_imgType; int panel_reconfig; u32 dst_format; int panel_power_on; struct disp_info_type_suspend suspend; struct ion_handle *ihdl; unsigned long iova; void *cursor_buf; unsigned long cursor_buf_phys; unsigned long cursor_buf_iova; int ext_ad_ctrl; u32 ext_bl_ctrl; u32 calib_mode; u32 bl_level; u32 bl_scale; u32 bl_min_lvl; u32 unset_bl_level; u32 bl_updated; u32 bl_level_old; struct mutex bl_lock; struct mutex lock; struct platform_device *pdev; u32 mdp_fb_page_protection; struct disp_info_notify update; struct disp_info_notify no_update; struct completion power_off_comp; struct msm_mdp_interface mdp; struct msm_sync_pt_data mdp_sync_pt_data; /* for non-blocking */ struct task_struct *disp_thread; atomic_t commits_pending; wait_queue_head_t commit_wait_q; wait_queue_head_t idle_wait_q; bool shutdown_pending; struct task_struct *splash_thread; bool splash_logo_enabled; struct msm_fb_backup_type msm_fb_backup; struct completion power_set_comp; u32 is_power_setting; u32 dcm_state; struct list_head proc_list; }; static inline void mdss_fb_update_notify_update(struct msm_fb_data_type *mfd) { int needs_complete = 0; mutex_lock(&mfd->update.lock); mfd->update.value = mfd->update.type; needs_complete = mfd->update.value == NOTIFY_TYPE_UPDATE; mutex_unlock(&mfd->update.lock); if (needs_complete) { complete(&mfd->update.comp); mutex_lock(&mfd->no_update.lock); if (mfd->no_update.timer.function) del_timer(&(mfd->no_update.timer)); mfd->no_update.timer.expires = jiffies + (2 * HZ); add_timer(&mfd->no_update.timer); mutex_unlock(&mfd->no_update.lock); } } int mdss_fb_get_phys_info(unsigned long *start, unsigned long *len, int fb_num); void mdss_fb_set_backlight(struct msm_fb_data_type *mfd, u32 bkl_lvl); void mdss_fb_update_backlight(struct msm_fb_data_type *mfd); void mdss_fb_wait_for_fence(struct msm_sync_pt_data *sync_pt_data); void mdss_fb_signal_timeline(struct msm_sync_pt_data *sync_pt_data); struct sync_fence *mdss_fb_sync_get_fence(struct sw_sync_timeline *timeline, const char *fence_name, int val); int mdss_fb_register_mdp_instance(struct msm_mdp_interface *mdp); int mdss_fb_dcm(struct msm_fb_data_type *mfd, int req_state); #endif /* MDSS_FB_H */
zombah/android_kernel_nokia_msm8610
drivers/video/msm/mdss/mdss_fb.h
C
gpl-2.0
7,490
/* * Cirrus Logic CS42448/CS42888 Audio CODEC Digital Audio Interface (DAI) driver * * Copyright (C) 2014 Freescale Semiconductor, Inc. * * Author: Nicolin Chen <Guangyu.Chen@freescale.com> * * This file is licensed under the terms of the GNU General Public License * version 2. This program is licensed "as is" without any warranty of any * kind, whether express or implied. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/of_device.h> #include <linux/pm_runtime.h> #include <linux/regulator/consumer.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/tlv.h> #include "cs42xx8.h" #define CS42XX8_NUM_SUPPLIES 4 static const char *const cs42xx8_supply_names[CS42XX8_NUM_SUPPLIES] = { "VA", "VD", "VLS", "VLC", }; #define CS42XX8_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | \ SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE | \ SNDRV_PCM_FMTBIT_S32_LE) /* codec private data */ struct cs42xx8_priv { struct regulator_bulk_data supplies[CS42XX8_NUM_SUPPLIES]; const struct cs42xx8_driver_data *drvdata; struct regmap *regmap; struct clk *clk; bool slave_mode; unsigned long sysclk; int rate[2]; }; /* -127.5dB to 0dB with step of 0.5dB */ static const DECLARE_TLV_DB_SCALE(dac_tlv, -12750, 50, 1); /* -64dB to 24dB with step of 0.5dB */ static const DECLARE_TLV_DB_SCALE(adc_tlv, -6400, 50, 0); static const char *const cs42xx8_adc_single[] = { "Differential", "Single-Ended" }; static const char *const cs42xx8_szc[] = { "Immediate Change", "Zero Cross", "Soft Ramp", "Soft Ramp on Zero Cross" }; static const struct soc_enum adc1_single_enum = SOC_ENUM_SINGLE(CS42XX8_ADCCTL, 4, 2, cs42xx8_adc_single); static const struct soc_enum adc2_single_enum = SOC_ENUM_SINGLE(CS42XX8_ADCCTL, 3, 2, cs42xx8_adc_single); static const struct soc_enum adc3_single_enum = SOC_ENUM_SINGLE(CS42XX8_ADCCTL, 2, 2, cs42xx8_adc_single); static const struct soc_enum dac_szc_enum = SOC_ENUM_SINGLE(CS42XX8_TXCTL, 5, 4, cs42xx8_szc); static const struct soc_enum adc_szc_enum = SOC_ENUM_SINGLE(CS42XX8_TXCTL, 0, 4, cs42xx8_szc); static const struct snd_kcontrol_new cs42xx8_snd_controls[] = { SOC_DOUBLE_R_TLV("DAC1 Playback Volume", CS42XX8_VOLAOUT1, CS42XX8_VOLAOUT2, 0, 0xff, 1, dac_tlv), SOC_DOUBLE_R_TLV("DAC2 Playback Volume", CS42XX8_VOLAOUT3, CS42XX8_VOLAOUT4, 0, 0xff, 1, dac_tlv), SOC_DOUBLE_R_TLV("DAC3 Playback Volume", CS42XX8_VOLAOUT5, CS42XX8_VOLAOUT6, 0, 0xff, 1, dac_tlv), SOC_DOUBLE_R_TLV("DAC4 Playback Volume", CS42XX8_VOLAOUT7, CS42XX8_VOLAOUT8, 0, 0xff, 1, dac_tlv), SOC_DOUBLE_R_S_TLV("ADC1 Capture Volume", CS42XX8_VOLAIN1, CS42XX8_VOLAIN2, 0, -0x80, 0x30, 7, 0, adc_tlv), SOC_DOUBLE_R_S_TLV("ADC2 Capture Volume", CS42XX8_VOLAIN3, CS42XX8_VOLAIN4, 0, -0x80, 0x30, 7, 0, adc_tlv), SOC_DOUBLE("DAC1 Invert Switch", CS42XX8_DACINV, 0, 1, 1, 0), SOC_DOUBLE("DAC2 Invert Switch", CS42XX8_DACINV, 2, 3, 1, 0), SOC_DOUBLE("DAC3 Invert Switch", CS42XX8_DACINV, 4, 5, 1, 0), SOC_DOUBLE("DAC4 Invert Switch", CS42XX8_DACINV, 6, 7, 1, 0), SOC_DOUBLE("ADC1 Invert Switch", CS42XX8_ADCINV, 0, 1, 1, 0), SOC_DOUBLE("ADC2 Invert Switch", CS42XX8_ADCINV, 2, 3, 1, 0), SOC_SINGLE("ADC High-Pass Filter Switch", CS42XX8_ADCCTL, 7, 1, 1), SOC_SINGLE("DAC De-emphasis Switch", CS42XX8_ADCCTL, 5, 1, 0), SOC_ENUM("ADC1 Single Ended Mode Switch", adc1_single_enum), SOC_ENUM("ADC2 Single Ended Mode Switch", adc2_single_enum), SOC_SINGLE("DAC Single Volume Control Switch", CS42XX8_TXCTL, 7, 1, 0), SOC_ENUM("DAC Soft Ramp & Zero Cross Control Switch", dac_szc_enum), SOC_SINGLE("DAC Auto Mute Switch", CS42XX8_TXCTL, 4, 1, 0), SOC_SINGLE("Mute ADC Serial Port Switch", CS42XX8_TXCTL, 3, 1, 0), SOC_SINGLE("ADC Single Volume Control Switch", CS42XX8_TXCTL, 2, 1, 0), SOC_ENUM("ADC Soft Ramp & Zero Cross Control Switch", adc_szc_enum), }; static const struct snd_kcontrol_new cs42xx8_adc3_snd_controls[] = { SOC_DOUBLE_R_S_TLV("ADC3 Capture Volume", CS42XX8_VOLAIN5, CS42XX8_VOLAIN6, 0, -0x80, 0x30, 7, 0, adc_tlv), SOC_DOUBLE("ADC3 Invert Switch", CS42XX8_ADCINV, 4, 5, 1, 0), SOC_ENUM("ADC3 Single Ended Mode Switch", adc3_single_enum), }; static const struct snd_soc_dapm_widget cs42xx8_dapm_widgets[] = { SND_SOC_DAPM_DAC("DAC1", "Playback", CS42XX8_PWRCTL, 1, 1), SND_SOC_DAPM_DAC("DAC2", "Playback", CS42XX8_PWRCTL, 2, 1), SND_SOC_DAPM_DAC("DAC3", "Playback", CS42XX8_PWRCTL, 3, 1), SND_SOC_DAPM_DAC("DAC4", "Playback", CS42XX8_PWRCTL, 4, 1), SND_SOC_DAPM_OUTPUT("AOUT1L"), SND_SOC_DAPM_OUTPUT("AOUT1R"), SND_SOC_DAPM_OUTPUT("AOUT2L"), SND_SOC_DAPM_OUTPUT("AOUT2R"), SND_SOC_DAPM_OUTPUT("AOUT3L"), SND_SOC_DAPM_OUTPUT("AOUT3R"), SND_SOC_DAPM_OUTPUT("AOUT4L"), SND_SOC_DAPM_OUTPUT("AOUT4R"), SND_SOC_DAPM_ADC("ADC1", "Capture", CS42XX8_PWRCTL, 5, 1), SND_SOC_DAPM_ADC("ADC2", "Capture", CS42XX8_PWRCTL, 6, 1), SND_SOC_DAPM_INPUT("AIN1L"), SND_SOC_DAPM_INPUT("AIN1R"), SND_SOC_DAPM_INPUT("AIN2L"), SND_SOC_DAPM_INPUT("AIN2R"), SND_SOC_DAPM_PGA_E("PWR", CS42XX8_PWRCTL, 0, 1, NULL, 0, NULL, 0), }; static const struct snd_soc_dapm_widget cs42xx8_adc3_dapm_widgets[] = { SND_SOC_DAPM_ADC("ADC3", "Capture", CS42XX8_PWRCTL, 7, 1), SND_SOC_DAPM_INPUT("AIN3L"), SND_SOC_DAPM_INPUT("AIN3R"), }; static const struct snd_soc_dapm_route cs42xx8_dapm_routes[] = { /* Playback */ { "PWR", NULL, "DAC1" }, { "PWR", NULL, "DAC1" }, { "PWR", NULL, "DAC2" }, { "PWR", NULL, "DAC2" }, { "PWR", NULL, "DAC3" }, { "PWR", NULL, "DAC3" }, { "PWR", NULL, "DAC4" }, { "PWR", NULL, "DAC4" }, { "AOUT1L", NULL, "PWR" }, { "AOUT1R", NULL, "PWR" }, { "AOUT2L", NULL, "PWR" }, { "AOUT2R", NULL, "PWR" }, { "AOUT3L", NULL, "PWR" }, { "AOUT3R", NULL, "PWR" }, { "AOUT4L", NULL, "PWR" }, { "AOUT4R", NULL, "PWR" }, /* Capture */ { "PWR", NULL, "AIN1L" }, { "PWR", NULL, "AIN1R" }, { "PWR", NULL, "AIN2L" }, { "PWR", NULL, "AIN2R" }, { "ADC1", NULL, "PWR" }, { "ADC1", NULL, "PWR" }, { "ADC2", NULL, "PWR" }, { "ADC2", NULL, "PWR" }, }; static const struct snd_soc_dapm_route cs42xx8_adc3_dapm_routes[] = { /* Capture */ { "ADC3", NULL, "AIN3L" }, { "ADC3", NULL, "AIN3R" }, { "ADC3", NULL, "PWR" }, }; struct cs42xx8_ratios { unsigned int mfreq; unsigned int min_mclk; unsigned int max_mclk; unsigned int ratio[3]; }; static const struct cs42xx8_ratios cs42xx8_ratios[] = { { 0, 1029000, 12800000, {256, 128, 64} }, { 2, 1536000, 19200000, {384, 192, 96} }, { 4, 2048000, 25600000, {512, 256, 128} }, { 6, 3072000, 38400000, {768, 384, 192} }, { 8, 4096000, 51200000, {1024, 512, 256} }, }; static int cs42xx8_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = codec_dai->codec; struct cs42xx8_priv *cs42xx8 = snd_soc_codec_get_drvdata(codec); cs42xx8->sysclk = freq; return 0; } static int cs42xx8_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int format) { struct snd_soc_codec *codec = codec_dai->codec; struct cs42xx8_priv *cs42xx8 = snd_soc_codec_get_drvdata(codec); u32 val; /* Set DAI format */ switch (format & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_LEFT_J: val = CS42XX8_INTF_DAC_DIF_LEFTJ | CS42XX8_INTF_ADC_DIF_LEFTJ; break; case SND_SOC_DAIFMT_I2S: val = CS42XX8_INTF_DAC_DIF_I2S | CS42XX8_INTF_ADC_DIF_I2S; break; case SND_SOC_DAIFMT_RIGHT_J: val = CS42XX8_INTF_DAC_DIF_RIGHTJ | CS42XX8_INTF_ADC_DIF_RIGHTJ; break; case SND_SOC_DAIFMT_DSP_A: val = CS42XX8_INTF_DAC_DIF_TDM | CS42XX8_INTF_ADC_DIF_TDM; break; default: dev_err(codec->dev, "unsupported dai format\n"); return -EINVAL; } regmap_update_bits(cs42xx8->regmap, CS42XX8_INTF, CS42XX8_INTF_DAC_DIF_MASK | CS42XX8_INTF_ADC_DIF_MASK, val); /* Set master/slave audio interface */ switch (format & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: cs42xx8->slave_mode = true; break; case SND_SOC_DAIFMT_CBM_CFM: cs42xx8->slave_mode = false; break; default: dev_err(codec->dev, "unsupported master/slave mode\n"); return -EINVAL; } return 0; } static int cs42xx8_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct cs42xx8_priv *cs42xx8 = snd_soc_codec_get_drvdata(codec); bool tx = substream->stream == SNDRV_PCM_STREAM_PLAYBACK; u32 rate = params_rate(params); u32 ratio_tx, ratio_rx; u32 rate_tx, rate_rx; u32 fm_tx, fm_rx; u32 i, fm, val, mask; rate_tx = tx ? rate : cs42xx8->rate[0]; rate_rx = tx ? cs42xx8->rate[1] : rate; ratio_tx = rate_tx > 0 ? cs42xx8->sysclk / rate_tx : 0; ratio_rx = rate_rx > 0 ? cs42xx8->sysclk / rate_rx : 0; if (cs42xx8->slave_mode) { fm_rx = CS42XX8_FM_AUTO; fm_tx = CS42XX8_FM_AUTO; } else { if (rate_tx >= 0 && rate_tx < 50000) fm_tx = CS42XX8_FM_SINGLE; else if (rate_tx > 50000 && rate_tx < 100000) fm_tx = CS42XX8_FM_DOUBLE; else if (rate_tx > 100000 && rate_tx < 200000) fm_tx = CS42XX8_FM_QUAD; else { dev_err(codec->dev, "unsupported sample rate or rate combine\n"); return -EINVAL; } if (rate_rx >= 0 && rate_rx < 50000) fm_rx = CS42XX8_FM_SINGLE; else if (rate_rx > 50000 && rate_rx < 100000) fm_rx = CS42XX8_FM_DOUBLE; else if (rate_rx > 100000 && rate_rx < 200000) fm_rx = CS42XX8_FM_QUAD; else { dev_err(codec->dev, "unsupported sample rate or rate combine\n"); return -EINVAL; } } fm = tx ? fm_tx : fm_rx; if (fm == CS42XX8_FM_AUTO) { for (i = 0; i < ARRAY_SIZE(cs42xx8_ratios); i++) { if ((ratio_tx > 0 ? (cs42xx8_ratios[i].ratio[0] == ratio_tx || cs42xx8_ratios[i].ratio[1] == ratio_tx || cs42xx8_ratios[i].ratio[2] == ratio_tx) : true) && (ratio_rx > 0 ? (cs42xx8_ratios[i].ratio[0] == ratio_rx || cs42xx8_ratios[i].ratio[1] == ratio_rx || cs42xx8_ratios[i].ratio[2] == ratio_rx) : true) && cs42xx8->sysclk >= cs42xx8_ratios[i].min_mclk && cs42xx8->sysclk <= cs42xx8_ratios[i].max_mclk) break; } } else { for (i = 0; i < ARRAY_SIZE(cs42xx8_ratios); i++) { if ((ratio_tx > 0 ? (cs42xx8_ratios[i].ratio[fm_tx] == ratio_tx) : true) && (ratio_rx > 0 ? (cs42xx8_ratios[i].ratio[fm_rx] == ratio_rx) : true) && cs42xx8->sysclk >= cs42xx8_ratios[i].min_mclk && cs42xx8->sysclk <= cs42xx8_ratios[i].max_mclk) break; } } if (i == ARRAY_SIZE(cs42xx8_ratios)) { dev_err(codec->dev, "unsupported sysclk ratio\n"); return -EINVAL; } cs42xx8->rate[substream->stream] = rate; mask = CS42XX8_FUNCMOD_MFREQ_MASK; val = cs42xx8_ratios[i].mfreq; regmap_update_bits(cs42xx8->regmap, CS42XX8_FUNCMOD, CS42XX8_FUNCMOD_xC_FM_MASK(tx) | mask, CS42XX8_FUNCMOD_xC_FM(tx, fm) | val); return 0; } static int cs42xx8_hw_free(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct cs42xx8_priv *cs42xx8 = snd_soc_codec_get_drvdata(codec); bool tx = substream->stream == SNDRV_PCM_STREAM_PLAYBACK; cs42xx8->rate[substream->stream] = 0; regmap_update_bits(cs42xx8->regmap, CS42XX8_FUNCMOD, CS42XX8_FUNCMOD_xC_FM_MASK(tx), CS42XX8_FUNCMOD_xC_FM(tx, CS42XX8_FM_AUTO)); return 0; } static int cs42xx8_digital_mute(struct snd_soc_dai *dai, int mute) { struct snd_soc_codec *codec = dai->codec; struct cs42xx8_priv *cs42xx8 = snd_soc_codec_get_drvdata(codec); regmap_update_bits(cs42xx8->regmap, CS42XX8_DACMUTE, CS42XX8_DACMUTE_ALL, mute ? CS42XX8_DACMUTE_ALL : 0); return 0; } static const struct snd_soc_dai_ops cs42xx8_dai_ops = { .set_fmt = cs42xx8_set_dai_fmt, .set_sysclk = cs42xx8_set_dai_sysclk, .hw_params = cs42xx8_hw_params, .hw_free = cs42xx8_hw_free, .digital_mute = cs42xx8_digital_mute, }; static struct snd_soc_dai_driver cs42xx8_dai = { .playback = { .stream_name = "Playback", .channels_min = 1, .channels_max = 8, .rates = SNDRV_PCM_RATE_8000_192000, .formats = CS42XX8_FORMATS, }, .capture = { .stream_name = "Capture", .channels_min = 1, .rates = SNDRV_PCM_RATE_8000_192000, .formats = CS42XX8_FORMATS, }, .ops = &cs42xx8_dai_ops, }; static const struct reg_default cs42xx8_reg[] = { { 0x01, 0x01 }, /* Chip I.D. and Revision Register */ { 0x02, 0x00 }, /* Power Control */ { 0x03, 0xF0 }, /* Functional Mode */ { 0x04, 0x46 }, /* Interface Formats */ { 0x05, 0x00 }, /* ADC Control & DAC De-Emphasis */ { 0x06, 0x10 }, /* Transition Control */ { 0x07, 0x00 }, /* DAC Channel Mute */ { 0x08, 0x00 }, /* Volume Control AOUT1 */ { 0x09, 0x00 }, /* Volume Control AOUT2 */ { 0x0a, 0x00 }, /* Volume Control AOUT3 */ { 0x0b, 0x00 }, /* Volume Control AOUT4 */ { 0x0c, 0x00 }, /* Volume Control AOUT5 */ { 0x0d, 0x00 }, /* Volume Control AOUT6 */ { 0x0e, 0x00 }, /* Volume Control AOUT7 */ { 0x0f, 0x00 }, /* Volume Control AOUT8 */ { 0x10, 0x00 }, /* DAC Channel Invert */ { 0x11, 0x00 }, /* Volume Control AIN1 */ { 0x12, 0x00 }, /* Volume Control AIN2 */ { 0x13, 0x00 }, /* Volume Control AIN3 */ { 0x14, 0x00 }, /* Volume Control AIN4 */ { 0x15, 0x00 }, /* Volume Control AIN5 */ { 0x16, 0x00 }, /* Volume Control AIN6 */ { 0x17, 0x00 }, /* ADC Channel Invert */ { 0x18, 0x00 }, /* Status Control */ { 0x1a, 0x00 }, /* Status Mask */ { 0x1b, 0x00 }, /* MUTEC Pin Control */ }; static bool cs42xx8_volatile_register(struct device *dev, unsigned int reg) { switch (reg) { case CS42XX8_STATUS: return true; default: return false; } } static bool cs42xx8_writeable_register(struct device *dev, unsigned int reg) { switch (reg) { case CS42XX8_CHIPID: case CS42XX8_STATUS: return false; default: return true; } } const struct regmap_config cs42xx8_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = CS42XX8_LASTREG, .reg_defaults = cs42xx8_reg, .num_reg_defaults = ARRAY_SIZE(cs42xx8_reg), .volatile_reg = cs42xx8_volatile_register, .writeable_reg = cs42xx8_writeable_register, .cache_type = REGCACHE_RBTREE, }; EXPORT_SYMBOL_GPL(cs42xx8_regmap_config); static int cs42xx8_codec_probe(struct snd_soc_codec *codec) { struct cs42xx8_priv *cs42xx8 = snd_soc_codec_get_drvdata(codec); struct snd_soc_dapm_context *dapm = &codec->dapm; switch (cs42xx8->drvdata->num_adcs) { case 3: snd_soc_add_codec_controls(codec, cs42xx8_adc3_snd_controls, ARRAY_SIZE(cs42xx8_adc3_snd_controls)); snd_soc_dapm_new_controls(dapm, cs42xx8_adc3_dapm_widgets, ARRAY_SIZE(cs42xx8_adc3_dapm_widgets)); snd_soc_dapm_add_routes(dapm, cs42xx8_adc3_dapm_routes, ARRAY_SIZE(cs42xx8_adc3_dapm_routes)); break; default: break; } /* Mute all DAC channels */ regmap_write(cs42xx8->regmap, CS42XX8_DACMUTE, CS42XX8_DACMUTE_ALL); return 0; } static const struct snd_soc_codec_driver cs42xx8_driver = { .probe = cs42xx8_codec_probe, .idle_bias_off = true, .controls = cs42xx8_snd_controls, .num_controls = ARRAY_SIZE(cs42xx8_snd_controls), .dapm_widgets = cs42xx8_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(cs42xx8_dapm_widgets), .dapm_routes = cs42xx8_dapm_routes, .num_dapm_routes = ARRAY_SIZE(cs42xx8_dapm_routes), }; const struct cs42xx8_driver_data cs42448_data = { .name = "cs42448", .num_adcs = 3, }; EXPORT_SYMBOL_GPL(cs42448_data); const struct cs42xx8_driver_data cs42888_data = { .name = "cs42888", .num_adcs = 2, }; EXPORT_SYMBOL_GPL(cs42888_data); const struct of_device_id cs42xx8_of_match[] = { { .compatible = "cirrus,cs42448", .data = &cs42448_data, }, { .compatible = "cirrus,cs42888", .data = &cs42888_data, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, cs42xx8_of_match); EXPORT_SYMBOL_GPL(cs42xx8_of_match); int cs42xx8_probe(struct device *dev, struct regmap *regmap) { const struct of_device_id *of_id = of_match_device(cs42xx8_of_match, dev); struct cs42xx8_priv *cs42xx8; int ret, val, i; cs42xx8 = devm_kzalloc(dev, sizeof(*cs42xx8), GFP_KERNEL); if (cs42xx8 == NULL) return -ENOMEM; dev_set_drvdata(dev, cs42xx8); if (of_id) cs42xx8->drvdata = of_id->data; if (!cs42xx8->drvdata) { dev_err(dev, "failed to find driver data\n"); return -EINVAL; } cs42xx8->clk = devm_clk_get(dev, "mclk"); if (IS_ERR(cs42xx8->clk)) { dev_err(dev, "failed to get the clock: %ld\n", PTR_ERR(cs42xx8->clk)); return -EINVAL; } cs42xx8->sysclk = clk_get_rate(cs42xx8->clk); for (i = 0; i < ARRAY_SIZE(cs42xx8->supplies); i++) cs42xx8->supplies[i].supply = cs42xx8_supply_names[i]; ret = devm_regulator_bulk_get(dev, ARRAY_SIZE(cs42xx8->supplies), cs42xx8->supplies); if (ret) { dev_err(dev, "failed to request supplies: %d\n", ret); return ret; } ret = regulator_bulk_enable(ARRAY_SIZE(cs42xx8->supplies), cs42xx8->supplies); if (ret) { dev_err(dev, "failed to enable supplies: %d\n", ret); return ret; } /* Make sure hardware reset done */ msleep(5); cs42xx8->regmap = regmap; if (IS_ERR(cs42xx8->regmap)) { ret = PTR_ERR(cs42xx8->regmap); dev_err(dev, "failed to allocate regmap: %d\n", ret); goto err_enable; } /* * We haven't marked the chip revision as volatile due to * sharing a register with the right input volume; explicitly * bypass the cache to read it. */ regcache_cache_bypass(cs42xx8->regmap, true); /* Validate the chip ID */ ret = regmap_read(cs42xx8->regmap, CS42XX8_CHIPID, &val); if (ret < 0) { dev_err(dev, "failed to get device ID, ret = %d", ret); goto err_enable; } /* The top four bits of the chip ID should be 0000 */ if (((val & CS42XX8_CHIPID_CHIP_ID_MASK) >> 4) != 0x00) { dev_err(dev, "unmatched chip ID: %d\n", (val & CS42XX8_CHIPID_CHIP_ID_MASK) >> 4); ret = -EINVAL; goto err_enable; } dev_info(dev, "found device, revision %X\n", val & CS42XX8_CHIPID_REV_ID_MASK); regcache_cache_bypass(cs42xx8->regmap, false); cs42xx8_dai.name = cs42xx8->drvdata->name; /* Each adc supports stereo input */ cs42xx8_dai.capture.channels_max = cs42xx8->drvdata->num_adcs * 2; ret = snd_soc_register_codec(dev, &cs42xx8_driver, &cs42xx8_dai, 1); if (ret) { dev_err(dev, "failed to register codec:%d\n", ret); goto err_enable; } regcache_cache_only(cs42xx8->regmap, true); err_enable: regulator_bulk_disable(ARRAY_SIZE(cs42xx8->supplies), cs42xx8->supplies); return ret; } EXPORT_SYMBOL_GPL(cs42xx8_probe); #ifdef CONFIG_PM_RUNTIME static int cs42xx8_runtime_resume(struct device *dev) { struct cs42xx8_priv *cs42xx8 = dev_get_drvdata(dev); int ret; ret = clk_prepare_enable(cs42xx8->clk); if (ret) { dev_err(dev, "failed to enable mclk: %d\n", ret); return ret; } ret = regulator_bulk_enable(ARRAY_SIZE(cs42xx8->supplies), cs42xx8->supplies); if (ret) { dev_err(dev, "failed to enable supplies: %d\n", ret); goto err_clk; } /* Make sure hardware reset done */ msleep(5); regcache_cache_only(cs42xx8->regmap, false); ret = regcache_sync(cs42xx8->regmap); if (ret) { dev_err(dev, "failed to sync regmap: %d\n", ret); goto err_bulk; } return 0; err_bulk: regulator_bulk_disable(ARRAY_SIZE(cs42xx8->supplies), cs42xx8->supplies); err_clk: clk_disable_unprepare(cs42xx8->clk); return ret; } static int cs42xx8_runtime_suspend(struct device *dev) { struct cs42xx8_priv *cs42xx8 = dev_get_drvdata(dev); regcache_cache_only(cs42xx8->regmap, true); regulator_bulk_disable(ARRAY_SIZE(cs42xx8->supplies), cs42xx8->supplies); clk_disable_unprepare(cs42xx8->clk); return 0; } #endif const struct dev_pm_ops cs42xx8_pm = { SET_RUNTIME_PM_OPS(cs42xx8_runtime_suspend, cs42xx8_runtime_resume, NULL) }; EXPORT_SYMBOL_GPL(cs42xx8_pm); MODULE_DESCRIPTION("Cirrus Logic CS42448/CS42888 ALSA SoC Codec Driver"); MODULE_AUTHOR("Freescale Semiconductor, Inc."); MODULE_LICENSE("GPL");
RealDigitalMediaAndroid/linux-imx6
sound/soc/codecs/cs42xx8.c
C
gpl-2.0
19,898
<?php class Kint_Parsers_Microtime extends kintParser { private static $_times = array(); private static $_laps = array(); protected function _parse( & $variable ) { if ( !is_string( $variable ) || !preg_match( '[0\.[0-9]{8} [0-9]{10}]', $variable ) ) { return false; } list( $usec, $sec ) = explode( " ", microtime() ); $time = (float)$usec + (float)$sec; $size = memory_get_usage( true ); $this->value = @date( 'Y-m-d H:i:s', $sec ) . '.' . substr( $usec, 2, 4 ); $numberOfCalls = count( self::$_times ); if ( $numberOfCalls > 0 ) { # meh, faster than count($times) > 1 $lap = $time - end( self::$_times ); self::$_laps[] = $lap; $this->value .= "\n<strong>SINCE LAST CALL:</strong> " . round( $lap, 4 ) . 's.'; if ( $numberOfCalls > 1 ) { $this->value .= "\n<strong>SINCE START:</strong> " . round( $time - self::$_times[0], 4 ) . 's.'; $this->value .= "\n<strong>AVERAGE DURATION:</strong> " . round( array_sum( self::$_laps ) / $numberOfCalls, 4 ) . 's.'; } } $unit = array( 'B', 'KB', 'MB', 'GB', 'TB' ); $this->value .= "\n<strong>MEMORY USAGE:</strong> " . $size . " bytes (" . round( $size / pow( 1024, ( $i = floor( log( $size, 1024 ) ) ) ), 3 ) . ' ' . $unit[$i] . ")"; self::$_times[] = $time; $this->type = 'Stats'; } /* function test() { $x = ''; d( microtime() ); for ( $i = 0; $i < 10; $i++ ) { $x .= str_repeat( 'x', mt_rand( 128 * 1024, 5 * 1024 * 1024 ) ); usleep( mt_rand( 0, 1000 * 1000 ) ); d( microtime() ); } unset( $x ); dd( microtime() ); } */ }
mindtheproduct/2014
wp-content/plugins/ns-cloner-site-copier/lib/kint/parsers/custom/microtime.php
PHP
gpl-2.0
1,638
colabsShortcodeMeta={ attributes:[ { label:"Tabs", id:"content", controlType:"tab-control" }, { label:"Tabber Style", id:"style", help:"Set an optional alternate style for the tabber.", controlType:"select-control", selectValues:['default', 'boxed', 'vertical'], defaultValue: 'default', defaultText: 'default' }, { label:"Tabber Title", id:"tabberTitle", help:"Set an optional main heading for the tabber.", defaultText: '' }, { label:"CSS Class", id:"css", help:"Set an optional custom CSS class for the tabber.", defaultText: '' } ], disablePreview:true, customMakeShortcode: function(b){ var a=b.data; var tabTitles = new Array(); if(!a)return""; var c=a.content; var tabberStyle = b.style; var tabberTitle = b.tabberTitle; var g = ''; // The shortcode. for ( var i = 0; i < a.numTabs; i++ ) { var currentField = 'tle_' + ( i + 1 ); if ( b[currentField] == '' ) { tabTitles.push( 'Tab ' + ( i + 1 ) ); } else { var currentTitle = b[currentField]; currentTitle = currentTitle.replace( /"/gi, "'" ); tabTitles.push( currentTitle ); } // End IF Statement } // End FOR Loop g += '[tabs style="'+ tabberStyle +'"'; if ( tabberTitle ) { g += ' title="' + tabberTitle + '"'; } // End IF Statement g += '] '; for ( var t in tabTitles ) { g += '[tab title="' + tabTitles[t] + '"]' + tabTitles[t] + ' content goes here.[/tab] '; } // End FOR Loop g += '[/tabs]'; return g } };
tiboucle/azimuthgallery
wp-content/themes/wardrobe/functions/js/shortcode-generator/shortcodes/tab.js
JavaScript
gpl-2.0
1,628